Commit Graph
701 Commits
Author SHA1 Message Date
yetone 37fec12409 import: OpenCode's keys come in from its auth.json, Go's on OpenCode Go (@hu_xiaomi on X)
@hu_xiaomi on X asked whether magpie could pick up OpenCode Go's API key
by itself. OpenCode keeps what `opencode auth login` signs in to in
auth.json, in $XDG_DATA_HOME/opencode (~/.local/share/opencode when that
is unset, on Windows too). Its format and path were checked against
anomalyco/opencode v1.19.0, packages/opencode/src/auth/index.ts.

- OpenCode is now a source in the import picker (appReaders,
  import_opencode.go). An "api" key comes in on the magpie preset with
  the same id: opencode-go on OpenCode Go, opencode (Zen) on OpenCode
  Zen, and a vendor's key (openai, anthropic, deepseek, openrouter, ...)
  on that vendor's preset, the same way Alma's almaPresets work.
- auth.json keeps no address beside a key, so a key for a provider with
  no preset is listed and skipped ("it has no base URL"). Sign-ins
  (oauth: Claude Pro/Max, Copilot; wellknown: an enterprise server's
  token) are listed and skipped with the reason the picker already
  translates. No new GUI strings.
- OpenCode is read only when the user opens the picker. The Providers
  page's automatic discovery leaves it out (DiscoverSources, the `asked`
  flag), because the file holds every sign-in OpenCode has. magpie never
  writes to it. OPENCODE_AUTH_CONTENT is not read.
- presetAt: the first preset at a host won even when a later one matched
  the URL exactly. OpenCode Zen and Go share opencode.ai, so a Zen key
  would have landed on Go. An exact match now wins.
- importSources: a source whose stat fails with anything but not-exist
  (a folder magpie can't search) is found with an error, which means
  unknown. Before, it read as "Not found".
- The picker's tab shows OpenCode's own mark (icons/opencode.svg).
- docs/reference.md describes the source.

Not added: an "use the key OpenCode has" offer in the OpenCode Go add
sheet, because no other app has one there (no sibling to follow).

Run (macOS, go1.26.8, worktree at dd25997a4 before the rebase):
- go test -tags nogui -timeout 40m ./...: every package ok
  (63 ok, none failed; gateway 1806s, agent 1769s at load ~160-230)
- gofmt -l internal/provider internal/gui: clean
- go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...: clean
- GUI, playwright 1.62.0: import-opencode.test.cjs in chromium and webkit,
  en/zh/zh-TW/ja/de, at 900 and 390px: 20/20. import-collision,
  import-row, provider-discovery and key-import pass. login-import fails
  in chromium (fill/click timeouts) at load ~230. It fails the same way
  with HEAD's app.js (dd25997a4 = origin/main, just fetched), and #1307
  already tracks it.
- Broken by hand, each went red and was then put back:
  1. presetAt's old first-hit rule: TestImportOpenCodeAuth, Zen came in
     as opencode-go-2.
  2. no sign-in skip: TestImportOpenCodeAuth, anthropic's oauth entry.
  3. stat errors read as not found: TestImportOpenCodeAuthUnknown,
     unreadable folder.
  4. discovery reads OpenCode: TestImportOpenCodeAuth and
     TestOpenCodeWaitsForThePicker.
  5. XDG_DATA_HOME ignored: TestImportOpenCodeAuth, TestImportOpenCodeAuthUnknown
     and TestOpenCodeWaitsForThePicker.
  6. tab icon left at app-opencode.png: import-opencode.test.cjs.

Fixtures are auth.json as OpenCode v1.19.0 writes it
(JSON.stringify(data, null, 2), 0600), under a sandbox HOME and
XDG_DATA_HOME. Not tried: a real OpenCode install with a real key, and
the Windows box (the path logic is the same there; GOOS=windows vet only).
2026-10-15 19:20:09 +08:00
yetone a1f7b8c13f plugin: gateway key limits are the Key limits plugin on the gateway's budget point (P3)
The last P3 point, after observer, router strategy, middleware and tool:
the budget point (internal/gwbudget). A plugin serves a Limiter while it
is on; the gateway asks gwbudget.Limiting before any request of a key held
to a limit goes to a provider (reserveFor: the chat APIs' keyLimited, the
search MCP server and the vision one). A request without a key, or of a
key with no limit, never asks it.

It fails closed. A key with a limit and no limiter served gets 503
gateway_key_limit_off, X-Should-Retry false, nothing sent, and a rejected
usage row. With none served, Limiting first asks the gateway's refresh
(pluginrt.Refresh, at most once a second, never from inside one), so a
limit set a moment ago turns the plugin on for the request that needs it.
A limit reached is the 429 gateway_key_limit with Retry-After and
X-Magpie-Limit-Reset, as before.

plugins/budget serves internal/budget's limiter (budget.Limiter). It is
Essential and in use while a gateway key has a limit, so it can only be
off while none has; a keys file that can't be read is an error, so it
stays on. KeepFresh watches the keys file too. What a key has used and
has left (/v1/magpie/limit, the Gateway page, the CLI) and budget.Append
stay in the core, so the ledger counts a key's use the same either way,
and the key editor's limit fields stay, since setting a limit is what
turns the plugin back on.

The builtins GUI test wheels to the Routing row as it did to Usage's: the
new row puts it below the fold in WebKit, where the page puts back a
scroll that isn't the reader's (scrollOnPurpose).

Run at this head (on origin/main 9d97fd073):
- go test -count=1 -timeout 45m ./... at this head (after two runs cut short by a full disk): 63 ok, 1 red: internal/gui TestMainWindowCorners/macOS_26_SDK killed at its 40s deadline at load ~280 (#1936, no window change here); alone it passed.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestKeyLimitsOnAndOff, TestVisionMCPHeldToKeyLimit, TestKeyLimit*,
  plugins/budget tests

Broken by hand, each test went red: reserveFor ignoring Limiting's error,
Limiting letting a limited key through with none served, the refresh
never asked, Apply serving nothing, InUse counting keys with no limit,
InUse swallowing a read error, the vision and search MCP servers not
reserving, a refusal answered as 503 rather than 429.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3594, fake vendor on 3593, two gateway keys):
- no key with a limit: `plugin builtin off budget` turned it off; the
  key's request was 200
- `gateway-key limit <id> day --tokens 3`, then a request at once: 200,
  and the plugin read "on, in use"; the next 200, then 429 "has used 4 of
  its 3 ... tokens for this day"; turning it off was refused, "in use"
- the key with no limit: 200; /v1/magpie/limit answered the spent day
- limit removed: turned off; the key's request 200; a limit set again and
  a request at once: 200, "on, in use"
Not tried: the 503 in real use. With a key limited, the refresh turns the
plugin on before the request is refused (a hand-set `enabled: false` in
plugins.yml read "on, in use"); the 503 is the test's.
2026-10-15 18:41:03 +08:00
yetone dd25997a45 codex: a client's access_programs and the account's extraBody reach the ChatGPT backend, and its refusal comes back as it said it (magpie-releases#18)
NonMirror (0.1.1239, OpenCode, codex/gpt-daybreak-blue-latest on a ChatGPT
sign-in): a top-level Responses access_programs never reached upstream,
and the codex provider's extraBody wasn't applied.

Cause:
- A Codex account is streamed upstream, so a whole (stream:false)
  Responses request and every Chat or Messages request is translated
  (parseResponses/parseChat -> Request -> buildResponses). Request had no
  field for access_programs, so the rebuilt body dropped it. Only a
  streamed Responses request, relayed through codexBody, kept it.
- WithExtraBody skipped every signed-in account, and withPicks didn't
  copy the providers.json ExtraBody onto the account.
- writeError rewrapped every vendor error with code and param null, so
  even a forwarded refusal lost what it was about.
- The backend refuses a program the workspace hasn't got inside a 200
  stream (error event, invalid_request_error, access_program_not_enabled).
  The whole-translated path answered that 502 api_error, and translated
  streams wrote it as api_error, which holdWriter reads as 502: the same
  request went three times, then to the other accounts, and every one
  rested.

Fix:
- Request.AccessPrograms (Responses and Chat), built into the Responses
  body as it came; a null is kept.
- A ChatGPT (Codex) account takes extraBody; store, tool_choice and
  include stay magpie's (codexOwned). withPicks keeps ExtraBody.
- writeVendorError keeps the vendor's error.code and error.param on the
  relayed, whole-translated and streamed-translated status-error paths.
- requestRefused: a Responses stream error/failed whose error type is
  invalid_request_error carries status 400 and the vendor's error
  (Event.Said). The whole path answers that 400 with code and param; the
  Chat, Anthropic and Responses encoders write its type/code/param
  (saidError). Read by the type, never by words.
- Codex CLI sends access_programs as a top-level object on its Responses
  request (codex-rs ResponsesApiRequest.access_programs); OpenAI's Daybreak
  guide documents the same field.

Run:
- New: internal/gateway/codex_access_programs_test.go
  (TestCodexAccessProgramsReachBackend, TestCodexAccountTakesExtraBody,
  TestAccessProgramsNullKept), passes -count=3.
- Broken by hand, each went red: buildResponses not emitting the field
  (probe answered 200, the reporter's symptom); extraBodyTakes' Codex case;
  withPicks' line; codexOwned emptied; writeVendorError ignoring the body;
  the continuation site alone; retryable(400) true (asked twice, rested);
  requestRefused returning nothing (502, asked 4 times, both accounts
  rested); saidError a no-op (streamed: asked 4 times, rested); the whole
  site back to 502 (same).
- go test -timeout 30m ./...: all 62 packages ok (gateway 1559s at load
  ~26; an earlier run at the default 10m timed out in gateway under that
  load, not a failure). gofmt -l clean. GOOS=linux and GOOS=windows
  go vet -tags nogui ./... clean.

Real account (sandbox HOME, own port 3486, copied auth.json with a dead
refresh token; owner's ChatGPT Pro account, model codex/gpt-5.6-luna):
- "__daybreak_forwarding_probe__": 400 invalid_value, param
  access_programs.cyber ("Supported values are: 'standard',
  'daybreak_blue', and 'daybreak_red'") on Responses whole and streamed,
  Chat whole and streamed. The backend says invalid_value, not the
  guide's invalid_access_program.
- standard: 200. null: 400 invalid_type.
- daybreak_blue (not enabled for this workspace): 400
  access_program_not_enabled with param on Responses and Chat whole, the
  error event with that code on Responses and Chat streamed; ~1s each,
  one try (was 3 tries and a 502 before this change).
- The next plain request was served 200 by the same account: nothing
  rested.

Not verified: the Daybreak model itself (not listed for this account),
so no 200 with daybreak_blue; OpenCode's own wire; the Messages route
against the real backend (fake backend only).
2026-10-15 16:51:31 +08:00
yetone 9d97fd0733 plugin: magpie's web search is the Search plugin on the gateway's tool point (P3)
The third P3 point after observer/rotation, groups and middleware: the
tool point (internal/gwtool). A plugin serves a tool by name while it is
on; the process serving the gateway gates on it (Gate in ListenAndServe),
and a process not serving the gateway (CLI, TUI) has every tool, as
before.

plugins/search serves gwtool.WebSearch. Off, magpie offers and answers no
search of its own: the stand-in web_search isn't given to a model that
can't search, the search MCP server and Codex's search in ChatGPT's place
say "turn the Web search plugin on", and neither a search API nor a Kimi
Code plan's own search service is asked. A vendor that searches by itself
is still sent its own web_search. It is Essential and stays on while a
search API is set up or a searcher is picked (InUse); a providers.json or
settings.json that can't be read counts as unknown, so it stays on.

Settings → Models' Web search section stays visible with the plugin off:
the plugin can only be off when nothing is set up there, and adding a
search API there is what turns it back on (as Privacy does for redact).

Run at this head (rebased on origin/main 35aa50cfb):
- go test -count=1 ./... (full suite): 63 packages ok, none failed
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestSearchOnAndOff, TestServingGatesTools, plugins/search tests

Broken by hand, each test went red: canSearch ungated, searchesOwn
ungated, webSearch ungated, no Gate in ListenAndServe, Apply serving
nothing, InUse ignoring the searcher, SearchAPIsSet swallowing the read
error, the gate never released.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3592, fake vendor and fake Tavily on 3591):
- on with a Tavily API set: a plain chat model was sent Read + web_search;
  MCP /mcp/magpie/web-search returned the fake's result
- `plugin builtin off search` with the API set: refused, "in use"
- API removed, turned off: the plain model got Read only; a native
  Anthropic provider still got its web_search; MCP answered isError with
  "turn the Web search plugin on"
- API added back: the plugin read "on, in use" and web_search was offered
  again
Not tried: a real search vendor or a real Kimi plan (fakes only).
2026-10-15 16:45:51 +08:00
yetone 35aa50cfb3 zhipu: a GLM Coding Plan key refused 200 in the platform's envelope reads as refused, in the test, the gateway and the quota card (@xanahopper on X)
On a Coding Plan with a key Zhipu refuses, Test showed OpenAI 401 and
Anthropic 401 but Responses (https://open.bigmodel.cn/api/v1) a green
check, and the 5h/weekly windows showed only "Allowance unavailable".

Cause: /api/v1 (Zhipu's real Responses endpoint, docs.bigmodel.cn
coding-plan/tool/codex) and /api/monitor answer a refused key HTTP 200
with {"code":1000,"msg":"身份验证失败。","success":false}. probe (endpoint
Test, model tests, Detect) took any 2xx as ok, and the gateway handed
the 200 to Codex as a reply, so no failover and no rest.

- provider.ZhipuEnveloped: a 2xx JSON, non-stream, unencoded reply from
  open.bigmodel.cn or api.z.ai whose body is the envelope with
  success:false becomes {"error":{...}} under the status Zhipu's code
  table gives (1000-1005 401, 1113/13xx 429, 1220 403, 121x/1261/1301
  400, else 502). Anything else passes through unchanged (64KB cap,
  body restored). Applied in probe and in the gateway's forwardOnce.
- planquota: a refused key (envelope 1000-1005 or HTTP 401 from a
  Zhipu/Z.ai host) says "Zhipu didn't take this key (...): it has
  expired, was deleted, or is mistyped; paste a current one from <keys
  page>", and skips the team retry. The card shows it in en, zh, zh-TW,
  ja, de.
- docs: providers-accounts and gateway-routing rows.

Run at this head (before rebase, base 95e7c6bcc):
- go test -timeout 20m ./internal/gateway ./internal/provider: ok
  (343s, 93s). New: TestZhipuResponsesRefusalNotGreen,
  TestZhipuEnveloped, TestZhipuRefusedKeyCard,
  TestZhipuResponsesRefusalIsRefusal (zhipu and zai presets).
- Full go test ./...: every package ok except internal/gateway, which
  hit the default 10m timeout while the full GUI suite and another
  session's GUI tests ran beside it; alone with -timeout 20m it passed.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet on provider and
  gateway clean.
- GUI: glm-quota-error (new) and opencode-go-quota-error 20/20 in
  chromium and webkit, five languages. The full GUI suite ran once (under
  load) and exited 1; each of its 16 red files was rerun alone here and
  on an origin/main 03eb0633a copy of internal/gui: 10 pass on both;
  quota-count-wrap (1), quota-name-translated (1),
  refusal-retries-setting (2), usage-agents-hide (22), usage-fold (2)
  fail the same counts on both; routing-held-member fails 1 here, 2 on
  main. None touches quotaError's GLM line.

Broken by hand: ZhipuEnveloped returning res unchanged, and
zhipuEnvelope returning ok=false, turned the provider tests red;
reverting the gateway line turned TestZhipuResponsesRefusalIsRefusal
red; breaking the GLM regex in app.js turned glm-quota-error 0/5 in
chromium. All restored.

Not tried: no real Zhipu or Z.ai key, valid or expired. The refusal
bytes are from a curl of /api/v1 with a bad key; the reporter's
"令牌已过期或验证不正确" code is unknown (assumed 1000-1005 or HTTP 401,
both handled). A valid key's quota read with a real plan was not run.
2026-10-15 15:55:24 +08:00
yetone 03eb0633af library: an agent not installed is on no row but those of what it still has (@jiahao_jayden on X)
Library → Skills showed a chip for WorkBuddy on every row though it
wasn't installed ("一排有点密恐了"). WorkBuddy has no CLI and no detect
rule, so it counted as installed whenever ~/.workbuddy (or its
models.json) existed; that folder stays after the app is trashed, and
magpie itself writes models.json, mcp.json and skills/ there.

- agent: on a Mac WorkBuddy and WorkBuddy AI are detected by their apps,
  each by its own bundle id (com.tencent.workbuddy.mac,
  com.workbuddy.workbuddy-ai) in /Applications or ~/Applications
  (macBundle). Off a Mac the folder still counts, as before.
- library: an agent that isn't a target but still has skills, servers or
  hooks magpie gave it is held (Target.Gone). A sync takes edits from its
  copies and then only takes things out of it; Read lists it with
  gone: true while it has any, and not once it has none.
- GUI: a gone agent's chip is only on the rows of what it has, lit; a
  click takes it away. All, the How-per-agent sheet and the pickers leave
  it out; By agent lists it as "Not installed here" with Turn all on off.
  No layout change. New strings in zh, zh-TW, ja, de.

Run at this tree (macOS, sandbox HOME, Go caches pinned):
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: ok.
- go test -tags nogui -timeout 30m ./...: all ok (59 packages);
  internal/gui rerun after the last string rename: ok.
- GUI: the 74 test files that open the Library, chromium and webkit:
  563/563 each. library-gone-agents.test.cjs (new; 1100px and 390px, en,
  zh, zh-TW, ja, de): 11/11 in both; i18n-keys.test.cjs: 3/3.

Broken by hand, each went red, then restored and green:
- old client.js: library-gone-agents fails "a chip for an agent not
  installed on a row it has nothing on".
- workbuddyHere's Mac branch falling back to the folder:
  TestWorkBuddyOnMacIsItsApp "no app, only the folders: WorkBuddy true,
  WorkBuddy AI true".
- syncSkills' Gone guard off: TestGoneAgentListedToTakeOut "a sync gave
  the gone hermes a skill again".
- held() returning nil: "hermes, holding a skill and a server, isn't
  listed as gone".
- the gone sync steps skipped: "hermes, holding nothing, is still listed".

Not verified: the reporter's machine; WorkBuddy detection on Windows and
Linux (unchanged, still by folder); other agents detected by folder alone
(zcode, alma, grok-app, air, hanako, morph, grok) are unchanged. WorkBuddy
AI.app is installed on the owner's Mac without ~/.workbuddy-ai, so it now
shows as detected there.
2026-10-15 14:52:51 +08:00
yetone 01c41e8ba2 library: a skill probe's download goes when it is probed again or 15 minutes are up, and one a magpie that quit left behind goes at the next probe (#2321)
ProbeSkills kept each GitHub probe's download, a magpie-skill-* folder in
the temp dir, cached for 15 minutes. An expired one went only at the
*next* probe, so a magpie that quit, or a test that ended, left it there
for good. One go test ./internal/library left 22. This machine's temp dir
had 5477, and with old test homes they filled the disk under a full run
(gateway tests failed "no space left on device").

- keepProbe: each cached probe has a timer that removes its folder when
  probeLife is up. A probe of the same input replaces it and removes the
  old folder at once, outside the lock.
- sweepStaleDownloads, at each probe: a magpie-skill-* in the temp dir over
  an hour old goes. No live one is that old, since a probe is kept 15
  minutes and a fetch takes seconds.
- internal/library's TestMain gives the tests a temp dir of their own
  (TMPDIR, and TMP/TEMP for Windows), ends the cached probes, and fails a
  run that leaves a skill download there. A test binary started again by a
  test keeps its parent's temp dir.

Run (on origin/main 8b89b2e36): go test -count=1 -timeout 60m ./... all ok;
gofmt clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.

Broken by hand, each went red:
- a replaced probe's folder kept (TestProbeDownloadEndsWithIt)
- no removal at expiry (TestProbeDownloadEndsWithIt)
- the sweep ignores age, or the prefix, or doesn't run
  (TestStaleDownloadsSwept)
- TestMain doesn't end the probes: "the tests left 16 skill downloads"

Not tried: the Windows box, though TMP/TEMP are set for it.
2026-10-15 14:19:00 +08:00
yetone 4ac4d9ba99 plugins: the gateway's middleware point; JS middleware and privacy masking are built-in plugins, masking fails closed (P3)
P3's third point (docs/subsystems/plugin-runtime.md). internal/gwmw has two
places, each with its own failure policy:

- Agent: a middleware on an agent's request in its own API and on its reply.
  serveAgent runs each registered one. The JS gateway middleware is the one
  there (middleware.Chain), registered by the new built-in plugin
  `middleware`. Its place, API, limits and fail-open are unchanged. InUse is
  middleware.On(). Off, no middleware runs.
- Masker: what goes to a vendor, masked, and the values back in what comes
  back. The new built-in plugin `redact` serves masking.Masker (in
  internal/masking, since settings imports redact). InUse is masking.Wanted.
  It fails closed: masking asked for with no masker serving, or a masker that
  panics, is a 503 "nothing was sent" at every call site that masked before
  (serve, count_tokens, embeddings and audio, transcriptions, images, video,
  search stand-ins and their queries, the Codex backend).

With no masker, or with no agent middleware while plugins.json has one on,
the gateway asks pluginrt.Refresh, at most once a second. A setting or
middleware added a moment ago serves the request that needs it.
pluginrt.KeepFresh also watches plugins.json now.

Run (on origin/main 95e7c6bcc + this change, with the next commit's two
test waits):
- go test -count=1 -timeout 60m ./...: all ok (gateway 682s, agent 617s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, Chromium and WebKit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw. builtins reaches the Usage row by wheel now, since the
  page puts back a scroll that isn't the reader's.

Broken by hand, each went red:
- masking fails open with no masker (TestMaskingOnAndOff)
- a panic isn't recovered (TestSafelyTurnsAPanicIntoAnError, TestMaskingOnAndOff)
- no refresh asked (TestServedRefreshesOnce, TestMaskingOnAndOff)
- the plugins don't register (plugins/redact, plugins/middleware
  TestOnServesOffDoesNot)
- InUse misses redactWords (plugins/redact TestInUse)
- maskedQuery fails open (TestMaskedQueryFailsClosed)
- middleware runs with the plugin off (TestMiddlewareOnAndOff/off)
- no refresh on a middleware miss (TestMiddlewareOnAndOff), want ignored
  (TestAgentsWantedRefreshesWhenWanted)

Real use, sandbox HOME, magpie serve and a fake vendor that echoes:
- redact off with nothing asked: sent as written
- redactWords written, request at once: the vendor got {{TERM_…}} and the
  agent got the word back; `plugin builtin off redact` refused while in use
- `magpie plugin add ./alias.middleware.js`: the next request is rewritten
  (200, was 404). Removed: 404 again.
  The first build left that request at 404 until a restart, since plugins.json
  wasn't watched. That's fixed here.

Not tried: a real vendor account; the Windows box.
2026-10-15 13:40:20 +08:00
yetone b1d02fa612 groups: the user's own routing groups are the groups plugin's, served only while it is on (P3 router strategy)
The groups plugin now owns the user's own routing groups at the router
strategy point. The groups magpie finds (auto-<model>, one model several
providers serve) stay core, as Smart does: a new install has groups off
under Essentials, and taking those would silently drop cross-provider
failover. planGroup and the walk over a group's members stay core too.

- provider.GateGroups / ServeGroups (group_serve.go): the gateway holds
  the gate while it serves; the plugin holds ServeGroups while on. Gated
  with none served, groupsIn drops every group not Auto, so FindGroup,
  GroupFor, the catalog and /v1/models go without them. The CLI and TUI
  are never gated. Nothing derived from groups is cached past a call, so
  a flip is seen by the next lookup.
- Gated and off, a lookup that finds a user group asks the gate's refresh
  (pluginrt.Refresh in the gateway) at most once a second, never
  re-entrantly, then looks again. Without this, `magpie group add` was
  404 for up to 2s until KeepFresh turned the plugin on (seen in the
  sandbox).
- plugins/groups and plugins/routing: InUse is provider.NamedGroups, the
  file's non-Auto, non-hidden groups read past the gate; an unreadable
  providers.json is an error, so the plugin stays on.

Run before rebasing onto 707fbb249:
- go test -count=1 -timeout 40m ./... : all ok (59 packages)
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean
- sandbox, real nogui binary + `magpie serve` + two fake upstreams:
  before add: group/auto-m listed, group/mine 404; right after
  `magpie group add Mine models=pa/x,pb/m`: group/mine listed and 200;
  after `group rm`: 404, auto-m still served.

After the rebase onto 707fbb249: vets (3 OSes) and go test of
internal/provider, internal/gateway, internal/pluginrt and plugins/...
all ok.

Broken by hand, each went red:
- groupsIn filter removed: TestOwnGroupsWaitOnThePlugin,
  TestGroupsOnAndOff/off
- NamedGroups swallowing the read error: TestNamedGroupsUnreadable,
  plugins/groups TestInUse
- Apply not serving: TestOnServesOffDoesNot
- refresh not called / not throttled / asked for Auto groups too:
  TestOwnGroupRefreshesTheGate
2026-10-15 10:42:23 +08:00
yetone 707fbb249d backup: a settings.json that can't be read stops a backup, an export and a sync, not carried as the defaults to every other computer (#2269, JasonBuildAI)
Collect read settings with settings.Load, which stands the defaults in
for a file that is there but can't be read, or doesn't parse with no
good .bak. A sync then pushed those defaults as "changed here", and
every other computer brought them in over its own theme, language,
text size, allow list and per-model settings; an export carried them
too. Collect now reads through settings.LoadChecked and stops with its
error, as it does for providers.json (9c54a560). The sync ends before
anything is sealed or pushed, and its status shows the error; the CLI
and the GUI's export show it. A missing or empty file is unchanged.

Sibling: library.Collect read any failed stat of library.json as "no
library"; only a missing file is that now, any other error stops the
backup. plugins.json (provider.Carried -> plugin.list) still reads as
no plugins when unreadable; bringing that in never removes a plugin,
so it is filed separately rather than changed here.

What was run:
- TestCollectStopsOnUnreadableSettings (new, internal/backup) and
  TestSyncStopsOnUnreadableSettings (new, internal/davsync: two
  computers on a fake WebDAV, a's file cut short with no .bak; a's sync
  errs with no PUT, the status says so, the server keeps a's settings,
  b keeps its own). Both FAIL on the old backup.go ("Collect read a
  settings.json that can't be read as settings: <nil> &{Theme:system
  ..." and "a synced a broken settings.json") and PASS on the new, on
  macOS and on the Windows box (cross-compiled binaries, sandbox home).
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  clean.
- go test -p 4 -timeout 40m ./... on macOS (origin/main 69d7ee33a plus
  these three commits, load average 15-27 from other suites): every
  package ok but internal/gateway, where TestMaxRPMTooLongIs429With
  RetryAfter got 200 (the window had passed under load; #1791, open,
  gateway untouched here). -run TestMaxRPM -count=3 passes on this
  tree.
- After rebasing on origin/main 226222118 (which touched
  internal/library): go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows clean; go test ./internal/update ./internal/pluginrt
  ./internal/backup ./internal/davsync ./internal/library
  ./internal/settings ok (library under -timeout 40m, 550 s at load
  average ~60).
Not tried: a settings.json held open by another Windows program, or a
real WebDAV/S3/GitHub server.
2026-10-15 10:10:18 +08:00
yetone c7830731ca sessions: a session nothing was said in, which the Sessions page lists, opens and exports instead of "no such session" (#2273)
ListAgent lists a session assemble calls empty (no title, nothing
counted), so it can be cleared away, but Find searched only List(0) and
Get, and both drop it. The row's conversation, Markdown and Terminal
routes all go through Find, so they answered "no such session" for a row
the page itself shows. A real case is Codex's Image Session Helper: a
rollout with session_meta, settings, task_started and turn_aborted only.

Find now falls back to get(), which reports a session's files were found
even when assemble calls it empty, and fills it in the way ListAgent does
(listed(): Resume, Carry, Transcript), so Find finds every session
ListAgent lists. Get and List are unchanged: an empty session still
isn't in the main list and Get still says ok=false for it.

Run:
- TestFindEmptySession (internal/sessions) and TestEmptySessionOpens
  (internal/gui), on a fixture made from the real aborted helper rollout
  (paths and ids redacted). Both fail with Find's fallback broken by
  hand (only taking ok sessions), and pass with it.
- gofmt -l clean; go vet for darwin, linux (nogui) and windows.
- go test -p 4 -timeout 40m ./... with pipefail, sandbox HOME, at
  2b0037f41 plus this change, with four other full suites running on the
  machine: every package green but internal/gateway, whose
  TestOTelFastRequestTranscriptDiscovery/true failed ("request must still
  have a cached discovery miss"). That is #1811, its 2s discovery cache
  window under load; this change doesn't reach that path (TraceSessionIndex
  reads headers itself, never Find or ListAgent). Run alone with -count=10
  with its sibling it passes 10/10. Noted on #1811.
- Real use: a dev-tagged build in a sandbox HOME holding a copy of the
  real empty rollout, sessions feature on. /api/sessions/manage lists it,
  /api/sessions/transcript returns 200 {"parts":[]}, /api/sessions/markdown
  returns 200 with the .md attachment.

Not run: real use on Windows or Linux; the GUI suite (no GUI asset
changes). Whether an aborted helper rollout should count as something
said, and so show in the main list, is left as it was.
2026-10-15 09:40:51 +08:00
yetoneandggbdpq 58651568b3 agent, sessions, provider: a state file that doesn't parse is kept aside, not written over as empty (#2263, ggbdpq)
applied.json, wsl.json and sessions-wsl.json were read as empty when they
didn't parse, and the next save wrote that emptiness over them. What
magpie had applied to each agent, the WSL distros and the WSL session
listing were lost with no copy. stash.json already kept a bad file aside
as .bad-<time>. Each of these now does the same through one helper,
lastgood.KeepUnparsed, instead of a copy per file:
- It does nothing when the file is missing or empty.
- When the file doesn't unmarshal into the reader's own type
  (lastgood.Into[T]), it copies the file aside (KeepBad).
- It stops the write when the copy can't be kept.

This also fixes the issue's claim about stash.json. Stash judged a file
with json.Valid, so `[]`, which a map reader takes as empty, was written
over unkept. Its failed copy was only logged, and the write went ahead
anyway. Both are fixed (TestUnreadStashArrayKeptAside), and
gateway-hidden.json uses the same helper.

Siblings found by going through every single-file JSON reader that takes
a bad file as empty and then writes it whole:
- stepfun-auth
- login-returns
- quota-history
- balance-history
- credits-daily
- Claude Desktop tiers
- plugin updates
- usage's computer id
- davsync's sync state

Each now keeps a bad copy. Caches that are rebuilt from the vendor are
left alone; docs/subsystems/providers-accounts.md lists them.

Run:
- gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui,
  GOOS=windows): clean.
- go test -tags nogui -p 4 -timeout 40m ./... with the other three
  commits of this push: see the last one's body.

Broken by hand: on the code before this, these fail:
- the issue's applied_keep_test.go and wsl_keep_test.go
- TestUnreadStashArrayKeptAside
- TestUnreadStateKeptAside (10 subtests)
- the gateway, usage, davsync and plugin _keep tests
TestKeepUnparsed and TestKeepUnparsedFailsWhenItCantBeKept cover the
helper.

I dropped a test, "not written when it can't be kept", for stash. It passed
on the old code too, because a read-only folder also stops the atomic
write.

Not tried: a real WSL distro.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 09:36:26 +08:00
yetoneandggbdpq 919c8b934a gateway: a second answer to one call is dropped on the way to Gemini and Responses (#2262, ggbdpq)
A client that answers one tool call twice sent Google a call turn with
more functionResponses than functionCalls, which Google refuses with 400,
along with every later turn of the conversation. The Chat and Messages
builds already keep the first answer (pairToolMessages, pairToolBlocks).
The Gemini build (buildCodeAssistSent: Google sign-in, Vertex, a custom
Gemini provider) and the Responses build (buildResponses) now leave the
second one out before they build, with the images it carried
(dropSecondAnswers). A call made again under the same id takes an answer
of its own, and the request itself is left as it was, since a fallback
builds from it again.

This differs from the issue's patch. It dedups across the whole history in
pairFunctionTurns, keyed by id, or by name when there is no id. Keying by
name drops a real answer to a second call of the same function. Keying by
id ignores a call made again under that id. The patch also left the
duplicate's images in the turn and didn't cover Responses. Also fixed:
parseGemini matched a functionResponse with no id to the latest call of
that name, so two calls of one function were both answered as the second.
Each now goes to the first call of that name still unanswered.
pairToolItems (relayed Codex bodies) already keeps one answer per call and
is unchanged.

Run:
- gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui,
  GOOS=windows): clean.
- go test -tags nogui -p 4 -timeout 40m ./... with the other three
  commits of this push: see the last one's body.

Broken by hand: TestGeminiDropsASecondAnswer,
TestSecondAnswerDroppedWithItsImages and
TestGeminiClientUnnamedCallsAnsweredInOrder fail on the code before this.

Not tried: against Google's or a Responses upstream's real API.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 09:36:25 +08:00
yetone 226222118a agent: on Windows Claude Code and Codex are never taken for uninstalled by their folder, so neither shows "CLI not found" with its settings hidden (#1482, edussss)
edussss (Windows 11) on 10-15: "昨天早上的版本还能找到,今天早上更新后又找不到了".
Their screenshot shows both Claude Code and Codex marked "CLI not found",
with no model or effort pickers. v0.1.1231 listed both.

Cause: d0fcb8bcd (#2177, in v0.1.1238). It made cliHeld declare a shared
folder (~/.claude, ~/.codex, ~/.cline) a leftover when neither the CLI nor
a known reader is here. The known readers are editor extensions under
~/.<editor>/extensions, Claude.app, Claude Desktop, JetBrains and Zed. Before
that commit a shared folder was never gone. The list was checked on a Mac
only. On Windows, other programs read these folders too: a Store app, an
editor run portable or with --extensions-dir, or a CLI on a PATH that only
a shell profile sets (fnm). The Agents page, the TUI, `magpie ls`, Install
another agent and the Library targets (all through CLIMissing) treated both
of the reporter's agents as uninstalled.

Fix: on Windows, cliHeld says "can't tell" for a shared folder whose CLI
isn't found. A shared folder is then never gone, as before v0.1.1238, and
as OpenCode and Goose already are off a Mac. A found CLI still holds it.
Agents whose folder only their CLI keeps (dsh, Hermes) are still gone on
Windows. The Windows-only branches in that path became unreachable and are
dropped: desktopdir.Installed in the claude case, and the Windows dirs of
jetBrainsHere and zedAgentsHere. goneOS lets a test judge for Windows on
any host. docs/subsystems/agent-wiring.md says so.

What was run:
- Windows box (Windows 11 x64), sandbox USERPROFILE/APPDATA/LOCALAPPDATA
  holding only ~\.claude\settings.json and ~\.codex\config.toml, PATH
  C:\Windows\system32 (the registry PATH has the box's real
  ~\.local\bin\claude.exe; there is no codex on the box):
  - `magpie ls` at v0.1.1231 lists Codex "gpt-5 · effort".
  - At origin/main 69d7ee33a it lists "Codex  CLI not found". That is the
    regression.
  - With this fix it lists "Codex gpt-5 · effort" again.
  - At main, a fake openai.chatgpt extension in ~\.vscode or ~\.cursor
    also kept Codex listed. So the extension check works on Windows, and
    the reporter's reader is something cliHeld doesn't list.
- agent.test.exe -test.run TestCLIMissing on the Windows box: all four
  pass (TestCLIMissing, Hermes, SharedFolders, SharedFoldersWindows).
- Broken by hand: with the Windows branch disabled,
  TestCLIMissingSharedFoldersWindows goes red for claude, codex and cline.
  Each is taken for gone and offered again as missing.
- gofmt -l clean. go vet -tags nogui passes for GOOS darwin, linux and
  windows.
- set -o pipefail; go test -p 4 -timeout 40m ./... on macOS at base
  69d7ee33a plus this change: all 55 packages ok, exit 0 (internal/agent,
  cli, gui, library and tui among them).

Not tried: the reporter's own setup. Their screenshot doesn't say what
reads their folders. The reply on #1482 asks for `where.exe claude`, the
install method and the magpie version.
2026-10-15 09:29:57 +08:00
yetone af9bd6c3e2 gateway, routes, plugins: the routings besides Smart are the rotation plugin's, on the gateway's router strategy point (P3)
The second P3 extension point (docs/subsystems/plugin-runtime.md). A
router strategy orders one pool of routes: a provider's accounts or keys,
or the heads of a group's members. The gateway still lists the pool and
keeps rests, affinity, rules, pins and failover; a strategy only orders.

- internal/routes: Seat, Strategy{Order, Exact, ByUse}, Register (stacks,
  the last serves), Find, Served, and Apply, which fails open: a strategy
  that panics or answers what isn't a permutation leaves the pool in its
  listed order, logged. Smart is the core's; Ordered, Rotate, LeastUsed,
  Pace and Weighted are routes.Builtin, moved out of the gateway with the
  rotate turns and the smooth weighted round (Round, MoveRound, Forget).
- plugins/rotation (Essential): registers routes.Builtin. InUse counts the
  providers and groups providers.json routes by one of them
  (provider.Routings), an unreadable file is an error, so it stays on. The
  gateway's KeepFresh watches providers.json too.
- Off, a routing no strategy serves is its listed order, and routingOf
  reads it as "order" wherever the core asks (a turn's mark, sinks, a
  rotate group's sessions, a group's heads, weightedKept).
- GUI: the routing pickers (provider editor, Routing page pools and group
  editor) mark the five as data-feature="rotation" (routingSegs), so off
  they offer Smart alone. i18n zh, zh-TW, ja, de.
- Docs: plugin-runtime.md router strategy section, gateway-routing.md
  (also drops a duplicated sentence about a lone key), reference.md.

Run in the worktree at this change (on origin/main fbfb76149):
- go test -count=1 ./... : 57 packages ok (gateway 587s)
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows
- GUI: full suite, chromium and webkit, every language: 9805 tests, 29
  red in 6 files. Each red alone the same way on origin/main bc470c6b6
  (just fetched): quota-count-wrap, quota-name-translated (#2228),
  refusal-retries-setting (#2258), routing-held-member (#2252), usage-fold
  (#2163), usage-agents-hide (#2276, from cf455ebd5). routing-save, builtins and
  rate-limited-sink pass in both engines.
- internal/gateway TestMain registers the strategies, so every routing test
  is the parity run with the plugin on; TestRotationOnAndOff turns it off
  (three Rotate sessions start k1,k2,k3 on, k1,k1,k1 off, no turn mark;
  Smart still served).

Rebased on origin/main 2b0037f41: go test ./... again, 56 packages ok at the
default timeout; internal/agent and internal/gateway passed with
-timeout 40m (1093s, 1039s: the machine at load ~17 with other sessions'
suites; the 10m panics stood in TestCodexAPIDisconnectStays and
TestCodexHeardWithinItsIdleTimeout, 1-2s in, no stack waiting on them).
Vets and gofmt clean again; routing-save, builtins, rate-limited-sink,
i18n-keys and the GUI files upstream changed pass.

Broken by hand, each test went red then restored:
- Apply's permutation check off: TestApplyFailsOpen
- Register's remove a no-op: TestRegisterStacks
- the plugin's Apply registers nothing: TestOnServesOffDoesNot
- InUse swallows providers.json's error: TestInUse
- routingOf passes an unserved routing through: TestRotationOnAndOff
- routingSegs not marking data-feature: routing-save.test.cjs "Smart alone"
2026-10-15 09:09:15 +08:00
yetone 2b0037f41d sessions: a Claude Code, Qoder or Cowork project folder, a session's folder or a Hermes profile behind a junction is read, not skipped (#2268, JasonBuildAI)
On Windows os.ReadDir lists a junction as ModeIrregular, neither IsDir
nor ModeSymlink, so a reader that goes into only IsDir() entries, or
IsDir() and ModeSymlink ones, walked past a folder kept on another drive
with a junction left in its place. ccFiles (Claude Code's own store,
Qoder's, Qoder CN's and Cowork's) skipped such a project folder whole, a
session's own folder (its subagents) and a workflow run's; HermesDirs
skipped such a profile. Sessions and Usage lost all of them, silently.
#2233/#2250 fixed walk roots (walkLinked); this is the entry check one
level in.

dirent.IsFolder is the one check now: an entry is a folder to read into
when it is one, or when it is a symlink or irregular entry that os.Stat
follows to a folder. A link to a file, a broken link and other irregular
entries are none. It follows only the entry asked about; none of its
callers recurses through one, so no visited set is needed.

Used at every reader of an agent's folder that picks entries this way:
- sessions: ccFiles' project, session-folder and workflow-run checks,
  HermesDirs' profile check, agyCallFiles' conversation check (IsDir only
  before, so even a symlink was skipped);
- agent: hermesProfiles and ompProfiles (IsDir only), so a linked profile
  still gets magpie's provider and its own row;
- library: desktopSkillRoots' org and account folders (IsDir only).
Left as they are, on purpose: WalkDir copies, hashes and deletes in
library and sessions/manage.go (they must not follow links), the
relocate code (it tells a link from a folder on purpose), library's
linkEntry (asks "is this a link", not "is this a folder"), magpie's own
folders (calls cache, gateway logs, OthersDir, backups, Bun, Devin
homes), and install/version detection (claudecode versions, VS Code
extensions, Desktop's folder name, Hanako's agents).

The issue's patch had sessions' own copy of library's linkEntry without
a Stat; this is a shared package and Stat-checked, so an irregular entry
that isn't a folder (a dedup or cloud placeholder file) isn't read as one.
docs/subsystems/gateway-sessions.md says how the readers treat links.

Run:
- New tests make real links, a junction (mklink /J) on Windows and a
  symlink elsewhere: TestIsFolder; TestClaudeProjectFolderBehindALink,
  TestClaudeSessionFolderBehindALink and TestHermesProfileBehindALink (the
  issue's), TestClaudeWorkflowRunBehindALink,
  TestAgyConversationBehindALink; agent's TestHermesProfileBehindALink and
  TestOmpProfileBehindALink; library's
  TestClaudeDesktopSkillRootsBehindALink.
- Broken by hand on macOS (IsFolder = e.IsDir()): all nine fail. Broken
  as before on the Windows box (IsDir() || ModeSymlink, no Stat):
  TestIsFolder and all eight reader tests fail there (e.g. "Claude
  session files behind a link: [], want [...]", "Hermes sessions behind
  a link: 1, want 2", "agy calls behind a link: 3, want 5"); with the
  fix all pass. Windows test binaries cross-built with go1.26.8
  (windows/amd64, nogui) and run on the box with a fresh sandbox
  USERPROFILE/HOME/APPDATA/LOCALAPPDATA/TEMP per run.
- Whole packages on the Windows box: dirent and sessions pass. usage,
  agent and library each have reds that fail the same with binaries
  built from origin/main 69d7ee33a: usage's
  TestDesktopSessionAccountMetadata (#1356/#1827), agent's
  TestFolderVarsAreListed (reads ..\gateway source the copied layout
  lacks), library's TestAgentsSkillsFolders,
  TestHooksCodexTrustMovesWithTheGroups and TestTargetsLeaveGoneAgentsOut
  (filed as #2275).
- gofmt -l: nothing. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./... and -tags nogui: clean.
- macOS: set -o pipefail; go test -p 4 -timeout 40m ./... on bc470c6b6
  plus this change: 56 packages ok, none failed. After rebasing onto
  origin/main 3a0b61275 (#2261's subagents, which touch sessions.go and
  the same doc): go test ./internal/sessions/ ./internal/dirent/ again.
2026-10-15 08:33:54 +08:00
yetone 3a0b61275f gui: the Sessions page nests subagents under their session and opens each one's conversation; Codex threads nest under their parent_session (#2261, infinitr0us)
Only main sessions sit at the top of the Sessions page now.

- A session with subagents shows an "N subagents" fold under its row. It starts folded.
  - Unfolding neither opens the session nor moves the page.
  - The rows are indented by the depth of the subagent that started them.
  - Clicking a row opens its conversation in place, via /api/sessions/transcript?sub=.
- Codex threads with a parent_session nest under that session, to any depth.
  - The parent chain is guarded against loops and capped at a depth of 8.
  - A thread whose parent isn't listed stays at the top.
  - A folder's count and its select-all include the nested threads.
  - Searching opens the folds that hold matches. Opening a nested session from elsewhere opens its ancestors' folds.
- New strings ("{n} subagent", "{n} subagents") in zh, en, zh-TW, ja and de.
- No native select and no left-border accent. The nested list is a bordered card.
- docs/subsystems/gateway-sessions.md describes the subagents field, the sub= route and the page.

What was run, at this head before the rebase (5618ade1e):

- internal/gui/tests/sessions-subagents.test.cjs (new): 40/40 pass in Chromium and WebKit, at widths 1100 and 420, in all 5 languages.
  - It checks the fold, the indentation and order, that the transcript is called with sub= and read once, and Codex nesting with a loop and a missing parent.
  - Its tidy check covers: no select, no left border, nothing wider than the page.
- Related GUI tests (sessions*, sess*, session*, i18n, routing-session, account-mask, click-scroll): 451/451 pass.
- Broken by hand, each restored afterwards:
  - Without nest(), the Codex test fails.
  - Without the fold, both tests fail.
  - Without &sub=, the Claude test fails.
- usage-agents-hide and usage-fold fail the same way on origin/main bc470c6b6, with or without this change. They are filed as #2211 and #2163.
- The full suite, go test -p 4 -timeout 40m ./... under a temp HOME at 5618ade1e with this change: green (exit 0).
- gofmt -l is clean. go vet passes for darwin, linux (-tags nogui) and windows.
- Real use: a sandbox magpie (temp HOME, ports 3486/3487) against read-only copies of real sessions.
  - Claude Code: the 5-subagent fold, and a real nested subagent indented one step whose conversation opened.
  - Codex: a real exec rollout pair, with the child's session_meta source rewritten to thread_spawn of the parent. Only the parent is at the top, and the child's details and conversation open in place.
  - Found on the way, and the same on main: a Codex Image Session Helper rollout is listed but can't be opened ("no such session"). Filed as #2273.

Rebased onto 69d7ee33a, whose new commits touch none of these files. Rerun at the rebased head:

- go test ./internal/sessions ./internal/gui: pass.
- sessions-subagents: 40/40.
- i18n-keys, sessions-* and claude-cloud-drift: 371/371.
- gofmt -l is clean.

Not tried:

- A real Codex rollout written as a subagent: none on this Mac, so the copied rollout above stands in.
- Real OpenCode children and real Kimi sessions.
- The GUI on Linux (WebKitGTK) and Windows.
2026-10-15 08:31:21 +08:00
yetone 69d7ee33ae agent: Codex with magpie as its provider (magpie API, or a ChatGPT account the app holds) no longer reads as joined beside its sign-in (#2267, isymbo)
isymbo's ChatGPT account ran out for the week, they set Codex's sign-in to
magpie API and picked DeepSeek, and the Codex app still showed "Codex 和
工作使用额度已用完" and sent nothing. The Agents row said "重开 Codex
后,/model 中既有它自己的模型,也有 magpie 的模型": the ChatGPT state
they had just left.

The config was right (model_provider = "magpie", magpie's catalog), but
the codex.joined mark from an earlier Join stayed, and Joined() read it
whenever openai_base_url was magpie's, which it also is with magpie as the
provider. Joined is now false while magpie is Codex's provider; the mark
itself stays, so Sync still puts Codex back beside the sign-in once the
account has room (codex.out), as before.

Why the app blocks: ChatGPT.app 26.1007.21159's two composer gates (FN in
app-primary and Cui/kui's hardBlocked in app-initial) both require the
app-server's getAuthStatus authMethod to be "chatgpt" and
rate_limit.allowed false. With magpie as the provider the app-server
reports no ChatGPT auth, so neither gate applies, but the app reads it
from the app-server it started with: it has to be quit and reopened. The
row now says "Reopen Codex, then pick any model in /model". Asked the
reporter to restart and, if it still blocks, for versions and config.

Test: TestCodexProviderIsNotJoined joins, picks a magpie model, sets
magpie API (provider, not joined, still wired), back to ChatGPT (joined),
held by the app (provider, not joined), room again (joined). Red with
Joined: joined ("magpie API: joined true").

Run, both commits together on 5618ade1e: gofmt -l clean; go vet ./...
for GOOS=darwin and windows clean, GOOS=linux clean on the 68 packages
that don't import Wails (the root, internal/cli and internal/gui need
cgo for Linux, which a Mac cross-vet can't do); set -o pipefail; go test
-p 4 -timeout 40m ./... green (rc 0).
2026-10-15 08:03:20 +08:00
yetone bc470c6b63 agent: Claude Code's own ANTHROPIC_MODEL comes back when magpie steps out
Wiring Claude Code in deletes env.ANTHROPIC_MODEL (writeTiers), because it
outranks a pick in /model. Unlike the tiers' models (#1050), the user's
own value was never stashed, so Disconnect or Claude Code's own model left
it gone for good. A Bedrock user like jw1dev keeps the Bedrock model id
there, so after the previous commit put the switch back, Claude Code would
come back on Bedrock without its model. ANTHROPIC_MODEL now joins
claudeOwnEnv: it is stashed raw beside the endpoint and token when first
routed from the user's own endpoint, put back by unroute, and forgotten
with the rest. A value an older magpie wrote, at its own key, is still not
kept (keyOurs), as before.

Run:
- gofmt -l: clean.
- go vet ./internal/agent: native, GOOS=linux -tags nogui, GOOS=windows:
  clean.
- go test -tags nogui ./internal/agent ./internal/gui: ok 4 times. One
  earlier run of the two together had internal/gui red, and only `tail -5`
  of it was kept, so the failing test's name was lost. It passed alone 3
  of 3 and with internal/agent 3 of 3. Nothing in internal/gui reads
  claudeOwnEnv.
- Targeted: ClaudeCloud, TestClaudeDisconnect, TestClaudePick, legacy,
  stand-in and T3 tests: ok.

Broken by hand: before the fix, TestClaudeDisconnect's new "own env
model" cases (with no settings model and beside one, [1m] kept; each by
Disconnect and by default) went red. The bedrock fixture of
TestClaudeCloudSwitchStepsAsideForMagpie now carries a Bedrock
ANTHROPIC_MODEL and compares the whole env after.

Not tried: WSL twins for real (the stash key goes through at.key as for
the tiers).
2026-10-15 07:41:30 +08:00
yetone 79fec406c6 agent, gui: a Claude Code provider switch (CLAUDE_CODE_USE_BEDROCK, …) steps aside while magpie is wired in and comes back after; one magpie can't take out is said (jw1dev on X)
jw1dev's ~/.claude/settings.json had CLAUDE_CODE_USE_BEDROCK=1. magpie wrote
ANTHROPIC_BASE_URL and its model ids beside it. Bedrock ignores the base URL,
so Claude Code went to AWS, Bedrock refused magpie's model, and magpie still
showed Claude Code as connected.

Claude Code 2.1.300's six switches (agentenv.ClaudeProviders: BEDROCK,
VERTEX, FOUNDRY, ANTHROPIC_AWS, ANTHROPIC_GOOGLE_CLOUD, MANTLE; on = 1, true,
yes or on, any case, trimmed):
- In a settings file magpie writes (user settings, WSL twins), a switch
  that is on is taken out on every route that writes the wiring: connect,
  model pick and Rewire/Reapply through writeTiers, and Sync. Its raw JSON
  value is stashed (claude.cloud.<var>, under the distro id for WSL). It is
  put back as written when magpie steps out (Disconnect, or the model set
  back to default), unless the user set it again since. AWS_*/GCP
  variables and a switch that is off stay.
- Where magpie doesn't write it (managed settings, ~/.claude.json's env,
  the login shell's env), Check names the variable, the cloud and the
  file. It reads them in Claude Code's own order: managed wins, then the
  user's settings, then ~/.claude.json, then the shell. Two notice
  templates, translated in zh, zh-TW, ja and de. The row's line and its
  Reconnect pill now show a drift detail through tNotice.
- proc.LoginEnv reads the switches but never sets them in magpie's env,
  and testenv unsets them.
- T3 Code: a switch is never carried onto magpie's instance. Its Check
  says when the user's ~/.claude settings have one on. That Check first
  checks the instance's ANTHROPIC_BASE_URL against the gateway (t3EnvOf),
  as every agent's Check must for TestDriftUnwiredEveryAgent,
  TestPortMovesEveryAgent and TestReverseProxyIsStillMagpie.
- Claude Desktop's Code tab runs with CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST,
  under which Claude Code ignores these switches in settings, so nothing
  changes there.

Run:
- gofmt -l: clean.
- go vet: native ./..., GOOS=linux -tags nogui, GOOS=windows: clean.
- go test -tags nogui ./...: every package ok except internal/agent, where
  t3code's first Check (cloud only) failed the three every-agent tests
  above. Fixed with the wiring check, then the whole internal/agent package
  was rerun: ok (368s).
- GUI, Chromium and WebKit, 102/102 each: new claude-cloud-drift (5
  languages, 1100 and 420px, file and shell notices), gui-de, gui-ja,
  gui-zh-tw, i18n-keys, agent-notice-lang, agent-proxied,
  agent-unreachable, cli-behind, menu-scroll, agent-connect,
  agent-disconnect.
- Sandbox HOME (scratchpad dir, live ~/.claude untouched):
  - Setup: real claude 2.1.300 with settings.json
    {CLAUDE_CODE_USE_BEDROCK:"1", AWS_REGION, AWS_PROFILE}, a magpie-cloud
    binary from this tree serving on 127.0.0.1:3487, a fake OpenAI
    upstream on 3486.
  - `magpie claude fake/fake-model` took the switch out and stashed "1".
  - `claude -p "say hi"` printed PONG-FROM-FAKE-UPSTREAM, and the fake
    logged POST /v1/chat/completions model=fake-model.
  - `magpie claude default` left settings.json byte-for-byte the same as
    before connect (cmp).
  - Control: the switch put back by hand beside the wiring (the reported
    state). Claude Code never reached magpie: the fake logged nothing.

Broken by hand, each went red:
- no dropClouds in writeTiers, then in Sync;
- putClouds returning at once, and putClouds writing over the user's own;
- no claudeCloud in Check;
- the T3 filter and the T3 Check;
- shellVars without ClaudeProviders;
- the tNotice calls taken out of the line and pill: claude-cloud-drift
  went 17 red.

Not tried:
- A project's .claude/settings.json(.local) isn't read, because magpie
  doesn't know where Claude Code runs.
- WSL and Windows were not run for real; tests only.
- Real Vertex, Foundry and AWS accounts.
- T3 Code and Claude Desktop with a switch, run for real.
- The drift shown in the real app window. The CLI has no drift output.
- The user's own ANTHROPIC_MODEL being lost across connect/disconnect is a
  separate gap, fixed in its own commit.
2026-10-15 07:41:30 +08:00
yetone 94bceea4d2 lessons: fold 10-14 04:16 to 10-15 07:30 (275 commits, v0.1.1229 to v0.1.1244)
New lessons: an origin exemption judges every Origin a browser can send
(#2242, #2256; seen 2x with the 10-10 rebinding case); a file another
process rewrites may be half-written; a pinned hash or new download
source is checked against the vendor and trusted as far as who can write
it; a fixed date in a test is checked against every clock the code reads
(3c4b4dc97 -> 21aa40285); a new field on a polled endpoint is costed at
the poll rate; a full run gives slow packages -timeout 45m; a community
layout PR is not merged on review alone (#1354).

Evidence added: five fixed-wait CI reds under the timing habit, unfiled
reds and a cancelled run that tested nothing, a second oversized squash
subject (seen 2x), "see the push" as a run record and plugins#56 under
the moved standards. ggbdpq's Watched row notes 94e3b3f52 and the
red-before/green-after fixes since.

Every cited sha was checked with git log; claims were checked against
their commit bodies. Ran: go test -tags nogui -count=1 -run
TestLoopGuardLeavesOrdinaryRepliesAlone ./internal/gateway (reads
LESSONS.md): ok. Docs only, no code.
2026-10-15 07:35:13 +08:00
yetone 5618ade1e6 sessions: each reply in a session's conversation names the model its own line in the agent's file names (#2253, cnlove7777777-art)
Usage -> Sessions' conversation said only "Assistant", so which model
wrote a reply couldn't be told, though the agents' files name it.

- sessions.Part gains model (omitempty), set on assistant parts only,
  from the part's own line: Claude Code's message.model (the model that
  answered; none for its "<synthetic>" lines), Codex's
  turn_context.model (the model the turn was sent to; a /model between
  turns moves the next turn), Pi's and omp's message.model, OpenCode's
  modelID and OpenCode 2's model.id.
- Kimi Code (its model is only on a usage.record written after the
  reply), Cursor (no model in the transcript) and gateway transcripts
  (GatewayTurn.Model is the model asked for, not the one that answered)
  name none. Nothing is guessed from nearby requests.
- The reader (sessions client.js) says it muted after the role, once a
  reply at its first part and again only where it changes inside the
  reply; the tooltip is "Model: <id>" (an existing string, translated).
  ledSaid takes the model as an argument, so the Usage page's
  per-request content, whose row already names its model, is unchanged.
  No layout change: one muted span in the existing header line,
  ellipsized at narrow widths.

Run:
- TestTranscriptModelClaude/Codex/Pi/OpenCodeV2/OpenCodeFiles: all five
  fail on the old content.go/transcript*.go, pass on the new.
- sessions-talk-model.test.cjs: 20/20 (chromium+webkit, en/zh/zh-TW/
  ja/de, 1100 and 420). Fails on the old app.js/client.js, and with the
  once-a-reply rule removed by hand (label every assistant part).
- sessions-talk, sessions-export, gateway-conversations,
  usage-ledger-content, usage-ledger-detail GUI tests: all pass.
- go test -tags nogui ./internal/sessions ./internal/gui
  ./internal/gateway: ok. gofmt -l clean; go vet -tags nogui darwin/
  linux/windows clean.

Full suite for this push (#2257, #2251, #2254, #2253) at 53677ed8d:
go test -tags nogui -p 4 -timeout 40m ./... with pipefail: every
package ok. (An earlier full run caught davsync's TestSyncLibrary and
profile's TestOldProfiles/TestProfileCarriesLibrary relying on a gone
CLI after #2254; their sandboxes now have the CLIs, in #2254's commit.)

Not tried: the real app against a live Codex rollout (fixtures follow
the lines the readers already parse for usage).
2026-10-15 06:07:43 +08:00
yetoneandggbdpq e413512d8e library: an agent whose CLI is gone (only its config folder left) is no Library write target, and nothing it already has is removed (#2254, ggbdpq)
After an agent is uninstalled, the Agents page shows "CLI not found"
(d0fcb8bc), but Library still offered it for skills, MCP servers, shared
instructions and rtk, and a sync wrote into a folder nothing reads.

- library.Targets() leaves out an agent whose CLI is missing
  (agent.CLIMissing: false for WSL, plugin and detect agents), so sync,
  the read view, market, instructions, skills and found servers all
  drop it at their one upstream.
- Takes() refuses a gone agent by name, so `library mcp add ...
  agents=hermes` says "Hermes Agent's CLI isn't installed here; nothing
  reads its MCP servers until it is installed again" instead of "every
  agent already has it".
- The guards that must still see a gone agent's files (projects'
  notGlobal for skills and MCP, instructions' own-file check) read
  everyTarget(), so a set kept in the agent's own file is still refused.
- rtk: a gone agent isn't offered rtk; one that still has the hook is
  listed so the hook can be taken out.
- Nothing a user wrote is removed: sync acts per target, so a gone
  agent's skills, servers and AGENTS.md stay as they are, and the client
  keeps agent ids it doesn't show.

Run:
- Sandbox HOME, real binaries: old wrote mcp_servers into a gone
  ~/.hermes/config.yaml; new refuses with the message above, exit 1.
- New tests TestTargetsLeaveGoneAgentsOut, TestGoneAgentKeepsWhatItHas,
  TestRTKLeavesGoneAgentsOut; each broken by hand (Targets check,
  Takes refusal, everyTarget in instructions, rtk gate) goes red.
- go test -tags nogui ./internal/library ./internal/tui ./internal/cli
  ./internal/gui: ok. Fixtures that relied on a gone CLI now place one
  (holdCLI, TestRTKHermesHome, TestRTKOffPath), and so do profile's
  and davsync's sandboxes, whose library syncs to claude and codex
  (TestOldProfiles, TestProfileCarriesLibrary, TestSyncLibrary went red
  in the full run without them).
- gofmt -l clean; go vet -tags nogui darwin/linux/windows clean.
- go test -tags nogui -p 4 ./... at the pushed head: see the last
  commit of this push.

Not tried: the real GUI with an uninstalled agent on a live machine.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 06:07:43 +08:00
yetoneandggbdpq c3bef99efd provider: magpie://import links take gemini=, and its host is named before adding (#2251, ggbdpq)
An import link could set chat=, responses= and anthropic= but not
gemini=, though the editor and the TUI take a Gemini base URL; a link
with only gemini= failed with "it needs chat=, responses= or anthropic=".
ParseImport now reads gemini= under the same base-URL rules, and the
error names it (ggbdpq's patch, with docs/reference.md and the en/zh
docs rows).

Its siblings that listed the three base URLs:
- the GUI's import dialog warned "Your prompts and this key will go to ;"
  with no host for a gemini-only link: it names the Gemini host now;
- the site's handoff page (site/public/import.html) left it out of
  "Sends to";
- the docs' link builder (en, zh, ja) had no Gemini field and didn't
  count it as a base URL; the ja docs lacked the table row, and all
  three said one of chat/responses/anthropic is required.

Run:
- TestParseImportGemini fails on the old importurl.go ("the link gives
  no base URL: it needs chat=, responses= or anthropic="), passes now;
  go test -run Import ./internal/provider/ ./internal/gui/: ok.
- import-link-gemini.test.cjs: 20/20 (chromium+webkit, en/zh/zh-TW/ja/de,
  1100 and 420 px); against the old app.js the warning reads "will go to
  ;" and it fails.
- docs builder (en/zh/ja) and handoff page in Chromium from file://: a
  gemini-only builder gives magpie://import?name=…&gemini=…, no errors;
  the handoff page lists gem.example under Sends to.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
Not tried: a real magpie://import click through the OS handler.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 06:07:43 +08:00
yetone e740ee7cc0 agent: a Claude Code tier set to a model keeps it when the main model moves onto that model, not "Same as main model" (#2257, luokinging)
A Fable tier set to GPT-6.1 Sol read "Same as main model" once the main
model was switched to Sol, and the next main-model move took it with it.
On a move of the main model, a tier equal to the new main model was kept
as its own only when it equalled what it would follow there. Fable follows
nothing on a model that is no Fable, and haiku follows a Claude model on
its Haiku, so neither was marked: Get then hid the tier as following, and
the next move rewrote it. The new main model itself now counts as the
tier's own model too, for every tier and both routes (magpie and Claude
Code's /model). GUI, TUI and CLI all read the same Field.

A user already caught by it sees "Same as main model" and sets the tier
again once; that state can't be told from a tier that follows.

TestClaudeFableTierOnClaude modelled 0.1.1229's wiring with fable=Sol
written before the main model moved onto Sol, which is this issue's own
case; its fixture now writes it after, as 0.1.1229 did.

Run:
- TestClaudeOwnTierOnTheNewMainModelStays (every tier, two own models,
  magpie and /model): on the old code fable fails for both models and
  routes, and haiku given Opus fails ("haiku reads \"\""); passes now.
- CLI in a sandbox HOME/CLAUDE_CONFIG_DIR, old and new binary: main ->
  k2.8, fable -> Sol, main -> Sol, main -> GLM. Old: fable gone after the
  move onto Sol, no ANTHROPIC_DEFAULT_FABLE_MODEL after GLM. New: fable
  Sol after both, env ANTHROPIC_DEFAULT_FABLE_MODEL=oa/gpt-6.1-sol.
- go test -tags nogui ./internal/agent/ ./internal/tui/ ./internal/cli/:
  ok. gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
Not tried: the GUI by hand (no asset changed; it reads the same Field).
2026-10-15 06:07:43 +08:00
yetone 9916a94608 gateway, usage, plugins: OTel export is the first plugin on the gateway's observer point (P3)
P3 of docs/subsystems/plugin-runtime.md opens the gateway to plugins. The
observer point is first: it only reads, so it carries the least risk.
With plugins/otel off, the gateway exports nothing and does no observing
work. It keeps no reply whole and adds no request context.

- usage.Observer:
  - Methods: Serve, Bodies, Begin(Request) Watch and Ledger(Record). Watch
    has Attempt and End.
  - Observe(o) registers an observer until its remove is called.
  - ServeObservers is counted, and only Server.ListenAndServe calls it.
  - ObservedBodies takes the most any observer wants.
  - Record.SkipOTel becomes Watched, set by appendUsage for a request an
    observer watched.
- The gateway's otel.go becomes observe.go:
  - observeRequest asks each observer through Begin.
  - attempt and end call each Watch. Bodies are added only when an
    observer asks for them, and the whole reply only for WholeBodies.
- internal/otlp: the exporter (otel*.go) moves out of internal/usage, and
  the gateway's per-request span state moves into request.go. otlp.New()
  is an Exporter, a usage.Observer. What it sends is unchanged.
- plugins/otel:
  - Apply registers otlp.New() and disposes of it when turned off.
  - InUse is 1 while settings.OTelExport says to send. A user who exports
    only through MAGPIE_OTEL_* keeps the plugin on under Essentials.
- pluginrt.KeepFresh: the process serving the gateway refreshes every 2s
  when plugins.yml or settings.json changes. A switch made in the window or
  the CLI reaches a running gateway, or a headless serve, without a restart.
- docs: plugin-runtime.md gets a P3 section, a gateway runtime path and an
  updated failure section; reference.md says the export is the otel plugin.

Run at this tree on origin/main 82f48f093 (rebased onto 52ee84761 after,
which touches only the Linux tray icon):
- gofmt -l is clean. go vet passes on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 -timeout 25m ./...: ok, 55 packages, none failed.
- New tests:
  - usage: TestObserverServesWithTheGateway and TestObserverLedgerAndBodies.
  - gateway: TestObserverPoint, covering unwatched, no bodies, captured,
    whole and whole streamed.
  - plugins/otel: TestOnExportsOffSendsNothing (on, off, on, with a real
    collector) and TestInUseByEnvironment.
  - pluginrt: TestKeepFreshFollowsPluginsYml.
  - The OTel tests moved with their code to internal/otlp.

Broken by hand, each red, then restored:
- Apply without Observe, and without its dispose.
- KeepFresh refreshing only once.
- InUse reading settings.json only.
- Ledger keeping Watched rows: 3 gateway OTel tests red.
- ObservedBodies taking the last observer's answer.
- Observe not serving a late registration.
- appendUsage not setting Watched.
- Whole bodies never kept.
- Bodies always on with no observer asking.
2026-10-15 05:39:01 +08:00
yetone 52ee847612 gui: a Linux bar's tray icon is the bird's silhouette, not the app's tile, and the tooltip says today's total (ylorn on Discord)
ylorn (Hyprland, 0.1.1241): the StatusNotifierItem's IconPixmap was the
coloured app icon on an opaque white tile, which clashed with a bar's
monochrome icons and became a solid block on bars that tint icons by
alpha; the tooltip said only "magpie".

- Linux now gets the macOS menu bar's template bird (tray.png) in one
  colour on transparency (trayIconFor / linuxTrayIcon, trayglyph.go):
  light, or dark when xdg-desktop-portal's org.freedesktop.appearance
  color-scheme is 2 (prefer light); it is set again on the portal's
  SettingChanged (watchTrayScheme, own D-Bus connection). An unreadable
  portal counts as no preference (light). No IconName is set: a host
  that resolves a -symbolic name but draws it untinted would show a
  black bird on a dark bar with no pixmap fallback. macOS keeps its
  template icon, Windows the coloured app icon.
- With no cards in the menu bar the tooltip is "magpie" over one line of
  today's total, as the panel's Usage tab sums it (trayIdleTip: all
  tokens, cost in Settings' currency, requests), refreshed with the
  cards' loop. Cards picked: unchanged.
- The menu is unchanged (Open / version / Quit): no info lines. The
  panel one click away has the models and usage, and the menu is shared
  with Windows and macOS.

Run (sandbox HOME, pinned GOMODCACHE, shared GOCACHE), on origin/main
21aa40285:
- TestTrayIconPerOS fails with Linux given appIcon back ("linux:
  (0,0)-(64,64), want the menu bar bird's (0,0)-(44,44)"); TestTrayIdleTip
  fails with the tooltip back to plain "magpie". Both pass restored, with
  TestPortalLight, TestTrayTotals, TestTrayIconSize, TestSNITipIsSafeMarkup.
- gofmt -l clean; go vet ./... (darwin), GOOS=windows go vet ./...,
  GOOS=linux go vet -tags nogui ./... clean; GOOS=windows go build and
  GOOS=linux go build -tags nogui OK.
- traytip_linux.go (linux && !nogui, cgo) can't be vetted from macOS: the
  two new functions were copied into a darwin build and vetted there.
- go test -p 4 -timeout 40m ./...: exit 0, 53 ok, no FAIL.
- GUI: tray-*.test.cjs (Playwright 1.62.0): 112/112 pass.

Not tried on a real Linux bar (the Windows box with its WSL2/Omarchy VM
was unreachable over ssh): the pixmap, its colour on a light/dark scheme
and the tooltip on waybar/Quickshell/KDE are unverified on hardware.
2026-10-15 05:30:58 +08:00
yetone 82f48f0935 gateway, provider, gui: a provider set to compact natively is asked Codex's compaction_trigger as sent and its sealed compaction goes back unchanged; a checkpoint stays with its writer (#1099)
A new per-provider option, off by default. With it on, Codex's
compaction_trigger reaches the provider as Codex sent it, and the
provider's encrypted compaction item goes back to Codex unchanged instead
of magpie's magpie1: summary. Off, nothing changes.

Where it can be on (provider.CarriesCompaction): a provider with a
Responses API (Sub2API and other OpenAI relays, a remote magpie), a
ChatGPT (codex) account, and the built-in GitHub Copilot on its GPT
Responses path. Copilot's Claude models are asked on chat completions, so
they still get magpie's summary (CompactsOn). A group compacts natively
only when every member does.

No silent downgrade:
- A turn carrying a sealed compaction goes only to the key or account that
  wrote it (compactions.json beside affinity.json, 0600, 1024 entries /
  30 days). With none left, Codex gets a 400 saying the conversation was
  compacted natively on <who>, not a summarised or dropped context.
- A provider whose request would have to be translated (not relayed) is
  refused with a 400 instead of losing the item.
- The upstream's own refusal goes back to Codex as it came, one call.
- base_instructions and Codex's identity are untouched.

Turning it on:
- GUI: the provider editor's Compaction row, "Codex compacts on this
  provider" (shown only where the wire can carry it; zh, zh-TW, ja, de).
- CLI: magpie provider set <id> compaction=native|magpie. A provider that
  can't carry it is refused.

Run on origin/main 00501401a, then rebased onto 84f14e555 (no file in
common) and reran gofmt, vet and go test for gateway, gui, provider,
cli, usage and sessions: all ok. Rebased again onto 8d2a4a7da (gateway.go
and codex_backend.go changed on both sides, merged clean) and reran
gofmt, vet (darwin, linux nogui, windows) and go test for gateway, cli,
provider and gui: all ok. Last rebased onto 7a3fed6bb (only
gateway-routing.md shared, merged clean): gofmt, vet on all three OSes,
and go test -run for the native compaction, sink, CORS, rebind and origin
tests in gateway plus the provider tests: ok.
- gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
  clean.
- set -o pipefail; go test -timeout 40m ./...: every package ok but
  internal/provider's TestCopilotSecretToolUsername (copilot_cli_test.go:93
  token "", 10.05s), the open load flake #1627; it passes alone -count=5
  and this change doesn't touch it.
- GUI (node --test, chromium + webkit): the provider-editor files, 946
  pass, 0 fail; the new provider-native-compaction.test.cjs runs 5
  languages at 1100 and 420 (60 cases).
- New Go tests: TestNativeCompactionPassesTheTrigger, ...RefusalGoesBack,
  ...StaysWithItsWriter, ...Copilot (gateway), TestCarriesCompaction,
  TestSetNativeCompaction (provider), TestProviderSaveNativeCompaction
  (gui), TestProviderCompactionPair (cli).

Broken by hand, each red, then restored:
1. codexInputAs dropping the trigger even when native: all 4 gateway
   tests fail.
2. checkpoint filter off: StaysWithItsWriter fails.
3. forced relay off: all 4 gateway tests fail (the web_search tool sends
   the turn to translation).
4. GUI save sending nativeCompaction false: the GUI test's first case
   fails.

Not tried: any real upstream (Sub2API, ChatGPT, Copilot). Copilot may
refuse a compacted history holding web_search items; that refusal would
go back to Codex as-is.
2026-10-15 05:20:17 +08:00
yetone 118f4f28bf plugin: a community plugin npm doesn't have installs from the plugins repo's dist branch, so a reviewed plugin no longer waits unmerged for an owner's npm 2FA (magpie-community/plugins#84)
npm's Trusted Publishing can't create a package, so a new plugin's first
version needs an owner's 2FA, and reviewed PRs sat unmerged for it. A
trust made after 2026-09-03 also allows stage publish only, which is why
npm refused zed 0.1.7 and zen-free 0.1.7.

The plugins repo now packs every merged version onto its `dist` branch
(scripts/dist.mjs, magpie-community/plugins f5308cd): tgz/<file> and an
index.json with each version's sha512, manifest and README, with no
credentials. magpie still asks npm first. Only when `bun add` fails for a
@magpie-community package at latest or an exact version, and not because
of the user's minimumReleaseAge (that hold is kept), does installDist
fetch the tarball. It refuses the tarball unless its sha512 is the index's,
keeps it in plugins/dist and runs `bun add ./dist/<file>`. A later npm
install replaces it, and pruneDist removes tarballs package.json no longer
names. npmAsk (market version, Update, the hourly check) takes dist's
latest when npm errors or is behind, and Readme falls back to dist's. The
branch is read through jsDelivr when the China mirror switch is on, else
raw.githubusercontent.com. installMu is now held for the whole install,
fallback included.

Run at this head (on origin/main 8d2a4a7da):
- go test ./... -count=1: all ok but internal/gateway, which hit the
  600s default timeout inside a file rename. The disk was at 5.3 GB free
  and the load around 22. Rerun alone with -timeout 30m: ok in 559.7s.
- gofmt -l clean. GOOS=windows go vet ./... ok. GOOS=linux go vet ok on
  every magpie package that doesn't import Wails (its Linux files need
  cgo, which can't be cross-compiled from macOS).
- New tests, with real Bun 1.4.2 against a fake npm and a fake dist:
  TestDistInstallsAPackageNPMDoesntHave, TestDistServesAVersionNPMRefused,
  TestDistRefusesATarballNotItsIndexs and TestDistWanted.
  TestUpdateBunHoldsBackSaysWhy now has dist holding the held version too.
- Broken by hand, each went red: no fallback, no sha512 check, no prune,
  no dist version in npmAsk, a loose file regexp, and no minAge guard.
- The real dist branch serves index.json and zed's 0.1.7 tarball from
  raw (200). jsDelivr's @dist answered 200, cold in ~20s.

- Real use, sandbox HOME, live npm and live dist: Info said zed 0.1.7
  (npm has 0.1.6), and Add@0.1.7 installed it from dist, package.json
  naming ./dist/magpie-community-opencode-zed-auth-0.1.7.tgz.

Not tried: the GUI's Add on the live branch, or the China mirror path.
2026-10-15 05:18:56 +08:00
yetoneandggbdpq 7a3fed6bb5 gateway: a group in the group sinks its own rate-limited keys by its own Sink, not only the group the agent named (#2255, ggbdpq)
What changed
- planLevel applies a nested group's own Sink (sinkOwn) to its own
  candidates and their trace rows at both places it plans one: the
  weighed units (Smart, usage, pace, weight) and the ordered walk. A
  key or account of that group rate limited with quota left goes behind
  its group's others, within that group's place, as it plans by its own
  routing (#576) and rules. The group the agent asked for still sinks
  the whole after, as before. sinks() still leaves out rotate, weight
  and manual.
- Why: only planGroup read Sink, for the group asked for; an inner
  group's switch did nothing, and its rate-limited account went back
  to the front as soon as its rest ended.
- provider/group.go's comment and gateway-routing.md's Sink row say so.

Ran
- TestNestedGroupSinksItsOwnOrder (outer ordered, smart and by weight;
  three levels deep with the middle group's Sink and with the
  innermost's; inner Sink off; the outer's Sink alone): fails on
  origin/main 00501401a ("order [a b x], want b then a"; "mid's Sink:
  order [a b c y], want [b c a y]"), passes with the change.
- Broken by hand, each red: sinkOwn never sinking (all subtests); only
  the ordered path left unsunk (outer ordered and deeper).
- TestGroupRateLimitedSinks, TestRateLimitedSinksToTheBack (-count=3),
  and -run 'Sink|Nested|OwnRouting|Weighted|Group': ok.
- gofmt -l clean; go vet ./..., GOOS=windows go vet ./...,
  GOOS=linux go vet -tags nogui ./... clean.
- go test -p 4 ./... (macOS): ok in every package but internal/agent and internal/gateway, which hit the 10m package timeout under load ~30 with no test hung (the running test 1-2s old); rerun with -timeout 40m: gateway ok 551s, agent ok 426s.

Not tried: a real nested pool with live accounts. The report's sibling,
a nested group's Affinity read only from the outer group, is left for
its own issue.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 05:17:38 +08:00
yetoneandggbdpq d182294be7 gateway: a page at a localhost subdomain spends a subscription only with a gateway key, as Origin null does (#2256, ggbdpq)
What changed
- corsGuard refuses (403) an http(s) Origin at a subdomain of localhost
  unless the call carries an enabled gateway key (localhostSubdomain),
  the rule Origin "null" got in #2242. foreignPage still passes it, so a
  page there that holds a key keeps working; neither gets CORS headers.
- Why: Chrome and Firefox resolve *.localhost to loopback themselves,
  but Safari and other WebKit views hand the name to the system
  resolver, which before macOS 26 asks the network's DNS (WebKit bug
  160504, closed MOVED: "implemented in OS frameworks below WebKit",
  2025-09-19; fails on macOS 15.7). A captive portal's or hostile
  network's resolver serves such a page from anywhere, and its "simple"
  text/plain POST spent subscriptions with no key.
- tauri.localhost and wails.localhost stay keyless on Windows only,
  where Tauri's and Wails' webviews serve themselves at those names. On
  macOS and Linux those apps use tauri:// and wails://, so the two names
  are any page's there, and a hostile resolver answers them as readily
  as any other (the residual the report left open). webviewOS
  (runtime.GOOS) lets the test be each system.
- The same page also reached the gateway rebound: at evil.localhost:3425
  once the name turns to 127.0.0.1, its GET carries no Origin, and
  lanGuard's ownHost counted every *.localhost Host as this computer, so
  GET /v1/models and /v1/magpie/quotas answered 200. ownHost no longer
  counts a subdomain of localhost (localhost itself and
  docker.for.mac.localhost still count); a browser at one needs a key.
- TestForeignPagesRefused's tauri.localhost row now sends a key, and
  TestReboundPageRefused expects wails.localhost refused.
- docs/subsystems/gateway-routing.md says both.

Ran
- TestLocalhostSubdomainNeedsAKey (darwin, linux and windows as
  webviewOS; six routes; cross-origin and rebound; the fake vendor never
  reached): fails on origin/main 00501401a (76 errors, e.g. "POST
  /v1/chat/completions from http://evil.localhost with no key: 200"),
  passes with the change.
- Broken by hand, each red: ownHost counting *.localhost again (the
  rebound GETs 200); localhostSubdomain always false; the Windows-only
  exception dropped (tauri.localhost answered keyless on darwin).
- The cors, rebind, LAN, usage-ingest and allow-list tests: ok.
- gofmt -l clean; go vet ./..., GOOS=windows go vet ./...,
  GOOS=linux go vet -tags nogui ./... clean.
- go test -p 4 ./... (macOS): ok in every package but internal/agent and internal/gateway, which hit the 10m package timeout under load ~30 with no test hung (the running test 1-2s old); rerun with -timeout 40m: gateway ok 551s, agent ok 426s.

Not tried: a real Safari on macOS 15 against a resolver that answers
*.localhost; Tauri or Wails apps on Windows.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 05:17:37 +08:00
yetone 84f14e555c usage: a Codex call with no response_id leaves compaction out of Usage requests instead of saying false (#1591)
Codex added token_usage_record and compaction_response_id together, in
openai/codex#41912 (2026-08-31). A call that magpie reads from a
token_count event alone, as in older rollouts, has no response_id. It
can't carry the compaction marker either way. The previous commit
reported such calls as `compaction: false`, which claims they were not
compactions. codexCompactionOf now returns no state for them, so the
ledger and the requests page leave the field out, as they do for any call
with no native evidence.

What was run:
- New test TestCodexCallWithoutResponseIDHasNoCompactionState. On the
  previous commit it fails with `ledger: a call with no response_id claimed
  a compaction state: {..."compaction":false...}`, and with the same message
  for the requests page. It passes now.
- go test -tags nogui ./internal/sessions ./internal/usage: ok.

For all three commits on origin/main 1ad60446f:
- gofmt -l on the changed files: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: ok.
- go build for darwin, linux (nogui) and windows: ok.
- Full suite: go test -tags nogui -timeout 40m ./... (pipefail, sandbox
  HOME): 53 packages ok, exit 0.
- No GUI asset changed, so no Playwright run.
- Not tried: a real Codex subagent rollout (legacy or paginated). The
  formats are from Codex's source, and Hogeexxl checked two real paginated
  subagents.
- Rebased onto origin/main f255a3e3b (12 commits newer, including #2233 and
  #2234 in internal/sessions; no cache-version clash). Rerun there: go
  test -tags nogui -count=1 ./internal/sessions ./internal/usage
  ./internal/gui, gofmt and vet on both packages: ok.
2026-10-15 04:21:31 +08:00
yetone a78ac27532 sessions: a Codex subagent in a legacy-history rollout gets its spawn task_name too, and a forked child's copy of its parent's spawns no longer erases its siblings' titles (#1591)
Two gaps in the previous commit's title link:

- Legacy rollouts. Codex's ThreadHistoryMode is Legacy by default. The local
  thread store has only defaulted to Paginated since openai/codex#47900
  (2026-09-24). A legacy rollout doesn't persist item_completed for a started
  SubAgentActivity. It persists an event_msg instead:
  {"type":"sub_agent_activity", "event_id": <call id>, "agent_thread_id",
  "kind":"started", ...}. Its children got no title. That event now links
  the same way, through one helper (codexAgentStarted) shared with the
  item_completed path.
- Forked children. A forked child's rollout repeats its parent's history,
  including the spawns of its siblings. The same call id then linked from
  two files, which counted as a conflict and erased the sibling's title.
  Titles are now keyed by {child, parent}, and only the file of the child's
  own parent_session names it or takes a name away from it.

What was run:
- New tests. On the previous commit each fails with:
  - TestCodexSubagentTaskTitleFromLegacyActivity: `legacy activity title
    for child-started = "", want "Legacy started task"`.
  - TestCodexSubagentTaskTitleComesFromItsOwnParent: `a fork's copy of the
    parent's spawn erased the child's title: ""`.
- Broken by hand: with the parent dropped from the key, the second test
  fails with `a spawn its parent never made named the child: "Only in the
  fork's copy"`.
- go test -tags nogui ./internal/sessions ./internal/usage: ok.
- The event's field names come from Codex's source (protocol
  SubAgentActivityEvent and the rollout persistence policy, openai/codex
  669449b). Not tried: a real legacy-history Codex subagent rollout.
2026-10-15 04:21:31 +08:00
Hogee 3c4b4dc973 sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:

- A Codex child thread whose title is still empty after the existing
  precedence takes the task_name of the parent's spawn_agent call, linked by
  the call id and the SubAgentActivity "started" item that names the child's
  agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
  manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
  (true/false) for Codex calls with native evidence, and leave it out
  otherwise. A gateway row matched by a unique response_id takes the marker
  and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
  TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
  cache goes to version 21 and the calls cache to calls-v15.

Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
  - v2 spawn_agent args carry task_name.
  - A paginated rollout persists item_completed with a SubAgentActivity
    item: kind "started", id = the call id, agent_thread_id.
  - SessionMeta has a top-level agent_nickname, which Codex's own list.rs
    and metadata.rs read too.
  - compaction_response_id lives in token_usage_record.
  Gaps in legacy rollouts and in calls without a response_id are fixed in
  the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
  are added to local API responses. Nothing new goes to a vendor or to
  telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.

What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
  and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
  - the nickname read removed;
  - the conflict checks removed;
  - mergeCodexCompactions broken;
  - the gateway pair's setCodexCompaction removed;
  - the flag read forced to true.
- Not caught:
  - the parent check on the title link (covered by a test in the next
    commit);
  - `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
    defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
  last one.
2026-10-15 04:21:31 +08:00
Haogao Gu d966e19154 gateway, gui: the Routing page tags a Claude Code subagent's turn as it does Codex's
Codex names a subagent's request (x-openai-subagent: collab_spawn), and
the Routing page tags its row Subagent, with why it went where it did.
Claude Code names no kind, so Claude Desktop's subagent turns, which
magpie now moves to their own model and effort, read as the lead's: a
Desktop session's rows on one routing group could not be told apart.

Claude Code 2.1.295 sends x-claude-code-agent-id from every agent context
but the main one. Its x-claude-code-request-class and
x-claude-code-agent-type hints go only to a first-party base URL or with
CLAUDE_CODE_GATEWAY_HINT_HEADERS, so magpie doesn't get them.

- subagentTurnOf keeps the id in Route.SubagentID for a request that
  offers tools and names no kind: the turn desktopSubagentPick and
  desktopSubagentEffort take. Desktop's and terminal Claude Code's turns
  are kept, moved or not. The lead's turns, a subagent's tool-less helper
  calls (#2081: Claude Code's housekeeping) and a blank id are not. A
  kind wins over the id.
- A Desktop pick or effort that found the turn is trusted, so the body
  isn't decoded again; a request without the id isn't decoded at all.
  Only a subagent's turn with neither setting reads its tools once.
- Kind stays empty (#2081), so the ledger, the Usage page and the
  Purpose filter keep the turn unmarked. The ledger's Subagent already
  keeps the same id, on the helper calls too.
- routing.js tags it through tagKind in the request list (by request and
  by session), the story, the replay and the tray panel, with Codex's
  words and reasons (kindWhy's collab_spawn: moved or kept, within a
  routing group, on the model asked for). No new strings.
- The day's history keeps the id. A route kept before it has no tag, and
  its moved/kept story reads as before.

Verified at this head, on b9c589eb, under a temporary HOME with Go's
caches pinned:
- Each new test fails with its guarantee broken by hand (a real FAIL, not
  a build error), then passes restored. Go, 10: the id never set; tools,
  kind or the trusted pick ignored; tools decoded before the header (the
  lead's request then allocates 10 times, 1 for its headers); the route
  not given the id; Desktop only (terminal fails); every request trusted
  (the helpers fail); the JSON key renamed; the field left out of the
  history. GUI, 8, each 0 pass / 4 fail (Chromium and WebKit, 1100 and
  420, zh) at its own assertion: tagKind ignoring the id; the list, the
  story, the replay or the panel testing Kind alone; kindWhy's
  collab_spawn reasons on Kind alone; the id over a kind; the Purpose
  filter following the tag.
- go test -tags nogui ./...: 53 packages ok.
- go test -race -count=20 -run
  '^(TestSubagentTurn|TestHistoryKeepsSubagentID|TestDesktopSubagent)'
  ./internal/gateway: ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: exit 0.
- claude-subagent-tag.test.cjs: 20/20 (Chromium and WebKit; en, zh,
  zh-TW, ja, de; 1100 and 420), three runs in a row.
- Desktop-bundled Claude Code 2.1.295 through the built gateway, a
  temporary HOME, a loopback-only sandbox and local fixture replies, its
  Agent tool spawning a real subagent: with nothing set, with a subagent
  model, and as terminal Claude Code, each run kept 4 routes; the
  subagent's one turn has the id the client sent upstream, the lead's 3
  requests none, Kind empty; the model pick moved it to m2. No tool-less
  helper call came in these runs; the Go tests cover them.
- The Routing GUI tests around it, 91 files (every routing-*, the tray
  panel's two, purpose-filter, click-scroll, the Codex and Desktop
  subagent files, subagent-effort, search-instead, search-mcp, vision-mcp,
  remote-group-served, reasoning-speed, usage-ledger, sessions-overview
  and the new one), six files at a time: Chromium 602/617, WebKit
  572/617. Each failure fails without this commit too. On b9c589eb
  untouched (checked for the effort commit): routing-days-fit,
  routing-failed-open and routing-side-calls in both engines (their
  position checks against #2134's at-top rule), routing-wb-restricted
  (#2115's wheel), and at 420 in WebKit routing-agent-gone,
  routing-agent-hue-not-red, routing-rest-off and routing-held-member.
  On 6926b7ce: search-instead in WebKit, 5 of 5 alone, and
  routing-context-fold's picked request in WebKit, a row out of view, 2
  of 5 runs alone there and 3 of 5 here.

Not run: the whole GUI suite, a real Claude Desktop window or Cowork,
Linux and Windows machines (GOOS vet and build only), WebKitGTK.
2026-10-15 03:34:59 +08:00
Haogao Gu b476dc5a93 agent, gateway, gui: Claude Desktop's subagents can have a reasoning effort of their own
After #2081 gave Desktop a subagent model, its effort still came from the
request. Add subagent_effort beside that model, using the existing effort
slider. The live setting DesktopSubagentEffort belongs to magpie; no
Claude client file or binary is changed.

Empty preserves the request's effort, including disabled thinking. A pick
applies only to Desktop requests with an agent id and tools, independently
of model replacement: unset, equal and unavailable model picks all work.
Reuse the attempt-level fitting; fixed group-member efforts and reasonless
models keep their existing precedence. count_tokens applies the pick after
unmasked-body restoration. A Codex SubagentPick is not evidence of a
Desktop tool turn.

Route.Effort keeps the incoming level, SubagentEffort records the configured
pick, and tries/usage keep the actual level. Routing explains the pick
even without a model replacement. Options follow the target model; a
saved level survives a model change. POST /api/settings preserves it.
Disconnected preferences, Disconnect/reconnect and restored settings work;
a Live pick gives restart advice only when it actually connects the agent.
Codex's own settings and default-effort explanation are unchanged.

Verification on b9c589eb plus this change, with temp HOME and pinned Go
caches:
- go test -tags nogui ./...: 53 packages pass.
- Gateway effort tests under -race -count=20: pass.
- gofmt -l: empty; darwin, linux nogui and windows vet/build: exit 0.
- 23 intentional Go behavior breaks produce real FAILs, then pass
  restored: application, scope, model independence, Default/none,
  disabled thinking, fitting/member priority, counts, next request,
  trace, saving/validation, Live notices and model-dependent options.
- Three UI breaks fail in both engines at 1100/420: default explanation,
  missing effort story and missing translation. Restored: Desktop's new
  controls/story matrix passes 20/20 across five languages. Desktop,
  Codex, tier/effort and translation regressions pass 97/97.
- Desktop-bundled Claude Code 2.1.295 runs real Agent calls through the
  built gateway, temporary HOME and loopback-only sandbox, all replies
  local fixtures. Low/high/Default sends its child low/high/xhigh on m2;
  its lead remains xhigh on m1. All three runs exit 0.

The expanded Routing run is not green: Chromium 510/525, WebKit 485/525.
These failures reproduce on untouched b9c589eb, including targeted reruns.
The day/row anchor assertions conflict with #2134's at-top rule: undoing
that one guard makes all 12 tests pass. A narrow request lies below the
viewport; user wheel input makes the failed click pass. WorkBuddy's wheel
pointer/hidden-button failures overlap #2115; moving the wheel to the
view gutter fixes 3/4 selected cases, one WebKit 420 case remains.
The held-member clipping assertion also reproduces on base; its timing
cause is not established. This baseline evidence is reported separately
in the follow-up feature issue, not counted as passed or fixed here.

Not run: the complete GUI suite, the Electron window/Cowork, native
Linux/Windows or WebKitGTK. Cross-builds are not runtime checks.

Reported-by: Koohoko
2026-10-15 03:34:59 +08:00
JasonBuildAI 7c5bfd7a1d gateway: auto affinity keeps a conversation where a vendor's cache is kept without saying so (#2230, JasonBuildAI)
A vendor that keeps the prompt cached by itself and reports nothing of it —
OpenAI's automatic prefix cache, Gemini — says neither a read nor a write of
the turn that built the cache. affine judged that turn's stick by what the
reply read and wrote (0 + 0), found it under cacheWorth and moved the
conversation's second turn as "no-cache": the whole prompt went afresh to
another key or account and was paid for in full, on every turn after the
first, for anyone with more than one key or account and Affinity auto (the
default).

7f968b95b named this as not covered: "a vendor that caches without reporting
a write (OpenAI's automatic prefix cache, Gemini) still reports CacheWrite 0
on a first turn, so its second turn may still move".

What such a vendor holds of the conversation after a turn is the prompt that
turn was sent, which is what its cache now has. answered takes the reply's
usage rather than its two cache counts, and where the reply reports neither
a read nor a write, the prompt it was sent (Input) stands for the write: the
second turn stays to read it, as it does for a turn that wrote its cache. A
reply that reports no usage at all (Input 0) counts as no cache, as before,
and a prompt under cacheWorth (1024) still moves. A read or a write the
vendor does report is used as it was, and resting, spent, cold, strict, turn
and rotate are judged before this, so nothing else changes.

The observable change: with Affinity auto, a conversation whose last reply
reported neither a cache read nor a cache write, and was sent at least 1024
tokens, is kept where it was (Why "cache", Kept true) rather than moved
(Why "no-cache"). Its stick, affinity.json and the trace's
Affinity.CacheWrite carry the prompt sent, and Affinity.CacheRead stays 0,
which is what the Routing page shows as read and written; the page itself is
unchanged.

Tests:
- affinity_silent_cache_test.go (new): TestAffinityKeepsACacheTheVendorKept
  Silently. Two keys, least-used routing, and a Chat vendor reporting
  prompt_tokens 3000 with cached_tokens 0 — what OpenAI and Gemini send of a
  first turn — keeps the second turn on k1 as "cache", with the trace
  telling CacheRead 0 and CacheWrite 3000; a vendor reporting no usage at
  all still moves to k2 as "no-cache".
- TestAffinityKeepsACacheJustWritten, its "too little either way" (300/300,
  no-cache) case included, passes as it did.

Run:
- go test -tags nogui -count=1 -run TestAffinity ./internal/gateway: ok,
  80.982s (TestAffinity 39.36s, TestAffinityKeepsACacheJustWritten 26.54s,
  TestAffinityKeepsACacheTheVendorKeptSilently 9.68s).
- go test -tags nogui -count=1 -timeout 45m ./...: every package passes
  except 21 tests red on this Windows machine — agent 4
  (TestInstallWithoutNodeParses, TestWSLClaudeFollowerOnTheMainModelIsNoDrift,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI), gui 4
  (TestGatewayHeldByAContainer, TestGatewayFixQuitsOnlyAMagpie,
  TestFXStateDoesNotWait, TestUpdateThatWontStart), library 3
  (TestAgentsSkillsFolders, TestRemoveFoundSkill,
  TestHooksCodexTrustMovesWithTheGroups), gateway 2 (TestClaudeAsRootEnv,
  TestSweepBridgeProjectsTakesOnlyTheBridgesFolders) and one each in backup,
  davsync, pluginrt, provider, sessions, update and usage. A fresh worktree
  at the base e98440ae, without this change, fails the same 20 of them. The
  21st, gui's TestPurposeAssetMatchesUsage, fails only in this checkout,
  whose internal/gui/assets/purposes.js is CRLF (git says i/lf w/crlf) and so
  keeps the "\r" its TrimSuffix(";\n") doesn't cut; the file is not in this
  diff and the test passes in the base worktree.
- gofmt -l on the changed files: nothing. go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./...: nothing. go build,
  GOOS=linux go build -tags nogui, GOOS=windows go build: ok.
- Broken by hand: with the substitution removed the new test fails —
  "silent cache: affinity &{... CacheRead:0 CacheWrite:0 ... Why:no-cache},
  want cache". At the base commit the case fails the same way, the second
  turn going to k2.

Not tried: the Playwright suite (no GUI asset changed; the Routing page
reads the same JSON) and a live OpenAI or Gemini key.
2026-10-15 03:34:58 +08:00
yetone 1ad60446ff gateway: a model failing between its siblings' answers climbs its own rest ladder, not a minute forever (#2241, weizsw)
The backoff count was kept per account (restKey), and any model's answer
cleared it. On an account serving several models, a model that kept
failing while its siblings answered was counted 1 every time and rested
one minute, forever. weizsw's Antigravity seat: 41 of 43 rests at
failures: 1.

restAfterMarked now also counts each model's own failures (restID), and
only that model's answer clears that count (servedCandidate). When a
model's own count is past the account's, a sibling answered since the
model last did, so the failure belongs to the model. It climbs its own
ladder (1, 2, 4, 8, 10 minutes) and rests alone, keyed by restID, while
its siblings stay served. If every model fails with no answer between
them, the account still climbs and rests whole, as before. A window
rest wins as before. A candidate naming no model keeps the account's
count alone.

What was run:
- TestModelLadderClimbsPastSiblingAnswers (new, model_ladder_test.go).
  Old code: FAIL ("failure #2 after a sibling's answer: 1 failures,
  rests 59.99s; want 2m0s"). With the restID choice taken out by hand:
  FAIL ("rests antigravity@seat@example.com, want the model alone").
  With the fix: pass.
- The first full run caught TestSmartRouting. Its modelless candidate
  ("t#fail") was given a "t#fail/" count that its served() call never
  cleared. Fixed by counting per model only when the candidate names
  one. TestSmartRouting and the rest/ladder tests pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and GOOS=windows
  clean.
- HOME=<scratch> go test -tags nogui -timeout 40m ./...: every package ok
  except gateway's TestSmartRouting (above). After the fix, gateway was
  rerun whole: ok (468s).
2026-10-15 03:25:41 +08:00
yetoneandJasonBuildAI c20bb76c4c gateway: a sandboxed frame's Origin: null spends a subscription only with a gateway key (#2242, JasonBuildAI)
A sandboxed iframe, or a page opened from file://, sends `Origin: null`.
foreignPage judges only http and https origins, so corsGuard let "null"
through without a key. A simple text/plain POST from such a page (no
preflight) reached /v1/chat/completions and spent the user's
subscription. corsGuard is where every route's same-origin is decided,
so the fix goes there: a request with Origin: null is answered only
when it carries a working gateway key (keyedCaller, which the listed-
origin 401 path now uses too). It gets 403 and a message that says how
to send a key. App schemes (app://…) and requests with no Origin are
unchanged.

The patch is JasonBuildAI's fe11a8abd (fork branch
fix/null-origin-keyless-spend-a13b21). docs/subsystems/gateway-sessions.md
also says that a null Origin needs a key.

What was run, at this commit's parent 8e8316ed2 vs. this tree:
- Repro with a sandbox HOME, a fake upstream on 127.0.0.1:3672 that logs
  each hit, and `magpie serve` on 127.0.0.1:3671. On main, curl POST
  with Origin: null got 200 and reached the vendor. A sandboxed srcdoc
  iframe in a file:// page, in Playwright WebKit and Chromium, reached
  it too (2 hits). Fixed: null POST and GET /v1/models got 403,
  app://cherry and no-Origin got 200, and both browsers were refused
  with 0 upstream hits.
- With main's cors.go and the new tests, TestForeignPagesRefused and
  TestOpaqueOriginNeedsAKey FAIL ("a sandboxed frame with no key reached
  the vendor 5 times"). With the fix both pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and GOOS=windows
  clean.
- HOME=<scratch> go test -tags nogui ./...: every package ok except
  internal/gateway and internal/agent. Those hit the 10m timeout at load
  average 76-91: the running tests were 14s and 23s old, not hung. Rerun
  with -timeout 40m: gateway ok (724s), agent ok (620s).

Co-authored-by: JasonBuildAI <jasonbuildai@gmail.com>
2026-10-15 02:58:41 +08:00
yetone d5847f1985 provider: a Codex token refresh replaces ~/.codex/auth.json through a flushed temp file, so a crash or a file held on Windows leaves Codex signed in, not an empty auth.json or a spent refresh token (#2239, JasonBuildAI)
codexToken wrote the rotated tokens back into the user's own Codex
sign-in (~/.codex/auth.json, $CODEX_HOME when set) with a bare
os.WriteFile: O_TRUNC, then write, error dropped. A machine going down
between the two leaves the file empty or zeroed (#1505's shape, on the
vendor's sign-in), and on Windows a file another program holds for a
moment refuses the open, so the rotation never reached the disk while
the refresh token on it was spent (refresh_token_reused on the next
refresh, magpie's or Codex CLI's). It now goes through writePrivate
(edit.Target + steady.WriteFile: temp file beside it, fsync, rename,
held target waited out by steady.Rename for up to 0.5s, mode 0600); a
write that still fails is logged rather than dropped silently, and the
fresh access token still serves the request. codexToken is the one
path for the default home's account, its usage, resets, keep-alive and
the Usage page.

Siblings: grepped every os.WriteFile / O_TRUNC / os.Create outside
tests. The only other write of an agent's live sign-in that truncated
was writeClaudeCredential's file branch (Claude Code's
.credentials.json, written when magpie switches Claude Code's
sign-in off the Keychain); it now goes through writePrivate too and returns a failed
flush as an error instead of "saved". Saved accounts' refreshes
(logins_on.go) already go through writeLogins; Kiro's IDE file through
writeFileAtomic; Codex/Claude switches through writePrivate; mcpauth
and plugin-auth through steady. Gemini's oauth_creds.json, Cursor's,
Grok's, Command Code's, ZCode's credential files are only read. The
remaining os.WriteFile calls write magpie's own caches, marks, ids,
temp files, or create a file only when it is empty (dsh, zcode).
docs/subsystems/providers-accounts.md's #1505 entry says so.

Tests (internal/provider/credentials_write_test.go, _windows_test.go):
- TestCodexRefreshFlushesAuthJSONBeforeReplacingIt: steady.Sync made to
  fail leaves auth.json byte-identical and no temp file; with a working
  flush, auth.json still holds the old sign-in at flush time, the temp
  is beside it, the result keeps every other field and mode 0600.
- TestClaudeCredentialFlushesBeforeReplacing: same for
  .credentials.json, and a failed flush is an error.
- TestCodexRefreshOutlastsAHeldAuthJSON (Windows): auth.json held with
  CreateFile(GENERIC_READ, FILE_SHARE_READ) for 100ms during the
  refresh; the rotated r-work-2 must be on the disk afterwards.

Broken by hand: with both writes put back to os.WriteFile, on macOS the
first two FAIL ("a flush that failed left auth.json ...r-work-2...,
want the sign-in as it was"; "a write whose flush failed reported as
saved"), and on the Windows box (Windows 11 x64, amd64 test binary,
sandbox USERPROFILE/APPDATA/LOCALAPPDATA/TEMP) all three FAIL, -count=3,
the third with "the rotated tokens are not on the disk, only the spent
one's: ...r-work...". With the fix all three PASS 3/3 on Windows and
the two PASS on macOS.

Run on origin/main 7be68467f: gofmt -l (empty),
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build,
and go test -tags nogui ./... under a sandbox HOME with pinned caches
(every package ok but internal/agent and
internal/gateway, which hit go test's default 10m timeout with no hang
in their stacks, the machine at load average 50-90 from other
sessions; rerun with -timeout 40m both ok, 800s and 874s). On the Windows box: the full internal/provider
test binary run from the package folder:
all pass but TestPluginsCarried (open #2229, the same on the old
binary), TestBorrowedOffLevelIsNotAdvertised and
TestAsksOwnBackendAgreesWithTheGatewayDispatch, which read ../catalog
and ../gateway that weren't copied there.

Rebased onto origin/main 3d3a834d6 (30 files, none of them these):
go vet ./internal/provider for darwin, linux (nogui) and windows, and
go test ./internal/provider in the sandbox HOME, ok.

Not tried: a real Codex refresh against OpenAI (the change is only the
write; the refresh request is unchanged), and a real power cut.
2026-10-15 02:47:23 +08:00
EdwinDigital 595b9a25bc gateway: WorkBuddy's own X-Conversation-ID names its session, so Routing groups its requests by conversation, not under No session ID (#2236, EdwinDigital)
WorkBuddy and CodeBuddy name their conversation in X-Conversation-ID,
which sessionHeaders didn't list, so every WorkBuddy request had no
session: Routing put them all under "No session ID", and affinity, usage,
transcripts, OTel and a remote magpie lost the conversation too. The header
is appended last, so the aliases already read keep precedence, and the
vendor is never sent it.

Moved users are covered by the same line: the gateway gives a plugin the
session as ConversationHeader from conversationID(), plugins.go passes it
as FetchRequest.Session, and the WorkBuddy plugin derives its own
X-Conversation-ID from that. No plugin change is needed.

EdwinDigital's record (Windows ARM64, Go 1.26.8, temporary HOME):
- Removing only the alias makes TestWorkBuddySessionHeader,
  TestWorkBuddySessionThroughGateway and TestRemoteMagpieKeepsTheSession
  fail. They pass with -count=20.
- gofmt and git diff --check are clean. Windows go vet ./... and Linux
  ARM64 go vet -tags nogui ./... pass.
- Installed WorkBuddy 5.8.2 (engine 2.161.0) ran against the patched
  gateway and a loopback streaming mock. Two native sessions grouped 2+1,
  with both titles resolved.

Review and run at this head (macOS, Go private cache, sandbox HOME):
- I read the patch line by line.
- The three tests pass. Commenting out the alias by hand makes all three
  fail.
- gofmt -l is clean. go vet passes on darwin, linux -tags nogui and
  windows.
- go test -tags nogui -count=1 -timeout 40m ./internal/gateway/: ok (811s).

Not tried by me: a real WorkBuddy or CodeBuddy client, and real vendor
calls. EdwinDigital ran WorkBuddy against a mock.
2026-10-15 02:36:26 +08:00
yetone 3d3a834d62 gateway: a held key its owner lets see quotas is told those of the providers and accounts it may use, not none (#2216, Kenoia)
#1981 refused every quota route to a gateway key held to a budget, models
or accounts, so a Remote magpie set up with such a key showed none of the
providers it may use. A key's owner can now let it be told them:
access.Key.Quotas, set from the key's new "Quotas" badge on the Gateway
page or `magpie gateway-key quotas <id> on|off`. Off stays the default,
so #1981's answer is unchanged for every key until its owner says so.

With it on, /v1/magpie/quotas (and ?kept=1), /quotas/history,
/quotas/cards and POST /quotas/refresh go through scopeQuotas
(internal/gateway/quotas_scope.go):
- a provider is told only when the key may use every model the catalog
  lists of it: a key with some of a provider's models is told nothing of
  it, since the models it may not use spend the same quota;
- of those, only cards of accounts and keys AllowsAccount lets it use,
  matched by the card's User against AccountIDs (a name two accounts
  share needs both; a card no account is known by only where the key's
  list names none of that provider's); a provider's only key's card,
  named by no one, is that key's;
- cards read from another magpie (From) are never told;
- a refresh of a card outside the scope is 403 gateway_key_held, one
  naming no card reads again only the scope's cards, not ReadAllCards;
- a scope with no card answers the cards routes 403 gateway_key_held, so
  the remote shows the key's own card rather than "nothing read".
/v1/magpie/concurrency and /v1/magpie/usage still refuse a held key.

Run at the reviewed head:
- gofmt -l: clean; go vet ./... (darwin), GOOS=linux -tags nogui,
  GOOS=windows: clean.
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, after the
  rebase onto 7be68467f (#2227's several limits; conflicts in access,
  the CLI usage and test, keys.js and providers-accounts.md resolved by
  keeping both): every package ok but internal/gateway, whose
  TestTranslatedSilenceStillTimesOut went red once at load ~95 (its
  400ms deadline also covers the response headers; filed #2248) and
  passed 5 of 5 alone. Before the rebase the whole suite was ok, with
  agent and gateway rerun at -timeout 40m after the 10m timeout under
  load.
- TestHeldKeyToldItsOwnQuotas (new): a provider-wide key sees A only,
  a key with A/m1 sees nothing of A, an account-held key sees only its
  key's card, a provider's only key, a key told nothing gets 403 from
  the cards route, Quotas-off still 403 everywhere, refreshes outside
  the scope 403. Broken by hand, each red: scope returned nil (every
  card told), every[id] forced true (partial models), the account check
  skipped, the refresh check removed, the only-key rule removed, and the
  told-none 403 removed. TestHeldKeyToldNoAccounts (#1981) still green.
- TestRemoteMagpieShowsHeldKeyItsQuotas (new): a magpie with this one as
  its Remote magpie provider, through a key held to alpha's Two, shows
  office/alpha's Two card beside the key's own; a key told none shows its
  own card alone. Red with the told-none 403 removed ("nothing read on
  that magpie yet").
- TestGatewayKeyQuotasCLI (new): show, on, off, bad values refused.
- GUI: gateway-key-quotas.test.cjs (new) in chromium and webkit, at 1100
  and 420, in en, zh, zh-TW, ja, de: 20/20; red when the badge sends the
  value it already has.
- The badge is a gateway key row's: off, it folds to no width until the
  row is hovered (the row had no room left at 390px: gateway-connect-keys
  went red in en until it did), and on a phone it is shown like the
  row's other controls (phone-rows went red until its rule won).
- GUI, 119 files matching gateway|key|usage|quota|remote|i18n|caller|
  web-|phone|narrow, both engines, concurrency 2: 1349/1385. The reds
  besides phone-rows (since fixed, above): quota-count-wrap and
  quota-name-translated webkit (#2228), usage-agents-hide (#2211) and
  usage-fold chromium en/zh (#2163), each red alike on a fresh
  origin/main. gateway-key-quotas, gateway-connect-keys, phone-rows and
  gateway-key-groups rerun: 38/38; after the rebase every gateway-*,
  phone-rows and key-limit file, both engines: 210/210.

Not tried: a real Remote magpie against a second machine with a held key;
the GUI badge in the Linux and Windows apps.
2026-10-15 02:29:11 +08:00
yetone 8e8316ed2f provider, gui: a routing group's pickers offer OpenRouter's decision models only as the provider's picks say (coeo91 on Discord)
coeo91 picked two free OpenRouter models, and a new routing group's member
picker showed those two and then a run of others. Those were OpenRouter's
decision models (liquid/d1, pplx-decider, jev-latest and the rest of its
output_modalities=decisions list): Deciders() took decideModels() for a
provider that lists its decisions (OpenRouter, oMLX, MLX-Serve), Bailian,
a remote magpie or a plugin, whatever its picks, while the provider editor
draws the same models as unpicked chips.

OfferedDeciders is what a group's pickers offer: with picks saved, only
the picked decision models plus any a group already names as a member or
classifier (so a group made before reads the same); with no picks, every
one, as before. /api/groups' deciders (member and classifier pickers),
the templates and the TUI's member picker use it. Deciders() is
unchanged, so the gateway still lists every decision model to a remote
magpie (X-Magpie-Deciders) and RouteDecider still answers an unpicked one.
docs/subsystems/providers-accounts.md says which is which.

Run in a private GOCACHE and sandbox HOME:
- the new TestOpenRouterDecidersOfferedAsPicked passes; with the pick
  filter turned off by hand it fails ("chat models picked, offered:
  [pplx-decider-v1-27b liquid/d1 jev-latest]").
- go test ./internal/provider -run 'Decide|Decider|OpenRouter|Template|
  RemoteMagpie|Bailian|OMLX|Omlx|MLX': ok.
- go test -tags nogui ./...: every package ok except internal/library,
  which hit the 10m timeout with the machine at load ~150 (stacks in
  mcpauth flow.end sleeps; nothing here touches library). Rerun alone
  at the same load with -timeout 25m: ok in 252s, 285 tests passed, the
  slowest TestAgentMCPFiles at 33s, so the 10m was the whole suite's
  load on this box, not a hang.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows;
  GOOS=linux -tags nogui and GOOS=windows builds.

After rebasing on origin/main 924f62e90: provider, gui, tui ok; gateway
ok alone with -timeout 28m in 1129s at load ~100 (it hit the 10m default
beside the other three packages; it passed in the full run before).

Not run: the Playwright GUI suite. internal/gui/assets is unchanged and
those tests mock /api/groups, so they can't see this server-side list.
Not tried against the real OpenRouter API or in a running GUI; the fake
OpenRouter serves its real decision-list shape.
2026-10-15 02:00:44 +08:00
yetone f299faef48 gateway keys: a key holds several limits at once, every one must pass, and the 429 names the one that resets last (#2227, oxsean)
A key may now hold up to five limits, each in its own window (5 hours
and a week, say). A request needs every one: budget.Reserve checks
each, holds one reservation per window and settles each, and when some
are spent refuses with the spent limit that resets last, so
X-Magpie-Limit-Reset and Retry-After say when the key is really back.
Two limits in one window are refused (change that one instead).

Saved format: the first limit stays in "limit", which older magpie
reads, the rest go in "moreLimits". A file without moreLimits reads as
before.

- access: Change.Index adds (index = len), replaces (keeps its Since)
  or removes (nil) one limit; reset-limit-key with an index resets one,
  without resets all; the plain limit-key replaces all, as before.
- /v1/magpie/limit: "limit" is the binding one (what older clients
  read), "limits" is each. A remote key card shows a window per cap of
  each limit and falls back to "limit" from an older remote.
- CLI: magpie gateway-key limit <id> list | add <period> ... |
  remove <n> | reset [<n>]; the single-limit form still replaces all.
- GUI: the key's badge names the limit holding it most and "+N limit(s)",
  a line per limit under the row, and the editor has a tab per limit
  with Add a limit / Remove this limit. Strings in en, zh, zh-TW, ja, de.
- docs/reference.md and docs/subsystems/gateway-routing.md say so.

Run (worktree on e98440ae6, sandbox HOME):
- go test ./internal/access/ ./internal/budget/ ./internal/gateway/
  ./internal/cli/ ./internal/provider/ ./internal/gui/: all ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags=nogui, GOOS=windows
  on those packages: clean.
- GUI (Playwright 1.62.0) chromium and webkit: the new
  gateway-key-limits test (5 languages x 1100/420), gateway-key*,
  gateway-caller-keys, gateway-keys-off, gateway-own-key,
  gateway-connect-keys: 94/94; i18n-keys ok. quota-name-translated
  webkit en is red with HEAD's assets too, filed as #2228.
- Broken by hand, each went red: Reserve checking the first limit only;
  the refusal naming the first spent limit, not the latest reset; the
  endpoint without "limits"; every limit saved in moreLimits; duplicate
  windows allowed; the remote card ignoring "limits"; the CLI plain form
  adding instead of replacing; the GUI save without its index; the GUI
  badge taking the first limit.

Not tried: against a real remote magpie or real accounts. Known gaps:
two N-day cycle limits are both named "this cycle" on a remote card;
an older magpie that rewrites the keys file keeps only the first limit.
2026-10-15 01:54:28 +08:00
yetone 3c7ec4ba24 gui: Usage is a plugin's page, its code, markup and words in plugins/usage (P2)
P2 of docs/subsystems/plugin-runtime.md, the fourth page after Sessions,
Library and Routing, and the largest part of app.js.

- The Usage page's code (~3000 lines: the Overview's cards, the
  Requests ledger and heatmap, the Sessions tab, the Agents list) moves
  from app.js to assets/plugins/usage/page.js; its markup, index.html's
  <main id="view-usage">, is client.js's part html. app.js 25756 →
  22675 lines (1,355,376 → 1,198,239 bytes).
- page.js builds on app.js at the top level (its timers, ?view=usage's
  tab and filters), so it is the one plugin script that loads after
  app.js. index.html: kernel.js, the plugins' other scripts, app.js and
  the scripts beside it, each page.js, then start.js, which is app.js's
  old tail (magpie.start(), navHides, OPEN_VIEWS, the first page shown,
  load()), so the first page has its code. TestBuiltinClientsLoaded
  holds that order.
- Hooks: open loads it, refresh(again) is load()'s read of it, reload is
  Refresh now, costs redraws costs on a currency change, tab says the
  tab for focusQuotaCard. app.js calls those through magpie.call. The
  allowance cards, quotasOpened, panelQuotaFocus and panelUseFocus stay
  in app.js: the tray panel draws them too.
- plugins/usage: Essential, Requires window, no InUse. Off, its nav tab
  goes and so do the ways to it (data-feature="usage": the panel's Open
  Usage, Routing's View usage); show("usage") gives way to Agents; the
  panel's Allowances tab stays. builtins.test.cjs switches it off and
  checks each.
- The 173 strings only Usage says move to plugins/usage/i18n.js;
  i18n.js 15032 → 14344 lines. "{n}s" and
  "All sessions" stay: context.js says them too since #1591.
- context.js: with context.js now in before the first page is shown,
  the page's open and load()'s first refresh both reached loadContext,
  and the second drew "Reading…" again over the advice the first had
  just drawn, so its curves never played their entrance (context-tune,
  3 of 3 red). loadContext draws the waiting pane once for the same
  days. Its dead last line, which loaded the tab once context.js came
  in late, goes.
- context-window.test.cjs's "arrives after the state" becomes "loads at
  once though context.js is slow": start.js now waits for it.
  usage-stale-answer reads page.js beside app.js. quota-refresh-order
  (#1630) cut app.js at the period picker's comment, now in page.js; it
  ends at the next comment that stays (5 of 5; without keepRefreshedQuotas'
  call, 2 of 5 red).
- docs: plugin-runtime.md, gui-shell.md.

Run, at this tree on origin/main af27b70b4 (main's keepRefreshedQuotas
and quotaRefresh changes, #1630, stay in app.js beside loadQuotas: the
tray panel draws those cards too):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/pluginrt ./plugins/...: ok
  (-skip TestMainWindowCorners, #1936); gateway and usage as above.
- usage-card-refresh, quota-refresh-order, builtins, editor-picker-clicks,
  context-window, usage-stale-answer: Chromium and WebKit green.
- The full GUI set: see the Routing commit; every Usage red there is the
  same on main or red only under load.
2026-10-15 01:32:13 +08:00
yetone eb7199e120 gui: Routing is a plugin's page, its script, style and words in plugins/routing (P2)
P2 of docs/subsystems/plugin-runtime.md, the third page after Sessions
and Library.

- routing.js and routing.css move to assets/plugins/routing/ (client.js,
  routing.css). Its part's html is the page's head and boxes that were
  index.html's <main id="view-routing">; the rest is drawn by
  routingPage, run at mount since it builds on app.js. It keeps itself
  after that as it did (its own hidden, the language, focus), so its
  hooks are dirty and discard, a routing group being edited, which
  show() and the window's close ask through magpie.call:
  window.routingDirty and discardRouting are gone.
- plugins/routing: Essential, Requires window and gateway, in use while
  the user has a routing group (not Auto, not Hidden), since the page is
  where it is edited. The gateway routes the same with it off.
- With it off, what leads to the page goes too: the nav and panel tabs
  and the panel's section (data-feature="routing"), the guide's Open
  Routing, Providers' "Make a routing group of …", the Usage list's
  View routing and its time as a link, the context card's Latest
  request. A panel left on its Routing tab shows Agents.
- What other pages use of it stays on window: openRoute (context.js),
  kindName, swapWhy, routedWhy (Usage's Requests), newGroupWith
  (Providers), panelRoutingShown (the panel).
- The 505 strings only Routing says move from i18n.js to
  plugins/routing/i18n.js (4 languages); i18n.js 17048 → 15032 lines.
  The plugin's own name and line stay in i18n.js: the Plugins page
  says them with the plugin off (TestBuiltinsTranslated).
- Tests and comments that named routing.js name the new path (gateway's
  antigravity_rest and loop_guard, codeassist.go, usage.go,
  web_compress, group_member_info, assets_revalidate, font-cascade,
  win-fonts, three routing-*.test.cjs). builtins.test.cjs and
  builtins_test.go count seven built-ins and switch Routing off: its
  tabs go, the page shown stays.
- docs: plugin-runtime.md, gui-shell.md, gateway-routing.md.

Run, first on origin/main 3ec45e715, then after rebasing onto af27b70b4
(main's routing.js, css, app.js and i18n.js changes since were carried
into the moved files; its new Routing words, as the rules' conditions,
are in the plugin's i18n.js):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/gateway ./internal/usage
  ./internal/pluginrt ./plugins/...: ok (gateway 1800s under load,
  -timeout 45m; gui with -skip TestMainWindowCorners, #1936).
- All 193 GUI test files, 3 at a time at load ~250, Chromium and WebKit,
  at the Usage commit on 743fcc035: 185 and 186 green. Every red run
  alone here and on a just-fetched origin/main c524bc018:
  - the same on main: routing-model-rest (#2115), routing-wb-restricted
    (#1905), usage-agents-hide (11 of 16 in both, #2211), usage-fold
    (#2163: 12 of 14 here, 9 of 14 on main over 7 runs, the same 4px),
    quota-count-wrap and quota-name-translated in WebKit (#2228);
  - red only under load, green alone on both: routing-flood (#2215),
    routing-log-icons, usage-ledger (#2211), and three plugin-* files
    whose tree was rebased under them mid-run.
- days-fit, failed-open, side-calls and burst-speed, red on main after
  cf455ebd5, are fixed before this commit (#2134, d692b2548).
2026-10-15 01:32:12 +08:00
yetoneandXIQIXIQIXIQI b789bcc45d gateway, proc: magpie ends a Claude Code run with SIGTERM and a 5s grace before the kill, so its OAuth refresh lock is let go (#2195, XIQIXIQIXIQI)
subscriptionRun.abort killed Claude Code's process group with SIGKILL at
once. A Claude Code holding ~/.claude/.oauth_refresh.lock at that moment
can't run its exit cleanup, and the lock was left for the next requests to
fail on ("another Claude Code process is refreshing it or exited
mid-refresh").

proc.Tree.Stop(grace) sends SIGTERM to the leader alone, then ends the
tree once it has exited (Wait sweeps the group) or grace has passed
(Kill). A second Stop shares the first's grace. Windows has no such
signal and kills the job at once. abort uses it with stopGrace (5s); the
run still counts as ended at once, and abortAll, as the gateway stops,
waits for every tree. Other agents' trees keep Kill.

Run (macOS, sandbox HOME, pinned caches):
- the real Claude Code 2.1.299 (-p, stream-json in/out, as the bridge
  starts it) under a sandbox HOME/CLAUDE_CONFIG_DIR, no credentials:
  SIGTERM after 4s, it exited in 0.497s with 143.
- go test -race -count=20 -run TestTree ./internal/proc: ok
- go test -race -count=5 -run TestClaudeAbortAllowsLockCleanup
  ./internal/gateway (the reporter's test, trap set before the lock is
  made): ok
- broken by hand: abort back to t.Kill() -> TestClaudeAbortAllowsLockCleanup
  FAIL "Claude abort left refresh lock: <nil>"; Stop killing at once ->
  TestTreeStopLetsItCleanUp FAIL "the command's lock is left after Stop".
- on b9c589ebb plus these commits: gofmt -l (nothing), go vet ./... on
  darwin, GOOS=linux -tags nogui and GOOS=windows, go test -tags nogui ./...:
  every package ok but two filed load flakes, TestMaxRPMWaitsForRoomInTheMinute
  (#1791) and TestCopilotSecretToolUsername (#1627), on a machine at load
  ~200; each passed -count=3 alone.
- rebased onto e98440ae6 (27 more commits on main) and
  run again there: gofmt -l, go vet ./... (darwin, linux nogui, windows),
  go test -tags nogui ./internal/gateway ./internal/proc ./internal/agent.
- then onto af27b70b4 (9 commits; gateway routing.go/gateway.go and agent
  codex.go touched, not these lines): gofmt -l, go vet on the three OSes,
  and the tests named above plus the new remote-magpie and Codex ones.
Not tried: a real OAuth refresh interrupted mid-way (no Claude request was
made); Linux and Windows at runtime.

Co-authored-by: XIQIXIQIXIQI <75725040+XIQIXIQIXIQI@users.noreply.github.com>
2026-10-15 01:22:13 +08:00
yetoneandlidi1011 244a21d471 gateway: a structured-output answer a model wrapped in a code fence reaches the client as the JSON inside it (#2196, lidi1011)
Codex's background memory extraction asks for text.format json_schema and
parses the reply text as JSON. A translated model that answered
```json\n{...}\n``` failed it with "expected value at line 1 column 1".

A client that asked for structured output (a format field, or one told in
the system prompt: Request.FormatTold, set by inSystem) now gets the JSON
inside a single unlabelled or json-labelled fence when that is a complete
valid JSON value: streamed (fenceEncoder, which holds text only while it
could still be a fence and passes other text on at once) and whole
(unfencedResult in render). Invalid or truncated JSON, other languages,
text outside the fence and plain-text clients are left as they came.
Relayed (passthrough) replies stay byte for byte. Rebased onto #2126's
asObject/told format: inSystem keeps its told check and sets FormatTold.

lidi1011's patch from lidi1011/magpie fix/structured-output-code-fence
(e67b4ba7b, 8bc440bbb), taken as is apart from the format.go conflict.

Run (macOS, sandbox HOME, pinned caches):
- go test -tags nogui -run 'Fence|Format|Structured|JSON' ./internal/gateway: ok
- with the encoder and render hooks removed by hand,
  TestStructuredOutputFencedAnswerUnfenced (json_schema/json_object, whole
  and streamed) and TestStructuredOutputFenceAfterSystemFallback FAIL with
  text = "```json\n{...}\n```"; restored, they pass.
- on b9c589ebb plus these commits: gofmt -l (nothing), go vet ./... on
  darwin, GOOS=linux -tags nogui and GOOS=windows, go test -tags nogui ./...:
  every package ok but two filed load flakes, TestMaxRPMWaitsForRoomInTheMinute
  (#1791) and TestCopilotSecretToolUsername (#1627), on a machine at load
  ~200; each passed -count=3 alone.
- rebased onto e98440ae6 (27 more commits on main) and
  run again there: gofmt -l, go vet ./... (darwin, linux nogui, windows),
  go test -tags nogui ./internal/gateway ./internal/proc ./internal/agent.
- then onto af27b70b4 (9 commits; gateway routing.go/gateway.go and agent
  codex.go touched, not these lines): gofmt -l, go vet on the three OSes,
  and the tests named above plus the new remote-magpie and Codex ones.
Not tried: a real Codex memory run against a live model that fences its
JSON; a Gemini stream whose thoughtSignature lands mid-text flushes the
held text and is left fenced (falls back to today's behaviour).

Co-authored-by: lidi1011 <283302260+lidi1011@users.noreply.github.com>
2026-10-15 01:22:13 +08:00
yetone 27a0458de1 gateway: /v1/magpie/concurrency lists each request in flight, its agent, model, start and phase, for a status bar's hover (#2132, bigbitbox)
The concurrency read now carries `active` beside requests/waiting/tools:
one entry per agent request counted for Busy, oldest first, [] when idle:
id, agent, model and provider (once routed, from the routing trace),
session when the agent sends one, started and ms, route (the trace id),
and phase only where the gateway knows it: "slot" waiting in a key's or
account's queue, "rpm" waiting for room in the minute, "upstream" while a
try is out at the vendor. No prompt, reply or key. The entry lives on the
request's context from `counted` (so a GET, this poll included, is never
listed), routing ties it to its first route in trace.beginFor, and
lanes.take / rpms.wait / the try loop note the phase, putting the one
before back when they return. Access is the endpoint's: this machine,
another with a gateway key, never a held key (TestHeldKeyToldNoAccounts).
Nothing in routing or limits reads it.

Run (worktree on e98440ae6, sandbox HOME, GOCACHE pinned):
- TestConcurrencyListsEachRequest (new): one request out and one of the
  same agent waiting for a one-slot provider; checks agent, model,
  provider, session, phase upstream/slot, no prompt or key, [] idle and
  after. Broken by hand, each goes red: active left out ("active left
  out or null"), the slot phase removed ("never one out and one
  waiting"), noteRoute removed (model/provider empty), the upstream
  phase removed (phase "").
- go test -race -count=5 -run 'TestConcurrency|TestBusy|TestMaxConcurrency|TestMaxRPM|TestHeldKey' ./internal/gateway: ok
- go test -tags nogui ./internal/gateway (-timeout 28m; 1394s on a loaded
  machine, the default 10m timeout cut the first run short), ./internal/proc,
  ./internal/usageapi: ok
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  on ./internal/gateway: clean
Not run: the full `go test ./...` (disk tight), a real SketchyBar hover;
no GUI change.
2026-10-15 01:13:18 +08:00
yetone d2d94917a6 provider: a Claude allowance heard as Claude Code answered is on the cards a Remote magpie is told, not "nothing read" (#2206, SuInk)
NoteClaudeLimits keeps the windows a Claude answer tells in claudeUsage
and drops the account's LoginUsage reading (StaleAllowance), while the
cards another magpie is told (CachedCards → withAccountReadings) were
built from loginUsageCache and quotas.json only. On a `magpie serve`
that only requests reach, the latest (often the only) Claude reading
was a header, so the remote's Claude card went missing or stale until
its refresh ran LoginUsage.

- claudeUsageEntry gets heardSeq, taken from quotaReadSequence when a
  header is noted: in the same order readings are (readSeq, which is
  taken when a read starts).
- withHeardClaude lays the kept windows on the Claude account's card
  when they were heard after the card's reading started; a reading
  started after the header stands. An account with no card and no
  reading gets one from the header (Plan from its login).
- A /usage run writes a fresh entry (heardSeq 0), so its own reading,
  carried by the card read that ran it, stands.
- docs/subsystems/providers-accounts.md: the allowance row says so.

Run (sandbox HOME, private GOCACHE):
- TestCachedCardsTellHeardClaudeLimits (new, from SuInk's repro): a
  header with no reading gives a card at 42%; a reading started before
  the header (10%) doesn't replace it; one started after (55%) does; a
  later header (60%) wins again. Red without the cards_kept.go change
  ("no Claude card"); with the seq comparison removed it fails "a
  reading started after the header: used 42, want 55".
- go test -tags nogui ./internal/provider -run
  'TestCachedCardsTellHeardClaudeLimits|TestCachedCards|Claude': ok.

Run on the stack of #2204, #2208, #2206 and #2201 on 743fcc035 (the
same trees as pushed), sandbox HOME, private GOCACHE, go1.26.8:
- gofmt -l on the changed Go files: clean. go vet ./... on darwin,
  GOOS=linux -tags nogui and GOOS=windows: clean. go build . on all
  three: ok.
- go test -tags nogui ./...: 51 packages ok; internal/agent and
  internal/gateway hit the 10m default timeout at load ~200 (#2191).
  Rerun with -timeout 60m: agent ok (1205s); gateway ok but
  TestOTelFastRequestTranscriptDiscovery/true (#1811, the 50ms session
  window under load), which passes alone -count=3.
- go test -race -tags nogui ./internal/gateway -run
  'TestRemoteMagpie|TestVerify' and ./internal/provider -run
  'TestCachedCards': ok.

Not tried: a real Remote magpie pair with a real Claude account (no
Claude API calls are made with a user's token here).
2026-10-15 00:54:00 +08:00