Commit Graph
997 Commits
Author SHA1 Message Date
yetone 75e78a5a04 tui: quitting hands the gateway to magpie's service on Linux
zaidu259434 on X: "启动codex这些cli连接会失败,AI分析没自动启动magpie的网关".
With magpie installed inside WSL (or on a server over SSH), nothing
opens magpie at login, and XDG autostart doesn't run there. So once
`magpie tui` quit, the agents it had connected asked a gateway that was
gone.

When the terminal quits having served the gateway with an agent
connected, on Linux and where magpie doesn't open at login, keepGateway:
- starts magpie's service (magpie daemon) when it is installed;
- installs it when the user never removed it (daemon.Removed: Uninstall
  now leaves a daemon-removed mark, and Install clears it), so it starts
  with the system or the login from then on, and says how to remove it;
- otherwise (no systemd, which is WSL's default, or the user removed it)
  starts `magpie serve` in its own session, logging to magpie's cache,
  and says so. In WSL it also says how to turn systemd on.
macOS, Windows, nothing connected, or magpie opening at login: the same
"gateway stopped" note as before. Docs: gui-shell.

Run:
- TestKeepGatewayAsTheTerminalQuits covers each of those cases, and
  TestUninstallRecordsTheUsersNo checks the mark.
- go test -timeout 45m on the four packages, the same run as the
  previous commit's: all four ok (gateway 428s, agent 255s, tui 23s, daemon 16s), at 6874095b1 plus this change, before the rebase
- GOOS=linux and GOOS=windows go vet, and gofmt -l, are clean.
- Real run in the magpie-desktop distro (WSL2, systemd on): a Linux build
  from this tree started under setsid as serveInBackground does,
  answered 200, and still answered 200 with its pid alive 30s after its
  wsl.exe session ended. It was stopped afterwards.

Not tried:
- the interactive TUI quit itself in WSL (over ssh there is no terminal
  to drive it), so the message and the path it picks are covered by the
  unit test only;
- a real daemon.Install inside WSL (it writes a systemd user unit for the
  distro's user).
2026-10-25 12:42:20 +08:00
yetone a1c1b7053b gateway: WSL under NAT reaches the Windows gateway with sharing off
zaidu259434 on X (tweet 2114203077989527990): on Win11, Codex and the
other CLIs in WSL failed to connect to magpie. A distro in NAT
networking (WSL's default) reaches Windows at the address Windows has
on the WSL network (vEthernet (WSL), 172.17.32.1 on the test box), and
magpie wrote that address into the distro's agents. But the gateway
listened on 127.0.0.1 alone unless LAN sharing was on, so every request
from WSL timed out. Turning sharing on wasn't enough either: the WSL
adapter is in Windows' Public profile, and a Private-only allow rule
still keeps WSL out (reproduced on the box).

- gateway: while it listens on loopback alone, on Windows it also
  serves at each address on a vEthernet (WSL...) adapter (serveWSL,
  looked for again every 10s, since the VM brings its adapter up and
  down). A request there counts as this computer's only when it comes
  from that network to that address with the WSL key (fromWSL). The key
  is `wsl-` plus 48 hex in magpie's folder (wsl-key, 0600), with
  `-<agent>` after it optional. The request is then served as a
  loopback one with the token (asFromLoopback). Anything else there is
  judged as another machine's, so a Docker Desktop container on the
  same network gets 403.
- agent: WSL twins at that address get the WSL key (keyAt, agentKeyAt,
  ourKey and gatewayKey know it). Whether it answers is asked from
  inside the running distro (reachFrom, wslReach: curl, wget or bash's
  /dev/tcp), never from Windows, where the listener answers whatever the
  firewall keeps out. A distro that can't connect is shown the firewall
  rule that lets it in (Profile Any, vEthernet (WSL*), magpie.exe).
- The NAT notices no longer say it answers only while sharing is on (en,
  zh, zh-TW, ja, de).
- Docs: gateway-routing (WSL under NAT) and agent-wiring.

Run:
- TestWSLCallerServedWithSharingOff and TestServeWSLListensBesideLoopback
  (gateway), and TestWSLAgentsGetTheWSLKey and
  TestWSLReachAskedInsideTheDistro (agent). All four were red with the
  fix taken out: "403 magpie isn't shared on the local network",
  "answers = false", the token given at the WSL address, and no drift.
- go test -timeout 45m ./internal/gateway ./internal/agent ./internal/tui
  ./internal/daemon: all four ok (gateway 428s, agent 255s, tui 23s, daemon 16s), at 6874095b1 plus this change, before the rebase
- GUI, NODE_PATH playwright 1.62.0, both engines: i18n-keys,
  agent-notice-lang, agent-unreachable, wsl-agents-setting, gui-zh-tw,
  gui-ja and gui-de, 105 of 105 ok.
- gofmt -l is clean, and GOOS=linux and GOOS=windows go vet are clean on
  the four packages.
- Real run on the Windows 11 box: a magpie.exe from this tree ran
  `serve` in a sandbox HOME, with MAGPIE_ADDR=127.0.0.1:3446 and sharing
  off. It listened on 127.0.0.1:3446 and 172.17.32.1:3446. From the
  magpie-desktop distro (NAT):
  - With no firewall rule, a request timed out (000 at 5s), and the
    probe script said "no".
  - After adding the rule this change advises:
    - the probe said "ok";
    - the WSL key got 200 in 0.09s, and so did key-codex;
    - no key got 403 "magpie isn't shared on the local network";
    - Bearer magpie got 403.
  The rule and the process were removed afterwards.

Not tried:
- a real Codex turn from WSL through this (the sandbox had no provider);
- `wsl --shutdown` re-addressing the adapter (it isn't my box to shut
  down; the 10s re-listen is covered by the unit test only);
- mirrored networking, which is unchanged.

Not changed: the Windows firewall prompt. magpie listens there itself,
so Windows asks once, and Public has to be ticked; the unreachable
notice gives the command for when it wasn't.
2026-10-25 12:42:20 +08:00
yetone 15f0d4cdeb sessions: a Claude Code session goes on in Codex, and a Codex one in Claude Code
0xPlato on X asked for conversations to carry across agents, at least on
one machine. A session row's Continue in (换 Agent 继续) now offers Codex
for a Claude Code session and Claude Code for a Codex one, when the other
is installed. Picking it converts the session then: a new session in the
target's own store, which its own resume opens. Listing converts nothing.

- Claude Code to Codex: a rollout in CODEX_HOME/sessions/YYYY/MM/DD with
  session_meta (model_provider from config.toml now, no
  base_instructions, so Codex uses its own), response_items and the
  event_msg user/agent messages the TUI shows. Codex indexes it on
  resume itself.
- Codex to Claude Code: CLAUDE_CONFIG_DIR/projects/<cwd>/<uuid>.jsonl,
  lines chained by parentUuid, assistant model "<synthetic>" so usage
  counts no call for them.
- Carried: user and agent text, pasted images, shell calls natively
  (Bash and exec_command) with their output, other tools as the agent's
  text (name, input, result in fences, cut at 64 KiB). Dropped: thinking,
  reasoning, signatures, encrypted content, Claude Code's own and Codex's
  context messages. After a compaction only what replaced the history.
- The source is only read. The new file goes through temp, sync, rename
  and never over an existing path. Asking again for an unchanged file
  gives the same session (memo by path, target, size, mtime).
- POST /api/sessions/carry {agent, id, to, open}: copies the resume line,
  or with open (Mac app) opens it in the session terminal. The details
  pane's Continue in line converts from its copy button too.
- Read-only and WSL sessions get no offer. Pi, omp, OpenCode, Kimi,
  Cursor and the rest are not converted.

Run (worktree at 42976f9a0, rebased onto origin/main before push):
- Real use in a sandbox HOME (HOME, CLAUDE_CONFIG_DIR, CODEX_HOME under
  magpie-wt/carry-sb), real binaries Claude Code 2.1.310 and Codex
  0.162.1, through magpie's gateway:
  - Claude to Codex: a Claude session that ran Bash, Write, Read and Edit
    was converted. `codex exec resume <id>` answered what the dog was
    called, which command ran and what was added. `codex resume` showed
    the whole history in the TUI.
  - Codex to Claude: a Codex session with exec_command and apply_patch was
    converted. `claude -p --resume <id>` answered the colour, the commands
    and the function added. `claude --resume` showed the history in the
    TUI.
- Fixtures in internal/sessions/testdata/carry are those real sandbox
  files. Claude's attachment text (system prompt, instruction files) and
  api-request lines were taken out; the line chain is kept.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  sessions ok (15.7s), gui ok (119s), size budgets among them.
- Broken by hand, each red: Codex context kept (environment_context
  carried), no convert offer (all four TestCarry* red), images dropped
  (TestCarryImagesAndCompaction red). sessions-convert.test.cjs is red
  in chromium on the old client.js.
- GUI (playwright 1.62.0, chromium and webkit): sessions-convert in en,
  zh, zh-TW, ja and de, every sessions-*.test.cjs, i18n-keys,
  click-scroll, gateway-conversations: 424 of 424 pass.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build.

Not tried: Windows and WSL with real binaries (WSL sessions get no
offer), images through the real binaries (round trip in tests only),
Open in session terminal on a real Terminal (the POST is tested, the
terminal path is the existing openTerminal), a Codex session compacted
by OpenAI (encrypted, not carried), and the full ./... suite.
2026-10-25 12:25:06 +08:00
yetoneandEdward4226 46c4188327 gateway: Codex's access_programs goes to OpenAI alone, so OpenCode Go's DeepSeek and GLM answer (#3172)
csic21, HONGs23 and TimWongUp (#3172): a Codex subagent inherits
access_programs {"cyber":"standard"}, magpie relayed it to OpenCode Go,
and Go answered DeepSeek and GLM with 503 "Upstream request failed:
Endpoint is unavailable."; without the field, or with null, 200. Go's
Haiku took it.

Scope: Codex itself sends the field only with a ChatGPT sign-in, or an
API key on its provider named "openai" (codex-rs core/src/
cyber_access_program.rs, for_auth and for_provider; read at openai/codex
970111f6c). It comes to magpie because Codex thinks magpie is OpenAI,
the same reason forVendor takes OpenAI-only parts out (#292). So the
class is "only the upstreams Codex would send it to", not an OpenCode Go
rule: no other vendor has a Cyber program to read, and Go is the one
seen to refuse it. keepsAccessPrograms keeps it for a ChatGPT (Codex)
account, a host ending in openai.com, another magpie (IsRemoteMagpie,
whose own upstream decides) and a codexAsSent relay when Codex sent the
request. Every other Responses upstream, relayed or built (from Chat
too), plugins included, goes without it. A relay that fronts ChatGPT
loses it unless set codex=as-sent, as Codex with a custom provider
would send it none.

- forwardOnce takes it out before the user's extraBody is merged, so an
  access_programs the user wrote there still goes (Edward4226's branch
  did it after, which would override the user's own value).
- withoutTopMember (from Edward4226's branch, using longBody's spans on
  a long body) removes the member, every one of that name, the rest byte
  for byte; a body that isn't a valid object goes as it came. A
  bytes.Contains check first, so a body without it costs nothing.
- Chat and Messages builds never carried it (now tested).
- Docs: gateway-routing.md, providers-accounts.md, ir.go comment.

Run:
- TestAccessProgramsGoToOpenAIAlone (new; fakes by the gateway client's
  RoundTrip, no network): Go DeepSeek/GLM from Codex and from curl, null,
  Chat built as Responses, Zen, a relay, codexAsSent with and without
  Codex's headers, the user's extraBody, OpenAI (daybreak_blue, null,
  from Chat), another magpie, a Chat and a Messages upstream.
  TestWithoutTopMember (new). TestCodexAccessProgramsReachBackend,
  TestAccessProgramsNullKept, TestCodexAccountTakesExtraBody pass.
- Broken by hand, each red: no strip (9 cases: Go, Zen, relay, extraBody);
  IsRemoteMagpie out; openai.com out (3 OpenAI cases); codexAsSent out;
  codexAsSent without fromCodex; Codex account out
  (TestCodexAccessProgramsReachBackend red); strip moved after extraBody
  (the user's value lost).
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows.
- HOME=<scratch> go test -tags nogui -timeout 45m ./internal/gateway/:
  ok (414s), at 42976f9a0 plus this change.

Not tried: a real OpenCode Go account on this head (the reporters' and
Edward4226's real A/B runs show the field alone turns 503 into 200);
OpenCode Zen's DeepSeek with the field (now sent without it either way);
a real Codex collab_spawn end to end.

Co-authored-by: Edward4226 <Edward4226@users.noreply.github.com>
2026-10-25 11:55:16 +08:00
yetone a2ff7e6cab plugin: add takes a community plugin's name (WorkBuddy, think-tags, qoder-cn)
Atlas on Discord (#help, 10-25, Linux): `magpie plugin add WorkBuddy`
said "isn't an npm package name". Worse, a bare `workbuddy` passed the
npm-name check and installed npm's unscoped workbuddy@latest, not
@magpie-community/opencode-workbuddy-auth.

plugin.Add, which the CLI, the Plugins page's field (/api/plugins/add)
and the movers all go through, now resolves a bare name first
(internal/plugin/resolve.go). Case aside, a name one community listing
goes by is its package, at the version given: the package or its bare
name, the short name (workbuddy, think-tags), the shown name (WorkBuddy,
Command Code), a provider id it serves or the subscription it replaces,
and a retired subscription's id through its mover (qoder-cn; provider
sets plugin.SubscriptionPlugin = MovePackage). The CLI says which
package it picked. A name two listings go by, or none that isn't an npm
name, is refused with the community plugins listed. A name no listing
goes by is npm's own package (opencode-gemini-auth keeps working), but
only when the list was fetched within the six hours: when the fetch
fails, the copy kept or built in may not name a newer plugin, so the
name is refused with why, and npm:<name> installs npm's package as
written. market() now says whether its list is a fresh fetch (marketErr).
Scoped names, paths and git specs are unchanged. A backup's or a sync's
plugins go in by their own spec (plugin.AddExact via addPluginExact),
never resolved, so a restore isn't held by GitHub being unreachable.
Update, Upgrade and InstallMissing use add with stored specs, unchanged.

Tests (fake registry over httptest, fake bun; no network):
TestResolveCommunityNames, TestResolveRefusesWhatItCantName,
TestResolveListUnread, TestAddByCommunityName. TestUpdateAllUpdatesAPinnedPlugin
adds an unscoped third-party name, so it now serves a registry.

Broken by hand: Add without resolve -> TestAddByCommunityName red with
the reporter's own error ("WorkBuddy" isn't an npm package name) and
workbuddy -> workbuddy@latest. The unread-list rule turned off (valid
name goes to npm regardless) -> TestResolveListUnread red.

Real use, sandbox HOME, built binary, real npm and GitHub:
`plugin add WorkBuddy` -> installed @magpie-community/opencode-workbuddy-auth@latest,
listed workbuddy and workbuddy-ai; `think-tags` -> middleware-think-tags;
`opencode-gemini-auth` -> npm's, google-plugin listed; `qoder-cn` with
MAGPIE_PLUGIN_MARKET=off -> opencode-qoder-auth; "Work Buddy Pro" ->
refused with the 38 community plugins listed; `twinz` with the list off
or at a dead URL -> refused, saying why and npm:twinz.

Run at this head (rebased on origin/main 42976f9a0): gofmt -l clean;
go vet (darwin) and GOOS=linux / GOOS=windows -tags nogui vet of
plugin, provider, cli, backup, gui clean; go test -timeout 45m
./internal/plugin ok (120s, after the pinned-update fix),
./internal/provider ./internal/cli ./internal/backup ./internal/gui ok.

Not tried: the full ./... suite; Windows and Linux runs of the tests.
No GUI JS changed: the Plugins page's field goes through the same Add,
and its status still says "<typed name> is installed" rather than the
package picked; the installed list shows the package.
2026-10-25 11:52:02 +08:00
yetone 42976f9a08 usage: a renamed provider is shown once, by the id it has now
cybercaius on Discord (#help, 10-25): "已经更改供应商 id 的也没有变更过来反而
分开显示了". Reproduced in a sandbox HOME (magpie web on 3582, fake upstream
on 3583): after renaming myrelay to newrelay in the editor, the Requests
page's provider list had both myrelay and newrelay, each named "myrelay",
because the model-list probe row was still under myrelay. The summary was
already folded; the probe chunk, the Sessions tab's vias and the gateway's
loggedAnswers (lead-first routing) were not renamed at all.

What changed
- provider.Renames (UsageRenames): Of(id, time) is the id a call recorded
  under id at that time belongs to now. Every usage reader goes through it:
  summarizeFrom (and its historical-key set), ledgerMatched, NewPricer,
  NewCoster, the Requests page's gateway blocks, probe rows and other
  computers' days, window holds and their history, buildVias, and
  gateway loggedAnswers. Visit stays as recorded so Of is taken once.
  The summary, Requests and vias caches key on Renames.Key.
- An id reused by another provider no longer pulls the new one's calls
  into the old one. Rename onto, or Save of a new provider under, an id in
  another's Was moves it into that one's Gave with the time (giveID):
  calls before then stay the old provider's. freeID treats Was ids as
  taken, so adding the vendor again gets "-2". Renamed() (refs) skips ids
  a provider or subscription holds now.
- A providers.json that can't be read keeps the last renames read instead
  of none (a failed read is unknown), so usage doesn't split meanwhile.
- History: nothing in usage.jsonl is rewritten. Calls from before this
  release under a renamed id show under the new id at once. An id that was
  reused before this release has no hand-over time, so its calls show under
  whoever holds the id now, as before.

Siblings checked: budget keys by caller key; per-key limits, RPM and
concurrency count live requests by the current id; tray totals go through
QueryPage; codex_memory reads Requested refs. None needed a change.

Run at the tree before the rebase; rebased onto 894603bcd (GUI-only,
none of these files) and provider, usage, usageapi, the build and the
Rename/Answer/Lead tests of gateway and gui run again there: ok.
- TestRenamesByWhenTheIDWasTaken (provider), TestRenamedProviderShownOnce
  (usage), TestRenamedProviderAnsweredItsLead (gateway): each red with its
  piece broken by hand (Save's giveID, freeID's Was, the last-good renames,
  probe rename, vias rename, block pricer's timed path, summarize's time,
  loggedAnswers' rename), green with it.
- go test -timeout 45m provider usage usageapi budget middleware cli agent
  gui gateway sessions profile tui: all ok.
- gofmt -l, go vet ./internal/..., GOOS=linux/windows -tags nogui vet of
  provider/usage/gateway and build of the binary: clean.
- Sandbox: rebuilt binary on the same HOME; /api/usage/requests lists only
  newrelay, the probe row included.

Not tried: the GUI suite (no JS or asset changed; /api/providers gains an
omitempty "gave"), Windows tests run on the Windows box, a real account,
and the full ./... suite (other sessions' suites were running).
2026-10-25 10:53:45 +08:00
yetone 769355ab93 library: an MCP server's startup timeout reaches Codex as startup_timeout_sec, a hand-written one stays (#3168, miaomiaozi)
The Library's MCP server editor has a "Startup timeout" field (seconds),
shown when an agent that reads one is installed (AgentView.Startup; Codex
only). It is written to Codex's [mcp_servers.<name>] startup_timeout_sec,
user-wide and in a project's .codex/config.toml. Empty writes nothing, so
Codex keeps its own 30s, as before. The key and its unit are from Codex's
own source: RawMcpServerConfig in codex-rs/config/src/mcp_types.rs
(cb2581dae8de) has startup_timeout_sec: Option<f64> in seconds, and the
older startup_timeout_ms, which is read only when _sec is absent.

A value the user wrote in config.toml is never written over. magpie
records the value it last wrote (Applied.Startup per agent,
Project.Startup per project file). A value in the entry that differs from
that record, one there before magpie wrote any, or any
startup_timeout_ms, is the user's (startupTheirs), and magpie leaves the
key alone. Once the user takes theirs out, magpie's goes in. The TUI's
server editor keeps the GUI-set value, as it does for OAuth.

Other agents with a startup timeout (Grok Build, Hermes, OpenCode) and a
`magpie mcp add` flag are #3536.

Run, in a sandbox HOME with pinned GOMODCACHE/GOCACHE:
- go test -tags nogui ./internal/library ./internal/tui: ok (162s, 16s).
- New tests: TestCodexStartupTimeout, TestCodexStartupTimeoutKeepsUsers,
  TestCodexProjectStartupTimeout. Broken by hand, each red:
  every existing value counted as the user's -> "startup_timeout_sec =
  120, want 45"; magpie always winning -> "= 20, want 90"; no encode (the
  old code) -> "= <nil>, want 120".
- GUI: new mcp-startup-timeout.test.cjs, Chromium and WebKit, en zh zh-TW
  ja de, 1100 and 390px: 22/22; red on the old client.js (no field).
  The 59 GUI files the change reaches (mcp-*, library-*, i18n-keys,
  gui-de/ja/zh-tw, every editServer/lib-editor file): 935 of 937 pass.
  The red, library-row-remove's hook-row trash in Chromium, fails the
  same way on origin/main 208bd5c48 run alone (2 of 2); it is #3099.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; linux nogui, windows and darwin builds ok.
- Real Codex: config.toml written by magpie under a scratch CODEX_HOME,
  read by codex-cli 0.162.1 `codex mcp list --json`:
  "startup_timeout_sec": 2.0.

After rebasing on origin/main 208bd5c48: go vet library+tui, linux nogui
and windows builds ok; go test -tags nogui internal/library (130s), tui
ok; internal/gui red once on TestRestartHandsTheGatewayOver (#3451, a
handover EOF, untouched here), then -count=3 alone and the package again
ok; GUI mcp-startup-timeout + i18n-keys 26/26.

Not tried: a real Codex start that actually times out (codex exec needs
a signed-in account in the scratch home); the full ./... suite.
2026-10-25 09:41:32 +08:00
yetone 208bd5c48b gui: Settings descriptions wrap instead of ending in … (arculongus on Discord)
arculongus (English UI, screenshot) couldn't read many Settings rows: the
line under a setting's name ended in "…". The generic `.row .sub` rule holds
a row's line to one line with an ellipsis; a few Settings rows opted out
(`.wraps`) and the rest were cut, among them Image generation's ChatGPT
note, Image recognition MCP server and Web search's Searches for other
models.

Fixed for the class, not the rows in the screenshot: every setting row's
line (`.row.pref .sub`) now wraps whole beside its control. That covers
every Settings part, Plugins › Built-in and an agent's own settings (the
same rows). The control keeps its size (`.prefs .val` is `flex: none`,
max 60%), and nothing else in the layout moves. The window is never
narrower than 560pt, so a row stays a few lines at most. Lines elsewhere (provider
and account cards, chips, URLs) stay one line; their full text is already
reachable through the hover title.

Tests:
- New settings-lines-wrap.test.cjs checks every visible Settings part plus
  Plugins › Built-in, in chromium and webkit, en/zh/zh-TW/ja/de, at
  1000px and 440px. No row's line is cut or nowrap, each control stays
  inside its row, and the page never scrolls sideways (more than 30 rows
  checked). It also checks the three reported rows by name.
- Tests that assumed one-line rows now follow the taller rows:
  - searcher-pick: the help wraps rather than ellipsizing with a title.
  - settings-general: one line only at 1000px, never cut at either width.
  - reader.cjs reach(): goes up to 8,000px, not 2,400.
  - member-model-setting, turn-done, connect-address-kept, tray-cost and
    tray-totals: wheel to the control with reach() before
    clicking, not scrollIntoViewIfNeeded or Playwright's own scroll, which
    the app undoes.
  - update-download, update-restart and tray-totals: a click whose row
    grows a line may scroll, but only to keep the clicked control under
    the pointer (the app's hold, #2134). tray-totals allows 2px, because
    WebKit's whole-pixel scrolls drifted 1.3px over four holds.
  - mobile-web: compares against an origin/main baseline without this
    change.
- Docs: gui-shell.md and gateway-routing.md.

Run (worktree from origin/main a6399dd49, then rebased):
- The new test passes 20/20. Broken by hand: pointed at the old assets
  (MAGPIE_WRAP_ASSETS), it is red 10/10 in chromium and red in webkit
  ("general: a row's line is cut short").
- Whole GUI suite (872 files) in two runs, at concurrency 3-4 and load
  20-150:
  - The 170 Settings-reaching files first: 2515/2575.
  - Then the other 702: 9767/9920.
  - Each red was rerun on settings-wrap-base. The files this change made
    red (settings-general, turn-done, update-download, update-restart,
    member-model-setting, codex-auto-reset-settings, mobile-web,
    connect-address-kept, quota-reads, tray-cost, tray-totals) are fixed
    above and pass on rerun: 86/86, 34/34, 112/112 and 50/50.
  - Also red on origin/main, already filed:
    - redact-words-any-case: #3500
    - s3-sync webkit: #2448
    - usage-checkin Qoder tab: #2549
    - plugin-card-update: #3079
    - builtins and gateway-mode masking tab: #3498
    - fonts webkit: #3227
  - The other files red on origin/main 31bff66be, run alone at a
    comparable count, all have issues: routing-pause #3410,
    routing-rule-effort #3411, routing-rule-remove #3094/#3096,
    routing-intent-entry #3408, routing-live-patch #2174, routing-manual
    #3409, routing-steady #3412, menu-input-scroll #3402, header-centre
    #3479, gateway-caller-keys #2572, gateway-key-models #2648,
    gateway-key-limit #3523, quota-count-wrap #3404, usage-agents-hide
    #3414, usage-fold #3415, usage-ledger #3001/#3104, sidebar and
    gateway-mode #3498, account-discovery #3497, sidebar-overlay-scrollbar
    #1863, account-alias #2984.
  - provider-user-agent failed only on browserType.launch timeouts (load)
    and passed on rerun.
- After the rebase onto b027ca264, these were run again at the pushed head: the
  14 changed or affected GUI files (the new test, the eleven above,
  quota-reads, which main already wheels, and i18n-keys) passed 302/302.
  go test -tags nogui ./internal/gui (budgets included) was ok, with no
  budget raised.
- Before and after screenshots, Settings › Models at 1000px and 700px,
  chromium and webkit, were looked at: the rows that ended in an ellipsis
  now read whole, and each control has the size and place it had before.

Not tried: the real app (WKWebView, WebKitGTK, WebView2). This is a CSS
white-space change with no motion and no new API.
2026-10-25 09:21:42 +08:00
yetone 73d17f90ce codex: every CODEX_HOME folder's sessions count, its account renewed there
phantom3792 on X: with several ChatGPT accounts kept the way Codex
supports, magpie counted only the default profile's usage, and the
accounts added from the other profiles read no quota.

Codex's mechanism, from openai/codex at 970111f6cb62:
- One sign-in per folder. In codex-rs/login/src/auth/storage.rs the
  sign-in is $CODEX_HOME/auth.json, or the keychain item that
  compute_store_key(codex_home) names.
- Sessions live in the same folder. rollout/src/lib.rs writes sessions/
  and archived_sessions/ under codex_home.
- `--profile <name>` only lays $CODEX_HOME/<name>.config.toml over
  config.toml (config/src/loader/mod.rs), and the sign-in stays shared.
So a second account is Codex run with CODEX_HOME=~/.codex-work, and
magpie read only the folder it runs with.

There were two causes:
- Sessions: codexFiles() walked CodexDir() alone. The sessions list,
  traces and the usage ledger (sessions.Calls) never saw other folders'
  rollouts.
- Quota: an account added by importing another folder's auth.json is
  refreshed from magpie's copy. The import rotates the refresh token,
  which leaves two holders of one token, and whichever refreshes first
  signs the other out. The saved account goes "sign-in has expired" and
  its quota read fails.

The fix:
- appdir.CodexHomes finds the folders: CodexHome first, then folders
  named codex* or .codex* in the home folder or beside CodexHome, or
  one level down in one (~/.codex-profiles/work), that hold auth.json
  or sessions/.
- sessions: codexFiles and Dirs read every folder.
- provider: rememberLogins saves each folder's account with Home set
  to it (codexHomeLogins). The one ~/.codex is signed in to stays that
  folder's.
- renewSaved renews such an account where that folder's Codex keeps
  it (codexHeldIn, as heldByCodex does for ~/.codex). This one funnel
  covers quota, gateway, warm-up, keep-alive and revoked sign-ins.
  codexLoginAuth reads its expiry from the same place.
- switchSavedLogin, NextLogin's spares and forgetLogin leave such an
  account alone. Their errors name the folder and the
  CODEX_HOME=... codex command.
- docs/subsystems/providers-accounts.md gains a row.

Run (worktree at 42ab93551 plus this diff, sandbox HOME, pinned
caches, log kept whole):
- go test -tags nogui -timeout 45m ./internal/appdir/
  ./internal/sessions/ ./internal/provider/ ./internal/usage/
  ./internal/cli/: all ok.
- gofmt -l internal/: clean.
- GOOS=linux and GOOS=windows go vet on appdir, sessions and provider:
  clean. go vet -tags nogui ./internal/gui/: clean.

Rebased onto 13f907013, which changes internal/sessions only. At that
head, sessions and appdir passed in full, and provider -run 'TestCodex|Login'
passed.

Broken by hand, each red:
- codexOtherHomes returning nil: TestCodexOtherHomeAccountReadsQuota
  fails with the reporter's symptom ("sign-in has expired", refreshed
  with the copy's spent token).
- renewSaved without the home path: ~/.codex-work/auth.json is not
  renewed in place.
- switchSavedLogin without its refusal: ~/.codex/auth.json is
  rewritten to the other account.
- CodexDirs returning CodexDir alone: TestCodexOtherHomeSessionsCounted
  lists 1 session, not 2.

Not tried:
- A real second CODEX_HOME with real accounts. The fixtures copy the
  real auth.json shape and the rollout layout, not real tokens.
- A folder outside the home folder that isn't next to CODEX_HOME.
- Codex keeping the other folder's sign-in in the keychain (the reader
  is the same readCodexLogin per folder).
- An entry whose folder was signed out keeps Home and goes back to
  being refreshed from its copy.

Not done (#3530): Codex thread names (session_index.jsonl) and a
config sqlite_home are still read from CODEX_HOME only.
2026-10-25 07:42:13 +08:00
yetone 402577c15a gateway: image generation is an MCP server on the gateway, /mcp/magpie/image
JonahFu on X runs magpie in Docker in gateway mode, so he has no Library and
no stdio Magpie Image server, while image recognition is an HTTP MCP server
on the gateway (/mcp/magpie/vision). Now image generation is one too, with
the stdio server's tools: generate_image, generate_video and
generation_result, drawing with Settings › Images › Image generation.

- image_mcp.go: served by serveMCP, so it is guarded as the vision server
  is (local or a shared magpie's caller, a refused Origin 403, POST only,
  the key's limit reserved per call). A drawing is s.images run in-process
  on a clone of the request (caller and key kept), so routing, key models,
  usage and the timeout setting are draw.go's own. It runs as a job (15
  min at most); the tool answers within 20s or gives an id that
  generation_result waits on. Images come back as MCP image content (5 MB
  each at most) and at /mcp/magpie/image/files/<name>, kept in memory an
  hour, 256 MB at most, readable only by the key that made them. Videos
  go through videosCreate/videosGet in-process and are given as
  /v1/videos/<id>/content. Image generation Off is a tool error naming
  where to turn it on, before the arguments are read.
- Input images go through the vision server's reader, now mcpImageSrc
  (vision_mcp.go), so a file path is read only for a local caller.
- The tool schemas live in the gateway (ImageToolProps, VideoToolProps,
  ResultToolProps); internal/imagemcp takes them and adds only its path
  argument. Its tools/list JSON was compared byte for byte with the old one.
- Settings › Models: #imageMcpRow under #visionMcpRow with the address and
  a copy button; the gateway-mode Image generation sub now points at it.
  en, zh, zh-TW, ja, de.
  The two rows are drawn by one helper (mcpRow), which took the vision
  row's own code, so the row costs 462 bytes of app.js.
- core_budget_test: appScriptBudget 1,321,336 -> 1,321,424 and
  coreScriptBudget 1,528,525 -> 1,528,972, the exact sizes with the row,
  with no room added (10-25). Nothing moved out: the row is Settings'
  own, which the core draws.
- search-api.test.cjs: the new row pushed the search row partly below the
  1400px window at 420px, where scrollIntoViewIfNeeded leaves it, and
  magpie puts back a scroll the reader didn't make, so the test's
  coordinate clicks missed. It now brings the whole row on screen with
  the wheel and checks it is still there a second later. Red with the new
  row before this, green after; green on origin/main's GUI either way.
- oneport_test knows ImageMCPPath and ImageMCPFiles (ClientPath covers
  them).

Run (worktree at this commit, on origin/main 94503901c):
- go test -tags nogui -run 'ImageMCP|VisionMCP|ClientPath|SearchMCP'
  ./internal/gateway/ ok; ./internal/imagemcp ok; the image and vision MCP
  tests with -race -count=3 ok.
- Red on the old code: TestImageMCPDrawsAndServesTheImage (the route is
  404).
- Broken by hand, each red: no route (DrawsAndServes), no key check on
  files (Guarded), no Off check (SaysWhenOff), no reserveFor
  (HeldToKeyLimit), no local-only file read in mcpImageSrc (Guarded).
- GUI, chromium and webkit, every language, at this commit: image-mcp,
  vision-mcp, i18n-keys, images-library-way, search-api,
  settings-sections, gui-de, gui-ja, gui-zh-tw (123/123). Before the
  helper and the rebase: image-mcp, vision-mcp,
  images-library-way, images-codex-one, image-timeout-setting,
  images-missing, i18n-keys, gui-de, gui-ja, gui-zh-tw, settings-sections,
  vision-not-marked (201/201); claude-lean-prompt-setting,
  classify-timeout-setting, disabled-models, member-model-setting,
  loop-guard-setting, refusal-retries-setting, search-first, search-order,
  search-mcp, searcher-pick, side-effort, search-api, search-keys (198/198
  after the search-api fix; search-api alone 8/8 twice).
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- Full suite (go test -tags nogui -timeout 45m ./...): the run before the
  helper was red only in TestCoreScriptBudget, fixed above; a run at this
  commit was started and not finished at push (pushed at once, the
  owner's rule), its result goes on the push report.
- Real: magpie serve (nogui) in a sandbox HOME on 127.0.0.1:3592, its
  Image generation a provider pointed at the live gateway's
  codex/gpt-image-2.5. curl: initialize (Magpie Image), tools/list (the
  three tools), Origin https://evil.example 403, GET 405, an unknown file
  404, GET /v1 lists /mcp/magpie/image, Off answers the Off text for both
  tools. generate_image reached Codex through the live gateway and came
  back as the tool error "yetoneful@gmail.com's sign-in has expired".

Not tried: a real image drawn end to end (the only drawing account's
sign-in has expired; image content and file URLs are covered by fake
upstreams), a real video, a call from another computer with a gateway key
(the remote and key paths are covered by TestImageMCPGuarded), Docker.
2026-10-25 06:42:03 +08:00
yetone 5b32b7ea80 plugins: a Bun Windows can't load (0xc0000139, before 10 1809 / Server 2019) says so and what to do (zgcwkj on Discord)
zgcwkj runs magpie-cli-windows-amd64.exe as a Windows service (nssm) and
every plugin install failed with "bun add …: exit status 0xc0000139: (and
from the community repo's dist branch: bun add ./dist/….tgz: exit status
0xc0000139: )".

Why: 0xc0000139 is STATUS_ENTRYPOINT_NOT_FOUND, the loader refusing the
exe before it runs. Reading the PE imports (debug/pe) of Bun's
windows-x64(-baseline) zips: 1.3.14 and later, so magpie's floor 1.4.2
and the latest 1.4.4, import kernel32's CreatePseudoConsole,
ClosePseudoConsole and ResizePseudoConsole, which Windows has from 10
1809 (build 17763) / Server 2019 on. 1.3.13 doesn't. Bun's docs say
"Windows 10 version 1809 or later" (bun.com/docs/installation). So
Windows Server 2016 and Windows 10 1507 to 1803 (LTSB 2015/2016) can't
run any Bun magpie uses. 1.4.2's pinned SHA-256 matches the asset.

What changes:
- wontLoad (internal/plugin/bun.go) reads an exit of 0xc0000139 as
  "this Windows" and 0xc000001d or SIGILL as "this processor" (Bun's x64
  build targets SSE4.2), as a *BunUnstartableError whose message says
  which, the versions Bun needs, and MAGPIE_BUN.
- bun add, bun update, cantStart and whyDied (the host's start) wrap it.
- An install no longer tries the dist branch after it: that bun add
  can't start either, and its error read as the dist branch's.
- The GUI's fail() answers it with code bun_unstartable, bunWhy and
  said, an i18n.js key (bunSaid in api.go), which api() in app.js puts
  through t(): en, zh, zh-TW, ja, de, in the window and in magpie web.
  The sentences live in Go so app.js grows one line: with both in
  app.js, TestCoreScriptBudget was 128 bytes over app.js's budget and
  487 over the core's, and no budget is raised here.
  TestBunSaidIsTranslated fails when a language lacks one. The CLI
  prints the English message.
- No fallback to an older Bun: 1.3.13 is below BunVersion and Bun
  doesn't support that Windows, and the -baseline assets are now the
  same binary.
- docs/subsystems/provider-plugins.md says all this.

Run:
- New tests: TestWontLoadSaysWindowsOrCPU (injected NTSTATUS exits, a
  real kill -ILL), TestInstallOnUnstartableBunSaysWhyAndSkipsDist (0
  dist requests), TestHostOnUnstartableBunSaysWhy, TestFailSaysBun
  Unstartable, TestBunSaidIsTranslated, plugin-bun-unstartable.test.cjs (chromium and webkit,
  every language, window and web).
- Real Windows (10.0.26200 box, a sandbox dir of its own): a
  windows/amd64 nogui magpie-cli.exe with a fake magpie-bun.exe that
  exits 0xc0000139, `plugin add @magpie-community/opencode-raccoon-auth`
  printed the new message, and no dist folder was made.
- gofmt -l; go vet darwin, linux -tags nogui, windows; builds of all three.
- Full suite (go test -tags nogui -timeout 45m ./..., through
  suite-lock, at a6399dd49 plus this change with both sentences in app.js):
  every package ok except internal/gui's TestCoreScriptBudget (128
  bytes over app.js's budget, 487 over the core's). After the sentences
  moved to bunSaid: internal/gui and internal/plugin ok, budget
  included (core 1,528,331 of 1,528,525 before scoping the line to the
  code, ~20 bytes more after).
- GUI (chromium and webkit, node --test): i18n-keys, every plugin-*
  file and signin-paste-plugin, 660 of 660 before the move to bunSaid;
  after it 656 of 660 at load ~140: plugin-card-update webkit (#3079)
  and plugin-quota-error chromium ja, whose Chromium launch hit
  Playwright's 180s timeout before the test ran. Both files alone: 16
  of 16, 14 of 16 (which one not kept), 16 of 16, 16 of 16.
- Rebased on ff6090354: TestCoreScriptBudget, the new Go tests,
  plugin-bun-unstartable and i18n-keys again ok; gofmt; windows and
  linux vet of internal/plugin and internal/gui.

Broken by hand (each restored):
- wontLoad always nil: the three plugin tests fail, the install one
  with the reporter's exact "(and from the community repo's dist
  branch: …)" shape.
- the dist skip removed: 1 dist request.
- the whyDied check removed: the host test fails.
- fail()'s block removed: the gui Go test fails.
- app.js's line turned off: the GUI test fails, 16 of 16 (chromium).
- one language's key renamed: TestBunSaidIsTranslated fails (3 of 4).

Not tried: a real Windows before 1809 (the box is Windows 11) and a real
processor without SSE4.2; zgcwkj's Windows version is still unknown.
2026-10-25 05:54:07 +08:00
yetone ff6090354e gateway: dsh's session and compaction marks are held on Messages and Responses too (#3298)
A user's own dsh llm-deepseek row pointed at magpie (e3491e2bb's docs)
calls /v1/messages with x-deepseek-harness-session-id and
x-deepseek-harness-compact. #2505 reads both in sessionOf/dshCompacts
for every route already, but TestDshMarksSessionAndCompaction only
covered /v1/chat/completions. TestDshMarksOnEveryRoute sends both marks
(and llm-deepseek's x-deepseek-harness-user-id) to /v1/messages on an
Anthropic provider and /v1/responses on a Responses provider, and checks
the recorded session, kind "compact" or none, and that the vendor gets
no x-deepseek-harness-* header. No behaviour changes: this guards what
the docs now tell users, and so it passes on the old code too.
docs/subsystems/gateway-sessions.md names it.

Broken by hand: dropping x-deepseek-harness-session-id from
sessionHeaders turns all four cases red (session ""); making dshCompacts
always false turns both compact cases red (kind ""). Restored after
each.

Run before the rebase onto 500aa7096: go test ./internal/gateway
-count=1 -timeout 45m (ok, 450s). At this head, after it (500aa7096
changes internal/sessions only): go test ./internal/gateway -run
'TestDshMarks|Session' ok, go test ./internal/sessions ok; gofmt -l internal/gateway empty; GOOS=linux and
GOOS=windows go vet ./internal/gateway ok. Real dsh 0.2.1-rc.2 through a
sandbox magpie recorded its session on /v1/messages (see e3491e2bb).

Not tried: streaming on these two routes in the test (the real dsh run
streamed /v1/messages), Windows test run.
2026-10-25 05:51:52 +08:00
yetone e3491e2bb0 docs: point dsh's own DeepSeek row at magpie by hand (#3298)
tom047784 (Discord) wants dsh's llm-deepseek row, which keeps DeepSeek's
cache across in-history prompt and tool updates and uploads images
through the Files API, to go through magpie. magpie doesn't take that
row over (the key would mean two things, it would override the user's
own entry, and a file_id belongs to one account while magpie fails
over), so this documents the entry a user writes themselves:
docs/reference.md under "Notes on some agents", and a FAQ entry in
site/public/docs start.html (en, zh, ja).

Checked against @deepseek-ai/dsh-llm-deepseek 0.2.1-rc.2's source
(npm pack into a scratchpad, read only): messagesApiRoot adds /v1 to
baseURL unless it ends in /v1; apiKeyEnv is a credential reference read
from dsh's credentials and then the environment; an explicit models list
replaces DEFAULT_MODELS, whose in-history/addition-only settings are on
deepseek-flash only; any Files failure rebuilds the request inline,
bounded by maxInlineRequestImageBytes (20 MiB) against
maxRequestFilesBytes (128 MiB). Against magpie: internal/agent/dsh.go
drops only magpie-marked llm-deepseek entries and removes
MAGPIE_GATEWAY_KEY on Disconnect; POST /v1/files answers 404; the
catalog ids are deepseek/deepseek-flash and deepseek/deepseek-v4-pro.

Tried: real dsh 0.2.1-rc.2, `dsh --profile headless`, sandbox DSH_HOME
and HOME, a magpie built from this tree on its own port. Through a fake
Anthropic upstream: "say pong" answered; the upstream got
output_config.effort, thinking, tools, dsh_session_log and
dsh_plugin_packages as sent, the provider's key, and no
x-deepseek-harness-* header. A mid-history system message with
tool_addition and the mid-conversation-tool-changes anthropic-beta went
through unchanged (curl). With a real DeepSeek key copied into the
sandbox: dsh read a file with a tool, three calls all 200, cache_read
5760 on a later call; a system message added in the history after two
turns was followed and cache_read_input_tokens was 3456. Usage rows had
agent dsh, /v1/messages and dsh's session; x-deepseek-harness-compact: 1
recorded kind compact.

Not tried: an image turn through dsh (the inline fallback is from the
source and the 404), the desktop app and its Models-page key entry,
Windows.
2026-10-25 05:50:34 +08:00
yetone 3387ea6156 gateway: an Antigravity drawing out of the image model's quota goes on to the next account and rests that model there (01huadalang)
01huadalang (Discord): with several Antigravity accounts, when one
account's image quota is spent, magpie doesn't move on to the next.
Model, entry point and error text were asked for and not answered yet.

What every image path does (generate_image MCP and /v1/images both go
through images() -> drawOnAccounts -> drawCodeAssist; a chat on the
image model goes through serve's candidate loop):
- A 429 (antigravityQuota, "You have exhausted your capacity on this
  model. Your quota will reset after 3h19m30s.") already went on to the
  next account, but rested nothing, so every drawing asked the spent
  account first again.
- Antigravity also says a model's quota used up as a 200 whose stream is
  the error event (the Code Assist decoder keeps its message; the chat
  path's TestAntigravityTurnedAwaySaidInsideTheReply). drawCodeAssist
  told every such error as 502, which accountRefusedDrawing doesn't move
  on for, so the drawing ended on the spent account while the next had
  its quota. The chat path already fails over on it.

Fix (internal/gateway/draw.go):
- saidStatus: an error said inside a drawing's 200 is 429 when its words
  say quota or rate (usedUpWords, quotaCodes, rateWords), 402 for credit,
  else the 502 it was. drawCodeAssist uses it, and so does the images
  API's 200 with no image (its sibling).
- restDrawer: an account's drawing refused as failQuota (failure) rests
  the image model on that account alone (restID, Rest.Model), until the
  reset the refusal names (resetsAt) or quotaRest, held to longestQuota.
  The account's text models aren't touched; keys and other failures rest
  nothing, as before. candidates' restLast then asks the accounts that
  still have the model first.

Tests (internal/gateway/antigravity_draw_test.go), Antigravity's real
QUOTA_EXHAUSTED 429 body (antigravityQuota) as a 429 and as the stream's
error event:
- TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn
- TestAntigravityDrawingQuotaRestsTheImageModel (u1 then u2, then u2
  alone; rest until ~3h19m30s; the account itself not resting)
- TestAntigravityDrawingOtherErrorInsideTheReplyStays (a 500 INTERNAL
  inside the reply asks no other account, rests nothing)

Broken by hand: draw.go at origin/main with the new tests: the first two
red (502 on the spent account; "asked u1 u2 u1 u2"), the third green.

Run at this head:
- go test -tags nogui -timeout 45m ./internal/gateway: ok github.com/yetone/magpie/internal/gateway 432.7s (go test -tags nogui -timeout 45m ./internal/gateway at 5509128b1 + this diff)
- gofmt -l internal/gateway: clean
- go vet ./internal/gateway on darwin, GOOS=linux and GOOS=windows: ok

Not tried: a real account. The owner's machine has one Antigravity
account, and none with its image quota spent, so neither rotation nor
the real in-stream error body was seen live; the stream case is
Antigravity's 429 body sent as the event, not a captured stream.

Docs: gateway-routing.md's Image generation row.
2026-10-25 05:16:50 +08:00
yetone ffe493773c usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.

The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.

The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.

Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
  Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
  the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
  every request the fake server saw is exactly one row, with the right
  kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
  light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
  kind api_detect, no key) and leaves usage.jsonl out of the unchanged
  config comparison.

Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).

Run at this head (on origin/main 22a7f86c9): gofmt -l clean; go vet
./..., GOOS=linux -tags nogui and GOOS=windows clean; go test -count=1
usage, probelog, netproxy, usageapi, provider and gui packages ok (the
rebase over 22a7f86c9 applied cleanly; upstream's 8b460833e chunk
cache leaves probeChunk, built per query, alone).

Run one rebase earlier (on origin/main 0b72ccbef; request_page.go
merged by hand onto 7d67910f7/66b6d6ade's per-row Totals, with
uncounted rows skipping the caller and account groups too):
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, log tee'd:
  every package ok (gateway 640s, agent 514s, provider 278s, usage 77s)
  but internal/gui's TestRestartHandsTheGatewayOver (7 of 8 requests
  answered during the restart), 3 of 3 green alone after (#3451).
- gofmt -l clean; go vet ./..., GOOS=linux -tags nogui and GOOS=windows
  go vet ./... clean.
- GUI usage-ledger-probe, usage-ledger-reported, i18n-keys,
  purpose-filter, quota-pool-model: 72/72. usage-ledger's "newest live
  route needs no return-to-live button" is red on origin/main 0b72ccbef
  alone too (#3104).
- Whole GUI suite, both engines, at the pre-rebase base 761904b5a:
  1313 tests; reds, each also red on origin/main 7b1faf99f alone:
  account-discovery "agents' sign-ins read" (#3497), builtins
  "Plugins > Built-in" (Masking page in the list, #3518 filed), and
  context-map "two tiles overlap" chromium ja 420 (#3488; 1 of 2 red on
  main alone, 3 of 3 green on this branch alone). Earlier package run:
  TestRestartHandsTheGatewayOver red under load, passes alone (#3451).
- No size budget raised.

Not tried: no real vendor account (fake servers only); a plugin's model
list, fetched in the JS plugin host, isn't written down; the real GUI
app wasn't launched (Playwright only).
2026-10-25 04:12:06 +08:00
yetone 1b32bdcfcb gui: magpie web's port answers the gateway's /v1 routes too, so one proxy location serves both (zgcwkj on Discord)
zgcwkj puts magpie behind nginx on one domain and wanted the browser UI
(magpie web / serve --web, 127.0.0.1:3430) and the gateway (:3425) from
one port, so one location works. Now the web port hands every gateway
client route to the gateway: /v1/..., /v1beta/..., /models, /chat/completions,
/responses, /messages, /images, /embeddings, /rerank, /audio, /videos,
/muse-code/models, /backend-api/codex/..., the search path and /mcp/...
(gateway.ClientPath). Everything else stays the page's, behind webGuard as
before. /api/* stays split: on the web port it is the UI's API; Ollama's
/api/* and Claude Desktop's /api/hello still need the gateway port, since
the two can't share the path.

Security: a handed-over request goes through the gateway's whole own
stack, not a copy of it. gateway.Server.Front() is lanGuard(Handler()),
built once; ListenAndServe serves the same handler. When this process
serves the gateway, the web port calls Front() in process; when another
magpie does, toGateway reverse-proxies to gateway.URL(), keeps the Host,
copies Forwarded/X-Forwarded-* back (ReverseProxy strips them), and adds
X-Forwarded-For for a non-loopback peer, so remote, proxied, rebound,
Origin null, *.localhost and foreign-Origin requests are judged exactly as
on the gateway port. The web cookie is never a gateway key. Paths that
aren't clean (/v1/../api, /v1//x, /v1/./x) are not client paths, so they
never reach the gateway as one. The allow list (AllowGuard) still wraps
both.

Tests:
- TestClientPathCoversHandler reads every mux pattern Handler registers
  and fails when one is neither a ClientPath nor /, /api/* or /_magpie/*,
  so a new gateway route has to be placed.
- TestClientPathOnlyClean.
- TestWebOnePortServedHere / ServedElsewhere: with no web cookie, the UI
  API (/api/settings) is never reached for: no Origin (GET, POST),
  Origin null, a foreign Origin, a rebound Host (GET, POST), through a
  proxy (XFF), from another machine, /v1/../api, /v1/%2e%2e/api,
  /v1//api, and with a gateway key. The gateway routes on the web port:
  local agent 200; Origin null POST 403; foreign Origin 403; rebound Host
  403 (with the page's cookie too); proxy or remote without a key 401
  (with the page's cookie too); with a gateway key 200; not shared 403.
- TestWebAssetsAreNoClientPath: no embedded asset shadows a client path.

Run (full packages at the first rebase, on origin/main 0b72ccbef):
- go test ./internal/gateway ./internal/gui -count=1 -timeout 45m:
  ok (gateway 644s, gui 193s).
- Rebased again on origin/main 8b460833e (upstream touched catalog,
  provider, redact and usage only); at this head: the three builds and
  the vets below again, and go test -run 'TestClientPath|TestWeb'
  ./internal/gateway ./internal/gui: ok. The full packages were not
  rerun at this head.
- gofmt -l internal/gateway internal/gui: empty
- go vet ./internal/gateway ./internal/gui; GOOS=linux go vet -tags
  nogui ./internal/gateway ./internal/gui ./internal/cli; GOOS=windows go
  vet ./internal/gateway ./internal/gui: ok
- go build .; GOOS=linux go build -tags nogui .; GOOS=windows go build .: ok

Broken by hand, each red, then restored:
- no onePort (the old web handler): agent 401 not 200, Origin null 401
  not 403 (ServedHere).
- Front without lanGuard: rebound Host 200, proxy without a key 200.
- toGateway not copying the forwarding headers: proxy without a key 200,
  not shared 200 (ServedElsewhere).
- no X-Forwarded-For for a remote peer: another machine 200.
- Host not kept: rebound Host 200.
- ClientPath taking unclean paths: TestClientPathOnlyClean red (4 paths).
  The gui tests stay green under this break, since the gateway's mux
  answers /v1/../api/settings with a redirect, not the UI API; the clean
  check is a second wall.

Real try: the built binary, `magpie serve --web=127.0.0.1:3472` under a
sandbox HOME (MAGPIE_ADDR=127.0.0.1:3471, MAGPIE_NO_ACCOUNTS=1,
MAGPIE_TEST_SANDBOX), then Homebrew's nginx 1.31.7 (bottle unpacked in a
scratch folder, proxy_pass to 3472 with Host and X-Forwarded-For) on
127.0.0.1:3473. Direct on 3472: / 401, /?k= 303, /api/settings 401
without and 200 with the cookie, /v1/models 200, Origin null POST 403,
foreign Origin 403, X-Forwarded-For 403 (not shared). Through nginx, not
shared: /v1/models 403 with the "came through a proxy" reason; the UI
signs in with /?k= and /api/settings is 200 with its cookie. Sharing
turned on and a key added from the UI API through nginx: /v1/models 401
without a key and 401 with only the page's cookie, 200 with the key;
/v1/messages and a streamed /v1/chat/completions with the key reach the
gateway (404: the sandbox has no provider); /api/settings with the key
401; Origin null and foreign Origin without a key 401; /v1/../api/settings
401; /api/tags 401 (the page's API, not Ollama's). A rebound Host on
either port is refused only for a request that looks like a browser's
(Sec-Fetch-Site), the same as the gateway port before.

Not tried: a real model reply (and so a long stream) through the one
port, since the sandbox has no provider; https, WebSocket (Codex's
/backend-api/codex websocket) through nginx; Windows and Linux, other
than vet and build; the GUI suite (no GUI asset changed).
2026-10-25 04:01:52 +08:00
yetone 0b72ccbeff agentplug: connect's models carry /v1/models' native_endpoints and pricing
cleary5779 on Discord builds an agent as an agent plugin and wants, in
connect({ gateway, model, models }), the API each model passes straight
through on and what it costs. Each entry of models (and model) now also
has, by the names /v1/models uses:

  "native_endpoints": ["/v1/chat/completions"],
  "pricing": {"prompt": "0.0000003", "completion": "0.0000012",
              "input_cache_read": "0.00000003"}

Each is left out when not known: a group or a model translated anyway
has no native_endpoints, an unpriced model no pricing, never [] or 0.
The fields connect had (id, name, context, output, images, efforts) are
as they were.

No second lookup: nativeEndpoints moved from the gateway to
provider.NativeEndpoints, and openRouterPricing/perToken to
catalog.OpenRouterPricing/PerToken (internal/catalog/openrouter.go); the
gateway calls them as before. magpieModels already priced each model with
provider.EntryPricer, the price /v1/models gives (m.Price); it now also
keeps NativeEndpoints in catalog.Model.Endpoints (json:"-"), which
plugged's wire turns into the two keys.

Docs: reference.md's agent plugins section (what connect gets, with an
example), agent-wiring and gateway-routing subsystem pages, and the
site's Plugins page in en, zh and ja.

Run at this tree (on origin/main 66b6d6ade), load ~150:
- gofmt -l internal: nothing. go vet on the touched packages,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test ./internal/catalog ./internal/provider: ok (agentplug has no
  tests). go test ./internal/gateway -run 'Models|PerToken|OpenCode|
  Native|Cursor': ok.
- go test ./internal/agent -run 'Plugged|Pi|Price|Alma|ModelOrder|Image|
  Group|Codex': one red, TestCodexThreadsComeBackOffMagpie/disconnect
  (.cache/magpie/sessions.json left in its TempDir), open as #3422; it
  passes 5 of 5 alone and this change doesn't touch sessions.
- TestPluggedConnectSeesEndpointsAndPricing is red with plugged.go's two
  keys taken out (no native_endpoints, no pricing on model or models),
  green with them.
Not run: the full ./... suite (machine at load ~150 with several suites
queued); the whole agent and gateway packages. Not tried: a real agent
plugin reading the fields.
2026-10-25 03:39:50 +08:00
yetone 9949ad5eb0 gateway: a subagent a Responses Lite lead spawns elsewhere goes without Lite's reasoning context and header (TangForX on X)
TangForX: Codex with gpt-6.1-sol leading spawned a subagent on OpenCode
Go's DeepSeek v4.1 flash, and every turn of it answered 503 "Endpoint is
unavailable"; the same subagent under a DeepSeek lead, and on DeepSeek's
own API, worked.

Cause: gpt-6.1-sol is use_responses_lite, and Codex sends a subagent it
spawns in the lead's Lite shape with only the model name swapped:
reasoning.context "all_turns", tools in an additional_tools input item,
and the X-OpenAI-Internal-Codex-Responses-Lite header. passthrough lifted
additional_tools (#350) but sent the reasoning context on, and
forwardOnce copied the Lite header (an x-openai-* header Codex sends) to
every key+URL provider. OpenCode Go's DeepSeek route refuses that shape.

Fix: fromLite takes the whole Lite shape off (additional_tools lifted,
reasoning.context dropped, effort and summary kept) for every Responses
upstream that isn't OpenAI, a Codex account, or a codexAsSent relay
(liteKept); forwardOnce drops the Lite header on the same rule, for a
translated Chat upstream too. A body with no Lite in it goes byte for
byte as before. codexAsSent relays still get the request and header as
Codex sent them (TestCodexAsSent).

Run at the pushed head:
- TestLiteSubagentLeavesLite: Codex's code-mode request with Lite's
  fields and the collab_spawn subagent headers, to opencode-go
  deepseek-v4.1-flash, deepseek and a custom Responses relay; the fake
  upstream answers 503 "Endpoint is unavailable" to any Lite remnant.
  TestFromLite: a non-Lite body is unchanged byte for byte.
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...: clean.
- go test -tags nogui -count=1 ./internal/gateway (Lite, Codex,
  CodexAsSent, DeepSeek, OpenCode tests): ok.
- go test -tags nogui -timeout 45m ./... at ecfab308e (on 40a0b442c),
  one suite on the machine, log kept whole: every package ok, exit 0.
- Rebased on 3133f6343 (gateway, catalog, provider, agent changed): gofmt,
  vet (darwin, linux nogui, windows) of internal/gateway, and go test
  -count=1 of internal/gateway, catalog, provider and agent at the pushed
  head: ok.

Broken by hand: passthrough back to liftAdditionalTools alone, and the
header skip turned off: TestLiteSubagentLeavesLite red (503) on all
three upstreams each time.

Not tried: a real OpenCode Go request (the owner's Go key answers 401
api_key_expired; Zen free is rate limited), so which of the context and
the header Go refuses is not known; both go. Lite's other parts (empty
instructions with the prompt in a developer message, namespace and
custom-grammar tools) go as they did before.
2026-10-25 03:11:28 +08:00
yetone 3133f63434 gateway: /v1/models gives each priced model OpenRouter's pricing
cleary5779 on Discord builds an agent on magpie's gateway and wants the
list to say what a call costs. Each model magpie knows a price of now has

  "pricing": {"prompt": "<USD/token>", "completion": "<USD/token>",
              "input_cache_read": ..., "input_cache_write": ...}

as OpenRouter's /models writes it: decimal strings, the decimal point
moved rather than the float divided (perToken: $0.3/M is "0.0000003",
not 2.9999999999999997e-07). prompt and completion are always there for
a priced model (a price the user set at 0 included); the cache parts
only when they have a price. A model with no known price has no pricing
key at all, never a 0. Base price only: no tiers, no 1-hour write.

The price is the Usage page's (provider.EntryPricer, as EntryPriceIn):
the user's own, else the provider's list price or its maker's at the
price rate, a subscription's model at list price, a group only when
every member costs the same. It goes to the callers magpie_price goes to
(local or sharedWith), with or without X-Magpie-Prices; magpie_price
itself is still only for a list that asks. GET /v1/models/{id} carries
it too (pricedModelObject).

Siblings left without it: Claude Desktop's and Claude Science's lists
(Anthropic's shape, their apps read their own fields), Muse Code's
(models.dev metadata Muse reads), Codex's catalog, Ollama's tags, the
decision models (another magpie's System One), and the image and video
models, whose price isn't a token's.

Cost on the poll path (LESSONS: work added to a path every request or
poll takes): 755 models, 30 providers, the real models.dev catalog:
before the previous commit the pricing added ~30ms to a ~10ms list; with
it, the list is ~13-20ms against ~8-10ms without pricing, at load 65.

Run at 9afa86306 (both commits, on origin/main 40a0b442c), load 73-95:
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
- go test -tags nogui -timeout 45m ./...: exit 0, 70 packages ok
  (gateway 810s, agent 652s, provider 306s, catalog 29s); log kept whole
  and grepped, no FAIL. No other ./... suite ran meanwhile.
- go test ./internal/gateway ./internal/catalog ./internal/provider
  again beside it: ok.
- TestModelsListPricing is red with the pricing assignment taken out
  (both the list and GET /v1/models/{id} lose pricing), green with it.
Not tried: a real agent reading the list; Windows run (vet only).
2026-10-25 02:50:12 +08:00
yetone 7b1faf99f2 agent: a Codex auth.json caught mid-rewrite leaves Codex beside its ChatGPT sign-in (lucy)
lucy on Discord (v0.1.1394, Codex app, signed in in Codex, not in
magpie): on and off, Codex's account menu showed "magpie" instead of the
ChatGPT account, and the model picker listed magpie's catalog ("6.1 Sol
· Codex" ...) instead of Codex's own models.

Cause. codexChatGPT (internal/agent/codex.go:2022 on 0d2a10116) took any
failed read or parse of auth.json as "not signed in to ChatGPT". Codex
rewrites auth.json in place when it refreshes its tokens (codex-rs
login/src/auth/storage.rs FileAuthStorage::save: OpenOptions
truncate(true), then write_all), so a read in that moment finds it empty
or cut off; a keychain read that fails for a moment is the same. Sync
(codex.go:1306, run from every SyncCatalog) then took a Codex on a magpie
model beside its sign-in for one "with no ChatGPT sign-in" and called
set, which (codex.go:1079) made magpie Codex's provider with no codex.out
mark. Nothing put it back: Sync returns it beside the sign-in only from
codex.out, so it stayed until the next pick or group switch. A pick in
that moment (a group switch, the Agents page) did the same, and while
the account was held (codex.out) it forgot the mark.

Fix. provider.CodexSignInKnown says whether the read says anything: no
auth.json, no keychain item, or a store magpie doesn't read is known;
a read error, an auth.json that isn't valid JSON (empty, cut off), or a
keychain read that failed is unknown. codexChatGPTKnown builds on it,
and Codex's chatGPT closure takes an unknown read as magpie last wired
it (joined, beside, or codex.out). A sign-in really gone (codex logout)
or one with no ChatGPT token (an API key) still moves Codex onto magpie
as its provider, as before. codexChatGPT keeps its bool for connectinfo.

Tests (red on the old code, by putting the old answer back by hand in
the closure: every subtest of the first and the second failed):
- TestCodexHalfWrittenAuthKeepsSignIn: beside the sign-in, auth.json
  empty / cut off / not JSON, then Sync and a pick: stays beside; on the
  old code it went to model_provider = "magpie" and stayed there after
  auth.json was whole again and Sync ran.
- TestCodexHalfWrittenAuthKeepsOut: held (codex.out), a pick while
  auth.json is empty keeps the mark, and Sync puts it back beside the
  sign-in once the account has room.
- TestCodexSignInGoneStillKnown: logged out, or an API key: magpie its
  provider, as before.
- TestCodexSignInKnown (provider): signed in, empty, half, removed,
  keyring with no item, keyring refusing, ephemeral.
docs/subsystems/agent-wiring.md says the rule.

Run at the pushed head (this commit on origin/main 761904b5a):
go test -tags nogui -count=1 ./internal/agent -run Codex: ok (26s);
./internal/provider -run Codex: ok (19s); gofmt -l: none; GOOS=linux
and GOOS=windows go vet -tags nogui ./...: ok.
Full suite (go test -tags nogui -timeout 45m ./..., sandbox HOME): still
queued behind other sessions' suites at push time, pushed without
waiting per the owner's rule; a red from this change gets a follow-up,
an unrelated one an issue.

Not tried: the real Codex app through a real token refresh; the race
was reproduced with auth.json written empty / cut off by the test, and
Codex's in-place write was read from codex-rs main's source, not traced
on lucy's machine. Whether lucy's flips were this or the held-account
move (codex.out, CodexUsedUp: allowance out and no credits) isn't known
from the report; this one is the one that sticks after the account is
fine.
2026-10-25 01:49:13 +08:00
yetone 0d2a101160 gateway: the Codex app's titles, descriptions and summaries go to the magpie model picked, not ChatGPT (atom_Ray on X)
atom_Ray on X: with a third-party model picked in the Codex app through
magpie, an hour of use still took 2% of the ChatGPT account's 5-hour
window, and at 0% left it could not be used at all.

The cause is the app's hidden side turns. ChatGPT.app 26.1013.40934 asks
for a thread's title, description and one-line summary
(ThreadMetadataGenerationService.generateTitle/generateDescription/
generateSummary in .vite/build/main-CLu1A25j.js; R0/z0/B0 via H0 and Jq
in src-DsLVGakC.js) on ephemeralGenerationModel, gpt-6-luna by default,
whatever model the conversation is on. A summary is asked after each
user and assistant message (bAu in app-initial). With magpie's model
beside the ChatGPT sign-in (openai_base_url), these reach
/backend-api/codex as gpt-6-luna. codexTitlesTo and codexDescriptionsTo
left an unset setting on the model Codex asked for, and thread_summary
had no route at all, so all three went to ChatGPT on the user's sign-in.

Now, with Codex's config model one of magpie's and magpie not Codex's
provider (agent.CodexSideModel, through gateway.CodexSideModel),
codexSideTo sends titles, descriptions and summaries on the Codex
backend path to that model. On Codex's own model nothing changes, and a
model the Titles or Descriptions setting names still wins. Summaries get
the same wrapper as descriptions (codexShaped): the plain answer is
handed back as the {"summary": ...} the schema asks for, with
compactSummary filled and cut to its maxLength (summaryJSON). This also
covers a summary on magpie's own API, where a Chat model's plain answer
was dropped by the app. No prompt, instructions or base_instructions are
changed: the request is sent to another model as Codex wrote it.

Run (this change on origin/main e57e78563 for the full suite; rebased
onto 3a47e377e, which touches internal/gateway, for the packages run
again; then onto 0e643b14e, internal/sessions only, built):
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows for
  internal/gateway, internal/agent and internal/cli: clean.
- New tests: TestCodexSideTurnsOnThePickedModel,
  TestCodexSummaryOnMagpieProvider, TestSummaryJSON (gateway) and
  TestCodexSideModel (agent). Also the existing title, description and
  #540 used-up tests: ok.
- Full suite (go test -tags nogui -timeout 45m ./..., one suite on the
  machine, log tee'd): 70 packages ok, 19 without tests, no FAIL, exit 0
  (gateway 594s, agent 449s, provider 220s, cli 151s).
- Rebased onto 3a47e377e: gofmt and vet (nogui) of gateway, agent and
  cli clean; go test -tags nogui -timeout 45m of internal/gateway,
  internal/agent, internal/cli and internal/usage: all ok.
- Rebased onto 0e643b14e (internal/sessions only): go build ./... ok;
  not run again.

Broken by hand:
- codexSideTo's side-model branch turned off: TestCodexSideTurnsOn-
  ThePickedModel red (the title went to ChatGPT, 0 magpie calls).
- Both codexSummariesTo call sites turned off: TestCodexSideTurnsOn-
  ThePickedModel red on thread_summary, and
  TestCodexSummaryOnMagpieProvider red (plain text came back).
- SideModel without the !asProvider() check: TestCodexSideModel red.

Not tried: the real Codex App with a real ChatGPT account (live ~/.codex
and the running magpie were left alone), Windows and Linux. The app's
ambient suggestions (ambientSuggestionsModel), safety recourse and
commit/PR message turns are not moved; they are asked rarely or only by
user action. Not changed: what ef37b6fb7 does at 0% (Send greyed in the
app until it is reopened). On macOS magpie reopens the app once when it
is idle. On Windows and Linux it only shows a notice
(internal/gui/codex_app_out.go:78). With account discovery off,
readLogins returns nil (internal/provider/logins.go:208), so a used-up
account is never known.
2026-10-25 01:41:23 +08:00
yetone 3a47e377e0 usage: a call whose vendor counts no cache is left out of every hit rate (#3464)
#3464 (zeewell on X): Kiro caches on its side, but its replies give only
credits and a context share, never cache tokens. Every hit rate outside
the Routing page read those calls' CacheRead of 0 as a miss. A Kiro-heavy
day showed "hit rate 6%" when the counted calls hit 90%.

The plugin already says so (opencode-kiro-auth 0.1.16 sends
usage.magpie_cache_unknown), and the gateway already kept it as
RouteUsage.CacheUnknown for Routing. This carries it the rest of the way:

- gateway: Usage.cacheNotCounted() (the vendor said so and no try
  reported a cache token) goes into usage.Record.CacheUnknown on every
  path that records a call: the gateway's own record, the OTel attempt
  path in observe.go, and trace's routeUsage.
- usage: Record.CacheUnknown is kept as ledger row flag 8192
  (rowCacheUnknown; grepped, no other flag uses that bit). Totals sums
  such calls' prompt into cache_unknown and counts them in
  cache_unknown_calls. Totals.HitRate leaves that prompt out of its
  denominator, and gives no rate when nothing is left.
- Old records: calls kept before the plugin said so carry no flag. A
  Kiro call (provider kiro or kiro-plugin) with no cache counted is read
  as uncounted (usage.CountsNoCache): in the ledger's row read, in
  Totals, and for Routing's history in internal/gui/trace.go
  (cacheCounted). The rule is scoped to Kiro's two ids, so another
  vendor's 0 stays a miss (tested).
- GUI: cacheHitOf in app.js drives the tray panel's card, the Usage
  page's agent rows and cache tile, the requests' Cache hit rate card and
  each ranking row. When only uncounted calls are left it shows "—" or
  nothing instead of 0%. Otherwise it says "{n} requests left out: their
  vendor doesn't count the cache". A request row's cache cells show "—",
  and its details say the vendor doesn't count the cache. The Context
  page (context.go, context.js) shows no cache for such a call and doesn't
  score it as a miss.
- No budget raised. This adds 625 bytes to app.js (1,320,224 to
  1,320,849, under its 1,321,336); d08b6118b had already moved the
  masking page's maskWho, maskProv and stillMotion out to
  plugins/redact, which an earlier version of this change did too.
- Strings in zh, zh-TW, ja and de. docs/subsystems/provider-plugins.md
  now describes the ledger side and what is not covered.

Not covered, filed: hit rates read from the agents' own session files
(the TUI and CLI session lists, the Sessions tab's totals) still count
Kiro's 0 as a miss (#3470). Found on the way: System One's calls are
recorded without their cache tokens (#3471).

Run at this tree (on origin/main e57e78563, fetched just before; the
54-file GUI run was at a84d2ec80, and the 14 files that main's
redact page change since could reach were run again here):
- gofmt -l . prints nothing. go build ./... ok. go vet ./... ok,
  GOOS=linux go vet -tags nogui ./... ok, GOOS=windows go vet ./... ok.
- go test -count=1 -timeout 45m ./internal/usage ./internal/gui
  ./internal/gateway: all ok (gateway 388s), TestCoreScriptBudget
  included.
- GUI, 54 files (ledger-*, panel-*, i18n-*, context-*, request*,
  usage-card*, usage-ledger and the masking/redact files),
  concurrency 2: WebKit 439/452, Chromium 444/457. The new
  ledger-cache-unknown test passed in both. Again here (ledger-*,
  masking-*, redact-*, mask-*, usage-ledger): WebKit 104/117,
  Chromium 109/122, the same reds. The reds, both already
  red alone on main before this change:
  - redact-words-any-case, 10/10 in each engine (#3500)
  - usage-ledger "newest live route needs no return-to-live button",
    en and zh in each engine (#3104)
- At earlier bases, with the same change: usage-agents-hide (#3414),
  usage-checkin's WebKit Qoder tab (#3091), usage-fold (#3415),
  usage-focus-steady (#3501) were red, each red alone on main too;
  usage-card-refresh read a row before it was laid out, under load
  (#3509); context-picks (#3483) and
  context-map's tile overlap (#3488) in Chromium. Filed while doing
  this: TestUsageReadAfterAppendHashesNothingOnAFineClock goes red
  about 1 in 20 on main aa3112f4e (#3511); it passed in this run.
- Red on the old code: the new Go tests in usage, gateway and gui, and
  ledger-cache-unknown.test.cjs (the old page shows "hit rate 6%"
  where this shows 90%). Each changed piece was broken by hand and
  turned a test red. The exception is the OTel attempt path in
  observe.go, which no test reaches.

Not tried: a real Kiro account through the GUI.
2026-10-25 01:23:42 +08:00
yetone d08b6118bd agents: Restart a desktop app that started before magpie's change, after asking
微雨南山 and stones on Discord: Claude Desktop, WorkBuddy and the Codex
app read magpie's settings only as they start, so a change made in
magpie did nothing until they quit and reopened the app themselves.

The agent's row now carries a Restart when the app is installed, running,
and started before its config last changed (agent.AppBehind):
Claude Desktop, WorkBuddy and WorkBuddy AI on macOS (bundle executable
via pgrep), Claude Desktop and WorkBuddy on Windows (process tree, main =
earliest process whose parent is outside it). A press opens magpie's own
dialog first (confirmAction); Cancel and Escape send nothing. On accept
POST /api/agents/restart/{id} quits the app gracefully (AppleScript quit
on macOS; taskkill without /F on Windows, then /F /T after appCloseWait
for a tray that holds on), waits, and opens it again. On macOS an app
that won't quit is reported (StillOpen) and never forced. The Codex
app's existing Restart now asks first too. CLI agents get none.

changedAt: a stash digest that changed with no file written since the
app started now counts the change as now, so a change magpie made while
the app ran is seen (it was dated to the old write and missed).

app.js budget, not raised: archivePanel moved into plugins/usage/page.js
(its own comment called it the Usage page's; Routing's trace calls it at
draw time, after page.js has loaded), maskWho, maskProv and stillMotion
into plugins/redact, and usageHidOpen into plugins/usage. app.js is
1,108 bytes smaller than on main, budget unchanged.

Run (the first five at the pre-rebase head, same code):
- GUI agent-app-restart + agent-stale-copies: 120/0, chromium and webkit,
  en/zh/zh-TW/ja/de, window 980 and 440 and panel 440, no sideways scroll,
  no placeholder in aria-label or title.
- Broken by hand: without the confirm the GUI test is red; without the
  changedAt fix TestChangedAtWithoutAWrite is red; without the since gate
  TestWorkBuddyRestartOnMac and TestWorkBuddyRestartOnWindows are red.
- macOS, real fake-app processes in a sandbox HOME with a stubbed
  launcher: quit in 100ms and reopened; a held quit returns StillOpen
  after 4s, not forced.
- Windows box, console session (schtasks /IT), fake app and stub
  launcher: graceful close in 407ms; a tray that holds on is ended after
  5.66s; reopened through the stub.
- gofmt -l clean; go vet darwin (agent, gui), GOOS=linux and
  GOOS=windows; builds.
- At 2c5327925 (on origin/main 703437866): go test -tags nogui
  ./internal/agent ./internal/gui ok. 95 GUI files (mask, redact, usage,
  request-archive, routing-bodies, agent-app-restart, agent-stale-copies,
  i18n, insights, panel), 6 wide: 1380/53. 52 of the reds are the same
  tests red on origin/main 3b5a2f612 run alone, all filed: #3500
  (redact-words-any-case), #3414 (usage-agents-hide), #3415 (usage-fold),
  #2549/#3091 (usage-checkin Qoder tab, WebKit), #3001 (usage-ledger's
  route callback). The 53rd, usage-curve-zoom-back chromium zh-TW, passes
  alone 20/0 twice; noted on #2399.
- At the pushed head (on origin/main 20d63621d, which changed app.js,
  routing/client.js and the panel tests, not internal/agent):
  TestCoreScriptBudget (budget unchanged), go test ./internal/gui ok,
  gofmt clean, go vet gui for linux, windows and darwin. 45 GUI files
  (routing-bodies, request-archive*, panel*, agent-app-restart,
  agent-stale-copies, i18n-keys, library-mcp*, mask-actions,
  masking-records, usage-agents*, usage-ledger*): 720/28. The only reds
  are #3414's and #3001's. Then rebased on aa3112f4e (app.js's panel fit()
  only): TestCoreScriptBudget, i18n and notice tests ok; agent-app-restart,
  i18n-keys and panel-fit-tabs 54/0.
- Not run at this head: the full go test ./... and the whole GUI suite
  (the machine's disk filled mid-run once; shipped on the packages and
  files above, per ship-immediately).

Not tried: a real AppleScript quit from a GUI session (this session is
Background, so the fake was quit by SIGINT and opened by exec), the real
Claude Desktop and WorkBuddy apps (never quit the user's running apps),
Codex app and WorkBuddy AI on Windows (process names unknown, so no
button there), Linux (no desktop app of these runs there).
2026-10-25 00:30:31 +08:00
yetone 14b10f1166 library: an MCP server signed in to in Claude Code, in WSL too, says so instead of "needs sign-in" (CyberCaius on Discord)
CyberCaius signed in to a remote MCP server with Claude Code's /mcp in
WSL, and the Library still said 需要登录. The check connects as magpie,
without the agent's tokens, so an OAuth server answers it 401, and magpie
read no agent's own sign-in anywhere: not on Windows, not in a distro.

The check now reads each Claude Code target's .credentials.json, beside
the settings.json the target already has (readOwnSignIns,
mcp_agent_signin.go). A distro's Claude Code is a target under the
distro's home (wslTargetOf), so its file is read there through
\\wsl.localhost with no new setting. An mcpOAuth entry of the server's
name and URL with an access or refresh token, as Claude Code 2.1.310
counts one, names the agent in ServerHealth.AgentSignIn; the row says
"signed in in Claude Code (Ubuntu)" with the ok dot, and the tooltip says
magpie can't list its tools without signing in itself. An entry without
a token, 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 tokens are
never sent or kept. A stopped distro has no target and isn't started.
On a Mac only the file is read, never the Keychain. The sign-ins are part
of the check's cache key, so a sign-in in the agent since isn't answered
from the session's earlier check. Strings in zh, zh-TW, ja and de.

Run:
- TestCheckNamesAgentsSignedInThemselves (internal/library): agent.FakeWSL
  forces the Windows+WSL switch (Ubuntu running, its home a temp root),
  sandbox HOME/USERPROFILE/XDG_CONFIG_HOME, CLAUDE_CONFIG_DIR 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): reading only this
    computer's Claude folder (claudeDir()) instead of the target's:
    "signed in in claude@wsl:Ubuntu, the check says {State:auth ...
    AgentSignIn:[]}".
  - counting an entry with no token: "a sign-in with no token counted".
  - leaving the sign-ins out of healthKey: "signed in on both sides, the
    check says ... AgentSignIn:[claude@wsl:Ubuntu]" (stale cache).
- library-mcp-health-wsl.test.cjs, chromium and webkit, en/zh/zh-TW/ja/de:
  red on the old client.js (expected "signed in in Claude Code (Ubuntu)",
  got "needs sign-in"), 12 of 12 after.
- gofmt -l (nothing); go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows for ./internal/library ./internal/gui; go build darwin,
  GOOS=windows and GOOS=linux -tags nogui ./...; go test -tags nogui
  -count=1 -timeout 45m ./internal/library ./internal/gui: ok (187s, 63s).
- GUI: library-mcp-health, library-mcp-health-wsl, mcp-signin-health,
  mcp-signin, mcp-oauth-app, library-mcp-tools, library-mcp-tool-switch,
  library-mcp-unshown, library-items, i18n-keys, gui-zh-tw, gui-ja,
  gui-de: 161 of 161 pass.
These ran first at a base before origin/main 1f589e3f4, then again at
this head (on 1f589e3f4): vet, builds, internal/library ok (149s), the 13
GUI files 161 of 161. internal/gui is red at this head on
TestCoreScriptBudget alone: app.js is 1321476 bytes, over 1321336. It is
the same on origin/main 1f589e3f4, from 2a8a17746 (this change doesn't
touch app.js, and its size is main's); #3367. The budget isn't raised.

Claude Code's file format was read from its 2.1.310 binary (td's key,
the token save's serverName/serverUrl/accessToken/refreshToken, $Ci's
"neither token is no sign-in").

Not tried: a real /mcp sign-in in Claude Code in WSL on the Windows box
(ssh to 10.0.0.132 timed out), and the full ./... suite. Not covered:
Codex's own MCP sign-ins (keyring, or a .credentials.json fallback whose
format wasn't checked against its source), #3508.
2026-10-25 00:03:52 +08:00
yetone 3b5a2f612d dsh: Max reaches GLM-5.3 as max, asked adaptively with its level
01huadalang on Discord (10-24): DSH Desktop on magpie-anthropic, zcode
GLM-5.3 at Max; magpie's Routing log showed 77 of 78 requests at low,
one at high, never max.

What DSH sends, from the real app (DSH Desktop 0.2.1-rc.3's app.asar,
pi-ai 1.1.0 and dsh-llm-pi-ai, run read-only through node with
magpie's GLM-5.3 entry): at Max and at High alike, max_tokens 128000
and thinking enabled, budget_tokens 16384. pi-ai's clampReasoning turns
xhigh and max into high before thinkingBudgetForLevel, so no
thinkingBudgets setting can give Max a budget of its own. At Low it
sends 2048; with reasoning off, no thinking field.

What magpie did with it: 16384 is read as high (effortOfBudget) and
sent as output_config.effort high, so Max could never reach max. The
"low" rows were not reproduced: no request DSH builds at Max reads as
low here, and Z.ai refused none of the shapes (live, below), so no
refusal memory lowered it. A 2048 budget (a session or a subagent DSH
runs at Low; dsh-tool-subagent lets the model pick reasoning_effort)
reads as low, and that is the likeliest source. It is asked of the
reporter.

The fix, zero-config: Z.ai's GLM-5.2 and GLM-5.3 (the GLM half of
effortInOutputConfig) are written into dsh's magpie-anthropic route
with compat.forceAdaptiveThinking (gateway.AdaptiveWithEffort, beside
AdaptiveThinking). MiniMax-M3.1-Flash, the other half, is left on its
budget: adaptive wasn't tried on MiniMax (no key), so it is on #3496. pi-ai then sends thinking adaptive and
output_config.effort from magpie's thinkingLevelMap, max as max
(checked against the real asar: low/high/max each go as themselves).
The gateway already passes adaptive thinking with output_config.effort
through for these models (fitted to their levels, withOutputEffort;
TestGLMEffortInOutputConfig pins it), so the gateway only gains
AdaptiveWithEffort. No client name is keyed on, and a budget alone is
read as before. An adaptive-to-budget rewrite in withOutputEffort was
tried first and dropped: TestGLMEffortInOutputConfig pins adaptive
passing through, and Z.ai takes it.

Live, Z.ai GLM-5.3 with the zcode key (sandbox script, key never
printed): adaptive and enabled+effort both accepted; effort max
thought 1237-1427 chars against 426 at high, so max is a real tier.

Run, at this head rebased on origin/main 3be1f14eb (head 7ae044226):
- go build ./...; go vet of gateway and agent for darwin, linux and
  windows; gofmt -l clean.
- go test ./internal/gateway/ ./internal/agent/ ./internal/plugin/
  -timeout 45m at this head: ok (655s, 469s, 187s)
  (an earlier run, with the dropped rewrite, was red on
  TestGLMEffortInOutputConfig only, which led to dropping it).
- Own GOCACHE: the shared one had files trimmed mid-build by another
  run (vet "could not import sort").
- A first run hit "no space left on device" from another session's
  disk use (18G free after); rerun in full.
Broken by hand: with dshKindConfig back on AdaptiveThinking alone,
TestDshMaxReachesOutputEffortModels is red for GLM-5.3 and GLM-5.2. TestAdaptiveOnOutputEffortModelAsksItsLevel (the
gateway end, through a fake zcode plugin) passes on the old gateway
too: it holds that DSH's new shape reaches the vendor and the Routing
log as max, not a gateway change.
Not tried: DSH Desktop itself against this build (the app isn't
installed here; its pi-ai was run from the asar instead); MiniMax with
adaptive (left out, #3496); the whole go test ./... and GUI suite (no GUI change).
Siblings left alone, filed as #3496: Pi and omp hit the same pi-ai
clamp, MiniMax-M3.1-Flash above, and dsh to a DeepSeek model on DeepSeek's host (#3298) still
goes as a 16384 budget, since dsh's compat is per model id.
2026-10-24 23:27:25 +08:00
yetone 40b5c2daf0 agent: say why Claude Desktop's 3p mode can't keep a Chinese language (Dx25 on Discord)
Dx25 (Windows) set Chinese and found %LOCALAPPDATA%\Claude-3p\config.json
back at "locale": "en-US" after every Desktop start. magpie doesn't write
it: config.json is touched only by desktopCarryLocale, at switch-on, and
only when it has no "locale" (TestClaudeDesktopKeepsThe3pLanguage,
TestClaudeDesktopUserEditsThenReapply). Desktop writes it.

Read from Desktop 3.6556.2's bundle (current RELEASES.json, 10-22): in 3p
mode the window is the bundled UI, Resources/ion-dist, with 11 catalogs
(en-US de-DE fr-FR ko-KR ja-JP es-419 es-ES it-IT hi-IN pt-BR id-ID) and
no Chinese; its locale is its localStorage, else navigator.languages
mapped onto those 11, else en-US. On mount it calls
electronIntl.requestLocaleChange(its locale), and the main process's
handler writes that value with store.set("locale", ...). The main process
has zh-Hans and zh-Hant catalogs (for the signed-in window), but the 3p
window asks for en-US on every start, so a Chinese locale, carried or
set by hand, is replaced each time. 2.7032 (this Mac) and 2.9939.2 (the
Windows box) have the same 11 in ion-dist. Nothing magpie can write
keeps Chinese in 3p mode; it is Desktop's missing translation.

This commit changes no behaviour: desktopCarryLocale's comment and
docs/subsystems/agent-wiring.md now say the above, where they implied the
carry kept a Chinese language.

Run at 3be1f14eb + this change: gofmt -l clean; go vet ./internal/agent
(darwin), GOOS=linux go vet -tags nogui and GOOS=windows go vet of it ok;
go test -run 'TestClaudeDesktop(CarriesTheLanguage|KeepsThe3pLanguage|
UserEditsThenReapply|LanguageOddValues)' ./internal/agent ok. Comment and
doc only, so no full suite.

Not tried: starting a real Desktop in 3p mode (no sandbox for its
userData on macOS); the mechanism is from its shipped code. The Windows
box's live Claude-3p/config.json holds "locale": "en-US", read only.
2026-10-24 23:17:04 +08:00
yetone 1184862583 agent: Codex background compaction writes the bare async_compaction = true where a Codex older than 0.163 reads the config (多喝热水)
多喝热水 (Discord #help, Windows, v0.1.1384, Codex desktop with ChatGPT
sign-in): Codex wouldn't open, "config.toml:154:1: invalid type: map,
expected a boolean". That line is the [features.async_compaction] table
1978eabe5 (#2490/#2493) writes.

Codex versions, from codex-rs source and the real binaries:
- up to 0.163.0-alpha.5 (0.160.0, 0.162.1 included) FeaturesToml is a
  flattened BTreeMap<String, bool>: any table under [features] fails the
  whole config; an unknown bool key is only a warning.
- from 0.163.0-alpha.8, async_compaction is FeatureToml<…>, bool or
  table, and model_async_compact_threshold_percent is read only from the
  table (the bool gives Codex's default 65).
- the provider table's capabilities = {...} is safe: 0.161 and older
  ignore unknown provider keys (schemars-only deny_unknown_fields),
  0.162 parses it. 0.160.0 and 0.162.1 load a config holding it.
- ChatGPT.app 26.1013.40934 bundles Codex 0.163.0-alpha.10.2
  (Contents/Resources/codex-cli/codex-package.json); the reporter's
  Windows app rejects the table, so it bundles one before alpha.8.

Fix: the table is written only when every Codex found here that reads
this config (the CLI on PATH, the desktop app's bundled codex on macOS,
the Store app on Windows, the editor extension, Codex in WSL) has a
version at or after 0.163.0-alpha.8. Otherwise, or when a version can't
be read (the Windows app, the extension), magpie writes the bare
[features] async_compaction = true with no share. A table magpie wrote
before is taken back through its stash (only the keys the stash names
as magpie's; an emptied table goes), so a config already broken opens
again on the next sync. A table or bool the user wrote stays. The stash
records a bool it wrote (`bool`), and the table comes back once every
reader is new enough. Settings' state carries codexAsyncHeld, and the
Codex row says which Codex holds the share back and that it needs
0.163. The note costs app.js 390 bytes; its budget and the core's are
raised by exactly that, the agent's own row in the core.

Run:
- real binaries, sandbox CODEX_HOME/HOME, `codex features list` on the
  config magpie writes (TestCodexAsyncConfigLoadsInRealCodex,
  MAGPIE_TEST_CODEX_BINS): 0.162.1, 0.163.0-alpha.8 and 0.164.0 load it;
  alpha.8 and 0.164.0 report async_compaction true. By hand before the
  fix: 0.160.0 and 0.162.1 exit 1 on the table ("invalid type: map,
  expected a boolean"), load the bool and nothing; alpha.8 and 0.164.0
  load all three.
- broken by hand (table always allowed): the real-binary test is red
  for 0.162.1 with Codex's own error, OldCodexGetsTheBareKey red in all
  four cases, TableTakenBackForOldCodex red ("magpie's table not
  mended"). Green again with the fix.
- go test -tags nogui ./internal/agent ./internal/gui ./internal/edit
  ./internal/settings: ok (gui after the budget, re-run alone: ok).
- GUI (node --test, chromium + webkit): codex-async-compact,
  agent-prefs, settings-general, segs-glide, i18n-keys: 100 pass, 0 fail.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...; go build for darwin, linux (nogui),
  windows: ok.

Not tried: the Windows box (Store-app detection, reading its bundled
codex's version, a non-Store install), a WSL distro, a real Codex run
past the share, the whole GUI suite. The full go test ./... is queued
behind other sessions' suites (one per machine) and wasn't waited for.
2026-10-24 22:02:49 +08:00
JoeyWu-tech 93435f27dc docs: the partner list is fetched on a process's first ask and hourly, and by the gateway's magpie unasked (#3362)
providers-accounts.md still said the list is fetched every 6 hours.
97902e93 made it a process's first ask and hourly after
(partnerEvery = time.Hour), and 7e0c0310 has the magpie serving the
gateway fetch it when it starts and whenever it is due, asked for or not
(KeepPartnersFresh).

Left out of this landing: the author's same fix to the privacy pages
(site/public/docs/privacy.html, zh/, ja/). A community change to site/
waits for the maintainer to look (docs/contributors.md); they stay on
JoeyWu-tech's branch, commit e46eee4b2, for that.

Landed by review from JoeyWu-tech's branch (posted on #3362 as
Coffemon's). The run record is in the stack's last commit.
2026-10-24 21:33:06 +08:00
JoeyWu-tech b18a6a080b gateway, cli: magpie goroutines writes the running magpie's goroutine stacks to a file (#3362)
#3362's second ask: an app stuck at something could only be read by
killing it, which ends what was stuck. magpie heap and magpie cpu
already ask the running gateway for a profile over loopback; magpie
goroutines asks it for every goroutine's stack. That works on Windows
too, where there is no SIGUSR1.

GET /v1/magpie/goroutines (goroutines.go) answers the callers
/v1/magpie/heap answers (profileRefused: a program on this computer
over loopback, no browser mark, a loopback Host; a gateway key lets
nothing else in) with runtime/pprof's goroutine profile at debug=2,
the form a crash prints: each goroutine's state and wait ("[select,
4320 minutes]"), its frames with source lines, and who started it. It
is text/plain and no-store, and X-Magpie-Goroutine-Stats names the
process (pid, program, version, window, uptime, goroutine count).
Arguments are words in hex, never what they point at, so the dump
holds no keys, prompts or messages; it does name magpie's source files
and the program's path, which the usage says.

magpie goroutines [<file>] writes it to <file>, else
magpie-goroutines-<date>-<time>.txt in this folder, 0600 and never over
a file there, then prints the file and the process. --help, -h and help
print the usage and ask nothing; a flag it doesn't take, "-", a blank
name or a second file are refused before the gateway is asked. A
magpie older than this one answers 404 and is told to update; with
none answering, it says so.

The refused callers TestHeapProfileOnlyToThisComputer listed move into
profileCallersRefused, which the CPU test and the new one share.

Run on b437e4ad, go1.26.8. internal/gateway and internal/cli are the
same here and at the branch's head (tree 613df3a9), where the checks of
them ran:
- gofmt -l and go vet as in the commit before: clean.
- go test ./internal/gateway -run 'Goroutine|Heap|CPU|Profile': ok;
  ./internal/cli -run 'Goroutines|Heap|CPU|Help': ok.
- Broken by hand: goroutinesRefused letting every caller in makes
  TestGoroutineDumpOnlyToThisComputer red ("Origin null with a key":
  200); debug=1 for 2 makes it red (the parked goroutine isn't in the
  dump); without the route it is red (404), and so is
  TestGoroutinesWritesTheRunningGatewaysDump ("older than this one").
  Restored, green.
- Full suite at this commit, go test -tags nogui -count=1 -timeout 45m
  ./... (tree e5cf04af, 498s): 62 packages ok. 14 reds in 7 packages,
  none in a file this commit touches, each red on b437e4ad without it:
    internal/agent TestInstalledVersion, TestOmpDetectedWithPiDir,
    TestCursorFolderFromTheEditorIsNotTheCLI and TestZedAppPath:
    proc.Look keeps "not found" for a tool written in the tick of its
    folder's last change (#3141).
    internal/agent TestCodexDriftReached: Drift answers from the read of
    Codex's log taken before the test's last insert (#3398).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: a real stuck app; magpie goroutines against the app on macOS
or Windows (the tests serve gateway.New().Handler() on loopback).
2026-10-24 21:33:06 +08:00
JoeyWu-tech a2cef8bf4f provider: partners.json keeps when the list was last tried and how it ended (#3362)
"partners":null} for three days, and nothing told a fetch that failed
every time from one that never came back, or from none being asked. A
failed fetch wrote nothing and logged nothing.

refreshPartners now keeps two fields with the list:
- tried: when the last fetch started, written before it is sent;
- error: how it failed (whitespace folded, cut at 500 runes), cleared
  when the next one starts.
Read together: error set, the last try failed; tried after at with no
error, a try is still out; tried long ago, nothing has asked since. A
failure is logged once until its error changes or a fetch gets the list
again, and the fetch that gets it after a failure is logged too. The
desktop app's log goes nowhere a user can read, so for the app the file
is what tells.

Checked for #3362 on the way: v0.1.1296's fetch, keep and save, given
the bytes /api/partners serves now (Kimi Code, listed from 10-23 00:00
+08:00) over the 10-20 file, writes the file, with the icon fetched or
not. So it isn't the save or the list.

Run on b437e4ad, go1.26.8. internal/provider is the same here and at
the branch's head (tree 613df3a9), where the checks of it ran:
- gofmt -l clean; go vet -tags nogui of internal/provider, gateway, cli
  and the root package with GOOS=linux, darwin and windows: clean.
- go test ./internal/provider -run Partner -count=1: ok.
- go test ./internal/provider -run '^TestPartners' -race -count=20: ok.
- TestPartnersKeepTheirLastTry on b437e4ad's partners.go: red at
  partners_test.go:511 (after a 503 there is no partners.json at all).
- Broken by hand, each red in TestPartnersKeepTheirLastTry: no write
  before the fetch (line 535: a try out shows no try since the last);
  the error not cleared when a try starts (535: a try out still shows
  the last error); the failure logged on every try (518: "logged 3
  times, want once"). Restored, green.
- Full suite at this commit, go test -tags nogui -count=1 -timeout 45m
  ./... (tree a661f529, 482s): 62 packages ok. 15 reds in 7 packages,
  none in a file this commit touches, each red on b437e4ad without it:
    internal/agent TestInstalledVersion, TestHowInstalled,
    TestOmpDetectedWithPiDir, TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI and TestZedAppPath:
    proc.Look keeps "not found" for a tool written in the tick of its
    folder's last change (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: a real app left running against usemagpie.ai, on macOS or
Windows.
2026-10-24 21:33:06 +08:00
JoeyWu-tech f252b403d3 provider: the icon prune leaves a listed partner's logo, so the add sheet keeps drawing it (#3424)
partnerIcon keeps a partner's logo in the icons folder beside
providers.json and, while its iconUrl stays the same, uses the file it
kept as it is (97902e93), so the file only ages. No provider points at
it until one is added from the partner, and pruneIcons, after every
save of providers.json, removes a picture no provider or plugin names
once it is an hour old. A logo kept from an earlier day is that old at
once, so the first save after a start (a key, a model picked, an order,
a sign-in, a sync's pull) took it: /api/icons/<name> answered 404 while
the partner still named file:<name>, the add sheet's img fell back to
the generic icon, and the next fetch, finding the file gone, downloaded
it again, for a save an hour on to take. Before 97902e93 every fetch
downloaded it again, six hours apart, and a save an hour after each
took it the same way.

Now pruneIcons also leaves the pictures of the partners listed now
(keptPartnerIcons), as it leaves a plugin's (keptPluginIcons). A
process that hasn't asked for the list reads it from partners.json, as
Partners does, so a save from the CLI leaves them too. A partner no
longer listed loses its logo at the next prune unless a provider added
from it names it, as before. With the list off (MAGPIE_PARTNERS=off,
and every test that names no list) nothing is kept for it.

Lock order: store, then pruneIcons, then partnerMu. Nothing under
partnerMu saves providers.json or takes a lock store holds, and no
fetch runs under it.

Old data: a logo pruned before this is fetched again by the list's next
fetch (at start, then hourly), as it was; nothing to move.

What was run (tree 0409d43e, on a93190ae, go1.26.8):
  broken by hand, with this change: pruneIcons without the
  keptPartnerIcons loop:
    partners_test.go:489: the listed partner's logo was pruned: stat
    .../icons/d1774929a9b62027.png: no such file or directory
    partners_test.go:496: the logo was downloaded 2 times, want once
  a real run: magpie web in a sandbox HOME with the real list
  (usemagpie.ai/api/partners, Kimi Code) and stats off. A first start
  kept Kimi Code's logo; its file was set two hours back, as one kept
  from an earlier day is; a second start's fetch used it as it was;
  then magpie provider add Local url=http://127.0.0.1:9/v1 saved
  providers.json:
    main (a93190ae): the file gone, GET /api/icons/<name> 404,
    /api/providers still naming file:<name>, and a new Chromium drew
    Kimi Code in the add sheet with the generic icon
    this change: the file kept, 200, and the add sheet drew the logo
    (128 px wide)
  gofmt -l internal/provider: nothing
  GOOS=linux, darwin, windows go vet -tags nogui ./internal/provider:
  exit 0; CGO_ENABLED=0 GOOS=darwin and windows go build -tags nogui
  .: exit 0
  full suite, go test -tags nogui -count=1 -timeout 45m ./...: a first
  run stalled, the test binaries of 14 packages sitting in close(2) for
  45 minutes until the timeout (internal/provider ok); run again with
  nothing changed (445 s): 62 packages ok, internal/provider among them.
  13 tests red in 8 packages, none in a file this change touches:
    internal/agent TestInstalledVersion, TestOmpDetectedWithPiDir and
    TestZedAppPath: proc.Look keeps "not found" for a tool written in
    the tick of its folder's last change (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
    internal/middleware TestFailOpen: "spin took 1.508697807s", past
    its 1 s bound under the run's load; alone, -count=10: ok.
Not tried: the desktop app's webview (a browser that drew the logo
before keeps drawing it from its cache, since /api/icons answers
immutable for a year), macOS, Windows.
2026-10-24 21:33:06 +08:00
JoeyWu-tech ba4b754b22 gateway: a relayed Chat stream's tool call with no index is given its call's (#3386)
xianfeng-zhu (#3386): Cursor's Private Inference on magpie's
/v1/chat/completions, a Gemini model behind it, failed every turn that
made a tool call with AI_TypeValidationError at
choices[0].delta.tool_calls[0].index ("expected number, received
undefined"), then a 499 loop; turns without tools went fine. Gemini's
OpenAI-compatible API sends its calls with no index (Linka's frames in
gemini_compat_cut_test.go have none either), where the OpenAI contract
has one on every fragment, and a relayed stream went on without one.
The AI SDK's OpenAI provider, which the report names as what Cursor
reads Chat with, checks every chunk and turns that one away, so the call
is never made. OpenAI's own node SDK, through its stream helper, keeps
no call at all.

chatTidy, which already mends a relayed Chat stream's empty ids, empty
names and "stop" after calls, now gives a fragment with no index (none,
or null) the index of its call (streamCallIndexes.give). A fragment with
an id other than the open call's, or after the first in its delta,
starts the next call, as chatDecoder reads a new id; any other goes on
with the open one. So two calls in chunks of their own are 0 and 1.
Given both 0, as their place in the delta would give them, OpenAI's
node SDK merged them into one call with both arguments run together. A
fragment with an index keeps it, and a stream whose calls have theirs
goes as it came. It runs before the ids are mended, so a call with no id
either (#3386's chunk) gets both.

Not changed: the translations write an index already (chatEncoder,
chatWholeEvents), and a whole reply's message needs none. Nor is a call
given a type: Gemini's frames have "type": "function". The report's
chunk has neither an id nor a type, and is taken as cut short: magpie
gives a call with no id one (#2611, v0.1.1277), so the chunk it sent
would have had one.

What was run (tree e6023c66, on a93190ae, go1.26.8):
  a real run: magpie built at a93190ae and at this commit (go build
  -tags nogui), magpie serve in a sandbox HOME, its provider's Chat URL
  a local server replaying Linka's frames (the call, its signature and
  the usage in one chunk, then "stop", then [DONE]) under
  gemini-4-argon, so the Gemini paths run as for Google's host
  (geminiCompat). Clients on magpie's /v1/chat/completions, with the
  tool codemode:
    curl, the chunk magpie sends on: main, the call with no index; this
    change, index 0 (0 and 1 with the second call below)
    @ai-sdk/openai 2.0.136 (ai 5.0.281), streamText:
      main: AI_TypeValidationError, path choices, 0, delta, tool_calls,
      0, index, "Invalid input: expected number, received undefined";
      no tool-call
      this change: tool-call codemode {"code":"run()"}, finish
      tool-calls
    @ai-sdk/openai 2.0.48 and 2.0.122, older releases that turn away a
    new call with no id (2.0.48 one with no type too): main, the same
    validation error; this change, the call
    openai 5.23.2, chat.completions.stream and finalChatCompletion:
      main: no tool_calls (finish_reason tool_calls)
      this change: call_1 codemode {"code":"run()"}
    @ai-sdk/openai-compatible 1.0.59, which gives a missing index the
    call's place in its delta: the call, on main and with this change
    with a second call in a chunk of its own (made up from Linka's
    frame, id call_2):
      @ai-sdk/openai 2.0.48, 2.0.122 and 2.0.136: main, the validation
      error for each; this change, both calls
      openai: main, no tool_calls; this change, call_1 {"code":"run()"}
      and call_2 {"code":"two()"}
      @ai-sdk/openai-compatible: both calls, on main and with this
      change
    the replay sending both calls at index 0, as their place in the
    delta would give them: openai keeps one call, id call_2, arguments
    {"code":"run()"}{"code":"two()"}, on main and with this change,
    which keeps an index the upstream sent
    #3386's chunk as the report shows it, the call with no id and no
    type: this change sends it on with index 0 and an id (#2611's);
    @ai-sdk/openai 2.0.122 and 2.0.136 make the call, 2.0.48 throws
    "Expected 'function' type." and openai "tool call snapshot missing
    `type`"
    two such calls, each in a chunk of its own: nothing tells them
    apart, here as in chatDecoder, so both go with index 0 (the second
    is given its id after, where its signature is carried);
    @ai-sdk/openai 2.0.136 makes both calls, 2.0.122 the first only,
    2.0.48 and openai throw as above
  broken by hand, with this change: chatTidy without the give step:
    TestChatTidyGivesCallsAnIndex: no line's calls have an index
    ("line 4: indexes [[-1 -1]], want [[1 2]]")
    TestGeminiCompatRelayedCallsHaveAnIndex: every case, "call 0 went
    with index <nil>, want 0"
  go test -race -count=20 -cpu 1,2 of those two, TestChatTidy* and
  TestStreamedCallGivenAnID: ok
  gofmt -l internal/gateway: nothing; GOOS=linux, darwin, windows go vet
  -tags nogui ./internal/gateway: exit 0; CGO_ENABLED=0 GOOS=darwin and
  windows go build -tags nogui .: exit 0
  full suite, go test -tags nogui -count=1 -timeout 45m ./... (475 s):
  63 packages ok. 14 tests red in 7 packages, none in a file this
  change touches:
    internal/agent TestHowInstalled, TestOmpDetectedWithPiDir,
    TestZedAppPath, TestCopilotFolderFromAnIDEPluginIsNotTheCLI and
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI (qoder-cn): proc.Look
    keeps "not found" for a tool written in the tick of its folder's
    last change (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress (the
    package's only red), internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: Google's own endpoint with a key (the frames are Linka's, as
the repo keeps them), Cursor itself, macOS, Windows.
2026-10-24 21:33:06 +08:00
yetone 9a2106220c gateway: a background sub-agent's notification after tool results reaches the Claude run (stones_2026 on Discord)
Claude Code 2.1.310 runs Agent sub-agents in the background by default.
When one ends while the main agent is mid-turn, Claude Code tells its
model with a <task-notification> in a {role: "system"} message after the
tool results (several that end together share one text block), or as a
text block of the results' message. On the Claude subscription path
saidWithResults drops every system message that isn't the user's own
mid-turn words (#2060, c4f4aaaa9), and agentNotice matches
<task-notification> too, so the run's Claude Code got only the tool
results. Its model never heard the sub-agent finished and kept waiting.

withTaskNotices now appends each such notification to the last tool
result inside <system-reminder>, where Claude Code itself puts one when
a notification lands in a tool result. saidWithResults strips them
first; token counts and hooks' notices are still dropped, and the
user's mid-turn words still go through as theirs. The other two shapes
already got through: a notification after the main agent's reply (a new
turn) and one inside a tool_result string (what Sonnet 4.5 gets).

Captured with a real Claude Code 2.1.310 against a local fake upstream
in a sandbox HOME (no real account): the system message after the
results, the shared text block, and the notice beside the user's
mid-turn message.

Tests (internal/gateway/claude_task_notice_test.go):
TestClaudeTaskNotificationsGoOnWithTheResults (4 cases),
TestClaudeTaskNotificationBesideTheUsersMessage (5 cases: the user's
mid-turn message and the notification in one block, in both orders, in
a system message and in a reminder after the results, with and without
Claude Code's "IMPORTANT: ... address the user's message" line),
TestWithTaskNoticesLeavesOtherResults, TestClaudeTurnToldTheTaskNotification.
Broken by hand (call site passes the bare results, no stripping): all 9
cases of the first two fail, e.g. "the run was never told SUBRESULT-A
finished: call-1 was answered \"slept\"". Stripping alone turned off:
the two user-first cases fail, the notification written to Claude Code
as the user's words.

Run at this head, rebased on origin/main 83234fe92:
- gofmt -l internal: clean; go build ./...; go vet ./internal/gateway on
  darwin, GOOS=linux and GOOS=windows: ok
- go test -race on the new tests and the #2060 mid-turn/hook tests: ok
- go test -run 'TestClaude|Context' ./internal/gateway: ok (64.5s)
- guard packages internal/proc, internal/testenv: ok
Full gateway suite (-count=1 -timeout 45m, alone on the box): ok in
819.6s at 1dd279f69 (base e219f699c), with the first version of the
BesideTheUsersMessage test; the widened test was run on its own above
(-race -count=3 too). Not run again after the rebase onto 83234fe92
(gateway/gui context parts, no overlap with this file) because three
other sessions' suites were running; CI runs it at this head.

Not tried: a real Claude account; the other candidates for the report
(a lost stream tail, concurrent streams ending together) with a
concurrent fake upstream, since the captures show content being dropped,
not a cut stream; the Windows box; go test ./... beyond gateway and the guard packages.
2026-10-24 21:29:57 +08:00
yetone e219f699ca gateway: with no S3 bucket the request archive keeps calls on this computer, oldest removed past 1 GiB (CyberCaius)
CyberCaius on Discord: "请求存档只能存在 s3 存储桶里,不能保存在本地吗". The
Usage page's Request archive switch refused without an s3:// sync. Now,
with no bucket, the same switch keeps each call in
<settings.Dir()>/request-archive/<date>/<id>.json: the same file the
bucket gets, masked the same way (Archived, archiveRequest), written to a
temporary file beside it, synced and renamed, 0600 in a 0700 folder.
Past its size (RequestArchiveLocalMB, 1 GiB unless set) the oldest calls
go first, down to a tenth under it; the call just written is never
removed, empty day folders go, and a .part file an hour old is removed
on the next scan. The running total is counted once and then added to,
so a write walks the folder only once it is over.

On by default or a switch: a switch, still off unless turned on. Bodies
can hold secrets, so nothing is written to a disk where the user didn't
ask. The local switch is its own field, RequestArchiveLocal, in KeepOwn
with its size, so sync never turns it on at another computer, and
RequestArchive synced from a computer with a bucket keeps nothing on one
without (archiveDest). The GUI switch writes RequestArchive while sync
has a bucket and RequestArchiveLocal while it has none; the tooltip names
the folder and the size, and a failed write reads "Not saved" (en, zh,
zh-TW, ja, de). GET /api/archive reads this computer's copy first, then
the bucket. The Settings page's save keeps both fields (api.go).

Docs: sync-backup.md and gui-shell.md say where the archive goes and why
the switch is per computer; the privacy pages (en, zh, ja) say what the
folder holds, that it is off by default, and how large it grows. The
READMEs' Privacy is about what is sent and is unchanged.

app.js stays under TestCoreScriptBudget (its comment was shortened, and
one t() call folded); no budget raised.

Run (worktree diff on 5222a4b12, sandbox HOME):
- go test -tags nogui -count=1 ./internal/settings/ ./internal/gui/
  ./internal/gateway/: ok (29s, 73s, 507s)
- node --test request-archive, request-archive-usage, routing-bodies,
  gui-zh-tw, gui-ja, gui-de, i18n-keys (chromium and webkit): 37/37 pass
- gofmt -l internal/: clean; go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build for darwin, linux
  (nogui), windows: ok
- TestCoreScriptBudget: ok

After rebasing onto origin/main 3840333c5: -run Budget|Archive|SaveKeeps|
RequestArchiveLocal in gui, gateway, settings ok; request-archive and
i18n-keys 8/8; gofmt clean; linux and windows vet clean.

Broken by hand, each red, then put back:
- archiveDest's local branch off: TestArchiveOnThisComputer red
- RequestArchive also writing to disk: TestArchiveNeverOnDiskUnasked red
- no pruning: TestLocalArchiveRemovesOldestPastItsSize red
- KeepOwn line removed: TestRequestArchiveLocalIsThisComputers red
- POST setting RequestArchive with no bucket:
  TestArchiveSwitchKeepsOnThisComputer red
- GET not reading the local copy: TestArchiveSwitchKeepsOnThisComputer red
- api.go not carrying the fields: TestSettingsSaveKeepsWhatItDoesNotSend red
- writing in place, not through temp+rename: TestArchiveOnThisComputer red
  (mode 0644, a .part left)

Not tried: the real app with a real agent's calls (the gateway tests
drive real requests through serve with a fake vendor); Windows' file
modes (0600 is skipped there); the full ./... suite before the push (the
machine had a queue of sessions' suites; it is queued after).
2026-10-24 21:01:18 +08:00
yetone b5d46acbed agent: Kiro Crew runs on a harness connected to magpie
Vincent on Discord asked for Kiro Crew (kirodotdev/KiroCrew v0.9.0: the
KiroCrew.app desktop app, the kirocrew CLI, its dashboard and the Gateway
on :5476). Crew has no model provider of its own. It runs each session on
an ACP harness picked by agent.acp_backend (and dispatched members by
agent.member_acp_backend) in $KIROCREW_HOME/config.json, default
~/.kiro/crew (src/kiro_crew/config/paths.py, loader.py, sections.py;
ACP_BACKENDS_MEMBER_DISPATCH in agent_sdk/backends.py).

Connecting sets those keys to an agent already connected to magpie,
tried in this order: Codex, Claude Code, OpenCode, Pi, Goose. One whose ACP
adapter is installed (codex-acp, claude-agent-acp, pi-acp) wins, so one
click is enough. magpie looks for the adapter where Crew does and installs
nothing; when it's missing, the notice gives the npm command. With no harness
connected the connect is refused with a message naming which agents to
connect. A harness set in config.local.json wins over config.json, so magpie
doesn't write it and the row says so. The previous values are stashed. On
Disconnect they are put back, but only for keys that still hold what magpie
wrote, and a file magpie created is removed once it's empty. The row reads as
connected only while its harness is still wired to magpie. deepseek is not
offered: Crew runs it as dsh --profile acp, which magpie's dsh wiring doesn't
reach. KIROCREW_HOME and the adapter path variables are read from the login
shell (agentenv).

Run (Go and the GUI files at base 137187a40, then again after the rebase onto 3d758d034):
- go test -tags nogui ./internal/agent ./internal/agentenv: ok, in a
  sandbox HOME
- gofmt -l is clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/agent/... ./internal/agentenv/...: ok
- GUI: the new agent-kiro-crew-lang.test.cjs (refusals, notice and words in
  en, zh, zh-TW, ja and de; chromium and webkit; 1100 and 420px) 22/22. The
  agent*, gui-*, i18n* and header-relang files (45), concurrency 2 at load
  ~250: 632/633. The red was agent-models-own, chromium en 420, where the dsh
  row's model click timed out at 5s (#1666, filed). After the rebase that
  file and the new one, run alone: 38/38.
- After the rebase: go build ./...; the KiroCrew, Notice, FolderVars,
  EveryPicker and ListsModels tests: ok. go test ./internal/gui: everything
  passed except TestMainWindowCorners, which was killed at its 40s
  measurement at load ~200 (#1936, #2645, both filed; this change touches
  no window code).
- No go test ./... at the pushed head before the push: the machine is at
  load 200-300, other sessions are queued for the suite lock, and ships go
  out at once (owner, 10-22). Queued to run behind them at the pushed
  head.
- Real Kiro Crew: Crew v0.9.0 was installed from source into a sandbox venv,
  and its own loader (load_config_with_content_stamp, overlay_pins) read the
  config.json magpie wrote over the real Codex wiring in a sandbox HOME:
  acp_backend='codex', member_acp_backend='codex'. With a config.local.json
  pin it reads the pinned value and overlay_pins is True. Disconnect gave the
  user's file back as it was, and removed the file magpie had created.

Broken by hand, each red:
- restore off: Connect, PicksAHarness, HarnessPick, MakesItsFile
- the pin check off: LocalPin
- adapter preference off: PicksAHarness
- the member key always written: PicksAHarness, HarnessPick
- harness wiring unchecked in on(): FollowsItsHarness, OnRealCodexWiring
- the ja translation of the pinned refusal removed: the new GUI test, ja at
  both widths

Not tried: Crew's Gateway starting a real session through codex-acp
against magpie's gateway, and none of Crew's harnesses was run under it.
Adapter paths on Windows. A user who pinned agent.model to a kiro-only
model on a non-kiro harness.
2026-10-24 20:59:25 +08:00
yetone 7765f27fcc gateway: a model an account refuses goes on to the accounts not listing it yet
01huadalang (Discord): Antigravity with several accounts, only some can
use Gemini 4. The model and its bar showed only after the right account
was made preferred and probed, and a request failed with the preferred
account's error instead of going on to the account that serves it.
st3lland (Discord): on ZCode (plugin) accounts serve different models.
Owner: no manual setting, magpie knows per account and routes.

Two causes:
- perKeyBarred puts an account whose own saved list lacks the model in
  pl.unlisted / pl.left (Unlisted) and serve never asked it. So when
  the listing accounts refused the model (Antigravity's real 404
  NOT_FOUND "Requested entity was not found.", codeAssistModelMissing;
  plugins through modelRefused's unservedWords), the agent got that
  error even though an account whose list was simply stale serves it.
  Now, once every listing account of that subscription/model has been
  asked and one refused it as unserved (unservedTry), its unlisted
  accounts are asked next, right after it and before any other member
  or fallback (unlistedNext, askUnlisted for the trace). The refusing
  try rests as before (restAfterMarked, for that model). Not for a
  pinned account, a sealed conversation or strict affinity; a gateway
  key's account list narrows unlisted too (allowedCandidates). Other
  refusals (403 PERMISSION_DENIED, 429 RESOURCE_EXHAUSTED) don't open
  the unlisted accounts.
- Antigravity's per-account lists were refreshed only on the first
  listing, a probe, a sync or a Refetch, so a model granted later and
  its bar (chosenWindows filters by exposed models) stayed hidden. Its
  quota reading already fetches fetchAvailableModels per account; now
  it saves that account's list (noteAntigravityList) and re-merges the
  pooled list from every On account's list when it changed. An Off
  account's reading changes nothing.

Other vendors: the unlisted route only opens on the existing unserved
classifiers (Antigravity's 404, plugins' unservedWords), unchanged here;
TestUnlistedAccountNotAskedForOtherRefusals holds that the other real
Antigravity bodies don't open it.

Run (at the rebased head on origin/main 5222a4b12):
- go test ./internal/gateway -run TestUnlistedAccount (4 new) and
  ./internal/provider -run 'TestAntigravityQuotaReadingListsNewModels|
  TestAntigravityModelsAcrossAccounts': ok.
- Targeted: ./internal/gateway -run 'Unlisted|Antigravity|Fallback|Refus|
  Unserved|KeyModel|Lists|Plan|Rest' and ./internal/provider -run
  'Antigravity|Google|Gemini|Pool|Lists': ok (gateway 34.9s, provider 4.5s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- Full suite: queued behind three other sessions' full runs on this
  machine (load ~300); its result goes on this commit's follow-up, not
  claimed here.
- GUI: no asset changed; none run.

Broken by hand, each red, then restored:
- unlisted fallback off (false && unservedBy[key]): AskedAfterModelRefused
  404, BeforeFallback served a's fallback.
- unlisted appended after fallbacks instead of inserted: BeforeFallback red.
- key doesn't narrow unlisted: HeldFromKey got b's 200, want a's 404.
- quota reading keeps no list: QuotaReadingListsNewModels pooled list
  lacks Gemini 4.

Not tried: no real Antigravity accounts with and without Gemini 4 (the
404 body is the one on record from earlier reports); no real ZCode
"model not available" body is on record, so none was invented and ZCode
relies on modelRefused's existing words; the plugins repo is unchanged
(ZCode's models(provider,{auth}) already lists per account). Known
limit: a resting listed account that is the lone candidate is still
asked first on later turns until the unlisted account's list refreshes
at its next quota reading, one extra request a turn.
2026-10-24 20:32:33 +08:00
yetone 31275d0734 gateway: a history call to a tool the request doesn't declare gets a stub where it is refused (pi, T3 Code tool_search)
Gearclickist on Discord: pi and T3 Code, on magpie's /v1 chat/completions,
load tools on demand. The tools a tool_search found are called in the
history but not declared in the next request's tools, and pi sends
"tools": [] with history calls when it has no tools left.

Cause, per upstream (magpie forwarded the calls unchanged on every path,
seen in a probe through fakes):
- Anthropic Messages (API, Bedrock/Vertex Claude, relays): a call to a
  tool it isn't given is accepted, but calls with no tools at all get
  400 "Requests which include tool_use or tool_result blocks must
  define tools". anthropicBody dropped tools when the request had none,
  so pi's tools: [] turn failed. Now each tool the history called is
  declared as a stub (any object, "Called earlier in this conversation;
  not available now.") with tool_choice none, as LiteLLM's dummy tool
  and the Kiro plugin do.
- OpenAI Chat/Responses, ChatGPT backend, Gemini/Code Assist: take the
  history as it is; left as sent (TestUndeclaredHistoryToolTakenAsSent).
- Stricter Chat/Responses/Messages upstreams (relays in front of Kiro or
  Bedrock, vendors that check each call's name): a 400/422 that names an
  undeclared history tool as not found/unknown/not defined, or says tools
  must be defined beside the calls, is asked once more with a stub per
  missing tool, relayed or translated, and remembered per provider and
  API (historyToolsRefused). tool_choice none only where the client
  offered no tools. Namespaced Responses calls are left to the namespace.
- Claude subscription: runs real Claude Code with the history as text,
  not affected. Kiro plugin already stubs its history's tools.

Run, at 54874c9ee rebased on origin/main:
- the new tests and the gateway's ToolStrict/Anthropic tests: ok
- gofmt -l: clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean (before the rebase)
- go test -tags nogui ./... -timeout 45m was running at the pre-rebase
  commit when this was pushed (ship-immediately); its result goes on the
  tag's report.

Broken by hand, each red, then restored green:
- the refusal matcher off: RefusedThenStubbed (chat, responses,
  anthropic) and ToollessHistoryRefusedOnChat red
- the remembered upfront stubs off: RefusedThenStubbed red (3 asks)
- anthropicBody's stubs off: ToollessHistoryToAnthropicDeclaresStubs red
- the stubs' tool_choice none off: same test red ("tool_choice \"\"")

Not tried: no real vendor was asked (fakes only); the refusal wordings
for stricter vendors are modelled, not captured from the reporter, who
named no upstream; the other community plugins' own translators
(Cursor, Devin, Qoder, ...) were not read for this; real pi/T3 Code not
run against this build.
2026-10-24 20:11:06 +08:00
yetone 48194bbee0 routing: an In order group's later members aren't said to go after a known allowance (bitssly on X)
bitssly on X (10-24) asked why, with a group set 按顺序 (In order), an
account whose quota isn't known "can't be used", quoting the Routing
page: "opencode:剩余额度未知,排在已知的之后。" and "腾讯-国际:剩余额度未知,
排在已知的之后。"

Cause: the gateway does what the mode says. planGroup/planLevel try an
In order group's members in the order given and never by what each has
left; each member's own accounts go as that member's provider routes
them (Smart by default, where an unknown allowance still comes before
any account at 90% or more and is tried when the known ones fail). The
explanation was wrong. weighed() gives an ordered group's rows their
member's routing (""), so the page's smart() judged each row against
every known row of the whole request: an In order group's later
members read as ranked behind a known allowance, and the first got a
Smart reason ("its allowance renews soonest ...") instead of In order.
A By weight group's first had the same fault.

Change:
- client.js: placeRouting/wholeMembers/weighedWith scope what a row is
  weighed against to its own member when the level that placed it takes
  members whole (order, weight). firstWhy says "In order: {who} is
  first ..." for such a group, and "By weight: it's {who}'s share ..."
  for a weighted one; the unknown, learns, spent and low asides are said
  only of an account weighed against another of its own member. Rebased
  onto 6d707af08 (Creat.wu, memberSplit): its member line now asks the
  scoped someKnown(x), so an unknown account alone in its member gets no
  line at all, and one beside a known account of its own member gets
  6d707af08's one line for the member.
- i18n.js: the By weight line in zh, zh-TW, ja, de.
- routing-order-unknown.test.cjs: In order, Smart and By weight groups
  over Codex (known), OpenCode Zen Free "opencode" (unknown) and two
  WorkBuddy AI accounts (one known, "腾讯-国际" unknown); chromium and
  webkit, en/zh/zh-TW/ja/de, 1100 and 420 wide.
- docs/reference.md: Smart's unknown account is still tried when the
  known ones fail; an In order group keeps its order whatever is known.

Why the quotas are unknown: OpenCode Zen Free is a free tier with no
allowance to report. Tencent Cloud Token Plan and Volcengine access-key
plans are read for the Usage page but not for routing; that class is
#3251. No plugin change.

Run:
- old client.js with the new test: red on the why line (chromium en/zh
  1100: "c@x.test goes first: of those with quota to spare, its allowance
  renews soonest ..." where "In order: c@x.test is first ..." was due).
- at the rebased head (origin/main 1f8f80e4a plus this):
  routing-order-unknown, routing-weight-member-low and i18n-* 64/64.
- go test -timeout 45m ./internal/gui/... at the rebased head: ok but
  TestMainWindowCorners (killed measuring windows at load ~80; red alone
  too; #1936, #2645, AppKit, not this change). Before the rebase: ok
  (112s).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. No Go file changed, so gofmt has nothing to check.
- whole GUI suite at ab287a839 (before the rebase), concurrency 4, load
  50 to 80: files a* to roughly o* ran; reds, all outside routing and
  filed: api-key-theme chromium system (#3307, also 1 of 3 alone),
  fonts webkit narrow (#3227), library-mcp-health-wsl ja (#3350),
  menu-input-scroll chromium en/zh (#3402). The rest of that run is void:
  my own rebase put conflict markers in client.js mid-run. The files from
  n* on are run again at the pushed head after this push.

Broken by hand: someKnown made global again (the old aside scoping):
red, the opencode aside is back under the In order group.

Not tried: the reporter's own trace and accounts (not shared); a Go
test for the gateway's order (unchanged here, covered by the existing
fallback tests); routing reading the access-key plans (#3251).
2026-10-24 19:09:41 +08:00
yetone 436bcc946d routing: a request whose vendor counts no cache tokens shows no hit rate, not 0% (zeewell on X)
zeewell on X: every Kiro request in a routing group showed cache 0%, for
claude-sonnet-5.5 and claude-opus-5.5 from Claude Code, with 148k to
182k tokens and consecutive calls.

The cause, from real Kiro calls on the owner's account (read-only, from
a sandbox): Kiro does cache. A repeated 900-line prefix cost 0.0912
credits and then 0.0484, with or without cachePoints, and with a fixed
conversationId too. But Kiro's reply holds only assistantResponseEvent,
metadataEvent {stopReason}, contextUsageEvent (a percent) and
meteringEvent (credits). There are no token counts at all, and
kiro-cli 2.32's own trace shows the same. The plugin wrote
cache_read_input_tokens: 0, which magpie showed as 0%.

opencode-kiro-auth 0.1.16 (plugins 9f6c4e8) now leaves the cache fields
out and says `magpie_cache_unknown: true`. This commit reads that field:
- aUsage reads it into Usage.cacheUnknown, ORed in Usage.add.
- routeUsage sets RouteUsage.CacheUnknown (cache_unknown, omitempty) on
  a try that counted no cache read or write.
- The Routing page's promptOf leaves such a try out of the hit rate. The
  row and its session then show no Cache metric, as for older history.

Clients are never told the field. Usage.anthropic() leaves it out, and
a passthrough forwards the plugin's bytes as they came. The gateway
already relays cache_control to an Anthropic-protocol plugin as Claude
Code sent it, so nothing was lost on the way to Kiro.

Left alone: the usage ledger. usage.Record has no such flag, so the
Usage page's aggregate hit rate still counts a Kiro prompt as a miss.
Filed as #3464.

Run at this head (rebased on origin/main 628e18987):
- gofmt -l internal/gateway internal/provider: clean.
- go vet ./internal/gateway ./internal/provider: clean on darwin, with
  GOOS=linux and with GOOS=windows.
- go test -timeout 45m ./internal/gateway ./internal/provider: ok, ok
  (465s, 126s).
- go test ./internal/gui -run Budget: ok.
- GUI: routing-request-metrics.test.cjs, chromium and webkit, en and zh:
  4 of 4 pass.
- Every routing-*.test.cjs, one base back, at load 130 to 150: the only
  reds were routing-intent-entry, routing-keys-fold and routing-manual.
  Run alone, those three files also go red on a fresh origin/main
  628e18987 worktree (8 reds there, 5 on this branch). They are already
  filed: #3408, #1612 and #3409. This change touches only promptOf's
  cache_unknown rows, which none of their fixtures have.

Broken by hand:
- With aUsage.usage() not carrying the field, TestCacheUnknownReachesTheRoute
  fails in its four Kiro cases (Claude Code whole and streamed, translated
  whole and streamed). The counted-miss case still passes, at 0%.
- With promptOf's skip removed, the GUI test fails in chromium for en and
  zh: "a vendor that counts no cache tokens has no hit rate, not 0%".

The test fixtures are the plugin's real reply bytes from Kiro, captured
10-24.

Not tried: a magpie build running the 0.1.16 plugin against Kiro from the
GUI. The plugin's own end-to-end run against Kiro gave
{"input_tokens":0,"output_tokens":19,"magpie_cache_unknown":true}.
2026-10-24 18:16:17 +08:00
yetone ef37b6fb76 gateway: an exhausted ChatGPT account no longer greys Codex app's Send while magpie can serve the turn (MasterYi on Discord)
MasterYi (#help, 1563467829687222343): with magpie wired into the Codex
app, a used-up ChatGPT account greys the Send button, so the third-party
models joined in Codex's picker can't be used either.

Cause, as far as the app's bundled code (ChatGPT.app 26.1013.40934,
read-only) shows: Send is gated in the app itself. It needs
authMethod == "chatgpt", the /wham/usage reading (fetched by the app
straight from chatgpt.com, not through magpie) saying not allowed, and
no credits. authMethod is read as the app opens or on account/updated,
which the app-server sends only on login/logout, not on a config change.
So the gate lifts only when model_provider is magpie AND the app has been
opened again. #540 already made magpie the provider while out, but only
when a magpie model was the default; on one of Codex's own models
(joined), nothing changed.

What changed:
- A (agent/codex.go Sync): joined on one of Codex's own models and the
  account out (not Always ChatGPT, not magpie API), magpie becomes the
  provider on that model as magpie serves it (codex/<model>), the model
  kept in codex.out_own. Once the account has room, Codex is put back
  joined on that model. A model picked meanwhile stays the user's. With
  no ChatGPT account in magpie to serve it, nothing changes. New
  Agent.AppOut says magpie is the provider for a used-up sign-in.
- C (provider/codex_app_out.go): a usage_limit_reached rest on the
  active Codex account (gateway routing) or an x-codex-* window heard at
  100% (NoteCodexLimits) has the account read again at once
  (CodexMayBeUsedUp: active account only, at most every 20s, only
  while a KeepOnAnAccountWithRoom loop has made its first reading and
  still runs), not only on the 5-minute look. A first cut turned this
  on for good as the loop started; every gateway test's Serve starts
  it, so later gateway tests had accounts read again behind them, and
  TestCodexOwnModelMovesToNextAccount and
  TestCodexSpentMovesToNextGroupMember went red in the package run
  (green alone 3 of 3). Now a counter, up after the first minute's
  reading, down as the loop ends; the package run is green with it.
- B (gui/codex_app_out.go): the app open when the account ran out is kept
  by its app-server's pid (provider.CodexAppOut; a new pid means it
  reopened and read the provider, standing in for "authMethod is still
  chatgpt"). On macOS, every 10s, magpie reopens it through the Agents
  row's ReopenCodexApp when: AppOut, the account still out, the app is a
  copy from before the config change, no turn in flight through the
  gateway and none ended in the last 30s. At most once per time the
  account runs out, success or not.
  Drafts: the app's code keeps composer drafts in a persisted store
  (composer-prompt-drafts-v2, 250ms debounce, flushed on quit), and
  threads are server-side, so an unsent draft and open threads should
  survive the quit. Not watched in a real app.
- D (GUI): Codex's accounts say "The Codex app can't send on {user}'s
  used-up account": on macOS that magpie reopens it once no turn runs;
  off macOS (no reopen path) or once tried, to quit and reopen it.
  en, zh, zh-TW, ja, de.

Tests (each red on the code without its part, broken by hand):
- TestCodexOwnModelGoesThroughMagpieWhileUsedUp: red at "used up" with
  the out case off, at "allowance back" with the restore off.
  TestCodexOwnModelKeptOnChatGPT: Always ChatGPT stays.
- TestCodexMayBeUsedUpReadsAtOnce: red at "a window full: not read"
  with the NoteCodexLimits hook off. TestCodexAppOutEpisode.
- TestCodexUsedUpReplyAsksAtOnce (gateway): red, asked [], with the
  routing hook off.
- TestCodexAppOutReopenedOnce (gui, reopen stubbed): red at "a turn in
  flight" with the idle check off, and at "again" with the once checks
  off.
- codex-app-out.test.cjs: 40 of 40 (chromium, webkit; 900/480; five
  languages; both texts); 2 of 2 red with the notice's call site off.

What was run, at this tree:
- gofmt -l: none. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: exit 0.
- go test -tags nogui -timeout 45m: internal/agent ok (414s, before a
  comment-only reorder in Sync); internal/gateway ok (534s),
  internal/gui ok (78s), internal/provider ok (137s), after the
  live-check fix, at this tree before the previous commit's JS-only
  move (then with a budget raise since taken back); internal/gui
  again after the move.
- GUI (chromium, webkit), at this tree: codex-app-out, codex-app-stale,
  i18n-keys, gui-de, gui-ja, gui-zh-tw and the files reaching the
  previous commit's move: 164 of 164. Before the trim, every codex-*
  and account-* file: 447 of 448; the red, codex-predictions chromium
  ja 420 "picking a model scrolled the page", is #2624 and is red alone
  on origin/main 5a85a2a91 too (1 of 2); one codex-app-out case timed
  out launching chromium at load ~100 and passed on the rerun.
- TestCoreScriptBudget with the budgets unchanged: ok. The three Codex
  notices now share one box builder (codexNote), and the previous
  commit moved ledSaid out of app.js.

Not tried:
- No real Codex app was quit or reopened (the owner's live app is left
  alone); the reopen path is stubbed. Whether the reopened app's Send
  comes back, and whether a draft survives, is from reading its code.
- No real used-up account; the move was run in a sandbox HOME.
- The full suite: no suite lock on this machine, load ~75.
- A gateway served by another magpie process: the episode lives in the
  process that serves the gateway, so a GUI that doesn't serve it never
  reopens the app or shows the notice.
2026-10-24 17:38:50 +08:00
yetone 6d707af083 routing: a member behind another by weight or order isn't told as kept for last (Creat.wu)
Creat.wu on Discord (#general, 10-24): in a group routed by weight, a
sub-group whose accounts are all near their limit "is skipped however
high its weight". The screenshot is the Routing page's line
"<account> 已用 91%,其他账号都无法响应时才用。"

Cause: the routing itself already gives such a member its share.
weightedUnits leaves a unit out of the round only when its head is
resting; Smart's 90% band orders accounts inside the sub-group and
nothing in the parent reads it. A sandbox probe with the reporter's
shape (parent weighted, group/sb:4 with two Codex accounts at 91% and
92%, a key at 1) sent 16 of 20 new conversations to the sub-group and 4
to the key. What was wrong is the explanation. On a request whose turn
went to the key, the sub-group's accounts are listed after it, and the
page's asides (client.js) said of each one "used 91%, kept for when the
others can't", which reads as the member being passed over.

Change:
- client.js: memberSplit finds where a later account parts from the
  first one in the group tree. When that level is routed by weight (the
  first has the round's turn) or by order (no affinity kept, no rule),
  a low or not-yet-known account there gets one line per member instead:
  "{member} isn't passed over for being near its limit: by weight this
  request was {first}'s share, and {member} takes its own share of the
  requests while it can answer." or "... it comes after {first} in
  {group}'s order." Spent and resting lines are unchanged, and inside a
  Smart sub-group the low line stays, since the band does order those
  accounts.
- i18n.js: both strings in zh, zh-TW, ja and de.
- weighted_low_test.go: TestWeightedGroupGivesALowGroupItsShare holds
  the share (16/4 over 20, only the account with most left inside, and
  the sub-group's accounts behind the key not resting).
- routing-weight-member-low.test.cjs: weight, inner-Smart, order and
  plain Smart scenes, chromium and webkit, every language.
- gateway-routing.md: the weighted sentence says a unit near its limit
  keeps its share, and points at memberSplit.

Siblings: Smart, usage and pace parents weigh a nested group by its
head, so a low head goes later there by design and its line stays.
Manual picks a member and sorts the rest smartly (line stays). Rotate
is account-level.

Run (worktree at origin/main 7d9165d84; rebased on c30af359b, which changes
nothing under the routing plugin, weighted.go or fallback.go, and run
again there: go test ./internal/gui (budgets) ok, the new Go test ok,
routing-weight-member-low and i18n-keys 44/44):
- the new Go test -count=3 with the weighted tests: ok
- go test ./internal/gui/...: ok (112s)
- node --test routing-*, i18n-*, group-member-weight GUI files, both
  engines, all languages, at load 40 to 110: 1227 of 1285 pass. The 58
  reds are in the rule editor and manual and steady files
  (routing-pause, -rule-effort, -rule-remove, -intent-entry, -manual,
  -steady, -time, -rules-line, -busy-frames), all click timeouts.
  busy-frames and rules-line pass when rerun one at a time. The rest are
  red the same way on a clean origin/main 5a85a2a91 worktree, and are
  filed: #3408, #3409, #3410, #3411, #3412, #3094, #3096, and #3465
  (routing-time, new). routing-weight-member-low: 40/40.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: clean; gofmt -l on the changed files: clean
- go test ./internal/gateway/... -timeout 45m: ok (408s)

Broken by hand:
- weightedUnits with `|| heads[i].p.Account != nil` added to the skip:
  the Go test is red (0 of 20 to the sub-group). Restored.
- the old client.js: the weight and order scenes are red (10 failures
  on chromium), the inner-Smart and Smart scenes stay green.

Not tried: real accounts, or the reporter's own config (not shared);
the full ./... suite (another session's full suite held the machine).
2026-10-24 17:38:26 +08:00
yetone c8901d4723 gateway: auto mode's classifier asks a model of unknown levels for no reasoning
CyberCaius on Discord (#help): in Claude Code's auto mode every
classifier request ended 499 in magpie, on a new-api relay's
gpt6.1-sol (an OpenAI-compatible provider the user added), v0.1.1364.

Cause (likely; not confirmed against the reporter's relay): Claude Code
2.1.310 sends the classifier as a non-stream sideQuery, thinking off or
left out, 64 (or 2112) tokens, and waits 60s an attempt for it (WWt in
the bundle; 120s cap on large prompts). fitAutoModeClassifier asked for
the least reasoning only when magpie knew the model's levels. For a
relay's own name it sent no reasoning_effort / reasoning.effort, so a
reasoning model reasoned at its vendor's default over the whole policy
and transcript. That ran past Claude Code's wait, and Claude Code
closed the request (499).

Change:
- automode.go: with the levels unknown, the classifier is asked for
  effort none, marked as magpie's own ask (Request.OwnEffort).
- gateway.go forwardTranslated: a 400 to that own effort
  (ownEffortRefused) is asked again. If it named the level, it is
  asked at low (offRefused). If it named the field ("Unrecognized
  request argument supplied: reasoning_effort", "Unsupported
  parameter: 'reasoning.effort'"), it is asked without the effort, as
  before. Either is remembered in unfit until restart. Only the
  classifier gets OwnEffort, and no other request changes.
- docs/subsystems/gateway-routing.md: a bullet on the local
  classifier.

Run:
- TestAutoModeClassifierReasonsLeastOnAnUnknownModel covers Chat and
  Responses, non-stream, thinking off/64 and left out/2112. It is red
  on the old code: no effort was sent in any of the four cases.
- TestAutoModeClassifierEffortRefusedGoesWithout covers a named level
  going to low, and the Chat and Responses field refusals going
  without. Each next ask takes one request.
- TestAutoModeClassifierOnlyTheClassifier now expects none for unknown
  levels (the 7a3337dd2 decision, re-derived). It still checks that a
  title ask is untouched.
- gofmt -l is clean. go vet ./... passes on darwin, GOOS=linux
  -tags nogui and GOOS=windows.
- go test -tags nogui -timeout 45m ./internal/gateway/ (sandbox HOME, this
  tree on 9d6436311): ok in 541s.

Broken by hand:
- With the refusal branch off, both field cases go red.
- With the remembered-field check off, the next ask takes 2 requests.

Not tried:
- the reporter's relay or a real reasoning model's timing. The 60s
  wait is read from Claude Code's bundle, and no fake measures time.
- Sibling side queries (agent_namer, hook_prompt,
  subagent_config_classifier, titles) that send thinking off to such a
  model still leave reasoning to the vendor. They aren't recognisable
  as the classifier is, and the main turn shares their shape.
- Responses still drops the classifier's stop sequence. Its verdict
  regex reads <block>no without it.
2026-10-24 17:25:01 +08:00
yetone 3e9efe1d51 gateway: a Codex turn chatgpt.com's WebSocket refuses as too big goes over HTTP (Lamrfu)
Lamrfu on Discord, after updating: the Codex desktop app through magpie
kept showing "正在重新连接 2/5" with
  unexpected status 502 Bad Gateway: Codex: Post ".../backend-api/codex/responses":
  codex websocket: failed to get reader: received close frame:
  status = StatusMessageTooBig and reason = ""

Cause. a2e98cd79 (v0.1.1349) sends a streamed Codex turn to chatgpt.com
over its WebSocket as one message, the whole request body. magpie's read
limit is -1, so the 1009 close came from chatgpt.com, after our message.
Codex's own client (codex-rs core/src/client.rs at openai/codex 970111f,
get_incremental_items / previous_response_id) keeps its socket and sends
each later request as a delta after previous_response_id, so its
messages stay small; it sets no outgoing size cap of its own
(responses_websocket.rs websocket_config: tungstenite defaults plus
permessage-deflate), and after its retry budget it falls back to HTTP for
the session (responses_retry.rs, try_switch_fallback_transport). Codex
speaks HTTP to magpie (magpie answers its handshake 426), so magpie gets
the whole conversation every turn and opens a socket per turn. That the
server's message size limit is what Lamrfu's long conversation passed is
likely but not confirmed: the limit isn't in codex-rs and I don't know
its value. Before this change the socket's close before the reply was a
502, and Codex retried into the same 502.

What changed (internal/gateway/codex_socket.go):
- codexSocketEnded: when the socket ends, or the message's write fails,
  before any frame of the reply was handed on (any close status, a
  dropped connection, a normal close with no reply, also after only the
  codex.rate_limits / metadata frames), the same body goes over HTTP
  (t.next), which answers as the route does. Nothing has reached the
  caller then and the backend has begun no reply. This replaces the 502
  for 1009 and its siblings (1001, 1008, 1011, 1012, 1013, 1006, 1000
  with no reply).
- codexTooBig: a 1009 records the message's size for that host; a
  message at least that big goes straight over HTTP to it for
  codexSocketShun (10 min), so a long conversation isn't uploaded twice
  each turn. Smaller turns keep the socket. Logged once per host.
- A close after the reply began is still a cut stream and is not asked
  again (no double turn).
- No Codex prompt, instructions or identity is touched.
- docs/subsystems/providers-accounts.md says the new fallback.

Tests (internal/gateway/codex_socket_test.go), fake WS server, no network:
- TestCodexSocketTooBigGoesOverHTTP: the fake's read limit closes 1009
  on a big turn; the turn is served over HTTP, a second big turn doesn't
  open a socket, a small turn still goes over the socket.
- TestCodexSocketEndedBeforeReplyGoesOverHTTP: 1009 after the message,
  1009 after the limits frames, 1011, 1012, 1013, 1008, 1001, and a
  normal close with no reply: each served over HTTP.
- TestCodexSocketTooBigMidReplyIsCut: 1009 after response.created and a
  delta is a cut stream with no HTTP post.

Broken by hand: with origin/main's codex_socket.go, TooBig and all eight
EndedBeforeReply subtests go red with 502, the first with Lamrfu's own
text ("received close frame: status = StatusMessageTooBig"). With only
the codexMessageTooBig check removed, TooBig goes red ("2 posts, 2
sockets"). MidReplyIsCut passes on both (it guards against asking twice).

Run at this head: gofmt -l (clean), go vet ./..., GOOS=linux go vet -tags
nogui ./..., GOOS=windows go vet ./..., go build; go test -run Codex
-count=1 ./internal/gateway/ in a sandbox HOME: ok (30.2s), every Codex
test in the package. Pending: go test -timeout 45m ./internal/gateway/...
is queued behind the machine's full suites and runs after this push, as
the owner's ship-at-once rule asks; its result goes on the release.

Not tried: a real chatgpt.com turn big enough to be refused 1009 (the
limit isn't known); Lamrfu hasn't confirmed yet. Not run: the full ./...
suite (only the gateway packages this touches).
2026-10-24 16:15:28 +08:00
yetone ef1a203df9 gateway: an Antigravity account out of quota rests until the reset its 429 names, not 15 minutes (Dani Ariyanto)
Dani Ariyanto (Discord #feedback, 10-24): seven Antigravity accounts,
several ticked, one First, OpenCode on Gemini 3.8 Flash. With the First
account out, requests kept going to it instead of the next account, which
had all its quota.

Cause: Antigravity's 429 for a model's quota used up says when it is back
as a Go duration: "You have exhausted your capacity on this model. Your
quota will reset after 3h19m30s." (QUOTA_EXHAUSTED; the fixture
antigravityQuota, already in the tests since ea1c5d045). Nothing read
that form. The try was failQuota and the request failed over to the next
account, but the account rested only quotaRest (15 minutes). The
per-model window fetchAvailableModels gives is the 5-hour figure, so when
the weekly pool is the one spent, no window reads full either. Every 15
minutes for hours or days, the First account was asked again, refused,
and only then passed over.

What changed:
- routing.go: quotaResetAfter reads "quota will reset after <duration>",
  and resetsAfter returns it (beside Factory's "resets in ...") when it is
  above zero and no more than longestWritten. The rest is By "resets" for
  that long. As before, pooled decides whether the account or only that
  model rests. keepRetry passes it on as Retry-After when no account is
  left.
- docs/subsystems/gateway-routing.md: a bullet on the form.

Checked and not changed:
- Failover within one request already worked. A probe with two accounts,
  OpenCode's system prompt on /v1/chat/completions, streamed and not, with
  the literal 429, had u1 fail as quota and u2 answer 200. A per-model
  window the vendor reports at 0 (remainingFraction left out) benches the
  account until that window's reset after one try.
- Routing doesn't read the pool windows from retrieveUserQuotaSummary
  (Aside). That is unchanged.

Run, in a worktree at ed91aa04e:
- TestAntigravityQuotaRestsUntilItsReset is red on the old routing.go
  ("u1 rests 14m59.98s by "quota", not the 3h19m30s its quota resets
  after") and green with the change. It also checks that the next request
  asks only u2, plus reader cases: 45m2s, 26s, 155h2m1s, past 7 days (0),
  cut short (0), and the "check quota" 429 with no time (0).
- go test ./internal/gateway -count=1 -timeout 45m: ok (598s)
- go test ./... -timeout 45m: not run before this push. Another
  session's full suite was running here; it runs after the push.
- gofmt -l clean. GOOS=linux go vet -tags nogui ./... and GOOS=windows go
  vet ./... clean.

Not tried: a real Antigravity account out of quota (none spent locally),
so the 429's words come from the existing fixture, not a fresh capture.
RetryInfo's retryDelay detail isn't read.
2026-10-24 15:31:51 +08:00
yetone 1d6b72ada8 gateway: a search magpie runs for a model cites its pages in Anthropic text blocks (H20)
H20 on Discord (#general, 10-24): a client offering web_search_20250305
to auto/deepseek-v4.1-flash or deepseek/deepseek-flash got its text
blocks back with no citations, where Anthropic's API gives
web_search_result_location entries pointing at the
web_search_tool_result pages.

magpie's web_search tool asks the model to "Cite the URLs you use", so
the answer names pages by URL. After a KSearch event (or a Search part),
the Anthropic encoder and renderAnthropic now cut the following text
into lines (citer, search_cite.go). A line naming a found page's URL
whole (urlIn: not a longer path, a query or another host; Chinese
punctuation, markdown links and bold end a URL) is its own text block
with citations {type, url, title, encrypted_index, cited_text}; the
lines between run together in one uncited block, and whitespace-only
lines are held for the next, so no block is whitespace alone (Anthropic
refuses one sent back). Streamed, a cited block's citations_delta come
before its text_delta; text is buffered to the line end, only after a
search. The text is the model's, unchanged. A reply with no search is
said exactly as before.

encrypted_index is "", as the results' encrypted_content already is:
it is Anthropic's sealed pointer, which magpie can't make (Claude Code
2.1.310 knows "invalid encrypted_index in text block" and strips these
citations when that comes back). cited_text is Hit.Cited cut to 150
characters: a search API's page text, or the cited_text of an Anthropic
searcher's own citation (searchWith now reads it), else "". No prompt
text sent upstream changed; no Codex prompt touched.

Sibling filed: Responses and Chat replies still carry no url_citation
annotations (#3455). docs/subsystems/gateway-routing.md has a new
"Citations in translated Anthropic replies" section.

Run (at c579609d9 on ed91aa04e, sandbox HOME, pinned caches):
- go test ./internal/gateway -run 'TestSearchCitedAsAnthropics|
  TestNoSearchNoCitations|TestCitesOnlyTheWholeURL|
  TestWebSearchForAModelThatCannot|TestSearchToldAsAnthropics': ok
- go test ./... -timeout 45m -count=1: exit 0, 70 packages ok,
  internal/gateway ok 647s
- gofmt -l internal/gateway: empty; go vet ./internal/gateway,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...,
  go build ./...: ok

Broken by hand: with anthropic.go put back to main,
TestSearchCitedAsAnthropics/stream and /body both FAIL ("blocks [text
server_tool_use web_search_tool_result text]": one text block, no
citations); restored, both pass. TestNoSearchNoCitations holds a reply
with no search to one uncited block, streamed and whole.

Not tried: a real DeepSeek model through a running magpie (whether it
writes the URLs the tool asks for, and how often); a real Anthropic API
taking such a reply back in history; [n] markers (a search API's
numbered pages) are not matched, since numbers repeat across searches.
2026-10-24 15:31:05 +08:00
yetone ccbbcbffcb gui: a restart to update leaves the Mac's menu bar icon for the next magpie (Mitsuha, audie)
From v0.1.1354 a restart to update hands the gateway over, and the old
magpie hides its own menu bar item with Wails' Hide, which is
[statusItem setVisible:NO]. AppKit keeps that in the app's defaults by
the item's autosave name ("NSStatusItem VisibleCC Item-0" = 0 on macOS
26), and the next item made under that name starts hidden. So after the
update the icon was gone, and quitting and reopening didn't bring it
back (Mitsuha on v0.1.1364; audie on two Macs, macOS 27.0.1).

Evidence: a 30-line Cocoa probe made a status item, setVisible:NO, and
every later launch of the same program started with visible=0 and the
key = 0; removeStatusItem kept nothing; removing the key brought it back
on the next launch. This machine's com.yetone.magpie.sbhandover.plist
(the handover commit's own sandbox run) holds
"NSStatusItem VisibleCC Item-0" => false.

Fix (internal/gui/trayshown_darwin.go, app.go):
- leaveMenuBar (was the onHandedOver closure) queues forgetTrayHidden
  on the main thread after Wails' hide block, so the hide is made on
  screen but not kept.
- bringTrayBack, once per computer (a flag in the Mac's defaults, never
  in a WebDAV backup), forgets a kept hide before the tray is made: that
  repairs everyone an older magpie already hit. A hide kept after that
  is the user's and is left alone.
- A magpie handed over to by an older one (which still hides for good)
  forgets the hide once that pid has quit and shows its item, unless a
  hide was already kept when it started.
docs/subsystems/gui-shell.md says so under the handover.

Run (worktree at origin/main ed91aa04e):
- TestHandoverLeavesTheMenuBarIconForTheNextMagpie (AppKit child with a
  real Wails tray, CFFIXED_USER_HOME sandbox): ok, -count=3.
- Broken by hand: leaveMenuBar without forgetTrayHiddenLater -> "handing
  over kept the menu bar icon hidden for the next magpie (1 kept)";
  bringTrayBack without forgetTrayHidden -> "the icon an older magpie hid
  wasn't brought back (still hidden true, 1 kept)".
- go test ./internal/gui/ -count=1: ok 86.7s; go test -tags nogui
  ./internal/gui/: ok 67.2s.
- gofmt -l: nothing. go vet ./internal/gui/ (darwin), GOOS=linux go vet
  -tags nogui, GOOS=windows go vet: ok. go build, GOOS=linux go build
  -tags nogui, GOOS=windows go build: ok.
- No GUI asset changed, so no Playwright run.

Not tried: a real signed update from v0.1.1367 to this build on the
user's bundle id; whether Control Center hides the new version's running
item live when the old one writes the key (the probe's running item kept
visible=1; the on-screen window list needs screen recording rights). Not
run: the full go test ./... (one package touched; other sessions are
queued for the suite). audie's WebDAV sync carries no tray setting and
doesn't restart magpie; the icon going there is taken to be the same
update's restart, not confirmed with them.
2026-10-24 15:20:37 +08:00
yetone ed91aa04ef checkin: an inactive or ineligible check-in shows the plugin's reason (plugins#304)
Qoder's plugin 0.2.32 (magpie-community/plugins 74be632) says why no
check-in was offered: it asked with this machine's own device identity
and Qoder offered no campaign, and Qoder desktop can claim one it shows.
magpie dropped a hook's message for inactive and ineligible and showed
only "No check-in event now". Now:

- GUI: the Usage card's row reads "<label> · <message>", wrapped under
  the label rather than cut off with "…" (data-why, as a failed row's
  reason wraps, #821); Settings' check-in line under the plugin's switch
  carries it too. A result without a message reads as before. No new
  i18n keys: the message is the plugin's own text, as for failed rows.
- TUI: the Usage cell is too narrow, so it adds "c says why"; c's flash
  carries the message (checkinWhy).
- CLI: `magpie accounts checkin` prints it after the label.
- The Qoder mover's min is 0.2.32 (npm view --prefer-online: 0.2.32).
- docs/subsystems/provider-plugins.md says how the message is shown.

Run at this tree (based on origin/main dd1e8822d):
- go test -timeout 45m ./... (tee'd, grepped): every package ok
  but internal/handoff, whose TestTakeOnlyAFreshOfferForThisProgram
  could not bind a unix socket under my long scratch TMPDIR (path over
  104 bytes); with the default TMPDIR internal/handoff is ok.
- gofmt -l: clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
- GUI, chromium and webkit: checkin-reason (new: en, zh, zh-TW, ja, de;
  900 and 440px), plugin-checkin, qoder-checkin-recheck, usage-checkin,
  checkin-account, checkin-early-done, usage-quota-head, i18n-keys:
  155/157. The 2 reds are usage-checkin's "webkit en/zh: Settings has a
  Qoder check-in tab", red the same on a fresh origin/main a9a001a7a
  (#2549, #3091).
- TestCoreScriptBudget: app.js 1,343,313 of 1,343,324, no raise.

Rebased on origin/main 4683a0382 (a9a001a7a's app.js line, 4683a0382's
provider change) and run again at this head: internal/gui (budget:
1,343,323 of 1,343,324), internal/cli, internal/tui and the whole
internal/provider ok; the same 8 GUI files in both engines, 155/157,
the same two #2549/#3091 reds.

Broken by hand: app.js's change reverted, checkin-reason goes red on the
reason; app.css's reverted, red on the wrap; checkinWhy returning "" in
internal/cli and internal/tui, TestCheckinSaysWhyNoneWasOffered red in
each.

Not tried: a real Qoder account offered no campaign (the fixture is the
plugin's own text); the real Linux app (WebKitGTK).
2026-10-24 14:52:13 +08:00
yetone a3b45eb91e provider: a re: pattern matches in any case, as a glob does (usrname1833 on Discord)
A routing group's patterns (Group.Match) and a provider's auto-include
rules both compile through compilePattern. A glob compiled with (?i)
and a re: pattern without it, so re:gpt-.* missed GPT-5.5 while gpt-*
took it. A re: pattern now compiles as (?i)^(?:…)$; (?-i) inside it
makes case matter again from there on (re:(?-i)gpt-.*).

The Routing page's editor works out a pattern's models in JS
(patternRe in plugins/routing/client.js) and refused what JS can't
read. It now reads re: with the i flag too, and takes Go's leading
flag group ((?-i), (?s), ...) as JS flags, so re:(?-i)OR/B is taken
and matches as the gateway will. A flag group further in is still
refused there (JS has no bare (?-i)); the CLI takes it.

Said in groupmatch.go's comments, magpie group's and magpie provider
auto-include's help, and providers-accounts.md (Routing groups, List
schedule and rules). No GUI hint said a pattern's case, so none
changed and no string was added.

Run:
- TestRegexpPatternIgnoresCase (new): ok. With compilePattern's (?i)
  taken off by hand: FAIL, "re:GPT-.* ~ gpt-5.5: false, want true" and
  three more cases.
- group-patterns.test.cjs, chromium and webkit, en and zh: 4 of 4 ok.
  With patternRe put back to the old re: line by hand: 4 of 4 red,
  "(?-i) keeps case 0 !== 1" (old JS refused re:(?-i)OR/B).
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
- go test -tags nogui -timeout 45m ./internal/provider ./internal/cli
  ./internal/gateway under a sandbox HOME at 1a956129c's tree: ok,
  ok, ok (380s). go build for darwin, linux (nogui) and windows: ok.
- A full ./... run was started and stopped: the machine's disk was
  full (1GB free), and internal/agent's tests failed on "no space
  left on device" in TempDir, not on this change. No full suite ran.

Not tried: the full suite (above); a real provider's auto-include fetch with mixed-case ids;
the Linux app's WebKitGTK; a (?-i) further into a re: in the GUI.
2026-10-24 07:07:57 +08:00
yetone edff2f819a provider: levels kept of a model's own narrow only what is offered again (#92)
4a3e07f1c made provider.Efforts return the levels a user kept, so the
gateway fitted every request to them. That reversed #92 (47e12df41),
which was explicit that narrowing a model's levels changes only what is
shown and "the levels the vendor is asked at stay as they were": a user
who had trimmed a picker with `magpie model efforts` or Names & levels
would have had their agents' xhigh and max asks lowered unasked. Dani's
request (magpie model spec) needs levels to count only where magpie
knows none for the model.

- Efforts is back to what it was before 4a3e07f1c: the vendor's list's
  or models.dev's levels when known, else the ones the user declared
  (`magpie model spec --reasoning` on a custom provider's model), which
  a request is then fitted to. --reasoning off (reasonless) is as
  4a3e07f1c built it.
- TestModelEfforts' "the vendor is still asked at any level it has" is
  restored as it was.
- TestKeptLevelsBoundTheAsk becomes TestNarrowedVendorLevelsAskAsBefore:
  a models.dev-known model narrowed to low-high is offered low..high and
  still sends xhigh, max and low as asked.
- gateway-routing.md, reference.md, the settings.go comment and spec's
  usage say so: narrowing is display-only, declared levels are fitted.

Run at this tree (base 4a3e07f1c):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
  ./internal/cli ./internal/settings: ok (gateway 386s).
- gofmt -l empty; go vet darwin, linux -tags nogui, windows clean.
- Broken by hand, each red: 4a3e07f1c's Efforts (TestNarrowedVendor-
  LevelsAskAsBefore: xhigh and max went as high; TestModelEfforts:
  [low high]); declared levels ignored (TestModelSpecReachesTheGateway:
  xhigh sent as xhigh with low-high declared).
- Every other p.Efforts caller (gateway fit, decide, classify, automode,
  rules, side effort) is on the request path and is back to its
  behaviour before 4a3e07f1c.

Not run: the GUI suite (no GUI file changed; the GUI reads entry
Efforts, which still carry the kept levels) and a full go test ./....
2026-10-24 05:51:22 +08:00
yetone 4a3e07f1cf model: magpie model spec sets a model's window, output, vision and levels at once
Dani Ariyanto on Discord (#feedback, 10-24): a custom provider's models
(kenari/*:free) had no window, reply limit, vision or reasoning known,
and there was no one place to say them.

  magpie model spec <provider/model>                 what it has, and whose each value is
  magpie model spec <provider/model> [--context <n>] [--output <n>] [--vision on|off|auto] [--reasoning <levels>|off|auto]
  magpie model spec '<provider>/*' --context <n> --output <n>
  magpie model spec <provider/model> --reset
  magpie model specs

It writes the stores magpie model context/output/images/efforts write
(providers.json contexts; settings.json modelOutputs, modelImages,
modelEfforts, modelReasonless), so every reader that went by those goes
by a spec: entryFor/EntryOf/Served, /v1/models, max_tokens, the GUI's
/api/providers badges and chips, and the agents' model lists. Every
part is checked before anything is written; a refused command writes
nothing. Agents are told once.

Readers that bypassed the stores and now honour them:
- provider.Efforts returns the kept levels, so the gateway fits a
  request to them (fitEffort): xhigh asked of a model kept to low-high
  goes as high. This reverses #92 (47e12df41), which narrowed only the
  lists handed out; docs/subsystems/gateway-routing.md says so.
- entryFor: levels given a model with none known make it Reasoning.
- gateway AutoVision picks by the user's ModelImages (seesAt).
- GUI gateway client: a reasonless model offers no level chips.

Run at this tree (base a93190ae1):
- go test -count=1 -timeout 45m ./internal/{provider,cli,gui,gateway,
  settings,tui,agent,catalog}: all ok (gateway 505s, agent 360s).
- GUI: gateway-*.test.cjs, model-reasonless, plugin-gateway, i18n-keys
  (25 files, both engines, the new file at 1100 and 420 in en, zh,
  zh-TW, ja, de): 225/225 pass. app.js untouched.
- gofmt -l empty; go vet darwin, linux -tags nogui, windows clean.
- Sandbox HOME, built binary, `magpie web` on 47821/47820 and a fake
  Chat vendor on 47811: before, kenari/glm-5:free had no window or
  levels; after spec 128k/16k/on/low-high, /v1/models said 128000,
  16000, image input, [low medium high]; max_tokens 100000 went as
  16000, xhigh as high, low as low; qwen-x with --reasoning off was
  sent no reasoning field; /api/providers had context 128000, output
  16000, images/imageSet, kept [low medium high], reasonless for qwen-x.
  A models.dev sync during the run (GLM-5 202752/131072) didn't move
  the spec; after --reset the vendor's values came back. Bad values,
  an unknown flag and --help wrote nothing (files hashed).

Rebased onto a6a3dbde8 (the ZCode mover's min, one line): at the
pushed head 5af093d8b's tree, ./internal/provider and ./internal/cli
-timeout 45m ok, and the spec tests in gateway and gui ok.

Broken by hand, each went red: AutoVision on raw sees; Efforts on the
full list; the Reasoning line removed; output, vision or context not
written; ParseLevels skipped; agents told twice; --context 0 taken;
help printing modelUsage; old client.js; the GUI named() image and
reasonless branches.

Not tried / not changed: no full go test ./... (another session's
full GUI suite was running). Codex's ChatGPT-model /models pass-through
and the Codex effort dropdown read catalog.Codex(), not a spec. The
TUI shows no spec badges. A Context-tab trace keeps the window it was
recorded with. Pre-existing and the same on origin/main a6a3dbde8: a
GLM-5 relay with no levels known has xhigh sent as high.
2026-10-24 05:31:59 +08:00