Commit Graph
1793 Commits
Author SHA1 Message Date
yetone 8a4e32febe tests: the overflow memory's compacted and answered cases stay one conversation (#3453)
TestOverflowRefusedOnceIsAskedLast's "compacted" request changed the
conversation's only user message. A ruled group keeps a conversation by
its first user message (firstWords in the stick key), so that request
was another conversation, and passed with behindOverflow's size check
taken out. Nothing asked that what a member answered is forgotten.

The conversation now has turns after its first user message, and the
compacted request keeps that message and drops the rest: the same key,
a smaller body. a answers it, and the conversation grown back to the
size a once refused begins with a again.

Run on mote, -tags nogui ./internal/gateway/:
- -run TestOverflowRefusedOnceIsAskedLast: ok.
- size check taken out (size >= r.bytes always true): FAIL at
  overflow_learn_test.go:71 "compacted: ... (a 0, b 1)".
- forgetOverflow call taken out: FAIL at :81 "after a answered: ...
  (a 0, b 1)".
- -race -count=20 of this test, TestOverflowMemoryReadWhileNoted and
  TestRelayInputCapGoesToTheNextMember: ok.
2026-11-01 16:43:21 +08:00
yetone 3af592f587 gateway: the overflow memory is read under its lock, so two requests of one conversation don't crash the gateway (#3453)
Review follow-up to ggbdpq's 075aaef62. behindOverflow took the
conversation's inner map under overflowLearned's lock, let go, and then
read it, while noteOverflow and forgetOverflow write that same map under
the lock. Two requests of one conversation at once (a turn beside its
title ask, a client's retry) read and wrote one Go map together, which
is a fatal "concurrent map read and map write", the whole gateway gone.
The loop now runs under the lock.

TestOverflowMemoryReadWhileNoted notes and forgets on one goroutine while
another orders members by the memory. Before this commit, on mote:
go test -tags nogui -race -count=1 -run TestOverflowMemoryReadWhileNoted
./internal/gateway/ -> "--- FAIL: TestOverflowMemoryReadWhileNoted ...
race detected during execution of test". With it, -race -count=20 of
that test, TestOverflowRefusedOnceIsAskedLast and
TestRelayInputCapGoesToTheNextMember: ok.

Also: behindOverflow's comment said resting members keep their order;
the code moves a refused member behind every other one, resting or not,
so the sentence is dropped. gateway-routing.md now describes the memory
beside withRoom's overflow paragraph.
2026-11-01 16:43:21 +08:00
ggbdpq e0a5091b7d gateway: a member that refused this conversation as too long is asked last, not first
What changed: an overflow (400, "prompt is too long") is the request's
length, not the account's, so it rests nobody — and left no trace: the
next request of the same conversation tried the member again, failed the
same way, and fell back again, for every request (#3453: a rule sent
every turn to a Claude subscription bridge that answered "Prompt is too
long" and DeepSeek answered; two consecutive requests of one turn each
paid the refused try first). Now the conversation remembers, per
provider's model, how large the request was when it was refused, and the
member is put behind the others — behind, not out: it is still asked
when every other member has failed, a rule that names it is still
heard (ruleOver has run), and what it answers makes magpie forget the
refusal. A request smaller than what was refused — the agent has
compacted the conversation — finds the member where the rule put it.
Another conversation is unaffected, and a byte cap (413) is not
remembered: it is not the conversation too long for the model.

TestRelayInputCapGoesToTheNextMember's second phase shares its server
with the first, whose overflow left this conversation's memory of a's
refusal behind; as that phase says how a plain bad request is classed,
its memory starts empty.

Run: go test -tags nogui -count=1 -run
'TestOverflowRefusedOnceIsAskedLast' ./internal/gateway/ (red on
c688211d1 with the test alone, green here); go test -tags nogui
-count=1 ./internal/gateway/; go vet -tags nogui ./internal/gateway/;
gofmt -l internal/gateway clean. Broken by hand: the product half of
the commit dropped (affinity.go, gateway.go hooks), the test red at
"second: (a 1, b 1)"; restored, green.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:20 +08:00
ggbdpq 9a4eaab82a gateway: a Chat body relayed to Gemini's OpenAI-compatible API goes without Ollama's options (#3097)
What changed: a client that takes the gateway for an Ollama server (its
/api/show is answered in Ollama's shape) sends Ollama's per-request
options beside its Chat fields. The google preset serves a model on
Gemini's OpenAI-compatible endpoint, so such a request is relayed as it
came, and that endpoint reads proto JSON: an unknown name turns the
whole request away with 400 "Invalid JSON payload received. Unknown
name \"options\": Cannot find field", every call, whatever the effort.
A body relayed to a Gemini OpenAI-compatible upstream (geminiCompat)
now goes without the top-level options, whose runner settings have no
place on a Chat API, as the Ollama route's own body builder already
leaves them out (ollamaChatBody). Another vendor's Chat upstream still
gets the body as the client sent it, and translated requests are
unchanged: they are built from the request's own fields, which never
carried options. geminiCompat is worked out once where the thought
signatures ask for it too.

Run: TestGeminiCompatRelayLeavesOutOllamaOptions fails on the old code
with "Ollama's options reached Gemini's OpenAI-compatible API" and
passes with the change; a request to another vendor's Chat upstream
still carries options there. go test ./internal/gateway/ ok (346.6s);
go test ./... -timeout 45m: 66 packages ok, internal/agent TestMothX
and internal/gui TestProxyCheckSaysAProxyPassedBy red, both red with
the change stashed on f5b01574 too (this machine's, not this change's);
gofmt -l clean; go vet ./... exits 0 (a cgo warning in internal/gui is
the baseline's); GOOS=linux GOARCH=amd64 go vet -tags nogui ./... and
GOOS=windows GOARCH=amd64 go vet ./... clean (GOOS=linux/darwin vet of
the gui fails in wails v3 beta on the baseline too); go build (darwin
arm64), GOOS=windows GOARCH=amd64 and GOOS=linux GOARCH=amd64
-tags nogui builds ok (a plain GOOS=linux/darwin build fails inside
wails v3 beta on the baseline too). Not tried against Google's real
endpoint: the reporter's 400 names the unknown field, and the fake
upstream checks what it is sent.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:20 +08:00
ggbdpq 026d4423d0 gateway: a Command Code stream that ends with no finish_reason is a cut (#2471)
What changed: a Chat stream of Command Code's whose reply ends with no
finish_reason anywhere - esp32gallery's day had 665 requests, 624 ended
with one, and the 20 that didn't were turns its slow starts lost to a
killed worker, each a ledger 200 with no stop and no error while the
client read "Stream ended without finish_reason" - was taken for a
turn that ended as it should, silence in the ledger and a bare
half-reply for the agent. Its API joins Gemini's OpenAI-compatible one
in saysItsEnd: every whole reply of its says its end, so a stream that
stops short of a finish_reason is said as the cut it is, in the stream,
the same way a relayed Gemini one is (#1644) - and one still held, with
nothing of the reply said yet, fails there for the group's next
candidate. Another vendor's Chat stream may still end whole with
neither a finish_reason nor [DONE]: nothing changes there.

Run: Four new tests, the first two red on cef8c1a4a before the change (the
cut passing as a whole reply, the next member never asked):
TestCommandCodeRelayEndedShort, a half-reply cut ends with "the reply
ended before it was complete", no finish_reason filled in;
TestCommandCodeTaillessFailsOver, a held lead-only stream fails 502 for
the next member; TestAnotherChatStreamWithoutAFinishReasonStaysAsItCame,
another vendor's tailless stream goes as it came; and
TestCommandCodeRelayWholeStaysWhole, a finished reply is never given a
second end.
TestGeminiCompatRelayEndedShort and TestGeminiCompatTranslatedEndedShort
green throughout. Not tried: a real Command Code upstream (the frames
are the reporter's ledger shapes, the host the one balance.go reads).

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:20 +08:00
ggbdpq eb7e72cc7f gateway: a response.completed with no output and no tokens fails over (#2471)
What changed: a Responses upstream that ends its 200 stream with a
response.completed carrying no output and counting no token - WorkBuddy
AI's account answered Codex's request with created, in_progress,
completed and `output: []` three times running (MurmuredVelpro) - had
the completed event taken for a reply's end: the held stream went to the
agent as a completed turn, the try stood as a 200 success, and the
group's healthy members were never asked. streamEvent now reads a
completed with an empty output and a zero usage as the no reply it is -
the same shape a translated reply that said nothing and counted nothing
has failed as since #2086 (repliesCounted) - and fails the held try for
the group's next candidate, in the candidate walk as an empty reply's
does: nobody rests, as the reply's shape failed, not the account. A
completed that counted a token stays a reply, as Claude's own empty
end_turn does; and an event this reaches is one nothing was said before,
since the hold lets the first content through and reads no event beside
it, so nothing of the try has reached the agent when it fires.

The fields said are what is read: a completed that names neither field
goes as it came, as the streamEvent table pinned it
(TestStreamEventRefusals, which caught the first draft reading an
omitted output as an empty one), and a completed that counted a token
stays a reply.

Run: TestEmptyCompletedFailsOver (new) red on 06c2c35d1 before the fix -
one try, status 200, Fail empty, the second member never asked, the
reported ledger shape byte for byte - green after, with
TestEmptyCompletedLeavesAWholeReplyAlone (new: a completed with output
and usage goes as it came) and TestFinishReasonErrorFailsOver green.
Not tried: a real WorkBuddy AI account (the stream is built from the
frames the reporter pasted).

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:16 +08:00
yetone c079b9ad7e claude: an interactive run's side question is branched before, not told whole (bbfatx on X)
Claude Code asks for a prompt suggestion as the conversation plus one
more user message (#1638). A claude -p run takes that aside and goes on;
on the next real turn the bridge rewinds it to the line before the aside
(behindKey/behindTurn and --resume-session-at). An interactive run
ignores --resume-session-at, so the bridge aborted it and told the next
turn whole to a new run: every turn after a suggestion wrote the whole
conversation into the cache again. That is bbfatx's second suggestion
(save a checkpoint at a history prefix and fork from the deepest one) in
the one place where it rewrites the cache today.

Now the run remembers the last session line it wrote before each turn
(lastLine, backLine, behindLine). When the next real turn finds an
interactive run behind an aside, the bridge cuts a copy of the run's
session at that line before the abort removes the file (branchAt, the
cut copy from the previous commit), and the new run resumes the copy in
interactive mode and is told only the new message.

Run (mote, at this tree):
- go test -tags nogui -count=1 -timeout 30m -run
  "Claude|Bridge|ToolChoice|Subscription|Retire|Rewrit|Fork|Branch|Shelf|Shelve"
  ./internal/gateway: ok (70.7s)
- go test -tags nogui -count=1 ./internal/claudetui: ok
- gofmt -l internal/: clean

Broken by hand (TestClaudeInteractiveSideQuestionBranchesBeforeIt):
- the old code (HEAD 37ff7356f): red, the turn after the suggestion is
  "had 0 turn 1" (told whole to a fresh run).
- backLine left "": red, "had 0".
- cut at the run's last line (after the suggestion) instead of the line
  before it: red, "had 6".

Not tried: a real interactive Claude Code prompt suggestion end to end;
the test uses the fake claude with the helper stand-in. The cut copy
itself was measured with real Claude Code 2.1.316 in the previous commit.

Not taken from the suggestion: a general store of checkpoints by history
prefix. The bridge already keeps one run per conversation and resumes it
at the line it is behind; the only case that lost the prefix was the
interactive aside, so only that case gets a cut. Prompt and system text
sent upstream are unchanged.
2026-11-01 16:33:07 +08:00
yetone 8215164296 claude: a branch is a cut copy of its run's session, in its run's mode (bbfatx on X)
A sub-agent's first request that answers calls another request already
answered branches off the lead's run's session (branch). That branch was
`claude -p --resume S --fork-session --resume-session-at U`, and
claudePrint forced every branch to -p, because Claude Code's interactive
mode ignores --resume-session-at (Claude Code 2.1.316 on mote: it resumes
the whole session). Runs are the interactive mode by default now, so the
lead's cache has the interactive prompt, and a -p branch of it read only
tools and system from the cache and wrote the conversation again
(measured on mote, sandbox HOME, 30 MCP tools: an interactive fork of a
-p session read only tools and system; the other way round was not
measured). With "Interactive only" no branch was made at all,
and the fork was told the whole conversation.

Now the branch's run copies the session's lines up to U into a new
session file next to it, with sessionId set to the copy's id
(cutSession), and resumes it with --resume <copy> in the mode its source
run had (savedSession.tui). claudePrint keeps "branch" only for a branch
of a -p run. Under "Interactive only" a -p run's session isn't branched.
The run owns the copy, as it owns an unshelved session. The copy waits up
to 2s for U's line to be fully written; if it never is, the turn is told
whole, as before. claudetui's translator now passes each assistant row's
uuid through, as -p does, so an interactive run's lines can be cut.
Measured on mote with real Claude Code 2.1.316: a cut copy resumed
interactively read 7648 and wrote 14; with -p it read 24009 and wrote 13.

Run (mote-run, this tree):
- go test -tags nogui -count=1 -timeout 30m -run 'Claude|Bridge|ToolChoice|Subscription|Retire|Rewrit|Fork|Branch|Shelf|Shelve' ./internal/gateway: ok 63s
- go test -tags nogui -count=1 ./internal/claudetui: ok
- go vet -tags nogui ./internal/gateway ./internal/claudetui; gofmt -l: clean

Broken by hand (each red, then put back):
- old claude_subscription.go and transcript.go (cutSession stubbed):
  TestClaudeForkBranchesOffTheLeadsSession interactive (branch ran -p),
  interactive only (told it whole), print (old flags),
  TestClaudeCutSessionCopiesAsFarAsTheLine and
  TestTranslatorTellsTheRowsUUID red
- claudePrint's branch reason for every branch again: interactive and
  interactive only red
- the copy taking the whole file: all three subtests and the cut test red
- branch() refusing every run under Interactive only: interactive only red

Not tried: a real fork sub-agent through the gateway. The cache numbers
come from copying by hand with real Claude Code; the tests use a
stand-in. Windows and WSL keep no session on disk, so they never
branch, as before.

Not taken from the suggestion: the fork's own runtime and TypeScript
wrapper. The cut is done here at the one place a branch starts.
2026-11-01 16:33:07 +08:00
yetone 85ab325d48 claude: a title asked between turns leaves the conversation's run waiting (bbfatx on X)
bbfatx on X: the Claude subscription bridge spends more of the quota
than it should. While checking which of the suggestions cause real cache
writes, this one turned up. A client asks a title or a summary between a
conversation's turns, the conversation so far and a question more, with
tool_choice none or with no tools. Such an aside cost the conversation
its run, in one of two ways:
- tool_choice none: the aside went to a run of its own, and retire,
  which lets go of the runs a new run carries the conversation on from,
  let go of the run the conversation waited in.
- no tools: looseTurn's key has no tools, so the aside was taken as the
  conversation rewritten (#912), and the conversation's run went on
  with it, to wait at the aside afterwards.
Either way the conversation's next turn found no run. A new Claude Code
was told the whole conversation in one message, and all of it was
written to the cache again.

Now an aside of a run that was told tools neither retires it (retire
takes the request; asideOf) nor takes it as rewritten. The aside is
answered by a run of its own, as before, and the next turn goes on in
the conversation's run. A client with no tools at all is unchanged:
asideOf holds only for a run that was told tools.

Run (mote, go1.26.8):
- go test -tags nogui ./internal/gateway -run TestClaudeAsideLeavesTheConversationsRun -count=1: ok.
- go test -tags nogui ./internal/gateway -run 'Claude|Bridge|ToolChoice|Subscription|Retire|Rewrit' -count=1: ok (75s).

Broken by hand:
- HEAD's claude_subscription.go: red. With none, the next turn went to
  a new run told it whole. With no tools, the title went on in the
  conversation's run.
- The rewritten check only: red (no tools).
- The retire check only: red (both).

Not tried: a real client's title request on a real account. The aside
still costs one new Claude Code told the conversation whole. The next
commit branches it from the run's session instead.
2026-11-01 16:33:06 +08:00
yetone e02df9e226 claude: a tool_choice none turn is offered the client's tools, and may call none (bbfatx on X)
bbfatx on X: the Claude subscription bridge spends more of the quota
than it should. Suggestion 1 was to keep a turn's tool definitions apart
from whether it may call them. bridgeTools dropped every tool for
tool_choice none. Anthropic caches a prompt as tools, then system, then
messages, so such a turn (a title or summary asked with the tools as
ever) was a prefix the cache had never seen. All of it was written
again, Claude Code's own tools and system prompt included.

Now a none turn's MCP helper offers every tool the client sent. A call
the turn makes anyway is answered at once with an error result
(mcpCall), and toolStart treats it as Claude Code's own call, as it does
magpie's web search. The client never sees it, and the reply goes on in
words. A named tool_choice still offers only that tool. The allowed set
(subscriptionRun.allowed) is set for each turn: at start, on resume, and
with tool results (a client may choose none once it has its results).
The system prompt and the turn's text are unchanged.

Measured with the real Claude Code 2.1.316 on mote, in a sandbox HOME
and CLAUDE_CONFIG_DIR, against a stand-in Anthropic that counts cache
reads and writes the way Anthropic's cache does (30 MCP tools):
- the same turn with no tools: 0 read, 7595 written;
- told whole in a new session with its tools: 15780 read (tools and
  system), only the history written.

Run (mote, go1.26.8):
- go test -tags nogui ./internal/gateway -run TestClaudeToolChoiceNoneKeepsTheTools: ok.
- go test -tags nogui ./internal/gateway -run 'Claude|Bridge|ToolChoice|Subscription' -count=1: ok (54s).

Broken by hand:
- HEAD's claude_subscription.go: red, the helper was offered [], the
  call was not refused, and the client was shown a tool_use.
- Only the refusal turned off (mcpCall and toolStart): red, the call
  was shown to the client.

Not tried: a real client's tool_choice none request through the gateway
to a real account. The measurement drove Claude Code directly.

Not taken from the suggestion: nothing of the fork's code is ported. The
fork drops a none turn's tool calls in its own runtime. Here the call is
refused where magpie already answers its web search. The only new text
upstream is that refusal, a short tool error result naming neither
magpie nor a vendor, and only when the model calls a tool anyway.
2026-11-01 16:33:06 +08:00
yetone 1adff37796 claude: a refusal Claude Code falls back from goes on to the fallback model's answer (Chixi_Fang on X)
Claude Code 2.1.316 doesn't end a turn at a refusal. It asks the same
model again, then its fallback model (claude-opus-4-8 for Opus 5.5),
whose answer ends the turn with result success. The bridge ended the
reply at the first stop_reason refusal, so the client got "Partial "
plus a refusal, and the gateway's hw.refused moved to another account
or handed the refusal back. That is the "model error" the reporter saw.

readOutput now holds a refusal from Claude Code's own model and goes on
with the next message as one reply. Not held: a client tool call, or a
schema reply. The refusal's stop_details are held too. The refusal is
told only if it stands: at a result with no API status (Claude Code's
model_refusal_no_fallback, -p or TUI) or at the end of output. Then
hw.refused and b01766d13 see it as before. A result with a status after
a refusal is that error, not a refusal. The continuing message's model
goes on the KUsage as Model and Served. The try records the fallback
model, and a reply told whole names it. A stream's message_start can't
change it. Prompts and system text sent upstream are unchanged.

Real behaviour: Claude Code 2.1.316 on mote, in a sandbox HOME and
CLAUDE_CONFIG_DIR, against a fake Anthropic upstream that refuses
claude-opus-5-5 (or every model). The -p and TUI stream-json lines were
captured and trimmed into the fixtures in
claude_refusal_fallback_test.go.

Run (mote-run, worktree at base 4a4a82cd4):
- gofmt -l internal/gateway: no output.
- go vet -tags nogui ./internal/gateway on darwin, GOOS=linux and
  GOOS=windows: clean.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
  (813s).
- The new tests plus TestClaudeSubscriptionRefusal*,
  TestClaudeSubscriptionBigRefusal*, TestClaudeCutStream* and
  TestClaudeRefusalMovesToNextKey: ok.

Broken by hand:
- On the unmodified claude_subscription.go (stashed), FallbackAnswers
  (print, tui) are red with reply "Partial " stop "refusal", and
  RetryFails is red. NoFallback passes, so that behaviour is unchanged.
- Dropping the Served on the continuing usage turns the served
  assertions red.
- Dropping the collector's KUsage Model turns the non-stream try's
  Served red (claude-opus-5-5).
- Making the standing-refusal case `case standing:` (no status check)
  turns RetryFails red.

Not tried:
- A real Claude account (none on mote). The fallback was a fake
  upstream's refusal.
- The full go test ./... suite.
- Words a retracted try streamed before its refusal stay in a stream.
  Claude Code shows them too.
- A refusal after the client's own tool call keeps the old behaviour
  (the reply ends there).
- The overload/529 fallback needs --fallback-model, which the bridge
  doesn't pass (nor does Claude Code by default). That path is
  unchanged.
2026-11-01 16:19:01 +08:00
yetone 726544eed7 browser: with two browsers connected, an agent lists them and picks one
With Magpie Browser in two browsers (Chrome and Edge, or two profiles),
every call went to the last to connect and nothing said there was another
(packinggoodsllc_07668 on Discord: which one is controlled?).

- Each connection gets an id (b1, b2, in connect order) and a name from its
  User-Agent (Edge, Opera, Vivaldi, Yandex say so; Brave, Arc and other
  Chromium browsers read as Chrome).
- browser_tabs action browsers lists them, * on the one calls go to; action
  use with browser (an id, or a name only one has) moves this session's
  calls there. Other sessions stay where they were; a browser that
  disconnects drops every session's pick of it.
- With two or more connected, browser_tabs list says whose tabs it lists.
  The default is still the last to connect.

Run (mote-run): go test ./internal/gateway -run Browser ok (new
TestBrowserMCPPicksAmongBrowsers, TestBrowserName); go vet, GOOS=linux and
windows go vet ./internal/gateway ok.
Broken by hand: forSession ignoring the pick, the new test red ("s1 after
picking chrome: ... b2's tabs (Edge 141)").
Not tried: two real browsers at once; the GUI still shows only the last
connected browser.
2026-11-01 16:10:16 +08:00
yetone 3cb8b17312 browser: two agents at once each work in a tab and tab group of their own
Magpie Browser kept a tab per session, but a session with no tab took the
tab the user was looking at, so two agents started together worked in one
tab, and every agent's tabs went in one "Magpie" group
(packinggoodsllc_07668 on Discord).

- A session whose first call finds the shown tab held by another session
  gets a new background tab of its own.
- Each session's tabs go in a group of its own: "Magpie", then "Magpie 2",
  "Magpie 3" beside other live sessions (session → group kept in
  storage.session with the tabs).
- browser_tabs list marks another session's tab ~ and names each tab's group.
- A link that opens a tab moves the session that clicked it (t.by), not the
  first session found holding the old tab.
- Instructions and the popup's hint say so; extension 0.1.1.

Run (mote-run, MAGPIE_BROWSER_CHROME = Playwright's Chrome for Testing
1234): TestBrowserToolsInARealBrowser and the new
TestBrowserSessionsApartInARealBrowser (two sessions, real tabs and groups)
ok; go test ./internal/browserext; ./internal/gateway -run
'Browser|MCP|Hub'; GOOS=linux and windows go vet of gateway, library,
browsermcp, browserext ok.
Broken by hand: the new test against the old background.js is red ("both
sessions work in t803211511").
Not tried: real Chrome/Edge with a user profile, a person watching the
groups; t.by with two sessions (the click test has one).
2026-11-01 16:10:16 +08:00
yetone de74cb53f7 mcp router: each caller gets its own Magpie Browser session
The router keeps one backend per Library server for every agent, so all
agents behind it shared one `magpie mcp browser`, one browser session and
so one tab (packinggoodsllc_07668 on Discord: two agents through a remote
router fought over one tab).

- serveMCP gives a client that initializes an Mcp-Session-Id (nothing is
  kept or checked by it).
- hubSession names each tools/call's caller: _meta magpie/session from a
  router in front, else hub-<agent>-<Mcp-Session-Id>.
- The router passes it in _meta magpie/session to `magpie mcp browser` and
  to another magpie's router only (keepsSession); the bridge sends it as
  that call's X-Magpie-Browser-Session (callerSession). A call naming none
  goes as the bridge's own session, as before.

Run (mote-run): go test ./internal/browsermcp; ./internal/gateway -run
'MCP|Hub'; ./internal/library -run 'TestHubTellsMagpieBrowser|TestKeepsSession|TestHubGivesMagpieImage'. ok.
Broken by hand, each red: no meta from the library (library test), no
Mcp-Session-Id from serveMCP and ignoring _meta in hubSession (gateway test).
Not tried: a real remote router chain between two machines.
2026-11-01 16:10:16 +08:00
yetone 4a4a82cd49 gateway: TestSearchAPIAsksAreLogged's query has no number a port can hold
The Linux box's full suite failed it: "the query's \"7781\" is in
usage.jsonl", where the only 7781 was the fake server's random port,
host 127.0.0.1:37817. Every row logs the host, so any query word made of
digits can match a port now and then. The query is letters only now; the
check that no query word reaches usage.jsonl is unchanged.

Run on mote at this tree (origin/main 1e6a27d4f + this):
go test -count=20 -run 'TestSearchAPIAsksAreLogged$' ./internal/gateway ok.
gofmt -l clean. Not run: the whole gateway package (one-line test
literal change).
2026-11-01 15:29:42 +08:00
yetone 403323af7f claude: a switch waits for another magpie's runs in the account's directory (#4532)
StringKe's audit, item 2. claudeDirRun is an in-process RWMutex, so
`magpie accounts switch` from the CLI never waited for the app's /usage,
warm-up or keep-alive run in the saved account's directory: it handed
Claude Code the refresh token that run could still spend, and removed
the directory under it. And the gateway's hand-over let go only of idle
runs; a run in a turn when the switch came was kept for its next turn,
waiting up to idleLongest in the removed directory with the same token.

- inSavedClaudeDir also holds a lock file of its own beside the
  account's directory (markClaudeRun, <dir>.run-<pid>-<n>.lock,
  filelock), removed as it ends.
- switchSavedLogin waits on every such file (waitClaudeRuns) up to
  claudeRunWait (90s), then fails with errClaudeRunning and leaves the
  sign-in as it was. A file whose run ended without removing it is free
  and taken out.
- handedOver marks the account's runs in a turn (subscriptionRun.handed);
  keepIdle ends such a run instead of keeping it.

Shelved (parked) sessions hold no process or token; a later turn starts
a new run under the account the gateway picks then, so nothing changes
there.

Run (mote, nogui):
- new tests TestClaudeSwitchWaitsForAnotherMagpiesRun,
  TestClaudeSwitchRunHeldAndLeft, TestSavedClaudeRunHoldsItsLock,
  TestClaudeHandOverEndsTheAccountsBusyRuns, plus TestClaudeSwitch*,
  TestSavedClaude*, TestClaudeHandOver*: ok.
- Broken by hand (wait call, run mark and the handed check taken out,
  helpers kept): all four new tests red ("switched while another magpie
  ran Claude Code…", "got <nil>", "a left lock file kept", "run locks []",
  "a run of the handed-over account was kept for its next turn").
- go vet darwin/linux/windows for provider and gateway: ok.
- Windows (win-run): the three provider tests and
  TestSavedClaudeUsageKeepsRotatedSignIn: ok.

Not tried: two real magpie processes with a real Claude Code (the other
process is a second open of the lock file, which flock and LockFileEx
treat as another holder; filelock's own test covers a real second
process). Not covered, filed as #4750: a run queued behind the switch
makes the handed-over account's directory again, and a run in a turn
can still refresh during that turn.
2026-11-01 15:25:56 +08:00
yetone 01ccbd40a0 library: an MCP router says which computer it is, so an agent can pick between two (packinggoodsllc_07668 on Discord)
Two magpies, one in China and one in Los Angeles, each serve the same
tools through their MCP router (/mcp/magpie/hub). An agent connected to
both saw two identical web fetches and couldn't pick the one in Los
Angeles to reach Google.

Each router now says where it is:
- initialize's instructions end "This router: <name>. Each of its
  tools' descriptions starts with [<name>]; ...", and serverInfo.title
  is "Magpie MCP hub · <name>";
- each tool's description in tools/list starts "[<name>] " (once: a
  description that starts so already, another magpie's router behind
  this one, isn't given it twice).
<name> is the user's words (settings.RouterNote, one line, 80
characters at most) to every caller. With none it is this computer's
name, to callers on other computers only: an agent on this computer
has one router at hand, and its prompts stay as they were.

RouterNote is this computer's own (KeepOwn): library.json is synced,
settings.json isn't, so a sync never brings the other machine's name.
It is set in the Library's MCP tab, in a Router name row under the
router's address (shown while the router is on): a plain field with the
computer's name as placeholder, saved on Enter or leaving it, Escape
puts the saved words back, an input method's Enter is its own. POST
/api/settings keeps it. Translated in zh, zh-TW, ja, de.
docs/subsystems/mcp-router.md has the rule.

Run (mote, at a5a9cdf7b + this change): go vet ./... for darwin, linux
and windows ok; go test -tags nogui ./... -timeout 45m: every package
ok except internal/gui's TestSettingsSaveKeepsWhatItDoesNotSend on
BusyLoad, red on main since 8d8df0639 (#4739, fixed in the next
commit). After rebasing on 9feb1024c: internal/gui, settings, library
and gateway again, and node --test library-mcp-router-note (new),
library-mcp-hub, mcp-hub-direct and i18n-keys, chromium and webkit,
en/zh/zh-TW/ja/de, at 1100 and 420 wide.

Broken by hand: hubWhere returning "" turns TestHubMCPSaysWhere red;
dropping RouterNote from KeepOwn turns TestRouterNote red; dropping it
from POST /api/settings' carry list turns TestHubNoteSaved and
TestSettingsSaveKeepsWhatItDoesNotSend red. i18n-keys caught a test
comment saying "Router name", reworded.

Not tried: two real magpies on two computers with a real Claude Code
or Codex connected to both, and whether a model actually picks by the
prefix; the Linux and Windows apps' Library tab.
2026-11-01 15:23:15 +08:00
yetone 39bade71d1 gateway: a plain <invoke> written into a reply's text is the call it is, on a relayed Messages reply too
packinggoodsllc_07668 on Discord (#general): Claude Code v2.1.316, magpie's
routing group "Hard to strong, easy to cheap", asked to open Google in
magpie's browser. The reply showed
  <invoke name="ToolSearch"><parameter name="query">select:…</parameter></invoke>
  *Result: Tool loaded.*
  <invoke name="mcp__magpie__magpie-browser__browser_navigate">…</invoke>
  *Result: Navigated to https://www.google.com — page title: "Google"*
  已用 magpie 的浏览器打开了谷歌 ...
as text. Nothing ran: the model wrote its calls and made up their results.
Asked, the reporter said the group holds only Claude models (v0.1.2545).

Cause: Claude wrote its own call form as text, and none of magpie's
readers of written calls knew that form on the routes Claude takes.
- The plain <invoke name=…><parameter name=…> shape (Claude's own calls,
  MiniMax's in <minimax:tool_call>, Claude's in <function_calls>) wasn't
  a mark: only <tool_call> and DeepSeek's DSML invoke were.
- A reply relayed as it came on the Messages API (a group member on a
  provider that speaks Messages itself: MiniMax, Kimi, GLM, DeepSeek, Claude
  relays) was never read for written calls at all; the subsystem doc said
  so. Claude Code's request to such a member takes that route.
- A Claude subscription member runs Claude Code itself (the bridge), whose
  textCalls held back only "[tool call …]" lines.
Not the cause: history isn't flattened (tool_use/tool_result translate to
native calls on every API), and this was the conversation's first turn.

Fix:
- textcalls.go: the invoke regexes take DSML's pipes, a namespace, or
  nothing; <invoke name=, <function_calls> and <minimax:tool_call> are
  marks; their leftover tags go. Text after a call read out, other than
  tags, ends the calls and goes with all after it: it is the model going
  on as if the call had run. This changes the old rule for every shape:
  prose after a Hermes call ("Done.") went on as text and now goes
  (TestTextWrittenCallCutEarlyNotCalled updated).
- textcalls_anthropic.go: anthropicTextCalls in passthrough, for a
  streamed Messages reply (holds the text block's start and stop with the
  held text, adds tool_use blocks after it or in its place, stop_reason
  tool_use) and a whole one.
- claude_text_calls.go: the bridge's textCalls also holds a line opening
  <invoke name= or <function_calls>, so the run is asked once to make the
  calls (textCallsAsk no longer names the "[tool call …]" form only).
- Responses and Gemini relays still aren't read: #4743.

Tests (textcalls_invoke_test.go), on the reporter's literal text: parse,
a relayed Chat stream, a Messages passthrough through a routing group
(streamed, with lead text, a lookalike left alone, and whole), and a
Chat upstream translated for a Messages client.
TestClaudeTextInvokeCallsAreMadeForReal: the bridge, bare and wrapped.

Run:
- On origin/main 586b59fe7 with only the new test file: all four
  TestInvokeReported* red. With the parser change but not the passthrough
  wiring: TestInvokeReportedAnthropicPassthrough red.
- mote-run at a6c37f936 (on origin/main 9feb1024c): gofmt -l clean, go vet ./internal/gateway for darwin, linux, windows ok, go test ./internal/gateway -timeout 45m -count=1 ok 716.8s.
- Rebased onto origin/main 5d63b3f99 (5 commits, two in internal/gateway: Codex
  loaded tools, HEIC images; no file of this change): gofmt clean, vet ok,
  and -run TestInvokeReported|TestTextWritten|TestTextCall|TestClaudeText|
  TestWritten|Passthrough ok. The full gateway suite was not rerun there.
Not tried: a real Claude Code against a real group member that writes
invokes (which provider serves the reporter's Claude models is unknown), and Responses/Gemini relays.
2026-11-01 15:08:24 +08:00
yetone d614f21721 gateway: a HEIC photo goes to the vendor as JPEG, or PNG with alpha (qikamatata on X)
Pi and Pi Desktop send an iPhone photo dragged in as image/heic, and
DeepSeek flash on WorkBuddy (a plugin's fetch) turned it away; most
vendors take JPEG, PNG, GIF and WebP only.

What: heicAsJPEG (heic.go) runs at the top of Server.serve, after
offAsNone, so every route below sees the converted image: a provider's
own, a plugin's fetch, the describer, every translation. count_tokens
does the same. It walks images through walkImages, the one image walker,
so it covers Chat image_url (string or object), Responses input_image,
Anthropic image blocks and Gemini inlineData, tool results included. It
goes by the bytes (ftyp + an HEVC still's brand), so a HEIC labelled
image/jpeg or image/png is converted too, and a JPEG labelled heic is
left alone. Other fields of the block (detail, cache_control) are kept.
Transparent images go as PNG, opaque ones as JPEG q90.

Cost: a body with no "image/hei" and no base64 ftyp mark ("eXB" + 5
chars, at the same place in any base64 that starts at the file) is not
walked. Caps: 48 MB of base64, 50 MP, the long side written at 4096 px,
one decode at a time, 30 s wait (a late result is cached for the next
turn), a 64 MB / 32 entry cache by sha256, since agents resend a
conversation's images every turn. Any failure, panic included, leaves
the image as it came. Measured on mote (M5 Pro): 12 MP 0.44 s, 24 MP
0.86 s, 48 MP 1.6 s / ~1 GB held, freed at once with FreeOSMemory.

Why gen2brain/h265 v0.2.4: pure Go (release builds are CGO_ENABLED=0),
MIT, no dependencies, SIMD on amd64 and arm64, maintained (latest
2026-10-29). Not chosen: gen2brain/heic (wazero WASM or a libheif dylib
through purego), jdeng/goheif (cgo libde265), OS converters (Windows
needs the paid HEVC extension, Linux tools are often missing).

Tests (heic_test.go, fixtures made on mote with sips, 1.6 KB each):
12 shapes converted with their kept fields, pixels kept, 7 non-HEIC
cases byte-identical, a cut file / a panicking decoder / a timeout go
as they came, and a plugin's fetch (fake plugin, new FAKE_SEES image
model) gets JPEG on /v1/chat/completions and /v1/messages.

Run at this tree (733fac48f + this change), on mote:
- gofmt -l internal: clean
- GOOS=darwin/linux/windows go vet -tags nogui ./internal/gateway
  ./internal/plugin: ok
- CGO_ENABLED=0 go build ./internal/gateway for darwin, linux, windows
  x amd64, arm64: ok
- go test ./internal/gateway ./internal/plugin -count=1 -timeout 45m:
  ok (774s, 134s)
- win-run (Windows amd64) and wsl-run (Linux amd64, AVX2 path):
  go test ./internal/gateway -run HEIC: ok

Broken by hand, each red, then restored:
- no heicAsJPEG call in serve: TestHEICReachesPluginAsJPEG red
- media_type not set for Anthropic: the messages subtests red
- no base64 mark scan: the "labelled jpeg/png" subtests red

Not tried: a real Pi -> WorkBuddy request with a real account; a real
iPhone gridded HEIC (only sips files and Apple's 26 MB wallpaper); a HEIC
behind an http URL (not fetched, goes as it came); Anthropic document
blocks, Responses input_file and images/edits.
2026-11-01 15:04:28 +08:00
yetone c688211d13 gateway: a ChatGPT (Codex) account gets loaded tools where they were loaded, keeping its cache (#4738)
infinitex233 (#4738, Discord): Claude Code -> magpie -> a Codex account,
and every ToolSearch load dropped cache_read to 0. loadsInPlace sent the
additional_tools item (#2660) only to OpenAI's own API, so for an
account the loaded tool went into the top-level tools and the cached
prefix broke at the tools.

Tried on the real ChatGPT backend first (owner's account, sandbox HOME
on mote with a copied auth.json whose refresh_token was replaced, so the
live token was never rotated; ~/.codex untouched). A probe client sent
Claude Code's shape: ToolSearch with two deferred mcp tools, then the
tool_reference result, then the calls, 4 requests per run.
- additional_tools item (on, and this commit's default): request 2..4
  read 7680-8320 tokens from cache on gpt-5.6-terra, gpt-6-luna and
  gpt-6-sol; the model called read_a and read_b from the item; no
  "turned away additional_tools" in the log.
- tools top-level (off): request 2 and 3 read 0 from cache (8044 and
  8163 tokens in), as the reporter saw.
So the backend takes it, and this makes it the default for a ChatGPT
account (p.Account.Agent == "codex"). Copilot and other sign-ins stay
off: not tried.

- loadsInPlace: AdditionalToolsOff wins, then AdditionalTools, then an
  account is in only if it's Codex's, then OpenAI's API as before.
- `magpie provider set <id> additional-tools=on|off|default`: off is new
  (AdditionalToolsOff, kept through an account's Save by accountSettings
  and through the GUI editor's save like AdditionalTools). The old
  "off"/"no" meant default; now they turn it off where the default is on.
- The 400/422 fallback that names the item still applies, so a backend
  that stops taking it costs one retry and then sends tools top-level.
- No prompt, instructions or identity line changed.

Run (mote, at base 586b59fe7, this commit and the previous together):
- go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/cli ./internal/gui: provider ok 248s, gateway ok 830s,
  cli ok 105s; gui FAIL on two filed reds that this doesn't touch:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, #4739) and
  TestMainWindowCorners/macOS_26_SDK on macOS 27 (#3949).
- Rebased on origin/main 9feb1024c, then again at this head: gofmt
  clean, vet darwin/linux/windows ok, provider ok 179s, cli ok 88s,
  gateway -run 'LoadsInPlace|LoadedTools|Codex|AdditionalTools|InPlace|
  Account' ok 99s, gui -run 'Provider|Settings|Account' red only on
  #4739. The whole gateway and gui packages ran at the base only.
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows ok.
- New TestCodexAccountLoadsInPlace (a fake ChatGPT backend through the
  gateway: the item with read_a, then tools top-level after
  additionalToolsOff in providers.json); TestLoadsInPlaceScope extended
  (Codex on, Codex off, OpenAI off, Copilot off by default and on when
  set); CLI test for off, on after off, default.
- Broken by hand: with the Codex default taken out of loadsInPlace,
  TestCodexAccountLoadsInPlace and TestLoadsInPlaceScope go red.
- GUI node suite not run: no JS changed; the Go editor save only keeps
  one more field, covered by the Go tests above.

Not tried: the reporter's own setup (Windows, gpt-6.1-terra), a real
Claude Code client (the probe sent its request shape), Copilot or any
other signed-in vendor with the item.
2026-11-01 14:59:44 +08:00
yetone 9feb1024c7 zen: free models are asked as OpenCode 2.2.5 asks them (#3491)
laomao04_65777 on Discord: Zen's free models answered 429 "Free usage limit
reached. Free models work in OpenCode" to the built-in OpenCode Zen provider,
while real OpenCode 2 on the same machine was served. magpie sent OpenCode
1.x's shape. It now sends what OpenCode 2.2.5 sent in a captured request
(internal/provider/testdata/opencode-2.2.5-chat.json, from a recording proxy),
as the zen-free plugin does since plugins d62193c and 8501988:

- User-Agent opencode/latest/<v>/cli. <v> is the version OpenCode's updater
  (opencode.ai/update/api/latest/cli/npm) names, never below 2.2.5 and never
  anything but a plain x.y.z. It is read in the background at most every 6h,
  with a 3s timeout and no redirects.
- x-opencode-project is OpenCode's project id for the folder the agent says it
  works in: sha1 of git-remote:host/path (origin, else the first remote;
  worktree .git files followed), else of directory:<root or folder>. It is no
  longer "global".
- b3 and traceparent: one trace a conversation, a new span a request.
- The session id goes in x-opencode-session, x-opencode-session-id,
  x-session-affinity and x-session-id. Accept is */*, and x-opencode-request
  is gone.
- On a free request the agent's own headers (Claude Code's x-stainless-*,
  Codex's originator) are dropped. Only Content-Type and Anthropic-Version
  and Anthropic-Beta are kept.
- The core tools are edit, glob, grep, read and shell with 2.2.5's schemas,
  strict false on Chat. Claude Code's Read, Edit, Glob and Grep are offered
  under those names. Its Bash is no longer bash: shell is a stub.
- OpenCode's <env> block, word for word, for the agent's folder, is added to
  the system prompt unless it has one already (OpenCode's own).
- Paths are the v2 catalog's: /inference/openai/v1 for Chat and Responses,
  and /inference/anthropic/v1 for Messages. The models list is unchanged.

Every route takes this: chat, responses and messages through forwardOnce, the
Test button's probe (tiny/zenFreeProbe), and the models list
(listHeadersAt: UA and x-opencode-client).

Sibling: paid Zen and OpenCode Go share OpenCodeClient, so they get 2.2.5's
headers. Their /zen/v1 and /zen/go/v1 paths are left as they are: #4740.

Run on mote (mote-run) at this tree:
- gofmt -l . is clean.
- GOOS=darwin and windows go vet ./... pass. GOOS=linux go vet passes for
  internal/provider and internal/gateway. The whole-tree Linux vet stops in
  Wails' cgo when run from macOS, and in WSL for want of gtk4, before it
  reaches this change.
- go test ./internal/provider ./internal/gateway -count=1 -timeout 45m:
  ok provider (154s) and ok gateway (715s) on base 788057340. After the
  rebase onto a5a9cdf7b, which touched gateway.go and ir.go, the same
  tree passed again: ok provider (138s) and ok gateway (816s), with GOOS
  darwin, linux and windows go vet of both packages.
- Rebased again onto 4c815ac2a, which touched search.go and provider.go.
  At that head gofmt and the three-OS vet of both packages are clean, and
  -run 'OpenCode|Zen|Search|Searcher' passes in both packages. The full
  suites were not rerun after this last rebase.

Broken by hand, each turning a test red (provider and gateway, -run
'OpenCode|Zen', on mote):
- version 1.19.0: TestOpenCodeClientIs225 and TestOpenCodeVersionFromUpdater.
- the old /inference/v1 path: TestOpenCodeFreeURL, TestZenFreeAsOpenCode225,
  TestZenFreeAtInferenceURL and TestZenPublicTestAsksFreeModels.
- caller headers kept: TestZenFreeAsOpenCode225.
- no env block: TestZenFreeAsOpenCode225.
- no strict: TestZenFreeAtInferenceURL.
- project "global": TestOpenCodeClientIs225, TestOpenCodeClientHeaders and
  TestZenFreeAsOpenCode225.
- the same span on every request: TestOpenCodeClientIs225 and
  TestOpenCodeClientHeaders.
- no 2.2.5 floor: TestOpenCodeVersionFromUpdater.
- a changed read schema: TestOpenCodeToolsAre225s.

Not tried:
- A real 200 from a free model: this egress IP's free allowance is spent.
  The captured 2.2.5 request itself got 429.
- Header order and case: Go's HTTP/1 writes headers sorted, and HTTP/2
  lowercases them, so OpenCode's order cannot be copied.
- Windows' project id against real OpenCode on Windows.
2026-11-01 14:48:19 +08:00
yetone 4c815ac2a5 search: searchers picked to follow the one named, tried in their order when it fails (axelburks on Discord)
axelburks asked for more than one searcher, so that when one fails
another provider searches. A searcher named in Settings gave way to no
other provider before, only to the Search APIs. Automatic already fell
back to up to three.

- settings: SearcherThen, the searchers after the one named. Entries
  are trimmed. Blanks, "off", the named one and repeats are dropped.
- gateway: when the named searcher fails (the context still live),
  modelSearch asks each of SearcherThen in order and skips one that
  can't search now or is the same model. The first that searches
  answers, and the call is marked searchingInstead, so the Routing row
  says why the named one didn't search. If all of them fail, their
  errors go back together, saying "the searchers picked ..., in their
  order", and webSearch goes on to the Search APIs as before.
  SearchFailure.Instead names the one that searched in its place.
- gui api: searchFailed.instead. A save takes only searchers that
  Searchers() offers. A save without searcherThen keeps the list, since
  the page's prefsKeep doesn't send it, and [] clears it.
- Settings › Web search (plugins/search/settings.js, outside app.js's
  budget): an "If it fails" row under a named searcher, with numbered
  chips and Add. A chip's picker changes the chip or removes it. The
  row is hidden for Automatic and Off. The failure line names who
  searched instead, or says the ones after it failed too. The help
  text says the same in en, zh, zh-TW, ja and de.
- docs: gateway-routing's failing searcher, and gui-shell.

Tests:
- TestPickedSearchersInTheirOrder (gateway): one test where the named
  searcher answers without searching and one where it fails. A gone
  entry and one that can't search are skipped, and the third searches
  once. With no working entry, the error says so and Instead is empty.
- TestSearcherThenSaved (settings) and TestSearcherThenFromSettings
  (gui): what is saved, kept and cleared; refusing an entry that can't
  search. settings_keep_test sets SearcherThen.
- searcher-then.test.cjs: chromium and webkit, en, zh, zh-TW, ja, de,
  at 560 and 1000 wide. Checks the row's place and words, what Add
  offers, the posted lists, that the chips fit with no horizontal
  scroll, that no click moves the page, and both failure lines.
Broken by hand: running no fallback turned TestPickedSearchersInTheirOrder
red (both subtests: "ds2 searched []"). Not keeping the list on save
turned TestSearcherThenFromSettings and the keep test red.

Run on mote (mote-run):
- At the pre-rebase tree (base 21882a68d): go test of settings, and
  -run 'Searcher|Search' of gateway and gui: ok.
- searcher-then, searcher-pick and i18n-keys in both engines: 46 of 46.
- gofmt clean. go vet: darwin gateway, gui, settings; windows the same;
  linux gateway and settings on mote, gui with -tags gtk3 on the Linux
  box (wsl-run): ok.
- Rebased onto origin/main 1e6a27d4f, this tree: -run
  'Search|Searcher|CoreScriptBudget|SettingsSave' of gateway, gui and
  settings: gateway and settings ok; gui ok but for
  TestSettingsSaveKeepsWhatItDoesNotSend on BusyLoad, red on main
  since 8d8df0639 (#4739, not this change; SearcherThen passes its
  check). The three GUI files above: 46 of 46.
  Pushed on origin/main e62a1bc51. Its 6 commits since touch routing,
  sessions and rex files only, none of these, and weren't run here.
Not run before the tag: the whole GUI suite and the full go test of
gateway, gui and settings. They are queued behind other sessions'
suites on mote and run after the push; any red they find gets its own
commit.
Not tried: a real relay or a real searcher failing in the GUI app.
2026-11-01 14:43:18 +08:00
yetone 0b4aa96fd0 gateway: a relay whose models are typed in by hand is offered as a searcher (axelburks on Discord)
axelburks added a custom provider on OpenAI's Responses API and ticked
"Searches the web by itself", but Settings › Web search's searcher
picker didn't offer it. Searchers() and namedSearcher took a
provider's models from Available() alone. A relay with no /models
list has its models typed in by hand (Exposed) and none available, so
it was left out of the picker, while the same row named it among the
relays to pick there. searcherModels gives what the provider lists,
then the hand-typed ones it doesn't. A relay that lists its models was
offered before this already.

Tests:
- TestSearcherRelayWithoutModelList (gateway): a Responses relay with
  no /models and a typed model is a searcher and is resolved by name.
- TestSearcherPickerOffersResponsesRelay (gui): the relay saved the way
  the editor saves it is in SearchChoices with its model.
Both were red on the old code.

Run (mote-run), at this commit alone: go vet of gateway and gui, and
go test -run 'Searcher' of gateway and gui: ok. The full checks ran
with the next commit; its body has them.
Not tried: the reporter's own relay (we don't know whether it lists
its models; the reply asks).
2026-11-01 14:43:07 +08:00
yetone a5a9cdf7be gateway: a refused big conversation isn't told again to the Claude subscription's other accounts (Aisiverto on X)
Aisiverto on X: a refused turn of a ~900K-token conversation made magpie
switch accounts and send it again, "one user action becomes several
expensive requests". In the usage, pairs ~100ms apart: one read the whole
conversation from the cache, the other read ~26K and wrote ~877K.

The cause: a refusal goes to the next candidate under RefusalRetries
(unset: every one left), and matesFirst puts the same model's other
accounts first (#248, where a verified account may answer). For a Claude
subscription each other account is a new Claude Code told the whole
conversation, all of it written to that account's cache again, for a
refusal about the content that it most likely gives too.

Now, before a Claude subscription account's try, a conversation of
retellMost (100K) tokens or more by estimate (tooBigToRetell) leaves the
subscription's other accounts out if that account refuses
(otherThanClaudeAccounts). Other members are still asked; with none left
the refusal is the agent's, and it isn't handed over mid-stream to
nobody (handsOver is given last). A smaller conversation goes to the next
account as before. The size is measured only when another Claude
subscription account is left. gateway-routing.md says so beside
RefusalRetries.

Run:
- TestClaudeSubscriptionBigRefusalNotToldAgain (new; streamed and not):
  red on the old code (runs "own,tok-spare"), green with the fix, the
  agent getting the refusal. TestClaudeSubscriptionRefusalMovesToNextAccount
  (small conversation, spare still asked), TestRefusalRetries* and
  TestPolicyRefusal* green.
- Broken by hand: tooBigToRetell always false, red.
- On mote: gofmt -l clean; go vet, GOOS=linux go vet -tags nogui and
  GOOS=windows go vet of internal/gateway ok; go test -tags nogui
  -timeout 45m ./internal/gateway: ok (702s). The whole suite ran at the
  parent commit (its body); this commit touches internal/gateway only.

Not tried:
- The handsOver change: the test's refusal comes with no reasoning
  before it, so nothing is handed over, and taking the change out stays
  green. Not covered by a test.
- A large conversation where another member of the group is a Claude
  subscription of a different provider id: it is left out too, as every
  Claude subscription account is.
- A real Claude refusal on a real account.
2026-11-01 14:28:40 +08:00
yetone 2af4d8c62d claude bridge: tool results another request answered first branch off the run's session (Aisiverto on X)
Aisiverto on X: a Claude Pro account's five hours went from 96% left to
1% in about five messages of a ~900K-token conversation. The usage had
pairs of requests about 100ms apart: one read ~900K from the cache, the
other read ~26K and wrote ~877K.

The cause: Claude Code's fork sub-agents start from their lead's
conversation, each of the lead's calls answered "Fork started", and they
come with the lead's own next turn. One of them goes on in the run that
made the calls. Each other one (and a resend, or one after the run has
delivered) got a new Claude Code told the whole conversation in one
message, a prefix Anthropic's cache had never seen. So it was written
to the cache again, about a fifth of the plan's five hours each time.

Now the run keeps where in its session each call of the client's tools
was written: the uuid on Claude Code's stream-json assistant line
(noteLines). As it parks, it also keeps the conversation those calls
answered. A request no run takes, whose last reply's calls a live run of
the same owner made from the same conversation, goes on in a -p branch:
--resume <session> --fork-session --resume-session-at <uuid>. That is the
conversation as Claude Code sent it to Anthropic, so it reads the
cache, and it is told only the results and the directive after them. The
lead's session file stays the lead's. There is no branch with client
cache marks, in interactive-only mode, or from a rewound, closed or
sessionless run. Then, and if the resume fails, the old path is taken.
The -p reason is "branch", worded in claudemode.js and i18n.js (zh, zh-TW,
ja, de). The subsystem doc's section says so.

Run:
- Claude Code 2.1.316 (real binary, on mote), against a fake Anthropic API and a
  fake MCP tool. --resume S --fork-session works while another
  process holds S. --resume-session-at <assistant uuid> cuts the copy
  there even after the lead went on, and the prefix up to the tool_use
  matches the lead's. Calls it answered nothing for get a
  synthetic error result.
- TestClaudeForkBranchesOffTheLeadsSession (new): red on the old code
  ("told it whole"), green with the fix.
- Broken by hand, each red: park() not stamping the conversation the
  calls answered; serveSubscription not asking branch().
- On mote, before the rebase onto origin/main 21882a68d: gofmt -l
  clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... ok.
- On mote at this commit (on 21882a68d):
  - go test -tags nogui -timeout 45m ./...: every package ok but
    internal/gui, whose two reds are filed and untouched here:
    TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, #4739) and
    TestColdTurnsTaken (#4510).
  - GUI claude-mode and i18n-keys, Chromium and WebKit: 78 of 78 pass.

Not tried:
- A real fork sub-agent against a real Claude subscription through
  magpie. The branch flags were run with the real binary, not through
  the gateway.
- A winner running in the interactive (TUI) mode: if its output has no
  uuid on assistant lines, there is no branch and the old path is taken.
- A loser that comes before the winner's run has parked takes the old
  path.
- Windows and WSL.
2026-11-01 14:28:40 +08:00
yetone 7503beee72 plugin, settings: a model's load goes past 100% for a vendor that queues (axelburks on Discord)
axelburks, on v0.1.2547: their vendor queues, so a model's load can be
past 100%, even 200%. magpie clamped every load to 100, and Busy models
last allowed 1-99 only.

- host.js reportLoad and plugin.noteLoads keep a load from 0 up. The
  floor is still 0, null still clears it, and a sanity cap of 10000
  (LOAD_MOST, plugin.LoadMost) keeps an absurd value from reaching the
  UI or the trace.
- settings.BusyLoad takes 1 to 9999 (BusyLoadMost-1). The segment
  choices stay Off/50/70/80/90, and a value set in settings.json (150)
  shows as its own choice, as before.
- The editor's badge reads "180%". It is a badge, not a bar, so nothing
  assumed 100 wide; the test checks it stays on one line.
- Docs: site plugins page (en, zh, ja) Values and Routing bullets, and
  provider-plugins.md and gateway-routing.md.

Run on mote via mote-run, on origin/main 8d8df0639+ rebased:
- go test ./internal/plugin ./internal/gateway ./internal/settings -run
  'ModelLoad|TestBusy' -v: all pass. TestPluginReportsModelLoad has
  over:250 kept and huge:1e9 at 10000. TestBusyModelGoesBehind has 180
  behind 120 at a threshold of 150, and 10000 refused.
- Broken by hand in a copy, with the old 100 clamps and the 99 limit:
  TestPluginReportsModelLoad red ("ModelLoad(over) = 100; want 250"),
  TestBusyModelGoesBehind red (150 refused).
- node --test model-load (with Queued 180% in every language, Chromium
  and WebKit, 420 and 900, plus Over 150% picked at 420) and i18n-keys:
  46/46 pass. go test ./internal/gui -run Budget: ok.
- gofmt -l: empty. GOOS=linux go vet -tags nogui and GOOS=windows go
  vet on plugin, settings and gateway: ok.

Not run before the push (owner: push and tag first): go test ./... and
the whole GUI suite. They are queued on mote behind another session's
suite.
2026-11-01 14:28:25 +08:00
yetone f2f75ee4ae provider: Volcengine Ark's System One API, in beta, as a decider (axelburks on Discord)
Ark answers System One at https://ark.cn-beijing.volces.com/api/v1/systemone
(and /api/v3/systemone) only with the beta header ark-beta-systemone-api:
true; without it the reply is a bare 404. The new volcengine-decision preset
asks it with an Ark API key, and magpie sets the header (DecideHeaders) on
Ark's own host only, ark.<region>.volces.com, in both the gateway's
/v1/systemone and the provider's Test. Its decision model,
doubao-seed-2-1-lite-260915 (ArkDecision), is kept apart from Ark's chat
list as Bailian's is (vendorDecision), since no /models names it.

Learnt from the real API on 11-01 with the owner's Ark key (read from
magpie's config, never printed): only doubao-seed-2-1-lite-260915 answers;
doubao-seed-2-1-pro-260628, doubao-seed-2-0-lite-260428 and
deepseek-v4-1-flash are refused 400 "does not support the SystemOne API".
The Coding and Agent Plans' paths (/api/coding/v3, /api/plan/v3, their v1s)
answer an empty 404 even with the header, so it bills as pay as you go. An
image in the request was left unread (a red square came back 0.48, input
tokens as for no image), so images are off. The tests' replies are the
real response bytes.

Run:
- Real: a magpie built from this tree on mote, in a sandbox HOME:
  `magpie provider add volcengine-decision <key>` and `provider test`
  (decide ok, 413 ms), then `magpie serve` on a free port and POST
  /v1/systemone through it: a real 200 with Ark's choice.
- gofmt -l internal/: clean. go vet darwin, linux, windows of
  internal/provider and internal/gateway: ok.
- mote-run go test -count=1 -timeout 45m ./internal/provider/
  ./internal/gateway/ ./internal/gui/ ./internal/cli/ at base 21882a68d:
  provider ok (140.6s), gateway ok (652.6s), cli ok (58.7s); gui FAIL on
  two tests this change doesn't reach, both filed:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, red on main, #4739)
  and TestMainWindowCorners/macOS_26_SDK (mote's macOS 27, #3949).
- Rebased onto origin/main 788057340, this tree: vet darwin, linux,
  windows ok; go test -run 'Ark|Decid|SystemOne|Bailian' of provider
  and gateway ok.
- Broken by hand: without the DecideHeaders calls both Ark tests go red
  (provider: Ark's empty 404; gateway: FAIL).

Not tried: a routing group classified by Ark end to end in an agent;
regions other than cn-beijing; Ark's window on System One (no docs page
for it was found, so none is set).
2026-11-01 14:17:21 +08:00
yetone 788057340b library: Magpie Image Recognition in Discover beside Magpie Image and Web Search (matrix0487 on Discord, #4653)
matrix0487 asked on Discord (#feedback) for all three of magpie's own MCP
servers, image recognition, image generation and search, in the Library's
Discover. Image generation and search were there; image recognition was
an address to copy in Settings only (#4653).

- `magpie mcp vision` (browsermcp.RunVision) relays stdio to the
  gateway's /mcp/magpie/vision, as `mcp search` does. analyze_image's
  relative image path is made one in the agent's folder on the way
  (imageFrom), since the gateway can't know where the agent runs; an
  absolute path, ~, a URL or a drive goes as written.
- library: magpie-vision is a featured, opt-in server (no agents until
  picked), any binary's `mcp vision` is one server (serverKey), and it
  gets the 120s tool timeout (selfTimeout).
- Settings › Models › Images: the Image recognition row has Give agents
  Magpie Image Recognition… / Turn on the Library, none with recognition
  off or in gateway mode. The three links are one helper, libWay, used by
  Image generation and Web search too (no budget raised: core 1,533,011
  of 1,533,105).
- Never a dead tool: Discover lists all three whatever is set up, and one
  that can't answer yet says why (gateway.OwnUnready, set by
  /api/library/market/servers as `unready`): a "Not set up yet" badge on
  its card with the reason as its title, and the reason in its sheet
  (nothing set up, or turned off in Settings / Plugins). It can still be
  added; its tools already answer with the same reason until then.
- Strings in en, zh, zh-TW, ja, de; docs/subsystems/library.md.

Run, all on mote (macOS 27) through mote-run, at this head's tree
(rebased on 21882a68d):
- gofmt -l internal/: clean. go vet darwin; GOOS=linux -tags nogui;
  GOOS=windows: browsermcp, cli, library, gateway, gui, imagemcp ok.
- go test -timeout 45m: internal/library, browsermcp, cli, imagemcp ok;
  internal/gateway ok (whole package, 556s, before the rebase; OwnMCP,
  OwnUnready, VisionMCP, SearchMCP after it). internal/gui: three reds,
  none from this change, each red on origin/main 21882a68d too:
  TestSettingsSaveKeepsWhatItDoesNotSend (BusyLoad, from 8d8df0639,
  filed #4739), TestMainWindowCorners/macOS_26_SDK (#3949),
  TestColdTurnsTaken (#4510). Budget tests ok.
- New: TestMagpieImageRecognitionIsOptIn, TestVisionBridgePassesLines,
  TestImageFromLeavesTheRest, TestOwnUnreadyWhileNotListed.
- New GUI test vision-mcp-library.test.cjs: chromium + webkit, en, zh,
  zh-TW, ja, de, 1100 and 420px (link opens the sheet with its hint and
  unready line; Library off → Turn on the Library; one added opens
  Discover with all three, only the unready one badged, inside its card;
  gateway mode and recognition off show no link; no horizontal overflow,
  no page errors): 206/206 with search-mcp-library and
  images-library-way. On e84870f17 (old code), chromium: every link and
  Discover case red.
- i18n-keys, gui-de, gui-zh-tw ok; gui-ja's one red is #4580, the same
  on origin/main 21882a68d.
- Broken by hand: serverKey without "vision" → TestMagpieImageRecognitionIsOptIn
  red; imageFrom not joining the folder → both browsermcp tests red.
- Real use, sandbox HOME on mote, nogui build, `magpie serve` on
  127.0.0.1:3591: `magpie mcp vision` initialize / tools/list answered;
  analyze_image of shots/a.png says "magpie has no model that sees
  images…"; missing/b.png names /…/work/missing/b.png (relative path
  resolved); an extra argument exits 1; gateway down answers id 9 with
  "magpie isn't running, so Magpie Image Recognition can't be reached".

Not tried: analyze_image against a real seeing model through the relay
(the sandbox had no provider; the gateway path is the one /mcp/magpie/vision
already serves); a real agent adding it from Discover; WSL (unchanged,
the MCP router serves it there); the whole GUI suite, queued after
mote's running one.

Reported-by: matrix0487 (Discord)
Closes #4653
2026-11-01 14:12:42 +08:00
yetone 8d8df06399 plugin, gateway: a plugin reports its models' load, and busy models can go last (axelburks on Discord)
axelburks (Discord #feedback): an in-house vendor queues requests to
its busy models, and the plugin could only put the load in the model's
name, which changed only when magpie re-read the list.

- A provider plugin calls input.magpie.load(provider, {"<model id>":
  0-100 | null}) whenever it likes, from its own timer. host.js
  (reportLoad) clamps each number to 0-100, null clears a model, every
  other value is dropped, at most 1000 a call, and it returns the count
  taken. A provider that isn't a string or loads that isn't an object
  throws a TypeError. It goes to Go as an unasked {event:"load"}.
- internal/plugin/load.go keeps each by provider and lowercased model
  id. ModelLoad answers unknown once a load is older than LoadFresh
  (5 minutes), never idle. model@size falls back to its model.
- The provider editor shows it by the model as a grey ctx badge
  ("87%", titled "87% busy now, as its plugin says").
- Settings > Network and sharing > Busy models last (settings.BusyLoad,
  POST /api/settings/busy-load, Off by default, over 50/70/80/90% or
  1-99 by hand): restLast puts a model reported over it behind the
  ready candidates, ahead of the resting. The trace row has busy:<load>.
  At a new turn affine moves a conversation off it (Why "busy",
  busyBehind); within a turn it stays. after, readyForNew and leastHeld
  skip it. Unknown load, a lone candidate, or all busy: nothing moves.
- Docs: site plugins page (en, zh, ja) "Model load" section and input
  table; docs/subsystems provider-plugins.md and gateway-routing.md.

Run, all on mote via mote-run at a42736807's tree rebased on
origin/main b683f1c0e:
- go test ./internal/plugin ./internal/gateway -run
  'ModelLoad|TestBusy' -v: TestPluginReportsModelLoad,
  TestModelLoadGoesStale, TestBusyModelGoesBehind,
  TestBusyModelNotKeptAtNewTurn pass.
- Broken by hand, each red: host.js not sending the event
  (TestPluginReportsModelLoad "the plugin's loads never arrived"), the
  busy case off in restLast (TestBusyModelGoesBehind order), the affine
  "busy" case off (TestBusyModelNotKeptAtNewTurn "kept true, why
  session").
- go test ./internal/gui -run Budget: ok. No budget raised. app.js
  +86 bytes, two comments trimmed to fit. The settings row lives in
  plugins/gateway/settings.js.
- node --test model-load, i18n-keys, bare-ids, model-rate: 69/69 pass.
  model-load is Chromium and WebKit, 420 and 900 wide, en zh zh-TW ja
  de.
- gofmt -l: empty. go vet ./... (darwin), GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./..., go build: ok.

Not run before the push (owner: push and tag first): go test ./...
-timeout 45m and the whole GUI suite. mote and the WSL box were each
running another session's full suite. Both run next, and any red gets
its own commit.
Not tried: a real plugin and vendor reporting load. The plugin side is
tested through the real Bun host with a plugin written in the test.
2026-11-01 13:45:40 +08:00
yetone b683f1c0e1 gateway: a search on Volcengine Ark asks for no include value Ark refuses
axelburks on Discord #feedback (1566310723922042991): every web search
on an Ark model (ark.cn-beijing.volces.com) failed with 400 "The
parameter `include` specified in the request are not valid: unknown
type: web_search_call.action.sources". buildResponses adds that value
to every Responses request offering web_search on any host but
api.x.ai (#315, c4ae3ca77); Ark became a host that searches by itself
later (a0cb8b646), and forArkSearch fitted the tool but not include.

Ark's 创建 Response page (docs.volcengine.com/docs/82379/1569618) names
`include` but lists no values, so they were asked of the real API with
the owner's key (deepseek-v4-1-flash-260910): reasoning.encrypted_content
is taken; web_search_call.action.sources, web_search_call.results,
file_search_call.results, message.input_image.image_url,
computer_call_output.output.image_url, code_interpreter_call.outputs and
message.output_text.logprobs are each refused with the reporter's 400.

- search_ark.go: arkIncludes (reasoning.encrypted_content alone) and
  includeTaken(host, v), Ark's host only.
- buildResponses (every translated request, Claude Code's
  web_search_20250305 and Settings' searcher on an Ark model included):
  a value Ark refuses is left out of the client's include, and the
  sources value isn't added for Ark. Every other host is as it was.
- forArkSearch (a Responses client relayed to Ark): include keeps what
  Ark takes, and goes when nothing is left. The AI SDK's OpenAI
  provider (OpenCode) adds web_search_call.action.sources itself
  whenever it offers web_search (@ai-sdk/openai 3.0.27, index.mjs
  addInclude), so that route failed the same way.

Siblings in searchHosts[Responses]: api.openai.com takes the value
(OpenAI's own), api.x.ai already gets none, and api.deepseek.com took
it with web_search on the real API (200, completed). open.bigmodel.cn
and api.z.ai: no key here, not tried; no report of a refusal.

Tests: TestArkSearchSendsNoIncludeItRefuses (a fake Ark on the real
host through a redirected dialer that answers the reporter's 400 for
any include value Ark refuses: Claude Code's search translated,
OpenCode's relayed with sealed reasoning kept, and Settings' searcher
on the Ark model), TestArkIncludeScope (OpenAI's and a relay's include
unchanged, sources still added; Ark's keeps only what it takes).

Broken by hand: includeTaken returning true and forArkSearch's include
filter off: all three subtests red with the reporter's exact 400
(searcher: "...unknown type: web_search_call.action.sources ... (the
searcher picked in Settings › Web search ...)"), and TestArkIncludeScope
red.

Real use: the bodies the fixed gateway sends Ark on all three routes
(captured from the test) sent to the real Ark API: each is accepted and
streams; the old shape (with the sources value) is refused with the
reporter's 400. This account hasn't activated Ark's web search, so the
search itself ends ToolNotOpen; a search returning pages wasn't seen.

Run (mote, mote-run, at e84870f17 + this change):
- gofmt -l internal/gateway: nothing.
- go vet ./internal/gateway, GOOS=linux go vet -tags nogui
  ./internal/gateway, GOOS=windows go vet ./internal/gateway: ok.
- go test -count=1 -timeout 45m ./internal/gateway: ok (572.5s).

Not run: the other packages' suites (only internal/gateway changed).

Rebased onto 6874b892b, which changes no internal/gateway file; gofmt, vet x3 and the Ark/include/search tests ran again there: ok.
2026-11-01 13:43:35 +08:00
yetone ed5872d186 gateway: a kept previous response holds its input, not the body it came in
previousResponse kept each turn's input items as views into the request
body, so every response kept for previous_response_id held its whole
body: tools, instructions and anything else the client sent. own counted
only the items, so prevCap's 256 MB bounded far less than was held. The
input is now copied out (ownItems, as the Codex socket does since
ec0a11d47) and own counts the bytes copied.

Run:
- Real zcode account (plugin), sandbox HOME with no network to anything
  else: 30 HTTP /v1/responses turns, store true, chained by
  previous_response_id, ~600 KB per body. Live heap before -> after:
  old (ec0a11d47) 23.9 -> 101.1 MB; this change 24.0 -> 42.9 MB, and 30
  more turns 41.6 -> 43.9 MB.
- mote: go test -run 'Prev|Previous|KeptTurn|HeldTurn|Socket'
  ./internal/gateway ok. TestKeptTurnOwnsItsInput is red with the copy
  taken out by hand ("kept after the body was written over").
- GOOS=linux and GOOS=windows go vet ./internal/gateway ok; gofmt clean.

Not run: the full suite before the push (the gateway package runs right
after it).
2026-11-01 12:58:45 +08:00
yetone ec0a11d47f gateway: a Codex socket's held reply keeps its input, not the frame it came in
A held turn's fresh input items were views into the response.create frame
they were decoded from, so each held reply kept that whole frame alive:
Codex's tools and instructions with it, for as long as the socket held
the reply (~39 MB of a long session's live heap). keep now copies the
fresh items into one buffer of their own; the conversation held before
is already owned, and the reply's items were already copied.

Run on mote: go vet ./internal/gateway; go test -run
'TestHeldTurnOwnsItsInput|TestResponsesSocket|TestCodexSocket'
./internal/gateway ok. Broken by hand (keep appends fresh as views):
TestHeldTurnOwnsItsInput fails, held items read back as the overwritten
frame.
Not run: the full gateway package before the push, and a real Codex
session over the socket.
2026-11-01 12:11:05 +08:00
yetone 36af588e2c gateway: "Context window is full" is a conversation too long for the model
ergou0954_54426 on Discord (#feedback, 11-01) routes by intent across
several models, one a "kiro opus" of an API-key relay (not magpie's Kiro
plugin). On long conversations the relay answered 400 "Context window is
full. Reduce conversation history, system prompt, or tools. (request id:
…)". That is the wording kiro.rs (src/anthropic/handlers.rs) and
kiro2claude (error-mapper.ts) give Kiro's CONTENT_LENGTH_EXCEEDS_THRESHOLD,
always as a 400 invalid_request_error, with new-api's request id after
it. tooLongRe had no words for it, so the 400 was an ordinary request
error: the group never asked the next member, and the agent got the
relay's 400 as a plain error, with no context_length_exceeded to compact
on. In a stream's error event it stood for a 502 (streamStatus), a
passing vendor fault that rests the account and is asked again.

tooLongRe now takes "context (window )?(is )?full", so overflowed,
failure, retryable, streamStatus, lateRests and writeErrorSaid all read
it the same way: on 400, 413 or 422, or in a stream's error event, the
member is passed for one with room (failOverflow, no rest), and alone
the agent is told context_length_exceeded. Not changed: a 5xx carrying
the words is still the vendor's fault (tooLong is 4xx only, as
TestContextOverflowSaidTheClientsWay holds for a 502), and
tooLongUnsaid still covers a 5xx only where the window is known.

Routing could not have skipped the member up front: a custom relay's
model has a window only from its own /v1/models list, models.dev by id
(catalog.ContextOf, with its spellings), or the user's Context setting.
A relay id such as "kiro-opus" matches none, so the window is unknown
(0), roomy keeps it and withRoom counts it as having room. A probe in a
fresh HOME gave windowOf 0 for claude-opus-4-6, kiro-claude-opus-4.6 and
kiro-opus on a custom provider.

TestContextWindowFullIsAnOverflow and
TestContextWindowFullGoesToAMemberWithRoom are built from the literal
text, with and without the request id, Anthropic- and OpenAI-shaped,
plus kiro.rs's sibling "Input is too long. Reduce the size of your
messages."; ordinary 400s (invalid model, model not found, messages
required) stay non-overflows.

Found and filed, not fixed: the last candidate's stream error event that
says too long reaches the agent as the vendor wrote it (#4675).

Run on mote, on this change at base 6f3dfc282: gofmt -l internal/gateway
clean; go vet ./internal/gateway, GOOS=linux go vet -tags nogui,
GOOS=windows go vet: ok; go test -timeout 45m -count=1 ./internal/gateway:
ok (730s). At the pushed head (rebased on 445891cf7, which changed
internal/gateway and internal/provider): gofmt and go vet
./internal/gateway clean, and go test -run of the two new tests,
TestContextOverflowSaidTheClientsWay, TestEveryVendorsOverflow,
TestChineseNotTooLong, TestKiroPluginOverflowGoesToAMemberWithRoom and
TestOverflowGoesToAMemberWithRoom: ok.
Broken by hand: the two new tests at origin/main 6f3dfc282 (without the
regex change) fail: every status reads as not an overflow, the stream
error stands for 502 and rests, and the group answers the relay's 400
with the second member never asked.
Not run: the whole gateway package at the pushed head, the full ./... suite (another session's suite held mote), the
GUI suite (no GUI change), a real Kiro-backed relay pushed past its
window.
2026-11-01 12:02:09 +08:00
yetone 6d23a4282f provider: whether a model sees images doesn't wait for usage readings; start ~9 s → <3 s
magpie's gateway listened ~9 s after start. A goroutine dump 3 s in had
main in provider.Allowances' first-ask wait: the start's migrations
(agent.RenameLegacy) read Pi's effort field, which builds Pi's model list,
which asks provider.Described (does any model see images), which ranks
the vision models by spent accounts, which asks each agent's allowances.
Each agent's first ask waits firstWait (3 s) for its accounts' usage over
the network. Every agent's model list asks Described, so the GUI's first
lists waited the same way.

Described only asks whether a model is there, not which account a request
goes to, so it now runs under provider.Unwaited: Allowances answers from
what is last known (the readings kept on disk) and starts the reading
behind it, as after firstWait. A request routed by the gateway still waits
as before.

Real history in a sandbox HOME (17,140 session files, every account
copied from this Mac's), the network blocked by a dead proxy, `magpie web`
started twice each:
- before (v0.1.2528 tree): gateway up at 9.8 s and 8.8 s.
- this change: 2.8 s and 0.6 s; first /api/sessions answered at 4.5 s and
  2.1 s, against 12.2 s and 10.7 s.

Tests, on mote: TestUnwaitedAllowancesDontWait is new. Broken by hand
(Allowances waiting under Unwaited too) it fails: "took 20.0s".
go test ./internal/provider/ ./internal/gateway/ ./internal/agent/ ok
(gateway 740 s). gofmt -l clean; go vet (darwin), GOOS=windows go vet,
GOOS=linux go vet -tags nogui of provider and gateway ok.

Not run: the full suite; a start with the network up (the wait there
was the vendor's answer time, up to 3 s an agent); Windows and Linux.

Picked onto 2be5d206e (origin/main at push); not run again there.
2026-11-01 11:53:58 +08:00
yetone 2be5d206e1 gateway: a Codex summary request too large for the vendor is asked again as text, then compacted locally (celestial_eagle_99230 on Discord)
celestial_eagle_99230 (Discord #general, v0.1.2403) runs Codex on official
DeepSeek (DeepSeek-V4.1-Flash, 1M window) and gets "413 Request Entity Too
Large: Failed to buffer the request body: length limit exceeded". The turn
path was fixed by 2cca11176 (v0.1.2419): Codex gets context_length_exceeded
and compacts. But the compaction is the problem. Codex (openai/codex main,
compact_remote_v2.rs) sends its summary request through the same /responses
route, trims only by its token estimate against the catalog's 1M window, and
on ContextWindowExceeded does not trim and retry. A conversation that is
over DeepSeek's byte cap (base64 images and long tool outputs sent each
turn) is under 1M tokens, so the summary request was the same oversize
body. magpie passed the 413 (or overflow) back, compaction failed each
time, compactFails held later tries, and the session could neither compact
nor go on.

codexCompact now counts a 413 or an overflow on the summary request
(summaryTooLarge) with the failures it already asks again as text
(plainCompact: images left out, tool outputs over 4000 chars cut, at most
400K chars), then compacts without a model (localSummary) when that is
refused too. This is keyed on the status and overflow words, not on
DeepSeek: a summary request refused for its size means the same thing for
every vendor, and the old result (a session stuck) is never better. Any
other refusal goes back unchanged (TestCodexCompactOtherRefusalStays,
TestCodexCompactOtherFailuresStay), and a non-Codex client still gets the
413 as request_too_large (TestDeepSeekByteCapTurn's opencode case,
TestByteCapBeforeStreamStaysStatusForOthers).

DeepSeek probed without a key (no tokens): bodies of 1 to 40MB to
api.deepseek.com/chat/completions get 401 "Authentication Fails"; 80MB and
120MB get openresty's text/html 413 page. The reporter's text is axum's
body-limit error, which sits behind auth, so its value is unknown. DeepSeek's
docs list no 413 and no byte limit.

Run, mote (mote-run):
- Red at origin/main fb3942ee6 with only the new test file:
  TestCodexCompactTooLargeAsksSmaller (all 4: Chat/Responses x byte
  cap/overflow) got 413 "compaction: ... answered the summary request 413"
  or 400 context_length_exceeded; TestCodexCompactTooLargeCompactsLocally
  got 413. TestDeepSeekByteCapTurn passed (2cca11176's turn path).
- Green with the fix; broken by hand (summaryTooLarge returning false):
  all 4 AsksSmaller subtests and CompactsLocally red again.
- At the pushed head (rebased on 90c02326b): go test -count=1 -run
  'Codex|Compact|Overflow|ByteCap|TooLarge|DeepSeek|StreamError'
  ./internal/gateway ok (90s). go vet ./internal/gateway on darwin,
  GOOS=linux -tags nogui and GOOS=windows ok. gofmt -l clean.

Not tried: the whole internal/gateway package and ./... (mote was running
another session's 45m multi-package suite at load ~210, and one suite runs
at a time); a real Codex binary end to end (its compaction was read from
source); a real signed-in DeepSeek request (the cap's value is unknown).
2026-11-01 11:52:46 +08:00
yetone 90c02326bb gui: an app takes the gateway over from its older copy once idle, and says any other version serving it (matrix0487)
matrix0487 on Discord: after an update, pi said 404 'magpie knows no
model "kimi/k3.1-pro" ... add a provider in magpie first'. The app had
written pi a model its older gateway didn't know, and updating the
gateway fixed it. A magpie that finds another one serving the gateway
used to log it and wait for that one to quit (watchGateway took the
port only once nothing answered). Only the Gateway page said so.

Now (otherServes, gateway_older.go):
- An older released copy of the app (it says serves app or tray, and a
  pid) is this app's predecessor. Once its /v1/magpie/concurrency says
  nothing is in flight (gateway.ServedBusy; unknown is never idle),
  the app quits it the way the Gateway page's button does
  (quitMagpieOnPort: a magpie only, by its program) and serves the
  gateway. A stream through it runs to its end first. watchGateway
  looks again every 15s while another serves. At most three times a
  run; a quit that fails is left to the button.
- Any other one (magpie serve or the service, magpie web, a TUI, a
  newer magpie, a build of its own) is left running. /api/state
  carries it as gatewayOther, and the Agents page says it above the
  list with what to do, plus the take-over button for an older one
  (gatewaySkewLine, in plugins/gateway/client.js so app.js stays under
  its budget). A dev build of this magpie says nothing. New strings in
  zh, zh-TW, ja and de.

How the reporter's older gateway outlived the update isn't known: they
never said whether one ran separately. A failed handover leaves the
old app serving for up to 15m, and a magpie serve left running is
another source. Both are covered now: the first is replaced, and the
second is said.

Known gap: a request that starts between the idle read and the quit
gets the older app's short drain. A socket handover between two
running apps (no gap) is not built.

Run on mote at 0f8ea30bb (this change on 2b067434d):
- go vet for internal/gui and internal/gateway, also GOOS=linux
  -tags nogui and GOOS=windows; gofmt -l clean.
- go test -count=1 -timeout 45m ./internal/gui ./internal/gateway:
  gateway ok. gui has two reds, the same on origin/main 0c3163804:
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestMainWindowCorners/macOS_26_SDK (#3949).
- GUI subset, Chromium and WebKit: gateway-*, agent-layout, agents-*,
  getting-started, i18n-keys, gui-ja/de/zh, panel-arrange, panel-fold:
  411 pass. Two reds, the same on origin/main 0c3163804:
  gateway-caller-keys chromium en (#3797) and gui-ja (#4580). Passing: the new gateway-skew.test.cjs (en and zh at 380px, the
  button POSTs take-over and the line goes).
- Real app on mote, sandbox HOMEs, port 3591, update feed pointed
  nowhere:
  - origin/main built as 0.1.2400 ran `magpie app`, and this head
    built as 0.1.2500 ran `magpie app` beside it. The new one logged
    "an older copy of this app ... with nothing in flight; quitting
    it" and served 0.1.2500 on the port 2s later. The old process was
    gone.
  - The same with the old one as `magpie serve`: it was left running,
    and the new one logged that it serves, older.

Red on origin/main: TestAppReplacesItsOlderGatewayOnceIdle ("the
older copy of the app still serves the gateway", 17s).

Again at the pushed head (this change on 6f3dfc282, mote): vet darwin, linux
nogui and windows; TestCoreScriptBudget (the core is 1,533,104 of
1,533,105: main's #4652 took the room, so app.js's hook line lost its
comment, no raise), TestAppReplacesItsOlderGatewayOnceIdle,
TestGatewaySkew*, TestGatewayFixQuitsOnlyAMagpie,
TestGatewayServedByAnOlderMagpie: ok. gateway-skew, i18n-keys, gui-zh,
gui-de: 11 of 11 pass.

Broken by hand, each red:
- quit without waiting for idle: "quit with a request in flight"
- replaceable() false: "still serves the gateway"
- any serves replaceable: TestGatewaySkewOfAnotherIsSaidNotQuit, the
  serve holder quit
- the Agents hook removed: gateway-skew.test.cjs red in both langs

Not tried: the whole GUI suite (mote was running another session's
full suite), a real app with a real agent stream in flight during the
take-over (the Go test holds a stream through a fake), Windows and
Linux apps (the replace path needs handoverHost, set by the app's Run
on every OS, but it was tried on macOS only).
2026-11-01 11:43:56 +08:00
yetone 0c31638045 kiro: the mover installs 0.1.24, which says a too-long conversation as one
ergou0954_54426 on Discord routes by intent across Kiro's Claude and GPT
models and DeepSeek, and sometimes a turn failed with Kiro saying the
context was exceeded. Kiro says a conversation is past the model's window
in three ways, and the plugin up to 0.1.23 turned only the HTTP 400 into
the "input is too long for the model's context" that the gateway reads as
an overflow (tooLong). The same ValidationException as an exception in
Kiro's event stream came out as a 502, so the gateway took it for a
passing vendor fault: it rested the account, asked Kiro again (15 asks
for a lone provider in a probe), and never told the agent
context_length_exceeded, so the agent never compacted. A reply Kiro
stopped with MODEL_CONTEXT_WINDOW_EXCEEDED came out as finished.
plugins e8050e8 (kiro 0.1.24, on npm) answers both as the 400 that says
too long. Routing was already right: roomy skips a member whose known
window the request is past, and withRoom moves an overflow to a member
with room.

The min goes to 0.1.24 so keepMovedCurrent updates every moved user.
TestKiroMoverHasTheTooLongFix holds it there.
TestKiroPluginOverflowGoesToAMemberWithRoom pins what the gateway does with
0.1.24's two wordings: in a group the other member answers, the try is
failOverflow with no rest, and alone the agent gets context_length_exceeded
after a single ask.

Run on mote: go vet ./internal/provider ./internal/gateway; go test
-timeout 45m -count=1 ./internal/provider (ok 150s) ./internal/gateway
(ok 712s). gofmt -l clean. Broken by hand: at origin/main's min 0.1.23,
TestKiroMoverHasTheTooLongFix fails. A probe with 0.1.23's 502 body
showed Fail other, a rest, and a vendor 502 for the lone provider.
Not run: the full ./... suite (another session's full suite held mote),
and a real Kiro account pushed past its window.
2026-11-01 11:30:12 +08:00
yetone f435aadbf3 gateway: an image is described once, whatever model describes it, and a canceled request stops its descriptions
Pkh on Discord (0.1.2509, Linux, QwenPaw, Auto routing): with images in
the conversation, the Routing view filled with "Image description" rows,
one request asking for 63 in ~60ms, and the request they were for had no
row of its own.

Causes, each red on origin/main b2145eac1 (the new tests run there):
- A description was kept under the describing model and its level
  (sha256(model, effort, src)): AutoVision's pick changing between turns
  (opencode-go/deepseek-v4.1-flash, auto/qwen3.8-flash) read every image
  again. It is now kept under sightKey: a base64 data URL's decoded bytes
  (strict base64), else the URL, with the level picked in Settings, so
  the same picture on another protocol or media type is described once
  too, and seenBody dedupes by the key.
- describe ran on the first asker's context. Its agent canceling it failed
  the description for every request waiting on it ("context canceled",
  a 502 to a request nobody canceled) and took it out of the cache. The
  work now runs on its own context (WithoutCancel + cancel); a request
  that goes stops waiting, and only the last to go stops it and forgets
  it. A reply that came whole is kept though its asker ended.
- seenBody's queued images took a slot without looking at the context,
  so after a cancel each went on to serve with a dead context and put an
  instant 499 row on the Routing page. One waiting for a slot when its
  request ends is now asked of no one.
- The descriptions' routes are noted on the request's inflight (they run
  on its context), which dropped its "routing" placeholder; a cancel
  then left it no route at all. It now gets one (notDescribed), 499 when
  its agent canceled and 502 else, and the usage record names it. A
  group's request ends 499 on a cancel too.

Not as reported: a failure never threw away good descriptions (only the
failed one went), and seenBody already deduped and shared in-flight work
within the cache; it was the cancel, the model in the key, and the
queued work that made it read everything again.

Run on mote at this tree (rebased on da0005df8):
- gofmt -l internal: clean. go vet ./... on darwin, and GOOS=linux /
  GOOS=windows -tags nogui go vet ./...: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
  (806s); also ok on the earlier bases 8ac1c7a56 (with ./internal/catalog)
  and ccb75030a.
- -race -count=10 on the four new tests, TestUnrouted* and
  TestTextOnlyModelIsGivenTheImagesDescription: ok.

Broken by hand, each red with the named test:
- the model back in the key, and the key by src string:
  TestSameImageDescribedOnceWhateverDescribesIt;
- the work on the first asker's context:
  TestOneRequestGoneLeavesTheDescriptionToAnother (502 context canceled);
- the slot taken without the context: TestCanceledRequestAsksNoMoreDescriptions
  (9 rows, want 4); on origin/main 10;
- no notDescribed: TestCanceledWhileDescribingKeepsItsRoute (no route).

Not tried: Pkh's own QwenPaw conversation and providers; the fix is
tested with a fake describer only. heldSight (unrouted_test.go) now seeds
the cache under sightKey.
2026-11-01 10:50:31 +08:00
yetone 9be72c9480 zcode: a level's thinking carries its budget, and the user's own level options stay (#3852)
Review of d7e1e284f, two things it changed beyond its case:

- Every level that thinks was written as {"thinking":{"type":"enabled"}}
  with no budget_tokens. ZCode puts a level's options in the request, so
  a Claude before 4.6 (Sonnet 4.5, Haiku 4.5, a relay's) asked through
  magpie at any level would be sent "enabled" without the budget
  Anthropic's Messages API requires with it, a 400 it didn't get before.
  Each level now carries the budget the gateway reads that effort as
  (gateway.ThinkingBudget, budgetOf: low 4096 ... max 32000). The
  gateway already makes it adaptive for Claude 4.6 and later
  (adaptiveThinking; ZCode's output_config.effort wins over the budget)
  and fits it under max_tokens (maxoutput.go).
- providerOptionsByLevel was written over on every sync. A user who put
  their own there (the workaround for this very bug) lost it. A level's
  options already in config.json now stay; no magpie before #3852
  wrote any, so whatever is there is the user's.

Tests: TestZCodeOutputAndReasoning expects the budgets;
TestZCodeKeepsTheUsersLevelOptions keeps a hand-written high level and
fills the others.

Run on mote: go test -run TestZCode ./internal/agent, ok. Broken by
hand: the kept options ignored and the budget left out, and those two
tests fail.
Not tried: a real ZCode 3.x (this Mac has Z Code 0.9.1, a different
app; mote has none), so ZCode putting the options in the body is the
reporter's and the author's reading of zcode.cjs, not seen here.

Batch record (gua's #2833 #3052 #3205 #3867 #4107 #4247 #4245 #4113
#3852 and the three review follow-ups; #4106 left out, its test isn't
red without its fix, see the issue):
- Full run on mote before the rebase (base fa4704f06): gofmt -l clean;
  go vet on darwin, GOOS=linux -tags nogui and GOOS=windows clean;
  go test -count=1 -timeout 45m ./...: 85 packages ok, internal/gui red
  in TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestMainWindowCorners/macOS_26_SDK (#3949), both already filed, and
  neither in a file this batch touches.
- Rebased on origin/main 9162277b9, at this tree, on mote: gofmt clean;
  go test -count=1 -timeout 45m ./internal/gateway/... ./internal/agent
  ./internal/library ./internal/handoff ./internal/routes, all ok
  (and ./internal/redact ok at the base before, b2145eac1). Then
  rebased again on ccb75030a (#4371, fastjson.go only) and
  ./internal/gateway/... run again at that tree: ok (636s). Pushed on 8ac1c7a56 (internal/catalog
  only), where catalog, handoff and library ran whole and the batch's
  gateway (Bili, TestRuleCompact, Kimi, TestClaudeMem, the two stall
  tests) and agent (TestZCode) tests ran: all ok. The whole gateway
  package was not run again on top of 8ac1c7a56.
- Windows (win-run): -run TestClaudeMem ./internal/gateway ok; with
  claude_room.go put back, TestClaudeMemRunsFromTheCgroup hangs in
  readLimit to the 5m timeout.
- Linux (wsl-run): ./internal/handoff ./internal/library ok; with the
  fixes put back, TestGiveKeepsTheListenerNonblocking,
  TestSaveDropsEmptyApplied and TestSyncAloneLeavesNoEmptyApplied fail.
Not tried: real Kimi, ZCode 3.x, Alma or bili accounts; #4245 is a
test-only change and was not reproduced red.
2026-11-01 10:26:42 +08:00
yetone 15ffd3b681 gateway: a compaction rule sees Alma's first compaction too (#2833)
Review of e72e97ef9: it knew Alma's compaction only by the ask of a
later one, "Merge the previous summary with the new conversation.".
Alma 0.4.335 (its app.asar, read on this Mac) has two: the first
compaction asks "Here is the full conversation to compact." under the
system prompt "You are compacting a long conversation so it can
continue WITHOUT losing context.", and a merge sends "You are UPDATING
an existing conversation summary ..." as its system prompt. The ask and
both system prompts are now known.

TestRuleCompactAlma also posts the first ask, and each system prompt
with an unrelated user message.

Run on mote: go test -run TestRuleCompactAlma ./internal/gateway, ok.
Broken by hand: the three new entries taken out, and the three new
cases go to the other rule (b/big).
Not tried: a real Alma compaction through magpie.
2026-11-01 10:22:57 +08:00
yetone 73528a9a03 gateway: x-bili- headers go only to a /bili/ URL of the user's own provider (#3052)
Review of 5d5a148ab: it sent every x-bili- header the agent sent to every
provider, Claude and Codex accounts and every vendor included. They are
the billion-context proxy's own headers, so they now go on only when the
request's URL is in bili's prefix form (http://host:8787/bili/<upstream>,
the form its README gives for putting it in front of a gateway and the
one the report uses), and never for a signed-in account.

TestForwardOnceKeepsBiliHeadersFromOthers: a plain URL, a URL with
/bili/ deeper in its path, and an account on a /bili/ URL get none.
TestForwardOnceCarriesBiliHeaders now posts to a /bili/ URL.

Run on mote: go test -run 'TestForwardOnce(Carries|Keeps)BiliHeaders'
./internal/gateway, ok. Broken by hand: the condition set to true, and
the new test fails for all three requests.
Not tried: a real bili proxy.
2026-11-01 10:22:57 +08:00
ggbdpq 9a951eb038 gateway: end the cgroup memory walk at "/" on every host (#4113)
What: the cgroup v2 walk read the path from /proc/self/cgroup with
filepath, whose separators and root are the host's. On Windows the
root is "\", so filepath.Clean("/"+dir) was
"\system.slice\magpie.service" and filepath.Dir stops at "\", which
is never "/": the loop read \memory.max and \memory.high until the
suite's timeout, holding internal/gateway with no result on Windows
(TestClaudeMemRunsFromTheCgroup, 45m). The cgroup path is a "/" path
whatever the host reads it on, so the walk is path's now (Clean, Dir,
and the label's Join); filepath.Join stays only for the limit file
under the cgroup root, which is a host path. On Linux and darwin,
where filepath's file is path's own code, nothing changes: the walk
reads the same files and the limits, and the "cgroup ..." label, are
byte for byte what they were.

Run: TestClaudeMemWalkEndsAtRoot is new: it runs memLimit("linux", a
fixture whose cgroup path is /system.slice/magpie.service) under a
one-minute watch and fails if the walk never ends at "/". On this
macOS machine it is green before the change too — filepath is path's
code there, so old and new cannot disagree on unix; on Windows it is
red before the change by construction (filepath.Dir of "\" is "\"),
and Windows is the reported host: the reporter's 45m stack at main is
the red this test gives there. With the change it passes, and
go test -count=1 -timeout 45m ./internal/gateway is green (461s),
-tags nogui green (464s); gofmt -l clean; go vet ./... on darwin,
GOOS=linux -tags nogui and GOOS=windows clean (the internal/gui cgo
warnings are main's); go build on the three.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 10:22:57 +08:00
ggbdpq 0d76d16ec6 test(gateway): let only the gateway's deadline end a stall's fake answer
What changed: the fake relays in TestStalledAnswerSaysUrlOrB64 and
TestVendorThatStopsMidAnswerIsSaid waited on r.Context().Done() with a
time.After(5 * time.Second) fallback of their own. Under load the fake's
5s could end its answer before the gateway's 500ms stall deadline
(drawUnit = 100ms) was acted on, so the gateway read a cut body and said
502 "isn't an images API's: unexpected end of JSON input" instead of the
stall's 504 (#4245). The fakes now wait on the context alone: the
deadline's cancel is what ends them, so the order can't flip. No product
behavior changes; both tests still assert the same 504 wording.

Run: go test ./internal/gateway -run
'TestStalledAnswerSaysUrlOrB64|TestVendorThatStopsMidAnswerIsSaid'
-count=5 - ok.
go test -tags nogui -timeout 45m ./internal/gateway/... - ok (500s).
go vet ./... and GOOS=windows go vet ./... - ok; GOOS=linux go vet ./...
fails in wails (undefined: pointer) at the base commit too.
CGO_ENABLED=0 GOOS=linux|windows|darwin go build -tags nogui . - ok.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 10:22:57 +08:00
ggbdpq 837ea5f565 gateway: a Kimi tool schema with items is an array, not its enum's string, as Gemini's is now (#3867)
yetone, #3867: kimiSchemaType and collectUntypedEnums read an untyped
schema's enum or const before its keywords, so a tool's
{"items":{"type":"string"},"enum":["a","b"]} reached Kimi typed "string"
with items beside it — the shape its Gemini sibling went out in until
d71362af made geminiSchemaType read an object's or array's keywords
(properties, items, keywordType) before its values, and Antigravity
turned that turn away over them.

- collectUntypedEnums: of an untyped node typed from its enum or const,
  its properties or items (keywordType, object or array) say the type
  first; a pattern's or minimum's string or number still loses to the
  values, as before (an integer enum beside a minimum stays integer).
- kimiSchemaType: the same keywords before the enum or const, a $ref's
  target included; the one its branches say unchanged.
- Whether Kimi refuses items on a string is not known (no report of it,
  no real Kimi request tried; #3867 leaves that to a real account); the
  two are kept apart either way, as Gemini's are.

Tests (kimi_schema_test.go): TestKimiToolEnumTypesItemsBeforeEnum, the
issue's shape through kimiToolEnumTypes and a $defs target with items
and a string enum through kimiToolRefTypes, an enum without items or
properties still typed from its values.

Run, in a worktree at upstream/main e056779a:
- go test -tags nogui ./internal/gateway -run
  'TestKimiToolEnumTypesItemsBeforeEnum' -count=1, before the change:
  FAIL (display typed "string" with items beside it, filter "string"
  with properties, the $ref's target "string"); after: ok, and
  TestKimiToolEnumTypes, TestKimiToolRefTypes and TestKimiLockedSampling
  pass as they were.

Fixes #3867

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 10:22:56 +08:00
ggbdpq 7bdf08f18d gateway: no type beside the $ref a Kimi schema's target is
kimiToolRefTypes wrote a type into each schema a tool's $refs reach that
has none. When the target was itself a $ref — zod writes one beside what
it changed of a reused schema, a format and a description among them, as
Codex's automation_update's targetThreadId reaches {"format":"uuid",
"description":"tt","$ref":"#/$defs/__schema1"} — the type went beside
that inner $ref, and Moonshot refuses one there, 400 "At path
'$defs.__schema14': when using $ref, type should be defined in the
referenced schema instead of the parent schema" (#3205), so every turn
failed though the tool is never called. The plugin side had the same bug
and fixed it in kimi-work 0.1.5.

The chain a $ref names is now followed to the schema it ends at, and it
is there the type goes, or nowhere when the chain ends at a ref to
nowhere or never ends: schemaTypes already resolved chains to say what
the type is, so only the place it is written moves. Codex's own
automation_update schema (the fixture its tests and magpie's root-union
tests share) goes as it was sent: its defs are notes beside a $ref to a
typed target, which Kimi takes.

Fixes #3205

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 10:22:56 +08:00
ggbdpq ee031e9539 gateway: a billion-context proxy in front of the provider gets the client's x-bili- headers (#3052)
What changed: forwardOnce copies the client's x-bili-* headers on to the
request it builds for the provider, by a biliHeader predicate beside
claudeCodeHeader and codexClientHeader — an x-bili- prefix, in the shape
of the anthropic-, x-stainless-, x-claude-code-, x-openai- and x-codex-
families already on the allowlist. The headers carry the cooperative
plugin's name, conversation and context window, never a key; a header no
family allowlists, and the client's own key, still stay off.

Why: forwardOnce builds the upstream request from nothing and copies only
allowlisted headers, so a client talking to a billion-context (bili)
proxy put in front of its provider lost the x-bili- ones that name its
cooperative session — bili then saw an anonymous session and injected a
duplicate set of compression tools beside the plugin's own (#3052).
Whether to generalize this into a per-provider "pass-through client
headers" setting, beside PassUserAgent (#1851) and a provider's own
Headers, is the maintainer's call; this change only admits the family
the issue reports.

Run: go test -run TestForwardOnceCarriesBiliHeaders ./internal/gateway
fails on the baseline with the three headers empty and passes with the
change (httptest, no network); ablation (product file back at baseline,
test kept) fails again. gofmt -l clean; go vet ./..., GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean; native, GOOS=linux -tags
nogui and GOOS=windows builds clean; go test -tags nogui
./internal/gateway green.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 10:22:56 +08:00
ggbdpq f0ff905167 gateway: a compaction rule sees Alma's compaction ask (#2833)
What changed: compactAsks in internal/gateway/compacting.go gains Alma's
compaction ask, "Merge the previous summary with the new conversation.",
which opens the last user message of Alma's compaction request. A group's
compact rule now matches it. No compactSystems entry was added: neither the
repository nor the report carries the opening of Alma's compaction system
prompt, so none is invented.

Why: compacting.go matched the compaction prompts of Claude Code, Codex,
OpenCode, Pi, Gemini CLI, Qwen Code, Minis and Kimi Code literally. Alma was
not in the table, so its compaction fell through to the intent classifier and
was routed by another rule's model, making every compaction cost more than
the group's compact rule intended. The ask sits at byte 0 of the user message,
well inside compactLead (2048), so one table entry recognises it.

Test: TestRuleCompactAlma drives a group whose rule 1 is compact and rule 2 is
tokens >= 1 through the gateway. With the fix the Alma request is answered by
rule 1's member and X-Magpie-Model says a/small; without it the request goes
to b/big. The same test asserts a long message that only quotes the ask past
compactLead is not a compaction; raising compactLead makes that assertion
fail, so the bound is what keeps notes from matching.

Run: go test -tags nogui -count=1 -run 'TestCompact|TestCompacting|TestRule'
./internal/gateway/ (ok, 2.839s); go test -tags nogui -count=1
./internal/gateway/ (ok, 344.144s); go test -race -tags nogui -count=1 -run
'TestCompact|TestCompacting' ./internal/gateway/ (ok, 2.172s); gofmt -l
internal/gateway/ (empty); go vet -tags nogui ./internal/gateway/ and with
GOOS=linux and GOOS=windows (all ok); go build -tags nogui ./..., GOOS=linux
go build -tags nogui ./..., and GOOS=windows go build -tags nogui -o /dev/null .
(all ok). Not tried against a real Alma client: the wording is quoted from
the report.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 10:22:56 +08:00
yetone ccb75030aa gateway: a held request body is known by where it is, not summed again (#4371)
Each of the dozen decodes, topMember reads and validity checks a request
body goes through summed all its bytes with maphash to find what
validMemo knew of it: about 5% of the gateway's CPU on long Codex
requests (#4371). A body being served (holdBody) is not written while
held, so longBody and jsonValid now know it by its address and length,
check and split it once, and keep that in heldBodies.long until it is
released, as factsOf keeps its facts. Any other long body is summed as
before.

Run on mote at this tree:
- gofmt, go vet (darwin, GOOS=windows, GOOS=linux): ok
- TestHeldBodyIsNotSummed, TestHeldBodyNotJSON, TestDecodeJSON*,
  TestRequestBodyRawValuesShareIt, TestTopMember*, TestWithoutTopMember*:
  ok 3 of 3 alone, ok under -race
- go test -timeout 45m ./internal/gateway: ok (609s)
- Broken by hand: held lookup skipped -> "a held 84077-byte body was
  summed 18 times"; release left the finds kept -> "a released body's
  finds were kept".
- BenchmarkHeldBodyDecodes (1.8MB Responses body held, 12 decodes plus 12
  topMember reads an op): 3.31ms/op before, 7.9us/op after, allocations
  the same (24/op).

Real use: sandbox HOME copied from the owner's, real DeepSeek account,
deepseek-flash, four turns of a 115-123KB history through
/v1/chat/completions with masking on: every reply HTTP 200 (three "ok",
one empty at finish_reason length, the model's reasoning using
max_tokens, as on the old binary).

Not run: the full ./... suite; a real Codex account; Windows and Linux
runs of the tests.

Picked onto 9162277b9 (3 commits, none in internal/gateway/fastjson.go); not run again there.
2026-11-01 09:59:21 +08:00
yetone 9162277b91 routing: Until used up stays on the next account once the first is used up (dzxx0496)
dzxx0496 on Discord: with free accounts one after another, the first used
up, requests went to the second; when the first renewed they went back to
it ("如果第一个恢复了,它又优先用第一个了"). No routing did what they asked:
In order and Smart both put the first back first.

A new routing, Until used up (drain, 用完再换): requests stay on one seat
until its quota is used up, then go on to the next in the list and stay
there. A seat counts as used up when its known allowance is at 100% or
it was refused for quota or credit (failQuota / failCredit, routes.Drained
called where the rest is recorded, so a failover inside one request moves
the pool too). A rate limit or other failure only passes it over while
it rests, as In order does. Each pool (a provider, a group/<id>) keeps its
own place; routes.Forget clears it.

Offered wherever a routing is picked: the provider editor, a group's row
menu and editor (app menu, no native select), the TUI, `magpie group set
<id> routing=drain` and a provider's routing=drain. Nothing defaults to
it, so no saved setting changes. SpentShareOf is 100 for it, as for In
order. Words in en, zh, zh-TW, ja and de (i18n.js and the routing
plugin's own), docs/subsystems and the site's start page (en, zh, ja).

Tests:
- internal/routes/drain_test.go: stays on the next when the first renews,
  through a rate limit, all used up, a seat gone, per pool, Forget,
  Drained after a renewal.
- internal/gateway/drain_test.go: a real request path with a fake upstream;
  k1 refused for quota, k2 takes over, k1 renews: drain stays on k2,
  In order goes back to k1. Red without the Drained hook (request 3 went
  to k1). A rate limit comes back to k1; drain is saved on a provider and
  a group.
- routing-drain.test.cjs: the Routing page's why and mode line in 5
  languages, 1100px and 420px, Chromium and WebKit; red on the old assets
  (20 of 20).
- routing-group-strategy, routing-save, builtins: the menu has 11 routings.

Run on mote (macOS) at origin/main 699ddf152 with this commit and its
two neighbours (nb5p chip, dzxx0496 renewal, dzxx0496 Until used up).
Pushed on b2145eac1, whose five commits since change app.css and app.js
only for a key row's chips; at the pushed tree gofmt, the gui, routes
and gateway vets (Linux nogui, Windows), TestCoreScriptBudget (core
1,532,891), the Drain Go tests and 11 GUI files (gateway-model-chip-
height, routing-drain, routing-renews-stay, routing-behind-why,
routing-group-strategy, routing-save, builtins, i18n-keys, gui-de,
gui-zh-tw, key-row-chips-fit) were run again: 190 of 190 ok.
- gofmt -l clean; GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./... and go vet ok.
- go test internal/routes, internal/gateway, internal/provider,
  internal/cli, internal/tui, plugins/rotation: ok; internal/gui's
  TestCoreScriptBudget ok (core 1,532,816 of 1,533,105).
- GUI: routing-*, builtins, gateway-model*, model-chip*, i18n-keys,
  gui-* and codex-credits-last in both engines: 2211 tests, 68 red,
  none new: model-chip-steady 20 (#4388), gui-ja's {agent} string
  (#4580), and 11 routing-* files under load (#4585, #3789, #3799).
  The same 11 files run alone at cdfdb62c6 were 32 of 116 red, and 26
  with the stack, the same tests but rule-remove, whose red languages
  vary run to run (9 cases, then 5). model-chip-steady was 20 of 20 red
  at cdfdb62c6 alone.
Earlier, at f811bf291 with the stack: go test -timeout 45m ./... had 82
packages ok, internal/gui red only on
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners/macOS_26_SDK (#3949). The whole GUI suite had 301
of 16930 red in 52 files. Those 52 files rerun had 272 red with the
stack and 276 at f811bf291 alone, the same tests.
2026-11-01 09:53:50 +08:00
yetone 699ddf1524 gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord)
gokoshiki wants a Codex subscription first, then an OpenAI API key, then
the subscription's credits. Until now an account at 100% that holds
credits either kept its place and spent them there (on) or was held
(off). This adds a third way per account, "last":

- settings: CodexCreditsLast []string, empty by default, so a setting
  saved before it keeps its order. provider.CodexCreditsLast,
  CodexCreditsMode and SetCodexCreditsMode(user, on|last|off);
  SetCodexCredits(on) still means "in its place" and clears last.
- gateway: candidate.creditsLast is true for such an account once a
  window for the model is used up and it is going on its credits (a
  call ChatGPT counts in no window stays in its place). restLast orders
  ready, then resting, then those, and marks Weighed.CreditsLast.
  restLast runs over the asides too, so such an account goes behind a
  provider's reserves (Accounts at once, 2c6b7c063) as well.
  lastBehind keeps In turn's next turn (after), a new conversation's
  spread (leastHeld) and a subagent's lead (readyForNew) from bringing
  it forward, and a kept conversation moves off it to one not on its
  credits (Affinity.Why "credits").
- CLI: magpie quota credits <account> [on|last|off]; alone it lists
  accounts set off and last.
- API: POST /api/settings/codex-credits takes {user, on, last?}.
- GUI: under a Codex account's Use credits, while on, a second switch
  "Only after every other account, key and fallback", in the Usage
  page's card and the tray panel's (both wrap it to its own line at 360
  to 900px), and the panel's folded brief says "On, after everything
  else". The Routing page's trace says why such an account is behind
  (aside, the kept conversation's why, the row tag). zh, zh-TW, ja, de.
  creditsButton and the new switch share creditsSwitch, and the Codex
  options' comments in app.js were cut, so the core budget holds with
  no raise (1,532,664 of 1,533,105).
- docs: reference.md (quota credits) and gateway-routing.md.

Tests:
- gateway: TestCodexCreditsLastAfterTheOthers (two accounts, In order:
  the one at 100% on its credits goes behind, the trace says so, and
  back in place when turned on), TestCodexCreditsLastAfterTheFallback
  (both accounts at 100% and set last: the API key the provider falls
  back to answers before either one's credits; with the credits in
  their place an account answers on them, as before),
  TestCodexCreditsLastNotKept (a kept conversation moves off it).
  All three red with creditsLast and lastBehind forced false.
- provider: TestCodexCreditsLastMode.
- gui: settings_keep_test carries CodexCreditsLast;
  tests/codex-credits-last.test.cjs (Chromium and WebKit, en zh zh-TW
  ja de; Usage at 900 and 440, the panel at 440 and 360, the folded
  brief, the Routing page's aside and why, every key in I18N). Red on
  the old assets (no .ar-credits-last).

Run at this change on origin/main c76bcaea7, on mote (pushed on fd70def82, whose
one commit since, fd70def82, changes only the Providers poll's Go
files in internal/gui):
gofmt clean; go vet of gateway, provider, gui, cli and settings ok;
their tests ok but internal/gui's #4514 and #3949, both on main. The
8 commits between d6aa9cdf6 and c76bcaea7 touch none of this
change's files.

Run at this change on origin/main d6aa9cdf6, Go 1.26.8:
- mote: gofmt -l clean; go vet ./..., and GOOS=linux and GOOS=windows
  go vet -tags nogui ./...: ok. go test -count=1 -timeout 45m ./...:
  85 packages ok; internal/gui red only on TestSettingsSaveKeepsWhatIt
  DoesNotSend's SearchAll (#4514), TestMainWindowCorners (#3949) and
  TestColdTurnsTaken (#4510), all three on main. TestCoreScriptBudget
  passes.
- WSL magpie-desktop, Playwright 1.62.0, both engines: codex-credits*,
  i18n-keys, gui-ja, gui-zh-tw, panel-options-fold, provider-at-once and
  every routing-* file: 2127 tests, 2064 pass. Every codex-credits and
  codex-credits-last test passed (26). The red files (gui-ja, 19 routing
  files) run again at this tree and at d6aa9cdf6, alike: 200 tests, 61
  and 57 red. gui-ja is #4580; the routing reds are timeouts and
  waits, on both. The one file red at this tree only,
  routing-request-model (WebKit 420px "the model is cut"), is 5 of 5
  green alone at both, and with six copies at once red at both (29 and
  27 of 30 here, 28 and 27 of 30 at d6aa9cdf6): a fixed 150ms wait
  after a resize, filed as #4650. Nothing this change adds to Routing
  draws unless an account is set last (fixtures don't).
- Earlier, at 3564eb04b (this change on 7428f3229), WSL: the whole GUI
  suite beside two other sessions' suites, 16944 tests, 16496 pass;
  its 102 red files again at that head and at 7428f3229, 444 and 425
  red. The files red at the head only, run alone: view-open-wheel,
  usage-accounts, add-button, usage-ledger-open-settled 0 red;
  view-wheel-after-click, view-wheel-unheard and context-map (#3488)
  red alone at 7428f3229 too. mote, the credits and i18n files: 172 of
  174, the two #4580 and a click timeout in quota-curve at load 148
  (alone 30 of 30).

Not tried: a real ChatGPT account at 100% with credits beside a real
OpenAI key; the order is shown with the gateway's fake Codex backend.
2026-11-01 09:08:07 +08:00