Commit Graph
96 Commits
Author SHA1 Message Date
yetone a19ecdea90 gateway: a relay's data:[DONE] ends the stream, so an agent that hangs up on it is not logged as 499 (#1978)
zhaoyaoyuan's relay ends its Chat stream with `data:[DONE]`, no space
after the colon, which SSE allows. holdWriter.see only knew
"data: [DONE]", so the try never counted as ended, and pi, which stops
reading at [DONE], was logged 499 "the agent canceled the request" for
a reply it had whole (48 of 58 requests through that relay).

streamEnds now lists every spelling a relay sends: data: with and
without the space, event: message_stop with and without it, and the
JSON type markers with and without a space after the colon (Python
relays write `"type": "message_stop"`). The SSE markers are anchored to
the start of a line, and the stream's first byte counts as one, so a
reply whose text quotes "data:[DONE]" no longer ends it (the old
unanchored "data: [DONE]" did).

Siblings: every other SSE reader in the gateway, middleware, redact and
library (sniff, sse.readSSE, ttft, streamEvent, loop_guard, member,
chattidy, textcalls, toolsearch, grok_*, gemini_signature, codex_limits,
qoder, provider/test.go) cuts "data:" and trims the space already, so
holdWriter.see was the only one with a spelling written in.

Not changed: an agent that hangs up on the finish_reason chunk, before
[DONE] (the repro script's --early mode), is still 499. The usage chunk
and [DONE] come after finish_reason in Chat, and the OpenAI SDK pi uses
reads on to [DONE].

Run:
- TestHangUpAfterStreamEndIsNotCanceled goes through the real Handler
  with an upstream that writes the reporter's stream tail and an agent
  that hangs up the moment [DONE] / message_stop reaches it. With the
  old streamEnds: chat unspaced, chat unspaced CRLF and anthropic
  unspaced FAIL "a reply the agent had whole was logged as 499 \"the
  agent canceled the request\", out=31"; chat spaced passes on both.
- TestHoldWriterSeesEveryStreamEnd cuts each stream at every byte. Old
  code: "chat unspaced cut at 1: ended = false, want true". With the
  markers unanchored: "text about DONE cut at 1: ended = true, want false".
- gofmt -l, go vet (darwin), GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on internal/gateway: clean.
- go test -tags nogui ./internal/gateway -count=1: ok (371s).

Not tried: the reporter's relay itself, or the built binary with pi.
2026-10-13 18:16:03 +08:00
yetone c8f103fac0 gateway: a conversation too long for the model reaches the agent at once, not retried as a rate limit (#1944, ASD-max)
The ChatGPT backend answers an overflowing Codex request with a 200
stream whose error event and response.failed say
context_length_exceeded. streamStatus read that through quotaWords,
whose "exceeded" matched, so it counted as a 429: the group's patience
asked the same member again 7-8 times and the account was rested,
while the agent never got the error that makes it compact.

quotaSaid(msg) is quotaWords minus anything tooLong(400, msg) already
calls an overflow. streamStatus checks tooLong first (-> 400), and its
429 case and claude_subscription.go's two quotaWords guesses use
quotaSaid. A real rate limit, an overload and a spent quota read as
before.

Tests (overflow_stream_test.go, from the real backend stream, its
safety_identifier redacted):
- TestStreamOverflowNotRateLimit: the overflow events are 400; rate
  limit 429, overload 529, usage limit 429 unchanged.
- TestCodexOverflowInGroupNotAskedAgain: the agent gets
  context_length_exceeded, the member is asked once, no rest.
Both fail on the old code. Ran: go test -tags nogui ./internal/gateway/
(full package, ok), go vet on darwin/linux/windows, gofmt -l.
2026-10-13 16:17:05 +08:00
yetone 419ef30219 gateway: Claude Code gets a safety refusal as Anthropic's own, and switches to its fallback model; how many more accounts are asked is a setting (#1925, DD on Discord)
DD on Discord: through magpie, Claude's safety filter refusing a turn never
makes Claude Code move to its fallback model, as it does on Anthropic's API.
magpie asked every other account and group member (#248), then told Claude
Code a 400 "<model> refused this request", which it takes as an API error.

Claude Code 2.1.296 switches on stop_reason "refusal" in a 200 reply (the
stream's message_delta or a whole message, stop_details giving the
category), and only with a fallback model set; a 400, Anthropic's
"Output blocked by content filtering policy" or magpie's, is never retried.

What changed:
- When nobody is left after a refusal, an agent on Anthropic's Messages API
  gets the held refusal itself, the vendor's 200 with stop_reason and
  stop_details, streamed or whole (holdWriter.handBack): keyed Anthropic
  providers, groups, the Claude subscription. Codex and Chat clients keep
  the 400, since an empty-looking whole reply makes Codex ask again.
- Settings' refusalRetries counts how many more candidates (accounts, then
  group members, another model among them) a refusal is asked of. Unset is
  every one, #248's behaviour (Koohoko asked for it); 0 hands it straight
  back. GUI: Settings > Models > Replies > "Ask again after a refusal"
  (Never ask again, 1, 2, 3, All), en/zh/zh-TW/ja/de. Global, no CLI:
  magpie has no general settings CLI (as noLoopGuard). Other 400s are still
  never asked again; refusals still rest nobody.
- disabled-models.test.cjs wheels to Enable, which the new row put past the
  window's foot at webkit de 420.
- Docs: reference.md "When the safety filter refuses", gateway-routing.md.

Run:
- go test -tags nogui ./internal/gateway (full, -timeout 40m: a first run
  hit the 10m default at load ~70 from other sessions), ./internal/gui,
  ./internal/settings; gofmt -l clean; GOOS=linux and windows go vet.
- GUI: refusal-retries-setting (en, zh, zh-TW, ja, de at 1100 and 420) with
  gui-zh-tw, gui-ja, gui-de, i18n-keys and every tab=models suite
  (disabled-models, images-*, loop-guard-setting, member-model-setting,
  search-*, searcher-pick, vision-mcp), chromium and webkit: 176 pass.
- refusal-retries-setting under load (8 runs at once, load ~200): first
  4 of 8 failed at en/ja 420, a press landing on the first save's "Saved"
  note over the row, then WebKit's wheel still moving the view as the
  press was measured. It now reaches each button clear of anything drawn
  over it (reader.cjs reach) and waits for the scroll to rest: 16 of 16.
Broken by hand:
- handBack off: TestRefusalRetriesNoneHandsClaudeCodeTheRefusal,
  ...CountsTheTries, ...Group, ...ClaudeSubscription and
  TestRefusalWithNobodyLeftIsAnError fail (400 "refused this request").
- count ignored: those plus ...CodexStillTold400 fail (the next key answers).
- GUI keep-on-omit dropped: TestSettingsRefusalRetries fails; the GUI test
  fails with All sent as undefined, and with the row not appended.
Not tried: a real Claude account's refusal, or Claude Code's fallback
switch end to end; the refusal shapes are from Claude Code's source and
Anthropic's docs.
2026-10-13 15:06:20 +08:00
yetone eba7187368 gateway, provider, cli, gui: a group can route By weight, each member's share set beside it (#1910, DD on Discord)
DD asked for weighted round robin as a group routing, next to In turn.
A provider's keys could already route by weight (#841). Groups could not.

What changes:
- provider: Group.Weights maps a member's spelling to its weight, 1 to
  1000. A member left out, or set to 0, weighs 1. SaveGroup accepts
  routing "weight". It also cleans weights the way it cleans fast and
  off: it strips :fast, drops weights of members that are gone and of
  members weighing 1, and refuses a weight below 0 or above 1000.
  Weights follow a member when it is renamed (RenameMember, Rename,
  RenameGroup) and survive Share/Import.
- gateway: planLevel treats each member of a weight-routed group as one
  unit: a model with its keys in its provider's order, or a nested group
  routed its own way. weightedUnits orders the units by smooth WRR on a
  round per group ("group/<id>"), sharing wrrPick with the keys. The
  round's pick goes first and the rest stay in member order for
  failover. A unit whose head is resting leaves the round. When a
  conversation is kept on another member (session/turn/cache/strict),
  the charge moves to that member (wrrSeat, wrrMove).
- cli: routing=weight (also weighted, wrr). weight=<model>=<n>[,...]
  sets weights and keeps the rest; weight= on its own clears them. The
  group view shows "· weight N" for each member.
- tui: By weight is in the group routing list.
- gui: the group editor offers By weight. Each member then shows
  "Weight N · S%", its share among the members that are on. Clicking it
  edits the number in place: Enter or blur keeps it, Escape cancels,
  and a value outside 1 to 1000 shows a warning. The trace header uses
  group wording for a weight-routed group. Strings are added in zh,
  zh-TW, ja and de.
- docs: reference.md, gateway-routing.md, and site start pages in en,
  zh and ja.

Run:
- go test -tags nogui ./internal/provider ./internal/cli ./internal/tui:
  ok.
- ./internal/gateway: ok in 988s with -timeout 45m. The first run hit
  the default 10m timeout at load average ~170. The test running at
  that moment had been running for 2s; it was not a hang.
- go vet -tags nogui on those packages, for darwin, GOOS=linux and
  GOOS=windows: clean. gofmt -l: clean.
- New group-member-weight.test.cjs: 8/8 in Chromium and WebKit, en and
  zh at 1100, en and de at 420. The WebKit de 420 case also passed six
  runs at once.
- gui-zh-tw, gui-ja, gui-de, i18n-keys, routing-*, group-*,
  panel-routing*, settings-groups and agent-model-groups: all green
  except two.
  - routing-steady (WebKit) is #1804. It is red 2/3 alone on origin/main
    e1b70c13d too.
  - routing-save-blank (chromium en) was red under load only, and 3/3
    green alone. The overshoot in its wheel loop is filed as #1924.

Broken by hand, each red, then restored:
- byWeight forced false:
  --- FAIL: TestWeightedGroup (weighted_group_test.go:69 its turn ...)
- cleanWeights call skipped:
  --- FAIL: TestSaveGroupWeights (groupweight_test.go:39 weights map[...
  an/claude-opus-5-5:0 ... oa/gpt-6.1-sol:high:fast:3 ...])
- CLI weight case renamed:
  --- FAIL: TestGroupWeightCLI (unknown field "weight")
- GUI chip not appended: group-member-weight chromium en 1100 timed out
  on the weight button.
- Not red: the test's "moved nothing" check. A scroll forced on click,
  or padding added above, did not turn it red, because the view's own
  scroll guard and scroll anchoring hold the clicked row in place. It
  only shows that the row stays under the pointer.

Not tried: real accounts through a running gateway. The routing is
proven by the plan-level test with synthetic providers only.
2026-10-13 13:10:30 +08:00
yetone 0c6752dbdf gateway: a too-long, shape or retired refusal read its Chinese escaped as \uXXXX too, and the translated thinking re-ask has its test (#1678)
Follow-up to ggbdpq's f16c1f7cd (#1678) after its review. Its four
sites now read wordsOf(body); three more deciders whose word lists hold
Chinese still matched the raw body, and one of its sites had no test:

- overflowed: an escaped 上下文长度超过限制 400 wasn't read as the
  conversation too long. It is called from retryable (now decoded) and
  from the candidate loop on the held error, so it decodes itself.
- shapeRefused: its negations (the quota and unserved words) missed
  escaped Chinese, so a decision group's raw postDecide body that also
  said 额度已用完 counted as a shape refusal and rested nobody.
- tooLongUnsaid: an escaped 该模型不支持 400 past the window was told
  to the agent as a prompt too long, as its quota and unserved checks
  read the raw body.
- forwardTranslated's alwaysThinks site had no test: breaking it left
  every test green. TestTranslatedThinkingOffRefused now carries the
  escaped #699 refusal.

Run (worktree on origin/main ebd7f4313 + f16c1f7cd + df4ea0ff6, sandbox
HOME, pinned caches): new TestEscapedWordsReadByEveryDecider passes
with and without escaping; each of overflowed, shapeRefused,
tooLongUnsaid and #1678's modelRetired put back to the raw body makes it
FAIL naming that decider ("上下文长度超过限制 not overflowed", "a shape
refusal that says the quota is spent rests nobody", "...told as too
long: prompt is too long ... (Fake answered 400: 该模型不支持当前令牌计划)",
"a retirement that says the quota is spent rests the model alone").
On main both sites now ask refusesThinkingOff (anthropic.go), which
reads alwaysThinks decoded since the rebase of f16c1f7cd; putting it
back to Match(b) makes TestTranslatedThinkingOffRefused/4 (and
#1678's passthrough test) FAIL with 400 "Fake: 该模型始终支持思
考,不可关闭". gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and
GOOS=windows go vet ./... exit 0. go test -tags nogui -count=1 ./...
(sandbox HOME): every package ok but internal/agent and internal/gateway,
which hit go test's default 10m bound at load average ~24 from other
sessions (the stacks show TestWSLMoreAgentsPick and
TestThinkingStreamsThroughGroup running for 2m and 2s, no hang); both
rerun alone with -timeout 40m: ok (gateway 669s, agent 600s).
2026-10-13 10:40:35 +08:00
ggbdpqandyetone 4ed379f116 gateway: error words escaped as \uXXXX are read by the other deciders too
What changed: #1669 taught failure(), resetsWritten and the per-model
rest's other-models check to read a JSON error whose encoder escapes
what isn't ASCII (Python's json.dumps does by default), but the other
word-list deciders still matched the raw body:

- modelRefused and modelRetired (fallback.go): an escaped 模型不支持
  refusal rests the whole key or account (a cooldown, longer on
  repeats) instead of the model alone (#1235's class), and the escaped
  quota words of their negation are missed the same way. The candidate
  loop's restAfterMarked feeds them the vendor's body as it arrived,
  and the decision group's decideFailed the raw postDecide body; a
  chat's rewritten error carries the decoded message, which is why the
  chat path was spared.
- retryable (fallback.go): an escaped 额度已用完 on a 400 reads as not
  retryable, so a decision group returns the error instead of asking
  its next decision model.
- alwaysThinks (gateway.go, both 400 learn-again sites): a vendor's
  escaped 思考不可关闭 refusal is not asked again with thinking left to
  the model (#699's class), so the agent sees the 400 every turn.

All three now match on wordsOf(body), as failure() already does.

Run:
- New TestAnthropicPassthroughAlwaysThinksInEscapedChinese sends the
  escaped refusal through /v1/messages: on the old code 400 after 1
  call (the re-ask not taken), with the change 200 after 2.
- New TestEscapedWordsReadByTheOtherDeciders: modelRefused(403, escaped
  模型不支持) and retryable(400, escaped 额度已用完) are false on the
  old code, true with it; the same refusals unescaped stay true.
- Both fail with the fix stashed, pass restored. go test -tags nogui
  -count=1 ./internal/gateway: ok. The named tests and the guards they
  touch (TestAnthropicPassthroughAlwaysThinksInChinese,
  TestModelNotInPlanRestsTheModelNotTheKey, TestFailureReadsEscapedWords,
  TestResetsWritten, TestWrittenResetRestsUntilThen) also -race -count=5:
  ok. go test -tags nogui -count=1 ./... under a temp HOME: ok.
  gofmt -l internal/ empty. go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean but the trayimage_darwin.go
  cgo -Wenum-conversion warning, as on main. Builds: darwin, linux
  (-tags nogui), windows.

Rebased by yetone onto main, where both learn-again sites ask
refusesThinkingOff (anthropic.go, #1465): the decoding moved there.

Co-authored-by: yetone <yetoneful@gmail.com>
2026-10-13 10:40:35 +08:00
雪莹ちゃん 8d224796aa gateway: an empty reply from Gemini/Antigravity asks the next member and rests no account (#1221)
A reply that said nothing is a failure of the model or request, not the
account: the account doesn't rest (lateRests skips emptyReply), and the
group's other members of the same model, likely to end empty too, are
asked last (matesLast) while the next member is tried.

From PR #1222 by SnowGlow-aww, reviewed at 9037dd84f. Put onto main
5b14ebf49 by hand: gateway.go's failover loop had main's codexReset block
(#1628) where this one goes, so the empty-reply branch follows it; the new
test file's trailing blank line (the review's only blocker, gofmt) is gone.

Run (-tags nogui, sandbox HOME, private GOCACHE):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows;
  build on all three.
- -race: TestGeminiEmptyReplyGroupFailover, TestLateRestsEmptyReply,
  TestGeminiEmptyRepliesAskedAgain, TestGeminiEmptyReplyIsAnError,
  Antigravity*, CodexReset*: pass.
- Broken by hand: the failover branch off -> TestGeminiEmptyReplyGroupFailover
  red; lateRests' emptyReply clause removed -> TestLateRestsEmptyReply red.
- go test ./...: all pass; internal/provider timed out at 10m under the
  machine's load (other suites running) and passed alone with -timeout 30m
  (666s). It's untouched here.
2026-10-13 08:54:20 +08:00
yetone a68d2ac944 gateway: a held stream lets through only text, reasoning or a call, so a 200 that only framed a reply fails over (#1418)
Aliceonly's trace on #1418: sub2api answered 502 "Upstream HTTP/2 stream
failed", then Codex account A answered 200, sent only the frames before a
reply, and failed server_is_overloaded 37s in. Five candidates after it
were never asked, and Codex ended the turn. The stream had been let
through (h.passing), so holdWriter.failed() was false and neither the next
candidate nor a replan was tried.

Two ways a frames-only stream went through:
- streamEvent's default was eventContent: any event it didn't know (and an
  item of a type said() didn't know) counted as the reply begun. Now only
  the events of each protocol that carry text, reasoning, a call or a
  reply's end (replyEvent) count; anything else is eventLead, held as a
  ping is. An unknown item counts only when it is a call or a tool's
  (web_search_call, server_tool_use, mcp_*). A stream that ends well is
  still released whole, so this can only delay, never drop, a reply.
- a reply under a Content-Type that says neither JSON nor a stream, once
  the agent had a stream's headers, went straight through when its first
  bytes were SSE (sseStart -> pass()). It is now held as a stream from
  there and read event by event.

Which event Codex's backend actually sent isn't in the trace; the test
uses a keepalive, response.rate_limits.updated and an unknown item type.

Run: go test ./internal/gateway -count=1, green (428s).
TestFramesThenOverloadedGoesToTheNext (new: 502, then 200 frames + unknown
events + server_is_overloaded, then a third member) and
TestStreamEventUnknownOnlyFrames (new) fail on the old fallback.go: the
overloaded stream reaches the agent and c is never asked.
TestHeldUnsureStreamPasses/KeptAlive now expect the stream held until its
first word, and TestHeldUnsureStreamFailsHeld (new) a failure among held
frames; all fail on the old code. Not tried against the real ChatGPT
backend.
2026-10-13 07:30:06 +08:00
yetone 3b4063e75e gateway: a 400 for a tool schema past a model's nesting depth goes to the group's next member (#1870)
OpenCode Go answered Claude Code's MCP tools on muse-spark-1.3-contributor
with 400 "JSON schema exceeds the maximum nesting depth of 10 levels", and
group/intent-auto returned it to the agent instead of asking the next
member. shapeWords didn't know the wording, so shapeRefused was false and
the error ended the turn. It now matches "schema exceeds the maximum
(nesting) depth" and "schema ... nesting depth". The schema isn't
truncated, nothing rests, and plain parameter errors ("Field required",
"not a valid type") and a 200 that mentions the depth still don't fail
over.

Run: go test ./internal/gateway -run 'TestGroupFailsOver' -count=1, green.
With the new alternatives removed, TestGroupFailsOverARequestShape fails
on both depth bodies and TestGroupFailsOverASchemaTooDeep gets the 400
back with b never asked (a 1, b 0).
2026-10-13 07:30:06 +08:00
yetone bf60d32bde gateway: a key set to a protocol its provider has no URL for is said on Routing and in the editor, not passed over quietly (#1702, edussss)
edussss set a relay key to Responses only on a provider with a Chat URL
and no Responses URL. perKeyBarred skipped the key (no endpoint for its
protocol), every key was skipped, so the provider was tried whole and the
request went out on Chat with nothing saying why. The owner: it shouldn't
fall back quietly.

Requests are still served on the URLs the provider has (so working setups
keep working), but now it is said:
- fallback.go: perKeyBarred remembers the protocol of the first key it
  skipped for having no URL, and the whole-provider candidate carries it
  as noURL.
- trace.go: Weighed.NoURL, so the Routing page sees it.
- routing.js: the row and the activity line say "key set to {api} only,
  no {api} URL · sent on the others".
- app.js/app.css: the editor's key row shows an amber "No {api} URL" chip
  (keyLacksURL) with a title that says how to fix it.
- i18n.js: the three strings in zh, zh-TW, ja and de.
- docs/subsystems/providers-accounts.md: the Keys row says so.

Run: go test -run 'TestKeyForAProtocolWithNoURLIsSaid' ./internal/gateway/
(the reporter's case: upstream /v1/chat/completions with k-resp, NoURL
"responses"; with an Any key added it goes to k-any and NoURL is empty);
key-nourl.test.cjs in chromium and webkit, en/zh/zh-TW/ja/de, at 420 and
1000 wide, no click-scroll, no sideways scroll: 40 pass; with i18n-keys,
gui-zh-tw/ja/de, key-copy, key-weight, key-weight-fit, key-import,
routing-key-windows, routing-keys-fold, proto-menu-overflow, nokey-editor
and ledger-protocol: 174 pass, 0 fail.
Broken by hand: without the noURL mark the Go test fails (noURL = "",
want "responses"); with keyLacksURL/noURLWord removed chromium fails 20
of 20.
Not tried: a real relay, or the GUI against a live gateway.
2026-10-13 07:07:18 +08:00
yetone 841af36bfc gateway: models the user disabled are refused on every route, and leave every list (#1867)
oxsean asked for one place to turn a model (claude-fable-5) off for good:
not reached by a direct request, an old session, a routing group member,
a fallback, a sub-agent, count_tokens or a decision model.

What changed:
- settings.DisabledModels: patterns, an exact id or a glob (* any run, /
  included; ? one), matched ignoring case against provider/model, the
  bare id and its last segment (provider/disabled.go). Empty by default,
  so nothing changes for anyone who doesn't set it.
- Lists: buildEntries (entriesOff) leaves a disabled model out of the
  catalog, so /v1/models, agents' model files and pickers, Codex's list
  and every group go without it; membersIn skips it as a member, Deciders
  as a decision model; codexModels drops Codex's own disabled slugs and
  codexListTag changes so Codex refetches.
- Requests (gateway/disabled.go): 403 "model <id> is disabled in magpie"
  in each API's error shape, at #882's choke points: serve (idOff),
  perKeyBarred (no candidate: group next member, provider Fallback),
  count_tokens and Gemini :countTokens, serveSystemOne,
  serveDecisionGroup and postDecide, draw/video/embeddings, and
  codexBackend for Codex's own bare models. A group with a member left
  goes on without it; one with none left is refused naming them. A bare
  id the catalog no longer has is refused as disabled, not 404. A Codex
  sub-agent pick onto a disabled model stays on its lead's model.
- An unreadable settings.json is never "none disabled": the list read
  last stays; with none read, every request is refused; nothing is
  written over the file.
- CLI: magpie model disable <model|glob>..., enable ..., disabled
  (list-disabled).
- GUI: Settings > Models > Disabled models: each pattern with the models
  it matches now and Enable; Disable... opens the model picker, which
  also takes a typed glob. Says only requests through magpie are covered.
  POST /api/settings/disabled-models; POST /api/settings keeps the list.
  Strings in zh, zh-TW, ja, de.
- docs/subsystems/gateway-routing.md: Disabled models section.

What was run (worktree at origin/main 091593f7d, private GOCACHE, temp HOME):
- gofmt -l clean; go vet on darwin (touched pkgs), GOOS=linux -tags nogui
  ./..., GOOS=windows ./... clean; go build ./...
- go test -count=1 ./internal/provider ./internal/gateway ./internal/cli
  ./internal/gui ./internal/settings: all ok (gui after adding the field to
  TestSettingsSaveKeepsWhatItDoesNotSend's fixture, which it asked for).
- node --test internal/gui/tests/disabled-models.test.cjs: 16/16 (chromium
  + webkit, en/zh/ja/de, 1100/420); neighbouring Settings > Models tests
  and i18n-keys: 131/131.
- Broken by hand, each turned TestDisabled* red: serve's idOff (404
  instead of 403), perKeyBarred's filter (fallback reached spare), the
  catalog filter (/v1/models and Codex list), countOff (count_tokens 200),
  postDecide's check (decision call went out).
- Not tried with a real vendor account or a real agent.

Ref #1867
2026-10-13 05:34:13 +08:00
yetone 908c910931 gateway, gui: Stays: Strict keeps a conversation on the account or key that answered it, even past its cap, and passes its error on rather than moving it (#1797)
miniers asked that a conversation never move to another account: a
move changes the account a vendor sees mid-conversation and loses its
prompt cache. Session affinity keeps the account while it can answer,
then moves on.

The new affinity mode "strict" (Stays: Strict) does what session does
for a new conversation. Once one has an account, strictKeep asks that
account alone (its other models too) and no other account, key or
provider:
- one resting or spent is still asked, and its error (429, 402, 5xx)
  goes to the agent rather than to the next candidate;
- one over a user cap is asked past it (plan's capped candidates,
  capHeldOnly);
- one held for credits answers 429 naming Stays: Strict rather than
  moving;
- one removed, turned off, barred or not allowed for the key counts as
  gone, and the conversation is routed as usual.
A last try that fails verification is not rested for a strict
conversation that had nowhere else to go.

Set in the provider editor and the Routing page's pool row (GUI, all
five languages), `magpie groups ... stays=strict` (strict-session,
never-move), and the TUI ("stays strictly"). Documented in
gateway-routing.md, reference.md and the site's start pages (en, zh,
ja).

Run:
- go test -tags nogui ./internal/gateway (-timeout 30m under load ~150),
  ./internal/provider ./internal/tui ./internal/cli: ok. The three
  TestStrictAffinity* tests fail on the code before this commit (200
  where 429 was expected, acct-2 answering).
- GUI: stays-strict.test.cjs, chromium and webkit, 900 and 560px, en,
  zh, zh-TW, ja, de: 30 of 30. On the assets before this commit it
  fails 15 of 15 in chromium. routing-*.test.cjs pass but for
  routing-steady's webkit 1.69px shift, which fails on the old assets
  too: filed as #1804.
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
  the push.

Not tried: a real agent conversation held on a real rate-limited
account.

Known and left: planLevel doesn't merge a nested group's sub.held, as
before this commit.
2026-10-12 23:16:54 +08:00
yetone b5d7f0574c gateway: image recognition and web search that magpie picks pass over a model out of its allowance, and ask none when every one is out (#1801, hibaliqya-yonma)
What was wrong: AutoVision (the model that describes images for models
that can't see) and autoSearcher (the model that searches for models
that can't) pick a provider and model before routing runs. They never
looked at routing's allowance state. That state covers accounts barred
at a usage cap, rests for quota or credit, and full key or subscription
windows. Routing then had one candidate and tried it all the same. Each
image or search was sent to the account that had run out and got the
same 429 again, while another provider with allowance sat unused.

What changed:
- fallback.go: spentModel(p, model, from, now). A model is spent when
  every candidate routing would try for it (perKeyBarred) is capped,
  resting for quota or credit, or has a full window (candidate.full,
  model-aware for pools). It also says when the first one is back. A
  rate rest doesn't count.
- search.go: smallModel goes through smallReady, which prefers models
  that aren't spent (pickSmall keeps the old choice among them).
  autoSearcher ranks a searcher with allowance before searchRank.
  modelSearch doesn't ask a spent searcher that magpie picked
  (searcherSpent), tries the others with allowance first, and adds why
  it skipped to its error. A searcher named in Settings is asked as
  before.
- vision.go: AutoVision ranks ready first, then tier and cost. When
  every describer is out it still names one, so seer and Described
  (which tell agents every model takes images) don't flip with a
  window. askVisionWith (gateway and MCP) answers an auto describer
  that is spent with the reason and when it is back, and doesn't call
  upstream. A describer named in Settings is asked as before.
- Image and video generation (AutoDrawer, AutoVideomaker) are left
  as they were.
- docs/subsystems/gateway-routing.md: new section, tests added to
  Verification.

What was run:
- New tests in side_spent_test.go: TestAutoVisionPassesOverOneOut,
  TestAutoVisionTierAmongThoseWithAllowance,
  TestSpentModelAcrossAccounts, TestVisionDoesNotAskSpentDescriber and
  TestSearcherPassesOverOneOut.
- Broken by hand three ways:
  - spentModel returning false: all five go red.
  - Only autoSpent's check in askVisionWith removed:
    TestVisionDoesNotAskSpentDescriber goes red (200 from upstream).
  - Only modelSearch's skip removed: TestSearcherPassesOverOneOut goes
    red.
- go test ./internal/gateway -run 'Search|WorkBuddy|Kimi|Vision|Spent|PassesOver'
- gofmt -l, go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  and GOOS=windows go vet ./... are all clean.
- Full go test -timeout 40m ./... in a sandbox HOME at load 66-100:
  47 packages ok. internal/gateway and internal/agent hit the 40m
  package timeout. Gateway also had failures, each filed:
  - TestOTelWaterfall* (#1794, fixed on main since).
  - TestCodexHeardWithinItsIdleTimeout (#1800).
  - TestIntentClassifierGroup (3.17s against a 3s bound, filed as
    #1813).
  All of them pass alone, and go test ./internal/gateway on its own is
  ok (982s).

Not verified: not tried with a real account that has run out. Windows
was only vetted.
2026-10-12 23:04:29 +08:00
yetone cb40e26ec2 gateway: a refusal's note keeps Anthropic's stop_details category and explanation, on the Routing page's try and in the agent's error (#1768)
jingchangshi's sessions got "claude-opus-5-5 refused this request (safety
filter: refusal) via Claude Code" 19 times, with nothing to say which of
Anthropic's classifier categories (cyber, bio, frontier_llm,
reasoning_extraction, general_harms…) it was. Anthropic sends that in
stop_details beside stop_reason "refusal"; magpie read only stop_reason.

Rather than the separate opt-in JSONL sink the issue proposes, the
category goes where every refused attempt is already recorded: the note
of that try on the Routing page, including a try a later key or group
member answered after, and the error the agent gets when nobody is left.
It is the vendor's own words, so nothing of the user's request is stored
anywhere new.

What changed:
- refusedDetail: "safety filter: refusal (category cyber: <explanation>)",
  the explanation whitespace-folded and cut at 200 characters; a null or
  missing category or explanation adds nothing, an unknown category is
  kept as given. Used for a streamed message_delta and a whole reply.
- stop_details is carried through the IR (Event.StopDetails,
  Result.StopDetails) from an Anthropic upstream's stream and from the
  claude CLI's stream-json (a Claude subscription), and written back into
  an Anthropic client's message_delta or whole reply, as
  safeguard_results already is.

What was run:
- TestRefusalKeepsStopDetails (stream, whole, nulls, absent, unknown
  category, long explanation), TestRefusalCategoryOnTheTry (refused key
  then an answering one: the refused try says "category cyber") and
  TestClaudeSubscriptionRefusalMovesToNextAccount (now with stop_details
  in the CLI's refusal) fail on the old code and pass now; the refusal,
  safeguard and Anthropic tests pass.

Not verified: no real Anthropic refusal with stop_details seen (the
bytes follow Anthropic's documented shape); a Codex or Chat client
served by Claude gets the category on the try only when the hold
writer sees it in its own protocol, which Responses and Chat have no
field for, so their try notes stay "safety filter: …" as before.
2026-10-12 22:42:46 +08:00
yetone ff930886a2 gateway: keys all out of their allowance are answered from their rests with a Retry-After, not asked again on every request, and a key listed twice is asked once (#1772)
A fleet on four Ollama Cloud keys, every one out of its weekly allowance:
each new request asked every key again (the first twice) and answered
429 with no Retry-After, so an agent that waits as told asked again at
once, and the vendor saw four refused requests a turn.

What changed:
- The first key twice: the reporter's providers.json named the first key
  in "keys" as well as "key". KeysOn now lists a key once.
- When every key left for a request rests out of its allowance (a 429 or
  402 that failure() calls quota or credit, keys only), the request is
  answered from the rest without asking: the vendor's own words, "not
  asked again before HH:MM", and Retry-After until the first of them is
  back (quotaHeld, soonestBack). Accounts are left out, so autoReset
  can still spend a reset for them; a 403 or 400 worded as quota is
  asked as before.
- The last key out of its allowance now rests as the ones before it do
  (before, the last one left was never rested), and a 429 the vendor gave
  no Retry-After for gets the soonest rest's end as one.
- A provider can set how long its keys rest when the vendor says nothing
  of when the allowance is back: quotaRest (minutes) in providers.json,
  or `magpie provider quota-rest <id> 7d`; default stays 15 minutes, at
  most 8 days. A time the vendor names (resets_at, Retry-After, a
  window) still wins. A GUI save keeps it.

What was run:
- TestAllRestingAnswersFromRest, TestFirstKeyListedTwiceAskedOnce and
  TestOwnQuotaRest fail on the old code (no Retry-After, keys re-asked;
  "dead-1 dead-1 dead-2 ok-3", the reporter's log); they pass now, with
  TestQuotaHeldOnlyForKeysOutOfAllowance, TestDeadChainWalksEachOnce and
  TestRestMinutes. The mock answers with the reporter's literal 429 body.
- go test -tags nogui ./internal/provider ./internal/gui pass. A gateway
  package run at load ~60 hit its 20m timeout mid-suite with only
  TestMaxRPM* red; those pass 8/8 alone here and on origin/main
  17c12621b (timing under load, filed as #1791).

Not verified: no run against real Ollama Cloud keys; quotaRest has no
field in the provider editor (CLI and providers.json only).
2026-10-12 22:42:46 +08:00
yetone 6c9048db51 gateway: a request asks only the resting member back soonest, not every resting one, so a failing member isn't hammered by each request (#1799, dbydd)
dbydd: a group's routing still goes over its members in order however
they have been failing, and with providers magpie can't read a quota
from, that is close to a DDoS of the ones that are down.

What was there: a failure rests the member (credit 30m, quota till its
reset, rate by Retry-After, anything else 1m doubling to 10m), and one
answer clears it. But restLast only moved resting candidates behind the
ready ones. Once the ready ones failed, every request went on to ask
each resting member in turn, so the rest kept nobody back: in an outage
of the whole group each request went to all N members, and the last one
again on its retries.

Now (probeOne, fallback.go): of the candidates resting, a request asks
only the one whose rest ends soonest (the first in order on a tie), at
its place. Every ready candidate is still asked in the user's order. A
lone candidate is always asked. A group that is down whole takes one
upstream request per request, and the backoff grows with each real
probe instead of each request. The trace still lists every member, the
resting ones with their rest. The same is applied where the other
paths go over candidates: count_tokens, embeddings/rerank, image
accounts (drawOnAccounts) and a group's System One decision models.
Codex autoReset still looks over the whole list (all), so a week used
up on every account still spends a reset.

Default on, no switch: it only reads rests the user's order already
demotes, and only within a rest's cooldown; once a rest ends, the member
is back at its place in the user's order. Each request still makes at
least one real upstream attempt and returns the vendor's own error.
Scoping: only rests are read, and a failure about the request's content
or its model rests no member (failShape, prompt, overflow, refused,
loop, auth, proxy...; a model refusal rests only restID), so neither
leaves a member out.

Borrowed from AxonHub's error-aware load balancing (looplj/axonhub,
docs/zh/guides/load-balance.md, ErrorAware), which dbydd pointed to: a
failed channel's score drops and recovers as its penalty decays, rather
than it being sent every request. magpie's rest and backoff already are
that decaying penalty; asking the one back soonest is how it recovers.
Not taken: a success-rate memory that keeps a member demoted after it
answers. One answer means it serves now, a flaky member already rests at
least a minute per failure, and holding it down past that would
override the user's order beyond a cooldown.

Unchanged: the last candidate still isn't rested by its own failure,
and the Patience rounds (#1418) and retries on the last one re-ask only
candidates already in the trimmed list.

Tests (resting_probe_test.go): TestGroupAsksOneRestingMemberNotEach
(three resting members, minutes apart: only the soonest is asked; with
a ready member, it then the soonest),
TestRetrievalGroupAsksOneRestingMember (embeddings),
TestLoneRestingMemberStillAsked, TestProbeOne. With
probeOne returning its input (the old behaviour), the first two fail:
"resting members asked map[a:1 b:1 c:1]".

TestSystemOneDecisionGroupFailsOver held the old behaviour (all
failing: kb, ka1, ka2 asked, ka2's 503 back); it now wants kb then ka1,
the one rested first, and ka1's 429 back.

Run: gofmt -l (clean); go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows); GOOS=linux -tags nogui and GOOS=windows go build;
go test -tags nogui ./... -timeout 40m under a sandbox HOME at load
average ~100: every package ok but gateway and agent, which hit the 40m
timeout mid-run (TestZenUnsupportedModelLeavesTheListAlone and
TestSnowNoProfiles running, a few seconds in), and plugin, where
TestNPMInfoDeadline hung on its own failed 2s check (filed #1808).
Rerun alone with -timeout 80m: gateway ok (1896s), agent ok (1811s),
plugin ok (746s). Not run: a real upstream outage, the Windows box;
count_tokens and image accounts have no test of their own.
2026-10-12 22:02:03 +08:00
yetone 34ce89945b gateway: an error that escapes its Chinese as \uXXXX is read as one that doesn't, for why it failed and when it's back (#1669, Natsumeretsu)
Every word list that decides why a reply failed (creditWords,
brokeWords, rateWords, plannedWords, usedUpWords, quotaCodes) and
af0558e6d's resetsWhen were matched against the raw body. A JSON error
whose encoder escapes what isn't ASCII (Python's json.dumps by default)
carries 用量 as 用量, so none of the Chinese words matched:
WorkBuddy's escaped refusal read as a 1-minute rate limit with no reset
time, Zhipu's escaped 1113 "余额不足…请充值" as a rate limit instead of
out of credit, a sub2api key's escaped "7天限额已用完" as a rate limit
instead of out of quota.

wordsOf is the one shared point: a JSON body containing \u has its
string values decoded and put after it, one to a line; any other body
is matched as it is. failure() matches its words on it, resetsWritten
reads the reset from it, the per-model rest's otherModels check uses
it, and the two creditWords checks beside failure() (fallback.go's
same-one retry, patience.go's busy) use it too.

Tests: TestResetsWritten gains the reporter's Chinese refusal escaped
(read, 3h16m2s) and escaped-but-cut-short (not read);
TestWrittenResetRestsUntilThen rests the escaped refusal's model until
then; TestFailureReadsEscapedWords: escaped Zhipu 1113 is credit,
escaped sub2api 7天限额已用完 is quota, escaped WorkBuddy is quota.
With wordsOf returning the body unchanged, all three fail.
internal/gateway passes; go test -tags nogui ./... under a temp HOME;
gofmt -l, go vet darwin, GOOS=linux, GOOS=windows on internal/gateway.
2026-10-12 03:30:25 +08:00
yetone 56bc93e9fa gateway: a 400 saying the user's location isn't supported goes to the next member or the fallback, and isn't told as too long (#1621, WardLu)
Antigravity (and Gemini, Code Assist) answer a request from an address
Google doesn't serve with HTTP 400 FAILED_PRECONDITION "User location is
not supported for the API use." retryable() only let a 400/422 through
for model, quota and credit wording, so a routing group stopped at the
member and the backup provider was never asked; Claude Code's turn just
ended. tooLongUnsaid could also read the bare 400 on a long request as a
context overflow.

regionWords now names the refusal: Google's sentence, OpenAI's
unsupported_country_region_territory code and its "Country, region, or
territory not supported" message. A 400/422 matching it is retryable, and
tooLongUnsaid leaves it alone. It is about the address the request went
out from (the machine, or the account's own proxy), not the request, so
the member is rested as failOther: the default 1 min backoff doubling to
10 min, never the 30 min credit rest or days. As WardLu set out, not every
400 is retryable: "location field is not supported", "Invalid value for
location parameter" and "messages: field required" stay where they were,
and a 200 whose text has the sentence switches nothing.

Run: go test -tags nogui ./internal/gateway/ (TestTurnDoneSaidAtTheTurnsEnd
red under load, the cause in #1629 and fixed in its own commit; everything
else green), -run 'Region|Shape|NoFallback|PayloadTooLarge|Fallback'
green; gofmt -l; go vet -tags nogui for linux, windows and darwin.
Without the change in fallback.go, TestRegionRefusalIsRetryable,
TestRegionRefusalIsNotTooLong, TestGroupFailsOverARegionRefusal and
TestFallbackOnRegionRefusal all fail.
2026-10-11 22:45:09 +08:00
yetone 0e89b090c1 gateway: Codex's auto-review on codex-auto-review goes through a ChatGPT account past its usage cap, since OpenAI made it free (#1593, hywang1230)
An account past the usage cap set on it in magpie was held for every
model, so Codex's auto-review on codex-auto-review was refused with
"usage cap reached" once the account reached its cap. OpenAI made
Auto-review free for every ChatGPT sign-in on 2026-10-06: the reviewer's
calls are counted in no usage window, so the cap, which keeps a share of
a window unspent, has nothing to keep for them.

capHeld now leaves the user's caps out for a Codex (ChatGPT) account's
call on codex-auto-review (freeOnChatGPT). Credits set not to be spent
still hold it at 100% of a window, as nothing says the backend answers it
there. A review run on another model, or any other model, is held as
before.

Verified:
- TestAccountCapLetsAutoReviewThrough: an account at 92% with a 90% cap
  takes codex-auto-review on Codex's backend path and as
  codex/codex-auto-review, and still refuses gpt-5.5 on both. With the
  exemption disabled it fails with the reporter's exact 429 ("usage cap
  reached: every account that serves "codex/codex-auto-review" ...").
- go test -run 'TestAccountCap|TestCodexNoCredits|TestWindowCaps'
  ./internal/gateway, gofmt -l, GOOS=linux/windows go vet -tags nogui.
- Not tried against the real ChatGPT backend with a capped account.
2026-10-11 21:00:28 +08:00
yetone 35eea09464 gateway: a provider routed its own way keeps that order inside a group that routes another way (kchen0x on X)
kchen0x had a Smart routing group with Antigravity (9 accounts, set to
按顺序) and a Business account. Requests still went to the 9th account, the
one renewing soonest. planLevel pooled every member's keys and accounts
into one list for any group not routed in order, so the provider's own
routing was never read; Smart then put the soonest renewal first.

Now a member whose provider routes other than Smart, and other than the
group does (ownRouting), is planned as a nested group already is: a unit
weighed by the first account or key it would try (firstAwake), then tried
whole in its own order. A provider left on Smart is pooled as before.
leastHeld, which reorders a rotate group's first request, leaves such a
group alone as it does one holding a nested group (without that, a
rotate group still came back "k2 k1 k3 kb").

GUI hint (GROUP_NEST, 4 languages), start docs (en, zh, ja) and
gateway-routing.md say so.

Run:
- TestProviderKeepsItsOwnRoutingInAGroup covers outer Smart, rotate,
  usage, pace and manual, plus a Smart provider still being pooled. On
  the old planLevel it fails with "k3 k2 k1 kb" (the reported order).
- go test -tags nogui -count=1 -timeout 40m ./...: all ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/gateway.
- GUI: i18n-keys, gui-ja/de/zh-tw and every *group*/*routing* test, both
  engines: 765 pass. A first run beside the full go test had 9 webkit
  timing reds (routing-group-fold, routing-keys-fold, routing-ctx-still,
  gateway-key-groups); each file passes alone, and the whole set passes
  when nothing else runs.
2026-10-11 19:54:55 +08:00
yetone c0a13dee3c gateway: a queued stream's agent, kept alive while it waited, goes on hearing a keepalive every 15s once the request goes to its vendor, not up to 30s of nothing
keepQueued keeps a streaming agent alive while its request waits for a
slot (MaxConcurrency) or for room in its minute (MaxRPM): past
keepHeldAfter it sends the stream's 200 and a comment every
keepaliveEvery (15s each). When the wait ends, keepQueued stops and the
try's watch starts, and watch only called keepQuiet once keepHeldAfter
(15s) had passed since it began, as if the agent had heard nothing yet.
An agent sent its last keepalive just before the handoff then went up
to keepHeldAfter + keepaliveEvery, ~30s, with nothing while the vendor
was quiet, twice the cadence magpie promises. Found while fixing
TestQueuedStreamKeptAliveForTheMinute's flake (4caae1c8).

watch now calls keepQuiet at once when the request's agent has already
been sent the stream's 200 (h.alive.sent), as keepQueued does;
keepAlive still paces the comments by keepaliveEvery since the last
one (a.at), so nothing is sent more often. scan's keepalive for a held
stream of frames takes the same condition. The 200 is already out in
that case, so the wait keepHeldAfter gave (a refusal still going to
another account with nothing sent) buys nothing.

The scan change is for the same rule in the other place that waits
keepHeldAfter; it isn't observable by itself, since watch's tick
keeps a held stream alive too. pauseAlive counts keepHeldAfter from the
request's start, not from a handoff, so it has no such gap.

Test: TestQueuedStreamKeptAliveOnceSentToItsVendor (chat, responses,
messages). The timing is injected, not waited for: keepHeldAfter
1.5s, keepaliveEvery 100ms, a 4s minute so the queued request is kept
alive before its handoff even when it arrives late under load, and a
vendor that stays quiet 1s on every request after the first. As
3f4287e6's tests do, it checks the gateway's own writes in order rather
than gaps a client measures (they stretch under load): wroteConn now
also logs every write on the agent's connection, and the vendor notes
when it answers. The agent must have been written to before the vendor
was asked, and again between the vendor being asked and its answer:
10 keepalives are due in that second, and the old watch, begun before
the vendor was asked, writes none until keepHeldAfter after it began.

Run:
- watch's change reverted by hand: all 3 subtests fail with "the
  gateway wrote nothing to the kept-alive agent in the 1.001s between
  the vendor being asked and its answer, want a keepalive every
  100ms"; with it, they pass.
- go test -race -count=5 -run TestQueued ./internal/gateway.
- gofmt -l internal/gateway; go vet, GOOS=linux and GOOS=windows go vet
  -tags nogui ./internal/gateway.
- go test -tags nogui -timeout 40m ./... under the suite lock.
2026-10-11 06:19:16 +08:00
yetone b1396d2360 gateway, provider, gui: a routing group of decision models answers /v1/systemone, failing over between them (ARNO on Discord)
ARNO asked for decision models to get the group feature too: /v1/systemone
took only "<provider>/<model>" (xxx/jev-latest), so one refusing key or
vendor failed the call with nothing to fall back on.

A routing group may now be of decision models alone (provider.Group.Decides,
provider/decide_group.go). SaveGroup refuses one mixed with models that hold
a conversation, a decision group inside a chat group, and patterns, rules,
classifier, effort, levels, fast mode or a member effort on it. It is kept
out of the agents' catalog (groupEntries), and a chat request to it gets a
400 pointing at /v1/systemone.

POST /v1/systemone with "model":"group/<id>" (or the group's id or name, as
GroupFor reads them) goes to serveDecisionGroup (gateway/decide_group.go):
- the members' keys and accounts are planned with planGroup in the group's
  routing order, resting ones last; perKeyBarred no longer drops a
  decision-only provider's keys (it speaks no chat protocol), so each key
  is a try of its own;
- a gateway key's model and account limits and pause rules hold as for chat;
- a retryable failure that isn't the request's own (shape/prompt/protection)
  rests the candidate via restAfter and the next is asked; a transport error
  rests it as a 502; the last one's answer and Retry-After are passed on;
- every try is a Try of one route in the routing log; one usage row for the
  answer.
A group classifier naming a decision group fails over the same way
(askDecisionGroup; systemOne now returns decideRefused with the vendor's
status, headers and body, and postDecide returns the headers).

The GUI group editor offers a group of decision models only decision models
(groups.deciders), a chat group no decision model or decision group, a new
one both, and a decision model's row has no reasoning picker (groupJSON
.decides). The TUI member picker and `magpie group add` follow the same rule.
#1514's plugin_decide_test and TestMixedDecisionProvider now assert a mixed group is refused and a group
of decision models saves. Docs: reference.md (routing groups),
gateway-routing.md, provider-plugins.md.

Run:
- go test -tags nogui -timeout 40m . ./internal/provider ./internal/gateway
  ./internal/gui ./internal/tui: ok
- new: TestSystemOneDecisionGroupFailsOver (httptest System One fakes: a
  provider with two keys answering 429 and 503, then a second provider
  answering 200: tries ka1,ka2,kb, both failures rested and ask by name
  goes to kb first; all failing passes the last answer on; chat to the
  group is 400), TestDecisionGroupClassifierFailsOver, TestDecisionGroup,
  TestGroupAddDecisionModels, TestMemberOptionsDecisionGroup,
  group-decide-members.test.cjs (Chromium and WebKit, en and zh; no new
  strings)
- each broken by hand and seen red: no dispatch (404), no perKeyBarred
  change (ka2 skipped), no classifier failover, no rest, decision group in
  the catalog, CLI resolver, TUI and GUI picker filters
- GUI: group-*, routing-effort*, routing-levels, routing-save*,
  routing-intent-entry, routing-manual, i18n-keys in both engines: 169 pass
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on the
  touched packages
- after rebasing on bc2496dca, the five packages again: ok. The first run
  had TestMaxRPMWaitsForRoomInTheMinute red once under load; it passed
  -count=3 alone and in the rerun, and nothing here touches rpm.go.
Not tried against a real TypeSafe or Bailian account.
2026-10-11 01:37:18 +08:00
yetone c60a5181c9 gateway: a free model OpenCode Zen serves no more leaves its provider's list and sits out alone, instead of resting the whole account (Jeremy.Zhou on Discord)
Zen now answers a model it has dropped (glm-5-free, kimi-k2.5-free,
any unknown id) with HTTP 401 {"type":"error","error":{"type":
"ModelError","message":"Model glm-5-free is not supported"}}, not the
410 ModelDeprecated modelRetired already knew. A 401 was failOther and
not modelRefused, so the account (for opencode-zen-free, its only one)
sat out with a backoff, every free model with it, and the gone model
stayed listed.

modelRetired now takes a 401 whose words are exactly "Model <id> is
not supported", in Zen's body or in the message the gateway puts it
into, so the existing path runs: provider.Retire takes the model out
of that provider's lists, modelRefused rests only that model, and an
answer later puts it back. Zen's AuthError ("Invalid API key.") and
"is not supported for format anthropic" (wrongEndpoint) are left as
they were.

Fixtures are Zen's literal bytes, read 2026-10-10 with the public key
(curl POST /zen/v1/chat/completions for glm-5-free, kimi-k2.5-free,
nonexistent-model-xyz; AuthError from a bogus key).

Run: go test -tags nogui ./internal/gateway -run 'Retired|ZenUnsupported'
(TestRetiredWords and TestZenUnsupportedModelLeavesTheListAlone fail on
the old fallback.go, pass now); full gateway package, gofmt -l, and
GOOS=linux/windows go vet -tags nogui ./internal/gateway before push.
2026-10-10 23:22:01 +08:00
yetone 53cce81664 gateway: Codex hears an event of its reply within its idle timeout while magpie holds its tries, instead of reconnecting on "idle timeout waiting for SSE" (fadenoob on Discord)
Codex counts only SSE events toward its stream idle timeout (300s by
default), not the ": keepalive" comments magpie sends while it holds a
try. Each try was bounded by itself (holdLead, 4 minutes since
1a5d7908), and a group's replan pauses (c43681d6) come between tries,
so held tries and pauses could add up past 300s with no event, and
Codex dropped the stream and reconnected. Reproduced against Codex's
own behaviour with a fake that sends only comments: the same error.

keptAlive now keeps the time of the request's start or its last event
(told) and whether the agent streams. For a streaming Responses agent,
once agentQuietMost (4 minutes) has passed with no event, the try in
hand is let through (scan, keepQuiet), and a replan or same-one retry
whose pause would end past the bound isn't taken, so the agent gets
the reply or the error in time.

Run: TestCodexHeardWithinItsIdleTimeout (agentQuietMost scaled to 1s;
a slow second member after a failed first: first event in ~1.0s,
bound 1.6s, old code 2.2s, red; every member overloaded with a 2s
replan pause: error reaches the agent in ~1.2s). Passed 3 times.
go test -tags nogui ./internal/gateway ./internal/provider ok; gofmt
-l clean; GOOS=linux and GOOS=windows go vet -tags nogui on both.
docs/subsystems/gateway-routing.md says the bound.
2026-10-10 18:54:16 +08:00
yetone 1a5d790814 gateway: a stream that has said nothing but its frames stays held while the agent is kept alive, so a server_is_overloaded after 15s goes to the group's next member (#1418, Aliceonly)
Aliceonly's trace: plus-B answered 200 with response.created,
in_progress and codex.rate_limits, nothing else, and 36s on failed the
response with server_is_overloaded. The holdWriter let any stream
through on the first write after holdLongest (15s), so the failure came
after passing was set: it reached Codex as the turn's end, and sub2api,
next in the group, was never asked.

A stream with nothing but its lead frames is now held as long as one
that is thinking (holdLead = holdThinking) when its agent is being kept
alive with SSE comments (keptQuiet: a streaming agent that isn't
Gemini). The comments keep the agent from timing out, so holding costs
nothing; a stream with content is let through as before, and a Gemini
stream, whose agent takes no comment, is let through at 15s as before.

Run:
- TestLeadOnlyStreamHeldWhileKeptAlive (new): fails on the old code with
  "let through after 15s with nothing said" (checked by putting the old
  hold back), passes now.
- go test -tags nogui ./internal/gateway under a temp HOME: ok.
- gofmt -l internal/gateway: clean.
2026-10-10 17:49:07 +08:00
yetone 8424a004e2 gateway: a reply whose reasoning loops before it says anything is asked again once in place, not ended (cdredfox on X)
cdredfox (X, 2108799237324701897): WorkBuddy AI's DeepSeek v4 flash through
magpie often stops half way with "magpie ended this reply: the model's
reasoning was stuck in a loop ... ("OK." "Writing." "Now." "Producing."
"Let me output." ...)". That is the #1359 loop, found correctly; nothing
magpie sends causes it (12 direct runs on the real account, effort
high/max, temperature 0/1/unset, a 900-line file: no loop, the same
"OK. Writing." precursors at the tails), so the model does it on its own
now and then, and the agent's turn ended on it.

When magpie translates the reply into the agent's protocol
(streamTranslated: Claude Code, Codex, Gemini clients) and the loop is in
the reasoning, before any text or call and not on a continuation, the
try is let go and the same request asked again once (loopReasks), the
way an empty reply is (#667): the agent keeps the reasoning it has, the
next try's follows in the same stream. A loop on that try ends the reply
with the error as before. holdWriter.onLoop lets streamTranslated take a
trip before cutLoop ends the stream. A text loop, a loop after a text or
call, and a Chat stream passed through stay ended at once.

Run: go test ./internal/gateway (ok); -race on the loop and empty-reply
tests -count=3 (ok); gofmt; GOOS=linux,windows go vet. On old code
TestReasoningLoopIsAskedAgain and the updated
TestLoopEndsTheReplyOnEveryProtocol/TestLoopEndsWorkBuddysReply fail
(the vendor is asked once). Real account: a sandbox gateway in front of
a proxy signing for WorkBuddy AI (deepseek-v4.1-flash); the proxy
injected the reporter's units into the first real stream, the guard let
it go after 257 lines, the second real request answered, and the agent
got one whole message (Anthropic: message_stop, no error; Responses:
response.completed).
2026-10-10 14:51:42 +08:00
yetone 0311c720c1 gateway, provider: a model its vendor answers is deprecated leaves that provider's lists until it is answered again, and the next member is asked (MOMO on Discord)
MOMO's /v1/models listed opencode-zen-free/exo-free, and a request for it
got 410 "Model exo-free has been deprecated.". OpenCode Zen's own
/zen/v1/models still lists exo-free (checked 2026-10-10), and models.dev
gives it no deprecated status, so the zen-free plugin's discovery keeps it
and a refresh of the list would bring it straight back. No preset
hardcodes it.

What changed:
- fallback.go: retiredWords / modelRetired: a 400, 404, 410 or 422 saying
  the model is deprecated/retired (Zen's "ModelDeprecated", OpenAI's
  "The model ... has been deprecated"), without quota words. It is
  retryable (410 wasn't), and modelRefused, so only that model rests.
- gateway.go: such an answer calls provider.Retire(provider, model);
  routing.go: servedCandidate calls Unretire.
- provider/retired.go: retired.json beside providers.json, re-read by
  mtime; Retire/Unretire touch the catalog so agents' lists are written
  again. buildEntries leaves a retired model out, for that provider only,
  for at most a week. provider/model requests are still sent.
- docs: gateway-routing.md failure handling, reference.md.

Tests: retired_test.go with Zen's literal 410 body: the model leaves
/v1/models while the provider's other model stays; a group falls over to
the next member and only the 410's provider is marked; modelRetired
cases. All three fail with the hooks reverted.

Run: gofmt -l; go vet -tags nogui on darwin, linux, windows for provider
and gateway; go test -tags nogui ./internal/provider ./internal/gateway
./internal/agent ./internal/catalog in a sandbox HOME.
2026-10-10 05:40:28 +08:00
yetone 69c21cdd77 gateway, settings, gui: a reply whose reasoning or text has become a loop of the same few lines is ended with an error the agent can act on, instead of running on to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash at max effort reasoned "Now." "Writing." "Go." "Let me write." "OK." "Producing." … until max tokens, while dsh waited and Pi hung)
holdWriter.Write, which every streamed try goes through (passed through or translated; a key's, a built-in subscription's, or a plugin's fetch, as a moved WorkBuddy's), feeds a loopGuard (loop_guard.go). It reads the reasoning and the text of each protocol's deltas (Anthropic, Chat, Responses, Gemini) and cuts each into units: lines and sentences, compared without case or a closing stop. A list's "1." or a decimal doesn't end a sentence. A unit with no word in it (braces, rules, 0x00, hashes, rows of numbers) isn't counted. When the last 256 counted units of either are among 24 or fewer distinct ones, the try is cut. What came with that write goes out, then the protocol's stream error (Anthropic error event, Chat error chunk, Responses response.failed server_error, Gemini 502 UNAVAILABLE), naming the loop and quoting its units, and the vendor's request is cancelled. The cycle needn't be exact; the reporter's has 9 units in two variants. It falls back to nobody and rests nobody (fail "loop"), and the usage record's err_type is reply_loop. A reply sent whole (no stream, or Gemini without alt=sse) isn't read. Settings › Models › Replies › Stop looping replies (noLoopGuard, on by default) turns it off; new strings in zh, zh-TW, ja and de.

Tested:
- loop_guard_test.go, with the screenshot's 28 lines cut into random 1–7 byte pieces, as one line, and in Chinese. It trips within the window. It reads every protocol's shapes, and tool-call arguments never trip it.
- No trip on magpie's own sources fed as both reasoning and text: gateway.go, fallback.go, anthropic.go, app.js, i18n.js, app.css, routing.js, sessions.js, index.html, docs, LESSONS.md and go.sum. Nor on generated numbered lists, logs, CSV, hex, rules and base64.
- Through the gateway on all 4 protocols with a fake DeepSeek, and on WorkBuddy both built-in and through the community plugin's fetch in the plugin host (TestLoopEndsWorkBuddysReply). In each case the agent gets the reasoning and then the error, the vendor is let go within 2000 lines, nobody rests, and usage keeps reply_loop.
- gateway.go as 4,900 lines of reasoning passes whole on every protocol. With the setting off, a loop runs to its end.
- With the guard removed, the end-to-end and WorkBuddy tests fail on every route.
- The built binary (magpie serve on 127.0.0.1:3592, temp HOME, fake DeepSeek upstream), checked with curl on chat, messages, responses and gemini alt=sse. Each loop ended with that protocol's error, the upstream was let go after 256–271 lines, and the usage log had err_type reply_loop and routing fail "loop". The long gateway.go reasoning came through to [DONE], message_stop, response.completed and STOP. With noLoopGuard, all 100,000 lines passed.
- GUI: loop-guard-setting.test.cjs in Chromium and WebKit, en/zh/ja/de, at 1100 and 420 wide. gui-ja, gui-de, gui-zh-tw, i18n-keys, member-model-setting, click-scroll and settings-sections/groups pass.
- go vet, GOOS=linux/windows vet and builds, go test -race ./internal/gateway ./internal/settings, and the full go test -tags nogui ./... all pass.

Not tried with the real WorkBuddy or DeepSeek model.
2026-10-09 22:32:31 +08:00
yetone 34a598372c providers, gateway, gui, cli: each usage window of an account can have a cap of its own beside the account's (willz on Discord)
willz asked for a cap per window: a friend's account should stop at 50%
of its five hours, while its week has its own 40%. Until now an account
had one usage cap, the same share of every window.

What the user sees: the account's pill still sets the cap for all its
windows and stays the default. Each window's meter on the account's row
is now a button: a click opens the app's own menu headed "Cap for
<window>" with the account's cap, No cap on this window, 50–90%, and
Other… typed in place. A window with its own cap says it beside its
figure ("Cap 50%", or "No cap"), its mark sits there, and the account's
pill says "Caps by window" when only windows have caps. The account is
held while any window is past its own cap, and the row's note, the
gateway's 429 and the Routing trace name that window's cap. CLI:
magpie provider account-cap <id> <account> --window "5 hours" 50
(none: no cap on that window; default: back to the account's), and
`account-cap <id>` lists the overrides.

How: Provider.AccountWindowCaps (providers.json, by account and the
window's capId, its name in lower case; 1–99, or 100 for none) beside
AccountCaps. provider.WindowCaps gives a window its share (its own, else
the account's); Allowance.CapHeld and capReached judge each window by
its own share and report the fullest holding window's cap.
provider.HoldShare becomes HoldCaps, used by gateway capHeld (plan and
group filtering, cappedError, trace) and codex_backend's route-or-relay
choice; codex_switch's NextLogin moves the agent off at per-window caps.
QuotaWindow carries capId; Limit.name is exported as Limit.Name. A
config with no window caps reads and routes exactly as before
(TestSetWindowCap reads an old one). The meter is a span with
role=button, Enter/Space: a <button> as a flex item of the wrapping
meter line kept WebKit's row at its one-line height until the next
layout, so the row grew under the pointer at the first click.

Verified:
- go test -tags nogui ./... in a sandbox HOME: all ok. New
  TestWindowCapHeld and TestSetWindowCap (provider), TestWindowCapsHoldTheAccount
  through the real gateway (5h 60%/cap 50 goes to the spare; 20/30 under
  50/40 is used; 20/45 with the spare past its own cap is a 429 naming
  "past its 40% cap"), TestAccountCapCmd --window cases.
- Break check: with WindowCaps.Of ignoring the window's own share,
  TestWindowCapHeld fails ("5 hours at 60% of 50%: <nil>") and
  TestWindowCapsHoldTheAccount fails (the request is answered 200 by the
  capped account).
- internal/gui/tests/window-cap.test.cjs: Chromium and WebKit, 420 and
  1100 wide, en, zh, zh-TW, ja, de (60 tests): held note per window,
  marks, menu from the meter with no native select, keyboard, posts of
  50, typed 45, 100 and 0, no page scroll on a click, no sideways scroll,
  no left border stripes, every new string translated. With
  windowOwnCapOf returning 0 it fails.
- account-cap, gui-zh-tw, gui-ja, gui-de, i18n-keys pass; full GUI suite
  in both engines (483 files, concurrency 6): 4315 of 4323
  pass; the 8 that failed (library-servers-bulk, purpose-filter,
  routing-proxy, routing-zcode-blocked) touch no account row and all 32
  of their tests pass when run alone
- gofmt -l clean; go vet -tags nogui ./... on darwin, linux and windows,
  and windows without the tag for ., internal/gui, internal/provider,
  internal/gateway; go build ./...
- Not tried in the real window with a live gateway or real accounts.

Docs: gateway-routing.md (HoldCaps, window caps, tests),
providers-accounts.md (AccountWindowCaps, tests), reference.md.
2026-10-09 12:00:26 +08:00
yetone 24bef0f9be gateway: a streamed request waiting for its key's slot (Concurrency) or for room in its minute (Requests per minute) has its agent sent the stream's 200 and SSE keepalives after 15s, as a held try's stream is, instead of nothing until it is sent (coeo91 on Discord: WorkBuddy, Trae and Qoder said it timed out)
serve's try took its lane slot and waited for the minute (04704111)
before holdWriter.watch started, so for up to 2 minutes (or QueueWait,
unbounded by default) the agent got no status, no headers, no byte.
keepQueued runs beside lanes.take and rpms.wait: past keepHeldAfter it
sends the stream's 200 and ": keepalive" comments every keepaliveEvery
(keepAlive, the mechanism held tries already use; none for Gemini, #934).
Once they are out the try is held, so the vendor's error, or the queue
turning it away, reaches the agent as its protocol's stream error
(failTo: Chat's error chunk, Responses' response.failed, Messages'
event: error), and the next candidate still answers in the same stream.
A wait shorter than keepHeldAfter sends nothing: its 429 keeps its
Retry-After. Non-streamed requests are unchanged.

What the agents do with it (read from their app bundles, not tried live):
- WorkBuddy 5.5.6 / WorkBuddy AI 5.6.2 (codebuddy-headless.js): no
  header timeout, first-token timer 20 min, so a 2-minute queue alone
  doesn't time it out there.
- Qoder 0.4.3: 60s to headers, then 60s more after them; its SSE parser
  drops comment lines, so keepalives don't extend that. Headers at 15s
  give it 75s instead of 60s; longer waits need firstPayloadTimeoutMs.
- Trae: its agent is downloaded at runtime and wasn't read.

Verified (Linux, golang:1.26.8 in Docker):
- queue_keepalive_test.go through lanGuard(New().Handler()), with an
  agent whose connection gives up after 400ms of silence: a request
  queued 1.2s for the minute (chat, responses, messages) and one queued
  for a Concurrency slot get 200, keepalives, then the reply; a vendor
  500 after keepalives is each protocol's stream error; a QueueWait
  waited out is the stream's error naming the limit; a short wait is
  still a plain 429. With keepQueued taken out, every one but the 429
  test fails with "i/o timeout". TestQueuedUnheldTryHeldOnceKeptAlive
  fails without the hold (": keepalive\n{\"error\":...}" in the stream).
- go test -tags nogui ./internal/gateway: ok (122s).
- go test -race on internal/gateway the way CI runs it (go test -race -c,
  build/race-shards.sh over 14 processes, -test.timeout=20m): 1258 tests,
  every shard ok. A single serial -race process passes 10m's default
  timeout, which is why CI shards it (#923).
- go vet -tags nogui ./internal/gateway for linux, windows and darwin;
  gofmt -l clean. After rebasing on 5e17a183: TestQueued, TestBurst,
  RPM, TestQuiet and TestSilentHeld under -race, and linux vet, pass.
2026-10-08 23:13:12 +08:00
yetone 3aeb7d1bf8 gateway: a model a key's plan doesn't serve rests that model alone, not the key (#1235)
SenseNova answers a Token Plan key asked for deepseek-v4.1-flash with
403 "model is not available in the current token plan" while the same
key serves deepseek-v4-flash. That refusal was a plain failure: it
rested the whole key, its backoff counted per key and doubling up to
10 minutes, so an agent that kept asking for the model left every key
of the provider resting for every model (Sun1090: both keys "失败 · 9
分钟后恢复").

A 400/403/404/422 whose body says the model isn't served
(unservedWords), with no quota, credit, rate-limit or channel words,
now rests only that key's or account's model (modelRefused, keyed by
restID, which is now restKey/model for every candidate), its backoff
counted by the model and cleared when the model answers. The key's
other models stay first in order, and its row shows no rest.

TestModelNotInPlanRestsTheModelNotTheKey (two keys, four requests for
the refused model, SenseNova's error shape) fails without the change:
"key One rests for a model its plan lacks: {Why:other Status:403 ...
By:backoff Failures:3}" and "deepseek-v4.1-flash doesn't rest". With
it: go test -tags nogui ./... under a temp HOME passes; -race -count=5
over TestModelNotInPlan|TestSeveralKeys|TestFallback|TestRouting|
TestPool|TestGroup passes; go vet (darwin, GOOS=linux, GOOS=windows,
nogui) passes. Not tried against a real SenseNova key: the body's
"code" field in the fixture is a guess; the message is the reporter's.
2026-10-08 12:26:53 +08:00
yetone 814dca9390 gateway: the ChatGPT backend's 502 "response protection is unavailable" is the request's, not the account's: asked once, no account rests, and a magpie-model compaction refused so is asked again as text (vs on Discord)
A long Codex conversation's compaction refused so went to every ChatGPT
account in turn, each rested on a growing backoff, then the last was asked
twice more: 5 upstream tries per Codex request with 3 accounts, times
Codex's own retries. Now the provider's other accounts and models are
not asked it, nor the same one after a moment; another vendor left in a
group is asked once. A reply broken off with it rests nobody either.
codexCompact falls back to plainCompact on it, as vs's control experiment
(the same history as text) was answered.

TestProtectionRefusalAskedOnceNobodyRests fails on the old code with
"asked 5 times ([acct-1 acct-3 acct-2 acct-2 acct-2]), not once" and two
accounts resting; TestProtectionRefusedCompactionAsText with status 502.
The error body's exact bytes are not the reporter's; no real ChatGPT
account was tried.
2026-10-08 11:34:33 +08:00
forever d151c10839 gateway: a whole reply after keepalives reaches the agent as its stream, not as an "OK" error (#1175)
Sometimes a held try's vendor says nothing for longer than keepHeldAfter.
keepAlive then sends the agent the stream's 200 and SSE comments. On the
passthrough path the vendor could then ignore stream:true and answer 200
with its reply whole. The try wasn't a failure, so release() told it to
the agent as the stream's error, "OK: {...the reply...}", and the agent
lost a reply that was billed. Found by reading the code, then reproduced
for Chat, Responses and Anthropic, in a group and for a lone provider.

Once the agent has a stream's headers, release() now sends a whole 200
reply as that protocol's stream (wholeAsStream). Each choice, output item
and content block is sent in the events that stream it, as the vendor
wrote it:
- text, with its citations (Anthropic citations_delta, Responses
  output_text.annotation.added)
- reasoning summaries, and thinking with its signature
- tool calls, refusals and stop details
- usage

A 200 under any type other than JSON or SSE is held too. Before, a
text/plain reply was written raw into the SSE stream. Its first bytes
decide (sseStart). If its first line begins with an SSE field, it was a
stream all along under the wrong type, and it goes through as it comes,
as before. While those bytes have yet to come, the agent is still kept
alive.

A 200 that is no reply of the protocol's now fails in settle(), the way
a translated reply that didn't stream does (502, "... did not stream").
The next member answers. On the last member the agent gets that error
and the request is logged as a 502.

Gemini gets no keepalives, so this changes nothing for it.

Verified:
- Each new test fails on the code before its fix and passes with it:
  - TestQuietWholeReplyStreamed covers Chat, Chat as text/plain,
    Responses, Anthropic, "not a reply" and "a stream as octet-stream".
    Before the fix the first four get "error:OK: {...}", or nothing for
    text/plain. The octet-stream case is the regression found on
    review: its stream was buffered and failed over.
  - TestQuietNotAReplyLastFails: before the fix the agent got the OK
    error, logged as 200.
  - TestWholeAsStreamClientReads and TestWholeAsStreamResponsesCitations.
  - TestHeldUnsureStreamPasses covers prefixes split across writes,
    id:/retry: first, and a whole reply.
  - TestHeldUnsureKeptAlive.
- go test -tags nogui -race -count=20 on these tests together with
  TestQuiet|TestSilentHeld|TestKeepAlive.
- go test -tags nogui ./internal/gateway, and the prebuilt test binary
  with GOMAXPROCS=2.
- go vet ./....
- go build, GOOS=linux go build -tags nogui, and GOOS=windows go build.
- go test -tags nogui ./... under a temp HOME.
- The synthesized streams were also fed to openai-node 7.30.0
  (chat.completions.stream, responses.stream) and @anthropic-ai/sdk
  0.131.0 (messages.stream, beta.messages.stream). Each accumulated the
  whole body's reply field for field.
- Not tried against a real vendor that ignores stream:true.
2026-10-08 06:48:48 +08:00
yetone 443f1cbc2d gateway: a held stream's first keepalive reads only magpie's notes until the vendor's reply has its status, so it never races the try writing the reply's headers
go test -race ./internal/gateway failed in TestQuietStreamsKeptAliveEveryProtocol
(chat held) with six data races: keepAlive, on watch's goroutine, sent the
held stream's 200 with the try's headers by iterating holdWriter.header,
while the try's goroutine wrote that map with no lock: noteMember (#822's
X-Magpie-Provider/Model) and passthrough copying the vendor's headers in.
In production, a vendor that answers only after keepHeldAfter does the
same, and outside -race that can end the process with "concurrent map
iteration and map write".

Before the try has its status (WriteHeader, under mu), keepAlive now sends
only magpie's own notes, which noteMember sets under mu (holdWriter.note);
the vendor has said nothing yet, so nothing of its is lost. It also clones
what it copies, so the agent's header shares no slice with the try's.

TestKeepAliveBeforeTheVendorsHeaders (a try writing its headers while the
first comment goes out) reports the race on the old code (2 of 3 runs);
-race -count=20 passes, and so does the whole package under -race.
2026-10-07 03:58:27 +08:00
yetone 555f570660 gateway, provider: the Routing page says what a lone key or account has left, and a key bought as a plan (Kimi Code, GLM Coding Plan, MiniMax, OpenCode Go, Command Code) is weighed by its plan's windows (#1016, gphysign: Kimi Code (China) with one key on, Smart routing; the card said only "Kimi Code (China) 只启用了一个 Key,无需选择。" while /v1/magpie/quotas had its 5 hours 49 used, 51 left and its 7 days 45 used) — two gaps. weighRouted returned before reading anyone's allowance when there was one candidate, so a lone key or a lone subscription account was never known in the trace, and the Routing page, which shows a bar and "{n} used · renews in {d}" for a known row, had nothing to show; every single-account subscription said "what's left not known yet" the same way. And KeyAllowance read only a sub2api key's limits, so a key whose plan the Usage page reads (planQuotaSourceOf: Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code) was never known to routing, with one key or several. weighRouted now reads what each candidate has left before returning a lone one (one alone is still weighed against nobody). readsKeyWindows takes a plan key too; keyWindows reads it through planKeyWindows (planWindows, with Zhipu's team quota behind a key that has none of its own, as PlanQuotas does), and PlanQuotas' own read of a card is noted for routing at once (noteKeyAllowance), so the Usage page and routing never ask twice; the card kept on disk seeds it after a restart (keyCardTag keys a plan card as plan:, a sub2api one as balance:). A key at such a vendor that turns out to be pay-as-you-go, with no windows, is asked again every 30 minutes (keyNoWindowsAge), not every minute it is used. So, beyond the issue: several plan keys on one provider are now weighed by their windows under Smart, usage and pace, and a plan key the vendor refuses as out of quota rests until its window renews and comes back once read short of full, as a sub2api key does. affine no longer says a lone key or account all but used up "moved" its conversation: there is nobody to move to (at > 0). The GUI needed no change. TestLoneOneTellsWhatItHasLeft (a lone Kimi key known at 49% with both renews, the week first; a lone Codex account known; a plain DeepSeek key not), TestLoneSpentKeyKeepsItsConversation (fails with the at > 0 guard taken out), TestPlanKeyAllowance (the windows read behind the request, asked once; DeepSeek and Moonshot keys never asked), TestPlanKeyAllowanceFromItsCard (PlanQuotas' read known at once without a second ask; after a restart with the vendor down, the card on disk stands in and a failed read keeps it) and TestPayAsYouGoKeyAskedSeldom (a GLM pay-as-you-go key asked once, not two minutes on, again 31 minutes on) all fail without the change and pass -race -count=20 (provider) / -count=10 (gateway). routing-key-windows.test.cjs gains a lone Kimi Code key at 1100px and 440px (the one-key story, the row's bar at 49%, its provider row "49% used · renews in …" fitting, no sideways scroll) and passes in full on Chromium and WebKit in en, zh, ja and de; routing-quota-left and panel-routing pass. go test -tags nogui ./internal/..., go test -race on ./internal/provider and ./internal/gateway in full, go vet, gofmt -l, darwin, linux and windows (nogui) builds pass. Not tried with a real Kimi Code key. StepFun's Step Plan is read through a sign-in, not the key, so it isn't one of these. docs/subsystems/gateway-routing.md, providers-accounts.md and docs/reference.md say it. 2026-10-06 20:25:04 +08:00
TryWorld fde0c38c56 fix(gateway): a refusal that arrives once the reply began rests nobody (#1015)
A member whose reply had begun and whose vendor's safety filter then
refused the turn — Chat's code content_filter, Anthropic's stop_reason
refusal, Responses' bio_policy — was booked as a vendor failure
(Fail other) and rested with a backoff, so later requests skipped a
healthy account. The same refusal, said before any of the reply was, is
booked failRefused and rests nobody, and the request is handed to the
next member (#248). Only the timing differed: a refusal is about the
request's content, not about the account (5353ed54 rested every
WorkBuddy AI account over one system prompt).

The refusal was read only while the stream was still held for its first
content (`scan`): once that content has been said the reply goes through
as it comes, and an event after it is never classified. The holdWriter
now reads the events of a reply that has begun for a refusal in one
(`refusalAfter`), with a word filter before the JSON is read, so an
ordinary stream pays one substring test a write, and the mid-reply
branch books such a refusal as failRefused without resting it.

What the agent gets does not change: the reply and the vendor's own
error event go to it as they came, nobody else is asked (its 200 has
been sent), and the conversation is still booked as unanswered. An
error of another kind — an unreachable vendor, an overloaded one —
still rests as it did (#733), as does a reply too long.

TestRefusalMidReplyRestsNobody is new. On main, with a group of two
Chat members whose first answers half and is then refused:

    after content:  try0: status=200 fail=other rest=other
    before content: try0: status=400 fail=refused rest=<nil>

With this change the after-content case reads fail=refused,
rest=<nil>, as the before-content one does, and the test fails on main
and passes. TestRefusalAfterContentPassesThrough passes unchanged.

go test -race -count=5 -run TestRefusal, go test ./internal/middleware,
go vet (windows, darwin), the darwin, linux and windows builds, and
gofmt -l on the three files pass. One test in internal/gateway fails on
this machine either way — TestSweepBridgeProjectsTakesOnlyThe-
BridgesFolders needs SeCreateSymbolicLink — so it is skipped by name
rather than taken for a baseline. Not tried with a real vendor's
safety filter.
2026-10-06 19:54:53 +08:00
forever b0a96cbbd7 gateway, provider, gui: a Sub2API key given 5h/1d/7d limits is weighed and rested by its own windows, like an account (#1004)
* gateway: a Sub2API key out of its 5h/1d/7d limit ("…限额已用完") rests as out of quota, not a 1-minute rate limit

Sub2API refuses a key that has spent the 5-hour, day or 7-day limit its
owner gave it with 429 "api key 7天限额已用完" (or 日限额, 5小时限额),
typed rate_limit_exceeded. It matched rateWords and not plannedWords
("限额" is not "额度"), so failure() said rate: the key rested a minute,
was tried again, refused again, and sank, for the days its 7-day window
had left. plannedWords now has 限额已用完, so it is failQuota.

The relay's other refusals keep their classes, fixed by the test: the
pool out of accounts (v0.1.149's 503 "No available accounts": other;
later versions' 429 "All available accounts are currently
rate-limited": rate), its upstream's rate limit (rate), the key's own
total quota API_KEY_QUOTA_EXHAUSTED (quota) and the wallet's 403
INSUFFICIENT_BALANCE (credit).

Verified: TestSub2APIKeyLimitIsQuota, with Sub2API v0.1.149's message
bodies. Without the change it fails: "429 {…api key 7天限额已用完…}:
rate, want quota", and the same for 日限额 and 5小时限额.

* provider: a Sub2API key's /v1/usage shows its 5 hours / 1 day / 7 days windows instead of nothing at "remaining"

A Sub2API key its owner gave a 5-hour, day or 7-day spending limit
answers /v1/usage in quota_limited mode with rate_limits — each
window's limit, used and reset_at in dollars — and, without a total
quota of its own, no "remaining". With the Balance URL set to it, the
key's card said `nothing at "remaining" in the reply`.

readSub2APIKeyLimits reads rate_limits into the windows the cards
already name 5 hours, 1 day and 7 days, in USD. A window not started
(used 0, no reset_at) is taken to renew a span from now; a window with
a limit of 0 is none. The card shows them, beside a balance field the
user wrote; with none, Check balance and `magpie provider show` give
what the fullest window has left. A wallet key's reply is unchanged.

KeyAllowance gives routing the same windows, per provider and key: read
behind the request, never waited for, at most once a minute (once for
any number of asks at a time); a failed read keeps the last; after a
restart it is seeded from the card's last reading in quotas.json;
StaleKeyAllowance has it read again at the next ask. ForgetBalances (a
key or Balance URL changed) has every key read again, a read begun
before dropped, the last reading standing until then. Only keys whose
Balance URL is a Sub2API /v1/usage are asked: any other key, and every
account, costs nothing here.

Verified with real bytes of a limited key's reply, its key removed
(testdata/sub2api_usage_key_limits*.json): TestReadSub2APIKeyLimits,
TestSub2APIKeyLimitsOnItsCard, TestKeyAllowance*. Each fails without
its part, e.g. the card without the windows: `Error:nothing at
"remaining" in the reply`; KeyAllowance waiting for the read: "waited
30.0s"; asking every time: "asked 11 times"; a failed read asked again
at once: "asked 22 times after failing"; not seeded: "seeded = [],
false"; any key asked: "asked /api/usage/token"; ForgetBalances
dropping what was read: "after ForgetBalances, and a read begun before
it: []"; leaving a read under way loading: "the key's windows were
never read"; a stale-generation read landing: it replaced 95%; a limit
of 0 taken: "a day's limit of 0 = [{… Used:100 …}]"; Balance from the
first window only: "$300.00" for $80 left.

* gateway, gui: keys whose windows magpie reads are weighed and rested by them, like accounts

Smart, least-used and pace routing weighed only subscriptions by their
windows: weighRouted skipped every key (c.p.Account == nil), so a
Sub2API key beside Codex accounts in a group went by its place in the
order, and, refused for its 7-day limit, rested a quarter of an hour at
a time while the window had days to run.

A key whose own windows magpie reads (KeyAllowance: a Sub2API key given
a 5h/1d/7d limit, its Balance URL /v1/usage) is now weighed as an
account is: fine, low (90%) or spent (98%), the one renewing soonest
first, in a provider and in a group alike, and its trace row carries
them. Out of quota it rests till the window it filled renews, by
candidate.full; when its windows as last read aren't full it rests
quotaRest, and either way they are read again (staleKeyAllowance).
Every other failure of a key backs off as before, never to the window:
the relay out of accounts for everyone (503/429) says nothing of the
key's own spend. capHeld and pooled stay accounts' only. Keys magpie
reads no windows of are ordered exactly as before.

The Routing page tells such a key as it does an account: its row's bar,
used share and renewal, why it went first by its allowance, "Every key
and account here is at 90% or more", and the Smart header. A key not
read yet beside one read is told as weighed with it, not "keys go in
their order" or by its tokens. New strings in en, zh, ja and de.

Other users of the relay draining its accounts don't show in a key's
windows, which count only its spend: they show as the pool's 503/429,
which back off and fall over to the next key, account or fallback.

Verified: TestKeysWeighedByTheirWindows, TestGroupWeighsKeyWindows,
TestKeyOutOfItsWindowRestsUntilReset, TestKeyPoolErrorDoesNotRestForWindow;
and routing-key-windows.test.cjs in Chromium and WebKit (en/zh/ja/de).
Without the change they fail: "smart: kw#a kw#b kw#c"; "the key renewing
first: codex sub2api"; "full: rests 14m59.99s by quota"; "read again:
[]"; backing off to the window: "pool empty: rests 71h59m59.99s by
window (other)"; and on the page "relay-a goes first: keys go in their
order, those that suit the request first." where all are at 90% or
more, or a key not read yet beside one read.

* gateway, provider: a Sub2API key out of its limit is back once its windows read short of full, not only when the window renews

A key refused for its 5h/1d/7d limit rests till the window it filled
renews: days, for the week. Its windows are read again behind the next
requests (a minute apart) and by its card, but nothing lifted the rest
when they came back short of full, so the owner raising the key's limit
in the relay's panel, or resetting its usage, left the key out till the
week turned, though the relay would take it at once. Accounts have this
already: a Codex reset spent tells OnRenewed, and the gateway lifts the
account's rests (renewed).

A key's reading, routing's or its card's, now tells OnRenewed the same
way, as agent "" and the key's KeyAllowanceID, when a window it was full
in (Allowance.Full at SpentShareOf its routing, as candidate.full counts
it) is full no more, or full till sooner. Its first reading, a failed
read, or one that finds it fuller tells nothing. The gateway notes the
key's KeyAllowanceID on its rest out of quota only, so renewed lifts
that rest and no other: the relay out of accounts for everyone (503)
still backs off, and another key still out of its week stays out.

Where nothing weighs the key by its windows, nothing read them again
either: an ordered group weighs each member's keys alone, so a member
with one key, like a provider with one key, never asks for them. After
the one read its 429 starts, the key sat out its week on that reading.
restingOf, which plans a resting key behind the rest, now asks for the
windows of a key resting out of them (agent "" and a user on its rest),
so the next request planned past a minute reads them, behind it, and a
reading short of full brings the key back there too. No card is read
for it, and a key resting for any other reason asks nothing.

Verified: TestKeyAllowanceRenewed (provider) and
TestKeyBackOnceItsWindowIsNotFull (gateway, end to end through the key
cards' reads and restAfter), each failing with a piece of the change
undone: never telling, "its week's limit raised to $1,000: told []" and
"a, its limit raised: still rests by window till …"; telling on any
change, "its first reading, out of its week: told [/sub2api#…]"; a
failed read telling, "a read that failed: told [… …]"; the card not
telling, "its usage reset, read on its card: told [/sub2api#…]"; the
rest not noted, "a, its limit raised: still rests by window"; every
rest of a key noted, "c, the relay out of accounts: …, false"; renewed
not matching the key, "b, still out of its week: …, false". And
TestRestingKeyReadAgainInAnOrderedGroup (gateway: an ordered group, its
first member one key on a fake /v1/usage, no card read after the 429),
failing without restingOf's ask: "its limit raised: still rests by
window till …, its windows read 1 times".

Tried on a real Sub2API v0.1.149 relay, in a sandbox HOME, its key's 7d
limit lowered under its spend for the test and then restored, with
magpie serve on a group ordered: the key, then a local stand-in. The
key answered 429 "api key 7天限额已用完"; it rested by window till its
7d reset, 2026-10-13 00:00 +08:00, and the stand-in served. Planned
again a minute later, still over, it still rested. With the limit back
at $800, the next request was planned with it resting, the stand-in
serving, and read its windows; the one after went to the key, 200.
2026-10-06 18:57:47 +08:00
forever 8754221203 gateway, usage: when the credits switch holds every account, the record and 429 say so accurately; the switch's text says it follows the latest reading (#999)
* gateway: a request refused as every account is held records why, caps or credits

When every account was held, the request's record always read "every
account at its usage cap", though the client's 429 (cappedError) already
told a usage cap, credits set not to be spent, and the two together
apart. The record now comes from the same classification (heldBy): the
cap-only wording is kept, credits-only reads "every account held: set not
to spend its credits", and a mix names both.

TestCodexNoCreditsEveryAccount checks the record for both requests; with
the old fixed string it fails with: recorded 429 "every account at its
usage cap" (twice).

Follow-up to #974.

* gateway: the 429 for accounts held off their credits says to spend them only if one holds some

When every account was held as set not to spend its credits, the 429
told the user to let an account spend them to go on now. An account that
holds no credits is refused by the vendor at 100% all the same, so
following that got one more 429. The hint now reads "if an account holds
credits, let it spend them", in the credits-only and the mixed message.
The gateway's allowance readings carry only the windows, and a Codex
reading's balance is "" for none, unlimited and unreadable alike, so a
known-empty balance isn't available to drop the hint by.

TestCodexNoCreditsEveryAccount checks the new wording in both messages;
with the old one it fails with: no "if an account holds credits, let it
spend them" in the body (both requests).

Follow-up to #974.

* usage, docs: a Codex account set not to spend its credits is held by magpie's latest reading

The Use credits hint, magpie quota credits' help and the docs said that,
turned off, the account's credits aren't spent. The hold goes by magpie's
latest reading of the account's windows, which is read again about once a
minute, so for a minute or two after a window fills, or while nothing is
read yet, a request can still reach the account and spend some credits.
Each now says the hold follows that reading, refreshed about every minute
(Usage card in en/zh/ja/de, quota help, reference.md, gateway-routing.md).

codex-credits (Chromium and WebKit, en/zh/ja/de: 8/8), i18n-keys (1/1),
gui-ja (3/3) and gui-de (3/3) pass; codex-credits checks the reworded
string has its zh, ja and de.

Follow-up to #974.
2026-10-06 16:09:00 +08:00
forever b37ac53bef codex: a switch for whether an account spends its credits (#974)
* tui: show a ChatGPT account's credits beside its windows

The Usage page printed only the balance for an account that had one, so a
ChatGPT account holding credits lost its 5-hour and weekly windows there.
The balance now follows the windows, as on the app's cards and in
magpie quota.

* accounts: tell a ChatGPT account's credits

magpie accounts left out the credits an account holds, which magpie quota
and the Usage page show. Its rows now carry them, in the line and as
balance in --json.

* codex: a switch for whether an account spends its credits

A ChatGPT account holding credits keeps answering once a usage window is
used up: the vendor spends the credits, and a task goes on. That stays the
default. Each Codex account now has a say in it (Usage card and menu bar
panel: Use credits; magpie quota credits <account> on|off; settings'
codexNoCredits). Turned off, the gateway holds the account at 100% of a
window, as a usage cap holds it at its share, so the other accounts,
groups and fallbacks take the request and no credits are spent. With none
left the request gets a 429 naming what holds each account and how to go
on, unless the account spends its resets by itself and its week is used
up: then a reset is spent first, whether every candidate was held or the
last one tried was refused. A cap set on the account takes precedence.

A reset made now forgets the account's cached allowance, so neither a cap
nor this hold outlives the windows it started again. The switch is
routing's only: which account Codex is signed in to is unchanged.

The Routing page tells why such an account was left out, and magpie quota,
magpie accounts and the TUI mark credits not spent.

* usage: an auto-reset switch keeps by its first line

The auto-reset row centred its switch on its words, so the switch moved
when they rewrapped on a click, and it sat lower than the Use credits
switch beneath it. Both now keep the switch by the first line.

* gui tests: quota-curve expects the Use credits row to close a Codex account's section

The credits switch adds a row after the Auto-use one, so the account after
a Codex account follows the curve, the Auto-use row and then the Use
credits row.
2026-10-06 14:20:09 +08:00
july_lu 47c2382467 gateway: a gateway key can be held to some accounts (#905, LCorleone) — a key could burn any account a provider had: two coding plans of one vendor, and a key given to someone had them both. A key now keeps an optional list of accounts and keys (caller-keys.json "accounts", none = every account, so older files read as before): "<provider>/<account>", an account by its stable id — the login's, set once it is written and kept through renames (logins.json's savedLogin id, written by every write and stood in for by one made of the name until then, so an entry made before stands), a key by its fingerprint — every one a provider has when the list is set, and one gone later (a key rotated, an account signed out) kept as it is, matching nothing, holding the key closer, never wider. The command line and the menu name an account by who is signed in and keep its id. Routing holds a plan to the key's accounts beside its models: a candidate whose account the key may not use is left out — through a routing group the key names no less, for naming a group is not naming its accounts — the plan's order keeping step and its left-out list marking what the key held out (Weighed's held); magpie's own calls for the key — a web search, a picture described, a Codex title — are of the models the user picked, so the models don't hold them, but their spend lands on an account all the same, and the accounts hold them too. When every account or key a model has is one the key may not use, the request is refused with a 403 in the API's own error shape naming the model and the accounts the key may use, logged as a rejected call: after a usage cap's 429 and before an account barred for the model's, itself before the no-member 404. /v1/models and the Anthropic and Gemini lists show the key only the models an account or key it may use serves (a provider's account set not to serve one, #474, is none of the key's); a provider with no account and no key (a local ollama) is one the key names no account of — its models stay listed and its asks pass — while an entry kept after its provider lost its last account or key serves none, holding the key closer. The embeddings, images and videos endpoints hold their candidate to the key's accounts the same way, and counting tokens counts on those alone (the local estimate where it may use none). System One asks its decision model of an account or key the key may use — and sends on that key, of those in use, not the provider's first, which a key held to a later one was spent on; the videos and images keyed paths send on one the key may use too, held to a later key no longer refused for the first alone. Set it in the app's menu the models are picked in — the accounts after the models, an account by who is signed in with their plan in the note, a key by its fingerprint, what the CLI kept that no provider has now kept as "Not signed in now" — or magpie gateway-key accounts <id> codex/me@example.com openai/<key id> (all takes it off); gateway-key list has an ACCOUNTS column. en/zh/ja/de, the German "{n} accounts" main already had left to it rather than written twice. The images API's fan-out over a subscription's accounts is held to the key's accounts as one: one of the key's whose plan refuses to draw no longer hands the pen to an account it may not use, and the second in the order, when it is the key's, draws what the first may not (drawOnAccounts filters the candidates, the account pinned to with the account header told plainly when the key may not use it). The Routing view's left-out list says an account the key held out for what it is, not that its plan lacks the model, in Chinese, Japanese and German too; the key's badge names its accounts by who is signed in, not by the stable ids it keeps. (#932) 2026-10-06 10:51:50 +08:00
yetone fa7a0f23a8 gateway: a streamed reply whose vendor goes quiet keeps its agent alive on a timer of its own, held or passed, so a proxy in front doesn't end it (#947, jorben) — a vendor that sent its 200 and response.created and then nothing had the stream held for its first content with no event to scan, so the agent got no headers at all until it spoke again, and Cloudflare in front of a remote magpie ended the request at 125s (524); a translated reply quiet mid-way was kept alive only as the vendor sent something, and the proxy reset it. holdWriter.watch now runs beside every streamed try (it was only Group.FirstToken's watchFirst): past keepHeldAfter it sends a held try's agent the stream's 200 and SSE comments (keepAlive), none of the try, so another account may still answer in the same stream; once passed, a comment goes between two of its lines after keepaliveEvery of quiet; it stops after keepaliveLongest with nothing from the vendor, and Gemini streams get none (#934). Covers every protocol, relayed or translated. quiet_keepalive_test.go is new (held, mid-reply, failover after keepalives, the 5-minute cap, Responses/Anthropic/Chat relayed and Anthropic from Chat) and fails without the change. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass (TestUserPath in internal/proc failed once under the full run and passes alone). 2026-10-06 03:51:44 +08:00
yetone 8d3cf5f86e gateway: a Gemini reply that says nothing is asked again on the same account before it fails, so a long conversation that ends with only reasoning a few times running goes on instead of stopping the agent (#667, tianshuo886)
antigravity/gemini-3.8-flash, deep into a long Pi session, ended its turn with only its reasoning three times in a row; the request's own tries (3, 1s and 2s apart) ran out, Pi got "an empty reply" and stopped until the user typed continue. streamTranslated now asks such a reply again in place: once while the stream is still held (the request's tries and the next account still follow), up to twice once the agent has the stream, when nothing else would. A model that never answers is asked at most 6 times and still ends with the error. What reasoning the agent already has stays; the next try's follows it in the same message.

TestGeminiEmptyRepliesAskedAgain (chat and Anthropic: three empties running end in "hello", one message_start; one that never answers errors within 6 calls) is new and fails without the change. go vet, go build (GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
2026-10-06 01:14:50 +08:00
yetone 86f48071cc gateway: an image or a PDF sent as Gemini's inline_data, or as a Chat Completions file part, reaches the model, and a Gemini stream gets no keepalive comment (#934, handong66)
/v1beta read a part's fields only as camelCase, while Google's API takes
their proto names too (inline_data, mime_type, file_data, function_call,
system_instruction, generation_config…), which agy and raw SDK calls
send: the image was left out, the call still answered 200, and the model
made up what it held. geminiCamel spells a request's fields in camelCase
before anything reads it, keeping the caller's own keys (a call's args, a
result's response, the schemas) as they are.

A Chat Completions {type: file} part (file_data as a data: URL or bare
base64, or a file_id) was dropped; it is now the request's file, which
Antigravity and other Gemini upstreams are given as inline data and the
others are told of ([attachment application/pdf]).

A held stream's keepalive comment went to Gemini clients too, which
agy fails on ("invalid stream chunk: : keepalive"); a Gemini stream gets
none, as geminiEncoder.keepalive already sent none.

TestGeminiSnakeCaseParts, TestGeminiSnakeCaseImageReachesUpstream,
TestChatFilePart and TestHeldGeminiStreamSendsNoComment are new and each
fails without the change. go vet, go build (GOOS=linux nogui, GOOS=windows)
and go test -tags nogui under a temp HOME pass (TestSavedButSignedOutClaudeServed,
in a package this doesn't touch, failed once on a 5s timeout and passes alone).
2026-10-06 01:09:29 +08:00
yetone 56cfb8fbba gateway, provider: a subscription refused for a pool of its allowance that counts some models only rests for that model, not the account (Xiaopodev on X) — Cursor's Other Models used up kept Auto and Composer, still in Cursor Models, off the account too: the refusal rested the whole account by its restKey. Allowance.Pooled says a refusal is the model's alone when the windows full for it each count some models only (a plugin's models/notModels pool, Opus's own week), or none known full, only pools count it; restAfter then rests restID (account/model), which every rest check already looks at beside restKey. Tested with the owner's real Cursor account in a sandbox HOME: its real pools read Auto and Composer in Cursor Models, Opus and GPT in Other Models; after an Other Models refusal for claude-opus-5-5 only that model rested, and cursor/auto and cursor/composer-2.5 answered 200 through the account. TestAllowancePooled and TestPoolRefusalRestsTheModelOnly are new; the latter fails without the change. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. 2026-10-05 23:21:24 +08:00
yetone 2033df0faa gateway, gui: WorkBuddy turning away an agent's system prompt ("unapproved channel") rests no account, its mates are asked last, and the Routing page tells it as the prompt, not the reasoning level (lemon on Discord)
WorkBuddy AI answers 400 "Illegal API invocation from an unapproved
channel" (code 11128, "blocked by security policy") to a chat whose
system prompt is Claude Code's own identity line, at any reasoning level
and on any account (checked against a real WorkBuddy AI account with
deepseek-v4.1-flash). It was treated as the account failing: each account
rested, so one agent's chats took WorkBuddy away from every agent. It is
now failPrompt: the next member is asked, the account's mates last, and
nobody rests. The Routing page says the vendor turns the agent's prompt
away and leaves out the level the try went at.
2026-10-05 22:19:40 +08:00
TryWorld f1f516cd73 fix(gateway): an account Antigravity turned away doesn't rest (#873)
* fix(gateway): an account Antigravity turned away doesn't rest

A 429 that is Antigravity refusing Claude Code's or its Agent SDK's
system instruction — "Resource has been exhausted (e.g. check quota)"
whatever quota the account has left (#666) — carries the word "quota",
so it was classified failQuota: the account rested 15 minutes and had
its usage asked of Google again, while it answers titles, background
requests and Codex normally.

Carry the fact the error path already works out from —
antigravityTurnsAway(request.System) and the CodeAssist agent, what the
8c652a83 hint is computed from — into the routing decision, the way
sharedPool and refused already carry an upstream routing fact through
error translation. The held attempt is marked on either failure path,
not only on a 429: the refusal also arrives as an in-stream error event,
which skips the 4xx branch and returns 200 while still failing the
attempt, and usedUpWords doesn't look at the status either. Where the
attempt then fails on that mark, the next member is asked first and
restAfterMarked is never called, as for a refusal — nobody rests and
nobody's usage is re-queried.

A 429 that really is the plan used up, with no such system prompt
asking, still rests the account and re-queries its usage, as it did
(#147, #530).

* fix(gateway): only the refusal leaves an Antigravity account alone

The mark was wider than the refusal it describes (yetone's review of
#873): it was set for any status >= 400, and for any failed stream,
whenever the system prompt was Claude Code's. A 500, 503 or 403 on such
a turn was therefore told as a refusal and never set the account aside,
and the account's 4xx handling below it was skipped for those requests.
The mark now goes on the refusal itself: a 429, or an in-stream error
event saying "Resource has been exhausted". The latter needs its own
predicate, since the Code Assist decoder keeps only the error's message
and leaves its status and code out of the event.

Two more of the review:

- the refused attempt now writes a usage.Record, as the hw.refused
  branch it is modelled on does, so these 429s stay in the ledger;
- the member's other Antigravity accounts are asked last rather than
  first, by matesLast, the inverse of matesFirst: they carry the same
  system prompt, so each is turned away just the same, and asking them
  first spent a round-trip apiece before the group reached a member
  that answers.

TestAntigravityTurnedAwayIsOnlyTheRefusal, ...StillLandsInTheLedger
and ...LeavesItsMatesForLast fail on the previous revision of this
branch for each of these reasons.

* fix(gateway): the refusal said inside a reply that isn't streamed

The mark was inside translate's `if stream` block, so a client that
doesn't ask for a stream — and a stream that isn't held — never set it:
the same "Resource has been exhausted" said as an in-stream error event
still rested the account 15 minutes on those requests.

A test for that path first: TestAntigravityTurnedAwaySaidInsideTheReply
drives a 200 that opens with the error event, and pairs it with an error
event of another kind, which still rests the account. The first half
failed on the previous commit for exactly this reason.

Both error paths now go through markAntigravityRefused, which decides
from what the failure said rather than repeating the four conditions at
each return: the Code Assist decoder keeps only the error's message, so
an in-stream refusal is recognised by its text, while a 429 is
recognised by its status as before.
2026-10-05 16:31:11 +08:00
yetone 3ec6b4da27 gateway, gui: a provider's keys can be routed by weight, a key weighing 3 taking three requests for every one a key weighing 1 takes (dengtongcai, #841) — Routing already spread requests over a provider's keys in order, in turn, least used first or by pace, but never in a set proportion: two team keys meant to split 75/25 could only go evenly or one after the other. Routing now has By weight (routing "weight") for a provider with keys: each key that's on shows its weight and its share beside it in the editor (Weight 3 · 75%), a click edits it in place and posts keys/weight (provider.SetKeyWeight, 1 to 1000; none or 0 counts as 1, kept out of the file), and providers.json takes it as "weight" on each of keys (keyWeight for the first). The gateway picks as NGINX's smooth weighted round robin does (weighted.go): 3, 1 and 4 go round in every 8 requests in that ratio, never bunched; the others follow in their order for failover. A key resting after a failure is left out of the round while it rests, the others taking its share by their weights, and goes last. A conversation still stays with its key as Stays says (cache-warm across turns by default, within a turn always), and a request kept so is counted against the key that took it, not the one the round picked, so new conversations make up the share; Stays Off gives the ratio request by request. The weight goes with its key through Make first, the editor's Save, backups and WebDAV sync. The Routing page offers By weight for key pools and explains a pick by it; sink (Goes to the back) is off for it as for In turn. zh, ja, de strings. TestWeightedKeys (3:1:4 exact in each of 50 rounds of 8 through perKey and route; with one resting the other two 75/25 and the resting one last; a kept request made up by the next picks) and TestSetKeyWeight fail on the old code (no Weighted); key-weight.test.cjs (WebKit, en and zh: By weight shows the weights and shares, a click sets one and the shares redraw, Smart hides them, no scroll) fails on the old code (no By weight). key-import, panel-routing, routing-save, rate-limited-sink, routing-reset-deadline, account-arrange, gui-ja, gui-de and click-scroll pass on WebKit. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-05 08:50:57 +08:00
yetone 6f64956f27 routing: a group can let a member go that hasn't begun answering after a set time and ask the next, and a request's detail splits its first token into magpie's time and the vendor's (Chen on X: answers through magpie felt slow, with no way to tell whether magpie or the vendor was the wait) — a group's editor has a Slow to start row (Wait, 30 s, 1 min, 2 min; Wait, the default, keeps today's behaviour). With a time set, a streamed request to a member that has sent no text, reasoning or tool call by then is cancelled before any of its bytes reach the agent (the held start is dropped; keepalives go on meanwhile) and the next member is asked; the try is marked slow ("slow to start", narrated in the route), and the member doesn't rest, since nothing is wrong with it. The last member left is always waited for. The card says "Next after 1 min without a first token". Each request now records when it went to the vendor (httptrace WroteRequest, sent_ms), and its detail shows In magpie and Vendor's first token beside First token; after a failover In magpie includes the time spent on the members let go. With the owner's real DeepSeek key in a sandbox, a group [a local member that sends its role chunk then stalls 60 s, deepseek-flash] with 3 s: the answer came from DeepSeek in 4.4 s, none of the stalled member's stream reached the client, its try read slow / "no first token in 3s" with no rest, and the ledger had ttft 3622, sent 3003. TestGroupFirstTokenFailsOver (failover, the last one waited for, one in time kept; passes -race) and group-first-token.test.cjs and usage-ledger-detail.test.cjs (WebKit, en and zh) fail on the old code. group-from-model-add's narrow-window case fails the same on origin/main; Chromium doesn't launch in this sandbox. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass (TestProvidersAnswerWhileListsComeIn flaked once, passes alone). 2026-10-04 19:33:55 +08:00
yetone 3eae3ee7fb gateway: a Claude stream held for its reasoning keeps the agent alive with SSE comments, and a request whose agent went away is recorded as canceled, not as a 200 done (#751, margbug01 on v0.1.679: Alma → magpie → Claude Code (Claude Max, claude-opus-5-5) ended with "No LLM streaming data for 240000ms", while the routing record said 200, about 240000 ms, TTFT about 4.3 s, 8 tokens out, done with no error) — for a Claude model, refusesAfterThinking, a stream that holds nothing but reasoning is held for up to holdThinking (4 minutes) so that a refusal after it can still go to another account (#248). Everything written meanwhile was held with it: message_start, the thinking deltas and the protocol keepalives relay sends every 15s (#436). The agent got no byte at all, and Alma's idle timeout for a reasoning model (60s ×4 = 240s, reset by any SSE line, comments included) ran out first. The hold is on for nearly every first try (!last || again < retries || …), so one Claude account alone was enough. The TTFT on the record is the held stream's first event, not a byte delivered. Now, once a stream has been held for its thinking or safety buffering past keepHeldAfter (holdLongest, 15s), holdWriter.keepAlive sends the agent the stream's 200 and headers once, then a ": keepalive" comment every keepaliveEvery while the stream stays held. The comment is not an event in any protocol and says nothing of the reasoning, and no model text is made up. The keptAlive is the request's and is shared by its tries. A refusal after the comments still goes to the next member: its pass() skips the headers already sent, and its stream follows in the same response. Once headers are out, a failure can no longer be a status, so the gateway's writeErrors inside the try loop go through failTo and holdWriter.release goes through streamError, which tell it as the stream's own error event (Anthropic event: error, Responses response.failed, Chat's error chunk). The last try's writer is held too once headers are out. A Responses agent (Codex) doesn't count comments, but its 300s timeout outlasts the 4-minute hold.
When the agent went away, serveSubscription's AfterFunc stopped Claude Code, but relay still called enc.finish(), which wrote message_stop to the gone writer. holdWriter.see took that as the reply made whole (ended), so serve's `r.Context().Err() != nil && !hw.ended` check, which records 499 "the agent canceled the request" with Fail canceled, was skipped and the request was recorded as 200 done. see now ignores a stream end written once the request's context is done, and the bridge logs "Claude Code run on <model> stopped: the client went away <t> into the reply".
TestHeldThinkingKeepsTheAgentAlive sends claude-opus-5-5 thinking that goes on (pings every 10ms until the client hears a keepalive, else 3s) through a group over a real HTTP gateway. It covers three cases: a refusal after it, where the client gets ": keepalive" before b's answer in the same stream, with one message_start, no reasoning text and Tries[0] refused; an answer after it, which arrives whole after the comments; and a refusal with nobody left, which arrives as a 200 stream with event: error. TestClientGoneRecordedAsCanceled checks a holdWriter whose context is canceled before message_stop, and a fake Claude Code run (fakeClaudeCalling's hang) stopped mid-reply through serveClaudeSubscription writing to a holdWriter. With keepAlive's call and see's context check taken out, both fail: the client heard nothing until the upstream gave up waiting at 3s, and ended was set. go vet, builds (darwin, GOOS=linux, GOOS=windows), go test -tags nogui -count=1 ./... under a temp HOME, and -race on the gateway's refusal, thinking, keepalive and cancel tests all pass. Not tried with real Claude Code, a real Claude Max account or Alma. Not changed: --thinking-display summarized is passed only when the request names an effort, so Claude Code's own thinking display is otherwise left at the API's default; relay's keepalives stop 5 minutes after the last event (keepaliveLongest); and Gemini clients get no keepalive.
2026-10-04 14:11:24 +08:00
yetone ed79a72927 provider: a subscription account can be capped at a share of its usage windows, and routing treats it as used up there (Discord: hold a new Claude account at 70% of its five hours and its week to keep its ban risk down, and let magpie go on to the other accounts) — an account's cap (1–99, keyed by the provider id and the account in lower case, AccountCaps in providers.json beside AccountModels and AccountProxies) holds it once any window that applies to the model is at or past the cap and hasn't reset (Allowance.CapHeld; Aside windows and windows kept for another model are left out). One share for every window rather than one per window: the windows an account has differ by vendor (five hours and week for Claude and Codex, a month or a day for others, per-model weeks), the request was one figure for both, and a lower share for one window would be set by lowering the cap. The gateway's perKeyBarred moves a capped account to the candidates left out (barredOf marks it Capped with its use and when it is back, so the routing trace says "held at its 70% usage cap"), so groups, fallback, Ordered and Spread routing and the Codex/Claude Code switch list (NextLogin: a capped account is moved off, not returned to, and isn't a spare) all go on to the next account; a pinned capped account and a draw over only capped accounts answer 429. When every account that serves the model is capped, the client is turned away as when all are used up — 429 rate_limit_error with Retry-After at the soonest reset — and told the cap was reached, which accounts, at what use and cap, and how to lift it. A cap never spends a Codex reset: weekUsedUp, usedUp, BackAt and spendExpiringNow still go by ChatGPT's own 100%, so an account held at 80% with auto reset on is held and nothing is spent; a lone Codex account with a cap goes through serve() instead of being relayed as it came (codexAccounts), so the cap holds it. The Providers page shows a cap pill on each account's row (on hover until set) that opens the app's own menu — No cap, 50/60/70/80/90%, Other… (typed inline, focused without scrolling) — posting provider/accountcap; each window's bar gets a tick at the cap (from the right when the bar shows what is left), and an account held by its cap says so and until when. zh strings in i18n.js. CLI: magpie provider account-cap <id> [account [percent|off]] shows or sets caps. Tests: TestCapHeld, TestCapReached, TestParseCap; TestCapNeverSpendsACodexReset (80% windows, 70% cap: not used up, no reset due, routing held); TestCodexSwitchedAtCap (the active account at 75% with a 70% cap is switched off to the one at 20%, not back while capped, back once lifted; 100 and an unknown account refused); gateway TestAccountCapMovesOn (first account at 75% capped at 70%: the second is tried and the trace says 75/70; lifted: the first), TestAccountCapEveryAccount (429 rate_limit_error naming both caps, nothing sent, logged 429) and TestAccountCapSpendsNoCodexReset (one account at an 80% week, auto reset on: 429, nothing tried or spent; lifted: 200, nothing spent) — the three gateway tests fail with the cap check taken out; TestAccountCapCmd; account-cap.test.cjs (webkit, en and zh: pill, menu, Other…, No cap, cap ticks, held note, no <select>, no border stripes, no scroll on click). account-models, click-scroll, keep-login, codex-auto-reset, account-return, routing-blocked, routing-account-order, routing-quota-left, routing-auto-reset, routing-manual, quota-pools, quota-families and usage-accounts GUI tests pass in webkit. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried with real accounts; a cap acts on usage as last read, so a burst between reads can run a little past it. 2026-10-04 10:18:50 +08:00