Commit Graph
151 Commits
Author SHA1 Message Date
ggbdpq 86fef947e8 gateway: a 200 stream ended with finish_reason "error" fails over (#2471)
What changed: a vendor that ends its 200 stream with finish_reason
"error" - WorkBuddy's and a DeepSeek harness's word for a turn it failed
rather than finished - had the chunk taken for content: the held stream
went to the agent, the try stood as a 200 success, and the group's next
member was never asked. streamEvent now reads the word as the failure it
says, held for the next candidate as an error event before content is;
in the candidate walk the try fails as an empty reply's or a cut-short
summary's does (#1221, #2274): the next is asked, and nobody rests, as
the reply's shape failed, not the account. Content already passed to the
agent can't be taken back, and is not touched.

Run: TestFinishReasonErrorFailsOver (new) red on a15e5765 before the fix
(the reporter's shape: one try, status 200, Fail empty, the second member
never asked), green after; red again with fallback.go and gateway.go
stashed, tests kept. TestStreamErrorBeforeContentFailsOver, the
streamEvent tables, and the stream families (Stream/Finish/Refusal/
Overload/LastOneLeft/GroupFail/Retry, Loop/Hold/Pass/Queue/Patience/
Incomplete/EndedShort/Grok) green. gofmt -l clean; vet on darwin, linux
(nogui) and windows clean; build ok on all three.

Review (magpie): the maintainer's call this waited on is made: the
literal "error" is a failure from any vendor, no vendor sends it for a
finished turn, so it is not keyed per vendor. Alone (no group), the
failure is the last one left's, tried again as a 502 is (15 asks in
the test's clock, the same count a plain 502 gets), then the vendor's
stream goes to the agent as it came. Content already shown is not taken
back. Not covered, still open on #2471: an empty response.completed
and a Chat stream with no finish_reason at all. Run on the Mac mini:
go test ./internal/gateway -count=1 ok. Broken by hand: fallback.go and
gateway.go at the base - TestFinishReasonErrorFailsOver (200, b never
asked) and the streamEvent table red. Not tried: a real WorkBuddy
reply ending so.

Generated-by: GLM-5.3-Flash (ZCode)
2026-10-31 02:00:10 +08:00
yetone cfcd6648fc gateway: Chinese that says the input is too long is an overflow, Chinese pace words a rate limit (#4420)
A group member answered 400 "内容太长了,请精简输入或开启新对话" once a
turn passed ~730K on a model it declares at 1M. tooLongRe's Chinese only
matched wordings that name 上下文, so the try was filed as a plain
failure that rested the member, and the group's other members were never
asked. Reported by MYCF711 (Discord, issue #4420).

tooLongRe gets a third line for Chinese that names what was sent (内容,
输入, 文本, 提示词/prompt, 问题, 对话, 消息) beside its length: "…太长/过长/
超长", "…超过/超出…长度/token/字数", "输入长度/token…超过", and
"字数太多/过多". Tied to: the reporter's vendor, z.ai's 1261 "Prompt 超长",
iFlytek Spark's 10907 "token数量超过上限。对话历史+问题的字数太多,需要精简
输入". Left out on purpose: bare "超出最大长度" (a field's length), bare
"token数量超过上限" (a day's allowance is said so too), "输出过长" (the
reply), and "请求体过大" (a 413 byte limit, already handled by status).

paceWords gets Chinese pace words (速率, 频繁, 频率, 限流, 并发, 每秒/
分钟/小时/天/日, 稍后再试/重试), so "内容太长,已达到速率限制" is a rate
limit, not a size. rateWords gains 过于频繁/速率 and quotaWords 频繁/速率,
so such a 400 is asked of the next account and such a 429 is failRate.

Tests:
- TestEveryVendorsOverflow: 8 Chinese rows (red on the old code, each).
- TestChineseNotTooLong (new): pace-with-size, a field's length, the
  reply's length, a day's token cap and plain errors aren't overflows; the
  pace 400 is retryable.
- TestChineseInputTooLongGoesToTheNextMember (new): two-member group, the
  reporter's literal words, raw and \u-escaped: member b answers, failOverflow,
  nobody rests (red on the old code: a 1, b 0, 400 to the agent).
- docs/subsystems/gateway-routing.md names the new wordings.

Run (mote, via mote-run, at this tree):
- go test ./internal/gateway -count=1 -timeout 45m: ok 500.9s
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: clean; gofmt -l clean
- Broken by hand: old gateway.go/routing.go/fallback.go with the new
  tests: all three tests red (11 failures). paceWords alone reverted:
  TestChineseNotTooLong red on 4 pace messages and the retryable check.

Not tried: the reporter's real vendor (unknown which member it is), nor a
real z.ai or iFlytek account; the wordings come from their docs. Only
internal/gateway was run, not the whole repo; the change is inside that
package's classifiers.
2026-10-30 17:52:14 +08:00
yetone 067e4c4846 gateway: Raccoon's token wall (user_model_rate_limited) isn't asked again in place (plugins#512)
SenseTime Raccoon answers an account whose token throughput is used up
with 429 {"error":{"code":"user_model_rate_limited","message":"您的模型请
求频率超限,请稍后重试","type":"rate_limit_error"}} and no Retry-After.
Its words read as a short rate limit, so the lone account was asked again
by the same-one retries (passing: 1, 2, 4s) and then by the plain
provider's patience (busy/replan: 2, 4, 8, 16s): eight asks in ~38s,
each one resending the whole ~88k-token request into the bucket it was
waiting on (cycocyco's numbers in plugins#512).

A 429 whose error.code is in wallCodes (only user_model_rate_limited) is
now neither passing nor busy. It still reads as failRate and rests as one
(a minute, doubled each time it comes back, up to 30 min, rateRest), so a
group's next member or the provider's next account is asked, and a lone
one hands the agent the vendor's error after one ask. The code is matched
at error.code only, not as words anywhere in the body. Other rate limits,
the same Chinese words under another code included, are retried as
before. The plugin passes the vendor's body through unchanged, so this is
the place for it.

Run (mote, at this change on origin/main 244d80e23):
- go test ./internal/gateway -run 'TestTokenWall|TestRateLimitIsWaitedOut|TestShortReset|TestLastOneLeft|TestGroup': ok
- gofmt -l internal cmd: clean; GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok
- go test -timeout 45m -count=1 ./...: every package ok except
  internal/gui, whose ten real-window AppKit tests (dock, panel, tray,
  titlebar, plugin page) were killed at their deadlines, mote's known
  state (#4125, #2645); this change touches no GUI code.
Rebased on origin/main 88e6fb9cf: go test -timeout 45m ./internal/gateway
./internal/usage: ok. Rebased again on 88e6fb9cf (routing.go's credit
rests changed, not the rate path): go test ./internal/gateway -run
'TestTokenWall|TestRateLimitIsWaitedOut|TestShortReset|TestLastOneLeft|
TestGroup|Rest|Credit': ok; the whole package not rerun there.
Broken by hand: with both !walled(body) guards taken out,
TestTokenWallIsNotRetriedInPlace is red (passes, busy) and
TestTokenWallFailsFast is red with "429 after 16 tries".
Not tried: the real Raccoon API (no account here), nor the reporter's
Hermes on Windows.
2026-10-30 15:40:49 +08:00
yetone c37b8b6594 gateway: a remote magpie's out-of-quota refusal is asked again, not replayed here (zaidu259434 on X)
A routing group on another computer's magpie had one member, Open
Design, out of its Coding Plan quota and wallet. This magpie rested
that remote model (remoteModelRest) and, through quotaHeld, gave the
402 again on every request until the time it named, never asking the
remote. The user moved the group to another vendor there, and Codex
here still got "Remote magpie: Open Design: [code=insufficient_balance]
... (out of its allowance: not asked again before 06:19)".

The remote magpie routes its own groups and holds its own rests, and
what it serves under a name can change there at any moment. A rest
from remoteModelRest is now marked (Rest.there), and quotaHeld passes
it by: the remote is asked, and answers from its own hold at once, or
from what it serves now. The rest still puts the model behind the
others in a local group. verifyHeld is unchanged: its hold is a
minute, and TestRemoteMagpieVerifyHeldOnTheModel asks for it.

Run (on mote, at cc81ad4ea plus this change):
- TestRemoteMagpieQuotaIsAskedNotReplayed and
  TestHandAddedMagpieQuotaIsAskedNotReplayed: red on cc81ad4ea (402
  replayed, remote asked 0 times), green with the change.
- go test ./internal/gateway -run 'QuotaIsAskedNotReplayed|RemoteMagpie
  |AddedByHand|QuotaHeld|1772': ok. A wider run (Held|Quota|Verify|
  Spent|Credit) is ok except TestAntigravityTurnedAwayLastIsNoQuota and
  TestCodexSpentGrokFailingIsTold, red alone on untouched cc81ad4ea
  too (#4362).
- go vet ./internal/gateway, GOOS=linux (nogui) and GOOS=windows: ok.
- Two sandbox magpies (own HOMEs, free ports) and a fake vendor: R with
  group never-stuck = opendesign/od-model (402 insufficient_balance),
  L with R as a remote-magpie provider. Old code: after
  `group set never-stuck models=newvendor/new-model` on R, L kept
  answering the reporter's exact 402 and the vendor never saw
  new-model. With the change: 200 from new-model at once. With both
  members in the group (order), R falls through: od-model asked once,
  then new-model answers every request.

Broken by hand: the change taken out, both new tests go red as above.
Not tried: a real Open Design account, the reporter's phone setup, and
the full Go suite (to run on mote when it is free).
2026-10-30 13:50:53 +08:00
yetone 750bd1bb69 gateway: Factory's usage policy refusal reaches agents as a refused request, not a failed sign-in
sweanng (Discord #general, ZCode + Factory + GLM 5.3) got Factory's
usage policy refusal shown as "Provider authentication failed"
(reason=auth_failed status=403). The refusal is Factory's own; the label
was wrong. Factory refuses at 403 with code content_policy_rejected. The
Factory plugin (up to 0.1.39) handed it on as a 403 permission_error
with no code, magpie didn't know the code as a refusal, so the 403 went
through as is and the agent read it as an auth failure.

- policyRefusal knows content_policy_rejected (Factory's code, in its
  own top-level and error.code shapes and the plugin's), so the existing
  refusal path answers every protocol with 400 and its own request
  error: Anthropic invalid_request_error, OpenAI chat and Responses
  invalid_request_error, Gemini INVALID_ARGUMENT. Not asked again of the
  same account; other accounts/members follow the Refusal retries
  setting as for any refusal.
- restAfter leaves the account unrested for a policy refusal at 403 too,
  not only 400 (it rested "other by backoff" before).
- The refusal note keeps up to 1000 bytes of the vendor's message, not
  300: Factory's advice (start a new session or drop the quoted text)
  and OpenAI's Daybreak link were cut.
- Factory mover min 0.1.40 (plugins #494, on npm as latest): the plugin
  now answers this refusal as a 400 invalid_request_error carrying code
  content_policy_rejected; its other 403s stay permission_error.

Siblings checked: Devin's plugin maps its content policy to 400, Qoder's
sensitive codes and Zhipu's 1301 are request errors already; Factory was
the one content refusal sent as a 403.

Run (mote, rebased on origin/main 96a703a59, with the next commit):
  go test -timeout 45m -count=1 ./internal/provider: ok
  go test -timeout 45m -count=1 ./internal/gateway: ok (768s)
  (the first gateway run at this commit alone failed only
  TestUnroutedUnknownHoldAnsweredSooner's TempDir cleanup, a race in
  the test fixed in the next commit)
  gofmt -l internal/: clean
  plugins: HOME=$(mktemp -d) bun test packages/factory 178 pass;
  bun scripts/check.mjs ok.
Broken by hand: with fallback.go and routing.go reverted, all three new
tests fail (403 permission_error / PERMISSION_DENIED reaches every
protocol; policyRefusal false; rests "other by backoff"). With the note
cap back at 300, TestFactoryPolicyRejectedIsARefusal and
TestFactoryPolicyRefusalReachesAgentsAsARefusal fail (advice cut). With
the plugin's index.mjs reverted, content-policy.test.mjs fails 3 of 6.
Not tried: a real Factory content_policy_rejected (no way to trip it on
purpose), and ZCode itself reading the 400: its error mapping isn't in
any source I could find, so ZCode showing it as a refusal is expected
from the Anthropic invalid_request_error, not seen.
2026-10-29 18:31:42 +08:00
yetone bb3565309d gateway: a provider's listed reply headers and the vendor's request ids reach the agent (#4145)
codex-cn (#4145, and smtmsnyw on X: "Magpie代理把我原始模型响应头给吃了"):
a relay's X-OneAPI-Request-ID never reached the agent, so a failed or
slow call couldn't be matched with the relay's logs.

What changes
- provider.ReplyHeaders (`replyHeaders` in providers.json, the editor's
  Advanced > Reply headers, comma-separated): headers of the vendor's
  reply passed on to the agent, matched whatever their case, saved
  canonical. Request-Id, X-Request-Id and X-Oneapi-Request-Id go from
  every provider without being listed (DefaultReplyHeaders): opaque ids,
  under names magpie sets nothing of its own, and passthrough already
  passed the first two on a 2xx. Nothing the user set is overridden:
  the list only adds.
- Never passed on, listed or not (ReplyHeaderPassable): Content-*,
  hop-by-hop and Transfer-Encoding (magpie writes the body it sends),
  Set-Cookie/Cookie/Authorization/WWW-Authenticate/Proxy-*/API keys,
  Access-Control-* and Sec-* (would let a page read magpie), Location,
  HSTS, CSP, Alt-Svc and the like, Retry-After/Cache-Control/Date/
  Server/Vary/X-Accel-Buffering (magpie's own), and X-Magpie-* (the
  gateway reads those as notes of a try). Save refuses such a name
  (ReplyHeadersOK); the editor says why before the save in every
  language (replyHeadersOf), its list held to Go's by
  TestReplyHeadersNeverAsTheProvidersAre; a name written by hand is
  dropped on read.

Where it's applied
- One choke point: forward (every model API, relayed or translated, a
  plugin's fetch, a signed-in account) and retrieveAs (embeddings,
  audio) tell the reply they return to the try that asked, through the
  try's context (withReplySink/heardReply). The sink is the try's
  holdWriter, so a try that fails and is let go takes its vendor's
  headers with it: a fallback's reply carries the answering provider's
  alone, and a failure released to the agent carries its own. Only the
  try's own provider is heard (a side model or searcher isn't); within a
  try the last reply replaces earlier ones (a refused beta asked again,
  a Mantle reroute); after the try has its status nothing more is heard
  (a cut reply's continuation). count_tokens writes them directly, and
  the passthrough effort-none probe's kept refusal counts as the reply.
- Not covered: images and video (#4211), and the Codex backend relay (which copies
  its reply's headers whole already). A stream whose headers keepAlive
  sent before the vendor answered (past keepHeldAfter) can't carry them.
- Docs: providers-accounts.md (Reply headers row), gateway-routing.md.

What was run
- New tests: TestReplyHeadersPassedOn (Anthropic relayed and Chat
  translated x whole and stream x 200 and 400), TestReplyHeadersOfThe-
  ReplyGiven (429 then fallback to another provider),
  TestReplyHeadersOnCountTokens, TestReplyHeadersOnEmbeddings (200 and
  400), TestReplyHeadersList, TestReplyHeadersNeverAsTheProvidersAre:
  pass on mote (macOS), on xiaomi-gpu (win-run) and in WSL (wsl-run).
- Broken by hand: without the main loop's withReplySink every
  TestReplyHeadersPassedOn subtest and the fallback test go red (ids
  ""); with the deny map ignored, Set-Cookie passes and 8 subtests go
  red; without count_tokens' passReplyHeaders its test goes red.
- gofmt -l clean; go vet ./internal/... for darwin, linux (-tags nogui)
  and windows: ok.
- At this commit rebased on 5f6a46630 (165a97b35; the plugin-move fix,
  a GUI test file only, came after the Go run) (wsl-run, magpie-desktop): gofmt -l clean; GOOS=linux -tags nogui and
  GOOS=windows go vet of gateway, provider and gui: ok. go test -tags nogui
  -count=1 -timeout 45m: internal/gateway ok 710s, internal/gui ok 1194s,
  internal/provider has one red, TestClaudeAccountServesModelsListedSinceItsFetch,
  which is #3174 (red in a full run, green alone). It passes 3 of 3 alone
  here.
- Earlier, at c1660481c on WSL: provider ok 235s, gui ok 1062s, gateway
  ok 1071s. win-run on xiaomi-gpu: the new tests ok.
- GUI at this head (WSL, chromium and webkit, en zh zh-TW ja de where the
  file runs them): the 32 files that reach the provider editor (Advanced,
  extra body, i18n), reply-headers.test.cjs and image-models-hide: 752
  pass, 2 fail. The fails were plugin-move webkit en and zh: the taller
  Advanced section made WebKit's last wheel land after the test read the
  scroll (367, then 397). Fixed in the commit before this one.
  provider-gemini webkit is red alone on origin/main 95b40fb2f too, in a
  different language each run: #4210. Earlier reds in a 32-file run
  (insecure-tls, native-compaction, limit-rest, unmasked, vertex-editor)
  passed alone.
- The mote GUI and Go run sat behind a load of 230-330 for 1.5h and was
  stopped with no result, so these ran on WSL.
- At the pushed tree (rebased on d95822eb3, 30 more files from main;
  app.js, i18n.js and provider.go among them), wsl-run: gofmt clean, vet
  ok, go test -run 'ReplyHeaders|Budget|I18n|Keys' of gateway, provider
  and gui ok. The GUI check of reply-headers, plugin-move and i18n-keys was
  still running when this was pushed.
- Real use: magpie serve (go build -tags nogui) in a sandbox HOME on
  mote with a fake relay and replyHeaders ["x-trace"]: /v1/messages
  translated to Chat, a streamed /v1/chat/completions and a 400 each
  answered with X-Oneapi-Request-Id, X-Request-Id and X-Trace, and no
  Set-Cookie or unlisted header.

Not tried: a plugin-served provider's reply (goes through forward like
the rest, no test with a real plugin host), a real one-api/new-api
relay, the whole GUI suite (32 files that touch the provider editor's
Advanced section, extra body and i18n were run), and a full ./... run.
2026-10-29 17:02:24 +08:00
yetone c3462d5fe8 gateway: a held stream gets its 200 after 3s, and a comment every 5s, so a proxy's 10s header cut no longer ends it 499
mrten_95615 (Discord, Windows): Codex through magpie to a relay ended 499
about 10s in once a turn's first token took longer than that. It happened
with a Clash-style app in system-proxy mode, not in TUN mode.

Cause:
- Codex (reqwest, hyper-util Matcher::from_system) sends its request for
  127.0.0.1 through the Windows system proxy. ProxyOverride is read only as
  IPs/CIDRs, so "127.*;localhost;<local>" doesn't keep it off. This was
  checked on xiaomi-gpu with Codex 0.165.0: mihomo logged 127.0.0.1:18431
  through the proxy.
- magpie held a stream's headers for up to holdLongest (15s) before
  keepAlive sent the 200 and its first `: keepalive`. A proxy that stops
  waiting for response headers after about 10s cut the request first, and
  Codex's context ended, which shows as 499.

Fix: keepHeldAfter is 3s, not 15s. Once the 200 is out, keepHeldEvery
(5s) is the most a held stream goes without a comment. Another candidate
can still answer in the same stream, and a failure before 3s is still a
status with its Retry-After. gateway-routing.md is updated.

Run:
- TestHeldStreamHeardBeforeAProxyCuts (new) is red on the old code with
  "headers 200 after 15.004s" and green after. It is green on mote together
  with the keepalive, queue and held tests (-run
  'TestHeldStreamHeardBeforeAProxyCuts|TestSilentHeld|Queue|Keepalive|KeptAlive|Held',
  ok 68.6s).
- End to end on xiaomi-gpu (Windows 11): Codex 0.165.0 goes through the
  system proxy, which is a Go proxy that cuts after 10s without headers,
  then magpie serve in a sandbox HOME, then a relay that holds its headers
  for 15s.
  - Old build: the proxy logged "CUT after 10.001s" on every try, the relay
    logged "client gone after ~10s", and Codex kept "Reconnecting... n/5".
  - New build: "headers 200 after 3.005s", then done at 15.0s, and Codex
    printed pong (exit 0).
  - The registry proxy settings were restored afterwards (ProxyEnable 0, no
    server or override), and none of the test processes were left running.
- On mote: gofmt -l is clean, and GOOS=windows/linux go vet -tags nogui
  ./internal/gateway/ is ok.
- On mote: go test -tags nogui -count=1 -timeout 45m ./... is ok except
  internal/gui TestCoreScriptBudget (1531531 > 1530861). That is red on
  main already, filed as #4133, and is not touched here.

Not tried:
- The reporter's own proxy app. mihomo's HTTP inbound doesn't cut by
  default, so which part of their setup cuts at 10s isn't known.
- A proxy that cuts on idle bytes rather than headers, end to end. Only the
  test's gap check covers the 5s cadence.
- Why turning the system proxy off didn't help until the app quit.
2026-10-29 10:43:59 +08:00
yetone b4267de595 gateway: a provider's fallback can be a routing group, routed as the group
01huadalang on Discord: "还有备用模型增加路由组的选择,现在只能选模型". A
provider's Fallback list held models only; a "group/<id>" entry resolved
to the group's first member alone. Now such an entry is served through the
group, as a request to the group would be:

- plan → planPaused: a fallback naming a group (provider.FallbackGroup,
  the group as routed, Live) hands its members to planLevel
  (planFallbackGroup): the group's own routing, its sink and asides, and
  its pause rules (serve passes provider.PausedOut for the agent's folder).
  Its trace rows are marked Fallback with the group in Via.
- No loop, each provider/model once a round: a member that is the primary,
  a model named earlier, or another fallback group's member is left out
  where it comes second. Groups have no fallbacks of their own and a
  member's fallbacks are not followed, so nothing leads back. A group that
  is gone or off is passed over, as a model none serves is.
- Every sibling that reads p.Fallback now reads a group's members through
  provider.FallbackModels: redaction (unredactedRoute: an unmasked
  provider with a fallback group holding a remote model is masked),
  careful accounts (carefulOf), native compaction, Codex's own turns
  (codexFallsBack) and Claude's auto-mode review (claudeReviewed, which
  moves from provider.Resolve to ResolveRoute, as the gateway reads
  fallbacks).
- CLI: `magpie provider fallback` already took group/<id> (Resolve knows
  groups); its usage and error now say so. Pinned by
  TestFallbackCmdTakesGroup.
- GUI: the provider editor's Fallback picker lists the routing groups
  (providers.gateway.groups) beside the models as chips with the Routing
  fan and a muted "routing group" tell; a picked group's row has the same
  fan and tell, and a gone one says "No routing group {id} now; it is
  skipped". A filter matches a group's name, id and its members'
  providers. New strings in zh, zh-TW, ja and de.
- app.js budget raised 187 bytes on main (1,311,922; core 1,531,060), the core's
  own editor, no room added; the addition was cut from ~900 bytes first.
- docs/subsystems/gateway-routing.md: the Candidates row says all this.

Not done: a fallback group's turn rules (ruleFor/ruleOver, which can ask
a classifier) are not applied. The plan is made before the primary is
tried, so they would cost a classifier call on every request the primary
answers. Its routing order, sink and pause rules are applied.

Run (at f6e7214af; after the rebase, the last bullet):
- gofmt -l: clean. mote: go build ./...; go vet on the touched packages;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: ok.
- mote: go test -timeout 45m ./...: every package ok except internal/gui:
  TestCoreScriptBudget (fixed above, then ok) and ten AppKit window tests
  (TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
  …) killed at their 30s bars while four other sessions' GUI suites held
  mote at load 70-110. Run alone, all ten
  pass (TestDockJoinLeadsCommandTab skips) except TestMainWindowCorners,
  red at base f6e7214af too (#3949); the load kills are #2645.
- GUI: the whole suite (962 files, node --test --test-concurrency=8) on the
  Linux box (WSL magpie-desktop, chromium + webkit): 14,217
  tests, 305 red in 99 files. Those 99 files rerun at base f6e7214af: 156
  red; at this head: 159; the ~20 that differ either way are flakes (the
  head-only ones, key-replace and vertex-editor, rerun twice on each: the
  same reds at base). Filed as #4120.
  fallback-group.test.cjs (new), fallback-more and i18n-keys: ok in
  chromium and webkit on mote and on Linux.
  After the app.js cut, at the final head: the three files 12 of 12 on
  Linux; webkit ok on mote, chromium there failed only at browser launch
  under load.
- Broken by hand, each red, then restored:
  - the group branch in planPaused off: all five gateway group tests red
    (TestFallbackToGroupServedByMember is red on the old code: only the
    first member was tried).
  - the dedup off: TestFallbackGroupWithThePrimaryTriesItOnce and
    TestFallbackGroupSharedModelTriedOnce red.
  - the pause filter off: TestFallbackGroupPauseHolds red.
  - redact.go from origin/main: TestFallbackGroupKeepsMasking red.
  - the GUI's group list off: fallback-group.test.cjs red in all four
    (chromium/webkit × en/zh).
- After the rebase onto 0daf36332 (18 commits, gateway.go among them;
  the budget test conflicted, kept main's and measured again): gofmt -l
  clean; mote: go build ./..., vet of the touched packages, linux and
  windows vet ok; go test internal/provider, internal/cli, internal/agent
  ok, and internal/gateway and internal/gui -run with Fallback, Redact,
  Unredacted, Careful, Compaction, CodexFalls, Budget, Rest and Probe ok; fallback-group, fallback-more, i18n-keys
  and rest-probed 52 of 52 on Linux.

Not tried: a real request through a real group fallback with real
accounts (the tests use fake upstreams); the Windows GUI; the TUI has no
fallback editor.
2026-10-29 05:19:28 +08:00
yetone 3627742104 gateway: an error read as out of credit moves on at any 4xx (#4095)
mycf_711 (#4095): SuperMagic answered an account with no points left
400 "非常抱歉,当前对话需要调用大模型 / 付费工具,您的可用积分已不足。
您可以点击右上角「用户头像」,通过「充值」通道补充积分…". failure() read
it as failCredit (creditWords: 充值), but retryable()'s 400/422 branch
asked quotaWords only, which has neither 积分, 不足 nor 充值. So
hw.failed() was false: the 400 went to the agent while another account
in the order had 6,467 points, and the empty account was never rested.

retryable() now takes any 4xx failure() reads as failCredit, after the
overflow check, so the two deciders agree on credit at every status
(400, 422, and the 4xx outside the always-retried list, 409 say).
Sibling: shapeRefused() kept out quotaWords but not creditWords, so a
shape refusal saying 请充值 would rest nobody; it now keeps out both.
Quota: usedUpWords (failQuota) is a subset of quotaWords, so 400/422
already agreed; a quota word at another 4xx (413's "exceeded the
limit" is the request's size) is left alone on purpose.

Tests (credit_400_test.go), with the reporter's literal body:
TestCreditRefusalIsRetryableAtAnyStatus (400/409/422, raw and as magpie
tells it on, plus shapeRefused) and TestCredit400MovesToTheNextAccount
(two keys: the empty one 400s, the next answers 200, the empty one
rests as credit 400, the next request goes straight past it).
docs/subsystems/gateway-routing.md says it.

Broken by hand: with the new case disabled and creditWords taken out
of shapeRefused, both tests are red (every status not retryable, the
shape case rests nobody, the request ends 400 after k-empty alone).
Run on mote, at 157d575c3 with both #4095 commits on it (the pushed tree):
go test -count=1 -timeout 45m ./internal/gateway/... ./internal/routes/...
ok (gateway 781s, routes 0.4s); gofmt -l internal/gateway internal/routes
empty; GOOS=windows and GOOS=linux go vet ./internal/gateway/...
./internal/routes/... ok. The same was green at the earlier bases
40f206dff and 7a7931833. Pushed on 99299c7b1, whose commits since
157d575c3 change only internal/edit's tests; not run again there.
Not tried: a real SuperMagic account at 0 points (the plugin 0.3.26
already turns this 400 into 402 there).
2026-10-29 01:14:42 +08:00
yetone 3ec25523cb provider: a plugin's 401 about the model keeps the account's sign-in (plugins#468)
A plugin that answered "this model isn't available on your plan" with 401
marked the account as needing a new sign-in, and the gateway fails a 401
over to the provider's next account (retryable in fallback.go), so every
account of the provider was marked "sign-in has expired" for credentials
that were fine.

notePluginSignIn now reads a 401 that carries no X-Magpie-Sign-In as
"kept" when its body says the model isn't served (provider.ModelUnserved,
the gateway's unservedWords moved here, read decoded by catalog.Words)
and nothing of a token, key, credential, session or sign-in. Only the
first 64KB is read, and the body goes on whole.

Not changed: the gateway still rests the account under its failure
backoff for that answer; modelRefused still reads only 400/403/404/422 as
the model refused. The guide asks for 403/404 (docs commit).

The 401 bodies the community plugins hold for a sign-in that is gone
(magpie-community/plugins 95fa761, every package's tests), each in the
test's "marks" list and none read as kept (none names a model, which
ModelUnserved needs):
- devin: {"code":"unauthenticated","message":"invalid api key" / "bad key"}
- zed: "unauthorized", "", {"code":"upstream","message":"bad key",...}
- cline: {"error":{"message":"nope"}}, {"success":false,"error":
  "unauthorized"}, {"message":"expired"}, "the sign-in lapsed — sign in
  again"
- raccoon: "unauthorized", {"code":200003,"message":
  "authorization_verify_error"}
- joycode: {"code":401,"msg":"登录票据已失效"}, "private-marker"
- zcode: "", {"code":1001,"msg":"Authorization Token非法"},
  {"error":{"message":"token expired or incorrect"}}
- mimo: "", {"code":401}, {"error":{"message":"stale"}},
  {"error":{"message":"Invalid API Key"}}
- cursor: "no", "Unauthorized — sign in to Cursor again in magpie",
  Connect's ERROR_NOT_LOGGED_IN body
- search1api: {"message":"expired"}
No plugin source builds a 401 whose text names a model.

Run (mote, at this tree): gofmt -l clean; go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./...; go test -tags nogui
-timeout 45m ./...
(go test -tags nogui -timeout 45m ./... at base 5bfd76cd8: 77 packages ok, none failed (log kept whole). Rebased onto 602ad84ad and run again there: vet on three OSes ok; go test -tags nogui -count=1 ./internal/provider (195s) ./internal/plugin (268s) ./internal/gateway (677s) ok. Rebased onto b5d2858f4 and run again: usage, provider, plugin, gateway ok. Rebased onto 87a983423, the pushed base, and run again at this tree: gofmt -l clean; go vet ./internal/... ok, GOOS=linux and windows go vet of provider, plugin, gateway ok; go test -tags nogui -count=1 ./internal/provider (126s) ./internal/plugin (180s) ./internal/gateway (588s) ./internal/codexcat (1s) ok. Then rebased onto 3ec9babe7 to push; its three commits (WorkBuddy mover min, redact, sessions) share no file with this one, and the same packages are run again at the pushed head after the push).
Broken by hand: with the check disabled (if false &&),
TestPluginModel401KeepsSignIn is red: "a 401 about the model marked the
sign-in: The model claude-opus-5 is not available on your plan".
Not tried: a real vendor answering a model-level 401 through a plugin.
2026-10-29 00:52:19 +08:00
yetone df9376592d routing: a group's member may offer several reasoning levels for the agent to pick among
Garydesu on X: "能不能让路由组里的模型设置多个可选推理强度,现在只能选一个或者整个
路由组的". A member was one fixed `:effort` or followed the group's levels.

A member's suffix may now join several levels with "+",
`provider/model:low+xhigh`, kept lowest first, each once. provider.MemberLevels
splits it into Member.Levels and leaves Effort empty, so the member isn't
fixed; one level is a fixed effort as before. The whole stays the member's
id, so rules, fast, off, weights, share and the CLI key it as any member.
The gateway fits the agent's ask to the member's own levels (groupLevels
returns the candidate's levels first; ofMember, the quiet check and the
trace see them), and the group lists them to agents (buildGroupEntries),
intersected with the other members' as usual. In the Routing page's group
editor the member's reasoning menu has "Several levels…", a menu that stays
open with each level ticked or not; a fixed level picked from the first menu
replaces the old one as before. i18n in zh, zh-TW, ja, de; CLI help and
docs/subsystems/gateway-routing.md say it.

Run on mote (mote-run). Rebased on efb55b5c9 (past e1721d640, which
changed the group editor) and run again there: provider, gateway, cli ok;
gofmt clean; GUI group-member-levels, group-member-fast,
group-member-weight, group-from-model-add and i18n-keys 53 of 54, the red
being i18n-keys' "masking…" from e296211b8, red on main (#4053). Linux
and Windows vet were clean at 7fe98c2af. Earlier, at the first base:
- go test -tags nogui -timeout 45m ./internal/provider ./internal/gateway
  ./internal/cli ./internal/tui ./internal/gui: all ok (gateway 525s).
  internal/cli again after the help wording below: ok.
- gofmt -l: nothing.
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go vet
  ./...: clean (darwin prints cgo warnings only).
- Whole GUI suite (node --test "internal/gui/tests/*.test.cjs", both
  engines, load 140 at its peak): 13,931 tests, 119 red in 31 files. One
  was this change: i18n-keys' "a plugin's words are its own", because the
  CLI help said "the agent picks among them" too; reworded the help, and
  i18n-keys passes. The other 30 files, run alone at --test-concurrency=4
  at this tree and at its parent e8c7dddcb: the same files red on both
  (97 and 100 cases, the routing-rule ones a random subset each run, all
  waiting on clicks), each with an open issue (#3527 lists the pattern;
  segs-press-redraw #3922, routing-story-shrinks #3954).
  group-from-model-add, account-*, login-import and signin-* pass alone.
- group-member-levels.test.cjs: 30 of 30 (5 languages, both engines,
  1100px and 420px); group-member-fast.test.cjs 4 of 4.

Broken by hand:
- groupLevels without the member's levels: TestMemberSeveralLevelsFollowAgent
  red (asked high, sent high, not xhigh).
- buildGroupEntries without the member's levels: TestMemberSeveralLevels red
  (offered all four, not low and xhigh).
- main's routing client.js: group-member-levels red 3 of 3 (chromium en).

Not tried: a real agent picking among a member's levels against a real
vendor; the TUI (its reasoning toggle cycles a "low+high" member back to
following the group, unchanged code).
2026-10-28 18:52:39 +08:00
yetoneandtimonwong 25fc92d59a fallback: a model unchecked in its provider's list is not a fallback to go to (#3911)
The sibling of the group fix before this: a provider's Fallback list
resolved each entry with Resolve, so a fallback the user unchecked in
its own provider's list was still sent to, while the fallback editor
says "No provider serves {id} now; it is skipped". plan's fallbacks,
and the places that read the same list (carefulOf, native compaction's
carrier check, unredactedRoute, codexFallsBack), now resolve through
provider.ResolveRoute, which skips it. ResolveRoute scans the entries
once for the one model rather than building a map per request.

Test: fallback_unpicked_test.go, plan/m answering 429 with fallbacks
a/x (unchecked) and b/x goes to b and never to a.

Run (mote): red on the previous commit's tree ("from ka", a tried
[ka]); green with this one. Full suite as recorded in the previous
commit, which ran at this tree: 76 packages ok, internal/plugin's
TestGatewayHookMixedPiPackage red at load ~134 (#2865), passing alone.
go vet darwin/linux/windows clean.

Not tried: a real provider with a fallback in the app.

Co-authored-by: timonwong <timon86.wang@gmail.com>
2026-10-28 17:34:16 +08:00
yetone e68327b217 gateway: an error carried in a 200 fails as its own status would
monater (Discord, #general): an OpenAI-format custom provider answered
gpt-6.1-sol with HTTP 200 carrying "Rate limit reached for gpt-6.1-sol
... on tokens per min (TPM) ... Please try again in 6ms." failure(200, …)
skipped every 429 case and fell to `status < 500 && usedUpWords`
("limit reached"), so the try failed as quota and rested 15 minutes,
shown as "200 quota used up". The same text as a real 429 has been a
rate limit since v0.1.1748.

One classifier: carriedStatus maps a 2xx/3xx body through streamStatus,
the reading already used for an error inside a stream, in failure,
failureOf and restAfterMarked. Words streamStatus doesn't know (its 502)
keep the 200 and read as before. insufficient_quota maps to 402 and
stays credit, as at 429.

Siblings:
- non-streamed 200 whose body is only an error (OpenAI/Gemini
  {"error":…}, Anthropic type:error, a failed Responses object):
  errorReply, read in holdWriter.settle, fails the try with that status,
  so it is retried or handed on instead of going to the agent as an
  answer; unheld, the passthrough sniffer books it failed (settleWhole),
  so the Requests list shows it red with its words.
- translated route (an Anthropic/Responses/Gemini client to a chat
  provider, plugins included): an error event with no status went out as
  502 and failed as "other"; it now takes streamStatus's status.
- Streamed passthrough with content then an error (the reporter's path)
  is covered by the failureOf/restAfter change.
Not changed: Codex's ChatGPT backend (always streams; its error events
already go through the same failure()), Claude Code's bridgeFailed and
tool_loop's relayStatus (own statuses).
The Requests list needed no change: a row with err is shown failed
(ledFailed_), "200 · <err_type>" with the reason as its tooltip.

Tests (carried_error_test.go, the reporter's literal text): failure and
failureOf at 200 equal 429's for it and for minuteLimitBodies,
restAfter at 200 is a rate limit's minute at 429, errorReply, the
sniffer, and end to end: a chat 200 error body and a Responses failed
object retried as rate and answered, a chat stream with content then
the error resting as rate at 429, and an Anthropic request translated
from a chat stream failing as rate.

Broken by hand: carriedStatus returning the status unchanged turns
the unit, rest and stream tests red (quota, 14m59s, Status 200: the
reported behaviour); errorReply off in settle turns both retried-body
tests red (the error went to the agent as a 200); translate back to
502 turns the translated test red ("other"); settleWhole a no-op
turns the sniffer test red.

Run (mote): go test -tags nogui -timeout 45m ./... at d8c70504d plus
this change: EXIT 0, 76 packages ok, internal/gateway 660s. Rebased on
origin/main (no gateway change in between); the new tests and gofmt -l
again at the pushed head. GOOS=linux and GOOS=windows go vet
./internal/gateway ok.
Not tried: a real relay answering 200 with this error; no GUI test run
(no GUI change).
2026-10-28 10:48:38 +08:00
yetone 08b02cf18c providers: a pool stops at its caps and reads usage again near them (plugins#349)
What was adopted on magpie-community/plugins#349 (1939869736luosi): one
place, in the GUI and the CLI, for a subscription's account pool, and an
opt-in conservative mode.

- Stop at the caps (Provider.CapStop, off by default): once every account
  in use is held at its cap, the request is answered 429 rather than going
  on to the provider's fallbacks (plan returns restLast). Off, as before.
- Check usage again near a cap (Provider.CapCareful, off by default,
  internal/gateway/cap_careful.go): before planning, a capped account's
  usage is read again when its reading is over 15s old within 5 points of
  a cap, or over 5m old at all; the request waits at most 10s, and a
  failed account is asked again at most every 15s. An account whose usage
  was never read, whose last read failed, or whose reading is still that
  old is then held as one at its cap is (capHold "unread", traced as
  Weighed.Unread, named in the 429 with "--careful off"). Generic: it
  goes by provider.UsageRead/ReadUsageNow, so every subscription that
  reports usage windows (Codex, Claude, plugins) gets it.
- provider: usedCache records each account's read state; a failed read
  keeps the last good reading's time. ReadUsageNow no longer reports
  false when the read had already finished on the first ask.
- GUI: under the provider's account list, once an account has a cap (or
  either is on), two ticks for the above, and a note naming the accounts
  in use with no cap ("used to 100% of each window"). Accounts, order and
  caps stay where they were in that list. zh, zh-TW, ja, de added.
  app.js 1,309,658 within its 1,310,460 budget, unraised: addRow and a
  per-row forgetOf replace 3 add-button and 5 Remove-button builds.
- CLI: magpie provider pool <id> [--accounts a,b,…] [--cap percent|off]
  [--stop on|off] [--careful on|off] shows and sets the whole pool.
- docs: gateway-routing.md and providers-accounts.md.

Run (mote, before the rebase at 8bade6c5e + this change):
- go test -tags nogui -timeout 45m ./...: exit 0, 76 packages ok, no
  FAIL (log grepped).
- GOOS=linux and GOOS=windows go vet of cli, gateway, provider, gui: ok.
- pool-ends.test.cjs: 32/32, Chromium and WebKit, en zh ja de, 1100 and
  420 wide.
- The 81 GUI files whose fixtures have accounts or caps, plus i18n*,
  6 at a time at load ~130: 76 pass. i18n-keys is red on the base too
  (#3897). account-mask (#3951), account-alias (#2984),
  signin-closes-sheet and signin-again timed out under load and pass
  run again, as on the base; signin-again filed as #3960.
- Real plugin host: TestPluginCarefulPool runs the fake plugin under Bun
  as Factory with two accounts capped at 90%: a failing usage call gives
  429 with nothing sent upstream while careful is on, the last reading
  is used with it off, a good read sends to A again, and with both at
  their caps the fallback serves unless Stop is on.
- CLI binary in a sandbox HOME on mote: unknown provider, a bad --stop
  value and no id each refuse and change nothing.
At the rebased head (0a7633136 + this): gofmt -l
clean, go build ./..., the new Go tests and the budget tests, and
pool-ends.test.cjs 32/32.

Broken by hand, each seen red, then restored:
- the CapStop line in plan: TestCapStopSkipsTheFallbacks and
  TestPluginCarefulPool red;
- the careful hold in capHeld: the three careful tests and
  TestPluginCarefulPool red;
- careful always on: TestCarefulOffByDefault red;
- readCareful not called: the failed, never-read, stale and re-read
  subtests red;
- a failed read not keeping the good time, or not counted as failed,
  and ReadUsageNow's early return forced false: TestUsageReadAndReadAgain
  red;
- the ticks' onchange emptied: pool-ends.test.cjs 16 of 16 red.

Not tried: a real Factory or any real account (fake plugin only); the
whole GUI suite (932 files, ~5h at this load), only the 81 files that
reach the account list; Linux WebKitGTK and Windows; the 15s/5m/5-point
figures against a real vendor's usage endpoint latency.
2026-10-28 09:29:44 +08:00
yetone b10f43e899 gateway: another magpie's key limit rests that magpie whole when relayed, and its marker stays here (#2791)
restAfterMarked reads a failed try's held header, which keepRetry
fills from the upstream's reply. keepRetry kept Retry-After and the
rate-limit reset headers but not X-Magpie-Limit-Reset
(remoteKeyLimitHeader), so a remote magpie's gateway key over its own
limit read as that one model's rate limit (remoteModelRest): the model
rested alone and the remote's other models were asked into the same
refusal.

Patch by ggbdpq (#2791): their test and the cause are theirs. Changed
from it: the patch whitelisted the raw marker into the held header,
and holdWriter passes that header on to the client, so the marker
reached the agent and, in a chain, a magpie asking this one, which
would rest all of this magpie for one key there. keepRetry now sets
an internal note (keyLimitThereHeader) that remoteModelRest reads and
holdWriter drops, with answeredThereHeader. The two keepRetry sites
that write to the client directly (count_tokens, decide_group) go
through keepRetryOut, which drops both notes; answeredThereHeader
leaked there before too. Doc sentence in gateway-routing.md.

Run (rebased on origin/main):
- TestRemoteMagpieKeyLimitRestsTheRemote (theirs): red with the note
  taken out of keepRetry by hand (rested office/glm/glm-5 and kimi, not
  office), green now.
- TestRemoteMagpieKeyLimitMarkerStaysHere (new): red with the patch's
  raw marker copy ("the agent's reply carries X-Magpie-Limit-Reset"),
  and red with keyLimitThereHeader taken out of pass()'s strip list
  ("carries X-Magpie-Key-Limit-There"), green now.
- RemoteMagpie|AnotherMagpie|KeyLimit ok; the whole internal/gateway
  package (-tags nogui -count=1 -timeout 45m) ok in 476s at fc860f2e6.
- gofmt -l clean; go vet ./internal/gateway for darwin, GOOS=windows,
  GOOS=linux -tags nogui clean.
Not tried: two real magpies over a network with a key limit hit.
2026-10-28 00:27:02 +08:00
JoeyWu-tech 47175a68ff gateway: an error in a kept-alive stream names the model the agent asked for (#3728)
jilen (#3728): fx asked magpie for codex/gpt-6.1-sol on
/v1/chat/completions and showed "system: InvalidChunk: Invalid Chat
Completions response at model (event 1).", while the usage log had the
vendor's 502, an EOF from chatgpt.com. No stream was saved, but fx's
InvalidChunk at event 1 says one had begun: magpie had kept fx alive
with the stream's headers and comments, so the failure went as an
event of that stream (streamError). The encoder streamError made, from
an empty Request, began the message before the error with a Chat chunk
whose "model" was "". fx takes a chunk with an empty model for a broken
one and stops there, so it never read the error after it. Anthropic's
message_start and Responses' response.created, response.in_progress
and response.failed went out with an empty model the same way.

keptAlive now keeps the model the request names when serve takes it,
as magpie spells it there: a flat id (a~m) is its catalog id, a dashed
Claude id its dotted one, and Codex's own model through magpie's
accounts codex/<model>. An effort the agent put on the model is kept on
it (a/m:high), the name it asked by. serve has it from the body it
already read for askedAt; on Codex's own sign-in (codexUpstreamOn) it
is the model Codex wrote, which its turn already read. Neither reads
the body again. streamError begins with that model, from failTo,
holdWriter.release and Codex's failWith. Gemini's error names no model,
as before. docs/subsystems/gateway-routing.md says so.

fx still shows no reason. Its Chat reader ends the stream with
ProviderError at an event with an "error" key and keeps nothing of it
(src/gateway/chat_completions_protocol.zig:723 in fx 0.0.14, :710 on
fx's main e71a663b); only an error status's body reaches its message.
So fx says ProviderError where it said InvalidChunk, and the vendor's
EOF is in the stream and magpie's usage log, not in fx.

Not changed: an error after a reply that already went, a loop cut's
(cutLoop), starts a message of its own after the vendor's, under a new
id. A model in it wouldn't help, fx stops at the new id: #3792. Nor the
error's shape: the encoders still begin a message ahead of it. fx looks
for an event's "error" before its id and model, so an error alone would
get past it too, but no other agent was tried on one; that is #3792's
question as well.

What was run (tree 908b9857, on origin/main 2beed3b0, go1.26.8,
linux/amd64):
- TestStreamErrorNamesTheModel, new: streamError in each protocol with
  the report's model and message. Chat's, Anthropic's and Responses'
  events name that model and no other, Gemini's none, and each has the
  message.
- TestKeptAliveChatErrorNamesTheModel, new: a Chat stream through serve,
  kept alive while the vendor says nothing, then the vendor gone with no
  reply (the EOF), or answering 502, 413, a 200 that isn't a stream, or
  a JSON 200 that is no reply. In each, the stream's first chunk names
  a/m and the error follows; the 413's says request_too_large. Asked
  for a/m:high, the vendor gone, the first chunk names a/m:high.
- TestKeptAliveChatOnCodexErrorNamesTheModel, new: the report's route, a
  Chat stream on magpie's codex provider (Codex's sign-in), the ChatGPT
  backend a local server that says nothing until the stream was kept
  alive and then hangs up, each time it is asked. The first chunk names
  codex/gpt-5.5, and the error after it has the backend's EOF.
- TestKeptAliveCodexErrorNamesTheModel, new: Codex on its own sign-in,
  the backend overloaded, Codex kept alive while the turn waits to be
  asked again, then the backend gone. Every model its events name is
  gpt-5.5, the model Codex asked for, and they name one.
- The four, -count=50: ok.
- -race -count=20 -cpu 1,2 over them and the stream tests beside them
  (TestStreamError*, TestGroupLastFailureInStreamSaysItPasses,
  TestStreamedByteCap, TestLoopEnds, TestLoopCutMidLine,
  TestCodexOneAccountOverload, the Quiet ones): ok, no race.
- Broken by hand, each red:
  - streamError's encoder made from an empty Request again:
    TestStreamErrorNamesTheModel, every case of
    TestKeptAliveChatErrorNamesTheModel,
    TestKeptAliveChatOnCodexErrorNamesTheModel and
    TestKeptAliveCodexErrorNamesTheModel.
  - serve's keptAlive with no model: every case of
    TestKeptAliveChatErrorNamesTheModel and
    TestKeptAliveChatOnCodexErrorNamesTheModel.
  - keptAlive given the model without its effort: the a/m:high case
    alone.
  - failTo naming none: the 413 case.
  - holdWriter.release naming none for a reply that is no reply: the
    JSON 200's case; for an error status: the vendor gone, a/m:high,
    the 502, the 200 that isn't a stream, and
    TestKeptAliveChatOnCodexErrorNamesTheModel.
  - Codex's keptAlive with no model, or its failWith naming none:
    TestKeptAliveCodexErrorNamesTheModel.
- A real run: magpie built at 2beed3b0 and at this tree (go build
  -tags nogui -buildvcs=false), magpie serve in a sandbox HOME, a
  provider (a local server) that holds its first answer 20s and then
  hangs up, or answers 502, and fx 0.0.14 asking it through
  /v1/chat/completions (fx ask, its settings' provider
  openai-chat-completions at the gateway), with --json and without.
  fx exits 1 after about 53s each time: InvalidChunk at 2beed3b0, all
  four times (hang-up and 502, --json and not), ProviderError at this
  tree, all four. curl asking the same: ": keepalive" lines, then a
  first chunk with "model":"" (2beed3b0) or "model":"up/m" (this
  tree), then the error with the vendor's EOF or 502.
- gofmt -l; go vet -tags nogui and go build -tags nogui for linux,
  windows and darwin, and go vet and go build for windows without the
  tag: exit 0 each. go vet and go build without the tag on linux: exit
  1 (this box has no GTK or WebKitGTK dev packages).
- go test -tags nogui -count=1 -timeout 45m ./..., Bun 1.4.2 on PATH:
  67 ok, and 7 red, none in what this changes: agent
  TestCodexDriftReached (#3398); TestInstalledVersion,
  TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); davsync
  TestSyncTeraCloudStillSeesOtherWrites (#3420); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (#3640);
  gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649); provider's "close of synctest channel from outside bubble"
  from TestUnreadLoginsWriteErrorsKeepCredentials (#3632).

Not tried: the real chatgpt.com (it needs a ChatGPT account); the
ChatGPT backend was a local server that hangs up. fx's interactive
view, where the report's line came from.

Review (yetone/magpie maintainer agent), for jilen's #3728:
- Read every line. The only encoder built with an empty Request is
  streamError's; its five callers (failTo, holdWriter.release's two
  cases, cutLoop, Codex's failWith) are each given a model, cutLoop ""
  on purpose (#3792).
- Red by hand at c711c3391 on 1cbdda25b, macOS, go1.27: streamError
  back to &Request{}: all four new tests red; keptAlive built without
  model: the two Chat kept-alive tests red; Codex's kept.model unset:
  TestKeptAliveCodexErrorNamesTheModel red. Green restored.
- go test -tags nogui -race ./internal/gateway -run
  'NamesTheModel|TestStreamError': ok. Full go test -tags nogui
  -timeout 45m ./internal/gateway: ok (573s).
- gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet
  ./internal/gateway: ok.
- Real run: magpie serve (base and patched builds) in a sandbox HOME, a
  fake Chat vendor that holds 20s then answers 502, a streamed
  /v1/chat/completions for fakev/fake-model. Base: the kept-alive first
  chunk says "model":"", then the error. Patched: "model":
  "fakev/fake-model", then the same error.
- Rebased onto ab546a4ee (gateway changed since): gofmt, vet linux and
  windows, and go test ./internal/gateway -run
  'NamesTheModel|StreamError|KeptAlive|KeepAlive|Alive|Codex' again
  there: ok. The full package ran at the earlier base only.
- Not tried: fx itself, the real ChatGPT backend.
2026-10-27 16:05:50 +08:00
yetone ff16f6c552 gateway: a remote magpie's providers are each a vendor of their own to a conversation (fremontdango)
fremontdango on Discord ran two magpies. On the local one, a routing
group held one model from two providers of the remote magpie
(office/first/m, office/second/m). Its conversations were kept as if the
two were one vendor, because both are the one remote-magpie key here
(candidate.who()). The same group made on the remote behaved
differently:
- strict: when the first provider ran out, the conversation failed over
  to the second, though strict means it never moves
- session/auto: with the first gone, the "same account, other model"
  match kept the conversation on the second as "session", though nothing
  of it was cached there
- the second's refusal of the first's sealed reasoning was recorded
  against the whole remote, so the first's own seals were then taken out
  of requests to it
- a native compaction one sealed went to the other too

There is now a vendor identity for these: candidate.vendor() and
sameVendor(who, model). Behind a remote magpie it is the key plus the
remote's provider, the model id's first part (remoteUpstream). A remote
group is one vendor by its whole id, and a model named without a
provider is the key alone. It is used by:
- affine's widest match
- strictOnly and strictKeep
- unanswered
- refused/withoutRefused
- checkpointReaders (native compaction)
- Codex leadFirst
Lanes, requests a minute and leastHeld's per-model seat stay on who(),
the limits the user set on the key here. Sticks and compaction writers
are stored as before (who plus model), so the sticks saved on disk still
match after the update. Only the local magpie (the one with the group)
needs this version.

Run:
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
  (559s) at 040a4ec29. After rebasing onto ab546a4ee (busy.go,
  draw.go, gateway.go changed upstream): vet, gofmt and -run
  'TestRemote|Strict|Affinity|Stick|NativeCompaction|Refused|Lead|Busy|Draw':
  ok
- go vet (darwin, GOOS=linux, GOOS=windows, -tags nogui)
  ./internal/gateway, and gofmt -l: clean
- Two sandbox magpies, each under its own HOME/XDG dirs: the remote on
  127.0.0.1:47611 with providers first and second (model m1, one fake
  upstream on :47613 that answers 429 to first's key once a flag file
  exists), and the local on :47612 with a Remote magpie provider and a
  strict, ordered group of office/first/m1 and office/second/m1. Turn 1
  of a session went to first. With the flag set, turn 2:
  - local on origin/main: 200 from office/second/m1 (moved)
  - local on this change: 429 "Office: First: usage limit reached"
    (kept), and a new session went to second

Broken by hand: sameVendor reduced to c.who() == who made
TestRemoteMagpieStrictKeepsTheRemotesProvider fail (went to second) and
TestRemoteMagpieOtherProviderIsNotTheSameAccount fail (traced
"session", want "gone").

Not tried: the sealed-reasoning and native-compaction paths through a
real remote. They use the same sameVendor/vendor, and the package tests
for them pass. Three layers (local, middle, remote): the middle's
provider is the vendor here, and the middle keeps its own providers
apart.
2026-10-27 16:05:23 +08:00
yetoneandMYCF711 6afbe3f304 routing: a member too small for the request keeps its row and says why (#3749)
roomy leaves out a member whose model's context window the request is
longer than, and the trace dropped it from the order with no word of
it: on the Routing page its row went away, and the reason was only an
absence. Now the trace lists it in the route's left with Weighed.window
set to the window it lacked. Its row stays, faded as a seat held out
is, and says "request longer than its 200K window · passed over"; the
why list says it is left out because the request is longer than its
context window, and is asked only once every one with room is out of
its allowance (en, zh, zh-TW, ja, de). When the last resort does ask
it, its row moves from left to the order with window cleared, as
askUnlisted and unhold move theirs.

MYCF711's patch (pr/small-seats) added a Route.Small list and a row
map fix. This takes their finding but not the shape: left already
carries seats not asked (unlisted, capped, out of credits), so a new
flag on Weighed reaches the page, the session copies and the last
resort without a second list, and the row map bug they fixed doesn't
exist on main. Limit: roomy fills smallW only when the order has one
row per candidate (pl.order parallel to the candidates); a member left
out otherwise still shows only by its absence, as before.

Run: go test ./internal/gateway -run
'Roomy|TooSmall|Small|Window|Trace|Left|Unhold|AutoReset' ok;
go test -timeout 45m ./internal/gateway/...
./internal/provider/... at fcf2a5271 plus this change: gateway ok
(426s); provider crashed in TestUnreadLoginsWriteErrorsKeepCredentials
(synctest close outside bubble, #3632) and with it skipped is ok. gofmt -l clean; GOOS=linux go vet -tags nogui and
GOOS=windows go vet of ./internal/gateway clean. go test
./internal/gui -run 'CoreScriptBudget|I18n|Strings|Plugin' ok.
tests/routing-small-seat.test.cjs (new), chromium and webkit,
en/zh/zh-TW/ja/de at 1100px and 420px: 11/11 each. The routing, panel-routing and
i18n GUI files, both engines, concurrency 3, load 40-280 from other
sessions: 1468 tests, 1410 pass, 58 fail. The reds are in
routing-pause (#3410), routing-rule-effort (#3411), intent-entry
(#3408), keys-fold (#1612, #2658), live-patch (#3637), rule-remove
(#3094, #3096) and the unfiled ones in #3786, plus seven more files
(agent-hue-not-red, columns, order-unknown, rule-remove, levels,
ctx-fold, many-keys). Those seven alone, one at a time: 68/81 here,
69/81 on origin/main d56c14e95, with only rule-remove red on both
(13 and 12). None of the red fixtures builds a left: list.
Again at the pushed head, on f92db4cdd: gofmt, linux/windows vet,
the gateway -run set above and the gui Go tests ok; routing-small-seat,
routing-free-seat, routing-held-member and i18n-keys 68/68.
Broken by hand: TestMemberTooSmallIsNotAsked red with smallW not
added to Left, and TestMemberTooSmallIsTheLastResort red with Left not
pruned after the last resort; routing-small-seat 0/11 on the client
without this change.
Not tried: a real request past a real 200K member's window in the
GUI; the trace was built by the gateway tests and the page by fixture.

Co-authored-by: MYCF711 <MYCF711@users.noreply.github.com>
2026-10-27 03:02:50 +08:00
yetone d56c14e953 gateway: a single provider's busy or briefly rate-limited reply is waited out, for its own Patience (zoecats)
zoecats on Discord: a request to one provider (not a group) got a local
relay's short 429 straight back in Claude Code once the few same-one
retries were spent. A group would have held the agent and asked again.

A plain provider now takes the group's replan path (patience.go: replan,
pauseAlive, the held writer) once passing's same-one retries are spent:
its accounts take turns as members do, each pause never shorter than the
Retry-After, and a streaming agent gets keepalives past keepHeldAfter.
- Zero-config: unset, it waits singlePatience, PatienceDefault (60s),
  counted from when the agent would have had the error.
- The user's value wins: Provider.Patience, the same values as a group's
  Patience, set with `magpie provider set <id> patience=2m|off|default`
  (at most 4m). The provider editor has no row for it (no new UI), and its
  save keeps it. A group the provider is in keeps the group's own.
- Not retried: a Retry-After past the budget, quota/credit/plan limits,
  401/403, refusals, response protection, didNotStream, and an agent
  that has gone (499, try marked Gone).
- The try is traced with Again alone, so the Routing page tells it as
  "tried again in …".
- codexReset (ChatGPT's 503 for a large request) is left out of the
  plain-provider replan, so Codex still gets its 503 with advice.
- Codex's own one-account relay (codexUpstreamOn) does not join. It is
  relayed outside the candidate loop, and its backend 429 is always the
  plan's usage limit (codexBusy never retries one), so the short rate
  limit this waits out doesn't arise there. Its overloads keep
  lastRetries and then fallbacks.

longestPause became a var so tests can scale it. Tests updated for the
new count (1 + retries + replanRounds when it never clears):
- TestLastOneLeftIsTriedAgain
- TestRateLimitIsWaitedOut
- TestQueuedStreamFailureIsTheStreamsError
- TestOverflowTheVendorDidntSay

New tests, through the server with a fake upstream and injected
durations, waiting on trace state, not a duration:
- TestSingleProviderWaitsOutAShortRateLimit (stream and whole: 200,
  keepalive before the answer, asked twice)
- TestSingleProviderPassesALongLimitThrough (an hour, quota, 401)
- TestSingleProviderAgentGoneInTheWait
- TestSingleProviderOwnPatienceWins (off, shorter and longer than the
  default)
- TestPatiencePair (cli)
- TestProviderSaveKeepsPatience (gui)

Broken by hand, each red, then restored:
- singlePatience fallback 0 for a plain provider: WaitsOut stream and
  whole got 429, and AgentGone never paused.
- replan's budget check off: PassesALongLimitThrough/an_hour, "magpie
  waits to ask again".
- pauseAlive's ctx.Done case removed: AgentGone, "route done false
  status 0".
- The gateway ignoring Provider.Patience: OwnPatienceWins off, shorter
  and longer all red.
- The GUI save not keeping Patience: TestProviderSaveKeepsPatience,
  "patience 0 … want -1 kept".

Run in this tree, before the rebase:
- go test ./internal/gateway ./internal/cli ./internal/gui: ok.
- ./internal/provider: ok with -skip TestUnreadLogins. That test crashes
  with "close of synctest channel from outside bubble", the known #3632,
  in filememo and not touched here.
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: all 0.
- go build for darwin, linux (nogui) and windows: ok.

Run again after rebasing on origin/main 39526c069 (17 commits, 22 files
in gateway/provider/cli): gofmt, go build, go vet on the four
packages, the replan, retry, overflow and Codex-reset tests, and every
new test: all ok. The whole gateway package was not run again there.

Not run:
- The full ./... suite: machine load ~150, other sessions' suites
  running.
- A real vendor's 429.
- The GUI suite: no GUI file changed.
2026-10-27 02:26:27 +08:00
yetone 1360689ef2 provider: Served is shared while a request holds the catalog, not copied for each look (#3725)
Served built a fresh copy of the whole catalog on every call: the
unlisted groups' entries plus every provider entry. An Entry is ~1.3KB,
and a request looks at Served from outputLimit, userOutput, askedOutput
and windowIn, so with 12 providers of 20 models each look copied ~380KB
and a request ~800KB, all garbage by the reply.

Served now goes through heldFrom like providerEntries: one slice, built
once while a request holds the catalog and kept across requests until a
file it is built from changes. It is clipped, so a caller's append makes
its own copy and never reaches the next caller. The four gateway loops
take each entry by pointer instead of copying 1.3KB a step. Every
caller of Served (gateway, gui, cli, tui, agent, provider) was read for
writes into the slice or its entries; all only read.

Measured on BenchmarkZZIO (12 providers x 20 models, an 8KB request,
not committed): 1.57MB allocated per request before, 640KB after.

TestServedSharedWhileHeld: under Hold two calls give the same backing
entry, and an append to one doesn't show in the next. Red on the old
code (a new copy each call), green now.

Run at f2aa7fe34 (origin/main plus this change): gofmt -l clean on
internal/gateway and internal/provider; GOOS=linux and GOOS=windows go
vet -tags nogui ./internal/gateway ./internal/provider ok; go test
-count=1 -timeout 45m ./internal/provider (skipping
TestUnreadLoginsWriteErrorsKeepCredentials, #3632) ./internal/gateway
./internal/gui ./internal/cli ./internal/gwmw all ok.
2026-10-27 01:55:25 +08:00
yetone b5d17b26e0 gateway: Antigravity's 429 to Codex's GPT-5 prompt says why and rests nothing, on the web-search path too (Jodiezzzzzz on X)
From Codex, every call to antigravity/claude-opus-5-5 failed with
"exceeded retry limit, last status: 429" while dsh worked on the same
account. The call was an agent_created_thread, and the vendor said
"Resource has been exhausted (e.g. check quota)".

Cause: a Codex thread begun on a GPT-5.x model keeps "You are Codex, an
agent based on GPT-5..." as its first developer message after /model,
resume -m or a fork, and magpie lifts it into systemInstruction.
Antigravity answers that line with a fake 429, whatever quota is left,
as it does Claude Code's (#666). Codex also sends a web_search tool every
turn, so for an Antigravity model magpie serves search itself (translate
-> searchReply -> askTranslated), and that path passed the bare 429 back:
no hint, no 400, so Codex retried to its limit.

- antigravityTurnsCodexAway: the two Codex GPT-5 opening lines count as
  a turned-away prompt; antigravityHint picks the Codex hint for them.
- antigravityRound wraps the search path's ask, so its 429 and an
  in-stream refusal get the same 400, hint and no rest as translate's.
- antigravityForeseen returns the hint, so a group skips Antigravity for
  the next 6h saying which prompt.
- The Routing page shows the new hint (routing/client.js HINTS) in en,
  zh, zh-TW, ja and de.
- Rest: none. The refusal is about the prompt, not the account (Fail
  "prompt"); a second account answers the same.

Plugins: middleware-antigravity-cloak 0.1.1 (plugins a52d1b3) breaks
the two Codex lines with U+200B. Its body says "npm had 0.1.0": wrong,
the package is not on npm; dist had 0.1.0 and now has 0.1.1 (6fd1438).
No mover applies.

Real account (owner's Antigravity, sandbox HOME copy, gateway built from
this branch) and real Codex 0.162.1:
- codex exec resume <a gpt-5.5 thread> -m antigravity/gemini-3-flash:
  before, 429 retried to "exceeded retry limit"; after, one request and a
  400 with the Codex hint; route try (429, prompt), no rest.
- A new Codex chat on the same model: 200.
- The two lines with U+200B after the first letter: 200; whole: 400.

Broken by hand:
- antigravityTurnsCodexAway returning false: the Codex tests go red
  (Codex got 429; the group's skip doesn't say why).
- The antigravityRound wrap removed: the search=true subtests go red
  ("Codex got 429").

Run:
- go test -count=1 -timeout 45m ./internal/gateway/: ok (476s, at
  865df2472; main's next three commits touch only GUI files).
- go test -count=1 -timeout 45m ./internal/gui/: ok (230s, at the pushed tree on a6d7e02c7).
- gofmt -l: clean; go vet ./internal/gateway/ for darwin, linux, windows.
- GUI, chromium and webkit: routing-ag-turned-away, i18n-keys, gui-ja,
  gui-de, gui-zh-tw, routing-wb-refused, routing-blocked 41/41; at the
  pushed tree routing-ag-turned-away, i18n-keys, routing-steps-cap and routing-js 34/34.
- Rebased on b9ab17231 (routing client.js): routing-ag-turned-away,
  i18n-keys, routing-free-seat 45/46, the red webkit zh-TW `.rt-day`
  click timeout at load 163 (#3781's class); routing-ag-turned-away
  alone 20/20 after. go test -run 'Budget|I18n|Hint|Routing' on
  internal/gui and internal/gateway: ok.
- Rebased again on 68ee4117a (gateway: gemini_schema, unrouted,
  masking wait): gofmt, vet x3, and go test -run
  'Antigravity|CodeAssist|Search|Gemini|Unrouted|Masking|Translate|Continu'
  ./internal/gateway/ ok; the whole package was not run again at this
  tree.
- Under load 89-150: TestTrayCellClickReleasedPanel killed at 20s
  (#2645), routing-js webkit zh (#3774), panel-routing and
  routing-zcode-blocked webkit zh click timeouts (#3781). All pass alone.

Not tried: Claude Opus itself (the sandbox account's free-tier Claude
quota was spent while probing, so gemini-3-flash stood in; the prompt
check is model-blind); the cloak installed in a running magpie; the
Windows box; the full GUI suite.
2026-10-27 01:33:53 +08:00
yetone 6e6aba51c8 providers: a key may be for another plan of its vendor, sent to that plan's endpoints
yckonnnn on X uses Volcengine's pay as you go and its Agent Plan, and
wants a key of each in one provider. Each plan takes its own keys at its
own endpoints (/api/v3, /api/plan/v3, /api/coding/v3), and every key of
a provider went to the provider's one plan, so only one kind worked.

A key now may say which of its preset's Regions it is for
(KeyAccount.Plan; Provider.KeyPlan for the first key, as KeyProtocol).
None, or the provider's own plan, is the provider's plan, stored as
none: old configs read and write as before. Presets whose plans take
keys of their own (PresetDef.KeyPlans): zhipu, zai, stepfun,
stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud,
volcengine, siliconflow. Not: yylx (one key everywhere),
bailian-decision (decide only), bedrock and bedrock-mantle (regions of
one account).

Every reader of the region or a base URL, and what it does now:
- WithKey (keys.go): moves the key's copy to its plan (atKeyPlan:
  Chat, Responses, Anthropic, Decide, KeysURL, Website, Catalog via
  atRegionOf; a provider at a host of its own keeps that host) and marks
  it keyView. Every gateway key path goes through it: chat, Responses,
  Messages, count_tokens, failover, embeddings (serveRetrieval via
  onKeys), drawing (drawOnAccounts via perKeyBarred), key tests
  (test.go), key_models.go, gui/groups.go, markedKey.
- perKeyBarred (gateway/fallback.go): a key whose plan's list lacks the
  model (PlanServing) is not asked; only when no key's plan has it.
- fetch / fetchPerKey / planOnly (models.go): a mixed provider lists
  each key's plan, a NoList plan from its preset list with no request,
  pay as you go from /api/v3/models with its own key.
- planMedia (PlanEmbeddings, PlanDrawers, PlanVideos): every plan's.
- PlanQuotas (planquota.go): each key read at its own plan's source.
- volcPlanQuotas, tencentPlanQuotas: one view per plan (planViews).
- KeyBalances (balance.go): each key at its plan's host (SiliconFlow).
- startVideo / videoMaker (gateway/video.go): a mixed provider starts on
  a key whose plan makes the model (onKeys) and names it in the id
  (keyMark), so the poll goes to that key's plan.
- GUI: POST /api/keys/plan (SetKeyPlan, then the lists are read again);
  the editor keeps KeyPlan with an unchanged first key, typed() clears
  it with a new one; KeepSecrets, AddCopy, backup's withoutKeys carry it.
- app.js: planPicker, a plan chip in each key row (the app's own menu,
  openProtoMenu, through pickPill, which protoPicker now shares), shown
  for a KeyPlans preset while the provider has several keys or the key
  has a plan; i18n zh, zh-TW, ja, de.

A key's plan is not guessed from the key: Volcengine's keys carry
nothing that says their plan. Xiaomi's tp-, Tencent's sk-tp-, MiniMax's
sk-cp- and Bailian's sk-sp- are noted in code but not used.

Not done: a gateway key held to some keys (videoAsker) on a mixed
provider's video may pick another key; a mixed provider whose own plan
has no balance source while a key's plan has one is not read; keys left
out for their plan don't show in the Routing trace; StepFun's plan
windows are a sign-in per site, unchanged.

Credit: yckonnnn on X (tweet 2114657701305487483).

Run at this commit on origin/main 1bb8143b3 (macOS, go1.26.8):
- gofmt -l internal: clean. go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- go test -count=1 -skip TestUnreadLoginsWriteErrorsKeepCredentials
  ./internal/provider/ ./internal/gateway/: ok (103s, 421s). The skipped
  test crashes the whole provider package on main (#3632, from 091153bf).
- TestCoreScriptBudget: ok, budgets not raised (app.js 1,307,430 bytes).
- GUI, chromium and webkit: key-*, provider*-*, add-sheet, i18n-keys,
  gui-de, gui-ja, gui-zh-tw (58 files): 956 of 956 pass. key-plan.test.cjs
  covers en, zh, zh-TW, ja and de at 420 and 1000px.
Earlier, at the same change on origin/main 9120acaff:
- go test -timeout 45m ./...: 71 packages ok, internal/gateway and
  internal/gui among them. internal/provider crashed on #3632 only; run
  again with that one test skipped, it passed.
- The whole GUI suite (node --test tests/*.test.cjs) did not finish: the
  disk ran out at about 319 tests and the run was stopped. Up to then the
  only reds were account-discovery in both engines, #3497, red on main.
Broken by hand: without atKeyPlan in WithKey, TestKeyPlanEndpoints,
TestKeyPlanModelList and TestKeyPlansEachToItsOwnEndpoint go red; without
the planless filter in perKeyBarred the gateway test goes red; without
the plan chip key-plan.test.cjs goes red.
Not tried: real Volcengine (or any other vendor's) keys of two plans in
one provider; the video path (startVideo with mixed plans) has no test of
its own; Windows and Linux were vetted, not run.
2026-10-26 20:37:07 +08:00
yetone 6e96903346 codex: auto-review follows the session on a ChatGPT Free plan (cybercaius)
cybercaius on Discord measured codex-auto-review spending a Free
account's allowance ("实测在 free 账号不免费"). magpie left an unset
auto-review to Codex (codex-auto-review), and held such a call by no
usage cap, on #1593's finding that OpenAI counts it in no window; that
was measured on a paid account.

Decision: with nothing picked and Codex signed in to a Free plan (the
ID token's chatgpt_plan_type is "free"), auto-review counts as "Same as
the session", as Codex's other side calls do, so the review stops
spending the free allowance when the session is on one of magpie's
models. On Codex's own model nothing changes (its entries keep OpenAI's
reviewer). A paid plan, or a plan magpie can't read, keeps Codex's pick;
a pick in Settings always wins.

- codexcat.AutoReviewModel is the setting in effect; the plan comes from
  provider.CodexSignInPlan (liveLogin, keychain read cached), read once
  per model list, and the list tag already re-stamps on auth.json.
- freeOnChatGPT no longer exempts a Free plan's codex-auto-review call
  from usage caps (capHeld).
- GUI tooltip says it (en, zh, zh-TW, ja, de); docs updated.

Run at the pushed tree (on origin/main 88ac42843), go test -tags nogui
-count=1 -timeout 45m: internal/gateway ok 447s, internal/codexcat ok,
internal/gui ok, internal/agent/... ok; internal/provider crashes in
TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest channel
from outside bubble" in filememo.Forget), red the same alone on
origin/main 88ac42843, filed as #3632 with a patch there; with that
test skipped internal/provider ok 152s. gofmt -l clean; GOOS=linux go
vet -tags nogui ./... and GOOS=windows go vet ./... clean.
- GUI (chromium + webkit, every language): codex-auto-review, i18n-keys,
  gui-ja, gui-zh-tw, gui-de, search-keys, agent-prefs: 79 of 79 pass
Broken by hand: with AutoReviewModel returning the raw setting,
TestCodexAutoReviewOnAFreePlan fails; with freeOnChatGPT ignoring the
plan, TestAccountCapHoldsAutoReviewOnAFreePlan fails.
TestCodexSignInPlan reads a Free plan from a sandbox auth.json.
Not tried: a real Free ChatGPT account; whether OpenAI bills
codex-auto-review on Plus/Pro is still #1593's measurement.
2026-10-26 17:19:00 +08:00
yetone 4e5b2ad81c gateway: another magpie added by hand rests only the model it refused
lagrangepoint1813 on Discord: Pi on a magpie whose provider is another
computer's magpie got "Remote Magpie: Claude Code: You've hit your
session limit" for every model of it, whichever Pi was switched to.
remoteModelRest rests such a refusal by model (restID) only for the
Remote magpie preset; that magpie was added as an OpenAI-compatible
provider of the user's own name (preset null in providers.json, the
reporter found), so the 429 rested the whole key
(restKey) and quotaHeld answered every model of it from that rest for
the five hours it named. A magpie's reply names the provider that
answered or held it (X-Magpie-Provider), as no vendor's does: keepRetry now notes it as
answeredThereHeader (this magpie writes its own provider into the same
header of its reply, so it can't be read there; the note is kept from
the client), and remoteModelRest reads a refusal carrying it as another
magpie's model's, whatever the provider was added as. A quotaHeld or
verifyHeld answer now names its member too (noteMember), as an asked
one does, so a refusal the other magpie held is read the same. The
key's own limit there (remoteKeyLimitHeader) still rests it whole.

TestAnotherMagpieAddedByHandRestsTheModel (two gateways over HTTP; the
other magpie asking Claude Code, and already holding it): both subtests
red on the old code with the reporter's message, green with this
change; -count=3 with TestRemoteMagpie* and Verify* green. Broken by
hand: reading X-Magpie-Provider straight from the reply header rested
by model everywhere (TestOwnQuotaRest, TestVerifyRefusalRestsTheLastOne,
TestAntigravityQuotaStillRests, TestCodexCompactCutSummaryFailsOver,
TestOpenRouterFreeAccountRateLimitKeepsProviderRest went red, the header
being this magpie's own); without noteMember on the held answer the
held-there subtest stays red.

Run at this head (on origin/main a1174674d):
- go test ./internal/gateway -count=1 -timeout 45m, both
  commits together: ok (391s)
- gofmt -l internal/gateway: clean; go vet ./internal/gateway, also
  GOOS=linux and GOOS=windows: ok

Not changed: a held answer's "(out of its allowance: …)" is said
twice when the other magpie held it too (seen in the old code's red);
the model alone is held now, the wording is left as it was (#3701).
Not changed: a Remote magpie's key-limit header doesn't reach
remoteModelRest in the main loop either (keepRetry doesn't copy it),
filed as #3705. A reply from a hand-added magpie that breaks off after
its 200 still rests the key whole (no quotaHeld answer follows from it).
Not tried: the reporter's real Claude subscription on the other magpie.
2026-10-26 15:42:59 +08:00
yetone b28e5ffd81 gateway: an array with no items goes to Antigravity with items {}, and Google's schema 400 falls through (plugins#375)
gcq909893267 (plugins#375): Claude Desktop's own MCP tools __batch and
__guide declare an array property with no items ("batch":{"type":
"array"}). plainSchema passed it through, and Google turned the whole
turn away: 400 "GenerateContentRequest.tools[0].function_declarations
[17].parameters.properties[batch].items: missing field". The group's
next member was never asked.

- plainSchema (codeassist.go): every node it writes that is type array
  with no items gets items {}, which Google takes (the reporter's A/B:
  {} and {"type":"string"} both 200). Its walk is the one every nested
  place goes through (properties, items, anyOf/oneOf members, allOf,
  $ref into $defs/definitions, a type list with null), so the check at
  the end of a node covers all of them.
- Siblings: plainSchema is the only Gemini-side schema cleaner. Gemini
  CLI's Code Assist and Vertex AI / a custom Gemini API go through the
  same buildCodeAssistSent but send parametersJsonSchema, full JSON
  Schema, where an array with no items is valid; gemini.go's jsonSchema
  is the other direction (a Gemini client's schema read in). Left as
  they are.
- Fall-through: a 400 that points at a function declaration's
  parameters (function_declarations[N].parameters) is now in
  shapeWords, so shapeRefused/retryable read it as the request's shape
  on that vendor: the next member is asked once, and the member doesn't
  rest (Fail "shape", Rest nil), as OpenCode Go's "schema exceeds the
  maximum nesting depth" (#1870). Not resting is right: the account is
  fine and the same request fails the same on every Antigravity
  account; the reporter's same tools answered 200 on a non-antigravity
  member. A declaration's name or the contents are not matched. A
  shape refusal still tries the same provider's next account first, as
  every shape refusal does now; not changed here.

Tests (antigravity_array_items_test.go), fixtures from the reporter's
literal request and error line:
- TestAntigravityArrayGetsItems: the reproduction through
  buildCodeAssist(antigravity); both declarations carry items {}.
- TestPlainSchemaArraysAllHaveItems: nested arrays under each keyword
  get items {}, an array with items keeps them, a non-array gets none.
- TestGroupFailsOverGoogleSchema400: a group's first member answering
  Google's 400 hands it to the second, Fail shape, no rest; plus a
  shapeRefused table (Google's both wordings, the agent-facing wrapped
  form; a function name and contents error, and a 500, are not).

Run: go test ./internal/gateway/ -run 'CodeAssist|Codeassist|Gemini|
Schema|Antigravity|Shape|FailsOver|Fallback|Region|Retryable|Refus|
Vertex|Plain|Google' ok (307 tests, 31s); gofmt -l clean; go vet,
GOOS=linux go vet -tags nogui, GOOS=windows go vet on internal/gateway
clean.
Broken by hand: codeassist.go reverted, the first two tests FAIL
(declaration 0 parameters.properties.batch: {"type":"array"}); fallback.go
reverted, TestGroupFailsOverGoogleSchema400 FAILs (a 1, b 0).
Not tried: a real Antigravity account (the reporter's own A/B shows
items {} answers 200); the full go test ./... suite; Gemini CLI and
Vertex AI with an items-less array against the real APIs.
2026-10-25 15:56:16 +08:00
yetone be7f174677 gateway: a key out of a guessed quota is asked again after one refusal, and held a minute (zoecats)
zoecats (Discord #feedback, 10-25): a local aggregator answers 429
insufficient_quota "quota exhausted" for the moment it switches
upstreams, and the agent's retry and every request after it were
answered by magpie itself, "out of its allowance: not asked again
before …", Retry-After 900. v0.1.1488 (c6768f06f) let it through only
when the user unticks the provider's new "Rests" switch; by default it
was still held (checked on origin/main 4dfd88206 below). The owner's
zero-config rule wants it to just work.

Cause: quotaHeld (#1772) answers from the rest, without asking, as soon
as every key left rests out of its allowance or credit, from the first
refusal on, for as long as the rest: 15 minutes (quotaRest) or 30
(creditRest) that magpie guessed when the vendor named no time.

Now (Rest.first, Rest.askAt, Rest.asksAt), for a rest whose length
magpie guessed (creditRest, or quotaRest with no OwnQuotaRest):
- The key is held only once it was refused so twice in a row. The first
  refusal still rests it (the order passes it over for a ready
  candidate), but the next request, the agent's retry first, asks it
  again; served, its rest is cleared as before.
- Held, it is asked again a minute on (fallbackCooldown), once, and
  held again if refused.
- A time the vendor named (resets, Retry-After, a window) or the user
  set (quotaRest, QuotaResetAt) holds it from the first refusal to
  then, as before. A first version gave every refusal one more ask;
  the full gateway suite turned it down in TestClineFreeLimitLeaves-
  OtherModels and TestZhipuRestsUntilItsReset (a named reset asked
  again), so it is limited to the guess.
  #1772's keys out for the week are asked at most once a minute each
  while requests come, not on every request.
- soonestBack, the Retry-After a 429 without one gets, says when the
  first of them is asked again: none after a first refusal, about 60s
  for a guessed hold (was 900 or 1800). That narrows #3556 for a
  guessed hold; a vendor-named or user-set one is as before.
- A rate limit was already asked again (restLast, retries within the
  request) and is unchanged; the new test holds it there, Retry-After
  0 and every key resting included.
- The "Rests" switch (LimitRestOff) stays: unticked, nothing rests at
  all.
docs/subsystems/gateway-routing.md says so.

Run (worktree at origin/main 4dfd88206 plus this change):
- Reproduced first on the old code with tests:
  TestRetryAfterALimitIsAsked (new; 429 insufficient_quota, a usage
  limit with no reset, the same with Retry-After: 0, 402, every key of
  two; plus two rate-limit cases): the five limit cases red on
  4dfd88206 ("request 2 after the refusal: 429 … not asked again before
  14:34"), green now; the rate cases green on both.
  TestHeldLimitAskedAgainInAMinute (new) red on the old code (Retry-After
  900, not asked a minute on), green now. TestAllRestingAnswersFromRest,
  TestOwnQuotaRest and TestQuotaHeldOnlyForKeysOutOfAllowance changed to
  the new rule (each key asked once more, then held; held Retry-After
  about 60s; a user-set week held from the first refusal); red on the
  old code. TestRemoteMagpieRestsTheModel (#2077) asks Claude Code once
  more before its hold: the other magpie can't read "resets 8:10pm
  (America/Los_Angeles)", so its 15 minutes there are a guess.
- Broken by hand, each red, then restored: r.first always false ->
  TestRetryAfterALimitIsAsked's five limit cases; askAt never set ->
  TestHeldLimitAskedAgainInAMinute and TestAllRestingAnswersFromRest
  (Retry-After 900).
- Sandbox HOME, a nogui build of 4dfd88206 and of this tree, `serve` on
  127.0.0.1:3481 over a Python fake answering 429 insufficient_quota
  "quota exhausted" once, then 200: old: 429, then 429 "not asked again
  before 14:41", 429 again, Retry-After 900, 1 upstream POST. New: 429
  (no Retry-After), 200, 200, 3 upstream POSTs (rerun on the final tree). The fake refusing every
  time, new: 429, 429 Retry-After 60, then held "not asked again before
  14:27" Retry-After 60, 2 upstream POSTs.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway/ at
  4dfd88206 plus this tree, through suite-lock (after the DSH run):
  ok 446.6s. The first full run, before the rule was limited to a
  guess, was red in the three tests named above.
- gofmt -l clean; go vet ./internal/gateway/ (darwin); GOOS=linux go
  vet -tags nogui ./...; GOOS=windows go vet -tags nogui
  ./internal/gateway/: ok.

Not tried: zoecats' own aggregator; a real vendor's out-of-credit key
(OpenAI insufficient_quota) to see the once-a-minute ask in use; the
GUI (no GUI file changed; the Routing page reads the same rests);
Windows box (Windows CI compiles the tests only).
2026-10-25 15:02:12 +08:00
yetone 67361b54fb routing: Try now from the editor reaches the Routing page, and puts a sunk key back
zoecats (Discord #feedback, 10-25, v0.1.1477): a local aggregator answered
"quota exhausted" while it switched upstreams; Try now in the provider's
editor left Routing showing 429 until magpie restarted.

Cause, in three holders:
- The Routing page kept lifts in its own liftedAt, filled only by its own
  Try now. A lift from the editor (or anywhere else) never reached it, and
  the kept routes' snapshots went on drawing the rest. The trace now
  carries every rest lifted (TraceState.Lifted, from restingUntil.lifted,
  kept up to longestMonthly), Unrest/UnrestAll/renewed wake the long-poll
  (trace.lifted), and the page leaves out a rest, a sunk key and an
  Accounts and keys count that a lift came after.
- With Sink on, a rate-limited key stayed at the back of the order until
  restart: Unrest never cleared sunk. unsink(key) now does.
- The gate itself: checked on the old binary in a sandbox HOME (single key
  over a fake answering 429 insufficient_quota "quota exhausted"). magpie
  rests it 30 min and answers later requests itself ("out of its
  allowance: not asked again before …"); Try now with the editor's key
  lifted that and the next request reached the upstream (200), on
  /v1/chat/completions and /v1/messages, streaming and not. So the stuck
  state was the display and the sink, not quotaHeld.
  Left alone, filed: #3555 (Try now lifts nothing when another magpie
  serves the gateway, unrest 400) and #3556 (the held reply's
  Retry-After, 900s here, outlives the lift for an agent that honours it).

Run at this change on its first base, 42976f9a0:
- gofmt -l clean; node --check client.js; go vet ./... on darwin, and
  GOOS=linux/windows -tags nogui: ok.
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/gui/ (suite
  lock): ok 404.9s, ok 128.9s.
- GUI, chromium and webkit, 5 languages, narrow and wide where the files
  do: rest-try-now, rate-limited-sink, routing-model-rest,
  routing-wb-restricted, routing-lifted-elsewhere (new), routing-rest-off,
  i18n-keys: 132/132. routing-lifted-elsewhere 20/20 alone. Every
  routing*, panel-routing* and rest-* file (108
  files, 1406 tests): 48 red in 8 files. routing-rule-effort, routing-pause,
  routing-live-patch, routing-rule-remove, routing-intent-entry,
  routing-manual and routing-time are red the same on origin/main
  15f0d4cde (a detached worktree, no changes) and filed (#3408-#3411,
  #2174, #3094, #3096, #3465, #1612). routing-steady flakes in both
  engines on both trees: WebKit alone, interleaved, 3 runs each, base 1
  of 3 green, this tree 1 of 3; the last group is read while the editor
  still opens (#3412, #1804).
- Sandbox HOME, fixed binary, two keys: after the editor's unrest the
  trace carried lifted, the next request went to key A (200), and the live
  Routing page went from "rest: A m1 rate limited · back in 10 min … Try
  now" to no rest.

Again on origin/main 1b039a3c7 with the next commit (its body says
what): vet, ./internal/gui, the gateway's rest and Try now tests, and
the Routing GUI files above, ok.

Broken by hand, each red, then restored:
- no unsink: TestTryNowPutsASunkAccountBack fails (order stays b,a).
- no trace.lifted, or no liftSeq wake: TestTryNowToldToTheRoutingPage's
  waiting Trace times out.
- no Lifted in Trace: Lifted empty.
- no lift recorded in renewed/UnrestAll: both tests fail.
- old client.js: routing-lifted-elsewhere times out in both engines; only
  the sunk check removed: "key c still at the back"; only the acts check:
  "Accounts and keys still counts key a resting".

Not tried: zoecats' own aggregator and harness; two magpies at once
(#3555). The Sink help text still says "Kept until magpie restarts", left
as it is: a key whose rest has ended shows no Try now.
2026-10-25 14:00:59 +08:00
yetone 7765f27fcc gateway: a model an account refuses goes on to the accounts not listing it yet
01huadalang (Discord): Antigravity with several accounts, only some can
use Gemini 4. The model and its bar showed only after the right account
was made preferred and probed, and a request failed with the preferred
account's error instead of going on to the account that serves it.
st3lland (Discord): on ZCode (plugin) accounts serve different models.
Owner: no manual setting, magpie knows per account and routes.

Two causes:
- perKeyBarred puts an account whose own saved list lacks the model in
  pl.unlisted / pl.left (Unlisted) and serve never asked it. So when
  the listing accounts refused the model (Antigravity's real 404
  NOT_FOUND "Requested entity was not found.", codeAssistModelMissing;
  plugins through modelRefused's unservedWords), the agent got that
  error even though an account whose list was simply stale serves it.
  Now, once every listing account of that subscription/model has been
  asked and one refused it as unserved (unservedTry), its unlisted
  accounts are asked next, right after it and before any other member
  or fallback (unlistedNext, askUnlisted for the trace). The refusing
  try rests as before (restAfterMarked, for that model). Not for a
  pinned account, a sealed conversation or strict affinity; a gateway
  key's account list narrows unlisted too (allowedCandidates). Other
  refusals (403 PERMISSION_DENIED, 429 RESOURCE_EXHAUSTED) don't open
  the unlisted accounts.
- Antigravity's per-account lists were refreshed only on the first
  listing, a probe, a sync or a Refetch, so a model granted later and
  its bar (chosenWindows filters by exposed models) stayed hidden. Its
  quota reading already fetches fetchAvailableModels per account; now
  it saves that account's list (noteAntigravityList) and re-merges the
  pooled list from every On account's list when it changed. An Off
  account's reading changes nothing.

Other vendors: the unlisted route only opens on the existing unserved
classifiers (Antigravity's 404, plugins' unservedWords), unchanged here;
TestUnlistedAccountNotAskedForOtherRefusals holds that the other real
Antigravity bodies don't open it.

Run (at the rebased head on origin/main 5222a4b12):
- go test ./internal/gateway -run TestUnlistedAccount (4 new) and
  ./internal/provider -run 'TestAntigravityQuotaReadingListsNewModels|
  TestAntigravityModelsAcrossAccounts': ok.
- Targeted: ./internal/gateway -run 'Unlisted|Antigravity|Fallback|Refus|
  Unserved|KeyModel|Lists|Plan|Rest' and ./internal/provider -run
  'Antigravity|Google|Gemini|Pool|Lists': ok (gateway 34.9s, provider 4.5s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- Full suite: queued behind three other sessions' full runs on this
  machine (load ~300); its result goes on this commit's follow-up, not
  claimed here.
- GUI: no asset changed; none run.

Broken by hand, each red, then restored:
- unlisted fallback off (false && unservedBy[key]): AskedAfterModelRefused
  404, BeforeFallback served a's fallback.
- unlisted appended after fallbacks instead of inserted: BeforeFallback red.
- key doesn't narrow unlisted: HeldFromKey got b's 200, want a's 404.
- quota reading keeps no list: QuotaReadingListsNewModels pooled list
  lacks Gemini 4.

Not tried: no real Antigravity accounts with and without Gemini 4 (the
404 body is the one on record from earlier reports); no real ZCode
"model not available" body is on record, so none was invented and ZCode
relies on modelRefused's existing words; the plugins repo is unchanged
(ZCode's models(provider,{auth}) already lists per account). Known
limit: a resting listed account that is the lone candidate is still
asked first on later turns until the unlisted account's list refreshes
at its next quota reading, one extra request a turn.
2026-10-24 20:32:33 +08:00
yetoneandCartethyiaQwQ 6e32942a24 gateway: a safety refusal that also says the model is retired retires nothing (#3274, CartethyiaQwQ)
CartethyiaQwQ (#3274) found one more way a safety refusal punished a
provider: serve's retirement check runs on any failed try, and
modelRetired accepts a 400 whose body says the model "is retired", so a
cyber_policy refusal whose message also said so took the model out of
the provider's lists (retired.json) until an answer brought it back.
No real refusal seen so far says it; a boundary case.

- serve: a try settled as a refusal (hw.refused) retires nothing. By
  then its body is magpie's note "safety filter: cyber_policy — <the
  vendor's message>", text, so policyRefusal can't tell it there.
- modelRetired: a body that is the safety filter's error object
  (policyRefusal) is never a retirement, for its other callers too
  (modelRefused, which rests the model, and retryable).

The note cuts the vendor's message at 300 characters, so the test's
refusal is short enough to keep the retirement words in it, as a real
one would.

Tests: TestRefusalSayingRetiredRetiresNothing (an OpenAI-compatible
provider answering a 400 cyber_policy refusal saying "The model m1 is
retired." retires nothing; the same words under model_deprecated still
retire), and TestRetiredWords gets three cases.

Broken by hand: without the serve guard, TestRefusalSayingRetiredRetiresNothing
is red ("retired true, want false"); without the modelRetired guard,
TestRetiredWords is red on both refusal cases. A Codex account's
refusal never reached Retire on main, so it was tried only through the
OpenAI-compatible path.

Full suite at 91f777e93 (base 8278fd9b0, origin/main at push): go test
-tags nogui -timeout 45m ./... — 69 packages ok, none failed
(internal/gateway 566.8s). gofmt clean; vet darwin, linux nogui, windows.

Co-authored-by: CartethyiaQwQ <CartethyiaQwQ@users.noreply.github.com>
2026-10-23 00:18:58 +08:00
yetoneand卡提希娅可爱捏 efb7cb11d4 gateway: a safety refusal said in a stream is a refusal for a client answered whole too, and rests nobody (#3274, CartethyiaQwQ)
CartethyiaQwQ (#3274): Codex's "safety filter: cyber_policy" refusal
(the Daybreak note) set healthy accounts aside; two such turns benched a
five-account pool for about 17 minutes.

Cause: the HTTP 400 cyber_policy is already a refusal (policyRefusal reads
its code: next account asked, nobody rests), and so is one said in a
stream relayed as a stream. A Codex account is always streamed upstream,
so a stream:false Responses, Chat or Messages request is answered from
that stream whole. There, a response.failed or error event whose error
has a code (cyber_policy) but no invalid_request_error type got no status
from the decoder, and the whole path answered it 502 api_error: retried
on the same account, then every account asked, each one but the last
resting by backoff. A refusal after a few words went to the client as a
finished 200 turn, and the failure after it rested the account.

Fix, at the decoders and the whole path:
- filterRefused (fallback.go): a stream error event refusedCode reads as
  the safety filter's gets status 400 and Said {"error":{type
  invalid_request_error, code}}. Used by every decoder that set
  Code: refusedCode -- Responses (both error sites, after requestRefused),
  Chat, Anthropic and carriedError.
- The whole path (gateway.go) answers a reply the filter cut part way as
  the refusal, not its words so far, and notes it in refusedHeader, since
  Anthropic's error shape drops the code that settle reads.
- restAfterMarked: a 400 whose error object policyRefusal reads as a
  refusal rests nobody and counts no failure (By "off", Why refused), as
  the ZDR refusal does, for any route that reaches it.
- docs/subsystems/gateway-routing.md says so.

Review of the submitted patch (dc6c695db, not taken as is): it matched
`safety filter|cyber_policy|Daybreak access` anywhere in a 400's words,
so a 400 that echoes the user's prompt in its message skipped the rest
too; its fixture was magpie's own refusedError text, which restAfter is
never handed for a 400; and it gated on status 400, while the path that
rested (above) answered 502, so it would not have stopped the rests.
Its restAfter unit tests' shape is kept in TestRestAfterPolicyRefusal.

Run at 21f7f9df2 (origin/main then) plus this change, unless said:
- New TestStreamRefusalAnsweredWholeRestsNobody: {response.failed, error
  event, refusal after text} x {Responses, Chat, Messages answered whole}
  x {next answers, nobody left}; fixture is the reporter's quoted message
  without magpie's 300-char cut. Asserts the client gets 200 from the
  next account or a 400 naming cyber_policy, every try failRefused with
  no Rest, nothing resting.
- New TestRestAfterPolicyRefusal: cyber_policy 400 rests nobody and
  counts 0 failures; a plain 400, and two 400s echoing the reporter's
  words in the message (code string_above_max_length / code null) still
  rest by backoff.
- Red on the old code: all 18 TestStreamRefusalAnsweredWholeRestsNobody
  subtests and TestRestAfterPolicyRefusal/cyber_policy. Broken by hand,
  each went red: filterRefused returning no status (all 18); the
  part-way clause dropped (6 "after some text"); refusedHeader not set
  (6 Messages subtests).
- A scratch matrix before the fix (also streamed Responses/Chat/Messages
  and Codex's own path, HTTP 400 and response.failed): only the whole
  routes rested; the streamed ones and the HTTP 400 already passed.
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./... clean.
- go test -race -timeout 45m ./internal/gateway/: FAIL on two tests
  this change doesn't reach, each ok alone with -race -count=3 and
  filed: TestPluginStreamLongActiveReader (client deadline after 36MB,
  #3286) and TestQuietKeptAliveOnlySoLong (0 keepalives in a 3s pause,
  #3287). Load was 180-280 from other sessions' GUI runs.
- Rebased on ba1dc7f97: gofmt, go vet ./internal/gateway/ and the two
  new tests again: ok.
- go test -timeout 45m ./... at ba1dc7f97 plus this change: ok, 69
  packages, no FAIL (internal/gateway 783s).

Not tried: a real Codex account. Whether the ChatGPT backend sends
cyber_policy as an HTTP 400 or inside a 200 stream, and with or without
an error type, isn't known from the issue; every shape is covered by
tests, not by a live refusal.

Co-authored-by: 卡提希娅可爱捏 <134358478+CartethyiaQwQ@users.noreply.github.com>
2026-10-22 22:53:47 +08:00
yetone 592899467b gateway: Gemini's reasoning streams as it comes on the last candidate, so Codex isn't left with nothing for the whole of its thinking (LuckymanJC on Discord)
LuckymanJC and kkgg: through magpie the first turn of a Codex session on
a Gemini model was very slow or seemed stalled. Measured with fake
upstreams through the gateway (Codex Responses -> Chat DeepSeek, Gemini;
OpenCode Chat; Anthropic passthrough), first content came within 1-50ms
on every path but one: a Gemini model's reasoning was held even on the
last candidate (`|| last && modelFamily(c.model) != ""` left Gemini out),
so Codex got nothing at all, not even response.created, until the text
began, while Claude's and GPT's has gone as it comes there since
iTianbao's report.

It was held there for #667, a reply that only reasoned being asked
again. That re-ask happens in place in streamTranslated, keeping the
reasoning the agent has, so it doesn't need the hold. But with the try
passing, emptyRetries counted it as past the request's own re-asks and
asked only streamRetries (2) times, and TestGeminiEmptyRepliesAskedAgain
(three empty replies running) went red. A held try that went through on
its reasoning alone (holdWriter.thoughtThrough) is now asked once more in
place (streamRetries+1); a never-answering model still makes at most 4
calls (the test's bound is 6).

Tests: TestThinkingStreamsWithNoOneElse gets "gemini" (Gemini upstream)
and "chat gemini" cases, to Claude Code and Codex. With the old line
restored they go red ("thinking held: first thought only 1.75us before
the text"). With emptyRetries' new branch broken by hand
(streamRetries+0), TestGeminiEmptyRepliesAskedAgain goes red with
"an empty reply"; green with both.
Run: go test -run 'TestGeminiEmpty|TestThinkingStreams|TestThinkingHeld|TestUncountedEmpty|TestReasoningLoop' ./internal/gateway: ok.
Break check repeated at push: the old `|| last && modelFamily(c.model)
!= ""` turns
TestThinkingStreamsWithNoOneElse/{gemini,chat_gemini}/v1/{messages,responses} red ("thinking held: first thought only 1.458µs before the text").
Full suite (go1.26.8 darwin-arm64, rebased on 0fe039f14): go test
-timeout 45m ./... gave 63 packages ok; internal/agent and
internal/gateway timed out at 45m with no test failed (load ~110 from
other sessions; deadline in TestJcode and TestVertexGeminiClients,
#2544 and #2870 seen again) and passed alone at that head: ok
internal/agent 1644.560s, ok internal/gateway 1397.712s. Rebased on
origin/main 4ae6c06dc, every package its new commits touch run in full
there: ok internal/agent 465.353s, internal/gateway 648.172s,
internal/sessions, internal/gui, internal/cli, internal/codexsummary;
gofmt -l on the changed files empty; go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... clean; go build for
darwin, linux (nogui) and windows ok (at 0fe039f14).
Then rebased on origin/main 2201b6628 (one line in
internal/provider/migrate_qoder.go): ok internal/provider 608.249s; go
vet of internal/provider, internal/agent and internal/gateway clean.
2026-10-21 03:40:27 +08:00
yetone c863904338 gateway: Command Code's Zero Data Retention refusal rests nothing and goes to another member (plugins #246)
Command Code plugin 0.1.14 sends x-cmd-zdr: 1 when its Zero Data
Retention switch is on. A model with no ZDR upstream is refused with
the Provider API's 422 (code "cmd_zdr_no_providers") or, on Go, a 400
the plugin makes with type "cmd_zdr_no_providers". The refusal is about
that request's setting, not the model or the account.

Before, on the plugin path (moved commandcode-plan):
- Go's 400 was rewritten with type invalid_request_error, read as the
  model unserved (unservedWords), rested commandcode-plan@<acct>/<model>
  for a minute, and the account's second key was asked the same thing.
- The 422 went to the agent as api_error, and in a group the next
  member was never asked.
- Raw bodies (restAfter, a decision group's decideFailed) read as
  modelRefused too.

Now:
- zdrRefused (fallback.go) matches only that code as the error's type
  or code, on 400/422. modelRefused and tooLongUnsaid leave it out.
- keepRetry notes it from the vendor's raw body (X-Magpie-ZDR-Refused)
  since the Anthropic error shape keeps no code; pass/keepAlive strip
  the note.
- The candidate loop skips the provider's mates at the same model
  (notMates, they'd be sent the same header), tries the next member,
  rests nobody, and returns the refusal alone.
- restAfterMarked and decideFailed rest nothing for it.
- docs/subsystems/gateway-routing.md says so.

Tests (internal/gateway/plugin_zdr_test.go), with the literal bodies
from plugins' zdr.test.mjs:
- TestCommandCodeZDRRefusalRestsNothing (422 and 400, plugin path,
  two accounts): alone the agent gets Command Code's words and one
  account is asked; group G answers from b over chat and over
  /v1/messages; nothing rests; switch off, Command Code answers first.
- TestZDRRefusalIsCommandCodesCodeOnly: the same words without the
  code, OpenAI model_not_found, unsupported_api_for_model and the code
  named in a message still read as model refusals.
- TestZDRRefusalNeverRests: restAfter with the raw 422/400 and the
  noted Anthropic body rests nothing; without the note it rests.

Broken by hand:
- old sources (zdrRefused stubbed false): e2e red in both subtests
  ("group: 422 ... (commandcode 1, b 0)", "alone: 400 ... (asked 2)"),
  classifier table red.
- restAfter guard removed: TestZDRRefusalNeverRests red ("422 ...
  rests: {Why:other Status:422 ...").
- loop branch removed: e2e red. keepRetry note removed: e2e red.

Run at this head: gofmt -l (clean); go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... (clean);
go test -timeout 45m ./... (go1.26.8, load avg ~300 from other
sessions): every package ok except
- internal/agent, internal/gateway, internal/library: past -timeout
  45m (TestClaudeTiers, TestMessageReasoningRefused,
  TestProjectServersQoderCodeBuddyDroid running), as #2869;
- internal/gui TestSetAnswersWhileDevinAndProvidersHang (13.8s), #1375;
- internal/plugin TestGatewayHookMixedPiPackage, #2865.
After rebasing on dd70c5e6a (b749cffbb's room retry in the same loop):
vet x3 clean again; ZDR tests pass; go test -timeout 60m
./internal/gateway alone: ok but TestIntentClassifierFails' 1.5s slow
bound (1.78s), #1829, which passes -count=5 alone.
2026-10-19 22:27:07 +08:00
yetone 2a27fb8da8 gateway: a request's body is looked at for web search without a copy, and not parsed for a provider that searches by itself
attempt() asked searchAsked first, on every relayed request, and only
then whether the provider searches by itself. searchAsked looked for
three words with strings.Contains(string(body), …), each conversion a
copy of the whole body (a 211KB body: ~640KB and ms a request), and a
body offering web_search was then parsed whole: Codex offers it on
every turn, so each relayed Codex turn was parsed only to be told
"Codex searches by itself". searchedForIt now asks what is known of the
provider and model first, and searchAsked looks with bytes.Contains.
The same copy in the siblings that look at an error body
(fallback.passing, patience.busy, routing.failure's insufficient_quota)
goes too. lan.go's and the lower-cased look-ups in gateway.go need the
string they make and are left as they are.

Test: TestSearchAskedLooksCheaply. Broken by hand (string(body) and the
old order put back): red, "a 211KB body with no search in it: 3
allocations, want 0" and "a provider that searches by itself: 29
allocations, the body parsed".

BenchmarkSearchedForIt (211KB Responses body; load average ~450):
  codex-asks   old 2.55-5.02 ms/op  665KB/op  29-30 allocs/op
               new 0.1-1.9 us/op    0B/op     0 allocs/op
  other-plain  old 1.6-4.8 ms/op    663KB/op  3 allocs/op
               new 0.26-1.15 ms/op  0B/op     0 allocs/op

Run: go test ./internal/gateway -run
'TestSearchAskedLooksCheaply|TestWebSearchAskedOfEachAPI|Search|Busy|
Passing|Failure|Credit|Quota' -count 1: ok (140s).
2026-10-19 15:19:31 +08:00
yetone b14784c03f gateway: a fallback too small for the request is asked once every account with room is out of its allowance (Kai on Discord)
Kai on Discord (0.1.1278): Claude Code to claude/claude-opus-5-5, the
Claude provider's two subscription accounts (Max, Pro) both at their
limit ("resets 5:58am", "resets Oct 18 at 3pm"), its Fallback
codex/gpt-6.1-sol. Routing said the second account's 429 had nobody left
to try, and Claude Code had the 429. The fallback was never in the
route's order.

Cause: roomy (0f398c489, 10-15) leaves out, before anyone is asked, a
candidate whose known window is no larger than the request's estimate.
A Codex account's gpt-6.1-sol is 272K (its live list's context_window);
Opus holds 1M. A Claude Code conversation past ~272K tokens left the
Codex fallback out of the candidates and the trace's order, silently,
and when both Claude accounts failed for their allowance the agent was
told to wait hours. "It worked yesterday": the conversation was shorter.
A short request on current main already fell back (the new test's first
cases pass on the old code).

Fix: roomy hands back what it left out (small, with its order rows).
When the last candidate with room fails out of its allowance or credit
(failQuota/failCredit), nothing before it failed otherwise (other ==
nil), no account is pinned, and it isn't an overflow, refusal or
turned-away prompt, those left out that aren't resting are appended and
asked, their rows added to the trace's order, and the failed one rests
as one before the last does. The too-small fallback's overflow then
reaches the agent through the existing outgrew path, to compact, after
which it holds the conversation. Any other failure (a bad key, a busy
vendor) reaches the agent as before, the small member not asked, so
dgqyushen's free-200K-first group keeps its behaviour. Streaming and
non-streaming share the loop; count_tokens and System One's decision
models don't go through roomy. The Routing page still shows a member
left out and not asked only by its absence (no GUI change).

Tests:
- TestClaudeAccountsSpentFallBackToCodex (new): fake `claude` CLI that
  answers every account with rate_limit_event rejected + "You've hit
  your limit", a fake Codex backend, Claude's Fallback codex/gpt-6.1-sol,
  Codex's window 272K. Short request streamed / not / with accounts
  already resting: Codex answers (green before and after). A ~375K-token
  request streamed and not: red on the old code (429, codex asked 0,
  order = the two Claude accounts), green now.
- TestMemberTooSmallIsTheLastResort (new): group paid(10K) then
  free(2K), a 2.2K request. paid 401: the agent gets the 401, free not
  asked. paid 429 insufficient_quota: free answers, paid rests, free in
  the order.
- TestRoomyLeavesWhatItCantJudge checks the handed-back candidates.

Broken by hand:
- the new block disabled (false &&): both stream cases of the Claude
  test red (429, codex asked 0), TestMemberTooSmallIsTheLastResort red
  (429 insufficient_quota, free 0). Restored: green.
- the quota condition forced true: TestMemberTooSmallIsTheLastResort's
  401 case red (free asked, 200). Restored: green.
- the other == nil condition removed: still green; no test has an
  earlier member failing otherwise before a quota failure.

Run:
- gofmt -l: clean. go vet ./internal/gateway (darwin), GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test -timeout 45m ./... at de671719a (load ~240-470): every package ok,
  internal/gateway included (2451s), except three reds in packages this
  doesn't touch, each already filed and each a timing bound under load:
  internal/gui TestMainWindowCorners/macOS_26_SDK killed at its deadline
  (#1936, #2645; red alone too on this loaded machine), internal/library
  TestCheckStdio/timeout_ends_the_tree (#2765; -count=3 alone: ok),
  internal/plugin TestStopLetsARenewalEnd (#2743; -count=2 alone: ok).
- After rebasing on origin/main: go test ./internal/gateway -run with the
  new and roomy/overflow tests: ok.

Not done: Routing still shows a member left out and not asked only by
its absence; a row saying "too small for this request" would be a GUI
and i18n change of its own. Not tried against Kai's real accounts.
2026-10-18 02:17:02 +08:00
yetone 992f288e20 gateway: a Chat-only relay that refuses tools with reasoning and none too moves a group on (#2670, JJ-Lin)
JJ-Lin's analysis in #2670 found both causes and gave the mock upstream
the tests use. A relay with a Chat URL alone answers tools with
reasoning_effort with "use /v1/responses or set reasoning_effort to
'none'", and then refuses none ("Supported values are: 'low', ...").

- forwardTranslated: when none was #176's own and is refused naming the
  levels, offRefused is still remembered (it is true of the model), but
  the request isn't asked again at the lowest level (refused the same by
  the upstream's own word). The tools refusal is the answer. The #176
  retry is gated on turnedAway(none) plus a per-request guard, so it
  can't loop. Before: the first request went [xhigh none low] and every
  later one [high], with the 400 going to the agent.
- passthrough (a chat client's relayed request), the sibling: the same.
  It used to ask none on every request and hand back the confusing
  "'none' is not supported" error.
- shapeRefused/retryable: a 400/422 that wrongEndpoint reads reaches the
  group only once the member has tried every API it has a URL for. The
  next member is now asked once, and this one doesn't rest (failShape).
  Before, the group stopped on it.
- The agent's error still names the Responses URL the provider lacks
  (wrongAPINote via asksResponses). Reading supported_endpoint_types from
  /v1/models was left out: wrongAPINote already says what to set, and
  trying Responses on the Chat base unasked isn't clean.
- docs/subsystems/gateway-routing.md says both.

Plain chat without tools, and gpt-6-astra (where none is taken) are
unchanged; TestToolsEffortNoneTaken pins both
([effort none] -> 200 three times in a row; no-tools [xhigh] -> 200).

Tests (internal/gateway/tools_effort_none_test.go, JJ-Lin's mock):
- TestToolsEffortNoneRefused: one Server, Codex xhigh/high/high asks
  [xhigh none], [high], [high]. Each answer is the tools refusal with
  the Responses-URL note. A chat client gets [high none], [high].
- TestGroupPassesOverToolsRefusedOnChat: group relay -> other. Three
  requests in a row are all 200 from other, tries[0] is failShape, no rest.
Broken by hand:
- fallback.go reverted: the group test is red (400 to the agent).
- translated restore off: "request 1 asked [xhigh none low]".
- passthrough check off: the chat client gets "'none' is not supported".
- turnedAway gate off: "request 2 asked [high low]". Without the
  per-request guard too, it loops forever (seen, killed).

Run on origin/main 7660399a1 (full suite), then rebased (darwin, machine load ~200):
- gofmt -l internal/gateway: empty.
- go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet -tags nogui ./...: ok.
- go test -tags nogui -timeout 45m ./... under pipefail: 63 packages ok,
  3 FAIL. internal/gateway hit the 45m timeout with no test failing
  (load ~200). internal/agent timed out in TestReverseProxyIsStillMagpie/nginx
  (#2723). internal/cli: TestPluginLoginInstallsItsCLIFirst TempDir
  cleanup "directory not empty" (#2722, as #2449).
- Rerun alone on cb05dc2d1: internal/gateway ok 2454s (-timeout 90m),
  internal/cli ok 764s, internal/agent ok 3100s (-timeout 60m).
- Rebased onto 04e8aa8f1 (fallback.go conflict with #2656's
  customToolRefusal; both matchers kept): vet (darwin, linux, windows)
  ok, internal/gateway ok 2454s.
- Rebased onto 50a703190 (no conflict; #2649, #2651, #2639 and #2444
  touch the gateway): go vet ./internal/gateway ok, and
  -run 'ToolsEffort|GroupPassesOverToolsRefused|CustomTool|Effort|Group'
  ok 234s. The whole package was not rerun at this last base.
Not tried against the reporter's real relay: the mock is built from the
bytes in the issue.
2026-10-17 20:33:28 +08:00
bf931f82c3 gateway: a Codex conversation compacted natively is held to its account only when native compaction is on, and told why when it can't go there (#2642, #2582)
ScarfQian (#2642, still on v0.1.1279): after a native compaction by one
Codex account, routing to another answered 400 "only that key or account
can read the compaction it sealed ... switched off, removed, or no longer
serves". Three causes, one fix each:

- #2582 (Dony2050, ump45nose's patch): one of Codex's own models asked on
  the backend path through magpie's accounts (codexAccounts) kept the
  compaction_trigger whatever the codex provider's native compaction
  setting, so every compaction was sealed by and recorded to one account.
  It is now decided as a magpie model's is: codexInputAs with
  nativeCompactionFor("codex/<model>"); off (the default) gives
  codexCompact's magpie1: summary, which any account reads, and records
  no writer. Unlike ump45nose's branch, /responses/compact and Codex's
  own single sign-in relay are left as they were: the legacy endpoint's
  body has no trigger for codexCompact to answer, and a lone sign-in has
  no other account to move to.
- ggbdpq's fix (0ab41eba0, e1646488d, ported as is): a writer whose own
  model list has since dropped the model sat in planned.left, out of the
  candidates, so checkpointReaders never found it and refused although it
  was on. It is now taken back from planned.unlisted (plan, planLevel and
  the nested weighted plan), its row moved from left to order.
  sealedReaders, run before it for a sealed subagent task, narrows
  unlisted too (sibling).
- A request carrying a recorded seal while only Codex's own sign-in is on
  was relayed as it came (codexAccounts false), so with the writer
  switched off the one account left was sent it. codexSealedFor routes
  it through serve, where checkpointReaders holds it to the writer.
- checkpointError now says the reason magpie's settings give
  (checkpointGone: provider removed, account signed out, sign-in lapsed,
  paused while others are on, switched off, kept from the model in Names &
  levels, key off or gone, model disabled, or the model/group asked for
  not routing to it), the fix for that reason, and whether native
  compaction is on for the writer's provider now. The old catch-all
  sentence is gone.

The seal is still treated as readable only by the account that wrote it,
as #1099 and #2271 found; chestnutLeeeee's report that another account read
one in a direct canary was not tried here (no real accounts).

Tests (fake ChatGPT backend, sandbox HOME, nothing on the network):
TestCodexOwnModelCompactionHonoursTheToggle (off: summary, no trigger
upstream, no writer; on: native seal kept, writer recorded),
TestNativeCompactionWriterGoneSaysWhy (spare switched off, own paused,
Names & levels, signed out), ggbdpq's
TestNativeCompactionWriterWhoseListLacksTheModel and
...ThroughAGroupWhoseListLacksTheModel. All four are red on 7660399a1.
Broken by hand on this change, each went red: codexInputAs back to
(false,false) -> Toggle; codexSealedFor not called -> spare switched off;
the unlisted loop emptied -> both WhoseList tests; the Paused case
skipped -> own paused.

TestProtectionRefusalAskedOnceNobodyRests (vs's 502 "response protection
is unavailable" on a bare gpt-5.5 compaction through three accounts) was
about the native path, which that model now takes only with native
compaction on; it turns it on (nativeOn). Off, the compaction is magpie's
summary, as TestProtectionRefusedCompactionAsText already covers.

Run at this change on 7660399a1: gofmt -l clean; go vet ./... (darwin),
GOOS=linux and GOOS=windows go vet -tags nogui ./... ok;
full go test -tags nogui -timeout 45m ./... (load average ~140): every
package ok except internal/agent and internal/gateway, which ran past 45m
(#2544, #2108), and TestProtectionRefusalAskedOnceNobodyRests, mine,
fixed above. Then each alone: internal/gateway -timeout 45m finished in
2345s with one red, TestTranslatedStreamKeepsClientAlive/responses_to_chat
(a keepalive timing test under load, passes alone; filed as #2711, sibling
of #2169); internal/agent -timeout 100m ok in 2115s. The protection,
compaction and Codex tests (-run 'TestProtection|Compact|Compaction|TestCodex')
ok after the test change.
No GUI file changed. Not tried against the real ChatGPT backend.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>
2026-10-17 18:19:51 +08:00
yetone 5b12407e8e gateway: a custom tool a Responses upstream turns away is translated, not given back as a 400 (#2656)
DeepSeek's Responses API answers Codex's exec, a custom tool, with 400
"Unsupported custom tool: 'exec'. Only 'apply_patch' is supported."
The relay (attempt -> passthrough) sent the tools as they came, so the
translation that offers a custom tool as a function and gives its call
back as a custom_tool_call never ran, and the 400 matched no word list,
so a group's next member wasn't asked either.

- passthrough: a 400/422 matching customToolRefusal, on a Responses
  body that offers a custom tool (tools, a namespace's, an input item's
  tools), marks the model (customToolRefused) and returns not done.
- attempt: then, and on a marked model's later requests with a custom
  tool, the request is translated on the client's own API (ownAPI), so
  exec keeps its name and comes back as custom_tool_call. A Codex
  compaction (keepsCompaction) isn't translated and gets the refusal.
- shapeRefused also takes customToolRefusal, so where the refusal does
  reach a group, the next member is asked and nobody rests.

Not scoped to DeepSeek: any Responses relay (key, plugin) that says its
custom tools are unsupported is handled the same; an upstream that never
refused them still gets them as sent (tested).

Tests: custom_tool_test.go, fixture from the reporter's literal error
text and request. TestCustomToolTranslatedWhereRefused (stream and
not), TestCustomToolRefusalInGroup (reporter's ordered group, next
member asked 0 times), TestCustomToolRefusalWordings. Broken by hand:
passthrough branch off -> both request tests 400 with the reporter's
exact message; attempt pre-skip off -> next turn asked 4 times, not 3;
shapeRefused addition off -> Wordings red.

Run:
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./... clean, at the pushed head.
- Full go test -tags nogui -timeout 45m ./... on e085d6e92 + this
  change: every package ok except internal/agent, timed out at 2706s
  (TestPortMovesEveryAgent running 30s at the deadline; load ~100-150;
  same as #2544, commented there). internal/agent alone -timeout 60m:
  ok 3031s.
- After rebasing onto cb05dc2d1 (3 commits, none in this path):
  internal/gateway -timeout 60m run twice. First: FAIL at 2559s; I
  piped it through tail and lost which test, so it is not named or
  filed here. Second, full log kept: ok 2509s (load ~150).
- Rebased again onto 9f9bfc160 (3 more commits: agent, provider's
  Codex window; none in this path): TestCustomTool*, TestCodexCustom*,
  TestToolStrict*, *Shape* ok; gofmt and vet (darwin, linux, windows)
  clean. Then onto 85eef5d87 (GUI quota refresh only): build and
  TestCustomTool* ok. The full suite was not rerun at this head.
- Not tried against the real DeepSeek API; the fake upstream refuses as
  the reporter's logs show.
2026-10-17 17:44:23 +08:00
yetoneandggbdpq df341e7671 gateway: a member that answers a stream request with a whole reply is asked once, not again and again (#2455)
An upstream that answers stream:true with a whole JSON reply (a relay
that doesn't speak SSE) fails as a 502 "did not stream". magpie read
that 502 as a failure a moment may mend: the same-one retries (passing)
asked it twice more, then a group's patience (busy, #1418) kept asking
it until the budget was spent. The failure is the same however often it
is asked. With production pauses that is about 7 requests and 60s at the
default Patience, about 14 at 240s; the test's 1ms pauses let the 12
replan rounds run out first, 15 requests (ggbdpq's correction on the
issue).

busy() and passing() now leave a body that says didNotStream alone, and
the four places that word the error (translate, streamTranslated,
askTranslated, holdWriter.settle) share that constant. A group still
moves on to the next member, whose API may stream; retryable() is
unchanged.

Patch by ggbdpq (f9e09ca7), applied on main with the docs sentence
placed by hand (the hunk no longer applied).

Run:
- TestStreamlessMemberIsAskedOnce with both exclusions taken out: FAIL,
  whole and stream ("asked 15 times"); with only busy()'s: FAIL ("asked
  13 times"); with only passing()'s: FAIL ("asked 3 times"). Restored:
  ok (asked once, the agent gets the 502 naming "did not stream").
- TestStreamlessMemberHandsOnToTheNextMember (b, which streams, answers
  after a): ok.
- TestQuietNotAReplyLastFails, TestPatience*, TestStreamOverflow*,
  TestCodexOverflowInGroupNotAskedAgain, TestAgentGoneInTheRetryPause,
  TestRelayInputCap, TestOverflowGoesToAMemberWithRoom: ok.
- Full suite, go test -tags nogui -timeout 45m ./... (set -o pipefail,
  sandbox HOME, load ~350) at 0224e826f (these four commits on
  ebf3f48f7) plus #2545's patch: every package ok except internal/agent,
  whose one red (TestRekeyGivesWSLAgentTheSharingKey) is #2545's, which
  was dropped (problems posted on #2545). internal/agent alone at
  0224e826f: ok. Rebased on dccfefdf7 (#2635, internal/library only):
  build, vet, internal/library ok. gofmt -l clean; go vet darwin (gui),
  GOOS=linux and GOOS=windows -tags nogui: clean. GUI (i18n-keys,
  gui-de/ja/zh-TW, import-*, key-import, login-import): all pass except
  login-import's Chromium case, which fails the same alone on origin/main
  ebf3f48f7 (#1307, output posted there).
Not changed: a same-protocol passthrough whose vendor answers 200 with
a whole reply is still relayed as it came (named on the issue). Not
tried against a real relay that doesn't stream.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-17 11:54:56 +08:00
yetoneandump45nose ae98cda651 gateway: an inner group's own Patience waits out its busy members through an outer group (#2410)
serve read Patience only from the group the request named (g.Waits()).
planLevel stamped a nested group's FirstToken (#2246) on its candidates
but not its Patience, so an inner group's budget was never read through
an outer one: an inner 4 min under an outer default gave up at 1 min,
and an inner Off was still asked again for 60s.

Each candidate carries the innermost Patience that is set on its way
down (innerPatience, as innerFirstToken). waitsOf reads it as Group.Waits
does, falling back to the asked group's when unset; PatienceOff keeps the
member out of replan. replan counts each member's budget from waitFrom
and asks again only those with budget left past the pause; the hold on
the last failure lasts while any member's may (maxWaits), and the
trace's Patience is the member's own. With no nested Patience set,
every member's budget is g.Waits(), as before.

Patch by ump45nose (61b1c17c); ggbdpq checked it against main on the
issue. Review changes: the docs sentence was placed by hand (the docs
hunk no longer applied), and the tests' budgets moved from inner 8s /
outer 3s to 10s / 4s, so every round's pause ends 2s or more from a
budget line (it was 1s from the 3s line), as a timing test leaves room
on both sides.

Run:
- With fallback.go, gateway.go, patience.go and patience_test.go put
  back to main: TestNestedGroupPatienceThroughOuter FAIL ("a.n=2, want
  3 — the inner group's 10s budget was not read"),
  TestNestedGroupPatienceInnerOff FAIL ("code=529 a.n=13 (want 529, 1 —
  no replan)"). With replan reading only the fallback budget:
  ThroughOuter FAIL the same. Restored: ok.
- TestNestedGroupPatienceFallsBackToOuter, TestGroupWaitsOut*,
  TestPatienceIsUsedUp: ok.
- Full suite, go test -tags nogui -timeout 45m ./... (set -o pipefail,
  sandbox HOME, load ~350) at 0224e826f (these four commits on
  ebf3f48f7) plus #2545's patch: every package ok except internal/agent,
  whose one red (TestRekeyGivesWSLAgentTheSharingKey) is #2545's, which
  was dropped (problems posted on #2545). internal/agent alone at
  0224e826f: ok. Rebased on dccfefdf7 (#2635, internal/library only):
  build, vet, internal/library ok. gofmt -l clean; go vet darwin (gui),
  GOOS=linux and GOOS=windows -tags nogui: clean. GUI (i18n-keys,
  gui-de/ja/zh-TW, import-*, key-import, login-import): all pass except
  login-import's Chromium case, which fails the same alone on origin/main
  ebf3f48f7 (#1307, output posted there).

Co-authored-by: ump45nose <ump45nose@users.noreply.github.com>
2026-10-17 11:54:56 +08:00
yetone 440f66701f gateway: a 429 for native compaction's one account says the compaction pinned it, not that every account is capped (#2517)
When a conversation was compacted natively, only the key or account that
sealed the compaction can read it (#1099), so checkpointReaders keeps the
candidates to that one. When that account was at its usage cap, the 429
and the call record said "every account that serves X is held at the
usage cap", although the other accounts were never candidates. That sent
lm0711 looking at routing modes, which can't change it.

checkpointHeld tells this case apart: the plan held only the sealer's
account(s), and others were left out for the checkpoint. The error then
names the account and its window, says the compaction it sealed is what
keeps the conversation there, that routing mode and stays don't change
that, and to raise the cap / spend credits or start a new conversation.
The record reads "native compaction's account at its usage cap" (or its
credits / both variants). cappedError and cappedRecord are unchanged for
every other 429; their text is split into heldReasons and heldAdvice so
both share it. docs/subsystems/gateway-routing.md says so.

Test: TestNativeCompactionWriterAtItsCap seals a checkpoint on one
account, caps it, and checks the 429 body and the record. Broken by hand
(checkpointHeld returning nil), it fails with the old "every account"
text.

Run on origin/main d9b943555 (head 663db0ecf), with the #2517,
#2521 and #2522 changes, load ~240:
- gofmt -l clean; go vet -tags nogui for darwin, linux and windows: ok.
- go test -timeout 120m -count=1 ./... (pipefail): exit 0, every package
  ok (gateway 1416.8s, agent 1535.5s). Before the rebase, on 63be47717:
  - The 45m run had agent and gateway past 45m (#2544, #2108).
  - TestMainWindowCorners was killed at its deadline (#1936).
  - TestSkillRelinkKeepsUnreadableCopy failed (#2555; it passes alone).
  - gateway alone with 120m was ok.
- GUI, the 41 Requests/Usage files in serial, both engines, before the
  rebase: 493 pass, 3 fail. The 3 were usage-refresh "not yet 2 !== 1",
  the same on 63be47717 alone (1 of 3); seen again on #2184.
- Rebased, these all pass, 102/102: i18n-keys, usage-ledger-ttft,
  usage-ledger-key-split, usage-ledger, usage-speed, usage-ledger-detail,
  gui-ja, gui-de and gui-zh-tw.
- Rebased again onto 9b04c4e20, which touches ledger.go, request_page.go
  and gateway.go:
  - vet ×3: ok.
  - internal/usage, internal/usageapi and internal/cli: ok.
  - internal/gateway -run 'NativeCompaction|UsageOverGateway|Capped|Cap':
    ok.
  - usage-ledger-ttft, usage-ledger-key-split, usage-ledger and
    usage-speed: 86 pass. i18n-keys was red from main's own words (#2586,
    fixed in the next commit).
2026-10-16 21:59:32 +08:00
yetone e243937ca3 gateway: a fast pick can be sent as Ultrafast where the account offers it (#1954)
zhenghaowen0967 asked for an agent's fast pick of a ChatGPT model to go as
Codex's Ultrafast without the client asking for it. settings.UltraPicks
holds the agent's fast picks that are set to Ultrafast; each one is in
FastPicks too.

- The gateway marks those candidates `ultra` in fastPick.
  - On Chat and Responses, a try sends service_tier "ultrafast".
  - From Messages, a try carries withUltra to forwardTranslated, which
    sets Request.Ultrafast for the ChatGPT backend.
  - In every case, the #1784 check decides the account. One whose list
    doesn't offer Ultrafast goes after a mate that does (tierMate). With
    no mate left, it is sent priority.
  - That check now covers Chat as well as Responses.
- Sibling fix: chat.go dropped a Chat client's own service_tier
  "ultrafast" (Fast was false, Ultrafast unset). It now parses as
  Responses does.
- provider: SetFastTier (""/priority/ultrafast) behind SetFastPick.
  CanUltra and UltraModels say whether one of Codex's accounts lists
  Ultrafast on the model. UltraPicks follow a provider rename
  (renameModelPrefs) and survive a GUI settings save.
- GUI: an option gets ultraOk/ultra. Where ultraOk is set, the bolt in
  the picker steps usual -> Fast -> Ultrafast -> usual, as a camera's
  flash button steps its modes. Ultrafast shows two overlapped bolts, in
  the row and after the field's model. Tooltips and the status line are
  in en, zh, zh-TW, ja and de. POST /api/agent-fast takes `ultra`.
- No `:ultrafast` suffix for routing groups yet.

Tests, each broken by hand and seen red:
- TestUltraPickSentUltrafast covers omp/Responses with no tier asked
  (acct-pro:ultrafast), the Pro account out (then acct-plus:priority),
  another agent unchanged, opencode/Chat and claude/Messages picks, a
  Chat client's own ultrafast, and switching back to Fast or off.
  - Red with ultra forced false (4 cases).
  - Red without withUltra (claude went priority).
  - Red without the chat.go parse (2 cases).
- TestSetFastPick: red without UltraPicks in renameModelPrefs.
- TestSettingsSaveKeepsWhatItDoesNotSend: red without the api.go carry.
- fast-ultra.test.cjs (en zh ja de, window and 440px panel): red (9/9)
  without the Ultrafast step.

Run (vet, gofmt, GUI and full suite at base 8b84dc902; the reruns
below at a rebase onto 6b3ee5a03 and then onto 63be47717 origin/main):
- gofmt -l: clean.
- go vet -tags nogui ./... for darwin, linux and windows: clean.
- GUI, chromium + webkit: fast-ultra, fast-pick, group-member-fast,
  i18n-keys, model-pick and 14 other agent-model/picker files. 197/197
  pass.
- Full suite: set -o pipefail; go test -timeout 45m ./... (sandbox
  HOME, macOS, 3 other sessions' suites running at the same time):
  every package ok except two.
  - internal/gateway: TestMaxRPMGroupPrefersMemberWithRoom hit its fixed
    1s bar (1.126s) under load. It passes 5/5 alone (-count=5). Filed
    as #2520.
  - internal/gui: TestPanelJoinsFullScreenSpaces, red on macOS 26.2 on
    main already, filed as #2450.
- Rerun of internal/gateway and internal/library after the rebase onto
  6b3ee5a03 (both packages changed upstream), -timeout 60m, load
  average ~290: library ok. gateway hit the 60m timeout (the test
  running, TestPauseByFolder, was 13s in) and
  TestQueueRefusalIsInTheUsageLedger saw b's 1s queue timeout as a
  second 429. Filed as #2541. TestQueueRefusalIsInTheUsageLedger,
  TestPauseByFolder and TestUltraPickSentUltrafast, -count=5 at this
  head: ok.
- At the 63be47717 rebase: gofmt clean; vet darwin/linux/windows clean.
  internal/provider ok, internal/settings ok. internal/agent hit the
  45m timeout under load ~295 (in TestCursorLocalEffort, at 0s), so
  this is not a green for that package. Its -run
  "Fast|Option|Models|Picker|Cursor|Codex" subset, run through the
  shared 3-slot queue, was ok in 794s. The whole package is left to
  CI's Test run.

Not tried: a real Pro account's Ultrafast. The fake ChatGPT backend's
model lists offer it on one account only.
2026-10-16 19:14:52 +08:00
deephbz d9e87eb328 gateway: clients opt into Claude subscription cache marks and TTLs (#1717)
Problem:
Messages clients need control of cache boundaries and TTLs when a Claude
subscription answers. Ordinary clients must retain their run identity,
prompt and environment. A routing group's API-key member keeps its marks
and must not report the subscription bridge's drops.

Change:
Select client-owned marks only with X-Magpie-Cache-Marks: client. Map system
and fresh-history boundaries and the request tail, default missing TTLs to
5m, validate slot and TTL order, and separate opted-in run identities.
Retain prefix constraints across live and saved runs. Report unmappable
marks only for the Claude subscription try. Bound its selection hold to
two seconds and clear the report and hold for a non-Claude fallback.
Check ordinary identity bytes without a version-specific hash golden.

What was run:
Sandbox HOME, nogui: go vet ./... on darwin; gateway vet with GOOS=linux
and GOOS=windows; full gateway tests; focused cache and usage tests with
-race. gofmt and git diff --check passed. The group probe failed before
the fix with tools:1 on the API-key reply in both routing orders and both
stream modes. Hand-broken candidate scoping, stale report clearing,
keepalive holds and ordinary identity bytes each failed behavior tests.
Live, Claude Code on a Claude subscription and an Anthropic API key,
through a recording proxy: in a group whose API-key member answers, in
either order and both stream modes, the reply has no dropped-mark header
and upstream receives the tool mark; a Claude answer reports tools:1; a
failed Claude try followed by an API-key answer leaves no report. With a
delayed API-key reply, the group's first keepalive came 0.85 s after a
direct request's. Without the header, the outgoing request equals one
from a gateway built at the same base. No GUI or real Linux/Windows
execution.
2026-10-16 14:16:51 +08:00
yetone 0bbb2f3ca4 provider, gui, gateway: a thousand keys are listed once and read eight at a time (@NetRozee on X)
@NetRozee on X: "when I add a thousand keys for a custom endpoint magpie
just froze or crash by itself".

Cause. The Providers page asked, for each key, what it rests by
(RestKey), and RestKey listed every key on again (KeysOn), which itself
looked along the list for each key: cubic in the keys. /api/providers
and every /api/keys/* answer, an import too, are drawn through it. The
gateway asked, for each key of every request, whether it serves the
model (Serves), and each asking read the provider's lists again (a
filememo stat, and a read while the file is new) and looked along each
model's key ids. fetchPerKey looked along the lists for each key and
model the same way.

Fix.
- KeysOn drops repeats by a set.
- RestKeys finds once whether several keys are on; providerInfo uses it.
- Serving(model) reads the lists once and answers for each key from sets
  (keyLists, made again when the lists are read anew); perKeyBarred and
  the test pick use it. Serves is Serving for one key.
- fetchPerKey keeps each model's keys as a set and indexes the old list
  by key once; a model kept for a failed key is kept once, as before.
- KeysListed and ListsRead count listings and list reads for the tests.
Behaviour is otherwise the same.

Measured (go test in a sandbox HOME, a custom provider, 50 models):
                         1000 keys          5000 keys
  providerInfo           1.54s -> 7.5ms     2m42.9s -> 18.3ms
  providersState         1.65s -> 110ms     2m40.3s -> 146ms
  POST /api/keys/import  1.64s -> 82ms      2m44.7s -> 288ms
  of one more key
  gateway perKey         100.9ms -> 8.2ms   (old not run) -> 40ms
  (each request)

Tests (counts, not time), each red on the old code by hand:
- TestProviderInfoListsKeysOnce: old 1001 listings for 1000 keys, 11 for
  10; new 0 and 0.
- TestPerKeyReadsListsOnce: old 1001 list reads for 1000 keys, 11 for
  10; new 1 and 1.
- TestServingReadsListsOnce, TestRestKeysIsRestKey,
  TestKeysOnDropsRepeats: same answers as before.

And the vendor reads. KeyBalances, PlanQuotas and remoteKeyCards started a goroutine
for each key and asked the vendor with all of them at once: a thousand
keys were a thousand requests to one relay together, each holding a
connection and its body.

Fix. keySlots holds each provider's reads to keyReadsAtOnce (8); other
providers' keys are read beside them. A read whose context is done goes
on without a slot and fails at once, as before.

Tests:
- TestKeyReadsEightAtOnce: a Command Code provider of 31 keys and a
  remote magpie of 31 keys behind a server that holds every request.
  Old code (the slots taken out by hand): 31 at once for balances, plans
  and remote limits; new: 8, every card still there.
- TestKeySlots: a done context takes no slot; another provider's keys
  have their own.

Run: gofmt -l (clean); GOOS=linux and GOOS=windows go vet -tags nogui
./... (clean); go test -tags nogui -count=1 -timeout 45m ./... in a sandbox HOME (GOCACHE, GOMODCACHE pinned) on af601541e with this series: 66 packages ok, 18 without tests, no FAIL (gateway 468.5s, provider 215.9s, gui 122.8s).
2026-10-16 08:43:02 +08:00
yetoneandggbdpq 7e4336e719 gateway: an event magpie appends to a cut stream begins after a blank line (#2446)
A passthrough stream cut mid-line got its error event written onto the
half-written line, so the client read "event: error" as more of that
line's data and never saw the error as an event. ggbdpq's patch (#2446)
tracks whether the last write ended a line (passthrough's write, and
holdWriter.atLine for cutLoop) and puts a blank line, two newlines when
mid-line, before the appended event.

The same join could happen to the other event passthrough appends: the
finish_reason filled in for a Gemini OpenAI-compatible reply that ended
done (a6f908ba5). It now goes through the same separator (apart). The
truncated pending event is still dispatched; SSE can't take it back, but
the error now arrives as an event of its own.

holdWriter's other appends (release, failTo) only follow keepalive
comment lines, so they already start on a line.

Tests: TestPassthroughStreamCutMidLine, TestPassthroughStreamEndsOnLineEnd,
TestLoopCutMidLine (ggbdpq), TestGeminiCompatFinishAfterPartialLine.
Broken by hand: apart returning "\n" always -> CutMidLine and
GeminiCompatFinishAfterPartialLine red; the Gemini fill-in without the
separator -> GeminiCompatFinishAfterPartialLine red; cutLoop's "\n\n" as
"\n" -> TestLoopCutMidLine red. Restored, all green.

gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui ./... clean.
Full suite: go test -tags nogui -timeout 45m ./... at base 0cad76cd9, 66 packages ok, 0 FAIL (gateway 1869s, provider 445s; sandbox HOME)

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
2026-10-16 04:56:34 +08:00
yetone a0a4d55ef7 gateway: a passed-through reply whose reasoning loops before it says anything is asked again once, and its tries counted (#2436)
lqisgod's five looped replies (pi → WorkBuddy, Chat in and out) each
ended at once with empty tries and status 200. The once-only re-ask of a
reasoning loop (loopReasks) lived only in streamTranslated's onLoop, so a
same-protocol passthrough had holdWriter.reask nil and cutLoop ran on the
first trip. A re-ask that did happen in place wasn't counted in the usage
record's tries either (tries came from route.Tries alone).

Now holdWriter lets such a try go (mayReloop/letGoLoop) when its
reasoning looped, nothing has spoken (loopGuard.spoke: no text or call),
the request has its re-ask left and its context is alive, and either
nothing of the try reached the agent (held bytes dropped, any protocol)
or the agent speaks Chat (bytes written up to the end of the tripping
event, the next try's chunks follow). The fallback loop records the try
as failLoop with reloopedError and asks the same provider again after
retryPause. In-place re-asks add to tries too. An Anthropic or Responses
stream whose reasoning already reached the agent still ends with the
loop error: a second message_start/response.created can't follow. The
plugin host's fetch goes through the same holdWriter
(TestLoopEndsWorkBuddysReply's plugin subtests).

Tests: loop_guard_test.go's chat case now expects 2 asks and an answer;
every passed-through `data:` line is valid JSON; the usage record has
Tries == asks and no error. docs/subsystems/gateway-routing.md updated.

Broken by hand, each red:
- hw.reloop = false (old behaviour): TestLoopEndsTheReplyOnEveryProtocol,
  TestLoopEndsWorkBuddysReply, TestReasoningLoopIsAskedAgain fail.
- reasked not added to tries: the same three fail with "usage record's
  tries 0, the vendor asked 2 times".
- spoke never set: TestLoopAfterTextIsNotAskedAgain fails.

Run: gofmt -l clean; go vet -tags nogui ./internal/gateway ./internal/usage
with GOOS=darwin, linux, windows ok; go test -run Loop ./internal/gateway ok.
Not tried: a real WorkBuddy account looping (the loop can't be forced).

Full suite: go test -tags nogui -count=1 -timeout 45m ./... on base
b03031738, every package ok, no FAIL line.
2026-10-16 01:55:47 +08:00
yetone d98e17808b gateway: a refusal that comes as an error ends the try at once, is read across writes after content, and the high-risk message alone is one (#2400, Jichao)
Three gaps Jichao reported, each reproduced on origin/main 4a6bf80f4
with fake upstreams before the change:

1. An HTTP error or stream error event whose message is, whole, "The
   request was rejected because it was considered high risk" with no
   policy code was any failure, not a refusal: no refusal fallback.
   policyRefusal now takes that exact message (trimmed) as a refusal
   (highRiskRefusal). It reads only an error's own message field, so an
   answer that quotes the sentence stays an answer. The vendor that sends
   it isn't known (no wire capture; none of our code or docs has it); it
   says the request was turned away, so it rests nobody and goes to the
   next candidate under RefusalRetries, like every refusal.
2. A policy error event before any content (content_filter, coded) left
   the held try waiting for the upstream's EOF: with the connection kept
   open the request hung until the client gave up. Such an event is now
   eventRefusalError and stops the try as eventError does; a refusal's
   stop/finish marker (eventRefusal) is still read to the end for its
   trailing usage and terminator.
3. After content, refusalAfter skipped a write that didn't look like a
   refusal, so an "event: error" whose name and data came in separate
   writes was never noted (a coded content_filter too). Every write is now
   read; only an unfinished event's bytes are kept, so a reply's content
   isn't copied. refusalSays matches the bare word error for the named
   event. Nothing already sent is replayed.

Reference patch by Jichao (585836c on Jichao/magpie
fix/provider-refusal-errors), reviewed line by line and taken with
changes: refusalAfter no longer appends every write to a buffer, the
message is a named const with why, the doc line is rewritten, and the
split test gains a coded named error (red on main without the message
match). No new retries or fallbacks: everything goes through the
existing refusal path.

Run (darwin, sandbox HOME, -tags nogui -p 1):
- New tests on main without the fix: TestHighRiskErrorMessage,
  TestHighRiskErrorFallsBack, TestRefusalErrorDoesNotWaitForEOF (hung to
  the 10s guard), TestHighRiskErrorWhenRetryStops,
  TestHighRiskTextAndStartedReplyAreNotReplayed,
  TestHighRiskNamedErrorAfterContentRestsNobody,
  TestHighRiskErrorSplitAfterContent all red. With it, ok.
- Broken by hand, each red: no stop on eventRefusalError
  (TestRefusalErrorDoesNotWaitForEOF), the per-write prefilter back
  (TestHighRiskErrorSplitAfterContent), the message case off (the
  TestHighRisk* set).
- -run 'Refus|Refuse|Hold|Fallback|StreamEvent|Late|Policy|Safety' ok;
  -race on 'TestHighRisk|TestRefusalErrorDoesNotWaitForEOF|Refus|
  StreamEvent|Hold' ok.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows ok.
Not run: the full suite, any real vendor.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone ad312dfee9 zhipu: a 1308 or 1310's reset time, written with no zone, is read as Beijing's, and a held refusal says its time with the offset (Player on Discord)
Player reached a Remote magpie with a GLM Coding Plan key: "Z.ai:
[1308][Usage limit reached for 5 hour. Your limit will reset at 2026-10-15
20:12 (out of its allowance: not asked again before 17:12)". Z.ai's 1308
and 1310 ("Usage limit reached for N hour. Your limit will reset at
YYYY-MM-DD HH:MM:SS", bigmodel.cn "您的限额将在 … 重置") write the time
with no zone. It is UTC+8: code-yeongyu/senpi#3348 has a 1308 received at
2026-09-21T17:17:32Z saying 01:18:11, 39s later as UTC+8 and 8h later as
UTC; kodustech/kodus-ai#2104 and openclaw/openclaw#97764 show the same
zone-less form for 1310. resetsWhen reads only a time with its offset, so
nothing read it: the key rested quotaRest (15 min), the held refusal said
"not asked again before" a quarter-hour on (17:12, this magpie's local
time with no zone), and after it Z.ai was asked and refused again until
20:12 Beijing time.

- routing.go: zhipuResets/resetsZhipu read Zhipu's own words ("Your limit
  will reset at", "您的限额将在") then a whole date and a time to the
  minute at least, in UTC+8; not when a digit, colon or zone follows
  (cut in its seconds, or a zone of its own, which resetsWritten reads).
  resetsAt tries it after resetsWritten, so restAfter and keepRetry both
  see it, for the built-in key, a relay passing it on, and a Remote
  magpie's held refusal.
- heldClock: a held time is given as "20:12 UTC+8" (today) or
  "Oct 16 09:00 UTC+8", since its reader may be a Remote magpie's user on
  another clock. Siblings: the quota-held 429 (gateway.go), the capped
  window error (fallback.go), the spent searcher (search.go) and describer
  (vision.go), all of which wrote Local() with no zone.
- docs/subsystems/gateway-routing.md says both.

The "manual weekly reset" was Z.ai's weekly reset card, spent on Z.ai's
site (magpie only counts them, b69b0e810). It clears the weekly window;
the 5-hour window stays full, which is the 1308 Player got. Not a magpie
bug.

The held message's parenthesis is balanced in the code; Player's quote
was cut before the ")".

Run:
- TestResetsZhipu: Player's literal words (no seconds), Z.ai's OpenAI and
  Anthropic envelopes, senpi#3348's case (39s), kodus#2104's 1310,
  bigmodel.cn's Chinese raw and \u-escaped, a Remote magpie's held line;
  not read: cut in seconds/after the colon/in the minute/in the date, its
  own UTC/+00:00/Z, month 13, hour 25, past, over a week, WorkBuddy's
  words without offset, a date in passing.
- TestHeldClock in UTC+8, UTC and UTC-3:30, today and tomorrow.
- TestZhipuRestsUntilItsReset: a 1308 three hours off rests the key three
  hours (Retry-After), Z.ai asked once, and the held refusal names the
  time with its offset.
- Broken by hand: resetsZhipu taken out of resetsAt, TestResetsZhipu and
  TestZhipuRestsUntilItsReset go red (Retry-After "900"; held refusal
  "Z.ai reset at 20:12:53 … not asked again before 17:27 UTC+8", the
  reporter's bug); heldClock put back to Local().Format("15:04"), the
  end-to-end test goes red ("not asked again before 20:13").
- go test -tags nogui -p 1 -run 'Zhipu|Reset|Rest|Held|Quota|Cap|Spent|
  Searcher|Vision|Written' ./internal/gateway: ok.
- gofmt -l clean; go vet -tags nogui ./... on darwin, linux, windows: ok.
- The full suite ran out of disk on this machine (df / down to ~1 GB,
  45 "no space left on device" in agent, cli, davsync, gateway, gui,
  library, provider, sessions); it is not a record.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 0f398c4895 gateway: a group member whose window can't hold the request isn't asked it (dgqyushen on Discord)
dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash (200K)
first in a group and a 1M DeepSeek subscription second, so that the
first 200K go free and past that go to the subscription.

The gateway fell over only on a refusal it reads as too long (#700,
withRoom/failOverflow, tooLongUnsaid past 1.2x the window). A vendor that
refuses a request just past its window without saying why (between 1.0x
and 1.2x) reached the agent as that error while the next member had
room, and every doomed request spent one against the free tier's limits.

roomy (fallback.go), in serve after rules, affinity, the image filter and
pinTo and before probeOne, estimates the request as the overflow path
does (estimate) and leaves out the candidates whose known window
(windowOf: Contexts, the catalog, ContextOf) is no larger, and their
order rows with them. It is a check before sending, not a retry. Kept:
a window not known, a body that doesn't parse, a single model, and a
request no candidate holds (the first is asked, its overflow told to the
agent to compact). A conversation stuck to the small member by affinity
moves once it outgrows it. count_tokens (a count on the first member) and
System One's decision models don't go through serve's candidate path and
are left alone; every generation route (middleware, classify, search,
vision, codex titles/backend, auto groups) goes through serve. No UI
change: a member left out is absent from the route's order.

TestPayloadTooLargeOverWindowTriesMemberWithRoom now expects the members
too small not to be asked at all (c only, one try).

Run:
- go test -tags nogui -p 1 ./internal/gateway -run
  'TestMemberTooSmallIsNotAsked|TestConversationOutgrowingItsMemberMoves|
  TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge': ok
- the overflow tests (TestPayloadTooLarge, TestOverflow,
  TestContextOverflow, TestEveryVendorsOverflow, TestCodexOverflowInGroup,
  TestStreamOverflow, TestRateLimitNotContextOverflow) with the new ones:
  ok
- gofmt -l clean; go vet ./internal/gateway (darwin); GOOS=linux and
  GOOS=windows go vet -tags nogui ./...: clean; go build darwin, linux,
  windows: ok.
Broken by hand: the roomy call in serve commented out:
TestMemberTooSmallIsNotAsked red (400 "FREE: Invalid request
parameters"), TestConversationOutgrowingItsMemberMoves red (free 2,
paid 0), TestPayloadTooLargeOverWindowTriesMemberWithRoom red (a 1, c 1,
2 tries); restored, all green.
Not run: the whole internal/gateway package (the run failed to build,
"no space left on device", the disk at 0 GB free) and the full suite
(left to the batch's run). Not tried against the real OpenCode Zen.
Known: the estimate is bytes/4, so mostly-CJK text counts high and a
member may be passed over a little early.

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 75035fa202 gateway: Command Code's bare 400 (a trace id, no reason) hands a group's request to the next member, not ends it (#2313, lqisgod)
Command Code's Provider API answers some requests with
{"message":"invalid request error trace_id: <hex>","type":"invalid_request_error"}:
a 400 (a 422 the week before), no code, no param. retryable() read it as
the request's own fault, so a group stopped there and its later members
were never asked: six requests in a row on lqisgod's wb-flash group, while
the fourth member answered the same ~660K prompt that hour.

What it turns away is the request's size, not the key: lqisgod's A/B on
one agent conversation (~748K tokens of history and tool calls, same bytes
otherwise) answered 200 with max_completion_tokens 64000 and this 400 with
384000, the max output Command Code lists for the model, so history plus
asked-for output is over a limit below the 1M context it lists. Its own
tracker has more of the kind (CommandCodeAI/command-code#960, #976).
Another member whose model has room may take the same request, so it is
asked, as for a shape another API can take.

unsaidWords matches that message alone, as the vendor sends it, wrapped by
a client in front of it, or told on after a provider's name. It goes the
way shapeWords do (shapeRefused, retryable): the next member is asked once,
Command Code doesn't rest, and the last member's error reaches the agent.
No retry of the same member is added. Its overflow ("The input is longer
than the model's context length trace_id: …") and a refusal naming a param
aren't matched. The keyed "commandcode" preset and the moved plan go
through the same gateway decision.

Tested: TestGroupFailsOverCommandCodesBare400 (streamed group request,
reporter's literal body; the 422 and wrapped forms from #960/#952; overflow,
param and longer-message negatives). With fallback.go put back it fails:
"400 ... COMMANDCODE: invalid request error trace_id: ... (a 1, b 0)".
go test -run 'TestGroupFailsOver|Shape' ./internal/gateway passes.

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00
yetone 51d5b8d0b2 gateway: a Codex compaction's summary cut short or 429'd halfway fails over and rests the account, and one that keeps failing is held, not asked every 18s (#2274, huangzuomin)
Codex on antigravity/gemini-3.8-flash with context_management's
experimental mode asked magpie for 1169 summaries in 6 hours (8.44M
billed tokens), ending in 502 "compaction: the model wrote no summary".

Cause, in three parts:
- serve's holdWriter let the summary's stream through at its first
  words, so Antigravity cutting it short ("the reply ended before it was
  complete"), or a 429 "Individual quota reached" after some of it,
  reached codexCompact as a 200 with an error: no failover, no rest.
- codexCompact took a summary that ended `incomplete`, or a body with
  no response at all, as one.
- Codex's async compaction (codex-rs async_compaction) starts a
  background compaction at every step while the conversation is over its
  threshold and drops a failed one silently, so the history never
  shrank and each step paid for the whole conversation again.

Fix:
- codexCompact marks its request askWhole; serve then holds the summary
  stream to its end (holdWriter.wantWhole). A cut, an error event or
  `response.incomplete` anywhere in it fails over to the next candidate
  like a failure before content and rests the account as that would; a
  model that reached its output limit rests nobody.
- With nobody left, the cut/incomplete summary is a 502 saying so, never
  the words before the cut.
- compactFails (codex_compact_guard.go): after 3 failed summaries in a
  row of one conversation (prompt_cache_key) on one model, each within
  5 minutes, the next is answered 400 at once (Codex doesn't retry a
  400) naming the last failure, until 5 minutes pass. A summary clears
  it; 401/403 aren't counted. Decision: a 400 is the only answer Codex's
  remote compaction stops on, and a per-conversation hold costs a user
  whose model recovers at most 5 minutes, while the loop cost tokens.
- docs/subsystems/gateway-routing.md says so.

Run (worktree at origin/main 69d7ee33a plus this):
- go test ./internal/gateway/ -count=1: ok (1054s).
- TestCodexCompactCutSummaryFailsOver (Responses cut / quota halfway /
  incomplete, Chat quota halfway), TestCodexCompactCutSummaryIsNoSummary,
  TestCodexCompactKeepsFailingIsHeld: fake upstreams, no network.
- Broken by hand: hw.wantWhole = false fails every FailsOver subtest
  (the spare is never asked, the cut text comes back); dropping the
  incomplete check fails IsNoSummary/incomplete; held() always false
  fails KeepsFailing (the model asked a 4th time).
- gofmt -l: clean; go vet -tags nogui GOOS=darwin/linux/windows
  ./internal/gateway: clean (on the rebased head with #2271).
Full suite: SUITE_LINE
Not tried against Antigravity itself.
2026-10-15 23:08:00 +08:00