Commit Graph
1564 Commits
Author SHA1 Message Date
yetone 59fdab0af7 gateway: a caller's folder the user hasn't trusted runs in magpie's, not a 502 (lwjef on X)
lwjef (X, 2116867007799030000): a cwd Claude Code hasn't trusted hangs
the interactive-mode bridge (paseo chat).

Cause: in the user's own account the helper leaves the trust question
to the user (no MAGPIE_CLAUDE_TUI_TRUST) and ends at once saying so. Up
to 11-01 that run became -p; since e5f66f8a6 nothing runs as -p, so the
turn got a 502 (endedBefore, "Claude Code asks whether to trust the
folder"). A Claude Code client such as paseo's asks again with backoff
on a 5xx, so the chat looked hung. The real Claude Code 2.1.309 in an
untrusted folder (sandbox HOME, copied account) ends the helper in 1.3s
with that line.

Fix: startTrusted runs startRun, and when the helper ended over the
trust question (its stderr read to the end, saidOnEnd) in the caller's
folder under the user's own account, remembers that folder for 10
minutes (passedOver) and starts the run once more in magpie's own folder,
told the caller's (envElsewhere), as a caller on another computer is.
Only one retry: a second refusal is returned as before. The saved-session
retry in start goes through startTrusted too.

Run (mote, at this tree):
- go test -run 'Claude|MCP|Bridge' ./internal/gateway: ok
- TestClaudeTUIUntrustedFolderAnswered: ok

Broken by hand: saidOnEnd returning false made the new test red (502
"exited before it answered magpie's initialize request ... trust the
folder"); passedOver turned off made it red with the same 502 after one
retry. An earlier draft that retried through start itself looped forever
with passedOver off; the retry is bounded to one since.

Not tried: a real gateway turn from paseo; the real helper and Claude
Code were run on each side of the retry (untrusted folder ends at once;
a trusted magpie folder answers), not through a live gateway. A user who
trusts the folder within 10 minutes still runs in magpie's folder until
then.

At the pushed head's tree, on origin/main 79f83798f (which has 2b52302dc,
crosscn's 400KB fix), on mote: gofmt -l is clean, and go vet
./internal/... is ok for darwin, windows and linux. go test -timeout 45m
./internal/claudetui ./internal/claudebridge is ok. ./internal/gateway is
ok except TestCodexPoolSaysTheClientsVersion, which fails the same way in
a gateway run at origin/main 79f83798f itself and passes alone at both
(#4807, filed here). The conflict with main's tuiRefusal and replay change
in start() was resolved by keeping main's req.told and calling
startTrusted. Before the rebase, the three packages were ok on
magpie-desktop (Linux) too.
2026-11-01 23:47:47 +08:00
yetone bee3ea6753 claudetui: the first message waits for Claude Code to list magpie's tools (MinhuWang on X)
MinhuWang (X, 2116836405548916907): in the interactive mode the first
message can go before MCP has loaded, and then has none of pi's tools.

Cause: the helper's ready() took the drawn "❯ " prompt as ready. Claude
Code connects its MCP servers beside the prompt, so a message pasted at
once was answered with no mcp__magpie__ tools. Reproduced with the real
Claude Code 2.1.309 (sandbox HOME, a copy of the owner's account): an MCP
server held 8s before answering initialize got "NOTOOL" for "what is the
secret word, use your tool".

Fix: startRun gives claude-mcp-helper a third argument, a `listed` file in
the run's temp folder, which RunMCP writes after it has answered
tools/list. The helper finds that path in the run's --mcp-config
(mcpListed) and ready() waits for it as well as the prompt, inside the
same ReadyWait (45s); past it the run ends saying the tools weren't
listed. Runs without that server (warm-up, model test) don't wait.

Run (mote, at this tree):
- go test ./internal/claudetui ./internal/claudebridge: ok
- go test -run 'Claude|MCP|Bridge' ./internal/gateway: ok
- real Claude Code 2.1.309 here, a sandbox HOME with a copy of the
  account's credentials, the new helper and the real claude-mcp-helper
  behind an 8s sleep: initialize answered at 12.7s, the first turn called
  mcp__magpie__pi_secret and answered "The secret word is PELICAN".
  Without the sleep: answered at 2.1s, same answer. 2.1.309 sends
  server/discover before initialize; the helper's method-not-found answer
  is taken and initialize follows.

Broken by hand: toolsListed returning true made
TestShimFirstMessageWaitsForTools red ("echo: hello (without magpie's
tools)"); RunMCP not writing the file made TestToolsListedFileWritten
red.

Not tried: Claude Code in WSL (the path is the gateway's Windows temp
path, handed to magpie.exe as the callback path is); a Claude Code that
lists tools only on its first request (2.1.309 lists them at start),
which would now wait 45s and fail saying so instead of answering
without tools; the full gateway suite (run after the next commits).
2026-11-01 23:26:57 +08:00
yetone 8569f39f6c agent: Claude Code's /model hides its own lineup while magpie's list is narrowed
yyhhyyyyyy on Discord picked only a routing group's models for Claude Code
on the Agents page, and Claude Code's /model still listed a model they had
not picked. Real Claude Code 2.1.316 in a sandbox HOME, with the settings
magpie writes, lists: Default, the group (as Custom Opus), Claude Code's
built-in "Fable 5.1" row, then the group as Sonnet and Haiku, then
magpie's modelPicker rows. The Fable row is Claude Code's own lineup.
magpie leaves ANTHROPIC_DEFAULT_FABLE_MODEL unset for a main model that
isn't a Fable (#2090), so Claude Code shows its own Fable there. The
gateway's /v1/models already follows the picks (CatalogFor), and Claude
Code's gateway discovery is off unless
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY is set. Neither of those is
where the row comes from.

Claude Code's documented modelPicker.replaceBuiltInOptions hides the
lineup and leaves Default and magpie's rows. In the same sandbox, the
same settings with the flag set list exactly those rows. magpie already
set the flag while "Show Claude Code's own models" is off (#4548). It now
also sets it while Claude Code's list leaves out some of magpie's
catalog: only the picked models, some taken out one by one, or a
visibility of families (claudeNarrowed, CatalogFor's hidden list). A
change to the picks already rewrites settings.json through
catalog.Touched and Sync.

The user's own values:
- A user's ANTHROPIC_CUSTOM_MODEL_OPTION, in the settings env or the
  shell, keeps the lineup. The flag would hide that row too.
- availableModels was not used. It also hid the Fable row in the
  sandbox, but it is the user's key, it blocks --model, and it is meant
  for enforcement.

Run at this head (rebased on origin/main 2503520f8), on mote:
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok.
- go test -tags nogui -timeout 45m ./...: internal/agent ok, along with
  84 packages. Three packages are red, all on main and filed:
  - internal/settingsapi TestKeysAreWhatTheSaveWrites and
    internal/cli TestSettingsCLISetsWhatTheWindowSaves (trayNoNumber,
    #4793);
  - internal/cli TestEveryRouteHasACommandOrIsNamed (/api/quit, #4794);
  - internal/gui TestRestartHandsTheGatewayOver (#4167, #4107).

Broken by hand:
- On the old claude.go, TestClaudePickerNarrowedListReplacesLineup fails:
  "glm-5 taken out: ... replaceBuiltInOptions=false".
- With the custom-option guard forced off, it fails on the user's
  ANTHROPIC_CUSTOM_MODEL_OPTION step.

Not tried:
- A real magpie writing settings.json for the real Claude Code. The
  sandbox used hand-written settings of the same shape, with the base URL
  on an unused port and no sign-in.
- Claude Code in WSL. claude@wsl takes the same writePicker path.

No GUI file is touched, so no GUI run.
2026-11-01 23:00:10 +08:00
yetone 37d7913c20 claude: the interactive mode is given an earlier conversation as a transcript
A conversation no run has (a run lost to an update, a client's own
history) was told to a new Claude Code in its interactive mode as one
first message, pasted. #4778's 229 messages and 3 images that way were
refused; #4780's 56 messages and 25 images were pasted one by one until
the paste timed out, and the request got a 502 or an empty reply.

Now, when the conversation has a reply that calls no tool,
replaySession writes it as Claude Code's own transcript: a session file
in the project folder Claude Code reads, a user line holding the
conversation before that reply (as renderClaudePrompt tells it, images
as image blocks, client cache marks out) and an assistant line holding
the reply's words. The run starts with --resume on it, as a saved
session's run does, and is typed only the turns after the reply. If
Claude Code can't go on from it, start tries once more told whole
(req.told). -p (interactive mode off), WSL (no session folder) and a
conversation with no such reply are told whole as before. The file goes
in the folder of the work path with its links followed: the first try
wrote it beside the unresolved /var/folders path on a Mac, and the
replay test was red on mote for it.

Real run (this Mac, sandbox HOME and CLAUDE_CONFIG_DIR, one of the
owner's real Claude accounts by CLAUDE_CODE_OAUTH_TOKEN, real Claude Code
2.1.316 through magpie claude-tui-helper, -p stream-json in, the
interactive mode under it, --model haiku): the transcript was made by
replaySession itself (a throwaway test on mote, not committed) from 6
earlier messages with 3 images (red, blue, green 64x64 PNGs) and a
455KB file whose line 004321 names a fruit, 464,798 bytes; the work
folder was reached through a symlink. Typed only "Name the colours of
images A, B and C, and the secret fruit named in line 004321 of the
file. One line." Answer in 8.4s: "A: red, B: blue, C: green; secret
fruit in line 004321: PAPAYA." Claude Code appended to the same session
file (504,788 bytes after).

Run (mote, at this tree, rebased on 85e37162e): go vet ./internal/gateway, GOOS=windows and
GOOS=linux -tags nogui go vet; go test -run
"TUI|Claude|Resume|Interactive|Refusal|Replay|Fallback|Branch"
./internal/gateway ok. gofmt -l clean.

Broken by hand: with replaySession returning nil,
TestClaudeTUIReplayGoesInATranscript is red ("the run wasn't given a
transcript to go on from"). TestClaudeTUISafeguardsInEnv now expects the
new run of changed safeguards to be given the whole conversation
through the transcript, not typed it, and
TestClaudeTUIBranchOfPrintRunIsToldWhole (049848c5e) accepts a branch of
a -p run's session given the whole conversation as a transcript of its
own, never the -p session (it was red at the rebased head before).

Not tried: the full gateway path (a real magpie serve with the
subscription) end to end; the request was driven at the helper with the
transcript replaySession wrote. Not changed: #4780's ask that an empty
200 not count as an answer and that the specific reason reach the
client; WSL still tells the conversation whole. Part of #4778 and #4780.
2026-11-01 22:43:52 +08:00
yetone 949000a36a claude: a request the interactive mode refuses is a 400 no account rests for
A request Claude Code's interactive mode can't take (a JSON schema, a
branch of a -p run's session, WSL Claude Code whose home wasn't found)
was refused with a 502. The fallback asked every account of the
subscription in turn and rested some for it: #4778 saw 15 tries across 3
accounts. The refusal is the same on every account, so it is now a 400
(tuiRefusal), which the fallback neither retries nor rests an account
for.

The message is reworded so that "Models" no longer stands just before
the error's "invalid_request_error": "Settings › Models › Replies
runs every request as -p\",\"type\":\"invalid_request_error" matched
provider.ModelUnserved, which made the 400 retryable again.

Run (mote, at this tree): go vet ./internal/gateway, GOOS=windows and
GOOS=linux -tags nogui go vet; go test -run
"TUI|Claude|Resume|Interactive|Refusal|Fallback" ./internal/gateway ok.
gofmt -l clean.

Broken by hand: with the 400 mapping taken out,
TestClaudeTUIRefusalIsNoAccountsFault is red (502); with the old wording
it was red on WSL (retryable true through ModelUnserved).

Not tried: a refusal against real accounts. Not changed: a run that
starts and fails (tuiNoStart) is still a 502, retried on the next
account. Part of #4778.
2026-11-01 22:43:52 +08:00
yetone 2503520f82 codexcat: each Codex model takes official Codex's own instructions for it (#3759, #4008, #4783)
Every magpie model in Codex's catalog (model_catalog_json) carried
gpt-5.2-codex_prompt.md ("You are Codex, based on GPT-5"), so a magpie
GPT-6 model, the auto group's included, ran on a GPT-5.2-era prompt while
official Codex sends GPT-6's own template. magpie still writes no words of
its own into the prompt and leaves the identity line alone: each entry now
takes the text official Codex sends that model, word for word.

- A model's slug (the id's last segment) is matched as Codex 0.166
  matches one (longest prefix of an official slug): first in the entries
  the user's ChatGPT account handed this Codex (models_cache.json), whose
  base_instructions and model_messages go over as sent; then in Codex
  rust-v0.166.0's bundled models.json (instructions_template only, as an
  older Codex may not read 0.166's model_messages), embedded as
  codex_instructions.json.
- Any other model, and a routing group, takes Codex's prompt for a model
  it doesn't know (models-manager/prompt.md, model_info_from_slug), which
  replaces codex_prompt.md: that is what official Codex sends it.
- ownEntry with no base_instructions, and internal/provider's
  codexInstructions fallback, take the same official text.
- testdata holds Codex's models.json and prompt.md at rust-v0.166.0;
  TestBundledIsCodexOwn fails when the embedded copies drift from them.
- GET /v1/codex/models (a remote Codex's model_catalog_url): entries are
  now ~21 KB, so Codex before 0.166's 1 MiB cap holds about 48 of them
  (was ~125). Codex 0.166 reads the catalog whole (models_endpoint.rs
  passes no body limit), and it sends ?client_version=, so the cap now
  applies only to a Codex below 0.166 or one that doesn't say
  (codexReadsWholeCatalog). docs/reference.md says so.
- docs/subsystems/agent-wiring.md: a "Codex instructions" row. The
  Antigravity cloak's comment no longer calls the GPT-5 prompt magpie's.

Run (mote's disk is full, 100% with other sessions' runs, so on WSL
magpie-desktop through wsl-run):
- go test ./internal/codexcat/: ok. go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok. gofmt -l: clean.
- go test -tags nogui -count=1 -timeout 45m codexcat, provider, agent,
  gui, gateway (every package that imports codexcat): codexcat, provider,
  gui ok. agent: TestGrokInstalled and TestOmpDetectedWithPiDir red, the
  same at origin/main 276c806db on the same box (#3548, #4033: WSL binfmt
  and install detection). gateway: TestCodexCatalogFitsCodexsLimit and
  TestCodexCatalogKeepsTheKeysUsedModelsFirst red from this change (the
  1 MiB cap, fixed above; both ok after, with every TestCodexCatalog*,
  TestCodexListed*, TestCodexApp*), and TestUnroutedHeldReportSaved, red
  only in the full run, ok alone here and at origin/main (#4300).
- Real Codex 0.166.0 (npm) in a sandbox HOME/CODEX_HOME, model_catalog_json
  from this codexcat, against a fake Responses gateway on 127.0.0.1:38611
  capturing each request: 0.166 sends the instructions as the first
  developer message (no top-level instructions). For magpie/gpt-6-astra it
  equals gpt-6-astra's instructions_template in Codex's models.json, byte
  for byte; for magpie/deepseek-v4-pro it equals prompt.md.

- After rebasing on origin/main 9da9bfabd: go vet (linux, windows) of
  codexcat, gateway, provider ok; codexcat ok; -run
  "Codex|Antigravity|Grok" in gateway and provider ok. Then rebased
  onto 546cdbde6 (7 commits in redact, gateway translation and a GUI
  test, none in codexcat or the Codex catalog) and not run again.

Broken by hand:
- The cap held for every client_version: both catalog tests FAIL (47
  listed for 0.166.0, 0.167.0-alpha.1 and 1.0.0).
- Old codex_prompt.md and Prompt everywhere: TestBundledIsCodexOwn,
  TestThirdPartyModelsTakeCodexOwnInstructions (all 7 slugs started "You
  are Codex, based on GPT-5"), TestThirdPartyModelsTakeCachedEntry,
  TestOwnEntryInstructions and TestCodexCatalogKeepsOwnEntries FAIL.
- The same real Codex run on origin/main's codexcat: both models' first
  developer message is the 7.5K GPT-5 prompt, differing from the official
  text at byte 15 (astra) and 8 (deepseek).

Not tried:
- GOOS=darwin go vet (needs mote, full).
- Reading the bundled catalog from the user's installed Codex binary;
  the snapshot is 0.166's, and a Codex release with new templates needs
  testdata and codex_instructions.json refreshed.
- An Antigravity account with Codex's unknown-model prompt ("You are a
  coding agent running in the Codex CLI"): the cloak breaks only the
  GPT-5 identity lines tried before.
- A remote Codex below 0.166 with many models through a gateway key: it
  lists fewer than before; the used ones FitOwn moves into the first 100
  can fall past the 48 that fit.
- A real ChatGPT account's models_cache.json entries (tested with a
  fixture cache).
2026-11-01 22:30:51 +08:00
yetone 276c806db2 plugins: a plugin's own requests are counted; a provider plugin's options get the editor (plugins#592)
zelong77 asked for two things once Devin 0.1.30's cache keep-alive
worked: its pings were invisible in magpie, and the interval and ping
count could only be edited in plugins.json. The owner decided pings are
shown as counted usage and the two numbers are edited in the GUI.

- host.js gives plugins input.magpie.usage(provider, call) and
  input.magpie.account(provider). usage validates the call (kind
  [a-z0-9_-]{1,40}, a model id, whole-number tokens from 0, status at
  most 999, error clipped to 500) and sends an unasked "usage" event;
  host.go hands it to plugin.OnUsage in the background.
- internal/usage/plugin_calls.go writes each one as a row of agent
  magpie on the plugin's provider (provider.PluginID) and account
  (provider.PluginAccountUser), with its kind. It is counted, priced
  and in every total, not a probe. Kind cache_keepalive is in the
  purpose catalog as "Cache keep-alive" (five languages), so the
  request log names and filters it. The ping itself still goes straight
  to Devin, never through the gateway, which would break the cache.
- /api/plugins reads every plugin's package options example, not only a
  middleware's or request hook's, and the Installed row offers the same
  Options JSON editor for a provider or agent plugin that suggests or
  has options (not while it is off). Clear's confirm no longer calls
  them a middleware's options.
- The Devin mover's min is 0.1.31, which reports each ping and gives
  its two settings' defaults (285 s, 6) to the editor. npm has 0.1.31
  (published 10:03Z); the plugins publish run is red only for
  think-tags' known E404 (plugins#180).
- docs: provider-plugins.md (the API, the options editor),
  gateway-sessions.md (the counted row beside probes).

Run at this tree (rebased on origin/main 85e37162e):
- mote (mote-run): go test -count=1 -timeout 45m ./internal/plugin
  ./internal/usage ./internal/gui ./internal/provider: plugin, usage,
  provider ok; gui red only in TestMainWindowCorners/macOS_26_SDK, the
  macOS 27 red already filed as #3949 (not this change's code).
- mote: GOOS=linux and GOOS=windows go vet of plugin, usage, provider ok;
  gofmt -l clean.
- mote: plugin-provider-options.test.cjs (new, 5 languages, 980/420px,
  Chromium + WebKit), plugin-gateway.test.cjs and i18n-keys.test.cjs:
  28 of 28 pass.
- The whole GUI suite (make test-ui) on WSL magpie-desktop (mote was at
  load ~100 with other sessions' suites, #4125), at the 8f804396f base:
  cut off after 498 test entries, when the session's background jobs
  were killed; 495 ok, 3 red, none on a page this change touches. Run
  again alone at origin/main 85e37162e, the same files are red there
  too: account-eye webkit (#4244), agent-expand-steady webkit 980px
  (#2935), add-button zh's 3000ms waitForFunction (filed #4792). The
  rest of the suite was not run.
Broken by hand (each red, then put back):
- host.go dropping the "usage" event: TestPluginReportsOwnUsage fails.
- plugins.go reading optionsExample for middleware/hooks only:
  TestProviderPluginOptionsExample fails.
- purpose.go without the Cache keep-alive kind:
  TestPluginKeepaliveIsCounted fails (purpose {}).
- plugins.js without ownOpts: plugin-provider-options.test.cjs times
  out waiting for the Options button in every language.
Not tried: a real Devin account's keep-alive ping reported into a real
magpie (needs a live Devin conversation idle for 285 s); a plugin can
report a row for any provider id, as magpie.load can.
2026-11-01 22:14:19 +08:00
yetone 85e37162e9 routing: a route group can be held to chosen accounts (duanckham on X)
duanckham has a personal and a company GPT account, one tool and one
gateway, and wants a group's GPT models to spend only the company
account (or only his own). A second gateway key doesn't fit: his tool
talks to one gateway, and a local agent needs no key at all.

Group.Accounts holds a group to some accounts or keys of the providers
it names, in a gateway key's form and by the key's rule (#905,
Identity.AllowsAccount). The asked group narrows the request's
identity (access.Identity.HeldToGroup: the strict intersection with
the key's own list; "<provider>/\x00" when they share none), so every
gate a key's accounts go through holds the group's too: chat,
responses, messages, count_tokens, embeddings, images and video,
streamed or not. A group reached inside another, as a member or a
fallback, is held in planLevel (hold, Member.Via): its candidates on
an excluded account are Held rows with Weighed.HeldBy, which the
Routing trace tells. Fallback stays within the group's entries; with
every allowed account resting or out the group's usual error comes
back, and a key and a group that share no account get a 403 naming
the group, nothing asked upstream. SaveGroup resolves each entry
(ResolveAccount, shared with the key's CleanAccounts); share and
import drop them. A group without accounts is as before.

GUI: the group editor's Accounts section, a row per member provider
with two or more accounts, "Any of its accounts" until some are ticked
in the app menu (openPicker multi). Every save sends accounts, since a
save replaces the group. Strings in all five languages.

Gateway keys stay as they are: Gateway › "Gateway keys are for other
computers … added here once Share on local network is on" already says
where, and this case needs none.

Run (mote, through mote-run), at cafed0067 on origin/main 9d08993c8:
- gofmt -l internal/: clean. go vet of access, gateway, provider,
  gui; GOOS=linux -tags nogui and GOOS=windows go vet ./internal/...:
  ok.
- go test -count=1 ./internal/access ./internal/provider
  ./internal/gateway ./internal/gui: access, provider, gateway ok; gui
  red only on TestMainWindowCorners/macOS_26_SDK, red on main too
  (#3949, mote's macOS 27).
- node --test group-*.test.cjs routing-group-*.test.cjs
  routing-save*.test.cjs i18n-keys.test.cjs: 433/434. The one red is
  group-found-skip "webkit de 390px: a provider left out of found
  groups" (the clicks moved the page), filed as #4617 from main; the
  file alone passes 20/20 here and on main 94f6f6092.
  group-accounts.test.cjs is 30/30 (Chromium and WebKit; en, zh,
  zh-TW, ja, de; 1100 and 420px; no scroll on the clicks, no sideways
  scroll, the save carries accounts).
- Earlier, at base 5a0c79ed9: go test -timeout 45m ./... all ok but
  TestVisionBridgePassesLines and TestSettingsSaveKeepsWhatItDoesNot-
  Send (fixed on main by 0b783b1dd and b646a9127; both pass after the
  rebase) and TestMainWindowCorners (#3949).
- The whole GUI suite was cut short twice (a wiped scratchpad, then a
  mote reboot). Its runs at load ~140-220 had about 35 reds, none in a
  file this change touches (account-mask, balance-fix, lan-*, the
  #4617 test among them); not chased here.
- Sandbox HOME on mote, the built binary (`magpie serve`, MAGPIE_ADDR
  on a free port) with a fake upstream answering with the key it got:
  group/work and Work -> sk-work (3 of 3), group/mine and relay/m ->
  sk-mine.

- Rebased again onto 8826a15ea (no file in common): go vet of gui,
  provider, gateway; go test -run 'TestGroupAccounts|TestHeldToGroup|
  TestCleanAccounts|Budget|TestGroup' of gateway, access, provider,
  gui: ok; group-accounts and i18n-keys GUI files: 34/34.

- Rebased onto ec104b862 (trace.go and gateway-routing.md in common,
  merged clean): gofmt clean; go vet of gateway for darwin, windows,
  linux nogui; go test -count=1 ./internal/gateway: ok (640s).

- Rebased onto 2b52302dc, then da275848b (no file in common): go vet ./internal/...,
  the TestGroupAccounts/TestHeldToGroup/Budget tests, group-accounts
  and i18n-keys GUI files: ok, 34/34.

Broken by hand, each red, then restored:
- serve's heldByGroup: three TestGroupAccounts* tests red (sk-mine spent).
- count_tokens' heldByGroupAt: the count_tokens route red.
- planLevel's hold: the nested "outer" group red.
- the editor save without accounts: group-accounts.test.cjs red.

Not tried: a real Codex or OpenAI account (the fake upstream stands
in); a CLI `magpie group set accounts=` (no CLI for it yet); a
provider's own fallback naming a held group has no test of its own
(planFallbackGroup passes the group as hold, the same path as nested).
2026-11-01 21:36:32 +08:00
yetone 049848c5ed claude: a branch of a -p run's session goes to the interactive mode, told whole
With the interactive mode on, tool results another request answered
first for a run made as claude -p (before the mode was turned on) were
refused with a 502 (claudePrint's "branch"): the branch would have gone
on as -p. It now starts a new interactive Claude Code told the whole
conversation (startRun): -p's prompt isn't the interactive mode's, so
the cache has nothing of the -p session to read either way, and nothing
runs as -p while the mode is on. This is the second refusal behind
@crosscn's 502 on an old conversation (X, 11-01); the first, words over
400KB, went in v0.1.2614.

- startRun drops such a branch (from and req.branch nil) and logs it;
- the "branch" entry in claudePrint is gone;
- docs/subsystems/claude-subscription-bridge.md says so.

Test: TestClaudeTUIBranchOfPrintRunIsToldWhole (a -p run's saved
session given as the branch: the run is interactive, has no --resume,
and is told the first words too; req.branch is cleared).

Run on mote (go1.26.8), at origin/main da275848b plus this change:
gofmt, vet (darwin, windows, linux -tags nogui) ./internal/gateway ok;
go test -run Claude ./internal/gateway ok (61s); the fork, branch and
cut tests (-run 'Fork|Branch|Cut') ok before the rebase.

Broken by hand: the new block turned off: the test red, the run resumed
the -p session with -p's arguments.

Not tried: a real -p branch with real Claude Code (it needs a -p run's
lead parked on calls when the mode is switched); whether @crosscn's
conversation reached this path rather than the 400KB one; the full go
test ./... (the gateway's Claude tests ran).
2026-11-01 21:36:20 +08:00
yetone da275848b6 tray: Windows shows a card's number in its icon (Benjaminliang_1 on X)
Windows' notification area shows no text beside an icon, so with a card
in the tray the icon itself is now the first card's figure: the first
row of the first card whose first row is a percentage, used or left as
Allowance display has it, its digits alone (trayIconFigure). It is drawn
in Segoe UI Semibold (Go's bold if the font can't be read) at
SM_CXSMICON, white on a dark taskbar, near black on a light one, as tall
as fits, centred by its ink, three digits narrowed into the square
(trayNumberIcon). It is drawn again when the figure, the icon size or
the taskbar theme changes (SystemThemeChanged wakes the loop); the
tooltip still lists every card. A balance or magpie's totals are
skipped; with no such card, or no cards at all, the icon is the bird as
before. Settings > Usage > Tray icon number (settings.TrayNoNumber,
Windows only, on by default, kept per computer) keeps the bird when off;
Menu bar windows is now shown on Windows too, since it picks the row
the number comes from. The number row sits after Menu bar cost, so the
bird > pace > cost order the other tests pin holds. Linux and the Mac
are unchanged. New words in zh, zh-TW, ja and de. app.js stays in the
core budget with one comment shortened, no raise.

Run at this commit on origin/main ec104b862 (traywindows.js merged with
94f6f6092's trayExtra pills; its "not on Windows" note dropped), mote:
gofmt -l empty; go vet and GOOS=windows go vet of gui and settings ok;
go test -count=1 -timeout 45m ./internal/settings ./internal/davsync
ok; ./internal/gui red only on TestMainWindowCorners (#3949),
TestCoreScriptBudget ok. GUI tray-windows, tray-cost, quota-pace,
i18n-keys, tray-bird, tray-logos, tray-usages, quit-ask: 140 pass,
0 fail. win-run on xiaomi-gpu: TestTrayNumberIcon and
TestTrayIconFigure ok. At c0477aa72 the same GUI set once had
quota-pace webkit "On moved the page" (439 !== 120), a late wheel
(#4784); green twice after, and quota-pace alone 3 of 3 green there
and on c0477aa72 itself.

Run before on the same change over origin/main 9d08993c8, mote:
- gofmt -l on gui/settings/davsync: empty; go vet ./internal/gui
  ./internal/settings and GOOS=windows go vet: ok.
- go test -count=1 -timeout 45m ./internal/gui ./internal/settings
  ./internal/davsync: settings ok, davsync ok; gui red only on
  TestMainWindowCorners/macOS_26_SDK (#3949) and TestCoreScriptBudget
  (5 bytes over after the rebase), which is green after the comment
  trim, rerun with TestTrayNumberIcon and TestTrayIconFigure: ok.
- GUI (both engines): tray-windows, tray-cost, quota-pace: 56 pass,
  0 fail. Earlier at this tree: tray-bird, tray-logos, tray-usages,
  i18n-keys green; quota-pace webkit de 420 red once, from a late wheel
  scroll (#4784), green on the rerun; segs-press-redraw red on
  searchAllRow, the same on a clean origin/main 9d08993c8 copy (#4566).
- A 184-file GUI run (the files touching Settings, the tray or i18n,
  before the rebase) under mote load 40-90: 3095 pass, 224 fail. My
  files' reds there (tray-cost: the number row was between pace and
  cost) are fixed above. The rest are in files this change doesn't
  reach (account-alias, model chips, menu-input-scroll, mobile-web,
  omarchy, plugin-github, key-replace, context-map and others; #4600
  lists several). Each was not compared on main one by one.
Windows (win-run on xiaomi-gpu, real Segoe UI): TestTrayNumberIcon and
TestTrayIconFigure ok.
Real Windows 11 run: a production build in a portable sandbox (own
data\, USERPROFILE/APPDATA/LOCALAPPDATA redirected, gateway on a free
port, a fake remote magpie serving one Claude card). The dark taskbar
showed a white "42", then a narrowed "100" when the card read 100%,
and the bird with trayNoNumber set. Only my processes, tasks and
NotifyIconSettings entry were removed afterwards.

Broken by hand: trayIconFigure always "" turns TestTrayIconFigure red
(6 cases); the dark and light colours swapped turn TestTrayNumberIcon
red; the old advance-width centring turns it red too.

Not tried: a light taskbar on the real box (it would change the user's
theme; covered by the test only), hovering the tooltip (screen locked),
other DPIs on real hardware, Windows on ARM64. Linux's code is
unchanged and was not run.
2026-11-01 21:31:55 +08:00
yetone 2b52302dcb claude: the interactive mode takes a first message of any length
@crosscn on X (11-01): after the upgrade made the interactive mode the
default, a week-old conversation (a DeepSeek harness on a Claude model)
got a 502, and worked again only with -p turned back on. A conversation
told whole to a new interactive Claude Code is its first message, and
words over 400KB were refused (claudePrint's "big", tuiPromptMost). The
bound was never tried: the commit that set it lists "a ~400KB paste"
under Not tried.

Tried on real Claude Code 2.1.316 in a sandbox HOME, haiku: a 3MB
bracketed paste showed "[Pasted text #1 +46154 lines]" after 35s; a
500KB one was sent, its transcript holds every line and the question,
and the model answered it (184,168 tokens written to the cache).

- tuiPromptMost and the "big" refusal are gone; claudeTUI, claudePrint,
  claudePrintWhy and claudeNotTUIWhy no longer take the prompt, which
  only that bound read.
- the helper waits for a paste to show a second per 64KB longer than
  pasteWait (shownWait): 10s alone would press Enter while a 3MB paste
  was still being taken in.
- the editor's tooltip says -p takes what the interactive mode can't
  "yet": a JSON schema (en, zh, zh-TW, ja, de).
- docs/subsystems/claude-subscription-bridge.md says so.

Tests: TestClaudeTUIBigFirstMessage (a ~1.1MB first message runs through
the helper, 200), TestShownWaitGrowsWithThePaste; TestClaudeTUIOnRefusesPrint
refuses a JSON schema now; TestClaudeTUIChosen's long-message row runs
interactively.

Run on mote (go1.26.8):
- full go test ./internal/gateway ./internal/claudetui (-timeout 45m) at
  15b035eef plus this change: claudetui ok, gateway red only on
  TestClaudeTUIOnRefusesPrint's -p half (the fake's "ok" fits no schema,
  502); that half now checks that -p ran it, not a 200. gofmt, vet
  (darwin, windows) ok; claude-mode and i18n-keys GUI files 44/44 and
  4/4 in chromium and webkit.
- rebased on origin/main ec104b862, at the pushed tree: gofmt, vet (darwin,
  windows, linux -tags nogui) ok; go test -run 'Claude|Budget'
  ./internal/gateway ./internal/gui ok; ./internal/claudetui ok;
  claude-mode 44/44, i18n-keys 4/4 in both engines.
- a real run through the helper (magpie built from this tree, real
  Claude Code 2.1.316, sandbox HOME, haiku): a 600KB first message as
  stream-json, answered "MANGO" in 12.5s, its transcript holding all of
  it.

Broken by hand: the 400KB refusal put back: TestClaudeTUIBigFirstMessage
red with the reporter's 502; shownWait returning pasteWait alone:
TestShownWaitGrowsWithThePaste red.

Not tried: the reporter's own conversation or a DeepSeek harness; a
first message past the model's context (Claude Code's own error then,
as with -p); a paste over 3MB; Windows or WSL with a large paste; the
whole go test ./... (the gateway and claudetui packages ran whole
before the rebase).
2026-11-01 21:30:04 +08:00
yetone 8f804396fd mcp router: the hub says what its servers are for, and Pi's first prompt hears it
Asked "can you drive a browser?", Pi said no until nudged. Two causes:

- The hub's initialize instructions were one generic sentence ("The tools
  of the MCP servers ticked for this agent…"), so nothing said that
  playwright drives a browser or deepwiki answers about GitHub repos.
  They now start with one line, "Tools of context7 (…), deepwiki (…),
  playwright (Drive a real browser), …", at most 250 characters (names
  first, "and N more" past room, abouts shared out short-first), then a
  "- name: about" line per server. An about comes from the market entry
  the server was added from (by key, then by name), else none.
- Pi 1.4.0 lists a codemode server in its system prompt by its config
  description, else its instructions' first line, but writes the first
  prompt without waiting for codemode servers. In -p runs the first
  prompt had "- mcp__magpie (codemode)" and nothing after it. The hub
  entry in Pi's mcp.json now carries that line as its description,
  kept in step with the servers ticked; a description on another entry
  is the user's and is left alone. Pi only: other formats are unchanged.

Sync runs under the library lock, so the hub's servers are read from the
library already loaded ((*Library).hubServers), not through hubServers().

Run (mote, at origin/main ee7b8b072 + this change):
- go test ./internal/library ./internal/gateway -run 'TestHub|TestPi'
- TestHubMCPNamesItsServers: 10 failures without the change, green with it.
- TestHubPiDescription: red with the description assignment removed by
  hand ("the hub entry's description \"\""), green with it.
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet,
  the three builds, go test -tags nogui -timeout 45m ./...: all ok (87 packages).

Real use: a sandbox HOME with context7, deepwiki, fetch, playwright and
time ticked for Pi 1.4.0 (deepseek through the sandbox gateway). After
`magpie library sync`, Pi's mcp.json hub entry carries the line. Five
everyday questions, none naming MCP, two runs without the description
and three with it:
- "can you drive a browser": playwright used every time.
- the H1 of usemagpie.ai: fetch + playwright every time.
- "is it OK to call a colleague in San Francisco now": bash `date`
  without the description (2 of 2), the time server with it (3 of 3).
- Hono timing middleware docs: context7 in 1 of 2 without, 2 of 3 with.
- how the Next.js App Router client cache works: deepwiki in 1 of 2
  without, 1 of 3 with; Pi mostly clones the repo instead. Not fixed here.

Not tried: other agents' first prompts (they get the new instructions
text, not a description), Pi versions other than 1.4.0.
2026-11-01 21:22:58 +08:00
yetone ec104b8625 gateway: a Codex account can spend its credits before magpie moves to another account (jojonas_xyz on X)
jojonas_xyz on X: "我账号额度用完了自动给我切了别的号…找不到怎么关掉设置…你怎么知道
我不是想用 credits 呢". (Roughly: "my account ran out of quota and magpie
switched me to another account by itself; I can't find a setting to turn
that off; how do you know I didn't want to use the credits?")

Cause. At 90% or 98% of a window, smart routing's tier put the account
behind every account that still had room, whether or not it had ChatGPT
credits. Codex's own sign-in (NextLogin / SwitchWhenSpent) moved at the
spent share in the same way. The account's credits were spent only once
every other account was used up, and the switch was a log line. The Use
credits switches that existed (on, and "Only after other accounts" from
699ddf152) were only on the Usage page and the panel. None of them meant
"stay on this account and spend its credits".

Change.
- A fourth credits mode, first: settings.CodexCreditsFirst. on, first,
  last and off are exclusive; one mode replaces another.
- routes.Seat.First: a first seat's tier is 0, so routing keeps it in
  front past its windows while it has credits. The trace records
  Weighed.CreditsFirst.
- NextLogin keeps Codex's own sign-in on such an account (spendsFirst).
- The POST /api/codex-credits handler takes "first". The general
  settings save keeps the stored value.
- The CLI: `magpie quota credits <account> first`.
- GUI. No new page and no new component, only the Use credits row that
  already exists:
  - 供应商 → Codex → 账号 ⋯ → 使用积分 → 「先用完积分再换账号」. The
    Providers ⋯ tools now carry the credits row too, which is where the
    reporter looked.
  - 用量 → Codex 账号卡 → 使用积分 → 「先用完积分再换账号」.
  - The menu-bar panel's folded line reads 「开,先于其他账号」.
  - The "First again once it has room" tag on a moved-off account now
    points to the switch in its title.
  - Strings are in en, zh, zh-TW, ja and de.
- "Only after other accounts" (gokoshiki, 699ddf152) is unchanged.
  Its off title now says what off means.
- Docs: docs/reference.md and docs/subsystems/gateway-routing.md.

Budgets: at this head app.js is 1,312,105 of 1,316,874 bytes, and
TestCoreScriptBudget passes (231 bytes under before the rebase). Comments
were condensed; no budget was raised.

Run on mote, at this tree (rebased on origin/main 9d08993c8; the rebase
moved the settings save into internal/settingsapi, which now carries
CodexCreditsFirst beside CodexCreditsLast):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
  ./internal/routes ./internal/settings ./internal/settingsapi
  ./internal/gui ./internal/cli at 9d08993c8+1: gateway, provider,
  routes, settings and settingsapi ok. Two reds, both filed:
  - internal/gui TestMainWindowCorners/macOS_26_SDK: #3949.
  - internal/cli TestLibraryMCPHub, TempDir cleanup not empty: #4140.
  At the pre-rebase tree (da0005df8+1) internal/gui also had
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestColdTurnsTaken
  (#4510), red the same at da0005df8; both pass at this head.
- New tests:
  - internal/provider/codex_credits_first_test.go
  - internal/gateway/codex_credits_first_test.go (routing and the trace)
  - internal/gui/codex_credits_first_test.go (POST sequence, sandbox HOME)
  - internal/gui/tests/codex-credits-first.test.cjs: the Usage page and
    Providers ⋯ at 900 and 440px, and the panel at 360px; chromium and
    webkit, en zh zh-TW ja de. It also checks for no select, no stripe,
    the i18n keys, and that a click does not move the page.
- The whole GUI suite (make test-ui), at da0005df8+1 on mote at load
  66 to 213, in two parts (a wiped scratchpad cut the first log; its red
  titles were kept): 59 files with a red. 45 of them are red at
  origin/main da0005df8 too, each under an open issue: #4304 (mote
  umbrella), #4600, #4471, #4120, #4119, #4621, and per file balance-fix
  #4682/#4683, gui-ja #4580, page-width-steady #4541, phone-connect-menu
  #4706/#4707, quota-curve #4768, segs-press-redraw #4566, signin-proxy
  #4643/#1814, zhipu-team #4728, model-copy-id #4621 (red 4 of 4 on main).
- The 14 green at da0005df8 were run again at this tree. One was this
  change's: usage-curve-zoom-back. The Codex card's fourth credits line
  (366px, was 344) held the DeepSeek card beside it to 261px, so the
  "card grows" check at 1100px had no room. Its fixture now turns the
  Codex account's credits off, since the count of credits lines isn't
  what it tests; 20 of 20 pass.
- At this head (9d08993c8+1), on mote at load 75 to 84: codex-credits-first,
  codex-credits-last, codex-credits, routing-codex-credits-again,
  panel-options-fold, usage-curve-zoom-back, i18n-keys and the 13 files
  above: 232 tests, 227 pass. Each red has an open issue:
  - models-fold webkit en/zh, "ebody holds" after the click: #4071; red
    the same at 9d08993c8 (run there).
  - account-weight webkit, same "ebody holds": #4644 (red at
    da0005df8+1, green in this run).
  - routing-many-keys chromium de "2 keys in sight at the foot": #4082
    (under load; red again alone here, green at 9d08993c8 in one run).
  - signin-closes-sheet chromium en/zh: #2628 (green alone at this head
    in a second run).
  - signin-again and signin-port-blocked, red once at da0005df8+1 under
    load, pass at this head and at 9d08993c8.

- Rebased last onto 94f6f6092 (three commits; c0477aa72 changes the
  Codex Providers row): go test -run 'Budget|CodexCredits|SettingsSave'
  ./internal/gui ok, and codex-credits-first, codex-credits,
  codex-credits-last, providers-reset-use, i18n-keys and
  usage-curve-zoom-back: 92 of 92 pass.

Broken by hand, each red, then restored:
- spendsFirst forced false: the provider test is red.
- The gateway's l.first forced false: both gateway tests are red.
- codex-credits-first.test.cjs against origin/main's assets: red
  (TimeoutError on the switch).

Not tried:
- No real ChatGPT account with credits went past its window. The routing
  order and NextLogin are tested on fakes only.
- The Linux and Windows apps were not run.

go vet -tags nogui ./... with GOOS darwin, linux and windows on mote:
clean (cgo enum warnings only). gofmt -l on the changed Go files: clean.

Claude has no equivalent: magpie reads no extra_usage and has no Use
credits modes for Claude. Filed as #4662 (see #4241).
2026-11-01 21:19:22 +08:00
yetone 8826a15ea4 gui: a Quit while agents go through magpie asks first, naming them (Aisiverto on X)
Aisiverto on X (Windows, v0.1.2519) wired Codex to magpie and quit magpie.
Codex then retried "unexpected status 502 Bad Gateway ... url:
http://127.0.0.1:3425/backend-api/codex/responses" five times and gave up,
and it took a long search to find magpie's openai_base_url in config.toml.

A Quit the user chooses (the tray's Quit, the panel's and window's Quit,
Command-Q on the Mac) now asks first when this process serves the gateway
and agents are wired to it. The window comes up on a sheet
(quitask.js, lazy-loaded) that names each agent cut off, says closing the
window keeps magpie running (menu bar on a Mac, system tray elsewhere),
and offers Quit (focused), Disconnect and quit, and Cancel. Disconnect and
quit puts each agent back as its row's Disconnect does, then quits; a
disconnect that fails keeps magpie open, named in the status line. A
second Quit within a minute of the question quits, so a window that
can't show it traps nobody. With nothing wired, or another magpie serving
the gateway, Quit quits at once.

Not asked: a restart to update, Uninstall, a browser's page (magpie web),
logging out or shutting down, and the Dock's Quit (AppKit terminate:).

Found while checking the report:
- Closing the window on Windows hides it; magpie stays in the tray and
  the gateway keeps serving (tried for real, below). Not a bug.
- Autostart is off by default on Windows.
- The proxy / NO_PROXY in the report isn't magpie's to fix: the 502 is
  magpie's port with nothing behind it.

Strings in en, zh, zh-TW, ja and de (existing terms: Agent, 退出). No
native dialog, no <select>. TestCoreScriptBudget met without a raise:
app.js gains two lines, the sheet is outside the core, and driftFix's
comment block is cut to six lines (453 bytes back; main's core had grown
to 258 bytes over with these lines in).

Run, at this head (on origin/main 94f6f6092), on mote unless said:
- gofmt -l internal/gui: clean.
- go vet ./..., GOOS=windows go vet ./..., GOOS=linux go vet -tags
  nogui ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows
  go build: ok.
- go test ./internal/gui -run 'Budget|Quit|CommandQ', and with -tags
  nogui -run 'Budget|Quit': ok (TestCommandQAsksFirst runs AppKit in a
  child process).
- quit-ask.test.cjs, old-webkit.test.cjs, i18n-keys.test.cjs in chromium
  and webkit, en/zh/zh-TW/ja/de: 60/60 ok.
- At the previous base (9d08993c8): go test ./internal/gui (whole
  package, GUI build): two reds. TestCoreScriptBudget (258 over, fixed
  above) and TestMainWindowCorners/macOS_26_SDK, red the same at
  9d08993c8 itself (#3949, macOS 27). The nogui run of the package was
  not reached.
- The whole GUI suite: started at 24fd4a250 on WSL (magpie-desktop),
  stopped about halfway (3,915 results) to rebase; 68 reds in 28 files.
  Those 28 files with quit-ask, old-webkit and i18n-keys at 9d08993c8+this
  on mote: 74 reds in 7 files, none in this change's files. The 7 alone
  at origin/main 9d08993c8: the same 6 files red (73), and
  gateway-caller-keys red at main when run alone (1 of 4). All filed:
  balance-fix #4682 #4683, key-replace #4126 #3476, agent-panel-name-width
  #4203 (red on macOS too, commented), context-map #3488, header-centre
  #3479, gateway-key-models #4616, gateway-caller-keys #3797.
- Not run: go test ./... in full (mote at load 140-160 with others' full
  suites, WSL with two GUI suites), and the GUI suite to its end.

Broken by hand, each red:
- api.go's ask skipped (false &&): TestWindowQuitAsksFirst "the window's
  Quit didn't ask (AskQuit never ran)".
- askingQuit without RemoveMenuItem: TestCommandQAsksFirst "the app menu
  still has the Quit role".
- quitNow as asked == 0 ||: TestQuitNow "connected, never asked: quitNow
  = true, want false".
- The return after a failed disconnect removed: quit-ask 5/25 chromium
  red (the failed-disconnect test in every language).
- app.js's ?ask=quit line removed: 20/25 webkit red.

Windows, for real (xiaomi-gpu, sandbox HOME/APPDATA under
C:\Users\yeton\quitask-sb, MAGPIE_ADDR 127.0.0.1:3471, MAGPIE_NO_ACCOUNTS,
a -H windowsgui build of this branch, launched in the desktop session):
`magpie codex fakeq/m1` wired the sandbox Codex to
http://127.0.0.1:3471/backend-api/codex; WM_CLOSE on the window left
the process alive with no visible window and the gateway listening.

Not tried:
- The tray's Quit and the sheet on real Windows: WebView2's CDP port
  never listened and UI Automation didn't find the tray icon, so the
  sheet was tried in Playwright only.
- A real Codex run against the sandbox gateway before and after a quit.
- The Dock's Quit (not covered by design).
2026-11-01 21:16:35 +08:00
yetone 15b035eef0 claude: the interactive mode takes an image known by its URL
The interactive mode is pasted files, so an image a client names by its
URL alone made the run fall to the refusal list ("image"), which with
the TUI on means a 502. Now serveSubscription downloads each such image
first (fetchURLImages): from public addresses only (publicClient, the
same fetch the other providers use), checked to be an image by its
bytes, and kept by URL (32 of them) so a conversation that hands the
same URLs over each turn downloads each once. One that can't be had
fails the request with a 400 naming the URL and why; nothing of a
non-image's content is echoed. claudePrint's "image" entry stays as a
backstop, unreachable with the mode on.

The provider editor's tooltip for claude -p no longer lists the image
among what the interactive mode can't take (en, zh, zh-TW, ja, de), and
the bridge's subsystem page says how the image is fetched.

Run (mote, at this tree on 9f17ad4c1): gofmt -l clean; go vet
./internal/gateway, also GOOS=windows; go test -count=1 -timeout 45m
./internal/gateway: ok (760s), with ./internal/claudetui ok; GUI claude-mode, claude-tui-setting and
i18n-keys in chromium and webkit: 44, 16 and 4 pass in each engine, 0 fail.

Rebased on 9d08993c8 (main touched claude_subscription.go's tool names), then
at the pushed tree: go vet ./internal/gateway; go test -run Claude
./internal/gateway ok (68s); i18n-keys and claude-mode 48 pass, 0 fail
in each engine.

Broken by hand: with the fetchURLImages call taken out,
TestClaudeTUIImageByURL is red (502 "an image known by its URL"); green
with it back.

Not tried: a real image by URL through a real interactive Claude Code
(the plan's quota is kept for the long-conversation runs that come
next); the download itself is
FetchImage's, which the other providers' image paths already use.
2026-11-01 20:54:37 +08:00
yetone 9d08993c8b routing: Cheapest first prices Ollama Cloud's DeepSeek models at double from 12:00 to 18:00 UTC on weekdays (hayden4608)
hayden4608 on Discord asked that time-of-day routing use the gap
between peak and off-peak prices, citing https://ollama.com/pricing.
That page (read live on 11-01) gives Off-Peak rows for two models
only, deepseek-v4.1-flash ($0.30/$1.20 peak, $0.15/$0.60 off-peak) and
deepseek-v4-pro ($1.32/$3.96 peak, $0.66/$1.98), and says off-peak is
"outside 12:00 and 18:00 UTC on weekdays and all day on weekends".
models.dev's ollama-cloud catalog lists the off-peak prices, so magpie
priced Ollama Cloud's peak hours at half.

- catalog: a new Peak kind, PeakOllama. Its hours are 12:00 to 18:00
  UTC, Monday to Friday, with no holidays. PeakFactor (2) matches the
  page for both models, cache reads included.
- provider: a peakBill for ollama.com (preset/catalog ollama-cloud)
  that names the two models. Dated tags (deepseek-v4-pro:1017) count
  as their model; the bare name before ':' is compared without
  allocating. Every other model there (glm-5.3, gpt-oss...) and every
  other vendor stays flat. A local Ollama, a relay that names itself
  ollama-cloud, and an ollama.com.evil host are not matched.
- GUI: a model's price tooltip names Ollama's hours for peak "ollama".
  The Cheapest first and rate-window texts no longer say that only
  DeepSeek's hours count, in en, zh, zh-TW, ja and de.
- docs/reference.md, site docs (en, zh, ja) and the gateway-routing
  and providers-accounts subsystem pages say the same.

Run (on mote through mote-run, at this tree rebased on ef3e74a07):
- go test for ./internal/catalog ./internal/provider ./internal/gateway
  for the new and changed tests, under TZ=UTC, Pacific/Kiritimati,
  Pacific/Pago_Pago and Asia/Kathmandu: ok. The tests check 11:59,
  12:00, 17:59, 18:00, 00:00 and 23:59 on weekdays, a Chinese holiday
  Monday, Saturday and Sunday, at +14, -11 and +0545 instants.
- gofmt -l internal: empty. go vet ./..., GOOS=linux go vet -tags
  nogui ./... and GOOS=windows go vet ./...: ok.
- GUI (Chromium and WebKit): model-price-edit, provider-rate-windows,
  routing-cheapest-first, i18n-keys, gui-de, gui-ja, gui-zh-tw.
- go test -count=1 -timeout 45m ./... (one suite on mote): every
  package ok except internal/gui. TestCoreScriptBudget was 7 bytes
  over, so this commit drops a comment from the app.js change rather
  than raise the budget; it passes now. TestMainWindowCorners/
  macOS_26_SDK (the window's toolbar taken off) is red on mote and
  touches nothing here: it is red
  the same way at origin/main ef3e74a07 alone, and is #3949 (macOS 27).

Broken by hand (each red, then restored):
- the peak hours ending at 17:00: TestOllamaPeakHours red.
- the Ollama bill removed: TestPeakOf, TestOllamaCloudOffPeakPrice red.
- tagged false: the dated-tag rows red.
- Ollama's hours used for every Peak kind: TestPeakHours,
  TestPriceOfPeak and TestCheapestFirstGroupFollowsPeakHours red.

Not tried: a real Ollama Cloud account or bill; a local Ollama's
":cloud" models (sent through the local server, so not priced here);
other vendors' off-peak schedules; the site is not deployed.
2026-11-01 19:02:59 +08:00
yetone 7d1f2ecba3 claudecode: magpie keeps the Claude Code it downloaded at the newest release
alextjy on Discord runs magpie in Docker with Claude Code from
`magpie claude-code install`, and asked whether a magpie update touches
it and how it updates. The download lives in <cache>/claude-code
(/config/cache, on the volume), so a new image keeps it. But nothing
ever updated it: every run magpie starts sets DISABLE_AUTOUPDATER, so it
stayed at the version first installed until the user ran install again.

claudecode.KeepCurrent now runs while magpie serves (a WhileServing
loop): a minute after start and every six hours it asks
downloads.claude.ai for the latest release and downloads a newer one,
checked against the manifest's SHA-256 and size as install does. The
version it replaced is removed on the next look rather than at once,
since a run being started may hold its path (Install, the CLI's, still
removes it at once; a folder with a .part download in it is left
alone). It does nothing when magpie downloaded none, when the machine
has its own `claude` (that one is run and updates itself), or when
DISABLE_AUTOUPDATER is set for magpie, Claude Code's own way to hold a
version. A failed look keeps the download and is logged. It never
downgrades.

The status line of `magpie claude-code`, the Docker docs (en, zh, ja)
and the bridge's subsystem page say so.

Run:
- wsl-run (Ubuntu 24.04, Go 1.26.8): go vet, then go test -race -v
  ./internal/claudecode/ -run 'Keep|Install|Find': all pass.
- Broken by hand on WSL, each red: no newer() check
  (UpdatesMagpiesDownload, LeavesWhatIsntMagpiesToUpdate), no own()
  check (the_machine's_own), pruning at install (UpdatesMagpiesDownload),
  no prune on the next look (UpdatesMagpiesDownload).
- Real use on WSL, sandbox HOME and XDG_CACHE_HOME: a throwaway program
  with a fake 2.1.1 download ran KeepCurrent against the real
  downloads.claude.ai. After 1m34s it logged "updated from 2.1.1 to
  2.1.316", the kept binary's --version said "2.1.316 (Claude Code)",
  2.1.1 was still there for the next look, and the loop ended with its
  context.
- mote, at this tree: GOOS=windows and GOOS=linux go vet -tags nogui of
  both packages, go vet ./internal/claudecode/, go build ., then
  go test -tags nogui ./internal/claudecode/ ./internal/cli/ -timeout 45m:
  VET-OK; claudecode ok 0.680s, cli ok 56.673s.
- gofmt -l clean.

Not tried: the Docker image itself (no docker on the test boxes), and a
Windows run whose replaced binary is still in use (prune leaves what it
can't remove for the next look). Full suite not run: the change is the
claudecode package, one WhileServing line and one CLI status line. A
WSL run of ./internal/cli/ at the default 10m timeout timed out while
the box ran other sessions' full suites; the 45m run above replaces it.
2026-11-01 19:00:51 +08:00
yetone 9f17ad4c12 claude: the interactive mode takes safeguards and a client's cache marks
With the interactive mode on, nothing runs as -p any more (e5f66f8a6),
so a request carrying safeguards or a client's own cache marks was
refused. The owner (11-01) asked for every such request to work in the
interactive mode.

Safeguards: interactive Claude Code reads CLAUDE_CODE_EXTRA_BODY only
as it starts, so startRun puts them in the run's environment
(claudeEnvVars now cleans it and DISABLE_PROMPT_CACHING from what is
inherited). A turn whose safeguards changed ends the run, and the next
starts anew, told the whole conversation (setSafeguards).

Client cache marks: the helper pastes the words without their marks, so
the run keeps Claude Code's own prompt caching (no
DISABLE_PROMPT_CACHING, no client tail), and X-Magpie-Cache-Marks-Dropped
names every mark the client placed (clientCache.pasted, systemMarks).

The provider editor's tooltip, in every language, no longer lists them
as what only -p takes. The bridge doc says how each is handled.

Run:
- mote, at this tree: go test -count=1 -timeout 45m ./internal/gateway
  ./internal/claudetui: ok (gateway 897s, claudetui 10s)
- mote: node --test claude-mode, claude-tui-setting, i18n-keys: ok, all three
- New TestClaudeTUISafeguardsInEnv and TestClaudeTUIClientCacheKeepsItsOwn
  (a stand-in helper running the script Claude Code). With each change
  broken by hand, its test went red.
- Windows (GOOS=windows on mote) and Linux (wsl-run -tags nogui) go vet
  of the gateway: ok, on the tree with the image change on top.
- Real Claude Code 2.1.316, interactive, sandbox HOME: an extra body
  given in its environment reaches Anthropic (it answered 400
  "safeguards.0.dangerous_tool_use.classifier_context: Input should be
  an object" to a made-up shape).

Not tried: a real run with a valid safeguards shape (the test account
is at its 5-hour limit).
2026-11-01 18:52:44 +08:00
yetone ee7b8b0723 commandcode: a key's Credits window says GOAT/Go/Pro's month in credits, not dollars
jiezhengj on Discord (#feedback): Command Code GOAT says "$100 on
DeepSeek V4.1 Flash", but magpie's bar counts against $70. Command Code
counts Go, GOAT and Pro in usage-value credits
(docs/resources/usage-limits: "full-allowance models like GLM-5.2 get
$1 of usage per credit, and lower-allowance models draw proportionally
more credits per dollar"); GOAT's month is 70 of them, $100 of DeepSeek
V4.1 Flash or $70 of GLM-5.2 (pricing page, read 2026-11-01). The 70 is
right: command-code 1.88.2's getPlanInfo still has individual-goat 70,
and billing/credits' monthlyCredits counts down in the same units. The
signed-in subscription's card, served by the plugin, says "credits"
since 0.1.20 (plugins #556; mover min is 0.1.21). magpie's own card for
a Command Code key (cmdQuotaOf, via cmdKeyWindows) still said
"$28.80 / $70.00" and added bought dollars into the pool.

Now, as the plugin: on Go, GOAT and Pro the window is "28.80 / 70.00
credits", used of the month's credits alone, with bought and free
credits said beside it ("+ $5.00 extra"); Max, Ultra and Teams Pro keep
the CLI's dollar pool; Provider, pay as you go, has no month.

Run (mote): go test ./internal/provider -count=1 ok at this commit on
origin/main d1a94f579; at the same change on cbfbcb383, go vet ./internal/provider on darwin,
linux and windows ok; gofmt -l clean; gateway LoopGuard (reads
docs/subsystems) ok.
Broken by hand: with the units branch turned off,
TestCommandCodeQuotaShowsWindows and TestCommandCodeKeyCardHasCredits go
red ("$28.80 / $75.00", "$4.78 / $10.00").
Not changed: a key's balance line (readCommandCode) still adds credits
and dollars; it has no plan to tell the unit by. Filed as #4774.
Not tried: a real GOAT key's card in the GUI.
2026-11-01 18:48:13 +08:00
yetone 57246b3818 usage: a provider's accounts together, and a routing group's (CryptoSarom on X)
CryptoSarom on X (tweet 2116797183207035245, the tray panel's Usage tab):
"能否支持合并用量和额度显示? 有时候更关心某个模型还能用多少 ... 同个供应商
同模型可以合并 ... 或者单个路由组单独显示用量和额度. 有需要关心账号限制
的时候可以进详情再去看".

What it does:
- A Usage card of several accounts has "All N accounts" under its head:
  each window the accounts share, one figure and a thin bar, and how
  many couldn't be read. The tray panel's group of several has the same
  strip above its cards (at most 3 windows). Each account stays below it
  as it was: the details are where they were.
- A routing group's row (Routing › groups) has a line for each provider
  among its members: "WorkBuddy AI, 4 accounts: Credits 355 / 1,500
  credits · 23.7% used · 1 couldn't be read", following Used/Left.

The design, and why:
- Only what reads alike goes together (mergeQuotas). Counted windows of
  one name and unit add their amounts and limits, the share is of the
  sum; wallets add balances in one unit. A window said only as a share
  is the mean over accounts on one plan, whose allowances are the same
  size, so the mean is the share of their allowance together; two plans
  are never averaged, and a share is never added to a count. Text-only
  windows are left out; unlimited only when every account read says so.
- An account whose reading failed is unknown, not 0 or 100: left out of
  the figure and counted ("1 couldn't be read"). A window an earlier
  reading (asOf) stands in for, past its reset, is left out the same way
  and counted in its tooltip. No single reset is claimed for the whole;
  the tooltip says when the first of them starts again.
- Only what two or more accounts have goes together: one account's
  window is already below it.
- No switch: the strip is additive and quiet (no gradient, no coloured
  stripe; the pill grey of the page, the accent bar the cards use), and
  it names no account, so Hide accounts holds.
- The code is in quotaall.js, imported when a provider first has two
  accounts (quotaAllJS) or a routing group's member has readings, and
  each place is drawn again once it is in. app.js has the loader and the
  two call sites; three comments in the quota code were cut to keep the
  core inside its budget (1,533,096 of 1,533,105), no raise.

Run, at this tree (rebased on origin/main df0320156):
- mote (macOS 27), node --test: usage-merge (7/7), usage-all-accounts
  (14/14: Chromium and WebKit; en, zh, zh-TW, ja, de; light and dark for
  en and zh; Usage page at 440px, tray panel at 360x760, Routing), i18n-keys
  (4/4), old-webkit (6/6): 31 of 31 ok.
- mote, go test -count=1 ./internal/gui: TestCoreScriptBudget ok (app.js
  1,311,777, core 1,533,096); one red, TestMainWindowCorners/macOS_26_SDK,
  #3949 (macOS 27, AppKit), no Go changed here.
- Screenshots of all three places in both engines, every language,
  light and dark (en, zh), looked at.
- Not run: the whole GUI suite. mote had four other sessions' full GUI
  suites running (1h46m+, load 57 to 240) and the WSL box three, so
  per the one-suite-a-machine rule it waited and wasn't run.

Broken by hand (red, then put back):
- quotaall.js counting a failed account as read and dropping the
  two-account rule: usage-merge 4 of 7 red (share vs count, failed is
  unknown, plans apart, balances/unlimited). Before the move to
  quotaall.js, dropping the kind from the key and the stale skip each
  turned their tests red too.
- the loader not drawing again once quotaall.js is in:
  usage-all-accounts 14 of 14 red (both engines, every language).
- usage-merge.test.cjs is red on the old code: quotaall.js isn't there.

Not tried: real accounts (the figures come from fixtures: WorkBuddy AI
credits, Codex Plus and Pro, Claude Max ×2, Kimi); the real tray app on
macOS, Windows or WebKitGTK; a slow first load of quotaall.js (the strip
comes in after the cards on its first draw, measured only on a local
server).
2026-11-01 18:27:45 +08:00
yetone e5f66f8a61 claude: with the interactive mode on, nothing ever runs as -p; the editor switches TUI and claude -p
The owner (11-01): the interactive mode falling back to -p is dangerous,
for the account (a -p request counts as another client's) and for the
cache (a -p run starts without the interactive mode's), so it goes
entirely. With Settings › Models › Replies' interactive mode on:

- a request it can't take (safeguards, client cache marks, a JSON
  schema, an image by URL, words over 400KB, a branch of a -p session,
  a WSL Claude Code whose home or transcripts magpie can't reach) is
  refused before any Claude Code starts, saying why and naming the
  setting (claudeTUIErr), never run as -p;
- a helper that can't start the interactive mode (sign-in asked,
  first-run notes, an untrusted folder, no prompt within ReadyWait)
  ends saying why (claudetui fail); printMode, OnlyEnv and the
  claude-tui-broken mark that sent every run to -p for a day are gone;
- a helper that never answers initialize fails the turn
  (tuiNoStart), and the next turn tries again.

Off still runs every request as -p. The "Interactive only" choice of
v0.1.2448 (claudeTUIOnly) is what On is now; the setting is no longer
read or sent.

The Claude Code provider editor's "Claude Code runs as" row is a
switch between Interactive mode (TUI) and claude -p (owner, 11-01),
saving claudePrintMode and reading /api/claude/mode again; disabled in
magpie web. It reads the settings first when the Settings page was
never opened (prefs null crashed the switch; found by the GUI test).
Chromium has no onfocusin property, so the card on keyboard focus
listens for focusin/focusout. Words in en, zh, zh-TW, ja and de.
Docs: claude-subscription-bridge.md describes refusal, not fallback.

Not covered yet, now refused under On rather than run as -p (follow-
ups, each to be done inside the interactive mode): an image by URL, a
JSON schema, safeguards, client cache marks, over 400KB, a -p
session's branch, WSL transcripts Windows can't read. /usage reads
the allowance with claude -p /usage (no model request) either way.

Run (worktree at df0320156 + this):
- mote: gofmt -l clean; go vet darwin/windows/linux of claudetui,
  gateway (gui for windows); go test claudetui, settings, settingsapi
  ok; gateway -run "TUI|Warm|Claude|AskClaude|Cache|Mode" ok (110s);
  gui -run "Budget|I18n|Settings|Claude" ok.
- mote GUI: claude-mode, claude-tui-setting, i18n-keys: 64/64 pass in
  Chromium and WebKit, 900 and 420 wide, en zh zh-TW ja de.
- wsl-run go vet -tags nogui ./internal/gui ./internal/claudetui ok;
  win-run go test ./internal/claudetui ok.
- Real Claude Code 2.1.316 on macOS through this build's
  claude-tui-helper, sandbox HOME, CLAUDE_CODE_OAUTH_TOKEN: trusted
  folder -> interactive run, streamed (message_start, 4 deltas,
  message_stop), result success in 5.2s; untrusted folder -> exit 1
  "Claude Code's interactive mode didn't run: Claude Code asks whether
  to trust the folder", no -p run; config without onboarding -> exit
  1 naming the first-run notes, no -p run.
Seen red: claude-mode's save test with prefs null before the fix, and
its focus test in Chromium before the listeners; TestClaudeModeLast
while it still read a helper's "this run is -p" line.
Not tried: a real gateway request refused in the GUI (covered by the
Go tests with the fake Claude Code); the new gateway tests run
against the old fallback code; Windows and WSL real runs of this
build; no full suite.
2026-11-01 17:43:17 +08:00
yetone 85fcac4a47 codexcat: a model with no known window still compacts where the user set
jiangguochao666 on X: "这个软件自动压缩设置之后还是不会启动啊,codex里面压缩还剩<一半的时候报错,只能手动压缩才可以".

Cause: when magpie knows no window for a model (a relay that lists no
context_length, a model models.dev lacks), entriesAt and listedEntry
wrote neither context_window nor auto_compact_token_limit, so Long
conversations' Compact at (and a model's own) was dropped. Codex 0.165's
ModelInfo::auto_compact_token_limit is then None and it never
auto-compacts; on the vendor's context_length_exceeded it calls
set_total_tokens_full, a no-op with no window, and errors, so every
later turn errors again until a manual /compact. Codex shows such a
model on its fallback window, which is why the error comes with "<half"
left.

Now such an entry gets the threshold alone as auto_compact_token_limit
(the model's Compact, else settings.Compact(): Compact at, else 272K;
none under Full window). A relay's own listed entry gets a user-set one
only (the model's, or Compact at), and not when its own context_window
or limit is already at or under it.

Run:
- Real Codex 0.165 on mote, sandbox HOME (~/cxc/h*), a fake relay
  refusing past 100K with context_length_exceeded and listing no
  window, magpie serve on 47812, `magpie model compact 80k`, 7 turns of
  ~20K tokens through `codex exec` / `exec resume --last`:
  - old build (h2): catalog None/None, 400 at ~119K, every later turn
    "Codex ran out of room";
  - this build (h4): catalog None/80000, CONTEXT CHECKPOINT COMPACTION
    at 80.6K, no 400 in 7 turns.
  - control (h1, old build, relay lists 200K): compacted at ~80.5K.
- go test ./... -timeout 45m on mote at 1d8ded3ec + this: all ok
  except internal/gui TestMainWindowCorners/macOS_26_SDK, #3949 (mote
  is macOS 27; AppKit title bar, untouched here).
- gofmt -l; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet
  -tags nogui ./...: clean.

Broken by hand:
- TestCodexCompactsWithNoKnownWindow on the old codexcat.go: 6 reds
  (plain, own, bare relay entry get no limit).
- The Full window guard in listedEntry dropped: red ("full window:
  relay/bare told 80000").

Not tried / not changed:
- A vendor that lists a larger window than it accepts (h3: listed 200K,
  takes 100K, default 272K threshold): Codex compacts at 90% of the
  listed window, so it still errors first. magpie can't know the real
  window; the fix there is Compact at under the vendor's limit.
- The interactive TUI (only codex exec); Codex 0.166's compaction path
  read from source, not run.
- GUI suite: no GUI file changed.
2026-11-01 17:38:33 +08:00
pipi f06551c277 gui: a closed window's page is told it is out of sight
A macOS orderOut hides the NSWindow but can leave its WKWebView document
visible. The Routing page's frame loop and SVG animations therefore kept
running in a closed window (20-40% Web Content CPU; reopening and closing
returned it to 0%).

Tell the page before every app-window hide and again on show. Compose that
signal with WebKit's own hidden state, and pause CSS animations while out of
sight.

Verified with:
- go test ./internal/gui -run '^(TestCoreScriptBudget|TestClosingWindowMarksPageOutOfSight|TestClosingHidesShownAccounts|TestPanelCloseHidesIt|TestPanelJoinsFullScreenSpaces)$' -count=1
- node --test internal/gui/tests/window-visibility.test.cjs (Chromium and WebKit)
- the new JS test against v0.1.2049's app.js: it times out without the bridge
- the new AppKit test with hideMain calling Hide directly: it times out without the visibility signal
- go vet ./internal/gui
- GOOS=linux CGO_ENABLED=0 go vet -tags nogui ./internal/gui
- GOOS=windows CGO_ENABLED=0 go vet ./internal/gui

The full GUI package still has unrelated environment failures in
TestProxyCheckSaysAProxyPassedBy and TestMainWindowCorners on this macOS 27
setup.
2026-11-01 17:28:30 +08:00
yetone 7c712847b7 agent: Antigravity's desktop app is a row, wired through its gateway setting (ryougi_hachi on X)
Antigravity (Google's desktop app, 2.15 and later; not Antigravity IDE)
takes a gateway from ~/.antigravity/settings.json: Google's Antigravity
Enterprise Gateway, documented at
docs.cloud.google.com/gemini/enterprise/docs/ai-developer-tools/connect-enterprise-gateway.
magpie writes gateway {enabled, url: magpie's, apiKey: magpie-antigravity,
wireProtocol: openai} and models.defaultModelId, and takes out models.list
(it would narrow the picker). The user's gateway, default model and list
are stashed and put back on disconnect or when a model of their own is
picked; caCertPath and the rest of the file are untouched. Sync keeps what
the user added to magpie's block, and so does a set again (a moved port,
Reconnect). Check speaks when admin_settings.json or AGY_LLM_GATEWAY_URL
wins over the file, and when the block's url or key is no longer magpie's
(wiringOff), so drift and a port move see it. AGY_LLM_GATEWAY_URL joins
agentenv.Vars, cleared in every sandbox. Found by its bundle
(com.google.antigravity, 2.15+) or the file its backend writes
(~/.gemini/antigravity/agyhub_summaries_proto.pb); ~/.antigravity alone is
the IDE's and agy's too. The notices are translated (zh, zh-TW, ja, de).
`magpie antigravity` now names the app; agy stays `magpie agy` /
`antigravity-cli`.

Run (worktree base 647323409, on mote):
- Real app backend in a sandbox HOME: Antigravity.app 2.28.2's
  language_server (hub), wired by this branch's magpie built from the
  worktree (`magpie antigravity magpie/rec/pro`, MAGPIE_ADDR on a port of
  its own, a recording upstream as a custom provider).
  GetCascadeModelConfigData listed rec/pro from magpie's /v1/models; a
  cascade ("Say hi") went app -> magpie -> upstream as
  /v1/chat/completions (stream, 12 tools) and its answer came back into
  the trajectory. `magpie usage` counted both calls to Antigravity.
  `magpie antigravity default` gave back the user's genai gateway, model
  and list byte for byte (JSON-equal).
- Before that the same file was checked with the real agy CLI 1.4.12.
- go vet (darwin, GOOS=linux, GOOS=windows) for internal/agent; gofmt.
- go test -tags nogui -count=1 ./internal/agent ./internal/agentenv
  ./internal/gui ./internal/usage ./internal/cli: all ok at this tree.
  The first run was red in four guard tests (TestFolderVarsAreListed,
  TestDriftUnwiredEveryAgent/antigravity, TestReverseProxyIsStillMagpie,
  TestPortMovesEveryAgent): Check had no wiringOff and the variable
  wasn't listed. Both fixed here.
- GUI (node --test, Chromium + WebKit): i18n-keys, agent-notice-lang,
  about-notices, 46 of 46 ok.

Broken by hand: renamed the gateway's stash key and dropped the
models.list deletion: TestAntigravityGateway, TestAntigravityGatewayFromNothing
and TestAntigravityOwnModelBack each went red; the desktopApps entry
missing made TestAntigravityDetected red; writing magpie's block whole on a set
again made TestAntigravitySync red (the user's customHeaders lost). The new tests are red on the
old code (no such agent).

Not tried: the Electron window itself (the backend was driven over its
RPCs, headless); the app on Windows or Linux (its install paths there
aren't known; the backend's file finds it); whether Google sign-in comes
back on its own after disconnect; the full ./... suite, because another
session's full suite was running on mote.
2026-11-01 16:49:55 +08:00
ggbdpq 947377307b usage: the Sessions tab's token totals count the cache, as the Overview's do (#2591)
n1majne3 reports the usage totals ignoring the cache reads the same page
shows beside them. The Overview's totals have counted the cache on request
since #2378 (magpie.usageWithCache); the Sessions tab counted tokens in and
out alone wherever they showed: the tokens tile, a session's row in both
lists (the Usage page's and the Sessions page's, sessSpent), the projects
and models bars and pickers (sessSums, spent), the day chart's bars,
tooltips and calendar, and the top sessions. A reader who asked for the
cache on the Overview saw two different totals for the same period.

The tab now reads usageTokens everywhere, so the one pick decides for both
pages. Its tokens tile carries the same label pop-up and says the cache's
count in its line; a pick made there refreshes the tab it is on, not the
Overview. The chart's day and week buckets carry the cache's counts now
that their value reads them, and the top sessions, ranked without the
cache, are ranked again by the count the reader sees. The default stays
without the cache, as #2378 left it; the per-session median and p90 stay
counted in and out (Stats.Overview ranks them), and the Requests tab's
totals always counted every token (allTokens).

Run at 89521b03 + this: sessions-cache-tokens.test.cjs (new; Chromium and
WebKit, en and zh, APIs faked) fails on the base with "AssertionError: the
tile's tokens: '57.0K' !== '168K'" and passes with the change;
sessions-overview, usage-overview-fold, api-key-usage and
sessions-usage-open pass with it (120 tests, both engines, en and zh).
Broken by hand, each red at its own assertion: the pick's callback pinned
back to renderUsage() (the tab doesn't follow the pick), the top list's
re-ranking left out ("ranked by the count shown"), and the day buckets
without their cache counts ("the day's tokens count the cache").

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:21 +08:00
ggbdpq 655d23f790 library: an MCP server signed in to in Codex itself says so instead of "needs sign-in" (#3508)
A server signed in to with `codex mcp login` was still "needs sign-in"
in the Library. Codex keeps those tokens in its keyring, or in a
.credentials.json of CODEX_HOME when its config's
mcp_oauth_credentials_store is file or the keyring is missing, and the
check read no such file.

It now reads it for each Codex target, beside the config.toml the
target already has, a distro's too (codexCredentialsOf, readCodex in
mcp_agent_signin.go). The file holds an entry per server under the key
codex-rs's compute_store_key makes of its name and a 16 hex of the
hash of its config, each entry naming its server and URL with the
tokens flattened into it (its FallbackTokenEntry, read from codex-rs's
rmcp-client/src/oauth.rs — not the StoredOAuthTokens of the login's
memory the report guessed at). An entry of the server's name and URL
with an access or refresh token names Codex in
ServerHealth.AgentSignIn, and the row says "signed in in Codex"
instead of "needs sign-in". An entry with neither token, one of the
executor's (executor_owned: codex answers no host's lookup with it),
another URL by the same name, and a file that can't be read or parsed
name nobody, so the row stays "needs sign-in". The keyring itself is
never read. A stopped distro has no target and isn't started. The
sign-ins are already part of the check's cache key, and the page names
any agent's id in the row, so mcp_check.go and the GUI needed nothing.

Run:
- TestCheckNamesCodexSignedInItself (internal/library): agent.FakeWSL
  forces the Windows+WSL switch (Ubuntu running, its home a temp root),
  sandbox HOME/USERPROFILE, CODEX_HOME cleared, a real httptest server
  answering 401 with WWW-Authenticate.
- Broken by hand, each red with a FAIL naming the behavior:
  - the old behavior (the reader names nobody): codexCredentialsOf
    returns "": "signed in in codex@wsl:Ubuntu, the check says
    {State:auth ... AgentSignIn:[]}".
  - counting an executor's entry: "only the executor's sign-in
    counted".
  - counting an entry with no token: "a sign-in with no token counted".
- gofmt -l (nothing); go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows for ./internal/library; go build darwin, GOOS=windows
  and GOOS=linux -tags nogui ./...; go test -tags nogui -count=1
  ./internal/library: ok (71s); the two sign-in tests also with -race:
  ok.

Codex's file format was read from codex-rs's source (rmcp-client/src/
oauth.rs, oauth/resolved_store.rs, core/src/config/mod.rs).

Not tried: a real `codex mcp login` (no .credentials.json on this
machine, whose Codex keeps its MCP tokens in the keyring, which is
never read); the test's file is built from codex-rs's writer
(save_oauth_tokens_to_file, its FallbackTokenEntry), and the WSL
distro's file is a temp root behind a FakeWSL probe.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:21 +08:00
yetone 3af592f587 gateway: the overflow memory is read under its lock, so two requests of one conversation don't crash the gateway (#3453)
Review follow-up to ggbdpq's 075aaef62. behindOverflow took the
conversation's inner map under overflowLearned's lock, let go, and then
read it, while noteOverflow and forgetOverflow write that same map under
the lock. Two requests of one conversation at once (a turn beside its
title ask, a client's retry) read and wrote one Go map together, which
is a fatal "concurrent map read and map write", the whole gateway gone.
The loop now runs under the lock.

TestOverflowMemoryReadWhileNoted notes and forgets on one goroutine while
another orders members by the memory. Before this commit, on mote:
go test -tags nogui -race -count=1 -run TestOverflowMemoryReadWhileNoted
./internal/gateway/ -> "--- FAIL: TestOverflowMemoryReadWhileNoted ...
race detected during execution of test". With it, -race -count=20 of
that test, TestOverflowRefusedOnceIsAskedLast and
TestRelayInputCapGoesToTheNextMember: ok.

Also: behindOverflow's comment said resting members keep their order;
the code moves a refused member behind every other one, resting or not,
so the sentence is dropped. gateway-routing.md now describes the memory
beside withRoom's overflow paragraph.
2026-11-01 16:43:21 +08:00
ggbdpq 9a4eaab82a gateway: a Chat body relayed to Gemini's OpenAI-compatible API goes without Ollama's options (#3097)
What changed: a client that takes the gateway for an Ollama server (its
/api/show is answered in Ollama's shape) sends Ollama's per-request
options beside its Chat fields. The google preset serves a model on
Gemini's OpenAI-compatible endpoint, so such a request is relayed as it
came, and that endpoint reads proto JSON: an unknown name turns the
whole request away with 400 "Invalid JSON payload received. Unknown
name \"options\": Cannot find field", every call, whatever the effort.
A body relayed to a Gemini OpenAI-compatible upstream (geminiCompat)
now goes without the top-level options, whose runner settings have no
place on a Chat API, as the Ollama route's own body builder already
leaves them out (ollamaChatBody). Another vendor's Chat upstream still
gets the body as the client sent it, and translated requests are
unchanged: they are built from the request's own fields, which never
carried options. geminiCompat is worked out once where the thought
signatures ask for it too.

Run: TestGeminiCompatRelayLeavesOutOllamaOptions fails on the old code
with "Ollama's options reached Gemini's OpenAI-compatible API" and
passes with the change; a request to another vendor's Chat upstream
still carries options there. go test ./internal/gateway/ ok (346.6s);
go test ./... -timeout 45m: 66 packages ok, internal/agent TestMothX
and internal/gui TestProxyCheckSaysAProxyPassedBy red, both red with
the change stashed on f5b01574 too (this machine's, not this change's);
gofmt -l clean; go vet ./... exits 0 (a cgo warning in internal/gui is
the baseline's); GOOS=linux GOARCH=amd64 go vet -tags nogui ./... and
GOOS=windows GOARCH=amd64 go vet ./... clean (GOOS=linux/darwin vet of
the gui fails in wails v3 beta on the baseline too); go build (darwin
arm64), GOOS=windows GOARCH=amd64 and GOOS=linux GOARCH=amd64
-tags nogui builds ok (a plain GOOS=linux/darwin build fails inside
wails v3 beta on the baseline too). Not tried against Google's real
endpoint: the reporter's 400 names the unknown field, and the fake
upstream checks what it is sent.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:20 +08:00
ggbdpq 026d4423d0 gateway: a Command Code stream that ends with no finish_reason is a cut (#2471)
What changed: a Chat stream of Command Code's whose reply ends with no
finish_reason anywhere - esp32gallery's day had 665 requests, 624 ended
with one, and the 20 that didn't were turns its slow starts lost to a
killed worker, each a ledger 200 with no stop and no error while the
client read "Stream ended without finish_reason" - was taken for a
turn that ended as it should, silence in the ledger and a bare
half-reply for the agent. Its API joins Gemini's OpenAI-compatible one
in saysItsEnd: every whole reply of its says its end, so a stream that
stops short of a finish_reason is said as the cut it is, in the stream,
the same way a relayed Gemini one is (#1644) - and one still held, with
nothing of the reply said yet, fails there for the group's next
candidate. Another vendor's Chat stream may still end whole with
neither a finish_reason nor [DONE]: nothing changes there.

Run: Four new tests, the first two red on cef8c1a4a before the change (the
cut passing as a whole reply, the next member never asked):
TestCommandCodeRelayEndedShort, a half-reply cut ends with "the reply
ended before it was complete", no finish_reason filled in;
TestCommandCodeTaillessFailsOver, a held lead-only stream fails 502 for
the next member; TestAnotherChatStreamWithoutAFinishReasonStaysAsItCame,
another vendor's tailless stream goes as it came; and
TestCommandCodeRelayWholeStaysWhole, a finished reply is never given a
second end.
TestGeminiCompatRelayEndedShort and TestGeminiCompatTranslatedEndedShort
green throughout. Not tried: a real Command Code upstream (the frames
are the reporter's ledger shapes, the host the one balance.go reads).

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:20 +08:00
ggbdpq eb7e72cc7f gateway: a response.completed with no output and no tokens fails over (#2471)
What changed: a Responses upstream that ends its 200 stream with a
response.completed carrying no output and counting no token - WorkBuddy
AI's account answered Codex's request with created, in_progress,
completed and `output: []` three times running (MurmuredVelpro) - had
the completed event taken for a reply's end: the held stream went to the
agent as a completed turn, the try stood as a 200 success, and the
group's healthy members were never asked. streamEvent now reads a
completed with an empty output and a zero usage as the no reply it is -
the same shape a translated reply that said nothing and counted nothing
has failed as since #2086 (repliesCounted) - and fails the held try for
the group's next candidate, in the candidate walk as an empty reply's
does: nobody rests, as the reply's shape failed, not the account. A
completed that counted a token stays a reply, as Claude's own empty
end_turn does; and an event this reaches is one nothing was said before,
since the hold lets the first content through and reads no event beside
it, so nothing of the try has reached the agent when it fires.

The fields said are what is read: a completed that names neither field
goes as it came, as the streamEvent table pinned it
(TestStreamEventRefusals, which caught the first draft reading an
omitted output as an empty one), and a completed that counted a token
stays a reply.

Run: TestEmptyCompletedFailsOver (new) red on 06c2c35d1 before the fix -
one try, status 200, Fail empty, the second member never asked, the
reported ledger shape byte for byte - green after, with
TestEmptyCompletedLeavesAWholeReplyAlone (new: a completed with output
and usage goes as it came) and TestFinishReasonErrorFailsOver green.
Not tried: a real WorkBuddy AI account (the stream is built from the
frames the reporter pasted).

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:16 +08:00
yetone c991733dca docs: the Claude bridge's tool_choice none, asides and cut-copy branches (bbfatx on X)
claude-subscription-bridge.md now describes the four commits before
this one:
- a tool_choice none turn is offered every tool, and what it may call is
  kept apart (subscriptionRun.allowed, mcpCall's refusal);
- an aside of a run that was told tools neither retires the
  conversation's run nor is taken as rewritten (asideOf);
- a branch is a cut copy of its run's session (cutSession), resumed in
  its run's mode (savedSession.tui), in place of --fork-session
  --resume-session-at, with the cache numbers measured on mote; the
  "-p because it is a branch" reason is only for a -p run's branch;
- an interactive run behind a prompt suggestion is cut at the line
  before it (branchAt, lastLine/backLine/behindLine), not told whole.
Verification lists the new tests.

Run at this tree (mote, the whole stack 252006e87..this):
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway
  ./internal/claudetui: ok (gateway 1045.8s, claudetui 9.6s)
- go vet -tags nogui, GOOS=linux go vet -tags nogui and GOOS=windows
  go vet of both packages: clean; gofmt -l internal/: clean
Every symbol and test named was checked against the tree with grep.

Not run: the full go test ./... ; queued behind other sessions' suites
on mote, it was lost before it started.

Not changed: gateway-sessions.md's --fork-session line, which is about
Claude Code's own forks of a user's sessions, not the bridge.
2026-11-01 16:33:07 +08:00
yetone 1adff37796 claude: a refusal Claude Code falls back from goes on to the fallback model's answer (Chixi_Fang on X)
Claude Code 2.1.316 doesn't end a turn at a refusal. It asks the same
model again, then its fallback model (claude-opus-4-8 for Opus 5.5),
whose answer ends the turn with result success. The bridge ended the
reply at the first stop_reason refusal, so the client got "Partial "
plus a refusal, and the gateway's hw.refused moved to another account
or handed the refusal back. That is the "model error" the reporter saw.

readOutput now holds a refusal from Claude Code's own model and goes on
with the next message as one reply. Not held: a client tool call, or a
schema reply. The refusal's stop_details are held too. The refusal is
told only if it stands: at a result with no API status (Claude Code's
model_refusal_no_fallback, -p or TUI) or at the end of output. Then
hw.refused and b01766d13 see it as before. A result with a status after
a refusal is that error, not a refusal. The continuing message's model
goes on the KUsage as Model and Served. The try records the fallback
model, and a reply told whole names it. A stream's message_start can't
change it. Prompts and system text sent upstream are unchanged.

Real behaviour: Claude Code 2.1.316 on mote, in a sandbox HOME and
CLAUDE_CONFIG_DIR, against a fake Anthropic upstream that refuses
claude-opus-5-5 (or every model). The -p and TUI stream-json lines were
captured and trimmed into the fixtures in
claude_refusal_fallback_test.go.

Run (mote-run, worktree at base 4a4a82cd4):
- gofmt -l internal/gateway: no output.
- go vet -tags nogui ./internal/gateway on darwin, GOOS=linux and
  GOOS=windows: clean.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
  (813s).
- The new tests plus TestClaudeSubscriptionRefusal*,
  TestClaudeSubscriptionBigRefusal*, TestClaudeCutStream* and
  TestClaudeRefusalMovesToNextKey: ok.

Broken by hand:
- On the unmodified claude_subscription.go (stashed), FallbackAnswers
  (print, tui) are red with reply "Partial " stop "refusal", and
  RetryFails is red. NoFallback passes, so that behaviour is unchanged.
- Dropping the Served on the continuing usage turns the served
  assertions red.
- Dropping the collector's KUsage Model turns the non-stream try's
  Served red (claude-opus-5-5).
- Making the standing-refusal case `case standing:` (no status check)
  turns RetryFails red.

Not tried:
- A real Claude account (none on mote). The fallback was a fake
  upstream's refusal.
- The full go test ./... suite.
- Words a retracted try streamed before its refusal stay in a stream.
  Claude Code shows them too.
- A refusal after the client's own tool call keeps the old behaviour
  (the reply ends there).
- The overload/529 fallback needs --fallback-model, which the bridge
  doesn't pass (nor does Claude Code by default). That path is
  unchanged.
2026-11-01 16:19:01 +08:00
yetone 5416fdb76b agent: Claude Code on magpie keeps its MCP tools deferred (ENABLE_TOOL_SEARCH)
cybercaius on Discord (#help): the MCP router's 245 tools took 124K
tokens of a 341K context ("Magpie ×245" in Usage › Context). Claude Code
before 2.1.304 keeps tool search off behind an ANTHROPIC_BASE_URL that
isn't Anthropic's, so every router tool's definition went on every
request. 2.1.304 (10-19) turned it on for gateways itself, but a
conversation begun without it stays held off.

While Claude Code is routed through magpie, magpie now writes
env.ENABLE_TOOL_SEARCH="true" into ~/.claude/settings.json: Claude
Code's own documented switch, no prompt or identity change. The gateway
carries deferred tools to every upstream already (#2660,
withoutDeferredTools). It follows the auto-mode review's ownership:
magpie's value is stashed (claude.tool_search), a value the user set,
an empty one too, is theirs, and magpie's goes in desktopOnly/unroute.
T3 Code's magpie instance gets the same "true" in its environment
unless the user gave it a value there.

Not changed, filed as #4755: agents with no tool search of their own
(OpenCode, Gemini CLI, ...) still get the router's whole list; a lazy
router mode for them needs an owner decision. Not changed: Codex, which
already sends tool_search on magpie's catalog (0.165.0 measured: 14
tools, no MCP ones), and newmax/claudescience, which run Claude Code
through the SDK and set no gateway env of this kind.

Run:
- Real Claude Code 2.1.290 on mote, sandbox HOME, sandbox magpie serve
  on 127.0.0.1:3563 built from this tree, a fake Anthropic upstream, a
  245-tool stdio MCP server in the Library behind the router, wired
  with `magpie claude up/fake-1`: first /v1/messages had 12 tools,
  27,443 bytes of tools JSON (+~9KB of deferred names in the messages).
  The same with magpie's ENABLE_TOOL_SEARCH taken out (the old
  wiring): 266 tools, 245 of them MCP, 242,346 bytes.
- Without magpie, against a capture server: 2.1.200 to 2.1.303 send
  every MCP tool (239-257KB); 2.1.304 to 2.1.316 defer them (~28KB);
  ENABLE_TOOL_SEARCH=true in settings.json env or the process env makes
  2.1.200, 2.1.260 and 2.1.290 defer them too.
- TestClaudeToolSearchOn, TestT3CodeToolSearchOn (new); #4755 filed.
- go test -tags nogui ./internal/agent on mote; GOOS=linux and
  GOOS=windows go vet ./internal/agent; gofmt -l.
Broken by hand: writeSearch stashing nothing and writing nothing, and
T3's entry left out: both new tests red. The user-value check skipped:
TestClaudeToolSearchOn red on the user's "false".
Not tried: a real model loading a deferred router tool through
ToolSearch and calling it via magpie (gateway tests cover deferred
tools); Claude Code on Windows/Linux; T3 Code's real app.
2026-11-01 16:15:27 +08:00
yetone de74cb53f7 mcp router: each caller gets its own Magpie Browser session
The router keeps one backend per Library server for every agent, so all
agents behind it shared one `magpie mcp browser`, one browser session and
so one tab (packinggoodsllc_07668 on Discord: two agents through a remote
router fought over one tab).

- serveMCP gives a client that initializes an Mcp-Session-Id (nothing is
  kept or checked by it).
- hubSession names each tools/call's caller: _meta magpie/session from a
  router in front, else hub-<agent>-<Mcp-Session-Id>.
- The router passes it in _meta magpie/session to `magpie mcp browser` and
  to another magpie's router only (keepsSession); the bridge sends it as
  that call's X-Magpie-Browser-Session (callerSession). A call naming none
  goes as the bridge's own session, as before.

Run (mote-run): go test ./internal/browsermcp; ./internal/gateway -run
'MCP|Hub'; ./internal/library -run 'TestHubTellsMagpieBrowser|TestKeepsSession|TestHubGivesMagpieImage'. ok.
Broken by hand, each red: no meta from the library (library test), no
Mcp-Session-Id from serveMCP and ignoring _meta in hubSession (gateway test).
Not tried: a real remote router chain between two machines.
2026-11-01 16:10:16 +08:00
yetone 5dfbca6274 cli: magpie settings list|get|set|reset, through the window's own save (#4745)
Stage 1 of #4745 (StringKe): every setting POST /api/settings saves can
be read and set from the terminal.

- internal/settingsapi holds the save the handler made: Merge (the
  carry of keys a page leaves out, moved verbatim from api.go, plus
  upstream's RouterNote line), the vision/imageGen/searcher checks,
  settings.Save's own checks, catalog.Touched. POST /api/settings and
  `magpie settings` both call settingsapi.Apply, so a value is checked
  and saved one way. It sits outside internal/gui so the nogui build
  has it.
- `magpie settings` (list, the default, with value, default and
  choices; get; set; reset to settings.Defaults()), --json on list and
  get. Body sends the whole file with one key changed, so a key the
  save keeps when absent (noBird, refusalRetries, ...) is set even to
  off. A flag where a key or value goes, an unknown key (with near
  matches named) or a refused value writes nothing and exits 1;
  --help prints usage.
- Parity guards: TestKeysAreWhatTheSaveWrites (each Settings field sent
  changed on its own; what the save takes must equal Keys),
  TestSettingsCLISetsWhatTheWindowSaves (every key the page's prefsKeep
  and savePrefs send is a key), TestEveryRouteHasACommandOrIsNamed
  (each /api route has a command or a reason in notYet, which later
  stages shrink; 36 have one now).
- Item 3 of the stage (per-provider CLI-only fields in the window) is
  left for stage 2.
- The open app's in-process follow-ups (fonts, Dock, tray menu, alerts,
  language, update re-check) run only from the window's save: #4752.

Run (mote, at the pushed head 1c3591b5d + this):
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; GOOS=linux go build -tags nogui;
  GOOS=windows go build: clean (before rebase, the vets again after).
- go test internal/settingsapi, internal/settings, internal/cli: ok.
  internal/gui -run Settings|Prefs|Keep after the rebase: ok. The full
  internal/gui run before the rebase had three reds:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, fixed on main in
  b646a9127), TestColdTurnsTaken (fixed on main in 647323409) and
  TestMainWindowCorners/macOS_26_SDK (#3949, mote is macOS 27).
- Real run in a sandbox HOME on mote with a magpie built from this:
  settings --help / help, list, get, set theme dark, noBird on,
  redactWords "acme, globex", usageAlert 85; refused theme neon, `them`
  (names theme), usageAlert lots, trayUsageEvery 4, vision
  nobody/nothing, each exit 1 with settings.json unchanged; set
  usageAlert --help printed usage and wrote nothing. Then `magpie web`
  with MAGPIE_WEB_KEY: GET /api/settings read back each value the CLI
  set; POST /api/settings lang ja, then `settings get lang` said ja;
  reset theme gave system.

Broken by hand, each red, then put back: noBird dropped from Keys
(TestKeys, TestBodySetsOneKeyOnly, the CLI set test and the GUI parity
test red); Body dropping false values (TestBodySetsOneKeyOnly and the
CLI "noBird off" check red); a route taken out of notYet and another
renamed (TestEveryRouteHasACommandOrIsNamed red, 3 errors). On the old
code the new tests don't compile (no settingsapi, no command).

Not tried: a real run on Windows or Linux; the live app reacting to a
CLI write while open (#4752); the GUI node suite (no page file changed).
2026-11-01 15:57:43 +08:00
yetone 403323af7f claude: a switch waits for another magpie's runs in the account's directory (#4532)
StringKe's audit, item 2. claudeDirRun is an in-process RWMutex, so
`magpie accounts switch` from the CLI never waited for the app's /usage,
warm-up or keep-alive run in the saved account's directory: it handed
Claude Code the refresh token that run could still spend, and removed
the directory under it. And the gateway's hand-over let go only of idle
runs; a run in a turn when the switch came was kept for its next turn,
waiting up to idleLongest in the removed directory with the same token.

- inSavedClaudeDir also holds a lock file of its own beside the
  account's directory (markClaudeRun, <dir>.run-<pid>-<n>.lock,
  filelock), removed as it ends.
- switchSavedLogin waits on every such file (waitClaudeRuns) up to
  claudeRunWait (90s), then fails with errClaudeRunning and leaves the
  sign-in as it was. A file whose run ended without removing it is free
  and taken out.
- handedOver marks the account's runs in a turn (subscriptionRun.handed);
  keepIdle ends such a run instead of keeping it.

Shelved (parked) sessions hold no process or token; a later turn starts
a new run under the account the gateway picks then, so nothing changes
there.

Run (mote, nogui):
- new tests TestClaudeSwitchWaitsForAnotherMagpiesRun,
  TestClaudeSwitchRunHeldAndLeft, TestSavedClaudeRunHoldsItsLock,
  TestClaudeHandOverEndsTheAccountsBusyRuns, plus TestClaudeSwitch*,
  TestSavedClaude*, TestClaudeHandOver*: ok.
- Broken by hand (wait call, run mark and the handed check taken out,
  helpers kept): all four new tests red ("switched while another magpie
  ran Claude Code…", "got <nil>", "a left lock file kept", "run locks []",
  "a run of the handed-over account was kept for its next turn").
- go vet darwin/linux/windows for provider and gateway: ok.
- Windows (win-run): the three provider tests and
  TestSavedClaudeUsageKeepsRotatedSignIn: ok.

Not tried: two real magpie processes with a real Claude Code (the other
process is a second open of the lock file, which flock and LockFileEx
treat as another holder; filelock's own test covers a real second
process). Not covered, filed as #4750: a run queued behind the switch
makes the handed-over account's directory again, and a run in a turn
can still refresh during that turn.
2026-11-01 15:25:56 +08:00
yetone 01ccbd40a0 library: an MCP router says which computer it is, so an agent can pick between two (packinggoodsllc_07668 on Discord)
Two magpies, one in China and one in Los Angeles, each serve the same
tools through their MCP router (/mcp/magpie/hub). An agent connected to
both saw two identical web fetches and couldn't pick the one in Los
Angeles to reach Google.

Each router now says where it is:
- initialize's instructions end "This router: <name>. Each of its
  tools' descriptions starts with [<name>]; ...", and serverInfo.title
  is "Magpie MCP hub · <name>";
- each tool's description in tools/list starts "[<name>] " (once: a
  description that starts so already, another magpie's router behind
  this one, isn't given it twice).
<name> is the user's words (settings.RouterNote, one line, 80
characters at most) to every caller. With none it is this computer's
name, to callers on other computers only: an agent on this computer
has one router at hand, and its prompts stay as they were.

RouterNote is this computer's own (KeepOwn): library.json is synced,
settings.json isn't, so a sync never brings the other machine's name.
It is set in the Library's MCP tab, in a Router name row under the
router's address (shown while the router is on): a plain field with the
computer's name as placeholder, saved on Enter or leaving it, Escape
puts the saved words back, an input method's Enter is its own. POST
/api/settings keeps it. Translated in zh, zh-TW, ja, de.
docs/subsystems/mcp-router.md has the rule.

Run (mote, at a5a9cdf7b + this change): go vet ./... for darwin, linux
and windows ok; go test -tags nogui ./... -timeout 45m: every package
ok except internal/gui's TestSettingsSaveKeepsWhatItDoesNotSend on
BusyLoad, red on main since 8d8df0639 (#4739, fixed in the next
commit). After rebasing on 9feb1024c: internal/gui, settings, library
and gateway again, and node --test library-mcp-router-note (new),
library-mcp-hub, mcp-hub-direct and i18n-keys, chromium and webkit,
en/zh/zh-TW/ja/de, at 1100 and 420 wide.

Broken by hand: hubWhere returning "" turns TestHubMCPSaysWhere red;
dropping RouterNote from KeepOwn turns TestRouterNote red; dropping it
from POST /api/settings' carry list turns TestHubNoteSaved and
TestSettingsSaveKeepsWhatItDoesNotSend red. i18n-keys caught a test
comment saying "Router name", reworded.

Not tried: two real magpies on two computers with a real Claude Code
or Codex connected to both, and whether a model actually picks by the
prefix; the Linux and Windows apps' Library tab.
2026-11-01 15:23:15 +08:00
yetone 822f526a63 claude: /usage's "Sonnet only" week is the Sonnet week (#4532)
Claude Code 2.1.316 names it "Current week (Sonnet only)", and
claudeScopeModel made that the model word "sonnet-only", which no model
id holds: the Sonnet week used up stopped no Sonnet request in routing,
and it was a row apart from the "7 days · Sonnet" its seven_day_sonnet
header keeps (StringKe's audit, item 4, second half). A trailing " only"
is now dropped from the scope, so it reads "7 days · Sonnet", counts
sonnet, and the header replaces it in place; the GUI's existing
translation of the name applies too.

Not changed (item 4, first half): a model's own week still doesn't move
Claude Code's sign-in; usedPast counts windows that hold every model.
Moving the sign-in for one model's limit is a design question left on
#4532.

Run (mote, -tags nogui):
- TestClaudeUsageSonnetOnly: red on the old claude_usage_cli.go
  (Model sonnet-only, name "Sonnet only"), green now.
- go test ./internal/provider -run 'Claude|Allowance|Routing' ok.
- go vet darwin/linux/windows; gofmt clean.

Not tried: a real Sonnet-limited account.
2026-11-01 15:19:06 +08:00
yetone 7b6b7492a9 claude: an account on overages is read with its windows and switched off (#4532)
Claude Code's /usage line "You are currently using your overages to
power your Claude Code usage…" was in claudeUsageDenied, so the whole
reading became an error: the card lost its windows, and NextLogin, which
stays on an account it can't read, left Claude Code billing overages
while other accounts had room (StringKe's audit, item 3).

Now the line is no error. The windows under it are read as usual, and a
Text row "Extra usage" with Used 100 is added (claudeOveragesWindow), so
usedPast/roomLeft count the account spent and the switch moves off it.
The row ends when the last used-up window renews (the time Claude Code
says it switches back), else at the next reading. Routing skips Text
rows, so the gateway's own account choice is unchanged. The GUI says the
row "In use" in the reader's language (quotaText; a plugin's text row
keeps its display as it came). The overages case is out of
TestClaudeUsageFailureDoesNotHideAccountErrors: it was the bug.

Run (mote):
- TestClaudeUsageOverages, TestClaudeSwitchOffOverages: red on the old
  claude_usage_cli.go (an error; switched to ""), red with the row's Used
  set to 0 by hand, green now.
- go test -tags nogui ./internal/provider -run
  'Claude|Usage|NextLogin|Next|Switch' ok.
- GUI: claude-overages (new, 5 languages, chromium + webkit) red 8 of 10
  on the old app.js (en passes there), green now; with quota-text-row,
  quota-name-translated, i18n-keys, usage-no-reading: 40 pass.
- go vet darwin/linux/windows; gofmt clean.

Not tried: a real account on overages; the text is Claude Code
2.1.316's string table, and the windows under it are what StringKe
describes.
2026-11-01 15:16:00 +08:00
9097687a31 gui: Hide accounts leaves the user's own account names and plans in sight (#3656)
With Hide accounts (账号打码) on, the name a user gave an account
(#1515) was blurred like the account, so faketrader's several
Antigravity accounts couldn't be told apart; and an Antigravity
account whose value is "Google" blurred "Google" of its plan
"Google AI Pro" on Usage and on the Providers row. The name the user
gave an account is shown text, not an identity. The account is.

- provider: a card's Alias says whether it is the user's own name
  (SubscriptionQuota.Named, set by withAccountNames from
  AccountNameOf), since Alias is also a plugin's name for an account
  (PluginUserOf, a masked phone, #4416) or a seat's key plan, and the
  Usage page and tray panel may have no /api/providers to tell them
  apart. labelProvider is AccountLabelOf's "plugin:" lookup, shared.
- app.js names(): the user's own names (accountNames) and named
  aliases are no longer accounts to hide; accountUsers, an unnamed
  alias and a seat still are (noteAccounts keeps an alias without
  named).
- app.js mask(): labels are scoped by element, never by value
  (LESSONS: scope an exemption by where the value sits). In
  .own-name, .plan, .acct-plan (the Providers row's plan pill, new
  class), .model-value and .subscription-head > b only an address is
  hidden; a plan's and a model's tooltip too (TIPS). The own name's
  tooltip ("name · account") is masked in full.
- .own-name is set only where the text is the user's own: the
  editor's rename span when it has one (else it shows the raw
  account and stays hidden), Usage's quota-alias and the panel's
  pq-user when q.named.

From skygunner's patch (95c0511 on 19253f67), changed:
- Its .acct-who .rename exemption showed a raw non-email account
  (the rename span shows the account when it has no name of the
  user's). Now only an own-name span is exempt.
- Its [title]:not(LABELS) skipped those elements' tooltips
  altogether, so the address in "alias · user" (quota-alias, rename)
  went unmasked. Tooltips are masked; only a plan's or model's hides
  just an address.
- Dropping every alias from names() would have shown a plugin's name
  for an account (#4416 came after the patch's base). Named tells
  the user's own apart.
- The n.data.length < 2 skip the patch removed is kept.
- Its test is rewritten on the new fixtures: an unnamed plugin
  alias, an address in a plan, the editor with and without an own
  name, the panel, a model value, tooltips.

account-alias.test.cjs and account-eye.test.cjs said Hide accounts
hides the user's own name; they now say it stays in sight, the
accounts still hidden. account-alias brings the window's page to the
front before clicking #usageMask, and the panel's before waiting on
it: behind the panel's page it gets no
frames and the click waited for one, red 5 times in 2 runs at
fb3942ee6 (#2984's account-alias half), 0 in 100 after.

Not changed: the tray panel card's tooltip is one string of account
and plan, so a plan word that equals an account's value is still
hidden there (#4677). OpenCode Zen's "Signed in as <account>"
in the issue's screenshot is the raw account, hidden as before.

Core scripts: app.js's own comments in the masking module are cut, so
the core is 742 bytes under its budget at the pushed head (no raise).

What was run:
- At this on 4c815ac2a, on mote (then rebased onto 39bade71d, whose 8
  commits change only i18n.js and plugins/gateway/settings.js; the
  budget measured again, 742 under): gofmt -l; go vet
  of provider, gui, usageapi; go test -tags nogui ./internal/provider
  ./internal/usageapi ok; TestCoreScriptBudget ok; the 19 masking GUI
  files (account-*, mask-*, masking-records, privacy-*, provider-mask,
  provider-unmasked, routing-masking, window-mask, click-scroll,
  i18n-keys), both engines: 539/540. The red was account-alias's
  panel wait behind the window's page, fixed by the panel bringToFront
  above. account-alias + account-mask-alias-plan after it: 4 runs,
  159/160 (one red in "renamed in place", whose body this change doesn't
  touch, #4749). account-alias 6 more runs: 120/120 here, 117/120 on
  origin/main 90c02326b (#2984).
- account-mask-alias-plan: 20/20 on the fix (Chromium, WebKit; en, zh,
  zh-TW, ja, de; 1100 and 420), 20/20 red at fb3942ee6 (the alias is
  masked); red with the plan selectors taken out of LABELS by hand.
  account_plugin_user_test red with Named always false by hand.
- At 4eeba1ca6 (this on 90c02326b): go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./..., go build for darwin,
  linux (nogui) and windows: ok. go test -tags nogui ./... on the
  Linux box: every package ok except internal/agent (8 install tests
  red the same on origin/main there, #4033, #3548) and internal/gui
  (TestSettingsSaveKeepsWhatItDoesNotSend, red on main, #4514;
  TestColdTurnsTaken on mote once, #4510). The whole GUI suite on the
  Linux box, 6 wide: 16857 pass, 491 fail in 100 files, none of them
  the masking files but account-every-reset; being run against
  origin/main to sort.

Co-authored-by: skygunner <84759+skygunner@users.noreply.github.com>
Co-authored-by: vincent <vincent@users.noreply.github.com>
Co-authored-by: Fake Trader <9635792+faketrader@users.noreply.github.com>
2026-11-01 15:15:08 +08:00
yetone 39bade71d1 gateway: a plain <invoke> written into a reply's text is the call it is, on a relayed Messages reply too
packinggoodsllc_07668 on Discord (#general): Claude Code v2.1.316, magpie's
routing group "Hard to strong, easy to cheap", asked to open Google in
magpie's browser. The reply showed
  <invoke name="ToolSearch"><parameter name="query">select:…</parameter></invoke>
  *Result: Tool loaded.*
  <invoke name="mcp__magpie__magpie-browser__browser_navigate">…</invoke>
  *Result: Navigated to https://www.google.com — page title: "Google"*
  已用 magpie 的浏览器打开了谷歌 ...
as text. Nothing ran: the model wrote its calls and made up their results.
Asked, the reporter said the group holds only Claude models (v0.1.2545).

Cause: Claude wrote its own call form as text, and none of magpie's
readers of written calls knew that form on the routes Claude takes.
- The plain <invoke name=…><parameter name=…> shape (Claude's own calls,
  MiniMax's in <minimax:tool_call>, Claude's in <function_calls>) wasn't
  a mark: only <tool_call> and DeepSeek's DSML invoke were.
- A reply relayed as it came on the Messages API (a group member on a
  provider that speaks Messages itself: MiniMax, Kimi, GLM, DeepSeek, Claude
  relays) was never read for written calls at all; the subsystem doc said
  so. Claude Code's request to such a member takes that route.
- A Claude subscription member runs Claude Code itself (the bridge), whose
  textCalls held back only "[tool call …]" lines.
Not the cause: history isn't flattened (tool_use/tool_result translate to
native calls on every API), and this was the conversation's first turn.

Fix:
- textcalls.go: the invoke regexes take DSML's pipes, a namespace, or
  nothing; <invoke name=, <function_calls> and <minimax:tool_call> are
  marks; their leftover tags go. Text after a call read out, other than
  tags, ends the calls and goes with all after it: it is the model going
  on as if the call had run. This changes the old rule for every shape:
  prose after a Hermes call ("Done.") went on as text and now goes
  (TestTextWrittenCallCutEarlyNotCalled updated).
- textcalls_anthropic.go: anthropicTextCalls in passthrough, for a
  streamed Messages reply (holds the text block's start and stop with the
  held text, adds tool_use blocks after it or in its place, stop_reason
  tool_use) and a whole one.
- claude_text_calls.go: the bridge's textCalls also holds a line opening
  <invoke name= or <function_calls>, so the run is asked once to make the
  calls (textCallsAsk no longer names the "[tool call …]" form only).
- Responses and Gemini relays still aren't read: #4743.

Tests (textcalls_invoke_test.go), on the reporter's literal text: parse,
a relayed Chat stream, a Messages passthrough through a routing group
(streamed, with lead text, a lookalike left alone, and whole), and a
Chat upstream translated for a Messages client.
TestClaudeTextInvokeCallsAreMadeForReal: the bridge, bare and wrapped.

Run:
- On origin/main 586b59fe7 with only the new test file: all four
  TestInvokeReported* red. With the parser change but not the passthrough
  wiring: TestInvokeReportedAnthropicPassthrough red.
- mote-run at a6c37f936 (on origin/main 9feb1024c): gofmt -l clean, go vet ./internal/gateway for darwin, linux, windows ok, go test ./internal/gateway -timeout 45m -count=1 ok 716.8s.
- Rebased onto origin/main 5d63b3f99 (5 commits, two in internal/gateway: Codex
  loaded tools, HEIC images; no file of this change): gofmt clean, vet ok,
  and -run TestInvokeReported|TestTextWritten|TestTextCall|TestClaudeText|
  TestWritten|Passthrough ok. The full gateway suite was not rerun there.
Not tried: a real Claude Code against a real group member that writes
invokes (which provider serves the reporter's Claude models is unknown), and Responses/Gemini relays.
2026-11-01 15:08:24 +08:00
yetone 5d63b3f995 accounts: a Claude import never writes an older sign-in over a newer one (#4532)
Importing a claude-swap export of the account Claude Code was signed in
to wrote the file's sign-in over Claude Code's own (addLogin, using).
cswap exports what it saved when it last switched; Claude Code has
refreshed since, each refresh spending the refresh token before it, so
the file's was spent and Claude Code was signed out. A saved account was
replaced the same way. Only an identical refresh token was caught.

Now a Claude sign-in for an account magpie already has (Claude Code's
own, or a saved one that can still be used) with another refresh token
is taken only when the file's expiresAt is later than what magpie has,
the account's own config directory counted (claudeNewerKept). Otherwise
it is "exists" with why, nothing written. cswapEntry and loginEntry read
claudeAiOauth.expiresAt. The CLI prints the reason.

Run (mote, -tags nogui):
- TestImportCswapKeepsNewerSignIn: older-than-live, undated, newer-than-
  live, older-than-saved. Red with the check turned off by hand (three
  subtests: updated over live / saved), green with it.
- go test ./internal/provider -run 'TestImport|Login' ok.
- go vet ./internal/provider ./internal/cli on darwin, linux, windows;
  gofmt clean.

Not tried: a real cswap export against a real Claude Code sign-in. A
sign-in that was itself imported and never run is saved with expiresAt 1
(so Claude Code refreshes it first), so any dated file still replaces it.
2026-11-01 15:07:37 +08:00
yetone 0b7d5f3a20 claude: a switch waits for Claude Code's own refresh locks (#4532)
A switch read the sign-in it was replacing while Claude Code could be
refreshing it. Claude Code 2.1.316 refreshes under two mkdir locks,
<config dir>/.oauth_refresh.lock then <realpath(config dir)>.lock
(~/.claude.lock), both stale after 60s, and saves the rotated pair with a
compare-and-swap on the refresh token. So the outgoing account's token
was not written over the incoming one, but magpie kept the outgoing
account with the refresh token that refresh spent, and it was signed out
of magpie on its next use.

switchSavedLogin and addLogin (Claude) now take both locks the way
Claude Code takes them (claude_lock.go: mkdir, touch while held, take
over one untouched past the stale time, let go in reverse order) before
reading the live sign-in, and hold them until the new one is written.
putClaudeLogin's ~/.claude.json rewrite takes <real path>.lock (stale
10s), after the refresh locks, the order Claude Code saves in. A lock
held past 20s fails the switch with nothing written.

Read from Claude Code 2.1.316's bundled source: lgr/Cki/cl (refresh
locks, owner record, retries), Vno (CAS write), gi (config save lock).

Run (mote, -tags nogui):
- TestClaudeSwitchWaitsForClaudeCodesRefresh (refresh/legacy/config) and
  TestClaudeSwitchStaleAndHeldLocks: red on the old code (switched while
  each lock was held; no error when held), green now. Also green on
  Windows (win-run).
- Broken by hand: no stale takeover -> stale subtest red (20s, locked).
- go test ./internal/provider -run 'TestClaudeSwitch|TestClaudeAccount|Login'
- go vet ./internal/provider for darwin, linux, windows; gofmt clean.

Not tried: a real Claude Code refreshing while a real switch runs (its
refresh fires only near expiry). magpie writes no
.oauth_refresh.lock.owner, so Claude Code takes over a lock magpie left
only by its 60s stale time. The Library's MCP writes to ~/.claude.json
don't take the config lock yet: #4747.
2026-11-01 15:02:38 +08:00
yetone 66c0ddc19a gui: Busy models last takes a custom threshold, 1 to 9999 (axelburks)
axelburks on Discord: a vendor that queues reports loads past 100%, and
the only way to a threshold such as 150 was settings.json. Settings ›
Network and sharing › Busy models last now ends in Custom…, one more
choice in the same in-app switch (no <select>). It opens a small field
in the row whose sub says what the number means: a load in percent as
the plugin reports it, 100 is all the vendor serves at once, past 100
requests queue (200 is twice that), 1 to 9999. Enter or Apply saves it
through settings/busy-load, Escape or Cancel closes it untouched. A
value that is not a whole number from 1 to 9999 is said in red in the
sub and nothing is posted; the field keeps it to correct. The number
saved shows as its own choice ("Over 150%"), and Custom… opens with it
filled in. The site docs (en, zh, ja) and gateway-routing.md say
Custom… instead of settings.json. Code in plugins/gateway/settings.js
and i18n.js only, so the core budget is untouched.

Run on mote at this tree:
- node --test model-load, i18n-keys, bare-ids, gateway-port: all pass.
  model-load's new test runs in Chromium and WebKit, at 420 and 900, in
  en, zh, zh-TW, ja and de: Custom… focuses the field, says what the
  number means, refuses abc, 0, 10000, 1.5 and -3 with nothing posted,
  Escape closes, 150 posts {at:150} and shows Over 150% picked, 2000 by
  Enter replaces it, the row and settings don't run sideways, and no
  press moves the page more than the row changed height.
- go test ./internal/gui -run Budget: ok. gofmt -l: clean.

Broken by hand: validation turned off (if (false)) went red in every
language; the Custom… entry taken out went red in the old and new
tests; the field without flex:none was squeezed to ~20px and the width
check went red.

Not tried: the real app window (only Playwright's engines), and the
full GUI and Go suites, which run after the push (one suite on mote at
a time).
2026-11-01 15:01:24 +08:00
yetone c688211d13 gateway: a ChatGPT (Codex) account gets loaded tools where they were loaded, keeping its cache (#4738)
infinitex233 (#4738, Discord): Claude Code -> magpie -> a Codex account,
and every ToolSearch load dropped cache_read to 0. loadsInPlace sent the
additional_tools item (#2660) only to OpenAI's own API, so for an
account the loaded tool went into the top-level tools and the cached
prefix broke at the tools.

Tried on the real ChatGPT backend first (owner's account, sandbox HOME
on mote with a copied auth.json whose refresh_token was replaced, so the
live token was never rotated; ~/.codex untouched). A probe client sent
Claude Code's shape: ToolSearch with two deferred mcp tools, then the
tool_reference result, then the calls, 4 requests per run.
- additional_tools item (on, and this commit's default): request 2..4
  read 7680-8320 tokens from cache on gpt-5.6-terra, gpt-6-luna and
  gpt-6-sol; the model called read_a and read_b from the item; no
  "turned away additional_tools" in the log.
- tools top-level (off): request 2 and 3 read 0 from cache (8044 and
  8163 tokens in), as the reporter saw.
So the backend takes it, and this makes it the default for a ChatGPT
account (p.Account.Agent == "codex"). Copilot and other sign-ins stay
off: not tried.

- loadsInPlace: AdditionalToolsOff wins, then AdditionalTools, then an
  account is in only if it's Codex's, then OpenAI's API as before.
- `magpie provider set <id> additional-tools=on|off|default`: off is new
  (AdditionalToolsOff, kept through an account's Save by accountSettings
  and through the GUI editor's save like AdditionalTools). The old
  "off"/"no" meant default; now they turn it off where the default is on.
- The 400/422 fallback that names the item still applies, so a backend
  that stops taking it costs one retry and then sends tools top-level.
- No prompt, instructions or identity line changed.

Run (mote, at base 586b59fe7, this commit and the previous together):
- go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/cli ./internal/gui: provider ok 248s, gateway ok 830s,
  cli ok 105s; gui FAIL on two filed reds that this doesn't touch:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, #4739) and
  TestMainWindowCorners/macOS_26_SDK on macOS 27 (#3949).
- Rebased on origin/main 9feb1024c, then again at this head: gofmt
  clean, vet darwin/linux/windows ok, provider ok 179s, cli ok 88s,
  gateway -run 'LoadsInPlace|LoadedTools|Codex|AdditionalTools|InPlace|
  Account' ok 99s, gui -run 'Provider|Settings|Account' red only on
  #4739. The whole gateway and gui packages ran at the base only.
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows ok.
- New TestCodexAccountLoadsInPlace (a fake ChatGPT backend through the
  gateway: the item with read_a, then tools top-level after
  additionalToolsOff in providers.json); TestLoadsInPlaceScope extended
  (Codex on, Codex off, OpenAI off, Copilot off by default and on when
  set); CLI test for off, on after off, default.
- Broken by hand: with the Codex default taken out of loadsInPlace,
  TestCodexAccountLoadsInPlace and TestLoadsInPlaceScope go red.
- GUI node suite not run: no JS changed; the Go editor save only keeps
  one more field, covered by the Go tests above.

Not tried: the reporter's own setup (Windows, gpt-6.1-terra), a real
Claude Code client (the probe sent its request shape), Copilot or any
other signed-in vendor with the item.
2026-11-01 14:59:44 +08:00
yetone 8042d1bf3b provider: a signed-in account's settings go through one list, so Save keeps what withPicks reads (#4738)
infinitex233 (#4738, Discord): `magpie provider set codex
additional-tools=on` said "saved" and changed nothing. Save rebuilt a
signed-in account's entry from one field list and withPicks read it back
from another; AdditionalTools was on neither.

The two lists had drifted in both directions, so the same class hit
other settings on every subscription account (Codex, Copilot, ...):
- written, never read back: QuotaRest, QuotaResetAt, RestCap. The gateway
  never saw them on an account, and the next Save of anything cleared
  them, since Save starts from Find.
- read back, never written: ExtraBody and ReplyHeaders. A Codex
  account's extraBody (magpie-releases#18), written by hand, was wiped
  by the next editor Save.
- on neither: AdditionalTools, LimitRestOff, Patience.

Fix: accountSettings is the one list. withPicks is it, and Save's account
branch builds {ID, Key, Hidden, Quiet, Tucked} and runs it, so a field
added to one is in both.

Run:
- New TestAccountSettingsKept (codex and copilot accounts): sets
  AdditionalTools, ExtraBody, ReplyHeaders, QuotaRest, RestCap,
  LimitRestOff and Patience, Save, Find, then clears them. Red on the
  old provider.go (every field lost on both accounts), green now.
  TestAccountPriceRateKept still green.
- Real CLI path in a sandbox HOME on mote: `magpie provider set codex
  additional-tools=on` wrote "additionalTools": true to providers.json
  and the running gateway used it (see the next commit for the backend).
- Suite record for this and the next commit together is in the next
  commit's body.
2026-11-01 14:50:45 +08:00
yetone 4c815ac2a5 search: searchers picked to follow the one named, tried in their order when it fails (axelburks on Discord)
axelburks asked for more than one searcher, so that when one fails
another provider searches. A searcher named in Settings gave way to no
other provider before, only to the Search APIs. Automatic already fell
back to up to three.

- settings: SearcherThen, the searchers after the one named. Entries
  are trimmed. Blanks, "off", the named one and repeats are dropped.
- gateway: when the named searcher fails (the context still live),
  modelSearch asks each of SearcherThen in order and skips one that
  can't search now or is the same model. The first that searches
  answers, and the call is marked searchingInstead, so the Routing row
  says why the named one didn't search. If all of them fail, their
  errors go back together, saying "the searchers picked ..., in their
  order", and webSearch goes on to the Search APIs as before.
  SearchFailure.Instead names the one that searched in its place.
- gui api: searchFailed.instead. A save takes only searchers that
  Searchers() offers. A save without searcherThen keeps the list, since
  the page's prefsKeep doesn't send it, and [] clears it.
- Settings › Web search (plugins/search/settings.js, outside app.js's
  budget): an "If it fails" row under a named searcher, with numbered
  chips and Add. A chip's picker changes the chip or removes it. The
  row is hidden for Automatic and Off. The failure line names who
  searched instead, or says the ones after it failed too. The help
  text says the same in en, zh, zh-TW, ja and de.
- docs: gateway-routing's failing searcher, and gui-shell.

Tests:
- TestPickedSearchersInTheirOrder (gateway): one test where the named
  searcher answers without searching and one where it fails. A gone
  entry and one that can't search are skipped, and the third searches
  once. With no working entry, the error says so and Instead is empty.
- TestSearcherThenSaved (settings) and TestSearcherThenFromSettings
  (gui): what is saved, kept and cleared; refusing an entry that can't
  search. settings_keep_test sets SearcherThen.
- searcher-then.test.cjs: chromium and webkit, en, zh, zh-TW, ja, de,
  at 560 and 1000 wide. Checks the row's place and words, what Add
  offers, the posted lists, that the chips fit with no horizontal
  scroll, that no click moves the page, and both failure lines.
Broken by hand: running no fallback turned TestPickedSearchersInTheirOrder
red (both subtests: "ds2 searched []"). Not keeping the list on save
turned TestSearcherThenFromSettings and the keep test red.

Run on mote (mote-run):
- At the pre-rebase tree (base 21882a68d): go test of settings, and
  -run 'Searcher|Search' of gateway and gui: ok.
- searcher-then, searcher-pick and i18n-keys in both engines: 46 of 46.
- gofmt clean. go vet: darwin gateway, gui, settings; windows the same;
  linux gateway and settings on mote, gui with -tags gtk3 on the Linux
  box (wsl-run): ok.
- Rebased onto origin/main 1e6a27d4f, this tree: -run
  'Search|Searcher|CoreScriptBudget|SettingsSave' of gateway, gui and
  settings: gateway and settings ok; gui ok but for
  TestSettingsSaveKeepsWhatItDoesNotSend on BusyLoad, red on main
  since 8d8df0639 (#4739, not this change; SearcherThen passes its
  check). The three GUI files above: 46 of 46.
  Pushed on origin/main e62a1bc51. Its 6 commits since touch routing,
  sessions and rex files only, none of these, and weren't run here.
Not run before the tag: the whole GUI suite and the full go test of
gateway, gui and settings. They are queued behind other sessions'
suites on mote and run after the push; any red they find gets its own
commit.
Not tried: a real relay or a real searcher failing in the GUI app.
2026-11-01 14:43:18 +08:00
yetone 0b4aa96fd0 gateway: a relay whose models are typed in by hand is offered as a searcher (axelburks on Discord)
axelburks added a custom provider on OpenAI's Responses API and ticked
"Searches the web by itself", but Settings › Web search's searcher
picker didn't offer it. Searchers() and namedSearcher took a
provider's models from Available() alone. A relay with no /models
list has its models typed in by hand (Exposed) and none available, so
it was left out of the picker, while the same row named it among the
relays to pick there. searcherModels gives what the provider lists,
then the hand-typed ones it doesn't. A relay that lists its models was
offered before this already.

Tests:
- TestSearcherRelayWithoutModelList (gateway): a Responses relay with
  no /models and a typed model is a searcher and is resolved by name.
- TestSearcherPickerOffersResponsesRelay (gui): the relay saved the way
  the editor saves it is in SearchChoices with its model.
Both were red on the old code.

Run (mote-run), at this commit alone: go vet of gateway and gui, and
go test -run 'Searcher' of gateway and gui: ok. The full checks ran
with the next commit; its body has them.
Not tried: the reporter's own relay (we don't know whether it lists
its models; the reply asks).
2026-11-01 14:43:07 +08:00
yetone 994cd4fb68 gui: Rex switches to the tab magpie opens, through the app's session.select (#4565, StringKe)
StringKe tried v0.1.2446 on the real Rex app (Rex Beta 0.1.0 (1696)):
the tab opens, but the app keeps showing the tab the user was on. The
new tab shows only in the sidebar, and `open -b` only brings the window
forward. The app's own session.select action, sent to the app client,
does switch to it.

After `rex run` (reused magpie session) or `rex new` (now with --json,
for session_id and initial_windows[0].window_id), openInRex brings Rex
forward and then calls rexSelect. rexSelect reads `rex client list
--json`, takes the client of info.kind "app" whose session_ids hold the
session, else the last app connected, and skips one whose
connection_state is "lost". Then it runs `rex -C <client_id> do
session.select session_id=<id> window_id=<window>`. App actions need
Remote Control on in Rex's settings. With no app, a failed list, a
refused do or no answer within 3s (rexSelectWait), the open still
succeeds, the same way a failed rename is ignored. docs/reference.md's
Rex paragraph says this.

Command shapes come from the real rex CLI, snapshot 0.0.1793420730-
g6d0d9a, on mote with a sandbox HOME and XDG_RUNTIME_DIR: `rex --help`
(-C is a global flag, label or ID), `rex do --help`, `rex client ls
--help`, `rex api describe client.list` (client_id, info.kind
app|cli|agent|other, connection_state connected|lost, session_ids),
`rex new --json` output. With no app connected, `do` without -C exits 3
("no app client is connected"), and -C <unknown> exits 3. A client that
doesn't answer keeps `do` waiting 10s ("did not answer within 10s").
That is why the select runs after open -b and has its own 3s bound.

Tests: TestOpenInRexSelectsTheTab runs a fake rex program (a sh script,
so arguments go through a real exec), with a new session and with
magpie's session reused. It checks that the app attached to the session
is picked over another, that a lost app is never asked, and that no
app, a failing client list, a refused do (exit 1) or a do that never
answers (exec sleep 30, killed at the bound) leave the open a success
within its time. The in-process fakeRex answers client list (no app)
and new --json. TestOpenInRexReal runs these paths against the real rex
server, with no app client.

Ran, through mote-run, on this tree before the rebase onto 1e6a27d4f:
- gofmt -l; go vet ./internal/gui; GOOS=linux -tags nogui and
  GOOS=windows go vet ./internal/gui; GOOS=linux -tags nogui and
  GOOS=windows go build .: ok.
- MAGPIE_TEST_REX=<real rex> go test -count=1 -timeout 45m
  ./internal/gui: everything passed, TestOpenInRexReal included, except
  TestSettingsSaveKeepsWhatItDoesNotSend (#4739, #4514) and
  TestMainWindowCorners/macOS_26_SDK (#3949). Both fail the same way
  alone on a detached origin/main 1e6a27d4f.
- At the rebased head on 1e6a27d4f: gofmt, go vet ./internal/gui and
  MAGPIE_TEST_REX=<real rex> go test -run
  "Rex|DiscoverTerminals|TerminalOpenArgs|AgentOpen" ./internal/gui: ok.
- No sleep, rex server or /tmp/rx* left on mote afterwards.

Broken by hand, each red, then restored: the old openInRex (4 of 7
cases red: "asked [], want [-C client:… do session.select …]"); the
attached-app preference dropped (the other app asked); the lost-state
skip dropped (the lost client asked); the 3s bound made an hour (the
never-answering case took 20.0s).

Not tried: the Rex app itself (its download needs a Discord sign-in),
so a real app client's session.select and what a refusal with Remote
Control off looks like are known only from StringKe's report and the
docs; the handling doesn't depend on which. Not the full go test ./...
(only internal/gui changed). No GUI Playwright run (no JS changed). Not
run on Linux or Windows (the tests skip on Windows).
2026-11-01 14:39:13 +08:00
yetone a5a9cdf7be gateway: a refused big conversation isn't told again to the Claude subscription's other accounts (Aisiverto on X)
Aisiverto on X: a refused turn of a ~900K-token conversation made magpie
switch accounts and send it again, "one user action becomes several
expensive requests". In the usage, pairs ~100ms apart: one read the whole
conversation from the cache, the other read ~26K and wrote ~877K.

The cause: a refusal goes to the next candidate under RefusalRetries
(unset: every one left), and matesFirst puts the same model's other
accounts first (#248, where a verified account may answer). For a Claude
subscription each other account is a new Claude Code told the whole
conversation, all of it written to that account's cache again, for a
refusal about the content that it most likely gives too.

Now, before a Claude subscription account's try, a conversation of
retellMost (100K) tokens or more by estimate (tooBigToRetell) leaves the
subscription's other accounts out if that account refuses
(otherThanClaudeAccounts). Other members are still asked; with none left
the refusal is the agent's, and it isn't handed over mid-stream to
nobody (handsOver is given last). A smaller conversation goes to the next
account as before. The size is measured only when another Claude
subscription account is left. gateway-routing.md says so beside
RefusalRetries.

Run:
- TestClaudeSubscriptionBigRefusalNotToldAgain (new; streamed and not):
  red on the old code (runs "own,tok-spare"), green with the fix, the
  agent getting the refusal. TestClaudeSubscriptionRefusalMovesToNextAccount
  (small conversation, spare still asked), TestRefusalRetries* and
  TestPolicyRefusal* green.
- Broken by hand: tooBigToRetell always false, red.
- On mote: gofmt -l clean; go vet, GOOS=linux go vet -tags nogui and
  GOOS=windows go vet of internal/gateway ok; go test -tags nogui
  -timeout 45m ./internal/gateway: ok (702s). The whole suite ran at the
  parent commit (its body); this commit touches internal/gateway only.

Not tried:
- The handsOver change: the test's refusal comes with no reasoning
  before it, so nothing is handed over, and taking the change out stays
  green. Not covered by a test.
- A large conversation where another member of the group is a Claude
  subscription of a different provider id: it is left out too, as every
  Claude subscription account is.
- A real Claude refusal on a real account.
2026-11-01 14:28:40 +08:00