Commit Graph
13 Commits
Author SHA1 Message Date
yetone 978284dd69 gateway: a transport failure or a plain 502 is not told as too long
Filed as #5486. ne9ko9 runs Codex through magpie to a custom OpenAI Responses relay
(gpt-6-astra, effort max). Three failures reached Codex as HTTP 400
"prompt is too long: about 385K/404K tokens, more than gpt-6-astra's
context window of 272000": a plain 502 "Upstream service temporarily
unavailable", a TCP connect timeout (dial tcp … connectex) and a TCP
read timeout. Codex took them as context_window_exceeded and ended the
turn instead of asking again, although the same session had just been
answered at 454K and 474K, and Codex's own window was 828,400.

tooLongUnsaid now:
- reads a 5xx as an overflow only for Devin (busyOverflows: p.ID or its
  plugin's host), the vendor b3ab3e42e added the 5xx for; every other
  vendor's 5xx is a busy moment and is asked again as before;
- never infers an overflow from a failure that is no vendor's answer
  (transportFailed): dial/read/TLS timeouts, resets, refused or closed
  connections, unexpected EOF, Bun's ConnectionRefused, and magpie's own
  "reply ended before it was complete" / "did not stream";
- weighs the request against no less than the most the model was seen to
  answer for this provider since start (Server.noteHeld, from the
  answered try's usage), and no less than the provider list's
  max_context_window (new provider.Entry.MaxContext, from
  catalog.Model.MaxContext).
An upstream that says context_length_exceeded is still passed as one,
and the 400/413/422 inference for Qoder/WorkBuddy-style refusals stays.
Mid-stream SSE is untouched (the inference runs only on a held try).
No setting: the fix is the default. NEKO-CwC's candidate (ac4aeb85d,
a passthrough request mode that turns off inference, retries and
fallback) was read; its tests are about that mode, so none were ported.

Tests (internal/gateway/toolong_transport_test.go):
TestTransportFailureIsNotTooLong (the reporter's connectex and read
timeout among 9 messages, plain and Devin), TestDevinBusyOverflowStillTooLong
(devin and devin-plugin ids), TestPlain502IsNotTooLong (the reporter's
body, end to end; a 400 context_length_exceeded still says so),
TestUnreachableIsNotTooLong, TestWindowNotBelowWhatWasAnswered,
TestWindowNotBelowListedMax. TestOverflowTheVendorDidntSay's "502
anthropic" row is now "502 plain", asked again (1+lastRetries+replanRounds).

Broken by hand, each on mote, with the targeted tests:
- busyOverflows returning true: TestPlain502IsNotTooLong and
  TestOverflowTheVendorDidntSay red;
- transportFailed returning false: TestTransportFailureIsNotTooLong red;
- held passed as 0: TestWindowNotBelowWhatWasAnswered red;
- windowMost returning 0: TestWindowNotBelowListedMax red.
The original Devin 502 and Qoder/WorkBuddy 400 cases stayed green in
each.

Run (mote-run): go vet (darwin, GOOS=linux, GOOS=windows) of
internal/gateway and internal/provider; go test -count=1 of
internal/gateway and internal/provider: vet ok on all three; gateway ok (809s); provider red only in
TestRenewLoginsKeepsClaudeReading, already #5481 and red on main 0f07fbd0c. Full suite after the
push, under ~/suite.lock.

Not tried: the reporter's real relay or a Windows run; held is kept in
memory only, so after a restart the first failure is weighed against
the listed window again.

Reported-by: ne9ko9 (Discord)
Reported-by: mahiro233 (Discord)
2026-11-06 16:33:39 +08:00
yetone 0c6752dbdf gateway: a too-long, shape or retired refusal read its Chinese escaped as \uXXXX too, and the translated thinking re-ask has its test (#1678)
Follow-up to ggbdpq's f16c1f7cd (#1678) after its review. Its four
sites now read wordsOf(body); three more deciders whose word lists hold
Chinese still matched the raw body, and one of its sites had no test:

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

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

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

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

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

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

Co-authored-by: yetone <yetoneful@gmail.com>
2026-10-13 10:40:35 +08:00
yetone 3aeb7d1bf8 gateway: a model a key's plan doesn't serve rests that model alone, not the key (#1235)
SenseNova answers a Token Plan key asked for deepseek-v4.1-flash with
403 "model is not available in the current token plan" while the same
key serves deepseek-v4-flash. That refusal was a plain failure: it
rested the whole key, its backoff counted per key and doubling up to
10 minutes, so an agent that kept asking for the model left every key
of the provider resting for every model (Sun1090: both keys "失败 · 9
分钟后恢复").

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

TestModelNotInPlanRestsTheModelNotTheKey (two keys, four requests for
the refused model, SenseNova's error shape) fails without the change:
"key One rests for a model its plan lacks: {Why:other Status:403 ...
By:backoff Failures:3}" and "deepseek-v4.1-flash doesn't rest". With
it: go test -tags nogui ./... under a temp HOME passes; -race -count=5
over TestModelNotInPlan|TestSeveralKeys|TestFallback|TestRouting|
TestPool|TestGroup passes; go vet (darwin, GOOS=linux, GOOS=windows,
nogui) passes. Not tried against a real SenseNova key: the body's
"code" field in the fixture is a guess; the message is the reporter's.
2026-10-08 12:26:53 +08:00
yetone 06420a7121 tests: a fake program is a file macOS has already let run (testenv.Program), so a fake's first start no longer eats a test's wait under load
macOS checks a newly written executable before its first exec: 0.27s
alone, 2-5s while other new programs start (a go test ./... starting its
test binaries). The same file again takes 0.009s, and the pass is kept
across a rename and an in-place rewrite. 108852b4 worked round this for one
test with /bin/sh -c; the class was every test that writes a `#!/bin/sh`
fake and times its answer.

testenv.Program(t, path, script) replaces os.WriteFile(path, script, 0o755)
for fakes. On macOS it renames a file that has run once from a pool to path
and writes the script into it in place; at the test's cleanup the file goes
back to the pool (only a path the test created; a stand-in it wrote over
stays). Fakes still end with their tests: nothing about how they are
started or waited on changed. Run (and gateway's TestMain) remove the pool
at the end. TestMain's PATH stand-ins are run once in the background
(testenv.StandIns). Other systems write the file as before.

Converted every `#!/bin/sh` fake written by tests under internal/ (agent,
gateway, gui, library, plugin, proc, provider, update). Windows, binary
and node/bun fakes are unchanged.

Under the same load (3 loops each starting 8 freshly written scripts at a
time), 4 rounds each, before (108852b4 / origin/main) vs after:
- provider TestSavedButSignedOutClaudeServed: 4/4 fail (8.01s) -> 4/4 pass
- provider TestClaudeSignInOverStaleCredentials: 4/4 fail (5.00s) -> 4/4 pass
- provider TestDevinSignedInOnlyInMagpie: 3/4 fail ("CLI's own []") -> 4/4 pass
- gateway TestClaudeRunEndsWhenTheClientLeaves: 4/4 fail -> 4/4 pass
  (and 3/3 fail -> 3/3 pass at a third of that load)
- gateway TestClientGoneRecordedAsCanceled: 4/4 fail -> 4/4 pass
- gui TestProvidersAnswerWhileListsComeIn ("cursor found false" at 3.03s):
  4/4 fail -> 4/4 pass. The same class, not bfe8bcaf's test order.
- proc TestUserPath (login shell's PATH never came, 7.01s): 4/4 fail ->
  4/4 pass
Unloaded, every touched package passes; no pool directory or process is
left after a run.
2026-10-07 03:00:47 +08:00
yetone b9895c2ded tests: the gateway's and Devin's tests run on Windows in a home of their own — on Windows os.UserHomeDir reads USERPROFILE, not HOME, so a test that set HOME to a temp dir still found the one USERPROFILE every gateway test shares (and the box's real agents); Devin's CLI keeps its sign-in under APPDATA. Each such test now sets USERPROFILE with HOME (setHome), TestDevinOwnMovesWithPlan sets APPDATA, and the tests whose Claude Code is a shell script skip on Windows, where it can't run and the box's real claude ran instead. Tests only. The gateway suite and TestDevinOwnMovesWithPlan pass on Windows; go test -tags nogui ./... passes on macOS. 2026-10-01 20:26:53 +08:00
yetone e698e7dddd claude: adding a Claude account is Claude Code's own claude auth login, and magpie never refreshes a Claude sign-in nor asks Anthropic anything with one (the user: 把 magpie 自己的 Claude 登录改成直接用 claude /login,只要体验上没什么差别就改) — magpie traded the sign-in page's code for tokens with Claude Code's OAuth client, asked Anthropic's profile and model list with them, refreshed saved accounts itself (daily keepalive included) and handed a saved account to Claude Code as CLAUDE_CODE_OAUTH_TOKEN. Now Add account runs claude auth login --claudeai in a config directory of magpie's own: the page Claude Code would open comes to magpie's window (Claude Code is given magpie as its BROWSER, which writes the page down and exits), the browser comes back to Claude Code's own listener, and when the browser can't reach this machine the address it ended on, or the code Claude's page shows, is pasted as before and handed to Claude Code. Who signed in is what Claude Code kept (.claude.json, auth status). A saved account in use beside the signed-in one runs Claude Code with CLAUDE_CONFIG_DIR set to its own directory (claude-accounts/ beside magpie's config), its sign-in put there once from logins.json and read back as Claude Code refreshes it; switching to it moves it into Claude Code's own store and removes the directory, as forgetting it does. Claude's models are the catalog's (models.dev), not asked of Anthropic; an imported Claude login is kept as the file has it, and Claude Code refreshes it on first use. Claude Code is required to add a Claude account. TestClaudeSignInByPaste, TestClaudeSignInByPastedAddress, TestClaudeSavedAccountDir (a fake claude CLI, and a server standing in for Anthropic that fails the test if asked) and the reworked sign-in, import and gateway tests fail without the change. With the real Claude Code 2.1.286 in a sandbox directory, its sign-in page (localhost callback) reached magpie's binary and the sign-in waited for the browser; nothing was left behind once it was canceled. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; claude-risk, plugin-signin, signin-callback, signin-link, signin-paste-codex, routing-signin, own-signin-remove, click-scroll, old-webkit pass. 2026-10-01 16:37:07 +08:00
yetone 207042dd78 claude: the signed-in account is one account, and one out of quota hands over to the next (#177) — the account Claude Code is signed in to was named one way as a provider and another as a saved login, so it was served twice and its limits weren't found under its name; and claude auth status was asked with magpie's own ANTHROPIC_BASE_URL/token in the environment, telling of those rather than the sign-in. Now both go by ~/.claude.json's email (with the org), the CLI's email when that has none, and the status is asked without magpie's wiring. A turn the CLI ends with an error result (out of quota, rate limited) ends the reply there instead of waiting on, and a non-streamed one answers 429 for quota words, so another account takes over as in a stream. Tested: the account named as its login, the quota result ending the reply, another account taking over 2026-09-29 10:50:39 +08:00
yetone ecaaf888b5 providers: a provider with several keys has its models asked with each key, and each model remembers which keys see it — a relay that hands out a key per group lists each group's models to its key only; requests go to a key that lists the model (every key when none does), and Test signs each endpoint with a key made for it and asks for a model that key sees 2026-09-25 01:15:02 +08:00
yetone f3b66c4784 provider: a key can be made for one protocol — for relays that hand out one key for Anthropic and another for OpenAI; the gateway uses each key on its own endpoint only and sends Claude models to the Anthropic key, GPT models to the OpenAI one, translating when it must 2026-09-24 14:54:56 +08:00
yetone 64d3a1c23a provider: several subscription accounts in use at once, each with its usage — tick more Claude or ChatGPT accounts and the gateway moves to the next when the first is out of quota; every account row shows how much of its 5-hour and weekly allowance is used 2026-09-24 14:46:26 +08:00
yetone 6514b559aa provider: several accounts of one provider in use at once — tick every key to use; requests go to the first, and when it is out of quota or rate limited the next ticked key takes over before any fallback model 2026-09-24 14:36:39 +08:00
yetone 435d65882b gateway: fallback — when a provider is out of quota, rate limited or down, a request goes to the next model you listed for it, before any of the reply is sent; set it in the provider editor or with magpie provider fallback 2026-09-24 14:04:42 +08:00