Commit Graph
1701 Commits
Author SHA1 Message Date
yetone db87e014f2 gateway: /v1/magpie/native/<provider>/<path> passes Ark's own images and video-task API on
axelburks on Discord asked for a way to reach what the OpenAI-shaped
routes can't carry: Ark's image stream, its task list and cancel, a
field newer than magpie. A coordinator asked for it to stay behind the
gateway's key and auth like every route, and for the design to be said.

Decided:
- One route, /v1/magpie/native/{provider}/{path...} (POST, GET, DELETE),
  for Volcengine Ark only (isArk, not a remote magpie), at the paths it
  makes images and videos at: POST images/generations; POST/GET
  contents/generations/tasks (with Ark's query); GET/DELETE
  contents/generations/tasks/<id> (nativeArkPath). Never Ark's chat,
  whose routing, usage and masking are the chat routes'. Another
  provider or path is a 404 that says what is served.
- Behind every guard a /v1 route has (a key beyond loopback, corsGuard,
  the key's rate), and refused to a read-only key (readOnlyRefused).
- Refused (403) to a key held to models, accounts or a spend limit, or
  issued by one (nativeHeld): a poll or a cancel can't be tied to a
  model, and magpie prices no answer it doesn't read, so it couldn't
  hold such a key to them. Such keys use /v1/images/generations and
  /v1/videos, which now pass the vendor's own fields on.
- A model the user switched off is refused. The body's strings are
  masked (fails closed) and put back in the answer (restoring); numbers
  go exact (UseNumber, a 17-digit seed is kept).
- Signed with the provider's key and magpie's User-Agent; no caller
  header goes on but Accept. The answer comes back as it came, an event
  stream flushed as it arrives.
- Each request is a Requests row and a usage record (Operation
  "native", no tokens).

Tests: TestNativeArkRoute (the stream, the task list's query and a
cancel reach Ark signed with the provider's key, the body as sent; chat,
a wrong method, a deeper path, another provider, an unknown one and
every held key are refused without Ark being asked),
TestNativeArkStreamsAsItComes (the first event reaches the caller while
Ark holds the rest), TestReadOnlyKeyEveryRoute (the three patterns in
readOnlyRefused). Docs: gateway-routing.md's native route section.

Run on mote at the head of this stack (the Ark video fields, the native
route and the Ark image fields, three commits on af9ac3d25):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/gui
  ./internal/access: gateway and access ok; gui red only in
  TestMainWindowCorners/macOS_26_SDK (#3949, red on main).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. gofmt -l: nothing.
- No GUI file or script changes in this stack, so no GUI run.
The commits between were not run on their own at this base.

Broken by hand, each red, then put back:
- nativeHeld skipped: TestNativeArkRoute red
- an issuer's hold not read: TestNativeArkRoute red
- nativeArkPath skipped: TestNativeArkRoute red
- isArk not checked: TestNativeArkRoute red
- no flush: TestNativeArkStreamsAsItComes red (its 30s bound)
- the DELETE pattern out of readOnlyRefused: TestReadOnlyKeyEveryRoute red

Not tried: no real Ark request through the route (it would spend money);
Ark's answers are a fake shaped from its docs.

Credit: axelburks on Discord.
2026-11-03 18:46:54 +08:00
yetone b2034c1bcf gateway: an Ark video keeps the caller's content, ratio and own fields, and answers Ark's
axelburks on Discord listed what /v1/videos did to a Seedance request
against Ark's own API (docs 82379/1520757 create, 1521309 query). Each
item checked against those docs and video.go; the real ones:

- A caller's content was overwritten. volcengineVideoBody built content
  from the prompt and OpenAI's image fields and set it over the caller's,
  so reference_video, reference_audio and draft_task items were lost.
  Now a content sent is Ark's own and kept whole; the prompt goes first
  only when it has no text item, OpenAI's image fields after it.
- Image-to-video needed a prompt; asset:// and seconds -1 were refused.
  Ark's image-to-video takes no prompt, its asset library's asset://
  ids are images, and duration -1 lets the model choose. Now the prompt
  is optional with an image or a content, asset:// is kept as it is, and
  -1 goes as -1. These three are Ark's alone: arkOnly turns them away
  with a 400 before another vendor (MiniMax, Grok, an OpenAI-compatible
  one) is asked.
- size overrode an explicit ratio/resolution, and its mapping was wrong.
  size went through to ratio and resolution after the caller's own were
  copied, so ratio "adaptive" was lost; its resolutions stopped at 1080p
  and its ratios were Grok's, without 21:9 (3840x2160 went as 1080p). Now a ratio, resolution
  or duration the caller sends is never overridden; size is the nearest
  of Ark's tiers by pixels (480p, 720p, 1080p, 4k) and of Ark's
  ratios (arkVideoSize).
- Every string field, a JSON body's too, was read as JSON when it parsed
  as a bool or a number, and nothing else was: a form's tools stayed the
  string "[{...}]", and safety_identifier "12345" became 12345. Now only a
  multipart form's values are parsed (formValue), and Ark's text fields
  (arkTextFields: safety_identifier, callback_url, service_tier, ratio, …) stay strings. A
  JSON body's values keep their JSON types.
- The query answer dropped Ark's extras. Now every field of Ark's task
  that OpenAI's video object doesn't have (content.last_frame_url, usage,
  resolution, ratio, framespersecond, seed, tools, output_format, …) is
  passed on as it came (videoState.Ark, all but arkOwnFields).
- A MOV was served as mp4. /content now reads the ftyp brand ("qt  " is
  video/quicktime), then the vendor's video/* type, then Ark's
  output_format; mp4 only when none says otherwise (videoType).
- The expired message was wrong: Ark's expired is a task that ran past
  its execution_expires_after (48h by default) unfinished, not a link
  that expired. It now says so.
Not real: watermark is not forced on videos (it went as sent already).

Tests (internal/gateway/ark_video_fields_test.go):
TestArkVideoKeepsCallersContent, TestArkVideoFromImageNeedsNoPrompt,
TestOnlyArkTakesItsOwnVideoAsks, TestArkVideoSize,
TestArkVideoFieldTypes, TestArkVideoAnswersItsOwnFields, TestVideoType.
Docs: gateway-routing.md's Ark video paragraph and /content row.

Run on mote at the head of this stack (the Ark video fields, the native
route and the Ark image fields, three commits on af9ac3d25):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/gui
  ./internal/access: gateway and access ok; gui red only in
  TestMainWindowCorners/macOS_26_SDK (#3949, red on main).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. gofmt -l: nothing.
- No GUI file or script changes in this stack, so no GUI run.
The commits between were not run on their own at this base.

Broken by hand, each red, then put back:
- the caller's content not read: TestArkVideoKeepsCallersContent red
- the prompt required with an image: TestArkVideoFromImageNeedsNoPrompt red
- arkOnly skipped: TestOnlyArkTakesItsOwnVideoAsks red
- size overriding a named ratio: TestArkVideoSize red
- Grok's ratios in place of Ark's: TestArkVideoSize red
- Ark's text fields parsed as JSON: TestArkVideoFieldTypes red
- a JSON body's values parsed as a form's: TestArkVideoFieldTypes red
- Ark's extra fields not copied: TestArkVideoAnswersItsOwnFields red
- the old expired wording: TestArkVideoAnswersItsOwnFields red
- a MOV served as mp4: TestVideoType red

Not tried: no real Ark video was made (no money spent); the request and
answer shapes are from Ark's docs, on a fake Ark.

Credit: axelburks on Discord.
2026-11-03 18:46:54 +08:00
yetone af9ac3d25d gateway: /v1/models lists image and video models when ?kind= asks for them, chat models alone by default
axelburks on Discord asked that /v1/models return the image and video
models too, so a client can find them. It listed chat models alone, with
no way to ask for the others.

Decided: they are listed only when asked for, with ?kind=image,video
(or ?kind=chat,image,video, or ?kind=all), each row marked "kind":
"image" or "kind": "video". Without ?kind= the list is the same chat
list as before. Why not add them by default:
- Agents and clients offer every id this list gives as a model to chat
  with: OpenCode's and Cherry Studio's model lists, ZCode's and others'
  pasted ?format=text. An image or video id there would sit in their chat
  pickers and fail on the first message (an image model on
  /v1/chat/completions).
- OpenAI's own list mixes gpt-image and sora in with nothing to tell them
  apart, so a client has no field it would already read to skip them.
- magpie's own callers that want them already ask (another magpie's
  drawers header, kind=image/video/decision on the MCP list); ?kind=
  gives any other client the same.
An unknown kind is a 400 that names the kinds, not read as none. A
gateway key held to models or accounts sees only its own image and video
models, as on the chat list (drawerObjects/videomakerObjects already
check modelAllowed and accountServes). Unticked image and video models
(HiddenDrawers, HiddenVideomakers) are left out.

TestModelsListMediaOnlyWhenAsked: the default list and ?kind=chat have no
image or video row (so no agent's chat picker that reads it can offer
one), ?format=text likewise; ?kind=image / video / image,video / all give
them, marked; a bad kind is 400.

Docs: docs/integrating.md, providers-accounts.md, site docs (en, zh).

Run on mote, this change rebased on f4c664a09:
- go test -count=1 -timeout 45m ./internal/catalog ./internal/provider
  ./internal/gateway ./internal/gui: catalog, provider and gateway ok;
  gui red only in TestMainWindowCorners/macOS_26_SDK (#3949, red on main).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean. gofmt -l: nothing.
- GUI: the 51 provider-*, drawers, image-models, i18n and
  video-models-hide files, both engines, every language, wide and narrow:
  1161 of 1188 ok. The 27 reds are 5 files that are red the same 27 at
  origin/main d1cdce130 run alone: provider-fetch-again (#3292/#5057),
  provider-models-rest (#4396), provider-picks-stay (#4397),
  provider-levels-scroll (#4395), provider-typed (#4673).
  video-models-hide: 22 of 22 ok.
- The whole GUI suite (all files) ran earlier at this change on 8af751987,
  347 of 19153 red at load 100 to 200; the 66 files with a red, run again
  alone, are red in the same tests at origin/main 17f2387e1 (all filed:
  #4388, #4391, #4398, #4320, #4541/#5013, #2564, #4244, #4304 and the
  above).
Rebased again onto d1cdce130 (sessions, Cursor mover, library and routing
plugins, group-unlists; nothing this change touches but gateway.go,
which merged clean) and run there: TestCoreScriptBudget and internal/gui's
new tests, the gateway's ?kind= and video tests, internal/provider and
internal/catalog, video-models-hide 22 of 22: ok.

Broken by hand, each red, then put back:
- listKinds' default returning all three kinds:
  TestModelsListMediaOnlyWhenAsked red
- an unknown kind let through: TestModelsListMediaOnlyWhenAsked red

Not tried: no real client was pointed at ?kind=; the agents' pickers were
checked by what they read (the default list, unchanged), not by opening
each one.

Credit: axelburks on Discord.
2026-11-03 18:34:19 +08:00
yetone 92d2ed74f9 providers: an Ark key's Seedance models are under Video models in its editor, each to tick
axelburks on Discord: "供应商里方舟的配置页,有图像模型选项能勾选模型,但是没
有视频模型选项不能勾选视频模型". A Volcengine Ark key's editor listed its
Seedream models under Image models, to tick, and had its Seedance models
among the chat models or nowhere.

Cause, two parts:
- The editor had no video section at all: video models had no list and no
  hidden set (gateway-routing.md said "Video models aren't listed in the
  editor, so there is nothing to hide there").
- catalog's live parse read only "kind" and modalities.input/output. Ark's
  /api/v3/models marks no kind: it says domain "VideoGeneration" /
  "ImageGeneration" and modalities.input_modalities/output_modalities. So
  Seedance came back as a chat model, and 3D models (output 3d, no text)
  as chat models too.

Change:
- catalog: a live row with no kind is a video model when its domain is
  VideoGeneration or it outputs video without text, an image model for
  ImageGeneration or image without text; Ark's input_modalities /
  output_modalities are read when input/output aren't there, so a model
  that gives no text (Ark's 3D) is left out of the chat list.
  TestFetchArkMarksVideoModels runs on a captured Ark list
  (testdata/volcengine-ark-models-2026-11-03.json, fetched read-only
  with GET /api/v3/models, no key in it).
- provider: HiddenVideomakers beside HiddenDrawers, VideomakerHidden.
- gateway: VideomakersOf (Videomakers on a given list, for the editor),
  OfferedVideomakers = Videomakers less the unticked ones, read by
  AutoVideomaker, videomakerObjects (another magpie's list) and
  mediaModels(true) (generate_video). A hidden one still makes its video
  when named: bareVideomaker, videosCreate and arkFilms read Videomakers.
- gui: the editor's Video models section (renderVideomakers), filmIds and
  hiddenVideomakers on /api/providers, kept on save as hiddenDrawers is;
  i18n for every language. app.js comments cut to stay under
  TestCoreScriptBudget, which this change reached; no raise.
- docs: gateway-routing.md's Hidden image models section.

Old data: an Ark list fetched before keeps Seedance among its chat models
until its list is fetched again;
customVideomakers already counts any Seedance id an Ark key lists or picks
as a video model, so it makes videos and shows under Video models now.

Run on mote, this change and the next (/v1/models ?kind=, gateway and
docs only) rebased on f4c664a09; this commit's own tree, on 17f2387e1,
gave the same Go results with Linux and Windows vet of ./internal/...
clean:
- go test -count=1 -timeout 45m ./internal/catalog ./internal/provider
  ./internal/gateway ./internal/gui: catalog, provider and gateway ok;
  gui red only in TestMainWindowCorners/macOS_26_SDK (#3949, red on main).
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean. gofmt -l: nothing.
- GUI (at the next commit's tree, which adds no GUI file or script): the 51 provider-*, drawers, image-models, i18n and
  video-models-hide files, both engines, every language, wide and narrow:
  1161 of 1188 ok. The 27 reds are 5 files that are red the same 27 at
  origin/main d1cdce130 run alone: provider-fetch-again (#3292/#5057),
  provider-models-rest (#4396), provider-picks-stay (#4397),
  provider-levels-scroll (#4395), provider-typed (#4673).
  video-models-hide: 22 of 22 ok.
- The whole GUI suite (all files) ran earlier at this change on 8af751987,
  347 of 19153 red at load 100 to 200; the 66 files with a red, run again
  alone, are red in the same tests at origin/main 17f2387e1 (all filed:
  #4388, #4391, #4398, #4320, #4541/#5013, #2564, #4244, #4304 and the
  above).
Rebased again onto d1cdce130 (sessions, Cursor mover, library and routing
plugins, group-unlists; nothing this change touches but gateway.go,
which merged clean) and run there: TestCoreScriptBudget and internal/gui's
new tests, the gateway's ?kind= and video tests, internal/provider and
internal/catalog, video-models-hide 22 of 22: ok.

Broken by hand, each red, then put back:
- the domain/output check in catalog's live parse:
  TestFetchArkMarksVideoModels red
- OfferedVideomakers returning Videomakers whole:
  TestHiddenVideomakerLeavesListsButStillFilms red
- the editor's filmIds left empty: TestVideoModelsHidden red
- a save without hiddenVideomakers dropping the old ones:
  TestVideoModelsHidden red
- renderVideomakers' call in the editor left out: video-models-hide
  22 of 22 red
- a chip's click not changing the draft: video-models-hide 22 of 22 red

Not tried: no real Ark video was made (no money spent); the list parse was
checked on a real Ark list fetched read-only. The editor was not opened in
the real app, only in the GUI tests' fake API.

Credit: axelburks on Discord.
2026-11-03 18:34:19 +08:00
yetone d1cdce1302 provider: the group alone keeps subscription models out of agents' lists (shaoyang.)
shaoyang. on Discord (#general, 11-03): with a routing group's Model
lists set to the group alone (its card's 成员模型不单独列出), the model
list fetched still had every model of the group.

Cause: 88e6fb9cf (v0.1.2176, 10-30) had catalogOf keep a signed-in
subscription's models (SubscriptionKept: a ChatGPT, Claude, Copilot or
plugin account's) for every agent, leaving the group alone only for a
client that is no agent (""). Over HTTP no client is "": agentOf falls
back to usage.AgentOf(User-Agent), which is "other" or the UA's name, so
every /v1/models fetch, every agent's written list and every picker
listed a subscription member beside the group. For a group made of
subscription models, as most are, the option changed nothing.

Fix: catalogOf gives every agent but Codex Catalog(), as before
88e6fb9cf; Codex keeps its ChatGPT sign-in's own models (CodexOwn,
a3ee00c05), which its app reaches on that sign-in. SubscriptionKept is
gone; Unlisted() and GroupKept() name subscription members again, so the
picker's "kept for routing groups" note and the provider editor's
"listed alone" line (3d063e34f) say where they went. The routing editor's
hint says Codex keeps its own, in en, zh, zh-TW, ja and de. Docs:
reference.md, gateway-routing.md.

Behaviour change for 士奇's case (88e6fb9cf): with "The group alone" on,
Hermes, WorkBuddy and the rest lose the group's subscription models
again; that is what the option says. Listing its models too keeps them beside
the group, which the new test checks.

Tests:
- gui TestGroupAloneKeepsSubscriptionModelsOutOfEveryAgentsList (replaces
  TestSubscriptionModelsStayInEveryAgentsListWithGroupOn): a sandbox
  ChatGPT sign-in's 5 models in a group listing alone. For every agent
  but Codex that lists the group, its Agents-page list, CatalogFor and
  model pickers leave them out; Unlisted names them; with "Its models
  too" hermes, workbuddy, claude and codex list them.
- gateway TestGroupAloneKeepsSubscriptionModelsOffAgentsModelList:
  GET /v1/models with no key, "magpie" and magpie-hermes/-claude/-opencode
  lists group/mine and not its members; /v1/models/{id} doesn't find one
  for Hermes; Codex's key lists and finds them; listed again with
  listed too.
- TestCodexOwnModelsListedOnlyThroughGroups again expects Claude Code not
  to list a group-alone member.

Run on mote at 3da80330a (rebased on origin/main c3593dc49): gofmt -l
clean; go vet (darwin -tags nogui, GOOS=linux -tags nogui at the base,
GOOS=windows) on provider, gateway, gui ok; go test -timeout 45m
internal/provider ok, internal/gui ok, internal/gateway -run
"TestGroup|TestCodex|TestUnlisted|TestModels|TestDesktop" ok. At the
base 40a287b21: internal/provider, gateway, gui and agent whole ok;
internal/cli red only in TestEveryRouteHasACommandOrIsNamed (GET
/api/context/reply, #5026, red on main since 0872bc2a0). GUI:
group-unlists (en/zh/zh-TW/ja/de, 1100 and 420px), unlisted-group-kept,
unlisted-models, agent-models-group-on, i18n-keys in chromium and webkit,
56 of 56.

Broken by hand: catalogOf back to SubscriptionKept with the new tests in
place; the gui test failed with 484 "the group alone" errors (codex/gpt-5.5
in claude's, claude-desktop's, claude-science's lists and pickers among
them) and the gateway test for every key, no key and "magpie" included.

Not tried: a real ChatGPT/Claude sign-in or the running app, and the
reporter's Docker deployment (same /v1/models path, no OS branch); which
agent fetched the list isn't known.
2026-11-03 18:23:13 +08:00
yetone 00098f12bf library: Magpie Browser's "which agents may use it" is a line of its own under its row
tao0194 on Discord (v0.1.2828, zh, panel-width window): in Library > MCP
servers the magpie-browser row showed the connected ask (green dot, the
question, a button per agent) inside the name's column, wrapped into a
narrow strip between the command and the row's Scope and agent chips,
three lines tall beside every other server's two.

browserAsk's element was appended to the row's .who. It is now the row's
own child: the row gets lib-asking while it shows, wraps, and the ask
takes a line under the name, command and chips, from the name's left
edge (the picture plus the row's gap, 37px, 38px in the window's rows)
to the row's right edge. The first line keeps the name, command and
chips as the other rows have them (.who flex-basis 0 above 560px). At
560px and under, where rows already wrap, a long command now ellipsizes
beside the row's picture instead of taking the name to a line of its
own under it; that was so for any server with a long command, and the
ask's left edge follows the name. docs/subsystems/library.md says where
the ask sits.

library-browser-ask.test.cjs now has three agents (Codex, Zed among
them) and a context7 row beside it, runs at 1100, 600, the panel's 440
and 360, and checks the ask starts under the first line, at the name's
left edge, reaches the chips' right edge, that the first line is as
tall as another server's, and that the name sits beside the picture.

Run (mote, Playwright 1.62.0, Chromium and WebKit, en/zh/zh-TW/ja/de):
- library-browser-ask.test.cjs on the old client.js/library.css: 42 of
  44 red (every layout subtest; the two not-connected/given ones pass).
  With the change: 44 of 44 green.
- The 84 GUI files that open the Library, name lib-row/lib-server or
  library.css, or check budgets and i18n keys: 1480 of 1480 ok, before
  the rebase onto c3593dc49 (no upstream change touches these files);
  library-browser-ask, i18n-keys and builtins again after it: 52 of 52
  ok. go test ./internal/gui at the rebased head: TestMainWindowCorners
  red only (an AppKit window test, the same on origin/main 78cd4e6dd,
  #3949); everything else ok.
Not tried: the real app's panel (WKWebView) with a connected extension;
the full GUI suite.
2026-11-03 18:21:58 +08:00
yetone f4c664a09c plugin, gui: magpie web ends its plugin hosts, waited for, before it runs the new version (#3285)
The second way acezan's 57 <defunct> magpie-bun (v0.1.2819, a Linux
systemd service, 47 hours) pile up: magpie web's restart to update
(AutoRestart) runs the new version with syscall.Exec in the same pid.
The running plugin host was the old image's child, and the old image's
host.read held the only Wait for it. After the exec nothing waits for
it, so it ends on stdin EOF and stays <defunct> under that pid, one per
restart to update. skygunner reproduced it and AAEE86 counted 22 zombies
for 23 images under one pid (#3285). With about a hundred releases a
day, an AutoRestart service makes about one a hour, as acezan's did.

- plugin.EndHosts (host.go) stops every host started and not yet
  reaped, including the retiring ones, waits until each one has been
  waited for, and refuses to start another (errHostsEnded). startOn
  starts the host and records it under one lock (live), so a host that
  starts during EndHosts isn't missed.
- Web.Wait calls it right before update.Reexec.

Run at 72bc741ef (on origin/main 40a287b21, after the previous commit):
- mote (macOS): gofmt -l clean; go vet ./internal/gui ./internal/plugin,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
  go test -count=1 -timeout 45m ./internal/plugin: ok; -run Web
  ./internal/gui: ok.
- WSL magpie-desktop (Linux): ./internal/plugin ok, including
  TestEndHostsLeavesNoChild and TestHostReapedWhileItsChildHoldsStdout
  with a real Bun host; -race -count=3 of both: ok; go vet -tags nogui
  and -run Web of ./internal/gui: ok.

Both commits were then rebased onto 0acba61a3, which changes only
app.js and plugin-checkin.test.cjs; no Go file these runs built moved,
and they were not run again there.

Broken by hand: EndHosts returning at once makes
TestEndHostsLeavesNoChild fail on Linux ("children left once EndHosts
returned: [16459 S bun]").

Not tried: a real magpie web restart to update (a downloaded update
exec'd in the same pid) on Linux. The test covers EndHosts, not the
exec. Not changed: anything else alive at the exec (pii's helper,
awake's caffeinate, #4188) still outlives it the same way.

Reported by acezan on Discord. Diagnosed in #3285 by skygunner and
AAEE86.
2026-11-03 17:58:31 +08:00
yetone a9a8f11e7f plugin, proc: a plugin host is waited for when it ends, not when its stdout does
acezan on Discord (v0.1.2819, Linux x86_64, a systemd service): after
47 hours, 57 <defunct> magpie-bun children of magpie, growing toward the
unit's TasksMax until a restart.

One cause: the plugin host's only cmd.Wait ran in host.read after its
stdout reached EOF. A program a plugin started that kept a copy of the
host's stdout (Bun.spawn given Bun.stdout, which host.js's spawn guard
doesn't catch, #5063; a daemon left behind) held that pipe open past the
host's end, so EOF never came, Wait never ran, the host was never marked
dead, and every host stopped (Restart, a moved proxy, hostStale) stayed a
zombie until magpie quit. Reproduced on Linux (WSL magpie-desktop,
Bun 1.4.2): one more Z-state bun under the test process per Restart,
1, 2, 3, 4 over four rounds. The other cause, magpie web's restart to
update leaving the running host behind its exec (#3285), is the next
commit.

- proc.Output (new, internal/proc/output.go) gives a command's stdout and
  stderr pipes of magpie's own and waits for the command the moment it
  ends. Its readers then have OutputGrace (2s) to read the last lines;
  the pipes are closed after that, which ends a read held up by a
  grandchild. startOn uses it, and a reap goroutine fails the host when
  its child ends. host.read no longer calls Wait. The tests' fake hosts
  (no child) keep cmd.Wait.
- Every other start that wasn't waited for now goes through
  proc.StartReaped (Start, then go cmd.Wait()). Process.Release doesn't
  reap on Unix: codexrelay.Start (a relay that can end while magpie
  runs), tui serveInBackground, uninstall's startAfter, update's
  runAfterExit and OpenBeside (no Wait at all), and Windows' Reexec.
- TestEveryStartedCommandIsWaited (internal/proc) parses every non-test
  .go file. In each function, an x.Start() on a command needs an
  x.Wait(), or x handed on (a call's argument, a struct field), and
  .Process.Release() is refused. It found exactly the sites above.
- docs/subsystems/provider-plugins.md says how the host is reaped.

Checked and left as they are (each waits): the StartTree callers
(provider/install, library mcp_run and mcp_check, gateway claude_warmup
and claude_subscription), pii/serve, provider grok and claude_signin,
claudetui child_unix and wslread, awake, every other bun start (bun.go,
bunupdate, store, dist use Output/CombinedOutput).

Run at 82460a2f9 (on origin/main 40a287b21):
- mote (macOS): gofmt -l clean; go vet on the touched packages,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
  go test -count=1 -timeout 45m ./internal/plugin ./internal/proc
  ./internal/codexrelay ./internal/tui ./internal/uninstall
  ./internal/update: all ok. -race -count=3 of the new proc tests: ok.
- WSL magpie-desktop (Linux): the same six packages ok, including
  TestHostReapedWhileItsChildHoldsStdout with a real Bun host; -race
  -count=3 of it and the Output tests: ok.
- Windows (xiaomi-gpu), at the tree before the rebase (base 5ee5274bd):
  proc and codexrelay ok. plugin and update had TestPiPackage,
  TestLoadConcurrentWithSavesAndEdits and TestPackagedByDpkg red; each
  fails the same at untouched origin/main 40a287b21 on that box, 3 of 3,
  and is filed (#4115, #1827, #4603).

Broken by hand, each red:
- host.go back to StdoutPipe with Wait only after EOF:
  TestHostReapedWhileItsChildHoldsStdout fails on Linux ("the host isn't
  marked ended 15s after Restart").
- Output.Start waiting for the readers before Wait:
  TestOutputWaitsPastWhatHoldsIt fails (not waited for in 10s).
- codexrelay back to Process.Release: TestEveryStartedCommandIsWaited
  names relay.go:89 and :92.

Not tried: a full go test ./... (mote and WSL were each running other
sessions' package runs, load 39 and 110); a real magpie serve or web
running for hours on Linux; the host test on macOS (no /proc; the
Output test runs there). Not changed: killing what a host left behind
(its process group) when it is stopped; an orphan like the sleep above
stays in the service's cgroup until it ends on its own.

Reported by acezan on Discord.
2026-11-03 17:58:31 +08:00
yetone 40a287b217 gateway: a quiet Claude Code run begins the reply and pings its client (#5043)
A streamed Claude subscription turn whose run says nothing for minutes
(the interactive mode tells a message only once it is whole; a long
conversation replayed to a new Claude Code is prefilled uncached first)
gave its client the held stream's 200 and comments, and those stop at
keepaliveLongest (5 min). Claude Code 2.1.316's byte watchdog then ended
the request 300s later, at 599s: the reporter's 599.29s and 599.33s.
Each cancel aborts the TUI run (letGo), so the retry is a new Claude Code
that replays the history and writes it to the cache again (#3808).

keepBridgeHeard wraps the run's events for a stream: after
bridgeHeardAfter (1 min) of a quiet run it sends an empty KStart, which
makes relay begin the reply (message_start), and a KAlive every
keepaliveEvery while it stays quiet, up to translatedQuietLongest, so the
client gets its protocol's pings (#2316's pattern). The hold still holds
the frames to holdLead and passes an error over. The run's own start
later adds its usage (collector), and a failure in the first minute is
still a status.

The gain is bounded. Claude Code 2.1.316 turns every 10s with bytes into
a ping of its own (RSr, __n=1e4) and counts 30 pings in a row (vSr=30),
so a stream of pings and comments alone ends 600s after its last other
event. The run now has until about 14 minutes (message_start at ~4 min
plus 600s), where it had 599s. The reporter's retries answered first at
385s and 527s.

Run:
- Real claude.exe 2.1.316 (-p, sandbox HOME, env -i) against a fake
  Anthropic server:
  - headers at 3s, comments to 300s: ended at 598.38s ("[byte-watchdog]
    ... no bytes for 300000ms"; "Stream idle timeout before first event").
  - comments forever: ended at ~600s from headers ("no chunks received
    for 300s").
  - no headers: "Request timed out" at 360s.
  - this fix's shape (message_start + ping at 300s, a ping every 60s):
    lasted to 904s, then "no chunks received for 300s" and fell back to
    non-streaming. That is the 600s bound above.
- mote-run: go test -tags nogui -count=1 -timeout 45m ./internal/gateway
  ok (675.8s), at this change before its comment-only edits.
- mote-run: go test -tags nogui -count=1 -timeout 45m ./internal/gateway
  ok (680.2s) again at this tree, rebased on origin/main 5ee5274bd.
- mote-run: TestClaudeBridgeQuietRunKeepsClientAlive -count=3 ok, and
  gofmt -l internal/gateway clean, at the committed tree.
- mote-run: GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/gateway ok.

Broken by hand:
- Without the keepBridgeHeard call, the new test fails: no
  message_start or ping before the reply.
- Without the synthetic KStart (KAlive alone), it fails with "0 pings
  while the run was quiet": the client gets comments only.

Not tried:
- A real Claude account, the interactive (TUI) mode, a real replay.
  The test uses a -p fake Claude Code. The wrapper doesn't depend on
  the mode.
- Chat and Responses clients through the bridge. Their encoders take an
  empty KStart, but no test covers it here.
- A run quiet for longer than ~14 min still ends. Only a real event of
  the reply would keep it alive (#5060).
- magpie's pingEvery comment in gateway.go describes 2.1.311's count
  without the synthetic pings. Not changed here.
2026-11-03 17:36:51 +08:00
yetone 9019ca88d6 gui: Scroll to top and Scroll to bottom move when the page under them changes, not only on a scroll (Jiabubu)
Jiabubu on Discord: with the capsule in sight, a click that opened a
Routing group left it over the editor's member rows (Remove beside Up
and Down) and its held Cancel and Add, and it moved off them only once
the page was scrolled.

scrollends.js placed the capsule on a scroll, a resize, focus or the
pointer leaving it, and a hidden attribute set anywhere. Opening a group
in place sets none, unless something else on the page happened to be
hidden again in the same draw (an empty pool list is, on every draw,
which is why the earlier tests saw it move). It now also watches the
open page and each of its own children with a ResizeObserver, and the
page's child list, so any change of size under it (a group opened or
closed, rows added or taken out) places it again on the next frame: it
rises above a held foot, steps aside at the page's foot, or comes back.
One file serves every page with the capsule (Agents, Providers, Routing,
Library, Settings, plugin pages), so they all take it. No core script
changed; scrollends.js loads lazily and has no budget.

view-ends-relayout.test.cjs: with no scroll after the change, the capsule
must be where the reader's next scroll puts it, and over nothing of the
editor's:
- Routing, 16 groups of the reporter's rows ("低-ultra", 922K), a pool in
  the list: a screen down, a click on the card lowest in sight opens its
  editor; then Cancel closes it.
- Agents, 40 rows: a little above the foot, a block at the list's end
  taken out so the foot comes up under the capsule.
Desktop 1100, 700, 560; browser page 1100, 440, 360; Chromium and WebKit,
en/zh/zh-TW/ja/de.

Run on mote (mote-run) at this tree:
- view-ends-relayout, both engines, every language: 10 of 10 ok.
- On 5ee5274bd (origin/main just fetched) plus this change:
  view-ends-relayout, view-ends, routing-editor-foot, old-webkit and
  i18n-keys: 62 of 62 ok.
- Before the rebase (on c0d4f17a3), with group-editor-selected,
  group-editor-fits, group-member-drag, drag-rows-shift, routing-rows-fit,
  click-scroll, add-button, library-discover-jump and account-eye beside
  those: 214 of 214 ok.

Broken by hand: scrollends.js as at origin/main, 20 of 20 red (both
engines, every language), each part on its own:
- Routing: "desktop 1100px: opened, the capsule above the held Cancel
  and Add, with no scroll: 569-624, bar from 591".
- Agents only: "desktop 1100px agents shorter: the capsule stepped aside
  as a scroll has it, with no scroll: [[true,569,624,1739],[false,...]]".

Not tried: the whole GUI suite. Both machines already had full suites of
other sessions running (WSL: four, at load ~140; mote: one, 49 minutes
in), and one full suite runs on a machine at a time. The capsule's
behaviour is the only change, no layout and no new API call. Also not
tried: the Windows app (WebView2) and the Linux app (WebKitGTK) themselves,
and the reporter's own groups.
2026-11-03 17:26:53 +08:00
yetone 900ae0fa51 backup, sync: sign-ins go too when picked, sealed, never over a later renewal
qianxunji (#feedback) and curtinp118 on Discord: a VPS restored from a
backup, or a new computer joining sync, had to sign in to every
subscription again. Sign-ins (subscription accounts in logins.json,
Codex's auth.json, plugins' sign-ins in plugin-auth.json) can now go too,
in each place only when picked; all are off by default, so an upgrade
carries nothing new.

- Sync (WebDAV, S3, GitHub): a "Sign-ins" tick in the form, with a line
  saying anyone with the passphrase and the server's file can use the
  accounts, and that an account on two computers can be signed out on one
  when the other renews it. CLI: `magpie webdav|s3|github set sign-ins=yes`.
- Export: "With the sign-ins", off; ticked, the passphrase hint says the
  file holds them. CLI: `magpie backup --sign-ins`.
- Import: "Bring in the sign-ins too, when the file has them", on. CLI:
  `magpie restore --no-sign-ins` leaves them out.
- Back up by itself: "Sign-ins in backups", Off/On. On asks for a
  passphrase (twice) that seals the sign-ins alone (the rest of an
  automatic backup stays unsealed, as before); it is kept in
  autobackup.json (0600), never sent in the view. A backup whose sign-ins
  another passphrase sealed restores without them and says so.

What goes (provider.CollectSignIns, plugin.CarriedAuth): magpie's own
copies only, not an agent's own account, an agent-home row, a hidden or
plugin: row, or a retired built-in. Each record is keyed by agent +
email + org (or the account key); ids two rows share go on neither side.

Restore/import (RestoreSignIns) adds what is missing and updates only
when the incoming copy was renewed later; nothing here is removed.
Before writing over a row it counts every row that could be the same
account (same login, same refresh token, same id): none adds, several
keeps all, one is kept when it isn't magpie's own copy, is held, or is
the agent's live account. Codex's auth.json is written temp-and-rename,
0600, only where Codex is signed out.

Sync merges per record against the last sync's hashes (MergeSignIns):
the later renewal wins; a removal crosses only when the other side still
had it as of the last sync; ApplySignIns re-checks each row's hash
before writing so a renewal in between is kept. A computer with the tick
off sends none, so others remove nothing for it; turning it off, a
Restore, or a replaced server file clears the last-sync record.

Export's and Import's forms moved out of app.js into syncfiles.js,
imported when one opens (as autobackup.js is), so the core is 3.2KB
under its budget with no raise (app.js 3.2KB smaller than before).

docs/subsystems/sync-backup.md has a "Sign-ins, when picked" section;
subscription_signin_test.go's header now says it pins the default.

Run at the pushed head (678d28cba on origin/main bc10a6198):
- wsl-run go test -tags nogui -timeout 45m: backup, davsync, plugin, gui
  ok (TestCoreScriptBudget in it). provider: one red,
  TestCancelledPluginSignInSavesNothing, the late sign-in saved after
  Cancel. It is green 20 of 20 alone, at this head and at origin/main
  alike, and this change adds only new files there whose tests run after
  it; filed as #5047. cli there hung in proc.lookStamp's os.Stat on WSL
  at load 100, so it ran again on mote: one red,
  TestEveryRouteHasACommandOrIsNamed (GET /api/context/reply, #5026),
  the same at origin/main. gateway -run TestCompactionOverByteCapEveryTime
  ok (#4862 on mote's full run). TestMainWindowCorners on mote: red the
  same at origin/main (#3949).
- GUI, on mote: the 16 files that open Sync, plus i18n-keys and
  old-webkit, Chromium and WebKit, every language: 255 of 294 pass. The 39
  reds are segs-press-redraw's searchAllRow (#4566), s3-sync in WebKit
  (#2448) and usage-agents-hide (#3414). The same files at origin/main
  bc10a6198 give the same 39 pass and 39 fail. sync-signins, auto-backup,
  sync-sign-in, i18n-keys and old-webkit alone on WSL: 92/92.
- The whole GUI suite on WSL, stopped at 737 of its tests (1162 files,
  load ~100 there): 9 reds, all WebKit, none in a Sync file:
  account-eye (#4244, #5052), add-button (#4792), account-plugin-user
  and agent-expand-steady. The last two pass at this head and at
  origin/main on mote. The rest of the suite was not run.
- gofmt -l: clean. go vet: darwin (internal/gui, internal/cli),
  GOOS=linux and GOOS=windows -tags nogui for backup, davsync, provider,
  plugin, cli, gui: ok.
- win-run and wsl-run: go test -tags nogui -run
  'SignIns|Carries|AutoBackupSignIns' ./internal/provider
  ./internal/backup ./internal/davsync: ok on Windows 11 and Ubuntu 24.04.
- sync-signins.test.cjs: 20/20, Chromium and WebKit, 1100 and 420px,
  en/zh/zh-TW/ja/de, no horizontal overflow, no page errors.

Then rebased on origin/main 5ee5274bd (12 commits; davsync.go, app.js and
i18n.js merged with no conflict) and run again at the pushed head on mote:
gofmt clean; go test -run 'TestCoreScriptBudget|SignIns|Carries|
AutoBackup|Sync' for gui, davsync, backup and provider: ok; sync-signins,
auto-backup, sync-sign-in, i18n-keys, old-webkit: 92/92.

Broken by hand, each red, then restored:
- RestoreSignIns writing an older token over a newer one:
  TestRestoreSignInsNeverWritesAnOlderTokenOver red.
- The ambiguous-account guard has two layers (more than one match, and
  a single match with another record id); with only the first removed
  the test stayed green, with both removed
  TestRestoreSignInsLeavesAnAmbiguousAccount went red.
- MergeSignIns removing a row renewed here: TestMergeSignInsRemovedOnlyWhenTheOtherSideRemovedIt
  red.
- Codex auth.json written over a signed-in Codex:
  TestRestoreSignInsSignsCodexInOnlyWhereSignedOut red.
- ApplySignIns not re-checking the hash: TestApplySignInsKeepsWhatChangedSinceTheMerge
  red.
- davsync forgetting the last-sync record (st.SignIns = nil):
  TestSyncSignIns red.
- GUI: Export's tick on by default, and auto backup's On posting with
  no passphrase: sync-signins.test.cjs red for each.

Not tried: real accounts carried to a real VPS or second computer (all
Go tests use testenv homes, fake DAV and fake tokens; the Keychain is
never reached); a real vendor's refresh after a carried sign-in, and how
each vendor treats one refresh token used from two machines; the CLI
flags against a sandbox HOME (covered by the cli package's tests only);
auto backup's sign-ins have no CLI switch.
2026-11-03 17:24:19 +08:00
yetone 5ee5274bd9 quotas: a remote magpie's Codex reset is used from its card here (#3850)
prgrmrwy runs magpie on a home server and uses it from work through a
remote magpie (and DSH). The remote Codex card said "1 reset", but the
reset could only be used from the GUI of the computer that holds the
sign-in.

What changed:
- Gateway: POST /v1/magpie/quotas/codex-reset?user=<email>[&credit=<id>]
  (Server.codexReset) spends one of that account's resets with
  provider.SpendCodexReset. That is the Usage page's own code
  (UseCodexResetCard, then AwaitAllowance), moved out of
  internal/gui/usage.go so both use it. A reset can't be undone, so the
  route needs an enabled gateway key with full access, from loopback too.
  No key gets 401, and that covers every corsGuard exemption that has no
  key: Origin null, app schemes, *.localhost and a missing Origin. A
  read-only key gets 403 gateway_key_read_only (readOnlyGuard, which
  readOnlyRefused now lists, and again in the handler). A held key gets
  403 gateway_key_held, even one told quotas. The account must be named
  (400 otherwise). One ask runs per account at a time (409). When the
  reset is used, that card is read again.
- Remote client: UseRemoteCodexReset (remote_quotas.go) asks the remote
  with the provider's key. remoteJSON's status mapping is shared through
  remoteBody. A read-only key there is told as such, and a 404 as a
  remote too old. With no answer in time it says the reset may have been
  used, and it never asks again by itself. A remote Codex card now keeps
  its Resets; a GLM team's (byWindow) and every check-in are still
  dropped.
- GUI: "Use a reset" / "Use one..." show on a remote Codex card
  (codexResetCard). They open the same in-app confirmation sheet, with a
  line saying which computer's magpie uses it, and send the card's
  provider to /api/usage/codex-reset. The remote's errors are put in the
  user's words. New strings are in all 5 languages.
- DSH: no code here. Its provider plugin reads /v1/magpie/quotas/cards
  and can call the new route with a full key.
- resetOutcome (a reset's result in words) moved from app.js into
  resetask.js, the only place that says it, so the core's scripts stay
  in TestCoreScriptBudget's 1,533,802 with no raise (1,533,003 after;
  origin/main b967b1620 is 1,533,756).
- Docs: reference.md (remote quotas, gateway keys), gateway-routing.md
  (read-only list, the route's admission), providers-accounts.md.

What was run (rebased on origin/main b967b1620, then on 2e4735f8f):
- mote, at the head before the rebase and the resetOutcome move:
  go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/gui at load ~300-450. provider ok. gateway: only
  TestCompactionOverByteCapEveryTime (#4862). gui: TestCoreScriptBudget
  (this change, 158 bytes over; fixed by the move), TestMainWindowCorners
  (#3949) and TestGatewaySkewOfAnotherIsSaidNotQuit/own_build (#5053,
  passes alone here and at b967b1620).
- mote, same run: 155 GUI files (reset|quota|usage-|panel-|i18n|budget|
  remote|gui-|old-webkit|core-script|script-size), 1856 of 1904 pass.
- WSL (magpie-desktop), the 9 red files alone, at this change and at
  origin/main b967b1620: this change 147 pass / 43 fail, main 146 / 44;
  every test red here is red on main too: codex-auto-reset webkit de
  (#4790), remote-magpie (#4398), usage-agents-hide (#3414), usage-fold
  (#3415, #4790), usage-heatmap (#4718), usage-ledger (#5048).
  codex-reset-lead (#5054) and panel-routing-providers (#5055) were red
  only under mote's load and pass alone on both.
- mote, at this head: TestCoreScriptBudget and
  TestGatewaySkewOfAnotherIsSaidNotQuit ok.
- WSL, at this head: account-every-reset, codex-resets-used, i18n-keys,
  providers-reset-use, remote-codex-reset, reset-each-title,
  reset-pick-card, reset-providers, quota-used-no-reset: 99 of 102 pass.
  The 3 reds are providers-reset-use's 420px Windows cases ("a click
  moved the page", #4873); that file alone is red on origin/main
  b967b1620 too (3 of 40 there, 2 of 40 here).
- WSL, rebased on 2e4735f8f (main had changed internal/gateway): the new
  tests and the read-only, CORS, LAN-guard, held-key, remote-magpie and
  UseCodexResetCard tests in ./internal/gateway ./internal/provider ok;
  core scripts 1,532,960 under 1,533,802; gofmt clean.
- Earlier on mote: TestCodexResetNeedsAFullKey,
  TestRemoteCodexResetThroughTheGateway, TestRemoteCodexResetAnswers, the
  read-only, CORS, LAN-guard, held-key and remote-magpie tests ok;
  remote-codex-reset and reset-pick-card 20 of 20 (chromium and webkit,
  5 languages, 900/390/440px). gofmt clean; go vet darwin, windows ok,
  linux for provider and gateway.

Broken by hand:
- With the handler's key check turned off, TestCodexResetNeedsAFullKey
  went red: "this computer, no key: 200 {code: reset}" and a reset was
  spent.
- With codexResetCard put back to provider === "codex",
  remote-codex-reset.test.cjs went red ("one Use, on the remote Codex
  card"). On the old code the route doesn't exist, so the full-key case
  gets 404.

Not tried:
- A real Codex reset spent between two real magpies: none was spent, to
  keep the owner's resets. The ChatGPT backend is the fake from
  codex_autoreset_test.
- DSH's plugin calling the route.
- GOOS=linux vet of internal/gui: it needs gtk4/webkitgtk, which neither
  mote nor magpie-desktop has. Its change is usage.go only, and that was
  vetted on darwin and windows.

Thanks to prgrmrwy for the report and the proposal.
2026-11-03 17:12:25 +08:00
yetone 69167bc299 usage: a reply let go under a second after a wait four times longer tells no speed
pluviophile714 on Discord: a gpt-6.1-sol row on Routing read 1,539
tok/s (input 21,617, output 392, first token 8.2 s, total 8.3 s), where
another monitor measures ~70. The reply came whole about 255 ms after an
8.2 s wait. Its content was spread over that short window (flow 230 ms),
so the HeldShare flow check passed, and so did the 100 ms floor, and
392/0.255 s read as 1,539 tok/s.

New rule, usage.HeldWindowMs: a window under 1,000 ms whose start
(first token, first text or first reasoning) is more than HeldShare (4)
times the window tells no speed. One rule in every place that computes
one:
- usage.DecodeOf: the Usage page's speed and totals, the CLI, the GUI's
  model speeds, and the gateway's Speed first pacing (noteTrySpeed);
- routing/client.js decodeOf: the Routing row's speed and its story line;
- usage/page.js ledDecode, plus a ledNoSpeed_ reason for the dash's
  tooltip, in en, zh, zh-TW, ja and de.
docs/reference.md and docs/subsystems/gateway-sessions.md say so.

On the owner's usage.jsonl (read only), 103 of the 106 rows over 600
tok/s were such windows (e.g. 448 tokens in 107 ms after 8.1 s) and are
dropped. The 3 that stay have windows of 2 to 5 s. The overall speed
goes from 103.8 to 97.9 tok/s.

What it costs: a short reply that really streamed after a long wait
tells no speed either. The live visible-reasoning fixture (76 tokens
over 731 ms after 6.8 s, ~104 tok/s) and #2637's grok record (307 tokens
403 ms after a 4.6 s first token, 531 tok/s) now read "—". Their tests
keep their guarantees with the same timings after a short wait, and also
check the long-wait case.

Tests:
- New: internal/usage TestShortWindowAfterLongWaitTellsNoSpeed (the
  reporter's numbers, a reasoned row from the ledger, the boundary, a
  second after a long wait, Totals) and internal/gateway
  TestShortWindowAfterLongWaitNotesNoPace.
- GUI: usage-speed-every-row has the reporter's row (dash, and the
  tooltip in all five languages); routing-burst-speed has it (first
  token 8.2 s, no tok/s).
- Updated to the new rule: TestVisibleReasoningSpeed's decode-minimum
  and max-speed cases (short wait now), TestCodexTurnMeasured...'s
  gateway/Claude rows, TestLiveVisibleReasoningFixture and
  TestUsageIngestTellsSpeed.

Run on mote at this tree (rebased on e41ef6288):
- go test -timeout 45m: internal/usage ok, internal/tui ok.
- internal/gateway: red only in TestCompactionOverByteCapEveryTime
  (#4862, full package run; passes 3 of 3 alone).
- internal/gui: red only in TestMainWindowCorners (#3949, macOS 27).
- internal/cli: red only in TestEveryRouteHasACommandOrIsNamed (#5026,
  red on main since 0872bc2a0).
- The two speed fixtures that failed in the gateway run pass on rerun.
- GUI, chromium and webkit: 36 files (every speed, ledger, i18n,
  routing-request and burst file), 609 tests, 603 pass. The 6 reds are
  usage-ledger's "newest live route needs no return-to-live button"
  (#5048, #4078, #3104 on main).
- Rebased on 1af868a15 (f0e0385a0 changed routing/client.js), then
  run again at the pushed head: internal/usage ok; the gateway speed
  tests (-run ...Speed|Pace|Decode|TTFT...) ok; 8 GUI files (both
  speed files, routing-request-metrics/-model, routing-speed-first,
  i18n-keys, reasoning-speed, usage-speed-tip) 94 of 94 in both engines.
- gofmt -l clean. GOOS=windows go vet of usage, gateway, gui and cli ok.
  GOOS=linux go vet of usage and gateway ok; gui and cli need cgo/GTK
  for Linux, the same on main.

Broken by hand: with the check off in usage.go, client.js and page.js,
the new Go tests, TestCodexTurnMeasured..., TestLiveVisibleReasoningFixture,
TestUsageIngestTellsSpeed and both GUI files (1537 tok/s shown) go red.

Not tried:
- the reporter's own request;
- a real GPT stream, to confirm that a 255 ms window after 8.2 s is a
  held reply from this vendor;
- the whole GUI suite (no new API call or layout change);
- the Linux and Windows app.
2026-11-03 17:01:51 +08:00
yetone d10f377657 providers: Names & levels is Names, prices & levels, where a model's own price at one provider is set (ferock4669)
ferock4669 asked on Discord whether magpie has a screen to price each
model, since one model can cost differently on each provider. It has:
each row in a provider's per-model list has a price box (input, output,
cache read, cache write, 1h cache write, long-context tier, $ / 1M
tokens), saved in settings' ModelPrices under pid/model. It wins over
the list price in Usage (usage.Pricer through provider.BasePriceIn) and
in a key's spend cap (usage.KeySpent through NewCoster). Nothing has to
be built; the button opening it said only "Names & levels", so nobody
finds a price there.

What changed:
- The button, its panel's heading and fold, and every note that sends
  the user there say "Names, prices & levels" (zh 名称、价格与推理档位,
  zh-TW 名稱、價格與推理檔位, ja 名前・価格・推論レベル, de "Namen,
  Preise & Stufen"); the gateway's vision and compaction notes, the
  provider package's text, the subsystem pages and the site's start
  docs (en, zh, ja) follow.
- The button's tooltip says it sets what each model costs at this
  provider; Usage's "estimated" tooltip says where a provider's own
  price is set and that it counts over the list price. Both in en, zh,
  zh-TW, ja and de.
- Not changed: the Codex model description text in internal/codexcat
  (it goes to Codex, so a vendor sees it) and core_budget_test's
  history comment.
- app.js: a comment above the price box is shortened so the core
  script stays under its budget, not raised (app.js 116 bytes under
  origin/main).

Run at the pushed head (rebased on origin/main 1af868a15), on mote:
- go test -run 'Budget|ModelPrice|ModelPref|Vision|Compaction'
  ./internal/gui ./internal/provider ./internal/gateway: ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
  ok (before the rebase, which touched no Go of this change).
- GUI, both engines, every language each file runs: the 149 files that
  name the label or open a provider's editor (before the rebase): 1191
  ok, 30 red in 7 files. Each of the 7 is red the same way alone at
  origin/main without this change: provider-fetch-again (#5057),
  provider-typed (#4673), provider-levels-scroll webkit (#4395),
  provider-picks-stay (#4397), usage-agents-hide (#3414), usage-ledger
  Requests (#5048), mobile-web (#3952, no .git in mote-run's copy).
  name-suffix-remote "chromium de" (ERR_NAME_NOT_RESOLVED once) passed
  alone at the head. After the rebase: model-price-edit, i18n-keys,
  name-suffix-remote, usage-ledger, usage-agents-hide again: go tests above ok; model-price-edit, i18n-keys and
  name-suffix-remote (all 10 cases) ok; usage-ledger Requests and
  usage-agents-hide red as at origin/main 1af868a15.
Broken by hand: model-price-edit.test.cjs at origin/main's label is red
in all 4 cases (the button "Names, prices & levels" is not found).
Not tried: the whole GUI suite (another session's full suite was on
mote, WSL at load ~100 with 31 test runners); the real app.
2026-11-03 17:00:38 +08:00
yetone 1af868a153 provider: a Codex app left on a used-up account restarts with Restart the app off too (atom0964)
v0.1.2826 (1dead5dc7) added Restart the Codex app when magpie switches
its account, off by default, so that atom0964's ChatGPT app stopped
relaunching at every switch magpie made between two Plus accounts. Its
guard in codexAppStep left the app-server running for every change
magpie made by itself, and that covered too much:

- the takeover in, where magpie becomes Codex's provider for its used-up
  account;
- the first look on a used-up account;
- magpie's switch off an account at 98% (SwitchWhenSpent).

The Codex app greys Send for every model while its signed-in account's
rate limit says not allowed, and reads the account only as its
app-server starts (ChatGPT.app 26.1013, 8b0132b3d). Left running, the
app stayed on the used-up account with Send grey, so neither magpie's
fallback nor the next account could serve it until the user restarted
it by hand. With the default off, that broke the takeover for every
user with a fallback.

Now those three restart the app-server tick or not (`needed` in
codexAppStep: `into || c.switched && c.spent`). The tick covers only
what the app works without: the switch back once the first account has
room, and Codex given its account back at the reset. The label, tooltip
and toasts say "switches its account back" in en, zh, zh-TW, ja and de.
The tooltip adds that a used-up account restarts the app anyway.
SwitchWhenSpent's stale-app log, RestartApp's comment and
agent-wiring.md say the same.

atom0964 will still see one restart when an account runs out. Send
needs it. The restarts at the switch back and at the reset are gone.

Run at the pushed head (on mote, rebased on c0d4f17a3):
- gofmt -l clean; GOOS=linux (-tags nogui) and GOOS=windows go vet of
  provider and gui clean.
- go test -count=1 -timeout 45m ./internal/provider ./internal/davsync
  ./internal/backup: ok. ./internal/gui -run "Budget|I18n|Restart": ok
  (the core script budget holds with the longer strings, no raise).
- GUI (chromium + webkit, narrow and wide, en/zh/ja/de): restart-app,
  switch-only, i18n-keys, codex-accounts-via: 76/76.

Broken by hand: codexAppStep's guard without `!needed`:
TestCodexAppLeftRunningForMagpiesOwnChanges ("magpie switched off the
used-up account: ended [], want [60]") and
TestCodexAppFirstLookOnAUsedUpAccountRestarts go red.

Not tried: a real ChatGPT desktop app on a real used-up account (the
app-server end is stubbed); Windows, where an end is followed by
CodexAppReopen.
2026-11-03 16:55:23 +08:00
yetone 1dead5dc7b provider: magpie's own Codex account switches leave the Codex app running unless Restart the app is ticked (atom0964)
atom0964 on Discord (#help) has two ChatGPT Plus accounts in magpie, with
Codex always signed in to the first and Only switch Codex's sign-in both
off, on Smart routing. The Codex desktop app kept restarting by itself.
They tried several combinations of the ticks and it still did.

Why: with both off, SwitchWhenSpent signs Codex in to the next account at
98% and back to the first below 90%. Each switch was noted for the Codex
app (codexAppSpentSwitch), and KeepCodexAppOnItsProvider ended its
app-server once no turn ran; the ChatGPT app shows that as an error and
relaunches (#4550). With Codex kept on the first account there is no
switch, but the used-up takeover (magpie made Codex's provider for a
used-up account and given back once it has room; f37742e14 only limits
it to when another account can serve, which two accounts always can)
changed Codex's route, and that ended it too. So every combination
restarted the app.

What changed:
- Provider.RestartApp (restartApp), off by default, set by
  provider/restartapp (SetRestartApp, Codex only). This computer's own,
  like KeepLogin: Mirror keeps it and davsync's hash leaves it out.
- switchLoginBy(agent, user, byMagpie): SwitchWhenSpent marks its
  switch magpie's own (codexApp.auto). In codexAppStep, a change that is
  magpie's own (its switch, the takeover in or out, the first look at an
  app on a used-up account) ends nothing unless RestartApp is on; it
  logs why and the app follows once restarted. The switch notice's
  Restart, the Agents row's Restart, and uninstall are unchanged.
- Still restarted: a switch the user makes (Switch, the Agents row, the
  CLI), a Connect or Disconnect, failover written or taken out (any
  route change while the takeover state is unchanged), and a user's
  switch pending when magpie's comes.
- GUI: under Codex's accounts, with more than one on (or the tick set),
  "Restart the Codex app when magpie switches its account", with a tip
  and toasts in en, zh, zh-TW, ja and de. app.js paid for it with five
  account-row comments cut; TestCoreScriptBudget is not raised.
- docs/subsystems/agent-wiring.md says which changes restart the app.

Known edge: a takeover flip in the same 3s tick as a Connect is taken
as the Connect's (restarted), since the route changed by the user.

Run at the pushed head (on mote, rebased on b967b1620; then rebased on 2a19043af, a Library change touching none of these files, with the core budget checked again: 160 bytes under):
- gofmt -l clean; GOOS=linux (-tags nogui) and GOOS=windows go vet of
  provider, gui, davsync clean.
- go test -count=1 -timeout 45m ./internal/provider ./internal/davsync
  ./internal/backup: ok. ./internal/gui: ok except
  TestMainWindowCorners/macOS_26_SDK, red alone on origin/main 694f4a6d6
  too (#3949). ./internal/cli: ok except TestEveryRouteHasACommandOrIsNamed
  on GET /api/context/reply (#5026).
- GUI (chromium + webkit, 1100 and 420 wide, en/zh/ja/de):
  restart-app (new), switch-only, claude-switch-only, keep-login,
  codex-accounts-via, account-arrange, i18n-keys: 110/110 and 94/94.
  account-arrange's webkit case went red once in a 5-file run on an
  aborted /api/lanes request; it passes alone on origin/main and at
  this head.

Broken by hand:
- codexAppStep's guard turned off: TestCodexAppLeftRunningForMagpiesOwnChanges
  and TestCodexAppFirstLookLeftRunning go red (ended [60]).
- SwitchWhenSpent marking its switch as the user's: TestCodexSwitchedWhenUsedUp
  goes red ("magpie's own switch is counted the user's").

Not tried: a real ChatGPT desktop app on a real used-up account (the
app-server end is stubbed as before); Windows, where the app is quit and
reopened (CodexAppReopen runs only after an end, so leaving it running
skips it too); no CLI command for the tick (switch-only has none either).
2026-11-03 16:34:30 +08:00
yetone 2a19043afc library: a skill's files are read as Markdown and edited in the page (refeccd)
refeccd on Discord kept skills in ~/.agents/skills, handed them over to
magpie ("let magpie manage"), and then had nowhere to edit them: the
Library's skill view showed SKILL.md as raw text with no way to change
it. There never was an edit path; this adds one.

- GET /api/library/skill takes `file` and answers library.ReadSkillFile:
  the file (SKILL.md by default), its text, the skill's folder and its
  text files (UTF-8, no NUL, up to 1 MB each, 200 listed, SKILL.md first;
  links, hidden folders and what installing writes left out).
- POST /api/library/skills/save {name, file, text, was} is
  library.SaveSkillFile, through change(): it writes only a regular
  file already in the skill's library folder (no .., no absolute path,
  no link, no folder that is a link out of the skill, nothing under
  node_modules/.venv/…), refuses when the file no longer holds `was`
  (the text the page opened), keeps CRLF line ends, and writes with
  edit.WriteAtomic. The sync after it reaches every agent: a linked
  one reads the library's folder, a copy is made again. A copy edited in
  an agent before the save is older, so takeEdits sets it aside in the
  backups. A GitHub skill saved here reads as Changed here, so an update
  asks first.
- The page (viewSkill in plugins/library/client.js) draws a Markdown
  file with the Plugins page's own renderer (plugins.js exports it as
  window.mdRender, 27 bytes of core script) and its front matter as
  rows; other files as text. Edit swaps in a text box; Save or ⌘S/Ctrl+S
  sends it; Cancel asks when there are changes. Other files are the
  app's menu under the name (no native select). New code is in the
  library plugin, so the core script budget is not raised.
- SkillText is gone (its only caller was the route). One new string, in
  all five languages. docs/subsystems/library.md says all this.

Run on mote at the change rebased on 9335e23d3:
- go test -count=1 -timeout 45m ./internal/library ./internal/gui
  ./internal/cli: library ok. gui: TestCoreScriptBudget passes; the only
  red is TestMainWindowCorners/macOS_26_SDK (#3949, mote's macOS 27).
  cli: the only red is TestEveryRouteHasACommandOrIsNamed on GET
  /api/context/reply (#5026, from 0872bc2a0). Both are red on main and
  filed.
- GOOS=linux and GOOS=windows go vet -tags nogui on the three packages;
  gofmt -l clean.
- skill-edit.test.cjs: 22/22 (chromium and webkit; en, zh, zh-TW, ja,
  de; 860px and 400px). It checks the drawn Markdown and front matter,
  no sideways scroll, ⌘S posting the exact body with `was`, the status,
  the file menu, Cancel sending nothing, Save on a second file, no click
  scrolling the page, no left-border stripe or gradient. i18n-keys ok.
- Whole GUI suite (a new API call), on the Linux box (wsl-run; mote had
  two other full suites): ~4460 of its results in at the push, not
  finished. Its reds are all WebKit and none is in a file this touches.
  The ones near it, run alone at this change and at origin/main
  bc10a6198: click-scroll, found-skill-pick-remove and account-eye fail
  the same on both (#4385, #4097/#5013, #4244).

Again at the pushed head (rebased on b967b1620; its commits change
app.js and the core budget), on the Linux box: TestCoreScriptBudget ok,
go test ./internal/library ok, gofmt -l clean, skill-edit.test.cjs and
i18n-keys 26/26.

Broken by hand: without the `was` check, without the linked-folder check
and without the CRLF handling, TestSkillFileSaveRefusesAChangedFile,
TestSkillFileStaysInTheSkill and TestSkillFileKeepsLineEnds each went red.
skill-edit.test.cjs on the old assets: 0/11 in chromium (.lib-mdview
never appears).

Not tried: refeccd's own skills (the fixture is a made-up handover from
~/.agents/skills, with a copy agent and a link agent); the real app
window (the GUI tests fake the API); the TUI and CLI, which have no
editor; making, renaming or removing a file from the page; Windows.
2026-11-03 16:33:03 +08:00
yetone b967b16208 usage: a Zhipu pay-as-you-go key's balance card; SiliconFlow's says its query is gone
nam.haid on Discord: the Usage page showed no balance for a Zhipu key,
and SiliconFlow's card always said only "暂时无法获取额度".

Zhipu / Z.ai: nothing read a pay-as-you-go key's balance. BigModel has no
documented balance API; its console asks
/api/biz/account/query-customer-account-report with the key as a Bearer,
and it answered a real key (the owner's, 2026-11-03) the same at
open.bigmodel.cn, www.bigmodel.cn and api.z.ai:
{"code":200,...,"data":{"balance":0E-9,...,"availableBalance":0E-9,
"frozenBalance":0E-9,...},"success":true}; a bad key gets code 1000 at
HTTP 200. zhipuBalanceSource reads availableBalance at the key's own host
(¥ on bigmodel.cn, $ on api.z.ai). A refused key says so in the words the
Coding Plan card already uses (zhipuRefused), another code says its code
and msg, a reply without availableBalance is an error, never a balance. A
GLM Coding Plan key (a base under /api/coding/, or a key on the "coding"
plan) isn't asked: its plan windows are its card. A key seen only at the
shared /api/anthropic endpoint gets a card only once the account was ever
paid in. KeyBalances now skips a key whose own plan has no balance
source, so a mixed provider's Coding Plan key gets no stray card.

SiliconFlow: /v1/user/info answers 410 (code 20092) since 2026-08-14 and
its release notes list no replacement through 2026-10-21. The reason was
already read but shown as the generic line, with the last balance kept.
It is now a typed error (siliconFlowRetired): no kept balance, the card
says the API is gone in the user's language (en, zh, zh-TW, ja, de) and
its "Open the console" button opens cloud.siliconflow.cn (or .com).

Run at this head, rebased on origin/main bc10a6198: on mote, go test
./internal/provider (ok, full package), ./internal/tui (ok), the
budget tests in ./internal/gui (ok); ./internal/gui and ./internal/cli
are red only in TestMainWindowCorners (#3949) and
TestEveryRouteHasACommandOrIsNamed (#5026), the same on main. go vet:
GOOS=windows provider and gui, GOOS=linux provider (ok); gui for linux
needs cgo, not run. gofmt -l clean. GUI on mote at 9335e23d3: the 126
files matching balance|quota|usage|i18n|glm, 1819 of 1856; the reds are
the Usage page's (usage-agents-hide #3414, usage-fold #3415,
usage-ledger #5048), and in WSL the six of them plus
siliconflow-balance and i18n-keys, chromium and webkit, give 32 red at
this head and 35 at bc10a6198 itself, the same tests. siliconflow-balance
20 of 20 (en, zh, zh-TW, ja, de; 900 and 420 wide).

Broken by hand, each red then green: no Zhipu source (TestZhipuBalance,
TestZhipuAndSiliconFlowBalanceCards), no SiliconFlow SeeAt (the cards
test), no per-key plan check (the cards test), the never-paid-in rule
("anthropic, never paid in: <nil>"), the GUI mapping
(siliconflow-balance.test.cjs 0 of 20).

Not tried: a funded Zhipu account (only a never-paid-in one answered, so
the funded fixture is that reply with amounts filled in); a real
SiliconFlow key (the 410 shape is the one TestSiliconFlowRetiredBalanceQuery already held); the credit
line (creditBalance) isn't read; a provider whose own plan is the Coding
Plan with a pay-as-you-go key beside it still gets no balance for that
key. The account report is undocumented and may change.
2026-11-03 16:26:17 +08:00
yetone 694f4a6d65 gateway: a Codex turn of its own reads past 512 MB, to a sixteenth of the machine's memory (dallascao)
dallascao on Discord: generating images in Codex and revising them again
and again, magpie answered 413 "request body is over magpie's gateway
limit of 512 MB (decoded); the provider was not asked" on
127.0.0.1:3425/backend-api/codex/responses, while Codex signed in to
OpenAI directly went on. The count was right: Codex keeps each image it
generated in the conversation (a function_call_output input_image, a
~3 MB PNG as ~4 MB base64; codex-rs ext/image-generation to_response_item,
and history keeps image_generation_call results), and over HTTP sends the
conversation whole every turn, so ~130 images is 512 MB decoded. To
OpenAI directly Codex uses its WebSocket and sends a delta.

- Codex's own path (codexBackend, the Codex relay, the Responses
  WebSocket's read limit, keyLimited on CodexPath) reads to
  codexBodyLimit: a sixteenth of the machine's memory (memLimit, else
  proc.MemTotal), 512 MB at least, 2 GB at most. 16 GB: 1024 MB,
  24 GB: 1536 MB, 32 GB+: 2048 MB, 8 GB or unknown: 512 MB as before.
  It is still the bomb guard: nothing decodes past it, and the zstd
  decoder keeps its window bound.
- A turn for a magpie model ("provider/model") on that path is held to
  the 512 MB of every other route once its model is read: it is
  translated, at several times its size. Its 413 says one of Codex's own
  models takes up to codexBodyLimit; writeError's /compact hint stays.
- provider.codexNamesBad read tools/input/tool_choice with
  GetManyBytes, which copied the whole input (the body's size: 300 MB of
  a 300 MB turn in the alloc profile). It reads in place now.

Cost at the largest input (mote, a relayed gpt-5.5 turn of random
~3 MB images, heap objects sampled every 5ms, load ~350): 300 MB took
4.7s, 600 MB 7.7s, 1000 MB 11.9s, peak heap 1.5 to 2.1 GB past the
body's own bytes. The rest of the cost is io.ReadAll growing the decoded
body and fillJSONIn/exchangeOf; bodyRoom still runs a body bigger than
its room alone.

Run at the pushed head (mote): gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/gateway ./internal/provider ok;
go test -timeout 45m ./internal/provider ok, ./internal/gateway ok but
TestCompactionOverByteCapEveryTime, red in the full package run only
(#4862, filed before this; passes alone 3 of 3 here).
TestRequestBodyTooLarge/codex now sends codexBodyLimit+1.
- TestCodexGeneratedImagesPastOldLimit (16 GB machine fixture, a 516 MB
  turn of generated images in Codex's shape): reaches the fake ChatGPT
  backend whole in ~6s; the same turn for x/gpt-5 is 413 naming
  "one of Codex's own models takes up to 1024 MB".
- TestCodexBodyLimitFromMemory: 2/8/16/24/64 GiB and unknown memory.
Broken by hand: codexBackend reading with limit 0 (the old code) makes
TestCodexGeneratedImagesPastOldLimit red with the reporter's 413; the
magpie-model check turned off makes it red (404 from routing, not 413).

Not tried: the reporter's own session or a real Codex image-generation
run through magpie; a turn past 1 GB on a 16 GB machine; the WebSocket's
raised read limit has no test of its own.
2026-11-03 16:05:53 +08:00
yetone bc10a61985 agents: Claude Code's status line, the 5h and 7d use, is a switch on its row (steven_4422)
steven_4422 on Discord asked for the 5h and 7d account use in Claude
Code. magpie has had `magpie statusline` since #1997 (kensenzhao), but
it was found only in docs/reference.md and needed a hand-written
settings.json entry naming a `magpie` the app doesn't put on PATH.

Claude Code's row now has a "status line" square beside ultracode (the
same toggle, now a table, TOGGLES in app.js), and `magpie claude
statusline on|off` in the CLI. On writes settings.json's statusLine as
{type: command, command: "<this magpie's full path> statusline"},
quoted for a POSIX shell (Git Bash on Windows, forward slashes).
The command reads the gateway's kept windows with a 1s timeout and
prints nothing when it can't, as before.

- A status line of the user's own is never written over: the square
  isn't offered while one is there, on is refused, and off and
  Disconnect leave it byte for byte. Ours is a single plain command
  whose program is magpie/magpie-* and first argument statusline, so a
  hand-written one from the reference counts and a compound (&&, |, ;,
  $(...)) is the user's.
- An unreadable settings.json is not written over.
- Disconnect takes magpie's status line out with the rest.
- Quiet: Claude Code reruns a changed statusLine command in its open
  sessions, so no restart notice.
- Not offered for a WSL distro, and a distro's settings.json isn't read
  for the options (a stopped one would start, #3896). A stopped
  distro's fields fall back to magpie's models as options, so without a
  case in wsl.go its square would have listed models
  (TestWSLClaudeNoStatusLine).

Run on mote (go1.26.8, load ~400):
- at f33e6d112 (rebased on 3088872e6): go test -count=1
  ./internal/agent ./internal/cli ./internal/gui. Red:
  TestWSLColdPlaceOpensNothing (mine: Options read a distro's
  settings.json; fixed), TestCoreScriptBudget (5 bytes over after the
  rebase; a comment trimmed, no raise), TestEveryRouteHasACommandOrIsNamed
  (#5026, from 0872bc2a0 on main), TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27). go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- GUI at f33e6d112: every agent-*, claude-*, i18n*, field* and tweak*
  file, both engines: 1294 of 1296. agent-stale-copies (webkit ja 980,
  #1949) and claude-subagent-tag (webkit ja 1100, filed #5040) timed out
  under load; at d85b4e49b both files and claude-statusline.test.cjs
  (en, zh, zh-TW, ja, de at 900 and 400 wide) alone: 130 of 130.
- at d85b4e49b (the fixes above): go test ./internal/agent ok;
  TestCoreScriptBudget ok.
- rebased on f37742e14 (a key's spend cap took the core to 21 bytes
  under its budget; this change's 207 bytes are paid for by foldSame's
  comment cut, no raise), at the pushed head: go test ./internal/agent
  ok (318s); TestCoreScriptBudget ok (1,533,597 of 1,533,802);
  claude-statusline, i18n-keys and claude-effort GUI files, both
  engines: 46 of 46.
- gofmt -l clean.

Broken by hand, each red then restored:
- the user's-own guard off: TestClaudeStatusLineLeavesTheUsers
- the Unwire call taken out: TestClaudeStatusLineGoesOnDisconnect
- the file wiped before the write: TestClaudeStatusLineUnreadable
- the compound check off: TestClaudeStatusCommand
- the WSL asleep case off: TestWSLClaudeNoStatusLine
- the here check after the read: TestWSLColdPlaceOpensNothing
- the statusline entry out of TOGGLES: claude-statusline 15/15 red

Not tried: a real Claude Code session showing it (and its hot
reload); Windows Git Bash and PowerShell with a real path; the Linux
AppImage path; WSL is not offered at all.
2026-11-03 16:03:14 +08:00
yetone 01de489de1 search: a ChatGPT account searches for another model by the backend's own search (lucy_85908)
A third-party model in Codex (DeepSeek, MiniMax, ...) had its web
searches made by asking gpt-6-luna on the Codex account to search
through /responses. A ChatGPT account now searches by the ChatGPT
backend's /alpha/search, the request Codex's web.run sends by itself
with no model turn (codex-rs ext/web-search): one search_query, the
account's small model in "model", allowed_callers ["direct"], and
external_web_access from the client's web_search tool (#5018: Codex's
"cached" sends false; live by default). The output's pages are read by
their 80-dash rule and ref_id; the private-use citation marks are dropped.

Measured on a real Plus account (2026-11-03, token not refreshed): 151
alpha/search calls left the 5h window at the same percent, ~1.5-2.2s
each; 51 searches by gpt-6-luna took 0% -> 1% of it, 7-15s each,
~9-17k tokens in (40 of them: 414,585 in, 10,313 out). The backend
answered the same for any "model" (deepseek-v4 too) and any
max_output_tokens.

- Automatic (and searchInTurn) picks the backend's search for a ChatGPT
  account; Settings > Web search offers "<id>/@search" as "its web
  search". "<id>" and "<id>/<model>" saved before still search by that
  model, so a user's pick is unchanged.
- When the backend's search fails, the account's small model searches
  (codexSearchBy).
- Codex web.run's own search for a non-ChatGPT model (alphaSearchHere)
  and a Responses request's web_search tool pass their mode on.

Run at this head (rebased on origin/main), on mote:
- go test ./internal/gateway/... ./internal/gui/ ./internal/agent/
  -timeout 45m: gateway and agent ok; gui red only on
  TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote).
  After the rebase: the gateway's search tests again ok.
- searcher-pick.test.cjs: 22/22, chromium + webkit, en/zh (+ the label
  is in zh, zh-TW, ja, de).
- gofmt -l clean; GOOS=linux go vet gateway, provider; GOOS=windows go
  vet gateway, gui.
- Whole GUI suite on the Linux box (wsl-run): not finished when pushed;
  its reds so far are WebKit pages this doesn't touch (add-provider,
  API key palette, Routing headers, click-scroll, Codex resets).

Broken by hand, each red: the Automatic switch (TestCodexSearchesWith
ItsCheapModel, TestChatGPTAccountSearchesByItsWebSearch), the
responses.go mode (TestResponsesWebSearchModeKept), the body's mode,
the fallback, and the picker option (searcher-pick).

Not tried: a real search through magpie in a sandbox (the request shape
was tried by hand against the backend); an account out of its
allowance (does alpha/search still answer?); the model fallback still
searches live when Codex asked cached.

Suggested by lucy_85908 on Discord.
2026-11-03 15:59:14 +08:00
yetone f37742e14d agent: a used-up ChatGPT account magpie can't serve past leaves the Codex app on its sign-in (xiaoq6285)
xiaoq6285 on Discord (magpie 0.1.2798, the Windows Codex app, one
ChatGPT Plus account, Codex on its own model joined beside the sign-in):
at the five-hour limit the app showed an error and had to be restarted,
then its account menu showed only "magpie" with no quota; at the reset
it restarted by itself and the account came back.

Cause. When the active account was held (used up, no credits), Sync's
own-model takeover made magpie Codex's provider on codex/<model>
whenever magpie's catalog listed that model on any Codex account -- the
same used-up one included. With one account and no fallback every turn
it took over is refused on that account anyway, while the takeover:
- has account/read answer no account, so the menu drops the user, Plus
  and the usage meter until the reset;
- changes the route twice (into it, back at the reset), and
  KeepCodexAppOnItsProvider ends the app's app-server each time, which
  ChatGPT desktop 26.1027.x shows as "ChatGPT 遇到了问题" and relaunches
  (#4550, still open, the app's own reaction to an ended app-server).
Separately, magpie's [model_providers.magpie] requires_openai_auth
follows the account out and back (openaiAuth), and codexAppRoute
counted it even when that table was not Codex's model_provider, so
staying beside the sign-in would still have ended the app-server at
the limit and at the reset.

Change.
- provider.CodexServesWhileOut(model): the Codex subscription has
  fallbacks for codex/<model> (FallbackModels), or another ChatGPT
  account is not known held and not lapsed.
- Sync's own-model takeover runs only when that holds. Otherwise Codex
  stays on its sign-in: the app keeps the account, its quota and reset,
  and shows its own limit message. With a fallback set it moves as
  before (affa979d5 serves the fallback through the gateway too).
- codexAppRoute counts magpie.requires_openai_auth only while
  model_provider is magpie; the table is still written as before.
- docs/subsystems/agent-wiring.md says both.

Tests.
- TestCodexOwnModelOneSpentAccountStaysOnItsSignIn (new): one account,
  no fallback, held: config stays on the sign-in, codexAppRoute and
  AppOut unchanged across two Syncs and the reset.
- TestCodexServesWhileOut (new): one account none; another not known
  out yes; every account out none; a codex fallback yes.
- TestCodexOwnModelGoesThroughMagpieWhileUsedUp and
  TestCodexOwnModelOutThenKeptOnChatGPT now set a codex fallback, the
  case where the takeover still serves something.

Broken by hand: the CodexServesWhileOut gate taken out -> the new agent
test red (Codex moved to model_provider = "magpie", codex/gpt-a);
codexAppRoute counting requires_openai_auth always -> red (route
changed with model_provider empty). Each put back, green.

Run on mote at this head (rebased on e41ef6288), -tags nogui -timeout 45m:
- internal/agent ok (381s), internal/provider ok (254s);
- internal/cli FAIL in TestEveryRouteHasACommandOrIsNamed alone: GET
  /api/context/reply has no command, from 0872bc2a0, filed as #5026,
  nothing of this change;
- gofmt -l clean; go vet of both packages, GOOS=linux go vet -tags
  nogui ./... and GOOS=windows go vet ./... ok.
- internal/gateway ok (1152s) at the earlier base 3088872e6, not run
  again after the rebase (it imports provider; this change adds a
  function there and changes nothing it calls).

Not tried: the real Windows Codex app signed in to a used-up Plus
account (the Windows box's app is not signed in; #4550's crash was not
reproduced there); a real codex app-server against a fake 429 upstream.
Users with a fallback or a second account still get the takeover and
its two app-server restarts, which #4550 tracks.
2026-11-03 15:46:42 +08:00
yetone e41ef6288c providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted
credits that other docker services spend from too, and they want magpie
to stop at a share of it. Their workaround was two magpies behind a
gateway-key limit.

What changed
- provider: KeySpendCaps on a provider, keyed by the key's fingerprint
  (key_spend.go): USD over a local calendar day, a local calendar month,
  or in all since it was set. Since is kept while the cap stays one in
  all. SetKeySpendCap and ParseSpendCap refuse an amount outside
  0 < usd <= 1,000,000 and an unknown period, and leave the saved cap
  as it was. Subscriptions are refused, since an account has its own
  usage-window cap.
- usage: KeySpent(keyID, start) is what magpie's own calls on the key
  cost at the Usage page's prices. Turned-away calls and app-reported
  ones are left out. It reads usage.jsonl once per key and start, keeps
  the sum for 5 minutes, and Append counts each new call into it
  (spentNew). A read that a write races is read again.
- gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap
  holds an account. The next key serves, then the fallbacks. With none,
  the reply is 429 "spend cap reached: ..." naming each key, what it
  spent of which cap, and how to go on. Retry-After is when the soonest
  period renews; a cap in all gives none. A spend hold is not a usage
  cap: Stop at the caps and strictKeep don't end at it (capHeldOnly).
  The trace's barred row carries the cap, the spend and the period.
- GUI: a pill on each key's row in the provider editor, for example
  "$7.50 of $20.00 today". It opens the app's menu (No spend cap,
  Per day..., Per month..., In all...) and then takes the amount in
  place, as the lane-limit pill does. A key at its cap gets a line
  under its row: "At its spend cap · back in ...". Every string is in
  all five languages. The pill and the line are in keyspend.js, which
  app.js imports when it draws a key's row, so the core's script
  budget is not raised. /api/providers' keyList carries spend, and
  POST provider/keyspendcap sets it.
- CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]]
  lists each key's spend and sets or removes a cap.
- docs: providers-accounts.md and gateway-routing.md.

Caveats, also in the tooltips:
- What counts is magpie's priced usage, not OpenAI's bill.
- A model with no known price counts $0.
- Requests already under way when the cap is reached still finish, so
  a key can go a little past it.

Run on mote at the pre-rebase head (3e3196222 + this change):
- go test -count=1 -timeout 45m for internal/provider, usage, cli, gui
  and gateway: provider, usage and gateway ok. Three reds, none from
  this change:
  - cli TestEveryRouteHasACommandOrIsNamed: GET /api/context/reply,
    red on main, #5026.
  - gui TestMainWindowCorners/macOS_26_SDK: macOS 27, #3949.
  - gui TestCoreScriptBudget: from this change. Fixed by moving the
    pill into keyspend.js, then ok on a rerun.
- go vet: plain, GOOS=linux -tags nogui and GOOS=windows -tags nogui,
  all clean. gofmt -l is clean.
- GUI, both engines: key-spend-cap.test.cjs passed 20 of 20 before
  the keyspend.js move, and all of its tests passed again after it.
  It covers en, zh, zh-TW, ja and de at 900 and 400px, a refused
  amount, the set, change and remove posts, and checks for no native
  select, no border stripe and no sideways scroll.
- Also run in both engines: i18n-keys, old-webkit, lane-limit,
  account-cap, key-row-chips-fit, key-weight-fit, key-nourl,
  provider-many-keys, key-switch, key-plan and key-rest-date.
  - key-replace's webkit 420px is red at base 3e3196222 too
    (#4126; base failed 2 of 3 en runs, this change 3 of 3).
  - key-rest-date's webkit zh-TW, ja and de tests time out at
    --test-concurrency=4 with three other files beside it, at base
    too (base 5 reds, this change 7). Run alone at concurrency 2, it
    passes 10 of 10 at base and with this change (#4691).

After the rebase onto 9c51f7fdb, at the pushed head:
- go build ./... and go vet on the five packages: clean.
- go test of the spend tests, TestCoreScriptBudget and the gui
  package's word tests: ok.
- i18n-keys and key-spend-cap in both engines: 24 of 24.

Broken by hand, each red and then restored:
- spentNew taken out of Append: TestKeySpentCountsTheKeysCalls red
  ("after a new call key a spent 3, want 7").
- spendHeld never barring: TestKeySpendCapPassesTheKeyOver red (the
  capped key reached the upstream).
- capHeldOnly keeping spend holds: TestKeySpendCapPassesTheKeyOver red
  (Stop at the caps answered 429 instead of using the fallback).

Not tried:
- a real OpenAI key or real spend;
- the real app window;
- Windows and Linux test runs (vet only);
- the whole GUI suite: mote was running two other sessions' full GUI
  suites at load 250 to 400.
2026-11-03 15:30:44 +08:00
yetone 3088872e63 claude: an interactive run goes on when only Claude Code's varying safety context changed (xybio)
xybio on Discord (Claude Pro, Claude Code through magpie, likely in auto
mode) saw it twice: right after the 5-hour window reset, one message took
the window from 100% to 0%. Their Usage page for the day (claude-opus-5-5):
- 62 requests and 17M tokens, almost all of it cache (input 102,
  output 31.3K);
- a 29.4% cache hit rate, so about 12M tokens were written to the cache,
  around 290K for each of the 41 that succeeded.
That is the whole conversation written again on almost every request.

The cause is in the bridge. With server review on, which it is for a Claude
account (AutoModeReviewed), every request carries Claude Code's
`safeguards`. The interactive mode's Claude Code reads
CLAUDE_CODE_EXTRA_BODY only as it starts, so setSafeguards restarted the run
whenever the field differed in any byte. A new run is told the whole
conversation, and that writes it all to the cache again.

The field's classifier_context differs on nearly every request. That is in
Claude Code's own code (2.1.316, Jmr):
- prior_turn_context grows with each tool round's tool_use_ids;
- git_state.status follows every edit;
- system_reminders, artifacts, text_provenance and the shed list vary too.
So every tool round and every turn of one message started a fresh run
(4 turns gave 4 runs in the new test on the old code), each paying a full
cache write of the history.

Change: in an interactive run, setSafeguards compares safeguardsKept forms.
That form leaves out the parts Claude Code itself names as variable and
sheds over its 256KB budget:
- prior_turn_context, system_reminders, artifacts, text_provenance, shed;
- Chrome's tabs;
- git_state except cwd, root, branch and default_branch.
When only those changed, the run goes on with the context it started with.
A change to the rules, permission or auto mode, folders, or the
repository and branch still restarts it. A field that isn't the expected
JSON is compared whole. The -p path is unchanged: it takes every change in
place through apply_flag_settings. The cost is that the server classifier
sees those varying parts as they were when the run started. This is noted
in docs/subsystems/claude-subscription-bridge.md.

Run at the pushed head (52d69934f, on origin/main 9335e23d3), on mote:
- go test -tags nogui -run 'TestClaudeTUI|TestClaudeBridgeSafeguard|
  TestClaude.*Safeguard|AutoMode' ./internal/gateway: ok.
- gofmt -l internal/gateway: clean.

Run at 4ff686b49, the same tree before the rebase (the rebase brought in
only 9335e23d3, outside these files):
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: one red,
  TestClosedBeforeSentEveryTimeSaysWhy (a bare EOF on the Codex
  closed-before-sent path, which this change doesn't touch). It passed
  30 of 30 alone. Filed as #5031.

Broken by hand:
- The comparison off (always restart):
  TestClaudeTUISafeguardsVaryingPartsKeepTheRun is red, "4 turns ...
  started 4 runs, want 1".
- The comparison always passing: the same test is red, "a changed rule
  went on in 1 runs", and so is TestClaudeTUISafeguardsInEnv.

Not tried:
- A real Claude account in auto mode through the interactive bridge, and
  the real 5h meter before and after.
- Whether xybio's windows also fell in the earlier cache regressions
  (v0.1.2677 to v0.1.2799). The local-classifier path, where each check is
  a one-off run that re-writes its transcript, is not changed here.
2026-11-03 14:58:57 +08:00
yetone 9335e23d3b claude-desktop: every inferenceModels entry carries its /v1/models name (chengming0v0)
chengming0v0 on Discord (v0.1.2806, Claude Desktop): the models of an
API-key provider read "mythos-magpie-0167851852", "mythos-magpie-3494120245"
and the like in Desktop's model menu, beside rows named properly
("DeepSeek V4.1 Flash 1017 · 寄吧鲁东", "GPT-6.1 Sol · ag:zdgit").

Cause: since ae060550b (v0.1.2770), while a model is picked for one of
Desktop's tiers, magpie writes its profile's inferenceModels so Claude
Code gets behavesAs. Desktop 4.4212 skips /v1/models discovery while that
list has no bare tier word as a name (adminListObviatesDiscovery in
index.chunk-m4oMImJ-.js, discoveryEnabled unset), and pzn then names each
entry labelOverride ?? catalog name ?? discovered name ?? ypn(id), which
for mythos-magpie-<n> and anthropic/magpie-<n> is the id itself. Only the
rows listed by their [1m] id (DesktopLongest) got a labelOverride, which is
why the user's 1M models kept their names, and why one GPT model of theirs
showed its name once its window was set from 400K to 1M.

Change: DesktopInferenceModels gives every entry the display_name
/v1/models gives its row as labelOverride, a catalog-named Claude model
(magpie-<n>.anthropic.<model>) too, whose description naming the provider
is lost with discovery. A list magpie wrote before is rewritten on the next
Sync (its hash is magpie's); Desktop reads it as it starts, so it needs a
restart (the Agents row offers one). agent-wiring.md updated.

Reproduced with the reporter's shape: an API-key provider whose models
have reasoning levels (listed as mythos-magpie-<n>), a GPT model at 400K
and one at 1M under DesktopLongest, one picked for a tier, in the tests'
sandbox HOME. TestDesktopInferenceModelsNamed (new) is red on the old
desktop_list.go for every entry but the 1M one ("mythos-magpie-3254679763
is labelled <nil>, /v1/models names it \"gpt-6.1-sol · 寄吧鲁东\"", 5
entries), and
TestClaudeDesktopModelsList's new check, on the profile magpie writes, is
red on it ("named by its id: … name:anthropic/magpie-4604110569"); both
green with the change.

Run on mote, rebased on 3e3196222: gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/gateway ./internal/agent ok; go test
-count=1 -timeout 45m ./internal/gateway ./internal/agent ./internal/gui:
gateway ok, agent ok, gui red on TestMainWindowCorners/macOS_26_SDK only
(#3949, open, unrelated). After that run the new test gained the 400K/1M
pair; -run 'TestDesktopInferenceModels|TestClaudeDesktop' over gateway and
agent ok at the pushed tree.
Not tried: a real Claude Desktop 4.4212 with the written profile (read
from its app.asar only); the reporter's own Desktop version is unknown.
2026-11-03 14:37:00 +08:00
yetone 3e31962225 provider: Request headers to pass, the agent's own values to its provider
A provider's fixed Headers can't say a value that changes from request
to request or from client to client. 3jRzfF52Qx on X asked for the
agent's own header values to reach the vendor. Each provider now has a
comma-separated list of request headers, saved as `passHeaders`. When the
agent's request carries one of them, its value goes to that provider as
the agent sent it.

- Where it is: the editor's "Request headers to pass" (zh 透传请求头),
  under Advanced, right after Reply headers.
- The agent's value stands over a fixed Headers value of the same name.
  When the agent sends none, the fixed one goes.
- Never passed on, listed or not (provider.RequestHeaderPassable):
  - magpie's key: Authorization, X-Api-Key, X-Goog-Api-Key, Api-Key;
  - cookies and sign-ins: Cookie, Set-Cookie(2), WWW-Authenticate,
    Authentication-Info, Proxy-*;
  - the connection's own fields: Host, Connection, Keep-Alive, TE,
    Trailer, Transfer-Encoding, Upgrade, Expect;
  - what magpie writes for the body: Content-*, Accept,
    Accept-Encoding;
  - Origin, Sec-* and X-Magpie-*.
  Save refuses such a name with a reason (RequestHeadersOK), and so does
  the editor, before the save. The editor's list is held to Go's by
  TestReplyHeadersNeverAsTheProvidersAre. A name written into
  providers.json by hand is dropped on read.
- Only that provider gets them. forwardOnce, which every chat,
  responses, messages, count_tokens, group-member, fallback and plugin
  try goes through, puts the agent's headers in the try's context under
  the try's provider id (WithClientHeaders). Provider.Sign passes only
  what that id lists, before an account signs, so a signed-in account's
  own signing still wins. A plugin's fetch gets them in req.Header.
- Wire headers are still masked when read (5ec237568), so a passed
  token header shows masked in a call's log.

Run on mote at the tree rebased on origin/main 06944e065:
- gofmt -l: clean.
- go vet: darwin (provider, gateway, gui), GOOS=linux -tags nogui
  ./..., and GOOS=windows ./...: ok.
- go test -timeout 45m ./internal/provider ./internal/gateway
  ./internal/gui: provider and gateway ok. In gui, TestCoreScriptBudget
  and the i18n tests are ok and only TestMainWindowCorners/macOS_26_SDK
  is red, as on main on macOS 27 (#3949).
- The core budget is not raised. This change's words, and the comments
  on extra body and the never lists, were cut first. After the rebase
  onto 63dc359fb it was 438 bytes over again, so three provider-editor
  comments (User-Agent, balance token, plan access keys) were cut to a
  line each. The core is 1,533,554 bytes, 248 under 1,533,802.
- At this head (rebased on origin/main 63dc359fb): go test -run
  Budget|I18n|ReplyHeaders ./internal/gui is ok. The new provider and
  gateway tests are ok. node --test pass-headers, reply-headers,
  i18n-keys, header-session-hint, balance-fix and extra-body: 162 of
  162 ok.
- node --test, Chromium and WebKit: pass-headers (en/zh/zh-TW/ja/de),
  reply-headers, i18n-keys, provider-detect-models, header-session-hint
  and extra-body: 46 of 46 ok.
- Before the budget cut, against the same base: every GUI file that
  opens the provider editor and saves (45 files plus i18n-keys) had 739
  of 758 ok. These were red, and red the same on a fresh origin/main
  06944e065 copy: models-works-only (#4391), provider-picks-stay
  (#4397) and remote-magpie (#4398). Also red: one WebKit sub-pixel
  miss in provider-detect-models (#4964), which passed on main and at
  this head.

New tests:
- TestRequestHeadersList: cleaning and refusals.
- TestSignPassesClientHeaders: the agent's value over the fixed one,
  never magpie's key even when listed by hand, nothing for another id,
  and the fixed value when nothing was sent.
- TestPassHeadersReachTheProvider: messages relayed and translated,
  chat, a chat stream, responses and count_tokens.
- TestPassHeadersOnlyToTheirProvider: a fallback that lists nothing gets
  nothing, the log shows the passed headers masked, and in a group the
  member that lists them gets them while the one before it, which lists
  nothing, doesn't.

Broken by hand, each red, then put back:
- forwardOnce without WithClientHeaders: both gateway tests red.
- RequestHeaderPassable ignoring the never list: TestRequestHeadersList
  red, and TestSignPassesClientHeaders red on X-Api-Key=magpie-key
  passed on.
- Sign not skipping a fixed header the agent sent: the provider test,
  and the gateway test on every route, red on X-Route=route-fixed.

Not covered: embeddings, images, video and the Codex backend relay,
which don't go through forwardOnce.

Not tried:
- a real vendor or a real plugin provider with the setting;
- Windows and Linux test runs (vet only);
- a gateway test with Authorization listed by hand, which normalize
  drops on read. Sign's own check is covered by
  TestSignPassesClientHeaders.

Requested by 3jRzfF52Qx on X.
2026-11-03 14:16:20 +08:00
yetone 63dc359fb4 providers: a subscription account's rest, or its model's, shows on its row (maxleebeta)
maxleebeta on Discord (#feedback): WorkBuddy answered 429
{"type":"rate_limit_error","message":"WorkBuddy: 您的使用量已超出频率限制,将在
2026-11-03 23:57:19 UTC+8 重置,您也可以切换其他模型继续使用。"} while the
provider's card said 1,934/2,350 credits left (82%), and nothing on the
Providers page said the account was held back.

Routing already handled the refusal: resetsWhen reads the time (UTC+8, the
space before 重置 included), failure() gives failQuota, and since it says
切换其他模型 the rest is that model's alone (restID), by "resets", till
15:57:19 UTC; the account's other models are still asked (#1669). What
was missing was the page: a key's rest showed on its row, an account's
never did.

- gateway.RestsUnder(prefix) lists the rests in force under a key prefix
  (provider@ for a subscription's accounts, provider@user/model for a
  model's), with Key and the rest's note (Model, By, Error).
- providerJSON.accountRests gives them by user in lower case, the model
  filled in from the key when the note has none; provider.KeyRest gains
  By, Model and Error.
- app.js: the account row in the provider editor gets a line per rest
  (accountRestLines): "<model> resting · 429 quota used up · back at
  <time>" or "Resting · …" for the whole account, the vendor's words
  beside it (shown whole when it names a time magpie couldn't read, so
  an unknown format still says why), and Try now (gateway/unrest by the
  rest's key). The key row's rest line is now the same helper
  (restLineOf), so app.js grows ~800 bytes, under the core budget.
- New strings in zh, zh-TW, ja and de. docs/subsystems/gateway-routing.md
  says where the Providers page reads them.

Not changed: the "-sg" maxleebeta saw in pi is WorkBuddy AI's own model
id (deepseek-v4.1-flash-sg, the paid Singapore id beside the free
deepseek-v4.1-flash); pi's footer and model picker show ids by design,
and the name magpie writes for it is the vendor's ("Deepseek-V4.1-Flash",
"(SG)" added by the plugin only where two ids share a name). Neither
magpie nor the plugin appends "-sg"; the CN build has no -sg ids.

Run (mote, through mote-run):
- go test ./internal/gateway ./internal/gui ./internal/provider at f0df4bb2b
  (base 06944e065): gateway ok (737s), provider ok, gui ok except
  TestMainWindowCorners/macOS_26_SDK, red on macOS 27 as on main (#3949).
- Rebased on 889767b7b: TestCoreScriptBudget, TestI18n*,
  TestAccountRestsInProviderState and the written-reset tests ok;
  gofmt -l clean. GOOS=linux and GOOS=windows go vet -tags nogui ok at
  f0df4bb2b, before the rebase. Then rebased once more onto 8ee172ca0,
  which changes only gateway search files; not re-run there.
- internal/gui/tests/account-rest.test.cjs: chromium and webkit, en, zh,
  zh-TW, ja, de, at 900 and 360px, ok. rest-try-now.test.cjs's 15 webkit
  reds fail the same on origin/main 06944e065 (#2564, #4127).
- Broken by hand: TestRateLimitedModelListedUnderAccount red with
  RestsUnder returning nothing, TestAccountRestsInProviderState red
  without accountRests, account-rest.test.cjs red without
  accountRestLines.

Not tried: a real WorkBuddy account hitting this 429, so the line has
not been seen on a live gateway; the whole GUI suite (mote under another
session's suite). The line shows in the provider editor's account rows,
not on the collapsed provider row.
2026-11-03 14:09:42 +08:00
yetone 06944e065b gateway: a reply that begins as an event stream is read as one whatever its Content-Type (uk.jent)
uk.jent (Discord, #feedback): MiniMax Code's plugin (0.1.7) served as
Anthropic Messages to Grok Build 1.0.74. The first token took minutes
(5-6 at worst), then hundreds of characters came at once, and every
thinking block said "Thought for 0.0s".

Cause: eventStream decided a reply was a stream by its Content-Type
alone, unless the type was empty or text/plain. A stream sent under
any other type (application/octet-stream, say) was read as a whole
reply. On the Messages passthrough, sigFieldTidy, anthropicTextCalls
and the other tidies hold a whole reply until it ends, so the agent got
the turn only at its end, every block at once. On Chat and Responses
(translated) the same reply failed "did not stream". Under
application/json, notAnAPIReply turned it into a 502 ("isn't JSON").
The plugin itself passes MiniMax's body through untouched, and the host
streams it chunk by chunk, so neither is the cause.

Fix:
- eventStream reads the body's first bytes under any Content-Type that
  isn't text/event-stream. A body that begins as an event stream
  (event:, data:, a ":" comment) is one, and its Content-Type is set to
  text/event-stream for the agent. A JSON or binary body never begins
  that way.
- notAnAPIReply lets a JSON-labelled body that begins as an event
  stream through (eventsStart, shared with eventStream).
- docs/subsystems/gateway-routing.md says the rule.

Test: TestPluginThinkingStreamsAsItComes. The fake MiniMax plugin is
put in front of a vendor that sends its first thinking and then waits
until the agent has heard it (or gives up after 10s). It covers
messages, messages with tools (as Grok Build sends them), chat and
responses, each under text/event-stream, application/json, text/plain,
no type and application/octet-stream.

Run on mote:
- On origin/main d73f2254d: gofmt -l internal/gateway clean; go vet
  -tags nogui ./internal/gateway with GOOS=linux and GOOS=windows ok;
  go test -tags nogui -timeout 45m ./internal/gateway ./internal/plugin:
  internal/gateway ok (742s), internal/plugin ok (136s).
- Rebased on origin/main 441a2b6b1, which brought the #4775 upload
  changes into internal/gateway: gofmt and both vets again ok; go test
  -run 'TestPluginThinkingStreamsAsItComes|NotAnAPIReply|
  APIReplyUntouched|Upload|Unrouted|Streamless|PluginStream|QuietWhole|
  Thinking|Signed|Passthrough|Continuation' ./internal/gateway: ok
  (108s). The whole package was not re-run at this head.

Broken by hand:
- With eventStream at the old code, the octet-stream cases go red in
  all four shapes: messages "reached the agent only once the vendor
  had finished"; chat and responses "FakeCo did not stream".
- The application/json cases go red with eventStream alone fixed and
  notAnAPIReply at the old code ("the thought never reached the agent",
  a 502 after 90s).
- text/event-stream, text/plain and no type pass on the old code.

Not tried:
- a real MiniMax Code account or a capture of the mavis endpoint's real
  reply headers. There is none here, so the cause is the class that
  fits the symptom, not MiniMax's literal bytes.
- a real Grok Build run.
- a stream that comes compressed (Content-Encoding).
2026-11-03 13:50:05 +08:00
yetone 441a2b6b16 plugin: a cancelled sign-in saves nothing, and a failed authorize says why (#5016)
Found reviewing magpie-community/plugins#658 (AStudio's and Agnes Code's
sign-ins wait up to 5 minutes for the vendor's desktop app).

Cancel didn't end a plugin sign-in. The window's Cancel (and the sign-in's
timeout) ended plugin.Finish's context, but "callback" was not a
cancellable call, so the host never heard: the plugin's wait went on, and
a session file written after Cancel still saved the account. Now
authorize, callback and apiKey are cancellable as gatewayRequest is
(host.go `cancellable`): magpie writes `abort`, host.js (`signInSteps`)
drops whatever the plugin answers after it, so nothing is saved, and
counts the call done at once. The plugin's wait is told too: every fetch
it makes for the sign-in carries the sign-in's signal
(`whileSigningIn`), and magpie's hook passes the signal as
callback(code, { signal }) / authorize(inputs, { signal }), which OpenCode
doesn't, so a plugin can stop polling a file. A plugin that ignores the
signal keeps running until its own deadline, but its answer is dropped.

An oauth method's authorize that returned { type: "failed", error } (no
callback) was stored and its missing callback called, so the user saw
"s.a.callback is not a function". host.js now answers that, or any result
with no callback, as the sign-in's failure, and plugin.Authorize returns
ErrFailed with the plugin's reason, for auto and code methods; an api
method's authorize already did. The GUI's start shows it as its failure,
`magpie plugin login` prints it.

Docs: provider-plugins.md, and the plugin guide (en, zh, ja) on failing
from authorize and the signal.

Not changed: #3083's timeout field, #4678's model/usage task lifetime.

Tests (testdata/signinend, no network; the vendor is testenv.FakeVendor):
TestCancelledSignInSavesNothing, TestCancelledSignInEndsThePluginsWait,
TestCancelledSignInEndsItsFetch, TestSignInFailsWithThePluginsReason
(internal/plugin), TestCancelledPluginSignInSavesNothing
(internal/provider, through StartPluginSignIn/CancelSignIn).

Run on mote (macOS 27), at this change on d73f2254d (the new tests and vet of both packages again after the rebase on 897e88d7e, which touches neither):
- go test -count=1 -timeout 45m ./internal/plugin/ ./internal/provider/:
  ok (134s, 145s); the new tests -v: all PASS.
- ./internal/cli ok; ./internal/gui FAIL only in
  TestMainWindowCorners/macOS_26_SDK, #3949 (macOS 27 on mote; this
  change touches no GUI code).
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok;
  gofmt -l: nothing.
- GUI (Chromium + WebKit): plugin-signin, plugin-signin-no-url,
  plugin-signin-opened (en, zh, zh-TW, ja, de), plugin-signin-scrolls,
  plugin-keyless-signin, plugin-moved-signin, signin-paste-plugin,
  signin-close, i18n-keys: 108/108.

Red on the old code (origin/main's host.js, host.go, providers.go): all
four plugin tests (an account saved after Cancel; the plugin's wait and
its fetch not ended, timed out; methods 2/3/4 said "s.a.callback is not
a function"), and TestCancelledPluginSignInSavesNothing.
Broken by hand: host.go's `cancellable` back to gatewayRequest only, all
three cancel tests red; the whileSigningIn line out of the fetch wrapper,
TestCancelledSignInEndsItsFetch red.

Not tried: the real AStudio and Agnes Code plugins (plugins#658) against
this host; the site's plugin guide isn't deployed by this commit.
2026-11-03 13:40:20 +08:00
897e88d7e6 gateway: most's timer looks again no sooner than a second while an upload earns (#4775)
Cause: with wuuli's upload credit, a request's charged time stands
still while its body earns at least as fast as it is read. When little
was left, checkMost re-armed most's timer at that sliver, and again
every time it fired, for as long as the body kept coming. In the #4775
review, a hold frozen 100µs short of unroutedMost was looked at 6731
times in a second.

Change: checkMost waits at least unroutedRecheck (1s, or an eighth of
unroutedMost when a test shortens it) before it looks again. A hold is
answered at most that much late. Masking, the 30s unknown-work guard,
the 60s socket idle deadline, the decoded cap and the trickle's 408
are unchanged.

Test: TestUnroutedMostRecheckIsNoSpin freezes a hold's charged time a
sliver short of unroutedMost and counts the timer's looks in a second.
It allows 30.

Run, via mote-run (macOS arm64, Go 1.26.8), at this tree before the
rebase (base affa979d5):
- gofmt -l: clean. go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...: all exit 0.
- go test -tags nogui -race -count=5 of the ten upload and body tests
  (the patches' four, this series' five, TrickledBodyAnswered408): ok
  (102.5s).
- go test -tags nogui -timeout 45m ./internal/gateway/...: one red
  (771.9s), TestCodexPoolSaysTheClientsVersion. That is #4807 (another
  test's Codex identity reaching it), fixed on main by 17f2387e1, which
  this tree's base predated.
- After the rebase onto f3335dd1b (which brings 17f2387e1), at
  698362aaf (this tree, before this message was amended):
  go test -tags nogui -timeout 45m ./internal/gateway/...: ok (775.7s).
- go test -run TestUnrouted at each of the three commits: ok.

Broken by hand, each with its test (this series and the patches):
- Reset(left) without the floor: NoSpin went red (6731 looks).
- origin/main's unrouted.go with only the two names the tests need:
  wuuli's TestUnroutedProgressingUploadOutlastsMost went red with 408
  at 1s (identity, chunked, gzip, zstd), and so did
  TestUnroutedUploadTimeIsBounded (5 of 6 cases). Leng's
  TestUnroutedUploadAllowanceHasCeiling charged 11m against 3m.
  TestUnroutedUploadCreditKeepsIdleDeadline passed, as a guard that
  holds on main too should.

Not tried: a real slow link or proxy, the reporter's own conversation,
and running on Linux or Windows (vet only).

Thanks to wuuli (Xulin Wu) and lengjingxu (Leng on X, who reported it
again) for the patches this series builds on.

Co-authored-by: Xulin Wu <wuxulin@bytedance.com>
Co-authored-by: Leng <Lengjingxu@gmail.com>
2026-11-03 13:36:52 +08:00
b4e3885477 gateway: earned upload time banks nothing, and a body that decodes to nothing still ends (#4775)
Review tests for wuuli's and Leng's upload credit, guarding the two
ways an earned allowance could hold a request too long.

Banking: a body sent at once earns far more than it took to read
(2 MiB earns 64s at 32 KiB/s). TestUnroutedFastUploadBanksNothing
holds a request after such a body with a lock routing needs. It is
answered 504 at unroutedMost, and the credit buys the later internal
hold nothing (`d -= min(spent, earned)`).

Empty encoded streams: empty gzip members (a 60 KB extra field, no
content) or zstd skippable frames keep the wire busy, decode to
nothing, never reach the 512 MiB decoded cap, and earn upload time
forty times faster than they are read. TestUnroutedEmptyEncodedStreamIsBounded
sends one chunked over a raw conn through Front. It is answered 408 at
unroutedMost plus unroutedUploadGrace: the cap ends it, not the rate.
Go 1.26.8's gzip.Reader loops over members without recursion (read on
mote), so no stack grows with the member count.

unroutedUploadGrace becomes a var so the test can scale it, as
unroutedMost already is. Its value is unchanged (8m).

Run, via mote-run (macOS arm64, Go 1.26.8, -tags nogui):
- go test -run TestUnrouted ./internal/gateway/: ok at this stage.
- The full verification is in this series' last commit.

Broken by hand:
- `d -= earned`: FastUploadBanksNothing went red, unanswered at 20s.
- No clamp on bytes read: EmptyEncodedStreamIsBounded went red in
  gzip and zstd, unanswered at 30s, and Leng's
  TestUnroutedUploadAllowanceHasCeiling went red (1m and 11m charged).

Not tried: a real client sending such a stream, and a slow real link.

Co-authored-by: Xulin Wu <wuxulin@bytedance.com>
Co-authored-by: Leng <Lengjingxu@gmail.com>
2026-11-03 13:36:52 +08:00
yetone 639a15c507 gateway: a chunked body is still arriving between two reads until a read meets its end (#4775)
Cause: bodyArriving (#4511) counted a body as still arriving between
two reads only when the request said its Content-Length. A chunked
body, which every encoded upload from an agent can be, was judged by
the read alone. When most's timer fired between two of its reads, the
request was answered 504 "without routing it to any provider", as a
hold of magpie's own, though its body was still coming. A decoder
spends its time between reads too: in the #4775 review, a stream of
empty gzip members got the 504 in 2 of 10 runs.

Change: waitedBody records that a read met its end or an error
(bodyEnded). A chunked body counts as arriving between reads until
then. A body read whole, an empty one, and one not yet begun (the wait
for body room) still count as magpie's hold. Every watched route reads
the body through request_bounds' io.ReadAll, so a read reaches EOF or
an error.

Tests:
- TestUnroutedBodyArrivingBetweenReads now expects a chunked body to
  count as arriving between reads, and not once its end is read.
- TestUnroutedChunkedBodyReadWholeHeld504 (identity, gzip and zstd,
  sent chunked) guards the other side: a hold after the whole body has
  been read is still 504.

Run, via mote-run (macOS arm64, Go 1.26.8, -tags nogui):
- go test -run TestUnrouted ./internal/gateway/: ok. 24 tests at this
  stage on 07b6834fe (wuuli's and Leng's patches).
- The full verification is in this series' last commit.

Broken by hand:
- No bodyEnded store: ChunkedBodyReadWholeHeld504 went red in all three
  encodings, answering 408 "its body was still arriving".
- The old `d <= 0` condition: BodyArrivingBetweenReads went red, with
  "a chunked body between two reads ... did not count as arriving".

Not tried: a real slow link or proxy, and the reporter's conversation.
2026-11-03 13:36:52 +08:00
Leng 19d04425c8 gateway: cap earned upload time before duration arithmetic
Bound upload credit to eight additional minutes so progressing compressed streams cannot keep pre-routing requests alive indefinitely. Clamp wire bytes before multiplication to avoid duration overflow. Keep the progressing-upload fix by Xulin Wu in its original authored commit.
2026-11-03 13:36:52 +08:00
Xulin Wu df69ffe979 gateway: let progressing uploads outlast the routing hold (#4775)
Latest main 9d08993c already classifies an unfinished body as 408, but
still ends a large upload at the two-minute unrouted budget. Credit
actual body-read time at one second per 32 KiB received on the wire,
never more than the time spent reading. Fast uploads cannot bank time
for later internal holds. The idle deadline, unknown-work budget, body
room and size cap remain; a trickle still exhausts the base allowance.
The 408 suggests checking the link/proxy or compacting before retrying.

Red: TestUnroutedProgressingUploadOutlastsMost failed on unchanged main
with HTTP 408 at the scaled 1s hold. Restoring main's budget calculation
via Go overlay with final tests makes all four TLS upload cases fail
with 408 and TestUnroutedUploadTimeIsBounded fail its numeric assertions.
Green: declared/chunked/gzip/zstd TLS tests through Front, idle protection,
rate boundaries and existing unrouted/request-body tests pass (28.267s).
Same selection -race -count=20 passes (547.523s).

Verified on macOS arm64, Go 1.26.8, Bun 1.4.3, temp HOME and pinned Go
caches. gofmt -l and git diff --check clean; native/Linux nogui/Windows
vet and builds pass. Final go test -tags nogui -timeout 45m ./... passes:
87 packages (32 cached), 18 without tests, wall 1152.1s; gateway 734.881s,
plugin 122.229s, claudebridge 3.813s. Individual skips not enumerated.

First full suite had 85 passing packages, gateway 743.006s, and two reds.
The known Bun SOCKS assertion (#2207) is fixed by the preceding unchanged
skygunner patch acb2249e (original a93c613a); its -race -count=20 and all
three vets pass locally. A callback helper timeout is filed as #4782:
its isolated -race -count=20 passes (3.586s) and final suite passes, but
the delayed stage is unresolved, not claimed fixed. Existing macOS C
compiler deprecation/enum warnings remain.

No live gateway, account, or original conversation used. No GUI assets
changed; Playwright not run. Linux/Windows were cross-built/vetted, not
runtime-tested. The original network throughput cause remains unknown.
2026-11-03 13:36:52 +08:00
yetone 0872bc2a0e context: a request's text and reply from the request archive (wangbinyq)
wangbinyq on Discord: with the request archive on, clicking a block of
the context window card still said "只保留最近 10 个请求的原文", since the
card read only the last 10 bodies magpie keeps in memory.

What changed:
- /api/context/text tries memory first, then the request archive's copy
  when the route names one (Route.Archive, the route found in the trace
  or in the history file of the card's ?day=, HistoryRoute looks a day
  either side). gateway.ArchivedPromptText parses it as PromptText does
  and masks it through maskedCopy, as the body in memory is; it is
  marked from "archive" and the card says so.
- New /api/context/reply: the reply to the request, from the Recent
  calls (Server.ReplyBody) or the archive's Response. gateway.ReplyPieces
  reads it into thinking/assistant/call pieces (conversationOutput, split
  out of conversationTurn) after redact.ScrubJSON, and masks every piece
  through maskedCopy. The card's text view has a Reply button beside
  Close that shows it and goes back to the part.
- What is shown is what the archive stores, masked as the memory copy
  would be, nothing more. A body or reply that can't be masked shows
  nothing (404 "unread"); one the archive cut short isn't parsed ("cut");
  one it names and doesn't have says so ("missing"), and one with no
  archive copy keeps the old "only the last 10" line ("off"). A failed
  bucket read is an error, not "gone".
- The archive read is capped at archiveReadMost and the last copy read is
  kept 5 minutes, so the items opened one by one read it once.
- ctxtext.js takes the route (id and time) instead of the id; context.js
  passes it (its one-line change paid for by a comment cut, core budget
  not raised). New strings in zh, zh-TW, ja and de.
- docs/subsystems/gateway-routing.md (Prompt) and gui-shell.md.

Run on f3335dd1b (main has since d73f2254d, textcalls_anthropic.go and
its test only, none of these files), on mote (macOS 27):
- go test -run 'TestArchivedPromptText|TestReplyPieces|TestPromptText|
  TestConversation|TestContext|TestCoreScriptBudget' ./internal/gateway
  ./internal/gui: ok.
- Whole ./internal/gui and ./internal/gateway (before the last rebase,
  same change): ok except TestMainWindowCorners/macOS_26_SDK (#3949) and
  TestCodexPoolSaysTheClientsVersion (#4807, fixed on main by 17f2387e1
  since).
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of both: ok;
  gofmt -l clean.
- GUI, both engines, every language, 1100 and 420 wide: every file that
  reaches the context card (context-text, context-map, context-window,
  context-map-live, context-scroll-end, context-scripts, context-tune,
  ctx-route, compact-one-value, routing-ctx-*, routing-context-fold,
  routing-live-patch, routing-return-cost) plus i18n-keys: 514 of 518.
  The 4 reds are context-map's webkit 420px "two tiles overlap", red the
  same on origin/main f3335dd1b run alone (5 of 10 webkit there), #3488.
- The whole GUI suite is running on the Linux box (wsl-run) as this is
  pushed; mote had another session's full suite on it.

Broken by hand (each went red):
- maskReplyPieces skipped: TestReplyPiecesAreMasked (phone unmasked).
- ArchivedPromptText's masking skipped: TestArchivedPromptTextIsMasked
  and TestContextTextFromTheArchive (phone in the 200 body).
- ctxtext.js's "missing" reason dropped: context-text.test.cjs, 10 of 10
  chromium.

Not tried: a real archived request in the running app, the bucket
(WebDAV) archive with a real server, and a reply cut short by the
archive's size in a real call.
2026-11-03 13:34:35 +08:00
yetone d73f2254d7 gateway: a relayed reply Anthropic reviewed for auto mode makes no call out of its text
xybio on Discord (#feedback): Claude Code through magpie (127.0.0.1:3425)
shows "We're changing auto mode to no longer charge for classifier
requests ... this session isn't eligible because your requests go through
127.0.0.1:3425". Anthropic's llm-gateway-protocol page asks a gateway to
forward request headers and body fields unchanged (safeguards among them)
and to return replies without dropping keys like safeguard_results or
rewriting tool-use ids.

Audit of the Anthropic-to-Anthropic path (passthrough, forwardOnce):
- Request: anthropic-beta and anthropic-version always go; safeguards and
  the dangerous-tool-use beta go as sent to a reviewed route
  (serverReview/AutoModeReviewed) and are taken off for any other model.
  No body field is dropped there.
- Reply: safeguard_results already pass, whole and streamed
  (TestAutoModeServerSideReviewRelayed). tool_use ids go as they came;
  toolUseIDs salts one only when the client already holds it (#4910),
  which Anthropic's unique ids never are.
- The one rewrite found: anthropicTextCalls (39bade71d, two days old)
  reads Claude's <invoke name=…> markup out of a relayed reply's text and
  makes it a tool_use with an id magpie invents (call_text_N), stop_reason
  tool_use. On a reviewed reply that call has an id Anthropic never
  judged, so Claude Code can match it to no verdict.

Fix (textcalls_anthropic.go): a stream whose message_delta carries
safeguard_results, or a whole reply that carries them, has no call read
out of its text; the text goes as text, stop_reason and results as they
came. Without results the written call is still made, so
packinggoodsllc_07668's case (a Claude group writing invokes) is kept.
docs/subsystems/gateway-routing.md says so.

Not changed, said here: masking (redact.MaskJSON, opt-in) masks values
inside safeguards.classifier_context (paths, user_identity) like any other
string the user sends; ids (tool_use_ids, *_id) are kept. Only
Content-Type and request ids are copied from a successful reply's
headers, so anthropic-ratelimit-unified-* don't reach Claude Code. The
wiring leaves the review on whenever a reviewed model is reachable
(claudeReviewEnv), so a session on a non-Claude model, or on a relay that
drops safeguard_results, still gets the notice; which route xybio uses is
not known.

Run (mote-run):
- TestAutoModeReviewedReplyMakesNoCall red with the stream check taken
  out (names [Bash], stop tool_use) and with the whole check taken out
  (call_text_1 tool_use), green with both.
- At e3f7d3194 (rebased on 2c214ce25): gofmt -l clean; GOOS=linux and
  GOOS=windows go vet ./internal/gateway ok; go test -count=1 -timeout
  45m ./internal/gateway: every test passed but
  TestCodexPoolSaysTheClientsVersion (734.7s), which is #4807.
- Rebased onto origin/main f3335dd1b, which fixes #4807 (17f2387e1) and
  changes thinking_bound.go: at the pushed head fe5d30d7c's tree, vet for
  linux and windows ok, and -run "TestAutoMode|TestInvokeReported|
  TestTextWritten|TestTextCall|TestClaudeBridgeSafeguard|TestCodexPool|
  Thinking|TestSafeguards|Passthrough" ok (36.6s). The full package was
  not rerun there.

Not tried: a real Claude Code auto-mode session through magpie and its
/status "Auto mode server" row; no real Anthropic reply carrying both
safeguard_results and written invoke text was seen.
2026-11-03 13:23:49 +08:00
yetone f3335dd1b4 gateway: DeepSeek's thinking is left out of a request to Claude (GgbondHi6930 on X)
GgbondHi6930 on X: a Smart group of DeepSeek and a Claude API key. A
conversation ran on DeepSeek at max effort; with DeepSeek unticked its
next turn went to Claude and failed "signature in thinking". A new
conversation worked.

Cause: DeepSeek's Anthropic endpoint signs each thinking block with its
reply's id, a UUID (checked against api.deepseek.com/anthropic). The
agent keeps those blocks and sends them back, so the first Claude turn
carries them, and Claude refuses the request, 400 "messages.1.content.0:
Invalid `signature` in `thinking` block" (real reply through
OpenRouter's Anthropic route, req_011CgfP4zyRcUhPiTg5sLpoe). Until now
magpie mended this only after the refusal, in forward's bound-thinking
retry. That needs the refusal to reach forward as a 400/422 with
Claude's wording, and it spends a request. With fakes that answer as
Claude does, main recovers through it, on Messages (whole and streamed)
and on Codex's Responses. So the reporter's failure is where that retry
can't read the refusal. A relay's status or wording is the likely case;
it is not reproduced exactly.

Change: forwardOnce, which every route to an Anthropic upstream passes
(relayed, translated Chat/Responses, group fallback and Smart routing,
a plugin's fetch, count_tokens), now calls withoutForeignThinking. For
an upstream serving Claude (api.anthropic.com, or a claude- model name)
and not DeepSeek, it leaves out each thinking block whose signature is a
UUID. Those blocks never reach Claude, and refuseBoundThinking reads a
refusal's indices against that same body. These go byte for byte:
- Claude's own signatures (base64; 3,000 of Claude Code's own were
  checked, all base64 and 800+ characters);
- unsigned blocks (Claude took one in a real request);
- redacted_thinking;
- other vendors' signatures, which the retry still mends.
DeepSeek's endpoint and every other upstream get the body unchanged.

Tests (thinking_switch_test.go):
- TestDeepSeekThinkingThenClaude: the reporter's case, whole and
  streamed. 3 DeepSeek tool turns, then DeepSeek unticked and 3 Claude
  turns. Claude refuses nothing and gets its own blocks back as signed.
  With DeepSeek ticked again and Claude unticked, DeepSeek is sent every
  block, its own and Claude's.
- TestDeepSeekThinkingThenClaudeResponses: the same through Codex's
  /v1/responses.
- TestWithoutForeignThinking: Claude, DeepSeek and Kimi upstreams.

Run on mote (mote-run):
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean, at cfa9a6987 (base 17d2ef10f).
- go test -timeout 45m ./internal/gateway/... ./internal/provider/...
  at cfa9a6987: provider ok. Gateway ok except
  TestCodexPoolSaysTheClientsVersion, which is #4807 (passes alone 3/3;
  commented there). It was fixed on main by 17f2387e1, which this commit
  is rebased onto.
- After the rebase onto 17f2387e1, which touched none of these files'
  code: -run 'Thinking|Bound|TestCodexPoolSaysTheClientsVersion' ok.

Broken by hand: with withoutForeignThinking returning the body as it
came, all three tests go red ("Claude refused 1 of its 4 requests",
"Claude refused 1 of its 3 requests", "message 1 = [thinking,text]").

Not tried:
- a real Claude account through magpie; no Anthropic key was usable
  here, and the relay accounts found (aihubmix, yylx) are out of credit;
- the reporter's own relay;
- Chat Completions clients, which carry no signatures;
- Kimi, GLM and MiniMax signatures, which the refusal path still mends.
2026-11-03 13:16:35 +08:00
yetone 2c214ce252 agents: Air's row says which of Air's own agents go through magpie (jumy_18634)
jumy_18634 on Discord picked a model on the Air (JetBrains IDEs) row and
found Air's Codex in IDEA 2026.3 still on another model. The model on an
Air row is the Magpie ACP agent's alone, and the row never said so.

What Air's own agents run, read from the jars (air-plugin
262.8665.521, Air app 262.1037.14):
- The IDE plugin's Codex runs this computer's codex (the terminal's
  PATH, else the @openai/codex it installs) as `codex app-server` with
  the user's CODEX_HOME or ~/.codex, and sets no model_provider
  (CodexAppServerProcessKt, CodexCliUtils). Its menu is model/list, its
  default config/read's model, and a task's model goes in thread/start.
  Its Claude Agent runs claude with only Air's hooks in --settings.
  So both are on magpie while Codex / Claude Code are connected here.
- The Air app's Codex runs with a CODEX_HOME of its own and JetBrains'
  gateway ([model_providers.air-gateway]), and never is.

Changed: an Air row, opened, says to pick Magpie in Air's agent menu and
that the model there is Magpie's. The IDE plugin's row says whether
Codex and Claude Code are connected here, and so whether Air's Codex and
Claude Agent go through magpie; the app's says its own agents don't
(airSaid in app.js, words in zh, zh-TW, ja, de). air.go's comment and
docs/subsystems/agent-wiring.md say what the jars showed, in place of
"not tried in an IDE". Six Agents-page comments in app.js are cut to one
line each to keep the core under its budget, no raise.

Run at the pushed head, on mote:
- Codex 0.166.0 `codex -c check_for_update_on_startup=false app-server`,
  as Air starts it, in a sandbox HOME with a magpie-style config.toml
  (model_catalog_json, model_provider magpie on a fake gateway at
  127.0.0.1:3599): model/list gave the catalog's two models, config/read
  the config's model; after config.toml changed under the running
  server, config/read gave the new model; a thread/start with model
  kimi/kimi-k3 (as Air's CodexThreadStartParams sends it) and a turn
  sent /v1/responses with model kimi/kimi-k3 to the gateway.
- GUI: agent-air-own.test.cjs (new), chromium and webkit, en zh zh-TW ja
  de, 1100 and 640px: 20 of 20.
  The 166 GUI files that reach the Agents page or i18n, both engines:
  red only in page-width-steady, found-skill-pick-remove, mobile-web and
  remote-magpie, which fail the same way alone on origin/main affa979d5
  (#5013), and nav-timeout, which fails at the old base and passes after
  the rebase.
- go test -tags nogui ./internal/agent -run 'Air|Notice', ./internal/gui
  -run 'Budget|I18n|Air|Notice': ok. GOOS=linux and GOOS=windows go vet
  -tags nogui ./internal/agent ./internal/gui: ok. gofmt -l: clean.

Broken by hand: without the Air branch in connectPanel,
agent-air-own.test.cjs is red, 10 of 10 in chromium.

Not tried: Air itself (no JetBrains IDE on this Mac or mote); a real
Codex or Claude Code connected through Air; Air on Windows or in WSL.
Air's bundled codex isn't among the running copies the Codex row names
as on an old list.
2026-11-03 13:02:15 +08:00
yetone 3d7b1233dd claudetui: /usage's screen is read at the terminal's own 200 by 50 on macOS and Linux (#4988, shinnqy on X)
shinnqy on X: in the latest magpie Claude Code's usage doesn't load.
#4988 (0.1.2776, macOS, Team plan): the card said 100% / unused, and
`magpie quota refresh claude` gave one window, "7 days · Fable" 0%, while
the account's 5 hours were 29% and 7 days 17% used.

Cause: 3a74cd92e reads /usage's panel off a terminal grid (screen.go) and
prefers that look of it over the stream. screenSize() made the grid 80 by
24 everywhere but Windows, saying "a pty here is given no size", but
child_unix.go makes the pseudo-terminal 200 by 50. Claude Code draws the
panel at the foot of its 50 rows; on the 80 by 24 grid every row under the
24th was clamped onto the 24th and drawn over it, so the kept look of the
panel held one window (the last drawn), or a figure redrawn in place was
lost to the stream's older one.

Fix: one screenCols/screenRows (200 by 50) for the Unix pseudo-terminal,
Windows' pseudo console and the grid. Windows is unchanged.

Test: TestShimReadsUsageBelowTheTwentyFourthRow, a 200 by 50 panel with
three windows drawn as 2.1.316 draws (ESC[H, CR + ESC[nB, ESC[55G), then a
frame that redraws only the session's figure (29% -> 30%). fakeFrames now
splits frames at a 50-row foot (ESC[50;1H) as well as ESC[24;1H.

Run at this head (mote): gofmt -l internal/claudetui clean; go vet
./internal/claudetui with GOOS darwin, linux, windows ok; go test
./internal/claudetui ok; go test -run 'Claude|Usage|TUI' ./internal/gateway
./internal/provider ok. xiaomi-gpu (win-run): -run
'TestShimReadsUsage|TestGrid|TestShimWaits' ./internal/claudetui ok.

Broken by hand: the new test on origin/main's tui.go (80 by 24 grid) is
red, telling "Current session: 29% used" for the redrawn 30%; green with
the fix.

Not tried: a real Claude Code panel with figures at 200 by 50 on macOS
(no real-account run in a sandbox; the fixture is synthetic, in 2.1.316's
encoding). The report's "messages can't be sent" half is not explained by
this: nothing here touches the request path, and no log came with it.
2026-11-03 12:51:31 +08:00
yetone affa979d56 gateway: Codex's one account used up goes on to the Codex subscription's fallbacks
adorable_piglet on Discord: once the ChatGPT (Plus) account's quota ran
out, the Codex app couldn't send at all, and magpie never moved the turn
to the fallback they had set (their own API key, another provider).

Cause: with one ChatGPT account and nothing to route, a turn on Codex's
own sign-in is relayed as it came (codexUpstreamOn). The relay handed an
overload on to the subscription's fallbacks (codexFallBack), but a
quota, credit or rate refusal went to Codex as the backend said it, the
429 usage_limit_reached with its x-codex headers. Codex then stops.

Change: codexAccountOut names the refusals that are the account's, not
the request's: failure() quota, credit or rate, as a status or as a
stream's failure before any reply (response.failed, an error event, a
stream without Content-Type), and a 403 usage_not_included. Never a 401:
Codex renews its own sign-in on it. When the subscription has fallbacks
(codexFallsBack, never a compaction), such a refusal now goes on to them
once the credits retry and the automatic reset have been looked at, as
an overload does; the trace keeps the try's real failure kind. With no
fallback set, Codex still gets the backend's refusal.

What Codex's own client does: it greys Send from its own /wham usage
read. magpie already gets past that once the usage reading says used up
(codex.out with the app-server restart, #540, 9f641daea); this change is
the turn itself.

docs/subsystems/gateway-routing.md says it.

Run (mote, at this tree):
- go test -tags nogui ./internal/gateway -run 'TestCodexOneAccount|TestCodexOwnModel|TestCodexSpent': ok.
- New TestCodexOneAccountSpentFallsBack: all 7 codexSpent shapes red on
  the old code (Codex got the 429/403 or the failed stream), green now.
  TestCodexOneAccountSpentNoFallbackRelayed and
  TestCodexOneAccountSignInRefusedNotFallenBack hold the no-fallback and
  401 cases.
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok. gofmt clean.
- The whole internal/gateway package (-timeout 45m) was still running at
  push; the result is reported separately.

Broken by hand: codexAccountOut returning false: the 7 subtests red again.

Not tried: a real used-up ChatGPT account in the real Codex app.
2026-11-03 12:41:12 +08:00
yetone 17d2ef10fa claude: a conversation's instructions stay after Claude Code's prompt in every interactive run
m4rs0n on Discord: since #2432 (eb8b840dd) a Claude subscription
conversation in the interactive mode broke the prompt cache as it grew.
The same body sent again read 100% from the cache, but the same body plus
an assistant "ok" and a new user turn read only 1,273 of 8,565 tokens and
wrote 7,290. A tool loop read a constant 1,273 every call (opus 1,273,
sonnet 1,197, haiku 2,000: Claude Code's own system prompt).

Cause: eb8b840dd gave a one-off ask (no tools, no reply) its caller's
instructions with --append-system-prompt-file, after Claude Code's own
prompt, and lets that run go after its reply. Every other run (with tools,
with a reply, a resumed or replayed session) kept them in the first pasted
message. So the conversation's next request started a run whose system
block ended at Claude Code's prompt and whose first message held the
instructions. The cached prefix broke right after Claude Code's prompt,
and the rest was written again. A tool loop's runs did the same: a pasted
first message loses magpie's mark (the paste is one text). The bisect
v0.1.2676..v0.1.2677 has only 541102eba (the onboarding mark), which
doesn't touch the request. Before it, those runs were -p, which keeps the
marks.

Change:
- appendsPrompt no longer requires no tools and no reply. Every
  interactive run that isn't lean and has no client cache marks appends
  the instructions. -p keeps them in the first message, where its mark
  holds.
- A run that resumes a session (shelved, branched, branchAt, or a
  replaySession transcript) is given the file again when the session's run
  had it (savedSession.appended). Sessions keep no system prompt, and every
  run key holds the system prompt, so the file is the one the session's
  run had. Appended runs can now be shelved and branched, which they
  couldn't before.
- replaySession leaves the instructions out of the transcript's user line
  when they are appended.
- docs/subsystems/claude-subscription-bridge.md says so.

Tests:
- TestClaudeTUIConversationKeepsItsInstructionsWhereTheFirstAskHadThem is
  the reporter's sequence: A, then A + "ok" + "Now say two words." Both
  runs are given the same append file, which starts with the rules. No
  run is typed them, and no session file holds them.
- TestClaudeTUIResumedSessionIsGivenItsInstructions: a shelved session is
  resumed with its append file.
- TestClaudeAppendInTheInteractiveMode replaces
  TestClaudeAppendOnlyForInteractiveOneOffs. Tools and reply append in
  the interactive mode; client marks and -p don't.
- TestClaudeTUIReplayGoesInATranscript now expects the rules out of the
  transcript's user line and the append flag on the run.

Run at the pushed head, on mote:
- go test ./internal/gateway -run 'Claude|TUI|Subscription|Replay|Branch|Lean|Append|Shelve|Resume': ok.
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok.
- gofmt -l: clean.
- The full internal/gateway package was red once, before the replay test
  was updated, with the failing test cut off by a tail. A rerun with the
  whole log is under way. Its result goes in the report and, if red, in an
  issue.

Broken by hand: the new tests on origin/main's code fail.
- TestClaudeAppendInTheInteractiveMode/tools and /reply fail.
- The conversation test fails ("given ... and <none> after Claude Code's
  system prompt, want the same instructions").
- The resumed test fails.
- With only the savedSession.appended carry removed, the resumed test
  fails ("<none> ... want A's instructions").

Not tried:
- A real Claude account. The sandbox recipe needs a live login's OAuth
  token copied out, and rotated tokens written back, which this session's
  rules forbid. The prefix claim rests on Claude Code 2.1.316 marking the
  end of its system block itself (recorded 2026-11-03 for #2432), not on a
  new real request.
- Windows and WSL runs of the interactive mode.

Sibling paths:
- Streaming and non-streaming both start runs through startRun.
- count_tokens doesn't write the cache.
- An API-key Claude request is passed through with the client's own
  marks, outside this bridge.
2026-11-03 12:40:21 +08:00
yetone 6b81344301 library: the keep-here switch says sync, and is on while it syncs (bin.90)
bin.90 on Discord read the Library editor's 「只在这台电脑」 switch as a
LAN-sharing switch: "this computer only" says nothing about what it keeps
from where. It is about sync, so it now says so.

- Library editor (MCP servers, skills): the switch is "Sync to your other
  computers" (同步到其他电脑 / 同步到其他電腦 / ほかのコンピュータと同期 /
  Mit deinen anderen Computern synchronisieren), on while the server or
  skill syncs. Its note says off keeps it here, and a sync from the
  others neither removes it nor replaces it.
- The stored value keeps its meaning: `local` true is still kept here.
  The switch shows !local and saves !on, so every saved library.json,
  sync payload and CLI flag (`magpie library mcp local NAME on|off`)
  means what it meant.
- Row tag: "Not synced" (不同步 / 同步しない / Nicht synchronisiert) where
  it said "This computer only", in the Library, the TUI ("not synced ·")
  and `magpie library` output.
- Agents page sibling (the same words for an agent's picks): its menu
  item is "Don't sync picks to your other computers", its tag "Not
  synced". The agentsHere setting is unchanged.
- docs/subsystems/library.md and sync-backup.md name the new labels.

app.js stays in its budget: origin/main 8af751987 was already 31 bytes
over coreScriptBudget (1,533,833 > 1,533,802), so a comment in
setAgentHidden was cut to one line (core 1,533,756 now), no raise.

Run on mote, rebased on 8af751987, budget again at 2cfeda3d3:
- GUI: mcp-local-server, agent-here, i18n-keys, skill-off-here: 78/78
  before the rebase, in Chromium and WebKit, every language, at 390, 640
  and 1100 wide and in the panel; after it agent-here, i18n-keys and
  mcp-local-server 56/56, agent-here again 30/30 after the trim.
- go test ./internal/tui ./internal/cli ok; ./internal/gui ok except
  TestMainWindowCorners/macOS_26_SDK, mote's macOS 27 (#3949, open,
  the same without this change); TestCoreScriptBudget ok after the trim.
- go vet ./internal/tui ./internal/cli ./internal/gui; GOOS=linux go vet
  -tags nogui and GOOS=windows go vet of tui and cli; gofmt -l clean.

Broken by hand: saving `d.local = on` (no negation) turns
mcp-local-server red (expected 'false', got 'true').

Not tried: a real sync between two computers with the switch flipped;
the stored value's meaning is checked through the saved request only.
2026-11-03 12:21:49 +08:00
yetone 1d8658abca routing: a group's model picker offers the providers' image models, and a group of them draws (jzw690 on X)
jzw690 on X: the Routing page's group editor ("Add a model") listed no
image models, so a group of image models, to draw at
/v1/images/generations and to pick in Settings > Images, couldn't be
made.

What changed:
- /api/groups gains `drawers`: each provider's image models
  (gateway.Drawers, less ones unticked in its editor unless a group
  names them), apart from the chat `models`. The picker offers them
  after the chat models, noted "<provider> · Image model" (an existing,
  translated key); a member row says so and offers no reasoning level.
  Decision-model groups don't offer them. Image models stay out of the
  chat catalog, so agents are not offered them.
- An image member drew only when its provider had no picks: picks are
  of chat models, so membersFound dropped it as unpicked, and GroupDraws,
  resolveDrawing, the group's turns and DrawerMissing all failed.
  provider.FindDrawingGroup keeps such a member when drawsModel holds;
  the image path uses it (drawingMembers), video keeps FindGroup.
  DrawerMissing for a group ref asks GroupDraws.
- Routing card: such a member reads ready (groupsState), and Settings >
  Images lists every group that draws, not only those reached through
  Served.
- docs/subsystems/gateway-routing.md says so.

Tests:
- TestImageGroupOfUnpickedImageModelsDraws (gateway), from the
  reporter's case: two key providers whose live lists hold gpt-5.5 and
  gpt-image-2, one with gpt-5.5 picked. group/<id> draws at
  /v1/images/generations (the first member's 502 moves on to the next),
  as the Settings pick a request naming no model draws, and the model
  gone from the list makes it missing.
- TestGroupEditorOffersImageModels (gui): drawers listed, an unticked
  one not offered unless a group names it, none among chat models, the
  group's members ready, Settings offers the group.
- group-pick-drawers.test.cjs: the picker offers it with its note, adds
  it, no reasoning button, Save posts it; en and zh, Chromium and
  WebKit.

Broken by hand: drawingMembers passing nil instead of drawsModel made
the gateway test red ("group/pix-images doesn't draw"); turning off the
groups.go drawer branch made the gui test red ("group not ready").

Run at b295d1196 plus this change (mote unless said):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/gui: provider ok. Two reds, neither on this path:
  TestCodexPoolSaysTheClientsVersion (full run only, passes alone 3/3;
  #4807) and TestMainWindowCorners (red on origin/main f49f6ba68 too,
  macOS 27; #3949). Both commented.
- GUI on the Linux VM (Playwright 1.62.0, both engines), 62 files:
  group-*, routing-group*, settings-groups, fallback-group,
  agent-model-groups, image*/images*, panel-routing*, routing-manual,
  routing-levels, i18n-keys. 698/710. i18n-keys was red on a comment of
  this change saying ", with an image" (reworded; 4/4 after). The
  WebKit reds under concurrency 4 passed on a serial run except
  group-member-info webkit zh, red 2/2 on origin/main f49f6ba68 too
  (#1745, commented).

Rebased on origin/main 809801f1f (its 8 commits change client.js and
gateway-routing.md), then again on mote: gofmt clean, go test -run
of the budgets, TestImageGroup*, TestDrawing*, TestGroupMember* and
TestGroupEditorOffersImageModels in gateway, gui and provider: ok; on
the Linux VM, both engines, group-pick-drawers, group-pick-filter,
group-decide-members, group-editor-fits, group-member-off,
routing-levels, settings-groups, image-models-hide, i18n-keys: 96/96.
Rebased last onto 03d7927a8 (search strings, i18n.js values only;
none of this change's files), not run again.

Not tried: a real provider's image model drawn through a group in the
running app; Windows and the real Linux app (WebKitGTK).
2026-11-03 11:57:11 +08:00
yetone 84da86ebd5 gui: Hide accounts is one switch for every page, window and the panel (paultian)
paultian on Discord (#feedback): Routing, Usage and Providers each kept
their own "Hide accounts" state, so turning it on in one page left the
others showing emails. Now window.hideAccounts is one switch, one
localStorage value (magpie.maskEmails), behind #rtMask, #usageMask and
#pvMask alike. Flipping it in any page applies to every page at once,
and a storage event carries it to other windows and the tray panel.
The old magpie.maskProviders value is folded in on first load (hidden
if either value was on) and then removed, so nobody who hid accounts
on one page sees them shown after updating. The tooltip and the
Settings line now say "on every page" instead of "on this page", in
every language.

Tests: provider-mask.test.cjs checks that one switch hides accounts on
every page and in a second window, that the state survives a reload,
and that an old maskProviders=1 comes through as hidden.
account-mask's expected tooltip text is updated.

Run on mote (GUI files at base 05aba5ca4; the Go asset/budget tests again
at this head after rebasing on a92cc3f33):
- go test -run 'Budget|I18n|Asset|Script|Strings|Lang' ./internal/gui: ok
- The masking/privacy GUI files at --test-concurrency=2, chromium and
  webkit, every language (account-mask-alias-plan, account-eye,
  window-mask, usage-fold, masking-demo-unblurred, account-alias,
  provider-mask, account-eye-provider, account-mask,
  privacy-hides-accounts, account-mask-sessions, mask-emails,
  plugin-name-unmasked, i18n-keys, masking-records): 403 of 408 pass.
  The 5 reds:
  - provider-mask "chromium en 420" (a click timed out). Rerun with
    usage-fold at concurrency 1: provider-mask is all green, and that
    run is 146 of 150.
  - usage-fold, 4 subtests: "17 subscriptions and 29 accounts" in
    chromium and webkit, and "several accounts" in webkit en and zh.
    They fail the same 4 at origin/main 625938a2f at concurrency 1
    (6 of 10 pass). That is #3415 / #4790, not this change.
- Not touched: Go code, so no go vet.

Broken by hand: with the old assets, provider-mask's one-switch tests
go red; with the maskProviders migration taken out, the
old-value-comes-through test goes red.

Not tried: the whole GUI suite (the owner's rule is to ship each
verified fix right away), and the real tray panel on Windows/Linux
following a switch flipped in the main window. Only the browser
storage event is tested.
2026-11-03 11:32:47 +08:00
yetone a92cc3f331 agent: Antigravity's effort is picked in its row, as its app can't say one (#4838)
MDX-Tom (#4838): Antigravity's app lists the gateway's models by id, with
no level control of its own, so a request for one of Antigravity's
families of levels (gemini-3.8-flash -> -high/-low) went at the level the
app asked or the family's default, and nothing in magpie could change it.
Their plugins PR #655 forced a level in middleware, over any level the
request carried and on every model named like gemini/flash, for every
agent. This puts it in core instead, as Cursor Private Inference has
since #1003: Antigravity's agent row gets an effort field, kept in
magpie (provider.AgentEffort "antigravity"), whose levels are those of
the models it lists (cursorLocalEfforts is now pickedEfforts(agent)).
The gateway already asks an agent's requests for its picked level; on an
Antigravity account that picks the family's variant (AntigravitySentID)
and its thinkingLevel. With none picked the requests go as they asked.
The field is shown only while the app is on magpie's gateway, and
nothing is written to the app's settings.json.

Run on mote at the pushed head (on a858e53fa): gofmt -l clean;
GOOS=linux (nogui) and GOOS=windows go vet of internal/agent and
internal/gateway ok; -run TestAntigravity|TestCursorLocal|TestClaudeDesktop
in internal/agent ok; -run TestAntigravity|TestAgentEffort|TestCodeAssist|
TestCursorLocal in internal/gateway ok. On b295d1196: go test
./internal/agent ok (196s). Before the rebase on 443e53d6b: internal/agent,
internal/provider ok; internal/gateway red only on
TestCodexPoolSaysTheClientsVersion (#4807, passes alone 3/3);
internal/gui red only on TestMainWindowCorners/macOS_26_SDK (#3949, red
on untouched 443e53d6b the same way on mote).

Broken by hand: without the field, TestAntigravityEffort is red ("no
effort field"); with the gateway's agentPick taken out,
TestAntigravityAgentEffort is red (both picks went as -high at "").

Not tried: a real Antigravity account and the real app's picker; the
agy CLI row has no such field (its own /model can say a level). No GUI
suite run: the field renders through the agent row's generic effort
field (cursor-local-effort.test.cjs), no new API call or layout.
2026-11-03 11:27:31 +08:00
yetone a858e53fa9 gateway: Copilot's "unsupported beta header(s)" is read as a refused beta
bigcat1800 on Discord: with Claude Desktop's tool search on (the commit
before), Claude Code in its Code tab asks tool search by
tool-search-tool-2025-10-19. Copilot's Messages API turns that name away:
400 "Copilot: unsupported beta header(s): tool-search-tool-2025-10-19",
which reached Claude Code, since refuseBetas read only Bedrock's
"Unexpected value(s) `x` for the `anthropic-beta` header". It now reads
Copilot's wording too: the request is asked again at once without the
betas named, and they are left out for that provider from then on, as
Bedrock's are. Any provider wording it the same way gets the same.

Through the live gateway, Copilot's claude-haiku-5.5 answered the same
request (a ToolSearch tool and a defer_loading MCP tool) with no beta and
with advanced-tool-use-2025-11-20, and refused tool-search-tool-2025-10-19.
A Claude subscription took both names.

Run at the pushed head, on mote: TestCopilotUnsupportedBetasLeftOut,
TestUserBetas*, TestBedrockBetas, TestSignInBetaStaysWithMagpie and
TestAutoModeReviewGoesWithItsBeta ok; go test ./internal/gateway
(-timeout 45m) ok but TestCodexPoolSaysTheClientsVersion, the full-run
red filed as #4807 (another test's Codex identity; nothing about betas);
linux and windows vet, gofmt clean.
At the pushed head, rebased on 625938a2f (search.go, handover.go moved):
linux and windows vet of gateway and agent ok, go test -run
'Beta|Bedrock|ClaudeDesktop|Search' of both ok, which covers the Desktop
commit before this one too.
Broken by hand: with the Copilot match turned off,
TestCopilotUnsupportedBetasLeftOut is red (status 400 "Relay: unsupported
beta header(s): tool-search-tool-2025-10-19, effort-2025-11-24").

Not tried: Copilot's raw error body (the fixture words it as magpie's log
shows it, without the "Copilot: " magpie adds; two betas are assumed
comma-separated), and a rebuilt magpie against real Copilot.
2026-11-03 11:25:42 +08:00
yetone 80d0cc1a66 claude-desktop: magpie's profile turns on Desktop's tool search
bigcat1800 on Discord: Claude Desktop 4.4212 in 3p mode (Code tab,
bundled Claude Code 2.1.309) on magpie, 13 MCP servers, and no MCP tool
was deferred: ~162K tokens of tool schemas on every request, though
ENABLE_TOOL_SEARCH=true was in the CLI's environment.

Cause, read from Desktop 2.7032's app.asar (Ztr, $tr, pnr) and Claude
Code 2.1.312/2.1.316 (oae, Wvn, Yar): with Desktop's 3p policy
toolSearchEnabled unset (the default, and magpie never wrote it), the
gateway provider's tool-search mode is "off", and Desktop starts the CLI
with CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1. The CLI then answers
"standard" (no tool search) whatever ENABLE_TOOL_SEARCH says; only an
admin-tier ENABLE_TOOL_SEARCH=force beats it. The model id shape
(magpie-<n>.anthropic.claude-opus-5-5[1m] or plain claude-opus-5-5)
plays no part. With toolSearchEnabled on, Desktop passes
ENABLE_TOOL_SEARCH=force as a managed setting ("host" mode, bundled CLI
2.1.247 and later) or turns the betas back on ("legacy").

magpie's profile now gets toolSearchEnabled: true once, on a switch on
and from Sync (so a Desktop already on magpie gets it at magpie's next
start), as claudeAiImport is: desktopSeedImport and the new
desktopSeedToolSearch share desktopSeedOnce. A value the user set, false
too, or took away in Desktop's window since, stays theirs (stash mark
claude-desktop.tool-search). A profile the user applied themselves for
magpie's gateway is not written. The gateway already carries deferred
tools and tool_reference to every upstream (#2660, anthropic_shapes.go).

Run:
- CLI 2.1.312 in a sandbox HOME against a recording fake (port 3591),
  60 MCP tools, model magpie-1.anthropic.claude-opus-5-5[1m]:
  DISABLE_EXPERIMENTAL_BETAS=1 (+ ENABLE_TOOL_SEARCH=true): 83 tools,
  0 deferred, 205KB. Same plus --managed-settings
  {"env":{"ENABLE_TOOL_SEARCH":"force"}} (Desktop's host mode): 13
  tools, ToolSearch, beta tool-search-tool-2025-10-19, 56KB. Plain
  claude-opus-5-5 behaves the same in each mode.
- At the pushed head, on mote: gofmt -l internal/agent empty; GOOS=linux
  (nogui) and GOOS=windows go vet ./internal/agent ok; go test
  ./internal/agent and its importers (backup cli davsync gui library
  profile stats tui uninstall) ok but internal/gui's
  TestMainWindowCorners/macOS_26_SDK, mote's macOS 27 red filed as
  #3949 (AppKit corners, nothing this touches).
- Broken by hand: the seed returning nil turns
  TestClaudeDesktopTurnsOnToolSearch red ("switch on: toolSearchEnabled
  <nil>"); the once-mark ignored turns it red ("seeded again over the
  user's choice").

- The same CLI in Desktop's host mode through the live gateway, in a
  sandbox HOME: a Claude subscription model and a GPT routing group each
  ran ToolSearch, loaded the deferred tool and called it. A Copilot
  Claude model got 400 "unsupported beta header(s):
  tool-search-tool-2025-10-19"; the next commit reads that refusal.

Not tried: a real Claude Desktop 4.4212 or its bundled CLI 2.1.309 (the
CLI was 2.1.312, Desktop's code read from 2.7032), a real request
through magpie in host mode to a Claude subscription or a translated
upstream with the tool-search-tool-2025-10-19 beta, and the reporter's
note that magpie's recorded shape had no anthropic-beta (the CLI sends
claude-code-20250219, interleaved-thinking and effort betas even in off
mode).
2026-11-03 11:24:14 +08:00
yetone 625938a2f8 search: a picked searcher that can't serve gives way to the next that can (plugins#635)
pedestrianz (magpie-community/plugins#635) set Codex's gpt-6.1-sol to
search for Cursor's models. When the Codex plan was used up (429, usage
limit), every web search of a Cursor turn failed with it: a searcher named
in Settings gave way only to the ones named after it (SearcherThen), never
to the searchers magpie would pick itself. That rule is Gearclickist's:
Grok, picked, answered without searching, and the search moved to a
pricier Codex model the user hadn't picked.

Now a named searcher that can't serve at all hands the search on, after
those named after it, to the searchers magpie would pick in turn
(searchInTurn: the ones not spent first, up to two more providers). Can't
serve means every account or key is out of its allowance (searcherSpent),
or the search was refused for quota, credit or rate (failure() in
searchWith). Both are marked errCantServe, through a cantServe wrapper,
without changing the error's text. A named searcher that is spent is no
longer asked first; it is asked last only if no one else could search.
One that answered without searching or found nothing still gives way to
no other, so Gearclickist's case is unchanged. The Routing row and
Settings' SearcherFailed name who searched in its place
(searchingInstead, namedFailed). If none can, the errors go back to the
model as a failed tool result ("... no other provider could search in its
place") and the turn goes on to the model's answer. The AI Studio keys
443e53d6b added to searchRank are among those asked.

pickedSearchSetup's failing searcher answered 400 "search quota used up",
which is now a quota refusal that hands on. Its body is now "invalid
tools: web_search", a refusal of the request, so
TestPickedSearcherIsNotHandedOn still covers the not-handed-on case.
docs/subsystems/gateway-routing.md says when a named searcher is handed
on.

Run on mote (macOS 27), at this commit's tree, rebased on origin/main
443e53d6b (the AI Studio search keys):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/agent
  ./internal/browsermcp ./internal/cli ./internal/davsync ./internal/gui
  ./internal/imagemcp ./internal/library ./internal/settingsapi
  ./internal/tui (gateway and its importers): all ok except two reds,
  both filed and not in search. TestCodexPoolSaysTheClientsVersion
  (#4807) is red in the full package run and passes alone at this tree
  (-count=3, with the search tests). TestMainWindowCorners/macOS_26_SDK
  (#3949) is red the same way at origin/main b295d1196.
- Rebased onto b295d1196 (route-events, the WorkBuddy min, #4938; none
  touches search): go vet and go test -run
  'Search|Searcher|Picked|RouteEvents|Trace' ./internal/gateway: ok.
- gofmt -l internal/gateway: clean. GOOS=linux go vet -tags nogui and
  GOOS=windows go vet ./internal/gateway: ok.
- TestPickedSearcherThatCantServeGivesWay (new; httptest fakes, no
  network): the named ds answers ChatGPT's 429 usage_limit_reached; ds2,
  named nowhere, searches; the model gets its "22/17℃"; SearcherFailed
  says ds2 searched in ds's place, and ds2's web_search row has
  For.Instead ds/deepseek-flash. A second search, with ds now resting,
  doesn't ask ds's vendor again and goes to ds2. With ds2 removed, the
  turn still ends 200, and the model is told "search failed" with the
  usage-limit reason.

Broken by hand:
- origin/main's search.go with the new tests: the new test is red ("the
  picked searcher asked 1 times, ds2 []"); TestPickedSearcherIsNotHandedOn,
  TestSearchInPlaceOfAutoSaysWhy and TestPickedSearchersInTheirOrder
  still pass.
- With searchWith's cantServe wrapping taken out: red the same way.

Not tried: a real Codex account that is used up, with Cursor's plugin
models searching through it. Grok, Claude or Gemini as the searcher in
its place were not tried with real accounts; the fake stands in for each.
2026-11-03 11:23:37 +08:00
yetone b295d11965 serve, update: one magpie works the gateway; the service waits, the copy an update left stops (#4938)
ox01024's #4938, Bug 2. Two magpies did the gateway's work at once on a
Mac:

- launchd's com.yetone.magpie.serve ran `magpie serve` beside the app.
  It ran startUp (plugin Settle/Refresh, FoldCopies, Hold, the agent
  moves), the plugin host and every account's model fetch, then failed
  to bind, exited 1 and was started again 5s later: 6,035 times in two
  days, a 279MB serve.log, and logins.json.lock held against the app's
  requests until they went 504.
- The copy an update left (.magpie-update/old) handed the socket over,
  hid, and lived on ~3h, its loops writing beside the new one.

What changed:

- cli: `magpie serve` (no --web) checks codexrelay.Leave,
  gateway.ServedBy and gateway.Taken before startUp, as the app's
  serveGatewayLocked does. While the port is held it prints one line
  and looks again every 15s, doing nothing else. Once the port is free
  it serves (serve_wait.go). It waits rather than exiting 0: under
  KeepAlive SuccessfulExit:false a clean exit would leave no service
  after the app quits.
- gui: after a handover the old magpie's loops end with backendCtx:
  - library.KeepLinked (now takes a ctx),
  - provider.WatchQuotas,
  - the menu bar usage loop,
  - the updater's check/auto-restart loop.
  lighten lets its hidden webviews go as lightweight mode does, so
  their polls stop. quitBy exits it at handedOffDrain + 3m whatever
  holds its quit up (gateway.HandedOffDrain getter; exitNow stubbable).
- docs/subsystems/gui-shell.md says both.

Run at the pushed head on mote (mote-run):
- gofmt -l internal/: nothing. go vet ./internal/{cli,gui,library,gateway};
  GOOS=linux go vet -tags nogui and GOOS=windows go vet of the same: ok.
- go test -count=1 -timeout 45m ./internal/cli ./internal/library
  ./internal/gui ./internal/gateway at bf05291e2 + this: cli and
  library ok. Two reds, both already filed:
  - gui TestMainWindowCorners/macOS_26_SDK (#3949). It is red the same
    on origin/main 443e53d6b, run alone.
  - gateway TestCodexPoolSaysTheClientsVersion (#4807). It is red only
    in the full package run, and passes alone 5 of 5 at this head.
- After rebasing on 8819beeb0, on that head: the vets above; cli and
  library in full, ok; gui and gateway with -run for handover, handoff
  and lightweight, ok.
- Sandbox HOME on mote, a fake app answering / as magpie 0.1.2770 on a
  private port (3593), `magpie serve` built from this tree beside it:
  alive after 8s at 0% CPU, nothing written under HOME, one standby
  line. 20s after the fake quit it served the port. The same with the
  old wait call removed: "magpie: listen tcp 127.0.0.1:3593: bind:
  address already in use", exit, and plugins.yml and lock files written
  first.

Broken by hand, each red:
- No wait before startUp: TestServeWaitsForTheGatewayBeforeStartingUp
  ("ran the start-up moves while another magpie served the gateway").
- KeepLinked ignoring its ctx: TestKeepLinkedEndsWithItsContext
  ("went on after its context ended").
- No quitBy in handover.run: TestRestartHandsTheGatewayOver ("has no
  deadline to quit by").

Not tried:
- A real launchd service beside the real app, and a real update
  handover on a Mac. Neither was run: no live app or launchd.
- The lighten change (needs Wails webviews) has no test.
- Not done here: serve.log rotation, `magpie daemon install` beside a
  running app (#4887), the old copy's appPage port, and Bug 1 and
  Bug 3 (ggbdpq has Bug 1).

cdredfox on Discord reports ~270% CPU after v0.1.2770. That fits this,
but it is not confirmed as their cause.
2026-11-03 11:16:02 +08:00
yetoneandJunyu Zhou 8819beeb0e gateway: a display reads routing as it happens at /v1/magpie/route-events (#3387)
joe21_eee (sywyyhykkk on GitHub) wrote this for an ESP32 screen that
shows each agent's requests live: started, each try, the first content,
fallback, done. Ported from their route-events branch (42e1fa43f) with
the changes below.

What a display gets (route_events.go):
- GET /v1/magpie/route-events/snapshot: cursor, active, routes (every
  request the trace has that is still going).
- GET /v1/magpie/route-events?after=<cursor> (or Last-Event-ID): SSE,
  one "route" event a change, id = cursor, from a 512-change ring under
  trace.mu, so a short request is told step by step. 409
  snapshot_required for a cursor not this process's or too old, "event:
  reset" for a reader that fell behind, a heartbeat every 15s, a 10s
  write deadline.
- A route is routeActivity, an allow list: trace id (base 36), time,
  agent label, the provider of the seat the last try went to (never the
  seat id, which names an account or a key fingerprint), model, attempt,
  fallback, phase, status, failed, ms, ttft_ms. No session, account,
  key, folder, prompt, reply or error text.
- firstToken.onFirst tells the first content as it comes (serve and the
  ChatGPT backend's reads), written to an unexported Try.firstMs so the
  full trace's TTFT is unchanged.

Changed from the branch:
- No new key type. The branch added an "sk-magpie-route-" key, its CLI
  flag and its own Authenticate path through access, identifyCaller and
  corsGuard. main has read-only keys now (readOnlyGuard), and the feed
  is answered as /v1/magpie/usage is: this computer, and another machine
  with an enabled key while shared; a held key is refused (refuseHeld).
  Both GETs are in readOnlyRoutes, so the display gets
  `magpie gateway-key add Screen --read-only`. A full key already reads
  more than this (every call's usage). access, cli, cors.go and lan.go
  are untouched.
- A route the trace drops unfinished (drop: an unrouted request's
  stand-in once its own route begins; trim past twice traceKeep) is told
  request_dropped and marked offFeed. The branch kept its own active map
  that only "done" cleared, so a stand-in stayed going forever. The
  snapshot is read from t.routes, no second map.
- A stream ends when the gateway stops serving (Server.streamsEnding,
  closed first thing in ListenAndServe's drain). Before, an open stream
  held srv.Shutdown for its whole drain, 15 minutes on a handover.
- Revocation is access.On(KeyID) (identifyCaller swaps the secret out
  before handlers see it), asked at most once a second when there are
  changes and at every heartbeat, and remoteKeyed for a remote reader. A
  rotated key keeps its id, so its open stream goes on until it
  reconnects (said in the docs).

Docs: gateway-routing.md "Route events for a display" and the
read-only key's route list; reference.md beside the usage API.

Run at the pushed head on mote (Go 1.26.8):
- At daaafeb6e (rebased on ffc4aa684): gofmt -l internal/gateway empty;
  GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  ./internal/gateway ./internal/access ok; go test -race -run
  'TestRouteEvents|TestReadOnlyKeyEveryRoute' ./internal/gateway ok.
- At daaafeb6e, every package that imports the gateway: internal/agent,
  browsermcp, cli, davsync, imagemcp, library, settingsapi, tui,
  access and the root package ok. internal/gui: one red,
  TestMainWindowCorners/macOS_26_SDK, which is #3949 (mote runs macOS
  27; this change touches no GUI code).
- Before the rebase (eb779ce92 base; gateway and access are the same
  at ffc4aa684): go build ./..., go vet, and the whole internal/gateway
  package, -timeout 45m. All ok except TestCodexPoolSaysTheClientsVersion,
  which is #4807 (red in a full package run on mote, passes alone; it
  passes alone at origin/main bf05291e2 too).
- At the pushed head (rebased on 443e53d6b, which changed search.go):
  gofmt, go vet ./internal/gateway and the -race run above again, ok.
- Not run: go test ./... in full. Other sessions' suites had mote at
  load 60 to 120.

Broken by hand (each on mote, then restored), the test that went red:
- serve's onFirst line removed: TestRouteEventsLiveFallback.
- drop's request_dropped removed: TestRouteEventsDroppedRouteGoes.
- the offFeed check removed: TestRouteEventsDroppedRouteGoes.
- the streamsEnding case removed: TestRouteEventsEndWithTheGateway.
- refuseHeld skipped: TestRouteEventsTold.
- the access.On recheck skipped: TestRouteEventsReplayAndRevocation.
- the snapshot taken out of readOnlyRoutes: TestRouteEventsTold,
  ReplayAndRevocation, LiveFallback.
- the seat's id told for its provider: TestRouteEventsReplayAndRevocation.
- the handler's own local/sharedWith gate removed: still green, since
  lanGuard refuses another machine first when not shared. It stays, as
  usage's does.

Not tried: an ESP32 or any real display, a real gateway with real
agents (tests drive httptest servers and fake upstreams), a handover
between two real magpie processes.

Co-authored-by: Junyu Zhou <feijifeibudao@gmail.com>
2026-11-03 11:06:59 +08:00