Commit Graph
899 Commits
Author SHA1 Message Date
yetone a093e9c3a5 claude: a Claude Code run holding over its memory budget is let go after its turn, its session resumed (#3256)
claudeRoom bounded how many Claude Code processes run, not how large
each one is. A run is kept for its conversation's next turn, turn after
turn, and on a service never restarted one grew for days: a
node-MainThread in magpie.service reached 8 GiB RSS on a 31 GiB host and
the OOM killer took the machine down (#3256).

Now each time a run's reply ends, its process tree's resident memory is
read (proc.Tree.RSS: /proc VmRSS on Linux, ps on macOS, the working sets
of its job's processes on Windows, so an npm claude.cmd's node counts)
and logged with its pid. Over the budget (an eighth of memLimit on
Linux, of the computer's memory elsewhere, 1 GiB at least, 4 GiB if
unknown), a whole turn's run is not kept idle: its session is shelved
and the next turn resumes it in a new Claude Code with --resume, told
only the new messages. A run parked on tool calls is let go past 1.5x
the budget (no session to shelve there; its results start a new run).
Each Claude Code also logs pid and model at start, and run time, how it
ended and peak RSS (ru_maxrss) at its end, so an OOM pid can be found in
magpie's log. Budget on the reporter's 31 GiB host: 3.9 GiB.

Run (worktree at 99de8e1ad + this change, macOS arm64):
- go test -timeout 45m ./internal/gateway -run
  'Claude|Subscription|Room|Park|Idle|Resume' -count=1: ok (60.5s).
- go test ./internal/proc -count=1: every test ok except
  TestNoCommandBypassesProc, red on origin/main since 75e78a5a0
  (internal/tui/keep.go, filed as #3567, not this change).
- New tests: TestClaudeOversizedRunIsLetGoAndResumes (injected RSS over
  budget: the run ends, the next turn runs --resume s<pid> and is not
  told a1 again), TestClaudeRunWithinBudgetIsKept,
  TestClaudeOversizedParkedRunIsLetGo, TestClaudeRunBudgetScalesWithMemory
  (31 GiB MemTotal -> an eighth; 2 GiB -> the 1 GiB floor), TestTreeRSS
  (a real sleep's RSS read; none once waited for).
- Broken by hand: with both checks turned off, the oversized idle and
  parked tests go red ("the oversized run to end", "a run over its
  budget was kept waiting on its tool calls").
- Real Claude Code 2.1.310 in a sandbox HOME and CLAUDE_CONFIG_DIR,
  stream-json like the bridge, against DeepSeek's Anthropic endpoint
  (deepseek-chat, real key, synthetic 40KB turns): RSS after turns
  1/10/20/30 = 192/244/223/233 MiB, peak 245 MiB over 30 turns and
  ~1.2 MB of conversation. oversized() on that real process with the
  budget 1 MiB under its RSS said over; with the real budget on this
  64 GiB Mac (8192 MiB) it said keep.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags
  nogui ./internal/proc ./internal/gateway clean.

Not tried: a real Claude subscription run through the bridge on Linux
until it crosses the budget (the retire path is shown with injected RSS
on the fake Claude Code, and the RSS read on a real one); the Windows
RSS reader and job listing on the Windows box (vet only); a Linux run of
the /proc reader (macOS reads through ps); the full ./internal/gateway
package.
2026-10-25 17:41:41 +08:00
yetone 4b1994ad31 agent: AionUi, added through its add-provider link
seven7032 on Discord asked how to connect AionUi to magpie. AionUi
keeps its providers in its own SQLite database
(<userData>/aionui/aionui-backend.db, WAL mode), each key encrypted, so
there is no config file for magpie to write. The one supported way in
is its deeplink. AionUi 2.2.2's main process parses it
(parseDeepLinkUrl), and its renderer opens Settings -> Model with the
add form filled in, which the user confirms:

  aionui://add-provider?api_key=magpie-aionui&base_url=<gw>/v1&name=magpie&platform=custom

The AionUi row works the way Cindy's and Lody's do:
- Add magpie opens that link. /api/open allows the aionui://add-provider?
  prefix only. `magpie aionui add` opens it from the CLI.
- The key is agentKeyAt("aionui"), so it becomes the LAN key while
  sharing is on (added to TestPinnedGatewayKeyForEveryWriter).
- "custom" is AionUi's OpenAI-compatible platform. Its base URLs end in
  /v1, as its own OpenAI preset's does.
- Added reads providers.base_url for the gateway's address without
  touching the database (sessions.OpenUntouched, from the previous
  commit). A database that can't be read is unknown, never "not added".
  The last read is kept while the database and its log keep their size
  and time, for 15s at most, so the Agents poll doesn't copy a running
  AionUi's database every time.
- It is detected by userData/aionui (os.UserConfigDir()/AionUi on every
  OS).
- As with Cindy and Lody, the TUI leaves the row out (nothing to pick).

Tests:
- TestAionUiLink: the link's exact bytes.
- TestAionUiLinkParsedAs2_2_2: runs the link through
  testdata/aionui/deeplink-2.2.2.js, which is parseDeepLinkUrl copied
  byte for byte from 2.2.2's app.asar (out/main/index.js 50995-51021)
  plus the renderer's add-provider mapping and the form prefill. The
  result is action add-provider, route /settings/model, and the form gets
  platform custom, the /v1 base URL and the key.
- TestAionUiHas: a fixture database built from 2.2.2's real providers
  schema (taken from the database 2.2.2 made at first start). It covers
  none, another gateway, a row present only in the log of a running app,
  and a closed app, and checks that AionUi's folder is unchanged each
  time.
- TestAionUiUnreadableIsUnknown, TestAionUiStatusRereadsOnChange,
  TestAionUiDetect, TestAionUiImportRow (GUI: the row, unknown status,
  and /api/open refusing other aionui:// links).
- import-row.test.cjs gains the AionUi row (icon, known status in each
  language, the click opens the exact link, and it fits at 420px), in
  chromium and webkit across en, zh, zh-TW, ja and de. The same file
  now waits for the rows to settle before its alignment check: under
  load 105 one run caught Cindy's button mid-resize at 193.4px beside
  the picker's 194.4px. The old file passed 3/3 alone, so it is a
  timing assumption, not a layout bug.

Run at 18041fc5b (this change on origin/main 714ab8e8b):
- go test ./... -timeout 45m, through the suite lock: every package ok
  except internal/proc's TestNoCommandBypassesProc, red on
  internal/tui/keep.go:102 from 75e78a5a0 on main (#3567, which has a
  fix on skygunner's fork).
- gofmt -l clean; GOOS=linux go vet -tags nogui ./... and GOOS=windows
  go vet of agent, gui, cli and sessions clean.
- import-row.test.cjs: 20/20 in chromium and webkit.
- The whole GUI suite (make test-ui, 882 files) was still running at
  push, so it is not recorded here.
Rebased onto cbbf3163c, which changes GUI assets and api.go. At the
pushed head: go vet of the four packages is clean; go test
./internal/gui ok; the AionUi, Cindy and pinned-key agent tests are ok.
import-row.test.cjs at load ~210: one run had 19/20, and that run's
output wasn't kept, so I can't name the failing case. The next three
runs were 20/20.

Tried: magpie built at this commit with -tags nogui under a sandbox
HOME. `magpie aionui` printed "magpie aionui add  to add magpie" with
AionUi's folder and no database. With a copy of the real 2.2.2 database
holding one row at the gateway's /v1, it printed "magpie added".

Broken by hand:
- Dropping the aionui prefix from /api/open: TestAionUiImportRow red
  ("AionUi's link was not handed to the desktop").
- The reader put back to a plain mode=ro open: TestAionUiHas red
  ("AionUi's folder changed: aionui-backend.db ->
  aionui-backend.db,aionui-backend.db-shm,aionui-backend.db-wal").
Both were restored and are green.

Not tried: the add form, the saved row and gateway traffic. The
released AionUi 2.2.2 desktop app asks for an aionui.com sign-in before
any page, Settings included. That sign-in was not faked, and no
aionui.com account was available, so the link has never been opened in
a signed-in AionUi end to end. Also not tried: what AionUi saves for
platform custom when it is confirmed, AionUi's User-Agent (so none is
matched), and the aionui:// handler on Linux and Windows (Electron's
setAsDefaultProtocolClient, unverified there).
2026-10-25 16:49:29 +08:00
yetone c26a418d23 agent: an import app's status magpie can't read is unknown, not "not added"
Agent.Added now returns (added, known). Cindy's reader turned any
failure (a locked, corrupt or unreadable cindy-local-v1.db) into "Not
added", which told a user who had added magpie that they hadn't. Now
an unreadable database is unknown: /api/agents leaves `added` out and
the row shows the "confirm it there" hint, as it does for Lody. A
stopped WSL distro's app is unknown too, not "not added".

Cindy's database is also read without writing beside it. A mode=ro
open of a WAL database while Cindy was closed made cindy-local-v1.db-wal
and -shm in Cindy's own folder. It now goes through
sessions.OpenUntouched, which is what the Cursor reader already did
(immutable with no log, from a copy with one), moved out of
openCursorStore so both share it.

The CLI's list still offers `magpie cindy add` when the status is
unknown; it never said magpie was missing.

Run: go test ./internal/agent ./internal/sessions ./internal/cli ok;
go test ./internal/gui -run 'Import|Lody|Cindy|Agents' ok.

Broken by hand: Cindy's reader put back on the mode=ro open made
TestCindyHasClosedWALAndUnreadable red ("Cindy's folder changed:
cindy-local-v1.db -> cindy-local-v1.db,cindy-local-v1.db-shm,
cindy-local-v1.db-wal"); api.go ignoring `known` made
TestImportStatusUnreadableIsUnknown red. Both restored, both green.

Not tried: a real Cindy install; the read is tested on fixture
databases only.
2026-10-25 16:49:29 +08:00
yetone 0152f66966 provider: a Remote magpie's model list follows the other magpie's, fetched every 10m (6igsteven on Discord)
6igsteven (Discord, 10-24/10-25): GLM-5.3-Trial and GLM-5.3-Flash-Trial
are listed on the magpie that runs the ZCode plugin, and not on the
magpie that uses it as a Remote magpie. The trial entries come from the
ZCode plugin once it reads the account's gift (zcode 0.1.26), and the
other magpie's /v1/models lists them as it lists every catalog entry.
But a Remote magpie is a provider of keys: its list was fetched when it
was added and then only when Fetch models was pressed in its editor
(KeepListsFresh asks only providers with a RefreshEvery, FetchNew only
accounts). So anything listed there later (the trial models, a new
provider, plugin or routing group) never reached this magpie.

A Remote magpie with no RefreshEvery now has a 10m schedule
(RemoteMagpieEvery, RefreshSchedule), so KeepListsFresh refetches it
through the same Refetch as Fetch models. `magpie provider refresh-every
<id> off` on a Remote magpie is kept as "off" rather than "" so the
user's off isn't read as unset. CLI show/refresh-every print the
schedule in force. Other providers are unchanged: no schedule means
only when asked.

Run: TestRemoteMagpieListFollowsTheOtherMagpie (new) with
TestKeepListsFreshFetchesWhatIsDue, TestParseRefreshEvery,
TestSaveKeepsTheListsScheduleAndRules: ok, sandbox HOME, Go caches
pinned. Broken by hand: RefreshSchedule returning RefreshEvery alone
(the old behaviour) fails the new test with "asked [], want [office]";
restored, ok. gofmt -l clean.
Then, at this commit: go test ./internal/provider ./internal/cli ok
(140s, 58s); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows ok; darwin, linux (nogui) and windows builds ok.
Not run: go test ./... - the machine's disk had under 1GB free
(other sessions' work) and load ~200, so a full suite would not fit.
Not tried: a real two-computer setup with a live ZCode gift. A Remote
magpie whose user curated its picks (left a listed model unpicked)
still doesn't take new models by itself (withNewlyListed, by design).
2026-10-25 16:30:48 +08:00
yetone bea9f905d0 redact: a key can go as a made-up key of its own form, not a placeholder (Charles Cao on X)
Charles Cao on X (2114238140835844575) asked for a format-preserving
swap: sk_w3axCByTQgK1PxqPhfKTrJOLBqz6sbZv sent as another sk_ key of the
same shape and put back on the way home. With Mask secrets on, a key went
as {{API_KEY_xxxxxxxx}}, which a tool's check of the key's form fails
and a model may remark on.

Settings › Privacy has "Keep a key's form" under Mask secrets (shown only
while secrets are masked; off by default, so nothing changes for anyone
who doesn't turn it on). settings.RedactShape → redact.Options.Shape;
api.go keeps it when a page from before doesn't send it.

How (internal/redact/shape.go):
- Only a secret's kind, 16+ characters, all of [A-Za-z0-9-_.]. Personal
  data, the user's words and anything else still go as placeholders. A
  made-up key needs no JSON escaping.
- Prefix kept (sk-proj-, sk-ant-api03-, github_pat_, AKIA/ASIA, or up to
  4 letters plus - or _), same length, separators in place, and each
  other character a random one of the same class. A hex key stays hex
  of its case. Random from HMAC(placeholder key, kind+value), so it is
  the same every turn and a vendor's prompt cache still matches.
- Kept in values like a placeholder (makeRoom shared with placeholder),
  so masking records, Value(), signed-thinking re-masking (the put
  closure) and known-value re-masking work unchanged; kindOf reads it.
- restore() puts made-up keys back first, then placeholders.
  RestoreJSON no longer returns early when one is in the body;
  hasShapes copies nothing while none was made.
- A stream holds an event's end that may start a made-up key
  (partialTail → shapeTail), but never one inside a key that has come
  whole: a key ending in "s" is also the start of every sk_ key, and
  without that its end was held and the key went out unrestored (found
  as 1 in ~40 fresh processes; 0 of 150 after).
- apply() leaves a made-up key that came back unrestored alone
  (outsideShapes), as it does a placeholder.

Tests: shape_test.go — form kept (the reporter's key, hex, ghp_,
sk-proj-), same fake twice, Restore; off is placeholders; email/short/
odd values not shaped; MaskJSON then RestoreJSON with escaped tool
args; signed thinking re-masked to the same fake; no re-mask of a fake;
a stream split mid-key, after one character, and a key ending as one
starts. GUI: redact-shape.test.cjs (both engines, 5 languages, 1100 and
640px; row under Mask secrets, Off by default, one save with the rest
kept, no scroll, a later save keeps it; no row while secrets are off).
redact-words-any-case now finds Mask personal data by place after the
new row, not by index.

Broken by hand, each red: no restoreShapes (KeepsForm, JSON, Stream),
no shapeTail (Stream), no outsideShapes (JSON), no hasShapes (JSON),
put ignoring Shape (all three), shapeTail without the whole-key bound
(Stream).

Budgets: app.js 1,321,994 → 1,322,289 and the core 1,529,542 →
1,529,837, the row's 295 bytes, Settings' own row, no room added.

Doc: docs/subsystems/gateway-routing.md, a bullet beside the other
masking options.

Run at 4dfd88206 + this change (worktree key-shape):
- GUI (node --test, playwright 1.62.0, both engines): redact-shape
  22/22, redact-words-any-case 20/20, i18n-keys 4/4, privacy-model
  24/24, redact-kinds 22/22, mask-actions 20/20, masking-records
  52/52, provider-proxy 8/8, click-scroll 22/22.
- go test -tags nogui ./internal/gui ./internal/redact
  ./internal/settings: ok (internal/masking has no tests).
- TestShapeStream in 150 fresh processes: 0 red.
- Rebased on 04439c859: budget tests, internal/redact,
  internal/settings ok; gofmt clean; vet -tags nogui on darwin, linux
  and windows ok; i18n-keys 4/4.
- Earlier, at load ~40: account-discovery 22 red, red the same on
  origin/main defbb1a15, #3497 (ggbdpq has it); redact-rule-edit
  webkit zh-TW 420px red once, 3/3 alone, #3407.
- The full suite was not run before this push: it is queued behind
  other sessions' suites (one per machine).
Not tried: a real vendor turn with the setting on.
2026-10-25 15:35:52 +08:00
yetone be7f174677 gateway: a key out of a guessed quota is asked again after one refusal, and held a minute (zoecats)
zoecats (Discord #feedback, 10-25): a local aggregator answers 429
insufficient_quota "quota exhausted" for the moment it switches
upstreams, and the agent's retry and every request after it were
answered by magpie itself, "out of its allowance: not asked again
before …", Retry-After 900. v0.1.1488 (c6768f06f) let it through only
when the user unticks the provider's new "Rests" switch; by default it
was still held (checked on origin/main 4dfd88206 below). The owner's
zero-config rule wants it to just work.

Cause: quotaHeld (#1772) answers from the rest, without asking, as soon
as every key left rests out of its allowance or credit, from the first
refusal on, for as long as the rest: 15 minutes (quotaRest) or 30
(creditRest) that magpie guessed when the vendor named no time.

Now (Rest.first, Rest.askAt, Rest.asksAt), for a rest whose length
magpie guessed (creditRest, or quotaRest with no OwnQuotaRest):
- The key is held only once it was refused so twice in a row. The first
  refusal still rests it (the order passes it over for a ready
  candidate), but the next request, the agent's retry first, asks it
  again; served, its rest is cleared as before.
- Held, it is asked again a minute on (fallbackCooldown), once, and
  held again if refused.
- A time the vendor named (resets, Retry-After, a window) or the user
  set (quotaRest, QuotaResetAt) holds it from the first refusal to
  then, as before. A first version gave every refusal one more ask;
  the full gateway suite turned it down in TestClineFreeLimitLeaves-
  OtherModels and TestZhipuRestsUntilItsReset (a named reset asked
  again), so it is limited to the guess.
  #1772's keys out for the week are asked at most once a minute each
  while requests come, not on every request.
- soonestBack, the Retry-After a 429 without one gets, says when the
  first of them is asked again: none after a first refusal, about 60s
  for a guessed hold (was 900 or 1800). That narrows #3556 for a
  guessed hold; a vendor-named or user-set one is as before.
- A rate limit was already asked again (restLast, retries within the
  request) and is unchanged; the new test holds it there, Retry-After
  0 and every key resting included.
- The "Rests" switch (LimitRestOff) stays: unticked, nothing rests at
  all.
docs/subsystems/gateway-routing.md says so.

Run (worktree at origin/main 4dfd88206 plus this change):
- Reproduced first on the old code with tests:
  TestRetryAfterALimitIsAsked (new; 429 insufficient_quota, a usage
  limit with no reset, the same with Retry-After: 0, 402, every key of
  two; plus two rate-limit cases): the five limit cases red on
  4dfd88206 ("request 2 after the refusal: 429 … not asked again before
  14:34"), green now; the rate cases green on both.
  TestHeldLimitAskedAgainInAMinute (new) red on the old code (Retry-After
  900, not asked a minute on), green now. TestAllRestingAnswersFromRest,
  TestOwnQuotaRest and TestQuotaHeldOnlyForKeysOutOfAllowance changed to
  the new rule (each key asked once more, then held; held Retry-After
  about 60s; a user-set week held from the first refusal); red on the
  old code. TestRemoteMagpieRestsTheModel (#2077) asks Claude Code once
  more before its hold: the other magpie can't read "resets 8:10pm
  (America/Los_Angeles)", so its 15 minutes there are a guess.
- Broken by hand, each red, then restored: r.first always false ->
  TestRetryAfterALimitIsAsked's five limit cases; askAt never set ->
  TestHeldLimitAskedAgainInAMinute and TestAllRestingAnswersFromRest
  (Retry-After 900).
- Sandbox HOME, a nogui build of 4dfd88206 and of this tree, `serve` on
  127.0.0.1:3481 over a Python fake answering 429 insufficient_quota
  "quota exhausted" once, then 200: old: 429, then 429 "not asked again
  before 14:41", 429 again, Retry-After 900, 1 upstream POST. New: 429
  (no Retry-After), 200, 200, 3 upstream POSTs (rerun on the final tree). The fake refusing every
  time, new: 429, 429 Retry-After 60, then held "not asked again before
  14:27" Retry-After 60, 2 upstream POSTs.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway/ at
  4dfd88206 plus this tree, through suite-lock (after the DSH run):
  ok 446.6s. The first full run, before the rule was limited to a
  guess, was red in the three tests named above.
- gofmt -l clean; go vet ./internal/gateway/ (darwin); GOOS=linux go
  vet -tags nogui ./...; GOOS=windows go vet -tags nogui
  ./internal/gateway/: ok.

Not tried: zoecats' own aggregator; a real vendor's out-of-credit key
(OpenAI insufficient_quota) to see the once-a-minute ask in use; the
GUI (no GUI file changed; the Routing page reads the same rests);
Windows box (Windows CI compiles the tests only).
2026-10-25 15:02:12 +08:00
yetone defbb1a159 gateway: a Chat reply's cache read reaches the agent in OpenAI's names (B3TT3R on Discord)
B3TT3R (Discord #feedback, 10-25): DeepSeek Harness on DS-v4.1-Flash showed
"缓存命中 0%" over 1.2M input, and dsh's message usage carried only
inputTokens, outputTokens and totalTokens.

dsh reaches magpie through @deepseek-ai/dsh-llm-pi-ai with api
openai-completions, so its usage comes from pi-ai 1.4.0's parseChunkUsage:
cacheRead = prompt_tokens_details.cached_tokens ?? prompt_cache_hit_tokens
?? cached_tokens ?? 0, and nothing of Anthropic's. dsh's mapUsage drops a
0. magpie's Chat passthrough sent the upstream's usage as it came, so when
a provider told the cache only in another vendor's names (a relay giving
Anthropic's cache_read_input_tokens, or DeepSeek's prompt_cache_hit_tokens
or Moonshot's top-level cached_tokens beside a 0 in prompt_tokens_details)
the gateway counted the hit in its own usage log while the agent saw none.

Now chatTidy (stream) and chatWhole (whole reply) tell such a usage in
OpenAI's names too: prompt_tokens_details.cached_tokens, cache_write_tokens
when a write was told, and prompt_tokens counting both, with total_tokens
moved by the same amount. Every field the upstream sent stays. A usage in
OpenAI's names alone is never decoded (mayMendUsage looks for the other
names first), and one that already agrees comes back byte for byte.
Translated routes (Responses, Messages, Gemini) and plugin replies already
build the usage from cUsage and needed nothing.

Not proven: which provider B3TT3R uses. "DS-v4.1-Flash" is not how magpie
names a dsh model, and DeepSeek's own API sends both names, which pi-ai
already read right through magpie (checked live below). So this fixes the
case where magpie is at fault; if B3TT3R is on DeepSeek's own key the
cause is elsewhere and the reply asks.

Run, at this head (rebased on 4dfd88206):
- go test -count=1 -timeout 45m ./internal/gateway/... : ok (457s)
- gofmt -l internal/gateway docs: empty
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet
  ./internal/gateway/: clean

Broken by hand: with chattidy.go from the parent,
TestAgentReadsCacheTokensOnEveryRoute fails for chat-anthropic-names,
chat-zero-details and chat-moonshot, each on chat whole and chat stream;
every translated route and the plugin route pass there as on the new code.
TestUsageRecordsCacheTokensOnEveryRoute (gateway's own count),
TestOpenAIUsageLeavesOpenAIsAlone, TestMayMendUsageOnlyOtherNames and
TestPluginAgentReadsCacheTokens pass on the new code.

Real use, sandbox HOMEs, real dsh 0.2.1-rc.2 headless, real DeepSeek
behind a local relay that rewrites usage into Anthropic's names: through
the parent's binary dsh's session log has usage
{"inputTokens":367,"outputTokens":97,"totalTokens":464}, the reporter's
shape; through this one {"inputTokens":367,...,"cacheReadTokens":5376},
then 5632 and 5888. Straight to DeepSeek's own API (no relay), through
this change, dsh read cacheReadTokens 5248 to 5888; the parent sends that
usage byte for byte, so it was read the same before (not run live).

Not tried: a real Moonshot or OpenRouter key; the dsh desktop app (same
llm-pi-ai provider); the -responses and -anthropic dsh routes with a real
relay (covered by the route tests only).
2026-10-25 14:41:03 +08:00
yetone 4dfd88206e agent: Lody on Linux is run with its import link, which xdg-open turned away (Atlas on Discord)
Atlas (Discord #help, 10-25, Linux): Lody was running, and adding it
from magpie said "failed to open uri". magpie handed the
lody://provider/import link to xdg-open, as every OS's opener.

Cause, shown with the real Lody 0.108.1 AppImage in an amd64 Ubuntu
24.04 container (Xvfb, no update-desktop-database, as on many
desktops): Lody writes ~/.local/share/applications/ai.lody.desktop.desktop
with MimeType x-scheme-handler/ai.lody.stable and x-scheme-handler/lody,
but runs `xdg-mime default` for ai.lody.stable only. lody:// then rests
on the desktop database cache, which nothing built, so
`xdg-open lody://...` answers "gio: lody://...: Operation not supported"
(rc 4) while ai.lody.stable:// opens. With update-desktop-database run,
both open. The same on GNOME and XFCE with a fake handler at that entry.

Fix: on Linux agent.OpenLody runs what xdg-open would have run, the
Exec line of Lody's own desktop entry (ai.lody.desktop, then
ai.lody.desktop.nightly, then dev.loro.lody.oss; $XDG_DATA_HOME before
$XDG_DATA_DIRS, the first file of a name decides), with %U as the link.
An entry whose program is gone, no entry, or a start that fails falls
back to the opener as before. macOS (Info.plist claims lody:) and
Windows (Lody registers lody itself) are unchanged. The GUI's
/api/open and `magpie lody add` both go through it.

Tests: TestOpenLodyRunsItsDesktopEntry and TestDesktopExec
(internal/agent), TestLodyImportRunsLodyOnLinux (internal/gui, Linux
only). The GUI test is red on the old providers.go in golang:1.26.8
docker ("the link went to xdg-open: lody://..."), green on this one.
TestLodyImportHandoff now sets XDG_DATA_HOME/XDG_DATA_DIRS to its
sandbox, and XDG_DATA_DIRS is in TestFolderVarsAreListed's notAnAgent
(the system's data folders; the first run of internal/agent was red on
it until then).

Not covered, and Lody's to change: magpie on a machine Lody Desktop
reaches as a remote (Atlas's later detail: Lody on their own computer
connected to the host magpie runs on). Lody 0.108.1 imports only into
the desktop's own machine (the renderer writes the configs with
machineId = its local machine and needs __LODY_ELECTRON__), and the
link's payload takes only kind/id/name/auth/endpoints with a loopback
gateway, so no link names another machine. Lody Desktop opened on that
host shares the agent's ~/.lody/machine-id, so the import lands on the
same machine; docs/subsystems/agent-wiring.md says so.

Run:
- real Lody 0.108.1 AppImage in docker: agent.OpenLody reached a
  running Lody (its log: "handleDeepLink accepted deep link {protocol
  'lody:', host 'provider', pathname '/import'}", "sending deep link to
  renderer") and a stopped one ("pending deep link sent to renderer
  after did-finish-load"); xdg-open on the same link: rc 4.
- golang:1.26.8 docker, -tags nogui: agent and gui Lody tests ok.
- macOS: HOME=<sandbox> go test -timeout 45m -count=1 ./internal/agent
  ./internal/gui ./internal/cli: gui ok (124.9s), cli ok (48.6s), agent
  FAIL on TestFolderVarsAreListed (XDG_DATA_DIRS, fixed here); agent
  again after the fix: ok (213.5s).
- rebased on origin/main c6768f06f (5 commits, providers.go among them): the
  Lody, DesktopExec and FolderVars tests of agent, gui and cli ok again.
- gofmt -l clean; GOOS=linux go vet -tags nogui ./... ok;
  GOOS=windows go vet ./internal/agent ./internal/gui ./internal/cli ok.

Not tried: a real GNOME/KDE session with a signed-in user, the .deb
install (its postinst runs update-desktop-database when present),
Nightly and OSS builds, KDE's kde-open, the web-mode page (location.href
still opens it there). No GUI asset changed, so no Playwright run; no
budget raised.
2026-10-25 14:13:38 +08:00
yetone c6768f06f6 providers: a provider of the user's can be set never to rest for a limit
zoecats (Discord #feedback, 10-25): a local aggregator answers "quota
exhausted" (429 insufficient_quota) for the moment it switches
upstreams, and magpie set its key aside for 30 minutes, answering every
request itself ("out of its allowance: not asked again before …").

A provider the user added now has, under the editor's Advanced fold,
"Set it aside when out of quota or rate limited" (Rests), ticked by
default, with a note. Unticked (provider.LimitRestOff, limitRestOff in
providers.json), restAfterMarked rests nothing, counts no failure and
sinks nothing for a refusal it reads as out of quota, credit or rate
limited, or any 429: by "off", and the next request is sent to it as
usual. restDrawer rests no image model of it either. A 401, a model not
served and a plain failure still rest it. The default is as before. The
editor offers it only to a provider the user added (custom); a Save that
leaves it out keeps it. A checkbox (tick), no native select; strings in
zh, zh-TW, ja and de. app.js's budget (and the core's) are raised by the
576 bytes the row adds, with no room, after the comment was cut.

Run on origin/main 75e78a5a0 plus these two commits:
- gofmt -l clean; node --check app.js, i18n.js; go vet ./... on darwin
  and GOOS=linux/windows -tags nogui: ok.
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/gui/
  ./internal/provider/ (suite lock): gateway ok 417.9s, provider ok
  114.4s, gui red only on TestCoreScriptBudget (741 over); after the
  trim and the raise, TestCoreScriptBudget, TestProviderSaveLimitRestOff
  and TestI18n* ok.
- GUI, chromium and webkit: provider-limit-rest (new; en, zh, zh-TW, ja,
  de at 1100 and 420), provider-insecure-tls, i18n-keys, fallback-more:
  128/128. Every provider*, every file opening Advanced, i18n-keys,
  routing-lifted-elsewhere, rest-try-now, rate-limited-sink (58 files):
  1053 of 1055 (on the pre-trim app.js, the trim only a comment and an
  unused class): providers-last-known webkit zh-TW (filed #3565) and
  tencent-access-key webkit en (#2733) red at load ~130; each passes
  alone in WebKit on this tree and on origin/main 5b2b3d3f5.
  After the trim: provider-limit-rest, i18n-keys, provider-insecure-tls
  124/124.
- Sandbox HOME, a dev build of this tree, fake upstream answering 429
  insufficient_quota "quota exhausted": by default the second request was
  magpie's own "not asked again before 13:17" (1 upstream hit). Saved
  limitRestOff:true through /api/provider/save and lifted the rest:
  three requests, three upstream hits, each the vendor's 429; then 429
  rate_limit_error: no rest on the key (each request still asked again
  after 1s, 2s, 4s within itself, as a lone candidate always is); the
  upstream back, 200 at once.

Broken by hand, each red, then restored:
- the check in restAfterMarked off: TestLimitRestOffKeepsAsking ("1
  rests set after the refusal, want none") and
  TestLimitRestOffRestsNothingForALimit ("rests 29m59s by credit").
- the save's keep-when-left-out branch removed: TestProviderSaveLimitRestOff
  ("a Save that left it out turned rests back on").
- app.js's save line removed: provider-limit-rest's first two tests red
  in webkit zh-TW 420.

Not tried: zoecats' own aggregator; the in-request retries on a rate
limit (1s, 2s, 4s) are left as they are, as they are not a rest.

Again after rebasing on origin/main 1b039a3c7 (which changed app.js,
client.js and gateway.go): gofmt, node --check, vet on three OSes ok;
go test ./internal/gui/ ok (the budgets set to this head's sizes);
go test -run 'TestTryNow|TestRenewed|TestLimitRestOff|TestRestCapOff|
TestOwnRestCap|Sink|Unrest|Rest' ./internal/gateway/ ok; GUI, both engines: provider-limit-rest,
i18n-keys, provider-insecure-tls, routing-lifted-elsewhere, rest-try-now,
rate-limited-sink, routing-model-rest, routing-rest-off, routing-rule-drag,
routing-rule-models, view-trackpad-coast, fallback-more: 272/272.
2026-10-25 14:00:59 +08:00
yetone 67361b54fb routing: Try now from the editor reaches the Routing page, and puts a sunk key back
zoecats (Discord #feedback, 10-25, v0.1.1477): a local aggregator answered
"quota exhausted" while it switched upstreams; Try now in the provider's
editor left Routing showing 429 until magpie restarted.

Cause, in three holders:
- The Routing page kept lifts in its own liftedAt, filled only by its own
  Try now. A lift from the editor (or anywhere else) never reached it, and
  the kept routes' snapshots went on drawing the rest. The trace now
  carries every rest lifted (TraceState.Lifted, from restingUntil.lifted,
  kept up to longestMonthly), Unrest/UnrestAll/renewed wake the long-poll
  (trace.lifted), and the page leaves out a rest, a sunk key and an
  Accounts and keys count that a lift came after.
- With Sink on, a rate-limited key stayed at the back of the order until
  restart: Unrest never cleared sunk. unsink(key) now does.
- The gate itself: checked on the old binary in a sandbox HOME (single key
  over a fake answering 429 insufficient_quota "quota exhausted"). magpie
  rests it 30 min and answers later requests itself ("out of its
  allowance: not asked again before …"); Try now with the editor's key
  lifted that and the next request reached the upstream (200), on
  /v1/chat/completions and /v1/messages, streaming and not. So the stuck
  state was the display and the sink, not quotaHeld.
  Left alone, filed: #3555 (Try now lifts nothing when another magpie
  serves the gateway, unrest 400) and #3556 (the held reply's
  Retry-After, 900s here, outlives the lift for an agent that honours it).

Run at this change on its first base, 42976f9a0:
- gofmt -l clean; node --check client.js; go vet ./... on darwin, and
  GOOS=linux/windows -tags nogui: ok.
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/gui/ (suite
  lock): ok 404.9s, ok 128.9s.
- GUI, chromium and webkit, 5 languages, narrow and wide where the files
  do: rest-try-now, rate-limited-sink, routing-model-rest,
  routing-wb-restricted, routing-lifted-elsewhere (new), routing-rest-off,
  i18n-keys: 132/132. routing-lifted-elsewhere 20/20 alone. Every
  routing*, panel-routing* and rest-* file (108
  files, 1406 tests): 48 red in 8 files. routing-rule-effort, routing-pause,
  routing-live-patch, routing-rule-remove, routing-intent-entry,
  routing-manual and routing-time are red the same on origin/main
  15f0d4cde (a detached worktree, no changes) and filed (#3408-#3411,
  #2174, #3094, #3096, #3465, #1612). routing-steady flakes in both
  engines on both trees: WebKit alone, interleaved, 3 runs each, base 1
  of 3 green, this tree 1 of 3; the last group is read while the editor
  still opens (#3412, #1804).
- Sandbox HOME, fixed binary, two keys: after the editor's unrest the
  trace carried lifted, the next request went to key A (200), and the live
  Routing page went from "rest: A m1 rate limited · back in 10 min … Try
  now" to no rest.

Again on origin/main 1b039a3c7 with the next commit (its body says
what): vet, ./internal/gui, the gateway's rest and Try now tests, and
the Routing GUI files above, ok.

Broken by hand, each red, then restored:
- no unsink: TestTryNowPutsASunkAccountBack fails (order stays b,a).
- no trace.lifted, or no liftSeq wake: TestTryNowToldToTheRoutingPage's
  waiting Trace times out.
- no Lifted in Trace: Lifted empty.
- no lift recorded in renewed/UnrestAll: both tests fail.
- old client.js: routing-lifted-elsewhere times out in both engines; only
  the sunk check removed: "key c still at the back"; only the acts check:
  "Accounts and keys still counts key a resting".

Not tried: zoecats' own aggregator and harness; two magpies at once
(#3555). The Sink help text still says "Kept until magpie restarts", left
as it is: a key whose rest has ended shows no Try now.
2026-10-25 14:00:59 +08:00
yetone 1b039a3c72 gui: a trackpad's coast after the lift is the reader's scroll, no longer put back (issenn on Discord)
issenn (v0.1.1472, macOS app): a page with a scrollbar wouldn't scroll by
trackpad. It shook fast and snapped back, and only dragging the bar
worked. Seen on Agents.

Cause: the scroll guard puts back any .view scroll that comes outside
a window the reader's own events open. A wheel opened 250ms. When the
fingers lift, WebKit on the Mac plays the coast itself, and the page
hears those scrolls with no wheel for each. Once the last wheel's 250ms
ran out, the guard put back every coast scroll. Each coast step moved
the page and each put-back moved it back, so it shook and came to rest
where the fingers lifted.

Fix: the wheel now starts the same chain a touch fling does (flings,
flingUntil). Each view scroll keeps the next one the reader's until the
coast rests, and a click still ends it (purposeUntil = flingUntil = 0).
A code scroll at rest is still put back. The code and the comment fit
the old app.js size; no budget raised.

Test: view-trackpad-coast.test.cjs, chromium and webkit, en and zh. It
does five trusted wheels, then a 1s coast the page plays each frame
with no wheel. The coast must reach its end, a code scroll at rest is
put back, and a click mid-coast stops the row under the pointer.
- On origin/main's app.js: red 6/6 ("lifted at 40, coast asked 166,
  left at 101/105").
- Broken by hand, flingUntil not reset by a click: red 6/6 ("the row
  was at 269 after the click, 140 once at rest").
- With the fix: 6/6.

Real WKWebView probe (a Swift app loading the GUI with synthetic
NSEvent scroll phases): with every momentum wheel delivered, old and new
both end at 277. With the wheels after the first 32 kept from the page,
standing in for the coast with no wheel, old ends at 249 and new at
277.

Run:
- click-scroll, view-scrollbar-drag, view-middle-autoscroll and
  view-trackpad-coast: 44/44.
- Whole GUI suite (internal/gui/tests/*.test.cjs, chromium and webkit,
  every language) through suite-lock: still running at push, no red in
  its first 30 minutes; a red it finds gets a follow-up commit and an issue.
- go test -tags nogui -run Budget ./internal/gui: ok, run again after
  the rebase.
- No Go changed, so no gofmt or vet.

Not tried: a real trackpad on the mac app. Synthetic NSEvents skip
WebKit's MomentumEventDispatcher, which swallows the system's momentum
and plays its own. That the page gets its coast with no wheel is the
best fit for the report, not something seen on issenn's hardware. Also
not tried: ProMotion 120Hz, and WebKitGTK and WebView2 with a real
touchpad.
2026-10-25 13:32:47 +08:00
yetone b5a78fd8b5 routing: a group's rules are dragged into order
monkeyin_92 on X: "希望可以上下拖动规则". Rules are checked top first, so
their order matters, and it could only be changed a place at a time from
each rule's ⋯ menu (Move up / Move down).

A rule's number is now its handle, as a model's number is in the same
editor (memberHandle): drag it up or down (the shared dragRows, which
the members, groups and agents use), or focus it and press Alt+↑/↓. The
rules are renumbered at once and the keyboard stays on the moved rule's
handle. The grip beside the number shows only on hover, while dragging,
or from the keyboard; the dragged rule is lifted with a card background
and shadow, no coloured border. Move up and Move down stay under ⋯ and
now go through the same moveRule. Saved as the group's rules in their
new order. "Move rule {n}" in zh, zh-TW, ja and de; the title reuses
"Drag to reorder · Alt+↑/↓ to move".

Run at this head:
- routing-rule-drag.test.cjs (new), chromium and webkit, en, zh, zh-TW,
  ja, de: 10 of 10. It checks the handles and their names, the grip hidden
  away from the row and shown on hover, a drag of rule 3 above rule 1
  with nothing opened by the drag's click, Alt+↓/↑ (past the end too)
  with focus kept, ⋯ Move down, the page not moved, and the saved rules'
  order with their conditions. Red on the parent (no .rt-rhandle): 10 of
  10 in the parent's full run.
- GUI: every routing-*.test.cjs plus i18n-keys, click-scroll and
  group-member-drag, both engines: 1321 pass, 55 red, all in files red the
  same on origin/main 42976f9a0 (routing-pause #3410, routing-intent-entry
  #3408, routing-rule-effort #3411, routing-rule-remove #3096/#3094,
  routing-manual #3409, routing-steady #3412/#1804, routing-live-patch
  #2174, routing-time #3465), but one routing-bodies case and one
  routing-intent-entry 440 case, which pass run alone (load ~40).
- Real run: built binary, sandbox HOME, magpie web on 127.0.0.1:3486;
  group Mix with rules "tokens >= 1 -> one/m, two/m" and
  "agent codex -> three/m". In headless Chromium dragged rule 2's number
  above rule 1, Save, reload: the editor and `magpie group rule mix` both
  list "agent codex -> three/m" first, the two-model rule second and
  whole.

Not tried: a real mouse or trackpad; touch; the WebKitGTK app on Linux;
Windows.

Rebased onto 5b2b3d3f5 (10 commits, gateway, gui and routing's
client.js among them) and run again at the rebased pair's head
68701dfe4: gofmt -l clean; GOOS=linux and windows vet -tags nogui of
provider, gateway, cli, tui clean; go test -tags nogui -timeout 45m
internal/provider (171s), cli, tui, gateway (422s), gui (budgets): all
ok; GUI routing-rule-drag, routing-rule-models, routing-compact,
i18n-keys, click-scroll, group-member-drag in both engines all pass;
routing-rule-remove red as on main (#3096, #3094).
2026-10-25 13:32:12 +08:00
yetone f99d27abc2 routing: a rule names several models, tried in order
monkeyin_92 on X: "can a rule take several models? Otherwise one rule
with several models is several rules." A rule now takes more than one
model (Rule.More after Rule.Use; `more` in the group's JSON, use=a,b
typed). They go first in that order: when the first fails or rests the
rule's next takes the request, ahead of the models the later matching
rules name and the group's others.

Every reader of Rule.Use goes through Uses/SetUses/MapUses/Without/Names
in grouprule.go:
- cleanRules: each must be the group's, each named once; a pause names one.
- gateway: ruleFor's turn hold, tool rounds and outgrown turns, compaction
  (the rule's first that takes the summary, the others in Small),
  ruleMembers/ruleOver/applyRule, nestedRules and ruleLed (the one a
  nested group's turn stays on), modelRuled, ruleEffort (useEffort asked
  of each), ThenUses (leaves out all of the rule's own). RuleHit.More is
  in the trace; Instead from More has Unready false, one from a later
  rule Unready true, as before.
- ruledEntry: what the group takes is what every one of them takes.
- provider rename, auto/ refs, groupfast, a member's removal (a rule
  goes with its last), ShareGroup and its import (one this magpie hasn't
  is left out of the rule).
- CLI `group rule add use=a,b` and its listing; `group models-=` keeps a
  rule's other models. The TUI shows them joined and keeps the rule when
  one is deleted.
- GUI (plugins/routing): a chip per model, a + for the next one, an ×
  on each while there is more than one, a chip picks another in its place
  (app menu, no native select); the card's tooltip and the trace's why
  ("…so c/mini, which the rule names after it, goes first"), nested too;
  en, zh, zh-TW, ja, de.

Old data: a rule of one model writes no `more`, so groups saved before
read and save unchanged (TestRuleMoreOnDisk). An older magpie reads `use`
alone: its requests go to the first model, the others are plain group
members in group order; if it saves the group, `more` is dropped.

Tests: TestRuleSeveralModelsInOrder, TestRuleEffortReachesTheRulesNextModel,
TestRuleCompactPassesOverTheRulesSmallModel (gateway); TestCleanRulesSeveralModels,
TestRuleMoreOnDisk, TestRuleWithout, TestParseRuleSeveralModels,
TestThenUsesLeavesOutTheRulesOwn, TestRuledEntrySeveralModels,
TestSharedGroupRuleSeveralModels, TestRuleMoreRenamedAndKept (provider);
TestGroupRuleSeveralModelsCmd (cli); TestGroupTakeOutKeepsARulesOtherModels
(tui); routing-rule-models.test.cjs. Broken by hand: ruleMembers on Use
alone turns the first two gateway tests red.

Run at this head:
- gofmt -l clean; go vet -tags nogui clean with GOOS=linux and GOOS=windows
  for provider, gateway, cli, tui.
- go test -tags nogui -timeout 45m: internal/provider, internal/cli,
  internal/tui ok; internal/gateway ok (384s); the new gateway tests
  again after; internal/gui budgets ok.
- GUI: every routing-*.test.cjs plus i18n-keys, click-scroll and
  group-member-drag, chromium and webkit (en, zh, zh-TW, ja, de where the
  file has them): 1319 pass, 57 red. routing-rule-models passes in both.
  The reds are in files that are red the same on origin/main 42976f9a0,
  run there just now: routing-pause (#3410), routing-intent-entry
  (#3408), routing-rule-effort (#3411), routing-rule-remove (#3096,
  #3094), routing-manual (#3409), routing-steady (#3412, #1804),
  routing-live-patch (#2174), routing-time (#3465). The other 10 reds are
  routing-rule-drag.test.cjs, which is the next commit's and not in this one.
- Real run, sandbox HOME, built binary: three fake OpenAI vendors, group
  Mix = three/m, one/m, two/m, rule `use=one/m,two/m tokens=1`. one/m
  answers 429: the request went one -> two (not three, the group's
  first); the next went straight to two, the trace saying
  instead=two/m with more=[two/m].

Not tried: a real vendor account; the TUI by hand; Windows and Linux
runs (vet only).

Rebased onto 5b2b3d3f5 (10 commits, gateway, gui and routing's
client.js among them) and run again at the rebased pair's head
68701dfe4: gofmt -l clean; GOOS=linux and windows vet -tags nogui of
provider, gateway, cli, tui clean; go test -tags nogui -timeout 45m
internal/provider (171s), cli, tui, gateway (422s), gui (budgets): all
ok; GUI routing-rule-drag, routing-rule-models, routing-compact,
i18n-keys, click-scroll, group-member-drag in both engines all pass;
routing-rule-remove red as on main (#3096, #3094).
2026-10-25 13:32:12 +08:00
yetone 75e78a5a04 tui: quitting hands the gateway to magpie's service on Linux
zaidu259434 on X: "启动codex这些cli连接会失败,AI分析没自动启动magpie的网关".
With magpie installed inside WSL (or on a server over SSH), nothing
opens magpie at login, and XDG autostart doesn't run there. So once
`magpie tui` quit, the agents it had connected asked a gateway that was
gone.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Not tried: streaming on these two routes in the test (the real dsh run
streamed /v1/messages), Windows test run.
2026-10-25 05:51:52 +08:00
yetone 3387ea6156 gateway: an Antigravity drawing out of the image model's quota goes on to the next account and rests that model there (01huadalang)
01huadalang (Discord): with several Antigravity accounts, when one
account's image quota is spent, magpie doesn't move on to the next.
Model, entry point and error text were asked for and not answered yet.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Not tried: no real vendor was asked (fakes only); the refusal wordings
for stricter vendors are modelled, not captured from the reporter, who
named no upstream; the other community plugins' own translators
(Cursor, Devin, Qoder, ...) were not read for this; real pi/T3 Code not
run against this build.
2026-10-24 20:11:06 +08:00
yetone 436bcc946d routing: a request whose vendor counts no cache tokens shows no hit rate, not 0% (zeewell on X)
zeewell on X: every Kiro request in a routing group showed cache 0%, for
claude-sonnet-5.5 and claude-opus-5.5 from Claude Code, with 148k to
182k tokens and consecutive calls.

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

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

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

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

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

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

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

Not tried: a magpie build running the 0.1.16 plugin against Kiro from the
GUI. The plugin's own end-to-end run against Kiro gave
{"input_tokens":0,"output_tokens":19,"magpie_cache_unknown":true}.
2026-10-24 18:16:17 +08:00