Commit Graph
1313 Commits
Author SHA1 Message Date
yetoneandskygunner e863f520c3 routing: an intent's effort survives the group's failover (#3664)
A routing group's intent rule picks a model and the reasoning it is
asked for (useEffort, #2633). When that model's provider turned the
request away and the group failed over to another member, the request
went out at the agent's own level (or none), not the intent's.

ruleEffort (internal/gateway/rules.go) gave a rule's useEffort only to
candidates of the member the rule names. Now the rule's effort is the
turn's: a member the group fails over to is asked it too, fitted to its
own model's levels (fitLevel), and Try.RuleEffort records it, so the
Routing page says "set by the rule". Unchanged: a rule that names the
candidate goes before one it only fails over from; a member the user
fixed at an effort keeps its own (#189; ruleEffort isn't asked when
c.effort is set); a model whose levels aren't known is asked as the
agent asked.

Ported from skygunner's fix (github.com/skygunner/magpie
fix/3664-intent-effort-failover, 2136cf044), with two changes after
review:
- A nested group's rule now decides for that group's members only.
  skygunner's version gave an inner group's useEffort to every candidate,
  so when the whole inner group failed, the outer group's member outside
  it was asked the inner rule's level. ruleEffort takes the outer
  group's members (ms) and skips a nested rule for a candidate not
  reached through that group. New TestNestedRuleEffortStaysInItsGroup.
- TestIntentEffortSurvivesTheGroupsFailover now covers four cases for
  the failover member, each in its own magpie: unknown levels (agent's
  high, nothing traced), the same levels (low), levels medium/high
  (fitted to medium) and fixed at high (high, Fixed traced, RuleEffort
  empty). The stale "Then asks nothing" comment now says its member is
  asked the first rule's.
docs/subsystems/gateway-routing.md says both.

Run (all on mote via mote-run, at this tree rebased on 4b4c4a806):
  gofmt -l internal/gateway: nothing
  go vet ./internal/gateway/, GOOS=linux and GOOS=windows: ok
  go test -timeout 45m -count=1 ./internal/gateway/: ok (595.7s)
  (an earlier full run on the pre-scoping tree: ok, 670.6s)
Broken by hand (-run TestIntentEffortSurvivesTheGroupsFailover,
TestNestedRuleEffortStaysInItsGroup), each red:
  origin/main's ruleEffort: "the intent's level: the member the group
    failed over to sent ... reasoning_effort:medium"; nested
    "within the inner group: q1=low/low q2=high/"
  return asked without fitLevel: "fitted to its own: traced ..."
  no unknown-levels check: "unknown levels: ... sent ..." (low, not high)
  ruleEffort called for a fixed member (c.effort guard dropped):
    "fixed at its own: ... sent ..." (low, not high)
  nested scoping off (skygunner's version): "outside it: q1=low/low
    q2=low/low f1=low/low"
Not run: go vet ./... and the rest of the suite (only internal/gateway
changed); no real-provider run.

Co-authored-by: skygunner <84759+skygunner@users.noreply.github.com>
2026-10-30 10:18:47 +08:00
yetone 4b4c4a8062 gui: tell a Chinese reader Claude Desktop's gateway window has no Chinese (GZXYMH on X)
GZXYMH on X, under the owner's tweet about Claude Code without the proxy:
"代理的话,就会变成网关形式的界面,就没有中文简体了(desktop版本)". The
"desktop version" is Claude Desktop. Connected to magpie it runs in its 3p
mode, whose window ("Gateway" inference) is Anthropic's bundled UI. That UI
has 11 catalogs and no Chinese, so the window comes up in English.

Cause, read from the real bundle: Desktop 4.4212.0 (darwin RELEASES.json
currentRelease, published 10-29) now packs that UI as
Resources/ion-dist.asar. Its header lists i18n/ en-US de-DE fr-FR ko-KR
ja-JP es-419 es-ES it-IT hi-IN pt-BR id-ID (and dynamic/ for the same 11),
with no zh. That matches 2.7032 (this Mac) and 3.6556.2 (40b5c2daf). The
window asks for its own locale at every start, so nothing magpie writes
keeps Chinese (desktopCarryLocale). It is Desktop's missing translation,
and magpie doesn't patch Anthropic's signed app.

The gap on magpie's side was that a Chinese reader wasn't told, and took
it for magpie's. Now:
- Claude Desktop's opened row on Agents, under "In Claude Desktop", has a
  warning line when magpie is in Chinese (zh or zh-TW): Desktop on magpie
  shows Anthropic's gateway window, which has no Chinese; disconnect it to
  get Chinese back. Other languages have their catalog there, so they
  don't see it.
- The switch-on notice in zh and zh-TW says the same.
- docs/subsystems/agent-wiring.md names 4.4212.0 and the line.
app.js stays within its budget (1,315,223 of 1,315,316): two comments
were cut down, no raise.

Siblings: magpie's own GUI language list has 简体中文 in the app, the tray
panel and magpie web (gateway mode included: one LOCALES list, one
picker). The TUI and CLI have no Chinese at all, so they have nothing to
say it in.

Run on mote at 9dc9b7306 (origin/main 99c2567cf + this):
- desktop-lang.test.cjs (new): Chromium and WebKit, en/zh/zh-TW/ja/de, at
  1100 and 640px. Red on the old code at 99c2567cf with only the test
  added: 8 fail (every zh and zh-TW case), 12 pass.
- GUI files agent-notice*, agent-connect*, agent-models*, agent-layout*,
  agent-row*, desktop-*, claude-in-*, gui-*, i18n*: 241 pass, 0 fail.
- go test -tags nogui ./internal/gui: ok (TestCoreScriptBudget included).
  Before the rebase, ./internal/agent: ok.
- Before the budget cut, the wider set (agent-*, agents-*, claude-*,
  desktop-*, gui-*, i18n*; 1105 subtests) had 32 red, all in
  agent-panel-name-width, the same at origin/main eed140c4d run alone,
  which is #4203 (commented: red on macOS in both engines as well).
Rebased onto 83e41a22c (internal/agent and the doc only, no GUI file),
run again at the pushed tree: desktop-lang, i18n-keys and desktop-longest
32 pass 0 fail, TestCoreScriptBudget ok.
Not tried: a real Claude Desktop switched onto magpie on this Mac. That
would rewrite the live Desktop config, so the evidence is the 4.4212.0
bundle above plus 40b5c2daf's reading of 3.6556.2.
2026-10-30 10:01:39 +08:00
yetone 83e41a22c9 agent: Claude Desktop's key, sealed at rest by Desktop 4.4212, isn't said to be changed (Discord)
A Windows user on Discord: the Agents list keeps saying Claude Desktop's
inferenceGatewayApiKey (00000000-0000-4000-8000-6d6167706965.json) was
changed. Reconnect and a Desktop restart help only until the next start.

Cause: Claude Desktop 4.4212.0 (2026-10-29, Windows and macOS) seals
configLibrary secrets at rest. Its custom-3p:keys sweep runs at every start
and rewrites each clear-text secret field, inferenceGatewayApiKey among
them, in place as
  "__sealed__:v1:" + base64(protect("anthropic.claude.crossProfileSecret.v1:"
    + {"configLibrary":{"key":k,"value":v}}))
Desktop opens the value again when it reads the profile, so it still sends
magpie's key and the gateway takes it. Only magpie's file check saw another
string. In 4.29.0 the writer was gated on !app.isPackaged; in 4.4212 the
gate is gone. Read from the 4.4212 nupkg and macOS zip's app.asar.
protect is the claude-native addon's userDpapiProtect on Windows (user
DPAPI, entropy "anthropic.claude.crossProfileSecret.v1") and Electron
safeStorage (Keychain) on macOS.

Fix: desktopOpen opens a sealed value before Check and Sync judge it. On
Windows it is opened with CryptUnprotectData and that entropy, the prefix
and the configLibrary key are checked, and the clear key is then compared
as before, so a sealed key that isn't magpie's is still "was changed". A
seal magpie can't open (macOS Keychain, another user, a bad blob) is
unknown, not changed: no notice, and Sync doesn't write over it. The
gateway's auth is unchanged; it still takes only the key magpie wrote,
which is what Desktop sends after opening the seal.

Run (mote, at this head on 99c2567cf): gofmt -l clean, go vet
./internal/agent, GOOS=windows and GOOS=linux go vet ./internal/agent,
go test -count=1 -timeout 45m ./internal/agent ok. Windows (xiaomi-gpu,
win-run): go test -count=1 -timeout 45m ./internal/agent: 14 reds, none
in Claude Desktop's key path. 13 fail the same at base 99c2567cf run
there; TestHermesProfilesFollowMagpieModel passed at the base and passes
6 of 6 alone at this head. All 14 are filed: #4115 (Hermes, Desktop
language, DesktopExec, WorkBuddy, Copilot/Qoder folders ...), #2808
(Codex keychain), #1827. The new Windows seal tests pass there.

Real blob: on xiaomi-gpu, Desktop's own claude-native-binding.node
(userDpapiProtect) sealed the clear text exactly as Desktop 4.4212 builds
it; desktopOpen opened it from Go to the original key (a throwaway test,
deleted after, since the blob opens only for that user).

Broken by hand: with the old claudedesktop.go, TestClaudeDesktopSealedKey
IsNotChanged fails with the reported message ("... inferenceGatewayApiKey
... was changed ...") and TestClaudeDesktopImportedSealedKeyStays fails on
its check and on Sync rewriting the sealed key. Without the entropy, the
real-blob open failed ("The data is invalid").

Not tried: a real Claude Desktop 4.4212 running against magpie on Windows
or macOS (not started; the live config on this Mac untouched). On macOS a
sealed key is left unknown rather than opened, so a key changed there by
hand after sealing is not reported until Desktop's file is clear again.
2026-10-30 09:57:50 +08:00
yetone ffa07395eb gateway: Codex talks Responses to magpie over a WebSocket, turns after the first as a delta (#4058)
Codex names previous_response_id and sends only the new input on its
WebSocket path alone; magpie answered the upgrade 426 (a87dc1ff2), so
Codex fell back to HTTP and re-sent the whole conversation, images
included, every turn (kevinzhow and neighbads on X).

/v1/responses, /responses and /backend-api/codex/responses now accept the
socket (responses_ws.go), with Codex's protocol (codex-rs 2f1e4f9,
responses_websocket.rs):
- each response.create frame is replayed as the POST it stands for through
  the outermost handler the upgrade came in on (socketEntry wraps Front and
  Handler), so the allow list, rebound Host check, key, corsGuard,
  keyLimited, routing, failover, usage and log judge every turn;
- previous_response_id resolves to the socket's own last two replies
  (input + output items); the provider gets the whole conversation, so a
  switch of account or provider mid-chain loses nothing. An id the socket
  doesn't hold is previous_response_not_found (Codex reconnects with
  everything);
- generate:false (warmup) is answered locally; response.interrupt cancels
  the turn (accepted + incomplete/interrupted, or failed); errors are
  Codex's error frame with status and the headers it acts on;
  response.metadata, codex.response.metadata (x-models-etag, magpie's tag)
  and codex.rate_limits are sent as the backend does;
- shutdown drains sockets with 1001 and refuses new ones 503.
Codex needs no config change: magpie's wiring points the built-in openai
provider at /backend-api/codex, which Codex already speaks WS to. Other
Codex backend paths still answer 426. Docs: gateway-routing (new section
"A Responses WebSocket"), providers-accounts, reference.

Run at the pushed head (rebased on origin/main 430005726), on mote:
gofmt -l clean; go vet ./internal/gateway for darwin, linux, windows;
go test -timeout 45m ./internal/gateway: ok (480s).

Real Codex (codex-cli 0.165.0, sandbox HOME/CODEX_HOME with a copy of the
owner's ChatGPT auth, sandbox magpie on 127.0.0.1:3481, gpt-5.6-luna, a
task with three tool calls). At the pushed head, built on mote: exit 0,
right answer, 5 turns on one socket, 4 continued, 75480 B received vs
278210 B sent on as whole requests, no fallback to HTTP. Before the
rebase, with a temporary per-turn log: exit 0, right answer. 5 turns on one socket,
4 continued with previous_response_id; frames 58073 B (first), then 4465,
3051, 3093 B, against 58.7-66.6 KB had each been a whole request. 70185 B
received over the socket vs 255379 B sent on as whole requests.

Broken by hand:
- serveResponsesSocket returning false (the old 426): 9 of the new tests
  red.
- turns sent straight to the Responses handler with the upgrade's
  post-guard context: TestResponsesSocketGuards red (a key turned off
  still served; a 700-token limit not held).

Not tried: images in a real run; Codex on Windows/Linux. Not done: the
leg magpie -> vendor still sends the whole conversation each turn (for
ChatGPT, keeping an upstream socket per client socket would save that);
the saving is Codex's upload to magpie. A socket's conversation does not
survive the socket or a restart (Codex then resends everything).
2026-10-30 08:51:03 +08:00
yetone e887139e7a providers: Best in family serves the newest model of each family a provider lists
Steven on Discord #feedback asked for a provider to serve only the newest
model of each family, so a newer one (Opus 5.6) takes the old one's place
without re-picking.

The provider editor's Models control gets a fourth option, beside
Vendor's list / Picked only / Usage only: Best in family. It is also on the
CLI as `magpie provider models <id> best`. With nothing picked, the provider
serves only the newest model of each family in the vendor's list, up to 24.
A family is the id with its version numbers taken out
(catalog.FamilyOf/BestInFamily in internal/catalog/family.go). A dated
snapshot counts as its alias, and sizes and suffixes (mini, flash, -fast,
-thinking) stay part of the name. Provider.Exposed applies it, and so does
Codex's native list (CodexNativePicked). A provider/model a request names
explicitly is still served, since resolve doesn't go through Exposed. A pick,
Select none or Usage only clears the flag (normalize), and a providers.json
without bestInFamily reads as before, so every existing mode is unchanged.
The editor draws the family's newest as dashed (m.best) before saving. Every
language has the wording (zh, zh-TW, ja, de). The design reference is
docs/subsystems/providers-accounts.md (Model picks).

Tests: family_test.go is a table of real ids, including the models.dev Claude
list in testdata (no network). There are also best_in_family_test.go
(provider), TestProviderModelsBest (cli), provider_save_best_test.go (gui
save keeps/clears), codex_best_in_family_test.go (gateway) and
provider-best-in-family.test.cjs (5 languages x chromium/webkit x 1100/420).

Broken by hand: with the BestInFamily filter in Exposed and in
CodexNativePicked turned off, the 4 new Go tests went red.

Budget: after the rebase app.js went over appScriptBudget. Comments were cut
and the tooltip and hint merged into one string, so app.js is 1,311,399 of
1,311,735. Neither budget was raised.

Run at this head, on origin/main 1027db408, via mote-run (macOS 27):
- gofmt -l clean; go vet clean for darwin, linux -tags nogui and windows
  (at base 05a6087e1, the same Go diff).
- go test -count=1 ./internal/catalog ./internal/provider ./internal/cli
  ./internal/gateway: ok.
- go test ./internal/gui: everything except TestMainWindowCorners/macOS_26_SDK
  (red on macOS 27, #3949; not this change).
- node --test: provider-best-in-family, provider-none-picked,
  provider-picked-only-shows-picks, i18n-keys, gui-de, gui-ja, gui-zh-tw,
  context-map and gateway-key-models, 113 tests, 108 pass. The 5 reds are
  context-map 420px "two tiles overlap" (#3488, #4304) and gateway-key-models
  webkit en (#4304). Both fail the same way on a clean origin/main 1027db408
  checkout run alone (8 of 30 red there).
- The earlier wider GUI run (38 provider/routing files, concurrency 3) had
  the same red files on origin/main deb0b8da7 as at this change's head:
  model-chip-steady, models-works-only, provider-fetch-again and the others
  in #4304. Three with no issue were filed: #4320 (recovered-file),
  #4321 (tencent-cloud), #4322 (warm-now).

Not tried: no real account or real magpie app; the editor was checked
through Playwright screenshots only. Families are read off the id alone, so
a vendor whose ids don't put the version in numbers (or orders them
oddly, e.g. grok-4.20 against grok-4.7 compared numerically) may group
or rank unexpectedly. Bedrock's -v1:0 counts as version digits.
2026-10-30 04:48:17 +08:00
yetone 55299ee304 agents: Switch accounts only, the account a Claude Code or Codex not connected is signed in to, a click from another
Users asked for an entry named 仅切换账号 (growaiskills), for the current
account to always show, for a clear sign that a switch took, and for the
switch away from the proxy settings that put them off (Rennix7t). The owner
said to build it.

On the Agents page, a Claude Code or Codex row that magpie doesn't connect now
shows the account the agent is signed in to as a button in its status line
(switchEntry). Clicking it opens the app menu, headed "Switch accounts only",
with:
- every sign-in;
- "Only switch {agent}'s sign-in", a ticked item (menuitemcheckbox). Claude
  always gets it; Codex gets it only with more than one usable account;
- "Manage accounts…", which opens the provider editor.
Picking another account goes through /api/login/switch, or through
/api/provider/keeplogin when the provider keeps a login. The button then
shows "Switched" for 5s, and the status line says that new sessions use the
account and an open one keeps its account until it is restarted. A pure
switcher (Claude kept to its own accounts with nothing else in magpie, the
"empty" connect kind) used to show only "Add a key or a subscription
first", so it couldn't switch from the page. It now gets the entry, and
switch-only reads "Not connected · switching accounts only". The failover
line's "ChatGPT accounts" button is gone, since this entry replaces it. A
connected agent, the tray panel and the WSL twin get no entry. Strings are
in zh, zh-TW, ja and de. Docs: providers-accounts.md and reference.md.

The core budget is raised by this change's bytes only (app.js 1,315,316,
core 1,536,357), after cutting comments and dropping a key.

Run on mote at 9f299d54e (rebased on 0c12662f2):
- GUI files agent-switch-accounts, agent-failover, i18n-keys, gui-zh-tw,
  gui-ja, gui-de, click-scroll, agent-connect-no-models, switch-only,
  claude-switch-only and keep-login: 177 of 177 pass. agent-panel-name-width,
  run beside them, is 0 of 32, the same on origin/main 0c12662f2 alone
  (#4203, commented)
- go test ./internal/gui: only TestMainWindowCorners/macOS_26_SDK red, #3949
- Earlier, at ad9f269c9 on 8cbd0a9c9, the whole GUI suite (concurrency 4)
  ran 508 tests before I stopped it, since it ran very slowly under load.
  The only red was agent-panel-name-width (chromium and webkit), a
  panel-only test where this entry is never drawn. It is #4203, and it is
  still red at this head and on main with 0f391a7a7 (above). The rest of
  the suite was not reached.
- A Linux full run (wsl-run, magpie-desktop) is not a valid environment:
  410 GUI reds at concurrency 8, mostly WebKit timeouts, and the Go builds
  fail without gtk4/webkitgtk. internal/gateway passed; internal/agent had
  6 that need tools installed there (TestInstalledVersion,
  TestGrokInstalled, …). Nothing in this change touches Go.

Broken by hand, each turned red, then restored:
- not setting accountSwitched: "Switched shows on the button" went red in
  every engine and language;
- login/switch in place of keeplogin: the kept-login test went red;
- removing the empty-kind bypass: 11 of 12 chromium tests went red.

Not tried:
- a real switch with real accounts in a sandbox HOME. On macOS Claude
  Code's credentials are in the login Keychain, which a sandbox HOME doesn't
  isolate, and the Linux box has no signed-in accounts. The endpoints are
  unchanged and were already used by Settings' switch.
- the real app on Windows and Linux (WebKitGTK);
- the tray panel, which reads no provider list, and the WSL twin rows,
  which get no entry;
- the rest of the whole GUI suite past 508 tests.
2026-10-30 04:01:35 +08:00
yetone deb0b8da72 codexcat: Codex shows a model's whole window and compacts at Long conversations' threshold (#3975, #3562; 01huadalang on Discord)
01huadalang on Discord: a Command Code model with a 1M window showed
258,400 in Codex. EasonSpirit (#3975) and greenfinchgreen-gif (#3562)
saw the same on OpenCode Go's 1M models.

The cause: magpie put Long conversations' threshold (272K by default, a
Compact at set on the model or provider, or a size typed in Settings)
into the Codex catalog entry's context_window, and the real window into
max_context_window. Codex shows context_window at 95% as the
conversation's context, so 272000 showed as 258400. The plugin was not
at fault: commandcode lists these models at 1M, from Command Code's
own list or its fallback table.

Now each catalog entry carries two values:
- context_window is the model's whole window.
- auto_compact_token_limit is the threshold, written only when it is
  below the window. Full window writes none.
This applies to entries magpie writes itself (entriesAt) and to a
relay's own Codex-shape entry (listedEntry). Codex 0.165 compacts at
the lesser of the threshold and 90% of the window. A
model_auto_compact_token_limit the user put in config.toml still comes
first.

Two other changes:
- max_context_window is never written now. It stays a field of
  codexcat's model, so Keep doesn't carry an old catalog's value
  forward as if the user had added it.
- Tag carries a format mark (catalogFormat), so a Codex holding a list
  in the old shape fetches it again.

Codex's own models (codex/) and Codex's base_instructions are
unchanged.

One behaviour moves. Codex used to compact at 90% of 272000 (244,800).
It now compacts at 272,000, the number the setting shows ("Compact at
272K").

Tests:
- TestCodexWindowShownCompactApart (new). Checks Command Code's
  claude-opus-5-5 at 1M, a relay entry, and a relay entry with its own
  Compact at, under the default, Compact at 400K, and Full window.
- TestCodexCatalogCompactAt, TestCodexCatalogToolSearch,
  TestCodexCatalogCompactAtReachesDisk and
  TestTypedWindowReachesCodexAndClaudeCode now expect the window in
  context_window and the threshold in auto_compact_token_limit.

Broken by hand: I put the old codexcat.go back. TestCodexCatalogToolSearch,
TestCodexCatalogCompactAt and TestCodexWindowShownCompactApart went red
("commandcode/claude-opus-5-5 told window/compact [272000 <nil>]; want
[1e+06 272000]"). With this change restored, all three are green.

Real Codex 0.165.0 in a sandbox CODEX_HOME, against a local fake
Responses server, using the catalog codexcat.Catalog now writes for
commandcode/claude-opus-5-5 at 1M:
- The rollout records model_context_window 950000. The old-shape entry
  (272000 with a max of 1000000) records 258400, the reporter's number.
- A turn reporting 260K tokens is not compacted. One reporting 280K is
  (CONTEXT CHECKPOINT COMPACTION). The old shape compacted at 260K.
- model_auto_compact_token_limit = 500000 in config.toml keeps the
  280K turn uncompacted.

Run (mote-run, at this change on origin/main 9b833205f; rebased onto 56bc3d515, which touches only GUI plugin files, and codexcat run again there: ok):
- gofmt -l: clean.
- go vet -tags nogui ./... for darwin, GOOS=linux and GOOS=windows.
- go test -tags nogui -count=1 -timeout 90m on codexcat, agent, gateway,
  provider, gui, cli and catalog: all 7 ok (codexcat 1.0s, agent 182s, gateway 510s,
  provider 119s, gui 70s, cli 43s, catalog 0.7s).

Not changed or not tried:
- Claude Code's CLAUDE_CODE_AUTO_COMPACT_WINDOW and Grok Build's
  context_window still carry the threshold, so they show it as the
  window. Filed as #4319.
- Not tried: a real Command Code account, and the Codex desktop app.
  The app reads the same catalog through the same app-server.
- #3553 asks for effective_context_window_percent 100. That isn't done:
  95% is Codex's own value for its models.
2026-10-30 03:47:58 +08:00
yetone 9b833205f7 groups: a found group's id and name come from models.dev's one spelling (XYenon)
XYenon on Discord (#feedback, 10-30): autoGroups() and spelledIn() picked
a found group's name and its public id apart, so a group read
glm-5-3-flash beside auto/glm-5.3-flash. The id also followed the order
the providers were added in.

Now:
- spelledIn takes the spelling models.dev gives the model most
  (catalog.Spelling, the normal index normalFor already reads): every
  member spelling of GLM-5.3 Flash (glm-5-3-flash, Ark's
  glm-5-3-flash-260828, glm-5.3-flash) gives auto/glm-5.3-flash. A model
  models.dev doesn't know keeps the old pick (first listed member
  spelling, else the first member's).
- autoGroups names the group from the same choice: catalog.NameOf of
  that spelling, else a vendor's own name, else the spelling itself.
  A found group the user changed keeps the name they saved.
- Old ids keep working. group/auto-<slug> doesn't change, and any
  auto/<spelling> is still the group (CanonicalRef: gateway, key
  allow-lists, fallbacks, members). PublicRef now takes an old
  auto/<spelling> to the current one too, so hidden, picked and ordered
  models saved by it hold, and a pick of it written now (Agent.Apply)
  is written as listed. An agent field magpie set to an old spelling
  moves on the next SyncCatalog (renameFoundGroups), as group/auto-
  values already did, because OpenCode checks its model against the list
  magpie writes. A value the user set stays as it is and is still served.

Tests (on mote, via mote-run):
- TestFoundGroupIDAndNameAreOneSpelling (5 member orders/spellings, the
  user's name kept), TestFoundGroupUnknownToModelsDevNamedByItsID,
  TestFoundGroupMovedOffAnOldSpelling. The catalog fixtures use
  models.dev's real spellings and names (glm-5.3-flash "GLM-5.3-Flash",
  volcengine's glm-5-3-flash "GLM 5.3 Flash").
- Broken by hand, one file reverted at a time: group.go reverted, the
  test is red (named "GLM 5.3 Flash" beside auto/glm-5.3-flash);
  provider/autoref.go reverted, red (id auto/glm-5-3-flash with Ark first,
  PublicRef of the old spelling unchanged); agent/autoref.go reverted,
  TestFoundGroupMovedOffAnOldSpelling red (field stays
  magpie/auto/glm-5-3-flash).
- go test -timeout 45m: internal/catalog, provider, agent, tui, cli,
  usageapi ok. internal/gui: everything ok except TestMainWindowCorners/
  macOS_26_SDK, which is #3949 (AppKit on macOS 27, nothing to do with
  this change). internal/gateway, codexcat, sessions ok.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows clean.
- No GUI file changed, so the GUI suite wasn't run. Names reach it
  through /api/groups.

Not tried: a real models.dev sync with real providers in a sandbox app.
Groups whose first provider spelled a model differently from models.dev
(e.g. claude-opus-4.8 from a relay vs Anthropic's claude-opus-4-8) get
the models.dev spelling once. Magpie-set agent fields move with it, and
values the user set keep resolving. A key or fallback chip saved under
the old spelling still shows it in the editor (it still works).
2026-10-30 03:09:29 +08:00
yetone 4054251865 library: an MCP server can be kept to this computer, never synced
huhuy72219405 on X: "能不能把不同设备的mcp区分一下,有些mcp属于本地的,
同步之后其他设备不应该读取到". A server in Library > MCP now has a
"This computer only" switch in its editor (Server.Local; CLI
`magpie library mcp add ... --local` and `magpie library mcp local
<name> on|off`; the TUI keeps it on edit and marks the row).

- Collect leaves local servers out (carriedServers), so neither a sync
  nor a backup file takes one to another computer. Turning a shared
  server local takes it out of what is carried, so the other computers
  drop it at their next sync; the flag itself is never carried.
- Put (sync, join, Restore, Undo, backup file) keeps every local
  server, with its agents, and clears Local on what comes in.
- Another computer's server by a local server's name goes to
  Library.Away: given to no agent, not in the hub, carried on as it
  came, so a push from here never removes it from the computers that
  have it. settleAway (every change) promotes it once the name is gone
  here, and drops it once the name is shared here again.
- The hub serves local servers like any other (it runs here);
  subagents aren't carried, so one naming a local server keeps it.

Docs: docs/subsystems/library.md, docs/subsystems/sync-backup.md.

Run at f5dd4e142 + this change; after rebasing on d3898ca8d (gui/provider only, then 2a1ef15ba, routing), vet, the five new Go tests, mcp-local-server and i18n-keys again, ok:
- mote: gofmt -l clean; go vet of library/backup/davsync/cli/tui;
  GOOS=linux and GOOS=windows go vet -tags nogui of the same; go test
  of TestLocalServerNotCarried, TestPutKeepsLocalServer,
  TestPutSameNameAsLocal (library), TestRestoreKeepsLocalServer
  (backup), TestLocalServerThroughSync (davsync, two computers through
  the fake S3) ok.
- mote GUI, Chromium and WebKit: mcp-local-server.test.cjs (new; every
  language, 1100 and 390 wide, switch saves local true/false, row tag,
  no sideways scroll), i18n-keys, mcp-editor-cancel,
  mcp-startup-timeout, every library-mcp-*, mcp-oauth-app, mcp-signin*,
  library-items, library-servers-bulk, library-subagents,
  library-pick-remove, library-env-refs, library-zed-mcp,
  library-loading: all pass (126 of 126 in the last batch).
- Full Go suite, -tags nogui -timeout 45m, on the Linux box (wsl-run;
  mote had another session's full suite running): every package ok
  but internal/agent, whose TestInstalledVersion, TestGrokInstalled,
  TestOmpDetectedWithPiDir and TestZedAppPath fail the same at
  origin/main 9b4d0bda8 on that box; all four are #4033.
- Real CLI in a sandbox HOME on mote: mcp add --local, local on/off,
  `magpie library` shows "this computer only", library.json has
  "local": true; an unknown name and a bad value are refused.

Broken by hand: putServers not keeping local servers turned
TestPutKeepsLocalServer, TestPutSameNameAsLocal,
TestRestoreKeepsLocalServer and TestLocalServerThroughSync red;
carriedServers carrying local servers turned TestLocalServerNotCarried,
TestPutSameNameAsLocal, TestRestoreKeepsLocalServer and
TestLocalServerThroughSync red.

Not tried: a sync between two real computers; the real GUI app (the
Playwright run fakes the API); the full Go suite on macOS or Windows.
2026-10-30 02:31:08 +08:00
yetone 2a1ef15ba9 routing: a found group's card leaves out a provider switched off, and counts it (XYenon)
XYenon on Discord (#feedback, 10-30): "已经关闭的提供商还会显示在路由页的
自动成组里是不是不太对". A provider switched off stays a member of the
groups magpie found (#2671, on purpose: agents on auto-<model> aren't
moved while it is off), and the gateway already skips it (membersIn reads
only providers that are on; TestFoundGroupWithAProviderOff covers chat,
and a fallback group, affinity and a group's classifier (decide_group.go)
go through the same FindGroup). So no request reached it. What was wrong was the page: the
card still listed it as "B · model (switched off)" and its logo sat in
the group's icon stack, where every other model list leaves a provider
switched off out.

- Routing page (plugins/routing/client.js): a found group's card, its
  remove-picker row and its logos (groupIcons, also used by the group
  pickers) leave out members whose provider is switched off; a tag
  "{n} switched off" says how many, its title why (offWords). When none
  would be left they are listed as before. The editor and a manual
  group's pick still show them, greyed with why. A group of the user's
  is unchanged: it lists what they put in.
- i18n: "{n} switched off" in zh, zh-TW, ja, de.
- TUI (sibling): the routing list's line for a found group does the same
  ("N models · ... · 1 switched off"), and a group's page marks such a
  member "· switched off: skipped until it is on again" (any group).
- docs/subsystems/providers-accounts.md: the row says it.

Tests: routing-provider-off.test.cjs gains a found group (card text,
tag text and title, no logo of the provider off, editor still has it)
and one whose only member is off (listed as before, no tag); every
language, 1100 and 420 wide, Chromium and WebKit.
TestFoundGroupLineLeavesASwitchedOffProviderOut (internal/tui).

Run on mote (mote-run, this tree): node --test of 45 GUI files
(group-*, panel-routing*, routing-group*, routing-groups*,
routing-provider-off, i18n-keys, found-*, remove-found*): 488/488 pass.
go test ./internal/tui ok; go test ./internal/gui: all ok except
TestMainWindowCorners/macOS_26_SDK, red on macOS 27 and already filed
(#3949), an AppKit window test this change doesn't reach. gofmt -l
clean; go vet ./internal/tui for darwin, linux (-tags nogui), windows ok.

Broken by hand: with client.js from HEAD the new GUI case is red
(expected 'A Cloud · luna', actual 'A Cloud · luna → B Cloud · luna
(switched off)'); with listedMembers returning every member the TUI test
is red ("2 models · ... pa/luna → pb/luna").

Not tried: the real app with a real provider switched off; the full GUI
suite (1002 files) and the full go test ./... were not run.
2026-10-30 02:28:29 +08:00
yetone d3898ca8d3 provider: ChatGPT account calls go with Codex's headers, and saved accounts are listed once a day
Two follow-ups of 6e55914b6's audit of what magpie sends OpenAI for
idle saved Codex accounts (owl, Discord #general: three ChatGPT accounts
deactivated). Product call made by the session the owner delegated
product calls to; mimicking the official client is allowed for every
vendor but Claude Code. Identity, base_instructions and prompts are not
touched.

- Headers. GET /backend-api/wham/usage, /wham/rate-limit-reset-credits,
  POST .../consume and POST auth.openai.com/oauth/token (live and saved
  sign-ins, and the sign-in's code exchange) went with Go's
  "Go-http-client/1.1" and no originator. They now carry Codex's
  originator and User-Agent through codexClientHeaders, the part of
  codexSign that /codex/models and /responses already used. No version
  header on them: codex-rs sends it with model requests only
  (login/src/auth/default_client.rs default_headers is originator +
  User-Agent; backend-client/src/client.rs adds auth headers).
- Refresh body. codex-rs (main f32b6cfd and rust-v0.165.0,
  login/src/oauth/client.rs refresh, auth/manager.rs
  request_chatgpt_token_refresh) sends JSON client_id, grant_type,
  refresh_token and refresh_reason, and no scope. magpie sent
  scope "openid profile email" and no reason. It now sends codex-rs's
  fields: proactive_expiry near expiry, unauthorized_recovery after a
  401 (stale token), scheduled from the 8-day keep-alive, forced for an
  import or a revoked-sign-in check. The code exchange's form already
  matched exchange_code; only its headers changed.
- Model lists. The active Codex account's /codex/models fetch (hourly
  KeepAccountsListed, FetchNew, Refresh) also fetched every switched-on
  saved account's list each time. codexFetchSaved now asks one with no
  list at once, and the others once a day, one per call, oldest asked
  first; a failed ask is remembered so a deactivated account doesn't go
  first every hour. The active account's list is unchanged.

Docs: providers-accounts.md says both.

Tests (codex_quiet_test.go), each red on the old behaviour (broken by
hand: wham/refresh/exchange headers removed, scope back, the age check
and the one-a-look cap removed, the keep-alive's reason dropped, and
separately the failed-ask memory skipped):
- TestCodexAccountCallsGoAsCodex counts the requests to a fake (usage 1,
  credits 1, consume 1, token 2) and checks User-Agent/originator on
  each and the refresh body's keys. Old: Go-http-client/1.1, "" and
  scope in the body.
- TestCodexRefreshSaysWhy: scheduled, forced, unauthorized_recovery.
  Old: no reason.
- TestSavedCodexListsOnceADay: 2 asks on the first look, 0 an hour on,
  1 then 1 a day on, 0 again, and 0 within the day while failing. Old:
  2 on every look; without the memory, a failing one asked again.

Run (mote-run, at origin/main 9b4d0bda8 plus this change, the tree
pushed unless the rebase below names a newer base):
- gofmt -l internal/provider: clean
- go vet ./internal/{provider,agent,cli,gateway} on darwin, GOOS=linux
  -tags nogui and GOOS=windows: ok
- go test -count=1 -timeout 45m ./internal/provider ./internal/agent
  ./internal/cli ./internal/gateway: all ok (118s, 199s, 44s, 562s)
Not tried: a real ChatGPT account (none touched, per the session's
rules), so OpenAI's answer to the new headers and the scope-less
refresh is known only from codex-rs doing the same. The Sign in with
ChatGPT API path (auth.openai.com/api/accounts/oauth/token, chatgpt_api.go)
is another client and is left as it was. Refresh in the GUI also lists
saved accounts by the once-a-day rule now.
2026-10-30 02:28:10 +08:00
yetone fb2e11e288 agent: a Codex sign-in OpenAI refused to refresh for good counts as none (#4308)
jjt on Discord: Codex's ChatGPT sign-in was revoked, and magpie's
models were gone from Codex until they signed in again.

Cause: Codex keeps a revoked sign-in's auth.json as it was and remembers
the permanent refresh failure in memory alone (codex-rs
login/src/auth/manager.rs). magpie read auth.json alone
(codexChatGPTKnown), counted the sign-in and wired Codex beside it
(openai_base_url, requires_openai_auth). There, Codex's /models went to
the gateway, which passed OpenAI's 401 token_revoked through, so the
picker had no magpie model; and every turn, magpie's models too, failed
at Codex 0.162.1's workspace routing discovery
(/backend-api/wham/accounts/check, 401).

Change:
- provider: codexRefresh tells a refusal Codex takes as permanent
  (request_chatgpt_token_refresh: refresh_token_expired, _reused or
  _invalidated, a 400 invalid_grant, or a 401 - here only a 401 that
  carries an error code, read as oauth/error.rs reads it). When magpie's
  own refresh of Codex's sign-in (codexTokenRenewing, from the usage read
  that KeepOnAnAccountWithRoom runs) is refused that way, and the store
  still holds that refresh token, codex-signin-gone.json keeps the Codex
  home -> sha256 of the refused refresh token (no token stored). A
  successful refresh forgets it. Writes Touch the catalog so the agents
  resync; the loop's noteCodexGoneNow notices a sign-in made again
  elsewhere within minutes.
- agent: codexChatGPTKnown reads such a sign-in as none
  (provider.CodexSignInGone), as v0.1.2087 did for forced_login_method =
  "api": magpie is Codex's provider without requires_openai_auth, the
  user's auth.json stays. A record that can't be read is unknown (as
  magpie last wired it). Signing in again gives another refresh token,
  which the record doesn't name: Sync writes requires_openai_auth back.
- gateway: codexModels doesn't pass a revoked /models answer
  (provider.SignInRevoked) through: it lists Codex's cached models and
  magpie's. The desk file does the same while the live list says revoked
  (CodexListRevoked). Any other refusal (token_expired, 5xx) is as before.
- docs: agent-wiring and gateway-routing.

Run:
- real codex 0.162.1 (app-server over stdio, and exec) on mote, sandbox
  HOME/CODEX_HOME, fake OpenAI (chatgpt_base_url,
  CODEX_REFRESH_TOKEN_URL_OVERRIDE, provider.CodexBase) answering 401
  token_revoked and refresh_token_invalidated; no real network.
  - Old wiring beside the dead sign-in, old gateway: model/list had no
    magpie model (jjt's case). With the gateway change: fake/m1 listed,
    but exec -m fake/m1 fails at workspace routing discovery (401), and
    account/read errors too - why the wiring change is needed.
  - Uncommitted e2e in the agent package with magpie's own written
    config: Set("fake/m1") wrote it beside the sign-in; magpie's
    LoginUsage("codex") then heard the refresh refused, Sync rewrote it
    to model_provider = "magpie", model_catalog_json, no
    requires_openai_auth. account/read: {"account":null,
    "requiresOpenaiAuth":false}; model/list: fake/m1 plus Codex's
    models; exec -m fake/m1 answered "hi from magpie"; auth.json byte
    for byte the same.
- Red on the old code (broken by hand): without the codexChatGPTKnown
  check TestCodexGoneSignInIsNoChatGPT is red; without the
  noteCodexSignInGone call TestCodexSignInGoneWhenRefusedForGood is red;
  with codexRefreshGone true for every failure TestCodexRefreshGoneRule
  is red; TestCodexModelListRevokedSignIn and
  TestCodexDesktopCatalogRevokedSignIn are red on the old gateway.
  Taking out the store re-check in noteCodexSignInGone leaves the tests
  green: a token Codex rotated meanwhile is already held by the hash
  comparison, and the re-check only saves a needless record, log line
  and resync. Not guarded on its own.
- via mote-run, at this commit rebased on origin/main 1f03d7546:
  gofmt -l clean; go vet ./internal/provider ./internal/agent
  ./internal/gateway for darwin, linux (-tags nogui) and windows ok;
  go test -timeout 45m -p 1 of the three: provider ok (92.3s), agent ok
  (192.1s), gateway ok (530.9s). The first full run had the new provider
  test red: run after the other Codex tests it read their cached logins
  and listed none; it now has the resetRevoked/rememberLogins setup its
  siblings use.
  Rebased after the run onto 05a6087e1 (access: key model scope) and
  8cbd0a9c9 (GUI loading bird); neither touches the Codex paths, and
  this push wasn't run again on them.

Not tried: the real Codex desktop app (ChatGPT.app); signing in again
with the real binary (the unit test writes a new auth.json); the
keychain credential store; magpie's left-alone mode, where magpie
doesn't refresh Codex's sign-in, so nothing is recorded there;
Codex homes on Windows and in WSL.
2026-10-30 01:40:48 +08:00
yetone 05a6087e1f access: a key with accounts and no model may use only its accounts' providers' models
Linka on Discord (#feedback): in a gateway key's "Models this key can
use", ticking only an account and no model let the key list and use
every model of every provider.

Cause: Key.Models empty meant "every model", and Key.Accounts (#905)
held only the providers it names, so every other provider stayed open.

Change: access.HeldModels gives a key with accounts and no models the
models "<provider>/*" of each account's provider. Authenticate builds
the Identity with it, so every route's existing model gate narrows:
/v1/models, /v1beta/models, chat, responses, messages, Gemini,
count_tokens, embeddings, images, the Codex backend path, System One,
groups and fallbacks. A key that lists models is unchanged (#905: its
accounts still hold only the providers they name); a key with neither
is unchanged. The CLI's MODELS column and `gateway-key models` say so,
and the GUI editor's hint, the "not used" notes on providers no model
or account reaches, and the save status follow (en, zh, zh-TW, ja, de).

Tests:
- TestGatewayKeyAccountsOnlyHoldTheModels: each route above is 403 for
  the accounts-only key and no upstream call reaches the other
  provider, the decider or the image provider; its own provider, a
  group of it and a key that also lists models work. Red on the old
  code on every route (list showed spare/m2, chat/count_tokens/
  embeddings/systemone 200).
- TestHeldModels (access).
- gateway-key-accounts.test.cjs: hint, notes and status; 4/4 red on
  the old assets, green on the new.
- TestGatewayKeyAccountsListModels / SystemOne / OfANamedProvider and
  TestHeldKeyToldItsOwnQuotas now encode the new rule (the held key is
  told only its own provider's quotas).

Run on mote: gofmt -l clean; go vet darwin, linux -tags nogui, windows
on access, cli, gateway, gui ok; go test -timeout 45m ./internal/access
./internal/cli ./internal/gui ./internal/gateway: ok except gui's
TestMainWindowCorners/macOS_26_SDK (#3949, not this change) and
gateway's TestHeldKeyToldItsOwnQuotas, updated and rerun ok. After the
rebase on 1f03d7546 the key tests ran again ok. GUI: gateway-key*,
i18n-keys, gui-de, gui-ja, gui-zh-tw in Chromium and WebKit: 131 pass.

Not tried: a plugin-served provider (same model gate), a real
account, Windows and Linux test runs (vet only).
2026-10-30 01:25:57 +08:00
yetone 1f03d75462 claude bridge: a caller on another computer naming no folder is told the tools run elsewhere
packinggoods on Discord: magpie on a Windows machine, the agent on a Mac.
Every shell command came wrapped in PowerShell. The model's prompt held
Claude Code's own environment section from the bridge's run: "Primary
working directory: C:\Users\...\Temp\magpie-claude-work, Platform: win32,
Shell: PowerShell". That describes the gateway, and no tool of the run
runs there: every tool is the caller's.

Claude Code has no option to leave that section out. With the real
claude 2.1.312 against a capture server (sandbox HOME, fake key), it is a
<system-reminder> in the run's first message, before magpie's text, with
the default prompt and with --system-prompt-file alike; the SDK's
excludeDynamicSections only moves it there. claude.exe on xiaomi-gpu gives
the same section with the Windows platform, temp folder and OS version.

13f9c7fca already told a run that the caller's environment wins, but only
when the caller's instructions name a folder in a form clientNamedWorkDir
reads, and never a lean run. Now:
- serveSubscription marks a request not from this computer
  (Request.remoteCaller = !local(r)). A run in magpie's folder for such a
  caller that names no folder (envUnknown) gets envUnknownNote after its
  instructions: the environment given elsewhere is not where the tools
  run, so no platform, shell or path is taken from it. A caller with no
  system prompt gets the instructions block for the note alone.
- a lean run gets the note in its system prompt (leanSystem), the named-
  folder one worded envElsewhereLeanNote since the environment comes after
  it there. startRun now picks the folder before writing system.md.
- A caller on this computer that names no folder, a run in the caller's
  own folder, and a named-folder caller in the non-lean run are told what
  they were before, so their cached prompts are unchanged.
The notes name no app and no vendor. Nothing else of the request changes:
no flag, header, env or Claude Code prompt text. Gateway facts beyond the
environment section don't reach the prompt: --setting-sources "" (no
CLAUDE.md), CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 and
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1 were already set.

Tests: TestClaudeRemoteCallerNamingNoFolderIsToldToolsAreElsewhere (IPv4
and IPv6 remote, with and without a system prompt, loopback, remote
naming a folder) and TestClaudeLeanPromptSaysWhereToolsRun. Both are red
on origin/main's claude_subscription.go and ir.go (0 of 2 runs told; lean
system prompt "Rules."). TestClaudeLeanPromptIsTheRunsSystemPrompt and
TestClaudeClientCacheAbsentUnchanged now send from loopback, which they
were about all along (httptest's address is another computer's).

Run (mote-run): go test ./internal/gateway -run
'Claude|Bridge|Subscription|Lean|Prompt|WorkDir|Resume' ok;
go test -timeout 45m ./internal/gateway: ok (532s); go vet ./internal/gateway
for darwin, linux (-tags nogui) and windows ok; gofmt -l clean. win-run on
xiaomi-gpu: the touched tests ok (the script-driven ones skip on Windows).
Real claude 2.1.312 fed the new first message: the note follows the
environment reminder inside external_system_instructions.
Not tried: a real model turn from a Mac client through a Windows
gateway, so whether the model now stops wrapping commands in PowerShell
is not measured; packinggoods's client and magpie version are not known.
2026-10-30 01:23:03 +08:00
yetone 9101bb8879 privacy: a request masking would change can go as written to a model you picked
jessyoungyu on X: when a masking rule hits, send the request to a
self-hosted model instead, so a prompt like 「百度这家公司怎么样」 gets an
answer about Baidu, not about a placeholder.

Settings › Privacy › Instead of masking, send to (settings
redactRouteTo). It is Off by default, and nothing changes for a user who
leaves it Off. It is picked in the app menu, and only models whose every
route is unmasked can be chosen: the provider is set to Send requests
unmasked, it is on this computer or the network, it has no account, and
any fallback or group member is unmasked too (gateway.MaskRoute, the
same rule as provider.SkipsRedaction). The setting is saved on its own
with POST /api/settings/redact-route, which checks it with MaskRoute.
The general settings save keeps the value.

Decisions:
- When a value would actually be masked on an agent's turn (maskHits.n
  > 0), serve sends the request to the chosen model unmasked. Warn-only
  hits don't count, and Block still answers 400.
- If that model fails, the request fails. It is never masked and re-sent
  to the model the agent asked for, and never goes to a cloud model with
  the unmasked text. Falling back to a masked cloud request would answer
  a different question in the background. The user picked this route
  because masking breaks the answer.
- Streaming works the same as on any route.
- The route is checked again on every request. A model that is gone or
  no longer unmasked, or that the caller's gateway key may not use,
  means the request is masked as before.
- Covered: agents' Messages, Chat, Responses and Gemini turns (serve,
  marked by serveAgent), count_tokens, Codex magpie-model turns, and
  Codex own-sign-in /responses (codexMaskRoute).
- Not covered: magpie's own asks (ownAsk clears the mark), embeddings,
  audio, images and video. These stay masked.

GUI: redactRouteRow lives in plugins/redact/settings.js and wraps
renderRedact, so app.js is byte-for-byte unchanged and the core budget
is not raised. Strings are added in zh, zh-TW, ja and de. Docs: gateway-routing.md,
gui-shell.md, and site/public/docs masking (en, zh, ja).

Tests: internal/gateway/mask_route_test.go
(TestMaskedRequestGoesToTheModelSet: unset, set, streamed, nothing to
mask, local fails, falls back to a vendor, no longer unmasked,
count_tokens; TestCodexSigninTurnGoesToTheModelSet;
TestMaskRouteTakesOnlyUnmaskedRoutes; TestMaskRouteOnlyForTheAgentsTurn);
internal/gui/redact_route_test.go; settings_keep_test.go;
internal/gui/tests/redact-route.test.cjs (every language, chromium and
webkit, 1100 and 640 wide).

Broken by hand, each red:
- serveAgent without the agent mark;
- MaskRoute taking any route (TestMaskedRequestGoesToTheModelSet,
  TestMaskRouteTakesOnlyUnmaskedRoutes; at the pushed head);
- the codex hook removed;
- count_tokens without the mark;
- ownAsk not clearing it;
- no key check;
- no reroute in serve;
- the GUI: no keep in the general save, no MaskRoute check on save, and
  the picker listing every model;
- the plugin script left out of index.html (redact-route.test.cjs 22 of
  24 red; at the pushed head).

Run on mote:
- at 221ede767's tree, this change on f5806ed21 (pushed on 44d697993,
  which adds only app.css lines and a Gateway page GUI test):
  go test -tags nogui ./internal/gui ./internal/settings ok (the core
  budget is green again since ec789445d; #4307, filed and closed);
  the mask-route tests in ./internal/gateway ok; GOOS=linux go vet
  -tags nogui ./internal/gui ./internal/gateway ok; GUI: node --test of
  redact-route, redact-*, privacy-*, mask-*, masking-*, settings-*,
  i18n-keys, account-discovery, sessions-reads and gui-de/ja/zh-tw:
  643 pass, 0 fail. gofmt -l clean.
- at the same change on af8f3a939, one rebase back (the only
  difference is index.html's script order and main's own commits):
  go test -timeout 45m ./internal/gateway (488s) ./internal/redact
  ./internal/settings ./internal/provider ok; GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./..., go vet ./... ok.
The whole Go suite was not run; every package this change touches was
run above.

Not tried: a real self-hosted model (Ollama) with a real agent. The
local model is a fake Chat server in the tests.
2026-10-30 00:46:45 +08:00
yetone f5806ed21e agent: Codex's forced_login_method = "api" counts as no ChatGPT sign-in (Tiger)
Tiger on Discord: after restarting Codex the Codex app showed a sign-in
screen whose only option was "Sign in with an API key", and they couldn't
get back in.

Cause: a top-level forced_login_method = "api" in ~/.codex/config.toml.
Other tools and guides write it; magpie never has (git log -S). With it,
Codex won't use a ChatGPT sign-in: the TUI logs it out as it starts
(codex-rs login/src/auth/manager.rs enforce_login_restrictions) and the
app server reads no account (load_auth). The app takes its allowed
methods from configRequirements/read, which then says ["api"]. magpie
read auth.json alone (codexChatGPTKnown), counted the sign-in, and wired
Codex beside it: the built-in provider, which requires OpenAI auth. The
app asked for a sign-in that only an API key could give.

Fix: codexChatGPTKnown reads forced_login_method = "api" as no ChatGPT
sign-in. magpie is then Codex's provider without requires_openai_auth,
and Codex needs no sign-in for magpie's models. The user's line stays
(magpie's default never overrides the user's value). Taking it out
brings the ChatGPT account back: Sync writes requires_openai_auth = true
again. connectinfo's codexChatGPT gets the same answer.

Run:
- real codex app-server 0.162.1 on mote in sandbox CODEX_HOMEs (stdio
  JSON-RPC: account/read, getAuthStatus, config/read,
  configRequirements/read). Beside a ChatGPT sign-in with forced api:
  account null, requiresOpenaiAuth true, allowedLoginMethods ["api"] —
  Tiger's screen. magpie as the provider, no requires_openai_auth, same
  auth.json: requiresOpenaiAuth false, and auth.json kept.
- TestCodexForcedAPILoginIsNoChatGPT is red on the old codex.go (it
  wrote openai_base_url and requires_openai_auth = true beside the
  sign-in) and green with the fix.
- via mote-run: gofmt -l; go vet ./internal/agent for darwin, linux
  (-tags nogui) and windows; go test -timeout 45m ./internal/agent ok
  (150.6s); ./internal/provider ok earlier on the same codex.go change.

Not tried: the real Codex app (ChatGPT.app) against a running magpie
built with this; managed requirements.toml / MDM allowed_login_methods
and forced_chatgpt_workspace_id, which this doesn't read; a revoked
ChatGPT sign-in (jjt's report): magpie still counts its tokens as a
sign-in and wires Codex beside it, and the /models 401 there comes from
OpenAI, passed through.
2026-10-30 00:19:43 +08:00
yetone ec789445db gui: Settings' session rows are the sessions plugin's settings.js; app.js back under its budget
af8f3a939 (session reads, RustCats on X) added Settings › Privacy's
Agents' session history to app.js and took it to 1,314,299 bytes, over
its 1,311,735 budget, and the core scripts to 1,535,027, over 1,532,459:
TestCoreScriptBudget red on main.

Moved, not raised: renderSessionReads and loadSessionReads (Privacy's
Agents' session history) and renderSessionTerminal (General's Session
terminal, data-feature="sessions") go to plugins/sessions/settings.js,
loaded after app.js like plugins/gateway and plugins/search's settings.js
and drawn whether the plugin is on or off. The code is moved as it was;
app.js calls them by name as before. app.js is 1,310,042 and the core
1,530,770, both under budgets left as they are. Docs: gateway-sessions.md
and plugin-runtime.md name the new file.

Run on mote at this tree (on af8f3a939):
- go test -count=1 ./internal/gui: TestCoreScriptBudget ok; red only
  TestMainWindowCorners/macOS_26_SDK, the same on main (#3949, open).
- GUI, Chromium and WebKit: i18n-keys, sessions-reads (5 languages,
  390-900 wide), session-terminal, account-discovery, settings-general:
  every case ok.

Not tried: the real app.
2026-10-30 00:14:37 +08:00
yetone af8f3a9399 sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.

- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
  from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
  the aggregators (allFiles, callFilesWith, callSourcesWith,
  traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
  readers of an already-listed session (TranscriptOf, ContentOf,
  SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
  ErrNotRead, so a cache from before a switch was turned off goes no
  further. The Sessions list, stats, /api/sessions/overview, the call and
  trace indexes, Usage's agent-file calls and the Codex/Pi title readers
  all pass it.
- SettleReads decides once and saves: an install with sessions.json or
  a calls-v* cache read sessions before and keeps all on; a fresh one
  reads none, not asked. A saved value is never replaced; save, sync and
  restore keep it (KeepOwn); only SetSessionReads writes it. An
  unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
  shows a consent card: each agent found (by a stat of its folder only)
  with a switch, Allow selected and Allow all. Settings > Privacy >
  Agents' session history has "Agents found later" and a row per agent.
  Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
  says on stderr when nothing is allowed yet; the TUI's empty Sessions
  page says how.

Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).

Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).

Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
  GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
  change on 8c63c5b78: 79 packages ok; internal/gui red on
  TestSettingsSaveKeepsWhatItDoesNotSend (mine: SessionReads is written
  by SetSessionReads only, the test now sets it so; green after) and
  TestMainWindowCorners (the same on origin/main c1da9ccda, #3949).
- whole GUI suite (make test-ui, concurrency 2) at this change on
  8c63c5b78: 14985 tests, 276 failed in 44 files. Mine: i18n-keys
  (comments named "Allow all"/"Allow selected"; lowercased) and
  account-discovery (read the last Privacy heading; now the one above
  its list); both green after. The 44 files again on origin/main
  c1da9ccda: 36 red there too (#4304, with #3218, #3412, #3414, #3795,
  #4120, #4125). stays-strict green alone; gateway-key-models webkit red
  1 of 3 alone on main too; plugin-github de 440 red on main (#3218).
- at the pushed head (rebased on cd10dfbe6): go build ./...; go test
  internal/sessions, settings, cli, tui ok; internal/gui
  TestSettingsSave*, TestSessionReads*, TestSessions* ok; i18n-keys,
  account-discovery, sessions-reads: 62 pass, 0 fail.

Broken by hand:
- the aggregator filter off with the leaf gates on: green (the leaf
  gates hold); both off: TestFreshInstall red on List, Agents, Calls,
  CallSources, traces, stats, TranscriptOf and Search.
- consentApplies=false and Settings' old save({all}) without the rows:
  all 13 Chromium cases of sessions-reads red.
- sessNothing's hint removed: TestSessionsNotAskedSaysHow red.

Real binary in a sandbox HOME on mote (removed after): a fresh
`magpie sessions` is empty with the hint on stderr; `sessions read`
says not asked, claude off; `read --help` prints usage and saves
nothing; `read on claude` lists the one session; `read off all`
empties it again.

Not tried: the GUI and real app on Windows and Linux; WSL agents in the
consent list (WSL distros are not looked into; Allow all covers them);
a fresh install of a signed release build.
2026-10-29 23:56:05 +08:00
yetone c46829e0b4 routing: a group's card says its classifier's failure only when that group asked it
jjt on Discord: the Routing card of "claude难易" (group/claude-ny), which
no turn of theirs was sent to, said "分类器3分钟前失败:claude/claude-haiku-5-5:
Claude Code: You've hit your weekly limit", read as magpie asking its
classifier at every turn. The card read the failure by classifier model
(ClassifierFailure), so every group sharing a classifier showed the
failure of whichever group had last asked it.

What runs the classifier was not changed: ruleFor asks it only for a
request whose model is the group (group/<id>, its name, or a stand-in an
agent's config names it by: Claude Code's tiers, Codex's bare name), or
for a group in it its rules or order put first (nestedRules). A request
for another model or group asks nothing. Out of quota, the classifier's
account rests until the reset (restAfter), so later classifier calls get
magpie's held refusal back, at most once each classifyRest (30s), and
do not reach the vendor.

Now ruleFor notes the outcome per group (classifiedFor) and the card
reads GroupClassifierFailure(group, classifier): the classifier's own
words and time (resting or not) from that group's last ask, cleared when
it answers that group, and nothing once the group's classifier changed.

Run (mote, macOS 27, Go 1.26.8), at base 4586307de:
- gofmt -l internal: clean; go vet darwin, GOOS=linux -tags nogui,
  GOOS=windows for ./internal/gateway ./internal/gui: ok
- go test -count=1 -timeout 45m ./internal/gateway ./internal/gui:
  two reds, neither in this change. TestUnroutedHeldReportSaved passed
  5 of 5 alone after; filed #4300. TestMainWindowCorners/macOS_26_SDK
  is #3949.
- -run 'TestClassifierFailure|TestGroupsSayAClassifier': ok
- node --test internal/gui/tests/group-classifier-failed.test.cjs: 20 of
  20 (Chromium and WebKit, both widths, every language)
- Broken by hand: GroupClassifierFailure read by model as before, and
  TestClassifierFailureIsTheGroupsOwn went red ("idle, which nothing
  asked: c/cls: C: classifier down").
Not tried: a real Claude Code account at its weekly limit.
2026-10-29 23:36:58 +08:00
yetone 4586307de5 gateway: Codex's own model on a thread started on magpie goes on Codex's sign-in, not a 404
iuengei on Discord: after turning Codex's routing off and restarting,
Codex's official models answered "unexpected status 404 Not Found: magpie
knows no model \"gpt-6.1-sol\"", in ChatGPT and Always ChatGPT modes too.

A Codex thread keeps the provider it was started on (the
[model_providers.magpie] table stays for that reason). A thread started
while magpie was Codex's provider (magpie API, or the takeover of a
used-up account) goes on sending to /v1 after Disconnect or a switch back
to ChatGPT. An official model picked in it reaches serve as a bare
"gpt-6.1-sol"; with no ChatGPT account in magpie serving it (the Codex
sign-in removed from Providers, or subscription accounts off) it was
answered 404. /backend-api/codex relays such a model on Codex's own
sign-in; /v1 never did.

Now handle (Responses) puts such a request on the ChatGPT backend's route
(codexBackend) signed with Codex's own ChatGPT sign-in as Codex keeps it
(provider.CodexSignInAsKept, never renewed by magpie), magpie's key and
x-openai-actor-authorization left behind (codexOwnOffMagpie). Only for: a
bare model no provider, group or stand-in serves, not disabled or
switched off; one of Codex's own (its models cache, magpie's entries left
out) or OpenAI's in the catalog; from Codex on this computer (local); no
gateway key held to models or accounts. When the sign-in can't be had
(subscription accounts off, signed out, expired) the 404 says the thread
was started on magpie, why the sign-in can't be used, and to start a new
thread. Codex's identity and prompts are untouched.

Tests (internal/gateway/codex_own_v1_test.go): the reporter's case, a
sandbox HOME with Codex signed in, gpt-6.1-sol in its models cache, the
sign-in removed from magpie's Providers, Codex's request to /v1/responses
with magpie's key: was 404 "magpie knows no model \"gpt-6.1-sol\"", now
200 from a stand-in ChatGPT backend that got Codex's token and account
id, not magpie's key or header. Not sent: from another computer, a key
held to fake/*, a model that isn't OpenAI's (still 404). With accounts
off, a 404 that says why.

Run (on mote, at this commit's tree rebased on 173fb6ab0):
- gofmt -l internal/gateway internal/provider: clean
- go vet darwin, GOOS=linux -tags nogui, GOOS=windows for
  ./internal/gateway ./internal/provider: ok
- go test -timeout 45m ./internal/gateway ./internal/provider: ok (gateway 482s, provider 91s)
Broken by hand: the hook in handle off, GoesOnSignIn and SaysWhy are red
(the old 404); local() off, StaysHere/another_computer is red. The held
key is also kept off the relay by codexAccounts in codexBackend, so the
guard here off alone leaves that subtest green.
Not tried: a real Codex app thread against a real ChatGPT account (no
live ~/.codex touched).
2026-10-29 23:15:19 +08:00
yetone 92f02d677b agent: a VS Code fork's own code launcher no longer lists it as VS Code too (ggbr on Discord)
Qoder IDE was listed twice, as Qoder and as VS Code. Qoder IDE ships
a launcher named code in Contents/Resources/app/bin beside qoder
(checked in the 2026-10-29 Qoder-IDE-darwin-arm64.dmg: product.json
applicationName "qoder", nameShort "Qoder", com.qoder.ide), and its
Windows installers put that bin folder on PATH. VS Code's detection
falls back to a code on PATH, and vscodeCodeBinary ruled out only a
product.json naming Cursor (#931), so any other fork's code counted
as VS Code.

The class fix: a code, code-insiders or codium launcher counts as VS
Code, Insiders or VSCodium only when the product.json beside it
(app/product.json, or resources/app/product.json on Windows and
Linux) names that build in applicationName. With no applicationName,
nameShort must be one of VS Code's own (Code, Code - Insiders,
Code - OSS, Visual Studio Code, VSCodium). A wrapper with no readable
product.json keeps the PATH fallback as before. This covers Cursor,
Qoder IDE, Windsurf, Trae, Kiro, CodeBuddy, Antigravity and any other
fork, on the mac, Linux and Windows layouts. A VS Code User folder
still detects VS Code by itself: a user who has both has both rows.

Run:
- TestVSCodeDetected gains rows for Qoder (mac with the real build's
  product.json, linux, windows, symlink), Windsurf, Trae, Kiro,
  CodeBuddy, Antigravity, an Insiders product behind code, and
  nameShort-only products; TestVSCodeBuildLauncher checks each build's
  own command. Broken by hand: with the old vscode.go, 11 of the new
  TestVSCodeDetected rows fail (mac/linux/windows qoder, qoder
  symlink, windsurf, trae, kiro, codebuddy, antigravity, insiders
  product, qoder name).
- Real Qoder IDE: on mote, the dmg's bin folder alone on PATH,
  vscodeCodeBinary(".../Qoder IDE.app/.../bin/code") = false and
  VS Code not Detected.
- gofmt -l clean; go vet ./internal/agent for darwin, linux (-tags
  nogui) and windows on mote.
- go test ./internal/agent -timeout 45m on mote: ok (171.6s) at this change on base abd94e0b1
- At the rebased head (on f49cebb35; nothing in internal/agent changed
  since abd94e0b1): TestVSCode* ok on mote.
- win-run TestVSCodeDetected and TestVSCodeBuildLauncher: pass on
  Windows 11. wsl-run TestVSCode -tags nogui: pass on Ubuntu 24.04.

Not tried: a real Windows or Linux Qoder IDE install (its Windows
bin layout is assumed from VS Code's installer, which the fork keeps).
2026-10-29 23:03:29 +08:00
yetone f11bf27c1f video: a plugin's model that gives video makes videos through its fetch on the account
XYenon asked for video for account-backed plugins: customVideomakers
left out every provider with an Account. A plugin's model that says it
gives video (capabilities.output.video / modalities.output) is now a
video maker (the Grok plugin keeps its own). Start, poll and content go
OpenAI-shaped to <base>/videos, /videos/{id} and /videos/{id}/content
through the plugin's fetch (videoBase now takes Provider.OpenAIBase,
the Chat base for any other provider). The video's id names the account
that started it (keyMark: "a" + signer), and markedKey asks after it on
that account of the plugin's (AlsoOn), as a key provider's videos are
asked on their key. Account and model holds (videoAsker,
videoModelHeld) and the start's usage row are the existing paths'.

Test: TestPluginMakesVideos (fake $FAKE_VIDEO, two accounts): started
by a key held to the second account, polled and fetched on it, a key
held to the first gets 403 on the poll, a key held to other models 403
on the start and the poll; the start is in the ledger. Broken by hand:
with the old video.go the video makers are empty (red); without the
account mark the poll goes to the first account and the content is
refused 403 (red).

Run on mote: gofmt -l clean; go vet ./internal/gateway ./internal/provider
./internal/plugin for darwin, linux (-tags nogui) and windows; go test
-count=1 -timeout 45m ./internal/gateway ./internal/plugin
./internal/provider ok at the tree of the video commit (7b8456f88), the three plugin-media commits
rebased on abd94e0b1 (gateway 504s, plugin 265s, provider 95s).
Not tried: a real Veo account through a plugin; no plugin serves
/videos yet.
2026-10-29 22:54:06 +08:00
yetone 6cb73ec4f0 gateway: embeddings and speech reach a plugin through its fetch whatever API its chat is on
XYenon asked how /v1/embeddings and /v1/audio/speech reach a plugin
whose models are all on Gemini's API. serveRetrieval sent them under
the provider's Chat base, which a plugin has only with an
@ai-sdk/openai-compatible model, so such a plugin was turned away 400
"has no OpenAI-style API". Provider.OpenAIBase is plugin://<id>/v1 for
a plugin (the Chat base for any other provider), and serveRetrieval
(embeddings, rerank, speech, transcriptions, translations) sends under
it: the request reaches the plugin's fetch OpenAI-shaped at
<base>/embeddings or /audio/speech, with the model's own id, for the
plugin to put in its vendor's shape. magpie converts none of them to
Gemini's embedContent or TTS; the plugin owns its vendor's protocol.
Key holds, account holds, masking and usage are serveRetrieval's, as
before.

Test: TestGooglePluginTakesEmbeddingsAndSpeech (fake $FAKE_GOOGLE: every
model on @ai-sdk/google, with $FAKE_KINDS' embedding and TTS): both
reach the vendor through the fetch, both are in the usage ledger, a
key held to other models gets 403 on each. Broken by hand: with the
old Base(provider.Chat) it is red (400 "has no OpenAI-style API").

Run on mote: gofmt -l clean; go vet ./internal/gateway ./internal/provider
./internal/plugin for darwin, linux (-tags nogui) and windows; go test
-count=1 -timeout 45m ./internal/gateway ./internal/plugin
./internal/provider ok at the tree of the video commit (7b8456f88), the three plugin-media commits
rebased on abd94e0b1 (gateway 504s, plugin 265s, provider 95s).
Not tried: a real Google AI Studio account through XYenon's plugin.
2026-10-29 22:54:06 +08:00
yetone e2b7233499 draw: a plugin's Gemini image model draws on generateContent through its fetch
XYenon (magpie-google-ai-studio, Discord) asked how a plugin's image
models reach /v1/images/generations and /v1/images/edits. A plugin's
model on Gemini's API (@ai-sdk/google) that says it gives images
(capabilities.output.image / modalities.output), or is named for them,
is now a drawer: Drawers lists it, and draw sends it to drawCodeAssist
(pluginDrawsGemini), as a Google sign-in's image models are drawn. That
asks generateContent with responseModalities ["TEXT","IMAGE"] through
the plugin's fetch, an edit's pictures as inlineData, and reads the
pictures from the answer. Request.draws asks for the IMAGE modality of
a model not named for images. Imagen (catalog.ImagesAPI, :predict) is
left out. The OpenAI-compatible plugin path (SenseNova) is unchanged.

Test: TestGeminiPluginDraws (fake plugin $FAKE_GEMINI_DRAWS: a model
named for images, one that only says it gives them, an Imagen).
Broken by hand: with the old draw.go the drawers are empty (red); with
the old codeassist.go the declared-only model is sent no
responseModalities (red).

Run on mote: gofmt -l clean; go vet ./internal/gateway ./internal/provider
./internal/plugin for darwin, linux (-tags nogui) and windows; go test
-count=1 -timeout 45m ./internal/gateway ./internal/plugin
./internal/provider ok at this commit on its first base 172e65c80
(gateway 515s, plugin 104s, provider 104s), and ok again with the next
two commits on top, rebased on abd94e0b1 (tree 7b8456f88: gateway 504s,
plugin 265s, provider 95s; vet for the three systems there too).
Not tried: a real Google AI Studio account through XYenon's plugin.
2026-10-29 22:54:06 +08:00
yetone 172e65c80b agent: a Windows app closed to the tray is ended at once on Restart, not after 10s
CyberCaius on Discord (10-29): magpie's Restart of Claude Desktop on
Windows is slower than quitting and opening it by hand. The cause:
RestartApp asks the app's windows to close (taskkill without /F), then
waited up to appCloseWait (10s) for every claude.exe to end. Claude
Desktop on Windows hides its window to the tray in ~0.6s and keeps all
its processes, so every Restart sat out the whole 10s before ending the
tree.

waitClosed now also watches the windows (winShown, EnumWindows +
IsWindowVisible over the app's pids): once every window is hidden and
the app still runs appTrayGrace (1s) after the close, it is in the tray
and its tree is ended at once. An app still showing a window (a
question) keeps the full appCloseWait, and one that ends by itself in
the grace is never ended. When the windows can't be listed, it is
treated as shown (the old wait). The Windows part of RestartApp moved
into restartWin, unchanged otherwise.

Measured on the Windows box (xiaomi-gpu, Squirrel Claude Desktop
4.29.0, run in the interactive session through a scheduled task), the
real restartWin path through a test binary, 3 runs each:
  before (tray grace off): returned 10.87-11.10s, window back 11.4-11.7s
  after: returned 1.88-2.16s, window back 2.4-2.8s
A forced kill and relaunch by hand: ~1.6s. A PowerShell emulation of the
old path on 2.9939.2 earlier: WM_CLOSE hid the window at 0.6s, 9
processes stayed, all gone only after the 10s kill (12.3s total).

Run:
- TestRestartEndsAppInTrayAtOnce (new): tray / asking / quits-itself.
  With the winShown check removed by hand, the tray case went red
  (took 3.01s, want under 2s).
- mote: go test ./internal/agent -count=1 -timeout 45m: ok (174s).
- win-run: TestRestartEndsAppInTrayAtOnce, TestWorkBuddyRestartOnWindows,
  TestRestartAppsOnWindows pass. The -run Restart|ChangedAt|WorkBuddyOwnSave
  set has TestWorkBuddyOwnSaveAfterStartIsNoChange red on Windows, red
  the same on untouched origin/main 5be581a1c (3 of 3); filed in #4115.
- mote: gofmt -l, go vet ./internal/agent for darwin, linux (-tags
  nogui) and windows: clean.

Not tried: the MSIX (Store) Claude build, and WorkBuddy on Windows with
the real app.
2026-10-29 22:25:36 +08:00
yetone fd5c631cbe image mcp: generate_image and generate_video take the model to use (XYenon)
XYenon on Discord asked whether an agent can pick the model magpie's
image/video MCP draws with. Both tools now take an optional `model`,
as provider/model:

- The schema lists the models that may be asked (the Settings default
  first, then each on provider's OfferedDrawers or Videomakers), only
  those the calling gateway key may use. Up to 40 of them form an enum;
  past that, the description names three.
- Left out, the Settings default is used, as before.
- A bare id only one provider has, a ChatGPT account's other GPT Image
  name (ListedDrawer), or a newer family model (drawsFamily,
  grokVideoFamily) is accepted. Anything else is a tool error naming the
  models the key may use, and nothing is drawn. It never falls back.
- The chosen model goes into the images/videos request's `model`, so
  the APIs' own key check (keyHolds, keyModelError, #882) refuses one
  the key may not use: the same check /v1/images makes.
- The stdio Magpie Image server copies the gateway's `model` property
  from its tools/list, and asks the hidden JSON-RPC method
  magpie/media_model which model a call means. An older gateway
  (-32601) passes the model through as named.
- `magpie tool generate_image --model ...` works through the schema;
  the usage text says so.

Docs: gateway-routing.md (image MCP section), reference.md.

Run (mote, via mote-run, at this tree):
- gofmt -l: clean.
- go vet ./... for darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/imagemcp/
  ./internal/cli/: ok.
Broken by hand: with `req["model"] = ref` dropped in imageMCPDraw and
imageMCPFilm, TestImageMCPDrawsWithTheModelAsked,
TestImageMCPModelHeldToTheKey and TestImageMCPVideoModelAsked go red
(the default was drawn instead); restored, they pass.
Not tried: a real vendor account. The fakes are easeled's art provider
and the fake Grok. GUI files not run: no GUI file changed.
2026-10-29 22:16:56 +08:00
yetone ba3a7384fb gateway: a Responses request may name the response it follows (previous_response_id, kevinzhow on X)
kevinzhow on X: magpie didn't support previous_response_id on
/v1/responses, so every turn carried the whole conversation, images
included, and each turn was slow.

Before: magpie kept no responses. previous_response_id went on as
sent, so a provider that never made that id (or a route that translates
to Chat or Messages) had nothing but the new input to give the model.

After (prev_response.go, run in serveAgent before anything reads the
body):
- Each Responses reply passed with 200 (not failed/cancelled, not cut at
  64 MB) is kept by its id with input + output, in memory, LRU to 256 MB
  of own bytes, 6h TTL. store:false keeps nothing.
- Kept per caller (prevScope): gateway key, remote magpie, keyless remote
  address. Another caller naming the id is told it isn't there.
- A kept id expands the request to the whole conversation, so routing,
  translation and masking see what they would have seen had the client
  sent it all. Masking runs on each request as it goes (deterministic
  placeholders), so a stored secret is masked the same on every turn;
  TestPreviousResponseMasked.
- An unknown id gets OpenAI's 400 previous_response_not_found on a route
  that translates (and on Claude/Codex accounts), before anything is sent.
  A Responses relay is sent the id as it came.
- Where the provider keeps responses itself (prevKeeps: API key, no
  plugin; api.openai.com, Azure, or Ark /api/v3 pay-as-you-go) and it
  answered the previous turn on the same key, with store not off, only
  the new input goes with the provider's own id (prevDelta). A provider
  that says it doesn't know the id (prevRefused) is sent the whole
  conversation at once.

Codex: its HTTP ResponsesApiRequest has no previous_response_id; only the
websocket's ResponseCreateWsRequest has it (openai/codex 9def09a,
codex-rs/codex-api/src/common.rs:341, client.rs:2284). Over HTTP it sends
store:false with the whole input, so nothing it sends or keeps changes.
No prompt is touched.

Ark checked with a real pay-as-you-go key (10-29): store:true then
previous_response_id returned the stored word; an unknown id answers 400
InvalidParameter.PreviousResponseNotFound (param previous_response_id),
which prevRefused matches.

Tests (prev_response_test.go): GivenWholeToChat (3 turns), NotFound
(unknown, other key, no key, store:false; upstream not called),
UnknownPreviousResponseRelayedAsSent, KeptUpstreamSentNewInputOnly
(200 KB image; delta < 2000 bytes; refusal retried whole), Masked,
PrevStoreBounded.

Broken by hand, each red, then restored:
- previousResponse a no-op: GivenWholeToChat, NotFound, KeptUpstream,
  Masked red.
- prevDelta off: KeptUpstream red (200355 bytes sent, no prev id).
- prevRefused always false: KeptUpstream red at the retry turn (400
  relayed).

Timings on mote (BenchmarkImageRequest / BenchmarkPreviousResponseTurn,
8 images, 20.18 MB conversation):
- whole Responses -> Responses: 277 ms, 145.6 MB/op before; 263 ms,
  145.6 MB/op after (a first version that json.Unmarshal'd the input
  cost 364 ms and +20 MB; it now reads items over the body's bytes).
- whole Responses -> Chat: 273 ms before, 224 ms after.
- previous_response_id to a provider that keeps responses: client sends
  82 B, upstream gets 122 B (was 20.18 MB each way), 309 ms locally.
- previous_response_id to Chat: client sends 83 B, upstream gets the
  whole 20.18 MB, 295 ms.

Run at this head on mote: gofmt -l clean; go vet ./internal/gateway for
darwin, linux, windows ok; go test -count=1 -timeout 45m
./internal/gateway ./internal/redact: gateway ok (464.4s), redact ok (1.8s).

Not tried: a real OpenAI or Azure key (Ark's real key only); Ark's
Coding Plan Responses path (not in prevKeeps). The store is in memory,
so ids are lost on restart (a translated route then answers 400, a relay
passes the id on). A kept-id request is still read and masked whole on
this computer before the delta is cut (~300 ms local for 20 MB).
Doc: docs/subsystems/gateway-routing.md, "A Responses request that names
the response it follows".
2026-10-29 21:25:33 +08:00
yetone 8e5567161e settings: an older settings.json with no Dock choice keeps Hide
v0.1.2060 (1407c9a3b) made With window the default for a settings file
with no Dock choice. Before it, Hide was the default and was stored as
nothing, so a user who picked Hide can't be told from one who never
chose, and v0.1.2060 put both in the Dock and Command-Tab. That broke
"never let magpie's default override a value the user set".

What changes:
- A new field, dockSettled, marks a file whose Dock choice is read with
  With window as the default.
- A file without it is read the way an older magpie read it
  (settleDock): no Dock, dockWindow or dockNever means Hide (dockNever),
  and the next save writes it settled. This happens once.
- A missing file (a new install) is settled from the start, so it gets
  With window.
- A file nobody can read is read like an older one, Hide.
- The Settings page never sends dockSettled; the API save keeps the
  file's. Without that, a new install's first save from the page would
  turn into Hide.
- KeepOwn keeps it machine-local, like the choice itself.
- An older magpie writing the file drops the marker, and the file then
  reads as old (Hide unless it chose), which is what that magpie meant.
- v0.1.2060 users who picked a choice keep it. Those who picked nothing
  are back to Hide and can choose With window under Settings › Show in
  Dock.

Tests:
- TestOlderSettingsKeepHide: {} and {"theme":"dark"} read and save as
  Hide; dockWindow, dock and dockNever are kept; a second read is
  unchanged.
- TestNewInstallFollowsWindow: no file means With window, settled, and
  the first save reads back the same.
- TestSettingsSaveKeepsDockReading (gui, !nogui): a POST /api/settings
  from the page keeps a new install in the Dock while open, and keeps an
  old file's Hide.
- TestLoadChecked's unreadable-file default now expects the settled Hide.

Broken by hand (each red, then restored):
- settleDock not setting dockNever: TestOlderSettingsKeepHide red,
  "{"theme":"dark"} read as ... never false".
- The missing-file branch not settling: TestNewInstallFollowsWindow red,
  "settled false".
- api.go not carrying DockSettled: TestSettingsSaveKeepsDockReading red,
  "a new install: after a save from the page ... in the Dock ... false".

Run at this commit's tree (9bdb831b7 before this body, on origin/main
66b5e4a84), on mote via mote-run:
- gofmt -l: clean.
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: all ok.
- go test -count=1 -timeout 45m ./internal/settings ./internal/gui:
  settings ok. In gui the only red is TestMainWindowCorners/macOS_26_SDK,
  which is red on origin/main on mote too (#3949).
- node --test dock-choice, settings-general and i18n-keys: 34/34 (5
  languages, chromium and webkit, 1000px and 440px).

Real app on mote: a -tags dev build, bundled as com.yetone.magpie.sbtest,
in a sandbox HOME on 127.0.0.1:3591/3592, launched with its window open,
type read with lsappinfo:
- An old {"theme":"dark"} file: UIElement (not in Command-Tab); the file
  now has dockNever and dockSettled.
- No file: Foreground; dockSettled is set, dockNever is not.
- An old {"dockWindow":true} file: Foreground.

Not tried:
- Closing the window by hand on mote, since ssh has no Accessibility.
- A downgrade to v0.1.2060 and back again with a real file (reasoned
  above).
2026-10-29 20:53:36 +08:00
yetone 66b5e4a844 provider: every request to a Remote magpie carries the provider's Headers; its key always goes as x-api-key (Yirasumi)
Yirasumi on Discord: with a Remote magpie behind something that wants
its own header, chat worked but the Usage page's read of the remote went
without the provider's Headers. remoteJSON (the remote's cards, a card's
refresh, its quota history) and askRemoteKeyLimit (each gateway key's
limit) set only Authorization: Bearer <key>.

- signRemote puts the provider's Headers on those four, as Sign and
  listHeaders already did for API requests and the model list. They are
  no turn of a conversation: ${sessionId}/${threadId} are an id of their
  own (SentHeaders with no conversation, v0.1.2058's path).
- Auth, decided: the key always reaches a remote magpie as x-api-key
  (remoteKey), which a magpie gateway reads beside Authorization. A
  user's Authorization (a proxy's own scheme) goes in place of magpie's
  Bearer copy, as it already did on API requests and the list, without
  taking the key away; a user's x-api-key is never sent to a remote
  magpie. Sign now adds x-api-key for a remote magpie on every API (it
  had it on Messages only), and listHeaders drops a user's x-api-key, so
  a user's Authorization no longer leaves chat or the list without the
  key, and each key's limit is read with that key.
- docs/subsystems/providers-accounts.md: a "remote magpie's headers" row.

Other requests to a remote magpie (every API, count_tokens, System One,
images, videos, embeddings, searches) already go through Sign; the model
list through listHeaders. No other request to one was found
(grep of p.Anthropic+, /v1/magpie/ and IsRemoteMagpie callers).

Run on mote at this head (rebased on 1407c9a3b):
- gofmt -l internal/: clean
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok
- go test -tags nogui ./internal/provider ./internal/gateway -timeout 45m:
  ok (90s, 487s)
- TestRemoteMagpieRequestsCarryHeaders (new): cards, refresh, history,
  both keys' limits, model list and a signed chat request, with and
  without a user Authorization.

Broken by hand, each red, then restored: the old code (every quota path
without the header, no x-api-key, a user x-api-key replacing the key on
list and chat); Sign without remoteKey (chat's x-api-key the user's);
listHeaders keeping the user's x-api-key (list red); signRemote without
the user's headers (cards, refresh, history, limits red).

Not tried: a real proxy in front of a real remote magpie, or two real
magpies; checked against a local httptest remote only. The GUI is not
changed.
2026-10-29 20:50:18 +08:00
yetone 1407c9a3bb gui: the Mac's window is in the Dock and Command-Tab while it is open, by default (ShouguangCao on X)
ShouguangCao on X: on the Mac, with the window (Settings) open, magpie
wasn't in Command-Tab, so going back to it to paste an API key copied in
another app took the menu bar.

Cause: Settings > Show in Dock already had "With window" (#101: Regular
activation policy while the main window is up, Accessory once it closes,
in openMain/hideMain through inDock and setDock), but the default was
Hide, so out of the box magpie stayed Accessory with its window open. The
main window is magpie's only window besides the tray panel, so no other
window kind needed it.

Change: With window is now the default. inDock is
`s.Dock || !s.DockNever && shown || fullscreen`; Hide is a choice of its
own, settings.DockNever (KeepOwn, like Dock and DockWindow), and the page
reads the choice through dockChoice (With window unless Show or Hide was
chosen) and saves dockNever with it. DockWindow is still written when
chosen, so an older magpie reading the file keeps With window. The tray
panel never calls dock(), so it is unchanged; Windows and Linux have no
Dock (setDock is a no-op there) and are unchanged.

For existing users: Hide was the default and was stored as nothing, so a
user who picked Hide before can't be told from one who never chose; both
now get With window, and choosing Hide again sticks (dockNever).

Run on mote at origin/main 2c89794ac + this commit; after rebasing onto
2d11cde05 (internal/provider only) the Go tests below were run again at
this head, same result:
- gofmt -l: nothing; go vet (darwin), GOOS=linux go vet -tags nogui,
  GOOS=windows go vet of internal/gui and internal/settings: ok;
  GOOS=linux go build -tags nogui and GOOS=windows go build: ok.
- go test -count=1 ./internal/gui/ ./internal/settings/: settings ok; gui
  ok except TestMainWindowCorners/macOS_26_SDK, red on origin/main
  2c89794ac on mote too (#3949, macOS 27).
- GUI, chromium + webkit: dock-choice (new, 5 languages),
  settings-general, lightweight, keep-awake, i18n-keys,
  classify-timeout-setting, image-timeout-setting, searcher-pick,
  side-effort, gui-de, gui-ja, gui-zh-tw: 158 of 159; the one red,
  searcher-pick chromium zh (a null box at line 224 under load ~30),
  passed 22 of 22 alone and is filed as #4274.
- Real app on mote (macOS 27.2): a bundle with its own bundle id, sandbox
  HOME, MAGPIE_ADDR 127.0.0.1:3591, launched with `open -n ... --args
  app`. A fresh settings.json (no dock keys) with the window open:
  lsappinfo type="Foreground" (in Command-Tab and the Dock). Through the
  real /api/settings (dev build's MAGPIE_DEV_UI) with the window open:
  Hide -> "UIElement", With window -> "Foreground", Hide -> "UIElement",
  nothing chosen -> "Foreground".

Broken by hand: inDock put back to `s.DockWindow && shown`:
TestDockFollowsWindowByDefault red ("default, window open: inDock =
false, want true"). dockChoice put back to read dockWindow: dock-choice
red 5 of 5 (chromium).

Not tried: closing the window by hand on mote and watching it leave
Command-Tab (ssh there has no Accessibility to press Cmd-W or the close
button); that path is #101's hideMain -> inDock(shown=false), unchanged,
and TestDockFollowsWindowByDefault covers "default, window closed".
Not tried on a real Command-Tab switcher by eye.
2026-10-29 20:38:00 +08:00
yetone 810a4144fe catalog: a model's Same as gives it that model's window, levels and images; a channel's tag in brackets is read past (pinmmis on X)
pinmmis on X (tweet 2115776439341506603): the same model from several
relays, each renamed to be told apart ("ds.4.1(WB)" for
deepseek-v4.1-flash), had none of models.dev's specs, and setting each
spec by hand per model was the only way.

The ids are the relay's own (magpie looks up the model's id, not a
display name), so this is not a display-name bug. The editor's
per-model "Same as" (settings' ModelSameAs) already merged routing
groups and priced the model; now it also gives the model that model's
window, reply limit, reasoning levels, thinking and images:

- catalog.UserSame, set by the settings package (sameas.go,
  sameAsBare: ModelSameAs indexed by bare model id, memoised per
  shared map), is asked by contextIn/lookupIn after the id as given
  and before magpie's own guesses (renamed, normalFor). An id
  models.dev lists stays its own; the user's own window, output,
  levels and images settings still win (callers read them first).
  The model named is looked up once, never sent back to UserSame (no
  loops). KnowsAsWritten (usage telemetry) never hears it.
- Zero-config part: those lookups also read past a channel's tag in
  brackets at an id's start or end (untagged: "deepseek-v4.1-flash
  (WB)", "[WB] ...", fullwidth and CJK brackets). A "[...]" written
  onto the id with no space is not a tag ("deepseek-v4.1-flash[fast]"
  may be a variant, TestRenameNeverTakesAModelForAnother). Prices are
  never borrowed this way (TestOtherSpellingIsNotPriced's rule); a
  Same as's price is still SamePriceIn.
- "ds.4.1(WB)" itself is not guessed: ds/4.1 could be flash or pro.
- GUI: the Same as box's tooltip says what it now covers, in every
  language; provider-same-as.test.cjs checks every language, not zh
  only. No layout or API change.
- docs/subsystems/providers-accounts.md says it.

Run on mote via mote-run:
- at the same change on 2c89794ac: go test -tags nogui -timeout 45m
  ./internal/catalog ./internal/settings ./internal/provider
  ./internal/agent ./internal/gateway ./internal/gui ./internal/cli:
  all ok (gateway 525s).
- at this commit (rebased on 2d11cde05, which touched provider and the
  GUI): catalog, settings, provider, gui again: all ok
- node --test provider-same-as, i18n-keys, names-fold in chromium and
  webkit, at this commit: 16 of 16 pass.
- gofmt -l clean; GOOS=linux/windows/darwin go vet -tags nogui of
  catalog, settings, provider: clean.
- Real use: magpie built in a sandbox HOME on mote with the real
  models.dev cache, a relay provider with ds.4.1(WB) (Same as
  deepseek-v4.1-flash), ds.4.1(other) and "deepseek-v4.1-flash (WB)":
  `magpie model spec` gives the first and third 1048576 / 384k /
  vision on / low,high,max, the second unknown.

Broken by hand: userSame and untagged made to find nothing ->
TestUserSameGivesTheSpecs, TestTaggedIDHasTheModelsSpecs (17 errors)
and TestSameAsGivesAnUnlistedModelItsSpecs go red.

Not tried: a real relay request in the GUI app; Windows/Linux runs
(pure Go lookups, no OS paths); the whole GUI suite (only a tooltip
string changed).
2026-10-29 20:36:04 +08:00
yetone 2d11cde056 provider: ${sessionId} and ${threadId} in a provider's Headers are the conversation's ids
Axel Burks on Discord (#feedback): his gateway in front of several Azure
accounts routes one conversation to one account by a session header, so
its reasoning can be read back. ${sessionId} was expanded only in Extra
body; in Headers it went out literally.

Now Sign expands ${sessionId} and ${threadId} in header values
(Provider.SentHeaders, conversation.go), with the id Extra body gets:
the agent's session header, else the id derived from the first user
message. The gateway carries it to Sign in the request's context
(WithConversation), on every API and count_tokens.

- ${threadId} is Codex's thread_id (turn metadata or thread-id header,
  threadOf), which a subagent has of its own while sharing its lead's
  session_id. No other agent names a thread; there it is the session's id.
  Supported in Extra body too. Read only when a header or Extra body
  names it (AsksThread).
- A request that is no conversation turn (model list, balance, embedding,
  image, Azure/Kilo lists, a remote magpie's list) gets an id of its own,
  "magpie-" and 12 random letters; Test and Detect use their
  magpie-test-… id in headers and body alike. A literal placeholder is
  never sent.
- Control characters (CR, LF, tab, NUL, DEL) are stripped from ids in a
  header (headerSafe); with a CRLF id Go used to fail the request 502.
- GUI: Headers and Extra body hints name both placeholders, in en, zh,
  zh-TW, ja, de. docs/subsystems/providers-accounts.md has a Headers row.

Run on mote at this head (rebased on 774baed6d):
- gofmt -l internal/: clean
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./...: ok
- go test -tags nogui ./internal/provider ./internal/gateway -timeout 45m:
  ok (121s, 570s)
- go test -tags nogui ./internal/gui: ok
- node --test header-session-hint (new, 5 languages x chromium/webkit),
  extra-body, i18n-keys, reply-headers, provider-auth-header: 52/52

Broken by hand, each red, then restored: Sign sending raw p.Headers (the
literal goes out); no headerSafe (502 invalid header field value);
threadOf returning "" (TestThreadIDIsCodexThread); tested not putting its
id in ctx (TestHeadersTakeTheConversation); listHeaders raw (list sends
the literal); the de hint's suffix removed (chromium de red).

Not tried: a real Azure gateway or any real vendor; checked against local
httptest servers only. Codex's thread_id read from fixtures shaped like
Codex 0.162's metadata, not a live Codex run.
2026-10-29 20:31:20 +08:00
yetone 2c89794acb gateway: a provider's fallback gives the conversation back once the provider is ready (01huadalang)
01huadalang on Discord (#feedback): once a provider's main model works
again, a conversation that went to its Fallback while it was down stayed
on the fallback, with no switch to stop it. affine treated the fallback
as any answerer: Auto kept it while its cache was worth reading (each
turn read it again, so it never went cold), Session for the session, and
a rotating provider's new turn went to the one after the fallback.

A provider's fallback is now its emergency path. When the last answerer
is a Fallback row and the provider's own model stands first in the plan,
ready (restLast put it ahead, so its rest is over), the next turn goes to
the provider (backToMain, Affinity.Why "main"), in every mode but Strict,
which the user set never to move a conversation. Within a turn the
conversation stays on the fallback until the user speaks again: the
turn's tool loop runs on reasoning the fallback sealed, which the
provider can't read, and the provider is sent the whole prompt afresh at
the next turn either way. A routing group's members are never Fallback
rows, so a group's own affinity is unchanged. No switch was added.

"Ready" is unchanged: a rest ends when restAfter set it to (a minute and
backing off for a plain failure; the vendor's reset or Retry-After for a
quota or rate limit; quotaRest 15 minutes when nothing names a time), or
earlier when renewed or a background probe lifts it.

docs/subsystems/gateway-routing.md says this beside Strict.

Run (mote, at this commit's tree on origin/main 3ce2a9819, rebased onto 774baed6d (a one-line Qoder mover min); the new tests and internal/provider run again there, then onto 13b4a29ab (Desktop tier calls in internal/gateway): go vet and TestFallback|TestAffinity|TestDesktop|the new tests ok there):
- TestFallbackGivesTheConversationBackOnceTheMainIsReady red on the old
  affinity.go: "next turn, main ready" and "..., session" answered from
  spare-key, want main. Green with the change. With !a.Within dropped by
  hand, "within the turn, main ready" goes red.
- TestGroupMemberKeepsTheConversationOnceAnotherIsBack green before and
  after (a group member stays by its cache once another is back).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet of internal/gateway: ok.
- go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider:
  ok internal/gateway 551.7s, ok internal/provider 108.4s

Not tried: a real account. The fake upstreams answer as Anthropic does
(a 429, then cache_creation_input_tokens 3000).
2026-10-29 20:23:30 +08:00
yetone 13b4a29ab9 gateway: Claude Code's tier calls in a Desktop chat on a non-Claude model go to that model (CyberCaius)
CyberCaius on Discord: Claude Desktop's Code tab was on Leee's DeepSeek V4.1
Flash, no tier picked in magpie, and Claude Code's own sonnet call
(claude-sonnet-5-5: its auto mode's classifier or a subagent on the
sonnet tier, which Desktop leaves at Claude Code's default while no model
is tagged for it) went to Leee's claude-sonnet-5-5, which Leee's key may
not use: 403, and the error reached Desktop.

servedBeside kept such a call on the chat's provider and gave it that
provider's Claude model of the tier (its model of the very name first).
That fits a chat on that provider's Claude model (#2187: the classifier's
sonnet beside an opus chat), but a chat on another vendor's model says
nothing of the provider's Claude models, so the user never picked one.
Now a call Claude Code makes on its own gets the provider's Claude model
only when the chat's model is a Claude model there; otherwise it goes to
the chat's model. Desktop's own client is unchanged (its tool-less
non-title request is the user's chat turn). A tier the user picked now
also takes Claude Code's own id of it where a provider lists a model by
that name (before, desktopTierTurn took only an id no provider serves).

Claude Desktop's tiers are its own (claude-desktop.tiers.json), apart
from Claude Code's agent card; Claude Code CLI is untouched. The Agents
page's "Not set" note for Desktop's tiers says the new rule, in en, zh,
zh-TW, ja and de.

Run (mote, via mote-run): go vet ./internal/gateway ./internal/agent for
darwin, linux (-tags nogui) and windows: ok. go test -timeout 45m
./internal/gateway ./internal/agent: ok (519s, 176s). node --test
desktop-tiers.test.cjs i18n-keys.test.cjs (chromium and webkit, en and
zh): 17/17 pass. gofmt -l clean.
Broken by hand: TestClaudeDesktopNonClaudeChatKeepsTierCalls against the
old desktop.go is red on all 6 cases (sonnet, haiku and opus[1m] sent to
leee/claude-*).
Not tried: a real Claude Desktop; the reporter's Leee key.
2026-10-29 20:20:12 +08:00
yetone 3ce2a9819f library: RTK for agents in WSL, with the distro's own rtk (lex on Discord)
lex: Claude Code and other agents in WSL couldn't use the RTK of magpie
on Windows. rtkAgents looked an agent up in rtkSpecs by its whole id, so
claude@wsl:Ubuntu never matched and WSL agents weren't on the RTK page at
all. Even matched, the specs read this machine's home, and Windows' rtk.exe
is no command inside the distro, where the hook runs.

Now an agent is looked up by its kind (rtkKind). One in WSL:
- has its files read and written under the distro's home as magpie opens
  it (rtkClaudeDir, rtkCodexDir, rtkHome), with blocked/version checks
  against the distro's rtk and OpenCode;
- uses the distro's own rtk: rtkDistroOf asks the distro (wsl.exe -d <d>
  -e sh -lc) where rtk is on its shells' PATH, else in ~/.local/bin or
  ~/.cargo/bin (offPath), kept 15s; ReadRTK lists one RTKDistro per distro;
- switching on runs that rtk there (rtk init -g ..., its folder on PATH);
- Install RTK in WSL <distro> (POST /api/library/rtk/install {distro},
  magpie library rtk install <distro>) runs RTK's own Linux installer in
  the distro (curl, or wget).
A distro that isn't running is never started (#3896): its agents are
listed asleep with the switch off, and switching or installing says to
start it. The page has a card per distro (install, off-PATH, asleep) and
uses the distro's rtk for each WSL row's tags and switch; strings in zh,
zh-TW, ja and de. The install route now refuses a body it can't read
instead of installing on this computer.

Run:
- mote (macOS 27), at origin/main ec8fe29b8 plus this: gofmt -l clean;
  go vet darwin, GOOS=linux -tags nogui, GOOS=windows for internal/library,
  internal/gui, internal/cli: ok. go test ./internal/library ./internal/cli
  ok; ./internal/gui: TestMainWindowCorners/macOS_26_SDK red (#3949, open,
  mote's macOS 27), everything else ok; -run Library ok after the route
  change. node --test library-*.test.cjs + i18n-keys in Chromium and WebKit:
  828 tests, 3 red, all library-row-remove (#3099, open; 1 of 2 runs alone
  is red the same); library-rtk-*.test.cjs + i18n-keys at the pushed base:
  180 pass. New library-rtk-wsl.test.cjs: en, zh, zh-TW, ja, de at 980 and
  380px, both engines.
- New TestRTKWSL / TestRTKWSLAsleep (fake wsl.exe runs the real probe
  script with sh, the distro's home as HOME). Broken by hand: the old
  rtkSpecs[a.ID] lookup makes TestRTKWSL red (claude@wsl not on the page).
  Also ok on Windows (win-run) and Linux (wsl-run), -run 'RTK|WSL'.
- Real WSL, xiaomi-gpu with magpie-desktop (Ubuntu 24.04): from Windows,
  through real wsl.exe and the exact rtkWSLScript/rtkWSLProbe/rtkInitWSL
  strings, with HOME set to a throwaway folder in the distro: RTK's
  installer put rtk 1.1.0 in ~/.local/bin, the probe found it (on:0, not
  on that bare PATH), rtk init -g --auto-patch wrote "rtk hook claude" into
  ~/.claude/settings.json, and sp.has read it back over
  \\wsl.localhost\magpie-desktop\.... ReadRTK on Windows lists
  claude@wsl, codex@wsl and pi@wsl:magpie-desktop with an install offered.

Not tried: a real Claude Code session in WSL running a command through
the hook; the install and switch in the distro's real home (only the
throwaway HOME); the real GUI window on Windows; OpenCode, Gemini, agy,
Hermes, OMP in WSL (same code path, not run for real).
2026-10-29 19:58:40 +08:00
yetone 2768f04f9b gateway: a thread switched off a used-up Codex model compacts locally (hiwise_aigc)
hiwise_aigc on X (2115741641017565304): with Codex's allowance used up,
an existing thread switched to a magpie model failed every turn and
"还会走gpt模型", restarts or not; a new thread worked.

Cause, from codex-rs: before a turn on a model with a smaller window
(or a changed comp_hash), core/src/session/turn.rs
maybe_run_previous_model_inline_compact compacts the thread on the
PREVIOUS model (gpt-5.5) through the current provider, turn metadata
compaction.reason "model_downshift" / "comp_hash_changed", phase
pre_turn. compact_model_fallback.rs retries with the turn's model only
when the provider is_openai() (name "OpenAI"). Under the takeover
provider "magpie" there is no fallback: /v1/responses resolved bare
gpt-5.5 to the used-up codex account, codexCompact returned its 429,
and that was the turn's error, every turn. A new thread has no previous
model, so no compaction.

Fix: codexCompact, off CodexPath only, reads the compaction reason from
x-codex-turn-metadata (header, else client_metadata in the body). For
model_downshift / comp_hash_changed, a failed, errored or empty
compaction on the old model is answered with localSummary (magpie's own
magpie1 summary, no model), so the thread goes on on the model it was
switched to. The held-account check doesn't short-circuit it either.
context_limit (the thread's own model out of room) still says the
refusal, and CodexPath is left alone: Codex's "OpenAI" provider falls
back to the turn's model itself and gets a better summary there.
Prompts and base_instructions are not touched.

Run:
- TestCodexLeavingModelCompactsLocally: red on the old code (429 at
  codex_leaving_model_test.go:84), green now.
- Broken by hand: without the body client_metadata fallback the
  header-less case goes red; without the CodexPath scope the CodexPath
  case goes red (got 200).
- Sandbox repro (sandbox HOME + CODEX_HOME, fake upstream, live ~/.codex
  untouched): codex 0.162.1, takeover-like config with
  remote_compaction v2 and a model catalog (gpt-5.5 400k, magpie-x
  128k), a gpt-5.5 thread relabelled to provider magpie, resumed on
  magpie-x: POST /v1/responses model gpt-5.5 + compaction_trigger,
  reason model_downshift; a 429 failed the turn ("Error running remote
  compact task: You've hit your usage limit"); answered with a
  compaction item, as the gateway now does, the turn went on to
  magpie-x and completed. ChatGPT.app's bundled codex has the same
  model_downshift / comp_hash_changed path (strings).
- gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=linux
  -tags nogui and GOOS=windows (mote).
- go test -timeout 45m -count=1 ./internal/gateway ./internal/codexsummary
  on mote at this tree (parent 0745db932 = origin/main at push): ok
  gateway 474s, ok codexsummary.

Not tried: a real used-up ChatGPT account through a real gateway end to
end; ChatGPT.app's bundled codex 0.164-alpha run itself; Codex without
remote_compaction v2 (the memento "responses" implementation sends a
plain turn, not covered here). The local summary is lossy (the user's
messages and the last reply), the same one codexCompact already falls
back to.
2026-10-29 19:46:39 +08:00
yetone f6263439af gateway: serve OpenAI's text to speech, POST /v1/audio/speech
liuyuexue2020 on X (tweet 2115742181734445238) wanted audio models
(Mistral among them) behind magpie, and the gateway had no
/v1/audio/speech.

POST /v1/audio/speech (and the bare /audio/speech) takes OpenAI's JSON
body and goes through serveRetrieval, as transcriptions (#2053) and
embeddings do: routed (a group's members, a provider's keys and
accounts, pause rules, key limits), metered against MaxRPM, recorded
(usage operation "speech", Routing, recent calls). Only "model" is
rewritten to the provider's own id; every other field goes as sent, so
Mistral's voice_id and ref_audio pass too.

The answer is never held whole: a speech request's 2xx answer is left
unread by the new retrieveOpen (retrieveAs now wraps it) and copied to
the client as it comes, flushed per read, in the vendor's own
Content-Type: audio (mp3/opus/aac/flac/wav/pcm), SSE for
stream_format=sse, or a vendor's JSON (Mistral answers
{"audio_data": base64}). No Accept: application/json is sent for it.
The usage in SSE's speech.audio.done event is counted from the last
16KB. A vendor's error is read and passed on as before, and a failing
member still falls over to the next.

Masking: "input" and "instructions" are masked as the settings say,
as text (maskTextHits), each where it sits; nothing else in the body
is (voice, formats, a voice-cloning clip are no text of the user's).
Nothing is put back: the answer is audio, so a masked value is read
aloud as its placeholder (docs/reference.md says so).

Mistral: its API has POST https://api.mistral.ai/v1/audio/speech
(voxtral-mini-tts-3-0), at the OpenAI path but not OpenAI's shape:
voice_id instead of voice, and JSON {"audio_data": base64} back, not
raw audio. Both pass through as sent; a client must speak Mistral's
shape to it. OpenAI, Groq and other OpenAI-style TTS vendors (vLLM-Omni
included) are served as they are.

Also: the 404 message's list, /v1's "apis", remote_magpie's suffix
list, cors_test and lan_test route lists, docs/reference.md,
gateway-routing.md, plugin-runtime.md, site remote.html (en/zh/ja).

Run (mote-run, at this commit):
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build ./...: ok; gofmt -l clean
- go test -timeout 45m -count=1 ./internal/gateway ./internal/provider at 7bc52d44e^{tree} (= this tree, origin/main 65bd4e4f7): gateway ok 497.9s, provider ok 88.7s
- go test ./internal/gateway -run 'Speech|Transcri|Embedding|Rerank|CORS|LAN|ReplyHeaders': ok

Broken by hand (mote-run, each red, then restored):
- the two mux lines removed: all five TestSpeech* red
- streams() false (answer read whole): TestSpeechStreamsAsItComes red
  (first event never reached the client while the vendor held the rest)
- "instructions" left out of the masked fields: TestSpeechInputMasked red

Not tried: a real vendor (OpenAI, Groq, Mistral) through a sandbox
magpie; only the fake upstream in speech_test.go. Not run on the
Windows or Linux boxes (vet only).
2026-10-29 19:25:40 +08:00
yetone 65bd4e4f72 provider: a model is priced at its maker's own API before a reseller's (bestony on Discord)
bestony on Discord (#feedback) asked that a subscription with no price of
its own, such as Command Code, be costed at the model's official list
price. magpie already estimates every subscription at the maker's list
price, but the maker step (PricedBy over the maker presets) took the
first preset that listed the id, and Mistral resells other labs' models:
deepseek-v4.1-flash-1017 was costed at Mistral's $0.30/$1.20 instead of
DeepSeek's $0.15/$0.60, glm-5-2 at Mistral's instead of Zhipu's, and a
lab that isn't a preset (Meta's muse-spark, Sakana, Tencent hy4-preview)
had no price at all.

catalog.MakerPriced prices a model at a models.dev provider that lists it
as its own: the entry's canonical_model_id names that provider as maker,
or the provider id is the maker's with a region (alibaba-cn), never a
plan's ("-plan") and never an entry at $0. A maker preset that is such
an API is asked first, in preset order, then the other owners by id;
the old PricedBy over the presets stays the fallback. makerListPrice
uses it in ListPrice's maker step, MakerPrice and PricedName. No new
setting: a model no maker lists still takes the user's price or a
same-as model.

Over every id in the real models.dev cache (2026-10-29, ~4086 ids) the
only prices that changed are the deepseek-v4.1-flash-1017 family
(0.30 -> 0.15), glm-5-2 (Mistral 1.40 -> Zhipu 1.19516), and newly
priced Meta, Sakana, Thinking Machines and Tencent hy4-preview models.

Run (mote-run, rebased on 1a8539432; catalog, provider, usage run again at this head):
- TestMakerPriceIsTheMakersOwn (fixture: literal entries of the real
  models.dev cache) red on the old code, 10 errors (Mistral's resale
  price, Meta unpriced), green on the new.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  for internal/catalog, internal/provider, internal/usage.
- go test -timeout 45m ./internal/catalog ./internal/provider
  ./internal/usage: ok.
- go test -run 'Pric|Cost|Usage' ./internal/gateway ./internal/gui
  ./internal/cli: ok.

Not tried: a real Command Code request and its Usage row in the GUI;
the full gateway suite; Windows/Linux runs of the tests.
2026-10-29 19:01:04 +08:00
yetone 75a7db27b9 usage: an allowance card can be hidden from the Overview (whqtian_07012 on Discord)
whqtian wanted StepFun's plan card on Usage › Overview without its
balance card. Right-click a card (or long-press it on a touch screen)
and the app menu offers "Hide from Overview". With several accounts on
one card it says "Hide this account from Overview". A plan card that
carries its key's balance also offers "Hide its balance from Overview",
which keeps the plan. Each hidden card is saved as its tray card id plus
its kind (stepfun|balance, kimi|me@x|plan) in settings.UsageCardsHidden,
through POST /api/usage/arrange (cardsHidden). The Settings save keeps
it. Under the cards, a quiet "{n} hidden" line opens them, each with
Unhide, and Show all from two. It is the same pattern as the Agents
list's hide.

Display only: routing, caps, counting, the Accounts list, the tray
panel's Allowances (it has its own Arrange) and the menu bar cells
never see it. A cell clicked for a hidden card shows it until the page
is left (usagePeek). UI: the app menu, not a native select, no
coloured stripes, no new button on the cards.

Run at this head (rebased on 96a703a59):
- mote: go test -timeout 45m ./internal/gui ./internal/settings.
  settings ok. gui: only TestMainWindowCorners/macOS_26_SDK red, and it
  is red on origin/main 96a703a59 too (#3949, macOS 27).
  TestUsageArrangeCardsHidden and TestSettingsSaveKeepsWhatItDoesNotSend
  pass.
- Linux box (wsl-run): 107 GUI files that reach the Usage page, the
  quotas, the panel, i18n and gui-de/ja/zh-tw, in Chromium and WebKit:
  1362 of 1419 pass. usage-cards-hide passes in both engines, in en, zh,
  zh-TW, ja and de, at 1200px, 560px and 390px (touch, magpie web).
  i18n-keys passes. The 9 red files were run alone at origin/main
  96a703a59 and are red there too (57 red at the base, 51 at the head).
  #4120 has 7 of them. usage-ledger-open-settled (#4262) and
  usage-ledger-chart (#4263) are newly filed.

Rebased again on 9f36d768d, which changed app.js elsewhere. At this
head: usage-cards-hide, i18n-keys, usage-arrange, panel-arrange,
key-balance-card and usage-shared-balance on the Linux box, 72 of 72
pass. On mote, go test -run 'TestUsageArrange|TestSettingsSave'
./internal/gui: ok.

Not tried: a real StepFun account in the real app. The fixture is a
StepFun plan card with its key's balance plus a balance-only card. Not
run on Windows.
2026-10-29 18:52:05 +08:00
yetone 9f36d768d3 gateway: Claude Desktop's connection check goes to the model chosen in its own menu (cybercaius on Discord)
cybercaius on Discord, after v0.1.2033: in Claude Desktop's Code tab he
chose a DeepSeek model and turned Cowork off, yet the connection check
Desktop sends as it starts did not go to DeepSeek. He asked whether it
follows Cowork's default model.

Cause: Desktop names the check's model itself, by name: the shortest
listed id with haiku in it, else sonnet, else opus (YT/lWt in its
app.asar 2.7032, read again from the installed app). Since ee6f8866f
magpie sent it to desktopDefault, the first model listed to Desktop
(its default for a new session), not to the model chosen in the menu.
So it went to whatever was first on the Agents page, another provider.

Desktop keeps each model menu's choice in its userData:
Claude-3p/local-agent-mode-sessions/<account>/<org>/
cowork_account_settings.json, "__model_selector_state":
{"code":{"model":…},"cowork":{…},"chat":{…}} (wLt, zLt, J1t in the same
app.asar; the file exists on the Windows box's 3p Desktop, holding only
__created_at as no menu was changed there). desktopChosen reads the
newest such file and the check now goes to a chosen model magpie still
serves: the one the last session ran on (desktopPicked) first, then
Code, Cowork, Chat. A choice magpie no longer serves, no file, or one
not parsed leaves it to desktopDefault as before, so the days-old
session model ee6f8866f kept it from is not used on its own. Nothing
is written; it is read only for the check (start and Test connection).

Run (mote, at this tree):
- go test -tags nogui ./internal/gateway/ -run
  'TestClaudeDesktopProbe|TestDesktopProbe': ok, with the new
  TestClaudeDesktopProbeToChosenModel (no choice; Code on DeepSeek;
  "[1m]"; Code before Cowork; the last session's menu first; an unserved
  choice; a half-written file)
- go test -tags nogui -timeout 45m ./internal/gateway/: ok (526s), at
  9f25de56c; after the rebase onto af1d9c456 (13 gateway files changed
  there), -run 'Desktop|Probe|Title': ok
- go vet ./internal/gateway/ for darwin, GOOS=linux -tags nogui and
  GOOS=windows: ok; gofmt -l: clean
Broken by hand: desktopChosen returning "" (the old routing), the new
test is red: "Code tab on DeepSeek: the check went elsewhere
(…"model":"claude-haiku-5-5")".
Not tried: a real Claude Desktop choosing a model in its menu and
starting against magpie; that the 3p menu writes the file is read from
its code, not seen. alwaysStartWithDefaultModel (an admin setting that
makes Desktop ignore the menu's choice) is not read.
Docs: docs/subsystems/gateway-routing.md's check paragraph.
2026-10-29 18:39:28 +08:00
yetone c1da9ccda3 library: a stopped WSL distro's agents are listed, and a tick for one is written there once it runs (cybercaius on Discord)
cybercaius: with WSL not started, the Library's MCP page didn't list the
agents in the distro at all, and nothing ticked for them could be kept.
A stopped distro's agents are no targets (#3896: opening their files
starts the distro), so they fell off the page.

While a distro runs, each agent's places and what its MCP file takes are
kept in wsl.json (keepShape, agent.WSLKeep, key library:<kind>). While it
is stopped, Read lists its agents from that (asleepView, asleep: <distro>)
with the library's ticks; one magpie never saw is listed only on rows that
name it, as unseen, its chip disabled and kept by every click (keptOf). A
tick on a stopped agent is kept in library.json (Takes accepts a known
shape, serversAgents judges it by shape.reaches); nothing is opened or run
in the distro. Woken, from KeepLinked's 30s loop, syncs once a distro the
library names goes from stopped to running (wsl.exe -l --running starts
nothing). The page greys a stopped agent's chip and says why in its
tooltip and one line per distro; the MCP hub leaves them out. The CLI says
the same on stderr (AsleepIn). en, zh, zh-TW, ja, de.

Run at this tree (20695ad8b before this message; on adc618bbf):
- mote: gofmt -l clean; go vet -tags nogui for darwin, GOOS=windows and
  GOOS=linux on internal/library, internal/agent, internal/cli; go test
  -tags nogui -timeout 45m ./internal/library ./internal/agent
  ./internal/cli: ok (internal/gui ok too at the 96a703a59 base).
- WSL magpie-desktop: library-wsl-asleep, i18n-keys, library-gone-agents,
  library-items and library-mcp-hub, Chromium and WebKit: 88/88. At the
  96a703a59 base every library-*, mcp-*, skill-* file and i18n-keys:
  1148 of 1164; the reds were library-chip-fan (WebKit),
  library-mcp-tools (chromium ja 420), library-items and
  skill-group-shared (WebKit) beside another session's full GUI suite.
  Alone, library-items and skill-group-shared pass, and chip-fan and
  mcp-tools are red the same on an origin/main 96a703a59 copy (#4120,
  commented).

Broken by hand: asleepView returning nothing made TestWSLStoppedListedAndQueued
("a stopped distro's Codex isn't listed") and TestWSLStoppedUnseen red;
Woken never syncing made TestWSLStoppedListedAndQueued red ("no sync once
the distro ran"); keptOf without unseen made library-wsl-asleep red in
all 10 Chromium cases (Pi's tick dropped by a click on Claude Code).

Rebased onto fa2332976 (gateway, provider and Codex effort commits, nothing
in internal/library, internal/agent/wsl or the Library page) before the
push: go vet of the three packages and go test -run TestWSL
./internal/library ok there; the full packages ran at adc618bbf.

Not tried: a real distro stopped and started. magpie-desktop was running
another session's full GUI suite, which stopping it would have killed, and
the other distros are other people's. The tests use FakeWSL, which counts
every wsl.exe -d command run in the stopped distro (none). Not changed:
the Instructions, Hooks and Subagents pages still leave a stopped
distro's agents out (#4182, #4237, #4238).
2026-10-29 18:34:44 +08:00
yetoneandskygunner 7eb7fa5407 agent: Pi, OmO and Prime Agent ask a Gemini model on google-generative-ai at the gateway's /v1beta (#3282)
A model served on Google's Gemini API (a custom provider's gemini=, a
Google sign-in's Code Assist, a plugin model declaring @ai-sdk/google)
was written into Pi's models.json with no api, so it inherited the
provider's openai-completions and the gateway translated Chat to Gemini.
magpieModels now gives such a model the Gemini API when no Chat,
Responses or Messages API was chosen for it, and piModelJSON writes it as
api "google-generative-ai" with baseUrl <gateway>/v1beta. A model whose
user picked Chat for it, routing groups and Pencil stay as they were.
Sync rewrites magpie's own model list, so files written before get it.

The patch is skygunner's (279e9bd1 on fix/pi-google-api in their fork).
Changed here:
- StepCode keeps such a model on Chat. Step-Code at 90a57820 registers
  only anthropic-messages, openai-completions and openai-responses
  (packages/providers/src/compat.ts BUILTIN_APIS); its docs list
  google-generative-ai but nothing streams it, so the patch would have
  broken every Gemini model there.
- On google-generative-ai, pi-ai's resolveGoogleThinkingLevel maps a level
  through thinkingLevelMap and throws on anything but minimal, low,
  medium or high, so a level the model names otherwise (xhigh, max) is
  set to null there and Pi doesn't offer it.

Checked against each client's source: pi-ai 1.4.0 and OmO's senpi-ai
2026.10.27-1 set apiVersion "" when baseUrl is given ("baseUrl already
includes version path"); Prime Agent's pa-ai providers/google.rs takes a
model baseUrl in place of host and version, and pa-core models/custom.rs
reads a per-model api and baseUrl.

Run (mote, at this tree rebased on 96a703a59, then again on adc618bbf):
- go test -tags nogui ./internal/agent -count=1 -timeout 45m: ok (385s).
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m: ok (744s,
  load ~20 from other sessions). A first run of both packages together
  exited 1 after agent's ok; its log was deleted from the shared
  scratchpad by another session before the red could be read, so it is
  unnamed. The rerun of gateway alone at the same tree passed.
- Rebased on adc618bbf (#3279's plugin text filter, fake plugin
  changes): internal/agent -timeout 45m ok (252s); internal/gateway
  -run 'TestPlugin|TestCustomGemini' ok (43s).
- Pushed on fa2332976: the three commits since adc618bbf (fc43c69e5,
  750bd1bb6, fa2332976) change gateway code this change doesn't touch;
  not run again on them.
- Red without the fix (origin/main with these tests): TestPiModelsAsked-
  OnTheirNativeAPI (gem/ and hybrid/gemini-3-flash api <nil>),
  TestPiGooglePluginModels for pi, omo, prime-agent, and
  TestPiGoogleThinkingLevelsAreGeminis. TestPluginProvider's new /v1beta
  part passes there too: it guards that the plugin's sign-in and fetch
  still serve the route, which already worked.
- Broken by hand: with the null-out of non-Gemini levels turned off and
  the StepCode exception removed, TestPiGoogleThinkingLevelsAreGeminis
  (xhigh, max kept) and TestPiGooglePluginModels/stepcode go red.
- Real Pi 1.4.0 (@earendil-works/pi-coding-agent) in a sandbox HOME on
  mote: a custom provider gemini=http://127.0.0.1:18761/v1beta (a local
  fake), magpie serve on 127.0.0.1:18762, `magpie pi
  magpie/gemfake/gemini-3-flash`. models.json had the model at
  google-generative-ai, <gw>/v1beta; `pi -p "say hi"` printed the fake's
  reply, its session recorded api google-generative-ai, and the fake got
  /v1beta/models/gemini-3-flash:streamGenerateContent?alt=sse.

Not tried: a real Google account or plugin sign-in, real OmO and Prime
Agent binaries (checked by their source only), Windows and Linux.

Co-authored-by: skygunner <84759+skygunner@users.noreply.github.com>
2026-10-29 18:34:21 +08:00
yetone adc618bbf9 codex: a Codex switched off in magpie still has its held ChatGPT account read, so the Codex app sends magpie's models (sherlock_23333 on X)
sherlock_23333 on X: once the ChatGPT account Codex is signed in to ran
out, the Codex app's Send stayed greyed even on a magpie model, through
restarts and reconnects.

The gate is the Codex app's own (ChatGPT.app 26.1021, composer gM):
Send is blocked while its authMethod is chatgpt and its own /wham/usage
says rate_limit.allowed false with no credits. magpie's one lever is
the takeover (codex.out): magpie becomes Codex's provider without
requires_openai_auth, so the app-server reports no ChatGPT account and
the gate lifts. That runs only when provider.CodexUsedUp says the
account is held, and CodexUsedUp read LoginUsage, which returns nothing
for a provider switched off or removed in magpie (leftAlone). So a user
who turned Codex off in magpie once its allowance ran out never got the
takeover, and one already taken over was put back on the held account.

Now, with Codex left alone, CodexUsedUp reads the active account alone
(codexHoldReading) while Codex takes magpie's models beside its sign-in
or magpie is its provider for the held account (Agent.HoldMatters, via
the new provider.CodexHoldMatters hook). At most once a minute (the
loginReading cache), with the token as Codex keeps it, never renewed or
written (codexTokenAsKept); the Usage page still shows nothing of it.
Codex's prompts and base_instructions are untouched.

Run at f41b63232 + this change, on mote via mote-run:
gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
GOOS=windows go vet ./...; go build ./... all ok.
go test -count=1 -timeout 45m ./internal/provider ./internal/agent: ok
(219s, 340s).
Rebased on 9f25de56c (a Cursor mover min and a GUI test), then at 9f25de56c +
this change: go vet and go test -count=1 -timeout 45m of
./internal/provider ./internal/agent again: ok (178s, 273s).
8c63c5b78 (plugin speech models; no file in common) landed on main
after that run and this is rebased onto it; the two packages were not
run again with it.

Broken by hand: without the leftAlone branch in CodexUsedUp,
TestCodexHoldReadLeftAlone fails ("switched off: CodexUsedUp = false on
a held account"); with the left-alone token read sent back through
codexToken, it fails with the expired sign-in refreshed once.

Not tried: the reporter's own config (whether their Codex was off in
magpie is inferred, not confirmed); the real Codex app against a held
account; internal/gateway's suite (no gateway code changed); Linux and
Windows test runs (vet only).
2026-10-29 18:20:50 +08:00
yetoneandggbdpq 8c63c5b787 provider, plugin: a plugin model that says it gives no text leaves the chat lists (#3279)
A plugin provider's list counted every model it named as a chat model.
XYenon's Google AI Studio plugin put gemini-embedding-001 and its TTS
models in the chat chips, the agents' lists and /v1/models. The plugin
does declare them: the embedding's capabilities.output is
{"text": false} and the TTS's says audio only. But the host's kinds()
kept only the true keys. That made "said it gives nothing" look the same
as "said nothing", and pluginCatalog never read Outputs.

- host.js passes outputsSaid, which is whether capabilities.output says
  yes or no to any kind (kindsSaid). It goes into plugin.Model.OutputsSaid.
- pluginCatalog leaves out a model whose outputs were declared and name
  no text, image or video (pluginTalks). Every chat list is built from
  that list: /v1/models, provider.Catalog (the agents' lists and routing),
  and Available (the editor's chips).
- A plugin that says nothing about outputs keeps every model, whatever
  the id. Image-only and video-only models stay where they are; #2792
  decides where they go.

Ported from ggbdpq's hunt65-c-3279-kinds (7391b0df2), with changes
after review. That patch found the right place (pluginCatalog) and
wrote the provider tests kept here. It judged an embedding by "embed" in
its id, because the host drops the declaration. So an embedding named
otherwise (bge-m3, text:false) stayed in the list. A plugin that says
nothing about outputs lost any model whose id held "embed" or "-tts",
which changes today's behaviour. An image-only model (outputs ["image"])
was dropped, though the patch said it left #2792's models alone. This
version fixes the declaration in the host instead and guesses nothing
from ids. catalog.textModel is unchanged.

Docs: docs/subsystems/provider-plugins.md, "A model that gives no text".

Run (mote, at base 96a703a59; then rebased onto 9f25de56c, which
changed only two mover mins, and ./internal/provider plus the e2e test
run again there: ok):
- TestPluginModelGivingNoTextLeavesTheChatLists (gateway, a real Bun
  host with the fake plugin under FAKE_KINDS, using XYenon's literal
  capabilities) is red on main: the embedding and the TTS are in
  /v1/models, the agents' catalog and Available. It is green with this
  change.
- go test -count=1 -timeout 45m ./internal/plugin ./internal/provider
  ./internal/gateway: ok (plugin 165s, provider
  121s, gateway 759s).
- GOOS=linux and GOOS=windows go vet of the three packages: clean.
  gofmt -l: clean.
Broken by hand:
- host.js without outputsSaid: the e2e test is red (embedding, bge-m3
  and TTS listed; rerun at this base).
- pluginTalks always true: the e2e test and both provider tests are red
  (rerun at this base: embedding, bge-m3 and TTS listed in each).
- ggbdpq's original product change with these tests: the e2e test is red
  on bge-m3. The unit test is red on bge-m3 kept, imagen-4 lost and
  embedder-chat lost.
Not tried: the reporter's real plugin with a Google AI Studio account.
The fixture is the plugin's parseModels output and the report's own
row. A TTS or embedding model still has no route of its own here.
Not run: the full ./... suite, and the GUI suite (no GUI file changed).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-29 18:17:55 +08:00
yetone 96a703a591 uninstall: magpie uninstall and Settings › Uninstall magpie put every agent back before magpie's files go
Jevik_AI on X (Windows, portable magpie) deleted magpie's folders by hand.
~/.codex/config.toml kept openai_base_url on 127.0.0.1:3425, and every
Codex turn then failed with a 502, with nothing left that knew why.
Deleting magpie's files never puts an agent back, so there is now an
uninstall that does.

- internal/uninstall: Run goes in this order. System removes the
  background service, opening at login, the Start menu shortcut
  (shortcut.Remove, with its App Paths key), the magpie:// links and the
  privacy model's helper. Agents ends Codex's account failover, then runs
  each connected agent's own Disconnect, or its offline disconnect for an
  app that is closed. That is the same code as the Agents page, so a value
  the user changed by hand since Connect stays theirs (e7f21dba5 for
  Codex). It then ports Codex's rollouts and restarts the Codex app's
  app-server (provider.RestartCodexAppWhenIdle, which says whether one was left on
  the old config). Data deletes magpie's folders, but keeps the Library's
  folder while it holds skills, servers or hooks the user's agents use.
  The executable is left where the user put it.
- `magpie uninstall [--yes]`: refuses while another magpie runs, and
  says which one. On a terminal it lists what goes and asks [y/N]; with
  no terminal, only --yes does it.
- Settings › About › Uninstall magpie: POST /api/uninstall runs System
  and Agents. If anything failed, nothing else is removed and the sheet
  offers Try again. Otherwise POST /api/uninstall/finish starts a
  detached `magpie uninstall --data-after <pid>` (Setsid on unix,
  DETACHED_PROCESS on Windows) and the app quits; the files go once it
  has ended, since WebView2 holds its folder open until then. A Codex app
  still on the old config is named before quitting. magpie web refuses
  both routes. Strings go through t() in all five languages.
- --data-after refuses a pid that is no process (0, negative, its own):
  kill(0) counts as alive, and a run given 0 waited out its 2 minutes.

Not done, and why:
- No restore on quit. Quitting keeps agents on magpie by design: the
  service or the next start serves them.
- No Apps & Features entry or Windows uninstall hook. A portable copy
  registers nothing with Windows, and an uninstaller that ran without
  magpie's own disconnect would leave the configs as they are. The
  `# magpie:` note above each line magpie writes (previous commit) is the
  recovery path for a copy deleted by hand.

Run at this head (db75663a0's tree, on 5d24bc6cc), on mote:
- gofmt -l clean; go vet ./... on darwin (-tags nogui), GOOS=windows and
  GOOS=linux -tags nogui: ok.
- go test -tags nogui -count=1 -timeout 45m on ., internal/uninstall,
  cli, gui (TestCoreScriptBudget included), provider, shortcut, edit,
  agent and proc: all ok.
- GUI at this head: mote was at load 100-120 with other sessions' GUI
  runs. Chromium crashed (SIGBUS) mid-file in settings-search and
  settings-sections after their en cases passed, WebKit failed to launch
  within 180s in s3-sync, settings-search and settings-sections, and
  fonts and title-bar-tools went red on unstable elements (#2984 has
  fonts under load). uninstall-settings had not reported when this was
  pushed.
- At the earlier base b3580c72c, on this machine: the full suite
  (-timeout 45m), red only on #3884, #3632 (both since fixed on main) and
  the core budget, which main's later move of Web search out (#4133) has
  room for now. GUI: 104 Settings and i18n files in chromium and webkit,
  uninstall-settings and i18n-keys green in both; the reds were #3797,
  #3876 and the load reds above.

Tried for real, in a sandbox HOME: `magpie uninstall` end to end with
Codex connected and a sandbox Codex app running (config.toml back
without magpie's lines, magpie's data gone, the exe kept, the app's
app-server restarted onto the restored config); codex-cli 0.162.1
reading the noted config.toml. Other agents were covered by tests only.
Not tried: the GUI's Uninstall in a real app window, a real
--data-after run waiting on a live app's pid, and the Windows box.

Broken by hand: --data-after's pid guard removed ->
TestUninstallDataAfterNeedsAProcess red (0, -1 and its own pid
accepted); restored, green.

At the pushed head (rebased on 51f66fe8b; the uninstall call adapted to
EndCodexFailover's (bool, error) on the way), on mote:
- gofmt clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok;
  go build ./... ok.
- go test -timeout 45m: internal/uninstall, edit, shortcut, cli, agent,
  provider ok; internal/gui red only on TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27).
- GUI: uninstall-settings and i18n-keys, 30 pass 0 fail.
- WSL (magpie-desktop, CGO_ENABLED=0): uninstall, edit, shortcut,
  provider ok; agent red on TestGrokInstalled, TestOmpDetectedWithPiDir,
  TestZedAppPath, the same at origin/main 51f66fe8b (#4033, #3548).
2026-10-29 17:47:30 +08:00
yetone 0c4e3455ee agents: a line magpie writes into a TOML, YAML or env config has a note above it saying so
Jevik_AI on X deleted magpie's folders by hand. Codex's config.toml kept
openai_base_url = "http://127.0.0.1:3425/backend-api/codex", with nothing
in the file naming magpie, and every Codex turn failed with a 502.

Each line magpie writes that points at the gateway, or at magpie's model
list, now gets a comment line of its own just above it:

  # magpie: Codex on magpie's local gateway; Disconnect in magpie or
  #   `magpie uninstall` undoes it, or delete this line and the model line
  model_provider = "magpie"

- Only a line the write adds or changes, or one that had a note, gets one.
  A line of the user's own that magpie leaves alone gets none.
- The note is never on the value's line. Grok App's providers.rs reads the
  rest of a line as the value, and an end-of-line comment broke
  TestGrokApp in a first try.
- Every write takes the notes out and puts back the ones still needed, so
  a note goes with its line and Disconnect leaves none.
- No note in JSON. A YAML note that would change what the file reads as
  isn't added.
- Wired in run (agent.MarkWritten); tests leave edit.Mark nil so their
  exact bytes stay.

Run at this commit's tree (worktree, sandbox HOME, private GOCACHE):
- gofmt -l clean; go vet darwin, GOOS=windows, GOOS=linux -tags nogui ok.
- go test -tags nogui -run Mark ./internal/edit ./internal/agent: ok.
- ./internal/agent and ./internal/edit whole with edit.Mark forced on for
  every test (a snapshot with lineNote set in agent's TestMain): edit ok;
  agent fails only TestDshRouteKeepsTheAPIPickedInDsh and
  TestDshSearchThroughGateway, which compare exact bytes and see the note
  line. With Mark unset (as shipped) they pass.
- Real Codex: built magpie from this tree, `magpie codex fakeai/fake-1` in
  a sandbox HOME. config.toml got the three notes above model_provider,
  model_catalog_json and openai_base_url; `codex mcp list` and `codex
  features list` (codex-cli 0.162.1) read it, rc 0, and Python's tomllib
  reads the same values. `magpie codex default` took them out.
- Broken by hand: a note on every line, not only changed ones ->
  TestMarkTOML and TestMarkOnlyWhatMagpieWrites red.

- The notes' line filter is withoutNotes, unexported: an exported
  Unmarked put a word the routing plugin translates into a Go file, and
  i18n-keys' "a plugin's words are its own" went red on it. It passes
  now.

Full suite: run with the uninstall commit that follows, recorded there.
2026-10-29 17:42:35 +08:00
yetone 51f66fe8bb gateway: Claude Desktop's haiku calls stay on the chat's provider, not another provider's Claude haiku (cybercaius on Discord)
cybercaius picked AgentRouter's gpt-6.1-sol in Claude Desktop, and the
Routing page showed Claude Code's background calls in the same chat
(3-9k tokens) going to leee/claude-haiku-5-5: "为什么Claude Desktop中模型
选择的是AgentRouter · gpt-6.1-sol,但在对话过程中还是会去请求leee供应商的
模型呢?"

Cause: magpie's own default, not a pick of theirs. desktopModels tagged
every Claude model magpie serves with its own tier in the /v1/models it
gives Desktop (anthropic_family_tier, f55747ce8) whenever that tier had
no pick. Desktop's Code tab hands a tagged model to Claude Code as
ANTHROPIC_DEFAULT_HAIKU_MODEL, its small, fast model, so every haiku
call (summaries, bash prefix checks and the like) asked for Leee's haiku
by its catalog id and was served there, whatever the chat was on.

Now:
- Only a model the user picked for a tier (claude-desktop.tiers.json,
  the Agents page's opus/sonnet/haiku/fable) is tagged. Untagged, Claude
  Code asks for its own id of the tier (claude-haiku-4-5-…).
- desktopTurn: a background call (no tools) or a subagent's turn for a
  Claude model by Claude's own id that is no catalog id (claudeOwnID)
  stays on the chat's provider (desktopPicked) even when another
  provider serves a model of that name; before, only an unserved one
  did. A lead's turn and a tier pick (a catalog id) go as asked.
- servedBeside: the chat's provider's model of that name (also one
  listed by the bare name), else its newest model of the same tier,
  beside the chat's model first, else "" and the call goes to the chat's
  model. A chat on GPT gets its haiku calls on that GPT; a chat on a
  provider with haikus keeps them on a haiku there.
- The tier picker's "Not set" note says so in en/zh/zh-TW/ja/de ("the
  chat's provider's model of the tier, else the chat's model").
- gateway-routing.md describes the rule.

A value the user set is untouched: a tier pick stays tagged and served
as picked (asserted in the new test).

Tests: TestClaudeDesktopBackgroundStaysOnChatProvider (new): AgentRouter
gpt-6.1-sol + Leee claude-haiku-5-5 + a third provider with two haikus;
asserts nothing tagged unpicked, Claude Code's haiku calls (bare
claude-haiku-5-5 served elsewhere, an unserved dated haiku, a subagent)
go to agentrouter/gpt-6.1-sol, a chat on the third provider gets its
haikus, and a picked haiku is tagged and kept. Red on 5143bf593 (old
code, test file only): "auto/claude-haiku-5-5 tagged "haiku" with
nothing picked". TestClaudeDesktopTiers expects no tag unpicked;
TestClaudeDesktopClassifierOnRemoteMagpie's unserved claude-haiku-4-5
now goes to the remote's claude-haiku-5-5 (same provider, same tier),
and an unserved fable still to the session's opus.

Broken by hand (mote, new test):
- elsewhere forced false: FAIL "chat on AgentRouter, claude-haiku-5-5
  (subagent false) sent to "claude-haiku-5-5"" (and the subagent and
  Claudeish cases).
- servedBeside's tier stand-in skipped: FAIL "chat on Claudeish,
  claude-haiku-4-5-20251001 sent to "claudeish/claude-opus-5-5"".
Restored, it passes. The first run of this change also turned the old
remote test's expectation red ("unserved: sent
"work/claude-haiku-5-5""), the tier stand-in at work; changed on
purpose, see above.

Run (mote, this change on 5143bf593): go test ./internal/gateway
./internal/agent/... -count=1 -timeout 45m: gateway ok (889s), agent ok
(469s). Rebased onto origin/main after the run; the commits since touch
no file here.
GUI (wsl-run, magpie-desktop): desktop-tiers.test.cjs chromium+webkit,
en+zh, 4/4 ok; i18n-keys.test.cjs 8/8 ok. gofmt -l clean.

Not tried: a real Claude Desktop. Desktop reads /v1/models at start-up,
so the change reaches it after Desktop is restarted.
2026-10-29 17:28:07 +08:00
yetone b64ec9d64f gateway: a picked model that turns an image away gets it described, not another provider (xyenon)
xyenon (Discord #feedback) picked provider-1/DeepSeek-V4.1-Flash in pi
with an Image recognition model set. An image they sent wasn't
described; the request was answered by provider-2/DeepSeek-V4.1-Flash.

Cause: provider-1's list says nothing of images, so magpie took
models.dev's word for the model (catalog.SeesImages: text+image) and sent
the raw image. The relay answered DeepSeek's 400 "Failed to deserialize
the JSON body ... unknown variant `image_url`, expected `text`". That
matches shapeWords, so the try failed as a shape refusal and went on to
the next candidate: provider-1's fallback (or the next group member),
the same model at provider-2, which sees. The describer was never asked.

Fix: a 400/415/422 whose words say images aren't taken (imageRefused:
unknown variant image_url/input_image/image, OpenAI's "only supported by
certain models", OpenRouter's "no endpoints found that support image",
vLLM's "not a multimodal model", 不支持图片 and the like) marks the model
blind for this server's run (refuseSight; blindTo checks it first). With
a describer, the same candidate is asked again at once with the images
described (seenBody, or seenGroup for a group), before any fallback or
other member; the try reads failSight, which the Routing page tells as
its own story (en/zh/zh-TW/ja/de); the row then reads answered, as
for floor's and foreign's re-asks. Later requests
are described up front, for a direct pick and a group (user or auto)
alike, on Chat, Responses and Messages.

Kept on purpose: with no describer (Image recognition off, or no model
that sees), going on to a candidate whose copy sees is the only way to
answer, so it still does (TestRefusedImageWithNoDescriberGoesToOneThatSees).
Documented in docs/subsystems/gateway-routing.md, "A model that turns an
image away".

Run (on mote, through mote-run):
- TestPickedModelThatRefusesAnImageIsGivenItDescribed (9 subtests:
  direct pick with a fallback, user group, group/auto-…; each API),
  TestRefusedImageWithNoDescriberGoesToOneThatSees, TestImageRefused: ok.
- Broken by hand: with gateway.go/vision.go/routing.go reverted to
  origin/main (d9cf85ae8), all 9 subtests fail with "the same model at
  the other provider was asked 2 times" and the raw image sent there.
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m: ok (996s)
  at the d9cf85ae8 base. After rebasing onto 4534561f6: the new tests
  and -run 'Vision|Image|Shape|Group' in internal/gateway ok, and the
  three vets and gofmt again clean.
- go vet ./internal/gateway (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./internal/gateway, gofmt -l: clean.
- GUI: routing-sight (new, 5 languages) and i18n-keys in chromium on
  mote: ok. routing-sight and routing-shape in webkit on the Linux box
  (wsl-run): ok. WebKit on mote couldn't launch (browserType.launch
  timed out at 180s beside other sessions' webkit stuck 2h, routing-shape
  untouched failed the same), so its webkit leg ran on Linux instead.

Not tried: a real pi session against a real text-only DeepSeek relay
(no such account here); the fixture uses DeepSeek's literal 400 body.
The full go test ./... and the whole GUI suite were not run.
2026-10-29 17:23:24 +08:00
yetone 4534561f6b codex: a thread open when magpie quits goes on through a relay, not a 503
idkatbro on X: a Codex session started while magpie was open keeps
failing after magpie quits with "unexpected status 503 Service
Unavailable: Unknown error, url:
http://127.0.0.1:3425/backend-api/codex/responses", until magpie is
opened again.

Cause: Codex signed in to ChatGPT, with more of its accounts on in
magpie, gets openai_base_url = the gateway's /backend-api/codex
(failover). At quit EndCodexFailover takes it out of config.toml, but
a thread already open, in the Codex app and its app-server above all,
keeps the base URL it started with. Every turn after went to a closed
port. With a system or env proxy in between, the proxy answers 503
with an empty body, which Codex shows as "Unknown error"; without one
Codex says "Connection refused" and reconnects. Reproduced on mote
with codex 0.162.1 and a proxy answering 503 for the closed port.
Masking plays no part: it runs only in the gateway, is opt-in, and its
own 503 carries a readable message.

Fix: when quit really ends failover (EndCodexFailover now says so),
the gateway is on loopback, and Codex processes run
(provider.CodexPIDs), magpie starts a detached `magpie codex-relay`
(internal/codexrelay). It waits up to 60s for the gateway's port, then
passes /backend-api/codex/* on to the ChatGPT backend with the same
transforms the gateway applies to Codex's own turns, signed by the
caller's own Authorization; it adds no credential
(gateway.CodexRelay).
- Refused with a readable 400 (Codex retries a 5xx five times over):
  a magpie model, a turn naming one of magpie's Codex accounts, and a
  turn masking would have masked, which is never sent unmasked.
- 403 for any Origin (null too) or a non-loopback Host, as corsGuard.
- Any other path gets 503 "magpie isn't running", never readable as
  magpie by ServedBy.
- It ends once every Codex process it was left for is gone and
  nothing is in flight.
- The next magpie (GUI or `magpie serve`) calls codexrelay.Leave
  first: a POST with the token from a 0600 state file. The relay
  closes its listener at once, so the port is free when Leave returns,
  and finishes its streams (up to 30 minutes). No running turn is cut.

Run (at 6df7dc287 on origin/main 4d9058a98, on mote):
- go vet of the six touched packages; gofmt -l clean.
- go test ./internal/codexrelay and the CodexRelay, CodexFailover,
  CodexProxy, RelayOpenCodex and CodexPIDs tests: ok.
- codexrelay tests on Windows (win-run) and Linux (wsl-run,
  magpie-desktop): ok.
- Windows smoke of the real binary (nogui build): `codex-relay`
  answers / with the readable 503, stays while its watched process
  lives, ends after it.
- Real codex 0.162.1 e2e on mote, sandbox CODEX_HOME, API-key sign-in,
  fake upstream: the relay waited out a port held 2s, then turn 1
  completed (RELAYED-OK); a turn on openrouter/kimi-k2 showed the
  refusal's message; turn 2 was mid-stream when Leave ran, the port
  was free at once, the turn completed, and the relay ended.
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... and a
  Windows build: ok.
- Full suite, go test -count=1 -timeout 45m ./... on mote: every
  package ok but internal/gui, where 10 real-window AppKit tests
  (dock, panel, tray, titlebar, covered window, plugin page) are
  killed at their 20-80s bars. The same 10 fail the same way at
  origin/main 4d9058a98 on mote, run alone: mote's AppKit hang, #4125
  (and #2645, #1936). None of them touches the quit path changed here.
- Rebased on origin/main 1198cff60 to push. Still running there when
  pushed: go vet ./..., Windows and Linux vet of the touched packages,
  and go test of codexrelay, gateway, agent, provider and cli. A red
  it shows gets its own issue.

Broken by hand, each red, then restored:
- Leave without ln.Close(), with a 1s delay before Shutdown injected:
  "the port isn't free after Leave" (with ln.Close: green).
- No pid watch: "relay outlived the Codex it was left for".
- Leave without the token check: an empty token got 204.
- No Origin/Host guard: Origin null got 200.
- No masking refusal, no magpie-model refusal: 200, sent upstream.
- An empty 503 at "/": TestCodexRelayIsNotMagpie red.
- RelayOpenCodex starting nothing: "no relay for the open Codex".
- EndCodexFailover never saying ended: TestCodexFailoverEndsWithMagpie.
- CodexPIDs missing "codex": the Codex app and CLI not found.

Not tried:
- the real Codex desktop app, and a real ChatGPT account. With a fake
  ChatGPT token codex 0.162.1 stops at its own "workspace routing
  discovery" against chatgpt.com before sending a turn, so the
  ChatGPT path is covered by unit tests only;
- a Codex in a WSL distro, and a connected (not failover) Codex: both
  left as they were;
- a magpie that ends without quitting (killed, crashed): still leaves
  failover in place and no relay;
- the relay's memory use as the full binary.
2026-10-29 17:13:05 +08:00
yetone 1198cff601 gui: a model picker's row says how fast its provider answered this week, fastest first under a search
axuhere on X: with several providers serving one model, the list and the
model picker should show each one's speed and sort by it. Each row of an
agent's model picker now carries a quiet tag from the usage ledger's last
seven days: tokens a second, or the first token's wait when only that was
timed (title: "first token in Xs, N tokens a second"). Under a search,
rows that match equally go fastest first by about how long a 200-token
reply takes, the untimed last. Without a search the rows keep catalog
order, grouped by provider. "Fastest first" for a routing group already
existed as Speed first (d9a8148d7); nothing added there.

- GET /api/model-speeds (internal/gui/speeds.go): usage.SummarizeTop(Week)
  models by provider/model, the catalog ref an option carries; a model
  whose calls went to more than one host is left out.
- app.js: readSpeeds (once a minute, on a model picker opening, re-filters
  keeping the cursor), speedRank, speedTag. Existing i18n keys only.
  app.js 1,304,233 under its 1,311,735 budget, no raise.
- menu-scroll's strict fixture answers /api/model-speeds.

Run, at this head (rebased on bb3565309) unless said:
- mote: go test -run 'Budget|TestModelSpeedsByRef' ./internal/gui ok;
  go vet ./internal/gui darwin ok, GOOS=windows ok.
- picker-speeds.test.cjs: Chromium 1000/440px x en, zh, zh-TW, ja, de 10/10
  on mote; WebKit 10/10 on the Linux box (wsl-run), because WebKit launch
  hangs on mote at present (many pw_run.sh from several sessions, 0 WebKit
  processes). i18n-keys 4/4.
- Broken by hand: speeds.go without TPS -> TestModelSpeedsByRef red;
  filter() without the speedRank tie-break -> picker-speeds red
  ("fastest first, the untimed last").
- 57 other GUI files that open a model picker, Chromium, at the pre-rebase
  tree, concurrency 4 on mote at load ~30-40: 185 pass, 180 fail. One was
  real (menu-scroll's "Unexpected API: /api/model-speeds", fixed here); the
  rest were 5000ms locator timeouts and 11 WebKit launch timeouts. A rerun
  of those files at concurrency 2 was still running at push.

Not tried: native Linux go vet (the WSL box lacks gtk4/webkitgtk dev
packages); the real app with a real ledger; the full GUI or Go suite.
2026-10-29 17:09:13 +08:00