Commit Graph
6078 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 78cd4e6dd4 sessions: a call through magpie in Cindy is counted once, as the gateway's (jealousy03888)
jealousy03888 on Discord: "cindy里用Zcode订阅 同一个请求两个记录是特性吗".
Their Routing list had one ZCode GLM-5.3 request twice: the gateway's row
(ZCode · api.z.ai, 135/37/84,736 tokens, ~$0.026) and five seconds later
a "local session" row on the provider "magpie-beedee1a" with the same
tokens and cost, so Usage and the Requests totals counted it twice too.

Cause: Cindy's import parser gives a custom provider the link's id plus
eight hex digits of a new UUID (`${id.slice(0,24)}-${randomUUID()
.slice(0,8)}`, read in Cindy 0.1.94's app.asar), so magpie's link (id
"magpie") becomes "magpie-<8 hex>", and Cindy's Pi writes that id on
every reply. The Pi reader left out only "magpie"/"dial", so Cindy's
calls through magpie were read as Cindy's own beside the gateway's.

Now piGateway(agent, provider) also takes "magpie-" + eight lowercase
hex digits as magpie's entry, in Cindy's files only (Pi's own and omp's
providers are named by the user; magpie writes "magpie" there). A
provider the user adds by hand in Cindy under the name Magpie gets the
slug "magpie" or "magpie-2", never this shape. callParseVersions raises
cindy to 1, so Cindy's call shards written before are read again once
on update and the duplicates already shown go away (usage's request and
heat caches key on CallCacheVersion, so they are rebuilt too); no other
agent's shards are re-read.

Every other agent's reader was checked for the same gap (an id the app
chooses rather than magpie): OpenCode and ZCode ("magpie", written by
magpie), dsh (magpie's three route names), MiniMax Code
(custom_provider:magpie), Kimi ("magpie/" model prefix), WorkBuddy and
CodeBuddy (models.json vendor magpie), Grok Build (its config.toml
tables), Pi, omp and Raft (models.json "magpie"), Claude Code, Codex
and Antigravity (paired with the gateway's rows by session, response id
or tokens and time). Cindy is the only one whose provider id is made by
the app; Lody and AionUi also import a link but their sessions aren't
read.

TestCindyGatewayCallsCountedOnce puts a Cindy Pi session shaped like
the report (provider magpie-beedee1a, zcode/GLM-5.3, 135/37/84,736,
durationMs 5292) and a reply on a user's own "magpie-relay" into
Cindy's session folder; the first must not be a call, the second must
be one. TestCallParseVersionRaiseReadsThatAgentAlone now restores the
real versions after it.

Run (on mote): gofmt -l internal/sessions (nothing); go vet;
GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go build
./... all ok. go test -tags nogui -timeout 45m ./... at 40a287b21+this:
86 packages ok, internal/cli red on two filed reds outside this change:
TestEveryRouteHasACommandOrIsNamed (GET /api/context/reply, #5026,
red alone too) and TestLibraryMCPHub (#4140, passes alone). Rebased on
c3593dc49 (no sessions or usage change between) and run again at the
pushed head: internal/sessions ok, internal/usage ok.

Broken by hand: piGateway's Cindy branch replaced by `return false`:
TestCindyGatewayCallsCountedOnce FAIL ("a call through magpie's link in
Cindy counted as Cindy's own: ... Upstream:magpie-beedee1a ...").

Not tried: a real Cindy session through magpie (none on this machine;
the shape is from Cindy's source and the reporter's screenshot); the
Sessions overview's session count for Cindy, which counts sessions,
not calls, and was not changed.
2026-11-03 18:15:07 +08:00
yetone c3593dc494 provider: the Cursor mover's min is 0.2.39, which lists the Claude Cursor hides from an account once per context size (plugins#634, jiaohanying)
@magpie-community/opencode-cursor-auth 0.2.39 (plugins b8ec827 by
jiaohanying, released in 0236317) asks Cursor's full catalog
(AvailableModels scope 3) alongside the picker. An account Cursor blocks
Claude for, whose picker has no Claude while cursor-agent's usable list
does, now gets those models as the picker's are listed: once per context
size (claude-opus-5-5@300k and @1m, 1m in Max Mode), the efforts the
account is served, and only the parameters the model defines (the
catalog's Opus 4.7 to 5.5 variants carry cyber=false, which is not
sent). Before, each such family was one fallback entry with a 200K
window. 0.2.39 also carries 0.2.38 (OpenCode 2.x entry, plugins#657).
Raising the min lets keepMovedCurrent bring every moved Cursor user up
to it.

npm view --prefer-online @magpie-community/opencode-cursor-auth version:
0.2.39 (latest) before this commit.

Run on mote at this head: go test -count=1 -run
'Mov|Migrat|Retir|HandOver|Adopt|Plugin|Cursor' ./internal/provider ok;
GOOS=linux and GOOS=windows go vet ./internal/provider ok; gofmt -l
clean. Plugin side (reviewed head f4cb8ed and the squash on main):
bun test packages/cursor 393 pass, whole bun test 0 fail, check.mjs ok;
the cyber test goes red with the parameter filter taken out.
Not tried: a real Cursor account (none for this run); the author ran a
real request at 300k and 1m on a blocked account.
2026-11-03 18:03:57 +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 0acba61a35 gui: a lone plugin's check-in tab is named for it, not "Plugins"
ljq906416 and justrun_way on X couldn't find WorkBuddy's daily check-in
after it moved to its plugin. The WorkBuddy plugin (0.2.0 on) checks in
itself, so magpie hides its own WorkBuddy tab under Settings › Usage's
check-in tabs and the switch sits under a tab labelled "Plugins" (插件),
which nobody looking for WorkBuddy reads. With one plugin checking in,
the tab now carries that plugin's name (WorkBuddy), as a built-in's tab
does; two or more still share "Plugins". The label is set through
data-en, so a language change keeps it.

Run (wsl-run, Linux, Chromium + WebKit, en/zh/zh-TW/ja/de):
plugin-checkin, checkin-reason, checkin-reason-once and i18n-keys:
64 pass, 0 fail. The new two-plugin test checks the shared tab's
translated name and both rows; the 440px test checks the lone tab reads
"FakeCo".
Broken by hand: with the old app.js the 440px test fails in chromium en
and zh (expected FakeCo, read "Plugins"); the two-plugin test passes
there, as it guards the shared case.
Size budgets summed by hand the way TestCoreScriptBudget does (the Go
package needs cgo, which wsl lacks): app.js 1,308,499 of 1,316,874,
core 1,529,963 of 1,533,802, no raise.
Not tried: the real app with a signed-in WorkBuddy plugin.
2026-11-03 17:58:06 +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 8c1ee85f91 provider: the Devin mover's min is 0.1.35, which keeps Claude's thinking signature (plugins#665)
@magpie-community/opencode-devin-auth 0.1.35 (plugins a064cf1, Vigilans'
report) reads delta_signature (10) and delta_signature_type (21), puts
the signature on a Messages reply's thinking block (signature_delta when
streamed), and sends signed thinking back on the next request's
assistant prompt with signature and signature_type. Raising the min lets
keepMovedCurrent bring every moved Devin user up to it.

npm view --prefer-online @magpie-community/opencode-devin-auth version:
0.1.35 (latest) before this commit.

Run on mote at this head: go test -run
'Mov|Migrat|Retir|HandOver|Adopt|Plugin' ./internal/provider ok;
GOOS=linux and GOOS=windows go vet ./internal/provider ok; gofmt -l
clean.
Not tried: a real Devin account (none in a sandbox).
2026-11-03 17:34:39 +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 2e4735f8f8 provider: WorkBuddy's mover min is 0.2.20, whose China accounts tell routing when their extra credits lapse (Kayphoon)
Kayphoon on Discord asked that routing spend first the WorkBuddy CN
account whose extra-credit packs expire soonest. Smart already orders
accounts by the soonest lapse a window it reads says (Allowance.Renewal,
Lapse, Pace), but extra credits only WorkBuddy's detail lists have
(plugin 0.2.17's "Extra credits" window) said their lapse only on that
window, which is set aside, and routing reads none set aside. Plugin
0.2.20 (magpie-community/plugins 311d628) puts it on the Credits window
too; keepMovedCurrent now brings every moved user to it.

Run at this head (mote): gofmt -l internal/provider empty; go test
-timeout 45m ./internal/provider ok. npm view --prefer-online shows
@magpie-community/opencode-workbuddy-auth 0.2.20.
Not tried: a real WorkBuddy CN account with expiring packs, routed
through the gateway.
2026-11-03 17:04: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 c0d4f17a34 provider: Qoder's mover min is 0.2.59, usage with each pool's count and the plan's refresh (jzing.draw)
jzing.draw on Discord (#feedback, 2026-11-03): Qoder's own panel said
套餐内 Credits 1,817 / 2,000 (refreshing 2026-11-22) and 资源包
2,400 / 3,400, while magpie's Routing row said a bare "剩余 15%".

Plugin 0.2.59 (magpie-community/plugins 1984cf6) sends amount, limit
and unit on Total credits and on each pool, and the plan's Credits window
resets at expiresAt. The Routing row and the Usage card now say
"1,183 / 5,400 credits · 22% left", Qoder's 183 + 1,000. Raising the min
lets keepMovedCurrent bring every moved Qoder and Qoder CN user up to it.
0.2.58 (OpenCode 2.x loading, plugins #657) is named too.

npm has 0.2.59: npm view --prefer-online --registry
https://registry.npmjs.org @magpie-community/opencode-qoder-auth version
-> 0.2.59.

Run at the pushed head (mote): go test -run 'Mov|Migrat|Qoder|Plugin'
./internal/provider ok; GOOS=linux and GOOS=windows go vet
./internal/provider clean; gofmt -l clean. The plugin's own bun test
packages/qoder: 382 pass, 0 fail.

Not tried: no real Qoder account. The reporter's 15% (85% used) isn't
reproduced from their screenshot's numbers, which leave 22% together.
2026-11-03 16:43:21 +08:00
yetone 219b60f494 accounts: the first account of a gateway-served subscription ticks off (Rime_Nan on X)
Rime_Nan on X: in WorkBuddy's account list the first account (First) couldn't be ticked off; it took dragging another account above it first. For a subscription the gateway serves itself (plugins, Copilot, ChatGPT API, Gemini, Antigravity), First is only the order the gateway tries accounts in; no agent is signed in to it. setSideLoginOn still refused it ("put another account first"), and the GUI drew its tick fixed.

Now, unticking the first account hands First to the next ticked account that hasn't lapsed and turns this one off. If no other account is ticked, it is still refused, with "tick another to stop using it", and the GUI's fixed tick says the same. An account the user left off is never ticked on. Claude and Codex (pausable) are unchanged.

To keep the core scripts in their budget without raising it, the bytes were paid for by cutting renderAccounts' comment to one line: app.js is +20 bytes, under 1,533,802.

TestCopilotAccounts asserted the old refusal; it now checks the handover and that the only account in use still can't be ticked off.

Run (mote, macOS 27, at f9dda0d3e on origin/main f0e0385a0):
- go test ./internal/provider: ok.
- internal/gui: TestCoreScriptBudget and TestI18n ok.
- gofmt clean; GOOS=windows go vet ./internal/provider ok; at the earlier base, GOOS=linux go vet ./internal/provider and GOOS=windows go vet ./internal/gui ok.
- GUI first-untick.test.cjs (both engines, en/zh/zh-TW/ja/de) and i18n-keys: 24/24.
- Earlier base 694f4a6d6: the whole internal/gui package on mote, red only in TestMainWindowCorners (#3949, macOS 27) and the budget, since fixed. internal/provider passed on Linux (WSL); internal/gui doesn't build there (no gtk4/webkitgtk-6.0 dev packages).
- GUI keep-login, settings-tabs-stick, view-no-sideways, *account*, *plugin*, *copilot* at the earlier base: 1773/1783. The reds, run alone, are red on origin/main 694f4a6d6 as well: plugin-move-unserved's Try again (#4410) and account-eye's Usage card subtest (filed #5052).

Broken by hand: with the old setSideLoginOn, TestFirstTickedOffHandsFirstOn and TestOwnFirstCopilotTickedOff fail ("magpie uses a@x.com first; put another account first"). With the old app.js, first-untick.test.cjs fails 10/10 in Chromium.

Not tried: unticking with a real WorkBuddy plugin account in the app; the tests use Antigravity and Copilot saved logins, and the GUI test uses a stubbed Copilot provider.
2026-11-03 16:43:12 +08:00
yetone f0e0385a0e routing: a row's model chip is whole; its status is what is cut short (yi_time)
yi_time on Discord (#feedback): on the Routing page, a group member's
row that was answering showed its model chip cut to "gpt-6.1-te…".
The status after it ("回答中… · 按意图"任务主要依靠视觉或界面…")
took up to 60% of the row (fit-content(60%)), and the head, with the
account, plan and model as one inline run, was cut at its end, which
is the model. So which model answered didn't show. The same happened
in a fold of keys, whose status column was auto, and at narrow widths,
where a long account name pushed the chip off.

The head's column is now as wide as its content (minmax(0,
max-content)). The status takes the rest and keeps at least
min(14em, 40%), cut short with an ellipsis. Inside the head, the
account name, then the plan, give up room. The chip and its
fast/fallback tags never shrink. Folds get the same columns, and their
status still wraps. A status beside the name is right-aligned, as
before. Under the name (max460/max560) it starts at the left. A status
cut short is read whole on hover: its em gets a title when the pointer
finds it overflowing. Measured on pointerenter, not each render
(#3164). Resting rows keep their rest tooltip; the intent and session
titles are as before. Sibling of 889767b7b (the failure tag cut).

Run:
- routing-model-chip-whole.test.cjs (new). Rows: answering with the
  reporter's intent text (the prefix their screenshot shows, then
  more), one gone on from (429), one failed to the agent (504), one
  resting, a plain provider row, and a fold of three keys. Models
  gpt-6.1-terra, gpt-6.1-sol:medium, gpt-6-astra:high and gpt-6-luna:low,
  plan prolite. en, zh, zh-TW, ja, de; Chromium and WebKit; 1600 and
  1280 wide (status beside the name, as the reporter had it) and 420
  (under it). Checks: every chip inside its head, at least 40px left
  for the status beside it, the intent row's status cut and titled
  whole, every cut status titled on hover, no sideways scroll.
  - On mote: 90 of 90 ok.
  - On WSL at 4a2bf73a0 (this change on bc10a6198): 90 of 90 ok.
  - Old code (origin/main with only the test added): 85 of 90 red at "the
    model's chip is whole" (gpt-6.1-terra in 53, the fold's chip in
    30), the reporter's case at 1600 among them.
- The 257 GUI files that reach the Routing page, plus i18n-keys, both
  engines, on mote at the pre-rebase head (load ~300). The run was
  stopped at ~680 results, with 12 reds in 9 files: codex-subagent-model,
  group-editor-selected, group-first-token, group-found-skip,
  group-from-model-add, group-member-weight, last-page, menu-input-scroll
  and mobile-web. None of them reads .rt-accts rows. Those 9 files on
  WSL, at this change and at origin/main bc10a6198:
  - At the change: 3 reds, group-editor-selected webkit and mobile-web
    in both engines.
  - At main: the same 3, plus codex-subagent-model chromium zh 560 and
    group-member-weight webkit en 420.
  Filed: #3952 (mobile-web), #2387 (group-member-weight), #5049
  (group-editor-selected), #5050 (codex-subagent-model).

At the pushed head (rebased on b967b1620, which touches no Routing
file):
- The new test and i18n-keys on WSL: 94 of 94 ok.
- go test ./internal/gui on mote: red only in TestMainWindowCorners,
  which is red the same way on origin/main b967b1620 (#3949, macOS 27).

Not tried: the rest of the 257 files after the stop; the real app's
WebKitGTK and WebView2; the reporter's own account and window width.
Screenshots were looked at by eye in Chromium only (zh 1600 and 420,
live and fold).
2026-11-03 16:37:33 +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 9c51f7fdbc gui: "deepseek-v4.1-flash tokens (est.)" is said in every language
WorkBuddy 0.2.19 (plugins #663) names the China build's token window
"deepseek-v4.1-flash tokens (est.)". The GUI shows a window's name through
t(), so zh, zh-TW, ja and de read it in English. Added beside "Free model
tokens" in i18n.js, and to TestPluginWindowWordsSaidInEveryLanguage's
workbuddy words, so a missing translation is red.

Run on mote at this tree: go test ./internal/gui (ok except #3949's
TestMainWindowCorners/macOS_26_SDK, unrelated, red alone on macOS 27);
node --test internal/gui/tests/i18n-keys.test.cjs 4/4.

Not tried: the card's look in the GUI with a real China account.
2026-11-03 15:21:17 +08:00
yetone 58af17aca7 provider: WorkBuddy's mover min is 0.2.19, the China window says it is an estimate (kunghim)
opencode-workbuddy-auth 0.2.19 (plugins #663, kunghim) renames the China
build's token window from "Free model tokens" to "deepseek-v4.1-flash
tokens (est.)", since on copilot.tencent.com that model is charged x0.11
credits (testdata/config-561.json), and the window's ~200M cap is magpie's
own estimate: "151.5M / ~200M". WorkBuddy AI's card is unchanged. 0.2.18
was #657's OpenCode 2.x entry. keepMovedCurrent now updates every moved
user to 0.2.19.

npm view --prefer-online @magpie-community/opencode-workbuddy-auth@0.2.19:
version 0.2.19, sha512-8qnqnKk3/qOxZxZI+klWx7V/WX1FHvrSCRaZOvN63givYmQ355YpPob7gL7hjaHLDu8gmaq7jTb6aXBd8o3LDg==

Run on mote at this tree (origin/main 3088872e6 plus this and the next
commit's i18n words): go test -count=1 ./internal/provider ok (256.8s);
gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet of
internal/provider and internal/gui ok. internal/gui: everything ok but
TestMainWindowCorners/macOS_26_SDK, the macOS 27 red filed as #3949 (red
alone too, an AppKit title-bar test).

The plugin itself was reviewed on plugins #663: full bun test 4900 pass,
check.mjs ok, and a load in magpie's host.js with a faked meter showed the
China card as "deepseek-v4.1-flash tokens (est.)" 151.5M / 2e8, aside.

Not tried: a real WorkBuddy China account's card after the update.
2026-11-03 15:21:17 +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 8ee172ca03 search: a Codex account searches with its cheap model, not the flagship its list starts with
lucy_85908 (Discord #feedback, v0.1.2682) ran a third-party model in Codex
and found each web search magpie ran for it logged as Anthropic -> Responses
on gpt-6.1-sol, 10,532 tokens in, through the Codex account. The searcher
was picked right (a Codex account searches for models that can't), but its
model was not. smallCands ranks a provider's models by small-tier name
(haiku/mini/flash), then m.Price. A subscription's list has no prices, and
GPT-6 has no mini, so every Codex model ranked equal and the first listed
(gpt-6.1-sol) was used for every search and every AutoVision description.

Now a model with no price on the list is ranked by its list price
(Provider.ListPrice, the price the Usage page counts it at). "luna" is a
small-tier word beside mini, for when no catalog is loaded yet (the same
rule warmPick has used since #604). codex-auto-review is left out: it is
free only for the reviews it runs. A searcher or model named in Settings
-> Web search still wins (namedSearcher is unchanged). The fix is in the
pool AutoVision shares, so a Codex account's image descriptions now go to
the cheap model too.

Not changed: Codex's web_search = "cached" (external_web_access:false)
is still dropped when magpie searches for a model that can't; filed as
#5018.

Run at the pushed head (mote-run):
- go test ./internal/gateway -run TestCodexSearchesWithItsCheapModel
  (new), and with Search|Searcher|Vision|Small|TestRankSmall|TestAutoVision:
  ok.
- go test -timeout 45m ./internal/gateway at the pushed head (rebased on
  06944e065): ok (714s). ./internal/gui (before the rebase, which touched
  no gui file): ok but TestMainWindowCorners/macOS_26_SDK, red alone too,
  open as #3949 (mote is macOS 27).
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok; gofmt -l
  clean.
Broken by hand: with search.go as on main, the test is red
("searcher = codex/gpt-6.1-sol with no catalog, want codex/gpt-6-luna").
With the list-price fill alone turned off, it is red at the priced
no-luna list (gpt-6.1-sol, want gpt-6-sol).
Not tried: a real search on a Codex account with gpt-6-luna. Its
models.json entry has web_search_tool_type text_and_image and
use_responses_lite, the same as gpt-6.1-sol.
2026-11-03 14:09:03 +08:00
yetone 889767b7b3 routing: a failed try's tag over its row is whole until it fades (yuancjun)
yuancjun on Discord (#feedback, v0.1.2784, Chrome 128 on macOS): a member
row's failure tag ("504 · 迟迟未开始") showed whole for ~0.45s, then its
top half, the ~10px over the row's top edge, was cut off until it faded
at 1.8s. Their analysis was right: `.rt-accts .tag` sits at top:-10px,
`.rt-accts li:not(.hit)` has content-visibility: auto (#3164), which
always paint-contains, and rerun() takes `.hit` off on the shake's
animationend at 0.45s while `.tagged` stays 1800ms.

The row is now drawn whole by a class of its own, `lift`, put on with
`tagged` and taken off 300ms after it, once the tag's .25s fade-out is
over: with `:not(.tagged)` alone the tag's top would be cut again for
the whole fade. The CSS rule goes on `:not(.lift)`; `.hit` always came
with the tag, so it adds nothing there. A row tagged again within 1.8s
(the next try failing on it) starts the 1.8s over: the first failure's
timer used to take the second tag down early. This is the only place a
row is tagged; nothing else in .rt-accts stands over a row's edge.

Run on mote (load 70-110 from other sessions' suites):
- routing-tag-whole.test.cjs (new): Chromium and WebKit, en, zh, zh-TW,
  ja, de, 1100 and 420 wide, motion on (the shake must end for the cut
  to show): 20 of 20 ok. It plays a live request failing 504 slow,
  checks the tag's words, then at ~0.8s screenshots the band of the tag
  over the row's edge and counts the tag's red in it, checks the row's
  content-visibility while tagged and while it fades, and that rows go
  back to auto after.
- At the rebased head (on 06944e065): routing-tag-whole, i18n-keys and
  routing-held-dot, both engines: 44 of 44 ok.
- Before the rebase (on 2c214ce25), every routing-*.test.cjs and
  panel-routing*.test.cjs, i18n-keys and claude-subagent-tag, both
  engines, concurrency 6: 2301 of 2342 ok, routing-tag-whole 20 of 20.
  The 41 reds are in routing-many-keys, -order-unknown, -row-swap,
  -rule-drag, -rule-remove, -rules-line, -sign-in-again, -steady,
  -steps-cap and -story-shrinks. Those ten files again at concurrency 2:
  30 red at this change, 23 at 2c214ce25 without it, the same tests
  (row-swap, rule-drag, steady, steps-cap, story-shrinks, order-unknown
  webkit de 420 red at both; rule-remove and rules-line vary by run).
  None of them reads .rt-accts content-visibility or the tag. Filed
  already: #4585 (these files under load), #3799, #3789, #4627, #4628,
  #4629.

Broken by hand: the CSS back on `:not(.hit)`: 20 of 20 red at "a tagged
row is drawn whole"; with that check taken out, the screenshot check
alone is red in both engines with 0% of the band red (8 of 8, en and zh).

Not tried: the real app's WebKitGTK and WebView2; Chrome 128 itself
(Playwright's Chromium is newer).
2026-11-03 14:01:55 +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 17f2387e10 gateway tests: each test's Codex pool starts from no Codex client seen (#4807)
TestCodexPoolSaysTheClientsVersion was red in full internal/gateway runs
on mote and passed alone: the pool signed its request as
codex_cli_rs/0.165.0 where the client said 0.161.0. 0.165.0 wasn't mote's
installed Codex (none is on mote's PATH, and the package's TestMain puts
an inert codex stand-in first anyway). It was another test's client:
provider.codexSeen keeps the newest version any Codex client sent through
CodexPath for the process's life, and
TestRemoteMagpieCodexModelKeepsLiteOnCodexPath sends
"codex/0.165.0 (Mac OS 27.2; arm64)" with an originator there. Any later
test then had its pool say 0.165.0. codexVersionCache (the installed and
models_cache version, kept ten minutes) is the same kind of state, read
in whichever test's HOME asked first.

provider.ForgetCodexClientsForTest clears both, and the package's fresh()
(which codexSignedIn and the other pool tests start with) calls it, as it
already clears Copilot's and the cards' caches. The test's assertion is
unchanged.

Run on mote at this tree:
- old code: go test ./internal/gateway -run
  '^(TestRemoteMagpieCodexModelKeepsLiteOnCodexPath|TestCodexPoolSaysTheClientsVersion)$'
  red every time, "request 0: User-Agent codex_cli_rs/0.165.0 (Mac OS
  27.2.0; arm64) Apple_Terminal/455", as in the issue's comments.
- new code: the same pair -count=3, 3 of 3 ok.
- go test -tags nogui ./internal/gateway -run
  "Draw|Drawing|Relay|Codex|UpBytes|TrysSecondAsk|OneAuth|TestClaude|TestWorkDir|Lite"
  (the set a comment on #4807 found red): ok, 183s.
- go test ./internal/provider -run Codex: ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of provider and
  gateway ok.

Not run: the full internal/gateway package. Three other sessions' full
gateway suites were running on mote, and one suite runs per machine.
2026-11-03 13:12:01 +08:00