Commit Graph
2027 Commits
Author SHA1 Message Date
yetone 34116ec012 gateway: Codex signed in to one account lists another account's models
bigfisheatsmall on X: Codex was kept signed in to ChatGPT account A, on
the Free plan. Account B (Team) was the only account on in magpie. dsh
listed B's models and Codex didn't. codexMerged added CodexListed(),
which leaves out every ChatGPT account's own models because it assumes
the backend lists them. But the backend list is fetched with Codex's own
sign-in (A, Free), so B's plan-only models were listed nowhere. Routing
already sent codex/<model> to B (codexAccounts).

- provider.CodexListedBeside(backend) lists an account's own model by
  magpie's id (codex/<slug>) when the sign-in's backend list lacks it.
  codexMerged uses it, and FitOwn keeps those entries.
- spawnChoices (spawn_agent's models) had the same gap. It now uses the
  same rule with the slugs in Codex's models cache.
- buildCodexListTag covers the accounts' own models, so another account
  gaining or losing one has Codex ask for the list again. Every Codex
  asks once after the update.
- TestSyncCatalogAgesCodexCache built its "current" tag by hand from
  CodexListed(). It now uses provider.CodexListTag(), the tag SyncCatalog
  compares against.

Tests (sandbox HOME, fake backend with per-plan lists):
TestCodexListHasAnotherAccountsModels covers the list, routing of
codex/gpt-6.1-sol to the Pro account, and spawn_agent's choices.
TestCodexListOneAccountNoneTwice checks that a single account gets no
codex/ duplicates.

Run on mote at this tree: go vet (darwin, windows, linux) on gateway,
provider and agent: ok. go test -count=1 on provider, agent and
codexcat: ok. go test -run 'Codex|Spawn' on gateway and gui: ok. Run at
the tree before the sync_test change and the buildCodexListTag tidy: the
full gateway package was ok (1224s). Agent was red only in
TestSyncCatalogAgesCodexCache, fixed above.

Broken by hand: on the old codexMerged, the new test fails with "Codex's
list lacks codex/gpt-6.1-sol: [gpt-6-luna gpt-5.6-terra gpt-5.6-luna]".
With only codex_spawn_models.go reverted, it fails with "spawn_agent's
models lack codex/gpt-6.1-sol".

Not tried: real accounts or a real Codex. Not a full go test ./... run.
Not tried: models the backend marks hidden. A Codex here for failover
alone (codexOwnOnly) is unchanged.
2026-11-04 22:00:42 +08:00
yetone 1b579ca4f8 router: Droid and omp get the hub's tools whole; find_tools' description names each server and its tools
tao5010 on Discord (11-04): with the MCP router on, omp, pi and droid
rarely called the servers behind it. Asked for a picture of a cat, the
model searched three times and stopped, and found magpie-image only when
told "我的mcp有啊".

Since v0.1.2950 an agent not in hubSearchesItself with more than 10 tools
is given only find_tools and call_tool. Droid (0.231) defers every MCP
tool to its own ToolSearch, showing the model names only, and omp (18.9)
mounts MCP tools in a catalog by each description's first line. Both were
handed two opaque tools whose description said only how to search, while
the servers were named in initialize's instructions, which Droid doesn't
show and omp shows apart from the tool. Read from droid's binary and
omp's dist/cli.js.

- hubSearchesItself gets droid and omp: they search their tools
  themselves, so they get every tool whole as Claude Code, Codex and Pi do.
- find_tools' description, for every agent still given tools on demand,
  starts with HubLine (each server and what it is for, <= 250 chars), then
  how to search, then hubDetails (each server's tools) within
  hubFindSayMax = 1200 characters.

Ran on mote at this head:
- gofmt -l internal/gateway (clean); go vet -tags nogui ./internal/gateway
  on darwin, GOOS=linux -tags nogui, GOOS=windows
- go test -tags nogui -count=1 -run 'Hub|MCP|FindTools' ./internal/gateway: ok
- repro (sandbox HOME, magpie serve on 127.0.0.1:3563/3564, a fake stdio
  server with generate_image/generate_video/generation_result and one with
  12 tools, router on): the old build (b61c71448) gave omp, droid and
  opencode find_tools + call_tool with the generic description; this
  build gives omp and droid the 15 tools, and opencode's find_tools
  description names magpie-image (Generate and edit images…) and
  generate_image.

Broken by hand: with the old hubSearchesItself and find_tools' old
description, TestHubMCPToolsWhole fails ("droid listed [find_tools
call_tool]") and TestHubFindToolsSaysWhatIsBehind fails on the first
line; both pass with the fix.

Not tried: a real omp, droid or pi turn against this build (none is on
mote with a model). Pi already had every tool whole; its MCP extension
shows a server by a 250-char description, so with many servers
magpie-image may still be cut there. Not checked: whether other agents
(kimi, gemini, opencode, qwen) search their tools themselves. find_tools'
scoring ranks generation_result above generate_image for "image
generation" (unchanged).
2026-11-04 21:57:48 +08:00
yetoneandMYCF711 a1f1810e93 gateway: a 400 that only says the request is too long counts as an overflow once it is past half the model's window (#4420, MYCF711)
A group member answered 400 "内容太长了,请精简输入或开启新对话" at ~730K
on a model it declares at 1M. cfcd6648f added that wording to tooLongRe,
the word list. This change adds the judgment MYCF711 proposed as fix A,
so the next vendor that says it differently isn't missed the same way:
the vendor's words decide, and the request's size rules out other meanings.

tooLongUnsaid lowers its margin from unsaidMargin (1.2 of the window) to
lengthMargin (0.5) when saysLength holds:
- a 400 or 422,
- whose message has length words (lengthWords: 太长, 过长, 超长, 精简,
  缩短, 删减, 开启新对话/会话, too long/large/big, shorten, reduce the
  length/size, start a new conversation),
- no pace word (paceWords),
- and names no part of the request (partWords: a picture, a file, the
  reply, a field, a name, max_tokens),
- and tooLongUnsaid's own checks still hold: no quota, credit, model
  unserved, refusal or region words.
Its message is then "prompt is too long…". The overflow branch already
reads that as an overflow: the next member with room is asked
(failOverflow), nobody rests, and the conversation remembers the refusal.
With no member left, the agent is told the prompt is too long and
compacts. When the request is under the declared window, the message
no longer says "more than its context window". It says "more than <model>
takes here, though its context window is N".

Fix B, the word list in tooLongRe and paceWords, already landed in
cfcd6648f, with more wordings than the four proposed. Nothing was added
to it here.

Tests:
- TestLengthWordsPastHalfTheWindowGoToTheNextMember (new): for
  "请求过长,请精简后开启新对话" (raw and \u-escaped) and "Request too
  large. Please shorten it…", none of them in tooLongRe, a request of
  ~1500 tokens to a member of window 2000 goes to the next member: failOverflow,
  no rest. A short request keeps the vendor's 400 for the agent. A pace
  ("请求过长,已达到速率限制"), a file ("文件过长…") and "Image too
  large" aren't taken as the request's length.
- docs/subsystems/gateway-routing.md says it.

Run (mote, via mote-run, at this tree rebased on origin/main 7818dc316):
- go test ./internal/gateway -count=1 -run 'TestLengthWordsPastHalf|
  TestChineseInput|TestChineseNotTooLong|TestRelayInputCap|
  TestEveryVendorsOverflow|TestMemberTooSmall|Unsaid|TooLong|
  PayloadTooLarge|Roomy|Overflow': ok
- go vet ./internal/gateway, GOOS=linux -tags nogui, GOOS=windows: clean;
  gofmt -l clean. The full suite runs after the push, see the issue.

Broken by hand:
- lengthMargin replaced by unsaidMargin: the new test fails, (a 1, b 0),
  and the agent gets the 400.
- partWords dropped from saysLength: the new test fails, "文件过长,请精简后重试"
  taken for an overflow.

Not tried: the reporter's real vendor. The 0.5 floor comes from the
reporter's two cases, both refused past half of a 1M window. It is not a
measurement of other vendors.

Co-authored-by: MYCF711 <323101370+MYCF711@users.noreply.github.com>
2026-11-04 21:52:48 +08:00
yetone 7818dc316a gateway: a relay's Cloudflare 520 to 524 is asked again before the agent sees it, as a 502 or 503 is (vdaoren)
vdaoren on Discord: an API-key provider's 4xx/5xx now and then went
straight to the agent; they asked for retries on chosen status codes.

What a single API-key provider already did: the last one left is asked
again after a failure that passes (passing, fallback.go): 408, 500, 502,
503, 504 and 529 twice (lastRetries), a 429 that is a short rate limit
three times (rateRetries), pauses 1s, 2s, 4s or a Retry-After up to 8s,
then within the provider's patience (singlePatience, 60s by default,
`magpie provider set <id> patience=`) in rounds (busy, patience.go), all
while the reply is held and nothing has gone to the agent. A plan used
up, no balance, a 401, a request the vendor refuses for its content and a
conversation too long are the agent's at once.

What was missing: Cloudflare's own 520 (unknown error), 521 (origin
down), 522 (connection timed out), 523 (origin unreachable) and 524
(timeout), which a relay behind Cloudflare gives now and then, were in
neither list. Such a 5xx moved on to another member in a group, but on a
lone provider it reached the agent after one try. busyStatus now holds
the one list passing and busy read, with 520 to 524 added. No setting:
the default serves it, and patience= already exists for the length.

TestCloudflareErrorIsTriedAgain (retry_test.go): each of 520 to 524, as
Cloudflare words it to an API client ("error code: 520") and as its HTML
page, twice and then 200, is answered 200 after 3 tries; a stream's 524
then an SSE reply reaches the agent with nothing of the 524 in it; a 401
invalid key and a 400 content_policy_violation are tried once.
Broken by hand (busyStatus's list back to 408..529): red, every 52x case
"520 after 1 tries" and the stream "524 after 1 tries"; the 401/400 cases
pass either way.

Run on mote at this tree (base origin/main b61c71448):
- go test -tags nogui -count=1 -run 'TestCloudflareErrorIsTriedAgain|
  TestLastOneLeftIsTriedAgain|TestRateLimitIsWaitedOut|Patience|Overload|
  Busy' ./internal/gateway/: ok
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: ok (DARWIN-VET-OK, LINUX-VET-OK, WINDOWS-VET-OK)
- gofmt -l internal/gateway: nothing
- go test -tags nogui -timeout 45m ./...: not run before this push;
  two other sessions' full suites held mote, one suite per machine. It
  runs after the push, as agent-rules says, and a red is filed as an
  issue with its output.

Not tried: a real relay behind Cloudflare answering 52x (none at hand);
Windows/Linux runs of the tests (the change has no OS-specific code).
Docs: gateway-routing.md's busy list names busyStatus and 520 to 524.
2026-11-04 21:49:51 +08:00
yetone b61c71448c keys: a custom provider's key can be made for its Gemini API (corddis_114)
corddis_114 on Discord has a relay that gives out a key per protocol,
one of them for Gemini ("gemini sk-d…SarG"), and the key row's protocol
menu offered Any, Anthropic, Chat Completions and Responses only. A
custom provider already serves Gemini upstream (its Gemini URL, the
"Gemini compatible" tab, x-goog-api-key, the model list through
FetchGemini, probes), so only the per-key layer lacked it:

- keyProtocolOK takes "gemini"; WithKey leaves a Gemini key the Gemini
  URL only and takes the Gemini URL from a key made for another
  protocol (it had kept it, so an Anthropic key could be sent to
  generateContent).
- keyFit: a gemini* model (modelFamily Gemini) goes to the key made for
  Gemini first, the other keys in their order behind it; a GPT model is
  never put on the Gemini key (it ranked 0 there before). Claude's rule
  is unchanged.
- app.js: Gemini in PROTO_OPTS ("Gemini API (generateContent) · Gemini
  CLI, Gemini models"), offered when the provider has a Gemini URL;
  keyLacksURL says "No Gemini URL" for a Gemini key without one. The
  note in zh, zh-TW, ja and de. The provider-level tabs and Routing's
  "keys for Gemini" already had it.

Run on mote (go1.26.8):
- go test -timeout 45m ./internal/provider ./internal/gateway: both ok (provider 229s, gateway 938s).
- TestKeyMadeForGemini, TestKeyProtocolGemini, TestKeysMadeForOneProtocol,
  TestKeyForAProtocolWithNoURLIsSaid, TestKeyPoolsByProtocol,
  TestCustomGeminiUpstream ok; internal/gui's budget tests ok.
- GUI (node --test, Chromium and WebKit, en/zh/zh-TW/ja/de, 420 and
  1000px): key-gemini (new, 40/40), key-nourl, proto-menu-overflow,
  key-row-chips-fit, key-plan, key-import, key-weight-fit,
  provider-many-keys, provider-gemini, provider-add-gemini,
  provider-url-each-api, model-api-gemini, provider-base-api,
  routing-keys-fold and i18n-keys ok; the only red in the 360 was
  tencent-cloud's region-strip test (#4321, open).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on provider, gateway, gui ok.

Broken by hand: the old fallback.go turns TestKeyMadeForGemini red
(Gemini models went to the Chat or Anthropic key, GPT to the Gemini
one); the old keys.go turns TestKeyProtocolGemini red (unknown
protocol "gemini"), and WithKey keeping p.Gemini turns it red too (the
Anthropic key speaks [anthropic gemini]); the old app.js turns
key-gemini red in all 40.

Not tried: the reporter's relay or any real Gemini-compatible relay;
the real app's editor.
2026-11-04 21:21:32 +08:00
yetone 4062cda781 provider: a custom provider at a Token Plan's or Ark's address is asked for no access key (ysm119)
ysm119 on Discord saved a custom provider (no preset) at
https://tokenhub.tencentmaas.com/plan/v3 with a plain sk- key on the
OpenAI-compatible tab, and its editor asked for a SecretId and
SecretKey. AccessKeyVendor decides by host alone, so any provider at a
Token Plan's /plan address (or an Ark plan's) got the access-key fields,
and a Singapore Token Plan or Ark one also got a Usage card asking for
them.

Now AsksAccessKey(p) gates the two places a user is asked: the editor's
listing (gui/providers.go) and the keyless Usage cards
(tencentPlanQuotas, volcPlanQuotas). A preset's provider is asked as
before; a custom one only once it has an access key saved (so a key the
user did give is still shown and still used for its usage). The host
rules themselves are unchanged, since presetAccessKey and the presets
read them on providers with no preset of their own.

The key itself was already sent as typed: no Tencent signing exists on
chat, Responses, the model list or a probe; the access key only reads
plan usage. TestCustomTokenHubIsSentAsTyped holds that (Authorization:
Bearer <key>, on Chat and Responses).

Run on mote (go1.26.8):
- go test ./internal/provider ./internal/gui: provider ok; gui red only
  in TestMainWindowCorners (AppKit, #3949, macOS 27 on mote).
- TestPlanCardWithoutAccessKey, TestCustomTokenHubIsSentAsTyped,
  TestProviderListTellsTencentAccessKey ok.
- GUI (node --test, Chromium and WebKit, 5 languages): tencent-access-key,
  tencent-cloud, volc-access-key, usage-access-key-card, i18n-keys and
  the provider editor's key files ok, except tencent-cloud's "a region
  clicked right after the strip scrolled" (#4321, open, same on main).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on provider, gateway, gui ok.

Broken by hand: AsksAccessKey returning AccessKeyVendor(p) always turns
TestPlanCardWithoutAccessKey (my-ark gets a card),
TestCustomTokenHubIsSentAsTyped and TestProviderListTellsTencentAccessKey
(my-tokenhub, my-intl, my-ark asked) red.

Not tried: the reporter's real tokenhub key; the real app's editor.
2026-11-04 21:21:32 +08:00
yetone 7564e46690 library: a subagent names its model, written into Codex's role as model (#4421)
luckymanjc (Discord) set Codex's subagent model to Default on the Agents
page and gave a Library subagent a prompt that named a routing group.
Codex knew the group's name, but the subagent ran on Codex's own model.
A Library subagent had no model field, and Codex's role file
($CODEX_HOME/agents/<name>.toml) got only name, description and
developer_instructions. So Codex started the subagent on the model the
lead passed in spawn_agent, or on the lead's own model. The group was
only text in the prompt.

codex-rs reads a role file's model (AgentRoleOverrides). In
child_config.rs, prepare_agent_spawn_config applies the lead's
spawn_agent model, or [agents] default_subagent_model, first, and then
the role. So the role's model wins. A subagent now has a Model field: an
app menu with "Picked by the agent", the models and routing groups Codex
lists (groups noted as a routing group), and a saved id Codex no longer
lists. The Model is written as model = "..." to Codex's role only. A
subagent without a Model is written as before, byte for byte. Other
agents' files don't change; the hint names the agents that don't take
it. When the Agents page's Codex subagent model is set, the gateway still
puts that in place of the role's model (codexSubagentPick), and the hint
says so.

Run:
- Real codex 0.165.0 on mote, sandbox CODEX_HOME, fake Responses
  server. With no role model, the collab_spawn request carried the
  lead's model. With model = "group/review" in the role, it carried
  group/review, also when the lead named gpt-6-sol in spawn_agent.
- mote-run go test ./internal/library: ok. TestSubagentModelGoesToCodex
  went red with codexRole given "" for the model by hand.
- GUI library-subagents.test.cjs: 12/12 in Chromium and WebKit, in en,
  zh, zh-TW, ja and de. Red with origin/main's client.js (timed out
  waiting for the model picker).
- i18n-keys 4/4: it was red at first, because the plugin defined
  "Routing group" and "Find a model". The change now uses core's
  "routing group" and "Find a model…".
- gui-zh-tw, gui-ja, gui-de, library-all, library-gone-agents,
  library-wsl-asleep: ok.
- gofmt -l is clean. go vet, GOOS=windows go vet, and GOOS=linux go vet
  -tags nogui on internal/library and internal/gui: ok.
- go test ./internal/gui: only TestMainWindowCorners/macOS_26_SDK is
  red. It is red alone on origin/main 93d5c76c0 too: #3949.

Not tried: a real magpie gateway with a real routing group end to end,
the Codex app or IDE extension, and Windows and Linux runs. A
reasoning effort per subagent, and a model for Claude Code, OpenCode,
Droid and the other agents, stay open in #4421.
2026-11-04 21:18:56 +08:00
yetone 532d054bee sessions: every Cursor row has a delete, and the right-hand column lines up
ysm119 (Discord), Sessions page, Cursor tab: some rows had a delete and
some had none, and the time / "N sessions" column stood at a different x
from row to row.

Causes:
- Delete: listAgentWith set Deletable = Deletable(agent) && !ReadOnly, so
  every editor-transcript row (read only) came back deletable:false, and
  client.js drew .sm-del only for deletable rows.
- Alignment: a folder adds its ⋯ only when it has actions, and a session
  row's Resume / terminal / Continue in / delete come and go per row, so
  .sm-when, .cost and .num moved with them. "Copied" is wider than
  "Resume", and at <=600px the cost line wrapped at different places.

Change:
- rowDeletable decides per row. An editor transcript the editor no longer
  keeps (no state.vscdb, or it was read and has no composer for that id)
  is "loose" and deletable: Delete trashes only its <id>/ folder or
  <id>.jsonl/.txt, never state.vscdb. A chat the editor keeps, or a store
  that can't be read, stays undeletable with undeletable:"cursor-editor".
- In an agent magpie deletes from, every row has its delete. One it can't
  delete is aria-disabled, says why in its title, and a click shows the
  reason in the status line and sends nothing (en, zh, zh-TW, ja, de).
- A row without Resume, Continue in or a terminal, and a folder without
  its ⋯, keep that room with an inert, aria-hidden slot. Resume reserves
  the wider of Resume and Copied; at <=600px the cost keeps a min width.
- docs/subsystems/gui-shell.md says so.

Run (on mote via mote-run, base f44fa2ef6; origin/main 93d5c76c0's 3
commits since touch none of these files):
- go test ./internal/sessions: ok. go test ./internal/gui: ok except
  TestMainWindowCorners/macOS_26_SDK, an AppKit titlebar red on macOS 27
  already filed as #3949.
- gofmt -l clean; go vet native, GOOS=linux -tags nogui, GOOS=windows ok.
- New sessions-cursor-align.test.cjs: 10/10 (chromium + webkit x en, zh,
  zh-TW, ja, de; widths 1100/660/420, hover, Copied).
- Sessions GUI set (sessions-*, session-*, gateway-conversations,
  gateway-mode-sessions, account-mask-sessions, header-session-hint,
  routing-session*, routing-ctx-sessions, usage-session*, i18n-keys,
  gui-de, gui-ja, gui-zh-tw): 728/728, and 728/728 again after the
  rebase onto 93d5c76c0 (which changed app.css and i18n.js).

Broken by hand:
- rowDeletable forced to "read only": all 3 new Go tests red.
- sessionPaths' editor-path branch off: TestCursorLooseFlatTranscript red
  (it trashed agent-transcripts/ itself).
- Old client.js/sessions.css/i18n.js: new GUI test 10/10 red. Folder slot
  alone removed: red at 1100 (when 1071 vs 1037). Lanes removed: cost
  edges differ. Before the Copied and de 420 fixes, those cases were red.

Not tried: a real Cursor editor or a real ~/.cursor (every delete ran on
fixture copies in a sandbox HOME); the Windows and Linux apps; deleting a
chat from Cursor's own UI and seeing magpie's list follow.
2026-11-04 21:15:33 +08:00
yetone 93d5c76c0d router: an agent with many tools is given them on demand
ArvinCharl on X: the MCP router's tools fill the context. An agent that
doesn't search its MCP tools itself (all but Claude Code, Claude
Desktop, Codex and Pi) sends every tool's whole schema on every
request. Given more than 10 router tools, such an agent now lists two in
their place: find_tools (matches by name and description, the first 5
with their inputSchema, 15 more by name) and call_tool (runs one by
<server>__<tool>, its bare name, or arguments sent as a string; an
unknown name is told the close ones). The instructions still name every
server and its tools, and a tool called by its own name still runs. The
request log names the tool call_tool ran. The address for any other app
lists every tool, since which app connects isn't known.

Library → MCP gains a "Tools on demand" toggle (settings
routerAllTools, kept by KeepOwn and the settings API); turned off,
every agent gets every tool whole as before.

Run on mote (after the rebase onto 083821dc9: gateway vet, -run
'Hub|MCP|Settings|Search' and the four GUI files again, ok, 70 of 70):
- gofmt -l: empty. go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet of gateway, settings, settingsapi, gui, library: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/settings
  ./internal/settingsapi ./internal/gui ./internal/library: ok;
  ./internal/gateway -run 'Hub|MCP|Settings': ok.
- GUI (Chromium + WebKit, every language): library-mcp-router-tools,
  library-mcp-router-note, library-mcp-hub, i18n-keys: 70 of 70.
Broken by hand: hubOnDemand forced false turns TestHubMCPToolsOnDemand
red.
Not tried: a real OpenCode or Gemini CLI session against the router;
the full gateway package and full GUI suite.
2026-11-04 21:00:51 +08:00
yetone 083821dc96 plugins: a search entry can use the plugin's own sign-in, with its own rests
Asked for by axelburks on Discord. A plugin's search hook entry can name
a provider its own auth hook signs in to, `auth: "<provider id>"`. It then
takes no key. The host picks an account, renews it under `fresh` (the wait
counts within the search's time), runs the hook in `inScope`, and gives it
`ctx.getAuth()`, which returns that account's sign-in. A token the hook saves
with client.auth.set goes to the same account.

The gateway (askSearchSignedIn) asks one account at a time. It takes the
accounts that are on, in the order the provider's model requests take them
(accountsOn, now shared with fallback.go), and puts an account resting from
a search refusal last. A refusal rests only that account's search
(restSearchKey "account <key>"), never its models' rest (restingUntil). Every
attempt gets its own request-log row. An entry without `auth`, or naming a
provider the plugin doesn't sign in to, is a keyed entry as before, with no
getAuth. In Settings → Search, a bound entry shows "Signs in with {name}" in
place of the key field, and the row says whether it is signed in and how
many accounts are on (every language).
Docs: reference.md (with an example), plugin-runtime, plugin-tools and
provider-plugins.

Run on mote at f44fa2ef6 + this change. After rebasing on acd789d45 (an
unrelated responses_ws change), go build ./... and -run "Search|Budget"
on plugin, gateway and provider are ok again at this tree.
- gofmt -l clean; go vet ./internal/... ok; Linux and Windows vet of
  plugin/gateway/provider/gui ok
- go test -count=1 -timeout 45m ./internal/plugin ./internal/provider
  ./internal/gateway ./internal/gui: plugin, provider and gateway
  ok; gui red only in TestMainWindowCorners/macOS_26_SDK, mote's
  macOS 27 title bar, already filed as #3949
- node --test on 15 GUI files: search-signs-in, search-api, search-keys,
  search-order, search-all, search-first, search-instead, searcher-pick,
  searcher-then, provider-search, settings-search, i18n-keys, gui-zh-tw,
  gui-ja, gui-de. 207 of 207 pass (chromium and webkit, 980/420px, en/zh).

Broken by hand. Each break made its test red:
- B1, no ctx.getAuth: plugin TestPluginSearchSignsIn "ctx.getAuth is not a
  function"
- B2, no renewal: "searched as due@seek acc-due", "the renewal never began"
- B3, gateway with no auth branch: gateway TestPluginSearchSignsIn "signed
  in: k9 undefined"
- B4, a refusal that also rests the model account: "a search's rate limit
  rested a@seek for its models"
- B5, getAuth handing out the provider's first account: "as the second
  account: a@seek acc-a"
- B6, the hook run outside inScope: "a token saved while searching as b: a
  rotated-b@seek"
- B7, getAuth given to every entry: "keyed: k9 function"
- settings.js showing the key field for a bound entry: search-signs-in red
  in every engine, width and language

Not tried: a real search vendor or Axel's own plugin; real accounts; runs
on the Windows or Linux boxes; the full GUI suite. The full go test ./...
runs after the push.
2026-11-04 20:55:42 +08:00
yetone f44fa2ef6a sessions: gateway mode lists only the gateway's sessions, never this computer's agents' files
paultian on Discord: magpie web in gateway mode, on a machine with Claude
Code and Codex installed, listed that machine's own sessions beside the
ones other computers sent through it. Owner's call (via the lead): keep
Sessions in gateway mode, scope it.

- sessions.OwnOff (set by the gui to ownSessionsOff): while it holds,
  currentReads answers "none", Found and Dirs are empty, the trash lists
  and restores/purges only what the gateway kept, and moving Claude
  Code's folder is refused. Every route built on Reads follows: the list,
  one, transcript, markdown, export, stats, overview, search, manage,
  delete, carry, Usage's agent-file calls. Gateway-recorded sessions
  (ledger projection, recorded conversations) are not behind the gate.
- ownSessionsOff: magpie web's page, and Settings' gateway mode On, or
  Automatic with --gateway or no agents found (looked at once per 30s,
  and again on another HOME/PATH). A turn of the answer resets the
  sessions' caches and stats; the gateway-mode route does it at once.
- /api/sessions/reads says gateway:true: the page asks nothing, its empty
  state names the gateway's sessions (en/zh/zh-TW/ja/de), and Settings ›
  Privacy leaves out Agents' session history.
- The gateway-mode subtitle (5 languages), docs/reference.md and
  site docs/docker.html (en/zh/ja) say Sessions stays and what it lists
  (they said there was no Sessions tab, which was already wrong);
  docs/subsystems/gateway-sessions.md has the design.
- Tests: Handler marks the process as magpie web for good, and 13 tests
  served magpie web's page, so a later test's sandbox could be in gateway
  mode by itself. webPageHandler ends the mark with the test, and
  TestWebPageHandlerEveryWhere fails on a direct Handler(webHost{...}).

Ran (mote, at this tree rebased on origin/main):
- TestGatewayModeListsNoOwnSessions: red on the old code, green now.
- gateway-mode-sessions.test.cjs: chromium + webkit, en 900/390, zh,
  zh-TW, ja 420, de 390: 36/36; red on the old client.js (every case).
- GUI files the change reaches (gateway-mode*, sessions-*, session-*,
  privacy-*, usage-sessions-*, i18n-keys), both engines: 657/657.
- TestCoreScriptBudget ok.
- go test -shuffle=on ./internal/gui ./internal/sessions: sessions ok;
  gui ok but TestMainWindowCorners/macOS_26_SDK, red the same on
  origin/main 2f726b1f9 on mote (#3949).
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of both
  packages; gofmt -l clean.

Broken by hand: OwnOff answering false (the Go test goes red on the list,
stats, manage, one, transcript); the Purge guard and the Restore guard
each (red on purge / restore); the old client.js and settings.js (the GUI
test red). An injected stale agents memo and leaked webPage did not
reproduce the one TestUsageRequestContent red seen in the first package
run; it did not come back in two more runs, one shuffled.

Not tried: a real magpie web on a server with real agents on other
computers; the Go test on Windows and Linux boxes; the 30s memo under
real use.
2026-11-04 20:20:41 +08:00
yetone 2f726b1f95 gateway: a request its vendor's risk control refused isn't sent on to the provider's other accounts (_teamtaylor_)
_teamtaylor_ on Discord: WorkBuddy's risk control spreads across accounts
that send the same request, and magpie sent one request on from account to
account until its tries ran out, so each account was restricted in turn.

The gateway already read the refusal (WorkBuddy's 403 11140 as the plugin
words it, provider.WBRestrictedHint; ZCode's 3012, ZCodeRestrictedHint) as
failRestricted and rested the account 2h, but the candidate loop then went
on to the next candidate, which is usually a sibling account. Now such a
refusal (riskRefused: failRestricted and not a remote magpie's) walls the
provider off for the rest of the request: its other accounts are dropped
from the candidates (elsewhere), from busyNow's replan rounds and from
roomy's left-out list (elsewhereWeighed). A group's other provider is
still asked; with none left the agent gets the refusal. The last
candidate's restricted refusal now rests the account too (before, only a
non-last one did). Generic: any plugin ending its error in either hint
gets it. The workbuddy plugin needs no change (it does no cross-account
retry of its own).

Run (on mote, through mote-run):
- go test -count=1 -timeout 45m ./internal/gateway: ok (727s), before
  the rebase onto origin/main 43849d51c
- at the pushed head (rebased on 43849d51c): go test -run
  'Risk|Restricted|ZCode|Plain403|PolicyRefusal|Protection|ZDR|Overflow|Live'
  ./internal/gateway: ok; GOOS=linux and GOOS=windows go vet
  ./internal/gateway: ok; gofmt -l: empty
- plugins repo, HOME=$(mktemp -d) bun test packages/workbuddy (0.2.20,
  unchanged): 318 pass, 0 fail

Broken by hand:
- the walling block made `if false && ...`: TestRiskRefusalNotSentTo-
  TheProvidersOtherAccounts (accounts asked [acct-1 acct-2], the other
  provider never), TestRiskRefusalAloneIsToldAndRests/two_accounts and
  TestPluginRestrictedAccountSkipped (asked a,b) go red
- the last candidate's rest back to failVerify only: TestRiskRefusal-
  AloneIsToldAndRests (no rest) and TestPluginRestrictedAccountSkipped
  (a's rest nil) go red

TestPluginRestrictedAccountSkipped changed meaning on purpose: the
restricted account's request is now answered 403 with the hint, b
unasked; the next request goes to b. Another vendor's 11140 still fails
over to b.

Not tried: a real WorkBuddy account (no restricted account to hand);
the agent's own retry, or the conversation's next request, still goes to
the provider's next account, so only the within-request walk is stopped.
2026-11-04 20:00:38 +08:00
yetone 43849d51c3 routing: By session heads a session by its title, its folder quieter beside it (flandern1211_58540 on Discord)
Routing's By session headed each session "Claude Code · folder · title",
and with no title only the folder and id ("路由这里的会话名只能看到目录名和
会话ID吗"). Now the head is the agent and the session's title on one
line (whitespace folded), with its folder after it in a quieter .dir; with
no title the folder stands in, and with neither the id. The tooltip keeps
the title, the folder and the id.

The title comes from what magpie already reads, no second reader:
sessions.Titles (the agent's own title, else its first prompt) and Codex's
name index, and where both find nothing, the first prompt the gateway
recorded for that session (sessions.GatewayTitler, the title the Sessions
page shows for it), looked up under the agent the page names and the one
the gateway records it under (usage.AgentOf). A Codex thread Codex never
named now goes to sessions.Titles as a codex: key, so its rollout's first
prompt names it. withGatewayTitles and codexReadableTitles in trace.go.
Nothing is read that the Sessions page doesn't show already, and nothing
leaves the local GUI.

Tests: TestSessionTitlesFallBackToFirstPrompt (new): an unnamed Codex
thread gets its first prompt, a named one keeps its name, an unknown id
stays out, a pi session known only to the gateway gets its first words.
routing-session-folder.test.cjs follows the new head: title then .dir,
the first prompt on one line, the folder said once, the id with neither,
nothing clipped (chromium and webkit, en zh zh-TW ja de, 1100 and 420px).

Run on mote via mote-run, at origin/main e7b0c398e plus this change:
- Whole Routing GUI set (routing-*, panel-routing*) + i18n-keys,
  chromium and webkit: 2583 pass, 35 fail. Every red is a known one:
  rule-remove (#3096), rule-drag (#3789), row-swap (#3799),
  order-unknown (#4627), rules-line (#3593), many-keys, steady,
  steps-cap and story-shrinks (#5088), and under the load of another
  session's whole GUI suite (load ~200) routing-credits webkit ja 420
  (#5161) and routing-flood webkit en (#2215). Run again: credits 20/20
  and flood 12/12 here; order-unknown's webkit de 420 red the same at
  e7b0c398e alone.
- routing-session-folder: 20/20 (both engines, 5 languages, 2 widths).
- go test ./internal/gui: TestSessionTitlesFallBackToFirstPrompt ok;
  red only TestCoreScriptBudget (1534001 > 1533802, the same at
  e7b0c398e, #5139: this change adds nothing to the core scripts) and
  TestMainWindowCorners (the same at e7b0c398e, #3949).
- Rebased onto origin/main 1a67ca614 (its routing client.js changes
  merged clean), at this commit: routing-session-folder 20/20,
  routing-session-title 40/40, routing-kept-again 20/20,
  usage-compact-counts 30/30, routing-live-calm 2/2, i18n-keys 4/4, and
  go test ./internal/gui -run 'TestSession|TestCoreScriptBudget' ok
  (the budget passes at this base). The whole Routing set was not run
  again here. Then onto 0f1b40bbc (routing client.js and css again,
  merged clean): routing-session-folder 20/20, routing-live-bytes
  20/20, routing-live-calm 2/2, i18n-keys 4/4.

Broken by hand:
- withGatewayTitles a no-op: TestSessionTitlesFallBackToFirstPrompt red
  ("titles = map[]").
- client.js back to the old head: routing-session-folder red in every
  engine, language and width.

Not tried: the real app with real Codex, Claude Code and gateway-only
sessions (fixtures only), the Linux WebKitGTK app, Windows.
2026-11-04 19:43:00 +08:00
yetoneandCanda15 0f1b40bbc4 gateway: a reply in flight shows on Routing how much has arrived and roughly its tokens (#4951, Canda15)
A long or reasoning reply looked stuck on the Routing page. A request still
out now shows, on its row and beside the account answering it, the bytes
the agent has had, "≈ n tokens" once a rate is learned, and how long ago
content last came; after 15s with no content the account's dot stops
pulsing. Nothing stays once the request is done.

Ported from Canda15's 7f7bdb189 (github.com/Canda15/magpie), the idea and
the per-protocol content extractors kept, the hot path and storage
reworked:
- every write to the agent passes captureResponseWriter.Write, which calls
  liveRow.observe; the row hangs on the request's inflight (an atomic
  pointer), not a context value made per request
- rates are in memory only (256 pairs); the fork wrote a JSON file under
  the estimate lock on every finished request
- a whole JSON reply is counted in bytes only: the fork held and decoded up
  to 8 MiB of it at the end; a stream is cut into lines in place, only a
  line cut by a write's end is copied, a line over 1 MiB passed over, and
  each event decoded once (the fork ran json.Valid then Unmarshal)
- the reply's kind comes from its first byte, not a header read on every
  write; the keepalive check allocates nothing (the fork split each write)
- everything a row counts is under its own lock, and inflight.tr is read
  under f.mu; the estimate is in float64 (the int64 product overflowed)
- the route's Seq is bumped on every write and traceGather batches the
  wake-ups; the fork's global throttle could drop the last update before
  a pause
- learned only from a streamed reply that did not fail and had the
  vendor's output tokens
- left out: the finished row's "Received" metric and the ended caption
  (layout restraint; an ended row has its own metrics), a duplicate
  "Received" i18n key, the receive-monitor doc (the design is in
  gateway-routing.md now), the fork's xmod and Windows CI commits
The Routing plugin and i18n.js are outside TestCoreScriptBudget.

Run on mote at this head unless named: gofmt -l; go vet (darwin),
GOOS=linux -tags nogui and GOOS=windows go vet ./...; go build ./...;
go test -race on the live tests; go test ./internal/gateway ./internal/gui
(gateway ok; gui red only on TestCoreScriptBudget, #5139, 1533907 >
1533802 before this change and untouched by it, and
TestMainWindowCorners/macOS_26_SDK, #3949); routing-live-bytes.test.cjs and i18n-keys in Chromium and
WebKit, en/zh/zh-TW/ja/de, 1100 and 420px (24/24); every routing-* and
panel-routing* GUI file with i18n-keys in WSL Linux (Chromium all green;
WebKit reds in 12 files, the same class at origin/main 7dd2434d3 run
the same way: 25 there, 28 here, the sets differing by timing samples;
routing-live-patch alone red 2 of 3 on main, 1 of 3 here; filed as
#4121, #4520, #5156, #2174).

Rebased onto 38f4f74e6 (gateway.go, trace.go and the Routing plugin
moved): build, gateway vet, the live tests, routing-live-bytes and
i18n-keys run again there, green (24/24).

Broken by hand, each red, then put back:
- no observe in capture.Write: TestLiveCountsARealStream
- commentOnly never true: TestLiveHeartbeatIsBytesNotContent,
  TestCommentOnlyTellsHeartbeatsApart
- learning from failed replies: TestRatesLearnFromRepliesTheVendorFinished
- a whole reply read as a stream: TestContentCounterLeavesAWholeReply
- no Seq bump in liveBytes: TestLiveWritesReachTheRoute
- no quiet class, no per-second repaint: routing-live-bytes 0/20

Not tried: a real vendor's stream in the running app; the ChatGPT backend
chain (codex_backend.go) writes past the capture writer and isn't counted;
the full Go and GUI suites run after the tag.

Co-authored-by: Canda15 <124772373+Canda15@users.noreply.github.com>
2026-11-04 19:39:08 +08:00
yetone 9095fd82d8 gateway: a conversation kept for its cache is asked again once on a passing 5xx before it moves (jiabubu)
jiabubu on Discord: a channel that errs once and answers a moment later
had the conversation moved off it at the first error, under every rule,
and the next one was sent it all uncached. Only the last candidate left
(or Strict's lone one) was ever asked again.

Now when the conversation is kept where it is (Affinity.Kept: Auto with
a warm cache, Session, or within a turn) and that key or account fails
in a way that passes (busy: overloaded 503/529, another 5xx that says
nothing of quota, 408), and not as a 429, quota, refusal or sign-in, it
is asked once more after retryPause (or a Retry-After up to
longestPause) without resting. Once per request; failing again it rests
and the next is asked as before. A conversation nobody answered yet, or
under Stays Off, moves at once (keptAgain in affinity.go). The trace
marks the try (Try.Kept) and the Routing page says it was asked again
for what its vendor cached, not "nobody else is left to ask", in en,
zh, zh-TW, ja and de.

TestFixedMemberEffort and TestHeldRuleFailsOverWithinItsMember had a
kept member fail with a lasting 500; they now expect it asked once more
(kq1 kq1 kq2) before it moves, the outcome unchanged.

Run on mote (mote-run):
- TestKeptConversationAskedAgainBeforeItMoves (7 cases: Auto, Use
  before expiry, Session, failing twice, 429, new conversation, Off),
  TestFixedMemberEffort, TestHeldRuleFailsOverWithinItsMember: ok.
- go test -count=1 -timeout 45m ./internal/gateway/: all ok but
  TestGroupBackupStandingInWhileTheFirstIsBackAndBehind and
  TestGroupMemberPutFirstOnItsMeritsKeepsItsCache, red with keptAgain
  switched off too: #5209.
- routing-kept-again.test.cjs: 20 of 20 (chromium + webkit, en zh zh-TW
  ja de, 1100 and 420 wide).
- GUI routing-*, group-*, i18n*, gui-* (2967 tests, concurrency 4):
  42 red, all in files this doesn't touch; 14 of those files alone:
  28 red, and the same files at origin/main 7dd2434d3 alone: 29 red,
  the same tests (mote at load 58-118). Filed: #5088, #4585, #4627,
  #4628, #3954, #1804.
- gofmt -l clean; go vet ./internal/gateway darwin, GOOS=linux -tags
  nogui, GOOS=windows: ok.

At the head rebased on 78128b510: vet (darwin, linux, windows), go test
-run 'TestKeptConversation…|TestFixedMemberEffort|TestHeldRule…|
Affinity|Strict|Patience' ./internal/gateway: ok; routing-kept-again,
i18n-keys, routing-agent-gone: 40 of 40.

Broken by hand: keptAgain's call made false: the four kept cases of the
Go test fail (b answers, a asked once); the story branch made false:
routing-kept-again 0 of 20.

Not tried: a real vendor's 503 on a real account; Linux/Windows runs of
the tests; the full ./... suite before this push (runs after the tag).
2026-11-04 19:24:12 +08:00
yetone 7dd2434d31 remote quotas: a key with Quotas on but told no card shows why too (yi_time)
ef6bd155f made a held remote read show the remote's own card saying why.
A key with Quotas on that may use no provider's cards is answered 403
held too (writeCards), so it now shows that card as well, and the full
suite went red on TestRemoteMagpieShowsHeldKeyItsQuotas, which expected
the key's own card alone. The test now expects the held card, and the
words tell such a key what is missing: let it use every model of a
provider whose usage it is to see, not only turn Quotas on. The GUI
string ends "hover for what to change there" in every language; the core
weighs 21 bytes less than before (1,533,980; main is over its budget
under #5139, not by this).

Run (mote, at 053fc9f9c, on ce21ea856):
- go test -count=1 -run 'Remote|Quota|HeldKey' ./internal/provider
  ./internal/gateway: ok, ok
- node --test usage-remote-cards, routing-remote-windows, i18n-keys
  (Chromium + WebKit; en, zh, zh-TW, ja, de): 36 pass, 0 fail
- TestCoreScriptBudget: red as on main (#5139)
- gofmt -l: clean
Broken by hand: errRemoteHeld's wording changed, the gateway test went
red with the new card's text; restored.
Not tried: a real Windows magpie against a real Mac one.
2026-11-04 18:49:38 +08:00
yetone c03dee7e3e agent: LiveAgent, magpie's models in its model picker (xiaoxiaofei. on Discord)
xiaoxiaofei. asked for LiveAgent (Stack-Cairn/LiveAgent, v2). LiveAgent 2
is a Tauri app that runs its models through K-brain, a Go backend it
starts as `k-brain backend -data-dir <root>`; every provider lives in
<root>/config.json (JSONC, Pi's provider shape). Root: $LIVEAGENT_HOME,
else $K_BRAIN_HOME, else the folder ~/.liveagent/data-dir.json points to,
else ~/.liveagent, on every OS (LiveAgent's data_home.rs and
kbrain_backend.rs, K-brain's internal/config and internal/storage).

Connect adds providers.magpie: type claude_code + api anthropic-messages
(what LiveAgent's own settings write for an Anthropic-compatible
provider), baseUrl the gateway root (K-brain appends /v1 and posts
/messages with X-Api-Key), the key naming LiveAgent, activeModels null,
modelOrder in magpie's order, models sorted by id with display name,
window, output limit and input [text, image]. K-brain decodes with
unknown fields refused, so only its fields are written. A default or
compact model still K-brain's endpoint-less demo model1 becomes magpie's
first; the user's own pick stays. Through a sync the user's name, the
models they turned off, their order, K-brain's metadata and a model's
own displayName stay; a new model is on and last; nothing to change
writes nothing. A file K-brain wouldn't read as providers (not an
object, providers not an object, top-level models, a bare provider) is
left alone. Disconnect takes the entry out, puts picks back to K-brain's
default, gives a file left with no provider K-brain's demo back (its CLI
restores config.json.bak, which could hold magpie's, from a file with
none), and removes a file holding only what magpie made. LiveAgent's
backend holds the settings and writes them whole on any change, so a
change is refused while liveagent or k-brain runs (macOS/Linux; the
notice says to quit it first, in every language). Logo: the app's own
64px icon (src-tauri/icons/64x64.png, MIT) in an SVG.

Run on mote at this tree:
- gofmt -l clean; go vet ./internal/agent ./internal/agentenv for darwin,
  linux (nogui) and windows
- go test -tags nogui ./internal/agent -run 'LiveAgent|GatewayKey|ListsModels'
  ok; ./internal/agentenv ok; ./internal/gui: only TestCoreScriptBudget
  red, which is red on its base too (app.js untouched here; #5139)
- GUI icon-tile, i18n-keys, agent-notice-lang, gui-zh-tw, gui-ja, gui-de:
  Chromium 27/27, WebKit 27/27
Broken by hand on mote, each red: the user's activeModels not kept
(TestLiveAgentProvider "activeModels after sync [], want [...]"); the
demo provider not put back (TestLiveAgentMakesItsFile "emptied file");
the demo default not replaced (TestLiveAgentProvider, TestLiveAgentMakesItsFile).

Real use on mote (sandbox HOME and LIVEAGENT_HOME, this magpie on
127.0.0.1:3562, a fake Anthropic upstream on 3561, LiveAgent 2.0.5's
bundled k-brain from the release dmg):
- k-brain backend's first start wrote config.json as {}; magpie
  liveagent magpie then wrote providers.magpie and the default pick
- `k-brain run "Reply with exactly: pong"` (K-brain's CLI, same config
  and routing code) answered "pong"; the upstream saw POST /v1/messages
  from magpie
- the backend LiveAgent starts listed magpie's model in /v1/models with
  it as the default, and its /v1/text/generate answered "pong" through
  magpie
- with k-brain running, connect/disconnect were refused with the notice;
  after it quit, disconnect removed the file magpie made
Not tried: LiveAgent's window itself (its model picker was not opened;
the backend's API it reads was); LiveAgent on Linux or Windows; a real
vendor reply (fake upstream).
2026-11-04 18:41:13 +08:00
yetoneandwaynesguan 0a5dc40abc gateway: a group's trusted Claude, GPT and Gemini thinking streams as it comes, a refusal or error after it going to the next member (#4166)
A try whose model's vendor may refuse after its reasoning (#248) had its
reasoning held while another candidate could answer, whatever the member
had answered lately. Through a routing group Claude Code saw a Claude
member's thinking only with its text, all at once, and never its
"thinking with <effort> effort". waynesguan measured it on one WorkBuddy
account: `workbuddy claude-opus-5.5` alone, first thinking at 3.66s;
through the group, all 67 thinking deltas with the text at 17.25s.

Ported from waynesguan's 71aacaa (on f8987ce61): the trust #4512 gave
DeepSeek now covers Claude, GPT and Gemini, but only where a refusal
after the reasoning can be handed to the next candidate in the same
stream (handsOver, refusalHandover). Once a member's thinking has gone
on to an answer thoughtCleanMost (3) times running, its reasoning goes
as it comes; a refusal after it, nothing yet said, goes to the next
member, whose reply follows as the same one; the refusal takes the trust
back. Where no handover is possible (no stream, a Gemini-protocol agent,
a compaction wanted whole, refusals asked again enough, the last
candidate) it is held as before. holdsThinking is decided after hw.over.

Added in review: the port alone lost failover for errors. passOver
handed over only a refusal; a retryable error after shown reasoning
(Anthropic's mid-stream overloaded_error) counted as the answer begun and
reached the agent, the next member never asked, where the held stream
had failed over. passOver now hands a retryable error over too
(handOver(status, msg, refused=false)): the try fails with its status
and words, as a held one did, and the next member's stream follows. A
non-retryable error (a request at fault) still reaches the agent. This
also applies to GLM's and trusted DeepSeek's shown reasoning, which had
the same gap.

Tests:
- TestTrustedThinkingFailsOverOnEveryPath: claude (Anthropic upstream),
  gpt and gemini (Chat upstream) members x refused / overloaded /
  invalid x /v1/messages, /v1/chat/completions, /v1/responses, 27
  cases; spliced stream checked per protocol (one message_start, block
  indexes, sequence numbers, one [DONE]).
- TestClaudeThinkingStreamsOnceTrusted, TestClaudeTrustedThinkingStreamsThroughGroup
  (waynesguan's), TestClaudeTrustedThinkingErrorFailsOver.

Broken by hand:
- main's fallback.go + gateway.go: the 18 refused/overloaded cases,
  TestClaudeThinkingStreamsOnceTrusted ("a trusted Claude member's
  reasoning is still held") and ...ThroughGroup ("first thought only
  1.541µs before the text") FAIL.
- port without the error handover: the 9 overloaded cases and
  TestClaudeTrustedThinkingErrorFailsOver FAIL (the agent got
  "Overloaded", b asked 0 times).

Run (mote, via mote-run): go test ./internal/gateway/ at 741f7a8f2
(877s) ok but TestClosedBeforeSentEveryTimeSaysWhy (bare EOF, Codex
closed-unsent path, already #5031, not touched here); after rebase on
e7b0c398e: -run 'Thinking|Refusal|Handover|ObjectRoot|DeepSeek' ok;
gofmt -l clean; go vet ./internal/gateway/, GOOS=linux go vet -tags
nogui ./..., GOOS=windows go vet ./... ok. Full suite runs after push;
its reds are filed separately.

Not tried: a real refusal or overloaded_error after thinking from a real
account (can't be triggered at will); Claude Code against a real group
with this build; Windows/WSL runs (vet only).

Co-authored-by: waynesguan <wenwenguan@tencent.com>
2026-11-04 18:37:43 +08:00
yetoneandFlandern e7b0c398ee sessions: find a ZCode title by its gateway id (#5195)
ZCode sends its session id to the gateway without the sess_ prefix stored
in its database. Routing asks Titles with that bare id, gets no title, and
falls back to the folder name even though the Sessions page can show the
real title.

Titles treats zcode:<id> as an alias for zcode:sess_<id> when it reads
local session files, and returns the title under the key Routing asked
for (the sess_ key too, which callers ignore). A regression test uses the
database id shape ZCode writes and the bare request id it sends.

Ported from Flandern's b1a952b73 (fix/zcode-routing-session-titles on
flandern12111/magpie), code and test unchanged, reviewed line by line;
the body is rewritten (the original had literal \n's), and
gateway-sessions.md says it.

Run on mote via mote-run, at origin/main c7bbd3faf plus the change before
this one: go test ./internal/sessions -run
'TestZCodeTitlesByRequestID|TestSessionTitles|TestTitles|TestZCode'
-count=1: ok. Again at this commit on origin/main 14f6d10de: go test
./internal/sessions -count=1 ok.
  Pushed on c4245c4c2, which changes only internal/gateway's
  object_root and its doc after 14f6d10de; not run again on it.

Broken by hand: the alias lookup removed, TestZCodeTitlesByRequestID red
("zcode:578bd3d1-…: title \"\", want \"A ZCode session's title\"").

Not tried: a real ZCode session through a running gateway.

Co-authored-by: Flandern <3180066912wzw@gmail.com>
2026-11-04 18:33:07 +08:00
yetone 70a98dd85c routing: a long Accounts and keys shows its first rows, the rest behind Show N more (ferock4669, iyou00 on Discord)
With many keys the Routing page's Accounts and keys ran on and on: each
card held every window, the models it answered and a meter. Now a card
keeps its name, one line of what is left (or its rest) and how it fares,
with Try now or Sign in again when it needs one. The models it answered
are in its tooltip under its id, and a subscription's other windows are
on hover over its figure.

A list longer than 8 rows shows the first 8 and puts the rest behind
"Show N more" at its foot (kept across a reload in
magpie.routingActsAll). Never behind it: a row to sign in again, a
resting account or model, failures with no answer, a remote whose
allowance can't be read, rows under a fold the reader opened, and the
heading of a provider with a row shown. Two more alone aren't folded.
The button clicked stays where it is on the screen. "View usage" beside
it opens Usage's Overview, where each account's card says it all,
without making that tab the reader's own (window.openUsageOverview).

The foot writes only what changed, so an idle page writes nothing
(routing-live-calm).

Tests: routing-acts-compact.test.cjs (new; chromium and webkit, en zh
zh-TW ja de, 1300px and 420px). routing-account-windows,
routing-read-allowances, routing-wallet-lapse, routing-accounts-narrow
and routing-columns follow the card's new shape and the foot.

Run on mote via mote-run, worktree based on origin/main c7bbd3faf:
- Whole Routing GUI set (routing-*, panel-routing*) + i18n-keys,
  chromium and webkit: 2487 pass, 29 fail, every red one of those
  below (many-keys and routing-levels #3620 too)
- Same reds on clean origin/main c7bbd3faf (11 files run there): the
  routing-rule-remove (#3096), rule-drag (#3789), row-swap (#3799),
  order-unknown (#4627), rules-line (#3593), steady, steps-cap and
  story-shrinks reds of #5088, in different languages run to run.
- routing-folder went red 2 of 3 with this change (30/30 on main):
  its press() clicked Save while the group editor was still growing
  open, and the foot moved .rt-gsec 8px. press() now waits for the
  button to hold still: 3 runs x both engines 20/20, webkit alone
  10/10.
- TestCoreScriptBudget red, 1534154 > 1533802, identical on clean
  c7bbd3faf (#5139): this change adds nothing to the core scripts.
- routing-acts-compact twice, alone and beside 5 files: 22/22, 20/20.
- Rebased onto origin/main 14f6d10de (its routing client.js changes
  merged clean), at this commit, both engines: routing-remote-windows,
  week-low, free-expiring, group-strategy, acts-compact, live-calm,
  folder, account-windows, read-allowances, accounts-narrow,
  wallet-lapse, columns and i18n-keys all green.
  Pushed on c4245c4c2, which changes only internal/gateway's
  object_root and its doc after 14f6d10de; not run again on it.

Broken by hand:
- rows needing the reader no longer kept out of the collapse (m.keep
  ignored): routing-acts-compact red (Show 4 more never shown).
- a row to sign in again under a shut fold not drawn: red (Zed's fold
  row 0 !== 1).
- the foot's hidden/aria-expanded written every draw: routing-live-calm
  red in both engines (attrs: 6 !== 0), as in an earlier run of this.
- the button's hold removed: routing-acts-compact red (chromium en
  1300px, "the click moved the button: 572.9 → 592.1").

Not tried: the real app with a real long key list (fixtures only), the
Linux WebKitGTK app, Windows.
2026-11-04 18:33:07 +08:00
yetone c4245c4c20 gateway: a Messages body's tools with a root union go folded to every upstream
ziko on X (11-04): ZCode on Zed's subscription, Claude Sonnet refused
every request. Six of the GoAnyAPI MCP server's tools (goanyapi_adsense,
the 36th, among them) have a oneOf at their input_schema's root, ZCode
sends every tool with every request, and Anthropic's API turns such a
request away: "input_schema does not support oneOf, allOf, or anyOf at
the top level".

Cause: a request translated to Messages always had its tools folded to an
object root (objectSchema, #1271), but a Messages body relayed as it came
(ZCode or Claude Code to an Anthropic-protocol provider, the Zed plugin's
models among them, whose plugin provider has an Anthropic URL) never
was: foldsRoots and objectRootsBody handled Chat and Responses only, so
neither the first ask nor the retry after the refusal folded it.

Change (object_root.go):
- foldsRoots is true for every Anthropic-protocol relay, from the first
  ask, as a translated request already was.
- objectRootsBody takes a Messages body: a client tool's input_schema goes
  through provider.ObjectRoot; a server tool (no input_schema) and a
  schema with no root union go as they came. The translated path
  (to != Anthropic guard at gateway.go's objectRootsReq) is unchanged, so
  nothing is folded twice.
- docs/subsystems/gateway-routing.md gains the root-union bullet.

Test: TestMessagesRootUnionFolded, POST /v1/messages (stream) to a relay
with an Anthropic URL whose fake refuses a root union with Anthropic's
own wording: the union tool goes as an object root on the first ask, its
branches' properties merged; a plain tool's schema goes unchanged, and so
does a body with no union.

Run on mote at 69eb93e0a (origin/main, just fetched) plus this change:
gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=windows and
GOOS=linux -tags nogui, ok; go test -timeout 45m ./internal/gateway:
ok (914s); go test ./internal/masking (reads the
subsystem docs), ok. Not run: the whole ./... suite; CI runs it.

Rebased after the run onto 14f6d10de: its three commits since 69eb93e0a
change catalog, provider/remote_quotas and GUI files, none in
internal/gateway.

Broken by hand: object_root.go back to HEAD, TestMessagesRootUnionFolded
answers 400 "tools.1.custom.input_schema: input_schema does not support
oneOf, allOf, or anyOf at the top level", the reported error.

Not tried: a real Zed account with GoAnyAPI's tools; the fake answers as
Anthropic's documented refusal does.
2026-11-04 18:26:37 +08:00
yetone 14f6d10de0 routing: a remote's Claude card whose read failed says so on its row, not nothing (yi_time on Discord)
remoteWinsOf (c7bbd3faf) drew a Remote magpie row's windows from the
remote's cards. It said "Allowance unavailable" only when the remote's own
card failed. When the remote answered but its Claude card there carried an
error (the remote's own Claude read failed), the Usage page showed that
card and its reason, while Routing's row showed nothing. The row now takes
the error of the card of its own family (Claude's on a claude row,
Codex's on a gpt/codex row), with the reason on hover. The remote's own
card still comes first. The plugin's file only; no core bytes.

Run (mote, worktree on origin/main 69eb93e0a plus 607f8b43a):
- routing-remote-windows.test.cjs (a new remote "elm", its model named
  as a remote really names it, claude/claude-opus-5, its Claude card
  erroring and its Codex card erroring otherwise) and
  routing-account-windows.test.cjs, 5 languages, 1100 and 420px, chromium
  and webkit: 44 pass, 0 fail.
- Broken by hand: the new fallback removed made routing-remote-windows go
  0 pass, 22 fail.
- Real two-magpie repro (see 607f8b43a): with A's key held, B's Routing
  row says "Allowance unavailable — hover for why", the held reason on
  hover; with Quotas on, 5 hours 40% · 7 days 12%.

Not tried: yi_time's own setup, which this may not be. Their Routing
report came before v0.1.2908 (c7bbd3faf) was published at 07:08 UTC on
11-04; a Windows magpie older than that draws no remote windows on
Routing at all. Not tried in WebView2 or WebKitGTK.
2026-11-04 18:14:11 +08:00
yetone ef6bd155ff provider: a remote magpie that holds this key says so, where its Claude card went missing with no word (yi_time on Discord)
yi_time on Discord: "没变化 还是不显示通过局域网添加的Claude额度". c7bbd3faf
(v0.1.2908) drew a Remote magpie's cards on Routing. It did not cover a
remote that answers 403 gateway_key_held. That is a key held to a budget,
models or accounts there, without the key's Quotas on (#1981, #2216). For
such a key, keepRemoteCards dropped the cards and remoteCards returned
nothing. The remote's Claude then vanished from Usage, the tray panel and
Routing, with no reason shown anywhere; only the key's own Limit card
stayed.

The remote's own card now carries errRemoteHeld. quotaError words it as
"That computer's magpie tells this key no quotas: it holds the key to a
budget, models or accounts — turn on Quotas for the key under Gateway keys
there", in en, zh, zh-TW, ja and de. Routing's existing "Allowance
unavailable — hover for why" shows it too. A failed read since the hold
(unreachable, refused) still leads with that read's own error.

Only the computer that shows the quota needs this release. The computer
that holds the account needs nothing new, but its owner turns on Quotas
for the key, or lifts the key's hold.

app.js pays for its one line with four quotaError comments cut. The core
weighs 1,534,001 against 1,534,022 on origin/main, so it grows nothing and
raises no budget. TestCoreScriptBudget stays red as on main (#5139, owned
there).

Run (mote, worktree on origin/main 69eb93e0a):
- Real two-magpie repro, sandbox HOMEs. A (old binary) on 3561/3562 had a
  Claude account and LAN on. B (this change) on 3571/3572 added A with
  `provider add remote-magpie <key> url=http://<lan ip>:3561`. A's key was
  held to claude/* models.
  - Before: B's Usage, panel and Routing had no Claude card and no reason.
  - After: Usage and the panel's Allowances show the new line; Routing
    shows "Allowance unavailable — hover for why".
  - With `gateway-key quotas <id> on` on A: B shows remote-magpie/claude,
    5 hours 40%, 7 days 12%.
- go test -run 'Remote|Quota' ./internal/provider: ok. gofmt -l clean.
  GOOS=windows and GOOS=linux go vet ./internal/provider: ok.
- usage-remote-cards.test.cjs (now en, zh, zh-TW, ja, de; chromium and
  webkit) and i18n-keys.test.cjs: 14 of 14 pass.

Broken by hand:
- remoteCards' held branch put back: TestRemoteMagpieHeldKeyShowsOnlyItsOwnCard
  red with 3 errors.
- quotaError's new line removed: usage-remote-cards went 0 pass, 5 fail.

Not tried: yi_time's own two computers, a real Claude account on the
remote (the repro's account is a fake token with a kept reading), the
Windows and Linux app engines (WebView2, WebKitGTK). Whether yi_time's key
is held is not known.

Sibling, filed rather than changed here: with Quotas on and a key held to
only some of a provider's models, the remote answers [] and this side says
"Nothing read on that computer yet" (#5217).
2026-11-04 18:14:10 +08:00
yetone 00d8aac596 routing: Free quota by expiry spends the soonest-lapsing free quota first (wowbbs)
wowbbs (and shamen_xiaohong) keep check-in free accounts in one group:
WorkBuddy CN x2, MiniMax Code, TraeCode CN and Qoder CN. They asked that
the group spend the free quota that lapses soonest first, go on to the next
when one is used up or has lapsed, and use a paid account only when no free
quota is left.

This adds `expiring` (provider.FreeExpiring, routes.FreeExpiring). It is a
group's only, picked in the Routing page's group menu, with
`magpie group set <g> routing=expiring` or in the TUI. Nothing changes for a
group or provider that doesn't pick it. A provider keeps refusing it, as it
refuses `cheap`.

- routes: Seat.FreePlan and Strategy.ByPlan. FreeExpiring has three tiers:
  - free seats (Free, a model at no cost, or FreePlan) by Expires, the
    earliest of the window renewals and Lapse, to the hour; an unknown
    expiry goes last and ties keep their listed order;
  - then the paid seats, as Smart orders them;
  - then the spent and resting seats, by when they come back.
- provider.FreePlan reads an account's plan word: free, trial, 免费, 试用,
  体验, 體驗.
- gateway: weighRouted fills FreePlan when the strategy asks. The trace's
  Weighed rows gain `expires`, so the Routing page's story can say "its free
  quota is lost soonest, in 1d 2h". There are also lines for "a free one with
  no expiry told" and "no free quota left, so the paid one".
- GUI: an option in the group menu, the mode line, the story lines, and
  i18n in zh, zh-TW, ja and de. app.js only adds `expiring` to ROTATION,
  paid for by a shorter comment beside it, so the core is 11 bytes smaller
  than at its base.
- docs: gateway-routing.md (order of keys and accounts) and
  plugin-runtime.md (Seat and Strategies).

Plugins whose usage doesn't say when their free quota lapses got issues
rather than edits:
- magpie-community/plugins#718: Trae sums its packs; the soonest end comes
  from any pack, spent or past, and there is no runsOutAt.
- magpie-community/plugins#719: Qoder's plan is the raw userType
  personal_standard, which doesn't read as free, and its add-on, shared and
  dedicated pools have no expiry.
WorkBuddy (Free plan, resetsAt and runsOutAt) and MiniMax (Free, runsOutAt
on credits) already report what this needs.

Run, all on mote via mote-run at this tree (base 0ee424e3e):
- gofmt -l internal plugins: empty. go build ./....
- go vet of routes, gateway, provider, cli and tui; the same with
  GOOS=linux -tags nogui and with GOOS=windows.
- go test ./internal/routes ./plugins/rotation ./internal/tui: ok.
- provider -run TestFreePlan|Group|Routing: ok.
- cli -run Routing|Group: ok.
- gateway -run TestGroupSpendsFreeQuota|Wallet|Free|Cheapest|Routing|Weigh: ok.
- internal/gui -run Budget|Size: TestCoreScriptBudget is red, already red
  at the base (1,534,154 > 1,533,802, #5139). This change takes the core
  down 11 bytes and doesn't raise the budget.
- GUI, node --test in chromium and webkit, en, zh, zh-TW, ja and de, wide
  and 420px:
  - routing-free-expiring (new), routing-group-strategy, routing-cheapest-first,
    i18n-keys, builtins, group-member-free and provider-count-free: 176 of
    176 pass;
  - every routing-*.test.cjs: 2,478 of 2,520 pass. The 42 reds are in ten
    files (routing-rule-remove, rule-drag, rules-line, rule-models,
    row-swap, steady, order-unknown, steps-cap, story-shrinks and
    keys-fold). Run alone at this tree they give 27 reds, and at the base
    0ee424e3e 25, the same tests. They are filed as #5088, #4585, #3096,
    #3789, #3799, #4627, #4628 and #4629.

Again after rebasing on origin/main 0e804be29: gofmt; vet of routes,
gateway and provider; the same Go tests: ok. routing-free-expiring,
routing-group-strategy and i18n-keys: 62 of 62 pass. The core is 1,534,034
here, against main's 1,534,045.

Red on the old code: TestGroupSpendsFreeQuotaSoonestToExpireFirst at
0ee424e3e gives "pro,wb1,wb2,mm,qoder" where it wants
"mm,wb2,qoder,wb1,pro".

Broken by hand: with FreePlan never set, the gateway test gives
"pro,mm,wb2,qoder,wb1" (red). routing-free-expiring.test.cjs reads strings
that exist only with this change. routing-group-strategy's two menu counts
(11) went red with the new option, and they now count 12.

Not tried: no real account of any vendor. WorkBuddy, MiniMax, Trae and
Qoder check-in accounts were not routed live. The order was tested on
fabricated allowances shaped as their plugins report them. The full
`go test ./...` runs after the push.
2026-11-04 17:11:55 +08:00
yetoneandggbdpq 0e804be29b provider: requests missing together list logins once, and a plan asks OwnPaused of the held list
Every request's routing plan lists the agent's accounts (perKeyEvery
asks AlsoOn, and OwnPaused of the signed-in one), and each list took
logins.json's lock. A write in a request (a token refresh) dropped what
was held, and every request then in flight listed again, one after
another on the lock: 20 requests queued on it in #5104's dump. And
OwnPaused was never held: each ask was its own read under the lock.

heldOf now builds a missed key once a request: the first caller builds,
the others wait for it and take its value. OwnPaused goes through
heldOf under its own key, so a write lists it anew as it does Logins.

Ported from ggbdpq's ecb829370 (#5104). Changed from that patch:
- A waiter takes the build only if nothing changed while it ran: held's
  generation, filememo's generation (settings.Save tells only filememo)
  and the environment. The patch skipped heldFreshLocked on wake and
  kept a build made across a filememo write, so a later caller could get
  settings from before the save.
- A caller outside a request (no Hold) never joins a build; it builds
  fresh, as on main.
- The wait is bounded (heldWait, 5s). A stuck or panicking builder, or
  one waiting on a lock its waiter holds, can't hang the request; the
  waiter builds on its own.
- When a write came during the build, waiters go round again (up to
  heldRounds) so one of them builds and the rest wait, instead of all
  rebuilding at once.
- With heldFor 0 a waiter takes the builder's own result (it is not
  kept, so the patch's waiters found nothing and built again).
- New tests: TestHeldWaiterBuildsAgainAfterAWrite (Changed and
  filememo.Forget), TestHeldWaiterTakesTheBuild, TestHeldWaiterNeverStuck
  (stuck builder, panicking builder). providers-accounts.md says it.

Run (mote, at the pushed tree):
- The patch's two tests on main's product code: red 3 of 3 ("20 listed
  before the first was built", "OwnPaused was not listed once a
  request").
- go test -race -count=20 -cpu 1,2,8 -run 'TestHeldWaiter|
  TestLoginsMissedTogetherListedOnce|TestOwnPausedListedOnceARequest|
  TestLoginsListedOnceARequest|TestHold' ./internal/provider: ok.
- go test ./internal/provider: ok. go vet for darwin, linux, windows;
  gofmt -l clean.
- Nesting: an instrumented run of provider, gui, agent, gateway and
  profile recorded every heldOf inside another build and every heldOf
  made under a file lock. No heldOf key reaches itself (only heldFrom,
  untouched). Under logins.json.lock only "migrations" is asked, and its
  build takes no lock and asks no key; under caller-keys.json.lock the
  keys asked take logins.json.lock only. No build takes caller-keys.json
  .lock. So a waiter never holds a lock its builder needs.
- Half-written files: unchanged readers. logins.json is written through
  temp+rename, sharedLogins keeps the last good list on a bad parse,
  another process's write is seen when loginsMu is taken (Look).

Broken by hand, each red:
- No filememo check on the build: TestHeldWaiterBuildsAgainAfterAWrite
  got "before", built 0 times.
- Unbounded wait: TestHeldWaiterNeverStuck timed out at 60s.
- No take of the builder's result: TestHeldWaiterTakesTheBuild built
  again.

Not tried: a live load of parallel Claude Code requests; two magpie
processes contending for logins.json; Windows and Linux test runs (vet
only).

#5104

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
2026-11-04 17:06:31 +08:00
yetone 129baeca01 gateway: the same 5xx from two accounts in one request rests neither (mycf_711)
mycf_711 on Discord: 127 of one provider's 128 503s in a day were
"AIError AI服务异常" word for word, all one agent's request with an empty
tool schema the upstream always refused. forbiddenAlike/unforbid
(plugins#243) only took plain 403s, so each such request walked every
account of the provider into backoff, and other agents' normal requests
then found every account resting.

A 500/502/503 that says nothing of why (plainUnavailable: failOther, not
overloaded, no proxy down, not codexReset, not the protection refusal, not
"did not stream", some words) now joins forbiddenAlike when:
- a second account of the same provider, model and reasoning gives it in
  the same status and words, request/trace ids left out (refusalWords);
- and the provider answered another request within answeringLately (5m,
  noted in servedCandidate as routed.answered).
Then neither rests, the first one's rest and failure count are taken back,
the other mates go last (matesLast, so a group's other members are asked
first), and the last one left isn't asked again after a moment
(sameRefusal; before, the two-account case re-sent the request 13 times).

Kept as before: one account's 503 alone rests it; 503s in other words are
each account's own; a provider that answered nothing in the last 5 minutes
may be down, and its alike 503s rest as before, so an outage is backed off
once 5 minutes have passed since its last answer. A 403 is still alike only
to a 403. Overloads keep their own short model rest.

Ran (mote, via mote-run, at this tree on 6b47bce67; after the rebase onto
186453e00, vet and TestPlain*|TestQoder* again: ok):
- TestPlain5xxOnTwoMatesRestsNeither (5 cases: alone, two alike + a third
  answers, two alike nobody left, two in other words, two alike with the
  provider down), TestPlainUnavailableWords, TestPlain403*: ok.
- go test -run "Plain|Forbid|Rest|Overload|Fallback|Group|Busy|Patience|
  Codex|Refus|Served|Unavailable|Protection" ./internal/gateway/: ok 240s.
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on
  ./internal/gateway/: ok. gofmt -l: nothing.
Broken by hand, each red with a real FAIL:
- no 5xx alike (words5xx never set, the old behaviour): acct-1 rests in
  "two alike, a third answers"; "nobody left" tried acct-1,acct-2 x13.
- last one asked again (sameRefusal dropped): tried acct-1,acct-2,acct-2,
  acct-1,acct-2.
- no outage guard (answeredLately always true): "provider down" case,
  acct-1 not resting.
- words not compared: "two in other words", acct-1 not resting.
Not tried: the reporter's real provider and plugin (unknown here, no
account); a group with another provider failing over during the first 5
minutes of a real outage (matesLast covers it, not tested here); the full
./... suite before push (run after the tag, per the loop rules). In the
first 5 minutes of a real outage alike 503s no longer rest, so each
request asks two accounts before moving on; a gateway whose only traffic
is the refused request still rests as before (no answer lately).
2026-11-04 16:59:02 +08:00
yetone f8987ce617 gateway: Qoder 1.1.82's requests find their session in Qoder's own files
qodercli/qoderclicn 1.1.82 (11-03) stopped sending session-id to a
provider of the user's own, and nothing else in a request names the
session (coderlee233 on Discord). Its requests were recorded with no
session: the Sessions page lost the conversation's title and showed each
title and suggestion side call as a row of its own.

A request from Qoder or Qoder CN (by its agent token) on this computer
that names no session is now matched against Qoder's session files
(sessions.QoderDir/projects/<project>/<id>.jsonl and its subagents'
files): the session whose typed prompts (user lines with humanInput /
origin.kind human) appear most in the request's user text wins, the file
written last on a tie. Qoder's <system-reminder> blocks are left out. A
side call (no tools) no file matches yet is held up to 600ms, since the
first title is asked ~0.1s before Qoder writes the file. The id found
goes on the request as session-id, the header 1.1.81 sent, so it is
grouped and titled as before. A request that names a session (older
Qoder's session-id, X-Magpie-Session) is left as it came. Files are read
incrementally; a half-written last line waits for the next read.

Run (on mote, rebased on origin/main 6b47bce67):
- go test -run TestQoder ./internal/gateway: ok. Fixtures are the literal
  bodies and headers qodercli 1.1.82 sent to a capture server, and its
  own session files, from a sandbox HOME (headless turns, a subagent, a
  second headless session, interactive turns, first title, later title,
  transcript title, suggestion).
- go test -timeout 45m ./internal/gateway and the full suite run after
  the push (mote at load 200 from another suite); a red is filed.
- gofmt -l; GOOS=linux and GOOS=windows go vet ./internal/gateway: clean.
Broken by hand, each red: no qoderSession call in handle; no
named-session guard; no agent check; subagent files not read; array
content not read; no wait for side calls; no newest-file tie-break; a
half-written line taken.

Not tried: the reporter's own account or a real model (fake upstream
only); Qoder in WSL (its files are in the WSL home, not found from the
Windows magpie); a keyed or MAGPIE_ADDR gateway on another machine (not
matched by design). The in-flight Active session (status bar) is not
fed from this. A large session file is read whole once per process.
2026-11-04 16:45:47 +08:00
yetone 6b47bce670 cli: magpie model compact <agent> sets an agent's own Long conversations
3eb2bda4f added POST /api/settings/agent-compact with no command, and
internal/cli's TestEveryRouteHasACommandOrIsNamed went red in the full
suite run after the push (settings_parity_test.go:437). Rather than
park the route in notYet, the command it names is here:

  magpie model compact <codex|claude|grok>            says the agent's
  magpie model compact <agent> every|off|<size>       sets it

every takes the agent's own away (it follows the value for every
agent), off is Full window, a size such as 300k compacts there; another
word is refused and nothing is written. A first word that isn't one of
settings.CompactAgents goes to the command as before (on|off|<size>).
cliForRoute names it; the usage text and agent-wiring.md say it.

Run at this tree (3eb2bda4f + this), on mote: go vet ./internal/cli,
GOOS=windows go vet ./internal/cli, go test ./internal/cli: ok.
TestModelCompactAgentCmd broken by hand (the command setting the shared
value instead): red, "codex 300000, claude 300000".
Not tried: the command against a real agent's files (catalog.Changed is
nil in the test, as in TestModelCompactCmd).
2026-11-04 16:35:16 +08:00
yetone 75e30625f5 plugin: a command that serves no pages moves a page's service off the app's port (#5187)
MYCF711 (#5187, Windows, 0.1.2901): magpie plugin update run while the
app runs hung with no output. Its host loads every plugin, and
page-chat's service waits for port 3477, which the app's host holds:
each CLI command that starts a host waited ~6s on it, then kept trying
the port every second in the background, so it could take 3477 from
the app's host when that restarted after the update.

Now magpie run with a command that serves no pages (anything but the
app, tray, tui, web, serve, a bare magpie or a magpie: link opened in
the app; servesPages) sets plugin.ServePages(false), and its host hands
a plugin whose magpie.page.service names an option a free port of its
own in that option (hostOptions). The plugin's other parts load at once
and the app's port is left alone. plugins.json is not changed, and a
service no option moves is started as before. The class, not
page-chat: any plugin page service declared with an option.

Run, at base 0ee424e3e plus this change:
- mote: go vet ./internal/plugin ./internal/cli (darwin), GOOS=linux go
  vet -tags nogui and GOOS=windows go vet of both, GOOS=linux nogui and
  GOOS=windows builds, go test -count=1 ./internal/plugin ./internal/cli:
  ok (280s, 65s). gofmt -l clean.
- Broken by hand: hostOptions handing options unchanged makes
  TestHostServingNoPagesLeavesHeldPort red (the load "didn't finish in
  10s") and TestHostOptionsMoveOnlyTheService red; servesPages returning
  true makes TestServesPages red on daemon, autostart, providers.
- Windows (xiaomi-gpu, win-run): the new tests and TestServesPages ok.
  Sandbox with page-chat and the reporter's git plugin
  (KevinFX-code/magpie-wps-lingxi), nogui builds:
  - 3477 held by bun, magpie plugin update: 13.9s before (page-chat
    "被占着" then "每秒试一次"), 10.6s after (page-chat "listening on
    127.0.0.1:51493").
  - beside magpie serve's host on 3477: 13.98s before, 12.4s after;
    serve's host keeps 3477.

Not tried / not reproduced: the reporter's literal no-output hang. Before
this change, update finished on 0.1.2909 in every setup tried (nogui
CLI with 3477 held, beside nogui serve, beside the release GUI exe in
the interactive session: 6-20s), so this removes the wait and the
port contention seen, not a hang reproduced. Not tried on Linux or the
macOS app.
2026-11-04 16:25:02 +08:00
yetone 3eb2bda4f2 settings: Codex, Claude Code and Grok Build each take a Long conversations of their own (molianyin4227 on Discord)
molianyin4227 (Discord #help): models differ, so one compaction size
for every agent fits none; they asked for Codex, Claude Code and Grok
Build to each have their own, falling back to the shared one.

- settings.AgentCompacts[agent] {At, Full} for the agents that write a
  compaction window (CompactAgents: codex, claude, grok); Settings.
  ForAgent(agent) lays it over CompactAt/FullContext for that agent's
  readers only: codexcat.entriesAt, provider codexListed, Claude Code's
  writeCompact and desktopPlan, grokModelTables, the route list's
  buildModels, Codex's window line (api.go) and Tuned for you
  (gui/tune.go, agent/tune.go). A model's or provider's own Compact at
  still comes first. An agent with none follows the shared value, so
  nothing new is written for it, and an agent outside the three has no
  such key and is refused (provider.SetAgentCompact).
- POST /api/settings/agent-compact {agent, own, full, at}; own false
  takes the agent's value away. settingsapi.Merge keeps the map.
- GUI: a row "Long conversations in <agent>" under Long conversations,
  in the agent's opened row and its sheet: Every agent / Compact at N /
  Full window (segs, no select), a size box when Compact at. It lives in
  agentcompact.js, imported when the agent's settings hold Long
  conversations, then put in synchronously (an async put-in after a
  redraw moved the page in chromium: codex-memories-settings' scroll
  check). It draws again only when its own values change. i18n in
  zh, zh-TW, ja, de.
- Tuned for you's Use on an agent with its own value changes that one,
  stashed under tune.long.compact.<agent>; Undo puts it back.
- codex-memories-settings' "no Codex" check counts Long conversations
  alone again (:not(.agent-compact)) and waits for the new row.
- docs/subsystems/agent-wiring.md: a row for it.

Core size: app.js 1,311,919 bytes, 109 under origin/main 0ee424e3e
(1,312,028): the two calls are paid for by four comments cut. The core
total is 1,534,045, still over its budget as on main (#5139), 109 less
than main's 1,534,154. No budget raised.

Run at this tree (based on origin/main 0ee424e3e, fetched just before
the commit), all on mote via mote-run:
- go test settings, settingsapi, codexcat; provider/agent/gui with
  -run "Compact|Tune|Grok|SettingsSave|CodexWindow|Long": ok.
- New tests broken by hand, each red: ForAgent taken out of codexcat
  (TestCodexCatalogCompactAt), grok.go (TestGrokWindowFollowsLong
  Conversations), claude.go (TestClaudeCompactAt); tune's per-agent key
  turned off (TestTuneAgentOwnLong: "after apply: codex {At:0
  Full:true}"); the row's import call taken out of app.js
  (agent-compact.test.cjs 4 of 4 red in chromium).
- GUI, chromium + webkit (en/zh/zh-TW/ja/de as each file has, narrow
  and wide): agent-compact, agent-prefs, compact-at, compact-one-value,
  settings-general, codex-async-compact, codex-compact-held,
  codex-memories-settings, context-tune, segs-glide, i18n-keys,
  old-webkit: 432 of 432 ok.
- gofmt -l clean; go vet darwin and GOOS=windows on mote, linux with
  -tags gtk3 on magpie-desktop (wsl-run): ok.
- TestCoreScriptBudget: red, 1,534,045 > 1,533,802, as on main (#5139),
  109 bytes lower than main.

Not tried: real Codex, Claude Code or Grok Build reading the values
(the config writers are unit-tested); the full go test ./... (after
the push). `magpie model compact` has no per-agent flag, and t3code's
route list reads the shared value.
2026-11-04 16:17:47 +08:00
yetone 0ee424e3ee codex: a thread Codex 0.166 won't resume for its provider moves with Codex (毅, AcMilan on Discord)
Codex 0.166 (openai/codex#57840) refuses to resume a thread whose saved
provider isn't the configured one: "This chat uses openai, but your
current provider is magpie. Switch to openai to continue." (毅), and
"This chat uses cc-switch-official, but your current provider is
openai" (AcMilan). The rollout's session_meta provider wins over the
state DB row, and no -c override gets past it (openai/codex#58865).

Cause on magpie's side: bringOver relabelled only plain rollouts in
place. A thread Codex had packed to .jsonl.zst (a week after its last
turn) stayed on openai, so with magpie as provider it can't resume.
cc-switch-official is the id CC Switch 3.17-3.20 gave the official
account; CC Switch 4 moves those threads back to openai itself (#7948
there), but a user who left CC Switch keeps them stranded.

- sessions.MovePackedCodexThreads: packed threads on `from` updated in
  the last 30 days, newest first, up to 128 MB per sync, each moved by
  the existing packed rewrite with its copy kept in the trash. Rows
  are checked against the file (plain absent, .zst present, meta on
  `from`, same home). A state DB without updated_at moves nothing.
- bringOver calls it after RelabelCodexThreads; bringBack already
  moves packed threads back.
- bringOfficial: while magpie wires Codex and Codex is on openai or
  magpie, cc-switch-official threads move there, unless the user's
  top-level model_provider or a profile names cc-switch-official.
- Other providers and packed threads older than 30 days are left; the
  Sessions page's Move or Resume takes them.

Run (mote, at the pushed base c7bbd3faf):
- gofmt -l clean; go vet darwin, GOOS=linux, GOOS=windows on
  internal/agent and internal/sessions: ok.
- go test ./internal/agent ./internal/sessions: ok.
- Real codex-cli 0.166.0 app-server in a sandbox CODEX_HOME with a
  fake Responses server: an openai thread packed, Codex on magpie,
  thread/resume gave 毅's error word for word; RelabelCodexThreads
  alone left it; after MovePackedCodexThreads the resume said
  provider magpie and a turn started. A cc-switch-official thread with
  Codex on openai gave AcMilan's error; after the move it resumed on
  openai and a turn started.

Broken by hand (each red, then restored):
- budget check off: TestMovePackedCodexThreads red (both moved).
- the packed call in bringOver removed: TestCodexThreadsFollowMagpieIn
  red (packed thread stayed on openai).
- defer bringOfficial removed: TestCodexMovesCCSwitchOfficialThreads red.

Not tried: the Codex App GUI itself; agent Sync against a real Codex
(unit tests only); Windows and Linux runs; threads on other provider
ids, which 0.166 also refuses (left to the Sessions page).
2026-11-04 15:12:08 +08:00
yetone c7bbd3faf6 routing: a Claude joined over the network shows its windows in Accounts and keys (yi_time on Discord)
A remote magpie's provider row on the Routing page showed no usage, while
the subscriptions above it did. The remote's cards already reach the
window as /api/usage/quotas entries with `from` set (provider =
<remote id>/<card provider>), but the page's cardOf/winsOf match only
kind "account" with no `from`. remoteWinsOf (plugins/routing/client.js)
now draws those windows on a remote-magpie row: a claude-* model row
gets the remote's claude cards, gpt/codex/o\d rows its codex cards, each
window prefixed by the user when several cards match. When the remote's
read failed it says "Allowance unavailable — hover for why" with the
error as the title (existing string, all languages), never 0. The usage
comes from the machine that owns the account; no gateway change.

Run (mote, no Go change):
- routing-remote-windows.test.cjs (new; 5 languages, widths 1100 and 420,
  chromium and webkit) and routing-account-windows.test.cjs at ec697e692
  on origin/main 07f02d0d9..: 44 pass, 0 fail.
- Broken by hand: render call removed, and the model-family filter
  removed; each took the new test to 0 pass, 11 fail.
- Full go test -timeout 45m ./... at ea1aab179 (same client.js, rebased on
  f177c36a9): 86 ok, 2 red, neither from this change: TestCoreScriptBudget
  (1534154 > 1533802 at origin/main too, #5139) and
  TestMainWindowCorners/macOS_26_SDK (#3949).
- Six routing GUI files, serial, on origin/main cd83c3147 with no change:
  85 pass, 19 fail (rule-remove #3096, rule-drag #3789, row-swap #3799,
  order-unknown #4627, rules-line #3593; commented there). On this change
  27 and 28 fail; routing-rules-line alone 6 and 7 of 20 against 4 of 20
  on main, all the same 5s waitForFunction on .rt-gedit with the failing
  cells changing between runs. I judge it the same flake; not proven.
- The full GUI suite was started and killed after ~3h unfinished; its
  reds were in unrelated files (account-eye passes 15/15 alone).

Not tried: a real two-machine LAN run, a real Claude account on a remote,
Windows or Linux GUI engines (WebKitGTK).
2026-11-04 14:59:26 +08:00
yetone f0b99745ed provider: a Codex account is held on allowed false alone, as the 26.1029 app's Send gate reads it (xiaoq6285)
xiaoq6285 (Discord, Codex App 26.1029 on Windows, Plus, model_provider =
"magpie", requires_openai_auth = true) answered 40cfd32b0: "但是5小时也得算的
我就是5小时用完了 周额度还有" - their 5h window was used up with the week
open, and Send was grey.

What the app greys Send on, read from the bundles:
- ChatGPT.app 26.1029.61003 (the macOS build of the reporter's version,
  from persistent.oaistatic.com/codex-app-prod/appcast.xml), async chunk
  "a6kU": the composer gate returns open unless
  "n.rate_limit?.allowed!==!1" fails, i.e. it greys only on allowed
  false (then lets credits and a workspace within its overage through, and
  a window redeemed with a reset). The composer's sendBlocked is that gate
  or a model-scoped additional_rate_limits entry for the selected model.
- OpenAI.Codex 26.1027.3384 on the Windows box (app-primary lV,
  composer-content TN) and ChatGPT.app 26.1021: the same.
- The app keeps a window of an allowed account at 1% or more left
  ("Math.max(100-e,+(!0===t))"), so allowed true with 100% reads as room.

What the backend says at a used-up 5h window: the real Team reply in
testdata (codex_usage_team_spend_cap.json) has 5h at 100%, the week at
63%, and allowed false, limit_reached true.

So the reporter's case is allowed false, which codexHeld held before
40cfd32b0 and still does; no 5h rule is needed. 40cfd32b0's two new
held cases (allowed not said with limit_reached or a window at 100%;
allowed true with every window at 100%) are readings the app still sends
for, so holding them only took the app out of ChatGPT (#996) for nothing.
codexAtLimit is allowed false again. A new subcase pins the reporter's
shape (Plus, 5h at 100%, week open, allowed false, no credits: held).

Why Send stayed grey with requires_openai_auth still written is not
explained by the rule: with allowed false and no credits magpie holds
it. Left open: their reading, their magpie log, and whether a
model-scoped limit (additional_rate_limits, which magpie doesn't read)
was what greyed it.

Run on mote: go test -count=1 -timeout 45m ./internal/provider
./internal/agent ok (172s, 334s); go vet ./internal/provider native, GOOS=windows
and GOOS=linux ok; gofmt -l clean. Broken by hand: with origin/main's
subscription_usage.go and these tests, TestCodexUsedUpIsWhatTheAppHolds
fails on "limit reached, allowed not said", "window at 100%, allowed not
said" and "every window at 100% but allowed" (CodexUsedUp = true, want
false).
Not tried: the real 26.1029 app with a used-up account, a real Plus
/wham/usage reading at a used-up 5h window (the Team one is the only real
one), a Windows run.
2026-11-04 14:38:48 +08:00
yetone f177c36a9b provider: routed Until used up, Codex's sign-in stays on the account the requests went on to
WalterAIBuilder on X (11-04): two Codex accounts, A (Team, first) and B
(Plus), routed Until used up, affinity auto, stop at cap on. A used up
its 5h window (98% cap). Codex was signed in to B, then signed back in
to A once A had room, while B's week kept being spent until it was at
100%.

Cause: returnsToFirst (internal/provider/codex_switch.go) sent Codex's
sign-in back to the first account for every routing but Claude's and a
switch-only Codex's. Routed Until used up, the gateway keeps requests on
the account it moved to (routes.Drain, internal/routes/strategies.go),
and auto affinity keeps a conversation on whoever answered last while
the cache is warm (chatGPTCold, internal/gateway/affinity.go). So Codex
and the accounts list showed A in use, with B marked to go back from,
while requests through magpie stayed on B. The GUI note under Routing
also promised "back to the first" for drain. This is the hxy920830 rule
("not use one up, then the next") missing its Drain sibling.

Now, routed Until used up, Codex's sign-in stays on the account it moved
to till that one is used up too, the same as the requests. In order and
Smart still go back to the first. The Routing note has its own drain
text in en, zh, zh-TW, ja and de. The subsystem page says so.

Old data: a user signed back in to the first stays there. A user with a
return still pending stays on the next account until it is used up, and
the "First again" mark goes away.

Not changed (filing is the reviewer's call): a provider's own accounts
have no back-to-first under auto affinity (backToFirst and
backFromStandIn apply to groups only, inOrder := isGroup && ... in
internal/gateway/gateway.go). Routed In order, a conversation that moved
to the second account stays there after the first renews, for as long as
its cache is warm.

Run on mote (mote-run), at base 5957223d8 plus this change:
- go test ./internal/provider -count=1 -timeout 45m: ok (193.7s)
- GOOS=linux and GOOS=windows go vet ./internal/provider: ok; gofmt -l:
  clean
- node --test --test-concurrency=1 on the GUI tests account-return,
  keep-login, i18n-keys and routing-drain: 64 of 64 pass
Broken by hand: with "&& p.Routing != Drain" removed from
returnsToFirst, TestCodexDrainSignInStaysOnTheNext/drain fails ("first
marked to go back to: true, want false") and /order passes.
Not tried: real accounts; the whole GUI suite; Windows and Linux GUI; an
end-to-end gateway drain run together with a sign-in switch.
origin/main has since moved to d3c544ddf (3 commits); none of them
touch these files.
2026-11-04 14:28:02 +08:00
yetone d3c544ddf4 claude: a replayed transcript marks no earlier turn as the one to answer
The interactive mode gives a conversation no run has to a new Claude
Code as its own transcript (replaySession): a user line with the
messages before the last reply, the reply as the assistant line, and
the turn after it typed. The user line was rendered with
renderClaudePrompt, which ran historyEnd again on the cut messages, so
for U0 A0 U1 A1 U2 it was history(U0, A0) + <current_turn>U1, "the turn
to answer now", followed by A1, then U2 typed. U1 was answered already;
the reporter saw the model answer an old question again, and say
earlier tool calls had no results (愛睏柴犬阿茶 on Discord #feedback,
with the analysis and the fix suggested).

renderClaudePrompt is now renderClaudePromptAt(req, historyEnd(...));
replaySession calls it with the split at the end, which tells every
message before the reply inside <conversation_history> and closes it
there, with no <current_turn>. Every other render is unchanged.

Siblings: historyEnd has two callers, replaySession (whose own split,
on the whole request, is right: the reply and the turn typed after it)
and renderClaudePrompt. replaySession is the only place that renders a
cut slice of the messages (grep 'Messages = .*Messages\[:').
renderClaudeTurn (the typed turn) has no history marks.

Run (on mote, mote-run):
- go test ./internal/gateway -run TestClaudeTUIReplayMarksNoEarlierTurnCurrent:
  red on the old code (all 5 subtests: two turns, three turns, tool
  results in both turns, tool results only before the reply, the
  client's calls after the reply), green with the fix.
- Broken by hand: put renderClaudePrompt(&before) back in replaySession,
  the new test went red; restored.
- go vet ./internal/gateway, GOOS=linux and GOOS=windows go vet: ok.
- go test ./internal/gateway -run 'Claude|Replay|Prompt|Turn': ok 124.6s.
- go test ./internal/gateway -run 'Loop|Guard|Doc': ok.
- gofmt -l internal/: clean.

Not tried: a real Claude Code resumed on such a transcript with a real
account (the change to what the model sees was checked in the
transcript file only); the full suite runs after the tag.
2026-11-04 14:26:27 +08:00
yetone 1987fe220c agent restart: a script run on the app's own executable is not the app (WorkBuddy's sidecar)
Northes (Discord #feedback, 11-04): WorkBuddy's Agents row kept "重启
WorkBuddy 后生效" after they quit and reopened it, and its Restart quit
WorkBuddy and never opened it again. #3700 (Raters0) is the second half on
WorkBuddy AI.

Cause, from WorkBuddy 5.5.6's app.asar (read only) and its processes on the
Windows box: WorkBuddy starts a sidecar as `<its own executable>
.../app.asar/main/sidecar-entry.js --token ...` (ELECTRON_RUN_AS_NODE,
detached). The sidecar outlives the app's quit and the next start reuses
it, and its prewarm and `--serve` CLIs run as `<executable>
.../cli/bin/codebuddy ...`. The daemon is `WorkBuddy.exe ...
daemon-app-server-entry.js --stdio`. All of them match the running check's
`Contents/MacOS/<exe>` pattern (and WorkBuddy.exe's image on Windows), so:
- (a) findRestartable took the oldest match, the sidecar, as the app's
  start, so magpie's change was always "after" it and the row never
  cleared, however often the app restarted. On Windows the earliest start
  was used too.
- (b) reopenBundle waited for every process under Contents/ to end; the
  sidecar never does, so after 30s it said "still open" and never ran
  `open`.

Fix: runsScript(cmd, exe) tells a script run on the app's executable (a
.js/.cjs/.mjs argument, or a first non-flag argument that is an absolute
path) from the app itself and its helpers (--type=..., /prefetch:,
-psn_, a deep link). The macOS running check and the reopen's wait skip
such processes (appProcs), and the Windows check reads each process's
command line (proc.CommandLine, new) and skips them too. The reopen still
waits for real helpers (renderer, GPU). This is shared by every restartable
app: Claude desktop, WorkBuddy, WorkBuddy AI and the Codex app.

Tests (red on the old code: a copy of the base with runsScript returning
false failed all three, since = the sidecar's 2h, the Windows since the
sidecar's, and 6 RunsScript rows):
- TestWorkBuddySidecarOutlivesQuitOnMac (WorkBuddy and WorkBuddy AI, a
  space in the bundle): a 2h-old sidecar and prewarm beside the app; the
  row is behind by the app's start, a manual reopen clears it, the
  sidecar alone is not "running", Restart quits then opens.
- TestWorkBuddySidecarOutlivesQuitOnWindows: same, and Restart closes and
  ends only the app's tree, then opens it.
- TestRunsScript: real Windows command lines from WorkBuddy on the box,
  macOS ones, and #3700's `codebuddy --serve` line.

Run at this head (rebased on d6d3e6cc8):
- mote: gofmt -l clean; GOOS=windows, linux and darwin go vet
  ./internal/agent ./internal/proc; go test -count=1 ./internal/agent
  ./internal/proc ok.
- xiaomi-gpu (win-run): go test ./internal/agent ./internal/proc -run
  'Restart|Sidecar|RunsScript|WorkBuddy|List': the new tests pass; red are
  TestWorkBuddyRestartOnMac and TestWorkBuddyOwnSaveAfterStartIsNoChange/
  darwin (red the same at origin/main d6d3e6cc8, #4115) and
  TestWithViaKeepsTheJoinedList (#4786). The new mac test skips on Windows
  for #4115's reason.
- Real processes, uncommitted tests: on mote a fake "WorkBuddy AI.app"
  (Go sleeper as Electron) with a sidecar started first, through real
  pgrep and sysctl: since is the app's (0.66s), the sidecar alone is not
  running. On xiaomi-gpu a fake WorkBuddy.exe sidecar and app:
  readWinProc's command lines are the real ones and runsScript tells
  them apart.

Not tried: the real WorkBuddy or WorkBuddy AI (not run, ~/.workbuddy not
touched); a real Restart end to end through osascript/open or on Windows
(the quit/open steps are faked); Linux (no restartable app there).

Refs #3700
2026-11-04 14:25:43 +08:00
yetone 5957223d89 library: a project's skills can be given to DeepSeek Harness, in the project's .agents/skills
xingchen_c on Discord (#general, 11-04): "资源库按照项目配置能否支持一下dsh".
projectSkillsDirs left dsh out, its comment saying it reads no project
folder magpie can rely on. It does, and always has: the skill provider
every dsh profile mounts (dsh-base's cordis.patch.yml, id skill-filesystem)
scans <projectRoot>/.dsh/skills (rank 100) and <projectRoot>/.agents/skills
(rank 200), the project root being the nearest folder up from the
session's cwd with a .git, else the cwd (roots and findProjectRoot in
@deepseek-ai/dsh-skill-filesystem 0.2.1-rc.5; the same two joins in
0.0.1-rc.3, 0.1.0-rc.6, 0.1.5-rc.3, 0.1.7-rc.2, 0.2.0-rc.2, 0.2.1-rc.1
and 0.2.2-alpha.3). dsh now gets the shared .agents/skills, so the
project row lists it and one link serves it with Codex and the rest.

MCP stays as it was: dsh's servers are dsh-mcp-client rows in a
profile's patch layers (bundles, the profile's and $DSH_HOME's
cordis.patch.yml, --patch overlays; composeProfile in @deepseek-ai/dsh
0.2.1-rc.5), none of them the project's. Said in project_mcp.go and
docs/subsystems/library.md.

Run:
- mote: go test -count=1 ./internal/library/ ok (102.9s); gofmt -l
  clean; GOOS=windows and GOOS=linux go vet ./internal/library/ ok.
- Broken by hand: TestProjectSkillsDsh with projects.go at origin/main
  fails ("magpie knows of no folder dsh reads a project's skills from").
- Real dsh: @deepseek-ai/dsh 0.2.1-rc.5 from npm on mote, sandbox HOME
  and DSH_HOME, headless profile against a fake OpenAI-compatible server.
  Run in a folder with .git, a skill linked into its .agents/skills is in
  the request's <available_skills>; run in a folder with no .git, its own
  .agents/skills is read; run in a subfolder of the repository, only the
  root's is read, not the subfolder's (filed as #5172).
- GUI: /api/library's view from library.Read with a sandbox ~/.dsh,
  served to the real assets in Chromium and WebKit, en and zh: the
  project card's skill rows have a dsh chip (lit where given), and the
  "reads no project skills folder" line no longer names it.

Not tried: the dsh Desktop app (its own profile; the same base bundle
is assumed, not checked); the full GUI suite (no GUI file changed);
Windows copy mode with a real dsh.
2026-11-04 13:53:04 +08:00
yetoneandreyoung 83bdfe70d2 otlp: OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME name the server a trace or metric came from (#5167)
Several magpie servers exporting to one collector or to Langfuse all sent
the same resource, service.name=magpie alone, so nothing said which server
an event came from. Both signals' resource now merges the standard
OTEL_RESOURCE_ATTRIBUTES over that default, and OTEL_SERVICE_NAME over
that (otelResourceAttributes in internal/otlp/otel_resource.go). Nothing
about the machine is looked up; only what the user set is sent. Neither
variable turns export on.

Ported from reyoung's 7ed03b819 (feat/otel-resource-attributes, base
4ca55c6b6), reviewed line by line; nothing in it reached past its goal.
Changed from it:
- service.name precedence. The resource SDK spec makes code-supplied
  attributes win over OTEL_RESOURCE_ATTRIBUTES, but magpie's "magpie" is
  the fallback in the role the spec gives unknown_service, not identity
  the user supplied, and magpie's default never overrides a value the
  user set (code standards). So a service.name in the variable wins, and
  OTEL_SERVICE_NAME, which the spec's env table puts over the variable's,
  wins over both. An empty service.name or blank OTEL_SERVICE_NAME counts
  as unset (the spec's "empty value = unset"), so the resource never
  carries service.name="".
- Bytes that aren't UTF-8 once decoded (%FF) are a decoding error and
  discard the variable; before, json.Marshal sent U+FFFD.
- The variable was parsed and, when bad, logged on every flush of each
  signal. It is now parsed once per value and logged once, naming the
  entry by position (never its contents).
- otlp tests clear both variables in otelConfig, so a developer's shell
  can't change what the existing wire tests see.
Kept: whole variable discarded on any invalid entry (no '=', empty key,
bad escape, empty entry such as a trailing comma), as the spec says;
keys and values trimmed and percent-decoded with PathUnescape ('+' stays
'+'); last repeated key wins; values are strings.

Docs: reference.md's OTLP export, plugin-runtime.md's internal/otlp row,
and the privacy pages (en, zh, ja) now say the resource carries what the
user sets there.

Verified:
- TestOTelResourceAttributes reads the resource a test collector gets on
  /v1/traces and /v1/metrics, 17 cases. On the old otelEnvelope it FAILs
  (server, override and duplicate, encoding and empty, unencoded UTF-8,
  OTEL_SERVICE_NAME cases: "traces resource attributes =
  map[service.name:magpie]", same for metrics). Broken by hand one at a
  time, each went red: UTF-8 check off (not_UTF-8_once_decoded), no
  OTEL_SERVICE_NAME (3 cases), empty service.name kept (empty_service_
  name_is_unset), valid entries kept from a bad variable (missing equals,
  trailing comma, empty key, ...), and the per-value cache off
  (TestOTelResourceAttributesLoggedOnceWithoutContents: "logged 4 times,
  want once"). All green restored.
- On mote: go test -tags nogui ./internal/otlp ok; go test -race -count=3
  -run TestOTel ./internal/otlp ok; go vet, GOOS=linux go vet -tags nogui,
  GOOS=windows go vet (internal/otlp); go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build; node --test site/*.test.mjs; gofmt -l
  empty.
- Full suite: run after the push (go test -tags nogui -timeout 45m ./...
  on mote); reds, if any, filed separately.

Not tried: a real collector or Langfuse; Windows/Linux runs of the
package (the code has no OS-specific path).

Co-authored-by: reyoung <728699+reyoung@users.noreply.github.com>
2026-11-04 13:50:09 +08:00
yetone cd83c3147f plugin: a hook's auth.set doesn't sign in again an account signed out while it ran (#5126, #5119)
Cause: a plugin hook that saves a sign-in through client.auth.set (a
models list spending a rotating refresh token) wrote it into
plugin-auth.json unconditionally. A listing that began before a
sign-out, or before a failed move's putBack took the accounts back out
of the plugin (plugin.Take), landed after it and wrote the account in
again. TestMoveToPlugin's reset signs fakeco out, but a background
listing set off by the step before spent a@fake's "rot-a" token again
(rot-a+++++ seen in the file right after the sign-out), so the next
Move saw a@fake as the plugin's own (movedAccount.Was), restored it on
failure, and "the plugin kept an account of a failed move".
TestMoveCutShort (#5119) fails the same way: the account Take removed
came back through the same write. Not a leak between runs: the race is
inside one run, and more runs only gave it more chances. It is a real
bug for users too: signing out of a rotating-token account while its
models are listed brought it back.

Fix: inScope in host.js notes whether the account was signed in when
the call began (had); auth.set skips the write under the file's lock
when it was and is gone now, as renewLocked already does for renewals.
Sign-in steps (signingIn) are not held to it, their account is new.

Test: TestSignOutOutlastsRunningHook holds the fake plugin's models
hook (new FAKE_MODELS_HOLD: marker file in, release file out) across a
SignOut in a real host and checks the account stays gone, and that a
hook not raced still keeps the token it saved.

Run (all at this tree):
- mote-run go test -count=30 -run 'TestMoveToPlugin$|TestMoveCutShort$'
  ./internal/provider: ok. Before the fix the same run on mote failed
  3 TestMoveToPlugin + 9 TestMoveCutShort of 30 each; -count=15 of
  TestMoveToPlugin alone failed 2 to 4 of 15.
- wsl-run go test -count=20 of the two plus the new test: ok. Before
  the fix: 4 + 17 of 20 failed on Linux.
- mote-run go test -count=5 -run TestMoveToPlugin$: ok.
- mote-run go test -count=5 TestSignOutOutlastsRunningHook: ok.
- mote-run go test -timeout 45m ./internal/provider ./internal/plugin:
  ok (provider 171.6s, plugin 160.4s).
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet of both
  packages: ok.

Broken by hand: host.js reverted with the test kept:
TestSignOutOutlastsRunningHook red 3 of 3 ("the hook signed the account
in again"), and the provider tests red as above.

Not tried: a real vendor's rotating-token plugin signed out mid-listing
(the fake plugin's rot- sign-ins stand in for it); the full ./... suite
runs after the push.
2026-11-04 13:23:28 +08:00
yetone 40cfd32b0b provider: a Codex account with no credits and every window at 100% counts held though allowed isn't false (xiaoq6285)
xiaoq6285 (Discord, magpie 0.1.2891, Codex App 26.1029, Windows): a used-up
Plus account, no credits, 用量 showing it used up, config.toml with
model_provider = "magpie" and requires_openai_auth = true, Send grey until
Codex was switched off in magpie. Banked resets and paid credits were ruled
out (codexHeld reads neither resets nor, here, any credits). What is left is
a reading that doesn't say allowed false: codexHeld needed exactly that, so
CodexUsedUp stayed false and Sync kept requires_openai_auth, which makes the
app read the account's rate limit and grey Send.

codexAtLimit now holds: allowed false (as before); allowed not said with
limit_reached or a window at 100%; allowed true with every reported window
at 100%. Credits and the workspace-overage exemptions are unchanged and
still run after it.

Why the two cases that were false stay narrow: a7c4e5ddd (#996) pinned
"limit_reached but allowed, no credits" to not held, because the composer
gate (hP / hardBlocked in 26.930) reads allowed alone and the app still
sent; holding such an account only takes the app out of ChatGPT (durable
threads, remote control, cloud tasks, its usage meter) for nothing. That
cost is real, so allowed true still stands unless no window has room: a 5h
window at 100% with the week open is not held (new case). The case
"limit_reached, allowed not said" does flip to held.

Not known: the reporter's actual reading (allowed true or missing, never
seen) or the 26.1029 gate (its bundle isn't on any test box; 26.1021 is).
If their reading says allowed false with no credits this changes nothing
for them.

Run on mote: go test -timeout 45m ./internal/provider ./internal/agent ok
(194s, 346s); GOOS=linux, GOOS=windows and native go vet on both ok; gofmt -l
clean. Broken by hand: with the old subscription_usage.go and the new tests,
TestCodexUsedUpIsWhatTheAppHolds fails on "limit_reached, allowed not said,
no credits" and "every window at 100% but allowed, no credits".
Not tried: the real 26.1029 app, a real used-up reading, Windows run.
2026-11-04 12:41:11 +08:00
yetone d1fa254b1d gui: masked words and Never mask are a list, a row per word (noahhrreion on Discord)
noahhrreion: "希望脱敏词选项可以做成真正的列表,在一个小输入框里面不方便管理多个脱敏词".
Settings → Privacy's Masked words was one comma-separated box. It is now a
list (wordList in plugins/redact/settings.js): each word is its own row,
edited in place (Enter or leaving the row saves, Escape puts it back,
emptied is removed), × removes it, and the last row adds. Its sibling,
Never mask under the mask actions, had the same box and gets the same list.

Stored values are unchanged: redactWords and the allow list are still
string arrays, saved through the same savePrefs / settings/redact-allow
calls, and nothing is rewritten on open (the new test checks that opening
the page saves nothing). Typed or pasted text splits as the old box did
(, , and newlines, trimmed, empties dropped), so a pasted "a, b" is two
rows. The Hide eye still shows every row as dots. New strings are in the
redact plugin's i18n for zh, zh-TW, ja and de; the two old "separated by
commas" hints are gone from the core i18n. The site's masking docs (en, zh,
ja) say a row each.

Run (on mote via mote-run, Chromium and WebKit):
- new redact-words-list.test.cjs: 5 languages × 1100/400px × both engines,
  draw, add with Enter, paste-split, edit, Escape, ×, empty-and-Tab, reload;
  with i18n-keys 24/24 ok
- redact-words-hidden, any-case, whole, mask-actions, redact-route,
  redact-kinds, redact-shape, settings-search, settings-sections,
  settings-lines-wrap, settings-hints, settings-groups, readable-focus,
  masking-records, mask-alert: 378/378 ok
- go test ./internal/gui/ -run 'TestCoreScriptBudget|TestSettings': ok
  (app.js shrank; no budget raised)
- screenshots light/dark, 1100/400px, both engines, looked at

Broken by hand: without wordFocusBack (focus kept across a redraw) the new
test goes red (waitForFunction timeout after the first add). Dropping the
blur guard during a redraw (wordsRedrawing / isConnected) stays green in
both Playwright engines, which fire no blur on removal; it is kept as a
guard for engines that do, with no test that fails without it.

Not tried: the real app on WebKitGTK / Windows WebView2; no Go files changed.
2026-11-04 12:38:10 +08:00
yetone 43345c0ca8 docs: gateway-routing names the GPT ids sent output_config.effort 2026-11-04 11:33:01 +08:00
yetone 247794c613 codex: an account that is out takes over for other models too (reverses f37742e14)
With one ChatGPT account out and nothing to serve Codex's own model on
(provider.CodexServesWhileOut false), f37742e14 left Codex on its sign-in
to keep the account's menu. But the Codex app greys Send for every model
while authMethod is chatgpt and /wham/usage says not allowed, so shamen
(mac, banner "Codex 和工作使用额度已用完"), chenhan and xiaoq6285 could send
nothing on GLM-5.3 or any other magpie model. A grey Send for every model
costs more than the menu, so this is the owner's product call: sending on
other models comes first.

When joined, on ChatGPT and held, and magpie has a model on no ChatGPT
account (codexOtherModel), Sync makes magpie the provider on that
stand-in, keeps the user's model in codex.out_own and the stand-in in
codex.out_stand, and at the reset puts Codex back joined on its own model
(#540 way back). Once per held/unheld transition: on the stand-in the model
is magpie's, so the branch is not met again. With nothing else to offer,
Codex stays on its sign-in as in f37742e14. Nothing about identity,
base_instructions or the account's state is changed or faked; magpie only
becomes the provider, as for any held account.

Run (mote-run, win-run, sandbox HOME, fake upstream; no real exhausted
account was tried):
- go test -tags nogui ./internal/agent -run Codex: ok; ./internal/provider
  -run CodexServes: ok; win-run ./internal/agent: see the tag notes.
- gofmt -l, go vet linux/windows/native on internal/agent: clean.
- New TestCodexOwnModelOneSpentAccountTakenOverForOtherModels: takeover,
  three more Syncs with no config write and no codexAppRoute change, the
  reset back once, a further Sync changing nothing. TestCodexOwnModel-
  OneSpentAccountStaysOnItsSignIn now covers only the nothing-else case
  (fake provider deleted).
- Broken by hand: new branch disabled -> the new test red; the
  !isMagpie(m) one-shot guard removed -> red.
Not tried: a real exhausted account in the Codex app; the stand-in picked
by the user is indistinguishable from staying on it and gives way to the
own model at the reset (documented in agent-wiring.md).
2026-11-04 10:05:32 +08:00
yetoneandSKYhuangjing 2741b749f9 sessions: a codex fork's rollout-<n> turn does not end the copied head (#5090)
ownTurn ended a Codex fork's copied head at the first turn id the parent's
file didn't hold (fb1f4856a). codex-rs names a turn that has no id of its
own "rollout-<n>" (the rollout canonicalizer's implicit turns; the
thread-history builder), and a copied head can carry one the parent's file
lacks. It was taken for the fork's first own turn, so every copied
checkpoint after it was booked as the fork's call: July and August usage
that was the parent's history over again. Reporter: SKYhuangjing, whose
fork branch codex-fork-head-marker (acb034645) this ports.

ownTurn now leaves a "rollout-" turn id alone. callParseVersions and
parseVersions raise codex to 3, so kept shards and call caches are read
again once (the same one-time re-read the codex 2 raise cost).

Changed from the patch: the code comment and the subsystem page
(docs/subsystems/gateway-sessions.md) say what codex-rs does, not what
the reporter's corpus showed; the test comment names #5090.

Checked, not changed: ZCode's fork path (zcDB.copied) matches copies by
the original message id and never reads a turn id; ownTurn has one
caller (codexUsageState.context).

Run (mote-run, at this tree on origin/main + this commit):
- TestCodexForkHeadMarkerDoesNotEndTheCopies red with ownTurn as on
  origin/main (4 calls on the fork, want 1), green with the fix.
- go test -count=1 ./internal/sessions ./internal/usage ok; gofmt -l clean.
- GOOS=windows and GOOS=linux go vet ./internal/sessions clean.
Not tried: the reporter's real database (we have no copy of their
corpus). Not confirmed: codex-rs main has no writer that puts a
turn_context with "rollout-<n>" into a forked file from
record_initial_history, as the issue says; the prefix is confirmed from
the two codex-rs writers above, but which one produced the reporter's
files is unknown. Not handled: a fork whose own first turn is itself a
"rollout-<n>" (a legacy rollout migrated with no ids) still doesn't end
the copies by turn id; checkpoints still match it as before.

Full suite: run after the push, result on #5090.

Co-authored-by: SKYhuangjing <13705011+SKYhuangjing@users.noreply.github.com>
2026-11-04 09:10:52 +08:00
yetone 90bf96a23d search: a plugin can give a web search API (its search hook)
treeman on Discord #help asked for web search to be pluggable so users can
add search vendors. A plugin's `search` hook, {search: {<id>: {name, keysURL?,
keyOptional?, url?, execute({query, count, key, url}, ctx)}}}, adds an API to
Settings > Models > Web search as `<plugin>:<id>`. It is added, keyed, ordered,
switched off and removed like Tavily or Brave. The built-in APIs stay built in.

How: host.js collects the hook's entries (id [a-z0-9-], an execute) into
Loaded.Searches and runs one with the `search` op (timeout from ctx, an error
with a numeric status comes back as a refusal). The host notes them in
plugin-searches.json (internal/plugin/search.go); provider.AllSearchVendors
adds the noted ones of plugins that are on to SearchVendors, so Ready, check,
the CLI and the GUI list see them. askSearchAPI hands a plugin vendor to
askPluginSearch below askSearchAPIKeys, so keys, rest on 401/402/403/429,
order, the masked query and the request-log row are the built-ins' own.

Run (mote, on this tree, whose base df7c94bdf was just fetched):
- go test -timeout 45m ./internal/plugin ./internal/provider ./internal/gateway
  ./internal/cli: ok.
- go vet native; GOOS=windows go vet plugin, provider, gateway, cli: ok;
  GOOS=linux go vet plugin, provider, gateway: ok. gofmt -l: empty.
- internal/gui: TestCoreScriptBudget and TestMainWindowCorners fail in a
  full run. This change touches no script (only api.go's loop), so the
  budget red is the base's (re-checked after the rebase, below);
  TestMainWindowCorners is AppKit on mote (macOS 27).
Broken by hand: skipping off plugins in NotedSearches turns TestPluginSearch
red; the refusal mapping removed turns TestPluginSearchAPI red.
Not tried: a real plugin against a real vendor's API; the GUI JS suite (no
GUI script changed); a Linux or Windows window; site/public/docs (en, zh, ja)
do not describe the hook yet. A plugin just added is listed once the host has
loaded it; RestoreSearchAPIs drops a plugin's entry on a machine without it.
The community README has the template (magpie-community/plugins 3ec42d4).

Reported by treeman.
2026-11-04 08:37:21 +08:00
yetoneandMYCF711 df7c94bdf5 gateway: inline image descriptions survive a restart (#5121)
The vision description cache (Server.sights) was in memory only, so a
restart, update or handover described every image of a long conversation
again (62 calls in 2.5 minutes in the report). Completed descriptions of
inline images are now appended to vision-cache.jsonl (0600) in the config
dir before their waiters are released, and New restores them under the
same 2048-entry LRU. URL images stay in memory (their bytes can change);
failures are never written. Appends and compaction go through a file lock,
a corrupt or truncated line is skipped (and backed up before compaction),
and shutdown waits for pending saves within the drain window.

Patch by MYCF711, applied clean on main. One change: the Unix permission
test now makes the config folder before it pre-creates the file (it failed
on a fresh sandbox, where the folder doesn't exist yet).

Run (mote, at this tree): go test ./internal/gateway filtered to the
vision/sight/cache tests, ok; gofmt -l clean; go vet ./internal/gateway
for linux and windows, clean. Broken by hand: saveSight call removed from
see(), TestDescriptionSurvivesGatewayRestart red (2 descriptions, want 1),
green again with it back. Windows: the same filtered tests on xiaomi-gpu
via win-run. Not tried: full go test ./..., go vet ./... for linux (wails
cgo doesn't build off-platform on mote), a real process kill or a real
handover, a real gateway with a real vision model.

Co-authored-by: MYCF711 <323101370+MYCF711@users.noreply.github.com>
2026-11-04 07:57:43 +08:00
yetone 6673171595 update: the app and magpie web follow each other's update (visamzh on X)
visamzh on X: with the desktop app and magpie web both open, an update
from either side left the other still offering it ("↑ 更新") until it was
quit by hand.

Cause: the app and magpie web are two processes over one program, each
with its own updater (state, download, latest) in memory. One restarting
to update puts the new binary in; the other is told nothing. Its
replaced() (the binary on disk is no longer the one it started from) was
read only on a click of its own Update or on magpie update's gateway ask
(restartBeside), which reaches only the process serving the gateway. And
a browser's page reloaded (backAsNew) only after a restart it asked for
itself, so magpie web's tab kept the old page and its pill even once
the process under it was new.

Fix:
- followReplaced (update_beside.go): every updater stats its binary each
  5 s and, once another magpie replaced it, restarts into it through
  restartBeside, once: at once when idle, else after the gateway's
  requests (waitIdle), as for magpie update's ask. Not for what this
  process put in itself (installed, set by install, cleared by
  wontStart), not twice (followed), not for a build that isn't a release
  (make dev, go build rebuild in place). It stops with backendCtx, so a
  copy left draining after a handover doesn't look.
- waitFor (update_wait.go): a wait for the gateway restarts into what
  another magpie put in whatever the feed says now; before, a feed out
  of reach or a "latest" answer ended the wait with nothing restarted.
- boot.js names the version that served the page (bootPrefs.version);
  app.js's servedAnew reloads a browser's page (web) when /api/update's
  current names another, on the reads it already made (load, focus, back
  into view) and once a minute while shown. The app's own windows come
  back with their new process and are left alone.
- docs/subsystems/gui-shell.md describes it.

Run (mote, through mote-run, at 1e1068c86 + this change unless said):
- gofmt -l internal/gui: nothing.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go
  build: all ok.
- go test -tags nogui -race -count=5 -run
  'Follow|AnotherMagpies|OwnUpdate|OwnBuild|UpdateClicked|Wait|Beside|
  Restart|Install|WhatsNew|Quiet' ./internal/gui/: ok (102.9s).
- go test -tags nogui -timeout 45m ./internal/gui/... ./internal/cli/...
  ./internal/update/... . : gui, update, update/launcher and magpie ok;
  internal/cli red in TestEveryRouteHasACommandOrIsNamed (GET
  /api/context/reply has no command), red the same on origin/main
  51fa4b7eb alone, filed as #5026 (from 0872bc2a0).
- node --test internal/gui/tests/update-served-anew.test.cjs: 34/34
  (Chromium and WebKit; en, zh, zh-TW, ja, de; 1100 and 420 wide; the
  minute poll under page.clock; the app's window not reloaded).

Broken by hand, each red, then put back:
- followReplaced never restarting: TestAnotherMagpiesUpdateRestartsThisOne
  and TestAnotherMagpiesUpdateWaitsForTheGatewayThenRestarts red.
- the installed guard dropped: TestOwnUpdateIsNotFollowedAgain and
  TestUpdateClickedOverAnothersIsNotFollowedAgain red (a second restart).
- waitFor's "in" case off: TestAnotherMagpiesUpdateWaitsForTheGateway
  ThenRestarts red (the wait ends with nothing restarted).
- boot.js without the version: TestBootNamesTheVersionThatServedThePage
  red.
- servedAnew not reloading: 15 of 16 subtests red in Chromium.
- the minute poll removed: the 5 "left on screen" subtests red in WebKit.

A first cut also refused a second install() once one was in; that made
TestRestartBySelfComesBackQuietly and TestWhatsNewQuietAfterRestartTo
Update red (they restart one updater several times), so the flag only
keeps followReplaced off.

Not tried: a real pair of the app and magpie web on two release builds
with one replacing the binary (only temp files and fakes); Windows
(InstallBinaryAside starts the staged file there, so the own-install
test is skipped and the click test covers the flag) and Linux runs;
the whole GUI suite: mote was never free (two other sessions' full GUI suites, load ~400), so it runs on the Linux box after this lands.
2026-11-04 06:59:29 +08:00
yetone 0e1054ce19 statusline: the gateway serves Claude Code's status line to another computer (steven_4422)
steven_4422 (Discord) runs magpie in Docker and Claude Code on the host.
The status line square writes the host's settings.json, which the
container can't reach, with a command naming a binary inside the container.

GET or POST /v1/magpie/statusline answers the line `magpie statusline`
prints, as text/plain, so the host needs only curl:
  curl -fsS -m 1 -H 'Authorization: Bearer <key>' --data-binary @- http://<host>:3425/v1/magpie/statusline || true
Claude Code's stdin JSON (session_id) adds the model, as /v1/magpie/route
does; ?session= and ?only= work too. The renderer moved to
provider.StatuslineText, shared by the CLI and the endpoint. A caller that
isn't this computer needs a gateway key (lanGuard, unchanged; the handler
also refuses a non-local caller without one). A read-only key is allowed
(GET and POST in readOnlyRoutes) and gets the windows without the model; a
key held to budget, models or accounts sees only its own (scopeQuotas).
corsGuard and origin checks are untouched.
magpie web shows the command in Settings -> About (en, zh, zh-TW, ja, de).
Docs: reference.md, agent-wiring.md, gateway-routing.md, docker pages en/zh/ja.

Run at this head (rebased on d8b3749ef), on mote:
- go build, gofmt -l, GOOS=windows go vet and GOOS=linux go vet -tags nogui
  on gateway, cli, provider: clean.
- go test: internal/gateway ok (a first full run failed once, 888s, name not
  kept; the rerun had no failure), TestStatusline*, TestReadOnlyKeyEveryRoute,
  TestStatuslineEndpointIsTheCLIsLine ok. internal/agent ok earlier, at the
  pre-rebase base.
- TestCoreScriptBudget ok after shortening the new strings (no raise).
- GUI: statusline-remote (22: 2 engines x 5 languages x 1100/400, plus the
  app without the row), public-url-default, i18n-keys, claude-statusline: all pass.
Broken by hand: model made wrong -> TestStatuslineEndpoint red; held-key
scope removed -> red; separator changed in the shared renderer ->
TestStatuslineEndpoint and cli TestStatuslineTellsRouteAndEveryAccount red;
the row's web check inverted -> the GUI test 0 of 22. Removing the
handler's own key check stays green because lanGuard refuses first (the
401 asserts hold through it).
Reds not from this change: cli TestEveryRouteHasACommandOrIsNamed
(GET /api/context/reply, from main), gui TestMainWindowCorners (red on
origin/main on mote), provider TestMoveToPlugin and TestMoveCutShort (red in
the full run, green alone).
Not tried: Docker or any container (not on mote or WSL); the real binary
from another computer over the LAN with a real Claude Code; the whole GUI
suite (running, 1182 files, finishes after the push); Windows and Linux
test runs.
2026-11-04 06:39:37 +08:00
yetone 59c1306035 claude: an auto-mode client's tool loop keeps its interactive run (#4804)
Auto mode's safeguards change with every tool batch: prior_turn_context
grows by the turn before. An interactive Claude Code run read them once,
from CLAUDE_CODE_EXTRA_BODY in its environment as it started. So a tool
loop either started the run again (the whole conversation written to the
cache again), or kept it and sent the classifier the context it started
with, which is not what real Claude Code sends.

Each turn's safeguards now reach the running run:
- The bridge writes the extra body to <run tmp>/guard.json and hands its
  path to the helper as MAGPIE_CLAUDE_GUARD (mapped for WSL in newTap).
- tap.js, on each /v1/messages request whose string body has a
  safeguards key, reads the file and puts its safeguards in the body. It
  also sets CLAUDE_CODE_EXTRA_BODY to the file's text, so Claude Code's
  own later reads agree. The first time, it writes guard.json.live.
- setSafeguards rewrites the file (temp and rename, retried for Windows)
  instead of restarting, once .live exists. Without .live (a Claude Code
  that doesn't load the tap), it falls back to the old rule: keep the run
  when only the varying parts changed, otherwise restart. A beta change,
  or safeguards appearing or going, still restarts.
The tap changes only the safeguards value; any other byte of the body is
Claude Code's own. Bodies without safeguards, count_tokens and non-string
bodies are passed through untouched.

The tool-results path logged "process expired" alone while the run's end
read "magpie ended it". It now aborts the run with the reason and logs
"tool results process expired: <reason>". continueWith's "not waiting for
tool results" does the same.

Tests:
- TestClaudeTUIToolLoopCarriesEachBatchsSafeguards: three tool batches
  with growing prior_turn_context, then the answer. Checks one run and
  that each request carried its own batch's safeguards.
- TestClaudeTUIToolResultsLogWhyTheRunEnded: no tap and the rules change.
  Checks that the log has the reason.
- TestTapPutsTheGuardFilesSafeguards (bun and node): the rewrite, the
  bodies left alone, the env, and .live.
- TestTapEnv: MAGPIE_CLAUDE_GUARD is passed through, WSL-mapped.

Run (worktree at c360d9d30 + this change):
- mote: go test -run 'TestClaudeTUI|TestClaudeBridgeSafeguard|
  TestClaudeToolResults|TestClaudeNoRunSaysWhy' ./internal/gateway ok
  (73 PASS); go test -run TestTap ./internal/claudetui ok (bun and
  node); go vet ./internal/claudetui ./internal/gateway on darwin, linux
  and windows ok; gofmt -l internal clean.
- Full suite, go test -timeout 45m ./..., ran on the Linux box (wsl-run,
  magpie-desktop), not mote. mote had two other sessions' GUI suites
  sitting at 0% CPU for 3h42m at load 300, and one suite per machine.
  Result: 80 packages ok, internal/claudetui ok. Red:
  - TestGrokInstalled (#3548)
  - TestCodexBodyLimitFromMemory (#5118)
  - TestMoveCutShort (#5119)
  - TestCCListingKeepsItsNames (#4925)
  All four are red the same way run alone at origin/main d8b3749ef on
  that box. Root, internal/cli and internal/gui don't build there
  without GTK4 (#5120).
- Real use, macOS:
  - Sandbox HOME and CLAUDE_CONFIG_DIR, the owner's Max account copied
    to the sandbox dir's keychain item and deleted after. The refresh
    token didn't rotate.
  - A gateway on 127.0.0.1:3496; magpie built -tags dev at c360d9d30
    (before) and with this change (after).
  - Client: real interactive Claude Code 2.1.316 in tmux,
    --permission-mode auto, sonnet 5.5 through the gateway.
  - One turn, three sequential Bash calls (echo one, ls -la, echo three),
    four upstream requests.
  - Before: one run (pid 49488), cache_write 23005/86/162/86 (the first
    request cold). Its CLAUDE_CODE_EXTRA_BODY stayed the first request's
    safeguards, with no prior_turn_context, so requests 2 to 4 sent the
    classifier stale context.
  - After: one run (pid 64000), cache_read 23005/23091/23091/23253,
    cache_write 0/0/162/86. guard.json.live was written; the tap logged
    3 "guard":"set" (requests 2 to 4), and guard.json ended with 3
    prior_turn_context entries.

Broken by hand:
- The old claude_subscription.go makes both gateway tests red ("request
  0 carried ..."; the log said "tool results process expired" alone).
- tap.js without the rewrite makes TestTapPutsTheGuardFilesSafeguards
  red in bun and node.

Not tried:
- A tool loop whose rules change mid-loop with a real client (restart
  path; only the fake covers it).
- Linux or WSL with a real Claude Code (the TUI isn't used on Windows).
- Comparing the before/after upstream bodies byte for byte (the tap
  logs that it set the value, not the bodies).
- The gateway package as its own -timeout 45m run on macOS: only the
  targeted tests ran on mote, and the full package ran on Linux.
2026-11-04 06:38:56 +08:00
yetone d8b3749ef7 agents: Copilot CLI reaches magpie's models through its providers.json (BYOK)
tony9759 on Discord asked for Copilot CLI to be wired to magpie, since its
docs say it takes a custom model provider URL.

What Copilot does (1.0.105, @github/copilot-darwin-arm64's cli-main.js,
`copilot help providers` / `help environment`; GitHub docs
docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/use-byok-models):
env BYOK (COPILOT_PROVIDER_BASE_URL, _TYPE openai|azure|anthropic, _API_KEY,
_WIRE_API completions|responses) and a providers.json at
$COPILOT_PROVIDERS_CONFIG, else <COPILOT_HOME or ~/.copilot>/providers.json:
{providers:[{name,type,baseUrl,apiKey}], models:[{id,provider,name,
maxPromptTokens,maxOutputTokens,...}]}, picked as <provider>/<id> in
settings.json "model". Neither needs a GitHub sign-in. The multi-provider
file is marked experimental in the SDK types. The version BYOK started in is
not verified (github/gh-aw#25014 says 1.0.19; GitHub's changelog of
2026-04-07 announces it).

magpie writes the persistent file, not the environment: provider "magpie"
(openai chat completions, the gateway's /v1, the agent-named key) and one
models entry per catalog model, then model = magpie/<ref>. Only entries
naming magpie are magpie's; the user's providers, models and other keys stay
through connect, Sync and Disconnect (which also restores the model they were
on); a file that does not parse is never written over. COPILOT_HOME and
COPILOT_PROVIDERS_CONFIG are honoured (the latter added to agentenv.Vars).
Copilot's own models stay in the field's list.

Run at this head (a4fb75bfd's tree on 47b7ba303, mote): go test -timeout 45m
-count=1 ./internal/agent ./internal/agentenv ok; gofmt -l clean; GOOS=linux
and GOOS=windows go vet ./internal/agent ./internal/agentenv ok. Before the
rebase also ./internal/gui (only TestMainWindowCorners, red on origin/main
47b7ba303 too, #3949) and ./internal/library ok. TestModelReadersShareTheList
caught a first draft ranging over magpieModels; it uses sharedModels.
Real e2e: magpie's own Pick wrote the files into a sandbox COPILOT_HOME, the
real copilot 1.0.105 binary (no GitHub account) ran `-p "say hi"` against a
fake OpenAI server and sent POST /v1/chat/completions, model deepseek/pro,
Bearer magpie-copilot. The interactive TUI was also started earlier on a hand-written
providers.json and answered from it.
Broken by hand, each red: user providers dropped on write, Disconnect's
unwrite a no-op, an unparseable file treated as empty, Sync a no-op.

Not tried: a real magpie gateway behind it (the fake stood in), Copilot's
`anthropic`/`responses` wire types, Windows/WSL Copilot, an org with
forceLoginOrgs, tools/streaming against a real vendor model, the GUI suite
(no Agents-row layout change).
2026-11-04 05:13:45 +08:00