Commit Graph
1028 Commits
Author SHA1 Message Date
yetone 2fbbd16945 gateway, gui: routing history keeps the last two levels of the folder an agent works in, and By session, the stage and the panel name it (#1068, emo172)
Routes now carry Folder: the last two levels of the working directory the
agent states (Claude Code's "Primary working directory", Codex's <cwd>,
Pi, OpenCode), cut by shortFolder before the route is stored, so no full
path reaches the routing history, /api, or the GUI. It is kept in the
routing history for as long as the history itself (30 days / 200 MB).
A request that states no folder (title, side calls) takes the folder its
session (or parent session) last stated; the per-session map is capped
at 512 entries.

GUI: By session headings read "Agent · folder · title", their tooltip
and every request row's tooltip (page and tray panel) name the folder,
the stage's agent subtitle lists the last level of each folder when an
agent works in more than one, and the panel's agent node tooltip lists
them.

Run:
- TestShortFolder (unix, trailing slash, C:\, D:\, UNC, CJK with spaces)
  and TestRouteKeepsItsFolderShort (real Handler, fake upstream: session
  inheritance, a moved Windows path, nothing of the full path in the
  marshalled routes, saveRoute -> History round trip), TestTurnDone.
  Broke it by hand: without the session lookup the title request has no
  folder; with the folder unshortened the full path shows. Both go red.
- routing-session-folder.test.cjs: chromium + webkit x en, zh, zh-TW,
  ja, de x 1100 and 420 px, 20/20. Red on the old routing.js and with
  the stage's live routes left out.
- GUI suites routing-*, panel-routing*, purpose-filter, reasoning-speed,
  gui-de/ja/zh-tw, click-scroll, number-units: 951/951.
- gofmt -l clean; go vet darwin, linux (nogui), windows; builds for all
  three. go test -tags nogui ./...: all ok except internal/gateway, which
  hit go test's default 10m timeout at 611s on a loaded machine (#2108);
  alone with -timeout 30m it passes in 356s.
- Real use: nogui build in a sandbox HOME, fake upstream, real Claude Code
  2.1.299 (claude -p) run from .../workspace/magpie and .../src/dial: the
  day's routing jsonl has folder "workspace/magpie" and "src/dial" and no
  part of the sandbox path above them.

Not tried: title/side requests' inheritance end to end with a real agent
(claude -p made none), Codex, OpenCode and Pi with real binaries, Windows.
2026-10-14 14:03:38 +08:00
yetone d9ca84a2f4 gateway: built-in TLS, magpie serve/web/daemon install --tls-cert --tls-key, reloaded on renewal (RoderickZH)
magpie serve, magpie web and magpie daemon install take --tls-cert <file>
--tls-key <file> (or MAGPIE_TLS_CERT / MAGPIE_TLS_KEY). The gateway and the
web UI on its listener then serve HTTPS to other computers. Without them
nothing changes.

- Half a pair, a file that doesn't parse, or a flag with no value is
  refused at start with a message naming the missing flag.
- The pair is re-read when either file's mtime or size changes (certbot
  renewal), with no restart. A renewal that doesn't parse keeps the
  certificate already served and is logged once.
- Other computers get HTTPS only. Plain HTTP from them gets net/http's
  400 "Client sent an HTTP request to an HTTPS server".
- This computer (loopback, or a peer address equal to the local one) may
  still use plain http on the same port. Its connections are sniffed on
  their own goroutine (a first byte of 0x16 is TLS) for up to 10s, so a
  silent client holds nobody else up. gateway.URL() stays
  http://127.0.0.1:<port>, which agents, MCP servers, ServedBy, the
  healthcheck and daemon status all use, and no certificate covers
  loopback.
- WSL NAT and containers count as other computers.
- ALPN is http/1.1 only (hijacked connections and websockets need it), with
  TLS 1.2 as the minimum.
- Printed links, LAN addresses, publicURL, the serve/web banners and
  daemon install show https:// for other computers' addresses.
- The DNS-rebinding Host checks (foreignPage, rebound, the MCP
  loopbackHost) don't depend on the scheme and are unchanged.
- daemon install carries MAGPIE_TLS_* into the unit or plist. A reinstall
  or `daemon web on` that names no certificate keeps the installed pair,
  and --no-tls removes it.
- Docs: reference.md gets an HTTPS section that names Caddy as the
  alternative, gateway-routing.md gets a TLS row, and docker.html (en,
  zh, ja) gets the env rows.

What was run:
- New tests: internal/gateway/tls_test.go (others HTTPS-only, this
  computer both, a silent local client holds no other, renewed
  certificate served, CheckTLS, addresses, Relisten keeps TLS),
  internal/cli/tls_cli_test.go and daemon TestInstallCarriesTLS (linux
  and darwin, paths with space, %, & and ").
- Each was broken by hand and went red: no wrap in listen, no reload, a
  synchronous sniff, a bad renewal dropping the certificate, http in
  publicURL or the pinned LANURLs, the carried entries removed, and
  keepTLS as a no-op.
- Real use under a sandbox HOME, with a self-signed pair, on
  0.0.0.0:3461:
  - Half a pair, a garbage certificate, a flag with no value, and the
    env set to half a pair each exit 1 with the message.
  - curl -k https://127.0.0.1 and https://<LAN IP>/v1/models with a key:
    200. Plain http on loopback: 200.
  - The cert files were swapped for a second pair while it ran.
    openssl s_client then showed the new CN and serial, and curl
    --cacert with the new pair got 200. A junk key file then kept the
    second pair, logged once.
  - From the Windows box over the LAN: plain http got 400; https with
    the key got 200, and without it 401.
  - magpie web --addr 0.0.0.0:3462: https network links. From Windows,
    http got 400 and https with the key got 303.
- gofmt -l clean. go vet passed on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -tags nogui for ./internal/cli, ./internal/daemon, and the TLS
  tests of ./internal/gateway and ./internal/gui: all pass at the rebased
  head.
- Two reds in the full suite (`go test -tags nogui ./...`) are the same
  on origin/main f074996d9; both are filed:
  - TestGatewayHeldByAContainer failed 2 of 5 there (#2107).
  - The gateway package runs past go test's default 10m under load:
    1208s on main and 1221s here, both passing with -timeout 40m
    (#2108).
2026-10-14 13:36:03 +08:00
yetone 353464f161 gateway: a translated Anthropic or Responses reply that said nothing and counted no token is asked again, then fails, not completed (#2086, tensornull)
tensornull's Codex turn on an Anthropic-compatible proxy (baseAPI
anthropic, claude-opus-5-5) ended as response.completed after 21s with
no output: the route had status 200, no usage, no served model, no
ttft. Codex took it as its turn's end (last_agent_message null) and
didn't ask again. No usage and no served model mean the proxy never sent
a message_start Claude would have (it counts the prompt and names the
model), yet the stream said it ended (message_stop or a stop_reason), so
320af9858's replyEnds read it as whole and errEndedShort didn't apply.

Now a reply from an Anthropic or Responses upstream (repliesCounted) that
said nothing (no text, call, search or image) and counted no token at all
(uncounted) is the empty reply #667 already handles for Gemini: asked
again in place, then failed with "an empty reply (the model answered
nothing; try again)", which Codex retries. Same in streamTranslated and
the unstreamed translate path, for Responses, Messages and Chat clients.
Claude's own empty end_turn (after a tool's result) counts its prompt and
still completes, as does a Responses reply with usage and no output.

Not changed: a reply passed through in its own protocol (Codex asking a
Responses provider, Claude Code an Anthropic one) isn't read for this;
the passthrough has no empty-reply rule at all, Gemini's included.

Verified:
- New stream_uncounted_test.go. TestUncountedEmptyReplyFails (message_stop
  only; pings then message_stop; message_start with no usage then a
  stop_reason; zero usage), TestUncountedResponsesReplyFails and
  TestUncountedEmptyReplyFailsEveryClient (Chat streamed, Responses and
  Chat unstreamed) all FAIL on the old code ("ended response.completed
  \"completed\", want response.failed", "status 200, want the empty
  reply's failure") and pass with the change. TestCountedEmptyReplyStillCompletes
  and the #1933 tests (TestWellFormedStreamsStillComplete, TestMalformed*)
  pass.
- The full go test -tags nogui ./internal/gateway run failed only
  TestCodexHeadersReachKeyedRelay and TestStandaloneNativeAccounts, whose
  fake Codex backends answered response.completed with output [] and no
  usage, which the real backend never sends; their fakes now count
  tokens, and both pass. Run in a sandbox HOME with pinned
  caches; gofmt -l; go vet ./internal/gateway for darwin,
  GOOS=linux -tags nogui and GOOS=windows; GOOS=linux go build -tags
  nogui and GOOS=windows go build.
- Not tried: the reporter's proxy or its real bytes (the report has none);
  the fixtures are the shapes its route record allows. Not run: the full
  go test ./... (only internal/gateway changed).
2026-10-14 13:26:18 +08:00
yetone e710c5accd gateway: the built-in Kiro tells Kiro where to cache the prompt (magpie-community/plugins#110)
plugins#110 ("kiro cli cache 率为 0"): a Kiro subscription read nothing
from its prompt cache. Kiro's generateAssistantResponse takes Bedrock's
cachePoint {"type":"default"} on a userInputMessage (the CodeWhisperer
streaming model in aws/amazon-q-developer-cli; Kiro CLI 2.27's model list
carries PromptCaching with up to 4 checkpoints), but neither the plugin
nor the built-in ever sent one. The plugin's fix is kiro 0.1.10
(plugins 386a2ba); this is the same for users who haven't moved.

buildKiro now marks the first message when there is a system prompt
(which it folds into that message) and the current message, the two
places buildAnthropic marks for Anthropic. gateway-routing.md says how
each Kiro path places them.

Run: gofmt -l (clean); go vet on darwin, GOOS=linux GOARCH=amd64 -tags
nogui and GOOS=windows for internal/gateway and internal/provider; go
test -count=1 ./internal/gateway ./internal/provider (ok; both isolate
HOME in TestMain). TestBuildKiroMarksTheCache fails with the current
message's mark taken out by hand, and passes with it back.
Not tried: a real Kiro account (none signed in here), so whether Kiro
then reports cache reads is for the reporter to confirm; kirocc#83 notes
Kiro often sends a metadataEvent with no token counts.
2026-10-14 13:20:36 +08:00
yetone f074996d93 provider, gateway, gui: a model with none of its levels ticked is sent no reasoning field, on every route and in a routing group (yuexian7)
yuexian7 on Discord: models.dev lists their model as reasoning, and the
vendor answers any reasoning parameter with 422 while the same request
without it works. In a routing group they couldn't set an effort per
model, and the model editor refused to untick the last level ("Keep at
least one level"). The learned refusals (bed306ae, #1062) don't cover
this: they learn a refusal of reasoning *off* and of Gemini levels, and
optionalFields holds thinking/enable_thinking, not reasoning_effort.

- settings.ModelReasonless, set by provider.SetModelReasonless (the
  provider editor's Names & levels with every level unticked, saved as
  modelPrefs {reasonless: true}; `magpie model efforts <ref> off`).
  Ticking levels again or Restore default clears it (setModelEfforts);
  setting it drops the model's kept levels.
- entryFor and Efforts/Thinks/Levelless: the model offers no levels and
  is Quiet, so agents are given none for it.
- Gateway: the candidate loop strips the body with withoutAnyReasoning
  in the agent's protocol (Chat/Responses reasoning_effort, reasoning,
  thinking, enable_thinking, include's reasoning.encrypted_content;
  Anthropic thinking of any type and output_config.effort; Gemini
  thinkingConfig). The Anthropic relay doesn't add
  thinking:{type:disabled} for it, and forwardTranslated clears Effort,
  ThinkOff and Thinking for its other callers (continuation, search).
- A routing group with it as a member keeps the other members' levels
  (it `continue`s like a member whose levels are unknown, #597), and the
  member that reasons is still sent the effort asked.
- GUI: none ticked shows "No reasoning field sent" beside the levels, in
  zh, zh-TW, ja and de too; a model with one known level now shows its
  picker so it can be unticked. A model whose levels aren't known
  (m.given) keeps none ticked meaning no levels known.

Run (worktree on origin/main 82f3befd2, sandbox HOME, private GOCACHE):
gofmt -l clean; with set -o pipefail go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... all clean; node --check
app.js. go test -count=1 ./internal/provider ./internal/gateway
./internal/settings ./internal/cli: ok. ./internal/gui: ok except
TestMainWindowCorners/macOS_15_SDK killed at its 40s deadline under
load (AppKit window measurement, untouched here; #1936, noted there).
The run caught TestSettingsSaveKeepsWhatItDoesNotSend (ModelReasonless
added to it) and the CLI usage alignment tests (fixed).
New tests and what breaking the change does: TestReasonlessModelSentNoReasoning
(Chat, Chat+enable_thinking, Responses with include, Anthropic->Chat
translated; by name and through group/mix) and TestReasonlessAnthropicRelay
fail with gateway.go/quiet.go reverted; TestGroupReasonlessMemberKeepsLevels
fails with group.go's reasonless branch disabled; TestModelReasonless
needs the new API. model-reasonless.test.cjs in chromium and webkit, at
1100 and 420, in en, zh, zh-TW, ja, de: 20/20; on the old assets all
fail. Related GUI tests 418/418 (one model-copy-id failure on a first
run under load, passed alone; #2066).
Not tried against the reporter's real vendor: the 422 is taken from
their report.
2026-10-14 09:38:12 +08:00
yetone c4f4aaaa97 gateway: Claude's bridge no longer passes hook notices and token counts on as the user's message (#2060)
Through the Claude subscription bridge, the inner Claude Code kept saying
"The user sent a new message while you were working:" followed by a hook's
additional context, a bare <total_tokens>... line or nothing at all. The
outer agent sends these after a tool result, and saidWithResults took every
text block after a result as words the user typed mid-turn and queued them
into the inner session.

Captured from a real Claude Code 2.1.296 with PreToolUse/PostToolUse hooks
against a local mock: after a tool_result it sends a {role:"system"}
message whose one text block joins "PreToolUse:Bash hook additional
context: ...", "PostToolUse:Bash hook additional context: ...", optionally
"The user sent a new message while you were working:\n<words>\n\nThis is how
Claude Code surfaces messages ...", and "<total_tokens>N tokens left
</total_tokens>". Older clients put the same in <system-reminder> blocks;
the reporter's had an empty reminder too, which is why some of their
"messages" were empty.

- saidWithResults takes only the user's words out of a mid-turn block
  (midTurnSaid, up to the client's own tail, a reminder's end, the token
  count or the next hook notice), skips the rest of a system or developer
  message, and drops a text that is an agent notice (agentNotice: empty
  once reminder tags are stripped, a hook notice of the known kinds, a
  token count, or one of the injected leads prompt.go already knows).
- renderParts, the sibling that labels text after a result as
  [user message] in the prompt for a fresh run, closes the result instead
  for an agent notice.
- docs/subsystems/claude-subscription-bridge.md says so.

Run:
- Fixtures are the literal 2.1.296 bytes and the reporter's
  (claude_hook_notice_test.go): nothing queued for hooks and token counts;
  only "also tell me the date" queued when the user did write; the
  rendered prompt has no [user message]. A "Stop hook is broken: fix it"
  typed by the user still goes on.
- With the old condition put back and the renderParts change off, the
  three new tests fail; restored, they pass.
- gofmt -l internal/: clean. go vet ./internal/gateway on darwin,
  GOOS=linux -tags nogui, GOOS=windows (set -o pipefail): clean.
- go test -count=1 -timeout 30m ./internal/gateway: ok (667s).
- Not tried end to end through the bridge with a real Claude subscription.
2026-10-14 09:32:21 +08:00
yetone ccffdadb8a gateway: /v1/audio/transcriptions passes speech-to-text through to the provider (#2053, niyoh120)
niyoh120 asked for an OpenAI-style speech-to-text endpoint so a client's
voice input can go through magpie like its chat does. magpie had no
/v1/audio route, so the request 404ed.

What changed:
- POST /v1/audio/transcriptions and /v1/audio/translations (and the
  /audio/... spellings) route through the same core as embeddings and
  rerank. embeddings.go's routing is pulled out into serveRetrieval, so
  disabled models, key access, groups, pause rules, account holds,
  failover, redaction and usage records are shared rather than copied.
- transcribe.go reads the multipart form only to find `model` (as
  provider/model) and `prompt`. The form goes to the provider byte for
  byte; it is rebuilt part by part, under the same boundary, only when
  the model name is rewritten or the prompt was masked. The audio part
  is always copied as sent.
- Only providers with an OpenAI-style base are tried; an Anthropic-only
  provider gets a 400 saying so. A body that isn't multipart, a form with
  no model, or one that doesn't parse gets a 400 and nothing is sent.
- The vendor's answer type passes through (response_format text/srt/vtt
  stays text/plain). Usage records output tokens from usage.output_tokens.
- The 404 message, the info api list, remote magpie's suffix list, the
  CORS and LAN tests, docs/reference.md, gateway-routing.md and the
  remote docs (en, zh, ja) name the new paths.

What was run, at 9c36c3a0 (this change rebased on 10f38770):
- gofmt -l internal/gateway internal/provider: empty
- go vet (darwin); GOOS=linux and GOOS=windows go vet -tags nogui on
  ./internal/gateway ./internal/provider: clean
- go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider:
  ok (1367s, 339s); also green on two earlier bases (b4fe6663, 06fbfd95)
- Rebased again on a0ebe003 (main had moved 5 commits, none in these
  files; routing.go's Factory rest is the nearest): gofmt, vet on darwin,
  linux (nogui) and windows (nogui) clean, and
  go test -tags nogui -run 'Transcri|Embed|Rerank|CORS|LAN|Lan|Factory|
  Retriev|NotFound|Info' ./internal/gateway ok. The full packages were not
  rerun on this last base.

Break-checks, each turned red and restored:
- routes removed (the old code): all 5 new tests fail
- model never rewritten: TestTranscriptionGoesToTheModelsProvider and
  TestTranscriptionPromptRedacted fail
- answer always labelled JSON: TestTranscriptAsTextKeepsItsType fails
- rebuild truncates the audio part: Goes + PromptRedacted fail
- prompt not masked: TestTranscriptionPromptRedacted fails
- output tokens ignored: TestTranscriptionGoesToTheModelsProvider fails

Real use: through magpie's real handler against aihubmix
(https://aihubmix.com/v1) with a `say`-made m4a: whisper-1 json 200
{"text":"Hello from the Magpie Gateway."}, response_format=text 200,
srt 200 text/plain with SRT cues, translations 200.

Not tried: OpenAI direct (the key answers 429 "account is not active"),
Groq, a local vLLM/whisper server, and any real client's voice input.
2026-10-14 09:19:16 +08:00
yetone 8cb0946fbe gateway: a Factory usage-limit 402 that arrives before the account's windows are read rests only that model once they are (#2036, Ziqi-Cui)
#1979 rests only the model when Factory answers 402 "You've reached your
weekly standard usage limit" and the account's windows say Standard's
pool is the one used up. Before the windows are read (just after a
start, or after a reading failed) nothing tells the pool from the
account, so the whole account rested, Droid Core's models with it,
until the reset the refusal named, often days.

Such a rest now starts narrowWhenRead in the background: it waits for a
reading (provider.AwaitAllowance, up to a minute), and if the reading
says the model's pool is the one used up, moves the rest to the model
alone (restID) with the same end. No reading in time, a reading that
says the whole account, or a rest lifted or made again meanwhile leaves
the account's rest as it is.

CodeAlex52's patch (c623610) waited for the reading inside the request
for up to 10s. That holds the failover the client is waiting on, so the
wait is off the request instead: the request has failed over already,
and the rest's scope only matters to later ones. The gateway's TestMain
turns the wait off so no test's goroutine asks a fake upstream after
the test ends; the tests that need it swap it in and wait on
narrowing.

Run: TestFactoryStandardOutLeavesCore's new unread case (built-in and
plugin windows) and TestResetsInWords' no-reading case; the unread case
fails with the narrowing removed; -race -count=3 on both; full
go test -tags nogui ./internal/gateway in a sandbox HOME; gofmt -l
clean; go vet darwin, linux nogui, windows nogui.
docs/subsystems/gateway-routing.md's 402 paragraph says so.
2026-10-14 09:15:21 +08:00
yetone 10f3877071 gateway tests: TestCodexHeardWithinItsIdleTimeout leaves over a second of room on both sides, where a busy machine's lag carried member a's failure past Codex's quiet limit (#1800)
#1800 has the test failing two ways on busy machines. The body check:
member a failed at 0.7s and Codex's quiet limit was 1s, so 300ms of the
gateway's lag put a's failure past the limit, and it went to Codex as
it was. The bound on the second half: 3s, against 1.2s expected and
3.2s for the pause waited.

Now the quiet limit is 2s (a fails 1.3s before it), b's reply comes at
4.7s with the first event bounded at 3.5s, and the second half's pause
is 10s with a 6s bound (1.2s expected, 11.2s waited).

Run:
- Reproduced the body failure on origin/main 7d15df78a by injecting
  350ms into a's wait (1050ms): overload_test.go:269 got a's
  server_is_overloaded, as in #1800's comments.
- With the change: passes 3/3; with 1s injected into a's wait (1.7s);
  with 1.3s injected into each member's wait in the second half; 8/8
  under 24 busy loops on top of other sessions' load (load average
  38 to 69).
- Broken by hand: tooQuiet returning false fails the first bound
  (4.72s); the replan and passing pauses no longer skipped when too
  quiet fails the second (21.8s, a 2, b 1).
- gofmt -l clean; go vet darwin, linux -tags nogui, windows.

Not tried: the whole gateway package after the change (only this
test); CI's machines. The test takes about 6.3s, up from 4.5s.
2026-10-14 08:47:30 +08:00
yetone 1eaf1e890a gui: Sessions is a plugin's page, its script, styles and words under assets/plugins/sessions (P2)
The first page of P2 to leave app.js's core. sessions.js and sessions.css
move to assets/plugins/sessions/ (client.js, sessions.css). The page
registers through the kernel as magpie.plugin("sessions"): mount takes its
<main>, which the kernel now makes, open and relang read it again, and
reveal is the Usage page's way in. window.loadSessionsPage and
window.openSessionOnPage are gone. app.js reaches the page only through
magpie.call, and show() takes a page's title from its part. The plugin's
manifest lists i18n.js, sessions.css and client.js.

Words: the kernel's magpie.strings(dict) adds a plugin's words to I18N.
A key that is already there is logged and not taken, since the later one
would silently win. The 65 keys only the Sessions page says (own-keys over
every asset, Go and index.html) move, as written, from i18n.js to
plugins/sessions/i18n.js. tests/strings.cjs reads i18n.js and every
plugin's i18n.js as the page has them. gui-de/ja/zh-tw use it, and
i18n-keys now checks that no key is said twice across files and that a
plugin's words are in every language. TestBuiltinClientsLoaded takes a
.css entry as a <link> in <head>, and a script between kernel.js and
app.js.

Docs: plugin-runtime.md (Words, Pages moved out: Sessions), gui-shell.md,
gateway-sessions.md.

Run:
- go test ./internal/gui/ ./internal/pluginrt/ ./internal/gateway/: ok.
- gofmt clean. go vet darwin, GOOS=linux -tags nogui and GOOS=windows on
  gui, pluginrt and plugins: clean.
- GUI, in both chromium and webkit, 40 files, all green:
  - the sessions-* and sess-* tests, session-identity, routing-sessions,
    account-mask-sessions, usage-session*, gateway-conversations;
  - plugin-kernel, the plugin-move* tests, font-cascade, win-fonts;
  - i18n-keys, gui-de, gui-ja, gui-zh-tw.
- session-terminal's red under parallel load is the same on origin/main
  591ed58b5. It is fixed at its cause in the commit before this one.
2026-10-14 08:33:24 +08:00
yetone a39e675d2a gui: magpie web beside a busy gateway waits for the port instead of failing to bind it (K.Liu)
K.Liu on Discord: `magpie web` next to the systemd `magpie daemon` logged
"gateway: listen tcp 0.0.0.0:3425: bind: address already in use".

Cause: before listening, serveGatewayLocked asks the gateway's address
whether a magpie serves it (ServedBy, one GET with a 700ms timeout). A
magpie that holds the port but doesn't answer in time (busy on a small
server, or still starting) reads as "nobody", so the page's process
listened itself and the bind failed. With the service answering, no
second gateway was started and the page's state matched.

Now, after ServedBy says no, gateway.Taken() dials the address (500ms).
When something accepts, this magpie doesn't listen; it logs once that the
port is taken and leaves it to the 15s watch, which serves the gateway
once the port is free.

Run:
- Sandbox HOME, settings {"port":3461,"lan":true}: `magpie serve`, then
  `kill -STOP` it, then `magpie web --no-open --addr 127.0.0.1:3462`. The
  old binary printed the exact bind error. The new one logs "is taken but
  doesn't answer as magpie yet" and doesn't bind. After SIGCONT,
  /v1/models and the page's /api/state show the same 3 models. With the
  serve killed, the page's process took 3461 over in about 16s.
- TestGatewayNotServedBesideASlowOne (a listener whose handler blocks):
  it goes red with the Taken check reverted by hand.
- gofmt -l; go vet (gui), and go vet -tags nogui for darwin, linux and
  windows, on cli, daemon, gui and gateway; go test -tags nogui ./... in a
  sandbox HOME.
2026-10-14 08:32:40 +08:00
yetoneandlu123bing c9af654b26 gateway: Kimi Code takes a Claude Code session that loaded a deferred tool, and DeepSeek one that dropped a tool (#2042, davisjiahao)
Claude Code's deferred tools (ToolSearch, MCP tools that come and go) put
blocks of their own in a message: tool_addition (its tool a
tool_reference naming the tool, or a tool_definition), tool_removal, and
tool_reference. magpie relays an Anthropic body as it is, so they reached
vendors' Anthropic endpoints.

Checked against the real endpoints on 2026-10-14 (a Kimi Code CN key, a
DeepSeek key; shapes read from Claude Code 2.1.296's own builder):
- Kimi Code refuses any of them, in any role and either tool shape, with a
  whole-request 400 "Invalid request Error" that names nothing; a
  tool_reference inside a tool_result passes.
- DeepSeek takes a tool_addition naming a tool, but refuses one defining
  it, a tool_removal and a message's tool_reference: 422 "messages[1].
  content: unknown variant `tool_removal`, expected one of ...".

What changed:
- withoutDeferredTools (anthropic_shapes.go) drops those message blocks
  and a message they leave empty. The tools stay in the request's tools,
  and ToolSearch's answer (a tool_reference inside a tool_result) stays.
- Kimi (isKimi) is never sent them: its 400 says nothing to learn from.
- Any provider that refuses one in DeepSeek's words is marked
  (shapeDeferred, refuseShapes) and asked again at once without them, and
  not sent them again while magpie runs. The shape-retry loop in forward
  now reads a 422 as well as a 400 (refuseShapes and refuseBetas only act
  on wording they recognise).
- Anthropic and every provider that takes them get them as Claude Code
  wrote them. Kimi's bare "Invalid request Error" is not added to
  shapeWords: it names no field, and with the blocks gone there is nothing
  left for it to cover.
- docs/subsystems/gateway-routing.md: a paragraph on the above.

Builds on lu123bing's fork branch (c4a0564), widened from Kimi to the
learned refusal after the DeepSeek check; this keeps a tool_addition
naming a tool for providers that take it.

Run:
- TestKimiIsSentNoDeferredToolBlocks (the reporter's literal body plus
  Claude Code's real shapes, through Handler) and
  TestDeferredToolBlocksRefusedOnceLeftOut (DeepSeek's literal 422,
  learned once; a provider that takes them keeps getting them).
- Break checks, each red: without the Kimi drop, 5 subtests "status 400:
  Kimi Code: Invalid request Error"; with the loop on 400 only, and
  without the mark, "status 422: DeepSeek: ... unknown variant
  `tool_removal`". Restored: green.
- Real use: a nogui build served from a sandbox HOME on 127.0.0.1:35211
  with copies of the Kimi Code CN and DeepSeek providers. The reporter's
  body to kimi-for-coding now reaches Kimi's account check (403, the test
  key's plan has lapsed) instead of the 400; a tool_removal to DeepSeek
  reaches its balance check (402) instead of the 422. A full successful
  Kimi turn wasn't possible on this key.
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on internal/gateway; go test -tags nogui ./internal/gateway/
  in a sandbox HOME: ok (1516s). An earlier run of the same suite, with
  five other gateway.test binaries running on the machine, ended FAIL
  after 1484s; its output was cut to the last 30 lines, which held no
  test name, so the failing test is not known.

Co-authored-by: lu123bing <12312702@mail.sustech.edu.cn>
2026-10-14 08:26:38 +08:00
yetone 8f03b78069 cli, gateway: magpie statusline prints the session's model and each account's windows for Claude Code's status line (#1997, kensenzhao)
kensenzhao asked for magpie's routing and quota in Claude Code's status
line. Claude Code runs the statusLine command on every update and cancels
the run that is still going, so the command must answer fast. It must never
make a vendor read.

- `magpie statusline [<provider|account>]` reads Claude Code's statusLine
  JSON from stdin. It prints "→ <served model>" from
  /v1/magpie/route?session=<session_id>, then each subscription account's
  windows ("claude a@x* 5h 62% 7d 41%"). `*` marks the account that served
  last. A window whose reset has passed shows 0%. With the gateway off it
  prints an empty line. Each request times out after 1s.
- /v1/magpie/quotas?kept=1 (provider.KeptQuotaReport) builds the same
  report from the kept cards (CachedCards) and never starts a vendor read.
  The plain endpoint can take up to 12s.
- magpie never writes statusLine into Claude Code's settings. The user
  adds `"statusLine": {"type": "command", "command": "magpie statusline"}`
  themselves (magpie statusline's help, docs/reference.md).

Run: go test -tags nogui ./internal/cli ./internal/provider
./internal/gateway in a sandbox HOME; gofmt -l; go vet natively and with
GOOS=linux and GOOS=windows.

Broken by hand, each went red:
- the CLI asking without kept=1 (TestStatuslineTellsRouteAndEveryAccount);
- dropping the route line (same test);
- KeptQuotaReport calling QuotaReport (TestKeptQuotaReportAsksNobody).

Real use: a built binary against a sandbox gateway on 127.0.0.1:3517.
- kept=1 answered in 0.07s and route in under 1ms.
- `magpie statusline` with Claude-style stdin printed an empty line, since
  the sandbox has no accounts.
- Its ~1.1s wall time matches `magpie version`, so that is process start.
Not tried: real accounts, or the line inside a real Claude Code statusLine.
2026-10-14 08:26:04 +08:00
yetone a5d72a095b gateway, gui, cli: a search API's keys take turns, a refused one rests, and each Tavily key shows what it has used (SlouchyQuill)
SlouchyQuill on Discord asked for a Tavily key pool after
dsh-tavily-pool: several keys, each key's quota shown, keys rotated.
Before this, the comma-separated keys (#1477) always started from the
key that last answered, so one key took every search until it was
refused, a refused key kept no rest of its own, and nothing showed what
a key had left.

What changed:
- Turns (internal/gateway/search_keys.go). Searches take turns over the
  keys by default (round robin, a counter per vendor). pick=order (CLI)
  or In order (Settings) always starts from the first key; the pick is
  saved in SearchAPI.Pick.
- Rests. A refused key rests: 401/403 for 10m ("turned away"), 402 for
  1h ("out of credit"), 429 for its Retry-After held to 30s-10m (1m
  without one). 432/433 count as out of credit from Tavily only; from
  any other vendor they rest as a rate limit. A resting key is asked
  after the others, soonest back first, so failover is kept, and it
  wakes when it answers. Rests are keyed by a hash of the key.
- Quota (internal/gateway/search_quota.go). Each Tavily key's quota is
  read from GET /usage with that key. The fixture is the documented
  reply from docs.tavily.com. The key's own limit is used when it has
  one; otherwise its plan's plan_limit/plan_usage, which the account's
  keys share. A failed read, or a reply missing those fields, says
  unknown and why, never 0. A read is kept 2m unless asked fresh. A key
  found used up with no pay-as-you-go credit rests 1h; a later read
  with credit wakes it.
- Keys never appear in full. The vendor's error has the key masked
  (tvly-…abcd), and errors name "key N (tvly-…abcd)".
- GUI. Settings › Models › Web search adds a "Keys of <API>" row under
  an API with several keys or with Tavily's: In turn / In order, each
  key masked with what it has used and why it is asked last, and Check
  again. There is an API for it (POST /api/settings/search-quota), and
  13 strings in zh, zh-TW, ja and de.
- CLI. `magpie search` lists the pick and each Tavily key's quota, read
  fresh; `magpie search add … pick=turns|order`.
- Docs. gateway-routing.md has a new section "A search API's keys";
  both READMEs have a line on web search.

What was run:
- go test -tags nogui ./internal/gateway ./internal/provider
  ./internal/cli ./internal/gui: ok. After the last rebase, provider
  and cli again, and gateway -race -run Search.
- New tests: TestReadTavilyUsage, TestSearchKeysTakeTurnsRoundRobin,
  TestSearchKeyRefusedRests, TestSearchRestFor, TestSearchQuotas and
  TestSearchKeyNeverInFull. Each guarantee was broken by hand and its
  tests went red:
  - turns pinned to the first key: RoundRobin and RefusedRests;
  - rests ignored: TestSearchAPIKeysTakeTurns, RefusedRests and
    TestSearchQuotas;
  - key masking removed: NeverInFull;
  - a failed read reported as known: TestSearchQuotas.
- gofmt -l; go vet -tags nogui for darwin, linux and windows on the
  four packages.
- GUI: search-keys.test.cjs covers en, zh, zh-TW, ja and de ×
  Chromium and WebKit × 1100 and 420px: 20/20. Without the new
  .search-keys .val wrap rule, de at 420px fails ("Erneut prüfen" went
  past the window's edge).
  - search-api, search-first, search-instead, search-mcp,
    searcher-pick, settings-search, provider-search, gui-de, gui-ja and
    i18n-keys: 56/56 in each engine.
  - Full suite in Chromium (concurrency 6, load ~40): 4498/4504. The
    files that failed (gateway-key-groups, rest-try-now,
    routing-wb-restricted, text-size, usage-sum-whole) were rerun
    alone. All pass except usage-sum-whole, which fails now and then
    on an origin/main worktree too under the same load (#1864, #2023;
    rest-try-now and routing-wb-restricted are #1905). None of them
    touch search.
- Real Tavily API with two invalid keys: /search returns 401
  {"detail":{"error":"Unauthorized: missing or invalid API key."}},
  which counts as a refusal. Both keys rest 10m as turned away, the
  error names them only masked, and both quotas read "unknown · 401".
  Checked through a test and through the nogui CLI binary in a sandbox
  HOME.

Not tried: a valid key's /usage against the real API. No Tavily key
was at hand, so the quota parsing is checked against the documented
bytes only.
2026-10-14 08:24:03 +08:00
yetone 4fbb75c3a8 gateway: Codex's 507 "exceeded request buffer limit" is asked again and told as a 503, not relayed as it came (#2034, sparrowu93)
sparrowu93's pi, on a ChatGPT account, stopped on
"Codex: 507 Insufficient Storage: exceeded request buffer limit while
retrying upstream". That text is Envoy's (ChatGPT's front): its first
try at the backend failed, and the body was more than it buffers to
try again. It is the same backend failure as #1628's 503 "reset before
headers", which magpie already asks again for without resting anybody,
only for a body the front couldn't retry itself. magpie relayed the 507
as it came; pi's _isRetryableError (pi-coding-agent 0.73.0,
agent-session.js) matches 503 but not 507 or these words, so the turn
just ended.

codexDropped now reads that 507 (by Envoy's words alone, any size, since
the 507 itself says the body was large) the way it reads the large
request's 503: the accounts loop asks the next account and the last one
again, nobody rests, and the agent is told a 503 with Envoy's words and
what may help (/compact, fewer or smaller images). The relayed path
(codexUpstreamOn, Codex's own sign-in) asks again the same way: the two
share edgeMayDrop/edgeSaidDrop. A 507 in other words is relayed as it
came. gateway-routing.md says so.

Run:
- New TestCodexUnbufferedAskedAgain, TestCodexUnbufferedTold503,
  TestCodexUnbufferedRelayed, TestCodexOther507Stays, with the
  reporter's literal Envoy text as the fixture. On the old code the first
  three fail: "status 507, want 200 pong: {...\"message\":\"Codex: 507
  Insufficient Storage: exceeded request buffer limit while retrying
  upstream\"...}" (the reporter's message byte for byte), and
  "507 once: 507 ... tried [acct-1]". With edgeSaidDrop matching every
  507, TestCodexOther507Stays fails. Restored, all pass, with #1628's
  TestCodexReset* tests.
- go test -tags nogui ./internal/gateway/ (sandbox HOME, pinned caches),
  gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  (with and without nogui) on internal/gateway.
Not tried: a real 507 from ChatGPT (it needs the backend to fail a
request over Envoy's buffer, which can't be made to happen on purpose).
2026-10-14 05:37:00 +08:00
yetone ea3ea11729 gateway: an image request to a routing group moves on to the next member when one answers 5xx (#2005, tianxia3111)
/v1/images/generations sent to a routing:"order" group only ever drew on
the member the model resolved to; a 502 from it went straight back to the
caller even though the group had other members that could draw.

draw.go: when the asked model names a group (group/<id>, or a bare id
whose group holds the resolved member), drawingTries lists the members in
planGroup's order and the request moves on with chat's retryable rule
(5xx, 429, auth and quota refusals). A request the caller got wrong
(plain 400) still stops at once. Pause rules and a gateway key's model
holds apply per group as in chat. Drawing still rests no account. The
recent call records the skipped members as Fallback, and the final error
says "(tried first: ...)", as embeddings do.

video.go: /v1/videos had the same single-member path. Its start logic
moved into startVideo, and videosCreate walks the same tries; a member
that can't make videos moves on too.

Run: TestImageGroupMovesOnToTheNextMember and
TestVideoGroupMovesOnToTheNextMember go red (502) with either loop forced
to stop after the first member, and the image test goes red with the
retryable check removed. go test -tags nogui ./... (full suite), gofmt -l,
go vet for darwin, GOOS=linux and GOOS=windows on internal/gateway.
Not tried against the reporter's real providers.
2026-10-14 05:32:31 +08:00
yetone 812ca5a5c6 gateway: a video request's other fields reach a provider's own videos API as sent, so Agnes gets its mode (#1399, shen-joe)
shen-joe's request to a model marked a Video model on an Agnes provider,
{"model":"agnes-cn/agnes-video-2.5-flash","mode":"text","aspect_ratio":"16:9",
"size":"720P","seconds":"10","prompt":"…"}, came back 400 from
api.agnes-ai.cn: "mode 不能为空". remoteVideoBody sent only model, prompt,
seconds, size and the images, so every field a vendor's own videos API
needs beyond OpenAI's was dropped.

readFilming now keeps the request's other fields (JSON, or a multipart
form's text values), and the body for a provider's OpenAI-shaped videos API
or another magpie's carries them as they came, under magpie's model and
prompt. Grok's and Volcengine's bodies are unchanged. Strings in them are
masked as the prompt is (a negative_prompt is the user's text too), and the
answer is unmasked when they were.

Polling stays at GET /v1/videos/{id}: api.agnes-ai.cn answers that route 401
on a bad key where an unknown route is 404 "Invalid URL", so the route
exists; the /agnesapi?video_id= query the reporter used wasn't needed.

TestCustomProviderVideoKeepsTheCallersFields sends the reporter's body and
checks mode, aspect_ratio, size and seconds reach the upstream, then that a
redacted word in negative_prompt and a nested field doesn't. It fails on
the old video.go, and with the masking taken out by hand. go test -run
'Video|Film|Redact' ./internal/gateway passes; gofmt clean; GOOS=linux and
windows go vet -tags nogui pass. Not tried against Agnes itself (no Agnes
account here).
2026-10-14 05:27:14 +08:00
yetoneandBussanQ 3aa22f9d9c gateway: a translated Responses reply keeps the web search that ran, with its query and sources (#2044, BussanQ)
What changed: responsesEncoder.event gets a KSearch case and
renderResponses a Search case. Both emit a completed web_search_call
item (ws_ id, action.type "search", query plus queries, and the
nonempty source URLs in action.sources) through the shared
responsesSearchItem. The stream adds the item, sends
response.web_search_call.completed {item_id, output_index} and
output_item.done, and the same item stays in the terminal response's
output, in order with text, reasoning and client tool calls.

Why: a search magpie ran for a model that can't search (searchRounds),
or one decoded from an upstream Responses or Anthropic reply, reached
the client only as answer text. Anthropic clients already got
server_tool_use / web_search_tool_result; Responses clients (bqAgent)
had no record that a search ran or what it found. No earlier progress
events or url_citation offsets are invented.

From BussanQ's reference commit b1a4e7b, reviewed line by line and
applied onto origin/main. Added on review:
TestResponsesSearchItemReplayed (the item sent back as the next input,
as Codex does, parses and leaves the turn's messages unchanged) and a
docs line saying so.

What was run (sandbox HOME, pinned caches, go1.26.8):
- go test -tags nogui -count=1 ./internal/gateway -run
  'TestResponsesSearch.*|TestWebSearchForAModelThatCannot|
  TestSearchToldAsAnthropics|TestWebSearchAskedOfEachAPI|
  TestAnthropicServerToolLeftOut|TestParallelToolCallIDs|
  TestResponsesStreamToolThenHiddenThinking': ok
- Break check: origin/main's responses.go put back with the new tests:
  TestResponsesSearchResults "search output lost or reordered: got
  [message message function_call]", TestResponsesSearchDecodedResults
  "decoded provider search missing", TestResponsesSearchFollowedByFailure
  "completed search or subsequent error lost", and
  TestWebSearchForAModelThatCannot "delegated search missing from
  Responses output" all FAIL; pass with the change restored.
- go test -tags nogui ./internal/gateway (whole package)
- gofmt -l; go vet -tags nogui for darwin, GOOS=linux, GOOS=windows
Not run: a live provider; the full repository suite.

Co-authored-by: BussanQ <bussanq@gmail.com>
2026-10-14 05:23:58 +08:00
yetone bf25842714 gateway: a provider's own cap on how long a key that keeps failing rests (#2008, Gaudi-XIX)
A key that keeps failing doubles its rest from a minute up to 10 minutes,
and one rate limited again as soon as its rest is over up to 30; both
caps were fixed, so a free key down for hours was asked again every 10
or 30 minutes all the while.

`magpie provider rest-cap <id> 4h` (Provider.RestCap, minutes, at most
MaxQuotaRest, 8 days) sets where both ladders stop for that provider's
keys and accounts (RestCapOr in restAfterMarked's default branch and in
rateRest); `default` gives back the gateway's own. A time the vendor names
still stands over it. Unset, nothing differs. It is kept by the editor's
save, the account copy and normalize.

Run: go test -tags nogui ./internal/provider ./internal/gateway
./internal/cli ./internal/gui (temp HOME). Broken by hand: both ladders
back on the fixed caps fail TestOwnRestCap (rate-long #6: 30m, want 32m);
the GUI keep removed fails TestSaveKeepsQuotaResetAt. Not tried against a
real vendor's outage.
2026-10-14 05:22:40 +08:00
yetone 064cffdbfd gateway: a key out of a daily allowance rests until the time of day it comes back (#2008, Gaudi-XIX)
A free tier's "You've reached today's free-model token quota" says
nothing of when it is back, so it rested 15 minutes (or the provider's
own quota-rest), and was asked again all day. A vendor Retry-After over
an hour was cut to the hour, and that hour then stood over the user's own
longer rest.

- Provider.QuotaResetAt: "08:00" on this computer's clock, or
  "00:00+08:00" on the vendor's. `magpie provider quota-rest <id> until
  08:00` sets it; a number of minutes set after it replaces it, and
  default clears both. normalize drops one that isn't a time of day.
  It is kept by the editor's save and the account copy.
- restAfterMarked's quota branch rests until its next occurrence
  (OwnQuotaRest). A time the vendor names, or a window's end, still
  stands over it; a Retry-After stands unless it was cut to longestWait
  while the user's own rest is longer.
- Defaults are unchanged: nothing set, nothing differs.

Run: go test -tags nogui ./internal/provider ./internal/gateway
./internal/cli ./internal/gui (temp HOME). Broken by hand, each fails:
OwnQuotaRest replaced by QuotaRestFor (TestQuotaRestsUntilTheTimeOfDaySet,
3 asserts), the Retry-After guard removed (the 7200 case), the GUI keep
removed (TestSaveKeepsQuotaResetAt), default not clearing it
(TestQuotaRestUntil). Not tried against a real free-tier vendor.
2026-10-14 05:22:39 +08:00
yetone 77f90fd84f gateway: a plugin whose config hook says searches: true is sent the client's web_search as sent (#2027, yudaleng)
A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api
relay whose quota the plugin reads) had no way to say its upstream runs
the hosted web search tool: searchesItself returned at once for any
signed-in account, letting only Codex and Grok through, so Claude Code's
WebSearch and Codex's web_search always went through magpie's own search.

Now a plugin's config hook can set `searches: true` on its provider, as
it sets `decide` (#1514). The host passes it through
(plugin.Provider.Searches), pluginProvider sets the provider's Searches,
and searchesItself honours it for a plugin's provider only, on Anthropic
or Responses and only where the plugin has a model on that API, the same
rule a custom provider's "Searches the web by itself" has (#359). Another
sign-in's Searches is never read; Codex and Grok are unchanged. As with a
relay, searchRank leaves it out, so magpie never picks it to search for
other models; Settings can name it by hand.

Documented in docs/subsystems/provider-plugins.md and the plugin guide
(site/public/docs plugins.html, en/zh/ja).

Verified:
- TestPluginSaidToSearch (new, gateway, through the real fake plugin on
  bun and New().Handler()): with FAKE_SEARCHES the plugin's upstream gets
  web_search_20250305; without it, it gets no search tool; Chat doesn't
  search and searchRank is -1 either way.
- Broken by hand, each red: search.go reverted, plugins.go reverted,
  host.js reverted (each "searches by itself on Anthropic: false"); with
  the searchesItself assertion disabled and search.go reverted, the wire
  check fails "said to search true, the plugin was sent []".
- TestMovedGrokSearchesItself, TestGrokPluginSearchesItself,
  TestWebSearch* pass.
- go test -tags nogui ./internal/plugin ./internal/provider ok, and
  ./internal/gateway (see the run noted on #2027) under a sandbox HOME
  with pinned caches; gofmt -l clean; GOOS=linux and GOOS=windows
  go vet -tags nogui on the three packages clean.
- Not tried with a real CPA/sub2api plugin.
2026-10-14 05:17:31 +08:00
yetone 0337ce4bc7 factory: Haiku 5.5 and Mistral Large 4, in droid 0.240.0's picker, are offered, and moved users get plugin 0.1.25 (JL on Discord)
JL (Windows, droid 0.240.0, Factory desktop 0.197.1, magpie 0.1.1226,
opencode-factory-auth 0.1.24): droid and Factory desktop offer
claude-haiku-5-5; droid through magpie couldn't pick it.

droid's models are the registry bundled in its npm binary
(@factory/cli-<platform> 0.240.0, bin/droid). Against 0.233.0's registry,
0.240.0 adds claude-haiku-5-5, mistral-large-4 and gpt-6-astra-ultrafast.
The plugin (magpie-community/plugins e4023d9, published as 0.1.25, npm view
checked) now offers Haiku 5.5 (Anthropic Messages, 872000/128000, efforts
low..max) and Mistral Large 4 (chat completions, x-api-provider mistral,
Droid Core, 524288/64000, images). GPT-6 Astra Ultra Fast stays out: droid
offers it only once the user accepts Factory's high-cost terms.

- migrate_factory.go: the mover's min is 0.1.25, so keepMovedCurrent
  updates moved users (JL is on the plugin).
- factory.go: the built-in had the same gap; its table gets the same two
  rows for users who haven't moved.
- factory_pool_rest_test.go: the plugin's Core list, copied from its
  usage, gains Mistral Large 4.
- TestFactoryDroid0240Models is new; its fixture is droid 0.240.0's
  registry bytes (the same as the plugin's models.test.mjs). It fails with
  the Haiku 5.5 row removed.

Run, under a temp HOME: go test -tags nogui ./... with the machine at load
35-190 (other sessions). Every package passed except five that hit the
10m timeout mid-test (agent, gateway, library, plugin, provider, in
tests that don't touch Factory). Rerun with -timeout 40m: provider ok;
gateway still timed out at load ~130 (TestCodexHeardWithinItsIdleTimeout
failed on its timing, unrelated); -run 'Factory|Moved' on gateway ok.
agent, library and plugin were not rerun to the end; this change
doesn't touch them. gofmt -l clean; GOOS=linux and GOOS=windows go vet
-tags nogui on internal/provider and internal/gateway ok.
Not tried against Factory itself (no Factory account here); droid was read,
not run.
2026-10-14 05:11:19 +08:00
youheyu bede73c34d gateway: concurrent tasks of an agent that sends no session id are told apart by their conversation (#2001, CnsMaple)
Task done 通知按 agent+session 分桶,turnState.start 建桶时定死:同一
agent 不带 session 头的多个并发任务共享一个桶,先结束的任务的通知读的
是仍在跑的最长任务的时间(且 going>0 时不发通知)。convOf 生成的
Conv(首个用户轮次的摘要)已存在于 Route 且只在无 session 时填充——
sessionTurnKey 在 Session 为空时用 Conv 兜底,并发任务各归各的桶。
同一 session 的多个请求仍共享一个 turn,等待全部结束、跨度和原来一致。

验证:TestTurnDoneConcurrentTasksByTheirConversation(短任务通知读自己的
一分钟、长任务不受影响各自报自己的跨度)与
TestTurnDoneSameSessionStillOneTurn(同 session 行为不变);未修复基线
前者 FAIL(等了 10s 无通知,因 going>0 被压住)。TestTurnDone* 全组通过。

Root cause and fix by AwadYoo (comment on #2001), landed as their commit.
Reviewed on main: both routes that mark a request as a turn
(gateway.go, codex_backend.go) set Conv, convOf is "" whenever a session
header is present, and begin/end read the key off the same Route, so a
request's begin and end always meet one bucket.

Run (sandbox HOME, pinned caches, rebased on e297a8ab2):
- go test -race -run 'TestTurnDone|TestToolScan' ./internal/gateway: ok
- sessionTurnKey put back alone: TestTurnDoneConcurrentTasksByTheirConversation
  FAILs "the turn's end was never said"; restored: ok
- go test -count=1 -timeout 30m ./internal/gateway: ok (1260s; the default
  10m timed out while five other gateway suites ran on this machine)
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway: ok
Known limit: an agent with no session id whose first user turn changes
mid-task (its own compaction rewriting it) starts a new turn there.
2026-10-14 04:37:07 +08:00
yetone a75de4c21a gateway tests: TestKeptLoginStandsAtItsPlace counts the replies its fake Codex gave, under a lock
The macOS race job of run 38380155723 (5f3a49254) failed with a DATA RACE
at keep_login_as_test.go:22: two handler goroutines of the test's fake
Codex appended to `tried` at once. Logging the fake's requests shows why:
besides the /responses calls the test makes, the gateway reads
/backend-api/wham/usage for each account behind a reply, on a goroutine
of its own, and that read reached the same handler and was also counted.

The handler now records only /responses calls, under a mutex, and the
checks read a copy. The usage read can no longer race the record, nor
land in the list the test compares with "acct-1".

Run: go test -tags nogui -race -count=30 -run TestKeptLoginStandsAtItsPlace
./internal/gateway (ok); go vet; gofmt -l. Not reproduced locally on the
old test (-race -count=60 -cpu 1,4 stayed clean: the usage read rarely
overlaps a reply here); the CI stacks are the evidence.
2026-10-13 18:44:49 +08:00
yetone a19ecdea90 gateway: a relay's data:[DONE] ends the stream, so an agent that hangs up on it is not logged as 499 (#1978)
zhaoyaoyuan's relay ends its Chat stream with `data:[DONE]`, no space
after the colon, which SSE allows. holdWriter.see only knew
"data: [DONE]", so the try never counted as ended, and pi, which stops
reading at [DONE], was logged 499 "the agent canceled the request" for
a reply it had whole (48 of 58 requests through that relay).

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

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

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

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

Not tried: the reporter's relay itself, or the built binary with pi.
2026-10-13 18:16:03 +08:00
yetone 5241de909a gateway: an image URL a caller sends is downloaded only from public addresses
An images request (/v1/images/edits, /v1/images/generations) may name a
reference image by URL. For a model that takes the image as bytes (an
images API's multipart edit, Gemini's own API, Code Assist), magpie
downloaded the URL itself with the gateway's client, to any address and
through any redirect, and sent what came to the vendor as the image.

fetchPicture, the one place a caller's URL is downloaded (all three draw
paths go through it), now uses publicClient (image_fetch_guard.go):
- the host is resolved and every address must be public (publicAddr:
  not loopback, RFC 1918, fc00::/7, link-local incl. 169.254.169.254,
  CGNAT 100.64/10, unspecified, multicast, documentation/reserved
  ranges, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one);
- the request is pinned to the address checked (Host and TLS
  ServerName keep the name), so a name resolving differently later
  changes nothing; a direct dial is checked again in the dialer's
  Control on the address actually connected;
- through a proxy (magpie's, the provider's, the system's) the proxy is
  chosen by the name and sent the pinned address (CONNECT or SOCKS);
  a plain http:// URL through an HTTP proxy is asked for by address in
  Host too, since Go writes the absolute URI from Host;
- redirects (at most 5) go through the same transport; only http(s);
  no keep-alives; the existing 64 MB / stall / 5-minute limits stay;
- what comes back must sniff as image/*, else 400 without the body.

Policy: a request from this computer (local(): loopback, no proxy or
tunnel headers, and not fromBrowser) keeps downloading from anywhere,
since its sender reaches those addresses already and a local agent may
serve images on localhost. Everyone else, a gateway key's holder
included, is held to public addresses. Vendor-returned image URLs
(FetchImage for b64_json, imagemcp, video content) are unchanged: they
are the vendor's, not the caller's. No other gateway path downloads a
caller's URL: chat/Responses/Anthropic/Gemini image URLs are passed on
for the vendor to fetch. Documented in docs/subsystems/gateway-routing.md.

Run:
- go test -race -count=3 -run 'PublicAddr|EditImageURL|PrivateDialer'
- broke by hand, each went red: old client in fetchPicture (all three
  e2e tests), no Unmap (::ffff:100.64.0.1), no pinning (proxy test
  sees the name), no resolve check (redirect to 192.168.1.10 through
  the proxy served), no dialer check, no image sniff, browser allowed
- go test -tags nogui ./internal/gateway/... (full)
- gofmt -l; go vet -tags nogui for darwin, GOOS=linux, GOOS=windows
- not tried: an https:// image through a real HTTP or SOCKS proxy
2026-10-13 18:15:06 +08:00
yetone 6d7b440924 gateway: a request's ms end with its reply, not with what magpie writes down after it (#1939)
bytecode-x's full-suite failures (Millis 3772 for a stream that ended at
~450 ms; Flow 377, so DecodeOf's flow*HeldShare < window told 0/0) came
from after the reply: serve took call.Millis at its very end, after the
answered bookkeeping. answered() saves sticks and servedCandidate's
provider.NoteServed rewrites the last-answer file, both on disk. With
timing stamps added between the last content byte and call.Millis, 12
CPU burners alone gave at most 7 ms of tail (420 samples); with three
dd+sync writers beside them the block between "before served" and
"after served" took 0.7-1.5 s, the whole of the tail, while the stream
itself had ended. A user's busy disk meets the same: a paced reply reads
as one held back and shows no speed, and its duration grows.

- serve keeps `ended`, the time the last try's reply ended (when its Try
  is made), reset at each try; call.Millis is ended-start when a try was
  made, as before otherwise (a lane turn-away). The handed-on records
  of a refused try take try.Millis, the same end.
- decide_group's usage row is timed before servedCandidate, the same
  sibling.
- ttft_test's paced fixture left a leading "~" on its first event (it
  strips it only for i > 0), so those fixtures' first event was no SSE
  event at all (bytecode-x's second point): it now strips it without a
  gap.
- docs/subsystems/gui-shell.md says where a duration ends.

Run: TestSpeedEndsWithTheReply (new: holds sticksSaving for 2 s during a
paced reasoning stream; the request must still take >= 2 s, and its
Millis must not), TestReasoningSpeed*, TestBurstTellsNoSpeed,
TestCodexBackendBurstTellsNoSpeed, TestHiddenReasoning*, TestTTFT*;
full internal/gateway and internal/provider; gofmt -l; go vet darwin,
windows, linux -tags nogui.
Broken by hand: gateway.go's change reverted -> TestSpeedEndsWithTheReply
red ("the reply's ms 2001 count the 2s magpie took saving after it").
Not done: the bookkeeping itself still runs before serve returns, so a
client that waits for the response's end still waits for the disk;
moving those writes off the request path is a separate change. The
decide_group sibling has no test of its own.
2026-10-13 18:11:23 +08:00
yetone af39ee4b5f gateway: a 402 for a usage limit rests the model out of quota, until the window renews (#1979)
Factory answers a Standard pool used up with 402 "You've reached your
weekly standard usage limit (resets in 0h 19min). Switch to Droid Core
...". failure() read every 402 as out of credit, so the whole account
rested a fixed 30 minutes: its Droid Core models (GLM-5.3, the
reporter's fallback) were skipped with it, the "resets in" was ignored,
and renewed() never lifted the rest when the window came back, since it
lifts only failQuota or By=="window" rests (Ziqi-Cui, 09:16Z).

- failure(): a 402 that matches usedUpWords and says nothing of money
  (creditWords, insufficient_quota) is failQuota. A payment 402, an
  empty one, Kiro's monthly count, Command Code's credits stay credit.
- With failQuota the pooled check applies: Factory's Standard windows
  are scoped away from Core (built-in factoryQuota matches; the
  plugin's notModels/models through quotaOfPlugin), so only the model
  rests, and only until its window's end.
- resetsAt also reads "resets in Xd Yh Zmin" (resetsAfter) when no
  windows are known, capped at longestWritten.
- FactoryAllowanceForTest / PluginAllowanceForTest let the gateway test
  build both paths' allowances from their real payloads.

Run: TestFactoryStandardOutLeavesCore (built-in and plugin:factory),
TestPaymentRequiredReadByItsWords, TestResetsInWords; full
internal/gateway (327s) and internal/provider ok; gofmt -l; go vet
darwin, windows, linux -tags nogui.
Broken by hand: the new failure() case removed -> both subtests red
(account rested for credit, GLM resting); resetsAfter returning 0 ->
TestResetsInWords red; quotaOfPlugin's notModels ignored -> plugin
subtest red.
Not tried: a live Factory account; Factory's Droid Core used-up
wording is assumed to read like Standard's.
2026-10-13 18:11:23 +08:00
yetone d46fb1e590 gateway: a tool's strict an upstream refuses is asked again without it, and left out after (#1980)
OpenCode 2 sends "strict": false on every tool through
@ai-sdk/openai-compatible. thonatos's custom provider turned it away with
400 "Unsupported Chat Completions API field: tools[0].function.strict",
which magpie relayed, and OpenCode ended the session. The reporter's
@ai-sdk/openai workaround worked only because magpie's Responses->Chat
translation leaves strict out.

What changed: in passthrough's retry loop, a 400 that names a tool's
strict as unsupported, unknown, unrecognized, not permitted or
extra_forbidden (toolStrictRefusal, strict_refused.go) is asked once more
with strict deleted from Chat tools[].function and Responses tools[]
(namespaces recursed), and marked for that provider and API
(toolStrictRefused, markUnfit). The next request leaves it out before
sending. An upstream that never refused it still gets strict, which the
ChatGPT backend needs (#383, TestResponsesToolStrict unchanged). The fix
is in the gateway, not in what magpie writes to opencode.json: any
client's strict reaches the same refusal.

What was run:
- Real OpenCode 2.0.25 in a sandbox HOME against a gateway built at the
  old code and a fake upstream refusing strict: the reporter's exact
  error ("custom-provider: Unsupported Chat Completions API field:
  tools[0].function.strict", opencode rc=1). With this change: answered.
- TestToolStrictLeftOutWhereRefused with the two recorded OpenCode 2.0.25
  requests (Chat and Responses, 12 tools each): first request carries
  strict, the retry none, the next turn none at once (3 upstream
  requests), another provider still gets strict.
- Broken by hand: without the retry branch both subtests get the 400;
  without the pre-send check, "next turn: 200, asked 4 times".
- TestToolStrictRefusalWordings, with negatives (an invalid schema, an
  invalid type for strict, an unsupported 'store').
- gofmt -l; go vet darwin, linux -tags nogui, windows; go test -tags
  nogui ./internal/gateway -count=1 (ok, 324s).

Not tried: the reporter's actual upstream vendor (not named in the
issue); the Responses refusal wording is assumed to match the Chat one.
A translated request (Chat->Responses) that an upstream refuses for
strict isn't retried by this.
2026-10-13 18:11:22 +08:00
yetone 12ecb6d8e9 gateway: a gateway key held to a budget, models or accounts is told none of this magpie's accounts, only its own limit and routes (#1981)
321sssrt-bit shared magpie on the LAN with a gateway key held to a budget,
and that key still read every account's quota and balance. A held key
(heldKey: a budget, models or accounts) is someone else's to use, so it
now gets 403 with code gateway_key_held (refuseHeld) on
/v1/magpie/quotas, quotas/history, quotas/cards, POST quotas/refresh and
/v1/magpie/concurrency. That holds from loopback as well as the LAN, the
same as usageSummary already did. /v1/magpie/route tells it only the
routes of its own requests. Route.callerKey is set by trace.beginFor at
all five begin sites, so a route begun without it fails closed. It still
reads its own limit at /v1/magpie/limit. Unrestricted keys and the local
owner are unchanged.

Client side (remote magpie): a 403 gateway_key_held drops the cards kept
from before and shows only the key's own card, instead of "isn't shared".
The cache is now keyed by provider and key (remoteCardsID), so a changed
key never shows what the old one was told, and keepRemoteCards keeps a
read only over one asked before it, so a slow pre-held answer can't bring
cards back.

Decided against letting an account-held key see its own accounts' cards:
that would still show the host's account email and balance to the key's
holder.

Run:
- New TestHeldKeyToldNoAccounts covers keys held by budget, models and
  accounts plus one held to nothing, from 127.0.0.1 and 192.168.1.9.
  Every route goes red with the refuseHeld calls or the route filter
  removed by hand.
- New TestRemoteMagpieHeldKeyShowsOnlyItsOwnCard goes red with the
  errKeyHeld mapping removed. TestRemoteMagpieCardsKeptByKey goes red with
  the cache keyed by p.ID alone.
- gofmt -l and go vet (darwin, linux -tags nogui, windows) are clean.
- go test -tags nogui ./internal/gateway ./internal/provider -count=1
  passes in a sandbox HOME.

Not tried: two real machines over the LAN; the tests drive the handler
with LAN remote addresses. An older client shows "isn't shared" (or its
cached cards until they expire) against an updated host until it updates
too.
2026-10-13 17:59:36 +08:00
yetone 42216ea609 gateway, gui: one model out of its pool rests on that model's rows only, not on the account's other models (#1960, WardLu)
An Antigravity account out of its Claude & GPT pool (claude-opus-5.5
refused until Sunday) rests that model alone: the gateway keys the rest
by restID and still sends gemini-3.8-flash, in its own pool, to the
account. Routing's page didn't know a rest could be one model's: it
kept rests by key or account, so the stage marked the account's
gemini-3.8-flash row "quota used up · back at Sun 17:53", and the row
under Accounts and keys said the whole account was out.

- gateway: Rest.Model names the model a rest is for when it rests by
  restID (a pool, a model not served, a paid model beside free ones);
  "" for an account- or key-wide rest.
- routing.js: restModel reads it (or, for a kept request from before,
  the model on the end of Rest.Key). The stage keeps a model's own rest
  by key and model, so only that model's row rests; an answered try
  ends the account's rest and its own model's. Accounts and keys keeps
  an account's model rests apart from its own: the account isn't shown
  as out, a line names the models resting with why and when, and Try
  now lifts those rests. An account resting as a whole is as before.
- docs/subsystems/gateway-routing.md says so.

Run: routing-model-rest.test.cjs (new), Chromium and WebKit, 1100 and
420, en/zh/zh-TW/ja/de, 20/20; with the old routing.js it fails
("old@x.test: gemini-3.8-flash rests with Opus"). All 74 routing/rest
GUI test files in both engines (456 each, 0 fail).
TestPoolRefusalRestsTheModelOnly checks Rest.Model, set and read back.
go test ./internal/gateway ./internal/gui, gofmt -l, go vet
darwin/linux/windows (-tags nogui).
Not tried: the reporter's real Antigravity account in the app.
2026-10-13 17:40:47 +08:00
yetone 113672508a claude: a re-told conversation says whose Claude Code's "[Image: …]" notes are, so a text-only turn isn't read as carrying the history's images (#1751)
arvakme's request from Pi over /v1/chat/completions: a read tool's image in an
earlier turn, then a text-only question. Through the Claude subscription the
model quoted "[Image: source: …-magpie-claude-work-501/<uuid>/images/1.png]"
and said the message had an image attached.

Why: a new run is told the whole conversation in one message, and Claude Code
2.1.296 notes every image block of the message it is given in a note of its
own after the message, so after </current_turn>. Read from its binary: with
the session kept on disk (the shared work folder, where the bridge drops
--no-session-persistence for savedSession) it stores each base64 image to
<tmp>/<session>/images/N.png and the note names the path; with the session
off it still notes any image it scaled down ("[Image: original 3000x2000,
displayed at 2000x1333 …]"). So turning persistence off was not enough. Images
under url sources are not noted.

What changed: when the history has images, the current turn's opening says
the notes after it are the history's (or, when the turn has images too, the
history's first and then the turn's), in currentTurnOpen. A history with no
image is told exactly as before, and the history's own text is unchanged, so
its cached chunks are too. countImages is shared with start's log line.

Run against the real model (owner's Max account, its access token in a
sandbox CLAUDE_CONFIG_DIR, Claude Code 2.1.296 with the bridge's flags and
the stream-json message renderClaudePrompt makes from arvakme's request, a
120x60 red PNG):
- old prompt, session kept (as the bridge runs): sonnet-5-5 2 of 2 said an
  image was attached and quoted the path; opus-5-5 2 of 2 quoted it and
  offered to read the file. Old prompt with a 3000x2000 image and the session
  off: 2 of 2 said attached (the size note).
- new prompt, session kept: sonnet-5-5 3 of 3 "no image attached", the note
  named as the earlier image's; opus-5-5 2 of 2 the same; 3000x2000 history
  image 2 of 2 the same; a new blue image in the turn after the red one in
  the history: 2 of 2 "one image, blue", note 1 the history's, note 2 the
  turn's.
The Anthropic request bodies were also captured from Claude Code against a
local fake API to see where the note lands (a text block after the turn).

TestClaudePromptSaysWhoseImageNotesAre builds arvakme's request through
parseChat; it fails on the old code (historyClose always) and with the mixed
case broken by hand. gofmt, go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows), builds on all three and go test -tags nogui ./internal/gateway/
pass.

Not done: the original report's duplicates (18 image blocks for 10 images
from Codex) are a separate question; Codex desktop itself was not run.
2026-10-13 17:24:46 +08:00
yetone ea1ba22c32 gateway, gui: Codex's composer predictions go where Settings › General says, Off among them (#1970)
pluo's Usage view showed Codex calls of kind composer_predictions at
133k-231k tokens each with no cache read: ChatGPT.app's Codex guesses the
user's next message with a hidden turn on a fork of the thread, on the
thread's own model, reading the whole conversation again each time. It
asks only when the thread's provider is "openai", so through Codex's own
ChatGPT sign-in (and a custom table pointed at magpie). The app's bundle
(fge) asks for {suggestion: string|null} and uses b.suggestion||null.

What changed:
- settings.CodexPredictions: "" as Codex sends it, "off", or a model id
  (provider/model, group/<id>); anything else is refused on load.
- gateway: codexPredictionsTo + codexPrediction, wired beside the
  descriptions at both entrypoints (gateway.go and codex_backend.go).
  Off answers {"suggestion":null} from magpie and sends nothing (the
  title Off path made generic as sentNowhere). A model's answer goes back
  only as the object Codex asked for (predictionJSON: think tags and code
  fences stripped, suggestion trimmed, blank = null). Plain text is never
  taken as a suggestion, since Codex would put it in the user's composer
  as their next message; it gives null and is recorded as a failure
  ("prediction: ...").
- usage: purpose "Prediction" for composer_predictions (purposes.js
  regenerated).
- gui: POST /api/settings/codex-predictions, kept by the general save;
  Settings › General row "Codex composer predictions" (Codex's own / Off /
  magpie's models, the app's picker), hidden in gateway mode; Routing's
  story for the kind says Codex's own switch (Settings › General › Show
  predictions) and magpie's. i18n in zh, zh-TW, ja, de.
- docs: gateway-routing.md's Codex section, reference.md's gateway-mode
  list. site/ docs left for the owner.

What was run:
- go test -tags nogui ./internal/gateway/ (full, -timeout 40m),
  ./internal/gui/ ./internal/settings/ ./internal/usage/: pass.
  New: TestCodexPredictionsSetting (default to ChatGPT, off sent nowhere,
  model routed, plain turn untouched, ledger kinds), TestNoPrediction,
  TestCodexPredictionOnMagpie (/v1/responses and the backend path),
  TestPredictionJSON; gui TestCodexPredictionsSetting.
- Broken by hand, each went red: backend wiring removed; plain text
  accepted as a suggestion; the general save not keeping the setting;
  the Routing story's kind check.
- Playwright codex-predictions.test.cjs: chromium + webkit, 1100 and 420
  wide, en/zh/zh-TW/ja/de (20 pass). routing-kind (with the new kind),
  codex-descriptions, codex-titles, i18n-keys, gateway-mode,
  purpose-filter, routing-purpose-state, settings-general,
  settings-sections, settings-search: pass.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows.

Not tried: the real ChatGPT.app's predictions against magpie (the
feature is gated server-side by /wham/predictions/config and isn't on for
the owner's account); the reply shape is from the app's bundle.
2026-10-13 17:23:00 +08:00
yetone 5b9530b567 agent: Claude Code's model notes name the Codex account magpie goes to first, not the one Codex is signed in to (#1957, parkavenue9639)
With the signed-in ChatGPT account paused for the others ("this
account off, the others on"), the gateway sends codex/<model> to the
first account still on, yet Claude Code's /model list still said
"<signed-in user> · via magpie". The note now names the account that
comes first in the gateway's order: provider.FirstLogin gives
inUseLogin without the allowance-room check (the note is written once,
not per request), so a kept "keep signed in to X" still names the
account at its place, and a paused own account is passed over.

Not changed: magpie still writes openai_base_url for Codex failover
when several accounts are on. That is the failover itself; the
"Only switch Codex's sign-in" tick (#1907, v0.1.1224) already keeps
magpie out of Codex's config for those who don't want it.

Run: TestViaMagpieNamesTheAccountFirstInOrder (new) fails with the
note reverted to a.User and passes with the fix;
TestCodexPausedOwnAccountPassedOver and TestKeptLoginStandsAtItsPlace
also check FirstLogin against the account the gateway served. Full
internal/agent tests, gateway/provider login tests, gofmt -l, go vet
for darwin/linux/windows (-tags nogui).
Not tried: a real Claude Code /model list with two real ChatGPT seats.
2026-10-13 17:02:05 +08:00
yetone 0c2dad1e12 provider: a Codex approval's auto-review is served by an account kept to some models, not refused as every account barred (#1959, parkavenue9639)
With Codex's own model calls going through magpie's account failover
(another ChatGPT account on), Codex's auto-review of an approval
(x-openai-subagent: guardian, model codex-auto-review) became
codex/codex-auto-review and went through perKey. An account with its own
list of models ("only serve these", #474) was struck from it, because
the list is picked from the provider's models and codex-auto-review is
hidden from those (#1460), so no list could hold it. With the signed-in
account paused, every approval got 403 "every account barred". Relayed
as it came (no failover) the same call was a 200.

AccountServes now lets a Codex account serve codex-auto-review whatever
its list says (codexOwnHidden), as freeOnChatGPT already passes it by the
usage windows. A gateway key's own model list (access.Key.Models) is not
changed: that is a restriction the user set on a key they hand out.

Test: TestCodexReviewPassesAnAccountsModelList reproduces the report:
me@ signed in and paused, spare@ on with a list of gpt-6.1-sol and
gpt-5.6-luna, a guardian call on codex-auto-review through Codex's
endpoint. It goes to acct-2 as codex-auto-review; a model the list leaves
out is still 403 and one it names still served. With the
codexOwnHidden check taken out it fails with the reporter's 403
("is set not to be served by any account or key of Codex").

Run: go test -tags nogui ./internal/provider ./internal/gateway (ok),
gofmt -l, go vet for darwin, linux (-tags nogui) and windows.
Not tried: a real ChatGPT account's approval through the failover.
2026-10-13 17:02:05 +08:00
yetone aef0327b61 gateway, provider: comments no longer say magpie spends Claude's usage resets (#1972)
AutoReset and ResetOutcome still named Claude's resets, which 9bf6d4352
took out on purpose (reading or spending one means magpie calling
Anthropic with the account's token). #1972 read them as a place left
for the feature. Comments only; no code changes.

Run: gofmt, go build -tags nogui ./internal/gateway ./internal/provider.
2026-10-13 17:01:26 +08:00
yetone 7d6358ff6b gateway: /v1/models can list each model by its bare id too, for apps moved from another proxy (love1sbug on X)
love1sbug moved from CLIProxyAPI: their clients ask for gpt-5.6-sol, and
magpie's /v1/models gave only codex/gpt-5.6-sol. "Provider in model names"
(36ca5432d, 6fa3109ea, 250bdd5c4) changes labels in agents' lists, never
ids, so no setting changed what the list returned. A bare request already
routed (serve: GroupFor, then Resolve); only the list didn't offer it.

What changed
- settings.BareModelIDs, off by default; Settings › Network and sharing ›
  "Model ids without the provider" (en, zh, zh-TW, ja, de), posted on its
  own to POST /api/settings/bare-ids (the general settings save keeps it).
  Drawn in gateway mode too, where such apps are.
- On, /v1/models (and ?format=text) lists every row it listed before,
  unchanged and first, then one row per bare model id
  (provider.BareEntries): the row of the entry that id reaches, its label
  that one's. GET /v1/models/{id} answers a bare id the same way.
- Which entry is decided by the gateway's own resolution (groupForIn, the
  GroupFor loop now shared; then resolveIn), so the list never offers what
  a request wouldn't reach: a model several providers serve is listed once
  and goes to its found group (found groups on) or the first provider in
  the Providers order (off), exactly as a bare request did before. An id
  already a catalog id isn't listed twice.
- The target must be in the shown list, so a gateway key held to some
  models sees only bare ids that reach them. Never listed for another
  magpie (DrawersHeader), whose remote provider would list each twice, nor
  in Claude Desktop's list.
- No agent file changes: magpie still writes provider/model ids, so the
  switch rewrites nothing and nobody who hasn't turned it on sees a change.
- docs/subsystems/gateway-routing.md: a section and verification lines.

What was run
- go test -tags nogui ./internal/gateway -run TestBareModelIDs: the
  reporter's case (a Codex provider with gpt-5.6-sol listed as
  gpt-5.6-sol, then asked for it on chat, responses and messages against a
  fake ChatGPT backend that saw gpt-5.6-sol; off, the list is byte-equal
  to before) and several providers with found groups on and off, a held
  key, another magpie. Both go red with the listing disabled by hand.
- go test -tags nogui ./internal/gui -run 'TestBareModelIDsSetting|TestSettingsSave'.
- node --test internal/gui/tests/bare-ids.test.cjs (playwright 1.62.0):
  Chromium and WebKit, 420px (gateway mode) and 900px, all five languages,
  20/20; i18n-keys.test.cjs passes.
- gofmt -l clean; go vet ./... (darwin), go vet -tags nogui ./... on
  darwin, GOOS=linux, GOOS=windows clean.
- go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui
  ./internal/settings ./internal/cli ./internal/agent -timeout 40m,
  rebased on origin/main 06ff45fed: all six ok (gateway 533s, agent 460s,
  the machine at load ~130; the default 10m ran out on wall time in an
  earlier run, the test then running 1s in, nothing failed). Before the
  rebase agent's TestFolderVarsAreListed was red on REASONIX_STATE_HOME,
  fixed upstream by 24146c031.
- After the rebase (a conflict with #1914's tiers for every client, kept;
  a bare row carries its source row's tiers): gofmt, vet on all three, and
  bare-ids, i18n-keys, plain-names, gateway-port .test.cjs, 31/31.
- Rebased again on 9b52fb504 (side efforts touched settings, api.go,
  app.js, i18n.js; a doc table conflict, upstream's rows kept): gofmt, go
  vet ./... and -tags nogui on linux and windows, go test ./internal/gui
  ./internal/settings, gateway -run 'TestBareModelIDs|TestModels|
  TestCodexTiers|TestSideEffort', and bare-ids, i18n-keys, side-effort
  .test.cjs 31/31.

Not tried: a real CLIProxyAPI client against a live gateway, or the
reporter's own setup; no CLI command for the switch (Settings only).
2026-10-13 16:55:27 +08:00
yetone 9b52fb504a gateway: Codex's web search on magpie's models answers, no longer 404 (anton on Discord)
anton on Discord (Linux): asked to look something up, Codex called its
web.run tool, which posts to <base_url>/alpha/search, here
http://127.0.0.1:3425/v1/alpha/search. magpie had no such route and
answered 404, and Codex takes any failed web.run as fatal, so the turn
ended.

Why Codex sends it: since 0.143 (#29909) Codex offers web.run to a
provider that sends x-openai-actor-authorization, as magpie's provider
table does, on a model whose catalog entry says use_responses_lite, as a
ChatGPT account's models do in magpie (codexcat copies Codex's own
entry). The request is codex-api's SearchRequest (id, model, input,
commands.search_query/open/click/find..., settings, max_output_tokens)
and the reply is {encrypted_output, output, results}, output being what
the model is shown.

What changed:
- POST /v1/alpha/search and /alpha/search are served (codex_search.go).
- A ChatGPT account's model goes to the ChatGPT backend's
  /backend-api/codex/alpha/search, as the official client sends it: on
  the account's sign-in (codexSign, no SSE Accept), the model bare, the
  body otherwise as it came (through redaction), only Codex's own
  x-openai-*/x-codex-* headers kept (codexHeader: never magpie's token or
  the actor header). Its own paused sign-in is passed over, the key's
  account and model holds kept, and the next account is asked on a
  non-2xx; the backend's answer is relayed as it is.
- Any other model's search_query/image_query (domains as site:) is
  searched by webSearch, as magpie searches for a model that can't. When
  nothing answers, or only open/click/find were asked, the reason goes
  back as a 200 with output, which the model reads, instead of a failure
  that ends the turn. A ChatGPT search that fails on every account falls
  back to the same, saying why.
- On the Codex backend path a magpie model's /alpha/search is served
  the same, never relayed on Codex's own sign-in; one of Codex's own
  models goes through magpie's accounts when its turns would
  (codexAccounts), else is relayed as before.
- docs/subsystems/gateway-routing.md names the route.

What was run (worktree on origin/main, sandbox HOME, private GOCACHE):
- New tests from Codex's own wire fixture (codex-api endpoint/search.rs):
  TestCodexWebRunSearchesOnChatGPTAccount (both paths; acct-1 429 ->
  acct-2, bare model, body kept, no magpie token/actor header, turn
  metadata kept), TestCodexWebRunChatGPTFailsSearchedByMagpie,
  TestCodexWebRunOnOtherModelSearchedByMagpie (no searcher hint, search
  API asked "OpenAI news site:openai.com", open-only, bad JSON 400, and
  a stub ChatGPT backend that fails the test if reached).
- Broken by hand three ways, each red: without the /v1 route (404 as
  anton saw), without the codexBackend case (relayed to the backend on
  Codex's sign-in), without the ChatGPT forward (searched by magpie).
- go test ./internal/gateway/ -timeout 30m, gofmt -l, go vet darwin,
  GOOS=linux go vet -tags nogui, GOOS=windows go vet.

Not tried: the real codex binary against a sandbox magpie, nor a real
ChatGPT account's /alpha/search; the shape is from Codex's source and
its own test fixture.
2026-10-13 16:49:29 +08:00
yetone dc2f0da820 gateway, gui: Image recognition and Web search pick how hard their model thinks (MOMO on Discord)
MOMO asked on Discord, "外置模型能不能提供思考深度选项": the model that
describes images (Image recognition, analyze_image) and the searcher's
model (e.g. Antigravity's Gemini 3 Flash) had no reasoning level of
their own to pick.

Settings › Models now has a chip beside each of those two pickers. It
opens the app's menu (openProtoMenu, no native select) and offers
Default plus only the levels that model has (Efforts, weakest first;
none shown when the model's levels aren't known, or the row is Off).
The pick is saved as settings.visionEffort / searcherEffort, one of
catalog.EffortRank or empty, and is checked on save. prefsKeep carries
both, so saving another setting keeps them.

Default keeps what magpie did before. Image recognition is still asked
at the least level the model has (classifyEffort), and the searcher
still gets no level. A picked level is fitted to the model's levels at
call time (fitEffort), and only these two calls carry it
(side_effort.go):
- askVisionWith sends reasoning_effort. The image cache key includes
  the level, so changing the level reads the image again.
- searchBody puts thinking (disabled for none, else enabled with
  budgetOf's budget) and output_config.effort (except for pre-adaptive
  Claude) on the searcher's Anthropic body. The gateway's translation
  turns that into each vendor's own form: adaptive or between_tools
  for new Claude, reasoning.effort for Responses, and thinkingLevel
  for Gemini 3 on Code Assist / Antigravity.
- A picked level raises max_tokens by its budget (replyRoom), so the
  thinking doesn't eat the reply.
- ownSearch and Kimi's search service are sent no level. A fallback
  searcher is sent the level fitted to its own model.

docs/subsystems/gateway-routing.md: new "How hard a side model thinks".

Tests:
- TestVisionEffortPicked and TestVisionEffortOnAnthropic check the
  vision body.
- TestSearcherEffortPicked checks the searcher body on new Claude, old
  Claude and Responses.
- TestSearcherEffortOnGemini checks the searcher body through
  buildCodeAssist for antigravity.
- TestSideEffortChecked covers settings validation.
- side-effort.test.cjs covers the chips: levels shown, a pick saved,
  Default clears it, toggle and Escape, no scroll, fit in the row and
  the menu inside the window. It runs in Chromium and WebKit at 1100
  and 420, in en/zh/zh-TW/ja/de.

Run:
- go test -tags nogui ./internal/gateway/ (full, -timeout 30m) on
  origin/main 3a9d73c5c + this change: everything passes except
  TestRateLimitIsWaitedOut "an hour away" (1.9s against its 1s bound,
  load ~190). That test passes on freshly fetched origin/main 41972b25f
  alone (-count=10) and in 8 parallel -cpu 1 copies. Filed as #1971.
- go test -tags nogui ./internal/settings/ ./internal/gui/: ok.
- Broken by hand, each goes red:
  - searchBody dropping the effort fails TestSearcherEffortPicked and
    TestSearcherEffortOnGemini;
  - askVisionWith back to classifyEffort fails TestVisionEffortPicked
    and TestVisionEffortOnAnthropic;
  - the settings check removed fails TestSideEffortChecked;
  - prefsKeep without the two fields fails side-effort.test.cjs.
- GUI:
  - side-effort.test.cjs: 10/10.
  - searcher-pick, images-*, vision-mcp, settings-search/sections/
    general, routing-vision-why and i18n-keys: 123/123.
  - 67 more Settings files: 778 pass. text-size "zh, dark ... 150%"
    failed in WebKit under parallel load; it passes 11/11 alone and is
    #1866.
- gofmt -l is clean. go vet passes for darwin, plus GOOS=linux and
  GOOS=windows with -tags nogui, on gateway, settings and gui. go build
  passes.
- Not tried against a real Antigravity or other real account: the
  request shapes are checked against fakes and the gateway's own
  translators.
2026-10-13 16:40:24 +08:00
yetone 08b1a60c03 gateway, gui: a routing group whose classifier fails says so on its card, and the log says why (#1929, versun)
What changed: the gateway keeps, per classifier model, why it couldn't
say the last time it was asked (an error from the request, or an answer
that was no number of the list) and when, until it answers again
(gateway.ClassifierFailure). The first failure, and each one that says
something new, is written to the log once ("routing: the classifier X
couldn't say: ..."). /api/groups sends it as a group's classifierFailed,
and the group's card on Routing shows a line "Classifier failed 3 min
ago: <why>" with an amber dot (no stripe); its title says that until the
classifier answers, no rule with an intent matches and turns reason as
the agent asked. Strings in en, zh, zh-TW, ja and de.

Why: versun's MLX-Serve answered its Clef decision model, asked as a
chat model, with a 400. The only place that said so was each request's
own details; the group's rules with an intent quietly never matched,
which read as the routing working. The preset itself is fixed in the
commit before this one (versun's, cherry-picked).

Run:
- go test: TestClassifierFailureIsKept (gateway: a 400, kept while
  resting, "not a number", cleared by an answer) and
  TestGroupsSayAClassifierThatFailed (gui: only the failing group's JSON
  has classifierFailed). Each went red with its line removed by hand
  (the record in classify(), the fill in groupsState).
- group-classifier-failed.test.cjs: chromium and webkit, en zh zh-TW ja
  de, at 1100 and 420: 20/20; with classifierFailed dropped from the
  fixture's reading in groupRow, 10/10 of one engine red. i18n-keys
  passes.
- go test -tags nogui ./internal/provider ./internal/usage ./internal/cli:
  ok. ./internal/gateway hit the 10m default timeout at load ~150-190
  (other sessions); rerun with a longer timeout before the push, below.
- go test ./internal/gui: TestDockJoinLeadsCommandTab (Command-Tab order
  had kitty in front) and TestMainWindowCorners (measuring killed under
  load) failed; both are desktop-window tests this change doesn't touch.

Not verified: a real MLX-Serve; versun ran his own.
2026-10-13 16:34:59 +08:00
yetone a65f2131dd gateway: a provider's model can be marked a video or image model in its editor (#1399, shen-joe)
shen-joe's relay serves a video model (agnes-video-2.5-flash), but its
/models list doesn't say "kind": "video". magpie only took a base-URL
provider's video models from that field, and its image models from that
field or from the model's name. So the model could never be asked at
/videos. They asked to tag video models, either in Settings or when
adding the provider.

What changed:
- settings.ModelKinds holds "image" or "video" by "<provider>/<model>".
  RenamePerModel carries it along with the other Model* maps.
- provider/modelkind.go:
  - MarksKinds: only a provider with its own base URL can be marked. A
    subscription, another magpie and a decision API can't.
  - ModelKind, KindModels and SetModelKind. A model can be marked if the
    provider serves it, or if its fetched list has it (a video model is
    left out of the chat list).
  - SetModelPrefs takes a "kind" with the model's other prefs.
- gateway:
  - Drawers adds the models marked image and drops the ones marked video.
  - customVideomakers adds the models marked video and drops the ones
    marked image.
  - The 400 for a model that can't make videos now says where to mark it.
- GUI: the model chip's right-click menu gets "Makes: Auto/Image
  model/Video model…" (an app menu, not a native select). The pick is
  staged until Save, and a marked model shows a small image/video tag.
  Strings are in zh, zh-TW, ja and de.
- docs/subsystems/gateway-routing.md describes it.
- settings_keep_test sets ModelKinds, so a Settings-page save is checked
  to keep it (that guard test went red until it did).

Why per model, in the provider's editor: the kind belongs to one model
of one provider, like the per-model API pref already set there.
Settings → Image/Video only pick the default model. This also covers
their "tag it on the provider" alternative.

Not done: Agnes's own video API (polling at /agnesapi?video_id=, the
finished video in "url") isn't OpenAI's GET /videos/{id}. Marking the
model gets the request to its /videos, but the poll won't match until
there's a mode for it. I've asked the reporter for real responses.

Run:
- go test ./internal/provider ./internal/settings ./internal/gui
  ./internal/gateway: ok (gateway 1658s).
- TestCustomProviderVideoTheUserMarks, which goes red with the
  KindModels loop in video.go removed.
- GUI model-kind.test.cjs, 16/16 (en/zh/ja/de, 900/420, Chromium and
  WebKit). It goes red with the menu item removed.
- Sibling GUI tests: model-api-gemini, model-copy-id, model-api-preset,
  model-test-one/as/why, provider-detect-models, provider-typed,
  i18n-keys, gui-ja and gui-de.
- gofmt, plus linux and windows go vet -tags nogui.
- Not tried against Agnes's real API (no key).
2026-10-13 16:33:44 +08:00
yetone f2b0780fa2 gateway: a held rule fails over within the member it chose, and a fallback outside it isn't kept for the turn (#1946, XcodeFish)
A group of coding-fast and coding-quality, its rule sending turns to
coding-quality: when coding-quality's member failed mid-turn the request
went to coding-fast's members before coding-quality's other one, and the
turn then stayed on coding-fast. Within a turn the rule is held, and
when affinity kept a member the rule's order wasn't applied at all
(gateway.go and nestedRules skipped `hit.Held && aff.Kept`), so the
failover order was the kept one, then the parent's own order.

ruleOver (rules.go), used at the group's rule and every nested group's:
- the kept one stays first while it is of the rule's member that goes
  first (the one it names, or a Then's while that is resting); the
  rule's other members follow it, ahead of the group's others;
- one kept outside that member, which took over when it failed, isn't
  held: once a member of the rule's target is out of its rest, the next
  request of the turn goes back to it (Affinity.Why "rule"). While all of
  it rests, the fallback stays. No new option.
docs/subsystems/gateway-routing.md says so.

Run (before the rebase onto origin/main): go test -tags nogui -count=1 ./internal/gateway/: green but for
TestKimiHeldBurstTellsNoSpeed at load average ~139 (passes 3 of 3
alone; filed as #1963, not on this path),
gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway/.
TestHeldRuleFailsOverWithinItsMember fails on the old code (tried
[kq1 kf1], the reporter's order), and with the go-back part disabled by
hand (round 3 kept on f1).

After the rebase: gofmt, both vets, and go test -run
'Rule|Group|Affin|Nested|Stick|Turn|Classif|Decide|Pause' ./internal/gateway/ green.
2026-10-13 16:18:05 +08:00
yetone 32201c6a06 gateway: what GLM leaves between a written tool call and its close is no longer sent on as text (#1945, XcodeFish)
GLM writes calls as text, <tool_call>{json}</tool_call>, and often
leaves stray "]", "}", "}}", `">` or longer runs between the JSON and
the close. hermesCall's json.Decoder stopped at the first whole object
and the tail went to the agent as an answer of its own beside the
call. A heredoc whose quotes the model left unescaped also closed the
object early, and the command went to the agent cut short.

hermesCall now looks at what follows the object: junk (blanks and
}]"'>) and then </tool_call> is taken with the call; other text before
a </tool_call> means the object closed early, so the block is no call
and stays text for the model to write again. A call with no close
followed by prose reads as before. textCallJunk also drops such a tail
after a call's own close.

The same fix for moved users is in the trae plugin 0.2.11
(magpie-community/plugins c3bcb5c).

Tests (textcalls_tail_test.go): TestTextWrittenCallTailDropped (the
issue's tails, and one after the close) and
TestTextWrittenCallCutEarlyNotCalled; both fail on the old code. Ran:
the full gateway package, go vet darwin/linux/windows, gofmt -l.
2026-10-13 16:17:06 +08:00
yetone c8f103fac0 gateway: a conversation too long for the model reaches the agent at once, not retried as a rate limit (#1944, ASD-max)
The ChatGPT backend answers an overflowing Codex request with a 200
stream whose error event and response.failed say
context_length_exceeded. streamStatus read that through quotaWords,
whose "exceeded" matched, so it counted as a 429: the group's patience
asked the same member again 7-8 times and the account was rested,
while the agent never got the error that makes it compact.

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

Tests (overflow_stream_test.go, from the real backend stream, its
safety_identifier redacted):
- TestStreamOverflowNotRateLimit: the overflow events are 400; rate
  limit 429, overload 529, usage limit 429 unchanged.
- TestCodexOverflowInGroupNotAskedAgain: the agent gets
  context_length_exceeded, the member is asked once, no rest.
Both fail on the old code. Ran: go test -tags nogui ./internal/gateway/
(full package, ok), go vet on darwin/linux/windows, gofmt -l.
2026-10-13 16:17:05 +08:00
Ha1baraA11 a75fa9e54a gateway, provider: OpenRouter's image-only models draw on its /images API, not chat (#1116, fixes #1105)
OpenRouter answers a chat request for gpt-image-*, seedream, flux,
qwen-image, grok-imagine and the like with 404 "Use the /api/v1/images
endpoint instead", and viaFor sent every OpenRouter model to chat. Models
catalog.ImagesAPI names now go to OpenRouter's POST /images, with reference
images as input_references (image_url parts) and its media_type and
prompt/completion token usage read back; a 404 there is returned as is
rather than retried on chat. Gemini and gpt-5-image stay on chat. The
provider Test probe asks the same endpoint.

Run: go test -tags nogui ./internal/gateway/ ./internal/provider/
./internal/catalog/, go vet (darwin, linux nogui, windows), gofmt. With
the /images dispatch removed, both new gateway tests go red. The real case
(owner's OpenRouter key, sandbox HOME, a throwaway test not committed):
openai/gpt-image-1-mini at quality low drew one image, 200, usage 12/272,
and with that image as a reference drew again, 200, usage 1035/272. The
request shape matches OpenRouter's openapi.json ImageGenerationRequest.
2026-10-13 16:00:31 +08:00
yetone b515538ad6 gateway: the model list names each model's service tiers for every client, so Cindy offers Fast where it is offered (#1914, tsuixl)
Cindy reads supportsFastMode from a model's service_tiers in /v1/models
(a priority entry), and its import link asks /v1/models with no magpie
header. The models handler gave service_tiers (codexTiers, the tiers
Codex here is offered on each model, #1234) only to a magpie asking with
X-Magpie-Drawers, so Cindy never showed Fast on GPT-6-Astra / GPT-6.1-Sol.
Every client now gets them; a model with no tier says nothing, and the
remote-magpie path is unchanged.

The context ring showing "—" in the same report is not touched: per the
reporter's own reading it is Cindy's Codex runtime wanting native
metadata, which /v1/models already carries as context_window.

Run:
- TestModelsListTiersForEveryClient (new): a relay's gpt-6.1-sol lists
  priority, its glm-5 lists none, on a plain GET /v1/models. Red on the
  old handler ("" for gpt-6.1-sol), green now.
- go test -tags nogui ./internal/gateway on every test in the 39 files
  that GET /v1/models plus every *Tier* and *Fast* test: ok (110s).
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- Not tried in a real Cindy: whether Cindy's Fast then sends
  service_tier priority through its Codex runtime is left to the
  reporter on the next release.
2026-10-13 15:50:19 +08:00
yetone 419ef30219 gateway: Claude Code gets a safety refusal as Anthropic's own, and switches to its fallback model; how many more accounts are asked is a setting (#1925, DD on Discord)
DD on Discord: through magpie, Claude's safety filter refusing a turn never
makes Claude Code move to its fallback model, as it does on Anthropic's API.
magpie asked every other account and group member (#248), then told Claude
Code a 400 "<model> refused this request", which it takes as an API error.

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

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

Run:
- go test -tags nogui ./internal/gateway (full, -timeout 40m: a first run
  hit the 10m default at load ~70 from other sessions), ./internal/gui,
  ./internal/settings; gofmt -l clean; GOOS=linux and windows go vet.
- GUI: refusal-retries-setting (en, zh, zh-TW, ja, de at 1100 and 420) with
  gui-zh-tw, gui-ja, gui-de, i18n-keys and every tab=models suite
  (disabled-models, images-*, loop-guard-setting, member-model-setting,
  search-*, searcher-pick, vision-mcp), chromium and webkit: 176 pass.
- refusal-retries-setting under load (8 runs at once, load ~200): first
  4 of 8 failed at en/ja 420, a press landing on the first save's "Saved"
  note over the row, then WebKit's wheel still moving the view as the
  press was measured. It now reaches each button clear of anything drawn
  over it (reader.cjs reach) and waits for the scroll to rest: 16 of 16.
Broken by hand:
- handBack off: TestRefusalRetriesNoneHandsClaudeCodeTheRefusal,
  ...CountsTheTries, ...Group, ...ClaudeSubscription and
  TestRefusalWithNobodyLeftIsAnError fail (400 "refused this request").
- count ignored: those plus ...CodexStillTold400 fail (the next key answers).
- GUI keep-on-omit dropped: TestSettingsRefusalRetries fails; the GUI test
  fails with All sent as undefined, and with the row not appended.
Not tried: a real Claude account's refusal, or Claude Code's fallback
switch end to end; the refusal shapes are from Claude Code's source and
Anthropic's docs.
2026-10-13 15:06:20 +08:00
geoqiao 3a9d73c5c6 gateway: a plugin's deferred usage is billed with its step, never told as the prompt
The Cursor plugin collects a tool step's late usage event with the
conversation's next step. It used to add it to that step's prompt_tokens,
which agents read as how full their context is: pi saw 366940 tokens
(181270 + 185670) on a 300k window where 185670 were in use, and compacted.
The plugin now reports it apart, as usage.magpie_deferred (yetone/magpie#1053).

The gateway parses the field into Usage.Deferred and adds it only where it
bills: the usage records (6 sites in serve), the OTel attempt span and route
pricing, as a tier before the request's own, so promptCounted still reads the
request's own prompt. What a client is told (Usage.chat, the Anthropic
encoding) stays the request's own. A reply without the field is handled as
before. docs/subsystems/provider-plugins.md describes the field.

Verified: go test -tags nogui ./... (50 packages ok, sandbox HOME, caches
pinned); gofmt; go vet on darwin, linux (nogui) and windows; go build on the
same three. The new tests were broken by hand and each went red: billed()
ignoring Deferred, cUsage dropping the field, routeUsage without the tier,
Usage.add forgetting it, the decoder ignoring a usage with only a deferred
part, the usage records and the OTel span not using billed(). Not tried: a
real Cursor account on this checkout; the plugin side was run against real
Cursor (composer-2.5, forced late events), where the deferred totals matched
the dashboard's events token for token.

Picked from geoqiao/magpie cursor-deferred-usage (595d6384c), as PRs here
are collaborators-only. Rebased over the service-tier logging (#1784),
keeping its TierAsked/TierSent/TierServed beside billed() at the three
usage.Record sites, and Usage's Tier beside Deferred. Run on this tree:
go test -tags nogui -timeout 40m ./internal/gateway and ./internal/provider
(sandbox HOME); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. billed() forced to ignore Deferred: 3 tests and 5 subtests
of deferred_usage_test.go go red.
2026-10-13 14:50:48 +08:00
yetone 320af98581 gateway: an upstream's error in a shape its decoder can't read fails the reply, so Codex tries again (#1933, tensornull)
A translated stream whose upstream said it failed, but not in the shape
its protocol's decoder reads, ended as a completed reply with no output
and zero usage. Codex took that as its turn's end (exit 0, no message)
and never used its stream retry. tensornull's three fixtures, on an
Anthropic provider asked from Codex's Responses:

- {"type":"error","error":"fixture upstream failure"}: decodeAnthropic's
  struct wants an object for error, so the event decoded to nothing,
  while upstreamEnds counted the type "error" as the reply's end.
- Messages events with their type left out (named only by "event:"):
  the decoder read nothing, and upstreamStop's delta.stop_reason still
  marked the reply ended.
- A Responses response.failed from the Anthropic endpoint: upstreamEnds
  took any protocol's last event, and the Anthropic decoder ignores it.

Now:
- replyEnds (upstream.go) reads a reply's end in the protocol it was
  asked in: Anthropic's message_stop, error or a message_delta's
  stop_reason; Responses' response.completed/incomplete/failed or error;
  Gemini's finishReason; Chat's finish_reason. The other two fixtures no
  longer read as whole and end as errEndedShort, a failure the gateway
  and the client retry, like the "ping then EOF" control. It replaces
  upstreamEnds in both the streaming loop (continuation.go) and the
  unstreamed one (gateway.go).
- carriedError: every decoder (Anthropic, Responses, Chat, Code
  Assist/Gemini) that can't decode an event still tells an error it
  carries ({"error":"…"}, type error, response.failed) as KError with
  its words. Siblings found the same way: a Chat upstream's
  {"error":"…"} chunk ended a translated reply as completed; a Responses
  upstream's string error or a response.failed with no error object
  (status failed) did too, read as stop.
- An error event with no message says its type or the event itself,
  never "".

One test's fixture changed with it: TestTranslatedEffortLoggedAsSent
served Chat chunks from its Responses upstream, which the Responses
decoder reads as nothing. It "completed" only because a finish_reason
counted as the end, the same empty success this fixes, so it now fails
with errEndedShort. The case gets a Responses reply (responsesHi).

What a whole reply does is unchanged: a valid Messages text reply, and
Claude's empty end_turn (asked of in the report), still complete on the
first ask (TestWellFormedStreamsStillComplete).

Run: the new tests in stream_error_shape_test.go use the report's bytes
(event: lines included). Against origin/main's code (fix reverted, tests
kept) 8 subtests fail: anthropic error string, error object with no
message, events with no type, responses failure on the messages route,
chat error string, both Responses-upstream cases, and the unstreamed
client; the error-object control and the well-formed ones pass on both.
With the fix all pass. go test -tags nogui -timeout 40m ./internal/gateway (sandbox
HOME, caches pinned); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. tensornull's reproduce.py against a nogui build of this
tree: error-string now ends response.failed "fixture upstream failure"
after 3 gateway attempts, the same as the error-object control (was
response.completed after 1). Not run: the Codex CLI replay; a Responses
client asking a Responses upstream is passed its bytes as they are, so
that pairing is unchanged.
2026-10-13 14:48:49 +08:00
yetone 30869e35a7 usage, gateway: each request's log row says the service tier asked, the one each try was sent at, and the one the vendor said it ran at (#1784, zhenghaowen0967)
What changed
- usage.Record has tier_asked, tier_sent and tier_served, and the CSV gets
  them as its last three columns.
  - tier_asked is the client body's service_tier (Claude's speed fast reads
    "fast").
  - tier_sent is the tier the try's last request actually went out at. It
    is noted in forwardOnce after every rewrite (a fast pick's priority,
    Ultrafast turned to priority on a plan without it, buildResponses
    dropping a tier the host can't take) onto the per-attempt wireAt. So a
    handed-on try's own row has its own tier.
  - tier_served is only what the reply said: service_tier at the top level,
    in response.service_tier, or in an Anthropic usage. It is read by the
    relay sniffer and by both translated readers, and is empty when the
    reply says nothing. It is never filled in from the ask.
- Codex's own relayed sign-in (codex_backend) records the same three.
- /v1/magpie/route: Route.tier (asked), and each Try has tier and
  tierServed. The session route has asked_tier, tier, tier_served and each
  try's tier and tier_served.
- docs/reference.md (CSV columns) and gateway-routing.md describe them.

Why
zhenghaowen0967 asked that a request whose Ultrafast was sent as priority
to an account without it show that in usage, per try, without calling
the served tier confirmed unless the reply says so.

What was run
- TestTierRecordedPerTry. With Pro out, the first try is recorded
  ultrafast, the second priority, and the final record has asked=ultrafast,
  sent=priority and served empty while the fake doesn't echo. With an
  echoing fake, served is what it said ("ultrafast", and "default" when
  none was asked). It also checks the CSV columns, and the Codex relay path
  with priority.
- TestUpstreamTierShapes covers the Chat chunk, Responses
  response.completed, a Responses body, an Anthropic message_start and
  message_delta usage, null, an over-long tier and non-JSON, as well as
  bodyTier per protocol.
- Broke it by hand:
  - with forwardOnce's noteWireTier removed, TestTierRecordedPerTry goes
    red (route tries' tier empty, TierSent empty);
  - with the sniffer's Tier line removed, TestUpstreamTierShapes goes red,
    and so does the Codex relay case of TestTierRecordedPerTry.
- go test -tags nogui ./internal/gateway ./internal/usage ./internal/cli;
  ledger_test's CSV expectations gain the three empty columns.
- gofmt -l; go vet on darwin; GOOS=linux and GOOS=windows go vet -tags
  nogui.

Not done
- The served-tier fixtures are built from the shapes OpenAI and Anthropic
  document, not from saved replies. Whether chatgpt.com's Codex backend
  echoes service_tier wasn't tried against a real account.
- Bridges that don't go through forwardOnce (the Claude subscription,
  Cursor's built-in) leave tier_sent empty.
- There is no price multiplier for priority/ultrafast and no GUI column.
2026-10-13 14:22:53 +08:00