Commit Graph
3181 Commits
Author SHA1 Message Date
yetone d1433be2a8 gui tests: profile-confirm finds and measures the home chip in one call, so a list drawn again in between doesn't read as a chip at 0
Under load "closing them leaves the chip where it is: 0 → 259" failed in
both engines: the chip's top before opening its details read 0 while a probe
right after read it at 259. The locator found the chip, the profiles list
was drawn again from the state that came back (renderProfiles replaces the
chips), and the evaluate then measured the detached old chip, whose
bounding rect is all zeros. The chip never moved; the test's two-step
lookup raced the redraw. top() now finds the chip and measures it inside
one page.evaluate.

Eight copies at once (chromium and webkit, en and zh, window and panel):
before 9 and 15 of 80 failed in two runs; after 80 of 80 pass.
2026-10-08 03:05:33 +08:00
yetone 8317d38383 gui tests: routing-failed-open measures the 400's row once the live page has followed the newest request and drawn its story
In WebKit the live cases read the row's top as soon as the list was there,
before the page had followed the newest request and drawn its story above
the list (.rt-log grows 17 → 104px), so the row was 87px lower by the click
and "picking the request moved the page" failed — with the test's own
commit's assets too (d6096e2f), so it is the test's timing, not a
regression. The test now waits for the newest row to be pressed and the
story's steps, then for the row's top to hold still, before clicking.

Before: webkit en/zh live failed 2 of 2 (row 524 → 611). After: 8 of 8
(chromium and webkit, en and zh, live and kept day), three runs.
2026-10-08 03:05:33 +08:00
yetone 6d1d202b7f providers: a SiliconFlow key's card says SiliconFlow retired its balance query and has no API in its place yet, and that the balance and vouchers are on its console, instead of "410 Gone: {...}" (#1094)
SiliconFlow stopped /v1/user/info on 2026-08-14 (release notes, 2026.08.11)
and answers it with 410 {"code":20092,"message":"This endpoint is
deprecated and is no longer available.","data":null}. Its docs and release
notes name no replacement yet ("new interfaces will be announced
separately"), and the balance given before 2025-12 became vouchers, seen
under 余额充值 → 代金券 on the console. So the card now says that and links
cloud.siliconflow.cn (cloud.siliconflow.com for the international site). A
key SiliconFlow refuses (401 30014 "Token is invalid.") is still said as it
came, and a 200 is still read.

TestSiliconFlowRetiredBalanceQuery replays the reporter's literal 410 body
for both hosts, plus the real 401 body and the documented 200; without the
change it fails with `410: true 410 Gone: {"code":20092,...}, want it
retired and https://cloud.siliconflow.cn named`. go test -race
./internal/provider and go vet ./... pass. Not tried with a real
SiliconFlow key (none on this machine); the 401 body was read from the
live endpoint with a dummy key.
2026-10-08 02:15:01 +08:00
yetone a8290d2772 agent: a catalog sync or a model pick keeps the keys a user or another tool added to magpie's provider block (Pi's providers.magpie.compat.sendSessionAffinityHeaders from pi-cache-optimizer) instead of writing the block whole (#1103)
syncJSON and Pi's writeMagpie set providers.magpie to a freshly built
object, so a key magpie doesn't write there was dropped on every sync.
theirsKept now merges magpie's block into what the file holds: keys magpie
writes are its own, objects in both are merged key by key, and anything
else (compat, an options key, Crush's extra_headers) stays. The model list
is still magpie's whole, so a model gone from the catalog leaves it, and a
sync with nothing new writes nothing.

The same goes for every agent that writes the block whole: Pi and OmO,
Aside, Pencil, OpenCode (and the agents built on it), OpenChamber, Crush
and Command Code.

Verified: TestPiKeepsTheirKeysInMagpiesProvider (the reporter's
compat.sendSessionAffinityHeaders: true in Pi's models.json, through
SyncCatalog and a pick) and TestOpenCodeAndCrushKeepTheirKeysInMagpiesProvider
fail without the change ("compat.sendSessionAffinityHeaders dropped by the
sync", "opencode sync") and pass with it. go test -race ./internal/agent
and go vet ./... pass in a sandbox HOME.
2026-10-08 02:15:01 +08:00
yetone d637a3cf5e gateway: a DeepSeek model whose Codex request is passed through as it is (OpenCode Go's deepseek-v4.1-flash) gets its reasoning back as reasoning_text, and is never asked without it (#1104)
Codex hands a reasoning item back as it got it; one from a turn magpie
translated, or another provider in a mixed group served, has only its
summary. Passed through to OpenCode Go's /responses, DeepSeek refused the
request with "The `reasoning_text` in the thinking mode must be passed back
to the API". That refusal names the input, so passthrough asked once more
without every unsealed reasoning item (withoutBareReasoning) and marked the
model as refusing them, which left the reasoning out of every later request.
For a model that wants its reasoning back (replaysReasoning, the predicate
#388's buildResponses uses), a reasoning item without reasoning_text now
gets its summary as one, and withoutBareReasoning is never applied to it.

TestDeepSeekReasoningPassedThrough plays OpenCode Go with the reporter's
error word for word. Without the change it fails ("reasoning_text sent =
\"\", want the summary"); with only the strip guards taken out it fails ("a
reasoning item with nothing in it was answered"). go test -race
./internal/gateway, -race -count=10 on the new test, and go vet ./... pass.
2026-10-08 02:15:01 +08:00
yetone 5a9c0c21ca codexcat: a third-party entry for a model Codex has its own entry for (s2a/gpt-6-astra) says the same multi_agent_reasoning_effort, so Codex's Ultra sends xhigh for it as for OpenAI's gpt-6-astra instead of falling back to max (#1108)
Codex resolves Ultra to the entry's multi_agent_reasoning_effort, and to
max when the entry has none and lists max. magpie's entries never carried
the field, so the same model ran at max through a relay and at xhigh
through the ChatGPT account. The value is taken from Codex's own entry in
models_cache.json for the model's slug (after the provider prefix and a
dated snapshot suffix), only when the third-party entry offers Ultra and
the effort itself; models whose own entry says nothing (gpt-6-sol today)
keep Codex's max. The gateway's literal "ultra" -> max mapping is
unchanged: Codex sends the resolved effort, not "ultra".

TestUltraEffortAsCodexOwnEntry, built from the reporter's entries, fails
without the change ("s2a/gpt-6-astra: multi_agent_reasoning_effort <nil>,
want xhigh"). go test -race ./internal/codexcat ./internal/gateway
./internal/agent and go vet ./... pass in a sandbox HOME.
2026-10-08 02:15:01 +08:00
yetone 842272df84 gateway: a Codex subagent's sealed task goes back to the Responses provider that answered its lead (a Sub2API relay of the ChatGPT backend), relayed as it came, instead of being refused before it is asked; the refusal names who sealed it (#1109)
Codex on Ultra with s2a/gpt-6-astra for both the lead and the subagent,
s2a a Sub2API relay: the relay's ChatGPT backend sealed the lead's
spawn_agent task, and magpie turned the subagent away because only a
Codex account counted as able to read it, telling a user already on a
magpie model to "use a Magpie-served model for the lead".

The provider that answered the lead (leadProvider, from the lead
thread's affinity in any scope) now reads it too when it is a key
provider serving the model on Responses; the task is relayed, even
when Codex offers web_search (it was translated, which dropped the
agent_message's encrypted_content). A subagent on another provider, or
whose lead magpie never answered, is still refused before anyone is
asked, with a message naming the lead's provider when known.

Verified: TestSealedTaskGoesBackToTheRelayThatSealedIt (lead and
subagent on s2a/gpt-6-astra, with Codex's web_search tool) fails without
the change with the old 400; without only the relay part it fails with
the ciphertext dropped from the upstream request.
TestSealedTaskRefusedByAnotherRelay covers a lead on s2b and an unknown
lead. go test -race ./internal/gateway, go vet ./..., GOOS=linux and
GOOS=windows builds pass.
2026-10-08 02:15:01 +08:00
yetone ed4476b981 agent: Hermes keeps magpie's provider when its model goes to one of its own, so it stays connected and its session picker still offers magpie's models; Disconnect takes it out (lijiho96940561 on X: changing Hermes's default model marked it Not connected and magpie's models left its picker) 2026-10-08 00:27:03 +08:00
yetone 8731dd9f38 docs: LESSONS.md gets the review of 10-07's commits — fix-the-class, re-derive, red-on-main and merge-record lessons seen a third day move into the code standards; not tried with the real thing seen a second day (b2345078→7837f90d, #1050, cda11d84); positives from 6b6113aa, d40fee80, bed306ae and #948 2026-10-07 23:46:48 +08:00
yetone 8b14afea15 docs: Plugins says magpie asks GitHub for tagged repositories at most every ten minutes (en, zh, ja) 2026-10-07 22:09:45 +08:00
yetone a12f6fc13a plugins: a repository tagged magpie-plugin shows within ten minutes, not up to six hours later (lee04052822 on X: tagged it, and magpie didn't show it)
GitHub's search was asked at most every six hours. An author who had opened
the Plugins page before tagging their repository, as lee04052822 had,
didn't see it until the six hours were up. It is now asked at most every
ten minutes. A search is one request of the ten a minute that GitHub allows
without a token. What each repository's package.json, npm and entry file
said is kept while its last push stays the same, so asking again costs one
request, not three per repository. An answer GitHub or npm didn't give (a
503 for the entry, say) isn't kept, and is asked again next time.

Against real GitHub: the topic has two repositories,
mu-zi-lee/magpie-doubao-translate and SadWood/magpie-gaccode. Both are
listed as github: installs, the first time in 3.8s and in 0.2s once the ten
minutes are up. Both installed and loaded in a sandbox magpie, giving the
Doubao Translation and GACCode providers. TestTaggedRepos checks that
asking again after ten minutes reads only flaky-entry again, and it fails
with 21 reads when the per-repository cache is turned off. go test -race
-count=2 ./internal/plugin and go vet pass.
2026-10-07 22:09:45 +08:00
wizzy-yangandwizzy-yang e95852e301 usage, gui: 用量页补上各 agent 会话文件里的用量,请求页按「经过 / 不经过 magpie」拆开 (#948)
* sessions: dsh、ZCode、WorkBuddy 的会话文件里有各自花掉的 token,用量台账从来不读

Sessions 页面一直都在读这些 agent 自己的会话文件,用量台账没有:用量页只显示网关本
身应答过的调用——也就是装上 magpie 之前的什么都没有,而一个直接指向厂商的 dsh 更
是什么都没有。本机上装 magpie 之前就已经在用这些 agent(用它们自带的模型),那段
用量一直对不上账。

  * 新增三类"整文件读取"的调用来源,走 wholeCallReaders(它们的调用不是一行一条,
    或者文件不能从中间接着读):dsh 的会话是 zstd 分帧追加的;ZCode 用的是 OpenCode
    那几张表;WorkBuddy 的同一句回复会在多行里重复同一个 messageId。三者的 token
    语义各自换算成 Call 的 Input/Output/CacheRead/CacheWrite,调用缓存跟着记一份(v9)。
  * 每个来源都跳过经由 magpie 网关发出的调用:网关自己记过那一本账,还带着真正应答
    的供应商和账号;dsh 发往网关的请求不带会话头,两边事后对不上(token 数每次不同、
    又没有可配对的 id),硬读就是同一通调用记两次。dsh 认它被配置去的那个 provider
    (dshGatewayProvider:magpie / dial),ZCode 和 OpenCode 认路由里写的 provider
    (ocGatewayProvider)。WorkBuddy 那部分见下一个提交。
  * WorkBuddy 的调用里,同一句回复的多行只记最后一次(它带这个回复的总量);而它从
    旧历史搬过来的回复一条 messageId 都没有,每一条都是独立的一通调用——会话汇总的
    读法(workbuddyLine)就是这么数的,这里照它来,否则台账会比 Sessions 页面少算,
    正是本次要消灭的那类"两页对不上",只是方向相反。
  * dsh 的一通调用保留它文件里记的两样东西:被配置去的供应商(Upstream,作为历史,
    从来不当成路由的证据),以及厂商真正应答的模型——回复的 replayState 里那个和
    请求模型不一致时,Model 记应答的、Requested 记被请求的,和 Claude Code 的文件
    一样的读法,好让请求表的若干列有东西可填。
  * 会话的 fork:dsh 的会话从另一个会话续起来时会带上对方已写入的事件(isSeeded /
    seedLength,session/end-seed 标记之后的不算),parser 跳过的这里同样跳过,否则
    同一通调用会在每个 fork 上再花一次。
  * WorkBuddy 的 subagents/ 子目录是父会话自己的调用来源(它带自己的消息 id,会话
    归到父会话名下);调用这条路不读 file.main,那个标记是 Sessions 页面给"会话自己的
    文件、不是子代理的"用的。

夹具:dsh 的三个会话(普通、带供应商与应答模型、以及一通经网关的),ZCode 的两条
(其中 ses_zcA 那条的 providerID 是 magpie,应被跳过),WorkBuddy 的既有会话(m1 的
usage 同时落在 assistant message 和它最后一个 function_call 上,只能记一次;旧历史
三条无 messageId 的回复各记一次)和一通经网关、一通走用户自建端点的会话。
调用缓存升到 v9:v8 里既没有 dsh 的供应商和应答模型,也没有"跳过网关调用"这件事,
旧缓存会继续把旧账 Serve 出来。

TestDshCalls、TestZCodeCalls、TestWorkBuddyCalls 是新的;把跳过网关调用那几行、以及
WorkBuddy 旧历史那条判据去掉,它们必挂、加上必过(都实际跑过反向验证)。

验证:go vet;go test ./internal/sessions(只余 TestCursor,Windows 路径前缀问题,
改动前同样失败);go build(windows)。

* usage: 请求页把"magpie 转的"和"它只读到的"分成两个数,GUI 跟着拆成两栏

用量页一直只显示网关自己应答过的调用,而现在它还要读 agent 自己会话文件里的调用:
两本账混在一行里,读者分不清哪一段是 magpie 转的、哪一段只是它从文件里读到的,
而总数事实上几乎全部来自后者(本机 30 天 847M token 里,网关只转了 2.4%)。Summary
里的两个来源卡片也加不出这个数来:它们只算 input 和 output,上面的 KPI 把缓存的
token 也算在内,于是"全部请求"读作 13.6M,而"Tokens"是 847M。

  * usage.RequestPage 和 usage.Filter 各多一样东西:前者在 Sum 之外带上 Through 和
    Direct(网关应答的,和从会话文件读到的),后者多一个 Through 维度。两种建页路径
    (流式的 queryPage 和治疗桌用的 pageFromLedger)都做同一个拆分,两边一致——
    TestCompactPageMatchesLedger 现在也覆盖两个来源筛选。
  * 每一行本来就是按 Source 区分这两类的("log" 是会话文件里的调用,其余走的网关),
    拆分就落在它上面;网关自己拒掉的调用两边都不算(页面在总数下面也这么说),所以
    SourceOf 对它返回 "",点哪一栏都同样把它排除,两栏自己的计数本来也不含它。
  * 两栏自己的数字是在"来源"这个挑选被清空的情况下数的,和各维度分组一样:三栏是读者
    来回切换的地方,各自得一直报着自己的数,否则点了其中一栏另一栏读作 0,且没有回
    到全部的路。
  * /api/usage/requests 支持 via=through|direct;GUI 那一侧的三个格子、计数单位、
    方块样式在下一个提交里。
  * Filter.Via 这个名字和 Record.Via(转发调用的那台电脑,#542)重了,改叫 Filter.Through。

Sessions 页列表长度那件事(sessionListLimit)拆到单独的 PR 里,不在这里。

验证:go vet;go test ./internal/usage(只余 TestOTelRetryAfterBound,计时的 ±30ms,
origin/main 同样失败);go build(windows)。

* gui: 请求页把来源拆成三栏,汇总那一排也改成方块

用途页的请求栏一直只有一本账(Sum),而现在它既显示网关应答的调用,也显示从各 agent
自己会话文件里读到的调用。三个格子画在上方汇总那一排方块里,样式一致:三张各自带
边框、彼此留缝的卡片,窄屏(≤620px)下竖排。

  * 每栏是一个 button:点一下就只列这一来源的请求,再点一下、或点"全部请求"回到
    全部;被选中的那一栏底下有一道本主题色的线。aria-pressed 标出当前选中的是哪一栏。
  * 计数后面跟单位("147 请求"),免得一个光秃秃的数字被读成下面的 token;token 是
    四项合计,和上面 KPI 的算法一致。
  * 三个格子在重绘之间是同一批元素、原地改(class / aria / 文本 / onclick),不是每次
    replaceChildren 重建——同一份 app.js 里 5810 行的规定就是这么写的("The switch is
    the same element across redraws, changed in place, so one being pressed or focused is
    never swapped out"),正在点的那个不该被换掉。
  * 汇总那一排本身(五张 KPI 卡)改成同样的方块:各自一张卡、有缝,边框写成
    var(--line) 而不是 --card-edge(那是面板用的变量,这些卡在独立窗口里也有)。
    ≤860px 两列排布时卡片之间的那几条线照旧:奇数位去掉左边框、第三张起加上边框,
    是 e0eaf5b4 带 #799 的老规则,这里只是跟着搬了位置,没有删。三张来源格是 button,
    不参与这套分隔线。
  * 供应商·账号 一栏:来自会话文件的行显示它文件里记的那个供应商 id(Codex 一向
    如此),有账号时仍是账号优先,什么都没有才说"本地会话"。"本地会话"角标的条件
    跟着放宽到账号或供应商任一存在,提示分两种说法:文件记了供应商的,说明这是它
    被配置去调用的那个记录、不是 magpie 看到的路由(不等于官方供应商);只认得出
    账号的,沿用原来那句"仅当本地元数据能明确识别时显示账号"。
  * 窗口参数支持 via,用后从地址栏清掉,和 tab/provider/agent 等一致。
  * 新增的串子在 en/zh/ja/de 四种语言里都有("{n} tokens" 上游已有,不重复加,
    i18n-keys 绿)。

验证:node --check(app.js、i18n.js);go vet;go build(windows)。
界面效果在本机用改动后的源码构建的二进制上过目:三栏的切换与计数、方块样式、
窄屏竖排、请求表新增的会话文件行(含供应商 id)。
浏览器套件(chromium 与 webkit、en/zh):session-identity、usage-ledger、
ledger-protocol、number-units、usage-ledger-chart、usage-ttft-rounding、
usage-chart-axis、usage-fold、web-page、usage-accounts、i18n-keys 全绿;
ledger-hscroll、usage-speed、click-scroll 全绿;gui-ja、gui-de 各一条失败、
usage-ledger-detail 六条失败,均在本机 origin/main 上同样失败,与本次改动无关。
usage-ledger-chart 新钉了 ≤620px 下 KPI 卡与来源格的分隔线(把 app.css 换回上游版本
它必挂,实测过)。

---------

Co-authored-by: wizzy-yang <wizzy-yang@users.noreply.github.com>
2026-10-07 19:43:01 +08:00
mslxl cd8d64a9fc feat(gui): add Sub2API balance autofill on account balance hint (#1059)
* feat(gui): add Sub2API balance autofill

Offer Sub2API alongside NewAPI in the custom provider's balance-token hint.
Fill /api/v1/user/profile and $data.balance, and describe both endpoints in
the existing translations.

Verified: native macOS build; 10 existing browser and translation checks;
Sub2API flows in Chromium and WebKit, four languages, at 900px and 440px;
live web assets. The original code fails the temporary two-shortcut check.
Full Go suite, cross-platform builds and live-account validation not run.

* fix(gui): preserve custom balance fields in account shortcuts

Use the same replacement rule for both account balance shortcuts, keeping
user-written expressions. Describe both endpoints in the key-only URL
warning and restore the rationale for flagging missing and key-only URLs.

Add browser cases for both URL states, new providers, saved form values,
narrow layouts and all four languages.

Validation: 111/111 related checks across Chromium and WebKit; native macOS
build; 38/38 after baseline failure checks. New button cases fail against
d9b2cdc5 app.js, and custom-field checks fail against cf3f3d9d app.js.
Full Go suite, cross-platform builds and live-account validation not run.
2026-10-07 19:11:01 +08:00
yetone 92e4fc32fa provider: moved ZCode users get plugin 0.1.12 and moved WorkBuddy users 0.1.10 — ZCode's counted windows carry their amount and limit so the card's count follows used/left (#659, magpie-community/plugins#35); WorkBuddy's credits-used-up error (code 14018, matched as the whole code) says so with the nested message (plugins#25). Both versions resolve with npm view. go test -tags nogui ./internal/provider under a temp HOME passes; the plugins' own bun tests passed at merge. Not tried with a real ZCode or WorkBuddy account here. 2026-10-07 18:52:23 +08:00
forever bed306ae60 gateway: reasoning off reaches Gemini 3 at its lowest level, and Google refusing minimal no longer stops a provider's thoughts (#1062)
* gateway: reasoning off goes to Gemini 3 at its lowest level where it has no minimal, and Google refusing minimal no longer stops the provider's thoughts until restart

With reasoning off, a request to Gemini's OpenAI-compatible API (AI
Studio's, or a proxy in front of it on this machine or the LAN) went with
reasoning_effort minimal, since Gemini 3 can't stop thinking.
gemini-3.8-flash has no minimal: models.dev gives its levels as low,
medium and high, and Google answers minimal with 400 "Thinking level is
unsupported: THINKING_LEVEL_MINIMAL". The message names thinking, so
refusesThinkingConfig took it for thinking_config turned away and marked
that field unfit for the provider. Until magpie restarted, nothing sent to
the provider asked for Gemini's thoughts again, on any model, and a client
that asked to see them got none. The turn itself was asked again with no
reasoning_effort, at the model's default level.

  * Reasoning off goes at the model's lowest level where its levels are
    known and have no minimal, and at minimal where they have it or aren't
    known (Request.OffLevel, geminiOffLevel). gemini-3.8-flash on AI
    Studio goes at low, in one request.
  * Where the levels aren't known (a proxy's own name for the model),
    Google's 400 for minimal is told apart from thinking_config turned
    away (geminiMinimalRefused, which also matches gemini-3.1-pro-preview's
    "thinking_level MINIMAL is not supported by this model" at
    generateContent). It is remembered as the model refusing reasoning off
    (offRefused, as for other vendors), and the model is asked again at its
    lowest level, low when none are known, and so from then on.
    thinking_config is kept, and the next turn that thinks gets the
    model's thoughts.
  * An effort of minimal set on the request, which fitFor keeps where the
    levels aren't known, is turned away the same way and asked again at
    low by the existing offEffort step, with its thinking_config.

Passthrough (a Chat client calling AI Studio itself) is unchanged: it fits
the effort to the model's levels where they're known, and has no retry for
a proxy whose levels aren't.

Tests, with what upstream's gateway gives:
  * TestGeminiThinkingOffAtItsLowest: an Anthropic client's turn with
    thinking disabled, then one thinking at high, then disabled again, to
    a fake Gemini that answers minimal with the 400 above, in its literal
    bytes. With the levels known, the first turn goes at [low]; not known,
    at [minimal low]. Either way the thinking turn then sends
    thinking_config {include_thoughts: true, thinking_level: high} and
    gets a thinking block, and the last turn goes at low in one request.
    Upstream sends [minimal <nil>] both ways.
  * TestAIStudioThinking: "off at its lowest" sends reasoning_effort low.
    Upstream sends minimal.
Each part was also broken on its own, and each break fails a test:
buildChat ignoring OffLevel ("reasoning_effort = "minimal", want "low"",
and [minimal minimal <nil>]), the loop never setting it ([minimal minimal
<nil>] both ways), no check for the refusal of minimal ([minimal <nil>]
with the levels not known), and geminiOffLevel ignoring the refusal
([minimal minimal <nil>]) or the known levels ([minimal low]).

Verified on 443f1cbc: gofmt -l, go vet ./..., go build, GOOS=linux go
build -tags nogui and GOOS=windows go build pass; go test -tags nogui
./... passes, and -race -count=20 on the tests above.

Live, with gemini-3.8-flash through a proxy on this machine in front of
Vertex AI's OpenAI-compatible API, the gateway in a temporary HOME (AI
Studio itself wasn't tried: there was no key for it). Upstream sent the
off turn at minimal, got the 400 and asked again with no
reasoning_effort; the thinking turn after it went as reasoning_effort high
with no thinking_config, and no thoughts came back. With this change the
off turn went at low in one request, the thinking turn with thinking_config
at high, and the last off turn at low. Under a name whose levels aren't
known, the first off turn went minimal, then low, and the next at low at
once. The thoughts reached the client as thinking with the next commit,
which reads how that endpoint marks them.

* gateway: Gemini's thoughts streamed from Vertex AI's OpenAI-compatible API reach the client as thinking, not as the start of the answer

A proxy on this machine or the LAN in front of Gemini is asked for the
model's thoughts as AI Studio is, in thinking_config. In front of Vertex
AI's OpenAI-compatible API, the thoughts don't come in AI Studio's
<thought> tags: each comes in a chunk of its own, the thought as the
delta's content, and the chunk is marked
"extra_content": {"google": {"thought": true}}. chatDecoder read only the
content, so the thoughts were streamed to the client as the first part of
the answer.

  * A chunk marked as a thought is thinking (KThink).

A whole reply from that API carries its thoughts in <think> tags instead.
That isn't changed: the gateway streams from the upstream when it
translates, and a Chat client's own request is passed through as it is.

Tests, with what upstream's gateway gives:
  * TestGeminiThoughtsMarkedInExtraContent: that API's stream for "你好"
    at high with the thoughts asked for, in its literal bytes
    (testdata/vertex_openai_thoughts.sse), to an Anthropic client: a
    thinking block that starts "**Acknowledging Greeting**", then the
    text "你好!很高兴与你交流。请问有什么我可以帮你的吗?". Upstream gives
    thinking "" and the thought at the head of the text.

Verified on 443f1cbc: gofmt -l, go vet ./..., go build, GOOS=linux go
build -tags nogui and GOOS=windows go build pass; go test -tags nogui
./... passes, and -race -count=20 on the tests of this and the previous
commit.

Live, through the proxy and temporary HOME of the previous commit, a turn
thinking at high gave a thinking block of 238 characters, and the answer
apart from it.
2026-10-07 18:51:01 +08:00
yetone cda11d8467 appdir: a data folder beside magpie in the home folder, Downloads, Desktop or Documents is its portable data only when it holds magpie's files and the installed folder doesn't (or with .portable), so magpie.exe run from Downloads no longer writes into a user's own Downloads\data (tangle778 on X) 2026-10-07 18:13:01 +08:00
yetoneandKuaaMU 07e246e515 gui: a key typed into the routing group filter, a provider's keys filter or the plugins search goes in once, through an IME too (#1055: 1, 2 → 1122)
Each filter drew its row again from its own input event, and the redraw
took the focused field out of the page and put it back (the routing
header's replaceChildren; the keys filter's whole renderProviders, which
made a new field; the plugins page's draw, which made a new head). An IME
committing while the field was out wrote its text twice.

replaceKeeping (app.js) replaces a box's children but leaves a node
already there in place. The routing header redraws around its filter, the
keys filter redraws its list around the filter instead of the whole
Providers page, and the plugins page keeps one head and one search field
and redraws around them. Everything around each field is still drawn
again, so a language switch, Select, and the counts follow as before.

The cause was found by KuaaMU in #1056, which stopped the routing header
being rebuilt while its shape was the same. That kept a language switch
from reaching the header and left the two sibling filters; this carries
over the diagnosis and fixes all three by not moving the field at all.

Verified: internal/gui/tests/filter-ime.test.cjs types into each field
through an IME in Chromium (CDP Input.imeSetComposition, then
Input.insertText) and by key in WebKit, in en/zh/ja/de at 1100px and
440px: 48/48 pass. Against origin/main's assets 48/48 fail (routing:
'1122', field out 4 times; keys and plugins: field taken out). Reverting
only routing.js, only plugins.js, or only the keys filter's oninput fails
exactly that field's 16 tests. Full GUI suite (both engines): 3326/3350;
the 24 failures (codex-auto-reset, mobile-web, old-webkit,
profile-confirm, purpose-filter, routing-failed-open, session-identity,
text-size) fail the same on origin/main. go build -tags nogui and go test
./internal/gui pass.

Co-authored-by: KuaaMU <KuaaMU@users.noreply.github.com>
2026-10-07 17:57:33 +08:00
yetone 01aaa8e925 plugins: the built-in market lists OpenCode Zen Free (@magpie-community/opencode-zen-free-auth), OpenCode Zen's free models, with the bundled opencode icon 2026-10-07 17:14:55 +08:00
yetone d40fee800d library: Pi's mcp.json is backed up to ~/.config/magpie/backups before magpie moves it whole to mcp-adapter.json, as it already was before a merge (#1097, heliar-k)
piMove renamed mcp.json to mcp-adapter.json when the adapter's file wasn't
there yet, with no copy kept. The user's file is now copied aside first;
one that can't be copied isn't moved.

Verified: TestPiMCPWholeMoveKeepsABackup (the reporter's layout: adapter
only in npm/node_modules, packages: [], a user-owned mcp.json) fails
without the change ("backups of mcp.json: []") and passes with it.
go test -race ./internal/library green under a temp HOME.
2026-10-07 16:49:30 +08:00
yetone c83c0d5fef gateway: sharing keeps the host MAGPIE_ADDR names (127.0.0.1 behind Tailscale Serve, one interface's address) instead of listening on every interface, and still asks what reaches it from elsewhere for a gateway key (#1112)
listenAddr turned sharing into 0.0.0.0:<port> and dropped the host of an
explicit MAGPIE_ADDR, so requiring gateway keys from remote callers also
widened the listener. A host MAGPIE_ADDR names is now kept while shared;
0.0.0.0, :: or no host still means every interface, and an unset
MAGPIE_ADDR still shares on every interface. LANURLs offers the pinned
address alone, or none on loopback (MAGPIE_PUBLIC_URL says the proxy's).

Verified: TestSharedKeepsPinnedAddr fails without the lan.go change
("shared, MAGPIE_ADDR on loopback, listens on 0.0.0.0:4555") and passes
with it, -race -count=20. go test -race ./internal/gateway ./internal/gui
green under a temp HOME.
2026-10-07 16:47:41 +08:00
yetone 6b6113aa7a gateway keys: a key can be created with a value of the user's own, one their clients already send, so moving from another gateway (CLIProxyAPI's api-keys) doesn't mean re-keying every client (love1sbug on X)
Gateway → Gateway keys → Add gateway key has a second field, "Your own key
(optional)"; `magpie gateway-key add <name> --key <value>` (or `--key -`
from stdin) does the same. Left empty, magpie makes a sk-magpie-key- as
before. A value is 8–256 printable ASCII characters with no spaces, can't
start with sk-magpie-, and can't be another key's. The list shows only its
last four characters ("…0042"); rotating it gives a magpie-made key.

From another computer any enabled key was already checked, so an own value
works there as is. From this computer the gateway only identified a request
whose key looked like sk-magpie-…, so an own value would have been let in
unidentified: not counted as the key, nor held to its limit, models or
accounts. managedKey now asks access.Named, which also knows the store's
own values (cached by the file's size and time).

Tested: go test -race . ./internal/access ./internal/gateway ./internal/gui;
-count=20 on the new and LAN guard tests; TestOwnKeyValueIsTheKey fails with
managedKey back on access.Managed. gateway-own-key.test.cjs passes 16/16
(chromium and webkit, en/zh/ja/de, 1000 and 440px), and the gateway-key
suites, i18n-keys, gui-ja and gui-de pass. A built binary in a sandbox HOME
with sharing on: own key from the LAN address 200, a wrong or no key 401,
from 127.0.0.1 200, the old value after rotate 401. GOOS=linux and windows
builds pass.
2026-10-07 14:34:36 +08:00
yetone 290c60a31e docs: Plugins says a GitHub repository tagged magpie-plugin is listed under Discover as unofficial (en, zh, ja) 2026-10-07 10:13:24 +08:00
yetone f6f960e42c plugins: a GitHub repository tagged magpie-plugin shows on the Plugins page under Discover, as an unofficial plugin nobody at magpie has reviewed
GitHub's search for topic:magpie-plugin (not archived, not a fork, not
magpie-community's own, which the market lists) is asked at most every six
hours and kept on disk, so a restart or GitHub being down shows what it said
last. Each repository is read from its package.json on the default branch.
When npm has that package published from the same repository, it is
installed from npm, because a repository often builds its dist only to
publish and Bun runs no build for a git install. Otherwise it is installed as
github:owner/repo, and only if the file it loads (exports, main or
magpie.middleware) is in the repository. Its page warns that it is
unofficial, says whether npm or the repository is what gets installed, and
shows the repository's README until it is installed. MAGPIE_PLUGIN_MARKET=off
asks GitHub nothing.

Checked against real GitHub with the topic set to opencode-plugin in a
sandbox: 43 repositories came back, and 32 were kept (30 from npm, 2 from
git). github:ndom91/open-plan-annotator, one of the git ones, really
installed and loaded. alfaoz/opencode-see-image, whose dist isn't in its
repository, failed to load before the entry check and is now left out. The
test fixtures are GitHub's and npm's real answers.

Ran: go test -race -count=3 ./internal/plugin, go test ./internal/gui, go
vet, and plugin-github.test.cjs (Chromium and WebKit, 980/440, en/zh/ja/de,
18/18). The full GUI suite passed 3343 of 3348. The 5 failures were WebKit
number-units, purpose-filter and routing-failed-open, which pass 3/3 on
their own and don't touch the Plugins page.
2026-10-07 10:13:20 +08:00
yetone f1821f4869 gui: Settings' Web pages help says a page from another site is refused, not that it only gets no CORS headers
Since d5468283 the gateway refuses with 403 a page whose origin is not
listed, not on this computer and not the gateway's own address; the help
under "Web pages that may call magpie" still said other pages merely get
no CORS headers. Reworded in English, Chinese, Japanese and German.

Verified: cors-origins.test.cjs, gui-ja, gui-de and i18n-keys pass in
Chromium and WebKit (10/10 each). With app.js from origin/main,
cors-origins fails ("not ok 1 - en", "not ok 2 - zh": the old sentence).
2026-10-07 07:32:22 +08:00
yetone e8a2b50703 gateway: a Claude subscription run started on a long conversation is told its past tool calls as mcp__magpie__<Name>, the names it can call, so the model no longer calls a bare Bash and gives up on "Bash is disabled for this session" (#958, Cyb3rN8)
The run's Claude Code has the caller's tools only through the MCP helper
(--tools "" turns its built-ins off). A run started anew (after an idle gap,
or magpie quitting for an update) was told the conversation in text with
every past call as [tool call Bash …]: hundreds of bare names and none of
the run's own. The model wrote Bash, Claude Code itself answered "Bash is
disabled for this session, in subagents as well as here.", nothing reached
magpie, and the turn ended without a call. renderClaudePrompt and
renderClaudeTurn now write a call of a tool the caller offers under
bridgeName (mcp__magpie__<Name>), and a forced tool_choice names it so too.
A call of a tool the caller doesn't offer (its framework's own) keeps its
name.

Verified: TestClaudePromptTellsPastCallsByTheRunsNames fails without the
change ("started anew: a call of the caller's Bash isn't told as the run's
mcp__magpie__Bash", the same for the next turn, and "You must call the Read
tool.") and passes with it. go vet, go test -tags nogui ./internal/gateway
(temp HOME, pinned caches), GOOS=linux go build -tags nogui and GOOS=windows
go build pass. Not tried against a real Claude subscription: the bare-name
call could not be brought about on demand (18 real runs called the right
name before this change).
2026-10-07 07:29:10 +08:00
yetone 3e38bd76dc gateway tests: TestRestingKeyReadAgainInAnOrderedGroup lets the key be back already once the relay has answered with its limit raised (red on ubuntu CI at fb9d1a4c, run 37540375720: "resting: ko first, its rest <nil>") — since ee2588c2 a reading of the key's windows still out as it refused for quota is followed by another at once. When that second reading reaches the relay after the test raises the limit, it lifts the rest before the test plans again, which is right; the test asked for the rest to still stand there. It now accepts ko first and not resting when a reading saw the raised limit, and still wants kx first and ko resting otherwise. With the first reading held 100 ms and 200 ms between raising the limit and planning (a loaded CI runner), the old test fails as CI did and the new one passes. With ee2588c2's re-read taken out and the second reading held 300 ms, the new test still fails 2 of 2 ("still rests by window"). go test -race -count=40 -cpu 1,2,4 -run 'TestRestingKey|TestKey|Lone|Allowance' ./internal/gateway and go vet pass. 2026-10-07 07:17:22 +08:00
yetone d688a8b43c providers, gui: a Copilot account on the individual_max plan reads "Max", not "Individual_max", and individual_edu reads "Education"
copilotPlans had no name for two copilot_plan values that GitHub sends,
so label() capitalised the raw id. GitHub's own clients name them:
- VS Code's chatEntitlementService maps individual_pro to ProPlus
  ("Copilot Pro+"), individual_max to Max ("Copilot Max") and
  individual_edu to EDU.
- CopilotForXcode's planDisplayName gives "Copilot Pro+ Plan" for
  individual_pro and "Copilot Max Plan" for individual_max.

So individual_max is Max, not Pro+. The real individual_max response in
copilot_usage_test.go has a premium allowance of 20000, above Pro+'s.
That test and its comments called it Pro+ and now say Max. VS Code also
gives individual_edu the EDU entitlement, which magpie already labels
"Education" through the free_educational_quota SKU, so the plan id gets
the same name. The full list of ids that GitHub's clients handle (free,
individual, individual_pro, individual_max, individual_edu, business,
enterprise) is now named. The Copilot tile's plan list in the Add sheet
includes Max.

Verified: TestCopilotEntitlementLabels fails without the map change
("{Plan:individual_max AccessSKU:free_github_star_quota}: "Individual_max",
want "Max""; individual_edu the same), and passes with it under -race
-count=20. deprecated-subscriptions and signin-closes-sheet GUI tests pass
in Chromium and WebKit (5/5 each). No new t() string.
2026-10-07 07:08:17 +08:00
yetone 1ef6c92670 tests: a fake that a test runs under a fixed wait is a file macOS has already let run, so the first-run check no longer kills it on a loaded Mac (WSL omp probe, Reasonix CLI, Grok install)
TestWSLProbeFindsBunOmp, TestReasonixCLIRequiresSupportedNativeVersion,
TestReasonixCLIRecoversAfterProbeTimeout and TestGrokInstallsWithoutShell
failed in loaded full runs and passed alone. None of the causes was a
serialized probe, a lock held across the exec or CPU starving the fake.
Each test exec'd a newly written file under a fixed wait. On macOS a new
executable waits for the system's first-run check before its first
exec. That check is a queue shared with every other new program starting
(each package's test binary and its fakes), so under a go test ./... it
outlasts the wait:

- WSL omp: the fake `omp` was written with os.WriteFile (its `bun` was
  already a testenv.Program). The probe script's own `timeout 10 "$p"
  --version` killed it, so the version came back empty. It is a
  testenv.Program now.
- Reasonix: warmReasonixCLIFixture gave the freshly built Go binary's
  first launch 10s ("start native CLI fixture: signal: killed"). It now
  waits as long as the test runs (t.Context()), which is what the warm-up
  is for. The probe assertions after it still run under reasonixCLI's 2s.
- Grok: the installer runs the downloaded file with `--version` under its
  own 30s, and that file was always new. The test puts an already-run
  file at the download's temp path. The installer writes over it in place
  (O_TRUNC) and renames it, which keeps the pass.
- quota_served_cli_test's inert stand-ins (`exit 1`, each asked under a
  3s wait) are testenv.Programs too. They gave the same answer when killed,
  so this one cost time (5s at load), not a failure.

Production timeouts are unchanged. The WSL probe's 10s runs inside a
Linux distro, which has no such check. Grok's 30s verify and Reasonix's
2s probe of a binary that has already run passed in every loaded run
here. Reasonix doesn't cache a failed probe, so a first run that is slow
after an update is tried again on the next scan.

Evidence (macOS, load2.sh = the hjc load.sh recipe with N fresh-exec
loops, tests under `taskpolicy -c background`):
- A fresh 2-line script's first exec took 2.1-7.0s at 8 loops and
  10.7-14.2s at 32. Its second exec took 0.02s. A file written over in
  place and renamed ran in 0.02s.
- An instrumented copy of the omp test at 8 loops: a fresh omp hit
  `timeout 10` in 6 of 6 runs (version empty). The same test with omp as
  a testenv.Program took 0-1s in 6 of 6.
- TestWSLProbeFindsBunOmp at 32 loops: before 21.0s FAIL (version empty),
  9.3s, 9.6s. After 0.63s and 0.75s, plus 21.6s for the first run, which
  is the pool's one-time warm-up and has no timeout on it.
- TestGrokInstallsWithoutShell at 32 loops, before: "the downloaded Grok
  Build 1.2.3 doesn't run here: signal: killed" after 78s.
- TestReasonixCLIRequiresSupportedNativeVersion at 8 loops, before:
  "reasonix_test.go:178: start native CLI fixture: signal: killed" (12.0s).
- After the change, the four tests passed in every loaded A/B round
  (8/24/32 loops).
2026-10-07 07:08:16 +08:00
forever fb9d1a4cc6 provider, plugins: a sign-in reads as done only once its account is listed again, and the command line's plugin sign-in brings the account back and takes its lapsed mark off (#1061)
* provider: a sign-in reads as done only once the account it brings back is listed again, so the window opens it rather than saying magpie can't list it (TestClaudeTeamSeatBesidePersonal failed so on macOS in #1046's CI)

Signing in brings back an account removed from magpie (ShowAccount clears
its Hidden mark). Since 440e535b, (*signInFlow).finish recorded the outcome
and let go of the sign-in's lock before it called ShowAccount, so a poll of
SignInStatus could read done while the account was still hidden. The
window polls every 800ms and, seeing done, looks for the account to open;
missing, it says "{user} signed in, but magpie can't list it — please
report this". #1046's macOS job (run 37502933081) hit the same gap:
  signin_team_test.go:52: account after sign-in: false []
WaitSignIn, which the command line uses, waits for the end of finish and
was not affected.

finish now marks the sign-in finished first. Only the first finish records
an outcome, as before: a cancel or the timeout that comes after it is
refused, and so is a callback (claim). A done sign-in then calls
ShowAccount, and only after that reads as done. ShowAccount's error is
ignored, as before: if providers.json can't be written, the account stays
hidden and the sign-in still ends done. Until then the sign-in reads as
waiting; that takes longer only when the account was hidden, since only
then does ShowAccount write providers.json (and sync the agents' catalogs,
as it did inside finish before).

Every built-in and plugin sign-in's done goes through finish, so this one
change covers them all. The other places that show an account again do it
before their result can be seen: PluginAPIKey returns after ShowAccount,
and ImportLogins and ImportGoogleAccounts call it before they return. The
command line's own plugin sign-in never showed the account again; that is
a change of its own. ImportFactoryKeys shows none either, but the window
offers a Factory key's import only for a Factory it lists, and a removed
one is left out of the Add sheet. providers-accounts.md's sign-in row now
says when a sign-in reads as done.

Verified: TestSignInDoneOnceTheAccountIsBack records what the sign-in reads
as at the moment providers.json shows the account again (catalog.Changed),
for magpie's own callback (Codex), Claude Code's login run by magpie
(Claude) and a plugin's (FakeCo, with Bun). With finish from main all three
fail with "the sign-in read as done before its account was shown again:
the window, seeing it done, can't list it"; with this they pass.
TestSignInCanceledWhileTheAccountComesBack cancels the sign-in at that
moment and checks it still ends done, the account listed; with this finish
guarded on the state alone, as main's was, it fails with a "close of
closed channel" panic in the callback. With a 300ms sleep where main's
finish lets go of its lock, TestClaudeTeamSeatBesidePersonal fails 10 of
10 runs, each in a process of its own, with #1046's message; main as it is
passes 10 of 10 here, the gap being that narrow. With the same sleep after
this finish publishes done, or before its ShowAccount, it passes 10 of 10.
Under a temporary HOME with Bun 1.4.2, -race -count=20 on those three
tests and -race -count=2 on the package's sign-in, plugin and login tests
pass, as do go vet and the darwin, GOOS=linux (nogui) and GOOS=windows
builds; this commit alone builds and passes internal/provider.
With the next commit, go test -tags nogui ./... passes on main at 443f1cbc
and at 0bf9d77d. Three earlier full runs failed, each only in
internal/plugin, which is unchanged and imports nothing changed here:
twice TestHostJSCancellation/ready-wait at its 10-second Node deadline
(signal: killed) while other sessions' tests loaded the machine, the
timeout 76dc5aed and #1036 also record, and once, with Bun 1.3.13,
TestPluginHTTP2TakesTheProxy.
The GUI suite was not run: nothing in internal/gui/assets changes, and its
tests answer /api/signin from fixtures. Not tried with a real vendor's
sign-in.

* plugins: magpie plugin login and magpie accounts add finish a plugin's sign-in as the window does, bringing back a provider removed from magpie and taking the account's lapsed mark off

The window's sign-in to a plugin's provider, once the plugin has saved
the account, takes the account's lapsed mark off and shows again the
agent's own account removed in magpie (clearPluginLapse), and brings the
provider back if it was removed from magpie (ShowAccount): pluginDone
through finish, and PluginAPIKey for a key. The command line's
(pluginLogin, which magpie plugin login runs, as magpie accounts add does
for a plugin's provider or a subscription moved onto one) said "✓ signed
in to …" and did none of it:
- a provider removed from magpie stayed out of magpie providers, the
  agents' catalogs and routing until it was added back (in the window, or
  with magpie provider add);
- an account signed in again after its vendor turned the sign-in away
  still said "sign in again" until a request or a usage read went through
  it;
- an agent's own account (Kiro's, Devin's, …) removed in magpie stayed
  hidden after it was signed in to again, though the window's sign-in
  shows it again (#320).

PluginSignedIn now does all three for a sign-in magpie doesn't follow
itself, and PluginAPIKey and pluginLogin call it. providers-accounts.md's
sign-in row says so.

Verified: TestAccountsAddBringsBackARemovedPlugin signs in to FakeCo, the
plugin host's test plugin, with a key, removes it from magpie and runs
magpie accounts add fakeco with another key.
TestPluginLoginTakesTheLapseOff signs in with magpie plugin login's
browser way (open and xdg-open stubbed), has a usage read mark the
account lapsed as FakeCo's answer says, and signs in again. With
plugins_cli.go from main they fail with "signed in again, but not listed:
no provider "fakeco" — magpie providers lists them" and "signed in again,
but still lapsed: [{… Lapsed:gone@fake's FakeCo sign-in has expired —
sign in again …}]"; with this they pass. With PluginSignedIn's
ShowAccount taken out only the first fails, and with its clearPluginLapse
taken out only the second. Neither covers the own account: FakeCo has
none, and no test covers that part of clearPluginLapse on main either.
Under a temporary HOME with Bun 1.4.2, -race -count=5 on the two and on
TestAccountsOfAPlugin pass. Like TestAccountsOfAPlugin, the two are in
the root package, which has no testenv.Offline, so the plugin host they
start asks models.dev for its catalog.
go test -tags nogui ./... passes on main at 443f1cbc and at 0bf9d77d. Two
earlier full runs failed only internal/plugin's
TestHostJSCancellation/ready-wait at its 10-second Node deadline (signal:
killed) while other sessions' tests loaded the machine, the timeout
76dc5aed and #1036 also record; internal/plugin is unchanged and imports
nothing changed here.
Not tried with a real plugin's sign-in.
2026-10-07 06:24:24 +08:00
yetone 395c4bc51e tests: a test that sets time.Local does it through testenv.Zone, which first waits out the stand-ins' first runs — their os.Stat reads time.Local, and TestDsh -race alone raced it every run
testenv.StandIns (06420a71) starts each stand-in once in the background on
macOS and records it with os.Stat, which reads time.Local. internal/
sessions' inZone, internal/usage's TestDayFilterDST and the root package's
sessions CLI setup assigned time.Local while those runs could still be
under way. `go test -race -run '^TestDsh$' ./internal/sessions` reported
the race 6 of 6 runs on main (stats_test.go:14 against program.go:140).

testenv.Zone(t, loc) waits on the same WaitGroup RemovePrograms waits on,
sets time.Local and restores it in a Cleanup; the three helpers use it.
The root setup registers Zone before its own Cleanup, so the zone still
goes back after sessions.Reset's index write, as before.

After: the same command 0 races in 6 runs; -race -count=20 of
Dsh|DST over sessions and usage, -race -count=3 of the root Sessions
tests, -race of sessions/testenv/usage/root, go vet, gofmt pass. Tests only.
2026-10-07 06:17:56 +08:00
yetone 2c2137beb7 sessions: a DeepSeek Harness session can be deleted — its folder, its subagents' and their cached listing rows go to magpie's trash, and Restore puts them back (lc on Discord: deepseek harness无法删除会话)
Deletable left dsh out, so the Sessions page said magpie could list dsh's
sessions but not delete them. dsh keeps each session as files of its own
(dsh-session-persistence-jsonl, root $DSH_HOME/sessions from dsh-base's
cordis.patch.yml): <sessions>/--<cwd>--/<id escaped by encodeSegment>/ with
every format generation and session.lock; a subagent's session is a folder
of its own whose header names its parent. dsh's listing caches a row per
session at storages/session_projcache/sessions/<id>.json (per-record
dsh-storage-json); dsh itself deletes nothing ("Nothing deletes session
files"), so there is no index to keep in step.

The delete moves each of the group's session folders and its cached row.
A folder is taken only when its name is the session id as dsh escapes it
and it sits two levels under the sessions root; when any file of the
group isn't in such a folder nothing is moved, so another session's files
never go with it.

Tested: TestDshDeleteRestore on dsh 0.2.0-rc.2's real layout (zstd frames,
session.v4 plus a v3 left behind, session.lock, a subagent, a second
session in the same project folder that stays untouched, ErrActive while
written), TestDshDeleteOnlyItsOwnFolder, TestDshSegment (checked against
dsh's own encodeSegment run in node). Fails with dsh out of Deletable.
With the real dsh 0.2.0-rc.2 in a sandbox DSH_HOME: two `dsh headless`
sessions, magpie deleted one (folder + cached row), restore gave a tree
identical to the original (diff -r), deleted again: `dsh headless
--session-id` on the other still resumes it, and on the deleted one says
it does not exist. go test -race -count=5 of the delete tests, go vet,
gofmt, go test -tags nogui ./... pass. No GUI change: the page already
offers delete when the API says deletable.

Siblings checked: Cline keeps sessions.db as its session list (its own
deleteSession removes the rows, checkpoint refs and files), so moving files
alone would leave it listing them; Grok Build keeps session_search.sqlite;
Droid's layout is only known from a closed binary. They stay list-only.
2026-10-07 06:17:56 +08:00
yetone 11ec99de71 providers: a provider whose id isn't one magpie would make (b.ai, put in providers.json by hand) saves, and its editor's ID renames it, where every Save said "provider id must be lowercase letters, digits and dashes"
01huadalang on Discord (screenshot): 我不管改成什么都显示不能用 b.ai,我没用 b.ai
做名字和 id. The provider was stored under the id "b.ai". The editor's Save
first saves the rest under the id the provider has, then renames it, and
provider.Save refused any id that isn't a slug, stored or not, so the
provider could be neither changed nor renamed to one that is right. An id
providers.json has already is now saved as it is; a new provider still
can't be given one (Add, imports, backups and the rename's target are
checked as before).

Verified: TestStoredOddIDSavedAndRenamed (stored b.ai saved, renamed to bai
with key and URL kept, a new c.ai refused) fails without the change. In a
sandbox HOME with the built binary and the real GUI: a provider stored as
"b.ai", ID typed as "bai" and Save showed the reporter's exact error on a build without
this change (Save as on origin/main); with it the editor closes and providers.json has
id bai, was ["b.ai"].
2026-10-07 06:14:20 +08:00
yetone 40ece3a0d1 gui: a provider's Save keeps the tag, website and key page set from the CLI or TUI, and on a preset's provider its Balance and Models URLs, which the editor doesn't show
Found while tracing 01huadalang's report (Discord, a Responses pick reopening
as OpenAI compatible): POST /api/provider/save replaces the whole provider
with what the editor sent, and the editor never sends family, website or
keysUrl (nor balance, balancePath and modelsUrl for a preset's provider,
whose editor has no field for them). So `magpie provider set x family=…`
or the TUI's "f" was undone by the next Save in the GUI. A field the
request leaves empty now keeps its saved value.

Verified: TestProviderSaveKeepsWhatTheEditorDoesntShow (preset and custom
cases) fails without the providers.go change and passes with it. In a
sandbox HOME with the built binary: `provider set relay-a family=relays
website=… keys=…`, then renamed and saved Relay A in the real GUI;
providers.json kept all three and baseAPI "responses".
2026-10-07 06:14:20 +08:00
yetone 54b4e36dcf providers, gui: a custom provider saved as OpenAI Responses opens as OpenAI Responses, not OpenAI compatible (01huadalang on Discord: 我选 response 保存了然后再打开一会就变成 openai 兼容了)
The editor never saved which API the Base URL was picked as; reopening
showed the first API with a URL, chat first. A provider added as OpenAI
compatible keeps its chat URL when Responses is picked (#105), so after
Responses was picked, its URL typed and saved, it opened as OpenAI
compatible again. Picked with no URL of its own, the Save sent nothing
for it and the pick was gone without a word.

Now the pick is saved with the provider (baseAPI), sent back to the
editor and shown while it has a URL; a save that doesn't say keeps it,
and one whose URL is cleared elsewhere drops it. A Save with the picked
API's URL empty while another has one says so in the form. Requests are
unchanged: they go by which URLs are set.

Verified: reproduced on origin/main in a sandbox HOME with the built
binary (magpie web, real GUI via Playwright, fake Responses-only upstream):
a provider added as OpenAI compatible, then saved as Responses with and
without its URL typed, reopened as OpenAI compatible. With the change it
reopens as OpenAI Responses after a reload, a 65s wait and an app
restart, and the empty Save shows the message. A provider added as
Responses from the start was already kept and still is.
TestProviderBaseAPIKept fails without the change ("added as OpenAI
compatible, shown as \"\""); provider-base-api.test.cjs fails on the old
app.js (actual 'OpenAI compatible', expected 'OpenAI Responses') and
passes in Chromium and WebKit, en and zh. gui-ja, gui-de, i18n-keys and
the provider*/system-one/azure/add-sheet/menu-scroll GUI tests pass in
both engines. go vet, GOOS=linux/windows builds, go test -tags nogui ./...
pass under a temp HOME.
2026-10-07 06:14:20 +08:00
yetone e13f151302 gateway tests: TestConcurrentRedactedCountTokens' children run the stand-in CLIs their parent already ran, and stop at the parent's deadline rather than a fixed 20s
The test re-executes its own binary once per mode so the redaction key
cache is cold. Each child went through TestMain again, which wrote all
eight stand-in CLIs (security, claude, codex, cursor-agent, devin, ...)
into a new temp home. On macOS a newly written program waits for the
system's first-run check before it runs. The child's fixture,
provider.Save, calls Accounts(), which runs those stand-ins (cursor and
devin identity asks, each waited for up to 3s, and `security` for the
Claude credential). So the child spent its budget on account discovery
it doesn't test. The masked count_tokens work under test takes ~6ms.

Evidence (stacks from the child's own timeout panic): every timed-out
child sat in provider.Save -> Accounts -> cliIdentity.get /
askDevinStatus / askCursorStatus / readClaudeCredential, waiting on a
stand-in's exec. None was in redact or count_tokens. Timing provider.Save
in the child under scratchpad load.sh (CPU burners plus new-script exec
loops), 6 interleaved runs each: 5.7-9.4s before, 3.9-5.1s after (one
8.1s). Idle: 4-6s before, 1.7-2.2s after. Under `taskpolicy -c
background` the old children timed out at 20s in 2 of 4 runs and in 2 of
6 earlier ones.

What remains after that is CPU starvation. Under background QoS at load
average ~150, children still went past 20s. Their stacks were runnable in
json encoding, or in `security` exec'd from a stand-in that had already
run, with nothing blocked. So the child's -test.timeout is now 90% of
the parent's remaining deadline instead of a fixed 20s. A child that
really hangs still prints its stacks before the parent's run ends.

Children now take the parent's stand-in folder from
MAGPIE_GATEWAY_TEST_STAND_INS. A child still gets its own temp HOME and
XDG folders.

Verified: -race -count=10 of the test; go test -race ./internal/gateway
(ok, 739s on a loaded machine; TestLargeRequestEndpoints alone took 272s
under -race, so the default 10m -timeout is too short there); go vet
./...; full go test -tags nogui ./... has gateway ok (298s).
2026-10-07 06:10:06 +08:00
forever ee7ab461c5 gateway tests: a Claude Code run a test keeps for the next turn ends with the test, so -count no longer gathers 11 fake Claude Code processes a round (#1060)
Six tests have their server keep a Claude Code run for a conversation's
next turn, which the bridge holds for idleLongest (an hour):
TestClaudeRunKeptForTheNextTurn, TestClaudeOneOffAskNotKept,
TestClaudeRunLetGoWhenTheConversationMovedOn and
TestClaudeRunKeptAcrossEffort (claude_subscription_test.go),
TestClaudeRunKeptAfterTheClientsOwnToolCall and
TestCodexThreadKeepsItsClaudeRunAcrossAMemoryCall. Nothing ended those
runs, so each test's fake Claude Code ran on until the test binary
exited, 11 more each round: under -race -count=50, gateway.test had 77
of them after about 8 rounds.

Each now ends its server's runs as the gateway does when it stops,
t.Cleanup(s.subscription.abortAll), like the tests that already keep
runs. fakeClaude, and TestClaudeRunKeptAcrossEffort's own fake, register
runsEndWithTest before New(), so it runs after the test's cleanups: it
fails the test when a run of that fake is still in its server's bridge
and not ended, and ends it. Like the park sweep, it counts a run killed
or exited, on its way out of the bridge, as ended.

Without the six abortAll cleanups the six tests fail:

    claude_subscription_foreign_test.go:19: Claude Code runs the test started, still going after it: 3
    --- FAIL: TestClaudeRunKeptAfterTheClientsOwnToolCall
    claude_subscription_test.go:148: Claude Code runs the test started, still going after it: 3
    --- FAIL: TestClaudeRunKeptForTheNextTurn
    claude_subscription_test.go:192: Claude Code runs the test started, still going after it: 1
    --- FAIL: TestClaudeOneOffAskNotKept
    claude_subscription_test.go:349: Claude Code runs the test started, still going after it: 2
    --- FAIL: TestClaudeRunLetGoWhenTheConversationMovedOn
    claude_subscription_test.go:571: Claude Code runs the test started, still going after it: 1
    --- FAIL: TestClaudeRunKeptAcrossEffort
    codex_developer_cache_test.go:73: Claude Code runs the test started, still going after it: 1
    --- FAIL: TestCodexThreadKeepsItsClaudeRunAcrossAMemoryCall

With them they pass.

The test binary's processes after each round of -count=3, each test run
alone with a probe that lists gateway.test's descendants after it: before,
3, 6, 9 (TestClaudeRunKeptForTheNextTurn,
TestClaudeRunKeptAfterTheClientsOwnToolCall), 2, 4, 6
(TestClaudeRunLetGoWhenTheConversationMovedOn) and 1, 2, 3 (the other
three); the six in one run 11, 22, 33. After, none for each. The
package's other tests, run the same way one by one, left none running
into their next round: in a first round the probe saw only the stand-ins
TestMain runs once (testenv.StandIns), and once a fake of
TestClaudeBridgeSafeguardContextUpdates that abortAll had just killed.
The 21 that need bun, which end their plugin host with plugin.Settle, and
the live Codex test were skipped here.

-race -count=20 of the six passes. gofmt -l, go vet ./..., go build ./...,
GOOS=linux go build -tags nogui ./..., GOOS=windows go build ./... and
go test -tags nogui ./... pass under a temp HOME with Go's caches pinned.
Tests only.
2026-10-07 05:59:51 +08:00
yetone a24458ca4b providers: a Copilot Business seat that has used up its premium requests reads as used up, not unlimited (#1063, n1majne3: Github copilot Bussiness额度用尽时显示为无限)
magpie counted a quota_snapshots entry only when has_quota was true. GitHub
sends has_quota false for an allowance that is used up, and under
token-based billing for every snapshot, so an exhausted seat's
premium_interactions was dropped and the card showed only Chat and
Completions, both unlimited. The snapshot is now read as VS Code's
chatEntitlementService (parseQuotas, getQuotaUsage, isChatQuotaExceeded)
reads it:

- an entitlement of 0 on a limited snapshot is no allowance (left out);
  otherwise used = entitlement - quota_remaining, or 100 - percent_remaining
  when quota_remaining is absent; neither known is unknown and left out,
  never unlimited;
- entitlement, quota_remaining and quota_reset_at come as numbers or as
  strings ("3900"); a string used to fail the whole reading;
- an organization's pooled premium allowance (unlimited true, has_quota
  false) is used up, not unlimited; chat and completions keep reading
  unlimited, as VS Code reads them;
- quota_reset_at, when set, is the snapshot's own reset;
- premium past its allowance with overage_permitted no longer stops a Pro
  account (Aside), while a Business or Enterprise seat stops whatever it
  says, as VS Code pauses it ("Contact your administrator").

GUI card, tray, TUI and CLI all render these windows, so none of them
changes. TestCopilotUsageReadsEverySeat (a real Pro+ response from
api.github.com, Business left / used up as numbers and as strings, Business
with overage, Enterprise pool spent / left, routing over each),
TestCopilotUsageFreeUnderTokenBilling and TestCopilotUsageUnknownIsNotUnlimited
fail on the old code (no Premium requests window; "cannot unmarshal string
into ... entitlement of type float64"). Not tried with a real Business seat:
its shapes are VS Code's test fixtures and the Pro+ account's live bytes.
2026-10-07 05:52:14 +08:00
yetone d2aa2e1f4e gui: Settings' "Codex's own pick" chips draw their OpenAI mark at the chip's 14px, not the row's 18–22px (duanckham on X) 2026-10-07 05:43:53 +08:00
yetone 6f65ffb5ff agent: CodeBuddy Code, Cline, Gemini CLI, AtomCode, Goose and Reasonix installed in a WSL distro are found and wired there (lgtm on Discord: magpie 现在无法检测到安装在wsl中的codebuddy呀?)
wslKinds had none of these CLIs, so each was set up only on Windows.
Each now has a place-aware constructor (codebuddyIn, clineIn, geminiIn,
atomcodeIn, gooseIn, reasonixIn). It writes the distro's own config with
the gateway as the distro reaches it (mirrored or NAT) and the key it
takes from there. A distro reads none of Windows' variables
(CODEBUDDY_CONFIG_DIR, CLINE_DIR, APPDATA...). Kinds are found by their
folder or their command. Gemini CLI is found by its command alone,
because Antigravity keeps ~/.gemini too. Goose is found by its folder
alone, because a goose command can be pressly's. Reasonix also needs a
native version (new wslKind.accept). Gemini CLI also counts a .env that
names an old address with magpie's key as magpie's own. Before this, a
WSL restart that moved the distro's address made it read "custom", and
picking the model again stashed magpie's old address as the user's.

Verified:
- On the Windows test box (WSL2 magpie-desktop, NAT), with a sandboxed
  nogui magpie.exe (own USERPROFILE/APPDATA, port 3441), real CodeBuddy
  Code 2.161.4, Gemini CLI 0.63.0 and Cline CLI 3.0.68 were installed in
  the distro. `magpie ls` listed each as "· WSL magpie-desktop".
  Picking relay/glm-4.6 wrote ~/.codebuddy/models.json, ~/.gemini/.env +
  settings.json and ~/.cline/data/settings/providers.json in the distro
  at http://172.17.32.1:3441, and wrote nothing in the sandbox home's
  agent folders. The installs were removed afterwards.
- Not tried for real: AtomCode, Goose and Reasonix in a distro, and a
  chat request from a WSL CLI through the gateway.
- Tests: gofmt; go vet ./...; -race on internal/agent; the full
  `go test -tags nogui ./...`; GOOS=windows and GOOS=linux builds.
  TestWSLProbeFindsMoreAgents and the rest of TestWSLMore* panic with
  "no WSL agent codebuddy" on the old wsl.go.
  TestWSLGeminiAddressMoved fails ("auth custom") without the gemini
  routed change.
2026-10-07 05:37:27 +08:00
yetone 51626258d1 gui tests: text-size zooms the page out only after the 100% post and the click's frame, as the webview does (scrolled from 120 to 61, max 78, since bd33e575's font rows made Settings run past the window's foot)
The test resized the page in the same frame as the click, while the Mac header still drew at 150%'s 33px: the view was 17px taller for a moment and the browser clamped its scroll to it. In magpie the webview zooms only once Go has the post (textsize.go), frames later. Before bd33e575 Settings fit the window and was clamped to 0 either way. Passes 3 runs in a row in Chromium and WebKit, and still fails 2 cases with newTextSize's reset (#911) taken out.
2026-10-07 05:21:17 +08:00
yetone 61838f7c94 gui tests: codex-auto-reset clicks its account group's Show more, not the panel's Arrange, which 490d2ea3 made a .pq-more too (strict-mode violation on .pq-more since the panel's Allowances tab got Arrange at its foot)
Passes in Chromium and WebKit.
2026-10-07 05:10:01 +08:00
yetone 134d388ba0 gui: a call's JSON tree keeps its keyboard focus styles in Safari before 15.4 — :focus-visible goes in rules of its own (old-webkit failed on 5b9b9c9b's .jt-fold and .jt-copy selector lists, which those Safaris drop whole, hover included)
old-webkit passes; json-tree passes in Chromium and WebKit.
2026-10-07 05:10:01 +08:00
yetone 479865bcfd gui: a Providers row with a vendor's outage badge is laid out by a class, not :has(), which Safari 15.0 doesn't parse (old-webkit failed on 2a990175's .provider .name:has(> .badge.upstream) since #971)
The Providers row's name gets with-upstream while it holds the badge, and loses it when the badge goes. old-webkit's style check passes this rule again; upstream-status passes in Chromium and WebKit.
2026-10-07 05:10:01 +08:00
yetone d9b2cdc593 plugin tests: TestHostJSCancellation's ready-wait cancels 1,000 bootstrap waits rather than 30,000, so it finishes inside its 10 s under a full suite's load
ready-wait failed twice on 10-07 in full `go test -tags nogui ./...` runs on
main ("signal: killed" at 10.00s) and passed alone. The cause is the test's
size, not the host's cancellation. The case runs 30,000 fetch+abort rounds,
each waiting at least one setImmediate turn. That takes ~4s alone, 4.4-8.5s
beside a full go test ./... plus CPU and fresh-script load loops, and more
than 10s when starved (taskpolicy -c background with every core busy: killed
3 of 3). The cost per round stays flat from 5,000 to 120,000 rounds (no growth,
so no leak), and the counts at the end are exact: retainedWaiters 0, one
reaction on the shared ready promise, one drain listener.

Those counts are what catches a leak, and they catch it at any size. With
1,000 rounds, leaving the waiter in readyWaiters fails with retainedWaiters
1000, and a reaction per request on the shared ready promise fails with
retainedReadyReactions 1000.

Before: starved, 3 of 3 runs killed at 10.04-10.26s; -race -count=20 79.9s.
After: starved, 5 of 5 pass (ready-wait 0.6-5.6s, mostly node startup);
-race -count=20 9.9s.
No production code changed.
2026-10-07 04:37:31 +08:00
yetone d5468283bb gateway: a web page that isn't listed in Settings, on this computer or the gateway's own address is refused 403 on every route
On loopback a call needs no key and the body's Content-Type isn't
checked, so any page the user visited could send a "simple" text/plain
POST to 127.0.0.1:3425 and spend their subscriptions without reading the
reply. corsGuard now refuses a request whose Origin is an http(s) origin
that is not on Settings → Network and sharing → Web pages, not loopback
(localhost, *.localhost, 127.0.0.0/8, [::1], any port) and not the
request's own (host:port equal to Host). usemagpie.ai still reads
/v1/magpie/omarchy. No Origin (agents), "null" and non-http schemes
(app://, file://, tauri://, vscode-webview://, chrome-extension://) pass
as before: those clients could only call before by not enforcing CORS,
and no web page can send those origins. Such a page never read a reply
before (no CORS headers), so nothing that worked is refused.

Verified: TestForeignPagesRefused (text/plain POSTs from https://evil.example
and other foreign origins on every route family: /v1/chat/completions,
/v1/responses, /v1/messages, count_tokens, /v1/systemone, /v1beta,
/v1/embeddings, /v1/rerank, images, videos, the Codex backend path, /mcp,
/_magpie/claude-mcp, /v1/magpie/*, /v1/models, the GET /v1/responses
upgrade, OPTIONS; loopback, *.localhost, listed with a key, same-origin
on a LAN address through lanGuard, no Origin, null, app://, file://,
tauri://, vscode-webview://, chrome-extension:// answered) fails without
the change (120 routes answered, the fake vendor reached 139 times).
go test -tags nogui ./... green; -race -count=10 on the CORS tests;
darwin, linux nogui and windows builds. The built binary served from a
sandbox HOME on 127.0.0.1:3591: curl from the foreign origins got 403 on
every route with the vendor untouched; the allowed origins got 200.
2026-10-07 04:31:03 +08:00
yetone 7837f90d00 gateway: a listed web page's call with a gateway key is answered by the running gateway, not refused 401
On the real server lanGuard sits in front of Handler and, for a gateway
key sent from this computer, records the caller and puts magpie's own
token in the key's place, so corsGuard never saw the key and refused every
listed page's call with "a web page calls magpie with a gateway key".
corsGuard now also takes the caller lanGuard recorded.

Verified: TestCORSKeyThroughTheServer (lanGuard(Handler), a listed origin
with and without a key) fails without the change (401 for the keyed call)
and passes with it; TestCORSOrigins passes.
2026-10-07 04:31:03 +08:00
yetone 82a36a35c7 click-scroll test: Live and a day, and the room kept for a click, are checked where the accounts sit beside the requests (1440px) — red on main since 5d871723 (#860)
5d871723 moved the Routing page's two columns from an 860px to a 1150px
Routing area. At the test's 1100px window the accounts now go below the
requests, so scrolling the view to its end takes the date bar out of sight
first, and "Live and a day, picked in turn, stay under the pointer" and
"the room kept for a click goes as the reader scrolls back" failed in
Chromium and WebKit on every run ("what's clicked must be in sight").
b2345078 and 76d82528 shipped saying they fail the same on origin/main.
Those two subtests open the page at 1440px, the layout they were written
for; the rest stay at 1100, one column, as before.

Verified: git bisect (69665a69 good) names 5d871723; the file fails 2 of 9
per engine on origin/main and passes 18 of 18 three runs in a row with
this change (Playwright 1.63, Chromium and WebKit).
2026-10-07 04:30:26 +08:00
yetone 780b3fa3da docs: the FAQ says how to let an agent reach magpie through Surge, Clash or mihomo: rules that send 127.0.0.0/8 and ::1 direct (amor90s, baksili_ on X: Codex got 502 from the proxy and magpie saw nothing) 2026-10-07 04:28:25 +08:00
forever 90960edcb7 gateway: the Routing view keeps a day's routes when a request that began before midnight is done after the day was gzipped, and lists the day once (waitingsnow) (#1057)
saveRoute writes a done route to the file of the day it began, and
pruneHistory, at most once an hour, gzips every day before today. gzipFile
wrote <day>.jsonl.gz whole from <day>.jsonl and removed the file, so a
request that began before midnight and was done after the first prune past
it (a long streamed reply, say) went into a new <day>.jsonl, and the next
prune gzipped that over the day's .gz: every other route of the day was
lost, and only the late ones were left. While both files were there,
History listed the day twice.

  * gzipFile keeps a day's .gz and adds the file's routes after it as a
    gzip member of their own, which the gzip reader reads back as one
    stream. The new .gz is written to <day>.jsonl.gz.tmp and renamed over
    the old one (steady.Rename), and the file is removed only once that is
    done.
  * A route the .gz has already is not added again: a file added and left
    behind (magpie stopped before removing it) adds only what was written
    to it since, however many times that happens. The .gz is read a route
    at a time and matched against a set made from the file's lines, never
    held whole unzipped.
  * A .gz that doesn't read to its end, or ends in a route cut short (an
    older magpie stopped, or the disk filled, while it or its file was
    written), is written anew from its whole routes and the file's when the
    file has a route to add. Added after the break, the file's routes could
    never be read, and after a route cut short the first of them would join
    it. A last route whole but for its newline is kept. The old gzipFile
    mended a .gz cut short by writing it over from its file, and this keeps
    that.
  * A .gz that can't be read, other than for not being there, is unknown,
    not empty: it and the file are left as they are for a later prune.
  * pruneHistory removes a <day>.jsonl.gz.tmp once it is an hour old, left
    by a magpie stopped between the write and the rename. A younger one
    may be another magpie's, still being written.
  * History counts a day's .jsonl beside its .gz into one entry of its day
    list.

A day with only its .jsonl, the usual case, is gzipped to the same lines
as before at the same cost: 6.3 MB allocated for a real 4.5 MB day, here
and upstream. A late route beside a real day's .gz (569 KB, 5,481 routes)
allocates 14.7 MB and takes about 16 ms; upstream allocated 1.1 MB in under
a millisecond, writing over the day. While a file added and left behind is
there, until the next prune, History counts its routes twice, as it did
before.

Tests, with what upstream's history.go gives:
  * TestHistoryKeepsALateRouteWithItsDay: a route done after its day's
    prune, the file it went to left behind once with nothing written since
    and twice with a late route written to it, and an older day beside it.
    Upstream lists the day twice before the second prune ([{2026-09-29 1}
    {2026-09-29 1} {2026-09-28 1}]), and after it returns routes [2] and
    "route 1 not found".
  * TestHistoryKeepsADayCutShort: a .gz cut short while written in place,
    its whole file still there, comes back [1 2 3]; a .gz gzipped from a
    file whose last route was cut short, a late route written since, comes
    back [1 3]; one whose last route had no newline comes back [1 2 3].
    Upstream returns [3] for the last two (the late file written over the
    day), and passes the first, which it mends the same way.
  * TestHistoryLeavesADayItCantRead: a .gz that can't be read keeps the
    file beside it, and both read back [1 2] once it can be. Upstream
    returns [2]. It skips where a file at mode 0 still reads: as root, on
    Windows, or on a file system without Unix permissions.
  * TestHistoryDropsALeftGzTmp: a .gz.tmp an hour and a minute old goes,
    one written just now stays. Upstream leaves both.
Each part was also broken on its own, and each break fails a test:
History's old day list (the day twice), matching a file left behind by the
.gz's last member instead of by line ([1 2 2 3 3 4]), no check for a route
the .gz has ([1 2 2]), adding after a .gz cut short ([1] and "flate:
corrupt input before offset 41"), a mend that drops the .gz's routes ([2
3]), no check of the .gz's last newline ([1]), dropping a whole last route
without its newline ([1 3]), keeping a route cut short (4 routes counted
for 3), reading an unreadable .gz as empty ([2]), no sweep of the .gz.tmp,
and a sweep with no hour's grace. Writing the .gz in place instead of
through the .tmp passes them all: the atomic replace isn't covered by a
test.

Verified on 0bf9d77d, under a temporary HOME with Go's caches pinned:
gofmt -l, go vet ./..., go build, GOOS=linux go build -tags nogui and
GOOS=windows go build pass; the four new tests pass with -race -count=20,
and the history tests with -race -count=10. go test -tags nogui ./...
passes but for internal/plugin, whose tests don't build internal/gateway:
its TestHostJSCancellation/ready-wait ran past its 10s limit with the
load average at about 25 to 35, and passes alone (4.6s).
On a copy of a real routing directory, one late route on 2026-10-05 left
that day's 5,481 routes in place and listed it once with 5,482; upstream
kept the late route alone. Not tried on Windows itself. Two magpies pruning
the same directory at once (during a take-over) aren't covered: history.mu
holds within one process only.
2026-10-07 04:21:29 +08:00
yetone 443f1cbc2d gateway: a held stream's first keepalive reads only magpie's notes until the vendor's reply has its status, so it never races the try writing the reply's headers
go test -race ./internal/gateway failed in TestQuietStreamsKeptAliveEveryProtocol
(chat held) with six data races: keepAlive, on watch's goroutine, sent the
held stream's 200 with the try's headers by iterating holdWriter.header,
while the try's goroutine wrote that map with no lock: noteMember (#822's
X-Magpie-Provider/Model) and passthrough copying the vendor's headers in.
In production, a vendor that answers only after keepHeldAfter does the
same, and outside -race that can end the process with "concurrent map
iteration and map write".

Before the try has its status (WriteHeader, under mu), keepAlive now sends
only magpie's own notes, which noteMember sets under mu (holdWriter.note);
the vendor has said nothing yet, so nothing of its is lost. It also clones
what it copies, so the agent's header shares no slice with the try's.

TestKeepAliveBeforeTheVendorsHeaders (a try writing its headers while the
first comment goes out) reports the race on the old code (2 of 3 runs);
-race -count=20 passes, and so does the whole package under -race.
2026-10-07 03:58:27 +08:00