Files
magpie/internal/agent/codex_agents_v1_test.go
T
+13 81b7016e6e codex: warn, not write, when Codex's own multi_agent_v2 holds off magpie's V1 (#1028)
* agent: Grok App is an agent magpie connects: a magpie provider channel with magpie's models and their efforts (#1625, fjrtdk)

fjrtdk asked for Grok App (RongleCat/grok-app, a desktop GUI over the Grok
Build CLI) as a full agent: MCP, skills, RTK, models and effort.

What was already there, read in the App's source:
- MCP: the App reads ~/.grok/config.toml's [mcp_servers] in both of its
  modes and hands them to the CLI it starts, so the Grok Build row's MCP
  sync already reaches it.
- Skills: Grok Build's ~/.agents/skills, synced from the Grok Build row.
- RTK: rtk has no installer for Grok Build, so there is nothing to wire.

What was missing is models, and that is what changed:
- internal/agent/grokapp.go: a new agent, "grok-app" (alias grokapp), for
  the App's agent-home/config.toml under its data folder: GROK_APP_HOME,
  else ~/Library/Application Support/com.grokapp.grok-app or ~/.grok-app
  on a Mac, %APPDATA%\grokapp\grok-app\data (and two older places) on
  Windows, $XDG_DATA_HOME/grok-app or ~/.grok-app on Linux; the first
  that exists.
  - Connecting writes a [model.magpie] channel in the App's own format
    (its custom routes): model, base_url = the gateway's /v1, name,
    api_key (magpie-grok-app, so usage says the App), api_backend =
    "chat_completions", app_provider_mode = "generic", app_models and
    app_efforts as JSON strings (the App unquotes them with serde_json),
    supports_reasoning_effort, app_supports_vision for a model that takes
    images, and context_window when magpie knows it. app_models lists
    magpie's models with their effort levels ("none" left out), so the
    App's model and effort pickers show them.
  - It sets [models] default = "magpie"; what was there is stashed, and
    Disconnect puts it back and drops the channel: the file is
    byte-identical to before (TestGrokApp).
  - A sync keeps the model and the default effort the user picked in the
    App while magpie still serves them, and writes nothing when nothing
    changed.
  - Picking one of the App's own routes (the official "grok", or a
    channel of the user's with a base_url) takes magpie out.
  - The notice says to start a new chat or restart the App, which reads
    its providers when it starts an agent; translated in i18n.js (zh-CN,
    zh-TW, ja, de) and listed in NOTICES.
- agents.go, agentenv.go (GROK_APP_HOME), docs/reference.md,
  docs/subsystems/agent-wiring.md, both READMEs' agent lists.

Picking magpie in the App is a custom route, so the App runs that agent in
its independent mode (its own #557): it clears agent-home's auth.json
rather than syncing the official sign-in. ~/.grok is never written.

What was run:
- go test -tags nogui ./internal/agent ./internal/agentenv ./internal/gui:
  ok. Full go test -tags nogui ./... under a temp HOME: ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui: ok.
- Broken by hand, each red: context_window written quoted (TestGrokApp);
  the user's picked model ignored (TestGrokAppSyncKeepsTheirs); their
  default effort dropped (SyncKeepsTheirs); Disconnect not unstashing
  (TestGrokApp); a no-op sync writing (SyncKeepsTheirs); "none" listed
  as an effort (TestGrokApp).
- Real use in a sandbox HOME: a built magpie on 127.0.0.1:3681 with a
  fake upstream; `magpie grok-app magpie/fake/echo-1` wrote the channel;
  the real grok 1.0.50, started as the App starts it on a custom route
  (GROK_HOME=agent-home, --model magpie), answered through magpie, the
  upstream saw echo-1 and usage.jsonl counted agent "grok-app". `magpie
  grok-app default` restored the file (the only difference was grok's own
  [marketplace] line written while it ran). ~/.grok/config.toml untouched.

Not tried: the real Grok App GUI (it would sign in through the keychain
and ~/.grok), a model with effort levels end to end, Windows and Linux
paths beyond TestGrokAppDir.

* gui: on a Mac a region or agent strip scrolls with no bar, so a click right after a scroll picks the option under it (#1620)

tencent-cloud.test.cjs was red in WebKit now and then: a region clicked
was not picked. The cause, found by scrolling the strip from the test and
clicking 30ms later: on a Mac page (body.mac) WebKit shows its overlay
scrollbar over the lower half of a scrolled strip for a moment, and
elementsFromPoint at an option's centre returned the strip, not the
option. A press there goes to the bar's track, which pages the strip
sideways (smoothly, 198 -> 44) and picks nothing. A reader on a Mac who
scrolls the regions and clicks at once meets the same miss.

On a Mac these strips (.segs.regions, Connect's segs, #sessAgent) now
scroll with no bar, as a Mac's own tab strips do (scrollbar-width: none,
::-webkit-scrollbar display none). Other systems keep their thin bar.
z-index, isolation and position on the options didn't help; only hiding
the bar did.

Tests:
- tencent-cloud.test.cjs: new "a region clicked right after the strip
  scrolled is the one picked", 480x1200 (the strip in the window; it
  checks so), 10 rounds over 5 scroll positions. Without the CSS WebKit
  missed 39 of 50 clicks (40 of 50 on origin/main 5dfcf4346); with it 0.
- strip-scrollbar.test.cjs now says the Mac strip has no bar (width none,
  bar 0), and goes red without the CSS.

Run: tencent-cloud 20/20 green in WebKit and 20/20 in Chromium;
strip-scrollbar, sess-agent-strip, usage-sessions-agents-fit,
tencent-access-key, system-one, click-scroll, segs-press-redraw in both
engines (segs-press-redraw's Chromium 440px case is red now and then
under load in other trees too: it is one of the Settings tests #1659 is
moving onto the page's last settings read; green 8/8 in each engine
with this change).

* gui tests: codex-credits measures the credits row it finds, after the panel's own read has drawn it (#1622)

codex-credits.test.cjs was red in Chromium now and then: "the say fits
the panel's card" got a switch 0 wide. The cause, found by holding the
tray panel's own allowances read (usage/quotas?asked=1) 0-300ms: picking
the Allowances tab reads the accounts again, and its answer redraws the
cards (renderPanelQuota replaces them) 100-400ms after the click. fits()
found the row through a locator and measured it in a second step; a
redraw between the two left it measuring a row out of the page, all
zeros. Answered 0, 20 or 40ms late the old test failed every time; 60ms
and later it passed. Nothing a reader sees: the redraw is synchronous and
draws the same row.

fits() now finds and measures the row in one page.evaluate, and the panel
step waits for the tab's read to finish (quotasLoading) before measuring.

Run: with the read held 0, 20, 40, 60, 80, 100, 150, 200, 300ms the test
passes every time (en and de, Chromium); 20/20 green in Chromium and
20/20 in WebKit.

* gui tests: market-have waits for the market's answer, not 2s, before looking for a mark (#1631)

"a server added by hand is marked added" timed out under the full suite.
The mark comes after two reads in a row: the change's answer, then the
market asked again (take() -> fetchMarket). Holding those answers in the
test showed nothing is dropped: with the save, the library and the market
each held 0 to 1200ms the mark always came, at about the sum of the
holds. The 2s bound on the whole was the busy machine's to miss: with the
save and the market each held 1200ms the old test failed in both engines.

Each of the three steps now waits for the market's answer that follows
its change (10s, the page's 5s for each of the two reads), then for the
mark with the page's own timeout. What the test checks is that the mark
comes with no focus (still asserted), not how fast.

Run: the save, library and market each held 0, 1200 and 3000ms: 8/8
green in Chromium and WebKit each time. Broken by hand (take() no longer
asks the market again): all three steps red, 8 of 8. 20/20 green in
WebKit and 20/20 in Chromium.

* gui tests: privacy-hides-accounts scrolls to Hide accounts as a reader does, and usage-stale-answer lifts quotasOpened with loadUsage (#1632)

Both were red on origin/main when run alone; each had its own cause.

privacy-hides-accounts (WebKit, every run): since Settings' search box
(51042630e; the test passes on its parent and fails on it) the Hide
accounts row sits under the window's foot at 900x760. Playwright scrolls
it into view by code, and the click guard puts a scroll that isn't the
reader's back (a scrollIntoView from the page: 0 -> 38 -> 0 in both
engines); WebKit's click came after the put-back and hit the foot.
Nothing a reader meets: they scroll with the wheel. The test now wheels
the settings view until the row is clear of the foot, waits for the
scroll to settle, and checks the click doesn't move the view's own
scrollTop (it read window.scrollY, which is always 0 here, so "a click
never scrolls" checked nothing).

usage-stale-answer (every run): since #1588 (917a36577) loadUsage(asked)
calls quotasOpened(), which the test's faked page didn't have, so the
asked read threw before it read anything ([] for [true]). The test now
lifts quotasOpened and QUOTAS_OPEN_GAP from app.js with loadUsage, in
both of its pages. Broken by hand (loadUsage no longer opening the
allowances when asked): red again.

Run: privacy-hides-accounts 20/20 green in WebKit and 20/20 in Chromium;
usage-stale-answer 20/20; the other browserless GUI tests pass.

* gui tests: routing-side-calls measures a row once Routing's groups are in and the row has stayed put (#1640)

"a title and magpie's web search say what they were" failed with
"picking the request moved the row" in Chromium, now and then alone and
often under load. The row hadn't moved because of the click: it was
measured before the page was done. Recorded frame by frame, the day's
list draws at one frame and the part above it grows on a later one
(rt 271 -> 428px), while the click guard scrolls to hold the day that was
clicked (scrollTop 0 -> 176), so the rows move 444 -> 424 before any row
is clicked. The test measured "was" between the two. Holding Routing's
groups answer (/api/groups) 300, 600 or 1000ms makes the old test fail
in most runs (7 of 9 runs red); that is what landed late.

The test now waits for the first groups answer and for the row to stay
put for 10 frames before measuring. Nothing a reader sees changes: the
clicked day stays where it was, as the click guard means it to.

Run: with groups held 600 and 2500ms the fixed test is green
every run (3 runs each); 20/20 green in WebKit and 20/20 in Chromium.

* gui: a Sessions figure never wraps, so picking a project no longer moves the page

In Chinese at a 142pt tile (a 1100pt window beside the sidebar, or an
888pt one without it) "139 小时 27 分" broke onto a second line. Picking a
project shortened it to "4 小时 28 分", the row of figures lost 23pt and
everything under it moved up under the pointer.

- .kpi b keeps to one line (ellipsis and a title as the last resort).
- The active time's units are drawn smaller and muted, as the Health
  app draws "h" and "min", so the figure fits.
- The six figures go to three columns under 960pt of pane, not 820pt.

Run: sessions-overview (28/0) in Chromium and WebKit; before this it
failed at the project bar (505.8 vs 528.8) on main with the sidebar and
on d4eae3618 minus the sidebar at 888pt. number-units, usage-speed,
usage-speed-count, usage-refresh, usage-refresh-flight and
usage-ttft-rounding pass in both engines; go test ./internal/gui/ ok.
Screenshots of the tiles in en and zh at 1100 and 1400 looked right.

* gui tests: the sidebar's room

18e82adc6 shows the sidebar from 1024pt, so the window's pages are 212pt
narrower and start at x=212. Eight files assumed the old room:

- header-centre measures the tabs' gap from the layout button.
- phone-web's desktop browser at 1000pt, under the sidebar's width.
- routing-pause and routing-pointer-pin wheel over the view, not the
  sidebar at x<212.
- routing-scroll-end takes its columns from .rt-more's own width
  (routing.js byWidth); usage-pack opens at 1512 to keep 1300 of room.
- purpose-filter closes the menu by a scroll that ends at the view's
  top, and measures once the rows and scroll are at rest.
- sessions-overview scrolls the shape card no further than a third down,
  and waits a frame after a resize: WebKit starts the reduced-motion
  transition of the sidebar's padding and settles it in the next frame.

Run: all eight, plus sidebar, side-toggle, session-identity and
usage-ledger, pass in Chromium and WebKit; each failed with 18e82adc6
and passed on d4eae3618 with it reverted.

* agent tests: the sandbox home holds XDG_DATA_HOME and XDG_STATE_HOME too, so Grok App's drift test passes on Linux (#1668)

codexHome, the helper TestDriftUnwiredEveryAgent and others start from,
pointed HOME, XDG_CONFIG_HOME and XDG_CACHE_HOME at the test's home but
left XDG_DATA_HOME at testenv's. On Linux grokAppDir (ee7a9b24a) reads
$XDG_DATA_HOME/grok-app, so the App's config was written outside the
home the test walks, its base_url never swapped, and no drift showed:
"applied_test.go:219: unwired: <nil>" on ubuntu CI (run 38162553532).

Run: with grokAppOS forced to "linux" in a throwaway file, the test fails
exactly so without this and passes with it. go test ./internal/agent/
ok on macOS; gofmt clean; GOOS=linux and GOOS=windows go vet ok.

* provider, plugin: a subscription's sign-in goes through the proxy its account's requests use, not always the global one (#1663, demystify0137)

What changed: every sign-in started in magpie now leaves through the
account's own proxy (ProxyOfLogin: the account's, else the
subscription's, else the global one). Before, the sign-in's token
exchange and checks went through the global proxy while the account's
later refresh and usage calls went through its own (ViaLogin), so the
vendor saw one account come from two exits.

- signin.go: SignInOptions{Site, Proxy, User}, StartSignInWith; the flow
  picks its proxy (pickProxy, validated with settings.CheckProxy) and
  every request goes through s.via. Each built-in sign-in (Claude,
  Codex/ChatGPT, Grok, Zed, WorkBuddy, Copilot, ZCode, Factory, MiMo,
  Qoder, Command Code, Kiro) uses s.via; Claude Code's own login gets the
  proxy as *_PROXY (netproxy.EnvWith).
- proxy.go keepSignInProxy: a proxy picked for the sign-in is kept as
  the subscription's when the account is its only one, else as that
  account's own entry. "" (global) is refused while the subscription has
  a proxy and other accounts, since nothing could keep it.
- plugin host: authorize and callback run under via.run(proxy), so a
  plugin's sign-in fetches go through the same proxy; plugins_cli.go
  does the same for `magpie plugins login`. PluginAPIKey goes through Via.
- gui: POST /api/signin and /api/plugin-signin take proxy and user.

What was run:
- go test -tags nogui ./... (sandbox HOME), all packages ok.
- gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui on the
  touched packages.
- Red without the change (each broken by hand, then restored):
  TestSignInGoesThroughItsProxy, TestDeviceSignInGoesThroughItsProxy,
  TestPluginSignInGoesThroughItsProxy, TestClaudeSignInGoesThroughItsProxy
  (internal/provider) and TestPluginSignInProxy (internal/plugin) each
  fail with the s.via / EnvWith / via.run / keepSignInProxy removed.

Not tried: a real vendor account through a real proxy. The browser's own
leg of an OAuth sign-in goes through the browser's network, not magpie's.
Devin's CLI probes still use the global proxy.

* gui: the sign-in box shows the proxy it goes through, and another can be picked and kept as the account's (#1663, demystify0137)

What changed: while a sign-in waits (or after it failed), the box shows
"Proxy: …" beside Open again. It opens the app menu (openProtoMenu, no
native select) with Global (only when it could be kept), Direct, the
subscription's proxy, each account's proxy and Custom…, which asks for
an http://, https:// or socks5:// address. Picking one starts the
sign-in again through it and cancels the open one; when it ends, the
backend keeps the pick as the account's (keepSignInProxy). Userinfo in a
proxy URL is never shown. "Sign in again" on an account now names that
account (user), so it goes through the account's own proxy. The user and
the pick are carried through the risk, site and plugin-method steps.
Strings in zh, zh-TW, ja and de. docs/subsystems/providers-accounts.md
describes the sign-in proxy.

Why: the reporter asked that a sign-in use the subscription's or the
account's proxy and be able to choose one; the default now does, and
this lets the user choose and see it.

What was run:
- signin-proxy.test.cjs (new): Chromium and WebKit, en/zh/zh-TW/ja/de,
  at 900 and 380 wide, 40/40. It fails against HEAD's app.js (no link).
- The sign-in, add-sheet, plugin-signin, click-scroll, i18n-keys and
  gui-<lang> files: 203/203; signin-close.test.cjs updated (the acts row
  now also holds the proxy link).
- go test -tags nogui ./... ok; gofmt; linux/windows vet.

Not tried: a real vendor sign-in through a real proxy from the window.

* library: a visit to the Library no longer parses Codex's config.toml again when it hasn't changed (#1665, laowangba233)

laowangba233 saw magpie's CPU jump on each switch to a Library page.
Profiled in a sandbox HOME with a copy of a real Codex config.toml (1.5 MB,
10,927 [projects."<dir>"] tables, one per folder Codex was ever opened
in): 69% of GET /api/library's CPU was go-toml parsing that file through
foundServersOf -> mcpFile.entries. go-toml's SeenTracker looks each table
name up among every sibling before it, so the parse is quadratic in the
number of projects, ~0.2 s of CPU each time, and the Library parsed it on
every visit (edit.Read already kept the bytes, not the parse).

mcpFile.entries now keeps what it parsed through filememo, keyed by the
file's size and time (and, written in the last two seconds, its bytes),
and hands each caller a deep copy of the servers it found, so a caller
changing an entry doesn't change the next caller's. The RTK page's
codexSandbox (Windows, Codex with rtk on) parsed the same file the same
way on each visit and is kept the same way.

Measured (sandbox HOME, the copied config and library, macOS, 10 warm
GET /api/library after start): 2.67 s of CPU before, 0.55 s after
(~0.27 s -> ~0.055 s a visit).

TestCodexEntriesParsedOncePerChange: a config with 2000 projects read
four times parses once, a caller's change to the entries doesn't reach
the next, a change to the file is read, a file gone is no servers. It
fails with the memo undone (entries parsing edit.Read's bytes each time)
and with the copy undone. go test -tags nogui ./internal/library
./internal/filememo pass; TestCodexSandbox passes. The RTK memo has no
test of its own (Windows only); filememo's own tests cover the keep.

* sessions: a visit to Sessions no longer parses Codex's config.toml again when it hasn't changed (#1665, laowangba233)

Profiled for laowangba233's report of CPU jumping on page switches: in a
sandbox HOME with a copy of a real Codex config.toml (10,927
[projects."<dir>"] tables), 67% of GET /api/sessions/manage's CPU was
go-toml parsing config.toml in readCodexConfig, for the provider Codex
uses now (codexProviders -> CodexProviderIn). go-toml checks each table
name against every sibling before it, so a file with that many projects
takes ~0.2 s to parse, and it was parsed on every visit.

readCodexConfig now keeps the parse through filememo, keyed by the file's
size and time (and its bytes while it is less than two seconds old). Its
callers only read the struct.

Measured (sandbox HOME, 8.9 GB of copied sessions, macOS, 10 warm GET
/api/sessions/manage after start): 3.00 s of CPU before, 0.94 s after
(~0.30 s -> ~0.09 s a visit).

TestCodexConfigParsedOncePerChange rewrites config.toml with the same
size and time and expects the first parse; a real change is read. It
fails with the memo undone. go test -tags nogui ./internal/sessions passes.

* sessions: the warm-up at start reads with a quarter of the cores unless a page waits, and a long first read keeps what it read (#1665, laowangba233)

#1665: magpie pegs the CPU on every start (Windows Task Manager showed
95.8%). Three seconds after start, warmSessions indexes every Claude/Codex
session file and reads every file's calls for usage. refresh() ran
min(max(8, 2*NumCPU), 32) parsers at once and usage's prefetch 8 more, so the
background warm-up took every core while nobody was looking at the result.

Two goals, in one commit because they touch the same loop in refresh():

1. Quiet warm-up (quiet.go). gui's warmSessions runs inside
   sessions.Warm. While a warm-up runs and no request waits, every parse in
   refresh() and every readCalls takes one of max(1, NumCPU/4) slots. A
   request to /api/sessions* or /api/usage* (gui's held middleware) calls
   sessions.Ask(), which lifts the limit for as long as it runs, so a page
   the user opened isn't slowed down. A waiting reader re-checks every 50ms,
   so Ask takes effect mid-read.

2. Checkpoints. refresh() saved sessions.json only once all files were
   parsed. Quitting magpie before that (a slow machine, or the user closing
   it because the CPU is pegged) kept nothing, and the next start parsed
   every file again. Now every 5s (checkpointEvery) the files done so far
   are published and saved, if the cache generation still matches.

Measured on a Mac (14 cores) with a sandbox HOME holding 8.9 GB of real
sessions (copied read-only), sessions.json and calls-v11 removed, sampling
ps every 2s:
- cold start before: 41.2 CPU-s, peak 580-600%, done ~14s
- cold start after:  34.7 CPU-s, peak ~300-360%, done ~16s
- quit mid-index, before: quit at 6s (13.5 CPU-s spent) left no
  sessions.json and no calls files; the next start spent 41 CPU-s again.
- quit mid-index, after: quit at 12s left a 1.3 MB sessions.json (of
  3.0 MB); the next start spent 26.6 CPU-s instead of 34.7.

Tests (each red with its part undone, script-checked: refresh's slot
replaced by a no-op, readCalls' slot removed, the checkpoint block removed):
- TestWarmReadsOnlyInItsSlots: with every slot held, neither the index nor
  the calls read anything for 300ms; Ask() lets both finish.
- TestReadSlotOnlyWhileWarming: outside Warm, or while asked, reads don't
  wait.
- TestLongReadKeepsWhatItRead: a read held after its 3rd file has saved
  sessions.json with fewer files than it has to do.

Run: go test -tags nogui ./internal/sessions ./internal/gui
./internal/library ./internal/usage; gofmt -l; GOOS=linux and
GOOS=windows go vet of sessions, gui, library; full go test ./... before
push.
Not tried: the reporter's machine or data volume; a Windows re-measure.

* provider: signing out of ChatGPT and Devin's CLI checks go through the account's own proxy, as its sign-in does (#1663, demystify0137)

What changed: two siblings of 3a53d06d9 still left through the global
proxy, so an account's sign-out or its CLI checks came from a different
exit than its sign-in and requests.

- chatgpt_api.go forgetSIWCLogin: the refresh-token revoke (discovery and
  revocation endpoint) goes through ViaLogin for that account, read
  before the account is forgotten.
- devin_accounts.go devinCommand: `devin auth status` and `devin models
  list` run with the proxy ctx names (a sign-in's), else the account's own
  (devinProxy: the logins.json entry for that home, the CLI's own for "",
  ProxyOfLogin; the subscription's for a home not kept yet), via
  netproxy.EnvWith, where it was netproxy.Env (global).
- devin.go: askDevinStatusAt/askDevinIdentityAt/addDevinLogin take the
  sign-in's ctx, so the probe naming a just-signed-in account uses the
  proxy the sign-in goes through. askDevinIdentity had no caller left and
  is removed.
- docs/subsystems/providers-accounts.md says so.

What was run:
- go test -tags nogui ./... (sandbox HOME) ok; gofmt -l clean; GOOS=linux
  and GOOS=windows go vet -tags nogui on the touched packages.
- New TestChatGPTSignOutGoesThroughItsProxy and
  TestDevinCLIGoesThroughItsProxy (internal/provider/signin_proxy_test.go).
  Red by hand: the revoke with context.Background() (it dials
  openai.invalid directly); devinCommand without devinProxy (models and
  status run with no proxy); askDevinStatusAt ignoring the sign-in's ctx
  (the new account's probe runs with the subscription's proxy, not the
  picked one).

Not tried: a real ChatGPT or Devin account through a real proxy.
Left out on purpose: a `--proxy` flag for `magpie accounts add`, and the
installer's downloads (global proxy).

* agent: Hermes's other bots (profiles) get magpie's provider too, and Disconnect takes it out of each (lijiho96940561 on X)

Each Hermes bot is a profile at <root>/profiles/<name>/ whose config.yaml
is read on its own (hermes_cli/config.py get_config_path; load_config
doesn't fall back to the root's). magpie wrote providers.magpie only into
$HERMES_HOME/config.yaml, so only the main bot's picker offered magpie.

Now, with magpie connected, its provider entry also goes into the
config.yaml of every profile Hermes lists (hermes_cli/profiles.py and
hermes_constants.py, Hermes be5e9f72c): a name matching PROFILE_ID_RE,
not "default", not tombstoned under profiles/.deleted/, with a config.yaml.
The root follows get_default_hermes_root: ~/.hermes, or for a HERMES_HOME
outside it, <root> of <root>/profiles/<name>, else HERMES_HOME itself.
Connecting writes it there, and each Sync refreshes it and adds it to
profiles made later. Only providers.magpie is written, so each bot's own
model.default/model.provider stays as its user set them. Disconnect deletes
providers.magpie from every profile. In a profile whose model.provider is
magpie (cloned from a connected main config, or picked in that bot), the
model and provider are deleted too, so the profile isn't left naming a
provider that is gone. There's no stash for those, so Hermes falls back to
its defaults there.

Run: go test ./... -count=1 under a scratchpad HOME (all ok); gofmt -l; go
vet ./internal/agent for darwin, linux and windows. TestHermesProfiles and
TestHermesProfilesOfCustomRoot fail on the old hermes.go ("coder after
connect"). Fixtures follow Hermes's profile layout, read from its source.
Not tried with a real Hermes running several bots; the live ~/.hermes was
not touched and hermes was not run.

* gateway: a 429 that says in words when it's back rests until then, in Chinese as in English (#1669, Natsumeretsu)

WorkBuddy answers a frequency limit with the time it resets, in words:
"将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at
2026-10-11 12:37:53 UTC+8, ...". resetsAt read neither (only Claude
Code's "limit reached|<unix>" and ChatGPT's resets_at), so the Chinese
one rested quotaRest (15 min, matched 用量) and the English one
fallbackCooldown (1 min, no word list matched): the account was asked
again long before it was back, refused, and benched again.

- resetsWritten reads a time beside the reset phrasing (resetsWhen:
  "reset(s) at", 将在/将于), in the UTC/GMT offset it is written with.
  The offset must be followed by 重置 or punctuation, so a refusal cut
  after "UTC" or "UTC+" is never read as UTC; a date that isn't real,
  one past, or more than a week off (longestWritten) isn't read; another
  vendor's date in passing ("deprecated on ...", "retry after ...") is no
  reset. resetsAt falls back to it, so keepRetry notes it too.
- failure reads such a 429 as out of quota in either language.
- One that points to the account's other models ("切换其他模型",
  "switch to the other models") rests that model alone (restID), so
  the account's other models are still asked during an hours-long rest.
- rateRest: a reset time the refusal names (resetsAt, or as keepRetry
  noted it) is believed up to longestQuota, as the quota branch does,
  and the trace says "resets"; a Retry-After or rate-limit reset header
  stays held to longestWait. Decided: the stated time is the vendor's
  statement of when the account is back, and how far it is believed
  shouldn't hang on which word list the message happened to match
  (8 days as quota vs 1 hour as rate for the same words); a Retry-After
  is generic advice and keeps the hour.

The rest is the gateway's, so it holds for moved WorkBuddy users too:
the plugin (packages/workbuddy 0.1.14, explained()) passes a 429 that
isn't "unapproved channel"/14018 on as it came.
TestPluginWrittenResetRests shows a plugin-served 429 with the
reporter's refusal resting the model until the stated time.

Tests: TestResetsWritten (reporter's bytes in both languages, other
offsets, cut-short, garbled, past, >7 days, other vendors' dates),
TestWrittenResetRestsUntilThen (both languages rest the model by
"resets", noted path, cut-short falls back, other vendors' 429s
unchanged), TestRateLimitBelievesItsReset, TestPluginWrittenResetRests.
Broke each piece by hand (reader, classification, rate cap, model
scope, offset, the terminator) and each made one of them fail.
TestRateLimitBacksOffWhenItComesBack now expects "resets" for a noted
reset. go test -tags nogui ./... under a temp HOME, rebased
on 498b77fbc, passes but internal/provider's
TestCopilotSecretToolUsername, which this doesn't touch: it is #1627
(5s secret-tool bound under load) and fails alone 3 of 5 on this head
too. internal/gateway rerun after rebasing on 6ebe481f8; gofmt -l, go
vet for darwin, GOOS=linux and GOOS=windows on internal/gateway.
Not tried against WorkBuddy itself: its raw 429 JSON shape isn't
known beyond the message (err_type 6004), and a body that escapes the
Chinese as \uXXXX wouldn't be read (the reporter's classification by
用量 shows theirs isn't escaped).

* gui tests: click-scroll's late wheel is looked at once the page has heard it and the reader's moment is over, not after a fixed 400ms (#1660)

"a wheel the page hears of after its scroll is still the reader's" failed
once in Chromium on a loaded machine.

Cause: the subtest delays the app's wheel listener by 60ms (the busy page
of the subtest), then waited a fixed 400ms before looking at the view,
and 100ms after a scroll by code. The listener opens a 250ms moment in
which scrolls are the reader's (readerScrolls(250)). That moment starts
when the page hears the wheel, not when the wheel happens. When the
machine ran the 60ms timer more than ~150ms late, the code's scroll that
followed fell inside that moment and stood ("code's scroll is put
back"). Later still, the view was looked at before the wheel was heard
("the late-heard wheel must scroll the view").

Fix: the wrapper counts the wheels the page has heard. Each wheel is
looked at once the page has heard it and performance.now() has passed
purposeUntil, the end of the reader's moment. The code's scroll is
looked at three frames on, since it is put back at the frame it is told
of. The wait of 100ms before the last wheel stays as a minimum gap: what
was put back from 50ms before a wheel counts as that wheel's own
(givesBack). The page is unchanged.

Run (injected: the late wheel's delay raised from 60ms, the test copied
to the scratchpad with only that number changed):
- Before, Chromium:
  - 200ms: 4 of 22 cases red, "code's scroll is put back".
  - 500ms: 4 of 22 red, "the late-heard wheel must scroll the view".
  - 60ms: green.
- After:
  - 200ms Chromium: 22 of 22.
  - 500ms Chromium: 22 of 22.
  - 500ms WebKit: 22 of 22.
- Broken by hand: with givesBack left out of the wheel listener, the
  test is red on "the late-heard wheel must scroll the view".
- A first try with no gap before the last wheel went red: the code's
  scroll was handed to the wheel. That is why the 100ms stays.
- click-scroll.test.cjs, both engines, 20 runs: 440 of 440 cases passed, with a load average of 12 to 17.

* gui tests: the 37 other Settings tests act on rows once the page has drawn its last read of the settings, as the masking-rules tests do since #1653 (#1659)

Opening Settings reads the settings twice: the page's own read
(showView), then the window's load() once the state is in. Each read
redraws every row. A test that found a row after the first draw, and
then called scrollIntoViewIfNeeded or boundingBox on it, failed when the
second read landed in between. The errors were "Element is not
attached", or a null box. #1653 fixed the three masking-rules tests and
listed these 37 in #1659.

Each of the 37 now calls watchSettingsReads(page) before every
page.goto, and settingsDrawn(page) right after it. Right after goto is
exact for ?view=settings: at boot, show(view) asks for showView's read
before load() runs. load() sets load.done in the same run that then asks
for its own read, so settingsDrawn's "load.done and every read asked
for drawn" holds only once the second read is drawn. For a test opened
on another page that clicks into Settings later, load is done by then,
the click makes the only read, and the wait passes at once.
watchSettingsReads now watches a page once, however many times it is
opened, since some of these tests open one page several times. The
page is unchanged.

Reproduced with a generic injection (scratchpad inject1659.cjs, loaded
with NODE_OPTIONS=--require). A route added at each goto holds the
page's second GET /api/settings. It lets the read go just as the test
calls scrollIntoViewIfNeeded or boundingBox, or waits on the page with
waitForFunction (which settingsDrawn is), with a 4s timer as a backstop.
This is #1653's injection, made generic.

Before, injected, both engines, all languages:
- 5 files red with the issue's error:
  - github-token: null box.
  - member-model-setting, searcher-pick, search-first and update-wait:
    "Element is not attached to the DOM".
- 4 files red on a check of a row drawn from the first read:
  model-suffix-own, otel, readable-focus and warm-at-times.
- 28 green.

After, injected: 36 of the 37 files green, every held read let go by
settingsDrawn's wait. otel stays red in WebKit at 360px. It is red the
same way with no injection, on origin/main's own copy of the test. That
cause is separate (the narrow nav laid out after setViewportSize
returns) and has its own commit next.

Plain (no injection), both engines, all 37 files: 460 cases passed and
2 failed, both otel's WebKit 360px check above.

The 8 files red under injection before, injected again after,
5 rounds: 390 of 390 cases passed.

* gui tests: otel measures its rows at each width two frames after resizing, since WebKit can still hand back the old width's layout when setViewportSize returns

otel's "no overflowing controls at 360px" was red in WebKit with no
change to the page, on origin/main's own copy of the test too (1 of 6
cases passed, 2 runs, at a load average near 11). #1659's injected runs
first showed it.

A probe at each width, run straight after setViewportSize and again two
frames later, showed the cause. Going from 1100px to 520px, innerWidth
is already 520 and body no longer has side-nav. But the views still
start at left 212, the side nav's padding at the old width. #otelList
measures 268px instead of 488px. Two frames later the views start at 0
and the list is 488px. At 360px a row then measured 106-108px instead
of 320px, so its control overflowed it.

The test now waits two requestAnimationFrames after each
setViewportSize before measuring. The page is unchanged: a user's
window is drawn at its new width by the next frame.

Run (WebKit, the engine that was red):
- Without the wait: 14 of 15 cases red over 5 runs, each on "no
  overflowing controls at 360px".
- With it: 20 runs, 60 of 60 cases passed (load average 15-16).

33 other test files measure right after setViewportSize. They are filed
as a follow-up, not changed here.

* gateway: a Claude run its timer ended mid-reply is no longer kept idle, holding one of 6 places (#1667)

A resumed turn's 30-minute timer calls abort. Fired during a reply,
finish closed the run and removeRun took it out of b.idle, where it
wasn't yet. The reply's last event, already in the segment, still
reached the client whole, so ended was told ok and kept the closed run
with keepIdle, then re-armed its timer. That timer found it closed and
never took it out, so it held one of idleMost places until pushed out,
and the push-out shelved a session removeRun may already have deleted.
letGo's keepIdle had the same window.

keepIdle now reads r.closed under b.mu and refuses an ended run,
returning false; ended and letGo then return without re-arming the
timer or rewinding. finish sets closed before removeRun takes b.mu, so a
run is either refused here or kept and then taken out by removeRun.

Tests: TestClaudeRunEndedMidReplyIsNotKeptIdle fires the run's timer
(abort through removeRun) and then calls ended with a whole reply. On
the old code it fails: "a run its timer ended mid-reply is kept idle (1
runs), holding a slot of 6"; it passes with the fix. TestClaudeIdle*
kept closed runs only so abort did nothing; they now keep live runs, and
TestClaudeIdleReplacementKeepsItsKey sets the other run at old's key
directly, since keeping it there through keepIdle would end old.

Run: go test -race -run 'Claude|Subscription|Idle|LetGo|Rewind'
./internal/gateway (ok); the full suite is in the next commit's body.
Not tried with a real Claude Code: the window needs a 30-minute reply.

* gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)

The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.

decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.

Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:

                    CPU in the request's handler    time per request
                    (pprof, per request)            (ns/op)
  anthropic         154ms -> 45ms                   208-212ms -> 52ms
  anthropic, group  178ms -> 51ms                   249-262ms -> 65-67ms
  chat              122ms -> 35ms                   167-254ms -> 50-54ms
  responses         215ms -> 56ms                   294-452ms -> 70ms

TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).

Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
  Responses; direct, through a group, translated to each other protocol,
  with images, thinking, escapes, odd spacing, a repeated key, and four
  2 MB conversations) and compares what the vendor gets with
  testdata/upstream_bodies, recorded on the code before this change
  (all 18 identical; three runs agreed). Breaking decodeJSON's \n
  unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
  json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
  the gateway's, and jsonValid with json.Valid, over seeds, every cut
  and a changed byte at every place of each seed, and 2.5 minutes of
  fuzzing (~1.75M inputs). Breaking the validator's control-byte check
  by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
  origin/main 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).

* gui: the header is fitted again when the language or the interface font changes, so the tabs no longer run under the magpie and the traffic lights (kiwiflysky on X)

With a wide interface font, the macOS window's header fit in Chinese but not
in English, Japanese or German: the tabs slid left under the magpie and the
window's buttons, and in German into the refresh button and the gear.
fitTop draws the header in step by step (tight, cramped, inrow, crowded,
packed), but it only ran again when .top, .brand or .actions changed size
(ResizeObserver) and once on document.fonts.ready. Another language or a
font picked later changes only #nav's width, so the header kept the fit it
had for the old one.

Now translateStatic (every language change) and desktopFonts.apply (every
font applied: picked, saved in the other webview, from settings) call
fitTop, and document.fonts' loadingdone does too, for a font still loading
when it's applied. Both run synchronously, where the change happens. A
ResizeObserver on #nav was tried first. It had to defer to a frame, since
fitting resizes the nav and WebKit reports that loop as a page error, and the
deferred refit moved the page after a click: text-size, number-units,
tray-logos and rail-tip went red. That approach was dropped.

Measured (830px, macOS window, before): switched live to en, ja and de, the
tabs ran 61, 105 and 148px under the magpie (Chromium and WebKit alike).

header-relang.test.cjs (new):
- Opens a macOS window in Chinese, with the header's tabs picked over the
  sidebar.
- Switches it from Settings to en, zh-TW, ja, de and back.
- In English, on the Agents page, it hands in Menlo at each width from 1000
  to 640px. Each fit must equal a fresh fitTop.
- Sweeps each language from 1100 to 600px: 7.5px clear of the magpie or
  padding and of the buttons.
- Chromium and WebKit.

Run on this commit:
- header-relang: 12/12 in Chromium and WebKit. Red on origin/main 781cb386c
  (en -61.5, ja -104.6, de -148.0 before the rebase onto the sidebar; ja
  -50.8, de -94.3 after it). Red with only the language hook removed (2
  subtests). Red with only the font hook removed (5 subtests:
  "top tight" where a fresh fit is "top tight cramped").
- Header, font, click-scroll and language neighbours: 77/77.
- text-size, number-units, tray-logos, rail-tip and menu-scroll alone: pass.
- Full GUI suite, concurrency 3, rebased on 781cb386c: 6261/6347. Each of
  the 19 failing files was run alone with this change and without it, at
  the same tree; the counts were the same (a few ±1 each way).
- On 6ebe481f8, after 054bdb8bb's sidebar fixes, 5 files are still red with
  or without this change: routing-group-fold, text-size (foot of the page),
  routing-sessions, pick-skills, otel. Filed as #1672.
- go test ./internal/gui/: TestPanelCloseHidesIt and
  TestTrayCellClickReleasedPanel fail the same on a fresh origin/main
  94fd332c3 (#1664, #1661). Everything else is ok.

Not done: in German the Settings page's sub-tabs wrap to two lines, and in
English and Japanese the "Find a setting" box drops to its own row. That is
wrapping, not overlap, and left for its own change. Beside the sidebar (from
1024px, the default since 18e82adc6) the header has no tabs. Checked by
screenshot in de with Menlo at 1100 and 1024px: nothing overlaps.

* gateway: an error that escapes its Chinese as \uXXXX is read as one that doesn't, for why it failed and when it's back (#1669, Natsumeretsu)

Every word list that decides why a reply failed (creditWords,
brokeWords, rateWords, plannedWords, usedUpWords, quotaCodes) and
af0558e6d's resetsWhen were matched against the raw body. A JSON error
whose encoder escapes what isn't ASCII (Python's json.dumps by default)
carries 用量 as 用量, so none of the Chinese words matched:
WorkBuddy's escaped refusal read as a 1-minute rate limit with no reset
time, Zhipu's escaped 1113 "余额不足…请充值" as a rate limit instead of
out of credit, a sub2api key's escaped "7天限额已用完" as a rate limit
instead of out of quota.

wordsOf is the one shared point: a JSON body containing \u has its
string values decoded and put after it, one to a line; any other body
is matched as it is. failure() matches its words on it, resetsWritten
reads the reset from it, the per-model rest's otherModels check uses
it, and the two creditWords checks beside failure() (fallback.go's
same-one retry, patience.go's busy) use it too.

Tests: TestResetsWritten gains the reporter's Chinese refusal escaped
(read, 3h16m2s) and escaped-but-cut-short (not read);
TestWrittenResetRestsUntilThen rests the escaped refusal's model until
then; TestFailureReadsEscapedWords: escaped Zhipu 1113 is credit,
escaped sub2api 7天限额已用完 is quota, escaped WorkBuddy is quota.
With wordsOf returning the body unchanged, all three fail.
internal/gateway passes; go test -tags nogui ./... under a temp HOME;
gofmt -l, go vet darwin, GOOS=linux, GOOS=windows on internal/gateway.

* provider: a magpie run from a terminal that only lists accounts no longer writes logins.json, and every change to it is made under a lock the gateway holds too, so a token the gateway just refreshed is never written back over (#1674, FaintGhost)

Every CLI command that reached Logins() (magpie ls, providers, sessions,
usage) ran rememberLogins, whose 30-second throttle (loginsSeenAt) lives
in the process, so in a new process it never held: each run moved Seen on
for the signed-in Codex and Claude accounts and wrote logins.json back.
loginsMu was an in-process mutex, so that read-modify-write could
interleave with the gateway's renewSavedLogin: the CLI reads, the gateway
writes a refreshed sign-in, the CLI writes what it read. Codex/OpenAI
refresh tokens are single use, so the account would be signed out.

- rememberLogins writes nothing when the only change is Seen and the saved
  Seen is less than seenEvery (10 minutes) old (onlySeenMoved, comparing
  with what was read, IDs and order normalised as writeLogins writes them;
  sortLogins is split out of writeLogins for that).
- internal/filelock (new): davsync's TryLock/Unlock (flock; LockFileEx on
  Windows) moved here and davsync uses it; Lock(path, wait) and
  filelock.Mutex, a sync.Mutex that also holds the OS lock on a lock file.
  A lock another magpie holds is waited for up to filelock.Wait (10s),
  then gone on without, as before, so a stuck magpie never hangs others.
- loginsMu is a filelock.Mutex on logins.json.lock, so all 107 existing
  Lock sites (every writeLogins is under one) are cross-process with no
  change at the call sites. Taking it calls filememo.Look (new), so the
  read under it isn't a parse filememo.Hold kept from before another
  magpie's write. savedTokenMu holds logins.json.renew.lock the same way:
  two magpies never refresh one saved account at once.
- Siblings: caller-keys.json (access.mu: magpie keys from the CLI vs the
  window; a lost revoke would bring a key back) and mcp-signins.json
  (mcpauth.fileMu, plus mcp-signins.json.renew.lock around renew, since
  library's MCP check renews from the CLI too) get the same lock.
  plugin-auth.json already has one (plugin-auth.json.lock, shared with
  host.js). Not covered: providers.json (33 store sites with no
  in-process lock either; user-entered keys, nothing refreshed there),
  migrations.json/settings.json (no credentials), and the agents' own
  files (~/.codex/auth.json etc.: the agent itself writes them without
  any lock of ours, so a magpie-only lock can't make them safe).

Tests:
- TestReadOnlyRunLeavesLogins: Codex and Claude signed in, Seen a minute
  old, file time set back; three "new processes" of Logins("")/codex/
  claude/All() leave logins.json's bytes and mtime as they were. Seen an
  hour old is written; Codex's own refresh is written at once.
- TestLoginsKeepAnotherMagpiesWrite: between this process's read and write
  (beforeLoginsWrite hook) a second test process (TestLoginsOtherMagpie,
  os.Args[0] -test.run) renews the saved work@ account's refresh token;
  both the renewed token and this process's change are in the file.
- TestLoginsReadAfreshUnderLock: with filememo.Hold held, a write
  filememo never heard of is seen by a read under loginsMu.
- TestLockAcrossProcesses (filelock): a holder subprocess makes Lock wait
  and give up after its wait; killed, the lock is free; a Mutex holds it.

Broken by hand: onlySeenMoved bypassed -> TestReadOnlyRunLeavesLogins
FAIL "a run that only listed the accounts wrote logins.json"; the file
lock taken out of filelock.Mutex.Lock -> TestLoginsKeepAnotherMagpiesWrite
FAIL "the other magpie's renewed sign-in was written over"; Locked hook
emptied -> TestLoginsReadAfreshUnderLock FAIL. Each restored, green.

Ran: gofmt -l (nothing); go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags
nogui, GOOS=windows go build; go test -tags nogui -count=1 ./... under a
temp HOME with pinned caches: all ok but internal/provider, whose
TestReadOnlyRunLeavesLogins failed at that point from its own fixture
(two rewrites of one size given the same mtime read as unchanged by
filememo); fixed in the test, then internal/provider, access, mcpauth,
filememo, filelock and davsync -count=1 all ok, and the three new provider
tests -race -count=10 ok.

Not tried: the reporter's Linux arm64 box with a real systemd gateway and
real Codex accounts; Windows (LockFileEx path) only vetted and built, not
run on the Windows box.

* gui: on niri the tray panel opens under the bar beside the clicked icon, not in the middle of the screen (#1670, Kenoia)

A Wayland window can't place itself. Under niri the panel opened where niri
floats a new window, the middle of the output. Hyprland already had an
adapter (omarchy/hypr.go); niri now has one too.

niri (checked in niri v26.04's source, niri-ipc/src/lib.rs and
src/ipc/server.rs) can't add window rules at runtime and doesn't report the
pointer over IPC. So omarchy.NiriPanel watches niri's event stream
($NIRI_SOCKET, one line of JSON per message) and moves each window of
magpie's pid titled "magpie panel" once as it opens:
MoveWindowToFloating if it was tiled, then MoveFloatingWindow with SetFixed
x/y, which count from the working area's top-left (below the bar). It goes 6
px under the bar, centred on the x that the tray host passed to the SNI
Activate(x, y), kept inside the output. Wails' Linux tray keeps that x in
private fields (lastClickX/lastClickY), read the same way trayProps already
reads props; TestTrayClickIsWails reads Wails' source to fail if they move.
Noctalia passes bar-surface-local coordinates, so the x is taken across
the focused output. With no click (`magpie panel`), or with one off the
output, it goes to the top right. Wails' HideOnFocusLost closes it when
another window takes the focus.

What was run:
- go test -race ./internal/omarchy/, go test ./internal/gui/ (sandbox
  HOME, pinned GOMODCACHE/GOCACHE). The IPC fixtures are built from
  niri-ipc 26.4.0's Window/Output/Event/Reply types, quoted in the test.
- Broke it by hand: dropping the placed-once map fails TestWatchWindows
  (placed [7 7 9 9 9]); dropping the right-edge clamp fails TestPanelSpot.
- gofmt -l; go vet (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...; linux nogui and windows builds.
- A nested niri 26.04 (winit backend on Xvfb, scale 1.5, Fedora 43
  container, magpie built with -tags gtk3), with SNI Activate sent via
  dbus-send. Activate(300, 14) put the panel at [58, 6] (300 - 484/2).
  A second Activate closed it. `magpie panel` reopened it at the top right
  (853 - 484 - 6 = 363). Activate(800, 14) clamped it to 363. `magpie gui`
  taking the focus closed it.

Not tried: a real niri desktop, Noctalia or another real tray host
(Waybar, ironbar), more than one monitor, a bar at the bottom or the side
(not accounted for), focus-follows-mouse. The panel still opens in the
middle and slides up; how visible that is on real hardware wasn't seen.

Not from this change: omarchy's TestCurrent fails with -count=2 on main
(it passes with -count=1).

* omarchy tests: TestCurrent starts from no theme read, so a second run (-count=2) isn't handed the first run's cached font

Current keeps the last theme it read for a second, and the package state
outlived the test, so the second run's first read came back from the cache
with the font the first run ended on. Seen while working on #1670.

Ran: go test -count=2 -run 'TestCurrent$' ./internal/omarchy/ fails on
f13111797 (font "JetBrains Mono"... then "Iosevka"...), passes with
-count=3 after; go test ./internal/omarchy/, gofmt -l, GOOS=linux go vet.

* gui: the sidebar's edge drags it wider or narrower, kept for the window; dragged well past its narrowest it folds away, as a Mac app's sidebar does (enzyme_dev on X)

The sidebar was always 212 points (184 in a narrow window). Its right
edge is now a separator (role=separator, col-resize, no-drag for the
window): dragged, it follows the hand between 168 and 320 points, the page
beside it moving with it, and the width is kept in localStorage
(magpie.sideWidth). A narrow window has it no wider than 36% of itself, so
the page keeps its room, and back at full width when the window is. Dragged
more than 64 points under its narrowest it folds into the header's tabs
(the same as the title bar's button), and comes back at the width it had
before that drag. The arrow keys move it 8 points, 32 with Shift. Under a
coarse pointer (an iPad's magpie web) the edge is 24 points wide for a
finger; a phone's magpie web has no sidebar and so no edge. "Sidebar
width" (its label) in zh, zh-TW, ja and de.

Run: side-width.test.cjs (new) in Chromium and WebKit, 3 times each: the
drag mid-way and after, the narrowest and widest, every name and the magpie
whole at 168, the keys, a reload, a 760 window, the fold and its width on
return, an iPad touch drag (Chromium; WebKit's Playwright sends no touch
moves), a phone with no edge. Without the fold's reset the return width
test fails (168 for 240). sidebar, side-toggle, phone-web, mobile-web,
view-no-sideways, header-centre, text-size pass in both engines, except
WebKit text-size's two "100% picked at the foot" cases, which fail the same
on origin/main f13111797 and are #1672. go test ./internal/gui ok. Tried on
a sandbox magpie (go build -tags dev, own HOME, the owner's providers.json)
through its dev UI in WebKit: dragged to 173, to 301, kept after a reload,
folded and back at 301; and `magpie web` on a 390 phone (no sidebar,
nothing sideways) and a 1180 iPad (the sidebar, 320). Not tried by hand in
the real Wails window.

* gateway, gui: magpie's image recognition is an MCP server of its own, /mcp/magpie/vision, with one analyze_image tool (JonahFu on X)

What: beside /mcp/magpie/web-search, the gateway serves the model that
describes images (Settings › Models › Image recognition, else magpie's
automatic pick) as a Streamable HTTP MCP server. analyze_image takes an
image (absolute file path, http(s) URL or data:image URL) and an optional
prompt: without one it is described as a model's image is (same cache and
system text), with one the prompt is asked beside it. The JSON-RPC serving,
guard and Origin check are shared with the web search server (serveMCP).
A file path is read only for a local, unproxied caller, up to 20 MB, and
only when its bytes are an image; another computer sends a URL or data
URL with a gateway key. Each call holds the key's limit (budget.Reserve)
and reads in Routing as the agent's analyze_image call. Settings › Models
shows the address under Image generation (#visionMcpRow), in every
language.

Run:
- go test -tags nogui ./... (no failures); gofmt -l clean; GOOS=linux and
  GOOS=windows go vet ./internal/gateway.
- New TestVisionMCPAnalyzesImage / WithNoSeer / Guarded / HeldToKeyLimit.
  Broke the local() guard by hand: TestVisionMCPGuarded went red on the
  other computer's file path being read.
- GUI (chromium + webkit, en/zh/zh-TW/ja/de, 1100 and 520px):
  vision-mcp, search-mcp, public-url-default, images-missing,
  settings-sections, i18n-keys, routing-vision-why: 95 pass. The row was
  first put between the two pickers and images-missing went red (it finds
  them by position), so it sits last.
- Real use: this build under a sandbox HOME holding only the owner's
  OpenRouter provider, Image recognition set to openai/gpt-6-luna.
  initialize, then tools/call with docs/screenshots/font-settings.png as a
  file path and a prompt: the model listed every settings row and its
  value correctly.
Not tried: a real agent (Claude Code, Cursor) mounting it; its MCP
exchange is the same as the web search server's.

* gui: Usage's subscription cards in one row are as tall as each other, so their bottoms line up (ikunbots on X)

ikunbots ("magpie 的这个卡片可以对齐吗") and duanjl_china ("有的长有的短"):
Claude Code, Codex and Antigravity sat side by side in one row on the
Usage page, each as tall as what it held, so their bottoms were ragged.

What changed
- packUsage (app.js) still packs the cards into columns as #860 made it
  (a short card stacks beside a tall one, never stretched to a row's
  height). After placing them, the last card in each column gets a
  min-height that takes it down to where the tallest column ends.
  - Cards side by side in one row (one card per column) are as tall as
    the tallest, bottoms on one line, content at each card's top.
  - A stack stays a stack: the upper cards are as tall as themselves and
    only the last one reaches down to end with the tall card beside it,
    which is what #860 asked for (堆叠和 Codex 对齐).
  - One column: each card is as tall as itself, nothing to line up.
  - The min-heights are cleared before every measuring, so a re-pack
    (resize, a fold opened, cards changed) measures each card as tall as
    itself. A min-height rather than a stretch keeps a card that outgrows
    it growing, so the ResizeObserver still re-packs.
- docs/subsystems/gui-shell.md says so.

Tests
- usage-pack.test.cjs:
  - New: ikunbots' three cards (Claude Code 2 windows, Codex, Antigravity
    6 families; content heights 107/169/217px) at 1400 and 1018px are one
    row with bottoms within 0.5px; at 480px one column, each card as tall
    as itself; widened again, one row lined up again.
  - The reporter's #860 stack at 897/1018/1400px still stacks:
    Antigravity as tall as itself, DeepSeek under it with the 7px gap,
    ending where Codex does.
  - sound(): a card is as tall as itself unless it is last in its column,
    which ends with the tallest; no card is shorter than its content.
  - The fold case: opening Codex's brief account grows what the card
    holds; the card already reaching down to the stack's end stays that
    tall rather than growing (was "the card grew").
- Broken by hand: no min-height applied -> "1400px: the cards' bottoms
  line up" red in all 8 (chromium/webkit x en/zh/ja/de); min-height not
  cleared before measuring -> "narrow: antigravity is as tall as itself"
  red. Restored: 8/8 pass.

Run
- usage-pack.test.cjs in Chromium and WebKit, en/zh/ja/de: 8/8 pass.
- Every GUI test file touching the Usage page (75 files, those naming
  #subscriptionUsage/.subscription-card/view=usage, plus click-scroll),
  both engines, concurrency 6: 917/918 pass. panel-usage webkit en failed
  once under that load ("asked: period=today&limit=1", a 2.4s poll in its
  Requests-window step this change doesn't reach), passes 3/3 alone;
  added to #1544 with its cause.
- Screenshots before/after with fixture data looked at: ragged row
  before, one line after; 897px stack unchanged but for DeepSeek/Codex
  ending together.
- No Go change; gofmt/vet/build not run. Full GUI suite not run.

* provider: a moved ZCode account is brought to plugin 0.1.16, whose app sign-in follows ZCode only while it is signed in to the same account (LingYi_Stu on X)

Raises the zcode mover's min so keepMovedCurrent updates every moved user
to @magpie-community/opencode-zcode-auth 0.1.16 (plugins d2be892). With
the "ZCode app's sign-in" added for account A and again after ZCode
switched to B, A's entry read ZCode's current credentials on every
request, so it sent B's requests and its usage card showed B. 0.1.16
follows ZCode only while ZCode's user is the entry's account; otherwise
it uses what was saved at sign-in, and asks for sign-in again when that
session has run out. Published by the plugins repo's publish workflow;
npm view says 0.1.16 is latest.

Run: go test ./internal/provider/ (ok, 99s); gofmt -l internal/provider
(clean); go vet ./internal/provider/ on darwin, GOOS=linux, GOOS=windows.

* gui: a client in the Usage page's Agents list can be hidden from it, and shown again from the line under it (ikunbots on X)

ikunbots asked to hide curl, Go-http-client, python-httpx and other clients
from the Agents list beside the agents they actually use.

What changed:
- Each Agents row has a "…" button that shows on hover (always on touch) and
  opens the app's row menu (openRowMenu) with "Hide from this list".
  Right-clicking the row opens the same menu. No native select.
- The hidden ids are saved by client id in settings.UsageAgentsHidden,
  trimmed and deduped. They go through POST /api/usage/arrange
  (agentsHidden), which changes only that field, and the Settings save
  carries the field over.
- Hiding is display only. The ledger keeps the calls, and the totals, the
  chart and every share still count them.
- When anything is hidden, a quiet "3 hidden" / "已隐藏 3 个" line sits under
  the list. It opens the hidden rows, dimmed, each with "Unhide" / "取消隐藏".
  No click scrolls the page: the scroll guard holds the clicked line in place.
- Where a pointer hovers, the "…" takes no room. Its margins give back its
  width and gap, so a row at rest is laid out as on main (mobile-web's
  desktop comparison is the same). It shows over the end of the share bar.
  On phones (body.web) it has its own grid column.
- Translated into zh, zh-TW, ja and de. docs/subsystems/gui-shell.md
  describes it.

What was run, in a worktree off origin/main:
- gofmt -l: clean.
- go build ./... and go vet ./...: pass.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: pass.
- HOME=<scratch> go test -tags nogui ./...: 49 packages ok. Includes the new
  TestUsageArrangeAgentsHidden, which covers saving, surviving a settings
  save, narrowing and emptying.
- New usage-agents-hide.test.cjs: 32/32 in Chromium and WebKit. It covers
  en, zh, zh-TW, ja and de at 1200, 560 and 390 (web). It hides by "…" and
  by right-click, checks the POST body, unchanged totals and an unmoved
  page, then unhides, reloads and checks the hidden rows persist.
- All 48 usage, panel-arrange and click-scroll GUI files: 503/503.
  old-webkit and mobile-web: pass.
- Full GUI suite (6489 tests, concurrency 5): the reds outside this change
  fail the same when run alone on origin/main 3deb85685, in WebKit only.
  They are filed in #1672 and #1609, and in #1745 (new: group-member-info,
  searcher-pick).
- Broken by hand:
  - Without the hidden filter in renderUsage, the new GUI test fails 16/16
    in Chromium (the shown rows still list curl).
  - Without the arrange handler, TestUsageArrangeAgentsHidden fails at
    line 82.
  - Without the Settings-save carry-over, it fails at line 84.

* gateway: a ChatGPT account's turn goes zstd-compressed, as Codex's own client sends it (ylorn on X)

ylorn (X, v0.1.1202) sent a text-only gpt-6-luna turn of 1,100,224 bytes
straight to chatgpt.com/backend-api/codex/responses. Sent plain it got 503.
The same turn zstd-compressed (259 B) got 200. magpie decodes Codex's
inbound zstd and sent the backend plain JSON, so the turn got 503 through
magpie too.

What Codex does (openai/codex a9b08151, 2026-10-11):
- codex-rs/core/src/client.rs:1704-1712 responses_request_compression:
  Zstd only with the enable_request_compression feature, a sign-in that
  uses_codex_backend, and the OpenAI provider.
- client.rs:1780: used for the POST /responses stream only.
  /responses/compact and /models go plain.
- codex-rs/features/src/lib.rs:1411-1416: the feature is Stable and on by
  default.
- codex-rs/protocol/src/auth.rs:54-63: uses_codex_backend is true for the
  ChatGPT sign-ins and false for ApiKey and Bedrock.
- codex-rs/codex-api/src/endpoint/responses.rs:130-147 sets it for
  /responses.
- codex-rs/http-client/src/request.rs:196-217 compresses with
  zstd encode_all at level 3, sets Content-Encoding: zstd, and never
  compresses twice.

What changed:
- provider.CodexCompressed compresses a body sent to CodexBase/responses
  with klauspost zstd, already a dependency. It uses SpeedDefault (about
  level 3) and no frame checksum, like libzstd's default. It sets
  Content-Encoding, Body, GetBody and ContentLength to the compressed
  bytes, and returns the wire size.
  - It is called once the body is final and signed: in forwardOnce for a
    codex account, in codexUpstreamOn (the relay) on every try (so a try
    again or a body without an unreadable image is compressed afresh), and
    in warmCodex.
  - Unchanged: /responses/compact, an sk- key's requests to api.openai.com,
    every key provider (even one at the same URL), and a body already
    encoded.
  - The plain body is still what magpie keeps, masks, traces and shows.
- codexDropped (#1628, a2b96139c/8029d98b7) judges "large request" by the
  bytes sent on the wire. A text turn that compresses to a few KB and is
  reset is a small request's 503, not a "MiB" hint asked again. A
  screenshot's random bytes stay past 1 MiB, and those are still asked
  again.
- The gateway and provider TestMains leave turns plain
  (CodexZstdForTests), since their fake backends read the body as JSON.
  The new tests turn it on.
- TestAsksOwnBackendAgreesWithTheGatewayDispatch read any call whose sixth
  letter is upper case (CodexCompressed) as a serveX dispatch. It now
  needs the "serve" prefix. Removing "kiro" from asksOwnBackend still
  turns it red.
- docs/subsystems/gateway-routing.md: the "sent plain JSON" line now names
  this exception.

Tests: internal/gateway/codex_zstd_test.go covers the accounts loop, the
relay (inbound zstd and plain), a try again after a drop, compact and an
API key plain, a key provider at the same URL plain, and a reset judged by
wire bytes. internal/provider/codex_zstd_test.go covers the round trip,
GetBody, Content-Length and the URLs left alone. Broken by hand, each went
red:
- no compression in forwardOnce: Account and AskedAgain
- no compression in the relay: Relayed, AskedAgain and JudgedByBytes
- no account guard: KeyProviderTurnStaysPlain
- compact compressed: CompactAndAPIKeyStayPlain
- the drop judged by len(body): JudgedByTheBytesSent

Real account (the owner's ChatGPT sign-in, gpt-6-luna, 1,100,279 B
text-only body, 391 B zstd):
- Direct to chatgpt.com, twice: plain 200/200, zstd 200/200. ylorn's 503
  did NOT reproduce from here (a2b96139c also saw 0.5-20 MiB served). The
  change rests on the official client's behaviour.
- Through a sandbox magpie (own HOME, :3486) via a byte-counting CONNECT
  proxy:
  - Old build: relay-zstd, relay plain and the account path were 200, 200,
    200, with 3,321,579 B uploaded to chatgpt.com.
  - New build: 200, 200, 200, with 13,362 B uploaded. Each 1.1 MB turn now
    goes as a few KB, as Codex sends it.

Run at origin/main e21ea07e4:
- go test ./... was all ok after the dispatch-test fix. The provider,
  agent and gateway packages were rerun.
- go test -race -count=3 on the new tests.
- gofmt -l is clean.
- go vet: darwin and windows ./... ok. linux ok for the changed packages.
  linux ./... fails the same on clean e21ea07e4 (wails v3's cgo-only Linux
  files, cross-vet from macOS).

* gateway: a key held to some models gets its model list as fast as one held to none, its groups read once a list, not once a group (#1762, LumenXY on X)

LumenXY's /v1/models over Tailscale took 12.4s with a gateway key held to
some models and 1.5s with an unheld one, so apps that list models timed
out and showed an empty list.

Cause (pprof, 1,000 models, 500 found groups): keyAllowed checked each
catalog entry on its own. Each group entry called provider.FindGroup,
which builds a new GroupFinder, so every provider's models were read again
(providerEntries, its files stat'ed and settings loaded) once a group.
That was 96% of the request. Each glob in the key's models was also
compiled to a regexp on every check, and a key held to accounts listed
each provider's accounts (Logins, from disk) once a model.

What changed:
- gateway/key_models.go: keyAllowed weighs a list through a keyList made
  for that request alone. It has one GroupFinder and each provider's
  AccountIDs read once. entryAllowed and accountServes are the same
  checks over them. accountServes(who, p, model) stays for decide.go's
  single check.
- access/models.go: globRe keeps each pattern's compiled expression. A
  pattern compiles to the same expression whatever key holds it, so
  nothing kept goes stale. The map is let go of whole past 4096 patterns.
- gui/groups.go: groupsState (the Routing page) called FindGroup once a
  group too, the same class. It now uses one GroupFinder.
Every route that lists models goes through keyAllowed: /v1/models,
/v1/models/{id}, /v1beta/models, /v1/codex/models, Muse's list and the
deciders. The single-model checks (serve, count_tokens, embeddings,
System One, draw, video) ask one group and are unchanged. Nothing is kept
past a request, so a change to a key's models or accounts, a group's
members or an account's own models shows on the next request. No key
limit is loosened. The documented behaviour is unchanged, so no subsystem
page changes.

Tests:
- TestKeyListShowsWhatItDid compares keyAllowed with the old per-entry
  check, kept in the test, for 14 keys over a catalog with found groups,
  named and nested groups, a no-key provider and an account's own models.
  The keys cover exact ids in any case, globs, group/<id>, group/*, a
  group inside one named, accounts, and models with accounts.
- TestKeyListSeesChangesNextRequest goes through /v1/models and
  /v1beta/models on one server while the key's models, the group's members,
  the key's accounts and an account's models change.
- TestModelPatternsKeptCompiled checks each pattern keeps its own
  expression and that past the cap works.
- Broken by hand, each went red: the accounts memo shared across providers
  (ShowsWhatItDid), the GroupFinder kept across requests
  (SeesChangesNextRequest), and the glob cache keyed by the pattern's first
  letter (KeptCompiled).

Numbers, BenchmarkHeldKeyListsModels (2 providers x 500 models, 500 found
groups, M4 Pro):
- held to models: 2.36s before, 55ms after
- held to accounts: 2.35s before, 60ms after
- held to none: 43ms either way

Real use: sandbox magpie on 127.0.0.1:3486 with its own HOME, the same
1,500-entry catalog, a key held to 5 patterns, and curl 3x each:
- held key, /v1/models and /v1beta/models: 27.8-28.7s before, 0.18s after
- unheld key: 0.12s either way
- The held list (212 entries) and the unheld one (1500) were
  byte-identical between the old and new builds.
- Changing the key's models while the server ran showed on the next
  request (10 entries, then 212 again).

Run at origin/main 8f2a314cf:
- go test ./...: every package ok (49), no FAIL
- go test -race -count=3 on the access tests and -count=2 on TestKeyList*,
  TestGatewayKeyModels* and TestGatewayKeyAccounts*
- gofmt -l and go vet ./... (darwin, GOOS=windows); GOOS=linux go vet
  -tags nogui on access, gateway and gui

* plugin: the unofficial plugins on GitHub aren't cut short through a slow proxy, and a list cut short is asked again in 20s, not kept ten minutes (larchsis on X)

larchsis (Windows, no system proxy, magpie's own proxy on) saw no
unofficial plugins on the Plugins page, and saw them with the system
proxy on and magpie's set to automatic.

No request bypasses magpie's proxy. Every listing and install read
(market.json, npm info and search, GitHub's search, package.json and
README, Bun's download, plugin icons) goes through http.DefaultClient or
DefaultTransport, which netproxy.Install routes through settings.Proxy,
else the environment, else the system proxy (HKCU Internet Settings on
Windows). Checked with a counting CONNECT proxy in a sandbox magpie on
macOS and on the Windows box: every connection to api.github.com,
raw.githubusercontent.com and registry.npmjs.org went through it, and
lsof / Get-NetTCPConnection showed none going direct.

The cause is timing. askTagged gave the whole listing 8s, six package.json
reads at once, each bounded by that same 8s, and a repository whose read
hadn't finished was left out. The cut list was then kept ten minutes, and
on disk for a restart. Through a sandbox proxy that adds latency per
chunk: no delay 29 repos, 150ms 21, 300ms 6. A slow proxy loses most of
"Unofficial, on GitHub", and when it loses all of them the section is gone.
The two setups differ in latency and in what was cached, not in proxy
handling.

Now:
- Reads go on past the page's wait (taggedEach 20s each, 12 at once), on a
  context detached from the request. They are kept by repository and push,
  as before, so the next ask has them.
- A repository whose read didn't come in time is as the last list had it
  (in memory, else on disk), with the search's current stars and
  description.
- A list that left one out is asked again after 20s, not ten minutes. Its
  copy on disk is dated so that a restarted magpie asks again too.

Run:
- TestTaggedReposSlowRead (new) holds word-guard's package.json past a
  300ms wait. It fails on the old code (5 repos, word-guard missing). It
  also fails with each part broken by hand: no fallback to the last list,
  a partial list kept 10 minutes, reads cancelled at the wait, and the disk
  copy not aged back.
- Sandbox magpie web (own HOME, own ports, proxy 127.0.0.1:3481 with
  injected latency), no cache: at 300ms 11 repos at 8s, then all 29 25s
  later (the old code kept 6 for ten minutes). At 1s none at first, all 29
  25s later.
- go test ./... on 5e7efce3b (origin/main): green. go test -race -count=5
  on the tagged tests. gofmt -l clean. go vet on darwin, GOOS=windows
  ./..., GOOS=linux -tags nogui ./internal/plugin.
- Windows box: plugin.test.exe with the tagged tests, 3 of 3. In the full
  package run only TestMarketIconsAreBundled failed, because it reads
  ../gui/assets, which wasn't copied over.

* site, readme: APINEBULA joins the sponsors, a card on usemagpie.ai and a small logo under the README badges

APINEBULA paid for the website seat and the en/zh README seat. The logo is
the SVG they sent (143x37). A white-text copy is used on dark backgrounds,
through .for-light/.for-dark on the site and <picture> in the READMEs (the
.bird invert would turn the orange mark blue). The site's sponsor cards now
stack in an equal-width grid, so the two cards line up; the intro has zh, ja
and de strings.

Run: site worker and install tests (28 pass). The home page served locally and
checked in chromium and webkit, at 1200 and 390px, light and dark, in en/zh/ja/de
(dictionary applied in the page): both logos load, the right one per theme,
and there is no horizontal scroll.

* provider: moved Cursor users get plugin 0.2.8, whose empty-reply error says what Cursor's Run sent before it (magpie-community/plugins#60, congee949)

Raises the cursor mover's min from 0.2.7 to 0.2.8 (published, npm view shows 0.2.8), so keepMovedCurrent updates moved users. 0.2.8 adds the thinking length, tokens, refused built-in tools, unknown messages and last frame to the empty-reply 502, for the next report on plugins #60. Ran gofmt -l, go vet (darwin, windows) and go test ./internal/provider (ok, 525s).

* provider: a model models.dev has just listed without its reasoning levels takes its family's, so Codex's picker offers them for a relay's gpt-6.1-sol (NextCommit on Discord)

NextCommit's Codex showed no reasoning-effort picker for a relay's (an
OpenAI-compatible key provider) gpt-6.1-sol, while gpt-6-astra had one, and
magpie's log said the effort went from none to low. models.dev had listed
gpt-6.1-sol as a reasoning model but without reasoning_options yet, or not
at all, so magpie knew no levels for it: Codex's catalog got
supported_reasoning_levels [] (no picker), and the gateway, not knowing
"none" was one of the model's levels, sent Codex's "none" as "low" (#899).

What changed:
- catalog: a thinking model with no levels of its own and no budget takes
  the levels of the newest model of its models.dev family (same provider,
  thinking, with levels) released on or before it (mdProvider.levels).
  Used by Provider and ListedBy. A model with its own levels, a budgeted
  one, one that doesn't think, or one with no family is as before.
- catalog.KinEfforts: for an id no provider lists, the levels of the newest
  listed model of the same shape with the version numbers left out
  (gpt-6.1-sol -> gpt-#-sol), never a budgeted or non-thinking one.
- provider.borrowedEfforts: tries ListedBy, then EffortsOf, then
  KinEfforts. Entry.Efforts, which every agent's model list is built from
  (Codex, Claude Code, OpenCode, dsh, ...), goes through it, as do Known,
  Levelless, groups and plugins.
- Xiaomi's mimo, which takes a thinking switch only (#214), still gets no
  levels; gpt-4.1 gets none.

With levels known, an effort the user picks in Codex goes through as
picked. The none->low mapping remains for models whose levels are still
unknown (#899).

What was run:
- New tests: TestFamilyLevels (catalog) and
  TestNewModelTakesItsFamilysLevels (provider, Codex catalog levels for
  relay/gpt-6.1-sol). Both fail with levels() and the KinEfforts call
  neutered (levels "" against the family's), and pass with them.
- Real Codex CLI 0.162.1 under a sandbox HOME against a sandbox magpie
  gateway (127.0.0.1:3592) and a fake relay (127.0.0.1:3591) listing
  gpt-6.1-sol and gpt-6-astra. The models.dev cache had reasoning_options
  stripped from every gpt-6.1-sol entry to match the reporter's.
  - Built from origin/main: magpie-models.json gave relay/gpt-6.1-sol
    default None, levels [].
  - With this change: default medium, levels none..max,ultra.
  - Codex /model showed "Select Reasoning Level for GPT-6.1 Sol · relay".
    Picking Medium, High and None sent reasoning_effort "medium", "high"
    and "none" to the relay.
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux and GOOS=windows builds: all
  clean.
- go test ./... under a temp HOME, with GOCACHE and GOMODCACHE
  pinned. Every package passed except four that hit the 10-minute default
  timeout with load average ~40 (TestCopilotSecretToolUsername's 5s
  secret-tool wait as well). Rerun with -timeout 40m -p 2, internal/agent,
  gateway, library and provider all passed.

Not tried: the Claude Code, OpenCode and dsh model files written for the
same relay model; they take Entry.Efforts like Codex.

* gui: the Linux app's sidebar button switches the layout at once, no view transition, which WebKitGTK with compositing off crashed in (depravity_wings on X)

Since 18e82adc6 (v0.1.1197) the sidebar button, Ctrl+Shift+S and dragging
the sidebar's edge past its narrowest trade the two layouts in a view
transition (navMorph). Under Wayland magpie turns WebKitGTK's compositing
off (webkit_linux.go), and WebKitGTK 2.52 then crashes in the transition:
SIGSEGV on the GTK main thread inside libwebkit2gtk-4.1, from a
JavaScriptCore run-loop timer. The reporter saw the window freeze.

The Linux app (body.linux) now has the new layout at once, the path reduced
motion already takes; magpie web in a Linux browser keeps the motion. Other
webviews get a guard: a transition still going after MORPH_MAX (1.5s, three
times its length) is skipped, so one that never ends can't leave the window
on the old layout's picture.

Run:
- Reproduced on the omarchy VM (Hyprland/Wayland, webkit2gtk-4.1 2.52.6),
  v0.1.1207 under a scratch HOME: the button crashed the app 4 of 4 clicks;
  with WEBKIT_DISABLE_COMPOSITING_MODE=0 it didn't.
- The fixed build there (same Linux path, compositing at magpie's default):
  8 button clicks, 4 Ctrl+Shift+S and an edge drag past its narrowest all
  switched the layout, checked by screenshot each step; no crash, no freeze.
- side-toggle.test.cjs: "Linux: at once, no transition" and "a transition
  that never ends is cut short", chromium and webkit; both go red with the
  change undone by hand. side-toggle, sidebar, side-width, header-centre
  pass in both engines (60 tests). go test -tags nogui ./internal/gui ok.
Not run: the 1.5s guard on a real webview that never ends a transition
(none found); it is tested with a stub.

* gui, profile: the profile in use is ticked and named on the panel's Profiles button, not a count read as its name (superhtoooth on X)

superhtoooth (macOS): 保存方案设置了方案名字,但是应用方案没有用这个名字。
menu 里面变成了方案 1,方案 2。而且在应用里面没有显示当前使用的方案.

The bug: the tray panel's Profiles button showed the number of saved
profiles next to its label ("方案" + "2"), which reads as a profile
named 方案 2. Profiles were saved and applied under the typed name all
along; nothing anywhere said which profile was in use.

What changed:
- profile.InUse: a profile is in use while applying it would change
  nothing on this computer - every detected agent's saved field is as
  the profile has it (compared with the same renamed-ref spelling Apply
  writes), its model lists are held (provider.ModelListsHeld, a dry run
  of SetModelLists via the extracted putModelLists) and its library
  setup is as saved (library.Holds, the mirror of Restore). A profile
  that touches no agent here is not in use.
- Why not "last applied": that would stay ticked after the user changes
  a model by hand, a tick that lies. With this definition a profile
  saved from the current setup is in use at once, a hand change clears
  the tick, and applying puts it back. Two identical profiles are both
  ticked; the button names the first.
- GUI: /api/state carries inUse. The panel's button names the profile
  in use (a pop-up button showing what is picked), else counts them as
  before; its chip gets a check mark and aria-current, in panel and
  window; the chip's tooltip and its details say "In use" (string
  already in every language). CLI `magpie profiles` marks it, the TUI
  notes "in use". Docs (reference, start en/zh/ja) say so.

What was run:
- go test ./internal/profile (new TestProfileInUse: save, hand change,
  apply, hidden model list, library instructions, absent agents) and
  ./internal/gui (new TestStateProfileInUse through the HTTP handler),
  scratch HOME. Broken by hand: field compare, ModelListsHeld,
  library.Holds and state's InUse each turned a test red.
- go test -tags nogui ./... in a scratch HOME (the four slow packages
  rerun with -timeout 40m under load ~45).
- GUI: new profile-in-use.test.cjs (reporter's steps in the panel at
  360px, every language, plus the window) and panel-profiles,
  profile-confirm, profile-details, old-webkit, i18n-keys, gui-zh-tw,
  gui-ja, gui-de in chromium and webkit: all pass. Old app.js fails the
  new test.
- Real CLI in a sandbox HOME with a codex config: save/use/profiles
  show the mark, and it goes after a hand edit.
- gofmt; go vet darwin, linux (nogui), windows.
Not tried: the real tray app with real agents, and Windows/Linux at
runtime.

* provider, gui: a ChatGPT sign-in whose port 1455 can't be opened goes on, says why, and is finished by the pasted address (#1782)

nianlee-official's ChatGPT sign-in stopped at "port 1455, where ChatGPT
sends the sign-in back, is busy" with nothing of ChatGPT's running. That
message was given for every listen error: a Windows port in a range
Hyper-V, WSL or Docker excluded (WSAEACCES, no program holds it) read the
same as one another program held, and either way the sign-in stopped,
though ChatGPT's page puts the code in the address the browser ends on.

What changed:
- begin (signin.go): when listenCodexCallback can't have the port, the
  codex sign-in still starts. Its handler serves no port and it waits for
  the address, pasted, as a Docker sign-in does (pastedCallback goes
  through the same handler). SignInState says why in CallbackBlocked
  ("reserved" for Windows' WSAEACCES 10013, else "busy") and names the
  port in CallbackPort. The redirect stays localhost:1455, the only one
  ChatGPT's client takes. listenCodexCallback returns the real error.
- GUI: the sign-in box says which of the two it is, with the port, in
  place of the server-or-Docker guess (5 languages). CLI: the same.
- Not changed: Kiro's built-in tries ten ports already; the ChatGPT API
  sign-in falls back to any port.

What was run:
- go test ./internal/provider -run
  'TestCodexSignInGoesOnWithItsPortTaken|TestCallbackBlocked|TestCodexSignIn|TestPasted|TestLoopback'
  -race -count=5: ok. With begin returning the listen error again,
  TestCodexSignInGoesOnWithItsPortTaken FAILs: "the sign-in stopped at the
  taken port: listen tcp 127.0.0.1:61025: bind: address already in use".
- signin-port-blocked.test.cjs (new), signin-paste-codex,
  signin-callback: 45/45 in Chromium and WebKit, en/zh/zh-TW/ja/de, 900
  and 420 wide. With app.js from HEAD the new test FAILs (the note never
  shows, TimeoutError).
- gofmt -l, go vet (darwin, GOOS=linux -tags nogui, GOOS=windows), full
  go test -tags nogui ./... before the push.

Not tried: a real Windows excluded port range (the Windows box was
unreachable over ssh); the reserved case is tested with errno 10013 as
Go's net.Listen wraps it. The reporter's own cause isn't confirmed yet;
the issue asks them.

* gateway, gui: a Routing row's share used renews with its own window, not the biggest one (#1778)

Vigilans' Factory account showed "32% used · renews in 27 days": the
week's 32% beside the month's reset. Allowance.For gives the fullest
window's share and the renewals biggest first, and routing.js paired the
share with renews[0], so for any account of more than one window the row
mixed two windows.

- provider.Allowance.Fullest(model, now): the reset of the window For's
  share is of (the later of two as full; a window whose reset has passed
  counts as empty, as For does).
- The trace's Weighed gains usedRenews (from weighRouted's left.fullest);
  routing.js's usedRenews(w) uses it in both the story rows and the
  account rows, and falls back to renews[0] only for an account of one
  window (a route recorded before this commit).
- Smart's order is unchanged on purpose: it goes by the biggest window,
  and Factory's month holds less than its weeks add up to, so what a week
  leaves isn't lost at the week's reset. docs/reference.md says so, and
  gateway-routing.md names Fullest/usedRenews.

Run:
- go test ./internal/provider ./internal/gateway -run
  'Fullest|UsedRenews|Weigh|Routing|Smart' and the packages whole.
- TestUsedRenewsWithItsOwnWindow fails with left.fullest set to the
  biggest window's reset (broken by hand, then restored).
- routing-key-windows.test.cjs: 44/44 in Chromium and WebKit, all
  languages and widths; it fails on HEAD's routing.js.
- Every routing-*.test.cjs plus panel-routing in both engines: 594/601.
  The 7 WebKit failures are clicks waiting for an element to be "stable"
  under load average ~44, in routing-group-fold (#1612, #1672),
  routing-sessions (#1307) and routing-days-fit. routing-days-fit passes
  run alone. The other two fail the same alone with HEAD's routing.js.

Not tried against a real Factory account: the windows are those the
Factory plugin's limitWindows reports (5h/7d/30d with resetsAt).

* davsync: a write a server without conditional PUTs let another go over is merged again at the next sync (#1776)

On an S3 server that refuses If-Match (Aliyun OSS answers 400
NotImplemented), put falls back to HEAD then an unconditional PUT. Two
computers writing in the moment between both pass the HEAD, both are
told they wrote, and the later file is kept. Worse, the loser's next sync
then took the winner's file as having seen its own: its st.Remote was the
file it wrote, so its changed parts looked unchanged here and changed
there, and the old parts were brought in over its own changes. The edit
was lost on the server and on the computer that made it.

- version.Blind marks a write the server didn't check (s3.go's fallback).
- state.Blind keeps, for such a write, the file's sum and the remote and
  local part hashes from before it. The next sync that reads another
  file than that one merges from before the write. What this computer
  changed counts as changed again and goes back up beside the other's.
  A 304 or the same file clears it. Restore and Upload clear it.
- docs/reference.md says what happens on such a server.

No compare-and-swap exists on OSS, so the race itself isn't closed: the
other computer's file is kept for up to one sync interval (3 minutes)
before this computer's change is merged back. The reporter's AppendObject
journal would close it but needs every computer upgraded and OSS-only
signing. If the other computer saw this one's write and then changed the
same part again, the next sync can't tell that from a write that went
over it. It counts the part as changed on both sides: the newer stays,
the other is saved, and a notice says so. Nothing is lost.

Run:
- TestS3BlindWriteGoneOverIsMergedAgain (fake S3 with no conditional
  writes, two computers): A renames a provider and B sets the theme, B's
  PUT goes over A's, then A's next sync puts both on the server with no
  conflict notice, B brings in the rename, and nothing more is written.
  With the reset taken out (broken by hand), it fails: "A's rename here
  after its next sync: \"DeepSeek\"".
- go test ./internal/davsync whole.

Not tried against real Aliyun OSS: the fake answers conditional PUTs the
way the reporter quotes OSS (NotImplemented).

* provider, gui, cli: a group can keep its models out of the lists agents see, offered through the group alone (#1783)

cybershape asked for a client's model list to show only a group, not
every model behind it. A provider could already be kept for routing
groups (Provider.Unlisted), but that hides the whole provider, and the
models a group names may come from providers used elsewhere too.

Group.Unlists (json "unlists"): the models a group names (a member fixed
at an effort counts as its model) and those its patterns match leave
Catalog(), so `magpie models`, /v1/models and every agent's list
(CatalogFor) show the group without them. They stay in Served(), so a
group routes over them and a request naming one as provider/model is
still answered, and Unlisted() returns them for the GUI as it does an
unlisted provider's. A nested group keeps its own setting; a group
switched off or hidden keeps nothing out. With no group unlisting,
Catalog() takes a fast path and is unchanged.

- Routing view: the group editor's "Model lists" (Its models too / The
  group alone, segmented, with a hint), saved with Save; the card shows
  "Its models unlisted". Both group Save paths send unlists. zh, zh-TW,
  ja, de.
- CLI: `magpie group set <id> listed=no|yes`; `magpie group <id>` shows
  listed: no.
- TUI: the group member picker offered Catalog(), so models kept out of
  the lists (an unlisted provider's, before this too) couldn't be put in
  a group from the TUI. It offers Served(), as the GUI's picker does.
- docs/reference.md, Routing groups: listed=no.

Product call: a per-group switch, off by default, rather than hiding
members of every group, so existing lists don't change under anyone.

Run:
- go test ./internal/provider -run 'Group|Catalog|Unlisted|Served',
  ./internal/gui, root package, ./internal/tui: ok.
  TestGroupUnlistsItsModels fails with the Catalog filter removed;
  TestMemberOptionsOfferUnlistedModels fails with the picker on
  Catalog(); TestApplyGroupPairs covers listed=no/YES/maybe.
- GUI group-unlists.test.cjs, Chromium and WebKit, en zh zh-TW ja de, at
  1100px and 420px: 20/20. i18n-keys: ok.
- gofmt; go vet darwin, windows, linux (-tags nogui): clean.

Not tried: with the reporter's own client; a real agent's model file
written after toggling (CatalogFor is covered by the test).

* plugin, gui: an installed plugin's row and page show its own magpie.icon, not its first provider's (#1775)

peterroe's plugin signs in to several providers. Each provider gets its own
picture from the auth hook, and package.json's magpie.icon is the picture
for the plugin itself. Settings → Plugins → Installed only took a plugin
picture from the market listing. A plugin that isn't listed (installed from
a path, git or an unlisted npm package) had none, so its row and its page
showed its first provider's picture.

- plugin.InstalledIcon reads magpie.icon from the installed package.json.
  It goes through the same ownIcon check as a listing's icon (data: or
  https only).
- pluginsState stores the picture through provider.RepoIcons, as listed
  plugins' pictures are, and returns it as `icon` on each plugin entry.
- plugins.js: the installed row and the detail page use the listing's
  icon, then the plugin's own, then its first provider's, as before.
- Docs (en, zh, ja): magpie.icon is the plugin's picture (Discover card
  and Installed row) and the fallback for providers without their own. A
  plugin of several providers gives each provider auth.icon.

Run:
- go test ./internal/plugin ./internal/gui: ok.
  TestPluginsStateGivesThePluginsOwnIcon covers a data: icon (kept), no
  icon and a plain-http icon (both "").
- internal/gui/tests/plugin-own-icon.test.cjs: Chromium and WebKit, en,
  zh, zh-TW, ja, de, at 980 and 420 wide. It fails on the old plugins.js
  (the row shows pa.png).
- The plugins GUI tests: 34/34 in each engine.
- gofmt; go vet darwin, windows, and linux -tags nogui.
- Full go test ./...: the only red is gateway OTel timing under load ~79.
  That's #1794, commented there; alone it passes 3/3.

Not tried with peterroe's real package; the fixture follows the layout
the issue describes.

* proc, provider, agent: a claude (or other agent CLI) that is a mise wrapper script is run as the program mise names, and a Claude sign-in that gets no link says which program it ran (deluxe on Discord)

deluxe (Omarchy Linux, magpie started from the desktop) never saw the
Claude sign-in link. ~/.local/bin/claude was a script ending
`exec mise x "claude" -- "claude" "$@"`; without the shell's mise
environment, `mise x` looks claude up on PATH, finds the same script
(~/.local/bin is before mise's shims) and it runs itself for ever.

What changed:
- proc.Unwrap / proc.LookPath (internal/proc/wrapper.go): a small #!
  script whose line is `[exec] mise|rtx x|exec [opts] [tool] -- <name>`
  is resolved with `mise which <name>` (then `mise which --tool <tool>
  <name>`), run as a probe (process group killed) with a 5s timeout,
  magpie's environment and the home folder as cwd. The answer must be an
  executable file that isn't the wrapper or another wrapper; otherwise,
  or with no mise, the old path is kept. Answers are cached per file
  (path, mtime, size); a failed ask is retried after a minute.
  Windows is unchanged.
- proc.FindTool (claude via claudecode.Find: the sign-in, the gateway's
  Claude subscription, `magpie claude-code`) unwraps what it finds.
- The siblings that looked an agent CLI up with exec.LookPath use
  proc.LookPath: agent.binAt (detection, CLI version/update), codex,
  kiro-cli, devin, cursor-agent, Air's opencode, nativemodels' npm
  package lookup.
- The Claude sign-in already gave up after linkWait (30s) with "claude
  auth login gave no link to open". It now adds the last line the CLI
  printed, or, when it printed nothing, the program it ran and to run
  `<path> auth login` in a terminal to see what it does.

asdf shims (`exec asdf exec "claude" "$@"`) are left alone: asdf exec
resolves the real program itself and doesn't recurse.

Verified (macOS, sandbox HOME, Go caches pinned):
- New tests: internal/proc/wrapper_test.go (wrapper -> mise's program;
  no mise -> wrapper; mise fails / names the wrapper / names a folder /
  hangs -> wrapper, and the hung mise's pid is gone; deluxe's own fixed
  script, a node launcher, a wrapper of another command, a commented
  line -> unchanged and mise never asked; parse cases; --tool retry),
  internal/provider/signin_claude_wrapper_test.go (the full Claude
  sign-in through the wrapper with a fake mise that really recurses:
  link shown, account added; with no `mise which`, the sign-in fails in
  linkWait naming the wrapper).
- Break checks: with find.go put back, TestFindToolUnwrapsMiseWrapper and
  TestFindToolAsksWithWrappersTool FAIL (FindTool = the wrapper), and
  TestClaudeSignInThroughMiseWrapper FAILs with "claude auth login gave
  no link to open: .../local-bin/claude printed nothing in 5s". With the
  old error string, TestClaudeSignInWrapperThatNeverStarts FAILs.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux go build -tags nogui;
  GOOS=windows go build.
- go test -tags nogui ./...: every package ok except internal/agent and
  internal/gateway, which hit the default 10m timeout with the machine
  at load ~45 (different tests each run, none in the new code). Those
  two were rerun with -timeout 40m; origin/main 217d2f8f2's
  internal/agent alone took 2094s under the same load.
- Rebased on 9964535ad, -timeout 40m: internal/agent ok (1689s),
  internal/proc ok, internal/provider ok (681s), internal/claudecode ok;
  internal/gateway FAIL in one test, TestCodexHeardWithinItsIdleTimeout
  (3.78s against its 3s wall-clock bound, body right, no retry taken).
  Alone with -count=5 it passes 5 of 5. Filed as #1800; unrelated to
  binary lookup.

Not verified: no real mise or the reporter's Omarchy machine; the fake
mise stands in for mise's which/x. The wrapper fixture is the line the
reporter quoted, not their whole file.

* gateway: a Claude Code turn after its prompt suggestion goes on in its run, taken back from the suggestion; a turn that finds no run says why (#1638, chicring)

Cause (case 2: 41 messages told to a new Claude Code at 02:40:00, minutes
after the last reply at 02:37:13, no stop log). Claude Code 2.1.290 asks
its prompt suggestion after each turn: the conversation so far, with the
turn's system prompt, tools and thinking, and one more user message,
"[SUGGESTION MODE: ...", with no system message after it. That request
goes on from the turn's reply, so resume handed it the conversation's
run, and ended kept the run waiting at the suggestion's reply. The user's
real next turn didn't follow the suggestion, found no run under its key,
and was told the whole conversation in a new run (88k tokens written to
the cache again). Nothing was logged because nothing ended.

Fix. ended keeps, beside the run's new key, the key it went on from
(behindKey) and the turn's uuid (behindTurn). resume, finding no run
under a turn's key, takes one whose behindKey is that key, rewinds it to
behindTurn (rewind_conversation, as letGo does), marks it rewound so it
isn't shelved, and tells it only the turn's messages. A run that can't be
rewound is let go and the turn told whole to a new run, as before.

Logging. A turn after a reply that starts a new run logs "claude: no run
waits for this turn: <why>" (whyNoRun): it went on with a turn this one
doesn't follow, waits under another key (model, settings, system prompt
or tools differ), waits at an earlier turn, is busy, ended (how long ago
and why: abortFor's reason, or how Claude Code exited), or no run here
had the conversation. "tool results no run waiting" now adds "the run
that made the calls ended Xs ago: <why>" (whyCallsLost).

Case 1 (499 mid-reply, then "tool results no run waiting" and 17 messages
told) is not fixed. The run that answered had been started anew for that
turn, so letGo has no earlier user message to rewind to, and its results
were already handed to it over MCP. Keeping its cache would mean rewinding
to Claude Code's own tool_result message and telling the results again as
text, or interrupting instead of ending the run; neither can be checked
without the reporter's request shapes, and a fork that took the lead's
calls (claimResume) looks the same from here. The new log line says which
run ended and why, so the next report can tell.

Tests (claude_side_question_test.go), with 2.1.290's request shapes
(billing line with changing cch, 1h cache_control, adaptive thinking,
output_config effort, context_management, system messages, signed
thinking sent back):
- TestClaudeSideQuestionKeepsTheConversationsRun: turn, turn, suggestion,
  real turn go to one Claude Code (turn 4), rewound to the suggestion's
  uuid, told only the new message; twice. Red with the take-back disabled
  ("went to another Claude Code: pid ... turn 1").
- TestClaudeSideQuestionNotRewound: a run refusing the rewind is let go,
  the turn goes to a new run, 1 run left. Red with the fix disabled (2 runs).
- TestClaudeNoRunSaysWhy (gone / another key) and
  TestClaudeToolResultsNoRunSaysWhy: red with the log line, or the
  lostCalls record, removed by hand.

Run:
- the new tests -race -count=5: ok
- real e2e: the real 2.1.290 client in -p --prompt-suggestions against
  the bridge, whose Claude Code was the real 2.1.290 too, both against a
  local mock of Anthropic: one bridge run for the whole session, "taken
  back from the side question" logged after each suggestion, 0 runs told
  the whole conversation; the real turn's request to the mock went on
  from the reply before the suggestion, without it.
- gofmt -l .: clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok
- set -o pipefail; go test -tags nogui ./... at load average ~45-53:
  every package ok but agent, gateway, library, plugin and provider, which
  hit go test's 10m default. Rerun with -timeout 40m -p 2: agent, library,
  plugin ok; gateway red only in TestOTelWaterfallIncludesUnbilledFallback
  and TestOTelWaterfallFailureAndCancellation (#1794, already filed: they
  read only the first OTel export; -count=10 alone passes); provider red
  only in TestCopilotSecretToolUsername (#1627, already filed; red 1 of 5
  alone under load, then 5 of 5 green). Neither touches this change.
- the new tests with the bridge's neighbours (LetGo, TurnGivenUpOn,
  ToolResultsGivenUpOn, Idle, EndedRunSaysWhy, ForksAnswering) -race
  -count=5: ok

Not tried: the real Claude subscription upstream, the interactive TUI
(the -p flag turns on the same suggestion), other side requests
(extract_memories, away_summary, /btw), case 1's actual requests.

* provider: a third-party Anthropic API that refuses x-api-key and Authorization together is sent one, picked in the editor or learned from its 401 (Aloha on Discord)

magpie sends a user's own Anthropic-compatible provider its key in both
x-api-key and Authorization: Bearer. Some relays answer 401 "鉴权 header,
x-api-key 和 Authorization 不可以同时存在", so every request failed.

- Provider.AuthHeader ("" both, "x-api-key", "bearer") picks which
  AuthHeaders sends on the Anthropic protocol. Anthropic's own API,
  Bedrock, Azure, Vertex and subscription accounts are untouched: they
  send x-api-key alone (or their own) whatever it says, and BothAuth()
  is false for them.
- Left at both, a 401 whose body catalog.BothAuthRefused tells as that
  refusal (names both headers and says they can't be together, Chinese or
  English) is asked once more with x-api-key alone, then Bearer alone
  (RetryOneAuth, in the gateway's forwardOnce and the provider test's
  probe; the model-list fetch through catalog.fetchOne too). The first not
  answered 401/403 is saved (LearnAuthHeader), never over a pick the user
  made. A request carrying the user's own Authorization/x-api-key header
  is never retried; any other 401 is passed on as it came, asked once.
- The editor has a "Key header" row (Both / x-api-key /
  Authorization: Bearer, the app's segmented control) while the provider
  has a third-party Anthropic URL; strings in zh, zh-TW, ja, de.
- docs/subsystems/providers-accounts.md: an "Anthropic key header" row.

Run (sandbox HOME, GOCACHE/GOMODCACHE pinned, set -o pipefail):
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux/windows go build.
- go test -tags nogui ./...: 47 packages ok; agent and gateway timed out
  at 10m under load average ~50-98 (other sessions' test runs), so rerun
  with -p 1 -timeout 60m: agent ok; gateway ok but for
  TestOTelWaterfallIncludesUnbilledFallback, a load flake unrelated to
  this (it reads only the first 200ms OTel export; passes 5/5 alone),
  filed as #1794.
- New tests: internal/provider/authheader_test.go (official Anthropic and
  Bedrock unchanged for every pick; Aloha's 401 body retried with
  x-api-key and kept; Bearer-only relay learns bearer; the model list
  learns; another 401 and the user's own header aren't retried; a user's
  pick isn't overwritten), internal/gateway/authheader_test.go (a
  /v1/messages turn through the gateway to such a relay succeeds and the
  next Chat Completions turn goes with one header first).
- Broken by hand: RetryOneAuth returning at once and AuthHeaders ignoring
  the pick -> TestAuthHeaderChoice, TestRetryOneAuthLearns,
  TestRetryOneAuthBearer, TestOneAuthHeaderRelay FAIL; the list retry off
  in live.go -> TestListLearnsOneAuth FAIL.
- GUI: provider-auth-header.test.cjs 20/20 in chromium and webkit, en and
  zh, 390px wide; the editor's other tests (provider-*, nokey-editor,
  editor-short-window, segs-*, vertex-editor) 439/440, the one
  (provider-discovery, chromium zh) passing 26/26 alone.

Not tried: a real relay of Aloha's; the retry is built from the body the
user quoted.

* provider: moved WorkBuddy users get plugin 0.1.15 and Command Code users 0.1.11 (magpie-community/plugins#96, #91)

WorkBuddy 0.1.15 (wowyuarm's plugins#96): a system prompt sent as a developer message no longer fails the channel check with 400, an object tool_choice is sent the way WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the output cap holds. Command Code 0.1.11 (plugins#91): a streamed Go reply the upstream cuts off after it has said something ends cut short with a note instead of losing the turn.

Only the movers' min strings and their notes change. Both versions were checked on npm with npm view. The plugins session ran #96 against the real WorkBuddy AI endpoint before and after the change.

Ran: gofmt -l, and go vet ./internal/provider on darwin and windows. go test ./internal/provider -run 'Mov|Migrat|Plugin|HandOver|Adopt' passed in 129s. The full suite was not run, because this is a two-string change.

* cli: magpie's commands move from the root into internal/cli; the root keeps only main.go

The root held 89 .go files (30 commands, 59 tests). They move as they are
to internal/cli (package cli), with git mv so history follows them. The
only code change is main() becoming cli.Main(version): the root's new
main.go keeps `var version` in package main, so -ldflags "-X
main.version=…" in the Makefile, the Dockerfile and magpie-releases, and
every workflow, work unchanged. go-winres's rsrc_windows_*.syso still land
next to package main in the root.

Tests that read testdata by a root-relative path now go up one level
(../plugin/testdata/fake, ../sessions/testdata). Five subsystem doc links
point at internal/cli/.

Run:
- go build ./..., gofmt -l, go vet on darwin, linux and windows (nogui)
- builds with tags production, dev, "production nogui"; windows
  -H windowsgui; linux CGO_ENABLED=0
- make release-cli TARGETS="darwin/arm64 linux/amd64 windows/amd64
  android/arm64" VERSION=9.9.9-tidy: all four built, binary prints
  "magpie 9.9.9-tidy"
- docker build --build-arg VERSION=7.7.7-tidy: container prints
  "magpie 7.7.7-tidy"
- go test ./internal/cli (default and nogui): 152 tests, the same count
  as the root on main
- go test ./...: all packages pass (agent, gateway, library, provider
  timed out at 10m under other sessions' load and passed rerun alone
  with -timeout 40m; none of them changed)
- the built binary in a sandbox HOME: version, help, ls, providers,
  claude, and an unknown command's error

* tui, provider, serve: a signed-in account's models are fetched at start, so Routing offers Cursor's whole list without m (#1789, reyoung)

The terminal and `magpie serve` never called provider.FetchNew, which the
window calls at start: a signed-in Cursor account's list exists only at
Cursor, so the TUI's Routing pickers (and a headless gateway's /v1/models)
offered the fallback cursor/auto alone until the list was fetched by hand
with m on the Providers page.

- tui: Init fetches the new lists (fetchModelsCmd, alongside the catalog
  sync). A model picker open when they arrive (Routing members, the
  classifier, a provider's models, an agent's model field) is filled in
  place through its relist, keeping its filter and the model under the
  cursor. A list left missing (no network) is asked for again a minute
  later (modelsRetry). Built on reyoung's branch and test.
- serve: FetchNew at start, again each minute while a list is missing.
- provider: FetchNew reports whether a list is missing, and waits for a
  CLI asked who is signed in for the first time (awaitIdentities), then
  lists the accounts again. With the real Cursor account in a fresh
  sandbox, `cursor-agent about` answered after a look's 3s firstAsk, so
  FetchNew saw no Cursor account and `magpie serve` still listed 1 model
  with the TUI fix alone. The window's startBackend gets the same wait.
- docs: providers-accounts.md says who fetches the lists and when.

Run:
- internal/tui TestTUIFetchesSubscriptionModels (6 views) and
  TestTUIAsksAgainForAMissingList, -race x3; red with the Init fetch,
  the relist, the cursor restore or the retry tick each removed by hand.
  A first `about` slowed to 12s injected: passes (the test re-asks).
- internal/provider TestFetchNewWaitsForASlowSignIn: red without
  awaitIdentities (no provider "cursor"); TestFetchNewAccount covers the
  missing result.
- Real Cursor account, sandbox HOME with a keychain holding only Cursor's
  two items: TUI on main showed cursor/auto only in Routing; the fix shows
  the full list and "24 models" on Providers. `magpie serve`: main 1
  Cursor model at /v1/models, the fix 24 within 5s.
- gofmt -l, go vet (darwin, GOOS=linux, GOOS=windows), go test ./... in a
  sandbox HOME.

Not tried: Linux and Windows real Cursor CLIs (the fake CLI tests skip on
Windows); Devin's CLI identity goes through the same wait but wasn't
tried with a real account.

* gateway: the waterfall OTel tests read every export, not only the first (#1794)

A request that outlasts one export interval (200ms in tests, a busy
machine) has its attempt spans sent in one export and its root in the
next, so TestOTelWaterfallIncludesUnbilledFallback and
TestOTelWaterfallFailureAndCancellation, which read only the first, went
red under load: on macOS CI for 23e764d0e and five times locally. They now
take every export once stop() has flushed (otelExports), split traces from
metrics by resourceMetrics, and check the spans of all of them.

Run, with the export interval injected down to 1ms so the split always
happens: the old tests failed 15 of 15 (-count=5) with CI's messages, the
new ones pass 5 of 5; at 200ms 5 of 5. All TestOTel tests pass -count=2
except TestOTelSessionDiscoveredDuringFirstRequest, red 3 of 10 under load
average ~90 on its 50ms session-cache window, untouched here and filed as
#1811. go vet, gofmt.

* agent, gateway: Claude Code on a model Anthropic doesn't review gets auto mode's server review turned off, so it no longer says magpie isn't eligible (1EFLOPS on X)

1EFLOPS runs Claude Code through magpie on Codex's gpt-6.1-sol. In auto
mode, Claude Code 2.1.296 says "this session isn't eligible because your
requests go through 127.0.0.1:3425 ... ask your gateway to implement
https://code.claude.com/docs/en/auto-mode-classifier-billing".

What the page asks of a gateway: pass the anthropic-beta header
(dangerous-tool-use-2026-09-03), the request's `safeguards` field, and
`safeguard_results` in the reply through unchanged, and leave tool-use ids
alone. The results are verdicts from Anthropic's own safety classifier.
For a gateway that can't provide them, the page's remedy is
CLAUDE_CODE_AUTO_MODE_SERVER=0. Pro, Max and Team plans never see the
notice. In the bundle, Claude Code falls back on server_unsupported,
server_unavailable_disabled or server_no_result, and the notice shows
whenever there's no real verdict. Only that variable removes it.

Per route:
- Claude subscription bridge, Anthropic API key, relays in front of
  Anthropic, Bedrock and Vertex: already pass the beta, `safeguards` and
  `safeguard_results` through (e8cd4bac8, 8c21a4184). This commit doesn't
  change them. serverReview now uses the shared AutoModeReviewed rule
  (adding the subscription account, which never reaches serverReview).
- Codex/OpenAI and every other non-Claude model: magpie can't answer
  honestly. A verdict would be made up, and "unsupported" still shows the
  notice. So magpie answers nothing on Anthropic's behalf. Instead the
  Claude Code wiring writes env.CLAUDE_CODE_AUTO_MODE_SERVER="0" to
  settings.json. It does this only while Claude Code is routed through
  magpie and no model it can reach there is reviewed. That means checking
  the models shown to Claude Code (and Claude Desktop's while Desktop is on
  magpie), a shown group's members, those providers' fallbacks, and the
  models it is set to (claudeReviewed). If any one is reviewed, the
  variable stays unset, because /model can move the session onto it (the
  reason 8c21a4184 didn't write it at all). The value is rewritten on every
  model set and Sync, so adding a Claude provider turns the review back on.
  It is stash-tracked (claude.auto_mode_server): a user's own value is left
  alone, and magpie's goes on Disconnect, reset or a move off magpie.
- T3 Code (sibling): its magpie instance runs Claude Code on the gateway
  through its own environment, so it gets the same "0" by the models it
  lists.
Not covered: Claude Desktop's Code tab while Claude Code itself isn't
routed through magpie. Desktop users are on Pro/Max/Team, which never see
the notice.

Tests (each fails with its part of the change broken by hand):
- TestClaudeAutoModeReview: off on a non-Claude model; on with a Claude
  model shown, in a group or as a fallback; the user's "1" and "0" kept;
  dropped on reset and on a move to Claude Code's own model.
  A group that keeps its models out of the lists (#1783, Unlists) still
  routes to them, so its Claude member counts: members come from what is
  served, not from the catalog.
- TestT3CodeAutoModeReview.
- TestAutoModeReviewedRoutes: subscription, api.anthropic.com, relay,
  Bedrock and Vertex spellings yes; Codex, DeepSeek's Anthropic API,
  openai/gpt-6 and claudette no.
Mutations that went red: skipping group members, skipping fallbacks,
skipping an unlisting group, overwriting the user's value, not dropping it off magpie, always writing
it, the T3 env always or never, and the subscription not counted.

Real Claude Code 2.1.296, sandbox HOME/CLAUDE_CONFIG_DIR, magpie serve on
127.0.0.1:3591 under a scratch HOME, fake upstreams on 3593 (OpenAI Chat)
and 3594 (Anthropic):
- Before, on fakeai/fake-gpt, -p --permission-mode auto: the notice is on
  stderr (2 of 2 fresh config dirs). With the env in settings: none.
- With this build, `magpie claude fakeai/fake-gpt` wrote the "0", and a
  fresh run shows no notice. The same settings without it show the notice.
- `magpie provider add fakeanth anthropic=... models=claude-sonnet-5`:
  Sync took the "0" out. `magpie claude fakeanth/claude-sonnet-5` and a run
  in auto mode: the upstream got the dangerous-tool-use beta and
  `safeguards` on both turns, answered not_flagged in message_delta, and
  there was no notice.
Not tried: the Claude subscription bridge with a real account (its plans
don't see the notice), and a real Codex account (a fake Chat upstream
stood in for it).

Run: gofmt -l; go vet -tags nogui ./... for darwin, linux and windows;
go test -tags nogui ./... in a scratch HOME with the Go caches pinned.
The only red was TestOTelWaterfallIncludesUnbilledFallback, whose first
export was cut before the root span under load. That is #1794, filed
earlier today; this run is noted there. This change doesn't touch OTel.
internal/agent was timed against the unchanged base under the same load
and ran at the same pace.

* provider: a Claude sign-in test's `claude auth login` run ends with the test, however it ends, and the mise-wrapper test waits the sign-in's own 30s for a link (#1802)

#1802: TestClaudeSignInThroughMiseWrapper failed once at load 80-89 in
1.45s, and every provider test after it failed in 0.00s. The run's
messages weren't kept.

What was found, by forcing each failure by hand rather than rerunning:
- The sign-in's run of `claude auth login` outlived the test that started
  it. A sign-in that gives up (no link in linkWait), or a test that fails
  between StartSignIn and the sign-in's end, leaves the run's goroutine
  letting go after the test: it reads claudeKeychain, removes its folder,
  forgets the account caches and, had the callback gone in, adds the
  account into whatever home is set by then. Under -race,
  TestClaudeSignInWrapperThatNeverStarts fails on main with that race
  (clearClaudeDir reading claudeKeychain while isolate's cleanup puts it
  back).
- TestClaudeSignInThroughMiseWrapper shortened linkWait to 5s, so a busy
  machine starting sh, the fake mise and sh again could miss it.
- miseWrapped set claudeExecutable and relied on fakeClaudeLogin's
  cleanup to put it back.
- The cascade itself didn't come back. Forced failures with the sign-in
  waiting (A), finishing (E) and failed early (D, the CLI exiting at once,
  ~1.9s like the report), on the old code and the whole package for D:
  only the forced test failed, the ~100 after it ran and passed. Nothing
  found in the test explains every later test failing in 0.00s. One
  unproven candidate: this machine's disk is at 99% (9.9-12 GiB free
  today), and a full disk fails every test that writes a file at once.
  #1802 stays open for a run that keeps -v output.

What changed:
- claude_signin.go: claudeLogins, a WaitGroup of the `claude auth login`
  runs still going on, to the end of their goroutine.
- signin_claude_test.go: fakeClaudeLogin, which every Claude sign-in test
  uses, registers endClaudeSignIns: when the test ends it cancels every
  Claude sign-in still listed (killing the CLI's process group) and waits
  for claudeLogins, failing the test if a run is still going after
  signInDeadline. It runs before the test's home and fakes are put back.
- signin_claude_wrapper_test.go: miseWrapped puts claudeExecutable back
  itself; the through-the-wrapper test keeps linkWait's own 30s (the link
  comes as soon as it is printed); the never-starts test checks it gives
  up no sooner than linkWait and no later than linkWait + 1m.

What was run (macOS, sandbox HOME, GOMODCACHE pinned, a private GOCACHE
since the shared one was being emptied):
- Old code (1bf722e28's tests), -race, -run 'TestClaude|TestCodexSignIn|SignIn':
  TestClaudeSignInWrapperThatNeverStarts FAILs "race detected".
  With this change: 181 pass, no race.
- This change with a forced t.Fatal in TestClaudeSignInThroughMiseWrapper,
  with the sign-in waiting (A) and finishing (E), -race, the Claude,
  sign-in, Vertex, WorkBuddy-add, store-error and key-allowance tests:
  only the forced test fails, 306 pass each time.
- gofmt -l clean; go vet ./... on darwin, GOOS=linux (-tags nogui) and
  GOOS=windows.
- go test -tags nogui -timeout 40m ./internal/provider ./internal/proc:
  provider ok (774s), proc ok (26s), at load 75-90.

* gui: on Linux the tray panel is a solid window with an opaque page, as the main window is, so scrolling it leaves no ghost of the old position (#1803)

MizuIro-H (Bazzite / Fedora 44, KDE Plasma 6, Wayland) saw the panel's
Allowances tab leave a fainter copy of what it showed at the old scroll
position, on Wayland and under GDK_BACKEND=x11, with
WEBKIT_DISABLE_COMPOSITING_MODE=1 (which magpie already sets under
Wayland, so that try changed nothing), at scale 1, and without KWin's
corner effect. The main window, with the same page, never did.

The panel was the one window with per-pixel alpha: Wails'
BackgroundTypeTranslucent on Linux makes it an app-paintable GTK window
on the screen's RGBA visual under a 0-alpha webview, and body.panel
painted --bg at 93% over it. Paint not cleared before a scroll repaint
shows through 93%, which is the fainter copy. The main window is a plain
solid window painting --bg whole.

On Linux only, panelOptions now makes the panel BackgroundTypeSolid, and
body.linux.panel paints --panel-tint as --bg (no alpha). The Mac (tinted
by tintPanel) and Windows keep the translucent panel. The corners are
square on Linux now (the body's paint fills the canvas).

Run: gofmt -l internal/gui (clean); go vet darwin ./internal/gui,
GOOS=linux -tags nogui ./..., GOOS=windows ./... (clean);
go test ./internal/gui under a sandbox HOME (ok);
node --test internal/gui/tests/panel-*.test.cjs, chromium and webkit
(74 pass), the new panel-linux-opaque test across en/zh/zh-TW/ja/de and
light/dark. Broken by hand: TestPanelSolidOnLinux fails without the
panelOptions change, and panel-linux-opaque fails without the CSS rule
(the Linux body read color(srgb ... / 0.93)).

Not tried on the reporter's setup. A repro of the panel's window
(GTK3 + WebKit2 4.1, RGBA visual, 0-alpha webview, 93% page) under Xvfb
with picom, on Ubuntu and on Fedora 44 (WebKitGTK 2.54), scrolled by JS
and by a real X wheel, with compositing mode on and off, showed no ghost
either way: software rendering there doesn't reproduce it, so whether
the opaque panel ends it rests on the reporter's KDE/GPU machine. No
real Linux magpie build was run.

* gateway: a request asks only the resting member back soonest, not every resting one, so a failing member isn't hammered by each request (#1799, dbydd)

dbydd: a group's routing still goes over its members in order however
they have been failing, and with providers magpie can't read a quota
from, that is close to a DDoS of the ones that are down.

What was there: a failure rests the member (credit 30m, quota till its
reset, rate by Retry-After, anything else 1m doubling to 10m), and one
answer clears it. But restLast only moved resting candidates behind the
ready ones. Once the ready ones failed, every request went on to ask
each resting member in turn, so the rest kept nobody back: in an outage
of the whole group each request went to all N members, and the last one
again on its retries.

Now (probeOne, fallback.go): of the candidates resting, a request asks
only the one whose rest ends soonest (the first in order on a tie), at
its place. Every ready candidate is still asked in the user's order. A
lone candidate is always asked. A group that is down whole takes one
upstream request per request, and the backoff grows with each real
probe instead of each request. The trace still lists every member, the
resting ones with their rest. The same is applied where the other
paths go over candidates: count_tokens, embeddings/rerank, image
accounts (drawOnAccounts) and a group's System One decision models.
Codex autoReset still looks over the whole list (all), so a week used
up on every account still spends a reset.

Default on, no switch: it only reads rests the user's order already
demotes, and only within a rest's cooldown; once a rest ends, the member
is back at its place in the user's order. Each request still makes at
least one real upstream attempt and returns the vendor's own error.
Scoping: only rests are read, and a failure about the request's content
or its model rests no member (failShape, prompt, overflow, refused,
loop, auth, proxy...; a model refusal rests only restID), so neither
leaves a member out.

Borrowed from AxonHub's error-aware load balancing (looplj/axonhub,
docs/zh/guides/load-balance.md, ErrorAware), which dbydd pointed to: a
failed channel's score drops and recovers as its penalty decays, rather
than it being sent every request. magpie's rest and backoff already are
that decaying penalty; asking the one back soonest is how it recovers.
Not taken: a success-rate memory that keeps a member demoted after it
answers. One answer means it serves now, a flaky member already rests at
least a minute per failure, and holding it down past that would
override the user's order beyond a cooldown.

Unchanged: the last candidate still isn't rested by its own failure,
and the Patience rounds (#1418) and retries on the last one re-ask only
candidates already in the trimmed list.

Tests (resting_probe_test.go): TestGroupAsksOneRestingMemberNotEach
(three resting members, minutes apart: only the soonest is asked; with
a ready member, it then the soonest),
TestRetrievalGroupAsksOneRestingMember (embeddings),
TestLoneRestingMemberStillAsked, TestProbeOne. With
probeOne returning its input (the old behaviour), the first two fail:
"resting members asked map[a:1 b:1 c:1]".

TestSystemOneDecisionGroupFailsOver held the old behaviour (all
failing: kb, ka1, ka2 asked, ka2's 503 back); it now wants kb then ka1,
the one rested first, and ka1's 429 back.

Run: gofmt -l (clean); go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows); GOOS=linux -tags nogui and GOOS=windows go build;
go test -tags nogui ./... -timeout 40m under a sandbox HOME at load
average ~100: every package ok but gateway and agent, which hit the 40m
timeout mid-run (TestZenUnsupportedModelLeavesTheListAlone and
TestSnowNoProfiles running, a few seconds in), and plugin, where
TestNPMInfoDeadline hung on its own failed 2s check (filed #1808).
Rerun alone with -timeout 80m: gateway ok (1896s), agent ok (1811s),
plugin ok (746s). Not run: a real upstream outage, the Windows box;
count_tokens and image accounts have no test of their own.

* provider: a switch of Claude Code's sign-in takes the account's own proxy into its env, and out again for one without (#1807)

kensenzhao signs Claude Code in to several accounts in direct mode and
gives each its own proxy in magpie (AccountProxies). Those proxies were
only ever honoured on what the gateway sends; Claude Code signed in to
its own subscription asks Anthropic itself, through the proxy its env
names, so a switch (by the user, or SwitchWhenSpent) left every account
on one route.

Decision: while the Claude subscription has a proxy for any of its
accounts, settings.json's env names the proxy of the account Claude Code
is signed in to: its own, else the subscription's (ProxyOfLogin, which
also covers the first account whose proxy is kept as the sub's, #1663).
None for "direct", and none for a SOCKS proxy, which Claude Code can't
use (logged). HTTPS_PROXY and HTTP_PROXY are written, with NO_PROXY set
to loopback so the gateway and local MCP servers are reached straight.
With no account proxy at all nothing is written: the subscription's
proxy alone was never Claude Code's, and turning it on now would change
every existing user's route unasked.

A proxy the user set themselves wins. magpie records the values it wrote
(claude-proxy-env.json beside providers.json) and a key is its own only
while it still holds that value; any proxy key that isn't (in either
case) means the route is the user's, so magpie writes none beside it and
takes out only its own. A NO_PROXY/no_proxy the user set stays. A
settings.json or record that can't be parsed is an error, never empty:
the file is left as it is.

It runs on every switch (switchLogin), on Save of the Claude
subscription (a proxy picked for the account it is on), and on the
gateway's 5-minute KeepOnAnAccountWithRoom tick (a sign-in made in
Claude Code itself). Claude Code reads its env as it starts, so running
sessions keep the old route; the log says which proxy new ones take.

Run: go test -tags nogui ./internal/provider (676s, ok) in a sandbox
HOME. TestClaudeSwitchTakesTheAccountsProxy fails with the sync call
taken out ("on b, HTTPS_PROXY = "", want b's proxy");
TestClaudeAccountProxyKeepsTheUsersOwn and ...EditedByTheUserStays fail
with the user-route check forced off, and EditedByTheUserStays with
ours() always true. gofmt -l clean; go vet ./... on darwin,
GOOS=linux -tags nogui and GOOS=windows; windows and linux builds.

Not tried: a real Claude Code session going through a real proxy after a
switch, and a remote LAN gateway's address isn't added to NO_PROXY.

* gui: Windows without the WebView2 runtime says so in a message box and offers the download page, instead of a double-click doing nothing (#1806)

magpie's windows are WebView2, which Windows 10 doesn't always have.
Without it Wails handed the failure to ErrorHandler and exited, and the
desktop build (-H windowsgui) has no console for the log line to land
in: ufec's double-click came up to nothing at all. ufec found the cause,
that Wails' own Env.Info().PlatformInfo["WebView2"] answers "" then, and
that a box can't come from ErrorHandler (it runs on the thread Wails
makes its windows on); this takes both from their branch.

Run asks webView2Check right after application.New, before any window.
Missing, it logs it and shows MessageBoxW (Yes/No, error icon, topmost)
in the reader's language (trayLang): the runtime is missing, Microsoft's
page https://developer.microsoft.com/microsoft-edge/webview2/, that
"magpie web" and "magpie tui" work without it, and whether to open the
page now; Yes opens it (ShellExecute), and Run ends. A key Wails doesn't
set is read as present: refusing to start a magpie that would have
worked is worse than the silent exit. The tray isn't kept: its panel is
a WebView2 window too.

Run: TestWebView2Missing and TestWebView2Notice (all OSes);
TestWebView2MissingFromWails on the Windows box (10.0.0.132, Windows
with WebView2 installed): a child process with Wails pointed at a folder
that isn't a runtime reads missing, the machine's own runtime reads
present. TestWebView2Missing goes red with webView2Missing made to answer
false. On the box, a throwaway -H windowsgui test binary calling
webView2Check with that bogus runtime path, run in the desktop session:
the box came up titled "magpie 需要 WebView2" with the Chinese text, the
page and 是/否 buttons (read back from the dialog's controls), the log
line was written, pressing 是 opened the page in Edge and the check
answered false. go test -tags nogui ./internal/gui in a sandbox HOME;
gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows; windows and linux builds.

Not tried: a machine that really lacks the runtime (the box has it; the
missing case is Wails' lookup failing on a path that isn't a runtime,
the same failure), nor a real magpie.exe start through Run.

* agent: dsh's web search asks the searcher picked under Settings › Web search, not the model dsh starts on (我只会玩单机 on Discord)

magpie's web-search-deepseek row in dsh's cordis.patch.yml was written
with the model dsh starts on (ref). The gateway then sent each search to
that model, which can't search itself and asked the searcher in turn:
two requests per search, and timeouts when the start model can't take
concurrent calls. The user had picked "6 Luna" under Settings › Web
search, and it was never written.

gateway.NamedSearchModel gives the searcher Settings names as
"<provider>/<model>" (empty when none is named, search is off, the one
named can't be used, or it searches with no model). dshSearchModel uses
it for the row on Set and on dshRouteAgain's ~30s pass, so a change in
Settings reaches dsh's file, and clearing it gives the start model
back. A row the user wrote themselves (no # magpie) stays untouched.

Run: go test -tags nogui ./internal/agent -run TestDsh (ok);
TestDshSearchAsksNamedSearcher fails with dsh.go and dsh_search.go
reverted; gofmt -l clean. Not tried with a real dsh, nor whether a real
searcher model answers dsh's web_search end to end.

* provider: Cursor's grok-4.7 fast ids are priced at Cursor's fast rate, so a routing group of them counts its cost (TradingLife on Discord)

A group of Cursor's and Grok's Grok 4.7 fast recorded calls with no cost.
Cursor's ids grok-4.7-fast, grok-4.7-<effort>-fast (and at a window,
@500k) had no price anywhere: no models.dev catalog lists them, and
30431e04 left fast ids unpriced on purpose rather than make one up. So
every usage record on them (provider cursor, model grok-4.7-fast) was
unpriced, and the group, whose price needs every member's, had none.

Cursor publishes the price (https://cursor.com/docs/models, read
2026-10-12): Grok 4.7 (Fast) $4 input / $1 cache read / $12 output per
million, "Fast mode for long context (>256k) is billed at 3x standard
rates". Provider.ListPrice now gives a Cursor account (the built-in's or
the Cursor plugin's) that price for its fast Grok 4.7 ids, with a tier
above 256k at $6 / $1.5 / $18. Scoped to Cursor: elsewhere a "-fast" Grok
id is a model of its own (xAI's grok-4-fast is $0.2 / $0.5), and Grok
Build's grok-4.7-build-fast (Grok's own list) has no published price, so
it stays unpriced, as does a fast id of a model Cursor gives no fast
price for.

Run: go test -tags nogui ./internal/provider ./internal/sessions
./internal/usage (ok); new TestCursorGrokFastPrice fails with the lookup
switched off; gofmt -l clean. Not done: a group member sent fast through
Group.Fast (the plugin's grok-4.7@256k with service_tier priority) is
still recorded at the standard price, since a usage record doesn't say
it went fast; not checked against the reporter's own usage log.

* library, gui: a skill pack added a while ago is grouped whole, and the Skills head has Group again (White Immortal on Discord)

Of mattpocock/skills' 38 skills only 20 were grouped with the repository on
the Library page; the rest sat under On this computer, and nothing could
trace them again. Cause: installing from a repository again (noteFrom)
grouped a library skill with it only when its SKILL.md was byte for byte
the repository's. A pack added a while ago is mostly older copies: of the
copies at mattpocock/skills 3cca18b3 (2026-09-04), 18 of 37 match HEAD; at
8b78b531 (2026-08-13) 2 of 35. The GUI's parts draw all 38 when the data
has them (checked with a Playwright run against 38 skills in the repo's
real folder layout, github, lock-traced and mixed paths, both engines).

noteFrom now also notes a skill traced to nowhere by a name the repository
has, when the library has others from that repository (same file, or
traced there already). A skill traced to another repository, and a
same-named skill when the library has nothing from there, are left alone.
RegroupSkills (POST /api/library/skills/regroup) fetches each GitHub
repository the skills are traced to and runs the same; it fails only when
no repository could be fetched. The Skills head has Group again (busy while
it runs, status says how many joined), en/zh/zh-TW/ja/de.

Run: TestRegroupOlderCopies (fails with the name match off: edited and
later stay ungrouped), TestInstallAgainNotesFrom, TestSkillRepoTraced;
skill-regroup.test.cjs in chromium and webkit, en/zh/zh-TW/ja/de at 1100
and 440 wide (red on the old assets: no Group again); skill-parts and
i18n-keys pass; go test -tags nogui ./internal/library ./internal/gui ok;
gofmt, go vet. Not tried against the reporter's library or real GitHub.

* provider, gateway, gui: an account whose sign-in its vendor revoked or refused reads as signed out and is passed over, not asked on every request (#1793 ysicing, echo_ts on Discord)

What changed, one fix for the class:

- ChatGPT and the other built-in subscriptions (#1793): ChatGPT answered
  401 token_revoked on every request, request after request (~18 rows in
  the reporter's log), because a refused sign-in was just "other" and
  rested a while, then asked again. Now a 401 whose words say the sign-in
  is gone (provider.SignInRevoked: token_revoked, token_invalidated,
  invalid_grant, refresh_token_reused/invalidated/expired; never
  token_expired, a 403, a 5xx or a network error) marks the account for
  the credential it was sent with (a 12-byte hash of the header, never the
  credential), in logins.json as Refused "revoked:<mark>" plus Lapsed.
  A saved ChatGPT account is refreshed first, as Codex does on a 401; a
  refresh that goes through marks nothing. The routing loop fails it as
  failAuth (next member at once, no rest); forwardOnce answers its later
  requests with magpie's own 401 without asking the vendor; compaction
  on a magpie account (compactOn) picks a marked one last. Signed in anew
  (upsertLogin with another credential, addSideLogin), refreshed, or a
  request served, the mark is gone. Claude, Copilot and plugins keep
  their own marks; a key's provider answering the same words rests as
  before.
- Copilot (echo_ts): a built-in Copilot account whose GitHub token GitHub
  refused (401/403 on the token exchange, the CLI stand-in or the usage
  read) is marked lapsed on its own account (copilot_lapsed.go), unless a
  working CLI stand-in serves; cleared when a token is served or it signs
  in again. 5xx and network errors never mark it.
- GUI: such an account's row says Sign-in required with Sign in again
  (Copilot's on its GHE.com host) and Remove, the reason on its allowance
  line in the user's language (zh, zh-TW, ja, de added); the card says
  Signed out once every account in use is.
- docs/subsystems: providers-accounts "A revoked sign-in", gateway-routing.

What was run (sandbox HOME, caches pinned, worktree only):
- go test -race on the new tests: provider TestSignInRevokedWords,
  TestRevokedSideLoginMarkedTillSignedInAgain, TestRevokedCodexRefreshedFirst,
  TestRevokedSignInLeavesOthersMarks, TestUpsertLoginKeepsRevokedMarkForTheSameSignIn,
  TestCopilot* (7); gateway TestRevokedSignInPassedOverTillSignedInAgain
  (fake ChatGPT backend, zstd, real routing: turn 1 asks acct-1 then
  acct-2, turns 2-4 and after a restart acct-2 only with no rests, after a
  new auth.json acct-1 again and the mark gone),
  TestRevokedSignInNotCompactedOnAgain, TestRevokedWordsFromAKeyRestAsBefore.
- Broken by hand, each turned a test red: the forwardOnce short-circuit,
  the failureOf clause, noteSignIn in codexUpstreamOn, compactOn's skip,
  ServedSignIn, its in-memory delete, the 401-only check, refresh-first,
  upsertLogin's keep and its sameAuth, sideLogins' Lapsed and
  addSideLogin's clear; and the six Copilot breaks. GUI: the signedOut
  and quotaError lines each turn revoked-signin-account red.
- GUI (Chromium and WebKit, 420 and 1100, en/zh/zh-TW/ja/de):
  revoked-signin-account (new), copilot-signed-out-account (new), and the
  account-*, claude-*, codex-*, plugin-*, quota-*, signin-*, routing-*,
  usage-accounts* suites: 1605 pass, 7 fail. Six are WebKit
  routing-group-fold/routing-sessions/routing-steady cases that fail the
  same on a clean 9964535ad run alone (#1672, #1612, #1307, #1804); one,
  signin-proxy Chromium de 380, timed out under load (load ~60-75) and
  passed 2 of 2 after, filed as #1814.
- gofmt; go vet darwin, linux (nogui) and windows; linux and windows
  builds. go test ./...: every package ok but gateway, where
  TestOTelFastRequestTranscriptDiscovery and
  TestOTelWaterfallIncludesUnbilledFallback failed under load (#1794);
  both pass alone, -count=3.

Not verified: no real revoked ChatGPT or Copilot account was tried; the
words come from the reporter's screenshot and OpenAI's documented codes.
Codex's own relayed sign-in (not one of magpie's accounts) isn't marked:
Codex refreshes and signs itself in. The short-circuit in
codexUpstreamOn (compaction on a marked account, reached only when every
account is marked) has no test of its own; plugins are left to their
plugin.

* gateway: a Claude turn that calls a tool and then thinks without showing it reaches Codex whole, ending in response.completed, not cut short by a panic (#1786)

The Responses encoder read the open function_call's id and name from the
collector's last part. When a hidden thinking block came after a
tool_use (a redacted_thinking block, or a thinking block signed with no
text, from content_block_start or a signature_delta), the collector had
already appended that thinking, last(ToolCall) was nil, and closing the
call dereferenced it. The server recovered the panic mid-stream, so the
client saw a 200 chunked body cut short ("unexpected EOF", "stream
disconnected before completion") and no response.completed.

The encoder now keeps the open call's id and name itself (e.call), set
when the item opens, for closing it and for the custom-tool check on its
argument deltas. The other stream encoders (Chat, Anthropic, Gemini)
track their open tool call in their own state and never read the
collector's last part, so only this one had the bug.

Verified:
- TestResponsesStreamToolThenHiddenThinking runs the reporter's sequence
  through a real gateway server (httptest) to a fake Anthropic upstream
  and a real HTTP client: redacted_thinking, empty thinking signed at its
  start, empty thinking signed in a delta, and visible thinking as the
  control. With the old responses.go the three hidden cases FAIL with
  "status 200, the stream was cut short: unexpected EOF" and the log shows
  the nil pointer panic; the visible case passes on both.
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go test -tags nogui ./... (see the push).

Not done here: the max_tokens setting the issue also asks for is a
separate feature request.

* gui: the sidebar's Installed under Plugins is selected on its own row, not a third of a row up over Discover (#1787)

The sidebar's list of a page's tabs (.nav-sub) unrolls from height 0 as
the page opens (navSubEnter). Its rows were flex items that shrink, so
while the list unrolled they were squeezed, 18px tall at 19px down
instead of 26px at 27px. Plugins draws its tab strip again once
/api/plugins answers ("Installed" becomes "Installed · 2"), navSubs then
rebuilds the rows, and navSubMark measured the squeezed row for the
selection. Nothing marked it again after the unroll, so with Installed
saved as the tab the grey selection sat 8px up and 8px short, over
Discover's text: the reporter's screenshot.

The rows are now flex: none, so they keep their size and place while the
list unrolls or folds, and offsetTop is right whenever the strip is drawn
again. The other pages' lists (Library, Usage, Settings) share the rule.

Run:
- new internal/gui/tests/nav-sub-unroll.test.cjs: Plugins with Installed
  saved, /api/plugins held until the list is animating, then answered.
  Chromium and WebKit; en, zh, zh-TW, ja, de; 1024 and 1440 wide.
  - 20/20 fail on the old app.css (the selection at 444.6-462.6 against
    the row's 452.6-478.6).
  - 20/20 pass with the fix.
- sidebar, side-toggle, side-width, plugin-check-updates, plugin-market,
  plugin-progressive and click-scroll in both engines: 82 pass.

Not tried: the packaged app on the reporter's machine. The timing there
is whatever /api/plugins takes; the test covers any answer that lands
during the 460ms unroll.

* omarchy: on Hyprland the tray panel opens under the click on a monitor that isn't at 0,0, not off the screen (#1785)

PanelAt answered where the panel goes in coordinates across the whole
layout (the cursor's, from hyprctl cursorpos), and PlacePanel handed them
to Hyprland's move rule. Hyprland counts a move from the corner of the
window's monitor (CDefaultFloatingAlgorithm::newTarget in 0.56.2:
COMPUTED + MONITOR_POS), so the monitor's place was added twice. The
reporter's click on the right of two 1920-wide monitors asked for
3238,40 and got 5158,40, off every screen. The monitor at 0,0 hid it,
and the only setup tried before (bf25a3ae8) had one monitor.

PanelAt now answers from the corner of the monitor under the cursor and
names it. The rule says monitor = that name, so the move counts from the
monitor clicked, not whichever one Hyprland would have opened the panel
on. The panel is still kept PanelGap inside that monitor's work area,
and the room below it is unchanged. ClickedOutside compares the cursor
with the clients' places, both across the layout, and stays as it was.
niri's placement already moves within the working area of the output and
doesn't share this. The fix follows laojianzi's draft (laojianzi/magpie#1).

Run:
- internal/omarchy TestPanelAtMonitorOffScreenOrigin (new), with the
  reporter's two 1920x1080 side by side, the right edge, a monitor left
  of and above 0,0, and a scaled one below. It plays Hyprland's sum and
  checks where the panel lands and that it's inside the clicked
  monitor's work area. With the old sum put back by hand it goes red,
  landing at 5158,40 for the reporter's case. TestPanelAt's turned
  monitor had the old global x written into it, and now has 6.
  TestPanelRule checks the rule's text.
- On the omarchy VM (Hyprland 0.56.2), with a headless second output at
  1600,0 made for the try and removed after, the same Lua rule on a
  throwaway foot window titled magpie-1785-probe (not magpie's rule
  name):
  - monitor = "PROBE-1785", move = { 100, 40 } landed at 1700,40;
  - the old global 1700,40 landed at 3300,40, off the screen;
  - monitor = "Virtual-1", move = { 100, 40 } landed at 100,40.
- go vet (darwin, windows; internal/omarchy for linux with nogui).
  gofmt is clean.

Not tried: magpie itself on two real monitors under Hyprland. The Linux
GUI build needs cgo and wasn't built here, so placePanel's two changed
lines are covered by the darwin and windows builds (app.go has no OS
tag).

* agent, gateway: Claude Code on a model Anthropic doesn't review gets auto mode's server review turned off, so it no longer says magpie isn't eligible (1EFLOPS on X)

1EFLOPS runs Claude Code through magpie on Codex's gpt-6.1-sol. In auto
mode, Claude Code 2.1.296 says "this session isn't eligible because your
requests go through 127.0.0.1:3425 ... ask your gateway to implement
https://code.claude.com/docs/en/auto-mode-classifier-billing".

What the page asks of a gateway: pass the anthropic-beta header
(dangerous-tool-use-2026-09-03), the request's `safeguards` field, and
`safeguard_results` in the reply through unchanged, and leave tool-use ids
alone. The results are verdicts from Anthropic's own safety classifier.
For a gateway that can't provide them, the page's remedy is
CLAUDE_CODE_AUTO_MODE_SERVER=0. Pro, Max and Team plans never see the
notice. In the bundle, Claude Code falls back on server_unsupported,
server_unavailable_disabled or server_no_result, and the notice shows
whenever there's no real verdict. Only that variable removes it.

Per route:
- Claude subscription bridge, Anthropic API key, relays in front of
  Anthropic, Bedrock and Vertex: already pass the beta, `safeguards` and
  `safeguard_results` through (e8cd4bac8, 8c21a4184). This commit doesn't
  change them. serverReview now uses the shared AutoModeReviewed rule
  (adding the subscription account, which never reaches serverReview).
- Codex/OpenAI and every other non-Claude model: magpie can't answer
  honestly. A verdict would be made up, and "unsupported" still shows the
  notice. So magpie answers nothing on Anthropic's behalf. Instead the
  Claude Code wiring writes env.CLAUDE_CODE_AUTO_MODE_SERVER="0" to
  settings.json. It does this only while Claude Code is routed through
  magpie and no model it can reach there is reviewed. That means checking
  the models shown to Claude Code (and Claude Desktop's while Desktop is on
  magpie), a shown group's members, those providers' fallbacks, and the
  models it is set to (claudeReviewed). If any one is reviewed, the
  variable stays unset, because /model can move the session onto it (the
  reason 8c21a4184 didn't write it at all). The value is rewritten on every
  model set and Sync, so adding a Claude provider turns the review back on.
  It is stash-tracked (claude.auto_mode_server): a user's own value is left
  alone, and magpie's goes on Disconnect, reset or a move off magpie.
- T3 Code (sibling): its magpie instance runs Claude Code on the gateway
  through its own environment, so it gets the same "0" by the models it
  lists.
Not covered: Claude Desktop's Code tab while Claude Code itself isn't
routed through magpie. Desktop users are on Pro/Max/Team, which never see
the notice.

Tests (each fails with its part of the change broken by hand):
- TestClaudeAutoModeReview: off on a non-Claude model; on with a Claude
  model shown, in a group or as a fallback; the user's "1" and "0" kept;
  dropped on reset and on a move to Claude Code's own model.
  A group that keeps its models out of the lists (#1783, Unlists) still
  routes to them, so its Claude member counts: members come from what is
  served, not from the catalog.
- TestT3CodeAutoModeReview.
- TestAutoModeReviewedRoutes: subscription, api.anthropic.com, relay,
  Bedrock and Vertex spellings yes; Codex, DeepSeek's Anthropic API,
  openai/gpt-6 and claudette no.
Mutations that went red: skipping group members, skipping fallbacks,
skipping an unlisting group, overwriting the user's value, not dropping it off magpie, always writing
it, the T3 env always or never, and the subscription not counted.

Real Claude Code 2.1.296, sandbox HOME/CLAUDE_CONFIG_DIR, magpie serve on
127.0.0.1:3591 under a scratch HOME, fake upstreams on 3593 (OpenAI Chat)
and 3594 (Anthropic):
- Before, on fakeai/fake-gpt, -p --permission-mode auto: the notice is on
  stderr (2 of 2 fresh config dirs). With the env in settings: none.
- With this build, `magpie claude fakeai/fake-gpt` wrote the "0", and a
  fresh run shows no notice. The same settings without it show the notice.
- `magpie provider add fakeanth anthropic=... models=claude-sonnet-5`:
  Sync took the "0" out. `magpie claude fakeanth/claude-sonnet-5` and a run
  in auto mode: the upstream got the dangerous-tool-use beta and
  `safeguards` on both turns, answered not_flagged in message_delta, and
  there was no notice.
Not tried: the Claude subscription bridge with a real account (its plans
don't see the notice), and a real Codex account (a fake Chat upstream
stood in for it).

Run: gofmt -l; go vet -tags nogui ./... for darwin, linux and windows;
go test -tags nogui ./... in a scratch HOME with the Go caches pinned.
The only red was TestOTelWaterfallIncludesUnbilledFallback, whose first
export was cut before the root span under load. That is #1794, filed
earlier today; this run is noted there. This change doesn't touch OTel.
internal/agent was timed against the unchanged base under the same load
and ran at the same pace.

Re-run after rebasing on origin/main 94aa15397 (load ~100, so not the
whole suite): gofmt -l on the touched files; go vet -tags nogui
./internal/agent ./internal/gateway for darwin, linux and windows;
go test -tags nogui -count=1 ./internal/agent (1381s) and
./internal/gateway (939s), green. Breaking writeReview to never write the
"0" turned TestClaudeAutoModeReview red, and dropping the subscription from
AutoModeReviewed turned TestAutoModeReviewedRoutes red.

* gui: the Agents page's hidden agents come last, behind a disclosure shut until opened (0xZaTe on Discord)

0xZaTe (#feedback): after hiding agents, they looked pinned, not hidden
(看着反而像是一个置顶功能了 … 现在反而更显眼了). renderAgents put the
fold's groups in the order [Hidden, Not set up], so once the fold was
opened (its button then reads 「收起」, which is what they saw under Codex)
the hidden rows, each with a Show pill, sat right under the agent in use,
above the ones nothing is set on.

What changed (internal/gui/assets/app.js, app.css, i18n.js):
- In the fold, Not set up comes first. The hidden ones come last, behind
  a line of their own, 「已隐藏(2)」 / "Hidden (2)", with a disclosure
  chevron (right shut, down open), as a Finder sidebar section does. It
  is shut by default (showHiddenAgents), its rows inert while shut, and
  it unrolls on the same curve as the fold, the panel's edge moving with
  it (fit) and the view following (unrollInView).
- The fold's button counts only the ones nothing is set on ("Show 3
  more"), no longer "Show 5 more (2 hidden)".
- With nothing but hidden ones folded, the fold is theirs: no second
  disclosure inside it, its button still reads "{n} hidden agents", and
  opening it leaves the hidden rows open, so Show on one of them doesn't
  shut the rest behind a new line once another goes under Not set up.
- New strings in zh, zh-TW, ja, de; the unused "Show {n} more ({h}
  hidden)" is dropped.

Siblings checked: the window and the tray panel draw the Agents list
with the same code, so both get it. The Usage page's hidden clients are
already a shut "{n} hidden" line under the list. The panel's Arrange
(usage tab) is an edit mode that lists every subscription with Show/Hide
in place, as iOS's edit lists do, so it is left as is. The model picker
is a checklist.

Tests:
- new agents-hidden-last.test.cjs: the reporter's list (Codex connected,
  two hidden, three not set up). Order of the fold, the hidden rows out
  of sight and inert until their line is opened, then shown under it
  with Show, the button's count, no sideways scroll. Window at 420px and
  the tray panel at 380px, Chromium and WebKit, en/zh/zh-TW/ja/de, plus
  the hidden-only case. Run against the old app.js/app.css/i18n.js it
  fails on the order ([Hidden, agy, commandcode, Not set up, ...]).
- hidden-agent-cleared and rollup-short updated for the new order and
  count.

Run (macOS, playwright 1.62.0, both engines): agents-hidden-last,
hidden-agent-cleared, rollup-short, show-unset-agent, fold-show-grip,
agent-grip, grip-inset, panel-fold, panel-arrange, panel-effort,
panel-profiles, click-scroll, usage-agents-hide, removed-hide,
i18n-keys, gui-zh-tw, gui-ja, gui-de, lightweight and every agent-*
test: all green. go test -tags nogui ./internal/gui/ ok; gofmt -l clean;
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./... clean. Screenshots of the window and the panel in zh checked by
eye. Not run: the whole GUI suite (no shared class or API changed).

* gui: a short window's sidebar has no scroll bar beside its pages, a thin one shows over them while they scroll and fades, as on a Mac (xybio and MOMO on Discord)

In a window shorter than the sidebar's pages, .side-scroll (scrollbar-width:
thin) and .side-foot kept a native bar and its gutter at rest on Windows and
Linux. On Windows this was MOMO's report (v0.1.1207, WebView2): a classic,
always-visible bar with arrows between the sidebar's items and the page,
because Chromium drops every ::-webkit-scrollbar rule on a box with
scrollbar-width set and draws the system bar. Both boxes now hide their native
bars (scrollbar-width: none and ::-webkit-scrollbar display:none, which
Chromium/WebView2, WebKit and WebKitGTK each honour), and app.js sideBars lays
a thin overlay bar inside, shown on scroll, faded ~900ms after, kept while
hovered or dragged, the thumb draggable with pointer capture, a click off it
pages the box, hidden when the box fits. ResizeObserver/MutationObserver keep
it placed as the nav's sub-tabs open and fold. gui-shell.md describes it.

Run: new sidebar-overlay-scrollbar.test.cjs (chromium with native bars on,
webkit; en, zh, zh-TW, ja, de at 1100x320 and a tall window) 14/14; it fails
without the change (no bar shown while scrolling, 5/5 languages both
engines). Its drag step first measured the thumb before the scroll event
had moved it, pressed the bar below the thumb and paged the box (3 of 6
webkit runs red, "162 of 191"); it now waits for that scroll, and 8 webkit
and 5 chromium runs in a row pass. sidebar, side-width, side-toggle, strip-scrollbar, view-scrollbar,
view-scrollbar-drag, click-scroll all pass in both engines. Screenshots at
rest and mid-scroll in both engines checked by eye.

Windows: on the Windows 11 box, headless Edge 155 (WebView2's engine)
rendered a sidebar box with origin/main's app.css and with this one. Old:
10px gutter and the classic bar with arrows, as in MOMO's screenshot. New:
0px gutter and no bar, with an unstyled overflow box beside it still drawing
its 10px bar, so system bars were on. Not tried: the overlay bar's JS inside a
real WebView2 or WebKitGTK window (it ran in Playwright's Chromium and WebKit
only).

* gui: Routing, Usage and Sessions keep to the width the other pages do on a large screen, centred (面条 on Discord)

What changed: the window's page-width rule (#860), padding each view to
max(16px, calc(50% - 600px)), now names #view-routing, #view-usage and
to edge while Agents, Providers, Library, Gateway, Plugins and Settings
sat in a 1200px column in the middle. A narrow window keeps the 16px
gutter it had.

Routing's two columns, the Usage cards' packing and the requests ledger
lay out by the room they get (byWidth, packUsage), so they follow the
narrower box: at 1920 Routing still gets its two columns (min1150) and
the ledger fits 1200 without a sideways scroll.

sess-agent-strip.test.cjs asserted that eleven long agent names fit a
1600px window's Usage page in one row. With the page kept to 1200px they
were 8px too wide in WebKit zh (its scroll bar takes width), which is the
strip's designed overflow; the first two names are shortened so the "fits"
case is still one that fits, and the narrow case still overflows. One word
off the first name left it 0.34px of room (1159.66 in 1160), which went
red once in WebKit en under load; two names shorter leave 135px, and it
passed 3 runs in a row in each engine.
sessions-toolbar.test.cjs asserted that ten agents' tabs fit an 1800px
window; in a 1200px page they need 1115px of 912, so the page shows the
compact agent menu (its designed overflow). The fixture now has eight
agents (829px), so the wide case still tests tabs that fit.

Run:
- new page-width.test.cjs: every view's content width 1150..1200 and
  centred at en 1920, zh 2560, zh-TW 1920, ja 2560, de 1920; 16px at en
  900; every view's left edge and padding equal Agents'; chromium and
  webkit, 14/14. Without the CSS change it fails ("sessions: 1676 wide
  at 1920").
- before/after screenshots of Routing, Usage cards, the ledger,
  Sessions and Providers at 1920, 2560, 1100 and 800 (chromium).
- GUI regression set, both engines: click-scroll, editor-short-window,
  ledger-*, panel-usage, quota-*, routing-*, usage-*, sessions-*,
  sess-agent-strip and sessions-toolbar (after the fixture changes).
  routing-group-fold (webkit en/ja/de) and routing-sessions (webkit en)
  fail the same with origin/main 17c12621b's own assets, run alone:
  already filed as #1612 and #1672.
  usage-ledger's webkit "dark, and narrow" failed once in the full run;
  it fails the same with 48e59c5b8's assets (the view left scrolled 32px
  after the resize, the tab under the header), noted on #1671.
- Go: gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., the builds: clean. go test -tags nogui
  ./... at load ~25-60 (other sessions' runs): every package passed but
  internal/agent and internal/gateway, which hit the 30m timeout; run
  again alone, agent passed and gateway's only red was
  TestOTelWaterfallIncludesUnbilledFallback, filed as #1794 (passes
  alone, -count=3).

Not verified: real WebView2 or WebKitGTK windows; layouts were checked
in Playwright's chromium and webkit only.

* sessions: the Sessions page's search finds a session by what was said in it, and a gateway session is titled by what it was first asked (YOU on Discord)

Why: the filter matched only titles, folders, ids and models, and a
session the gateway recorded was listed under its bare ses_… id, so one
couldn't be found by anything a person remembers about it.

What changed:
- sessions.GatewayTitle: the first user text of a recorded session (not
  a <…> context tag, # AGENTS.md or an image), made one line. It reads at
  most 8 complete turns of the oldest file of it, caches a finished
  file's answer by path, and costs one stat when nothing is recorded.
  gatewayListed applies it in every list (/api/sessions, /manage, /one,
  the stats summaries); ExternalSession gained Title.
- GET /api/sessions/search?agent=&q= (searchSessions): an agent's
  sessions, newest first, read by up to 4 workers, each only to its
  first match. Native files go through a byte prefilter (mayHold: the
  query's longest word, ASCII case folded without a copy, 1 MiB chunks,
  skipped for zstd and for queries JSON may escape), and of a Claude or
  Codex file only the lines holding every word are decoded
  (readTranscriptOf; claudeContentOf/codexContentOf take an optional
  line test, nil for every other caller); gateway sessions, and an
  unreadable agent's sessions (unread: true), through their recorded
  transcript. System prompts, tool definitions and images never match.
  It stops at 200 hits or 8s (cut, searched of total) and when the
  request's context ends. Each hit carries the match with 36 runes
  before and 120 after.
- sessions.js: the field says "Search sessions"; title/folder/id/model
  matches show at once, the server is asked 300ms after the last
  keystroke, a new query aborts the request in flight and its answer is
  dropped, under 2 letters asks nothing. A session found shows a line of
  the words round its match with the match in <mark> (text nodes, no
  innerHTML). A note says when it is searching, cut short, failed, or
  limited to recorded text. New strings in zh, zh-TW, ja and de.
- docs/subsystems/gateway-sessions.md describes both.

Run:
- Go: TestSearchSession* (snippet, case and line breaks, said text
  preferred over a tool call, cut ends, cancelled context, a Codex file,
  only matching lines decoded: 1 part of 3), TestContainsFold,
  TestMayHoldSkipsAFileWithoutTheWords (incl. a match across chunks),
  TestGatewayTitleAndSearch (context tag and system prompt skipped),
  TestSessionsSearchFindsGatewaySessionsByWhatWasSaid (endpoint + manage
  titles), TestSessionsSearchStopsWhenItsRequestEnds. Without the
  endpoint/title they fail (404, id as title).
- GUI: new sessions-search.test.cjs in chromium and webkit, en/zh at
  1100, zh-TW/ja at 560, de at 420: title shown, one letter no request,
  one debounced request, snippet mark, cancelled earlier request never
  shown, cut note, empty state, Escape, every language's strings, no
  overflow; 12/12, and 0/12 with the old sessions.js. The sessions-*,
  sess-*, session-* and i18n-keys tests pass in both engines
  (sessions-manage's placeholder updated to "Search sessions").
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., the builds: clean. go test -tags nogui
  ./... at load ~25-60 (other sessions' runs): every package passed but
  internal/agent and internal/gateway, which hit the 30m timeout; run
  again alone, agent passed and gateway's only red was
  TestOTelWaterfallIncludesUnbilledFallback, filed as #1794 (passes
  alone, -count=3).
- Real data, read-only (a temporary probe, not committed, pointed at
  the owner's ~/.claude and ~/.codex; one worker, 8s, load ~50):
  Claude, 58 sessions / 3 GB: before the line filter one 1.3 GB session
  took the whole 8s ("redis": 1 of 58); after, all 58 in 4.7s ("redis",
  13 hits), 7.4s ("gateway session"), 2.8s (no match). Codex, 11534
  sessions / 65 GB: 245-656 sessions in 8s either way, which is what
  the cut note ("latest n of total") is for.

Not verified: the endpoint and page against a real recorded gateway
store (only fixtures and temp homes); the timings above were taken on
a machine at load ~50 and vary run to run.

* gateway: an account out of credits on a model that costs them still serves its subscription's free models (Creat.wu on Discord)

Creat.wu (WorkBuddy AI) spent the credits on glm-5.3-flash, switched to a
free model, and magpie skipped the account. An out-of-credit refusal
rested the whole account (restKey) for 30 minutes: through the WorkBuddy
plugin, whose `explained` passes 14018 on as insufficient_quota, and on the
built-in, whose raw 429 {"error":{"data":{"code":14018,"msg":"Credits
exhausted…"}}} matched no credit word and was read as a rate limit, the
account benched a minute and longer on repeats.

- provider.PaidBesideFree: the model costs credits while the subscription
  lists others Free (catalog.Model.Free: WorkBuddy's x0.00, Qoder's
  is_free, Cline's free models, Command Code's).
- restAfterMarked: out of credit or quota on such a model rests that model
  alone (restID). A free model the vendor still refuses (WorkBuddy refuses
  0-rate models to an account with no package) rests the account on its
  own refusal, as before.
- brokeWords takes "credits exhausted", so the built-in's 429 is out of
  credit, not a rate limit. A rate limit naming credits in passing stays one.
- The fix is in the gateway, which both moved (plugin) and built-in users
  go through, so no plugin release or mover min is needed.
- docs/subsystems/gateway-routing.md says so, with the tests to run.

Tests: TestCreditsExhaustedIsOutOfCredit (literal 14018 body, raw and as
the plugin passes it) and TestOutOfCreditLeavesFreeModels (fake plugin,
two keys, deepseek-v4-pro answered 429 with the plugin's body, then fake-1
must go to the first key). With the restAfterMarked change taken out the
second fails (fakeco@api key rested 30m for credit); with brokeWords back
as before the first fails (rate, want credit). Both pass with the fix.

Not done: credit windows still count free models in Smart/Pace order and
the 98% affinity stop; the account isn't held out there (Credits has no
reset, so Full is 0), only ordered later. Not tried with a real WorkBuddy
AI account. gofmt, vet and the full suite: see the next commit's body.

* provider, catalog: a model listed with a 512-token window is told to agents at models.dev's window, or none, never 512 (H20 on Discord)

H20 and others saw free models (hy3, Cline's free ones) at a 512-token
context window, and Claude Code and Codex then treated them as unusable:
they compact at once. Every agent and the gateway read a model's window
from its catalog entry (Entry.Context, from WindowOf and ListedWindow),
which took any positive window the vendor's or plugin's list gave as said.

Where the 512 itself comes from isn't seen here: models.dev's cache
(2026-10-12), Cline's live /ai/cline/models and recommended feed, the
WorkBuddy and Cline plugins' static lists and magpie's own code give no
window under 4095 for any of these models. It is in a vendor's live list
read at run time (WorkBuddy's /v3/config maxInputTokens or a plugin's
list); so the floor is where every listed window is read:

- catalog.LeastWindow (2048) and catalog.Window: a window under it is not
  known. The smallest real chat windows are about 4096
  (gpt-3.5-turbo-instruct's 4095, mythomax's 4096) and stand.
- mdModel.window: a models.dev limit under it doesn't vote, so the other
  limit, or nothing, answers.
- ListedWindow: a vendor's window under it falls back to models.dev's
  for the model, else 0 (the agent's default).
- pluginCatalog: a plugin's input or context under it is none, so a
  512 prompt cap under a 192K window leaves 192K.
- planModels (Cline): a free model's 512 takes models.dev's too.
- A window the user sets (Contexts) is theirs, however small.

Tests, with the literal 512: TestTinyListedWindowIsUnknown (a Cline
plugin listing cline-free/mimo-v2.6-flash and cline-free/hy3 at 512 is
served at models.dev's 1048576 and 192000; one nothing knows at 0; a real
4096 stands; ListedWindow on a built-in's hy3 at 512 gives 192000; a
user-set 1024 stands) and four new cases in
TestWindowClampsInputAboveContext. Both fail on the code before (512, want
1048576 / 192000 / 0) and pass with it.

Not verified: the reporter's own list, so which vendor sent 512 is
inferred, not seen; not tried in a real Claude Code or Codex.

Run for both commits, on origin/main 94aa15397, sandbox HOME,
private GOCACHE (the shared one was being emptied under the build), load
average 70-86: gofmt -l clean; go vet ./... (darwin) and go vet -tags nogui
./... with GOOS=linux and GOOS=windows pass; go build -tags nogui ./...
passes. go test -tags nogui: catalog, agent, plugin, library pass;
provider -run 'Window|Listed|Plugin|Cline|Free|Catalog|Models' passes, and
the whole of provider passed before the rebase (794s) but for
TestCopilotSecretToolUsername, which fails only inside the command sandbox
(its secret-tool script can't run there) and passes outside it; gateway
-run 'TestVertex|Credit|Rest|Quota|Rate|Free|Plugin' passes. The whole
gateway and provider packages hit their 25m and 9m timeouts on this
machine's load, with stacks in tests still running (vertex, signin_proxy),
not stuck; those two packages weren't run whole at this head.
Rebased again onto 24350a372 (the doc's Verification list took both
lines): go vet -tags nogui ./internal/... and go test -tags nogui -run
'Credit|Rest|Quota|Rate|Free|Group|Window|Listed|AutoMode|Codex' on
gateway, catalog and provider pass.

* agent: Codex's proxy is worked out from the login shell's NO_PROXY and HTTP_PROXY and macOS' HTTP entry alone, as its reqwest reads them, so "Codex 经代理连 magpie" no longer shows while Codex goes direct (liu_dyj on X)

liu_dyj: with the VPN on, magpie said Codex reached magpie through a
proxy that didn't pass its requests on; versions before f156d9046 had
no such check, which is why upgrading brought it.

Cause: codexProxyFor didn't read the proxy the way Codex does.
- It read magpie's own environment. Codex in a terminal has the login
  shell's, and the ChatGPT app's Codex too (ChatGPT.app 26.1007 runs
  $SHELL -ilc at start and Object.assign()s its env into process.env).
  magpie opened from the Dock has neither, so a NO_PROXY=127.0.0.1 in
  .zshrc, which keeps Codex direct, wasn't seen, and magpie probed the
  system proxy and warned.
- For the system proxy it took netproxy's one URL (HTTPS over HTTP over
  SOCKS). hyper-util 0.1.20's Matcher::from_system, which reqwest
  0.12.28 uses for Codex, takes only macOS' HTTP entry for an http://
  URL; with only the HTTPS or SOCKS entry set (ShadowsocksX-NG's global
  mode is SOCKS only) Codex goes direct and magpie warned. On Windows
  it takes ProxyServer as one address, which a per-protocol list
  ("http=..;https=..") isn't (http's Authority::parse refuses two
  colons), so Codex goes direct there too.
- With respect_system_proxy on macOS, CFNetwork's SOCKS entry is
  UnsupportedProxyScheme, and Codex falls back to HTTP_PROXY/ALL_PROXY
  with NO_PROXY (codex-rs outbound_proxy.rs resolve_env_proxy_route);
  magpie used the SOCKS URL.
- The probe spoke real SOCKS5 to a socks5:// proxy. Codex's reqwest is
  built without SOCKS (no tokio-socks in codex-rs Cargo.lock) and sends
  an absolute-URI HTTP request to it, so the probe now does the same:
  it passes a Clash mixed port as Codex does and fails a SOCKS-only
  port as Codex does.

So netproxy.Proxy carries the HTTP and SOCKS entries alone beside URL
(parseScutil, parseWindows), proc asks the login shell for the
*_PROXY variables with agentenv.Vars in the same probe and only reads
them (proc.LoginEnv; never set in magpie's env, whose requests use
netproxy), and codexProxyFor uses both. Failover's gate
(codexProxyOK) and the drift share codexProxyFor and proxyProbe, so
both follow. The pill's How to fix now names the shell profile for
NO_PROXY. Clash/mihomo rule mode with a 127.0.0.0/8 DIRECT rule never
warned and still doesn't; global mode or a rule set without it still
warns, rightly (real codex 502s there). TUN mode sets no proxy and
never warned.

Run:
- real codex-cli 0.162.1 in a sandbox HOME/CODEX_HOME against a fake
  gateway and mihomo v1.19.32 (rule, no-LAN-rule, global ports):
  direct, rule, and ALL_PROXY=socks5:// on the rule port reach the
  gateway; no-LAN-rule and global 502; global with NO_PROXY=127.0.0.1
  reaches it. The Go probe agrees on every one.
- go test -tags nogui ./internal/agent, ./internal/netproxy,
  ./internal/proc; gofmt -l; GOOS=linux and GOOS=windows go vet
  -tags nogui on the three packages.
- Broke each part by hand: sys.URL back in codexProxyFor (Windows per
  protocol, macOS HTTPS/SOCKS alone red), the probe's socks->http
  (TestRealProxyProbe red), codexEnv without the login shell
  (TestCodexEnvTakesLoginShell red), the respect-path SOCKS fallback
  (three respect cases red), setUnset of every shell var and the probe
  without ProxyVars (TestLoginEnvProxyVarsNotSet red).

Not tried: the macOS system proxy cases with real Codex (changing the
system's proxy settings is off limits here; read from hyper-util,
reqwest and codex-rs sources), the Windows per-protocol ProxyServer
with real Codex (from the http crate's source; no Windows run), and
the reporter's own app and mode, which are asked on X.

* gateway: an MCP request longer than its route takes is refused whole with 413, not run as the part that fit (#1766)

What changed: serveMCP (magpie's own web-search and vision MCP servers)
and the signed-in MCP proxy (/mcp/{name}) read the body through
readMCPBody, which reads one byte past the limit and answers 413 when the
body is longer, or when Content-Length already says so. Before, a plain
io.LimitReader ended at the limit as if the body had, so a valid JSON-RPC
message padded with whitespace past the limit, or followed there by a
second message, was parsed as its prefix and run: an analyze_image call
reached the image model, and the proxy sent the cut body on to the
signed-in server with the user's token. A body exactly at the limit still
works.

Why: #1766 (ggbdpq) reported it for the two own MCP routes with a patch;
the proxy's read was the same shape and is fixed beside them.

Run: TestOwnMCPRejectsOversizedBody (the reporter's test, extended to a
known Content-Length too) and the new TestMCPProxyRejectsOversizedBody
fail on the old search_mcp.go/mcp.go with HTTP 200 instead of 413, the
image model called 1 -> 5 times, and the proxied server seeing the cut
"tools/call"; they pass with the change. TestMCPProxy*, TestVisionMCP*,
TestSearchMCP* pass. Full suite and vets are recorded on the push.

Not done: the GUI's local /api handlers decode JSON through LimitReader
too; they take only the first JSON value whatever the length and are
not reachable by another machine, so they are left as they are.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>

* gateway: another model's reasoning_details goes to Kimi as reasoning_content, so a conversation MiMo began is no longer refused 400 on every turn (#1765)

What changed: a Chat request to Kimi (isKimi: the Kimi platform's or a
Kimi Code membership's host or preset) has each message's
reasoning_details left out, its thinking put in reasoning_content when
the message has none (reasoningDetailsAsContent). refusedInMessages also
reads Kimi's own wording, "the <field> at position N", so another
upstream that refuses the field that way (a relay in front of Kimi) is
asked once more without it and marked; the retry and the remembered mark
keep reasoning_details' thinking as reasoning_content too
(withoutMessageReasoning).

Why: Leo-origin's session was answered by MiMo through Command Code,
whose reasoning_details entries carry a stream's index; pi sends them
back, and Kimi Code answered 400 "the reasoning_details at position 2
entry 0 must not contain streaming index" on every turn. Probed against
the real api.kimi.com/coding/v1 on 2026-10-12: Kimi refuses
reasoning_details in every shape tried (with index: "must not contain
streaming index"; reasoning.text, reasoning.summary, reasoning.encrypted,
text, thinking without it: "has an invalid type"), and passes
reasoning_content, reasoning and an empty list through validation.

Run: TestKimiGetsReasoningDetailsAsContent and
TestReasoningDetailsRefusedAtPosition (fake Kimi answering with the
probed bytes) fail on the old gateway.go/chattidy.go: 400 "Kimi Code
(China): the reasoning_details at position 1 entry 0 must not contain
streaming index" after 1 call, the reporter's message, and "400 after 1
calls (want 2)". They pass with the change, as do TestMistral*,
TestMessageReasoning* and the other *Reasoning* tests.

Not verified: a real k3 reply through magpie; the owner's Kimi Code
subscription has lapsed, so the real probe reached only validation
(a valid request got 403 "does not have access"). A 400 magpie doesn't
recognize still ends the request rather than failing over; that is
unchanged.

* gateway: keys all out of their allowance are answered from their rests with a Retry-After, not asked again on every request, and a key listed twice is asked once (#1772)

A fleet on four Ollama Cloud keys, every one out of its weekly allowance:
each new request asked every key again (the first twice) and answered
429 with no Retry-After, so an agent that waits as told asked again at
once, and the vendor saw four refused requests a turn.

What changed:
- The first key twice: the reporter's providers.json named the first key
  in "keys" as well as "key". KeysOn now lists a key once.
- When every key left for a request rests out of its allowance (a 429 or
  402 that failure() calls quota or credit, keys only), the request is
  answered from the rest without asking: the vendor's own words, "not
  asked again before HH:MM", and Retry-After until the first of them is
  back (quotaHeld, soonestBack). Accounts are left out, so autoReset
  can still spend a reset for them; a 403 or 400 worded as quota is
  asked as before.
- The last key out of its allowance now rests as the ones before it do
  (before, the last one left was never rested), and a 429 the vendor gave
  no Retry-After for gets the soonest rest's end as one.
- A provider can set how long its keys rest when the vendor says nothing
  of when the allowance is back: quotaRest (minutes) in providers.json,
  or `magpie provider quota-rest <id> 7d`; default stays 15 minutes, at
  most 8 days. A time the vendor names (resets_at, Retry-After, a
  window) still wins. A GUI save keeps it.

What was run:
- TestAllRestingAnswersFromRest, TestFirstKeyListedTwiceAskedOnce and
  TestOwnQuotaRest fail on the old code (no Retry-After, keys re-asked;
  "dead-1 dead-1 dead-2 ok-3", the reporter's log); they pass now, with
  TestQuotaHeldOnlyForKeysOutOfAllowance, TestDeadChainWalksEachOnce and
  TestRestMinutes. The mock answers with the reporter's literal 429 body.
- go test -tags nogui ./internal/provider ./internal/gui pass. A gateway
  package run at load ~60 hit its 20m timeout mid-suite with only
  TestMaxRPM* red; those pass 8/8 alone here and on origin/main
  17c12621b (timing under load, filed as #1791).

Not verified: no run against real Ollama Cloud keys; quotaRest has no
field in the provider editor (CLI and providers.json only).

* gateway: a refusal's note keeps Anthropic's stop_details category and explanation, on the Routing page's try and in the agent's error (#1768)

jingchangshi's sessions got "claude-opus-5-5 refused this request (safety
filter: refusal) via Claude Code" 19 times, with nothing to say which of
Anthropic's classifier categories (cyber, bio, frontier_llm,
reasoning_extraction, general_harms…) it was. Anthropic sends that in
stop_details beside stop_reason "refusal"; magpie read only stop_reason.

Rather than the separate opt-in JSONL sink the issue proposes, the
category goes where every refused attempt is already recorded: the note
of that try on the Routing page, including a try a later key or group
member answered after, and the error the agent gets when nobody is left.
It is the vendor's own words, so nothing of the user's request is stored
anywhere new.

What changed:
- refusedDetail: "safety filter: refusal (category cyber: <explanation>)",
  the explanation whitespace-folded and cut at 200 characters; a null or
  missing category or explanation adds nothing, an unknown category is
  kept as given. Used for a streamed message_delta and a whole reply.
- stop_details is carried through the IR (Event.StopDetails,
  Result.StopDetails) from an Anthropic upstream's stream and from the
  claude CLI's stream-json (a Claude subscription), and written back into
  an Anthropic client's message_delta or whole reply, as
  safeguard_results already is.

What was run:
- TestRefusalKeepsStopDetails (stream, whole, nulls, absent, unknown
  category, long explanation), TestRefusalCategoryOnTheTry (refused key
  then an answering one: the refused try says "category cyber") and
  TestClaudeSubscriptionRefusalMovesToNextAccount (now with stop_details
  in the CLI's refusal) fail on the old code and pass now; the refusal,
  safeguard and Anthropic tests pass.

Not verified: no real Anthropic refusal with stop_details seen (the
bytes follow Anthropic's documented shape); a Codex or Chat client
served by Claude gets the category on the try only when the hold
writer sees it in its own protocol, which Responses and Chat have no
field for, so their try notes stay "safety filter: …" as before.

* gateway: a Responses provider set codex=as-sent gets Codex's requests as Codex sent them, for a relay that checks they are Codex's own (#1758)

A relay that checks a request is Codex's own answered magpie 400
"Codex 客户端请求特征无效" (10014). magpie fits every Codex request
for a Responses backend that isn't OpenAI's: Responses Lite's
additional_tools item is lifted into tools (#350), the tool search
goes as a function, and OpenAI-only fields such as
stream_options.reasoning_summary_delivery are left out. The reporter
found that the relay takes the request when additional_tools is left
as an input item, and that the lifted shape is what it refuses.

The lifting stays the default, because backends that aren't OpenAI's
refuse additional_tools or silently drop it (#350). A provider can now
opt out: `magpie provider set <id> codex=as-sent` (`codexAsSent` in
providers.json; `codex=default` turns it back off). With it on, a
request from Codex (fromCodex: Codex's User-Agent or originator) goes
as Codex sent it, with only its model name swapped. Codex's own
headers go with it as before. A subscription account is never sent
this way, and the GUI's provider save keeps the setting.

What was run:
- TestCodexAsSent: by default the request is still fitted; with
  codexAsSent the upstream gets exactly what Codex sent, with model
  m1, X-Codex-Turn-Metadata and the Responses Lite header. It fails
  on the old gateway.go and passes now. TestAdditionalTools and the
  gateway's Codex tests pass.

Not verified: not tried against the reporter's relay. Their check
was made by hand outside magpie, so which other fields that relay
looks at is not known. There is no GUI control for the setting
(CLI or providers.json only).

* gateway: a provider that refuses auto mode's safeguards is asked again without them and not sent them again, so Copilot's claude-opus-5.5 answers Claude Code (#1756)

Pylogmon's Claude Code on Copilot's claude-opus-5.5 got 400
invalid_request_error "Copilot: safeguards: Extra inputs are not
permitted" on every turn, which magpie labels "request format not
accepted". Their Sonnet worked. Claude Code's auto mode adds a
top-level `safeguards` field for the API's review of its actions.
magpie passes it on to any Claude model (automode.go), and Copilot's
Messages API checks its fields strictly and turns the field away.

The fix uses the existing class for Claude Code's newer fields that a
relay refuses (anthropic_shapes.go: thinking.display, a turn's
output_config). On a 400 naming `safeguards` with "Extra inputs are
not permitted", forward asks again at once without the field and
remembers that the provider refuses it (shapeSafeguards), so later
requests leave it out the first time. Claude Code, finding no
safeguard_results, reviews its actions locally, as it does for every
non-Claude model. The fix sits in forward/forwardOnce, so it reaches
every route to an Anthropic endpoint: relayed and translated
(buildAnthropic), any provider, not only Copilot.

What was run:
- TestSafeguardsRefusedLeftOut (refusal text as the reporter quoted
  it): on the old anthropic_shapes.go the agent gets the same
  "Cop: safeguards: Extra inputs are not permitted" 400; now it gets
  200, asked twice the first time and once after that.
- TestSafeguardsKeptWhereTaken: a provider that takes the field
  still gets it.
- The shapes, system-message and auto mode tests pass.

Not verified: no Copilot account with claude-opus-5.5 was available,
so Copilot's raw error body is assumed. The match is on the words the
reporter quoted, which magpie shows after "Copilot: ".

* gateway: a turn that names no reply limit is sent the model's own as max_tokens on Anthropic's API, not a flat 16384 (#1792, tensornull)

Anthropic's Messages API needs max_tokens. A request that names none
(Codex's Responses turns, a Chat client's) was always sent 16384, so a
long thinking and tool turn on a Claude-shaped relay hit the limit, and
Codex showed "Incomplete response returned, reason: max_output_tokens".

Now such a request is sent askedOutput(p, model). That is the plain
Served entry's PublishedOutput(), the same number the agents are told:
the user's Max output first, else the vendor's list or models.dev,
within the window. 16384 (defaultMaxTokens) is used only when nobody
knows the limit. A limit the client names still goes as it is. The
thinking budget is still fitted under max_tokens (anthropicBody),
whatever the limit is.

Both places that build an Anthropic body are covered:
forwardTranslated, for every translated route, and serveZed for a Zed
subscription's Claude models.

The provider editor's Max output hint now says this number is also
sent as max_tokens (en, zh, zh-TW, ja, de). docs/reference.md and
docs/subsystems/gateway-routing.md no longer say the gateway never uses
the limit.

Run:
- TestAnthropicMaxTokensIsTheModels covers: the user's 65536 (Responses
  plain and streamed, and Chat), models.dev's 64000, a 500000 limit
  held to the 100000 window, an unknown model at 16384, the client's
  own 1000, and thinking under 8192.
- TestZedClaudeMaxTokensIsTheModels expects 40000 when the client names
  no limit and 1000 when it does.
- Both tests fail on the old code: 16384 where the model's number was
  expected.
- go test ./internal/gateway/ passed (1270s, under load).
- provider-max-output.test.cjs passes 28/28 in chromium and webkit:
  5 languages at 900 and 420px. The hint names max_tokens and
  Anthropic, is translated, and doesn't overflow.
- gofmt -l is clean. go vet passes on darwin, on linux with -tags
  nogui, and on windows.

Not tried against a real Anthropic-compatible relay with a real Codex
session.

* library, gui: Hooks are a fifth Library category, kept once and written into each ticked agent's own hooks file (#1790, AllenReder)

What: the Library page has a Hooks tab beside Instructions, MCP, Skills
and RTK. A hook is a command, an event, an optional tool filter, a
timeout and the agents ticked for it. magpie writes it into each agent in
that agent's own file and shape:
  Claude Code  <claude dir>/settings.json   hooks.<Event>[{matcher, hooks[]}]
  Codex        <codex home>/hooks.json       same shape
  Gemini CLI   ~/.gemini/settings.json       same shape, timeout in ms
  Cursor       ~/.cursor/hooks.json          flat entries, version 1
Portable events (turn end, after a tool, before a tool, prompt sent,
session start) map to each agent's own name; "shell"/"edit" map to each
agent's own tool names. An agent's own event (codex:PermissionRequest,
cursor:afterFileEdit, ...) is offered too and given to that agent only.
Rows have agent chips (All first), Select + bar, and Remove all, like
skills and servers. An agent that can't take a hook has its chip greyed
with the reason: every agent but those four ("has no hooks magpie can
write"), an agent in WSL (not yet), and another agent for a native event.
The page also says when an agent has all hooks turned off
(disableAllHooks, hooksConfig.enabled=false, [features] hooks=false).

Why these choices (product call delegated to us): the four agents are
the ones with a documented, file-based command-hook API whose events line
up; others (OpenCode's JS plugins, dsh, ...) have no comparable file, so
they're named as unavailable rather than half-supported. Removal is
exact: Applied.Hooks records each entry as written (canonical JSON), and
only an entry still exactly as written is taken out; one the user edited
is theirs, and their own hooks beside it are never touched. A hooks file
that doesn't parse is a problem, never treated as empty or written over.
Codex keeps trust per hook in config.toml keyed by group position, so
taking a group out re-keys the user's trust for the groups after it
(codexRekey) instead of silently untrusting them. Carried bundles
(backup/WebDAV/S3) don't carry hooks in this first version.

Run:
- go test ./internal/library ./internal/gui (sandbox HOME): pass. New
  hooks_test.go: each agent's shape; the user's edited entry stays and is
  no longer recorded; an unparseable file is left alone and reported;
  Codex trust moves with its groups; native events/unavailable agents;
  hooks-off reported.
- library-hooks.test.cjs: 12/12 in chromium and webkit, at 440px, in en,
  zh, zh-TW, ja, de; against the old library.js it fails (timeouts on the
  missing tab). All 52 new strings translated in the 4 languages.
- library-loading.test.cjs expects the Hooks tab in its tab lists
  (it failed on this change before; 6/6 now).
- Every library-*/skill-* GUI test in chromium and webkit: all pass but
  WebKit timeouts in library-mcp-tool-switch/library-mcp-tools, which fail
  the same on origin/main b0a904bd9 under load (#1609, commented).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. Full go test ./... at the pre-rebase
  head c1c1a730f: 49 packages ok. After rebasing onto 86b2f4d05:
  library, gui and gateway's Anthropic/Zed tests ok.

Not tried: real Claude Code / Codex / Gemini / Cursor runs firing the
written hooks; the shapes were checked against each agent's source and
docs, not executed.

* gui: Settings › General says each setting's name alone where it says enough, and Language is one menu (1ooogle on X)

1ooogle's mockup on X redrew Settings › General the way macOS System
Settings reads it. The owner approved, and this follows it.

Rows that now show only their name:
- Appearance, Text size, Interface and Code font, the tray click,
  Provider in model names, the Codex titles, auto-review and memories
  model rows, Open at login and Show in Dock.
- A font row's line shows only while its fonts are loading or have
  failed.
- The text size keys (⌘0 / Ctrl+0) move into the choices' tooltip.

Rows that keep one short line, because the name alone doesn't explain
the setting or what it costs:
- Codex subagents, Long conversations, Lightweight mode, Prevent sleep
  and Session terminal.

Renames:
- "Tray icon" becomes "Click the tray icon to", with the choices "Open
  the quick panel" and "Open the main window" (点击托盘图标: 打开快捷面板 /
  打开主窗口).
- "Keep awake while agents work" becomes "Prevent sleep" (防止休眠: 在
  magpie 运行任务时,让电脑保持唤醒状态).
- "Dock" becomes "Show in Dock" (显示程序坞).

Language is one button showing the language picked (renderLangPick).
It opens in the app's own menu (openProtoMenu, styled like Session
terminal's sess-pick), not a native <select> and not six segments.

Every language gets the same text: en, zh, zh-TW, ja and de. The 25
strings no longer used are removed from all four translations.

Tests:
- New: settings-general.test.cjs. In Chromium and WebKit, en, zh,
  zh-TW, ja and de, at 1000 and 440 px, on a Mac, it checks that:
  - the rows that should show only their name have no line;
  - the kept lines are one line each, and none is cut short at 1000px;
  - Language is a button showing the language, and its menu lists all
    six;
  - a pick saves lang and redraws the page in that language, with the
    button staying under the pointer;
  - nothing has a left stripe and nothing scrolls sideways.
  I broke it by hand twice and saw it fail both times: once by giving
  the Dock row a line back, once by making the pick save nothing.
- Updated to the new text and controls: codex-titles,
  codex-auto-review, codex-memories-settings, model-suffix-own,
  plain-names, lightweight, keep-awake, text-size, gateway-mode,
  omarchy, settings-search, gui-zh-tw (Language's button and menu fit
  at 1000/440px), header-relang (picks through the menu) and
  readable-focus (the first shown line).
- German's long-conversations line was shortened to fit on one line at
  1000px.

What was run:
- go test -tags nogui ./internal/gui passes; gofmt -l is clean; go vet
  passes on darwin, linux and windows.
- The whole GUI suite (601 files, --test-concurrency=4): 6584 passed,
  33 failed. Every failing file was then run alone:
  - mobile-web fails on purpose. It compares desktop screenshots with
    origin/main, and only the Settings page differs.
  - routing-group-fold, text-size, routing-sessions and pick-skills
    are #1672; searcher-pick is #1745. Each also fails alone on
    origin/main 260ded9af.
  - routing-provider-off, routing-steady and usage-sum-whole pass when
    run alone, both here and on main.
- Screenshots before and after (zh, en and de light at 1000px, zh at
  440px, zh dark) were looked at.

Not tried in the real Wails window.

* agent, proc: where each command is on PATH is looked up once while its folders are unchanged, so a Windows page doesn't stat PATH per agent and per session (#1771)

oxyuan profiled every page's first load on Windows at seconds (4-7s), and
Sessions, Usage → Sessions and Context at 26-45s: 96-98% of the samples
were os.Stat under exec.LookPath and proc.FindTool. A failed lookup stats
every PATHEXT candidate in every PATH folder (111ms there), and the pages
asked once per known agent (Detected → binAt) and once per Pi session
(sessions.carries → ompThere) on every request.

proc.Look (new, look.go) is exec.LookPath with its answers kept. The
proc.LookPath that 1bf722e28 added (exec.LookPath, then Unwrap of a mise
wrapper script) is now Look then Unwrap, and FindTool keeps its PATH
answer the same way before Unwrap. Unwrap keeps its own answer by the
script's size and time, and on Windows it returns at once. The PATH
answers are keyed on PATH and PATHEXT,
and dropped when a looked-in folder's modification time changes (an
install or removal), checked at most every 2s, every time in a test binary
testenv isolated. proc.Forget drops them all and agent.Rescan (the Agents
page's refresh) calls it. Every exec.LookPath that a page or the gateway
reaches now goes through one of them. The sites 1bf722e28 made unwrap keep
LookPath: agent (agent, air, nativemodels) and provider (codex models,
cursor, devin, kiro). The rest keep exec.LookPath's answer as it was,
through Look: agent (agents, cliupdate, the shim, gemini, install,
reasonix, vscode, zed), sessions/carry and library/rtk. Those left
on exec.LookPath run once per user action (update's pkexec, the
secret-tool read, installers, rtk upgrade) or in tests.

Run:
- look_test.go: asks once while folders are unchanged, sees an install and
  a removal, a changed PATH and Forget, concurrent lookups under -race. The
  first goes red with LookPath calling exec.LookPath directly.
- On the Windows box (yeton@10.0.0.132, amd64 probe, sandbox USERPROFILE):
  Detected with 4 agents 252ms → 7ms per call after the first, 297x
  LookPath(omp) 879ms → 1.1ms; drift over Detected 274ms → 42ms; Titles
  for 6 sessions 23ms → 4ms. The first call is the same (it looks).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., sandboxed go test ./... at the rebased head.
Not run: the reporter's own machine (47 PATH folders, 59 agents).

* build: the Windows app's icon group is resource 3, the one Wails gives its window, so the taskbar shows the bird and not a blank page (#1777)

Wails v3 sets a Windows window's icon from the icon group with numeric
resource ID 3 (NewIconFromResource(GetModuleHandle(""), 3) in
webview_window_windows.go). build/windows/winres.json named the group
"APP", and go-winres makes a numeric ID only of a "#n" key, so the exe
had no group 3: the window got no icon, and the taskbar and Alt-Tab drew
Windows' blank page. The group is now "#3".

internal/cli/winres_test.go fails while the group isn't under "#3".

Run:
- go-winres v0.3.3 make as the Makefile's release-windows, an amd64 build
  of each on the Windows box (yeton@10.0.0.132): the new exe has group 3
  and LoadImage(3) succeeds; the old one has neither.
- TestWindowsIconIsResourceThree red on the old winres.json, green now.
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., sandboxed go test ./... at the rebased head.
Not run: the taskbar of the running app seen with the eye; the release
build (signed) wasn't made.

* agent: a model picked for omp's default role joins its enabledModels list when there is one, so omp starts on it and doesn't pick another (#1769)

real-jacket: with enabledModels in ~/.omp/agent/config.yml, magpie wrote
only modelRoles.default, and omp kept starting on a model of the list. omp
holds a new session's default role to that list while it names anything
(main.ts buildSessionOptions, sdk.ts resolveAllowedModels and
pickDefaultAvailableModel); its other roles resolve against every model it
has, so only the default role is held to it. Pi had the same rule, fixed
in #160.

omp_scope.go: a model picked for the default role is added to the end of a
list that doesn't already take it in, by name or by one of omp's globs
(Bun.Glob, where * doesn't cross "/"), comments and order kept
(edit.EditYAMLNode, new). No list, or an empty one, is left as it is: omp
then takes every model. Entries scoped to folders ({path, models}) are the
user's and never changed. Disconnect takes the plain magpie/... entries out
once nothing else in config.yml is on magpie (a list left empty goes,
never []); a scoped entry on magpie still counts as in use. A renamed
provider's entries are renamed once (ompScopeOnce). Check reports a
default role on magpie the list leaves out as drift, which Reapply mends.

docs/subsystems/agent-wiring.md says the same.

Run:
- omp_scope_test.go: the default joins the list (plain, glob, level
  suffix, comments kept), a list that takes it in or none is left alone,
  Disconnect clears magpie's entries and keeps the user's and scoped ones,
  and the leaving-out is drift. Each goes red with its part taken out
  (ompScopeWith not appending, dropMagpie not calling ompScopeWithout,
  Check without the list).
- go test -tags nogui ./internal/agent ./internal/edit.
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., sandboxed go test ./... at the rebased head.
Not run: a real omp binary starting a session on the config written. Pi
has no RenameRefs, so a renamed provider's magpie/<old>/... entry stays in
Pi's enabledModels (not changed here).

* gui: turning subscription accounts off asks first, naming the subscriptions that stop working in magpie (#1761)

The reporter turned Settings → Privacy → Subscription accounts off and every
subscription they had stopped working, with nothing to say why, and asked
for the switch to go. It stays: #1535 asked for it so that magpie can run
on a managed or shared machine as a gateway for API-key providers alone,
without reading any agent's credential files or the Keychain, and that
reporter confirmed it on v0.1.1176. What reading those files means is a
privacy question, so it stays on the Privacy page too.

What went wrong is that one click took them all away. Off now asks first
in a dialog (confirmAction, as Remove does), titled "Turn off subscription
accounts?", that names the subscriptions in use it stops (switched-off
ones and API-key providers aren't named; the Providers list is read for it
when no page has yet) and says API-key providers go on. Cancel leaves it
on with nothing saved. On, and the CLI's `magpie accounts discovery off`,
don't ask. New strings in zh, zh-TW, ja and de.

docs/subsystems/providers-accounts.md says so.

Run:
- account-discovery.test.cjs, chromium and webkit, en/zh/zh-TW/ja/de at
  900 and 360: the dialog's title and button in each language, the two
  subscriptions in use named and the switched-off one and the API-key
  provider not, the dialog inside the window, Cancel posts nothing and
  leaves On, then taking it posts {off:true}; the rest as before. 32 pass;
  with app.js put back, the dialog never comes and it goes red.
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., sandboxed go test ./... at the rebased head.
Not run: the desktop app's webview by hand.

* sessions: CodeBuddy Code's own calls reach Usage, read from its session files as WorkBuddy's are, and its calls through magpie's gateway are left to the gateway (#1779)

CodeBuddy Code was wired on the Agents page, but nothing read its session
files, so a call it made straight to its vendor never reached the usage
ledger. Only the calls it made through magpie's gateway showed, logged by
the gateway.

CodeBuddy Code writes its sessions the way WorkBuddy does:
projects/<cwd>/<id>.jsonl under $CODEBUDDY_CONFIG_DIR, else ~/.codebuddy.
A reply's usage sits in providerData.usage on its function_call or
assistant message line, keyed by providerData.messageId, and models.json
has the same format. So WorkBuddy's reader is now parameterized by agent:
- buddyFiles(agent, dir) lists the files.
- buddyGateway(dir, id) reads that agent's own models.json. Its stamp
  cache is kept per path.
- readWorkBuddyCalls takes the agent from the file.
"codebuddy" is registered in callSources and wholeCallReaders. A model
CodeBuddy asks for as custom-local:<id>, where models.json names <id> with
vendor "magpie", went to the gateway, and is skipped as WorkBuddy's are.

The fixtures in testdata/codebuddy are CodeBuddy Code 2.164.0's own files
(npm @tencent-ai/codebuddy-code), with only the cwd path shortened. They
come from two `codebuddy -p` runs in a sandbox HOME against a local OpenAI
fake: one on a model the user added for another vendor (counted: two
replies, 521 in + 26496 cache read, 115 out), and one on a vendor "magpie"
entry (skipped).

Run:
- TestCodeBuddyCalls goes red (0 calls) with codebuddyCallFiles taken out
  of callSources, and green with it in.
- TestCodeBuddyGatewayIsItsOwn checks that each agent's models.json is its
  own.
- go test ./internal/sessions passes.
- gofmt, go vet, Linux nogui vet and Windows vet are clean.
- Sandboxed go test ./... at the rebased head.

Not done:
- The Sessions page still doesn't list CodeBuddy Code's sessions. This
  commit is the Usage side only.
- Reasoning tokens (outputTokensDetails) aren't recorded, as for WorkBuddy.
- Not run against the reporter's China-edition session (47 calls). The
  line shapes match those in the issue.

* gateway: image recognition and web search that magpie picks pass over a model out of its allowance, and ask none when every one is out (#1801, hibaliqya-yonma)

What was wrong: AutoVision (the model that describes images for models
that can't see) and autoSearcher (the model that searches for models
that can't) pick a provider and model before routing runs. They never
looked at routing's allowance state. That state covers accounts barred
at a usage cap, rests for quota or credit, and full key or subscription
windows. Routing then had one candidate and tried it all the same. Each
image or search was sent to the account that had run out and got the
same 429 again, while another provider with allowance sat unused.

What changed:
- fallback.go: spentModel(p, model, from, now). A model is spent when
  every candidate routing would try for it (perKeyBarred) is capped,
  resting for quota or credit, or has a full window (candidate.full,
  model-aware for pools). It also says when the first one is back. A
  rate rest doesn't count.
- search.go: smallModel goes through smallReady, which prefers models
  that aren't spent (pickSmall keeps the old choice among them).
  autoSearcher ranks a searcher with allowance before searchRank.
  modelSearch doesn't ask a spent searcher that magpie picked
  (searcherSpent), tries the others with allowance first, and adds why
  it skipped to its error. A searcher named in Settings is asked as
  before.
- vision.go: AutoVision ranks ready first, then tier and cost. When
  every describer is out it still names one, so seer and Described
  (which tell agents every model takes images) don't flip with a
  window. askVisionWith (gateway and MCP) answers an auto describer
  that is spent with the reason and when it is back, and doesn't call
  upstream. A describer named in Settings is asked as before.
- Image and video generation (AutoDrawer, AutoVideomaker) are left
  as they were.
- docs/subsystems/gateway-routing.md: new section, tests added to
  Verification.

What was run:
- New tests in side_spent_test.go: TestAutoVisionPassesOverOneOut,
  TestAutoVisionTierAmongThoseWithAllowance,
  TestSpentModelAcrossAccounts, TestVisionDoesNotAskSpentDescriber and
  TestSearcherPassesOverOneOut.
- Broken by hand three ways:
  - spentModel returning false: all five go red.
  - Only autoSpent's check in askVisionWith removed:
    TestVisionDoesNotAskSpentDescriber goes red (200 from upstream).
  - Only modelSearch's skip removed: TestSearcherPassesOverOneOut goes
    red.
- go test ./internal/gateway -run 'Search|WorkBuddy|Kimi|Vision|Spent|PassesOver'
- gofmt -l, go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  and GOOS=windows go vet ./... are all clean.
- Full go test -timeout 40m ./... in a sandbox HOME at load 66-100:
  47 packages ok. internal/gateway and internal/agent hit the 40m
  package timeout. Gateway also had failures, each filed:
  - TestOTelWaterfall* (#1794, fixed on main since).
  - TestCodexHeardWithinItsIdleTimeout (#1800).
  - TestIntentClassifierGroup (3.17s against a 3s bound, filed as
    #1813).
  All of them pass alone, and go test ./internal/gateway on its own is
  ok (982s).

Not verified: not tried with a real account that has run out. Windows
was only vetted.

* gateway: a WorkBuddy model searches the web with WorkBuddy's own search service, so Claude Code's WebSearch on it gets results (#1798, lemonwater379)

What was wrong: WorkBuddy's models have no search tool of their own.
When magpie had nothing else that searches (no Claude or Codex account,
no search API), canSearchFor was false. magpie then took the
web_search_20250305 server tool out of Claude Code's WebSearch request,
the model answered from nothing, and WebSearch showed no results.
WorkBuddy's own client searches through a service of its plan.
Its CLI's WebSearch tool (WorkBuddy.app's
app.asar.unpacked/cli/dist/codebuddy.js, WEB_SEARCH_API_PATH) sends
POST <site>/agenttool/v1/search with
{"query","type":"text2text","max_results":5}.

What changed:
- search_workbuddy.go: wbSearch asks that service. Provider.Sign
  signs the request as the plan's chats are signed, and Provider.Do
  sends it, so it works the same for the built-in and for a WorkBuddy
  moved onto its plugin (the plugin's fetch signs it, as for
  /v3/config and images). No plugin change is needed.
- searchesOwn includes a WorkBuddy plan, as it does a Kimi Code plan.
  Its own models' searches go there first, before magpie's picked
  searcher and the search APIs. Other providers' models never use it.
  It is off when provider search is off in Settings.
- A {code, msg} refusal (15001 is its search quota) is reported as an
  error, not as an empty result.
- docs/subsystems/gateway-routing.md: new section, tests added to
  Verification.

What was run:
- The real service, read-only, with the owner's desktop sign-in (China
  build) and the plugin's WorkBuddy AI sign-in. Both answered 200 with
  results, including with only the built-in's smaller header set. The
  test fixture is WorkBuddy AI's real reply bytes.
- End to end with the real China-build account: a throwaway program
  (not committed) under a sandbox HOME holding a copy of the desktop
  sign-in. It sent Claude Code's literal WebSearch request through
  gateway.New().Handler() to workbuddy/deepseek-v4.1-flash and got 200
  with one web_search_tool_result block holding real URLs.
- New tests: TestWorkBuddySearchesForItsModels (built-in, Claude Code
  2.1.285's literal request) and TestWorkBuddyPluginSearches (plugin).
- Broken by hand (wbSearches returning false): both go red. The
  built-in test's reply is the model's "I can't search." with no
  web_search_tool_result, which is the reporter's case.
- go test ./internal/gateway -run 'Search|WorkBuddy|Kimi|Vision|Spent|PassesOver'
- gofmt -l, go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  and GOOS=windows go vet ./... are all clean.
- Full go test -timeout 40m ./... in a sandbox HOME at load 66-100:
  47 packages ok. internal/gateway and internal/agent hit the 40m
  package timeout. Gateway also had failures, each filed:
  - TestOTelWaterfall* (#1794, fixed on main since).
  - TestCodexHeardWithinItsIdleTimeout (#1800).
  - TestIntentClassifierGroup (3.17s against a 3s bound, filed as
    #1813).
  All of them pass alone, and go test ./internal/gateway on its own is
  ok (982s).

Not verified: WorkBuddy AI end to end through the gateway (its desktop
sign-in in the sandbox wasn't picked up; the service itself answered).
Not tried through a running magpie app with the plugin installed.

* provider: the Qoder movers ask for opencode-qoder-auth 0.2.14, so a queued 10605 is a 503 to retry, not "sign in again" (plugins #98)

What changed: the min of the "qoder" and "qoder-cn" movers (one
qoderMover for both) goes from 0.2.11 to 0.2.14, with the note of what
0.2.12 to 0.2.14 brought. keepMovedCurrent updates every moved user's
plugin to it.

Why: 0.2.14 reads Qoder's error code the way Qoder.app's own client does
(QoderErrorCode in its qoder-agent-sdk worker): 10605 (the model's queue)
is a 503 with Retry-After from retryAfterSeconds, the quota/credit codes
110, 112-119, 122 are 429, the request refusals 406, 416, 430, 80411,
80412, 100400, 100401, 100403 are 400, and only 105 or no code is the
"sign in again" 401. A real trial account had every chat answered
403 10605 and was told to sign in again. 0.2.13 lists models from
Qoder's app scene first, so its new default Fast 0.8x shows (plugins #97).
0.2.12 keeps Qoder's own reason in a refused chat's error.

Qoder's table has no 100402 (checked in Qoder.app's
qoder-worker-runtime.obf.mjs), so the note lists 100400, 100401, 100403
as the plugin does.

Run: npm view @magpie-community/opencode-qoder-auth version -> 0.2.14;
go test ./internal/provider -run 'Mov|Migrat|Plugin|HandOver|Adopt' ok;
gofmt -l clean; go vet ./internal/provider on darwin, linux, windows ok.

* gateway: Qoder's queue (code 10605) is a 503 with Retry-After for users still on the built-in, not "sign in again" (plugins #98)

What changed: qoderFailure (internal/gateway/qoder.go) read every 401/403
as "Qoder: the sign-in lapsed — sign in again". It now reads Qoder's own
code first, whatever the HTTP status, the way Qoder.app's client does
(the QoderErrorCode table in its qoder-agent-sdk worker,
qoder-worker-runtime.obf.mjs) and as @magpie-community/opencode-qoder-auth
0.2.14 does (plugins f573cfd):
- 10605, or a queue state (in "queue" or in the message as JSON) with
  isQueued true or serviceAvailable false: 503 "Qoder is busy for
  <model> (this plan's queue: <tier>); try again in <n>s", with
  Retry-After from retryAfterSeconds rounded up (30s when absent).
- 110, 112-119, 122 (usage or credits used up): 429.
- 406, 416, 430, 80411, 80412, 100400, 100401, 100403 (refusals of the
  request; Qoder's table has no 100402): 400 with Qoder's words.
- 105 or no code on a 401/403: the 401 "sign in again" as before.
Both the HTTP status path (askQoder) and the in-stream statusCodeValue
path (decodeQoder) go through it. Event gets a Wait field for a KError,
and relayStatus's fail and serveQoder's first-round failure send it as
Retry-After (retryAfterOn); askQoderWait is askQoder that also returns
the wait, and askQoder (the round searchRounds uses) wraps it. Zed and
Command Code share relayStatus and never set Wait, so they are
unchanged.

Why: a real Qoder trial account had every chat answered
403 {"code":"10605",...} (Qoder's model queue) and was told to sign in
again, which can't help. The plugin was fixed in 0.2.14 for moved users;
this is the same fix for users still signed in through the built-in. The
built-in never marked an account lapsed from a refused chat (only from a
refused refresh, provider/qoder.go), and now a 10605 doesn't even return
the 401: the gateway's busy() reads the 503 as busy (failOther), so a
group asks it again after the pause, no shorter than its Retry-After
(noteBusy/retryAfter), and the agent gets the Retry-After too.

Run:
- New tests in internal/gateway/qoder_busy_test.go, the fixture
  testdata/qoder_queued_10605.json taken byte for byte from plugins #98:
  TestQoderQueuedIsBusy (serveQoder, HTTP 403 and in-stream 403, stream
  and not: 503, Retry-After 30, the busy words, no "sign in", busy() true,
  retryAfter 30s), TestQoderQueueWait, TestQoderErrorCodes. With the old
  401/403 rule put back at the top of qoderFailure all three FAIL
  ("got 401 ... want 503"); with retryAfterOn made a no-op
  TestQoderQueuedIsBusy FAILs on Retry-After "" in both subtests. Restored,
  they pass.
- go test -tags nogui ./internal/provider ok (458s). go test -tags nogui
  -timeout 40m ./internal/gateway (the default 10m ran out under the
  machine's load): every test passed except TestCodexHeardWithinItsIdleTimeout,
  which failed with the body #1800 already describes (Codex got member
  a's server_is_overloaded under load); it passes 10 of 10 alone
  (-count=10) and is on the Codex passthrough path, which this doesn't
  touch. Noted on #1800.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build ok.
- Not run: the rest of go test ./... (only the two packages touched);
  a real 10605 through the built-in (the queue had reopened when the
  plugin shipped); no Qoder parity test exists in
  internal/gateway/plugin_*_test.go to extend.

* gateway: a Claude model a provider writes with a dot (Copilot's claude-opus-5.5, claude-sonnet-5.5, claude-haiku-4.5) is listed to Claude Desktop by its dashed id, so Claude Code knows it (#1819, mdwsk88)

Claude Desktop's Code tab runs Claude Code on the id magpie lists a model
by. claudeLooking lists a Claude model with reasoning levels as
magpie-<n>.anthropic.<model>, which Desktop and Claude Code read as that
Claude model, but claudeModel matched dashed versions only. Copilot writes
a version with a dot, so each of its Claude models fell to
mythos-magpie-<n>, a model Claude Code doesn't know: Opus 5.5 ran at 32000
output tokens and effort high (128000 and medium for the model it knows),
and Haiku 4.5, the haiku tier, was sent output_config.effort, which
Copilot answers with 400 "model claude-haiku-4.5 does not support
reasoning effort".

claudeModel now dashes the version first (provider.ClaudeDashed). A
request is still served by <n> alone (aliased), so Copilot still gets its
own claude-opus-5.5. An id with a suffix (claude-sonnet-4.5-thinking) and
other vendors' ids are listed as before. This is mdwsk88's fix from
mdwsk88/magpie@51a5ad80, reviewed line by line and taken with its tests.

Sibling: ClaudeDashed and ClaudeUndashed knew opus, sonnet, haiku and fable
but not mythos, while desktopClaude, claudeLine and claudeVersion know it.
Claude Code 2.1.296 (read from its binary) matches claude-mythos-5-1 by
substring before claude-mythos-5, so a dotted claude-mythos-5.1 would read
as Mythos 5; it is now dashed like the others, in Claude Code's settings
and in Desktop's list. The other matchers of Claude ids (agent's
claudeName, gateway's claudeFamily, claudeVersion, claudeLine,
provider.sameModel) already take a dot. ClaudeFast's list is dashed but
applies to api.anthropic.com alone, which never writes a dot.

Run (go1.26.8 toolchain, sandbox HOME, private GOCACHE/GOMODCACHE, -tags nogui):
- With the old desktop.go and claudedash.go put back, the new tests fail:
  TestClaudeDesktopEffortIDs "copilot/claude-opus-5.5 listed as
  mythos-magpie-5238445297, want ^magpie-\d{10}\.anthropic\.claude-opus-5-5$"
  (and the opus-4.6, sonnet-5.5, haiku-4.5, dated sonnet-4.5 and
  mythos-5.1 rows), TestClaudeDesktopDottedClaudeReachesItsModel "listed
  as mythos-magpie-9584025798", TestClaudeDashedOnlyClaudeVersions
  "ClaudeDashed("claude-mythos-5.1") = "claude-mythos-5.1"". Green with
  the change.
- go test ./internal/gateway ./internal/provider: ok; -run 'Desktop|Claude'
  over internal/agent too: ok. -race -count=3 -run TestClaudeDesktop
  ./internal/gateway: ok.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.

Not run: a real Copilot account or the real Claude Desktop through this
build (the reporter's own run used a stub upstream and real Claude Code
2.1.295); Windows and WSL; the full go test ./... (machine loaded).

Co-Authored-By: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>

* provider, gui: Add another key on an OpenCode Zen provider says an empty field adds public, the key its free models answer, and adds it (#1795)

An OpenCode Zen provider added with no key asks with public, the key
OpenCode sends signed out (normalize). On a Zen provider that already had
a key of the user's own, Add another key said only "paste an API key", and
with nothing pasted AddKey refused before it knew which provider it was
("paste the key to add"), so there was no way to learn of public or add it
as the anonymous fallback behind the user's own key.

- provider: Provider.AnonymousKey is the key a provider is asked with when
  the user has none (OpenCode Zen's public, by its preset, as normalize
  already decided; "" for every other, Kilo included). AddKey looks the
  provider up first; nothing pasted adds that key, and asked again says
  "<name> already has public, the key its free models answer with none of
  yours" rather than "already has this key". Every other provider still
  wants a key pasted. normalize reads the same method.
- gui: /api/providers names anonKey on a provider that has such a key and
  doesn't have it yet. Its Add another key field reads "paste an API key,
  or leave empty for public: free models only" (title too, where a narrow
  field cuts it short), and the row added is marked as any new key's is.
  zh, zh-TW, ja and de translations.

Verified:
- TestZenAddKeyEmptyIsPublic (provider) fails on the old code with
  "paste the key to add"; TestZenAddAnotherKeyEmptyAddsPublic (gui,
  through /api/keys/add and /api/providers) fails with `Zen with its own
  key offers ""`. Both pass with the change.
- zen-anon-key.test.cjs: 40 pass in chromium and webkit, en/zh/zh-TW/ja/de,
  at 900 and 560px; on the old app.js the placeholder test fails
  ('paste an API key' vs the new hint).
- gui-de, gui-ja, gui-zh-tw, i18n-keys, key-import, provider-many-keys,
  nokey-editor, key-copy: 46 pass.
- Not tried against Zen itself: whether a gateway falling from a spent key
  to public on a paid model rests public is unchanged behavior, the same as
  for public typed by hand.

* agent: a Codex thread started on CC Switch's OpenAI mirror goes through magpie while a magpie model is on, so reopened it isn't refused by ChatGPT for the magpie model picked in it (#1796)

WardLu's old threads say model_provider "custom": CC Switch's mirror of
the official OpenAI provider ([model_providers.custom], name "OpenAI",
requires_openai_auth, no base_url). magpie takes Codex onto a magpie
model by openai_base_url, which Codex applies to its built-in "openai"
provider only. A thread resumed on "custom" therefore went straight to
chatgpt.com with the magpie model picked in it, and ChatGPT answered
"The 'group/intent-auto' model is not supported when using Codex with a
ChatGPT account"; magpie's log never saw it.

While Codex goes to magpie by the base URL, takeMirrors now gives each
such mirror magpie's ChatGPT backend (codexURL) as its base_url, as
failover already does for a mirror that is Codex's current provider,
and records the ids in the stash (codex.mirrors). giveMirrors takes the
base URL off again when Codex steps off magpie (one of its own models,
reset, Disconnect), leaving one changed since as it is. A mirror a
profile names is the user's and is left alone. isCCSwitchMirror still
counts a taken mirror as a mirror, so its models stay grouped under
OpenAI and ccSwitchTables doesn't treat it as a relay.

No detection or guide was added: with the requests reaching magpie the
old threads keep their history and model. Moving them onto another
provider is already the Sessions page's Move (#887), which rewrites
every rollout of the thread (resumed _segment files too) and the state
DB row.

Run:
- go test -tags nogui ./internal/agent -run 'CCSwitch|Mirror|Codex':
  ok. TestCodexTakesCCSwitchMirrorForItsThreads fails on the code
  before this commit ("the mirror isn't through magpie").
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
  the push.

Not tried: a real Codex resuming a "custom" thread against a real
ChatGPT account. The same base_url on a requires_openai_auth mirror is
what mirror failover (#504) has written since it shipped.

* gateway, gui: Stays: Strict keeps a conversation on the account or key that answered it, even past its cap, and passes its error on rather than moving it (#1797)

miniers asked that a conversation never move to another account: a
move changes the account a vendor sees mid-conversation and loses its
prompt cache. Session affinity keeps the account while it can answer,
then moves on.

The new affinity mode "strict" (Stays: Strict) does what session does
for a new conversation. Once one has an account, strictKeep asks that
account alone (its other models too) and no other account, key or
provider:
- one resting or spent is still asked, and its error (429, 402, 5xx)
  goes to the agent rather than to the next candidate;
- one over a user cap is asked past it (plan's capped candidates,
  capHeldOnly);
- one held for credits answers 429 naming Stays: Strict rather than
  moving;
- one removed, turned off, barred or not allowed for the key counts as
  gone, and the conversation is routed as usual.
A last try that fails verification is not rested for a strict
conversation that had nowhere else to go.

Set in the provider editor and the Routing page's pool row (GUI, all
five languages), `magpie groups ... stays=strict` (strict-session,
never-move), and the TUI ("stays strictly"). Documented in
gateway-routing.md, reference.md and the site's start pages (en, zh,
ja).

Run:
- go test -tags nogui ./internal/gateway (-timeout 30m under load ~150),
  ./internal/provider ./internal/tui ./internal/cli: ok. The three
  TestStrictAffinity* tests fail on the code before this commit (200
  where 429 was expected, acct-2 answering).
- GUI: stays-strict.test.cjs, chromium and webkit, 900 and 560px, en,
  zh, zh-TW, ja, de: 30 of 30. On the assets before this commit it
  fails 15 of 15 in chromium. routing-*.test.cjs pass but for
  routing-steady's webkit 1.69px shift, which fails on the old assets
  too: filed as #1804.
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
  the push.

Not tried: a real agent conversation held on a real rate-limited
account.

Known and left: planLevel doesn't merge a nested group's sub.held, as
before this commit.

* agent, codexcat: the effort new sessions are set to lasts a switch of model in Codex, Claude Code and Grok Build, at the model's nearest level where it lacks it (Creat.wu on Discord)

Creat.wu set magpie's "New sessions" effort to the highest level. A new
session started at it, but picking another model (a routing group) dropped
the effort back to the model's default.

Codex: on a switch, the TUI's /model highlights and saves the picked model's
preset default_reasoning_effort. The desktop app keeps the current effort only
if the new model lists it, and otherwise uses defaultReasoningEffort. Both come
from magpie's catalog default_reasoning_level, which codexcat.DefaultEffort
always set to the middle level. A group's levels are the intersection of its
members' levels, so a group often lacks xhigh or max.
- The catalog default is now codexcat.ModelDefault: the model_reasoning_effort
  set in config.toml when the model takes it. Otherwise it is the model's
  nearest level (catalog.NearestEffort: by rank, a tie going up, never
  "none"), so xhigh on low/high/max gives max. When the effort is left at
  Default, the default is still the middle of the road.
- This covers both magpie-models.json and the list the gateway hands a
  signed-in Codex. The effort is now part of that list's tag, so Codex asks
  for the list again.
- Setting the effort in magpie rewrites the list, or marks Codex's cached
  list stale.
- An effort the model picked in magpie doesn't take now settles on the
  nearest level, not the middle.
- The gateway's fitEffort uses the same NearestEffort.

Claude Code: Opus 5.5 and later read only
modelSettings.<model>.effortLevel. A level set while on one of them was
written only there, so a routing group or another vendor's model picked
afterwards (which reads the top effortLevel) started at its own default.
- The top effortLevel is now written too.
- A reset takes the top one out only when it is the level written beside
  the model's own; a top level the user set themselves stays.
- max was already written to the env and applied to every model.

Grok Build: picking a model without the chosen default_reasoning_effort
deleted the key. It now keeps the model's nearest level.

Checked and not affected:
- WorkBuddy, ZCode, Kimi and MiniMax keep per-model levels (keptEffort).
- Qoder and Command Code keep one level for each model by their own design.
- AtomCode keeps one model table each.

What was run:
- Real codex 0.162.1, `codex debug models` with CODEX_HOME in the
  scratchpad, on a catalog from CatalogAt(..., "xhigh"). It renders
  default_reasoning_level max for low/high/max, high for a low/medium/high
  group and xhigh for a model that has xhigh.
- New tests TestCodex/Grok/ClaudeNewSessionEffortLastsModelSwitch,
  TestNearestEffort and TestModelDefault. The three agent tests, plus the
  updated TestCodexCustomProviderModelHasEfforts and
  TestClaudeEffortModelSettings, fail on the old code: the source files were
  checked out from the parent with the tests kept.
- gofmt -l is clean. go vet -tags nogui ./internal/... passes for GOOS
  darwin, linux and windows.
- go test -tags nogui: internal/agent, catalog, codexcat and provider pass in
  full before the rebase.
- In gateway, only TestOTelWaterfallIncludesUnbilledFallback failed. The
  root span was in a second export, which is #1794, fixed on main by
  6ae6b3402.
- After rebasing on origin/main, catalog and codexcat pass in full. gateway
  -run 'Effort|OTel|Reasoning' and agent -run 'Effort|Codex|Claude|Grok'
  pass.

Not tried: the Codex desktop app's picker by hand. Its behaviour was read
from ChatGPT.app's app.asar.

* gateway, gui, settings: an IP / CIDR allow list for the gateway, from MAGPIE_ALLOW_IPS or Settings beside Share on local network (lc on Discord)

What changed: lc runs magpie in Docker on a public host and asked that
only some addresses reach it at all. With a list set, a request from an
address outside it is refused 403 ("magpie answers only the addresses on
its allow list ..., and this request came from <addr>: add it there to
let it in") before its gateway key is looked at, so a leaked key is no use from
elsewhere. No list is as before.
- internal/settings/allowips.go: SplitAllowIPs, ParseAllowIP (an IP or a
  CIDR range, v4 or v6; zones dropped, v4-mapped unmapped), CleanAllowIPs.
  Settings gets AllowIPs (allowIPs).
- internal/gateway/allow.go: MAGPIE_ALLOW_IPS (comma or space separated)
  sets the list in place of Settings'. The address judged is the
  connection's own (r.RemoteAddr); X-Forwarded-For and the rest are never
  believed (magpie has no trusted-proxy list; MAGPIE_TRUST_PROXY never
  reads forwarding headers, and this follows it). Loopback and this
  computer's own interface addresses always pass. An entry that doesn't
  read lets nothing in and is logged once, so a typo never opens magpie
  to every address. lanGuard checks it after the OAuth callback and
  before the rebound-Host and key checks; `magpie web` is wrapped with
  AllowGuard too.
- GUI: Settings > Network shows an "Allowed addresses" row under Share on local
  network when sharing is on, the page is open from another computer, or
  the env var is set (then read-only, saying so). POST
  /api/settings/allowips saves it, refuses it while the env var is set,
  refuses an entry that doesn't read, and refuses a list that would shut
  out the address the page itself is open from (KeepsOut). The generic
  settings save keeps AllowIPs. Strings in zh, zh-TW, ja and de.
- Docs: the Docker page (en, zh, ja) lists MAGPIE_ALLOW_IPS with a note
  that a request from the host itself arrives from the bridge's gateway
  (172.17.0.1), that Docker Desktop and rootless Docker show clients as
  one address of their own, and that behind a proxy every request comes
  from the proxy; docs/reference.md and docs/subsystems/gateway-routing.md
  describe it. The READMEs list no env vars, so they are unchanged.

Why: a gateway key is the only lock on a public host; an allow list keeps
everyone else from even trying it.

Run (machine load average 75-140 from other sessions, so the large
packages ran in slices of their top-level tests, each slice
-timeout 9m, private GOCACHE, sandbox HOME):
- New tests: internal/gateway/allow_test.go TestAllowList (allowed,
  denied, CIDR v4/v6, IPv6 literal, link-local with zone, v4-mapped,
  loopback and own address always in, on the list still needs a key,
  a typo shuts everything out, env over settings), TestAllowListServed
  (a real connection from loopback passes lanGuard under a list naming
  nothing of this computer's; a request from elsewhere is 403 naming its
  address and MAGPIE_ALLOW_IPS), TestKeepsOut; internal/settings/allowips_test.go
  TestCleanAllowIPs; internal/gui/allowips_settings_test.go
  TestAllowIPsSetting; internal/gui/tests/allow-ips.test.cjs (14/14 in
  chromium and webkit, at a 390px panel, en and zh, keys in zh, zh-TW,
  ja and de). Broken by
  hand: with lanGuard's check removed TestAllowList and TestAllowListServed
  FAIL; with KeepsOut skipped TestAllowIPsSetting FAILs; with renderAllow
  not called the GUI test has 5 failures. Restored, all pass.
- internal/gui/settings_keep_test.go gains AllowIPs:
  TestSettingsSaveKeepsWhatItDoesNotSend failed without it, as it should
  for a new field.
- go test -tags nogui: every package ok. internal/gateway (4 slices),
  internal/agent (4), internal/provider (3), internal/gui (2),
  internal/plugin (2), the rest whole. GUI Network-settings test files
  (11) 98/98 and i18n-keys ok, both engines.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; linux and windows builds ok.
- Not tried: a real Docker container on a public host (the bridge note
  is from Docker's docs, not checked here); behind a real reverse proxy.

* provider, agent: a context window the user typed on a routing group or a provider is the one Codex and Claude Code run to, not magpie's default 272K (#1809)

A DeepSeek V4.1 Flash routing group set to 500K reached the catalog as
Context 500000, but magpie's default working window (settings.Working,
272K, #876) cut it: Codex's magpie-models.json said context_window
272000, max_context_window 500000, and Codex runs to 95% of
context_window, the ~258K in the report. Claude Code showed 500K
(CLAUDE_CODE_MAX_CONTEXT_TOKENS) while magpie also wrote
CLAUDE_CODE_AUTO_COMPACT_WINDOW=272000, so it compacted at 272K too and
only displayed the larger number.

From Codex's source (openai/codex @0c7362d, codex-cli 0.162.1):
config.toml's model_context_window sets context_window to
min(value, max_context_window); usable = context_window x
effective_context_window_percent (95 by default); the auto-compact
limit is min(model_auto_compact_token_limit, 90% of context_window).
magpie writes neither config key and still doesn't, so a user's own
model_context_window keeps working as before.

magpie's default compaction now gives way to a window the user typed,
as it already gives way to Claude Code's own autoCompactWindow
(602d4ec6):
- provider: Entry.WindowSet marks a window typed on the provider for
  the model or all its models (ContextOf) or on the group (a size).
  CompactFor answers the threshold Codex is told: a per-model or
  provider Compact at first (CompactSet), else that whole typed window
  when no size is typed in Settings, else 0 (the default). Used by the
  gateway's Codex list (codexListed) and WindowTyped for Claude Code.
- agent: magpie-models.json (and the WSL twin) take CompactFor, so the
  group says context_window 500000 with no max; Claude Code gets no
  AUTO_COMPACT_WINDOW on a typed window unless Compact at is typed in
  Settings.
- A model nobody typed a window for keeps 272K, and a Compact at size
  typed in Settings still comes before a typed window.
- gui: unchanged. f36e744c3 shortened Settings > Long conversations to
  one line upstream; it no longer spells out precedence.

Run:
- internal/agent TestTypedWindowReachesCodexAndClaudeCode: group 500K,
  provider per-model 400K, an untyped 1M model, then Compact at 300K;
  checks magpie-models.json, the gateway's Codex list and Claude Code's
  env. On the old code it fails 6 ways (272000/500000 and 272000/400000
  on disk, list Compact 0, Claude compact 272000), checked by reverting
  the non-test files.
- Sandbox HOME with the built binary and real codex 0.162.1
  (`codex debug models`): old binary group/ds-flash 272000 / max
  500000; new 500000, no max. A per-model `context` override of 1m:
  old 272000 / 1000000, new 1000000. `magpie model compact 300k`:
  300000 with the typed window as max. Claude Code in the sandbox: old
  wrote AUTO_COMPACT_WINDOW=272000 + MAX_CONTEXT_TOKENS=500000, new
  only MAX_CONTEXT_TOKENS=500000.
- gofmt -l, go vet (darwin, GOOS=linux -tags nogui, GOOS=windows), the
  three builds, go test -tags nogui ./...: 45 packages ok. At load
  average ~115 agent, gateway, library and provider hit the 10m
  timeout with no failure. Rerun with -timeout 40m, agent, library and
  provider pass. gateway failed three timing tests that pass 3 of 3
  alone: TestOTelWaterfallIncludesUnbilledFallback (#1794, already
  fixed on origin/main by 6ae6b3402), TestCodexHeardWithinItsIdleTimeout
  (#1800, open) and TestIntentClassifierFails (filed as #1829).

Not tried: a real `codex exec` turn against a sandbox gateway (the
catalog Codex reads was checked with `codex debug models` instead), and
Windows itself; the path is the same Go code on every OS.

* plugin, provider, gateway, upstream: a test whose check fails while its fake vendor holds a reply ends with a FAIL, not a package hung until -timeout (#1808)

TestNPMInfoDeadline's fake npm held slow-one's reply on <-release, closed only
on the happy path. A check firing first under load (on the issue's machine,
the quick ones missing at npmAll = 300ms) left the handler held, and
httptest.Server.Close, run in the test's cleanup, waited for it forever:
the whole internal/plugin package hung to -timeout and lost every result.

- TestNPMInfoDeadline: a t.Cleanup registered after fakeNPM (so it runs
  before the fake's Close) lets the handler go once (sync.OnceFunc). Its
  timing assumptions, all listed: the 2s wall-clock bound on Info is gone
  (slow-one is held and npmEach is an hour, so Info coming back at all is
  npmAll at work; a minute only turns a wait into a FAIL); npmAll is 5s,
  the quick ones' time to answer on a loaded machine, not 300ms; the slow
  one's kept answer is polled for 30s, not 3s.
- The same pattern in its siblings, each fake handler blocked on a channel
  only the happy path closed, now let go by a cleanup/defer that runs
  before the server's Close: TestRestartFinishesTheReply (plugin),
  TestPastedAddressAndCallbackFinishOnce, TestPartnersFetchedLastIsHeld
  (provider), TestBusy (before gw.Close too, whose request waits on it),
  TestLaneReleasedOnFailure (gateway), TestReadOnceInFresh (upstream; its
  100ms bound on Of goes the same way as the 2s one: the page is held, so
  Of coming back is its not waiting, 10s being short of the read's 15s).
- Audited, already right: grok_accounts, quota_refresh_order,
  quota_history_waiter, subscription_usage, sub2api_usage, qoder, routing,
  github_test, session_route, request_encoding, key_limits, vertex (quit),
  plugin_usage (r.Context).

Run, in a sandbox HOME with pinned caches:
- Old TestNPMInfoDeadline with its check forced (took > 0): "httptest.Server
  blocked in Close", panic at -timeout 30s. With a 500ms delay injected into
  the fake's answers (a loaded machine): FAIL at the quick-ones check, then
  the same hang. New test: with the delay injected, PASS (5.55s); with the
  check forced, FAIL in 5.5s and the package's other tests run; with
  npmAll an hour (the deadline broken), "Info waited for the slow package"
  and the package ends.
- Each sibling with t.Fatal injected while its handler is held: old code,
  all five httptest siblings hang to -timeout 90s ("blocked in Close"),
  upstream's stalls ~56s; new code, each ends at once with FAIL.
- go test -race -count=5 of every touched test: pass.
- gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean, before and after rebasing onto
  a3f2097ed. go test -tags nogui ./... (darwin): all 49 packages ok before
  the rebase; after it, all ok but internal/proc's
  TestFindToolKeepsWrapperWhenMiseDoesntSay/hangs ("mise wasn't asked",
  a 300ms miseWait under load; passes 20 of 20 alone), filed as #1838.
Not run: the Windows box, Linux tests.

* gateway, gui: a web search made in place of the picked searcher says in its Routing row which searcher failed or found nothing, and why (Gearclickist on Discord)

Gearclickist picked Grok as the web-search model (代搜). In Codex, a
web_search did go to Grok, but Codex's default search model then searched,
and nothing said why. modelSearch asks the searcher picked in Settings
first. When it errors, or its reply names no page it found, the next of
Searchers() searches in its place (#669, up to three). The first error was
dropped, so the Routing row only showed the model that answered.

Falling back stays. searchingInstead now puts on the search's CallFor the
searcher asked first (instead), whether the user picked it (picked), and
its error (why) or that it found nothing (nothingFound, from a new
errFoundNothing that searchWith and kimiSearch wrap). Routing's kindWhy
says "<grok>, the searcher picked in Settings › Models › Web search,
didn't search for Codex's <model>: <why>. So magpie had <next>, the next
searcher it can use, search in its place." There are 7 new strings, in
zh, zh-TW, ja and de.

Grok itself: magpie's exact search body was sent to real Grok (4 models,
6 queries) through the built-in, and replayed through the plugin. Every
time it answered with pages, so no Grok or plugin cause was found, and
there is no plugin publish or mover min raise. The next time Grok fails
for Gearclickist, the row now names the error.

Run:
- go test ./internal/gateway ./internal/agent -count=1 under a sandbox
  HOME: ok (933s, 720s).
- TestSearchInPlaceOfPickedSaysWhy (found nothing, failed) passes. With
  the searchingInstead call taken out by hand, both subtests go red.
- search-instead.test.cjs: chromium and webkit, en/zh/zh-TW/ja/de, at
  1100 and 520px: 10/10 pass. With kindWhy's new branch turned off by
  hand: red.
- search-mcp, routing-side-calls, provider-search and routing-kind GUI
  tests pass.
- go vet on darwin, GOOS=linux -tags nogui, and GOOS=windows; gofmt -l
  is clean.

Not verified: a real Grok search failing for Gearclickist's account,
since it couldn't be reproduced.

* gateway: Codex's spawn_agent names every model a subagent may be put on, not only the first five (Gearclickist on Discord)

Gearclickist turned on "Codex subagents on any model", but when Codex
dispatched subagents only a few models could be picked. Codex itself caps
the list: spawn_agent's description names only the first five
show_in_picker models of its catalog (codex-rs child_config.rs
MAX_SPAWN_AGENT_MODEL_OVERRIDES, multi_agents_spec.rs
spawn_agent_models_description), Codex's own ahead of magpie's. Yet it
takes any catalog model by name (find_spawn_agent_model_name). So the lead
saw none of magpie's models.

spawnAgentModels (codex_spawn_models.go) adds the rest of the catalog
Codex was handed after Codex's own list, under a line of its own, at most
200. It covers spawn_agent at the top level and in Codex's multi_agent_v1
namespace, at CodexPath (codexBackend) and at /v1/responses for Codex
(handle).
- At CodexPath the list is Codex's own listed models less those hidden on
  the Agents page, then CodexListed unless Codex is held to its own.
- At /v1 it is CodexCatalog under the key's allowance.
- A lead the ChatGPT backend answers in multi-agent V2 seals its
  subagents' tasks for a ChatGPT account (#619), so it is offered Codex's
  own only.
Only the tool's description changes, never base_instructions. With V1 on,
it does change in requests to the ChatGPT backend too.

Not covered: the model_catalog_in_context feature (under development, off
by default) puts a five-model catalog in context, and it is not widened.

Run:
- go test ./internal/gateway ./internal/agent -count=1 under a sandbox
  HOME: ok.
- TestSpawnAgentNamesEveryModel uses 40 models on a real Codex 0.162.0
  request (testdata/workdir/codex-0.162.0.json). Its 4 subtests are
  CodexPath, /v1, a sealed V2 lead and a V1 lead, and all pass.
  - With spawnAgentModels returning body by hand: CodexPath, /v1 and V1
    go red.
  - With the sealed rule taken out: V2 goes red.
- go vet on darwin, GOOS=linux -tags nogui, and GOOS=windows; gofmt -l
  is clean.

Not verified: a real Codex lead picking one of magpie's models past the
fifth from the longer list.

* gui: the Library's Backups button is at the top of every tab, after Library folder (Dade on Discord)

Dade: each Library tab's 备份 (Backups) sat at the very foot of the page,
under the whole list, and was hard to find. It is now a button in the
Library's head strip, on every tab (Instructions, MCP servers, Skills,
RTK). That strip stays at the top as the page scrolls. The button sits
right after 资源库文件夹 (Library folder) and looks the same: a small
glyph (a clock with a turning arrow, as macOS draws backups) and a label.
- It opens magpie's backups folder.
- Its tooltip keeps the sentence the foot had ("magpie keeps a copy of
  every file before it writes it.") with the folder's path.
- It is disabled until the library has loaded, as Library folder is.
The foot line and its .lib-foot/.lib-link styles are removed. Two
messages that pointed to "Backups, at the foot of the Library" now say
"at the top", in all five languages. The page with no agents, which had
no foot, now has Backups too.

Run:
- library-backups-top.test.cjs covers chromium and webkit,
  en/zh/zh-TW/ja/de, each of the four tabs, and browser 1000/420px plus
  window 1000/800/560px. It checks the button comes right after Library
  folder on the same line and looks the same, waits for the library, has
  a label that doesn't wrap, has no left border, causes no sideways
  scroll and nothing at the foot, opens the backups folder, and doesn't
  move the page on click. 10/10 pass. Without the button appended, red.
- library-loading, library-discover-jump, library-all, library-items,
  library-rtk-gain and library-own-folder pass (138).
- go test ./internal/gui -count=1 under a sandbox HOME: ok.
- mobile-web.test.cjs: the phone widths pass. Its desktop 900/1280
  comparison with origin/main fails only on the library page (about 650
  pixels: the new button in the strip). Its before/after screenshots show
  nothing else changed, and it matches again once this is on main.

* gateway: the models added to Codex's spawn_agent are headed neutrally, naming neither magpie nor Codex's limit (Gearclickist on Discord)

5d33f060b added the rest of the catalog to spawn_agent's description
under "More models that may be set as `model` (Codex names only five
above; magpie serves these too):". That text goes upstream with the
prompt, to OpenAI too when the lead is a ChatGPT account, and the
project keeps Codex's prompts and identity unrewritten (ban risk). The
header is now "More models that may be set as `model`:". The check that
a description already has it (spawnMore) is unchanged, so a request is
still widened once.

TestSpawnAgentNamesEveryModel now fails when the added text names
magpie, Codex or "five".

Run: TestSpawnAgentNamesEveryModel (4 subtests) and the gateway's Codex
tests pass. With the old header restored by hand, the three subtests
that add models fail ("the added text names \"magpie\""); V2 adds
nothing and passes. gofmt -l clean; go vet ./internal/gateway on
darwin, linux (-tags nogui) and windows.
Not run: the full gateway package, a real Codex lead.

* gui: the Usage page's session-stats memo keeps the 8 most recently asked ?days ranges, not one per number a request sends

statsFor keeps a whole sessions.Stats per distinct ?days= value, and
only forgetStats ever emptied the map. Each new number a caller sent
added a snapshot that stayed until a session was deleted, restored or
purged. Now the memo keeps the 8 most recently used ranges.

Run before this commit (Linux, WSL2 Ubuntu 24.04, official go1.26.8):
the new test fails with the fix reverted and passes with it;
go test -tags nogui ./internal/gui ./internal/plugin is ok. Both
builds were compared with magpie web on a sandbox copy of a real
~/.codex/sessions: all 10 stats/overview answers byte-identical, and
300 distinct ?days values left HEAD's memory up 21-25 MB against 6 MB
for this change.

macOS was not run here; CI's macOS job runs the new test.

Reviewed for magpie (CaramelizedCUDA/magpie pr/stats-memo-cap at 05f0afa4, cherry-picked onto f340aecab, then rebased onto 6ccf23efa and run again there): on macOS, go1.26.8, sandbox HOME, TestStatsMemoKeepsAFewDays fails with the cap turned off ("the memo holds 64, want at most 8") and passes with it. The next commits add a test for which range goes and stamp by ask count.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* plugin: the host keeps reading a plugin's stderr after a line over 4 MiB, so the plugin host no longer hangs (Windows) or keeps the unread output in memory (Linux)

The host logged the plugin child's stderr with a bufio.Scanner capped
at 4 MiB. On the first longer line Scan stopped with ErrTooLong, the
goroutine returned, and nothing read the pipe again. host.js sends
console.log and process.stdout.write to stderr, so one long line from
any plugin was enough. Now the reader drains the pipe past an
overlong line and logs what it can, so the output stops being
dropped silently.

Measured on Bun 1.4.2 (Windows and Linux, official binaries, sha256
checked): on Windows the plugin host stopped answering init when a
plugin wrote one long line while loading; on Linux a script writing
200 MiB to stderr with no reader went from 18 MiB to 412 MiB RSS.
Each of those reproduced at HEAD and is gone with this change; the
Linux memory number comes from that Bun-only measurement, since
magpie's own RSS did not differ at this scale.

Run before this commit: go test -tags nogui ./internal/gui
./internal/plugin is ok on Linux (WSL2 Ubuntu 24.04, go1.26.8) both on
HEAD and on this change. On Windows, go test -tags nogui ./... (49
packages): every failing test also fails at 6c1c0a74 and is listed in
#1827; the plugin package's TestLoadConcurrentWithSavesAndEdits fails
at HEAD too.

macOS was not run here; CI's macOS job has no Bun setup step, so the
end-to-end test skips there if bun is not on PATH. The unit test runs
either way.

Reviewed for magpie (CaramelizedCUDA/magpie pr/plugin-stderr-drain at 56120240, cherry-picked onto f340aecab, then rebased onto 6ccf23efa and run again there): with drainStderr's io.Copy removed, TestDrainStderrKeepsTheChildGoing fails on macOS ("the child is still blocked writing stderr after a line over 4 MiB"). On the Windows 11 box (windows/amd64 test binary, Bun 1.4.2 official zip, sha256 checked, USERPROFILE/APPDATA in a scratch folder) both tests fail without it, TestHostStartsPastAnOverlongStderrLine with "starting plugins: context deadline exceeded" after 62s, and both pass with it (0.02s, 1.99s). go test -tags nogui ./internal/gui ./internal/plugin is ok on macOS.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* ci: Bun on every test runner, and the plugin stderr tests on Windows

The end-to-end plugin test needs bun on PATH, and setup-bun only ran on
Linux, so macOS skipped it (run 38250283461: "no bun on PATH"). Windows
skips the Test step, so the stderr tests were only compiled there. Both
now run: setup-bun on all three runners, and a Windows step that runs
the two stderr tests with -v, so a skip shows in the log.

Run before this commit: the change is CI-only and is checked by the
workflow run on this branch.

Reviewed for magpie: the workflow change only drops setup-bun's Linux-only condition (same pinned oven-sh/setup-bun@v2, bun 1.4.2) and adds one Windows step running the two tests; no new trigger, permission, secret or action. The contributor's run 38263044397 shows both tests passing on windows-latest with bun 1.4.2, and macOS green with bun installed.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* gui: the session-stats memo lets go of the range asked least recently, counted by asks rather than the clock (review of CaramelizedCUDA's cap, #1827)

9f0c9593 caps the memo at 8 ranges and stamps each with time.Now() when
asked. Its test only checked the count and that the newest range stays,
which passes with the eviction reversed (k.used.After) or with a hit that
doesn't restamp. TestStatsMemoKeepsTheRangeAskedAgain fills the memo, asks
range 1 again, adds one more and checks 1 is kept and 2 let go.

The stamp is now the memo's ask count: Windows' clock can read the same
for two asks in a row, so with time stamps the range asked again could
tie with one asked once and either could go.

Run (macOS, go1.26.8, sandbox HOME, private caches):
- reversed comparison (> for <): the new test fails, "the range asked
  again was let go before one asked once"; a hit that doesn't restamp:
  the same failure. Both pass with the change.
- go test -tags nogui -count=1 ./internal/gui ./internal/plugin: ok.
- gofmt -l clean; go vet on both packages for darwin, linux (nogui) and
  windows/amd64; go build for darwin, linux nogui and windows.
Not run: the whole suite (machine loaded), the new test on Windows.

* gateway, settings: an unreadable settings.json keeps the allow list read last, or lets in only this computer, never every address

Follow-up to 7a9490638. AllowIPs read settings.Load().AllowIPs, and Load
returns the defaults when settings.json can't be read or doesn't parse with
no good backup, so for those requests the allow list read as empty and
every address was let in (fail-open). A failed read is unknown, never
empty (LESSONS.md).

- settings: LoadChecked() returns Load's settings and an error when the
  file is there but can't be read, or doesn't parse with no last good
  generation, the same cases Save already refuses. No file, or an empty
  one, is not an error. Load is unchanged and now goes through the same
  reader.
- gateway: the Settings list is read with LoadChecked. On an unknown read
  the list read last in this process stays in force; with none read yet,
  only loopback and this computer's own addresses pass, and the 403 says
  settings.json in <dir> couldn't be read. Logged once until a read
  succeeds. MAGPIE_ALLOW_IPS is unaffected. AllowIPs returns the list in
  force (the last one read on an unknown read).
- gui: POST /api/settings and POST /api/settings/allowips read with
  LoadChecked and refuse on an unknown read. settings.Save already
  refused to write over such a file, so this didn't write an empty list
  before either; the handlers now refuse before building on defaults.
- docs: reference.md and gateway-routing.md say so.

Run (darwin, sandbox HOME/XDG via the tests' own setup, private GOCACHE):
- gofmt -l on the changed packages: empty.
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: clean.
- go test -count=1 ./internal/settings ./internal/gui ./internal/gateway: ok.
- Broken by hand: allowList reading settings.Load() with no error makes
  TestAllowListUnreadableSettings fail (garbled after a read: 203.0.113.9
  got 200, want 403; never read: remote got 200, want 403 saying
  settings.json). LoadChecked never erroring on a parse failure makes
  TestLoadChecked fail ("garbled with no backup read as good") and the
  gateway test fail at its precondition.
- TestAllowIPsUnreadableSettingsNotSavedOver passes on the old GUI code
  too (Save refused already); it guards that path.

Not run: the Windows box, Linux tests, the GUI Playwright suite (no
assets changed), the full go test ./... . Not covered: an empty
settings.json with no .bak still reads as no list, matching Save, so a
file truncated to zero bytes before any second save opens a freshly
started magpie.

* plugin, cli: on Windows, a plugin added from a folder is found by its short name too (magpie plugin off/on/rm/options zz-tags) (#1827)

ShortName cut a plugin's name at its last "/". A plugin added from a
folder is named by its path, and on Windows that path has only
backslashes, so its short name was the whole path: `magpie plugin off
zz-tags` said there was no plugin "zz-tags", and so did on, rm, options
and plugin.SetOptions. It now cuts at the last "/" or "\". npm names
have no backslash, so they are unchanged.

TestPluginOnOffRmShortName was one of the 26 Windows failures listed in
#1827 (CaramelizedCUDA). TestSetOptionsShortName now also checks a
Windows path, so the case fails on every OS without the fix.

Run:
- without the fix, macOS: TestSetOptionsShortName fails, ShortName
  ("C:\\Users\\me\\plugins\\middleware-zz-tags") = the whole path, want
  "zz-tags"; with it, passes.
- Windows 11 box (windows/amd64 test binaries, sandbox USERPROFILE and
  APPDATA): at 9dd5917a4 TestPluginOnOffRmShortName fails "off by short
  name: err no plugin \"zz-tags\""; with the fix it and
  TestSetOptionsShortName pass.
- macOS: go test -tags nogui ./internal/cli ./internal/plugin ok; gofmt
  clean; go vet on both packages for darwin, linux (nogui), windows.

* provider: a provider saved with Select none serves no models, unlisted or not (#1818)

Select none saved `models: []`, which omitempty wrote as no models key at
all, so the provider read back as "no picks" and served the first 24 of
the vendor's list on /v1/models, in auto groups and on the card, while
the editor said none would be served.

What changed:
- Provider.NoModels (json noModels) records the choice; ServesNone() is
  NoModels with no picks. A file with no models key still serves the
  vendor's list as before.
- Exposed() is empty for it, so the catalog, /v1/models and auto groups
  leave it out; resolveIn refuses an explicit pid/model to it; listedBy
  and Deciders skip it (a decide-only provider is still a decider).
- SetModels and normalize clear NoModels once there are picks.
- GUI: the editor sends noModels on Save, an edit that omits it keeps it,
  the card's exposed count is 0, the hint says nothing is served; with
  unlisted the dashed chips explain they are only for groups. Strings in
  en, zh, zh-TW, ja, de.
- CLI: `magpie provider models <id> none`.
- docs/subsystems/providers-accounts.md describes it.

Decision (owner delegated): Select none means none, whether or not
unlisted is on; unlisted keeps meaning "hide from the list, still
usable by groups that name it".

Run:
- go test ./internal/provider ./internal/gui ./internal/cli -count=1
  (green; second pass ran too) with private GOCACHE and sandbox HOME.
- Broke Exposed's ServesNone check: TestSelectNoneServesNone red
  ("exposed 24"); broke resolveIn's: red ("watched/m0 resolved"); broke
  the GUI keep line: TestProviderSaveSelectNone red ("exposed 24").
- GUI tests chromium + webkit, 5 languages: provider-none-picked 20/20,
  provider-draft-picks 10/10 (red with noneChosen broken), plus 12
  related model/group/editor tests green.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows clean for the
  three packages.

Not run: the gateway package; Codex native model narrowing is unchanged.
searcher-pick.test.cjs fails 3 webkit cases (hover timeout) identically
on the unmodified base 556c01c80, unrelated.

* provider: a Volcengine or Tencent access key is kept through sync, restore, a stale editor and a copy, and a plan card without one says what to give (#1821, Edward4226)

The reporter's Volcengine Agent Plan card vanished: providers.json had
lost accessKeyID/secretAccessKey, and volcPlanQuotas skipped a provider
without them before building any card, so nothing said why.

Writers that dropped the access key, fixed at the cause:
- Sync and restore (Mirror, Restore, davsync take) kept this machine's
  access key and balance token only when the incoming provider had no
  key at all. A magpie before v0.1.1142 (aa82288f), or one the access
  key was never given on, sends the same key with no access key, and
  that replaced it here and on the server. KeepSecrets now keeps them
  when the incoming has the same key and none of its own; another key is
  another account and still brings its own (TestBackupBalanceToken
  unchanged). A keyless copy also keeps this machine's secret headers,
  which withoutKeys strips and nothing put back. The secret-name regex
  moves to provider.SecretHeader; backup.Secret delegates to it.
- The GUI save kept the access key ID only when the field was left out;
  the editor always sends it, so an editor opened before the key was
  given saved "" over it (the Secret was kept). Blank now keeps it; only
  clearAccessKey drops it.
- AddCopy skipped the Secret when the copy's form sent the source's ID.
- read() and validProviders didn't strip a UTF-8 BOM (lastgood.JSON
  does): a BOM'd providers.json fell back to its .bak, an older
  generation.
Import's replace mode replaces providers on purpose and is unchanged.

The Usage page: a plan endpoint (Volcengine Coding/Agent Plan, Tencent
Token Plan Enterprise) whose providers have no access key is a card
with no windows, an error naming AccessKey ID and Secret (SecretId and
SecretKey for Tencent), needsAccessKey, and an "Open settings" button to
the provider's editor; one card per plan, none when another provider on
the plan has the key. Strings in en, zh, zh-TW, ja, de.

Run:
- go test ./internal/provider ./internal/davsync ./internal/backup
  ./internal/gui -count=1, twice, green (private GOCACHE, sandbox HOME).
- Broke each by hand and saw red: KeepSecrets same-key keep
  (TestSyncKeepsAccessKey, TestTakeKeepsAccessKey), header keep, BOM
  strip (TestProvidersFileWithBOM), GUI blank-ID keep
  (TestProviderSaveKeepsVolcengineSecret), AddCopy
  (TestAddCopyKeepsAccessKeySecret), the Volcengine missing card
  (TestPlanCardWithoutAccessKey).
- GUI: usage-access-key-card 20/20 (chromium + webkit, 5 languages, 900
  and 420px; red with the button removed and with the ja string
  changed); i18n-keys, volc-access-key, tencent-access-key,
  tencent-cloud, quota-balance-error, usage-card-refresh,
  usage-remote-cards green.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows clean for
  provider, davsync, backup, gui, cli.

Not verified: which writer dropped the reporter's key is inferred from
their 10-10 to 10-11 snapshots, not reproduced on their machine (most
likely sync from another computer). Not tried against real Volcengine or
Tencent accounts. The tray panel shows the error text with no button.

* agent, provider: tests no longer read the machine's /Applications or Program Files, so a Mac with DeepSeek Harness.app installed keeps TestAsideOfflineDisconnectRestoresWithoutDaemon green (#1823)

What: every place magpie looks for installed apps outside the home folder
now goes through proc.SystemDirs, which in a test binary testenv isolated
puts the path under the test's home (as it already does for Homebrew's
bin, #1525):
- agent: a new macAppFolders(home) (/Applications via SystemDirs, plus
  ~/Applications) is used by appFolders (desktop apps: Codex, dsh),
  pencilApp, t3App and reasonixDetected;
- cursorLocalRoots: macOS through macAppFolders, Windows' ProgramFiles and
  Linux's /opt, /usr/share, /usr/lib through SystemDirs;
- zedAppPath's /Applications/Zed*.app, npmGlobalPrefix's ProgramFiles npm
  fallback, and provider's /Applications/ZCode.app builtin config.
Production behaviour is unchanged: SystemDirs returns paths as they are
outside a sandboxed test.

Why: HasApp/AppVersion read the real /Applications, so on a Mac with
DeepSeek Harness.app the dsh fixture's CLI was never "missing" and the test
failed every time; CI has no such app, so nobody else saw it. The same
shape was in five other readers.

Test: TestAppFoldersStayInTheTestHome checks every app folder lies under
testenv's home (all OSes), and on macOS that an app installed in the
sandbox's /Applications is the one found.

Run (go1.26.8, sandbox HOME, private GOCACHE):
- repro on old code: appFolders pointed at a temp folder holding a fake
  "DeepSeek Harness.app/Contents/Info.plist" (com.deepseek.dsh) ->
  TestAsideOfflineDisconnectRestoresWithoutDaemon FAIL "native fixture must
  report missing CLI".
- break check: macAppFolders put back to the literal /Applications ->
  TestAppFoldersStayInTheTestHome FAIL (appFolders, macAppFolders,
  cursorLocalRoots look in /Applications; sandbox app not found). Restored:
  pass.
- gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- go test -tags nogui ./internal/agent ./internal/proc ./internal/provider: ok.
- -race -count=5 on the touched agent tests: ok.
Not run: the full go test ./...; Windows and Linux test runs (vet only);
reasonix's Windows registry lookup and Zed's mdfind fallback still ask
the machine (not folder paths) and are left as they are.

Reported-by: mdwsk88

* proc: the mise-hangs test gives up on its fake mise once it has written its pid, not after 300ms a loaded machine passes first (#1838)

What: the context an ask of mise runs under comes from miseAsk (a var;
production keeps miseWait = 5s, now a const). The "hangs" case of
TestFindToolKeepsWrapperWhenMiseDoesntSay cancels it once the fake mise
has written its pid (polled, with a minute's cap), then checks that
FindTool returns the wrapper within 30s of that (the fake sleeps 60s) and
that the fake's process is gone. The other wrapper tests give an
answering fake a minute instead of the production 5s.

Why: the test set miseWait to 300ms; at load average ~20 the fake's shell
hadn't written its pid by then, was killed, and the test said "mise
wasn't asked" though FindTool had asked. Under the same load the "fails"
case took 4.5s of the 5s budget here, so the answering fakes got room too.

Run (go1.26.8, sandbox HOME, private GOCACHE, load avg ~20):
- repro on old code: a 0.5s sleep injected before the fake writes its pid
  -> hangs FAIL "mise wasn't asked".
- new code with a 2s sleep injected: pass (hangs 2.2s). Removed after.
- break check: miseWhich ignoring the context -> FAIL "FindTool returned
  1m0s after mise was given up on". Restored: pass.
- gofmt -l clean; go vet ./... darwin, linux -tags nogui, windows: clean.
- go test -tags nogui ./internal/proc: ok; -race -count=5 -run
  'TestFindTool|TestParseMiseWrapper': ok.
Not run: the full go test ./...; Linux CI's run of this test.

* gateway: a test's fake left out of its allowance no longer answers later tests from its rest (#1840)

Cause: rests are kept for the process in restingUntil, keyed by provider
id, and every setup() test's provider is "fake". Since ff930886a (#1772)
the last key out of its allowance rests too, and a request whose keys all
rest that way is answered from the rest without asking.
TestErrorsAndUnknownModel's 402 "Insufficient Balance" so rested "fake"
for 30 minutes, and any later test in the same process (CI's shard order)
got "Fake: Insufficient Balance (out of its allowance: not asked again
before HH:MM)" with its fake called 0 times: TestOpenCodeGetsConversationSession,
TestGeminiRequestValidation, TestRequestValidationPreservesPayload,
TestGeminiClientChatUpstream, TestModelListSaysWhichAPI.

The production keying is right: distinct providers have distinct ids, and
a provider's one key rests as the provider by design. The shared state is
the tests', so setup() lifts every rest before the test and again in its
Cleanup (noRests), as several tests already did by hand.

Run (worktree at 7d9382db2):
- reproduced: go test -count=1 -run with TestErrorsAndUnknownModel and
  the five failing tests: 5 FAIL with the 402 above.
- with the fix: same run ok. With both noRests calls commented out: the
  same 5 FAIL again.
- go test -race -count=1 ./internal/gateway: ok (843s).
- gofmt -l internal/gateway: clean. GOOS=linux and GOOS=windows
  go vet -tags nogui ./internal/gateway: clean.

Fixes #1840

* gateway, provider: an image model the vendor turns away in chat, naming its images API, draws there (#1837)

What: when a drawing asked on chat completions comes back 400/422 with
the vendor's message naming images/generations, magpie asks the images
API with it (and the other way round: an images-API refusal naming
chat/completions goes to chat), and tells that second answer. Before,
only a 404/405 moved a drawing to the other API. The model test in the
provider editor does the same for an image model (DrawsID) refused in
chat that way, so it is tested where the gateway draws with it.
catalog.PointsToImagesAPI / PointsToChat are the one shared check.

Why: #1837, omp's generate_image with Settings > Image generation on
agnes-image-2.5-flash got 400 "Model agnes-image-2.5-flash is an image
model. Use /v1/images/generations". catalog.ImagesAPI goes by name, and
agnes-image-2.5-flash reads like gemini-*-flash-image, which chat, so it
went to chat completions and the vendor's 400 was passed on. The vendor's
own words are the rule now, not one more name in the list.

Run: TestDrawGoesWhereTheVendorPointsIt (gateway; the reporter's exact
400 body) and TestTestModelsGoesWhereTheVendorPointsIt (provider) both
fail on the old draw.go / test.go and pass now. gofmt -l clean; go vet
./... on darwin, linux (-tags nogui) and windows clean; go test
./internal/catalog ./internal/provider ./internal/gateway green.

Not run: against Agnes's real API (no account); the 400 text is the one
in the reporter's screenshot. Image models stay out of chat agents'
model lists as before (catalog.Chat / LiveDrawers): the omp error came
from magpie's image tool, not from omp's chat model list.

* agent, library: Hermes Agent's folder is %LOCALAPPDATA%\hermes on Windows, and rtk's installer is told it (新v学员 on Discord)

新v学员 runs magpie on native Windows. Library -> RTK -> Hermes Agent
failed with "rtk's installer didn't add its hook to Hermes Agent:
Config: C:\Users\admin\AppData\Local\hermes\config.yaml ...". magpie
hard-coded ~/.hermes. Hermes' own default
(hermes_constants._get_platform_default_hermes_home) is
$LOCALAPPDATA\hermes on win32 (~/AppData/Local/hermes when LOCALAPPDATA
is empty) and ~/.hermes elsewhere, with $HERMES_HOME overriding it.
rtk 0.51's resolve_hermes_home knows only $HERMES_HOME and ~/.hermes,
on every OS.

What changed:
- appdir.HermesHome / HermesHomeIn / HermesDefaultIn: $HERMES_HOME,
  else Hermes' per-OS default. This is the one place that resolves it.
- agent: hermesIn (Agents-page model wiring) and hermesProfiles use it
  through place.hermesHome / hermesDefault. A WSL distro keeps
  ~/.hermes (Linux paths, Windows env not read). The Agents-page wiring
  was wrong on native Windows too: without HERMES_HOME it wrote
  %USERPROFILE%\.hermes\config.yaml, which Hermes never reads.
- sessions.HermesDir uses it, so Windows sessions are found.
- library/rtk: the hermes spec reads and writes the agent's own folder
  (a.Dir), and rtkSpec.env passes HERMES_HOME=<that folder> to
  `rtk init -g --agent hermes --auto-patch`.
- Tests resolve the folder through appdir instead of home/.hermes. New
  TestHermesDefault/TestHermesHome (appdir), TestHermesFolder (agent:
  Windows default, profiles under it, WSL unchanged), and
  TestRTKHermesHome (library, a fake rtk that behaves like 0.51).
- docs/reference.md and docs/subsystems/library.md describe the
  Windows folder and the env.

Run:
- gofmt -l clean. go vet ./... on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- darwin: go test ./internal/appdir ./internal/library
  ./internal/sessions ./internal/agent ./internal/tui.
- TestRTKHermesHome against the old rtk.go fails with the reporter's
  exact message ("didn't add its hook ... AppData/Local/hermes/
  config.yaml"), and its default subtest fails with HERMES_HOME="".
- Windows box (cross-compiled test binaries, testenv sandbox
  USERPROFILE/LOCALAPPDATA): appdir Hermes tests, agent
  Hermes|Reseat|Effort (incl. TestHermesFolder) and library Hermes|RTK
  pass. TestRTKHermesHome skips there (shell fake). The sessions binary
  failed only TestHermesMessageVisibility, because its testdata wasn't
  copied to the box.
- Real rtk.exe 0.51.0 on the Windows box: with
  HERMES_HOME=<sandbox>\AppData\Local\hermes it wrote the plugin there
  and patched that config.yaml. Without HERMES_HOME it wrote
  C:\Users\<user>\.hermes, ignoring a sandbox USERPROFILE (rtk asks
  Windows for the home folder). That confirms the cause and the fix.
  The stray folder it made on the test box was removed.

Not run: real Hermes on Windows (no install, and running hermes under
a temp HERMES_HOME rewrites the live launcher); the GUI suite; the full
go test ./... ; the reporter's own machine.

* gateway: a DeepSeek step that said something before its call leads with its reasoning, so DeepSeek no longer refuses it with 400 (#1822, #1592, #1687)

Codex through magpie to OpenCode Go's DeepSeek (#1822), and to DeepSeek's
own API (#1592, #1687), was refused now and then with "The `reasoning_text`
in the thinking mode must be passed back to the API".

The cause, checked against api.deepseek.com/v1/responses on 2026-10-12:
DeepSeek reads each step (a run of reasoning, assistant messages and calls
after a user message or tool output) as one assistant message whose
thinking is the item the step starts with. In the current turn (since the
last user message), a step that has a call or follows a tool output must
lead with a reasoning item. [message, reasoning, call] and [output, message]
are refused; [reasoning, message, call] and [output, reasoning, message] are
taken. When a step had no reasoning (another model's turn, a translated
one), magpie inserted its " " reasoning right before the call, which gave
[message, reasoning " ", call]. A step with only a call worked, and only
the current turn is checked, which is why the reporter saw it come and go.

What changed:
- responses.go: withReasoningText and buildResponses now share reasonFirst.
  Each such step leads with reasoning: the step's own first reasoning item
  is moved ahead, otherwise one holding a space is put first. A sealed item
  keeps its id and encrypted_content. A body already in that shape goes
  byte for byte.
- Sibling, the same API family: an assistant reply right after a tool
  result, with no reasoning, is refused too (checked on DeepSeek's Chat and
  Anthropic endpoints). Chat (withReasoningOnToolTurns relayed, buildChat
  translated) now gives such a reply reasoning_content " ". Anthropic
  (withThinkingOnToolTurns) gives it a thinking block. Anthropic takes
  thinking anywhere in the message, so ordering is not an issue there.
- The DeepSeek fakes in the tests now model the real rules. The stricter
  Responses fake also turns TestDeepSeekGroupMemberAfterChatGPT red on the
  old code: its "an assistant note" case is this bug, which the old lenient
  fake hid.
- docs/subsystems/gateway-routing.md: the Responses, Chat and Messages
  replay paragraphs.

What was run:
- New tests: TestDeepSeekStepSaysBeforeItsCall covers the reporter's shape
  across OpenCode Go, DeepSeek and a group, streamed and not. Also
  TestWithReasoningTextLedStepsUnchanged,
  TestTranslatedDeepSeekStepLeadsWithReasoning,
  TestChatReplyAfterToolGetsReasoning and
  TestAnthropicReplyAfterToolGetsThinking. All but the unchanged-body test
  fail on the old code.
- gofmt -l; go vet ./... on darwin, and with -tags nogui on linux and
  windows; go test ./internal/gateway.
- Real API: direct requests to api.deepseek.com (Responses, Chat,
  Anthropic) with the old and new shapes, as listed above.

What wasn't:
- OpenCode Go's own endpoint: the test account is refused with "This Go
  model requires Global regions", an account setting, so its fix rests on
  it relaying DeepSeek's rule unchanged (the reporter's error text is
  DeepSeek's).
- A built magpie end to end against the real API.
- Other thinking vendors (Kimi, GLM) were not checked for the same step
  rule. Their paths are unchanged.

* agent, gui: Codex's magpie API sign-in says its Chrome control needs ChatGPT, so pick ChatGPT to keep it (#1824)

What: the "magpie API" option of Codex's sign-in (internal/agent/codex.go;
the GUI picker and the TUI both show the option's note) now ends with
"Codex's Chrome control needs the ChatGPT sign-in, so pick ChatGPT to keep
it", in en, zh, zh-TW, ja and de (i18n.js). The login field's comment and
docs/subsystems/agent-wiring.md say why.

Why: with magpie as Codex's provider (no requires_openai_auth), codex-rs's
getAuthStatus returns authMethod null and no token, so Codex's Chrome
control says "Codex auth token is unavailable". Reproduced earlier with real
codex 0.162.1 in a sandbox CODEX_HOME; the ChatGPT sign-in
(openai_base_url) keeps the token. Nothing magpie writes can bring the token
back on magpie API without turning the Codex app into a ChatGPT account,
so the option says what it costs.

Run: codex-signin-always.test.cjs (now also zh-TW, and asserts the API
note names Chrome and ChatGPT in the page's language) in Chromium and
WebKit at 1100px and 440px, 10/10 pass with playwright 1.62.0; with
origin/main's i18n.js it goes red for zh, zh-TW, ja, de. gofmt -l clean;
go vet ./... on darwin, linux (-tags nogui), windows; go test
./internal/agent ./internal/gui ./internal/tui green.
Not run: the Windows box, the real Codex app's picker.

* gateway: a user message the agent wrote alone is no new turn, and routing asks about and keys on the user's own words (#1826)

What: one helper, userWords/userSaid in prompt.go, says what the user
said in a text: it drops <system-reminder …> blocks (now with a source=
attribute too, as ZCode sends) and any text that begins as an agent
writes for the model alone, and keeps only what follows the Codex app's
"## My request (for Codex):". The leads, beside agentsFor: Codex's
<environment_context>, <user_instructions>, <turn_aborted>,
<user_shell_command>, <subagent_notification>; Claude Code's and
ZCode's <task-notification>, <subagent-notification>, agent lists
("Available agent types …", "New agent types are now available …"),
TodoWrite and task-tool nudges, rewind notices; ZCode's
<plugin_reference>; the Codex app's <in-app-browser-context …>. Each
was taken from the clients' own code or a real transcript (Claude Code
2.1.296, ZCode.app's zcode.cjs, Codex CLI 0.162.1, ChatGPT.app).

Everything that asks "did the user say something" now goes by it:
- turnIn: a user message with nothing of the user's (and no image or
  file) begins no turn. After an answer or a tool round it carries the
  turn on (within), so the turn's rule and stick hold and the classifier
  isn't asked; right after the user's own message it leaves that turn as
  it began.
- userText: the classifier is asked about the last user message with
  words of the user's, only those words (it was the last user message,
  ZCode's agent list after the user's plugin question).
- firstWords (ruleKey and the affinity scope): the words of the first
  user message that has any, so an instruction file or notice the agent
  changes beside them no longer moves a conversation to a new key
  mid-turn. A conversation with no words yet keys on its first message
  as before.
- lastUserText (Copilot's Auto, a sibling): the same.
- userSays (the prompt breakdown's turns) is userWords != "".

Why: #1826 (ZCode) and @321sssrt-bit's comment (Codex): a TodoWrite
nudge was classified as a new, harder turn and sent a 常规 turn to the
复杂 member; a task notification or agent list re-classified the turn;
one ZCode session had three firstWords keys, and the turn that lost its
key fell to the group's first member.

Upgrade: a conversation whose first user message held injected text
gets a new key once (its words only), so its stick and turn rule are
looked up afresh on the first request after the upgrade.

Run: user_said_test.go (TestTurnInSkipsWhatTheAgentPutIn,
TestUserTextSkipsWhatTheAgentPutIn, TestFirstWordsAreWhatTheUserSaid,
TestLastUserTextSkipsWhatTheAgentPutIn,
TestIntentHoldsPastWhatTheAgentPutIn end to end through the server,
TestUserSaysPastAReminderWithASource) fails on the old code (all six
red with the five source files put back) and passes now; go test
./internal/gateway -count=1 green (323s); gofmt -l clean; go vet ./...
on darwin, GOOS=linux -tags nogui and GOOS=windows clean.
Not tried: a live ZCode, Claude Code or Codex session against a
group with intent rules; fixtures are the clients' literal strings.
Not done here: persisting turnRules beside the sticks (the issue's
idea 3); the classifier-failure fallback is the next commit.

* gateway, gui: a classifier that can't say keeps the intent the turn before had, rather than sending the turn to the group's first member (#1826)

What: in ruleFor, when the classifier errs (an error, no answer within
classifyTimeout, an answer that isn't a number, or resting classifyRest
after a failure) and the conversation's turn before had an intent that
is still one of this turn's (Classified.After), the turn keeps it:
Classified.Intent is that intent, the new Classified.Fallback
(json "fallback") is "previous", and Error is kept. With no intent
before, nothing changes: no rule with an intent matches. The Routing
page's classWhy says "… but couldn't — {err} — so the turn keeps
“{intent}”, as turn {prev} was.", in zh, zh-TW, ja and de too.

Why: #1826 section 3: two timeouts in a row (20:54:43, 20:55:20) sent
turns of a known 复杂 conversation to the group's cheap first member.

Not done: persisting turnRules beside the sticks (the issue's idea 3).
After a restart a turn under way still waits for the next turn, with the
stick holding it meanwhile; with the previous commit the stick's key no
longer changes mid-conversation, which was how the reporter lost both.

Run: TestIntentClassifierFailsKeepsThePreviousIntent (down, then resting,
then a conversation with nothing to keep) fails with the fallback line
taken out and passes now; routing-intent-fallback.test.cjs (Chromium and
WebKit, en/zh/zh-TW/ja/de, 1100px and 390px with no sideways scroll)
30/30, and 10 of 15 red on Chromium with the old routing.js;
routing-intent-entry, routing-effort, panel-routing, routing-folder,
i18n-keys and gui-de pass; go test ./internal/gateway -count=1 green
(295s); go test -tags nogui ./internal/gui green; gofmt -l clean; go vet
on darwin (gateway), GOOS=linux -tags nogui ./... and GOOS=windows ./...
clean.
Not tried: a real classifier timing out in a live session.

* claude: a fresh sign-in goes into the keychain item Claude Code reads, not beside it (#1742, #1842, iefnaf)

What changed: readClaudeCredential asked the Keychain only when the
credentials file held no sign-in. On a Mac whose "Claude Code-credentials"
item is there but emptied (what Claude Code leaves of a sign-in Anthropic
refused to refresh), an older, parseable ~/.claude/.credentials.json was
taken for the sign-in: a sign-in made in magpie was written into that file,
the dead item stayed, Claude Code stayed signed out, and a minute later
claudeIdentity's loggedIn: false lapsed the account and took the provider
out. Now the item under the account ($USER) is read first, emptied or not,
as Claude Code reads it: its own storage asks the Keychain first and reads
the file only when the item is absent, empty or no JSON — the rule
readClaudeDir already applies, with its own test, to the item in a saved
account's config directory. putClaudeLogin, reusing what was found, puts a
fresh sign-in into the item. The item is asked by service alone only after
the file has no sign-in, as before (an earlier sign-in's leftover,
58b67666).

Amended in review (yetone): the patch as sent took an item magpie wrote
over lines, which `security -w` prints as hex (#70), for the sign-in ahead
of the file and rewrote it on one line. Claude Code 2.1.296's keychain leg
JSON-parses what `security` prints, so hex reads as no item and it goes by
the file: the account's hex item now comes after the file, and is only
rewritten when the file has no sign-in either, as before. The two reads are
one claudeKeychainItem value instead of a four-result helper.
TestClaudeHexKeychainItemIsNoneBesideAFile covers it.

Checked against Claude Code 2.1.296's binary: its secure storage is
M(keychain, plaintext); the fallback leg's read returns the keychain's
result whenever it is not null, and the keychain leg returns
JSON.parse(`security find-generic-password -a $USER -w -s
"Claude Code-credentials"`) when that prints anything, else null (a parse
error is caught as null). Every HOME reader in magpie (liveLogin,
claudeAccount, Usage, claude_auth, putClaudeLogin) goes through
readClaudeCredential via claudeCredential, so they all follow the one order.

Run: TestClaudeEmptiedKeychainItemIsTheSignInBesideAFile fails with main's
order (the account's item not asked first) and passes with the change;
TestClaudeHexKeychainItemIsNoneBesideAFile fails with the patch as sent
(hex item taken over the file) and passes with the amendment;
TestClaudeFileSignInWhenNoKeychainItem guards the file fallback. All with a
sandbox HOME and a fake `security` on PATH. Full checks are in the next
commit's body. Not run: no real Keychain, no real emptied item, no real
sign-in from the GUI.

Co-authored-by: yetone <yetoneful@gmail.com>

* claude: with CLAUDE_CONFIG_DIR set, the keychain item read and written is the one Claude Code keeps there (#1842)

What changed: magpie read and wrote Claude Code's own sign-in under the
service "Claude Code-credentials" whatever CLAUDE_CONFIG_DIR said. Claude
Code 2.1.296 names its item "Claude Code-credentials-<sha256(dir)[:8]>"
when CLAUDE_CONFIG_DIR is set (j$ in its secure storage: the suffix is
dropped only when CLAUDE_CONFIG_DIR is unset), which is what
claudeDirService already computes for saved accounts' directories. Now
claudeHomeService gives that name for the read (both the account's item
and by service alone) and for saveClaudeCredential.

Why now: the previous commit asks the account's item before the file, so
with CLAUDE_CONFIG_DIR set the plain "Claude Code-credentials" item — the
default directory's sign-in, maybe another account — would have beaten the
.credentials.json in CLAUDE_CONFIG_DIR. It was already wrong before that
commit (a sign-in was written to an item Claude Code under that directory
never reads), only less visible.

Run (tip of both commits, sandbox HOME, fake `security` on PATH, private
GOCACHE): TestClaudeConfigDirKeychainItem fails with claudeHomeService
ignoring CLAUDE_CONFIG_DIR (it read "home-item") and passes with it.
gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows pass; go test -count=1 ./internal/provider ok (116s);
go test -race -count=5 on the keychain tests ok.
Not run: no real Keychain, no real Claude Code run under CLAUDE_CONFIG_DIR
(the name rule is read from the 2.1.296 binary), no other package's tests
(only internal/provider changed).

* provider: moved Command Code users get plugin 0.1.12, whose model list follows the account's plan (01huadalang on Discord)

Command Code 0.1.12 (magpie-community/plugins 49e9d89): Command Code's model
list is the same for every plan, and the plugin filtered only Go's, by the
CLI 1.73.0 table, which lacked Claude Haiku 5.5. So a Go account was shown a
model only GOAT and above may use, and GOAT, Pro and Provider accounts every
model, those their plan refuses included. Each plan's list now leaves out
what the CLI 1.79.2's table refuses it; a plan that can't be read, or an
account with bought or free credits, keeps the whole list, and a refused
model still reaches the agent as Command Code's MODEL_NOT_IN_PLAN.

Only the mover's min string and its note change. 0.1.12 was checked on npm
with npm view.

Ran: gofmt -l internal/provider, go vet ./internal/provider on darwin, linux
and windows, and go test ./internal/provider -run 'Mov|Migrat' (ok, 8.6s).
The full suite was not run, as this is a one-string change.

* gui: the Sessions page draws its folders 100 at a time, so thousands of one-session folders don't hold every click (yetone)

An app that runs Codex once per picture, each in a folder of its own,
left 11,358 Codex folders of one session each on the owner's machine.
The page paged the sessions inside a folder (100 at a time) but drew
every folder: 113,900 elements. In WebKit a click to Sessions held the
main thread up to 2.7s, and since the hidden page stayed in the
document, a click to Library after it took ~240ms instead of ~40ms.

The folders are now drawn a page at a time like a folder's sessions:
the first 100, and a "Show N more folders" that adds the next 100 above
itself without redrawing or moving what is drawn (data-unrolls, as
moreRow). How many are drawn is kept in drawnIn, so it starts again at
a page wherever a folder's sessions do (another agent, the filter), and
unfolding a folder or coming back to the page keeps it. A session
opened from the Usage page has its folder drawn however far down it
is. The bar and a folder's box still pick every session, drawn or not.
New string in zh, zh-TW, ja and de.

Run:
- On the owner's real data (dev backend, 11,584 Codex sessions), WebKit,
  this branch's assets vs main's: Sessions 113,900 -> 1,101 elements,
  worst main-thread stall 2,675ms -> 44ms; Library click 238ms -> 32-62ms.
- New sessions-folder-paging.test.cjs: 10/10 (chromium + webkit, en, zh,
  zh-TW, ja, de, 1000px and 380px). Drawing every folder again turns it
  red (expected 100, actual 250).
- Every sessions GUI file (23): all pass except routing-sessions webkit
  en, red the same alone on origin/main d9bb0fbc8 (#1672, noted there),
  and session-identity once under the back-to-back run, 10/10 alone on
  both (noted on #1544).
- go test ./internal/gui: ok.

* gateway: a tool call a model wrote into the text of a Chat reply asked for whole is made the call it is, as a streamed one is (#1845)

A request with stream:false relayed to a Chat upstream had its reply
mended by chatWhole, which only flattened typed content (#483). The
rescue of calls written into the text (textcalls.go, #823) ran only in
textCallTidy, on a stream. So a DeepSeek reply whose content was its
DSML <|DSML|invoke name="Bash">… reached the client as that text with
finish_reason stop, and the agent ran nothing; the same request
streamed got a real tool_call (#1845, cline-pass/deepseek-v4.1-flash).

chatWhole now gets the request's tool names and, for each choice,
wholeTextCalls reads the content with the streaming parser
(textCallAt + parseTextCalls), so the same formats are taken: Hermes'
<tool_call>, DSML, the half-Hermes <parameter> form (#917) and GLM's
(#906). The text before the first block is kept (null when none), the
tags go, the calls become tool_calls with call_text_ ids and
finish_reason becomes tool_calls. As in the stream: a reply that made
a call itself, a block naming a tool not offered, arguments that can't
be read, or no tools offered leave the reply as it came; tags and
nothing else are dropped. A cheap check (tool_call or DSML in the
bytes, escaped brackets included) keeps other replies byte for byte.
chatWhole is now also used for a whole reply under text/plain or no
type, which eventStream had found isn't a stream; before, only JSON
types were mended.

Routes checked: Chat relayed whole (fixed); a streamed request a vendor
answered whole goes through chatWhole before wholeAsStream (fixed by
the same, tested); Responses and Anthropic translations of a Chat
upstream, streamed and whole, a plugin's, and a Chat request for one
body asked streamed (DashScope) all go through textCallSee already
(tests added). A relayed Responses or Messages upstream's text isn't
read for calls, streamed or whole; unchanged.

Run (Go 1.26.8, sandbox HOME, private GOCACHE):
- New TestTextWrittenCallWhole (the issue's DSML, after text, Go-escaped
  brackets, text/plain, Hermes, #823's junk, #917's param, GLM, wrapped
  invoke, two calls; left as text: no tools, unknown tool, cut short,
  lookalike, empty content, plain; tags only; beside a native call;
  truncated body; empty body), TestTextWrittenCallWholeTranslated, a
  case in TestQuietWholeReplyStreamed and a chat-whole subtest in
  TestPluginTextWrittenCall.
- Broken by hand: chatWhole without names turns 11 subtests of
  TestTextWrittenCallWhole and the TestQuietWholeReplyStreamed case
  red; leaving finish_reason alone turns them red on "finish stop";
  the old JSON-only gate turns the text/plain case red; turning
  textCallSee's rescue off turns the translated and plugin tests red.
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. go test -tags nogui
  ./internal/gateway in full: ok (363s).
- Real: no ClinePass key here, so the reporter's request went through
  this branch's gateway in a sandbox to DeepSeek's own API
  (deepseek/deepseek-flash), 5 runs each way. One stream:false reply
  in DSML came back as tool_calls Bash {"command":"ls /tmp"},
  finish_reason tool_calls. Other runs the model wrote other markup
  (<|tool▁calls▁begin|>…, <|invoke name="Bash"|>) that neither the
  streamed nor the whole rescue reads, streamed or not; not changed here.

Not run: the full go test ./... (only internal/gateway), Windows and
Linux test runs, ClinePass itself.

* usage, gui: a usage record and a request's details carry its cache read and cache creation beside in and out (#1839)

kensenzhao asked for usage.jsonl and the Usage page's request details to
carry cache read and cache creation tokens beside input and output.

What changed
- usage.Record's cache_read and cache_write are written on every record,
  0 too (they were omitempty), so a prompt that missed the cache reads as
  that rather than as a record that kept no cache. A record from before
  has neither and reads as 0, as it did. Input still holds neither.
- Every route already filled them; this pins it per wire format:
  Anthropic messages, OpenAI Chat (prompt_tokens_details.cached_tokens and
  DeepSeek's prompt_cache_hit_tokens), Responses
  (input_tokens_details.cached_tokens) and Gemini
  (cachedContentTokenCount), relayed and translated, whole and streamed,
  a plugin's fetch, and the Claude subscription bridge. System One's
  decision calls report no cache and are left as they are.
- A request's details in the ledger have a Tokens row at every width:
  "{i} in · {o} out · {r} cache read · {w} cache creation", plus the
  5-minute/1-hour split when known. Before, the cache showed only as
  "{w} written · {r} read" when non-zero, so a missed cache said nothing.
  That string is gone; the new one is in zh, zh-TW, ja and de.

Prices and quotas: the JSON tag is the only change to the record, so the
cost math (CostAt -> CostSplit reads CacheRead/CacheWrite/CacheWrite1h),
Totals' cache sums, budget's CacheReads and access/limit's token windows
read the same values as before. Checked by reading each and by the usage,
access and catalog tests passing unchanged.

Tests
- TestRecordAlwaysCarriesCacheTokens (usage): 0s written, old records read.
- TestUsageRecordsCacheTokensOnEveryRoute, TestPluginUsageRecordsCacheTokens,
  TestClaudeSubscriptionUsageKeepsCacheTokens (gateway): each wire format,
  whole and streamed.
- ledger-cache-tokens.test.cjs: Chromium and WebKit, 1100 and 390 wide,
  en/zh/zh-TW/ja/de; usage-ledger-detail.test.cjs updated for the row.
- Broken by hand: putting omitempty back and dropping the Tokens row each
  turned its test red. The gateway route tests pin what the routes
  already did; they don't fail on the code before this commit.

Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above plus the translation tests. Not run: a real vendor
request to see its cache figures land in usage.jsonl.

* usage, gateway, gui: magpie's own requests are told apart from the agent's, and a classifier on a subscription says it asks it every turn (#1839)

kensenzhao saw a subscription's allowance spent by requests the agent
didn't make: a routing group's classifier, set to a subscription's model,
asks it as every turn begins, and those calls looked like the agent's own.

What changed
- usage.Group has an own share (calls, tokens, cost) of the calls magpie
  made by itself, filled for models, keys and accounts. Record.ByMagpie
  is the test: agent "magpie", or one of its own User-Agents
  (magpie-router/1, magpie-search/1, magpie-vision/1) where the agents
  aren't loaded. The calls still count in the group's totals, as they
  went to the same key or account. A group with none sends no "own".
- The classifier's calls are Kind "routing": callKind marks RouterAgent's
  requests, and the decision model's record (Jev / System One) is written
  with it. A "Routing classifier" purpose names them in the ledger.
- Usage page: magpie's row among the agents and its ledger rows carry a
  "magpie's own" mark; an account's, key's or model's row adds "{n} by
  magpie itself"; an account's card says how many of the period's
  requests were magpie's own, drawn again once the summary arrives after
  the allowances.
- Routing page: /api/groups marks a model a subscription account serves
  (modelRef.Sub, servedRef). Beside a classifier on such a model, or a
  group whose first member is one, the editor says every turn starts
  with a request to that subscription, two when it picks both intent and
  effort in words. A classifier on a key or a free model says nothing.
- New strings in zh, zh-TW, ja and de. The mark is a muted chip with an
  even border all round (no left stripe).

Tests
- TestSummaryCountsMagpiesOwnCallsApart, TestByMagpie (usage).
- TestIntentRoutesATurn and TestJevPicksTheIntent (gateway) now check
  the classifier's records are Kind routing and magpie's own, and the
  agent's records are not.
- TestServedRefSaysASubscription (gui).
- own-requests.test.cjs: Chromium and WebKit, 1100 and 390 wide,
  en/zh/zh-TW/ja/de, the API faked; no click scroll, no sideways page.
- Broken by hand, each turned its test red: addOwn counting nothing;
  callKind's routing case removed; decide.go's Kind blanked; the ledger
  mark, the agents' mark, the "{n} by magpie itself" line, the card's
  line, its redraw after the summary, the Routing hint, its group case
  and modelRef.Sub each removed.

Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above, the ledger, routing-intent and translation tests.
Not done: the warmups (warmClaude/askClaude) write no usage record at
all, so they can't be marked; that is left as it was. Not tried with a
real subscription classifier against a live account.

* gui: the ja Hooks notice names its agent once, so the ja translation test passes again

e3a497d7a (#1790) added "{event} is {agent}'s own event: only it can run this hook" with a ja value that said {agent} twice ("…実行できるのは {agent} だけです"). gui-ja.test.cjs checks each value has the zh one's placeholders, so it has failed on main since: run alone on origin/main 98b5a02d1 it is red on that string and nothing else. The second {agent} is now "そのエージェント" (that agent), as the English "only it" says it.

Run: gui-ja.test.cjs (red before, green after), and the zh-TW, de and i18n-keys tests.

* gui: a tab picked in the sidebar opens at its top, not where the tab before was left (#1844)

Usage, Library, Plugins and Settings list their tabs under the page in the
sidebar (navSubs), and a page's tabs share its one scroll. A row only
clicked the page's own tab, so scrolled to the foot of Settings › General
and Allowances picked, Allowances showed at its foot; Library › MCP
servers and Skills the same. A row that picks another tab now clicks it
and scrolls the page to its top through scrollOnPurpose with the row's own
click. The tab already open, picked again, leaves the page where it is.
The page's own strip (the header's tabs) and switching between pages are
unchanged.

sidebar-tab-top.test.cjs (Chromium, WebKit, en, zh) fails without the
change, 6 of 6: "Allowances opens at its top", 177 (en) and 228 (zh)
instead of 0; with the Settings part left out, "Skills opens at its top",
about 2100 instead of 0. It passes 6 of 6 with it. go test -tags nogui
./internal/gui in a temp HOME passes.

* gui: sidebar-tab-top also holds the page's own strip and page switching still, in every language (#1844)

lainbo's test checked the sidebar rows in English and Chinese. The rule the
change sits beside ("where the reader is", 73af4c28) is that a tab clicked
in the page's own strip leaves the page where it is, and switching pages
keeps each where it was left. The test now checks both, so a later change
that lets the new scroll reach them goes red:

- the sidebar part runs in en, zh, zh-TW, ja and de, and after the tab
  switches goes to Settings and back to the Library: each is where it was
  left;
- a new test per engine, with the sidebar turned off (1100px, navLayout
  top) and in a window narrower than SIDE_AT (900px), scrolls Library ›
  MCP servers to its foot and clicks Skills in the page's strip: the page
  is not taken to its top. Every language.

Run: sidebar-tab-top 34/34 (Chromium, WebKit) with the change. The strip
test passes 22/22 on main's app.js too (unchanged behaviour). Broken by
hand: the strip's segs click scrolling its view to 0 fails the strip test
10/10; Settings' place reset to 0 on a page switch fails "Settings is where
it was left"; the row scrolling with the tab already open fails "the tab
already open leaves the page where it is"; scrollOnPurpose() without the
click's event fails "Allowances opens at its top" (refused, 177/228).

* settings, gateway, gui: a browser extension is listed among the web pages that may call magpie by its origin, chrome-extension://<id> and the like (#1051, SkyAerope on Discord)

What: Settings › Network and sharing › Web pages now takes a browser
extension's origin besides http(s) ones: chrome-extension://<id>
(Chromium, the id 32 letters a-p), moz-extension://<uuid> (Firefox's
Internal UUID) and safari-web-extension://<uuid> (Safari). cleanOrigin
takes only those three schemes, only with an id of that browser's shape,
lower-cased and with a trailing "/" let go; a bare scheme, a wildcard, a
path, a port, user info, a query or another browser's id shape is
refused. The GUI maps the new refusal to the same message, which now
names the extension form, in en/zh/zh-TW/ja/de, and a listed origin
wraps instead of being cut (an extension's runs to 50-60 characters and
was ellipsized at a 440px panel). The 401 a listed caller gets without a
key names extensions too. Docs: gateway-routing.md, the settings field.

Why: an extension without host_permissions (Sider and the like) is held
to CORS; the gateway never answered its preflight, since its origin
couldn't be listed. Nothing else in the access rules changes: corsGuard
treats a listed extension exactly as a listed page (preflight answered,
every call needs an enabled gateway key or gets 401, even on loopback),
an unlisted extension passes with no CORS headers as before (foreignPage
still only judges http/https), and lanGuard's rebound/Host checks, the
allow list and every other route guard are untouched.

The Origin each browser sends was checked, not guessed: real Chromium
(below) sent Origin: chrome-extension://<32 a-p>; Firefox's is
moz-extension://<Internal UUID> (Gotify's and others' CORS docs list
it); Safari's is safari-web-extension://<lowercase uuid>, per Apple's
developer forums (thread 654839), where an Apple engineer notes the uuid
changes on each Safari launch, so a Safari listing lasts until it
restarts (said in the doc). A content script's fetch carries the page's
origin (MDN), so only extension pages, popups and workers are covered.

Run, at 28aac86bc:
- TestCleanExtensionOrigins (good ids, upper case, trailing slash;
  malformed, wildcard, bare scheme, path, port, userinfo, query, swapped
  id shapes) and TestCORSExtensionOrigin (through lanGuard: unlisted
  preflight/request get no CORS headers and the request runs as before;
  listed chrome and moz preflight 204 with the headers; keyed call 200
  with Access-Control-Allow-Origin; keyless or wrong key 401 without
  reaching the vendor; another id still unlisted). Both fail on the old
  origins.go (the extension origin "is not an origin").
- go test ./internal/settings ./internal/gateway ./internal/gui: green.
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui,
  GOOS=windows: clean.
- GUI: cors-origins (extended: an extension added upper-cased with a
  trailing slash is saved lower-cased and fits the panel, a malformed id
  and chrome-extension://* refused in the page's language), i18n-keys,
  gui-de, gui-ja, gui-zh-tw, allow-ips, lan-docker, chromium and webkit:
  green. cors-origins fails on the old app.js/app.css (the name was cut,
  the extension refusal untranslated).
- Real use: an unpacked MV3 extension with no host_permissions, loaded in
  headless Chromium 1234 (playwright launchPersistentContext,
  --load-extension), fetched a sandbox gateway (lanGuard(New().Handler())
  on 127.0.0.1:3591 under a temp HOME, fake vendor) from its service
  worker and its own page. Not listed: "Failed to fetch" in all four
  cases. Listed (typed upper-case with "/"): with the key, read 200 and
  the vendor's reply; without it, read the 401.

Not tried: Firefox and Safari extensions for real (their origins are from
the sources above), Edge/Brave, and the full magpie serve binary (the
harness ran the gateway's own handler stack, not its background loops).

* provider: WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images; the plugin to 0.1.16 (Yirasumi on Discord)

What: for workbuddy-ai alone, a model whose id starts with glm- is listed
with ImageInput false (wbSite.textOnly), whatever /v3/config's
supportsImages says: in the list fetched, in the built-in list shown
before it, and in a list saved before this change (Provider.available).
The workbuddy movers' min goes to 0.1.16, where the plugin does the same
(magpie-community/plugins cb90931).

Why: checked on 2026-10-13 with the owner's real WorkBuddy AI account.
www.workbuddy.ai/v3/config marks every model supportsImages: true, but
its server takes the image out of a chat to glm-5.3-flash, glm-5.3 or
glm-5.2 and puts "[System reminder: the current model does not support
images. Content filtered. ...]" in its place. Its other models read
images, and WorkBuddy (China)'s glm-5.3-flash does too, so China and the
other families are left as the config says. A user's own answer in
Settings (ModelImages) still wins: entryFor applies it over the list.

Run:
- go test ./internal/provider (full, ok); go test ./internal/gateway
  -run 'WorkBuddy|WB|Vision|Describ|Image' (ok).
- TestWorkBuddyAIGLMIsTextOnly fails with textOnly turned off by hand;
  TestWorkBuddyAISavedGLMIsTextOnly fails without the models.go case.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- Sandbox gateway (own HOME, port 3486, built-in WorkBuddy AI login from
  the owner's migration backup, nothing live written): /v1/models lists
  glm-5.3-flash, glm-5.3, glm-5.2 as text, deepseek, kimi, gemini, gpt,
  grok with image. A blue|yellow split PNG sent to glm-5.3-flash was
  described by workbuddy-ai/deepseek-v4.1-flash (Routing kind "vision"),
  and glm-5.3-flash answered "left: blue, right: yellow". With
  modelImages {"workbuddy-ai/glm-5.3": true} in the sandbox settings,
  glm-5.3 listed image again and glm-5.3-flash stayed text.

Not run: the moved (plugin) path through a sandbox app; the plugin's own
bun tests cover its list, and magpie maps its input.image as ImageInput.

* gui: dates, times and numbers read in the GUI's language, not the system's, so a Chinese Mac set to English no longer shows Routing's days as 10月11日 周日 (#1843)

What changed: intlLang() was the GUI's tag for Intl, but returned
undefined for English ("the system's own formats"), and about 60 calls
in app.js, routing.js, library.js, plugins.js, caller-keys.js and
context.js formatted with no locale, [] or undefined anyway. All of
those follow the system's locale, so with magpie set to English on a
zh-CN Mac, Routing's day pills read "10月11日 周日" (the report), and so
did request times, reset/until titles on Accounts and Usage, plugin and
library dates, the restore notice, and key rest times. Now intlLang()
always returns a tag: zh-CN, zh-TW, ja-JP, de-DE for those languages,
and for English the system's own English (en-GB keeps day-month) or
plain "en" on a system in another language. Every date, time and number
formatting call in the assets takes intlLang(); the `intlLang() || "en"`
and `documentElement.lang || undefined` variants are folded into it.
<html lang> stays "en" for English. Routing's clock formatters, made
once, are made again when the language changes.

Tests: dates-gui-lang.test.cjs runs English on a zh-CN browser, English
on en-GB, and zh, zh-TW, ja, de on en-US, in Chromium and WebKit at
1100 and 390px: Routing's day pills (in the bar and under its menu) and
a request's time must read in the GUI's tag and not the browser's.
TestDatesFollowGUILanguage (Go, so CI runs it) fails on any formatting
call in the assets given no locale, [] or undefined.
github-token and reset-each-title computed their expected text in the
browser's locale, i.e. they encoded the bug for zh/ja/de; they now ask
intlLang().

Run: with routing.js put back to origin/main the new GUI test fails 10
of 12 (all but en-GB, where the system's English is right either way);
with intlLang() returning undefined for English the English cases fail.
TestDatesFollowGUILanguage fails on origin/main's routing.js (lines 244,
688, 1925, 2230, ...) and passes on the fix. gofmt -l clean; go vet
./internal/gui on darwin, GOOS=linux -tags nogui and GOOS=windows ok;
go test -tags nogui ./internal/gui ok. Full GUI suite (621 files,
concurrency 6): 51 failures in 21 files; rerun alone, the same 8 files
fail the same way on an origin/main 552e974f2 copy (gui-ja,
library-mcp-tools, pick-skills, profile-in-use, routing-group-fold,
routing-sessions, searcher-pick, text-size), signin-proxy failed once
under load ("element was detached", de 380) and passes 3/3 alone, the
rest pass.
Not run: not tried in the real app on a zh-CN Mac; no Windows or Linux
webview run.

* gui tests: tray-logos says what the wheel met when the settings list stays at 0, since Chromium zh's red could not be made again (#1850)

The zh case failed "the settings list must be scrolled" in Chromium in
other sessions' runs (wt-nav navrepro alone/full/refail logs, Oct 12; the
a1843 full run, Oct 13), each time Chromium zh only, and passed on rerun.

What changed: the assertion is the same (scrollTop > 0 after the wheel),
but its failure message now records the scrollTop after each wheel, any
"refused" scroll-guard console warning, the hovered button's box,
#view-settings' rect/scrollHeight/clientHeight/overflow, and what
elementsFromPoint finds under the pointer. Nothing in the app changed.

Why not a fix: no cause was found. It passed every way tried at fe4295e1d,
28aac86bc and 98b5a02d1, in both engines: 120+ runs, alone and 4-5 in
parallel, inside a 21-file GUI batch, under CDP CPU throttling 4/10/20x,
with faked clocks, LANG C/en/zh/ja, TZ UTC/LA, a main-thread block before
the wheel, and wheel latching. Measured: #view-settings is the only
scroller under the pointer in en and zh; #trayLogosRow is already in view
at scrollTop 0, so the test rests on the wheel alone. The one injection
that reproduces "stays at 0" is a wheel handler busy for 300ms: the
scroll then lands after readerScrolls' 250ms window and the scroll guard
puts it back. That fails en and zh in both engines, so it does not
explain zh-Chromium-only; it is a lead, not the cause.

Run: tray-logos, tray-bird, tray-cell-click, tray-inuse,
tray-usage-redraw, tray-usages, models-add-and-icons, plugin-own-icon,
routing-log-icons in chromium and webkit, all pass. The new failure
message checked by breaking the wheel (300ms busy wheel handler): it
fails with tops all 0, no refused warning, and the button over the view.
Not run: the full GUI suite; Windows/Linux.

* gateway, gui: the web searcher picked in Settings is never handed on to another provider, and one that answered without searching is said so (Gearclickist on Discord)

Cause: Gearclickist picked the Grok subscription's grok-4.7 in Settings ›
Web search. Their grok rows were about 1.3k tokens. That is the size of a
Grok request that ran no search. With the tool and searching, our real
Grok account gives 6k-66k input every time, and /models says
supports_backend_search for all four models. So on their account Grok
answered from what it knew. searchWith read that as "found nothing", and
modelSearch handed the search to the next of Searchers() by rank: Codex's
gpt-6-astra, a pricier subscription model they never picked.

Change:
- modelSearch: a searcher named in Settings gives way to no other
  provider. Its error goes back to the model ("no other provider searches
  in its place"), and webSearch then asks the search APIs, if any are set
  up. Automatic keeps its fallback (#669) with the Routing row that says
  why.
- searchWith tells a reply with no server_tool_use or
  web_search_tool_result (errNotSearched) apart from one that searched and
  named no page (errFoundNothing). CallFor gets notSearched.
- namedFailed/SearcherFailed keep the named searcher's last failed search,
  cleared by its next success or by picking another searcher.
  /api/settings returns it as searchFailed.
- Settings › Web search puts a warning at the start of the row's help
  (before the ellipsis) naming the searcher, when, and why ("answered
  without searching the web, so its account or plan may not offer web
  search"). The help text now says a picked provider is never replaced by
  another provider. The Routing row (kindWhy) says not-searched too.
  zh, zh-TW, ja and de strings added.
- docs/subsystems/gateway-routing.md rewritten for the rule.

Run (worktree on origin/main fd0359233):
- Real Grok account (sandbox, requests only): grok-4.x with the
  web_search tool searched each time (6k-66k input, cache 3456). Without
  it, about 1.3k input, cache 1152, which matches the reporter's rows.
- go test -tags nogui ./internal/gateway ./internal/gui: ok.
- gofmt -l is clean. go vet passes on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- Broken by hand, the tests go red:
  - Dropping the no-handover rule turns TestPickedSearcherIsNotHandedOn
    and TestSearcherFindingNothingGivesWay red.
  - Dropping the !searched check turns the NotSearched assertions red.
  - Reverting app.js/routing.js turns the new searcher-pick and
    search-instead cases red.
- GUI (playwright 1.62.0), chromium and webkit, every language, widths
  560 and 1000: search-instead, searcher-pick, i18n-keys, settings-search,
  provider-search, search-api, search-first and search-mcp all pass,
  except searcher-pick's "search help preserves ellipsis and hover titles"
  on webkit en/ja/de. That case is red on origin/main too (#1745).

Not run or not changed:
- The reporter's own account wasn't reproducible, so why Grok skipped the
  search there isn't known.
- No change to the Grok plugin or the built-in: supports_backend_search
  is true for every model, so reading it wouldn't have caught this case.
- Not tried on Windows or Linux GUI.

* gateway: Codex's spawn_agent names every model also when Codex hands it to the lead through a tool search, as it does on 0.162 (Gearclickist on Discord)

Gearclickist, after v0.1.1214: the lead still saw only five models for
its subagents. v0.1.1214 (5d33f060b) widened spawn_agent in the request's
tools only. Codex 0.162 doesn't put it there for a model that can search
tools: with supports_search_tool the multi-agent V1 tools are Deferred
(codex-rs rust-v0.162.1 core/src/tools/spec_plan.rs:1475-1479), the lead
calls tool_search, and spawn_agent, with Codex's five
(core/src/agent/child_config.rs:20 MAX_SPAWN_AGENT_MODEL_OVERRIDES = 5,
used in core/src/tools/handlers/multi_agents_spec.rs:830), arrives in a
tool_search_output item in the conversation. Codex resends that item on
every later turn. magpie's /models entries and Codex's own say
supports_search_tool, so this is the usual case, and the fix never fired.

The limit is only in what Codex writes. find_spawn_agent_model_name
(child_config.rs:318) takes any model of the catalog Codex loaded; the
five also appear in its error text (child_config.rs:335).

spawnAgentModels now widens the spawn_agent in each tool_search_output
in input as well as in tools (moreSpawnTools, shared by both). The added
text is unchanged and stays neutral; base_instructions are untouched.
The same output is widened the same way on each turn, so the history
Codex resends stays byte-stable.

Run:
- Real Codex 0.162.1 in a sandbox HOME/CODEX_HOME, wired by a sandbox
  magpie (`magpie codex fake/m1`, gateway on 127.0.0.1:3593) to a fake
  Responses upstream with 40 models that calls tool_search, then
  spawn_agent with model fake/m12.
  - Before: the lead's searched spawn_agent named fake/m1..m5 only.
  - After: it names all 40, Codex's five then the other 35 under the
    added header.
  - Both times Codex accepted fake/m12 and the child's request reached
    the upstream on m12.
  - The same Codex pointed straight at the fake (no magpie) gave the raw
    request saved as testdata/workdir/codex-0.162.1-tool-search.json
    (sandbox paths replaced).
- TestSpawnAgentNamesEveryModelAfterToolSearch (/v1, CodexPath with a
  magpie lead, CodexPath with a ChatGPT lead and V1) fails on the old
  codex_spawn_models.go in all 3 subtests ("doesn't name fake/m6") and
  passes now.
- go test ./internal/gateway -count=1 under a sandbox HOME: ok.
- gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=linux -tags
  nogui, GOOS=windows.

Not run: a real ChatGPT-account lead at CodexPath (covered by the stub
backend test only), the Codex App, and a V2 lead (V2 keeps spawn_agent in
tools, which v0.1.1214 already covers).

* gui: Settings › Network's Proxy line says it holds for requests to vendors without a proxy of their own (#1832, wfb835)

Off and Auto-with-no-system-proxy said requests to vendors "go direct", and a
proxy set here said they "go through" it. Neither is true for a provider,
account or key that names its own proxy (or Direct): netproxy.With keeps
that whatever this row is set to. The three lines now say they cover
requests to vendors without a proxy of their own, and update checks, in
en, zh, zh-TW, ja and de. "Following the system proxy" and "Following
HTTPS_PROXY" name where the proxy came from and are left as they are.

Run: tests/proxy-own-wording.test.cjs (new) in chromium and webkit, all
five languages, at 900px and 420px, for Off, none found and a proxy set
here: exact #proxySub text, and no overflow from the longer line. 22/22 pass;
with app.js and i18n.js put back to 5b8708742 it fails on the old wording.
gui-zh-tw and gui-de pass; gui-ja is red on origin/main for a Hooks string
from e3a497d7a, fixed in its own commit next.

* gui: a subscription account in Routing's Accounts and keys shows each of its windows and when each resets, as the Usage page read them (#1833)

The list said one figure for an account, the window routing went by. A
Claude account's 5 hours and 7 days, or Codex's, each with its reset, are
now on a line under it ("5 hours 40% used · resets in 2h"). cardOf matches
the route's account to app.js's quotas: a subscription card of this
computer (no from) whose provider is the account's agent (a plugin's
provider id) or its provider, and whose user is the account's, ignoring
case. Nothing new is read from vendors: opening Routing asks
/api/usage/quotas in the ordinary way when the readings are missing or
over a minute old, never ?asked=1. A kept day's list shows none, as its
requests were weighed by readings long gone.

loadQuotas now treats an answer that isn't a list of cards as a failed
read and keeps what it had. Routing reading quotas showed it: a page given
{} stored it and renderQuotas threw on quotas.some.

docs/subsystems/gui-shell.md: Routing account windows.

Run: tests/routing-account-windows.test.cjs (new), chromium and webkit,
en, zh, zh-TW, ja, de at 1100 and 420px: exact window lines, none for an
account whose only card is another computer's, no overflow, no asked
read. 22/22 pass; fails with app.js, routing.js and routing.css as
before. Looked at in a screenshot at 1100px (en) and 420px (de). All 60
routing-*.test.cjs and click-scroll: 636 pass, 5 fail, all in WebKit in
routing-group-fold (en, ja, de) and routing-sessions (en), which fail the
same alone on the old assets at 7a9490638 and are filed as #1672.
Not tried with a real Claude or Codex account.

* gui: Routing's Accounts and keys has a refresh beside its heading that reads the accounts' allowances again, by hand only (#1834)

The windows each account shows (#1833) are the Usage page's readings,
read the ordinary way when Routing opens. To see them fresh one had to go
to Usage and back. The icon button beside "Accounts and keys" makes the
asked read Usage's Refresh now makes (loadQuotas(true),
/api/usage/quotas?asked=1). It turns while the read is on its way, a
click then asks nothing more, and the rows are drawn from what comes
back. There is no timer: nothing reads again by itself, as #1518 has
allowances read only when asked. It shows only live, with a subscription
account listed. Its tooltip is new ("Read the accounts' allowances
again", in zh, zh-TW, ja, de), and its label reuses "Refresh now".

docs/subsystems/gui-shell.md: under Routing account windows.

Run: tests/routing-read-allowances.test.cjs (new), chromium and webkit,
en, zh, zh-TW, ja, de at 1100 and 420px: title and label, on the heading's
line, opening reads only unasked, one asked read on click with the
button busy until it lands, a second click while busy asks nothing, the
windows show the new reading, the view doesn't move, and no asked read
in 2.5s after. A list of keys only has no button. 24/24 pass, and 11 of 12
fail with routing.js, routing.css and i18n.js as before. gui-ja,
gui-zh-tw, gui-de, i18n-keys and routing-account-windows pass. Looked at
in screenshots at 1100px (en) and 420px (ja). Not tried with a real
account.

* gui: an account's seat on the Routing stage tells each of its windows and when each resets in its tooltip (#1835)

A seat on the stage says the fullest window's figure while idle
("40% used · renews in 2h"), and what it is doing while it answers. The
other windows, and their resets, weren't anywhere on the stage. Its
tooltip, which held only its id, now adds one line a window, the same
lines Accounts and keys shows (winsOf, the Usage page's readings,
#1833). It is a tooltip rather than a second line on each seat because
the stage is the live picture of a request, and a line more on every
seat would crowd it. Live only.

docs/subsystems/gui-shell.md: under Routing account windows.

Run: tests/routing-seat-windows.test.cjs (new), chromium and webkit,
en, zh, zh-TW, ja, de at 1100 and 420px: the answering seat's title is
its id and both windows, and the seat whose only card is another
computer's keeps its id alone. 22/22 pass, and 11 of 11 fail in chromium
with routing.js as before. Not tried with a real account.

* gui: the Library's Select bar removes the skills, servers or hooks picked, a whole group at once with its header's box (#1852)

What: Select's bar on the skills, servers and hooks pages gets Remove…
(red, beside Clear). It asks first, as Remove all does, naming the count
("Remove 3 skills?", or "Remove pack-a?" for one), and posts only the
picked names to the existing remove-all endpoints (RemoveSkills /
RemoveServers / RemoveHooks), so each goes exactly as its row's Remove
would: same backups, only magpie's own copies. A group's or part's header
box (already there in Select) picks the whole group, so an outdated group
goes in one step. Groups have no menu, so no "Delete group…" item was
added.

A name that wasn't removed stays picked, its row's second line shows
"Not removed: <error>" in red, the status names it ("notes removed ·
stuck wasn't removed: …"), and nothing reports success for it. When every
name fails the endpoint answers 400: the sheet stays open with its button
enabled again. The label stays "Remove…" whatever the count (the count is
beside it and in the sheet): "Remove 3…" rewrapped the bar at 440px in
ja and moved the box under the pointer (library-servers-bulk caught it).
No Go change: the batch removals already reported Unremoved per name.

Strings in zh, zh-TW, ja, de. docs/subsystems/library.md says it.

Run: new internal/gui/tests/library-pick-remove.test.cjs (Playwright
1.62.0, chromium and webkit, en/zh/zh-TW/ja/de, 1100 and 390 px): group
box picks 3, Cancel posts nothing, Remove takes 3 and leaves the rest, a
partial failure keeps the failed one picked with its error, a total
failure keeps the sheet; every click checked for no scroll and nothing
moving. Red by hand: dropping every name from picked after a partial
failure, and dropping the partial-failure status. With it, both engines:
library-servers-bulk, library-hooks, i18n-keys, gui-de, gui-ja,
gui-zh-tw, click-scroll, group-pick-filter, remove-found-skill,
library-items, remove-all-skills: 60/60 pass. library-servers-bulk
chromium failed once in a parallel run, then passed 3/3 alone and 2/2 in
the same parallel run on this tree and on origin/main.

Not run: pick-skills.test.cjs is red in webkit (en, zh: the click on the
"pdf" row times out) on origin/main 6669d497d without this change too,
the same as before; chromium passes. Not tried in the real app.

* readme: sponsor logos at 36px, up from 26px

The owner found the README sponsor logos too small. 36px is the
APINEBULA SVG's own size (143x37), about 139px wide: clearly bigger
than the 20px badges above it, still well under the 112px icon, and six
logos at this height fit one row in the 900px column. Both READMEs.

* gateway, provider, gui, cli: a key+URL provider may be sent the agent's own User-Agent in place of magpie's (#1851)

Every forward went with User-Agent magpie/<version>. A coding plan that
serves only the agents it names (pi, OpenCode, Claude Code…) knows them by
their User-Agent, so it turned magpie away.

What changed
- provider: PassUserAgent (passUserAgent in providers.json), off by
  default. PassesUserAgent takes it only for a key+URL provider: never a
  signed-in account, a plugin's, or a vendor whose own client magpie goes
  as (OwnClient: OpenCode, Cline, Kilo, another magpie). A copy keeps it.
- gateway: userAgentFor in forwardOnce (chat, Anthropic, Responses,
  Gemini, count_tokens) sends the inbound User-Agent unchanged where the
  provider passes it on. It sends magpie's where it doesn't, where the
  agent sent none, and on magpie's own requests (magpiesOwn: magpie/…,
  magpie-router/vision/search, the image tool's "<client> magpie-image/1",
  which is built from MCP clientInfo, not a User-Agent). magpie never
  invents another client's. The claude-cli/Codex header copies, the
  OpenCode/Cline/Kilo overrides and account signing run after it as
  before, and the user's header.User-Agent is put on at signing, so it
  wins.
- gateway: embeddings, images and videos (retrieveFrom, sendWith,
  remoteVideoContent) now stamp the same for a key+URL provider through
  stampUA, from the caller's User-Agent kept on the request ctx
  (caller.ua, withCaller). Before, they went with Go's default
  (Go-http-client/1.1). Account and remote-magpie paths are untouched.
- cli: `magpie provider set <id> user-agent=agent|magpie`, refused for a
  signed-in account; `magpie provider <id>` shows it.
- gui: the provider editor's User-Agent row, "Send the agent's own
  User-Agent", with an explanation, for a provider with a key only (the
  JSON says ownClient for presets and providers); en/zh/zh-TW/ja/de.
  The TUI only adds presets, so it has no field for this.
- docs: reference.md (provider set) and subsystems/gateway-routing.md.

What was run
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 ./internal/gateway ./internal/provider ./internal/cli
  ./internal/gui: all ok (sandbox HOME, private GOCACHE).
- TestUserAgentPassedOn covers 7 routes (messages, count_tokens, chat,
  responses, gemini, embeddings, images) x off / on / on with no UA / on
  with magpie-router/1 / on with the image tool's UA / the user's header
  with it on and off. TestUserAgentAccountUntouched: a Factory account
  with passUserAgent in providers.json is still asked as factory-cli/.
  Also TestUserAgentClaudeCodeAsBefore, TestUserAgentFor,
  TestPassesUserAgent, TestAddCopyPassUserAgent, TestProviderUserAgentPair.
- Broken by hand, each went red: forwardOnce back to magpie's UA (5
  routes red); stampUA removed from embeddings/draw (both red, seen as
  Go-http-client/1.1); PassesUserAgent ignoring accounts/OwnClient;
  magpiesOwn dropped (the internal UAs leaked on all 7 routes); the GUI
  row shown for OpenCode and Save not posting it.
- provider-user-agent.test.cjs: 60/60 in chromium and webkit, en, zh,
  zh-TW, ja, de, at 900 and 440 wide. The provider/editor/add/i18n GUI
  tests in chromium: 244/244.

Not run
- Not tried against a real coding plan that checks User-Agent, nor with a
  real agent through a live gateway. Videos have no test of their own
  (they go through sendWith, which the images test covers).
- The GUI suite was not run in full; the Windows box was not used.

* gateway: a Grok subscription draws any grok-imagine-image* named bare, and makes any grok-imagine-video* (#1857)

A bare grok-imagine-image-2.0 on /v1/images/generations got 404 "magpie
knows no model ... to draw with", while grok/grok-imagine-image-2.0 drew:
a bare name was looked up only in grokDrawers, a fixed list of two. The
same held for a bare video name not in grokVideoModels, though with the
provider named videosCreate already took any grok-imagine-video*.

What changed
- draw.go: resolveDrawing, after an exact match in any provider's
  Drawers, sends a bare name of a subscription's image family to it
  (drawsFamily): grok-imagine-image* on a Grok subscription, gpt-image-*
  on a ChatGPT account (the sibling list, codexDrawers). The vendor draws
  it or refuses it in its own words. Exact matches still win, so an API
  key that lists the model keeps it; a name of no family is still 404.
- drawing_route.go: Codex's per-turn preferred provider takes the same
  family match.
- video.go: bareVideomaker takes any grok-imagine-video* on a Grok
  subscription, matching what videosCreate takes with the provider named.
- AutoDrawer and AutoVideomaker are unchanged (still the listed models).
- A moved Grok user goes through this same gateway code (drawsGrok covers
  the plugin's provider; the plugin only signs), so the Grok plugin needs
  no change and the mover's min stays.

What was run
- New TestGrokDrawsANewerModelByItsBareName (the reporter's request),
  TestCodexDrawsANewerModelByItsBareName, a bare grok-imagine-image-2.0
  in TestGrokPluginDraws (plugin parity) and grok-imagine-video-2.0 in
  TestVideoModelByItsBareName. With the family match switched off by hand
  all four fail with the 404 "magpie knows no model"; restored they pass.
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui,
  GOOS=windows; go build on darwin, linux (nogui), windows.
- go test -tags nogui -count=1 ./internal/gateway/... ./internal/imagemcp/...
  ./internal/provider/...: ok (sandbox HOME, private GOCACHE).

Not run
- Not tried against a real Grok or ChatGPT account: the request sent is
  the one the reporter already drew with as grok/grok-imagine-image-2.0;
  only which provider a bare name resolves to changed. Whether chatgpt.com
  serves any other gpt-image-* is the vendor's to answer.
- The full go test ./... was not run.

* gateway: a Codex subagent refused for a sealed task is told the task itself is sealed, which fork_turns="none" doesn't change (#1855, hanekoo)

hanekoo's Codex Desktop lead on gpt-6.1-sol (Codex's own ChatGPT sign-in)
spawned a subagent on antigravity/gemini-3.8-flash with fork_turns="none"
and got the sealed-task refusal, which read as if the lead's turns were
the problem and fork_turns="none" should have avoided it.

What Codex rust-v0.162.0-alpha.17.2 sends (read from its source, not the
reporter's bytes, which aren't available): spawn.rs's fork_mode is None
for "none", so no turn of the lead's is copied in. The subagent's task is
spawn_agent's `message` argument; the ChatGPT backend returns it sealed
(the function call's encrypted_function_args), router.rs's direct_source
makes it ToolCallSource::Direct, agent_message_from_tool makes it
AgentMessage::Encrypted, and to_model_input_item writes it as the
agent_message's encrypted_content under the NEW_TASK header. So the one
sealed thing in the subagent's first request is the task itself: there is
nothing magpie can leave out and still give the subagent work, and no
request flag in Codex asks the backend for plaintext arguments. The
refusal stays; it now says why.

- codex_backend.go: sealedTaskItself, added to all three sealedTaskError
  variants (lead unknown / Codex's own sign-in, a relay that sealed it,
  plugins#70's earlier chat provider): what is sealed is the task the
  spawning agent wrote in spawn_agent, and fork_turns="none" keeps only
  the lead's turns out, not the seal. The existing advice (the lead's
  model for the subagent, or a lead not on the ChatGPT backend) stays.
- docs/subsystems/gateway-routing.md: the same, under sealed tasks.
- sealed_fork_none_test.go: the fork_turns="none" first request rebuilt
  from Codex's source (developer + environment_context + the sealed
  NEW_TASK with Task name/Sender lines), a lead first on Codex's own
  sign-in, the subagent on a chat provider. It is refused before the
  provider is asked, with no ciphertext in the reply, and says the task
  itself is sealed whatever fork_turns says.

Run: with the old codex_backend.go put back,
TestSealedTaskWithForkTurnsNoneSaysTheTaskItselfIsSealed fails ("the
refusal doesn't say the task itself is sealed whatever fork_turns
says"); with the change it passes. gofmt -l (empty), go vet / GOOS=linux
-tags nogui / GOOS=windows go vet ./internal/gateway, go build, GOOS=linux
-tags nogui and GOOS=windows go build ./..., go test -tags nogui
./internal/gateway (ok, 353s) under a sandbox HOME with a private GOCACHE.

Not run: the whole `go test ./...` (only the gateway package changed);
no real Codex Desktop or ChatGPT account was used, so the reporter's
bytes are not reproduced; the GUI's sealedKept text is unchanged. The
502 "context canceled" on gpt-6.1-sol in the report is Codex's own
sign-in request most likely cancelled by Codex itself (the client went away), a separate
request, and wasn't chased.

* site: every sponsor link goes through usemagpie.ai/go, so its clicks are counted per place

The home page's "Sponsored by" cards and the READMEs' Sponsors logo linked
the sponsors directly, so nothing told the owner how many clicks each seat
brought. They now link /go/<id>/home and https://usemagpie.ai/go/<id>/readme.
site/sponsors.js holds where each sends the browser (the sponsor's own ref
link, unchanged: APINEBULA has one per place). The worker counts a GET as
"magpie sponsor go" {id, where, country} in PostHog, beside the in-app
partners' "magpie partner go" (whose /go links were already counted), and a
HEAD goes on uncounted. A partner's keys/site links are tried first; a
sponsor link takes no region.

A test fails if index.html or either README links a sponsor's own URL
directly, or names a /go link sponsors.js doesn't have.

Run: node --test site/worker.test.mjs (20 pass) and site/install.test.mjs
(10 pass). Broke it by hand: README.zh-CN.md back on the direct link turns
the guard red. Deployed (version e4f40cff); curl on usemagpie.ai:
/go/apinebula/readme → 302 apinebula.ai/ref/qmXqFGpr, /go/apinebula/home →
302 apinebula.ai/ref/Gs54HwyB, /go/yylx/home → 302 yylx.io/?ref=magpie,
/go/yylx/readme and /go/apinebula/home/x → 404; / and /zh/ serve the /go
hrefs. Not checked: the events arriving in PostHog (the worker's key can't
read).

* library, gateway: an MCP server magpie is signed in to no longer shows "Signed in" beside "needs sign-in" (新v学员 on Discord)

What was wrong, reproduced in a sandbox HOME with mcpauthtest's fake OAuth
server behind a sandbox magpie:

- A server no agent has is checked only on a click (#1597). Clicked before
  its sign-in it said "needs sign-in"; after signing in, the page rechecked
  only servers in use, so the row kept that result beside the new "Signed
  in" tag. The page now rechecks any server it has a result for once its
  key (sign-in included) changed.
- The check sent magpie's token but never renewed it on a 401, so an
  expired access token with a good refresh token read "needs sign-in"
  beside "Signed in". checkHTTP now renews once and asks again, as the
  gateway's relay does.
- A server that refuses even a just-renewed token was still "Signed in".
  mcpauth.Rejected marks such a sign-in run out, from the check and from
  the gateway's /mcp/<name> relay; ServerHealth.SignIn carries the status
  back (only for a server magpie has a sign-in record for) and the row's
  tag turns to "Sign-in ran out".

mcpauthtest.Fake gains RefuseTokens for the last case.

Run:
- go test -tags nogui ./internal/mcpauth/... ./internal/library
  ./internal/gateway (HOME and GOCACHE in scratch): ok.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on the
  touched packages: clean.
- New TestCheckRenewsMagpiesSignIn, TestCheckSaysSignInRanOut,
  TestMCPProxyRefusedAfterRenewalRunsOut. Broken by hand: renewal removed
  from checkHTTP, Rejected removed from the check, and from the gateway;
  each went red.
- New mcp-signin-health.test.cjs: Chromium and WebKit, en/zh/zh-TW/ja/de,
  1100 and 390 wide, 22/22. Each of the two library.js changes reverted
  on its own: 0/11 in Chromium. library-mcp-health, mcp-signin and
  i18n-keys pass.
- Sandbox repro before and after with the fake server: both cases now
  show one tag; forget+revoke shows "Sign-in ran out · needs sign-in".

Not run: a real vendor's server refusing a renewed token; the fake stands
in for it.

* gui: Cancel in an MCP server's editor leaves the server as saved, after a Sign in too (新v学员 on Discord)

GitHub's remote MCP server, brought in from CC Switch with its token as an
Authorization header: removing the header, picking Sign in, then Cancel
(even with Discard asked and picked) left the header removed in
library.json and every agent's file.

Cause: Sign in calls ready(), which saved the whole form whenever its name,
transport, URL or headers differed from the saved server. The sign-in
(mcpauth.Start) uses only the name and URL, so the headers never needed
saving for it. Now ready saves only when the sign-in is to another server
than the saved one (new, name, transport or URL changed); the button then
reads "Save and sign in" (zh, zh-TW, ja, de), and what it saved becomes
the form's saved state, so Cancel doesn't offer to discard what is already
written.

Audited the page's other sheets for the same thing: the hook editor,
paste-many, the server sheet, the skill how-to, By agent (Done only) and
the confirm dialogs save nothing before their own Save. Env and command
arguments in this editor only ever saved through Save; the new test
covers them too.

Run:
- New mcp-editor-cancel.test.cjs: Chromium and WebKit, en/zh/zh-TW/ja/de,
  1100 and 390 wide, 22/22 twice. Broken by hand each: the old
  headers-count rule, the saved state not updated after the save, and
  the button not saying it saves; each 0/11 in Chromium.
- mcp-signin (updated for the new label), mcp-signin-health,
  library-mcp-health, library-mcp-copy-config, library-servers-bulk,
  library-env-refs, i18n-keys, ux-safety: pass.
- library-mcp-tools and library-mcp-tool-switch have WebKit reds (the
  footer over the clicked switch) that come and go, 1 to 7 per run, the
  same with this commit's parent's assets.
- Sandbox HOME, rebuilt magpie web: header removed, Sign in (GitHub
  answered with its no-registration refusal), Cancel, Discard: the
  header is still in library.json and ~/.claude.json, and no save
  request was sent.

* library: an MCP server whose sign-in has no client registration (GitHub's) is signed in to as the user's own OAuth app (新v学员 on Discord)

What changed: GitHub's remote MCP server (api.githubcopilot.com/mcp/)
points to https://github.com/login/oauth, whose metadata has no
registration_endpoint, so magpie's sign-in, which always registered
itself (DCR), could never sign in to it. A server now carries an
optional OAuth app, `oauth: {clientId, clientSecret, callbackPort}`,
Claude Code's names for --client-id/--client-secret/--callback-port
(oauth.clientId in its .claude.json). mcpauth.StartWith signs in as
that app without registering: PKCE S256, a loopback callback
http://127.0.0.1:<port>/callback (any port unless callbackPort is set),
client_secret_post with a secret (basic only when the server lists
basic alone), "none" without one.

Without an app, a server with no registration endpoint now fails with
mcpauth.ErrNoRegistration, which says to make an OAuth app with the
vendor (GitHub's under Settings > Developer settings > OAuth Apps, with
http://127.0.0.1/callback) and give it under "OAuth app" in the editor.
The editor opens those fields with Client ID focused when that error
comes back. Filling them makes Sign in read "Save and sign in", and
Cancel asks before dropping them, as the earlier Cancel fix does.

GitHub answers token errors with 200 and {"error": ...}; tokenRequest
now reads a 2xx body with `error` as the error, and bad_refresh_token /
incorrect_client_credentials count as a dead sign-in as
invalid_grant/invalid_client do.

Secrets: the client secret sits in library.json like header and env
values. A backup without keys blanks it; WithSecrets puts this
computer's secret back only for the same client ID. No agent file is
given the app. The TUI editor, which doesn't show it, keeps it on save.
check() keeps it only on an HTTP server, requires a client ID when a
secret or port is given, and a port 1-65535.

Run (worktree at 98b5a02d1 + the two earlier commits):
- go test -race ./internal/mcpauth/... (new github_app_test.go: an
  httptest fake built from GitHub's real PRM and AS metadata bytes:
  no app -> ErrNoRegistration, sign-in as the app, wrong secret, fixed
  callback port, bad refresh token)
- go test -tags nogui ./internal/library ./internal/tui ./internal/gui;
  go test ./internal/gateway -run MCP
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
- GUI, Chromium and WebKit, 1100/390, en zh zh-TW ja de:
  mcp-oauth-app (new, 22/22), mcp-editor-cancel, mcp-signin,
  mcp-signin-health, library-mcp-health, i18n-keys - all pass
- Broken by hand, each went red: no 2xx error parse, GitHub codes out
  of dead(), app ignored in StartWith, secret not blanked / not matched
  by client ID in carry, check() without the non-HTTP rule; in the GUI,
  oauth left out of the save, and the failed hook not opening the fields.
- Sandbox HOME, rebuilt magpie web, against the real GitHub server:
  Sign in showed the new error and opened the fields; Save and sign in
  saved the app and produced a real github.com/login/oauth/authorize
  URL with the app's client_id, S256 and a 127.0.0.1 redirect, which
  GitHub answered with its login page. .claude.json didn't hold the app.

Not run: a real GitHub sign-in to completion. There's no real OAuth app
to use, and I didn't make one on the owner's account. Claude Code's
callback says localhost where magpie's says 127.0.0.1, so an app made
for Claude Code needs its callback URL changed; that isn't bridged.

* gateway: an item a batch's tool results were interrupted by goes after them, so strict Responses upstreams stop refusing the relayed request

What: the normalization a relayed Responses request goes through before it
leaves (gateway.go, attempt) gains joinToolRuns beside orphanedToolOutputs
and pairToolItems: an item that sits inside a run of tool calls and results
- between a call and the result that answers it - is moved to the end of
that run. A run is open while one of its calls has been seen and the result
answering it is still ahead, so an item between two whole exchanges stays
where it is. Codex writes such an item itself: when a tool returned an
image it resized, its <image_resize_notice> goes between one batch's two
results (the report from the Codex app on Windows, one assistant step with
view_image and exec_command).

Before, the run reached the upstream with the item inside it and a strict
one refused the whole request with 400: Volcengine's Agent Plan "An
assistant message with 'tool_calls' must be followed by tool messages
responding to each 'tool_call_id'", OpenCode Zen/Go "No tool output found
for tool call <id>" - both naming a result that is in the request. After,
the results follow the calls, the item goes after them, and both answer
200. This is the rule the chat path has had since #1275 (pairToolMessages
closes a run with its results, interrupted ones included, before another
message) and the same family as #1341 (pairToolItems, a call nothing
answers), and it is applied before the request is relayed or translated,
so every destination whose own form is strict gets it in the same change.

The item's own bytes, its role and its order among the other non-tool items
are as they were. A request with no tool items, one whose exchanges are each
whole, and a body that is not a Responses request come back byte for byte
(TestJoinToolRunsLeavesWholeExchangesAlone). One expectation changed on
purpose: TestGrokGetsAgentMessageAsUser's turn holds a subagent's reply
between the send_message call and its output, and Grok is now given that
reply after the run. Its conversion is unchanged (same user message, same
"From <author> to <recipient>" header, same text and images) and only its
place moved, the way every other item Grok is handed keeps the place magpie
gave it; a review that knows Grok's backend needs the reply in place can
narrow the rule to messages other than agent_message.

Run:
- go test -tags nogui ./internal/gateway/: 2 failures, both red on
  origin/main 6c1c0a7 as well and neither from this change -
  TestClaudeAsRootEnv (a Linux-only expectation with no Windows guard) and
  TestSweepBridgeProjectsTakesOnlyTheBridgesFolders (needs a symlink
  privilege this Windows box doesn't hold). Everything else passes,
  TestQueuedStreamKeptAliveOnceSentToItsVendor among them (that one failed
  once on main under load; it is the queued-stream timing in the standards).
- the same run under a temporary HOME with GOPATH/GOMODCACHE/GOCACHE pinned
  from go env: the same two failures.
- gofmt -l on the four changed files: nothing. go vet ./..., GOOS=linux go
  vet -tags nogui ./..., GOOS=windows go vet ./...: clean. go build,
  GOOS=windows go build, GOOS=linux go build -tags nogui: ok.
- without the change: with the one call-site line taken out,
  TestResponsesRelayKeepsAToolRunTogether prints
  `status 400: ... "Fake: An assistant message with 'tool_calls' must be
  followed by tool messages responding to each 'tool_call_id'."`; the line
  back, it passes.
- real upstreams, the reporter's shape (two parallel calls, an image
  result, Codex's <image_resize_notice>, the second result), the same build
  with the line and without it, streamed the way Codex sends it:
  Volcengine Agent Plan / deepseek-v4.1-flash - run whole 200/200; the
  notice between the results 400 "insufficient tool messages following
  tool_calls message" then 200; any other note there 400 then 200.
  OpenCode Zen/Go / deepseek-v4.1-flash - run whole 200/200; a note between
  the results 400 "No tool output found for tool call call_b" then 200; the
  notice between them 200/200, their gateway recognizing that one item.
- the reporter's own rebuilt turn (1399 items, from their rollout) to
  Volcengine: refused "insufficient tool messages following tool_calls
  message" without the change, past that check with it (what is left is the
  input's length, 1.7M tokens, over the model's limit).

Not tried: a real Grok subscription - the reply's new place is unverified
against xAI's backend, though its conversion is unchanged and its plugin
(community plugins packages/grok) converts in place the same way; a real
ChatGPT (native Codex account) destination, which takes standalone tool
outputs itself and is left as it came; the Windows GUI. The OpenCode Zen/Go
400 of the original report is not reproduced by the reporter's own bytes:
with both results and the notice between them that gateway answers 200
before and after this change, so the report's refusal may be the follow-up
body assembled before the batch's last output was in it
(openai/codex#44604).

Refs: #1341, #1275. Reported as anomalyco/opencode#54698 and
openai/codex#44604.

* gateway: joinToolRuns leaves the model's own step and every call-carrying item in place, and a result written before its call opens no run (#1752, #1822)

What: follow-up to Edward4226's joinToolRuns (previous commit), after review
against Codex rust-v0.162.1 and the code around it.

- An item carrying a call_id is never moved, whatever its type. Before, only
  function_call/custom_tool_call/tool_search_call counted as calls, so a
  local_shell_call (or any call type Codex adds) inside a run was moved after
  results, its own output's among them.
- Before the run's first result, what the model wrote between its own calls
  (reasoning, assistant text, a hosted tool's call) stays where it is. Before,
  [call_a, reasoning, call_b, out_a, out_b] sent the reasoning after the
  results, where it reads as the next step's: DeepSeek, whose step must lead
  with its reasoning (reasonFirst, f4cc7459), would get a step that isn't.
  Anything else there (a subagent's agent_message, a note) still moves after
  the run, so TestGrokGetsAgentMessageAsUser's expectation from the previous
  commit stands.
- A call opens a run only when a result after it answers it. Before, a result
  written before its call (an odd replay) left the run open for the rest of
  the request, and every later message was moved to its end.

Where it happens, checked in Codex's source: prepare_response_items
(core/src/image_preparation.rs) pushes the developer <image_resize_notice>
right after each function_call_output / custom_tool_call_output whose image
it resized, so a batch of two image results has it between them, as #1822's
rollout shows (lines 347-349).

Routes: joinToolRuns sits in attempt before every destination, so the
Responses relay, plugins (relayed through passthrough) and translations all
get it. Translations rebuilt the order themselves for a developer or user
item (the developer one is lifted into the system prompt, user turns merge
and results go first), but an assistant message between two results closed
the chat exchange: pairToolMessages answered the second call with the
synthetic "unavailable" result and sent the real one as user text
(TestTranslatedToolRunKeepsItsRealResults, red without the call site).

Docs: gateway-routing.md says what attempt mends in a Responses request's
tool exchanges (joinToolRuns, orphanedToolOutputs, pairToolItems).

Run:
- TestRelayedCodexImageBatchKeepsItsResultsTogether (#1822's call ids, two
  view_image results, the notice between; the fake answers DeepSeek's "No
  tool output found for tool call …") and TestTranslatedToolRunKeepsItsRealResults
  fail with the call site removed (400 / synthetic result) and pass with it.
  TestJoinToolRunsOnlyMovesWhatBreaksARun fails on the previous commit's
  joinToolRuns (reasoning moved, local_shell_call moved, a request rewritten
  for a result before its call) and passes now.
- go test -tags nogui -count=1 ./internal/gateway/ under a sandbox HOME with
  a private GOCACHE: ok (376s). gofmt -l: nothing. go vet (darwin),
  GOOS=linux go vet -tags nogui, GOOS=windows go vet on ./internal/gateway/:
  clean.
- Real DeepSeek (api.deepseek.com/v1/responses, deepseek-v4-flash), direct:
  a developer note between the two results 400 "No tool output found for
  tool call call_01_x2"; the same note after the results 200. Through a
  sandbox magpie (own HOME, :3591, only the deepseek provider), streamed and
  whole: origin/main's build 400 with that refusal, this build 200. The
  <image_resize_notice> text itself between the results is answered 200 by
  DeepSeek directly, before and after, with text results.

Not tried: OpenCode Go (this account's workspace isn't set to Global
regions, so every request there is refused before the model); the
reporter's image results and full-length history; Volcengine; a real Grok
subscription for the agent_message's new place.

Co-authored-by: Edward4226 <234070868+Edward4226@users.noreply.github.com>

* usage, gui: a Codex turn of one call is measured only over a second and 100 tokens after its first token, else told as the least it wrote over the whole turn (Fallmonkey on Discord)

Fallmonkey's repro: a Codex turn whose first token came at 6.8 s (the
model working) and the rest 0.2 s later in one network push read as
thousands of tok/s from its session file. The promised rule, now in:

- A Codex turn of one call read from its session file (source "log",
  turn TTFT known) tells a measured speed only when the window after its
  first token is 1 s or more and its body 100 tokens or more
  (usage.CodexWindowMs, CodexBodyTokens; Row.Decode, app.js ledDecode).
- The floor from e5b82cf38 for such a turn that reasoned (its answer over
  the time after the first token, "②") is held to the same threshold:
  827 ms after a 10.2 s first token no longer reads ≥329, as that window
  can be one push too.
- A turn that tells neither tells its output over the whole turn
  (Row.Floor, ledFloor_ "turn"), the wait in it, of any size: everything
  it wrote was written in that time, so it is a true floor. 380 tokens in
  6.8 + 0.2 s read ≥54 tok/s. Its tooltip says the whole turn was used and
  why, with the time after the first token (new string in en, zh, zh-TW,
  ja, de).

Gateway rows and other agents' rows keep DecodeOf as before; Codex calls
in turns of several keep the 1,000-token rule. The ledger's period sum
now adds each row after it is built (Totals.addFrom) so it uses
Row.Decode too. docs/reference.md says the rule.

Tests: TestCodexTurnMeasuredOnlyOverASecondAndAHundredTokens (new: 380
over 0.2 s after 6.8 s, 60 over 2 s, the 1 s/100 edges, gateway and
Claude rows unchanged, group, ledgerWith sum, Part) and
TestCodexRowsTellAFloor (updated cases) fail on the old ledger.go and
usage.go; the sum check fails with only the ledger closure reverted.
usage-speed-count.test.cjs: the 496/224 row now ≥45 with the whole-turn
tooltip, a 1,000-token answer over 10 s ≥100, Fallmonkey's row ≥54;
fails on the old app.js.

Ran: go test -tags nogui ./internal/usage ./internal/gui ./internal/cli;
gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
internal/usage and internal/gui; 50 GUI suites (usage-*, ledger-*,
reasoning-speed, routing-burst-speed, routing-request-metrics,
panel-usage, gui-de/ja/zh-tw, i18n-keys) in Chromium and WebKit: 506/507,
the one red usage-sum-whole chromium ja at 780px under load, reproduced
on origin/main 5c82e6880 and filed as #1864. On copies of the owner's
recent Codex rollouts (955 calls), 2 were turns of one call; one, 13
tokens 315 ms after a 4.3 s first token, moves from 41 tok/s to a floor.
Not tried with Fallmonkey's own sessions.

* gui: a window made wider or narrower keeps the reader where they were, or at the foot, while the page is laid out again, so Settings no longer ends 6px short of its foot across the sidebar's width in WebKit (#1672)

Cause: 18e82adc6 (the sidebar) added heldWidth, which lets go of what the
last click held when the window's width changes. Before it, the held
click's ResizeObserver followed the page as it grew back. text-size's
#911 case scrolls Settings to its foot and then resizes the window
across SIDE_AT (960 to 1440). In WebKit the scroll is clamped to each
layout the page passes through:
1. scrollTop goes from 120 to 46 on the resize;
2. after the side-nav swap the max is 10, so scrollTop is 10;
3. about 40ms later a part grows 6px (max 16), but nothing moves the
   scroll back.
So the page ends 6px short of its foot, and 3 of text-size's 11 subtests
fail in WebKit, run alone.

Change: on a width change, for a second, a ResizeObserver on the open
view's parts calls backToReader. The reader's own place (readerAt, still
120) is kept, or as far down as the page now goes. It doesn't act while a
click holds the page or while a purposeful scroll runs. Calling
backToReader at the end of layoutNav was tried first and didn't help,
because the growth comes after it. docs/subsystems/gui-shell.md says so.

Run (worktree on origin/main 31c1e3ab1, playwright 1.62.0, chromium-1234
and webkit-2336, each file alone):
- text-size: 11/11 in WebKit, repeated, and 11/11 in Chromium.
  Without the change 3 of 11 fail in WebKit, as on 31c1e3ab1.
- 37 files that resize the window and check scroll, or are the
  sidebar's: agent-update-all, cli-update, click-scroll, menu-scroll,
  panel-usage, sidebar*, side-toggle, sidebar-tab-top, phone-web,
  header-zoom-fit, usage-*, settings-groups and others. In both engines,
  4 at a time: 73 of 74 green.
  The one red is sidebar-overlay-scrollbar in chromium ("dragged to the
  end: 162 of 191"). It fails 1 run in 3 alone on unchanged 31c1e3ab1
  too, so it is filed as #1863.
- Under parallel load, text-size's "zh, dark: nothing runs off the side
  at 150%" sometimes fails on 31c1e3ab1 too ("ResizeObserver loop
  completed with undelivered notifications", 2 of 4 runs), and once with
  this change ("element not stable"). It passes 3/3 alone and 3/3 in
  parallel with the change. Noted on #1672.

Not run: the Windows and Linux apps, and the full GUI suite. No Go code
changed.

* gui tests: routing-sessions, pick-skills and routing-group-fold wheel to the control they press, as the reader would, since the sidebar moved it out of sight or under a bar (#1672)

Cause: 18e82adc6 (the sidebar). From 1024 points wide the page sits
beside the sidebar, and a width change lets go of what the last click
held (heldWidth). Both are intended: a sidebar like a Mac app's, and a
relayout isn't the click's doing. That commit updated the tests whose
window is 1024+, but missed these three. Each now presses a control that
is out of sight or under a bar:
- routing-sessions ("background memory groups"): after the resize from
  1100 to 560, By request is at y=902 in an 800px window, with scrollTop
  0. Before 18e82adc6 the click's hold kept scrollTop at 296, and the
  button was at y=606.
- pick-skills: pdf's row is at 683-750. That is partly under the sticky
  bar Select brings up (664-712), and the view ends at 732. Before, the
  row was wholly below the view (715-782), and Playwright scrolled it.
- routing-group-fold: with the pool open, the Team and Big folds are
  under the window's foot (en, ja, de).
The app puts back any scroll that isn't the reader's, Playwright's
included. Playwright doesn't scroll a control that is partly in sight at
all. So in WebKit the click waits ("element is outside of the viewport",
"<footer class=foot> intercepts pointer events") until it times out.
Chromium gets through some of these by a few pixels.

Change: reader.cjs gets reach(page, locator). It is inView for any
page: it wheels the control's own .view until the control is wholly
inside it and elementFromPoint at its centre is the control. The three
tests call it before those clicks. Nothing is loosened: every assertion
is unchanged, and the press is still a real click on the control.

Run (worktree on origin/main 31c1e3ab1, playwright 1.62.0, each file
alone):
- routing-sessions: 19/19 in both engines. Before: 18/19 in WebKit.
- pick-skills: 3/3 in both. Before: 0/3 in WebKit.
- routing-group-fold: 20/20 in both. Before: 17/20 in WebKit.
- The bisect for each lands on 18e82adc6.
- inView and every other export of reader.cjs is unchanged. The 37
  resize/scroll files, several of which use inView, are green apart
  from #1863, which fails on 31c1e3ab1 too.

Not run: the full GUI suite.

* gui tests: library-mcp-tools wheels down to Check again, which the Hooks tab put under the window's foot at 420 in German

Cause: e3a497d7a (Hooks, a fifth Library category). It is intended,
since Hooks were asked for (#1790). The new tab adds a row to the
Library's head at 420 points wide in German, which pushes the tool
list's Check again button under the window's foot. The app puts back
Playwright's own scroll, as any scroll that isn't the reader's, so in
WebKit the click times out. Bisected with the test: green on
e3a497d7a^, red from e3a497d7a.

Change: wheel to the button with reader.cjs's reach before the test
reads the scroll and presses it. The test's assertions are unchanged:
the list stays and the scroll doesn't move while it checks.

Run (worktree on origin/main 31c1e3ab1, playwright 1.62.0, alone):
10/10 in chromium and webkit. Before: 9/10 in webkit.
Not run: the full GUI suite.

* gui tests: profile-in-use wheels down to the profile chips and Apply, which the Get started card put past the window's foot (#1853)

Cause: 3e88fc09d. Its diff also brought in the Get started card (per
#1825), which is intended. In profile-in-use's window case (1100 wide,
460 high) the card pushes the profile chips and the detail's Apply past
the window's foot. The app puts back Playwright's own scroll, so in
WebKit "<footer class=foot> intercepts pointer events" until the click
times out. Bisected with the test: green on 3e88fc09d^, red from
3e88fc09d.

Change: wheel to the chip and then to Apply with reader.cjs's reach
before each click. The assertions are unchanged.

Run (worktree on origin/main 31c1e3ab1, playwright 1.62.0, alone):
11/11 in chromium and webkit. Before: 5/11 in webkit.
Not run: the full GUI suite.

* gui tests: searcher-pick wheels down to the web search row, which Image recognition's MCP address put past the window's foot (#1745)

Cause: 6c1c0a747. It made image recognition an MCP server of magpie's
own, and added its address row (#visionMcpRow) to Settings › Models.
That is intended. In the "search help preserves ellipsis and hover
titles" case, the row pushes the web search row past the window's foot.
The app puts back Playwright's own scroll, so in WebKit the hover times
out in en, ja and de. Bisected with the test: green on 6c1c0a747^, red
from 6c1c0a747.

Change: wheel to the row's searcher button with reader.cjs's reach
before the hover. The assertions on the help's ellipsis and titles are
unchanged.

Run (playwright 1.62.0, alone):
- On origin/main 31c1e3ab1: 6/6 in chromium and webkit. Before: 3/6 in
  webkit.
- Rebased on accc8c090, which adds searcher-pick's failed-searcher cases
  (50adf78e6, which also names this red as #1745): 11/11 in both engines.
  The other seven of #1672's files and text-size were rerun on that head
  in both engines too, all green: gui-ja, routing-sessions, pick-skills,
  routing-group-fold, library-mcp-tools, profile-in-use.
Not run: the full GUI suite.

* provider: a moved Kiro shows the model a tool's images, Codex's view_image among them (#1861)

simonsmh (v0.1.1215) saw Codex's view_image and screenshot results come
back empty on a Kiro subscription. magpie hands Kiro's plugin an Anthropic
body whose tool_result holds the image as a base64 image block, but the
plugin (@magpie-community/opencode-kiro-auth up to 0.1.8) read only a
tool_result's text, so the image was dropped and the model was told
"(no output)". #369 had fixed this in the built-in for Claude Code; the
plugin never got it.

Kiro plugin 0.1.9 (magpie-community/plugins 66facac) sends a tool's images
with the userInputMessage that answers the call, latest images only, as
the built-in does. This raises the mover's min to 0.1.9, so
keepMovedCurrent updates every moved user.

tool_images_1861_test.go builds the request from what codex-rs 0.162
sends (FunctionCallOutputContentItem, view_image's input_image data: URL
with detail "high") and checks the handoff to the plugin (the image in
the tool_result, bytes intact) and the built-in Kiro body. Both pass on
the old code too: the bug was in the plugin, whose tool-images.test.mjs
fails 3 of 4 on 0.1.8. gateway-routing.md says how a tool's images reach
the model on each translation.

Run: gofmt -l; go vet darwin, linux -tags nogui, windows on
internal/gateway and internal/provider; go test -tags nogui
./internal/gateway ./internal/provider (sandbox HOME, ok); the plugin's
bun test (1152 pass) and scripts/check.mjs; npm view on
registry.npmjs.org shows 0.1.9.
Not tried: a real Kiro account, or real Codex against it.

* gateway: Cursor's built-in shows the model a tool's images, in the message after its results (#1861)

Found while checking every translation of a tool's images for #1861.
cursorMessages wrote a tool result's text alone, so an image Codex's
view_image (or any tool) returned never reached a model behind the
Cursor built-in. Cursor's plugin already gets it, since magpie hands it
a Chat body (seeLater: the result says the image follows, and a user
message after the results carries it).

The built-in now does the same: a result with images says
"[The tool returned an image; it follows in the next message.]", and a
user message after the results holds "[From the result of <name> (tool
call <id>):]" and each image as Cursor's image block (cursorImage, the
same block a user's own image already used). gateway-routing.md names
Cursor among the translations.

TestCodexToolImageCursor, from codex-rs 0.162's view_image output, fails
on the old cursor.go and passes now.

Run: gofmt -l; go vet darwin, linux -tags nogui, windows on
internal/gateway; go test -tags nogui ./internal/gateway
./internal/provider (sandbox HOME, ok).
Not tried: a real Cursor account. Whether Cursor's backend shows the
model an image in a user message that follows tool results is taken from
how it takes a user's own image, not seen.

* mcpauth: an MCP server's own OAuth app is called back at Claude Code's http://localhost:<port>/callback, so an app made for Claude Code signs magpie in as it is (新v学员 on Discord)

What changed: accc8c090 took Claude Code's names for a server's own
OAuth app (oauth.clientId, clientSecret, callbackPort) but sent
redirect_uri=http://127.0.0.1:<port>/callback. Claude Code sends
http://localhost:<port>/callback:
- code.claude.com/docs/en/mcp, "Use pre-configured OAuth credentials":
  register http://localhost:PORT/callback; --callback-port fixes the
  port to match it. Its version note says 2.1.229 sent 127.0.0.1 and
  servers that match the registered URL exactly refused the sign-in,
  so 2.1.231 went back to localhost.
- The installed Claude Code 2.1.296 binary builds
  `http://localhost:${n}/callback` (default port 3118 / a random
  free one, MCP_OAUTH_CALLBACK_PORT) and listens on 127.0.0.1 only.
So an app registered for Claude Code at an exact-match server was
refused by magpie. StartWith now sends localhost for a user's own app
and still listens on 127.0.0.1 alone, as Claude Code does, so the hosts
don't differ and the editor needs no note. magpie's own dynamic
registration keeps 127.0.0.1 (it registers that URL itself).

The no-registration error, the editor's hint (now
http://localhost[:port]/callback), its zh/zh-TW/ja/de translations,
the OAuthApp comment and docs/subsystems/library.md say localhost.

Run:
- New TestAppMadeForClaudeCode: the GitHub-shaped fake matching one
  exact registered URL http://localhost:<port>/callback, at authorize
  and at the token request. With the old mcpauth.go it fails (as do
  the three GitHub tests now asserting localhost); with the fix all
  pass. go test -race ./internal/mcpauth/...
- go test -tags nogui ./internal/library ./internal/gui
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
- GUI mcp-oauth-app (Chromium+WebKit, 1100/390, en zh zh-TW ja de,
  22/22) and i18n-keys; with the hint's old 127.0.0.1 put back by hand,
  mcp-oauth-app goes red (0/11 Chromium).

Not run: a real sign-in with a real OAuth app (none to use). GitHub's
docs say a loopback redirect needn't match the registered port but
don't say whether that holds for localhost as it does for 127.0.0.1;
if GitHub wants the port, the user sets Callback port and registers
http://localhost:<port>/callback, as Claude Code's docs also say.

* usage, gui: revert def3a41e3 until Fallmonkey says what context it missed

Fallmonkey asked on Discord (#feedback, 10-12 19:55) to hold the
single-call Codex threshold: "先别做?感觉你漏掉context了". It is not in a
release yet, so take it off main until the rule is agreed, rather than
ship a speed rule its own requester has paused.

This reverts commit def3a41e36.

Run: gofmt -l, go vet, go test ./internal/usage.

* gui: a mono logo drawn again paints at once: each mask picture is probed once and kept on a hidden shelf (#1847)

kyya saw Command Code's logo blink in the Routing group editor on every
redraw, while the colour logos (<img>) beside it stayed put. A mono logo
is a CSS mask on a span, and icon() did two things wrong with it:

- It made a probe Image for every logo it drew, so every redraw asked for
  the file again: in the new test one group editor probed commandcode.svg
  14 times. Chromium revalidated it on the redraw, and a WKWebView with a
  wails:// handler went from 17 to 18 requests.
- Nothing kept the picture between the old span going and the new one
  painting. A new span has nothing that holds the decoded picture, so the
  engine is free to drop it and paint the new span empty until it has
  loaded the picture again. keepIcons (Providers only) doesn't help here,
  even if more pages used it: a node it moves is taken out and put back,
  and its CSS image is resolved again.

maskSpan (app.js) now builds every mask span. Each picture is probed once
per page, not once per logo. When the picture loads, a span of its own is
put on a hidden shelf (.mask-shelf: fixed, 0x0, visibility hidden,
aria-hidden) that holds it for as long as the page is open. A picture
that fails still falls back to the plain outline, the same as before.
library.js's RTK logo, the only other place that set a mask's --i
itself, now goes through maskSpan too. Logos look the same as before.
The shelf costs one extra load per distinct mask picture, once each.

Run:
- New internal/gui/tests/mono-icon-redraw.test.cjs, in Chromium and
  WebKit, en and zh: the rows really are drawn afresh (the editor's own
  redraw and drawGroups' replaceKeeping), logos look the same, one probe
  per picture, no new request for it, the shelf holds it once, takes no
  room, is hidden, and a missing logo stays the outline. A source guard
  checks that only maskSpan sets a mask's picture.
  - On the old code all five tests are red (14 probes, and the guard
    names app.js:237).
  - With the shelving taken out by hand, the WebKit cases are red.
- 112 related GUI files (group-*, routing-*, icons, rtk, mask, keepIcons),
  both engines: 1053 of 1058 pass. The 5 reds are group-member-info,
  routing-group-fold and routing-sessions in WebKit, and they fail the
  same run alone on unchanged main (#1672, #1745).
- The full GUI suite, once, under load 60-150 from other sessions: 7261
  of 7290 pass. Every failing file was rerun alone on the fix and on
  unchanged main, and fails the same on both, under #1672, #1745 and
  #1609. library-mcp-tool-switch fails 1-4 random WebKit cases per run on
  both (#1609). profile-in-use and library-mcp-tools have been fixed on
  main since (cce4960bd, b7df1b7c6).
- A Swift WKWebView harness (wails:// scheme handler, real assets) with
  60fps screen recordings analysed frame by frame: the request counts
  above, and with the fix no request on a redraw (26 -> 26) and the logo
  identical, frame by frame.

Not done: the blink itself never showed, on macOS 26.2 in WKWebView,
playwright WebKit or Chromium, before or after the fix. So the fix is
grounded in the two defects above, not in a reproduced blink, and isn't
confirmed on the reporter's machine. The Windows (WebView2) and Linux
(WebKitGTK) webviews were not tried. No Go changed.

* gui: on Routing picked mid-request, the request's dot waits at the account answering it, not where the account was a frame before (#1859)

What changed: a request's dot, let go at the account that answers it, is
held there (`.pkt.held`) until the try ends. It was posed only while
flying, so any layout after it landed left it where the seat had been.
Picking Routing while a request is under way does exactly that: the
view's box is 0 wide while hidden, so byWidth marks it max560 and the
stage comes back stacked (accounts under magpie) for its first frames.
With reduced motion the flight is one frame, so the dot lands at the
stacked seat's edge; the stage then goes wide and the wires follow
(the stage's ResizeObserver runs layout()), but the dot doesn't. That
is ouchxp's screenshot: a dot at the left of the line under the stage,
and the seat's own dot plain. A window resized while a request waits
did the same with any motion setting.

Now play() records each held dot with its row (`holds`), and layout()
poses every held dot at the end of its row's wires again (holdAll),
so it follows the seat through the narrow-to-wide switch, resizes and
FLIP moves. holds is cleared with the play, and by stopPlays.

Not changed: byWidth still marks a hidden box narrow, so the stage is
stacked for a frame or two after the view is picked. Skipping a 0
width there also hides this case at wide windows, but not a resize or
a narrow window, so the fix is in the held dot.

Run (worktree on 5c82e6880, then rebased on 3869b0a27):
- new routing-held-dot.test.cjs: chromium and webkit, en zh zh-TW ja
  de, 1100 and 560px, reduced motion: Agents first, the request under
  way, Routing picked, the held dot at the seat's edge; then the window
  resized to the other width and checked again. 20/20 pass. On the old
  routing.js it fails in both engines (dot at x 267, seat at 607 after
  the switch; and after the resize). With only the byWidth change and
  not holds, it still fails, so the test guards holds.
- all routing-*.test.cjs and panel-routing, both engines: 715/719 on
  5c82e6880; the 4 (routing-group-fold webkit en/ja/de,
  routing-sessions webkit en) fail the same there without this change
  and pass on origin/main 3869b0a27 (fixed by 94aa793db). Rerun on
  3869b0a27 + this: 718/719; routing-steady webkit "requests coming in
  leave the routing groups where they are" moved the editor 1.69px under
  load. That is #1804: alone it passes 3/3 with and without this
  change; 4 copies at once fail 4/8 on the old routing.js and 0/8 with
  this change.
- Not tried in the real app window with a live request.

* readme: the Chinese README's bold lead-ins render as bold again, not as **…**

CommonMark only closes ** that is right-flanking: one after punctuation
(。 ) or a link's ")") must be followed by a space or punctuation. In
"**1 · 安装。**从" it is followed by 从, so GitHub showed the asterisks.
The three Quick start steps and "方案(Profile)" move their punctuation
out of the bold; the two bold links put the bold inside the link text.

Run: every tracked .md with CJK text (12 files) rendered through GitHub's
own renderer (gh api markdown, gfm); README.zh-CN.md was the only one
with stray ** (6), and after this change it has 0.

* readme: the architecture diagram is a drawn picture in both themes, not a mermaid flowchart

The mermaid "How it fits together" / 整体结构 chart rendered as grey
boxes in GitHub's default style. It is now four hand-made SVGs
(en/zh × light/dark) under site/public/img/architecture*.svg, shown
through <picture> with prefers-color-scheme:
- agents on the left (the 40+ others as a dashed row), providers on the
  right, joined by curves into one magpie card;
- the magpie card is inverted (black in light, near-white in dark), with
  the logo, 127.0.0.1:3425 in a mono face, and the gateway → routing
  groups → plugins stages on a rail, the four protocols as chips;
- system font stacks only, since an SVG in <img> loads no web fonts.

Run: rendered all four in headless Chrome on GitHub's backgrounds
(#fff, #0d1117) at 2x and at the README's 880px width; checked no text
overlaps or is clipped and the shadows aren't cut by the viewBox.
Both READMEs no longer contain a mermaid block. Docs-only.

* readme: the architecture diagram shows each agent's and provider's real logo

The owner asked for real logos on the agents and the models. Each agent
row now carries its own mark (Claude Code, Codex, Gemini CLI, OpenCode),
the "+ 40 more" row shows Zed, Cursor, Cline and Goose, and every
provider name sits behind its logo (DeepSeek, Kimi, GLM, OpenRouter;
Claude, ChatGPT, Copilot, Gemini; Ollama, LM Studio). The marks are
inlined from internal/gui/assets/icons, the same files the GUI shows,
with their gradient ids prefixed per use so the four copies don't clash;
monochrome marks follow the theme's ink. Text and chip widths are now
measured from SF Pro rather than estimated per character.

Run: rendered all four SVGs in headless Chrome on #fff and #0d1117 at
2x and at the README's 880px width; no overlaps, every logo resolves.

* images: a ChatGPT account lists one GPT Image, said to be ChatGPT's pick (#1865)

Settings › Models › Image generation offered "GPT Image 2 · Codex" and
"GPT Image 2.5 · Codex". chatgpt.com/backend-api/codex/images/generations
ignores the model (and size): tested with the owner's Pro account, it
answers gpt-image-2, gpt-image-2.5, gpt-image-2.5-sunburst and a made-up
"x" with 200 and the same image (#1865 comment 6131731318), as 3a18ec8e
already suspected. The picker implied a choice that doesn't exist.

What changed:
- gateway: codexDrawers is one entry, gpt-image-2 named "GPT Image" (what
  Codex CLI asks for). VendorPicksDrawer(p) marks a ChatGPT account.
  ListedDrawer(ref) maps any gpt-image-* picked on a ChatGPT account
  (a saved codex/gpt-image-2.5) to that entry, for display only.
  drawsFamily still lets a named or saved gpt-image-2.5 draw there.
- gui: /api/settings sends imageGenShown when the saved ImageGen stands
  for another listed entry, and vendorPicks on the ChatGPT entry. The row
  shows and ticks the entry, picking it again saves nothing (the saved
  value is never rewritten), its option note and a line under the row say
  ChatGPT's image backend picks the model itself. en/zh/zh-TW/ja/de.
- Aside: magpie/codex/gpt-image-2.5, picked when it was offered, is still
  taken as an image model (asideImageOffered maps it via ListedDrawer).
- An API key's gpt-image-2.5 (OpenAI, relays) is listed and drawn as
  before: there the model field matters.

Checked: no doc, site page, MCP tool description or CLI lists these ids.
The remote-magpie list (drawerObjects) follows Drawers and now lists one.

Run, at this head:
- New tests failing on the old code: TestCodexListsOneGPTImage ("codex
  lists [gpt-image-2 gpt-image-2.5], want only gpt-image-2") and
  TestCodexAccountDraws with the old codexDrawers;
  TestAsideCodexOneGPTImage ("magpie/codex/gpt-image-2.5 not offered")
  without the aside mapping; TestImageGenCodexOneEntry ("shown \"\"")
  without the api.go wiring; images-codex-one.test.cjs with the old
  app.js (button "codex/gpt-image-2.5", not "GPT Image · Codex").
- go test -tags nogui ./internal/gateway ./internal/gui ./internal/agent
  ./internal/catalog ./internal/provider under a sandbox HOME: ok.
- gofmt -l (empty), go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: clean.
- Playwright (1.62.0), chromium and webkit: images-codex-one (en, zh,
  zh-TW, ja, de at 1000px; en, zh at 360px), images-missing, vision-mcp,
  searcher-pick, routing-vision-why, i18n-keys: all pass.
Not run: the full go test ./... and the whole GUI suite; no new request
was made to chatgpt.com (the backend's behaviour is the #1865 test).

* usage: a cost total says how many calls it couldn't price, never reads them as free (#1856)

cnlove7777777-art's Kimi K3 Auto and GLM-5.3 Max calls had "no price",
and Usage's sum counted them as $0 with nothing beside it but a "+" and a
tooltip. Now every total that sums cost says the count:

- GUI: Overview's and Requests' heads read "≈$0.001+  2 calls unpriced";
  with nothing priced, the count alone (Requests showed nothing at all
  before). Overview's calls tile adds "2 unpriced". Sessions, which prices
  by model, says "1 model unpriced" in its head and cost tile. The count
  stays at every width: the narrow and .tight rules no longer hide it,
  and the head goes tight when the count would be cut, sum or not.
  "no price for these models" is no longer shown, its key removed.
- CLI `magpie usage`: "≈$0.001+ (2 calls unpriced)". TUI Usage page: the
  same after its cost.
- docs/reference.md: unpriced calls are left out, said beside the total;
  magpie doesn't guess a variant's price from a similar name.

No variant price is mapped: models.dev lists neither "Kimi K3 Auto" nor
"GLM-5.3 Max", Zhipu's "Max" is a Coding Plan tier, and -fast variants
are 1.5x their base, so a suffix strip would be a guess. The existing
per-model price override (provider editor, `magpie model price`) covers it.

Run: go test ./internal/cli ./internal/tui ./internal/gui (ok);
TestUsageSaysCallsUnpriced and TestUsagePageSaysCallsUnpriced fail with
the fix taken out. usage-unpriced-sum.test.cjs (new) passes in Chromium
and WebKit, en/zh/zh-TW/ja/de, 360-1240px, and fails 5 of 5 on
origin/main's assets. Related GUI files (every test naming usageCost,
unpriced, effective prices, usage-head or "{n} failed", plus i18n-keys,
gui-zh-tw/ja/de, number-units, text-size, usage-ledger, ledger-protocol,
usage-range, mobile-web, phone-web, view-no-sideways): 655 pass; the
WebKit text-size foot case and routing-sessions fail the same run alone
on origin/main 5c82e6880 (filed #1672, #1307). gofmt -l clean; go vet
darwin, GOOS=linux -tags nogui, GOOS=windows clean. Not tried in the
real app window.

* gui: Tuned for you names its advice "Fewest tokens" and says a compaction window is a token estimate, not what the agent keeps (#1854)

cnlove7777777-art: the card called 230K -> 150K "best for you" on token
savings alone, while compacting sooner may lose more of a long coding
task. A retention benchmark isn't built now; the card says what it
measures instead:

- the advised value's label is "Fewest tokens", not "Best for you";
- a compaction row that advises a change adds "A token estimate only: it
  doesn't measure how well the agent keeps the task after a compaction.
  The lower the window, the more often it compacts." Not on a window
  already the leanest, nor on the cache lifetimes.
- zh, zh-TW, ja, de translations; agent-wiring.md says the same.

Run: context-tune.test.cjs (new assertions on label and caveat) passes in
Chromium and WebKit, 360 and 1100 wide, en/zh/zh-TW/ja/de; on
origin/main's assets it fails 11 of 12. context-*.test.cjs, gui-zh-tw,
gui-ja, gui-de, compact-at, i18n-keys: 99 pass, 0 fail. Not tried in the
real app window.

* gui: Tuned for you lets a compaction window be picked, each with its estimated extra tokens and compactions (#1860)

MrMengJ applied the advised 200K auto-compaction window and wanted 250K or
300K instead, seeing what each costs against the cheapest. A compaction
row now has "Other window…", which opens the app menu (never a native
select) with every value of the curve the card already replays. Each says
its estimated extra tokens over the fewest (or "Fewest tokens" / "As few
tokens") and about how many compactions it would have made over the range.
The head says it is estimated from the reader's calls. The one picked is put
in through /api/tune/apply like Use, with Undo.

tune.Point gains compacts, counted by the same replayCompact that prices
the point, so tokens and compactions come from one model.

Run: go test ./internal/tune ./internal/gui; TestCompactCurveCountsCompactions
(compactions fall as the window grows; the last point is close to
Facts.Compacts). gofmt -l; go vet internal/tune on darwin, linux -tags
nogui, windows. GUI: context-*, gui-zh-tw/ja/de, compact-at, click-scroll,
i18n-keys in chromium and webkit, 144 pass. The new context-tune test covers
5 languages at 360 and 1100px: menu inside the window, 300K ticked, notes
for 250K and 160K, picking 250K posts apply with no page scroll, Escape
posts nothing. On HEAD~ assets context-tune fails 22 of 23.
Not run: against a real Claude Code settings.json (the apply path is
unchanged from Use).

* usage, gui: a model says how many of its replies were ended for looping (#1858)

#1858 asked for recovery across turns when a model loops. magpie is a
gateway and can't rewind the agent's session, so that is not planned now.
What it can do is let the reader see which model loops. Each reply the loop
guard ends (#1359) is logged with err_type "reply_loop", but Usage only
counted it among the failures.

usage.LoopErrType is now that type (the gateway's loopErrType is it), and
Totals.Loops counts, among the failed requests, those ended for looping. A
handed-on try is still no request. The Overview's model, agent, account
and key rows and the Requests ranking say "{n} looped" beside "{n}
failed", and the ranking's "Other" adds them up. Translated into zh,
zh-TW, ja and de.

Run: TestLoopsCountedPerModel (Overview groups, the ledger sum and
Breakdown; red with the increment removed). go test ./internal/usage
./internal/gateway ./internal/gui; gofmt -l; go vet on darwin, linux
-tags nogui and windows. The new usage-loops.test.cjs ran in chromium and
webkit, 5 languages at 360 and 1100px, 20 pass; it fails 10 of 10 on HEAD~
assets. usage-*, ledger-*, own-requests, i18n-keys and gui-zh-tw/ja/de in
both engines: 565 pass.
Not run: a real looping model through the gateway (the logging path is
unchanged from #1359).

* gateway, gui: a WorkBuddy account the vendor restricted (403 11140) rests 2 hours as restricted, and Routing names the appeal as the way back (#1849)

WorkBuddy answers an account it restricted for unusual activity with
403 {"code":11140,"msg":"request illegal","displayMsg":{"en":"Your
account has been restricted due to unusual activity",...}}. failure()
read it as an unknown failure, so the account rested 1-10 minutes and
was asked again, refused, all day.

What changed:
- provider: WBRestricted knows the refusal by code 11140 (top level,
  data or error; number or string; whole, so 111400 isn't it) or by its
  displayMsg words. wbExplain ends the built-in's error with
  WBRestrictedHint.
- gateway: a new failRestricted ("restricted") rests restrictedRest, 2h:
  one refused request per account per 2h, and a lifted restriction (or a
  misread refusal) comes back the same afternoon; Unrest lifts it at
  once. It is read from the hint in the error (restrictedSaid; both the
  built-in and the plugin translate the vendor's body before failure()
  sees it, so the raw JSON never reaches it in a chat try), or from the
  raw body only for a WorkBuddy candidate (restrictedRefused,
  isWorkBuddy), since another vendor's 11140 is its own. Bare "request
  illegal" is not matched. 11128 stays promptRefused and rests nobody.
  The stale-allowance shortcut skips it, as it does model refusals.
  drawsWorkBuddy now uses isWorkBuddy.
- plugin: @magpie-community/opencode-workbuddy-auth 0.1.17 (plugins
  caf3908) ends the error with the same hint; the mover's min is 0.1.17
  so keepMovedCurrent brings moved users to it.
- gui: Routing labels the try "account restricted by the vendor", says it
  rests because only the vendor lifting it brings it back and to appeal,
  shows the hint translated, and the account's row has "The restriction
  is lifted — try it again" (POST /api/gateway/unrest). en, zh, zh-TW, ja,
  de.
- docs/subsystems/gateway-routing.md says the above.

Run: gofmt -l (clean); go vet darwin, GOOS=linux -tags nogui, GOOS=windows
on gateway, provider, gui; go test ./internal/gateway ./internal/provider
./internal/gui (ok). New Go tests use the reporter's literal body through
the vendor's shape, the built-in's and the plugin's, a string code and the
words alone; another vendor's 11140, a non-WorkBuddy account with the same
body, 11128/14018/111400 not restricted; an e2e through the fake plugin
host where the restricted account is skipped by the next request.
Broken by hand, each went red: rest case removed, restrictedSaid removed,
the match unscoped, the raw match removed, the provider hint removed.
GUI: routing-wb-restricted (chromium and webkit x en/zh/zh-TW/ja/de x
1100/420px, 20 pass), routing-wb-refused, i18n-keys; after the rebase
every GUI test of the Routing page (107 files, both engines): 103 green.
The 4 red ones fail the same in WebKit on origin/main 689edbd6b run
alone and are filed: group-member-info (#1745), routing-sessions
(#1307, #1672), routing-steady (#1804, passed on this head on a rerun),
routing-group-fold's group-of-eight (#1672).
Rebased onto 2c30e5cee (with #1672's test fixes) and run again: vet x3,
go test ./internal/gateway ./internal/provider ok. On the final base
5756651e3 (only GUI assets and READMEs changed since): routing-wb-restricted
20/20, routing-wb-refused, i18n-keys, routing-held-dot, mono-icon-redraw,
routing-sessions 38/38, routing-group-fold 40/40; routing-steady's WebKit
case red again, the flake filed as #1804.
 Not tried against a real restricted account;
plugin users on <0.1.17 rest by minutes until their plugin updates.

* gui: a skill group's agent chips count only the skills magpie decides, and a row's chip for one an agent reads from ~/.agents/skills itself is locked (#1862, WardLu)

A skill kept in ~/.agents/skills is had by every agent that reads that
folder itself (SkillView.Always), whatever is ticked. Its row's chip said
so only on a click, greyed like a chip that can't take the skill, while
the group's chip counted s.agents alone. Turning the group off for Codex
then said "off for Codex" and left the row lit.

What changed:
- groupChips (group headings, parts and the Select bar) counts, gives and
  takes only the skills magpie decides for each agent. agents-some is
  sent, per agent, the names it doesn't read itself, so a skill Codex
  reads from the shared folder is never sent for Codex.
- A chip whose agent reads only some of them itself says how many, in its
  tooltip. After a click, the status says "Codex still reads 1 of them
  from ~/.agents/skills itself".
- An agent that reads every one of them itself has a lit, locked chip, as
  the row's is. It sends nothing, and a click says why.
- The group's heading says "N in ~/.agents/skills", with a tooltip naming
  the agents that read it, before any click.
- A row's locked chip is lit, with a small lock on its corner, rather
  than greyed out at .35.
- Nothing deletes from the shared folder or touches another agent's
  config. Servers and hooks keep their own reach rules unchanged.
- Strings in zh, zh-TW, ja and de. docs/subsystems/library.md (Skill
  groups) says it.

What was run:
- New skill-group-shared.test.cjs, in Chromium and WebKit; en, zh, zh-TW,
  ja and de; 640px and 1180px:
  - heading note;
  - partial chip tooltip;
  - the locked row chip's opacity and its lock;
  - the post sent, the status, and parents and rows agreeing after a
    click;
  - All;
  - a fully locked group chip sends nothing;
  - no sideways scroll.
  22/22 pass, twice. It fails on the old code (no heading note; Codex is
  sent mango too).
- group-skill-chips, skill-parts, skill-groups, shared-skills,
  every-skill, library-all, i18n-keys, library-own-folder,
  skill-repo-groups, library-pick-remove and library-null-agents pass in
  both engines.
- pick-skills is red in WebKit on origin/main's own assets too, the same
  as here. It is out of date since 18e82adc6, and the GUI-triage session
  is fixing it (#1672).
- Looked at in WebKit screenshots, light.

What wasn't run:
- Not tried with a real Codex reading a real ~/.agents/skills. The
  backend (SkillView.Always, agents-some) is unchanged.

* library: Collapse all / Expand all for the skill groups (#1862)

WardLu (#1862) asked for a way to fold every skill group at once in a
library of many groups. Library > Skills now has a Collapse all / Expand
all button beside the sort (foldAllButton in library.js):

- without a filter it sets every shown group's kept fold
  (magpie.libSkillFolds), the same as clicking each heading;
- while filtering it folds or opens only the groups the filter shows,
  until the filter changes (unfiltered), and leaves the kept folds alone;
- it says Collapse all while any shown group is open, else Expand all;
- it is hidden with fewer than two groups (A->Z, or a filter only one
  group matches);
- a part inside a group keeps its own fold, and nothing is sent.

skillHits/groupFolded pull out the rules drawSkills already used, so the
button and the headings can't disagree. Strings in en, zh, zh-TW, ja, de.
docs/subsystems/library.md's Skill groups row describes it.

Run:
- new internal/gui/tests/skill-fold-all.test.cjs: chromium and webkit,
  en/zh/zh-TW/ja/de, at 640 and 1180. 22/22 pass, three times. With
  origin/main's assets it fails in every case (no button).
- the skill-*, library-* (skills side), pick/remove/import skill tests
  and i18n-keys, at concurrency 4: everything passes except
  pick-skills.test.cjs in WebKit. That test is red with main's own assets
  too (#1672, being fixed separately).
- screenshots in German at 640 and 1180: the button sits in the heading
  row and wraps with it.

Not run: a real library with many groups in the app window. I didn't
check by hand that the scroll check fails when something scrolls.

* library: a site's well-known kit of skills is one group, by the lock's sourceBaseUrl (#1862)

WardLu (#1862): skills that `npx skills add` got from a site's
/.well-known/agent-skills/ index were one group per skill. That was
Feishu's lark-base, lark-doc and lark-sheets, and Fish Audio's
fish-audio-api and fish-audio-sdk. readSkillLock grouped them by each
skill's own sourceUrl (".../lark-base.tar.gz", ".../fish-audio-api/skill.md").

Now a lock entry with sourceType "well-known" is grouped by its
sourceBaseUrl, read as host/path (wellKnownBase/siteOf):
- the user, query and trailing slash are dropped, and the host is
  lower-cased without "www.";
- so Feishu's three are open.feishu.cn/lark-cli/skills/regular and Fish
  Audio's two are docs.fish.audio;
- a kit on the same host with a different base URL stays apart. Hosts are
  not merged.

Fallbacks:
- an older lock with no sourceBaseUrl takes the part of its sourceUrl
  before /.well-known/;
- an entry with neither is grouped by its sourceUrl, as before.

Two things this new key would otherwise get wrong:
- Group again (RegroupSkills) tried every owner/repo-shaped key on GitHub.
  A kit one folder down a site (docs.example.com/kit) has that shape, so a
  key whose owner has a dot is skipped now. GitHub owners have no dot.
- the heading's link sent a key with no path ("docs.fish.audio") to
  github.com. repoURL now opens it at https://docs.fish.audio.

Run:
- go test ./internal/library (all pass). New TestWellKnownKitGrouped uses
  the issue's base and source URLs for 3 Feishu + 2 Fish Audio skills, plus
  another kit on open.feishu.cn, an entry with no base, and a
  docs.example.com/kit kit that Group again must not fetch.
  - With the well-known branch disabled it fails, with the reporter's five
    one-skill groups.
  - With the dot check removed it fails on a GitHub fetch.
- new TestWellKnownBase: a table of base and source forms.
- skill-repo-groups.test.cjs now has a docs.fish.audio group that opens the
  site. It fails with origin/main's assets, which say "on GitHub". It and
  skill-regroup/skill-groups pass in chromium and webkit.
- gofmt -l; go vet for darwin, linux -tags nogui and windows on
  internal/library.

Not run: the reporter's real ~/.agents/.skill-lock.json. The issue quotes
only these three fields of it. A row's own link still isn't its sourceUrl.

* gui: Plugins' "Unofficial, on GitHub" has its kinds to pick and a field of its own to narrow it

The owner: 这里应该有分类以及搜索框方便用户筛选. The section lists every
repository tagged magpie-plugin, 31 on the dev instance today, as one
long grid, and the page's only search ("Search plugins and npm…") sits
at the top and also asks npm.

Once more than six repositories are tagged, the section's head has:
- its kinds as a segmented control (All · 31, Provider · 27,
  Middleware · 3, Agent · 1): only kinds that have repositories, each
  counting what the field leaves, and none when one kind is all there is;
- a field that narrows by name, author or description as it is typed,
  with Escape to clear it;
- "No plugin on GitHub matches" with Show all when nothing is left.
Both narrow what the page's search has already found. Only the section
is drawn again as they change. The section, its field and the page's
body are made once and kept in the page, as the page's own field is
(#1055), so an answer that redraws the page while someone types (npm's)
keeps the field's focus and every key. Strings in zh, zh-TW, ja and de.

Run:
- plugin-github-filter.test.cjs (new), built on the dev instance's real
  /api/plugins/github answer: chromium and webkit, en/zh/zh-TW/ja/de,
  980px and 440px, 22/22. Putting back drawBody's replaceChildren turns
  the field-keeps-its-focus check red.
- Every other plugin-* GUI test, plus i18n-keys and nav-sub-unroll, in
  both engines: all green. plugin-github went 0/18 at first, because two
  fields matched its `.pm-find input`; with the six-repository threshold
  its four repositories show the plain grid, and it is 18/18.
- Looked at in dark WebKit at 1200px and light Chromium at 440px.

* provider: moved Cursor users get plugin 0.2.9 and WorkBuddy users 0.1.18 (magpie-community/plugins#55, #18)

Cursor 0.2.9: a default model whose own branch stops short of the asked
effort goes to its nearest effort, so the id and its parameters agree.
WorkBuddy 0.1.18: WorkBuddy 5.6+ keeps its desktop sign-in encrypted; the
plugin now says so and points to the browser sign-in, instead of
"isn't signed in" and a 502.

Both versions checked on registry.npmjs.org (dist-tags latest).
Run: gofmt -l, go vet (darwin, linux -tags nogui, windows) and
go test ./internal/provider -run 'Mov|Plugin|Migrat|Hand'.

* gui: Connect's Shell and curl snippets can be for Windows or macOS · Linux, whichever machine runs them (#1514)

FourLeafTec on #1514: at home on Windows, but mostly running things on a
Linux server over ssh, and Connect only ever wrote the snippets for the
machine magpie runs on (PowerShell + curl.exe on Windows, bash elsewhere).

What changes
- Beside the snippet language, the Shell and curl tabs get a two-way
  segmented control, Windows | macOS · Linux. It starts as the host's OS
  (also when Local network / Public address is picked: those say where the
  gateway is reached, not where the snippet is pasted), and the pick is
  kept in localStorage (magpie.snipOS), next to magpie.lang. The Shell tab
  is named PowerShell or Shell after it. Python and Node show no switch.
- Quoting is now right for any key a user brings (ownSecret allows every
  ASCII symbol): POSIX values and headers go in '...' with ' as '\'' when
  they hold ' " $ ` \ !, the -d body escapes its own ', and a URL with
  brackets (a [1m] model id) is quoted and gets -g. PowerShell values go in
  '...' with ' doubled when they hold $ ` "; a header holding " goes to
  curl.exe after --% on one line, quoted as the C runtime reads it, since
  Windows PowerShell 5.1 split such a header in two (seen on the box). A
  %NAME% of a defined variable in such a key is still expanded there; noted
  in the code.
- Translations for the control's label in zh, zh-TW, ja, de.

What was run
- New internal/gui/tests/connect-snippet-shell.test.cjs: Chromium and
  WebKit x en/zh/zh-TW/ja/de x 1100/390 px, 20/20 pass. It picks a LAN
  address on a Win32 page, checks the PowerShell form, switches to
  macOS · Linux (the control's position and the page's scroll unchanged),
  runs the export snippet in bash and zsh and the curl snippet against an
  echo server in the test (the key with ' " $ ! ` \ arrives whole, body
  parses), reloads (pick kept), switches back (--% form), Python shows no
  switch, a Mac page starts on macOS · Linux, and no horizontal overflow.
  With the old app.js it fails: "Expected values to be strictly equal"
  on the PowerShell env snippet ($env:OPENAI_API_KEY="k'ey"$HOME..." was
  unquoted), and there is no .snip-os control at all.
- On the Windows box (Windows PowerShell 5.1.26100; no pwsh there or on
  the Mac): the snippets the GUI made for OpenAI, Anthropic and Gemini,
  each as $env: and curl.exe, with three keys (sk-magpie-key-abc123,
  k'ey"$HOME!`x\y, ab\"cd%PATH%\), run with powershell -File against a
  TcpListener echo server started and stopped by the script. Plain and
  symbol keys arrive whole in the header and $env:, with the body as POST;
  the third shows the %PATH% limit above. Before the --% form, the symbol
  key's header was cut at the " and the request went out as a GET.
- Related GUI tests in both engines (click-scroll, connect-address-kept,
  gateway-*, phone-*, public-url*, omp-profile-connect, i18n-keys): all
  pass except mobile-web's "desktop matches origin/main" for the gateway
  view (415 px), the new control itself; screenshots looked at.
- go test ./internal/gui/ in a sandbox HOME: ok.

* gateway: MiniMax's and Volcengine Ark's refusals of thinking turned off are asked again with it left to the model (#1141)

thinkingOffUnlessAsked turns thinking off on a Messages request for a
non-Claude model that doesn't mention it (Claude Desktop's model_validation
probe, its health probe, title generation). MiniMax-M3.1-Flash-Preview and
Ark's glm-5.3 / glm-5.3-flash refuse that with 400, in wordings neither
alwaysThinks, mandatoryReasoning nor thinkingOffRefused matched, so the 400
went back to the client and Desktop wouldn't switch to the model.

alwaysThinks now matches the reporters' literal messages, narrowly:
- MiniMax: `requires adaptive thinking; thinking.type="disabled" (including
  reasoning.effort=none) is not allowed (2013)`
- Ark: "thinking.type `disabled` is not supported by this model"
Both retry sites use it: the relayed Messages path (withoutThinkingOff,
gateway.go) and the translated Chat/Responses path (thinkingBackOn).

Tests: TestAnthropicPassthroughMiniMaxArkThinkingOffRefused (each vendor's
body: omitted thinking succeeds after one retry without thinking; adaptive
goes once, as sent; another 400 of MiniMax's own 2013 and a near Ark
wording "top_k is not supported by this model" are not retried), and
TestTranslatedThinkingOffRefused now runs the GLM, MiniMax and Ark wordings.
With the regex change reverted both fail (400 handed back). The JSON
envelopes around the reporters' messages are assumed (Anthropic's error
shape); not tried against the live MiniMax or Ark endpoints.

Run (sandbox HOME, private GOCACHE, worktree at origin/main 97dfed0f3):
gofmt -l; go vet ./... (darwin), GOOS=linux -tags nogui, GOOS=windows;
go build for all three; go test -tags nogui ./internal/gateway
./internal/provider ./internal/catalog ./internal/codexcat: all ok.

* gateway: a codex provider used only through routing groups keeps the ChatGPT account's own models out of Codex's list (#1602)

With Codex signed in to ChatGPT, Codex asks magpie's /backend-api/codex/models
for its list, and codexModels passes the backend's own models through,
narrowed only by the codex provider's picks (CodexNativePicked) and the
Agents page's hides (CodexNativeHidden, built from Catalog()). A provider
set to "Only through routing groups" (Provider.Unlisted) has none of its
models in Catalog(), so neither filter saw them: all of the account's
models stayed in Codex's picker, and the Agents page had no Codex group to
hide. Every other agent's list is Catalog-based and already left them out.

provider.CodexNativeUnlisted says which of the account's models are kept
out of agents' lists: every one when the codex provider is Unlisted, and by
slug those a group with Unlists names. codexModels drops them (hidden
entries such as codex-auto-review stay, as with picks; a Codex reached for
failover alone keeps them, as it is handed no groups), spawnChoices drops
the same ones from spawn_agent's list, and CodexListTag carries them so
Codex refetches. gateway-routing.md says so.

Test: TestCodexModelListUnlistedForGroups (a group unlisting gpt-5.5 takes
gpt-5.5 alone; the provider Unlisted takes gpt-6-sol and gpt-5.5 and keeps
codex-auto-review; ETag changes; spawn_agent offers neither; own-only keeps
them). With codex_backend.go and codex_spawn_models.go reverted it fails on
all three checks. Not tried with a real ChatGPT sign-in and Codex app.

Run (sandbox HOME, private GOCACHE, worktree at origin/main 97dfed0f3):
gofmt -l; go vet ./... (darwin), GOOS=linux -tags nogui, GOOS=windows;
go build for all three; go test -tags nogui ./internal/gateway
./internal/provider ./internal/catalog ./internal/codexcat: all ok.

* gateway: drawing reads a relay's whole model list for which key serves an image model, and a key's 404 about the model asks the next key (#1657)

What: Provider.Serves now reads a new catalog.LiveAll (the fetched list
with image and video models kept) instead of live(), which drops Draws and
Films models. The draw key loop and the custom video path move on to the
next key when a key answers 404 whose body says the model isn't served
(keyLacksModel = 404 + modelRefused's wording); any other 404 still stops.

Why: wangru8080's analysis on #1657. A relay whose per-key lists name
gpt-image-2 under one key only still had drawing try a key that lacks it:
Serves read a list with the image model filtered out, so every key looked
unlisted, and that key's 404 "Model ... is not supported by any configured
account in this group" ended the loop instead of asking the next key.
Embeddings already move on any error short of the last key.

Run (sandbox HOME, private GOCACHE, worktree at origin/main 97dfed0f3):
- TestDrawGoesPastAKeyTheRelayListsForText, TestCustomVideoGoesPastAKeyThatLacksTheModel.
  Break checks: old Serves -> subtest 1 asks key-a first; draw loop without
  keyLacksModel -> subtest 2 gets the 404; video loop off -> 404 on start.
  A bare 404 still never reaches key-b.
- gofmt -l; go vet ./... (darwin), GOOS=linux -tags nogui, GOOS=windows;
  go build for all three.
- go test -tags nogui ./internal/gateway ./internal/provider
  ./internal/catalog ./internal/codexcat: all ok.
Not tried against a real relay.

Co-authored-by: wangru8080 <22983744+wangru8080@users.noreply.github.com>

* gateway: an image Claude Code sends to a Responses provider carries detail auto, so a strict upstream (vLLM) no longer refuses it with 400 (#1474, zacharyxz)

* gateway: the saved Anthropic-to-Responses body carries the image's detail auto that the commit before it sends (#1474)

TestUpstreamBodiesUnchanged (5feadabe, added after ump45nose's branch)
saved the bytes a vendor gets before input_image carried detail, so it
went red with the fix. Re-saved with UPDATE_UPSTREAM_BODIES=1; the only
byte change is "detail":"auto" on the one input_image.

Run: the two new tests fail on the old responses.go and pass on the new;
openai-python's ResponseInputImageParam (pydantic TypeAdapter) refuses
the old shape with "detail Field required" and takes the new one.

Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>

* docs: list StepCode in both README agent lists

Add StepCode beside Pi and oh-my-pi in the English and Simplified Chinese supported-agent lists, matching the existing implementation and reference documentation from 8b393938 (#1526, BUKOWSKIREAL).

Verified with git diff --check and a manual word-diff review. Go tests and builds were not run because this only changes README text.

* docs: list Ante and AstrBot in both README agent lists, which missed them the way they missed StepCode (#1526)

Checked every Name: of an agent in internal/agent against the README
list after the StepCode commit before it: Ante (e5e87d98, #1210) and AstrBot (2c75d898) were
the other two agents magpie connects that weren't listed. docs/reference.md
already has both rows.

The site's lists (site/public/index.html, docs/start.html in en, zh, ja)
are a hand-picked subset with icons, not every agent, so they're left as
they are.

Run: the same name check over README.md and README.zh-CN.md now finds
none missing (Magpie, Cindy's own custom provider, isn't an agent).

Co-authored-by: Ruijia Zhang <ruijiazhang76@gmail.com>

* agent: Grok App keeps its own route; magpie is a custom provider under Accounts, and the Library writes instructions, MCP and skills on agent-home (#1625)

* agent: Grok App's own route picked in magpie is taken, and Disconnect can put one back; a sync that isn't connected writes nothing (#1625)

Follow-up to fjrtdk's commit before this one, which this keeps: magpie never names
itself as Grok App's route.

- Set refused every own route (errGrokAppRoute) while Options still
  offered them, so the picker showed choices that only errored. It also
  broke Disconnect: when unwire leaves no route (Use set it to magpie,
  nothing stashed), Disconnect sets connect.was's route back through Set,
  got the error and stopped half done. An own route now takes magpie's
  channel out and is written as [models] default, the way picking
  another provider leaves magpie on other agents. That route can't be
  magpie, so the App's sign-in is never touched.
- Sync ran rememberRoute/releaseRoute before checking for the channel,
  so every user with Grok App installed but not connected got stash
  entries. Now it returns before them unless the channel is there or
  the route is still magpie (an older magpie's takeover to put back).
- Check again warns when the route is magpie and the channel is gone,
  which that commit dropped.
- The notice uses the App's own labels (Settings › Account, Use; ja
  「使う」, de Einstellungen › Konto / Verwenden, from grok-app 0.2.40's
  settings.nav.account and prov.useThis) and says a chat can pick
  magpie's models in its model picker (composer_prefs_set, which
  doesn't move the route).
- Sibling: rtk init has no grok agent for Grok Build either (rtk 311ebcb
  agents: claude codex copilot cursor droid gemini hermes opencode pi
  trae vibe antigravity), so Grok Build is in rtkNoHook too.

Run: gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows clean; go test ./internal/gateway ./internal/agent
./internal/library -count=1 pass; node --test i18n-keys and
agent-notice-lang pass. Broken by hand: that commit's grokapp.go fails
TestGrokAppOwnRouteStays, TestGrokAppDisconnectPutsTheRouteBack and
TestGrokAppSyncUnconnected; dropping the Check branch fails
TestGrokAppSyncUnconnected; dropping rtkNoHook["grok"] fails
TestRTKNoHookGrokBuild. Not tried: the Grok App GUI itself; the config
format and behaviour are from grok-app 0.2.40's source.

Co-authored-by: fjrtdk <fjrtdk@gmail.com>

* proc: EndProbes returns once a killed probe's whole group is gone, so an exit right after can't leave a missed child running (#1278)

JJ-Lin's fault injection on #1278: when the first signal to a probe's
group missed a process being forked, group.kill went on signalling it
from a goroutine nobody waited for, and the probe counted as ended as
soon as the first signal went out. EndProbes returned in ~0.2ms; magpie
then exiting (or Exec'ing the new version) ended that goroutine, and the
missed child lived on with PPID 1.

group.kill now returns a channel closed once none of the group is left
(or killFor has passed). A probe's Cancel marks its kill as begun and
counts the probe ended only when that channel closes. EndProbes waits up
to endWait for each kill to begin (a probe that already answered has
none, as before) and then for the group to be empty, bounded by killFor
plus a second. Every exit path goes through EndProbes: the GUI's
OnShutdown, the CLI's return and signal handler, and update.Reexec.

Windows: the job's TerminateJobObject takes no new process once it is
ending, and a probe is killed alone with TerminateProcess, so there was
no background loop to outlive; kill returns a closed channel there. The
known Windows gap that a shim's children aren't in a job for probes is
unchanged.

Run:
- TestEndProbesThenExitLeavesNothing (new) re-runs the test binary as a
  magpie whose group signals miss for 300ms, which calls EndProbes and
  os.Exit(0) at once. On the old code it fails 3/3 on darwin: "what the
  probe started (pid N) outlived magpie's exit after EndProbes".
- darwin: go test -race ./internal/proc ok; -race -count=10 of the
  probe/EndProbes tests ok.
- linux (docker golang:1.26.8 --init, GOTOOLCHAIN=local): -race -count=5
  of the probe/tree tests ok. Without --init the container's PID 1
  reaps nothing and every group test fails on zombies, on old code too.
- Windows box: new TestEndProbesWindows (ping probe ended, EndProbes
  ~0ms) passes 3/3; the rest of the package passes except
  TestNoCommandBypassesProc, which walks ../.. and found other
  checkouts in C:\Users\yeton since the binary ran outside a tree.
- gofmt -l, go vet (darwin), GOOS=linux vet -tags nogui, GOOS=windows vet.

* gui tests: key-balance-card watches for the card's flash rather than polling for it, which a busy WebKit missed under reduced motion

The test runs with reducedMotion "reduce", where app.css cuts every
animation to .01ms: the flash class panelQuotaFocus puts on the Command
Code card is removed on animationend a frame later (instrumented:
animationstart and animationend both at 43ms, elapsedTime 0.00001). A
waitForFunction poll landing outside that frame timed out at 5s. On
origin/main 0d39515b1, 8 runs of key-balance-card + tray-usages in WebKit
at --test-concurrency=4 had 10 such failures; no app code is involved.

A MutationObserver set before the focus now records that the card was
flashed. tray-cell-click, the other test that asserts the flash, runs
without reduced motion and only waits for its absence under it.

Run: 6 more WebKit runs of the same pair at --test-concurrency=4, 0
failures; key-balance-card in Chromium, 10/10.

* gui: Settings' menu-bar allowance picker lists a key's plan and balance as one row, not two "Command Code" rows ticked together (#1658, MizuIro-H)

658fbdc14 merged a key's plan and balance into one card on the Usage
page and the tray panel (keyCards), but the picker under Settings ›
Allowances › Shown beside the icon still built its rows from the
unmerged quotas. MizuIro-H's Command Code key reports a plan card and a
balance card, neither with a user, so both rows were "Command Code" with
the same trayCardID ("commandcode"), and ticking one showed both ticked.

The picker now takes keyCards' list, as the Usage page does. A balance
keyCards leaves on its own (a stale stand-in) whose id another row
already has is left out: the menu bar resolves an id to the first card
that has it (trayPick), so a second row of that id could only ever tick
the first. A failed balance was already left out (it has an error).

Run:
- tray-usages.test.cjs: a new test from the reporter's `magpie quota
  --json` (Codex, Command Code plan + balance with no user, SudoCode,
  DeepSeek) plus a plan with a stale balance, in Chromium and WebKit, en,
  zh, zh-TW, ja, de: each card is one row, ticking Command Code ticks
  that row alone and saves ["commandcode"]. With the old app.js all 10
  fail: the names list has "Command Code" and "Kimi Code" twice.
- every tray*.test.cjs and key-balance-card.test.cjs, both engines,
  --test-concurrency=4: 60 pass, 0 fail.
- Not run: the real Windows tray with a real Command Code key.

* agent: Claude Code isn't handed 272000 for a routing group made only of Claude models (#1741, yanjieee)

writeCompact gives a Claude model its own window (no
CLAUDE_CODE_AUTO_COMPACT_WINDOW unless the user set a threshold), but
claudeModel looks only at the id's last part, so group/auto-claude-opus-5-5
or any group of Claude [1m] models was told magpie's default 272000.
provider.ClaudeGroup is true when every member of a group (nested groups
flattened, by the listed name or the wire name, Bedrock names included)
is a Claude model; writeCompact now treats such a group as it treats a
Claude model. A group with another vendor's model keeps 272000. A
threshold set on a member's provider still comes first (CompactSet), and
the user's own env, autoCompactWindow and modelSettings are untouched.

Siblings: only Claude Code has a Claude exemption. Codex (codexcat
work.Working, route.go/models.go CompactFor) applies the working window
to every model, so has no group misread. claudeOutput's claudeModel uses
are about output tokens and are left as they are. Part (b), per-model
modelSettings windows, is tracked separately.

Run: TestClaudeGroupCompactWindow (new) fails on the old writeCompact
("a group of Claude models: 272000"), passes now, with a user-owned env
500000 and autoCompactWindow 900000 kept; go test ./internal/agent
./internal/provider; gofmt -l; go vet darwin, linux -tags nogui, windows.
Not tried in a real Claude Code session.

* gateway: models the user disabled are refused on every route, and leave every list (#1867)

oxsean asked for one place to turn a model (claude-fable-5) off for good:
not reached by a direct request, an old session, a routing group member,
a fallback, a sub-agent, count_tokens or a decision model.

What changed:
- settings.DisabledModels: patterns, an exact id or a glob (* any run, /
  included; ? one), matched ignoring case against provider/model, the
  bare id and its last segment (provider/disabled.go). Empty by default,
  so nothing changes for anyone who doesn't set it.
- Lists: buildEntries (entriesOff) leaves a disabled model out of the
  catalog, so /v1/models, agents' model files and pickers, Codex's list
  and every group go without it; membersIn skips it as a member, Deciders
  as a decision model; codexModels drops Codex's own disabled slugs and
  codexListTag changes so Codex refetches.
- Requests (gateway/disabled.go): 403 "model <id> is disabled in magpie"
  in each API's error shape, at #882's choke points: serve (idOff),
  perKeyBarred (no candidate: group next member, provider Fallback),
  count_tokens and Gemini :countTokens, serveSystemOne,
  serveDecisionGroup and postDecide, draw/video/embeddings, and
  codexBackend for Codex's own bare models. A group with a member left
  goes on without it; one with none left is refused naming them. A bare
  id the catalog no longer has is refused as disabled, not 404. A Codex
  sub-agent pick onto a disabled model stays on its lead's model.
- An unreadable settings.json is never "none disabled": the list read
  last stays; with none read, every request is refused; nothing is
  written over the file.
- CLI: magpie model disable <model|glob>..., enable ..., disabled
  (list-disabled).
- GUI: Settings > Models > Disabled models: each pattern with the models
  it matches now and Enable; Disable... opens the model picker, which
  also takes a typed glob. Says only requests through magpie are covered.
  POST /api/settings/disabled-models; POST /api/settings keeps the list.
  Strings in zh, zh-TW, ja, de.
- docs/subsystems/gateway-routing.md: Disabled models section.

What was run (worktree at origin/main 091593f7d, private GOCACHE, temp HOME):
- gofmt -l clean; go vet on darwin (touched pkgs), GOOS=linux -tags nogui
  ./..., GOOS=windows ./... clean; go build ./...
- go test -count=1 ./internal/provider ./internal/gateway ./internal/cli
  ./internal/gui ./internal/settings: all ok (gui after adding the field to
  TestSettingsSaveKeepsWhatItDoesNotSend's fixture, which it asked for).
- node --test internal/gui/tests/disabled-models.test.cjs: 16/16 (chromium
  + webkit, en/zh/ja/de, 1100/420); neighbouring Settings > Models tests
  and i18n-keys: 131/131.
- Broken by hand, each turned TestDisabled* red: serve's idOff (404
  instead of 403), perKeyBarred's filter (fallback reached spare), the
  catalog filter (/v1/models and Codex list), countOff (count_tokens 200),
  postDecide's check (decision call went out).
- Not tried with a real vendor account or a real agent.

Ref #1867

* gui: a Library row's agent chips fan out like a hand of cards, by translate alone

The owner: hovering an MCP server's row, the agent icons came out with
"一点都不丝滑优雅精致美观,应该像翻起扑克牌一样丝滑优雅". The fan grew every
chip's margin at once while a spacer before them shrank, so the row was
laid out again on every frame and all the cards moved as one block.

The chips are now laid out fanned for good and drawn stacked by sliding
each one by translate (--k, the chips to its right, set in agentChips).
Hovering only clears translate: the compositor moves the cards, the
strip, All and the name beside them never move, and the cards are dealt
one after another (a stagger of at most 120ms in all), the one with the
furthest to go first, so none passes over another; they go back
together, quicker. Transform stays free for the press. Reduced motion
fans at once.

Run: library-chip-fan.test.cjs (new), chromium and webkit, en, zh,
zh-TW, ja, de, with and without reduced motion: 22/22; 0/22 on
origin/main 689edbd6b. It samples each frame: no relayout, no card
passing another, more than three frames in motion. It caught that the
reduced-motion rule lost to the stagger's specificity, fixed here.
Measured with the dev instance's real 26 agents at 1800px: strip, All
and name at the same places as before at rest and fanned. The library
and skill GUI tests pass in both engines, except pick-skills on WebKit,
which fails 0/3 the same on origin/main 689edbd6b (.lib-pickbar takes
the click on the pdf skill's name).

* gui: Routing's story of a request keeps its logos as it is redrawn, so they no longer blink

The owner: in "How the request at … was routed" the provider logos "会不
停地闪烁". renderSteps made every line and logo afresh whenever the story
changed, which is on every new request and at each step of a live one,
so with an agent at work the logos were made again and again, and WebKit
draws a mask logo made afresh as nothing for a moment.

A line whose text, kind, model and logos are unchanged is now kept as it
is, and a changed line takes the logos of the lines it replaces
(keepIcons), so only what changed is made.

Run: routing-log-icons.test.cjs's new case walks a live request through
three steps (trying, 429 and trying the next, done) and checks the why
line and every logo are the same nodes after: chromium and webkit, en,
zh, zh-TW, ja, de, 14/14 with the old cases; the 10 new cases fail on
origin/main 689edbd6b. Not reproduced: the blank frame itself, which
headless WebKit didn't show; on an idle pinned request the logos'
pixels were stable before and after. Every GUI test that reads the
Routing page passes in both engines.

* library: an MCP server off for every agent shown isn't started when magpie opens (#1597, xiaozhu1337)

The library page checks (starts) every server it counts as in use when
it opens. inUse counted any agent id in the server's library record, and
any project entry. The library keeps the agents it once gave a server to
even when the page doesn't show them: one hidden on the Agents page, one
no longer installed, one with no MCP of its own (skills only), and
projects whose folder is gone. A server on only for those had every chip
off on the page and was still started each time, which is what the
reporter saw with ida-pro-mcp and windbg-mcp.

inUse now counts only agents the page shows with MCP (mcpAgents), and
project entries for shown agents with project MCP, in projects whose
folder is there. Such a server shows "not checked" and a click checks
it, as before. Its tooltip says no agent shown here has it on (new
string in zh, zh-TW, ja, de), and one on for nobody keeps the old text.

Siblings: inUse is the only thing that picks the servers checked on
open (renderServers and paintHealth both call it). The Go side,
library.CheckServers, checks only the names the GUI sends. The
remove-all confirmation still counts every project, which is right for
a removal.

library-mcp-health's fixture agent now declares projectMCP, since its
project-only server is meant to count as in use.

Run: new library-mcp-unshown.test.cjs (5 languages, 420 and 980,
chromium and webkit) fails on main with ida-pro-mcp, projgone,
projhidden, skillonly and windbg-mcp in the first check. With the fix,
all 34 library/MCP GUI test files pass in chromium and webkit (270
each), and go test ./internal/gui passes. Not tried: the reporter's
Windows machine; which of the hidden, uninstalled or no-MCP cases they
hit isn't confirmed.

* routing: a picked request goes back to live once it leaves the list, and the panel's stage has a place per provider (#1389, Creat55)

The reporter's two screenshots are the Routing window holding one
request: at 13:42 the stage still showed a 13:22 Antigravity request,
and at 15:58 it still showed a 13:42 qoder request while every request
listed went to WorkBuddy's deepseek. A request picked in the list (or
from the tray panel's row that opens the window on it) pins the stage.
followListed lets a pin go when a filter leaves it out, but poll never
did when the request dropped out of the 60 the page keeps, so the stage
stayed on it for hours. poll now lets it go and follows live.

The tray panel's mini stage (pDraw) had three places on the right, each
a provider's account. A provider whose requests went from account to
account filled all three, and the providers other sessions used were
left off. A place is now a provider, naming the account its latest try
went to, with how that went.

A request under way when the page dropped it kept its panel dot waiting
at its account until pUntil's 180 s limit, holding the dot, the place
and one of four play slots. pPlay now ends it at the next trace update,
as the window's play does through its rt(). The dot doesn't fly home
red, since nothing failed.

Run:
- routing-pin-leaves.test.cjs (new): 5 languages, 420 and 1100 wide,
  chromium and webkit. On main it fails in every case with "the stage
  stayed on the picked request".
- panel-routing-providers.test.cjs (new): 5 languages, chromium and
  webkit. On main it fails with three Qoder places. With only the pDraw
  part, it fails with "a dropped request still flies".
- All 67 routing/panel/tray-bird GUI files: 429/429 in chromium and
  428/429 in webkit. The one webkit red was routing-steady under
  --test-concurrency=4 (1.69 px), which is the known #1804. It passed
  3/3 alone and 6/6 in parallel with and without this change.
  panel-routing's stage expectations are unchanged.

Not tried: the reporter's real gateway traffic, and Windows.

* agent: the Agents page shows the Windows Codex app's version, read from the Microsoft Store package registered for the user (#1334, laacmilan)

On Windows the Codex app is the Store package OpenAI.Codex
(C:\Program Files\WindowsApps\OpenAI.Codex_26.1002.7124.0_x64__2p2nqsd0c76g0
in the report), which magpie didn't read: only %LOCALAPPDATA%\Programs was
looked in. The version now comes from the package full names under the
current user's AppX repository key (HKCU\...\AppModel\Repository\Packages),
which needs no access to the protected WindowsApps folder and starts no
PowerShell. The newest OpenAI.Codex package with publisher id 2p2nqsd0c76g0
wins.

Test: TestCodexWindowsStoreAppVersion (picks the newest, skips a bad
version and another publisher, and a WSL twin shows none).

[Message rewritten at review to say what and why; the code is AwadYoo's. The
conflict with 2221b63f9 (macAppFolders) was resolved by keeping both.]

* agent: the Windows Codex app's version comes from its main Store package only, and agent tests never read the machine's AppX registry (#1334)

Review follow-up to 46e4107 (AwadYoo).

What:
- storeAppVersion counts only the main package (empty resource id). The
  Windows box's AppX registry key keeps a resource package that Get-AppxPackage
  no longer lists (Clipchamp.Clipchamp_4.6.10420.0_neutral_split.scale-125_…
  beside the installed 4.7.10020.0_x64__…). A stale entry like that is no sign
  the app is installed, and a newer-numbered one would win "newest".
- internal/agent's TestMain stubs windowsStorePackages, as it already does
  for nodeModulesOf and the other machine readers (#1823's rule): on a
  Windows box with the Codex app installed, tests read nothing of it.
- the doc comment for storeAppVersion had a blank line in the middle of it.
  It is joined, and windowsStorePackages has its own comment.

Run (go1.26.8, sandbox HOME, private GOCACHE):
- Windows box (Win 11 x64): installed the real Store app (winget
  9PLM9XGG6VKS, "ChatGPT", OpenAI.Codex_26.1007.2314.0_x64__2p2nqsd0c76g0).
  A probe built from origin/main printed AppVersion="" HasApp=false; built
  from this series: AppVersion="26.1007.2314.0" HasApp=true, and CLI()
  ok=true App="26.1007.2314.0" with no codex CLI on PATH.
- break checks: the resource-id filter put back to len(fields) < 3 ->
  TestCodexWindowsStoreAppVersion FAIL `Codex Store app: "27.0.0.0"`;
  AppVersion without the Store read -> FAIL `Codex Store app: ""`.
  Restored: pass on darwin and on the Windows box (test binary built with
  GOOS=windows GOARCH=amd64, run there with the real app installed).

* gateway: Claude Desktop's model menu names a model as the agents' lists do, by the Provider in model names setting (#1746, marsxxl)

/v1/models for claude-desktop named every model by its own name alone,
with its provider's id in parentheses only where two read the same
(desktopNames, 03421f9f), so with the setting on Codex's list said
"Grok 4.7 @ 500k · Cursor" while Desktop's menu said "Grok 4.7 @ 500k",
and only same-name models got "(cursor)" (Gemini 3.8 Flash (cursor),
(antigravity)). The menu now names models as every agent's list does
(provider.Labels): on, the name with its provider's display name after
it; own, a name the user gave as they wrote it and a vendor's with its
provider's; off, plain names — and two of one name keep their provider's
so they stay apart, while where that still leaves two alike (one
provider's models named alike) the whole catalog id follows, for
Desktop's menu shows the name alone. 蓝猫's plain names (03421f9f) are
the setting's off; a user-given name that already says its provider is
left without it, as Label does everywhere.

Nothing changes for ids, routing, tiers, the 1M listing or the effort
picker. A model whose id reads as one of Desktop's own Claude models is
still renamed by Desktop's own catalog there ("Opus 5.5"), which no
gateway can reach; every other model's display_name is rendered, as the
reporter's "(cursor)" names show.

What was run: go test ./internal/gateway/ -count=1 (ok, 209s) with the
rewritten TestClaudeDesktopPickedModels and TestDesktopNames and the new
TestClaudeDesktopNamesFollowSuffixMode (on/own/off through /v1/models
with the claude-desktop key, red before the change); go test
./internal/provider/ ./internal/agent/ ./internal/codexcat/ -count=1
(ok); HOME=<temp> go test -tags nogui -count=1 ./... (ok, no FAIL);
gofmt -l clean; go vet on darwin, GOOS=linux and GOOS=windows. The
desktop GUI .cjs tests were not run (no playwright in this checkout):
they fake the backend and no GUI file changed. Not tried against a real
Claude Desktop: that it renders these display_name values is from the
reporter's screenshot, whose "(cursor)" names were this same field.

* gateway: a system prompt or message that only quotes a compaction prompt is no longer taken for a compaction; the prompt must lead (#1635, jueda12)

What: compacting() looked for an agent's compaction prompt anywhere in the
system prompt (strings.Contains) and its ask anywhere in the last user
message. Minis puts the user's memory after its own prompt in every request,
so a memory that held Minis's compaction line made every turn of that
conversation a "compaction", routed to the compaction rule's model (28
requests in a row in the report, one with 4 tokens of chat). Now:
- a compactSystems prompt counts only when it begins within compactLead
  (2048 bytes) of the system prompt's start: alone, or behind a short lead
  (Claude Code's billing header and identity line, which its Anthropic
  system blocks join with no separator, so a line-start check would miss it);
- a compactAsks ask counts only when it begins within compactLead of a text
  part of the last user message (Claude Code 2.1.296 puts its ~420-byte
  "CRITICAL: Respond with TEXT ONLY" preamble first; Codex and Kimi start
  the part with it). Minis's END OF CONVERSATION TO COMPACT. follows the
  whole conversation in one part, so it counts only in a part that opens
  with Minis's own "Compact this conversation into a context summary:".
- Kimi Code's own compaction system prompt (kimi-cli 1.52.0,
  soul/compaction.py COMPACTION_SYSTEM_PROMPT) is added, so Kimi stays found
  without relying on the ask's part alone.

The approach (a leading window instead of the whole prompt) and the test
TestCompactingIgnoresQuotedPromptInSystem are jueda12's. Their sample put the
quote ~30 bytes into a short system prompt, which a leading window still
takes, and no rule can tell that apart from a short real lead; the test puts
the memory behind a long agent prompt, as Minis sends it.

Run (go1.26.8, sandbox HOME, private GOCACHE):
- the prompts were checked against the installed Claude Code 2.1.296
  binary (the hnn preamble, then "Your task is to create a detailed
  summary…") and kimi-cli 1.52.0's compaction.py (prompt in its own part).
- break checks: main's compacting.go -> TestCompactingIgnoresQuotedPromptInSystem
  FAIL (memory, claude code taken; kimi not taken) and
  TestCompactingAsksWhereTheAgentPutsThem FAIL (minis marker quoted, ask deep
  in a paste); leads() without the window -> the same, minus Minis; the
  Minis opens check dropped -> "minis marker quoted: taken for compacting".
  Restored: pass, with TestCompacting, TestCompactingMinis, TestRuleCompact,
  TestCompactionBrokeOffKeepsTheStick.
Not run: a real Minis client (the reporter offered to check with the
memory that still holds the line).

Co-authored-by: jueda12 <180685381+jueda12@users.noreply.github.com>

* gui: the panel's usage rings are round on a 1x screen; the inner circle is 28px, so the band is a whole 3px a side (#1735, beansiayo)

A ring is .pq-dial (34px) with .pq-dial b (27px) over it. 34 - 27 is odd,
so the band was 3.5px a side and the inner circle sat on a half pixel. At
device scale 1 (an external 1080p display) each edge rounded its own way,
and the band came out 4, 3, 3 and 4 pixels left, right, above and below:
the slightly oval ring beansiayo saw. At 2x every edge falls on a whole
device pixel, which is why the built-in Retina screen looked fine.
parkavenue9639 found the cause and the fix: a 28px inner circle makes the
band a whole 3px.

quota-dial.test.cjs paints the band and the inner circle in flat colours
(sizes untouched), screenshots each ring in the panel and counts the
band's device pixels on each side of the inner circle, at device scale 1
and 2, Chromium and WebKit, en and zh.

Run: quota-dial.test.cjs on main's app.css fails all four (1x
{"left":4,"right":3,"top":3,"bottom":4}, the contributor's numbers); with
28px all four pass (1x 3/3/3/3, 2x 6/6/6/6). quota-pools, panel-usage,
quota-families and quota-curve pass (16). Screenshots looked at by eye.
Not tried on a real external 1x display.

Co-authored-by: parkavenue9639 <92194680+parkavenue9639@users.noreply.github.com>

* tests: the Codex fixtures' Windows paths are quoted for TOML

* tests: Zed's relative config dir falls back to its Windows default

* tests: syncHome scopes APPDATA and LOCALAPPDATA into the per-test home

* tests: the Aside offline tests refuse a write the way each OS does, and read the record's mode as Windows reports it (#1388)

On Windows six Aside tests failed: a directory's mode is ignored there,
so chmod 0500 on the record's folder refused nothing; os.Stat reports the
0600 record as 0666; and os.Symlink needs a right a test isn't given.

RaykieLee's 448967806 made the file itself read-only instead, on every
OS. That passes on Windows but turns four of the tests red on macOS and
Linux: edit.WriteAtomic renames a temporary file over the record, and a
rename over a 0400 file in a writable folder succeeds there, so nothing
is refused (TestAsidePostReadFailuresNeverOfferOffline/save_record,
TestAsideOfflineWriteFailureRollsBack,
TestAsideDisconnectUnavailableOnlyAtInitialRead/record,
TestAsideOfflineProviderWriteFailureRollsBackAllFiles; red at the
branch's own tip too). This keeps its Windows half and the folder elsewhere:
refuseWrites makes the folder unwritable on macOS and Linux, and the file
read-only on Windows, where neither a write nor a rename replaces it.
recordPerm wants 0666 on Windows. The provider-file test links its target
with a symlink, or a hard link on Windows, and refuses the target the same
way.

Run: go test ./internal/agent on macOS green; with refuseWrites a no-op
all four go red.
Windows box (Windows 11 x64, amd64 test binary of the whole package,
sandbox HOME/USERPROFILE/APPDATA/LOCALAPPDATA/TEMP): main plus the
series' base fails 21 tests; with the whole series only
TestInstallWithoutNodeParses (bash there is WSL's, whose default distro
has no /bin/bash) and the two TestReasonixCLI* (no Go on the box) fail,
both environmental and listed as untested by RaykieLee too. The six Aside tests are
among the 21 and pass.

Co-authored-by: RaykieLee <42793273+RaykieLee@users.noreply.github.com>

* tests: the Codex process-list stale tests skip Windows, where the row's copy is the daemon's last check, tested on every OS (#1388)

TestCodexStaleOnlyForMagpiesChange, TestCodexStaleCopiesSayWhichIsLeft
and TestCodexDaemonHelperIsNoStaleCopy test copies told apart from the
process list. StaleCopies lists no processes on Windows (a PowerShell run
each look); there it returns codexDaemonBehind, the daemon as
KeepCodexDaemonCurrent last found it. So the three failed on Windows.

RaykieLee's f3e0672fd added Windows branches that seed codexDaemonSeen
with the answer and assert it back, so on Windows the tests named for
"only magpie's change" and "which copy is left" pass whatever those
guarantees do; its keepCodexDaemon mock is never called there, and one
branch leaves the seeded check behind for later tests. Taken instead:
the three skip on Windows and say why, and
TestCodexStaleOnWindowsIsTheDaemonsLastCheck drives the Windows path
itself, through codexDaemonCheck with keepCodexDaemon faked: none before
a check, none when not behind, the daemon (with its start) when behind,
none after CodexDaemonRestarted, none when magpie restarted it, none once
the check is older than three loops. It reads StaleCopies on Windows and
codexDaemonBehind elsewhere, and resets codexDaemonSeen when done.

Run: go test ./internal/agent on macOS green. Broken by hand, each red:
codexDaemonBehind ignoring Restarted, ignoring the check's age, and
CodexDaemonRestarted not clearing.
Windows box (Windows 11 x64, amd64 test binary of the whole package,
sandbox HOME/USERPROFILE/APPDATA/LOCALAPPDATA/TEMP): main plus the
series' base fails 21 tests; with the whole series only
TestInstallWithoutNodeParses (bash there is WSL's, whose default distro
has no /bin/bash) and the two TestReasonixCLI* (no Go on the box) fail,
both environmental and listed as untested by RaykieLee too. The three skip there
and TestCodexStaleOnWindowsIsTheDaemonsLastCheck passes.

Co-authored-by: RaykieLee <42793273+RaykieLee@users.noreply.github.com>

* tests: the skills-only and leftover-folder tests keep AppData in each case's own home, so Hermes isn't found from another test on Windows (#1388)

The same class as 7743c52e5 (syncHome), in two tests that don't use it.
On Windows Hermes keeps %LOCALAPPDATA%\hermes, and
TestSkillsOnlyFolderIsNotInstalled and TestLeftoverFoldersAreNotInstalled
left LOCALAPPDATA at the package's test home. The case's own home held
only skills (or cache, log, skills), but the shared folder held what an
earlier case or test had written there, so Hermes read as installed and
both tests failed on the Windows box, before and after RaykieLee's series.
ownAppData sets APPDATA and LOCALAPPDATA inside each case's home.

Run: go test ./internal/agent on macOS green. Windows box: both red
without this (main, and the series without it), green with it.
Windows box (Windows 11 x64, amd64 test binary of the whole package,
sandbox HOME/USERPROFILE/APPDATA/LOCALAPPDATA/TEMP): main plus the
series' base fails 21 tests; with the whole series only
TestInstallWithoutNodeParses (bash there is WSL's, whose default distro
has no /bin/bash) and the two TestReasonixCLI* (no Go on the box) fail,
both environmental and listed as untested by RaykieLee too.

* provider: Xiaomi MiMo is priced at xiaomi's list price, not its Token Plans' $0, and pay as you go looks only in xiaomi (#1873)

mengyianx found every pay-as-you-go MiMo call counted at $0.000:
models.dev's xiaomi-token-plan-cn, -sgp and -ams list all nine models
at cost 0 (the plan's per-token charge, not the model's price), the
preset's catalog was "xiaomi-token-plan-cn, xiaomi" at every region, and
catalog.PricedBy takes the first catalog with a cost field. makerCatalogs
puts the plan catalog ahead of xiaomi too, so the maker fallback gave $0
as well.

What changed:
- membershipCatalogs (never read for a price) gains the three
  xiaomi-token-plan catalogs, as #1370 did for Kimi Code. That covers
  ListPrice, MakerPrice and PricedName through makerPriceCatalogs.
  kimiCodeMember now checks a list of Kimi Code's plans of its own
  (kimiCodePlans), so a Xiaomi provider isn't taken for Kimi Code and
  its ids aren't mapped to Kimi's.
- Each Xiaomi region names its own catalog: plan-cn/sgp/ams
  "xiaomi-token-plan-<r>, xiaomi", pay as you go "xiaomi" alone. A plan
  user is priced at the API-equivalent price, the same meaning as #1370.
- PricedBy is unchanged: a catalog that lists a model at $0 still prices
  it at $0 (nvidia, modelscope have truly free models).
- docs/subsystems/providers-accounts.md says so.

Providers saved before this: the preset's own catalog stays
"xiaomi-token-plan-cn, xiaomi", the same string an existing provider
saved with the old default holds. normalize already lets a catalog that
equals the preset's or one of its regions' follow the region the
provider is at (the Tencent Cloud mechanism), on every read, so an old
default at pay-as-you-go reads as "xiaomi" and at Singapore as
"xiaomi-token-plan-sgp, xiaomi"; nothing is written to providers.json
until the user next saves it. Any other catalog the user typed is kept
as typed, and is priced right anyway because the plan catalogs are out
of pricing. The one value that can't be told apart is a bare "xiaomi"
typed at a plan region (the issue's workaround, which was for pay as
you go): it equals the pay-as-you-go region's catalog, so it reads as
that plan's "xiaomi-token-plan-<r>, xiaomi". Its prices are identical
either way; only the model-metadata lookup order differs. That is the
existing rule for every preset with region catalogs, kept rather than
special-cased.

Siblings: scanned the models.dev cache (read only) for catalogs whose
priced models are all or mostly $0. Of those, only kimi-code-plan-* and
xiaomi-token-plan-* are named by any preset or region. stepfun's
*-step-plan catalogs carry no cost at all, so they never shadowed a
price. alibaba/minimax/zai/zhipuai/volcengine/tencent coding and token
plan catalogs are all-$0 on models.dev but no preset uses them.

Tests (internal/provider/xiaomi_price_test.go, fixture
testdata/xiaomi_catalog.json cut from models.dev's real entries):
- TestXiaomiListPrice: every region, the old default, a user's own
  catalogs: mimo-v2.6-flash $0.14/$0.28/$0.0028, mimo-v2.6-pro
  $0.435/$0.87/$0.0036; MakerPrice; EffectivePrice of a saved provider;
  a relay's own $0 model ahead of xiaomi stays $0; a Xiaomi provider is
  not a Kimi Code member.
- TestXiaomiRegionCatalogs: each region resolves to its catalogs from
  the preset's, the old default and another region's; import links at
  each region; FromPreset; a user's catalog kept at two regions.

Broken by hand, each red, then restored:
- membershipCatalogs back to Kimi only: TestXiaomiListPrice FAIL, plan
  regions and MakerPrice at $0.
- region catalogs removed: TestXiaomiRegionCatalogs FAIL (api with the
  old default stays [xiaomi-token-plan-cn xiaomi], imports at sgp/ams
  get cn's).
- both: TestXiaomiListPrice FAIL, api with the old default at $0 (the
  reported bug).
- kimiCodeMember on membershipCatalogs: FAIL "a Xiaomi Token Plan
  provider counts as a Kimi Code membership".
- PricedBy's exact match skipping all-zero costs: FAIL "relay
  mimo-v2.6-flash: ... want its own $0".

Run: gofmt -l (nothing); go vet ./... on darwin, GOOS=linux -tags nogui,
GOOS=windows; go build on all three; go test -tags nogui -count=1
./internal/provider ./internal/catalog ./internal/cli ./internal/gui
./internal/usage, all ok, in a sandbox HOME with pinned caches.
Real use: built binaries before and after, sandbox HOME with a copy of
the real models.dev cache and a providers.json holding the reporter's
saved state. `magpie model price xiaomi/mimo-v2.6-flash` printed $0/$0
before and $0.14/$0.28 after; an old-default provider at Singapore went
$0 -> $0.14/$0.28 and shows catalog "xiaomi-token-plan-sgp, xiaomi";
one with the user's "openrouter, xiaomi" kept it; providers.json was
byte-identical afterwards. Not tried: a real MiMo key or call, the GUI
editor's region switch, the full go test ./... suite.

Co-authored-by: mengyianx <106875577+mengyianx@users.noreply.github.com>

* provider: a Cursor Team member with no limit of their own spends the team's on-demand pool, shown and counted as the limit, not as unlimited (#1868)

PaSSw0rds' Team account (#1476) has on-demand turned on for the whole
organization: spendLimitUsage has no individualLimit, pooledLimit
"45120000" and pooledRemaining "38785730" are int64 strings, pooledUsed
6334270 a number, and GetHardLimit answers {"hardLimit": 451200} with or
without a team id. cursorOnDemandOf read that as unlimited, as
cursor-agent's own usage view does, so On-demand showed only the member's
$198.55 at 0%, aside, and a spent team pool never counted the account
used up; magpie would keep routing to it until Cursor refused.

Now a team member with no individualLimit and a pooledLimit > 0 gets a
fixed On-demand window on the pool: used = pooledUsed / pooledLimit,
display "$63,342.70 / $451,200.00 (you: $198.55)", not aside. A hard
limit that forbids on-demand still reads as disabled, and a team with no
pool and a hard limit still as unlimited. Dollar figures group thousands
(cursorDollars), as plugin 0.2.10 does. This is the built-in, for users
who haven't moved to the plugin; moved users get the same from
@magpie-community/opencode-cursor-auth 0.2.10 (next commit raises the
mover's min).

Run, under a sandbox HOME with pinned caches: go test -tags nogui
./internal/provider/ (ok); gofmt -l; go vet ./... on darwin,
GOOS=linux -tags nogui and GOOS=windows (clean).
Broken by hand: with the old cursor_usage.go,
TestCursorOnDemandKeepsTheAccount/a_team's_org-wide_on-demand_pool_is_the_allowance
fails (On-demand "$198.55", used 0, aside; the spent pool "used up
false"); with a fix that puts the member's spend against the pool, it
fails too. Built from the payloads quoted in #1476. Not tried against a
real Team account.

* provider: moved Cursor users get plugin 0.2.10, which counts a Team's org-wide on-demand pool as the limit (#1868)

@magpie-community/opencode-cursor-auth 0.2.10 (magpie-community/plugins
a885a16) gives a team member with no limit of their own a fixed
On-demand window on the team's pool (pooledUsed / pooledLimit, the
member's own spend beside it) instead of unlimited, the same change as
the built-in's in the previous commit. keepMovedCurrent updates every
moved user's plugin to it.

Run: 0.2.10 checked on registry.npmjs.org (latest, its tarball holds the
fix); go test -tags nogui ./internal/provider/ under a sandbox HOME (ok,
TestMovedBuiltinsSayTheirPlugin included); gofmt -l and go vet on darwin,
linux (nogui) and windows clean.

* gui: an opened agent's labels stay on one line, the column as wide as its longest label (#1169, emo172)

The opened row's label column was a fixed 112px with nothing to stop a
label from wrapping, so "In {agent}" broke over two lines for long agent
names (Cursor Private Inference, DeepSeek Harness) and for wider UI
fonts, and pushed its row taller than the rest. The rows now share one
grid whose label column is minmax(112px, max-content) with nowrap, so
every label sits on one line and every value starts at the same x. Under
600px the rows still stack, label over value.

Run (by the maintainer, on origin/main 97dfed0f with this commit):
- the new "opened agent labels stay on one aligned line" test fails on
  main in all ten engine/language runs (chromium and webkit; en, zh,
  zh-TW, ja, de): "a wide label wrapped: In Cursor Private Inference,
  lines 2, labelWidth 112"; passes with this commit.
- every GUI test that opens an agent row, plus gui-de/gui-ja/gui-zh-tw,
  45 files, chromium and webkit: 701 pass, 0 fail.
- the same test at 610, 680 and 760px wide (between the stacked
  breakpoint and the desk width), every language: no label wraps and
  nothing spills out of the opened row.

* gui: the line over each opened agent setting runs unbroken across label and value (#1169)

The label/value grid that keeps "In {agent}" on one line put 16px of
column-gap between the label's top border and the value's, so every
separator in the opened row had a 16px hole in it where one line ran
across before. The space between the columns is now the label's own
right padding (column at least 128px = the old 112px label + 16px gap),
so the two borders meet.

Run: agent-field-names' "one aligned line" test now also checks that
each value starts where its label's box ends. With the previous commit's
CSS it fails in all ten engine/language runs ("a gap between a label and
its value", valueLeft 16px past labelRight); with this one it passes.
The 45 GUI files that open an agent row plus gui-de/ja/zh-tw, chromium
and webkit: 701 tests; mobile-web's desktop screenshots match 97dfed0f
(BASE_REF=97dfed0f; against a newer origin/main its gateway shot
differs by #1514's Connect snippets, which this doesn't touch).
Screenshots in German at 980px before/after compared by eye.

Co-authored-by: 尤贺雨 <youheyu@sungrowpower.com>

* usage: the Context tab's curve no longer draws the leanest value's label over the axis's first one when they sit a step apart (#1549, Ti800)

The axis labels the advice's value, the setting now and the range's two
ends. One that sits within 16% of the axis of one that matters more (the
advice first, then the setting now, then the ends) is left off, so two
labels are never drawn over each other: 170K one step from 160K read as
"1170K".

* usage: the tags over the Context curve's dots never print over each other either (#1549)

The previous commit keeps the axis labels apart. The tags over the dots
had the same fault: a setting one step from the advice printed its
"+3%" on "Leanest", and a setting one step from the costliest value
printed "+147%" on "+150%". The tags now go by the same rule, "Leanest"
first, then the setting now, then the costliest: one within 16% of the
axis of a tag that matters more and at about its height (20 of the
plot's 100 units) keeps its dot and tooltip but not its tag.

Run: context-tune's overlap test gains a row whose setting sits one step
from the advice, checks the tags' boxes as well as the axis labels', and
runs in German ("Sparsamste", the widest "Leanest") as well as English,
at 360 and 1100px. With the previous commit's context.js it fails in
chromium and webkit ('en 360px: tag "+150%" overlaps "+147%"'); with
this one it passes. The axis test alone failed on main before the
previous commit ('360px: "160K" overlaps "170K"'). context-tune,
compact-at and context-window: 80/80. 56 context/usage/language GUI
files in both engines: 652/654; the two reds are usage-ledger's route
export (passes 3 of 3 alone, filed as #1876) and, in an earlier run,
usage-sum-whole at 780px in German (#1864, noted there); neither reads
context.js.

Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>

* library: start stdio MCP checks in the home directory (#1727)

A magpie started from a Windows shortcut keeps C:\Windows\system32 as
its cwd. The Library check inherited that directory, so a server that
writes into "." failed as exited (1) with no log. Agents start the same
server from a project or home directory and succeed. Pin cmd.Dir to HOME
for the check.

* library: a checked MCP server's PWD is home too, and #1727's cwd test holds on macOS (#1727)

The previous commit starts the check's server in home. Its own test
failed on macOS with that fix in: the child reported
/private/var/folders/.../magpie-test-home-N and HOME was
/var/folders/.../magpie-test-home-N, the same folder spelled through
macOS's /var symlink, compared as strings. The test now compares the
folders with os.SameFile.

exec sets PWD to Dir by itself only when Env is nil, and the check sets
Env, so the server ran in home with PWD still naming magpie's own
folder; a shell-script server that reads $PWD would see the folder the
fix moved it out of. The check now sets PWD=home with Dir (not on
Windows, which doesn't use PWD, as exec does), before the server's own
variables so one it sets still wins.

The two subtests now give each run a home of its own (t.Setenv HOME and
USERPROFILE) and move the process with t.Chdir, so the "needcwd" fake's
./logs goes with the test instead of staying in the package's shared
test home, and nothing is left in another cwd when a subtest fails. The
read-only-cwd subtest also checks that ./logs landed in home: Windows
doesn't enforce a folder's read-only bit, so that is what makes it fail
there without the fix.

Run (sandbox HOME, private GOCACHE): TestCheckStdio -count=3 on macOS;
the whole internal/library package. Broken by hand: without cmd.Dir both
subtests fail (wrong folder; "mkdir logs: permission denied"); without
the PWD line the cwd subtest fails on its PWD. On the Windows box
(windows/amd64 test binary): TestCheckStdio passes, and without cmd.Dir
both subtests fail there too (the server ran in the test's temp cwd,
and ./logs wasn't in home).

Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>

* netproxy, provider, gateway: every request to the ChatGPT backend goes over HTTP/1.1, magpie's own too, not only the gateway's turns (#1700)

f6e1e98e put the gateway's turns to chatgpt.com on HTTP/1.1 through a
wrapper on the gateway's client. magpie's own requests there go through
http.DefaultClient and still spoke HTTP/2: the models list
(codexModels), the warm-up's POST to /backend-api/codex/responses
(warmCodex), the allowance (codexWindows via accountJSON), the reset
credits (codexResets) and spending one (consumeCodexReset). #1700's
reporter, on 0.1.1164, had Codex's /responses fail with PROTOCOL_ERROR
through a local proxy until GODEBUG=http2client=0, set by editing the
app bundle.

The rule now lives where every magpie Go client goes through.
netproxy.Dispatch sends a request netproxy.HTTP1 names through a clone
of its transport kept for HTTP/1.1, beside a provider's own proxy if
any, and the provider package sets HTTP1 to codexBackend (CodexBase's
host). The clone's TLS hello offers no ALPN, as codex-cli's: a transport
that has spoken HTTP/2 carries h2 in its TLS config, which a clone
copies, and a server that took it would be sent HTTP/1.1 on an HTTP/2
connection. The gateway's codexHTTP1 wrapper is folded into this; its
transport file is now upstream_transport.go. Every other vendor is still
offered HTTP/2, and GODEBUG=http2client=0 still turns HTTP/2 off for all.

What was run (Go 1.26.8, darwin/arm64, a sandbox HOME):
- TestCodexBackendOwnRequestsOverHTTP1 (provider): http.DefaultClient
  as netproxy.Install leaves it, a TLS server offering HTTP/2, the five
  requests directly, through Settings' proxy and through an account's
  own CONNECT proxy. On origin/main 6c1c0a74 it fails: all five
  "HTTP/2.0 (h2 offered)" each way. Another vendor's accountJSON read
  stays HTTP/2.0.
- TestDispatchHTTP1 (netproxy): after the transport has spoken HTTP/2
  to the server, a named request arrives HTTP/1.1 with no h2 offered,
  with a proxy choice too. Without the NextProtos reset it fails with
  "malformed HTTP response"; with HTTP1 ignored, with "HTTP/2.0".
- With the provider's hook off, the gateway's TestCodexBackendOverHTTP1
  fails too ("asked over HTTP/2.0, not HTTP/1.1"). TestAccountProxy,
  which stubs http.DefaultClient with a Dispatch of its own, passes; a
  separate Codex client in provider, tried first, failed it.
- go test -race -count=20: ./internal/netproxy TestDispatchHTTP1 and
  TestWith, ./internal/provider TestCodex* (this one included),
  ./internal/gateway TestCodexBackendOverHTTP1 and TestAccountProxy.
  gofmt -l; go vet (darwin, GOOS=linux -tags nogui, GOOS=windows); go
  build (the same three); go test -tags nogui ./... (49 packages) pass.
- Real use, behind Clash on a Mac: Codex's own sign-in copied into a
  sandbox HOME (days left on the token, nothing refreshed), and a
  CONNECT proxy in front of Clash logging each TLS hello's ALPN.
  origin/main: `magpie provider models codex` and one request at the
  gateway's start offered h2 to chatgpt.com, the turn none. This
  branch: no hello to chatgpt.com offered any, models.dev still h2.
  #1700's minimal request on codex/gpt-6-astra answered 200 with
  MAGPIE_CODEX_OK on both.

Not reproduced: PROTOCOL_ERROR itself; chatgpt.com answered HTTP/2 on
this Mac, so whether HTTP/1.1 is what the reporter's path needs is for
their use to say. The warm-up and spending a reset weren't sent for
real.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XSjhwVsPdGd6QUTrq4KvE4

* mcpauth: a server that registers magpie for a client authentication magpie can't do is said no at the registration

What changed: register took the registration response's
token_endpoint_auth_method as it came. RFC 7591's response lets the
server assign another of the methods it supports than the one asked
for, and one assigned that magpie can't send (client_secret_jwt,
private_key_jwt, tls_client_auth) opened the sign-in page all the
same: the failure came at the code exchange, after the browser round
trip, as "the token endpoint answered 400: invalid_grant", and every
renewal would fail the same way. A method outside none,
client_secret_post and client_secret_basic is now refused at the
registration, before the browser is opened, with the request side's
own wording. An assignment magpie can do (a server handing
client_secret_basic and a secret for a client that asked none) still
works as before.

mcpauthtest.Fake gains Assign: a server that registers the client for
another of the methods its metadata lists, giving a secret and taking
the token endpoint's word for it. Without it set, the fake answers as
it did.

Run:
- TestSignInRefusesAssignedSecretJWT (new) fails on the old register:
  "the sign-in page was opened for a client magpie can't authenticate
  as: http://127.0.0.1:…/oauth/authorize?…" — and passes now, Start
  saying the server registered magpie for client_secret_jwt, which
  magpie can't do.
- go test -tags nogui -count=1 ./internal/mcpauth/... ok, every
  existing case unchanged; full go test -tags nogui ./... under a temp
  HOME ok except testenv's TestOffline, red the same on the untouched
  baseline (loopback proxy escapes this machine).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet clean; go build, GOOS=linux go build -tags nogui, GOOS=windows
  go build ok.
- Not tried against a real authorization server that assigns a method:
  none is known in the wild; this is the response-side half of #1490's
  class, set by RFC 7591.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

* mcpauth: an assigned method magpie can do is checked to sign in and renew, both ways round (#1490)

The previous commit refuses at registration a method the server assigns
that magpie can't send. The owner asked on #1490 that an assignment
magpie can do be shown still to work; no test did. One now does, for
the code exchange and a renewal after the access token is refused:

- asked none, assigned client_secret_basic with a secret;
- asked none, assigned client_secret_post with a secret;
- asked client_secret_post, assigned none with no secret (a public
  client), which sends no secret;
- asked client_secret_basic (the only one listed), assigned post.

The fake's registration took an assigned method only when its metadata
listed it, so "none" assigned to a server listing only post was turned
away as invalid_client_metadata; a method the server assigns is one it
supports, so with Assign set it is taken.

Run (sandbox HOME, private GOCACHE): the new test and
TestSignInRefusesAssignedSecretJWT, TestSignInBySecretBasic; go test
-race ./internal/mcpauth/... and ./internal/library (which signs in
through the fake) pass. Broken by hand: with register ignoring the
response's token_endpoint_auth_method the new test fails at the first
case ("the token endpoint answered 400: invalid_grant"); without the
previous commit's check TestSignInRefusesAssignedSecretJWT fails ("the
sign-in page was opened for a client magpie can't authenticate as").

Co-authored-by: ggbdpq <ggbdpq@gmail.com>

* gateway: the client's comment points at where the ChatGPT backend's HTTP/1.1 rule now lives (#1700)

The previous #1700 commit deleted gateway/codex_http1.go and moved the
rule into netproxy.HTTP1, which provider/codex_http1.go sets; the
comment on the gateway's client still named the deleted file.

Review of #1700 (no other change needed): every Codex request magpie
makes goes through a netproxy.Dispatch transport, http.DefaultClient's
(codexModels, warmCodex, accountJSON for /wham/usage and the reset
credits, consumeCodexReset) or the gateway's s.client (turns, /models);
the HTTP/1.1 clone keeps netproxy.Func, or the account's own proxy,
and Clone deep-copies TLSClientConfig, so clearing NextProtos there
leaves the base transport offering h2 to every other vendor.

Run on 7485065d (the cherry-picked #1700, sandbox HOME, private
GOCACHE): go test -tags nogui ./internal/netproxy ./internal/provider
./internal/gateway pass; -race on TestDispatchHTTP1, TestWith,
TestCodexBackendOwnRequestsOverHTTP1, TestAccountProxy (provider and
gateway) and TestCodexBackendOverHTTP1 pass. Broken by hand: with
netproxy.HTTP1 left nil, TestCodexBackendOwnRequestsOverHTTP1 fails
(all five requests "HTTP/2.0 (h2 offered)") and the gateway's
TestCodexBackendOverHTTP1 fails ("asked over HTTP/2.0"); without the
NextProtos reset TestDispatchHTTP1 fails ("malformed HTTP response",
the server took h2 from the hello). gofmt -l clean; go vet darwin,
GOOS=linux -tags nogui, GOOS=windows clean; linux and windows builds.
Not reproduced: the reporter's PROTOCOL_ERROR itself.

Co-authored-by: appointat <65004114+Appointat@users.noreply.github.com>

* usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)

What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
  one record or an array, in usage.jsonl's shape:
  - the post may carry up to 5000 records and 32 MiB;
  - t, agent, provider, model and rid are required.
  Each field is checked: unknown fields, quoted numbers, negative or absurd
  counts, a status outside 100-599, a cost over 10000 USD, and a t more
  than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
  whole post with a 400 that names error.index and error.param, and nothing
  is written. A past t is otherwise taken as given, so history can be
  backfilled. The reply gives accepted and skipped counts and each
  record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
  shared, behind the Host check). A browser page also needs a key, since
  corsGuard lets localhost pages and Origin null through. A held key is
  refused.
- usage.IngestReported writes under usage.mu to the same file as
  usage.Append. Rows carry source "reported" and no caller key. A rid
  already reported is skipped, as is one repeated in the post. The set of
  reported rids is read back from the log: one scan after a restart (lines
  without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
  flag; packed flags widened to uint16). Otherwise it is priced at
  magpie's prices.
- Display:
  - SourceReported is a source of its own: RequestPage.Reported,
    ?via=reported, and Ledger now honours via.
  - The Requests tab gains a fourth cell "reported by apps", shown once
    there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
  - a key's budget/spend limit (budget.counts);
  - window holds, and the log start that decides whether a window can be
    reckoned (logSnapshot.firstOwn);
  - gateway sessions and Vias;
  - Codex's sealed answers and remembered model.
  There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
  site integrate.html (en, zh).

Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.

Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
  - usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
    languages, 1180 and 420 wide, light and dark);
  - usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
    usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
  - 40 posts of 5000 took 0.40 s (worst batch 18 ms);
  - the first post after a restart took 0.45 s (rid rescan), a later one
    1.6 ms;
  - the cold index build took 2.1 s (as for gateway rows);
  - page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
  - summary all took 215 ms, 30d 20 ms.

Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
  cost; the block pricer overwriting own cost; the Reported split;
  fromBrowser's key rule; skipping bad records instead of refusing; the
  max-records and body limits; the ingest lock (race); both locks;
  firstOwn -> first; the IsReported guards in windowHolds,
  buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.

Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.

* provider: a Claude usage ask invalidates an older read even in the same clock tick

Refs #1228. The original test fails with "a reading from before the ask
was kept". A temporary diagnostic measured identical UnixNano values for
the read's start and the later ask; that diagnostic is not shipped.

What changed:
- Count both whole-page and manual-card Claude asks with a generation.
  Advance it under subscription then login cache locks, so publication
  cannot check the old generation and then commit after the ask.
- Capture the generation before launching LoginUsage/SubscriptionUsage;
  reject an older account read or leave the cards due for another read.
- Record each Claude /usage run's ask generation. Keep timestamps, the
  zero sentinel, floor, idle behavior, saved-account scope and fallbacks.
- Document ordering and lock ownership in the providers/accounts design.
  No tests, routing.go, account files or dependency versions changed.

Run on upstream 8f2a314cf9:
- Original test unchanged: count=50 passes (12.317s). Product-only stash
  restores real red, count=30 (7.077s); pop then count=5 passes (2.137s).
- Expanded usage/header/saved-card paths race count=5 pass (122.691s),
  Go 1.26.8 and installed MinGW gcc, external sandbox home/temp and
  pinned Go caches.
- Provider nogui vet passes on Windows, Linux, Darwin. Windows default
  build and Linux/Darwin nogui builds pass. gofmt and staged diff clean.
- Provider full package and full ./... were not rerun; real account,
  GUI engines/languages, Darwin GUI build and cross-OS runtime not tried.
  Targeted evidence only, not a claim of complete merge acceptance.

Generated-by: Factory Droid (GPT-6.1 Sol)

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

* gateway: a broken tool exchange a Chat or Zed client left is mended for a Messages upstream, as the Chat and Responses paths mend theirs

What changed: buildAnthropic (every request built for a Messages
upstream: a Chat or Responses client's conversation translated, Zed's
bridge) now runs its messages through pairToolBlocks, as buildChat's
pairToolMessages (#554) and the relayed Responses path's pairToolItems
(#1341) mend theirs. Anthropic refuses a tool_use the next message's
tool_results don't answer ("`tool_use` ids were found without
`tool_result` blocks immediately after") and a tool_result naming a call
it never saw ("unexpected `tool_use_id` found in `tool_result` blocks");
an interrupted turn leaves the first behind, a client that dropped a
call the second. A call left unanswered gets the synthetic result the
other paths make; an answer to no call becomes a text block keeping
what it said. A well-formed exchange is built exactly as it was (ids in
their places, results in the order the client sent, text after them).

TestZedToolResultSaysIsError's fixture carried a result for a call the
request never made; it asserted the orphan went through as a
tool_result, which the cloud refuses. It now goes out as the text it
said, and the test says so.

Run:
- /tmp/sbx.sh test -tags nogui -count=1 -run 'TestMessages' ./internal/gateway/
  with the pairing call taken out: 6 FAIL (trace "user assistant(A)",
  and the end-to-end one 400 "unexpected `tool_use_id` found in
  `tool_result` blocks"); with it back in, all pass
- /tmp/sbx.sh test -tags nogui -count=1 ./internal/gateway/ — ok
- gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... (the trayimage_darwin.go -Wenum-conversion
  warning as on main), go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

* provider: tests that a Claude usage ask on a read's own clock tick is answered (#1228)

What changed: three tests for c56eccab's generation counter, one per
place a Claude reading is kept against an ask: loginReading (LoginUsage),
SubscriptionUsage's whole-page cache, and claudeWindows' /usage run.
Each asks while the reading is under way and stores the ask's time as of
before the reading began, as Windows' ~15ms clock or a clock set back
reads it. TestLoginUsageClaudeAskedMeanwhile only failed on Windows, 3 in
5, because on macOS the two times never tie; these fail every time on the
old code. The claudeWindows test also ages the answered run past the 30s
floor and checks no run follows unasked.

Why: the patch came with no test of its own that fails on the old code
outside Windows.

Run (sandbox HOME, private GOCACHE, go1.26.8 darwin/arm64):
- with the three product files put back to origin/main: all three FAIL
  ("a reading from before the ask was kept", "cards read before the ask
  were kept as fresh", "the ask wasn't answered: <nil>, 1 runs").
- broken by hand, one at a time: loginReading's check made always true
  (login test red); SubscriptionUsage's reset dropped (page test red);
  the successful run's entry without asked (claudeWindows "ran again
  unasked: 3 runs"); markClaudeUsageAsked's Add removed (all three red);
  RefreshUsage's markClaudeUsageAsked removed (existing
  TestRefreshSavedClaudeUsage red).
- go test -tags nogui -count=3 -run 'AskedOnThe|AskedMeanwhile' passes.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>

* gateway: Zed's test still checks is_error true on a real result, beside the mended orphan (#1558)

What changed: d1d45dd3 made TestZedToolResultSaysIsError's toolu_2 result
an orphan turned to text, and its assertion went from [false true] to
[false]: nothing checked any more that a result with is_error true goes
to Zed's cloud with it (yetone/magpie-releases#9). The fixture's
assistant now makes toolu_2's call, so both real results keep [false
true], and a separate toolu_9 result with no call checks the orphan goes
as its text. The pairing tests also check the synthetic result is
is_error, and a new TestMessagesSecondAnswerDropped checks a call answered
twice keeps only its first answer. docs/subsystems/gateway-routing.md gets a bullet for the Messages build's mending, beside the Gemini and Responses ones.

Why: the patch's tests passed with is_error dropped from the synthetic
result and with the second-answer rule removed.

Run (sandbox HOME, private GOCACHE):
- go test -tags nogui -run 'TestMessages|TestZed' ./internal/gateway/: ok
- pairToolBlocks call removed: the six TestMessages tests and
  TestZedToolResultSaysIsError fail ("is_error: [false true false]",
  "what the lost result said is not kept").
- IsError dropped from the synthetic result: TestMessagesUnansweredCall
  GetsSyntheticResult fails. The duplicate's continue removed:
  TestMessagesSecondAnswerDropped fails ("user[A,A]").

Co-authored-by: ggbdpq <ggbdpq@gmail.com>

* usage: time tool-only replies only with visible reasoning evidence

Revises #1463 after the hidden-reasoning inflation review. Keep answers separate, retain evidence in routes and cached ledger rows, and exclude sealed or summary-only reasoning even without a token breakdown. Sync the backend and both GUI formulas.

Checked real WorkBuddy DeepSeek, Codex and Claude bridge responses in an isolated HOME; sanitized timings and failures are in docs/verification. Chromium/WebKit speed regressions pass (20 tests, five languages). New edge regressions and loop-order check pass under race repetition. Restoring the old formula or removing the hidden guard fails TestVisibleReasoningSpeed. macOS/Linux/Windows vet/build pass. Full-suite verification is recorded in the issue at this head; inherited proxy/Bun 1.3.14 failures are retained, with clean Bun 1.4.2 rerun in progress. No installed app replacement.

Rebased onto main by yetone (#1463). Conflicts with main's Own/Retried/
Queued/Tries row fields, HandedOn and the Codex speed floors were resolved
by keeping both. The packed row's ReasoningHidden bit was 64, which main
has since given to block_price.go's swapKnown, and main's rowHandedOn took
128, filling the uint8: Flags is now uint16 and ReasoningHidden is bit 512
(rowReasoningHidden; #1874's rowOwnCost took 256), read back in row(). The docs/verification notes and
their sample JSON are left out of the tree; they stay on the contributor's
branch and the issue. Run after the rebase: go test -tags nogui ./internal/usage/
and the gateway's reasoning/speed/TTFT tests, ok.

* usage, gateway: tests for the #1463 rebase: a priced row keeps its reasoning evidence, and a summary after an endpoint fallback stays hidden

Follow-up to congee949's rebased dfc24632
(#1463, streamed reasoning speed).

- TestPricedRowKeepsReasoningEvidence: the Requests page reads gateway rows
  through blockPricer, which sets swapKnown (64) on every row. The patch
  put ReasoningHidden on bit 64 too; on main that would have read every
  priced row as hidden, so a tool-only reply with no reasoning, and paced
  visible reasoning, lost their speed on the Requests tab. The rebase gave
  ReasoningHidden its own bit (256, Flags widened to uint16); this test
  prices visible, tool-only and hidden rows, raw and packed, and checks
  the flag and the speed read back.
- TestSummaryAfterEndpointFallbackStaysHidden: a Messages client, a model
  answered on /responses after /chat/completions said it isn't served
  there. call.To still reads Chat, so hidesReasoning(call.To) doesn't see
  the summary; only streamTranslated's summaryUpstream marking does. With
  no reasoning count the 1500 output tokens were otherwise timed from the
  first summary delta. Nothing covered that marking before.
- reasoning-speed.test.cjs: the "no reasoning: 500 in 5 s" comment had
  been joined onto the redacted row; put back on its own row.
- docs/subsystems/gui-shell.md: the flag bit, the fallback marking, the
  two tests.

Run: go test -tags nogui -count=1 ./internal/usage/ and the gateway's
reasoning tests; reasoning-speed.test.cjs in Chromium and WebKit (en, zh,
zh-TW, ja, de), 10/10.
Broken by hand: rowReasoningHidden = 64 turns TestPricedRowKeepsReasoningEvidence
red (visible and tool-only rows read hidden, 0 tok/s); summaryUpstream
forced false turns TestSummaryAfterEndpointFallbackStaysHidden red (1500
tokens in 314 ms).

Co-authored-by: congee949 <c86474321@gmail.com>

* sessions: read Cursor editor history and Cursor/OpenCode conversations (#1743)

Discover editor project transcripts and cursorDiskKV histories without modifying the source. Share one SQLite/WAL snapshot across a scan, refresh metadata changes, deduplicate CLI histories, and reject deletion of read-only sessions.

Count message-only sessions and expose an all-dates action when a filter hides existing history. Read Cursor CLI text, reasoning and tool parts, and OpenCode v1/v2 transcripts through the existing transcript API.

* sessions: reproduce missing editor histories and unreadable conversations (#1743)

The new Go tests fail on upstream 6a8b2c68 with missing editor sessions and ErrNoTranscript; the date-range UI test fails on the missing history shortcut.

* sessions: search finds Cursor and OpenCode sessions read from their stores, and a Cursor chat's system prompt isn't shown as said (#1743)

Follow-up to liubing's #1743 patch, which put cursor and opencode in
HasTranscript. That moved their search from magpie's recorded
transcript to SearchSession, whose byte prefilter (mayHold) reads
s.Path. For these agents s.Path isn't the conversation:
- OpenCode's JSON storage: the session info file, without messages,
  so every word missed;
- OpenCode's and Cursor's SQLite stores: the newest pages are in the
  -wal, so a live chat's latest turns missed.
linesFile now skips the prefilter for them (a Cursor .jsonl still
gets it).

cursorTranscript also handed the CLI store's system message ("You
are a coding agent.") to the transcript as a said part; system
messages are skipped, as the listing already does.

The patch's tests commit left TestSearchSessionWithoutATranscript
red (it used cursor as the agent without a transcript; now gemini).
sessions-empty-range.test.cjs runs in every language, de at 420px.

Run: go test -tags nogui -count=1 ./internal/sessions/ ok, and -race
ok; sessions-empty-range 10/10 (Chromium+WebKit, en zh zh-TW ja de);
sessions-today/overview/toolbar/search/manage/calendar-fill/paging
GUI tests pass.
Broken by hand: prefilter always on -> TestSearchOpenCodeFiles and
TestSearchCursorLiveChat red; system skip removed ->
TestSearchCursorLiveChat red. Also broke the patch itself: editor
files not appended, readOnly Delete guard, stats message dates, CLI
dedupe, HasTranscript entries, parseCursor readOnly dispatch, and
the "All sessions" button (via MAGPIE_TEST_APP_JS); each went red.

Co-authored-by: liubing <lb0806@foxmail.com>

* library: two changes in one millisecond each get a backup folder of their own (#1743)

liubing reported on #1743 that TestRemoveFoundEntryEveryFormat failed
in a full run on Linux, the backup read holding another format's
content, on an unmodified main too. The backup folder was named by
the millisecond and taken as this change's own: a second change in
the same millisecond wrote into the first's folder, its file kept
under its folder's name since the first's held the name, and the
copy at the name the change wrote was the other change's. The test's
loop runs one change per format, all named config.json, and on a fast
machine two land in one millisecond. A user's two quick changes did
the same: the backup the second change named wasn't its own.

freshBackup makes the folder with os.Mkdir, adding -2, -3... when the
millisecond's is taken. pruneBackups' sort keeps them in order.
Siblings checked: the skill backups (keepLibrarySkill, keepReplaced,
setAside, carry's and RemoveSkills' aside) use per-skill paths under
the stamp; setAside already steps past a taken name, and the others
only collide on the same skill in the same millisecond, where move
fails loudly rather than mixing; they are left as they were, since
a folder each would split one change's skills over many folders.

Run: go test -tags nogui ./internal/library/ ok on macOS and in
Docker golang:1.26.8 GOTOOLCHAIN=local (also -count=30 of the two
tests). The original red didn't show in Docker in 100 runs; it was
reproduced by injecting a minute-wide stamp, which turned
TestRemoveFoundEntryEveryFormat red on the old code and leaves it
green with the fix. Broken by hand: os.Mkdir -> os.MkdirAll (no
claim on the folder) turns TestBackupsInOneMillisecond red.

* usage: a test that a row's own cost and its hidden reasoning are read back apart (#1463, #1874)

#1874 (d4c2512d2) gave the packed row's Flags bit 256 to rowOwnCost
while the #1463 rebase gave the same bit to rowReasoningHidden; the
rebase onto it moved rowReasoningHidden to 512. With both on 256 a
reported call that said its cost read back as hidden reasoning (its
speed dropped) and every hidden-reasoning row as having said its own
cost. TestRowFlagsApart checks both rows raw, priced and packed, and
that no Flags bit is used twice.

Run: go test -tags nogui -count=1 ./... ok on macOS at this head
(rebased on d4c2512d2); gofmt and vet clean.
Broken by hand: rowReasoningHidden back to 256 turns both subtests
and the bit check red.

Co-authored-by: congee949 <c86474321@gmail.com>

* sessions: Kimi Code's own calls reach Usage, read from its wire files (#1607, infinitr0us)

Usage counts the gateway's calls and the calls the agents' own session
files record (sessions.Calls). Kimi Code had no reader, so its calls
straight to api.kimi.com on Kimi's own sign-in never showed (the
reporter's 47 k3 calls of one session on 2026-10-11).

The reader (calls_kimi.go) is built from the redacted real wire files
infinitr0us shared from two machines (protocols 1.0, 1.4, 1.5; text
replaced, every id, model and number kept) and their notes from Kimi
Code's source. It reads every agents/*/wire.jsonl under
$KIMI_CODE_HOME/sessions, else ~/.kimi-code/sessions (as agent.KimiDir
finds the new Kimi Code), main and subagents, ses_* folders included.
One call per usage.record: inputOther, inputCacheRead and
inputCacheCreation go to Input, CacheRead and CacheWrite, output as is,
the record's own model and time. Nothing is paired with step.end, since
1.4 and 1.5 write them in opposite orders and the June 1.4 build has no
messageId or llm.request. A model beginning "magpie/" (magpie's own
entry in Kimi's config) is skipped: the gateway counted it. kimi fork
copies the parent's records unchanged, so a call is keyed by agent
(agentId, else its agents/<id> folder), time, model and usage, and Calls
counts a key once. It is a whole-file call source (callSources,
wholeCallReaders) and the folder is watched (Dirs). The subsystem page
gets the list of call readers.

Fixtures (testdata/kimi-code) are the reporter's files cut to the lines
a call is read from, each line verbatim (50 KB; one of the July
session's eight agents kept).

Run: the reader over the reporter's whole, untrimmed files gives exactly
their README's totals (32/2,841,972/12,283; 151/7,025,587/122,782;
6/147,822/2,009; 10/338,328/2,176; 0 for the four others).
TestKimiCodeCalls (both homes), TestKimiCodeSkipsCallsThroughMagpie,
TestKimiCodeForkCountsOnce, TestKimiCodeBrokenFiles (cut mid-record,
empty, junk, null/negative/timeless usage) pass. Broken by hand, each
goes red: no magpie skip, no key, key without agent, no negative or
time guard, main only, KIMI_CODE_HOME ignored, cache read dropped.
go test -tags nogui ./internal/sessions ./internal/usage ./internal/cli
./internal/gui under a sandbox HOME, gofmt -l, go vet (darwin),
GOOS=linux go vet -tags nogui, GOOS=windows go vet.

Not tried: a live Kimi Code run (fixtures are the reporter's real
files, not a sandbox capture), a successful call through magpie (the
magpie-routed record in the test is the reporter's quoted 1.5 line with
a magpie/ model), a compaction record (usageScope "session", none in
the files), Kimi Code in WSL (not read), Windows paths at runtime. A
subagent's calls carry the session but no Subagent field.

Thanks to infinitr0us for the write-up from Kimi's source and the
redacted wire files.

Reported-by: infinitr0us

* agent: Goose's requests show as Goose on Routing and in Usage, by a key that names it (#1083, EZN7L2C3)

Goose's HTTP client sends no User-Agent (reqwest's default in
crates/goose-providers/src/api_client.rs, checked on block/goose main), and
the custom provider magpie writes for it (custom_providers/magpie.json)
carried the plain gateway key. The gateway tells an agent by its key first,
then its User-Agent, so Goose's requests were "your agent" on Routing and
"other" in Usage. The file now carries agentKeyAt("goose") (magpie-goose on
this machine, the LAN key from a NAT'd WSL distro, as before), the same as
Alma, Hanako, Snow, AstrBot and Prime Agent, which also send no User-Agent.
Goose's Check compares the same key, so a file an older magpie wrote counts
as drift and Sync rewrites it. Goose reads custom_providers at start, so a
running Goose needs a restart (the existing notice says so).

Tests: TestGooseKeyNamesGoose (the key written, an older file's plain key
noticed by Check and replaced by Sync) and TestGooseRunsOnMagpie's key
assertion fail on the old code (Authorization = "Bearer magpie", want
"Bearer magpie-goose"). Breaking only the Check back to the plain key fails
both with "headers.Authorization (magpie.json) was changed". The gateway's
TestGooseAgentByKey records a request with no User-Agent and magpie-goose
as goose's (it passes on the old code: the gateway side already worked; it
guards the path end to end). go test ./internal/agent/ ./internal/gateway/
in a sandbox HOME. Not tried with a real Goose.

* gateway: a key set to a protocol its provider has no URL for is said on Routing and in the editor, not passed over quietly (#1702, edussss)

edussss set a relay key to Responses only on a provider with a Chat URL
and no Responses URL. perKeyBarred skipped the key (no endpoint for its
protocol), every key was skipped, so the provider was tried whole and the
request went out on Chat with nothing saying why. The owner: it shouldn't
fall back quietly.

Requests are still served on the URLs the provider has (so working setups
keep working), but now it is said:
- fallback.go: perKeyBarred remembers the protocol of the first key it
  skipped for having no URL, and the whole-provider candidate carries it
  as noURL.
- trace.go: Weighed.NoURL, so the Routing page sees it.
- routing.js: the row and the activity line say "key set to {api} only,
  no {api} URL · sent on the others".
- app.js/app.css: the editor's key row shows an amber "No {api} URL" chip
  (keyLacksURL) with a title that says how to fix it.
- i18n.js: the three strings in zh, zh-TW, ja and de.
- docs/subsystems/providers-accounts.md: the Keys row says so.

Run: go test -run 'TestKeyForAProtocolWithNoURLIsSaid' ./internal/gateway/
(the reporter's case: upstream /v1/chat/completions with k-resp, NoURL
"responses"; with an Any key added it goes to k-any and NoURL is empty);
key-nourl.test.cjs in chromium and webkit, en/zh/zh-TW/ja/de, at 420 and
1000 wide, no click-scroll, no sideways scroll: 40 pass; with i18n-keys,
gui-zh-tw/ja/de, key-copy, key-weight, key-weight-fit, key-import,
routing-key-windows, routing-keys-fold, proto-menu-overflow, nokey-editor
and ledger-protocol: 174 pass, 0 fail.
Broken by hand: without the noURL mark the Go test fails (noURL = "",
want "responses"); with keyLacksURL/noURLWord removed chromium fails 20
of 20.
Not tried: a real relay, or the GUI against a live gateway.

* agent: an IDE plugin's ~/.copilot or ~/.qoder-cn isn't taken for the CLI (#1495, v5tech)

v5tech traced two agents listed with no CLI installed to the JetBrains
plugins that write the CLI's folder:
- GitHub Copilot's JetBrains plugin writes ~/.copilot (ide/, instructions/,
  prompts/, agents/, skills/, hooks/; the paths are in its jar). Copilot
  CLI was detected by that folder alone.
- Qoder CN's JetBrains plugin fills ~/.qoder-cn (its indexer in
  shared_client/, app/, plugins/) and writes a settings.json holding only
  {"enabledPlugins":{...}}, which is the CLI's Path, so the CLI was found
  by its "config file".

What changed:
- Copilot CLI sets dirShared, as omp does for Pi's folder: settings.json
  or the copilot command still finds it.
- Agent gets pathOwn: when set, the file at Path counts only if it says
  the file is the agent's. Qoder (both builds, one qoderAt) sets dirShared
  and pathOwn = !qoderPluginOnly: a settings.json that parses as an object
  of enabledPlugins alone is the plugin's. Any other key, {}, or a file
  that can't be read or parsed still counts (unknown is not "the
  plugin's"), and so does qodercli / qoderclicn on PATH. The global build
  is held to the same because the code and the plugin are shared; that
  the intl plugin writes ~/.qoder the same way is by analogy, not seen.
- docs/subsystems/agent-wiring.md says so.

Run: go test ./internal/agent/ -count=1 (ok, 226s), including the new
TestCopilotFolderFromAnIDEPluginIsNotTheCLI and
TestQoderSettingsFromAnIDEPluginIsNotTheCLI (the reporter's folders,
then the command on PATH, then the CLI's own settings).
Broken by hand: Copilot's dirShared off -> the Copilot test fails; Qoder's
pathOwn nil -> both qoder subtests fail; Qoder's dirShared off -> both
fail.
Not tried: a real JetBrains plugin or Qoder CLI; WSL (its probe counts the
distro's folder and isn't changed; a Windows JetBrains writes the Windows
home, not the distro's).

* gateway: a long Codex session full of images is read up to 512 MB, and magpie's 413 says it is magpie's limit and to /compact (#1422, NeoPengZhile)

NeoPengZhile's Codex (signed in to ChatGPT, through /backend-api/codex/
responses) got "413 Payload Too Large: request body exceeds gateway
limit" on all five reconnects in a long session that had read many
images; a new session worked. Codex sends the whole conversation every
turn, screenshots inline as base64, zstd-compressed; magpie's limit is on
the decoded body and was 128 MB, while magpie compresses a ChatGPT turn
again on the way out, so the backend sees about what Codex alone would
send. The message didn't say whose limit it was or what to do.

What changed:
- request_bounds.go: defaultBodyLimit 128 MB -> 512 MB (decoded, which
  also sets the zstd decoder's memory cap). Every route that reads with
  the default gets it, keyLimited's read among them, so a limited key
  isn't held to the old number first. Routes with their own lower limit
  (System One 16 MB, a Claude subscription's 16 MB) keep it.
- overLimit: magpie's own 413 says "request body is over magpie's
  gateway limit of 512 MB (decoded); the provider was not asked".
- gateway.go writeError: the hint added to a 413 now says it is a byte
  limit, not the model's context, and to /compact (Codex, Claude Code) or
  start a new conversation.
- request_bounds_test.go: TestRequestBodyTooLarge uses defaultBodyLimit+1
  in place of a literal 129 MB.
- docs/subsystems/gateway-routing.md says so.

Run: go test ./internal/gateway/ -count=1 (ok, 354s), with the new
TestImageHeavyCodexTurnIsRead (a zstd body of inline images decoding to
136 MB on Codex's backend path, read with the default limits) and
TestOverLimitSaysWhoseAndWhatToDo; go test ./internal/gui/ (ok); go vet
./... on darwin, GOOS=linux -tags nogui and GOOS=windows; gofmt -l.
Broken by hand: the limit back at 128 MB -> TestImageHeavyCodexTurnIsRead
fails with the 413; the old "exceeds gateway limit" message, or the old
hint, -> TestOverLimitSaysWhoseAndWhatToDo fails.
Not tried: the reporter's real session, or how big a turn the ChatGPT
backend itself takes; the test's images repeat, so its wire size is far
smaller than real screenshots'. Peak memory for a turn near 512 MB was
not measured.

* sessions: Claude Desktop uses its saved conversation titles (#1675)

Read Code and Cowork metadata when native CLI transcripts are absent,
including current/prior CLI IDs and renames. Keep gateway identity,
accounting and capabilities. Desktop titles take precedence over the
recorded first-prompt fallback added upstream; unknown names keep it.

Rebased onto 751e05d8. All three new regressions fail on that unmodified
base and pass with the patch. Full Go suite, targeted race checks repeated
20 times, and macOS/Linux/Windows vet/builds pass. Baseline and patched
binaries reproduce UUID/title display in Chromium and WebKit with the
same synthetic Code/Cowork metadata and recording off. The patch applies
cleanly to newer origin/main 84cd8153. Linux/Windows runtime UI was not
executed. No live gateway or agent files were modified.

* sessions: Desktop titles read once per second, from every handle Desktop keeps, and reach stats and Context (#1675)

Follow-up to Koohoko's 3d6f8b8e, after review.

- Cost: assemble asks DesktopTitles once per native Claude Desktop
  session, and each call globbed and stat'ed every local_*.json, so a
  list of N Cowork sessions looked at the metadata N times. The names
  are now one index, rebuilt at most once a second (desktopTitlesHeld);
  a rename in Desktop shows within that second. Files are read through
  filememo, the shared reader the usage resolver already uses for these
  same files, which also catches a same-size rewrite inside one mtime
  tick (the patch's own size+mtime cache didn't).
- A record that is there but doesn't parse (Desktop midway through a
  write) keeps its last parse instead of dropping to the bare id; a
  record gone still takes its names with it.
- Handles: Claude.app 2.7032's LocalSessionManager (app.asar, read-only)
  counts unarchivedCliSessionId as a live handle beside cliSessionId and
  preClearCliSessionId as lineage beside priorCliSessionIds, and runs a
  record with no cliSessionId under its sessionId without "local_".
  All are named now; the raw "local_..." id no longer is (no usage
  record carries it).
- Siblings: MergeExternalStats (the Sessions page's stats summaries)
  and the Context page named gateway-only Desktop sessions by the
  recorded prompt or nothing; both use the Desktop name now.
- docs/subsystems/gateway-sessions.md says all of the above.

Real layout: no Desktop session records exist on this Mac or the
Windows box (only claude_desktop_config.json), so field names and types
were checked against Claude.app 2.7032's own reader/writer code: a
string title, string cliSessionId/unarchivedCliSessionId/
preClearCliSessionId, an array priorCliSessionIds, files
<account>/<org>/local_*.json under claude-code-sessions and
local-agent-mode-sessions. Dirs come from desktopdir.Everywhere, the
resolver the other Desktop session readers use (Windows %APPDATA% and
MSIX LocalCache, Linux ~/.config); Windows/Linux not run.

Run: new tests TestDesktopSessionTitleHandles, TestDesktopSessionTitleInStats,
TestDesktopTitlesReadOncePerList, and context checks in
TestDesktopSessionTitlesOnPages. Each broken by hand went red:
rescan per call -> "metadata looked at 12 times, want once"; no
last-good -> "a half-written file lost its names"; no unarchived/stem ->
missing ids; stats without the name -> "stats titles map[cli-s:Recorded
prompt ...]"; Context without it -> "context titles map[...: ...]".
go test -race -count=20 -run TestDesktop ./internal/sessions;
go test -tags nogui ./... (sandbox HOME, pinned caches): all ok but
internal/plugin's TestPiPackage (pi-codemode export missing; passes
alone, doesn't import sessions or gui), filed as #1879; gofmt -l;
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./...; go build, GOOS=linux go build -tags nogui, GOOS=windows go build.
GUI: routing-sessions, session-identity, sessions-overview,
sessions-bar-names, sessions-gateway-delete, sessions-manage,
context-window in Chromium and WebKit (84/84 each).
Real binary: magpie web under a sandbox HOME with Claude-3p Code and
Claude Cowork fixture records and five claude-desktop usage records;
the Sessions page (Chromium, WebKit) showed both titles on current,
prior and unarchived ids and the bare id on the unmatched one;
/api/gateway/session-titles named them; a rename showed after 1.3s;
a half-written file kept the name; deleting the record went back to
the id.

Co-authored-by: Koohoko <koohoko@gmail.com>

* plugin: a musl Linux (Alpine) runs plugins on Bun's musl build, kept apart from the glibc one (#1877)

emptyteeth found it: bunTarget picked Bun's build from GOOS/GOARCH alone,
so Alpine got bun-linux-x64-baseline, a glibc build whose interpreter
(/lib64/ld-linux-x86-64.so.2) Alpine lacks. exec then said "fork/exec
…/bun/1.4.2/magpie-bun: no such file or directory", which reads as a
missing file, and no plugin could be added or run.

- bunTarget: a musl Linux gets bun-linux-x64-musl-baseline or
  bun-linux-aarch64-musl. The musl check moves out of internal/claudecode
  into internal/libc (libc.Musl, unchanged rule: Anthropic's installer's
  /lib/libc.musl-*.so.1), which claudecode, the plugin host and the CLI
  test that skipped on musl now share.
- bunSums: the two musl builds' checksums, checked against Bun v1.4.2's
  own SHASUMS256.txt (downloaded from the GitHub release; they match the
  issue's numbers).
- Cache: a musl Linux keeps its Buns and state.json under bun/musl, so a
  machine whose C library changed never runs the other build, nor takes
  its state, whose Bad may list versions only the glibc build failed
  (CheckBun on Alpine set aside every newer Bun). glibc, macOS and Windows
  stay in bun/<v>, so a Bun downloaded before is used as it is, with no
  new download.
- A bun on disk that exec can't start with ENOENT says it is a build for
  another C library and names MAGPIE_BUN (cantStart), for the host's start
  and for bun add/bun update. The same for a $MAGPIE_BUN.
- Bun's musl build needs libstdc++ and libgcc, which a bare Alpine lacks:
  the loader then prints "Error loading shared library libstdc++.so.6"
  above ~40 "Error relocating" lines, and bun add cut it off. bun add,
  bun update and a host that died starting now say which library is
  missing and `apk add libstdc++ libgcc` (missingLibs, whyDied).

Decided: a Bun that can't be started at all is not counted as crashed.
The fallback goes to the version before, which is the same build for
this system and fails the same way, and setting the current one aside
would mark a good version bad for good. The libc check happens before the
download instead (the target), so Alpine never fetches the glibc build.

Run:
- docker alpine:3.20 (arm64, and amd64 under emulation), sandbox HOME in
  the container, linux nogui builds. origin/main's binary reproduces the
  report: "bun add …: fork/exec /sbx/.cache/magpie/bun/1.4.2/magpie-bun:
  no such file or directory". This one on bare Alpine downloads
  bun/musl/1.4.2 and says "this system lacks libstdc++.so.6 … apk add
  libstdc++ libgcc"; after apk add, `magpie plugin add
  @magpie-community/opencode-cursor-auth` adds it and `plugin list` starts
  the host and lists cursor (arm64 and amd64), with the old glibc
  bun/1.4.2 left beside it unused. With libstdc++ removed again, plugin
  list says the library; MAGPIE_BUN pointed at the glibc build gives the
  C library message.
- New tests (bunmusl_test.go, libc_test.go), each broken by hand and seen
  red: no musl branch (TestBunTargetForMusl, TestMuslBunKeptApartFromGlibc),
  no bun/musl root (TestMuslBunKeptApartFromGlibc), cantStart returning
  the error as is (TestCantStartSaysCLibrary,
  TestHostOnUnstartableBunSaysCLibrary, which fails with the reporter's
  exact message), host.go without it, no musl sum (TestBunDefaultSums),
  no hint in bun add (TestMissingLibsNamesThem) or in the host's start
  (TestHostOnBunLackingLibsSaysWhich), muslAt always false (TestMuslAt).
  -race -count=20 on them: green.
- gofmt -l; go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows;
  go build for darwin, linux nogui, windows; go test -tags nogui for
  internal/plugin, libc, claudecode, cli in a sandbox HOME, and
  go test -tags nogui ./... (all green). One earlier run of
  internal/plugin with the other three packages went red, and its output
  was lost to a tail; four reruns of it, alone and together, were green,
  and the new tests were green under -race -count=20, so which test it
  was isn't known.

Not tried: a glibc Linux end to end after the change (the unit test
covers that its Bun stays at bun/<v>); a musl Linux other than Alpine
(the detection is unchanged and looks for Alpine's libc.musl-*.so.1).
The old glibc bun/<v> on an Alpine machine stays on disk (~90 MB); it
isn't removed, as a volume shared with a glibc container could be using
it.

* gateway: a 400 for a tool schema past a model's nesting depth goes to the group's next member (#1870)

OpenCode Go answered Claude Code's MCP tools on muse-spark-1.3-contributor
with 400 "JSON schema exceeds the maximum nesting depth of 10 levels", and
group/intent-auto returned it to the agent instead of asking the next
member. shapeWords didn't know the wording, so shapeRefused was false and
the error ended the turn. It now matches "schema exceeds the maximum
(nesting) depth" and "schema ... nesting depth". The schema isn't
truncated, nothing rests, and plain parameter errors ("Field required",
"not a valid type") and a 200 that mentions the depth still don't fail
over.

Run: go test ./internal/gateway -run 'TestGroupFailsOver' -count=1, green.
With the new alternatives removed, TestGroupFailsOverARequestShape fails
on both depth bodies and TestGroupFailsOverASchemaTooDeep gets the 400
back with b never asked (a 1, b 0).

* gateway: a group's Patience is waited out in full, not cut at 90s by the round count (#1418)

A group asks its busy members again after pauses of 2s, 4s, 8s, 16s, then
30s, for as long as its Patience lasts, but replanRounds stopped it after
6 rounds: 90s of pauses whatever the group was set to. real-jacket's trace
on #1418 shows patience=240 with replan=6 and ~103s in all. replanRounds
is now 12, a backstop sized so that the pauses alone reach
PatienceLongest (240s) in 11 rounds, and the patience is what ends the
wait. It stays bound by kept.tooQuiet, as before. The longest pause is
now 30 x retryPause (30s in use), so the tests' 1ms retryPause doesn't
grow a 4s pause at round 12.

Run: TestPatienceIsUsedUp (new) counts replan's pauses for 30s to 240s of
patience, and TestReplanRoundsOutlastPatience (new) sums the backstop's
schedule. With replanRounds back at 6, both fail: patience 3m0s and 4m0s
pause 1m30s. go test ./internal/gateway -run
'Overload|Patience|Replan|WaitsOut|Busy|Codex' is green. Not tried
against a real overloaded vendor for 240s.

* gateway: a held stream lets through only text, reasoning or a call, so a 200 that only framed a reply fails over (#1418)

Aliceonly's trace on #1418: sub2api answered 502 "Upstream HTTP/2 stream
failed", then Codex account A answered 200, sent only the frames before a
reply, and failed server_is_overloaded 37s in. Five candidates after it
were never asked, and Codex ended the turn. The stream had been let
through (h.passing), so holdWriter.failed() was false and neither the next
candidate nor a replan was tried.

Two ways a frames-only stream went through:
- streamEvent's default was eventContent: any event it didn't know (and an
  item of a type said() didn't know) counted as the reply begun. Now only
  the events of each protocol that carry text, reasoning, a call or a
  reply's end (replyEvent) count; anything else is eventLead, held as a
  ping is. An unknown item counts only when it is a call or a tool's
  (web_search_call, server_tool_use, mcp_*). A stream that ends well is
  still released whole, so this can only delay, never drop, a reply.
- a reply under a Content-Type that says neither JSON nor a stream, once
  the agent had a stream's headers, went straight through when its first
  bytes were SSE (sseStart -> pass()). It is now held as a stream from
  there and read event by event.

Which event Codex's backend actually sent isn't in the trace; the test
uses a keepalive, response.rate_limits.updated and an unknown item type.

Run: go test ./internal/gateway -count=1, green (428s).
TestFramesThenOverloadedGoesToTheNext (new: 502, then 200 frames + unknown
events + server_is_overloaded, then a third member) and
TestStreamEventUnknownOnlyFrames (new) fail on the old fallback.go: the
overloaded stream reaches the agent and c is never asked.
TestHeldUnsureStreamPasses/KeptAlive now expect the stream held until its
first word, and TestHeldUnsureStreamFailsHeld (new) a failure among held
frames; all fail on the old code. Not tried against the real ChatGPT
backend.

* gui: every resting key or account can be tried again by hand, on Routing and in the provider's key list (#1869)

A key resting after a 429 with a long Retry-After (a relay's 3600s) came
back only by waiting or a restart, though relays often recover in a
minute or two. The Routing page offered the lift (/api/gateway/unrest,
which already takes any rest key) only to verify and restricted rests.

- routing.js: every resting row with a rest key gets the button: "Try
  now" for quota, rate, retry-after and backoff rests, the old wording for
  verify and restricted. A lifted rest is remembered by key and the time
  it was lifted (liftedAt), so the history re-render, which reuses the
  try's rest, doesn't show it again; a newer rest still shows.
- app.js: "Try now" beside the "resting · back at …" note in a
  provider's key list, posting the key's own rest key; not hover-only.
- i18n: the three new strings in zh, zh-TW, ja and de.
- gateway-routing.md: any rest can be lifted; only the rest ends, the
  backoff count stays.

Run: rest-try-now.test.cjs (new: Routing row with the issue's zx
retry-after rest, key list row; en/zh/zh-TW/ja/de, chromium and webkit,
1100 and 420px; asserts the post, the note gone, no sideways scroll,
reached by wheel, the click doesn't scroll) 40/40, red on the old
app.js/routing.js. 71 key*/routing*/rest* GUI files at concurrency 6:
826/831; the 5 reds (key-balance-card, routing-group-fold) pass alone
and are timing under load (routing-group-fold fixed in the next commit).
go test ./internal/gui passes.

* gui tests: routing-group-fold's rests run from when the test builds them, not from when the file loaded

The fixture's rests ended 3 minutes after the module loaded. Under load
(71 files at --test-concurrency=6) the webkit half ran later than that,
so p2 and p3 were no longer resting and "6 available · 2 resting" read
"8 available" (3 webkit languages red). The page is told the time of
each poll, so the rest had simply expired.

Run: with the file's `now` moved 4 minutes back to inject the delay,
webkit was 15/20 before and 20/20 after; the file alone, both engines,
40/40.

* gui: a resting key's note and Try now take a line of their own, so the row's buttons stay in reach (#1869)

In a provider's list of several keys, a resting key's row held the
"resting · back at …" note on the same line as its switch, name, value,
weight, protocol, Remove and Make first. At 1100px the row ran past the
editor's edge and Remove and Make first could not be clicked, in German
already before 9ac763d2c and in every language once its Try now joined
the note.

- app.js: the note and Try now go in a .key-rest-line appended after the
  row's controls; the row is marked .resting.
- app.css: a resting row wraps, and its rest line takes the full width
  under the key's own line, lined up with the name; the note ellipsizes
  before Try now does.

Run: rest-try-now.test.cjs now hovers the key's row and asserts Remove
and Make first are hit by elementFromPoint at their centres, in
en/zh/zh-TW/ja/de, chromium and webkit, 1100 and 420px: 40/40 at this
commit; on the old app.js/app.css 30/40, the 10 reds being every
language and engine at 1100px.

* gui: a key's value can be changed in place, keeping its name, place and settings, and its rest is lifted (#1869)

A key rotated at its vendor had to be removed and added again, which
lost its name, its place in the order, its weight, protocol, models,
proxy and concurrency, and any gateway key restricted to it. As decided
on #1869, in multi-key mode the row now has a Change key action, with a
double-click on the row as a shortcut.

- provider.ReplaceKey(id, ref, key) sets the key's new value and moves
  what providers.json keys by the key's fingerprint (AccountModels,
  AccountProxies, AccountConcurrency) to the new one. An empty value, an
  unknown key and a value another key of the provider already holds are
  refused. The same value is a no-op.
- access.ReplaceAccount moves gateway keys' Accounts entries from
  provider/old to provider/new, under the caller-keys lock.
- gateway.Server.UnrestAll lifts a rest key and every per-model rest
  under it. The GUI's keys/replace lifts the key's rest (provider#key, and
  the provider's own rest key when it is the only key on), so the new
  value is asked from the next request.
- app.js: a pencil beside the key's copy button opens a password field in
  place of the masked value. Enter saves, Escape leaves it, and a
  double-click on the row away from its controls opens it too. The button
  has its own class (.key-edit) with the copy button's look.
- i18n: four strings in zh, zh-TW, ja and de.
- providers-accounts.md: ReplaceKey in the Keys table.

Past requests keep the old fingerprint in history, under the same name.
A rest is lifted only in the gateway this magpie serves.

Run:
- go test ./internal/gateway ./internal/provider ./internal/access
  ./internal/gui -count=1: ok. New TestReplaceKeyKeepsItsPlace,
  TestKeysReplaceKeepsTheKeyAndLiftsItsRest and
  TestUnrestAllLiftsAKeysModels each fail with their change taken out.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows.
- key-replace.test.cjs (new): en/zh/zh-TW/ja/de, chromium and webkit,
  1100 and 420px. Checks the post, order, note, no sideways scroll, and
  no scroll on change or on double-click plus Escape.
- With key-copy, rest-try-now and key-import: 96/96.
- 72 key*/routing*/rest* GUI files at concurrency 6: 863/871. The 8 reds
  were key-copy, whose button.copy locator matched the pencil; that's why
  it has its own class now, and key-copy passes.
- Under load, about one run in 300 saw the editor body go back to the top
  after the copy button's double-click, with no script scrolling it. That
  is #1504 (findings added there). The test checks scroll before that
  step.

* plugin tests: TestPiPackage runs on a pi pinned by a bun.lock, not npm's latest that minute (#1879)

TestPiPackage installed pi the way ensurePi does, `bun add
@earendil-works/pi-coding-agent` at npm's latest, so it ran on whatever
pi's packages were that minute. pi-codemode 1.2.0 (2026-10-12 23:00:01Z)
dropped MCP_TYPESCRIPT_PREAMBLE and mcpStructuredContentSchema, which
pi-coding-agent 1.0.x and 1.1.0 import from it; their ^1.x range takes
1.2.0. pi-coding-agent 1.2.0 (no longer importing them) came out at
23:03:25Z. A full run that reached TestPiPackage in between got
pi-coding-agent 1.1.0 + pi-codemode 1.2.0 and pi didn't load; the run
alone came after. Nothing is shared between tests here (each has its
own plugins folder, and bunCommand puts Bun's cache under the test's
HOME), so "only in the full run" was the clock, not the suite.

The test now writes testdata/pi-lock's package.json and bun.lock (pi
1.2.0, every package at its npm integrity) into the plugins folder and
runs `bun install --frozen-lockfile`; Add then finds pi there. The
"pi is installed with a pi package" half moves to TestEnsurePi, with bun
stubbed: installed once for a pi package, not again with pi there, not
for an OpenCode plugin. The BUN_INSTALL_CACHE_DIR the test set did
nothing (bunCommand sets its own after it) and is gone.

Users: magpie installs pi at latest (1.2.0 with 1.2.0 now), and bun
keeps a plugins folder's lock when other plugins are added, so a folder
installed before the 1.2.0 release keeps 1.1.0 with 1.1.0. Only a pi
install that resolved in those ~3-8 minutes (CDN metadata cache) got the
broken pair. No magpie change.

Run:
- with the lock swapped for pi-coding-agent 1.1.0 (codemode resolved to
  1.2.0): TestPiPackage fails with the issue's exact "Export named
  'MCP_TYPESCRIPT_PREAMBLE' not found"; with 1.1.0 + codemode 1.1.0 and
  with the 1.2.0 lock committed it passes
- TestEnsurePi fails with ensurePi's "pi is there" check removed
- go test ./internal/plugin/ -count=1 three times: ok (140s, 121s, 112s)
- go test ./internal/plugin/ -run 'TestPiPackage|TestEnsurePi' -count=5: ok
- go test -tags nogui ./internal/...: ok
- gofmt -l; go vet darwin, linux -tags nogui, windows: clean

* gateway: a Claude subscription run is told the user's words after a tool result as theirs, not the tool's (#1878)

JinJieBeWater found that Claude Code's AgentSummary label request ("Describe
your most recent action in 3-5 words. Do not use tools.", sent as a text
block after the sub-agent's last tool_result) reached the inner Claude as
tool output, so it went on with the task instead of answering the label.

Two paths had it:

- renderParts (a run started anew, or a resumed turn) wrote the text right
  after the tool's last line. A text or file part after a tool result in the
  same message now closes it with "[end of tool result id=…]" and is marked
  "[user message]". A result followed by nothing or by another result is
  told as before, so existing prompts and their cache prefix don't change.
- match folded the text into the last result, and continueWith handed it to
  Claude Code as the MCP result. It no longer folds; saidWithResults takes
  the words, and continueWith writes them to Claude Code's stdin as a user
  message before handing the results over, waiting for Claude Code's
  command_lifecycle "queued" for that uuid (2s at most). Claude Code then
  tells its model the message with the result as one the user sent while it
  worked, in the same turn.

Going on in the run, rather than starting a new one for such requests, keeps
the cache prefix (#1716/#1717) and #872's mid-turn messages, which use the
same shape. #872's text is now queued as the user's instead of appended to
the result. Words in a message that holds images (pi-ai's "Attached
image(s) from tool result:" captions) still fold into the result, decided by
the message's parts, not its text. A tool whose output says "Do not use
tools." keeps it inside its result. The fork test's fake Claude now models
mid-turn absorption the way Claude Code does.

Run: gofmt -l; go vet on darwin, linux (-tags nogui), windows for
./internal/gateway; go test -tags nogui ./internal/gateway/ -count=1 green;
-race -count=3 on the new tests. Broken by hand, each red: no end marker;
an end marker after every result; the words not passed to continueWith; the
old fold into the result; the words queued after the result is handed over.
Real Claude Code 2.1.296 driven through the gateway in a sandbox HOME
against a local mock of Anthropic: on continuation the next request's
tool_result holds "SOURCE_LAST_LINE" then the "user sent a new message
while you were working" reminder with the label request; on a new run the
prompt holds the closed result and "[user message]".

Not run: the owner's real Claude subscription (its credentials are in the
Keychain, off-limits here), so the real model's answer to the label isn't
seen; Windows tests; the full ./... suite.

---------

Co-authored-by: yetone <yetoneful@gmail.com>
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>
Co-authored-by: CaramelizedCUDA <1418451053@qq.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: lainbo <github@lainbo.com>
Co-authored-by: Edward4226 <234070868+Edward4226@users.noreply.github.com>
Co-authored-by: wangru8080 <22983744+wangru8080@users.noreply.github.com>
Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>
Co-authored-by: Ruijia Zhang <ruijiazhang76@gmail.com>
Co-authored-by: fjrtdk <fjrtdk@gmail.com>
Co-authored-by: 尤贺雨 <youheyu@sungrowpower.com>
Co-authored-by: NineSu <niceninesu@qq.com>
Co-authored-by: jueda12 <180685381+jueda12@users.noreply.github.com>
Co-authored-by: parkavenue9639 <92194680+parkavenue9639@users.noreply.github.com>
Co-authored-by: RaykieLee <42793273+RaykieLee@users.noreply.github.com>
Co-authored-by: mengyianx <106875577+mengyianx@users.noreply.github.com>
Co-authored-by: appointat <65004114+Appointat@users.noreply.github.com>
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: congee949 <c86474321@gmail.com>
Co-authored-by: liubing <lb0806@foxmail.com>
Co-authored-by: Haogao Gu <koohoko@gmail.com>
2026-10-13 12:11:23 +08:00

282 lines
12 KiB
Go

package agent
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// setAgentsV1 turns settings.CodexAgentsV1 on or off as the Settings page's
// switch does, without provider's own helper (the agent package must not
// import provider back). The setting is process-wide, so it is put back when
// the test ends.
func setAgentsV1(t *testing.T, on bool) {
t.Helper()
was := settings.Load().CodexAgentsV1
t.Cleanup(func() {
s := settings.Load()
s.CodexAgentsV1 = was
if err := settings.Save(s); err != nil {
t.Errorf("restoring settings.CodexAgentsV1: %v", err)
}
})
s := settings.Load()
s.CodexAgentsV1 = on
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
}
// codexAgentsHome is codexHome signed in, which routing needs; its config and
// magpie's own files live under codexHome's temp home.
// No Codex runs and no app-server is behind, so Notice is the V1 warning
// alone and asks no real daemon.
func codexAgentsHome(t *testing.T, config string) (home string, read func() string) {
t.Helper()
quietCodex(t, false, provider.CodexDaemonCheck{})
return codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, config)
}
func modTime(t *testing.T, path string) time.Time {
t.Helper()
st, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
return st.ModTime()
}
// route points Codex at one of magpie's models, as picking one does, and
// fails the test if the config isn't routed afterwards.
func route(t *testing.T, cx *Agent, read func() string) {
t.Helper()
if err := cx.Fields[0].Set("fake/m1"); err != nil {
t.Fatal(err)
}
if !strings.Contains(read(), "openai_base_url") {
t.Fatalf("not routed:\n%s", read())
}
}
// Codex's own multi_agent_v2 explicitly on — the bare key or enabled = true in
// its table, spelled as a table, an inline object or a dotted key — turns the
// V1 magpie's models ask for off, so the Codex notice says so and magpie
// writes nothing: the config stays byte for byte, the user turns the key off
// (#141).
func TestCodexAgentsV1WarnsWhenCodexOwnV2IsOn(t *testing.T) {
for _, tc := range []struct{ name, config string }{
{"bool key", "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = true\n"},
{"bool key comment", "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = true # codex v2\n"},
{"table", "model = \"gpt-5.5\"\n\n[features.multi_agent_v2]\nenabled = true\nmax_concurrent_threads_per_session = 4\n"},
{"inline", "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = { enabled = true, max_concurrent_threads_per_session = 4 }\n"},
{"dotted", "model = \"gpt-5.5\"\nfeatures.multi_agent_v2.enabled = true\n"},
} {
t.Run(tc.name, func(t *testing.T) {
home, read := codexAgentsHome(t, tc.config)
cx := codex(home)
route(t, cx, read)
setAgentsV1(t, true)
before, bt := read(), modTime(t, cx.Path)
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if after := read(); after != before {
t.Fatalf("magpie wrote to the config:\n%s\n→\n%s", before, after)
}
if mt := modTime(t, cx.Path); !mt.Equal(bt) {
t.Fatalf("the config was rewritten: %v → %v", bt, mt)
}
if n := cx.Notice(); !strings.Contains(n, "multi_agent_v2") || !strings.Contains(n, "turn it off") {
t.Fatalf("no notice that Codex's own V2 wins: %q", n)
}
})
}
}
// The legacy in-file profile's features win over the top level's, as Codex
// 0.133.0 applied them (base then profile) and as magpie's Check reads
// profiles.<profile>: multi_agent_v2 is read there in the same four forms, and
// only the profile the config names decides — one that sets nothing inherits
// the top level, and one that isn't selected is no input. This is the legacy
// in-file shape, not modern Codex's --profile + {profile}.config.toml. Still no
// write (#141).
func TestCodexAgentsV1WarnsByLegacySelectedProfileFeatures(t *testing.T) {
for _, tc := range []struct {
name, config string
warn bool
}{
{"profile bool on over top off", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[features]\nmulti_agent_v2 = false\n\n[profiles.work.features]\nmulti_agent_v2 = true\n", true},
{"profile table on over top off", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[features]\nmulti_agent_v2 = false\n\n[profiles.work.features.multi_agent_v2]\nenabled = true\n", true},
{"profile inline on over top off", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[features]\nmulti_agent_v2 = false\n\n[profiles.work.features]\nmulti_agent_v2 = { enabled = true, max_concurrent_threads_per_session = 4 }\n", true},
{"profile dotted on over top off", "model = \"gpt-5.5\"\nprofile = \"work\"\nfeatures.multi_agent_v2 = false\nprofiles.work.features.multi_agent_v2.enabled = true\n", true},
{"profile bool off over top on", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[features]\nmulti_agent_v2 = true\n\n[profiles.work.features]\nmulti_agent_v2 = false\n", false},
{"profile table off over top on", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[features]\nmulti_agent_v2 = true\n\n[profiles.work.features.multi_agent_v2]\nenabled = false\n", false},
{"profile table enabled omitted inherits top on", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[features]\nmulti_agent_v2 = true\n\n[profiles.work.features.multi_agent_v2]\nmax_concurrent_threads_per_session = 4\n", true},
{"profile sets nothing inherits top off", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[profiles.work.features]\nfoo = true\n", false},
{"profile string true is not a bool", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[features]\nmulti_agent_v2 = false\n\n[profiles.work.features]\nmulti_agent_v2 = \"true\"\n", false},
{"profile string true over top on inherits", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[features]\nmulti_agent_v2 = true\n\n[profiles.work.features]\nmulti_agent_v2 = \"true\"\n", true},
{"unselected profile ignored", "model = \"gpt-5.5\"\nprofile = \"work\"\n\n[profiles.other.features]\nmulti_agent_v2 = true\n", false},
{"no active profile ignored", "model = \"gpt-5.5\"\n\n[profiles.work.features]\nmulti_agent_v2 = true\n", false},
} {
t.Run(tc.name, func(t *testing.T) {
home, read := codexAgentsHome(t, tc.config)
cx := codex(home)
route(t, cx, read)
setAgentsV1(t, true)
before := read()
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if after := read(); after != before {
t.Fatalf("magpie wrote to the config:\n%s\n→\n%s", before, after)
}
n := cx.Notice()
if tc.warn {
if !strings.Contains(n, "multi_agent_v2") || !strings.Contains(n, "turn it off") {
t.Fatalf("no notice that Codex's own V2 wins: %q", n)
}
} else if strings.Contains(n, "multi_agent_v2") {
t.Fatalf("a warning with Codex's own V2 off: %q", n)
}
})
}
}
// Codex's own multi_agent_v2 off — absent, false, a table/inline object whose
// enabled is false or left out, or a string rather than a boolean — is Codex's
// default, which the V1 already is: no warning, and no write.
func TestCodexAgentsV1NoWarningWhenCodexOwnV2IsOff(t *testing.T) {
for _, tc := range []struct{ name, config string }{
{"absent", "model = \"gpt-5.5\"\n"},
{"false", "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = false\n"},
{"table enabled false", "model = \"gpt-5.5\"\n\n[features.multi_agent_v2]\nenabled = false\n"},
{"table enabled omitted", "model = \"gpt-5.5\"\n\n[features.multi_agent_v2]\nmax_concurrent_threads_per_session = 4\n"},
{"inline enabled false", "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = { enabled = false }\n"},
{"inline enabled omitted", "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = { max_concurrent_threads_per_session = 4 }\n"},
{"bare string", "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = \"true\"\n"},
{"table string enabled", "model = \"gpt-5.5\"\n\n[features.multi_agent_v2]\nenabled = \"true\"\n"},
} {
t.Run(tc.name, func(t *testing.T) {
home, read := codexAgentsHome(t, tc.config)
cx := codex(home)
route(t, cx, read)
setAgentsV1(t, true)
before := read()
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if after := read(); after != before {
t.Fatalf("magpie wrote to the config:\n%s\n→\n%s", before, after)
}
if n := cx.Notice(); strings.Contains(n, "multi_agent_v2") {
t.Fatalf("a warning with Codex's own V2 off: %q", n)
}
})
}
}
// The setting off, or Codex not routed through magpie, is nothing to warn
// about even with Codex's own V2 on: the setting has no effect there.
func TestCodexAgentsV1NoWarningOffOrUnrouted(t *testing.T) {
// the setting off, Codex routed, its own V2 on
home, read := codexAgentsHome(t, "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = true\n")
cx := codex(home)
route(t, cx, read)
setAgentsV1(t, false)
if n := cx.Notice(); strings.Contains(n, "multi_agent_v2") {
t.Fatalf("a warning with the setting off: %q", n)
}
// the setting on, Codex not routed
home2, _ := codexAgentsHome(t, "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = true\n")
cx2 := codex(home2)
setAgentsV1(t, true)
if n := cx2.Notice(); strings.Contains(n, "multi_agent_v2") {
t.Fatalf("a warning with Codex unrouted: %q", n)
}
}
// A features key of a shape magpie doesn't take for a boolean or a table — an
// array table in [features]' place — is not a conflict: no warning, no write,
// and the rest of the sync still runs on the config left exactly as it was.
func TestCodexAgentsV1UnexpectedFeaturesShapeNotBlocked(t *testing.T) {
home, read := codexAgentsHome(t, "model = \"gpt-5.5\"\n\n[[features]]\nname = \"x\"\n")
cx := codex(home)
route(t, cx, read)
setAgentsV1(t, true)
before := read()
if err := cx.Sync(); err != nil {
t.Fatalf("an unexpected features shape blocked Sync: %v", err)
}
if after := read(); after != before {
t.Fatalf("the config was rewritten:\n%s\n→\n%s", before, after)
}
if n := cx.Notice(); strings.Contains(n, "multi_agent_v2") {
t.Fatalf("a conflict warning for a shape magpie doesn't read: %q", n)
}
}
// A config the TOML parser refuses is a read error for the notice too: told as
// such rather than taken for a conflict or read as absent.
func TestCodexAgentsV1UnparseableConfigNotice(t *testing.T) {
home, read := codexAgentsHome(t, "model = \"gpt-5.5\"\n")
cx := codex(home)
route(t, cx, read)
setAgentsV1(t, true)
if err := os.WriteFile(cx.Path, []byte(read()+"\noops =\n"), 0o644); err != nil {
t.Fatal(err)
}
if n := cx.Notice(); !strings.Contains(n, "couldn't read") {
t.Fatalf("unparseable config: %q", n)
}
}
// CodexSubAgentsV1Warning is the same warning for the Settings row, found from
// the Codex config here rather than a path the caller already has.
func TestCodexSubAgentsV1WarningSetting(t *testing.T) {
home, read := codexAgentsHome(t, "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = true\n")
cx := codex(home)
route(t, cx, read)
setAgentsV1(t, true)
if n := CodexSubAgentsV1Warning(); !strings.Contains(n, "multi_agent_v2") {
t.Fatalf("setting row warning: %q", n)
}
setAgentsV1(t, false)
if n := CodexSubAgentsV1Warning(); n != "" {
t.Fatalf("setting row warning with the setting off: %q", n)
}
}
// quietCodex says whether a Codex runs and what its app-server answers, for
// the test's length.
func quietCodex(t *testing.T, running bool, daemon provider.CodexDaemonCheck) {
t.Helper()
wasRunning, wasKeep := codexRunning, keepCodexDaemon
t.Cleanup(func() { codexRunning, keepCodexDaemon = wasRunning, wasKeep })
codexRunning = func() bool { return running }
keepCodexDaemon = func(context.Context, string, time.Time) provider.CodexDaemonCheck { return daemon }
}
// The V2 warning is joined with the restart advice, not put in its place: a
// user who just switched models while Codex runs still needs "restart Codex"
// (#1028 review point 2), and the app-server magpie restarted is still said.
// Joined with a space, as notices are, so the GUI translates both.
func TestCodexV2WarningJoinsRestart(t *testing.T) {
home, read := codexAgentsHome(t, "model = \"gpt-5.5\"\n\n[features]\nmulti_agent_v2 = true\n")
cx := codex(home)
route(t, cx, read)
setAgentsV1(t, true)
quietCodex(t, true, provider.CodexDaemonCheck{})
if n, want := cx.Notice(), codexV1ConflictNotice.String()+" "+codexRestartAll; n != want {
t.Fatalf("Codex running:\n%q\nwant\n%q", n, want)
}
quietCodex(t, true, provider.CodexDaemonCheck{Behind: true, Restarted: true})
if n, want := cx.Notice(), codexV1ConflictNotice.String()+" "+noticeCodexdaemon.String(); n != want {
t.Fatalf("app-server restarted:\n%q\nwant\n%q", n, want)
}
}