Commit Graph
4 Commits
Author SHA1 Message Date
538026e62b gateway: an error frame inside a 200 fails at the status it names (#4855)
mycf_711's wps-lingxi rows read status=200: the plugin's stream already
sent its 200, then wrote {"error":{"message":"灵犀上游返回 AIError:
AI服务异常(上游暂时不可用,可重试)(HTTP 503)",...}}. On main a frame
mid-reply was booked at 200 and rested 60s as "other" with the error
"OK: ...", and one as the first event failed at the 502 the words'
guess gives. Routing never saw the 503 (or AuditFailed's 502).

Now the status an error frame names is what it fails, rests and is
booked at:
- a numeric status or code member, 400-599 (skygunner's patch: held
  stream's errOf, errorReply, carriedStatus, and the sniffer's note on
  the try's header for a reply already streaming, kept from the client);
- else "(HTTP 503)" / "(HTTP 503)" in the words, 429 and 5xx only, as a
  quoted 4xx ("the image link answered (HTTP 404)") may not be the
  provider's;
- a mid-reply call is booked at that status in Routing and Usage.
A quoted string code ("429", "1113") is the vendor's own code, not a
status. Words magpie wrote itself (loop guard, empty reply, relooped)
and too-long words name nothing, whatever members they carry: a LAN
peer's loop guard frame carries 502 in its Gemini shape. Such a frame
also no longer rests the route mid-reply (main rested it 60s as
"other" at 200); the model looping is not the provider failing.

Left out of skygunner's patch: streamFailure giving magpie's own Chat
frames a code and status. A peer magpie would read its loop guard frame
as a named 502.

Run (mote, at a1f1810e9 + this change):
- go test -count=1 -run 'TestRelayStreamErrorFrame|TestNamedStatusOf|
  TestGeminiCompat|TestLoop|Stream|Late|Carried|ErrorReply|Rest'
  ./internal/gateway: first run red on TestNamedStatusOf (a quoted
  "429" read as a status through json.Number), fixed. At this commit
  (on 8a8079680; d02b8a000 under it since changes the GUI only), the same -run with
  |Refus|Fallback added: ok (222s); go vet ./internal/gateway on
  darwin, GOOS=linux and GOOS=windows: clean; gofmt -l: nothing.
- The new tests at a1f1810e9 without the change: every subtest of
  TestRelayStreamErrorFrameSaysItsStatus and
  TestRelayStreamErrorFrameNamesItsStatusInWords red except the 4xx
  quoted case (mid-reply rested at 200, first event booked at 502,
  the peer's loop guard rested).
Broken by hand:
- namedStatusOf without textStatus: first_event and TestNamedStatusOf
  red.
- magpieSaid returning false: the peer loop guard subtest and
  TestNamedStatusOf red.
Not tried: a real wps-lingxi account; the full suite (runs after the
push). AuditFailed (the plugin's "audit_blocked") is counted as the 502
it names, not as a refusal of the request's content; whether a content
refusal there should rest nobody was not checked.

Co-authored-by: vincent <vincent@users.noreply.github.com>
Co-authored-by: MYCF711 <323101370+MYCF711@users.noreply.github.com>
2026-11-04 22:17:49 +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 6d1c7df9e7 gateway: a reply looping on the same few words with no line or sentence's end ("mcp mcp mcp …") is found and ended, as a loop of lines is (#1489, bfxh)
bfxh: the model loops, saying "mcp" over and over. The loop guard cuts a
reply into lines and sentences and finds a loop in 256 of them. Words
repeated with no line break and no sentence stop form no such unit: the
text is cut only every unitMost (4096) bytes, so 256 units would be about
1 MB, far past any reply's output limit. A loop like that ran on to the
limit.

A unit cut at unitMost, with no break in it, is now read by itself
(runOnWords). It is a loop when it is one piece repeated (period of at
most 64 bytes, "mcpmcp…" or "重复说mcp重复说mcp…"), or when its words, at
least one per 32 bytes, are no more than 8 different ones. Two such units
in a row, about 8K characters or 2,000 tokens, end the reply. Text and
reasoning are both read. Reasoning that loops before anything is said is
asked again once, as 8424a004 does for a loop of lines. A loop broken
into lines longer than a unit still counts. The error says "the same over
and over without a break" and quotes the words.

Run:
- TestLoopGuardFindsARunOnLoop (new): spaced, comma, unspaced, a few
  words, Chinese; as text and as reasoning; found within 3 units.
- TestLoopGuardLeavesOrdinaryRepliesAlone also feeds, with no break at
  all: gateway.go, LESSONS.md, i18n.js, a log, a CSV, hex, table rules,
  and a one-line JSON array of 2,000 records. None trips.
- Break checks: runOnUnits = 1000 turns the new test red. No distinct
  limit and no word density check turns 10 of the ordinary texts red.

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

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

Not tried with the real WorkBuddy or DeepSeek model.
2026-10-09 22:32:31 +08:00