Commit Graph
231 Commits
Author SHA1 Message Date
yetone 7476328901 settings: one longest context for every model (WJaunita45604 on X)
Settings > Models > Routing has a Longest context field (magpie model
context-cap [<size>|off], POST /api/settings/context-cap). It lowers every
model's window to it, so a user need not set each model. A window the user
set on a model, or on its provider with "*", wins and is not capped; a model
whose window is unknown stays unknown.

It is applied where the window is derived, provider.windowIn, so /v1/models,
every agent's catalog, group windows and the compaction thresholds that
follow the window all agree. Codex's own models take it through
CodexNativeWindow, CodexWindow and codexcat.Cap on the list the gateway
serves; the list's ETag carries the cap so Codex asks again. The provider
editor's Listed value stays the vendor's.

Run (mote): provider, codexcat, cli, settings, settingsapi, gateway tests;
GUI context-cap, model-load, settings-places, i18n-keys, settings-general in
chromium and webkit (en, zh); TestCoreScriptBudget; gofmt; vet on darwin,
linux nogui and windows. Broken by hand: windowIn without the cap turns
TestContextCapHoldsEveryModelButTheOnesTheUserSet and TestModelsListContextCap
red.
Not tried: the whole GUI suite (one row added to an existing list, no new API
read on page load), a real Codex reading the capped list, Windows run.
Not covered: Claude Code's own [1m] choice (claudeRunName) and agent/claude.go's
fallback when a ref has no window.
2026-11-11 11:07:57 +08:00
yetone 418bb6c9e1 codex: Show Codex's own models off leaves them out of Codex's own picker (iiiiiimone on X)
The switch (#1642) only narrowed the Agents page's pickers. Codex's own list,
which the gateway hands it beside its sign-in and as the Codex app's list
file, kept every model of the ChatGPT account, also with the Codex provider
switched off. codexMerged now leaves the sign-in's visible models out when the
switch is off (provider.CodexOwnLeftOut); the model Codex is set to, models
magpie serves on a ChatGPT account and hidden jobs stay, and the list's ETag
carries the switch so Codex asks again. Codex has one openai_base_url for every
model, so one it is still set to goes through the gateway to OpenAI on its own
sign-in; a model of it can't be sent direct beside magpie's models.

Run: TestCodexListWithOwnModelsOff, red with the filter turned off (own models
all listed, ETag unchanged); gateway, provider tests at this tree.
Not tried: a real Codex app against the list.
2026-11-11 01:54:05 +08:00
yetone e6f151507f sessions: each session's output speed, a curve of its last two minutes
The owner liked a tweet's token-speed curve and approved a mockup
(claude.ai/artifact/7mrkMKdVi6jA3HA1Z6pRr5). Each Sessions row now
shows its output speed with a small curve; clicking it opens a popover
with the current tok/s, two minutes of seconds, tool gaps, and the
round's average, fastest second and output so far. A row not live
shows "Avg {n} tok/s".

Gateway: a curveMeter (session_speed.go) on the Server counts every
reply's content bytes per agent and session, from liveRow.observe, the
same count the Live view uses, and turns them into tokens with the
learned per-model rate (tokenRates.rate). A model with no rate yet
shows the curve's shape and no number: a guess would be a wrong
number. counted() opens a session's in-flight span, so a second with
nothing in flight is a gap (a tool ran), not a zero. A pause past 2m
starts a new round; 10m of quiet forgets the session; at most 256
sessions. Codex's own sign-in (codex_backend.go) went past serve and
liveRow before; it now has a liveRow too, so its sessions are counted.

GUI: GET /api/speeds, kept out of /api/sessions* so a once-a-second
poll doesn't set off session reading. The page polls only while
Sessions is shown and visible. managedJSON gains keys, so a row
matches a session the gateway saw under another of its keys. The
curve hides below 620px.

Run (mote's sshd resets every connection today, so Linux and Windows):
- Linux (magpie-desktop, wsl-run): gofmt clean; go test -timeout 45m
  ./internal/gateway ./internal/sessions ok except
  TestGroupFailoverTimesEachTry, red once under load, 5/5 green alone
  here and on main (#5948); node --test over every sessions-*.test.cjs
  and i18n-*.test.cjs: 546/549, the reds sessions-export en in both
  engines, the same on origin/main d657e182a alone (#5947), and
  sessions-folder-paging webkit zh, green alone. sessions-speed in
  Chromium and WebKit x en, zh, zh-TW, ja, de (row, popover, live
  update, narrow width, no poll off the page).
- Windows (xiaomi-gpu, win-run), at this head: go vet ./... clean; the
  curve/live/rates/codex tests of ./internal/gateway ok; go test
  ./internal/gui ./internal/sessions ok but 12 tests, every one red the
  same on origin/main 4d95d81ea and filed (#4115, #5928, #4043, #4925,
  #5324; TestAntigravityAppFolder new as #5957). (internal/gui needs gtk4 for cgo, which
  the WSL distro lacks.)
- At the pushed head (on 6886da1ca, which changed core i18n.js and
  gateway.go), Linux: sessions-speed, i18n-keys, i18n-en-no-cjk,
  sessions-row-narrow 22/22; the gateway curve/live/rates/codex/CORS
  tests ok. The Windows run above was at 4d95d81ea.
Broken by hand: with live.go's curves.add skipped, both
TestSessionCurveFromARealStream and TestSessionCurveFromCodexOwnSignIn
went red; green once restored.

Not tried: a real agent session in the built app; macOS (mote down);
darwin vet; the full go and GUI suites (run after the push, reds
filed).
2026-11-10 20:22:17 +08:00
yetone f1996e7e5d gateway: a provider named past its usage cap is not sent on to a group (Anotiaww on X)
Anotiaww on X: magpie on server B asked magpie on server A for
claude/claude-opus-5-5. A's Claude account was past its usage cap (the
trace: "a usage window at 98%, over the account's 98% cap"), and the
Claude provider had no fallback set. The request was answered by a
WorkBuddy member of the user's routing group claude-opus-5.5 (the trace
row marked Fallback), with nothing said. They expect the cap's refusal.

Cause: 44d6dd75d (adorable_piglet, v0.1.3354) made serve plan a capped
provider again with every user-built routing group that has the model
in it (provider.GroupsAfter, groupsAfter) whenever no candidate was
left, so the Codex app, which asks its own model bare and never the
group, reaches the group's APIs. That rule did not look at what the
client asked for: a request naming the provider itself got the same
implicit fallback. Not the cause: the remote/shared path, auto groups
(GroupsAfter leaves them out), or a peer magpie's model mapping; the
peer sent claude/claude-opus-5-5 as written.

Fix: namedProvider(r, call.Model) in serve's groupsAfter arm. A model
asked with its provider in it (call.Model after unprefixed, so a flat
or aliased spelling of one too) is that provider's alone: past the cap
it goes to the provider's own Fallback list (planned before, untouched)
and else gets cappedError's 429 "usage cap reached". A bare model, and
Codex's own model that codexAccounts rewrote to codex/<model> on the
backend path (marked with providerPicked), still go on to the groups as
adorable_piglet asked; so does a turn codexFallBack hands on. CapStop is
unchanged. GroupsAfter's only other caller, codexFallsBack, is the
backend path, where Codex asks bare. Images and embeddings never read
GroupsAfter.

Tests:
- TestNamedProviderCappedRefuses: codex/gpt-5.5 past its 98% cap, a
  group [codex/gpt-5.5, a/m], on /v1/chat/completions, /v1/responses
  and /v1/messages, stream and not: 429 "usage cap reached" and the
  group's API not asked; with a fallback f/m set on the provider, the
  fallback answers (the user's fallback still holds).
- TestPluginCarefulPool: the plugin's model asked bare ("fake-1") still
  goes to the group; named "factory/fake-1" it is the 429.
- TestCappedCodexOwnModelGoesToItsGroup keeps the backend path's bare
  gpt-5.5; its /v1/responses "codex/gpt-5.5" subtest is now the named
  case above, the reverse answer.

Broken by hand (mote-run): the namedProvider guard out of serve:
TestNamedProviderCappedRefuses 6 subtests red (200 "from the group")
and TestPluginCarefulPool red ("named, group, stop off: 200 ... from
kf"). Restored: green.

Run (mote-run, mote at load ~130-165):
- gofmt -l internal empty.
- At the pushed tree, rebased on origin/main 208b89422: go test -count=1 ./internal/gateway -run 'TestNamedProviderCappedRefuses|
  TestCappedCodexOwnModelGoesToItsGroup|TestCappedSubscriptionGivesWayInGroup|
  TestSubscriptionCappedMidConversationGivesWay|TestCodexOneAccount|
  TestPluginCarefulPool|Fallback|Cap|Group': ok (144.6s; 138.9s before the rebase).
- go vet ./internal/gateway ./internal/provider: darwin, GOOS=linux -tags nogui, GOOS=windows: ok.

Rebased again onto 6b92824ff before the push (26 files of usage,
sessions and provider window-hold changes, none of the files here); the
runs above were at 208b89422, the tests run again at the pushed head
after the tag.

Not tried: a real Claude account past a real cap, and a real second
magpie (fakes only). The full suite runs after the tag. No GUI change.
2026-11-10 18:04:25 +08:00
yetoneandggbdpq 1ad9d157fe gateway: a compaction a ChatGPT-account relay refuses as system asks again with the roles as sent (#5067, acui145 on X)
Codex's summary ask to a provider that isn't OpenAI's carries its
developer messages as system ones (forVendor, #2955). A plugin provider
fronting a ChatGPT account (magpie-sub2api -> sub2api -> Codex backend)
is such a provider, and the backend behind it takes developer alone:
every compaction came back "System messages are not allowed", the
sessions that got through fell to the conversation-as-text summary,
and the ones whose refusal came as an error event after a 200 skipped
every retry and were held after three (compactFails).

Now a summary refused "System messages are not allowed" (as passed
through, or as a current sub2api words it), or with a relay's bare
"Upstream request failed" (the reporter's sub2api), as a 4xx or as an
error event in the stream (roleRefused), is asked once more with the
roles as Codex sent them (askAsSent turns off the compaction marker,
whose only reader is forVendor's swap), then as text, then made by
magpie. A summary with no developer message to give back is not asked
the same twice. Every route a compaction reaches a Responses provider
by (CodexPath, Codex's own models through magpie's accounts, the mask
route, a CC Switch table) goes through codexCompact and serve's one
forVendor call, so all of them are covered. #2955's chat-only vendors
take system and are unchanged.

Ported from ggbdpq's patch (fix/5067-compaction-system-messages,
79ec15d26), which matched only the passed-through wording on a 400.
The review added the reporter's own "Upstream request failed", the
error-event shape, the developer gate, lazyre for the words, and the
subsystem page.

Run on mote at this change on 6a253f8af; rebased onto fbc1808f2 (then 15acba534, no gateway change) and the targeted
run repeated on Linux (wsl-run, mote refused ssh): ok.
- TestCodexCompactSystemRefusedAsksAgainDeveloper (5 wordings/shapes)
  and TestCodexCompactSystemRefusedEverywhereNeverHolds: ok.
- Red on origin/main's product files: all 7 subtests fail (400 to Codex,
  502 "so there is no summary", or the text downgrade).
- Red on ggbdpq's patch alone: older sub2api, both in-stream shapes and
  the in-stream never-holds case fail.
- Broken by hand: the developer gate dropped -> the existing
  TestCodexCompactUpstreamFailed400AsksAgainAsText goes red (3 asks).
- go test -tags nogui ./internal/gateway/: queued behind ~/suite.lock on mote at push time (other sessions' suites); the full suite runs after the tag
- gofmt -l clean; go vet darwin, linux -tags nogui, windows: clean.

Not tried: a real sub2api relay of a ChatGPT account; the fakes answer
sub2api's two wordings (writeOpenAIUpstreamClientError and the older
upstream_error) and the backend's {"detail":...}. After an in-stream
"Upstream request failed" serve itself asks the same account again
(15 asks in the fake), unchanged here. The reporter's other 400
(reasoning effort 'none' on gpt-6.1-sol) is a separate path, not
touched.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-10 17:13:15 +08:00
yetone f2b9ec354a gateway: Codex's auto-review goes on where its conversation does when the sign-in is out (riverleaf88 on X)
riverleaf88 on X: with Codex's ChatGPT allowance spent and magpie routing
Codex on to another model, Codex's automatic review still failed.

Codex's guardian (codex-rs guardian-v2 sync_reviewer) asks the same
provider, so magpie's /backend-api/codex/responses, on codex-auto-review
(approval_review_preferred_model) with x-openai-subagent: guardian. On a
spent sign-in codexFallsBack and serve's groupsAfter looked for fallbacks
and routing groups of codex/codex-auto-review, a model no group names, so
the review was handed ChatGPT's 429 while the conversation's turns went
on to the group.

- codexReviewAfter: an auto-review on the codex sign-in takes the model
  its conversation's own turns go on (codexLeads). A codex model brings
  that model's fallbacks and groups (fallbacksOnly on the lead too); a
  magpie model the caller may use (servedSession) is tried itself.
  codexFallsBack and groupsAfter add them.
- codexHolds: once a 429 naming a reset held the account, later turns
  (main turns too) were answered with the held refusal before any
  fallback. The held branch now hands a /responses turn with fallbacks to
  codexFallBack as the first spent turn was.
- docs/subsystems/gateway-routing.md says both.

Run (mote): go test -count=1 -run 'TestCodexReviewSpent|TestCodexHeld|
TestCodexOneAccount|TestCodexSpent|Hold|Held' ./internal/gateway/ ok
71.2s; gofmt -l clean.
New tests red on the old code: TestCodexReviewSpentFollowsTheGroup and
...FollowsMagpieModel (review got 429 usage_limit_reached); the held case
in TestCodexHeldTurnFollowsTheGroup.
Broken by hand: codexReviewAfter returning nil turns
TestCodexReviewSpentFollowsTheGroup, ...FollowsMagpieModel and
TestCodexHeldTurnFollowsTheGroup red; dropping the held-branch fallback
turns TestCodexHeldTurnFollowsTheGroup and ...FollowsTheGroup red.
Not tried: a real exhausted ChatGPT account; guardian-v2's async scorer;
the multi-account pool path past serve's candidate loop is covered only
through the one-account tests.
Also run (mote, at this tree): go vet ./internal/gateway/ for darwin,
GOOS=linux -tags nogui and GOOS=windows: clean. go test -count=1
-timeout 45m ./internal/gateway/: ok 1037.9s (base 2219fdd49).
Rebased on 662546e78 (agentpath change only): go vet ./internal/gateway/
and -run 'TestCodex|Hold|Held|Fallback|Group': ok 289.7s.
2026-11-10 16:43:25 +08:00
yetone add0dadd4f codex: a service tier set in Codex's settings goes on every request of Codex's (JackyFill on X)
JackyFill asked for a choice in Codex's agent settings that rewrites
service_tier: follow the request, force Fast, force Ultra Fast. Codex's
settings on the Agents page now have "Codex service tier", picked from
the app menu: As Codex asks (the default, nothing changes), Standard,
Fast or Ultrafast.

The values are Codex's own request values (codex-rs protocol
config_types.rs ServiceTier, tui service_tier_resolution.rs): Fast is
"priority", Ultra Fast is "ultrafast", and Standard sends no
service_tier. Flex isn't offered: the ChatGPT backend's requests drop
it (codex_request.go).

settings.CodexServiceTier ("", "default", "priority", "ultrafast";
anything else refused) is set through POST
/api/settings/codex-service-tier. codexTiered rewrites the body where
Codex's requests come in, on both ways: codexBackend (Codex signed in,
/backend-api/codex) and the main handler's Codex-on-Responses block,
which a websocket turn goes through too. It applies only when the
request is Codex's (fromCodex or agentOf == codex). Everything after
treats it as Codex's own ask: an account whose list lacks Ultrafast is
put after a mate that has it or sent priority. A bare model (Codex's own
sign-in, whose plan magpie doesn't know) gets ultrafast only where one
of magpie's Codex accounts lists it on the model (UltraModels), else
priority. The body is edited with topMember/withoutTopMember, no full
decode. Fast picks still apply after, unchanged.

Run (mote):
- TestCodexServiceTierSet, TestWithServiceTier: ok. The test signs in a
  Plus and a Pro ChatGPT account against a fake backend whose lists offer
  gpt-6-luna's Ultrafast to Pro only, and checks the tier sent for each
  setting x what Codex asked, through /v1/responses (account:tier tried)
  and on /backend-api/codex for a model with Ultrafast and one without;
  OpenCode's own priority is left alone; "flex" is refused.
- go test -count=1 -timeout 45m ./internal/settings ./internal/provider
  ./internal/gui ./internal/gateway: ok but internal/gui, which was red
  twice: TestCoreScriptBudget (1,535,075 > 1,533,802) and
  TestSettingsSaveKeepsWhatItDoesNotSend (a save of the Settings page
  dropped the tier). Paid for by eight Codex-row comments cut in app.js
  (now 1,533,416), no raise; settingsapi.Apply keeps CodexServiceTier
  as it keeps the other Codex rows. At the pushed head: go test
  ./internal/settingsapi ./internal/settings ./internal/gui ok, the two
  gateway tier tests ok.
- go vet darwin; GOOS=linux -tags nogui; GOOS=windows (gateway,
  provider, settings, gui): clean. gofmt -l: clean.
- GUI, chromium + webkit: codex-service-tier (new, en/zh/zh-TW/ja/de at
  900 and 400px: 20/20), agent-prefs (56/56, Codex's row list updated),
  i18n-keys, i18n-en-no-cjk, settings-search, codex-titles,
  codex-subagent-model, settings-general, codex-sheet-providers,
  click-scroll: all pass; at the pushed head codex-service-tier,
  agent-prefs, i18n-keys, settings-search, codex-titles,
  codex-subagent-model, settings-general, click-scroll: 166/166.

Broken by hand:
- codexTiered returning the body as it came: TestCodexServiceTierSet red
  (17 lines).
- the Ultrafast-to-Fast downgrade for a bare model removed: red on
  gpt-6-sol (sent ultrafast, want priority).
- the GUI posting to the wrong path, and the row left out of Codex's
  AGENT_PREFS: codex-service-tier red in chromium and webkit.
- settingsapi without the CodexServiceTier keep:
  TestSettingsSaveKeepsWhatItDoesNotSend red.

Not tried: a real ChatGPT account's Ultrafast or Fast request with the
setting on (only the fake backend), a real Codex websocket session, and
Windows/Linux runs of the GUI.
2026-11-10 15:24:40 +08:00
yetone 59d9f5c7d9 gateway, redact: compile their 275 package-level regexps on first use, not at every start
magpie is one binary, so every package's init runs on every launch,
including `magpie statusline`, which Claude Code runs on every message.
internal/gateway and internal/redact compiled 275 patterns at init:
3.7 MB + 2.3 MB and ~38k allocations per launch, most of them for
vendors and rules that launch never reaches.

New internal/lazyre: RE holds the source and compiles it through a
sync.Once on first use, with the *regexp.Regexp methods magpie calls
delegating to it (Of wraps one already compiled, for the user's own
privacy rules). A one-off Go AST rewrite turned every regexp.MustCompile
in a package-level var (outside func literals) into lazyre.New; the
struct fields, map and parameter that hold them took the new type. A
bad pattern now panics on first use instead of at start, so
TestAllCompile in gateway and redact compiles every registered one.

Measured on mote (M5 Pro), sandbox HOME with a copy of real accounts,
v0.1.3515 (273b9f5a9) vs this change:
- GODEBUG=inittrace=1: all init 13.0 MB / 106k allocs -> 7.4 MB / 70k;
  gateway 3.68 MB -> 70 KB, redact 2.31 MB -> 261 KB.
- `echo {} | magpie statusline`, /usr/bin/time -l, 3 runs each:
  instructions retired 260-265M -> 212-215M (-18%), peak footprint
  22.1-22.3 MB -> 18.6-19.2 MB.

Run: go vet ./... (mote); GOOS=linux and GOOS=windows go vet of
gateway, redact, lazyre; go test -race ./internal/lazyre (incl. a
bad-pattern test that MustAll panics); go test ./internal/redact (all);
go test ./internal/gateway -run 'TestAllCompile|OtherOff|WorkDir|
WorkPlace|RunNoise': ok. Broken by hand: TestBadPatternPanicsInMustAll
registers `(` and fails if MustAll does not panic.
Not run before the push: the whole internal/gateway package and the
full suite (a full suite of 273b9f5a9 was running on mote).
2026-11-10 12:34:14 +08:00
yetone 9309e28ced plugins: a plugin's provider in front of a vendor's API is that vendor to the gateway (songlairui on X, #5462, #5464)
A plugin whose provider's `api` is on a vendor's preset host (a Mistral
Vibe plugin's https://api.mistral.ai/v1) got none of what magpie does for
that vendor, since its Host() is the plugin's id. An earlier turn's
thinking went to the plugin's fetch as reasoning_content, and Mistral
turned the whole request away (422 extra_forbidden); the plugin had to
rewrite the body itself.

provider.VendorHost and VendorPreset now resolve a plugin's declared `api`
host to the preset that names it (every Chat, Responses and Anthropic base
of every preset and region; local and remote magpie presets excluded, and
an api on loopback, a private address, .local or .localhost names no
vendor). For every other provider, and a moved subscription, they are
Host() and Preset as before. The gateway's vendor checks read them: 38
p.Host() sites, Mistral's, OpenRouter's, DeepSeek's, Kimi's and
DashScope's preset checks. Host() stays the plugin's id where calls are
kept and shown; requests still go only to the plugin's fetch. Search and
the video plan check are unchanged. No community plugin's api is on a
preset host today (checked at plugins 7b52e3fc), so none changes.

Any plugin gets this with no new field; documented in
docs/subsystems/provider-plugins.md and the plugin docs (en, zh, ja).

Run (mote): go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows;
go test -count=1 -timeout 45m ./internal/provider ./internal/plugin
./internal/gateway: ok (provider 209s, plugin 182s, gateway 1002s). gofmt -l clean.
Broken by hand: pluginVendor resolving nothing (the old behaviour) turns
TestPluginVendor red, and TestPluginInFrontOfMistralIsMistral red on both
halves: the translated Claude Code turn is answered Mistral's 422
extra_forbidden, and the relayed Chat request carries reasoning_content.
Not tried: a real Mistral Vibe key through the reporter's plugin; Windows
and Linux runs of the tests (no OS-specific code).
2026-11-10 10:01:59 +08:00
yetone ca5e537ecb usage: traffic over time in Requests' chart, and how fast it flows now (songlairui on X)
songlairui on X asked for the gateway's bandwidth: many LLM calls, base64
images above all, weigh on the network. Each request's row already kept
its bytes up (UpBytes) and down (DownBytes), shown in its details and as
the period's "↑ · ↓" under the Requests card. What was missing was
bandwidth over time and right now.

- The Requests chart's metrics take Traffic: each hour's/day's bytes up and
  down, stacked by model, provider or agent. Its axis is in bytes ("4 MB"),
  its tooltip splits a column into "↑ up · ↓ down", and the ranking's
  values are bytes with the same split under each. A period with none
  says "No traffic counted in this period". A chart point's Part now
  carries up_bytes/down_bytes, from rows (Part.add) and from the request
  page's cells (Part.plus). The cells already kept Totals, so no cache
  version bump is needed.
- While requests are in flight, the Requests card says how fast traffic
  flows now: "↑ 1.0 MB/s · ↓ 40 KB/s", over the last ~3s, read from the
  new GET /api/usage/traffic a second apart. That route reports the
  gateway's running totals (Server.Traffic) and its requests in flight.
  The totals are atomics added where a row's bytes are added (sentUp,
  downCount.Read). So a stream counts as it arrives, nothing is buffered
  or scanned, and the totals and rows count the same bytes once. Polling
  runs only while Usage → Requests is shown and the window is visible.
  The line goes when nothing is in flight and nothing flowed. When another
  magpie serves the gateway, the route answers {} and the page shows no
  rate.

A Codex turn on the Responses WebSocket (7c1dc198d) is in the totals as
its row is: what the socket was written. The HTTP body sentUp counted is
taken back when the transport chooses the socket (toSocket) and given back
if the turn falls to HTTP after all (toHTTP), so the totals equal the sum
of the rows either way (TestTrafficCountsWhatTheSocketSent, kept and
refused).

Not counted, as before: Claude bridge turns (no HTTP to the vendor). A
plugin's row counts the local hop to the plugin host. An upload is counted
when its try is sent, so a large body shows as a burst in the live rate.
docs/subsystems/gateway-sessions.md has a Bandwidth section.

Run (mote; first at this change on da8480326, then again on 16a2dfac9):
- go test -count=1 -run 'Traffic|Socket|UpBytes|Ledger|Series'
  ./internal/gateway ./internal/usage ./internal/gui: ok.
- Broken by hand, each red, then restored: the down tally in downCount,
  the up tally in addUp, Part.plus's bytes, Part.add's bytes, the
  toSocket call (kept socket: traffic 151020, rows 50469) and the toHTTP
  call (refused: traffic 50360, rows 100551).
- gofmt -l clean; go vet -tags production ./..., GOOS=linux and
  GOOS=windows go vet ./...: ok; darwin, linux and windows builds: ok.
- GUI (mote, this tree): i18n-keys, i18n-en-no-cjk, usage-traffic and
  request-archive-usage, 54/54 in Chromium and WebKit (usage-traffic in
  en, zh, zh-TW, ja and de); usage-traffic red with the rate line broken
  by hand. "Traffic" is in i18n.js, not the Usage plugin's: Go says it
  too, and i18n-keys was red with it in the plugin's file.
- internal/cli TestEveryRouteHasACommandOrIsNamed: ok, with GET
  /api/usage/traffic named in notYet (the full run found it red).
- On 16a2dfac9 (the pushed base): gofmt -l internal clean; go test
  -count=1 -run 'Traffic|Socket|UpBytes|Ledger|Series|
  TestEveryRouteHasACommandOrIsNamed|Budget' ./internal/gateway
  ./internal/usage ./internal/gui ./internal/cli ok; i18n-keys and
  usage-traffic 40/40.
- Not finished at the tag, still running on mote: go test ./... -timeout
  45m and the whole GUI suite (under suite.lock), and the whole
  internal/gui, internal/usage and internal/gateway packages with every
  usage* GUI file. What they find is fixed in follow-ups.
2026-11-10 07:37:34 +08:00
yetone 7c1dc198d1 usage: a turn over the Responses WebSocket counts what the socket was sent, and says so
A Codex turn kept on a Responses WebSocket sends only the new items as a
delta, but the row's ↑ was the whole HTTP body magpie built before the
transport ran, so a long conversation read as ~13MB up per turn
(matrix0487 on Discord). overSocket now records what each socket write
carried (wroteSocket) and, when the turn went out on the socket alone,
replaces the HTTP figure with those bytes (sentOnSocket); a turn that fell
back to HTTP keeps the HTTP body and adds any socket write made before the
fallback. errCodexSocketAgain's retry on a new socket counts both writes.

The row remembers that it went over the socket: Record.Socket (json "ws"),
packed as Flags bit 16384 (rowSocket, added to TestRowFlagsApart). The
Requests table's protocol badge says "Responses · WS" and the details'
Protocol line "Responses · WebSocket".

Run on mote at this commit (rebased on origin/main b4a0a2a1a): gofmt -l
clean; GOOS=linux and GOOS=windows go vet of internal/gateway and
internal/usage; go test ./internal/usage ./internal/gui ok; go test
./internal/gateway -run 'Codex|UpBytes|Ledger|Socket' ok; node --test of
every ledger-*, usage-ledger* GUI file and i18n-keys, 502 of 511, both
engines. The reds are filed and untouched by this change: ledger-swipe
webkit (#5223) and usage-ledger's "newest live route needs no
return-to-live button" (#3104, #4078, #4626, #5048).

Broken by hand: without the deferred sentOnSocket,
TestCodexSocketRowCountsWhatTheSocketSent reads 50,360 B for a 253 B
delta; without the Flags set, TestRowKeepsSocket's packed rows lose
Socket.

Not tried: a real Codex Pro account over the socket, and the full suite
(it runs after the tag). There is no "saved by the socket" figure yet,
since PlainBytes isn't packed.

Reported-by: matrix0487 (Discord)
2026-11-10 03:44:19 +08:00
yetone 803d7747e7 gateway: an account rate limited till a time its vendor named is not asked again before it (hsjzg58958 on X)
hsjzg58958 on X: a vendor limited an account for 300 seconds, and magpie
asked it again about every half a second as the agent retried, until the
vendor flagged two accounts.

Cause: a candidate resting on a 429 was still "tried all the same" when
it was the last one left (restLast/probeOne), and the last one left was
never rested at all, so every client retry went upstream. Codex on its
own sign-in is relayed by codexUpstreamOn outside the candidate loop and
had no hold at all.

Fix:
- timedHeld/vendorTimed (fallback.go): when every candidate left rests on
  a 429 whose time the vendor named (Retry-After, anthropic-ratelimit-*-
  reset, x-ratelimit-reset-*, resets_in_seconds/resets_at), none is asked;
  the agent gets 429 with Retry-After = when the first is back. A ChatGPT
  account out of its allowance is answered as the backend's
  usage_limit_reached with its x-codex-* windows (Rest.out/outHeader).
- The last one left now rests too on such a 429 (vendorSaidWhen); a 429
  naming no time rests nobody, as before.
- codexHolds (codex_held.go): Codex's own relayed sign-in is held till the
  vendor's time; its retries are answered locally with the stored body,
  x-codex-* headers and Retry-After. Lifted by restarted() for quota holds.
- Not held: LimitRestOff accounts (the user's setting), auto-reset weeks,
  rests "there" (answered by the vendor's own hold), Codex's API key.

Run:
- New TestRateLimitedKeysHeldUntilTheirReset (4 signals x 1 and 2 keys)
  and TestRateLimitedCodexAccountsHeldUntilTheirReset (3 refusals x 1 and
  2 accounts): red at fc9ce34d8 (each key/account asked on every retry),
  green after.
- Broken by hand: held branch off -> every case red (4 extra hits);
  last-one rest off -> 1-key cases red, Retry-After lost; codexHeld off ->
  1-account Codex cases red.
- mote: go test ./internal/gateway -run 'TestRateLimited|TestAllResting|
  TestQuotaHeld|TestGroupSpent|TestCodex|TestRetryAfter|TestHeldLimit'
  ok; TestCodexLeavingModelCompactsLocally updated (the used-up account is
  now asked once, then held) and ok.
- gofmt -l clean; go vet, GOOS=linux -tags nogui and GOOS=windows go vet
  and build ok.
- mote, whole internal/gateway package at the rebased head 46199a6ae
  (on 80161247a): ok but for TestStrictAffinityPassesTheErrorOn, which
  asserted the bug itself ("resting now, it is still the one asked"). A
  strict conversation's account resting till ChatGPT's named reset now
  gets its own usage-limit 429 from the rest, with nobody asked; updated,
  and with TestRateLimited|TestCodexLeavingModel|TestCodexEveryAccountOut
  ok at this head.
- The full ./... suite was queued behind six other sessions' suites on
  mote's lock and not run before the push; queued again at this head.

Not tried: a real vendor account limited live (no account was rate
limited to test on); Codex API-key relay is not held (OpenAI's platform
headers are Codex's own to read); plugin providers are held only through
the shared candidate loop; a held Codex passthrough body's
resets_in_seconds is stale by the time elapsed (Retry-After is exact).
2026-11-10 00:58:01 +08:00
yetone dae104bfac capre: a length check, not an unrolled repeat, holds nine patterns
Go's regexp unrolls a bounded repeat into that many copies of its
class: [A-Za-z0-9.-]{0,254} (the session terminal's bundle id) was
89kB of program, kept from start to exit, and Codex's item-id refusal
`.{0,1000}?` 88kB. Measured one by one over magpie's 540 package-level
patterns (1.5MB in all), the nine largest bounded ones were ~440kB.

capre.MustCompile(expr, max) is the pattern with * or +, matching only
a string of max characters at most (rune count, so the (?i) Kelvin
sign and invalid bytes count as the regexp counted them). The nine:
settings' bundle id, library's name and agent id (now name@wsl:distro
cut in two), Anthropic tool names, the trace page's name and find,
access's MCP server, OpenClaw's profile and Codex's provider id. The
item-id refusal is a function: the tail within 1000 characters of a
head.

Run on mote (go1.26.8):
- go test ./internal/capre ./internal/access ./internal/settings
  ./internal/library ./internal/sessions ./internal/agent ./internal/gui
  . : ok; ./internal/gateway -run 'ItemID|Undeclared|ToolName|Refus': ok
- TestCappedMatchesBounded holds each old pattern against its new one
  over 14 units x 19 lengths (0..300, at each bound +-1); with the
  length check taken out it is red (1586 mismatches).
  TestItemIDRefusalAsTheRegexp holds the function against the old
  regexp at 998..1002 characters of x, é, 日, \xff, \n; with 1001 it is
  red. TestCappedIsSmall: 1304 bytes held, 49680 bounded.
- go vet native, GOOS=linux and GOOS=windows over the touched packages
  (gui natively: its Linux build needs cgo); gofmt -l clean.
- Real build, GODEBUG=inittrace=1: magpie's own inits allocate
  11.93MB -> 10.61MB.
- Idle on the real-account copy, 180s heap: regexp programs (sampled)
  4.54MB -> 3.01MB.

Not tried: the full ./... suite; the gateway package beyond the run
above.
2026-11-09 21:47:24 +08:00
yetone 44d6dd75d1 gateway: a subscription's capped or spent turn goes on to the user's group with it in
adorable_piglet on Discord (v0.1.3354): a Codex subscription with a usage
cap set in magpie, first in a routing group with two APIs after it. Past
the cap the Codex app's turns were answered 429 "usage cap reached" and
never reached the APIs; only switching the subscription off in Providers
moved them.

Cause: the Codex app signed in to ChatGPT asks Codex's own model
("gpt-5.5"), never "group/<id>". With a cap on the account,
codexAccounts routes the turn as codex/gpt-5.5, and serve plans the
codex provider and its own Fallback list only. A group that merely has
codex/gpt-5.5 in it was never planned, so with every account held the
answer was cappedError's 429. A request for the group itself was already
routed on past the cap (TestCappedSubscriptionGivesWayInGroup, green on
the old code too). The same gap was on Codex's own sign-in out of its
allowance at OpenAI: codexFallsBack counted the subscription's Fallback
only, so the backend's usage_limit_reached reached Codex.

Fix:
- provider.GroupsAfter(id): the routing groups the user built that have
  the model in them and another member to go on to, in the user's order;
  auto groups, hidden or switched-off ones are none.
- serve: when every account is held at its cap (pl.capped, no candidate
  left, CapStop off), or for a turn codexFallBack handed on, the provider
  is planned again with those groups after its own fallbacks
  (groupsAfter), each group routed as a request to it is. One place, so
  it holds on every protocol (chat, responses, messages, Codex's backend
  path), streaming or not, and for plugin-served subscriptions.
- codexFallsBack counts those groups as fallbacks too.
- Stop at the caps (CapStop) still answers 429 (planPaused returns
  before any fallback, the groups included).

Tests:
- TestCappedCodexOwnModelGoesToItsGroup: backend path with "gpt-5.5" and
  /v1/responses with "codex/gpt-5.5", stream and not; red on origin/main
  3cabaab54 (4 of 4, 429 usage cap reached).
- TestCodexOneAccountSpentGoesToItsGroup: one ChatGPT account, the
  backend's usage_limit_reached, group [codex/gpt-5.5, a/m].
- TestPluginCarefulPool: the fake plugin as Factory through a real
  plugin host, both accounts past their caps, no fallback, group
  [factory/fake-1, spare/m2]: 429 with Stop at the caps on, the API with
  it off.
- TestCappedSubscriptionGivesWayInGroup (11 routings x 4 paths) and
  TestSubscriptionCappedMidConversationGivesWay pin the group/<id> case.

Broken by hand (each through mote-run):
- the serve block off: TestCappedCodexOwnModelGoesToItsGroup 4 of 4 red
  and TestPluginCarefulPool red ("group, stop off: 429").
- GroupsAfter out of codexFallsBack: TestCodexOneAccountSpentGoesToItsGroup
  red (429 usage_limit_reached).
- the handedOnOf arm out of serve: the same test red.
- the !p.CapStop guard out: still green, since planPaused itself returns
  before fallbacks with CapStop; the guard only saves a second plan.

Run at this tree (mote-run, mote under load from other sessions):
- gofmt -l . empty; go vet (darwin, GOOS=windows, GOOS=linux) of
  internal/gateway and internal/provider ok.
- go test -timeout 45m -count=1 ./internal/gateway ./internal/provider:
  provider ok (673s); gateway FAIL (2545s) on TestBurstTellsNoSpeed/
  responses_from_chat_burst alone (5000 tokens in 1091ms read as a
  speed), a timing red under load, ttft untouched here; 3 of 3 green
  alone at this tree, noted on #2719 (the same test's chat_burst).
  That run was at base 3cabaab54.
- Rebased onto origin/main 8a7f77cb7 (9 gateway/provider files changed
  there): gofmt empty, go vet ok, and go test ./internal/gateway -run
  "Cap|Capped|Fallback|TestCodexOneAccount|TestPluginCarefulPool|
  TestSubscriptionCapped" ok (199s) at the pushed tree.

Not tried: a real Codex app and ChatGPT account past a real cap (fakes
only). Not covered: an account that crosses its cap in serve's near-cap
walk (planned with room, held at its turn) still gets the 429 for that
turn; the next turn is planned with it held and goes to the group.
Drawing (images) and embeddings keep their own planning and are
unchanged. No GUI change.
2026-11-09 12:31:00 +08:00
yetone c9d253e4a2 gateway: an agent's compaction is recorded as Compaction, not a plain turn
shangyuan0818 (Discord, v0.1.3354): Claude Code's compactions don't show
in Usage → Requests. Through the gateway they were recorded and counted,
but as ordinary turns (Kind ""), so nothing read as a compaction: the
Compaction purpose listed none, the OTel export skipped them as turns
the transcript has (Claude Code's compaction is skipTranscript, so it
has none), and the reply ended the agent's turn.

The main handler now marks a call compacting() recognises (Claude
Code's summary ask, OpenCode's and the other agents' prompts) as
KindCompact, on every route it serves (messages, chat, responses,
gemini), unless a header already set its kind. The check reads the
facts parse the request already makes (bodyFacts.compact). Codex's
backend route already took the kind from its header; it now uses the
same constant.

Not fixable here: Claude Code used directly (not through magpie) never
writes a compaction's usage to its transcript (only compact_boundary
with token counts before and after), so magpie can't count those.

Run (mote, at this change on 3cabaab54):
- go test -timeout 45m -count=1 ./internal/gateway ./internal/usage ./internal/otlp: ok
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: ok
- gofmt -l internal/: clean
Rebased onto 25eec8f6c (4 commits, 65 lines in internal/gateway, an
images-API change); at the pushed head: go vet ./internal/gateway and
go test ./internal/gateway -run 'Compact' (every compaction test): ok.
Broken by hand: TestCompactionRecordedAsCompaction on the old code is
red in 4 of 5 cases (claude code fork, claude code plain, chat,
responses: recorded as kind "", want "compact"); the plain turn stays "".
Not tried: a real Claude Code /compact through a sandbox gateway, and
Claude Desktop (assumed to be the same, since it runs Claude Code).
2026-11-09 11:37:06 +08:00
yetone 7a56c83e72 gateway: a compaction Copilot sealed stays out of Codex's auto-review
echo_ts (Discord #feedback) runs Codex Desktop's turns on GitHub Copilot
through magpie, with Copilot's native compaction on, and Codex's
auto-review on its built-in codex-auto-review through the ChatGPT
sign-in. The guardian's review carries the conversation's history, so
after the first compaction it carried Copilot's sealed compaction item
too. A request for one of Codex's own models with no magpie Codex
account to route it is relayed to the sign-in as it came, and
codexInputAs keeps any non-magpie1: compaction ("OpenAI's own, for
OpenAI"), so OpenAI was sent Copilot's ciphertext and refused every
review: 400 invalid_encrypted_content "The encrypted content P4ih...bDU
could not be verified". After the next compaction, the new ciphertext.

The siblings: a side call routed through magpie (the auto-review set to
a magpie model, a subagent or a title on another provider's model)
met checkpointReaders, found no writer among its candidates and was
refused with checkpointError, so the review failed there too. A turn or
a /responses/compact on one of Codex's own models relayed to the sign-in
sent the seal to OpenAI to be refused (sealedCompact took a Copilot
writer for the sign-in's own and relayed it).

Now:
- compactionAside names the calls Codex makes beside the conversation
  with its history in them: the guardian (or anything asked on
  codex-auto-review), memory, subagent, title, description, thread
  summary, prediction and suggestion. In serve, when the writer of the
  sealed compaction isn't among such a call's candidates, it goes on
  without the compaction item (withoutCompaction, body and plain);
  instructions, developer/user messages, the turns since and their tool
  calls and outputs stay. The conversation's own turns are still held
  to the writer or refused saying why (#1099), unchanged.
- foreignToSignin: on the relay to Codex's own sign-in (codexBackend), a
  compaction magpie recorded as sealed by a provider other than the
  Codex subscription is never relayed. A side call goes without it; a
  turn or a /responses/compact is answered checkpointError, magpie's
  own explanation, with nothing sent to OpenAI. A seal with no record
  (OpenAI's own, compacted on the sign-in), one the codex provider
  sealed, and one whose provider can't be read are left as before.
No portable plaintext summary exists for a native compaction (only the
writer can read it), so the side call goes without it rather than with
a summary.

Run (on mote, through mote-run, at 9730e0199 + this change):
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/usage/: ok (gateway 926s, usage 35s)
- go test -run 'TestForeignCompaction|TestNativeCompaction|TestCodex'
  ./internal/gateway: ok, again after rebasing onto f1a4b5751
  (which changed internal/gateway: trace.go and others)
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  ./internal/gateway; GOOS=linux go build -tags nogui, GOOS=windows go
  build: clean; gofmt -l internal: clean

Broken by hand: with the three non-test files at 9730e0199,
TestForeignCompactionLeftOutOfAutoReview is red in 4 subtests: the
review through the sign-in gets the reporter's exact 400 ("The
encrypted content P4ih...bDU could not be verified ...
invalid_encrypted_content"), the review and a subagent on another
provider's model are refused "compacted natively by copilot@student",
and a gpt-5.5 turn and its /responses/compact sent Copilot's seal to
OpenAI.

Not tried: the reporter's real Codex Desktop, Copilot or ChatGPT
account; the shape is from their report (Copilot compaction item with
encrypted_content, guardian on codex-auto-review). A Copilot compaction
magpie has no record of (made before compactions.json, or older than
30 days) still goes to the sign-in as before. No full ./... run: mote's
suite lock has had full suites queued for 4h; the change is confined
to internal/gateway.

Reported-by: echo_ts
2026-11-08 22:33:12 +08:00
yetone e215d335a6 gateway: a gateway key can cap its requests at once; the rest wait their turn
young02036 on Discord: a provider can be given a concurrency, so why
can't a gateway key? A key now has an optional MaxConcurrency, from 1
to 1000. Left unset (every key today), nothing changes.

- access: Key and Change get MaxConcurrency, and Identity carries it, the
  issuer's cap included. The concurrency-key action refuses a value
  below 0 or above 1000.
- gateway (key_slots.go): every route that asks a model is held to the
  key's cap, however the request came (loopback, LAN, a Remote magpie, a
  Responses socket's turn). One request too many waits in the key's
  queue in arrival order. It shows as "slot" in Active, and its wait goes
  into the try's Queued. A request whose agent goes away while it waits
  leaves the queue and sends nothing. A stream holds its slot until it
  ends. serve's routes (chat, responses, messages, ollama, gemini, the
  Codex backend) wait inside the try, after keepQueued, so a streaming
  agent gets keepalives while it waits. The other model routes (images,
  embeddings, rerank, audio, videos, search, decisions, native) wait
  before their handler runs. forward and codexUpstreamOn take the slot
  too, so nothing reaches a vendor without one. A key issued under
  another waits for its own slot, then for its issuer's.
  /v1/magpie/concurrency lists each capped key under "keys", and counts
  its waiters in "waiting". A key's limit (key_limit) reports the cap.
  Not held, as a provider's MaxConcurrency doesn't hold them: GET,
  HEAD, OPTIONS, count_tokens, :countTokens and MCP.
  TestKeySlotEveryRoute fails when a route is judged neither held nor
  free.
- cli: magpie gateway-key concurrency <id> [<n>|off]. It refuses 0, a
  negative, over 1000, a fraction, a word, --help or an extra argument
  with its usage.
- gui: the key row gets a badge in the provider concurrency badge's
  style. It opens the app's menu with No limit, 1/2/3/5/10 and Other…,
  and Other… takes a number typed in place. A value that isn't a whole
  number up to 1000 is refused and nothing is sent. Browser and
  read-only keys have no badge. Strings are in en, zh, zh-TW, ja and
  de. An unset badge, which a hover shows, gives way before the masked
  key (flex-shrink 8). Without that, at 420px in en and de, the extra
  badge squeezed the key until its copy button slid under the pointer
  that came to drag the row, and gateway-key-arrange went red.
- docs/subsystems/gateway-routing.md describes it.

Run (on mote, at this tree on origin/main 0f8c3d867; rebased onto 627fd1a3b,
which touches none of these files, and the budgets were run again):
- go test -timeout 45m ./internal/access ./internal/gateway ./internal/cli
  ./internal/gui: access, gateway (839s) and cli ok. gui had one red,
  TestGatewayModeStatsNameTheGatewaySessions, run at 00:40 PST: its
  record an hour back falls on yesterday in a day's first hour. It
  passes from 01:09, so it is unrelated; filed as #5690. The Budget/Size
  tests were run again after the CSS change: ok.
- gofmt -l: clean. go vet for darwin, plus GOOS=linux and GOOS=windows
  (-tags nogui), on those packages: ok.
- GUI (node --test, Chromium and WebKit, 1100 and 420 wide, en, zh,
  zh-TW, ja and de): every file that loads the gateway keys (59) plus
  i18n-keys and i18n-en-no-cjk. The reds left are the same on
  origin/main and already filed: gateway-key-models en (#5233, #4081),
  i18n-keys "a plugin's words are its own" (#5332), phone-connect-menu
  at 420 (#4706, #4707). After the flex-shrink fix:
  gateway-connect-keys, gateway-key-arrange, -concurrency, -mcp,
  -own-rotate and -quotas passed 104/104 in both engines, against
  84/84 on base.
- The tests:
  - TestKeyConcurrency, over LAN with cap 2: 2 of 3 requests reach the
    vendor and the third is shown as "slot". Another key isn't held. A
    cancelled waiter leaves the queue and never reaches the vendor. The
    third goes once one ends, every lane is given back, and its Queued
    is at least 40ms.
  - TestKeyConcurrencyKeepsStreamAlive: a waiting stream gets 200 and
    keepalives.
  - TestKeyConcurrencyEager: on embeddings an issued key waits on its
    parent's lane, a cancelled waiter leaves, never more than 1 runs at
    once, and a GET takes no slot.
- A real `serve` in a sandbox HOME (built from this tree, MAGPIE_ADDR
  127.0.0.1:38612) against a fake slow SSE upstream. Steps: `provider
  add fake url=…`, `gateway-key add`, `gateway-key concurrency <id> 1`,
  then three concurrent keyed streams. /v1/magpie/concurrency showed the
  key at busy 1, waiting 2, limit 1 (two in "slot"). The upstream's
  most at once was 1, and it saw 3 requests one after another (200s at
  1.9s, 3.7s and 5.5s, each with [DONE]). Afterwards "keys" was empty.
  `concurrency <id> 2000` exited 1 with its usage.

Broken by hand (each went red, then restored):
- keySlot returns nil: TestKeyConcurrency ("timed out waiting for c
  queued") and KeepsStreamAlive.
- The issuer's lane skipped: TestKeyConcurrencyEager.
- The eager take skipped: TestKeyConcurrencyEager.
- The CLI's bounds check removed: "accepted [concurrency id 0]".
- The GUI's bounds check removed: gateway-key-concurrency.
- Without the flex-shrink line: gateway-key-arrange chromium/webkit en
  and de 420px.

Not tried / not done:
- Full suite not run at push (neither `go test ./...` nor the whole GUI
  suite).
- Not tried with a real vendor account or a second computer on the LAN.
  The LAN path is covered by TestKeyConcurrency's lanServer.
- The key's badge shows the cap, not live running or waiting counts.
  /v1/magpie/concurrency has those.

Reported-by: young02036 (Discord)
2026-11-08 17:52:09 +08:00
yetone 7d196b6797 gateway: what a proxy says of the caller reaches no vendor, ChatGPT backend or MCP server
Behind Tailscale Serve, a Cloudflare Tunnel or another reverse proxy,
the request magpie gets carries what the proxy says of the caller:
Tailscale-User-Login, -Name and -Profile-Pic (the user's email, name
and picture), True-Client-IP, X-Forwarded-*, Cf-*. The native route
dropped X-Forwarded-*, Forwarded, Cf-*, X-Real-Ip and Via, but not
True-Client-IP or any Tailscale-*, even though lanGuard itself reads
True-Client-IP and Tailscale-User-Login as forwarded
(forwardHeaders). The Codex passthrough and relay to the ChatGPT
backend (copyHeaders) and the MCP proxy dropped none of them.

proxyIdentity names them once: every forwardHeaders entry; any
X-Forwarded-*, Cf-* and Tailscale-*; Forwarded, Via, X-Real-Ip,
True-Client-Ip, X-Client-Ip and X-Original-Forwarded-For.
nativeHeaderDropped, copyHeaders and the MCP proxy's header loop all
skip them. The caller's other headers still go on. Checked and left
as they are: a provider's PassHeaders (names the user chose), Codex's
allow-listed codexHeader, the Codex websocket's headers and passOnCaller.

Tests: TestNativeAnyDropsProxyIdentity (native route, under
MAGPIE_TRUST_PROXY) and TestPassthroughDropsProxyIdentity (Codex relay
through copyHeaders, and /mcp/<server>). Each sends twelve identity
headers and checks that none arrive and that X-Custom still does.

Broken by hand: with native.go, codex_backend.go and mcp.go at their
parent, both tests are red. The native vendor was told True-Client-IP
and the three Tailscale-User-* headers. The ChatGPT backend and the
MCP server were told all twelve.

Run on mote at the pushed head 883690a0b (this commit and the one before,
on origin/main 9a0aab32c): gofmt -l clean, go vet, GOOS=windows go vet
and GOOS=linux -tags nogui go vet all clean. go test ./... -timeout 45m
-count=1: 84 packages ok, including internal/gateway. 3 red, each filed
and none in this change's path:
- TestMainWindowCorners/macOS_26_SDK (gui, macOS 27, #3949)
- TestRenewLoginsKeepsClaudeReading (provider, #5481). It is red 3 of 3
  at the base 49c9491b7 without either commit.
- TestHostEndedEndsWhatItsPluginStarted/own_end (plugin, a 30s wait in
  a full run; passes 3 of 3 alone at this head, #5515)
Rebased then onto origin/main 303a31dd6 (which fixed #5481) and run
again at that tree: gofmt and the three vets clean, and internal/gateway,
internal/provider, internal/plugin and internal/netproxy all ok.
Rebased on 19c45d5d4, which changes gateway.go (kept_error), Codex's
usage_limit_reached, Cursor's mover min, sessions and the GUI; ran
gofmt, go vet ./internal/..., GOOS=windows go vet of gateway and
provider, and go test ./internal/gateway ./internal/provider: both ok.
Rebased on 94d4866b5, which changes only internal/sessions; ran gofmt,
go vet of gateway, provider and sessions, and this change's own tests
(-run Redirect|DropsProxyIdentity|SameOrigin|Keyed): ok.
Rebased on cd77c725d, which changes only internal/provider's check-in;
ran gofmt, go vet of gateway and provider, and this change's own
tests again: ok.
Not tried: a real Tailscale Serve or Cloudflare Tunnel in front of
magpie.
2026-11-06 19:50:19 +08:00
yetoneandMmx233 ff415f39cb gateway: a compaction refused for an input kind it doesn't take is asked again as text (#5181, #5259)
Command Code's /responses takes messages, function calls, their outputs
and reasoning only. A Codex subagent's compaction carries agent_message,
custom_tool_call and compaction_trigger items, and Command Code answered
400 unsupported_input_item (param input). codexCompact didn't count that
as a reason to ask again with the conversation as text, so the 400 went
back to Codex three times and compactFails held the conversation for
5 minutes.

inputKindRefused now asks again as text on unsupported_input_item or
"unknown item type" (Grok's 422) in a 400, 422 or 502 (another magpie in
front wraps it), or in a stream's error / response.failed event. A 401,
403 or 429 with the same words still goes back as it came. itemText
reads an agent_message as the user's turn, so the subagent's task and
follow-ups are in the text summary and in the local one.

No plugin change: the Command Code plugin passes /responses through, and
the fallback covers it direct, through a remote magpie and in a stream.

Run (mote):
- go test -run 'TestCodexCompact|TestCodexCompacts|AgentMessage' ./internal/gateway: ok
- go test -timeout 45m -count=1 ./internal/gateway: ok (809.6s)
- gofmt -l clean; go vet ./internal/gateway native, GOOS=linux -tags
  nogui and GOOS=windows: ok
Broken by hand:
- origin/main's codex_backend.go: every AsksAgainAsText subtest red
  (400 / 502 back to Codex).
- agent_message case removed: the text lacks the subagent's task.
- status guard loosened: the 401/403/429 test red.
Not tried: a real Command Code account (the keys on this machine are
answered 401), the reporters' own sessions; why the compaction reached
/responses rather than chat is not confirmed.

Reported-by: Mmx233 <36563672+Mmx233@users.noreply.github.com>
Reported-by: Edward4226 <Edward4226@users.noreply.github.com>
Reported-by: mahiro233 (Discord)
Co-authored-by: Mmx233 <36563672+Mmx233@users.noreply.github.com>
2026-11-06 16:04:03 +08:00
yetone 8b70b7d976 usage: a request's bytes up and down, and what DeepSeek's image files saved, in Requests
Suggested by @faithleysath (matrix0487 on Discord): the usage ledger now
keeps what each request received back (down_bytes) beside what it sent up
(up_bytes, #4456), and what DeepSeek's image files (#5407) kept out of the
upload (image_files_saved).

Shown in Usage → Requests:
- a row's details: "Sent upstream", "Received" and "Saved by image files",
  each only when it is above 0. A row from before has none of them, not 0;
- under the Requests card, the period's "↑ up · ↓ down", with
  "{n} saved by image files" when there is a saving. Its title gives the
  exact bytes. A period with no counted bytes shows no line.

What is counted:
- Down bytes are counted as the reply body is read, after Go's transport
  has undone gzip, so a gzipped reply counts its plain size, not wire
  bytes. A plugin's row counts the local hop to the plugin host. A 101
  body is not wrapped. Every try counts, so a refused try plus the
  answering one add up (TestLedgerKeepsDownBytes).
- Image files saved, per try: the body before the swap minus the body
  sent, minus the upload bytes this request itself paid (len(b64)/4*3).
  It can be negative on the turn that uploads; the GUI shows only a
  saving above 0. Gaps: an upload that finishes after the wait timeout or
  ctx-done is not subtracted (as with up_bytes); a joined upload flight is
  paid by the request that started it; multipart overhead is approximate.
- packedRow grows by three int32 (152 bytes, still within the test's
  bound), clamped to the int32 range. Totals sum all three.
- settledCountVersion goes 1 → 2, because Totals now count bytes. The
  settled page, heat and effort caches recount once, on the first start
  after the update. The heat key hash includes the new fields.

Run on mote at 84ad780b6 (origin/main, fetched):
- go test ./internal/usage: ok.
- go test ./internal/gateway -run 'TestLedgerKeepsDownBytes|TestDeepSeek|
  TestCodexOwnTurnKeepsUpBytes|TestLedgerKeepsUpBytes|
  TestLedgerCountsATrysSecondAsk': ok.
- go test ./internal/gui: only TestMainWindowCorners/macOS_26_SDK fails,
  as on main (#3949).
- gofmt -l clean; go vet of usage and gateway for darwin, linux (nogui)
  and windows; go build ./...
- New GUI test usage-ledger-bytes.test.cjs: 30 of 30 in Chromium and
  WebKit, en/zh/zh-TW/ja/de, at 1180 and 420 wide. It is red on the old
  page.js.
- usage-*, ledger-*, i18n-* and nav-timeout GUI files: 1231 of 1267.
  Every red is red on a clean 84ad780b6 too: usage-agents-hide (#3414),
  usage-fold (#3415), usage-ledger's "newest live route" (#5048),
  usage-overview-fold, which flakes in other languages on each run
  (#3947), i18n-keys (#5332, and #5426 filed now for "No session ID"),
  and nav-timeout (#5425, filed now).

Broken by hand:
- gotDown not wrapping the body: red, "down 0; the vendors answered
  141/265 bytes" and "the backend answered 105 bytes".
- the saved += removed: red, "saved 0".
- the settled guard red with the bytes fixture until the version raise.

Not tried: a real DeepSeek or other vendor account through a built app,
and a screenshot of the real app. The CSV export does not have the new
columns yet.
2026-11-06 09:17:10 +08:00
yetone 1100ed6494 gateway: an overlong item id goes left out on every kind that may go without one, and under its kind's own prefix on the rest (echo_ts, web_search_call)
echo_ts (Discord, Codex on GitHub Copilot, after 125fd93ec / v0.1.3060):
with native web search on, the turn after a search failed with Copilot's
empty 400 {"error":{"message":"","code":"invalid_request_body"}}. Copilot
gives a web_search_call an id of ~450 characters of Base64 with no ws_ at
the front. plainItemIDs left out only a message's or function_call's
overlong id and bound the rest with boundItemID, which knew a kind prefix
for reasoning, tool_search_call and custom_tool_call only. So the search
call went as a bare 64-hex digest, the shape Copilot refuses (#5266). The
bare digest dates from dd809ea60 (v0.1.2652, #4525/#4527).

The fix covers every kind of input item, not only this one. Which kinds
need an id comes from OpenAI's own SDK, openai-go v3.42.0's
ResponseInputItemUnionParam, where each kind's id is either param.Opt or
required:

- id optional, so an overlong one is left out (idOptional): message
  (typed or not), function_call(_output), custom_tool_call(_output),
  tool_search_call/_output, computer_call_output, shell_call(_output),
  apply_patch_call(_output), mcp_approval_response, additional_tools,
  compaction. Each call and output keeps its call_id, which pairs them.
  Leaving the id out is the case both reporters saw Copilot answer 200.
- id required, so an overlong one is bound under the prefix OpenAI gives
  that kind (itemKindPrefix): reasoning rs_, web_search_call ws_,
  file_search_call fs_, computer_call cu_, image_generation_call ig_,
  code_interpreter_call ci_, mcp_call mcp_, mcp_list_tools mcpl_,
  mcp_approval_request mcpr_. A message bound as msg_+hash was 200 on
  Copilot (isnine, #4525).
- Kinds left as before, keeping their id's own prefix or else a bare
  digest: local_shell_call(_output), item_reference and
  program/program_output. Codex doesn't send these and Copilot isn't known
  to make them. An item_reference's id names a stored item, so hashing it
  can't keep it working anyway.

The 64-character bound (#4525/#4527) stays the same for every kind. An id
of 64 or fewer stays as it was, other characters as "_" (d75ea9282).
custom_tool_call and tool_search_call used to be bound as ctc_/tsc_ and are
now left out. Their schema makes the id optional, and callItemIDs still
re-prefixes a fitting fc_ id.

Tests (internal/gateway/item_ids_test.go):
- TestCopilotTakesItsOwnOpaqueSearchCallID: the reporter's shape, a
  452-character Base64 id with + and / and no prefix on a web_search_call
  between two turns, with tools [web_search], streamed and not, against
  the fake Copilot (opaqueCopilot, which now also checks ws_ on a search
  call). The fake answers the empty 400 word for word.
- TestPlainItemIDsBindsOtherKinds now lists every kind above, each with
  the prefix it gets or "without", and checks that every call kind keeps
  its call_id.
- TestPlainItemIDsBoundItemIDs: the "two ids that begin alike go to two"
  check moved from custom_tool_call to web_search_call (ws_).
- The fake Copilot's setup moved into onOpaqueCopilot, which both Copilot
  tests use.

Run (mote, -tags nogui): -run 'ItemID|CodexRewrites|OpaqueCallID|
OpaqueSearchCallID|BindsOtherKinds' ./internal/gateway: ok, 14 PASS
(including the CodexRewritesAsBefore parity test and its fuzz seed).
Broken by hand (codex_backend.go at origin/main, new tests kept): all
three red. The search-call test failed with Copilot's empty 400 verbatim
("stream true: 400 … invalid_request_body"), BoundItemIDs got msg_ for the
search calls, and BindsOtherKinds got the old ids.
Whole internal/gateway package (go test -tags nogui -timeout 45m): ok (700s).
go vet -tags nogui ./internal/gateway for GOOS darwin, linux and windows:
clean. gofmt -l: nothing.

Not tried: a real Copilot account; this session has none it can use
safely. ws_+hash on Copilot has not been tried live. The evidence is
msg_+hash 200 and bare digest 400 for a message (#4525) and the same 400
in echo_ts's report. The other required kinds' prefixes come from OpenAI's
documented id shapes, and none of them was sent to OpenAI or Copilot.
2026-11-06 01:13:42 +08:00
yetone 125fd93ecd gateway: an overlong message or call id goes left out, and any other is bound under its kind's prefix, which Copilot checks (echo_ts, #5266, #4972)
echo_ts (Discord #feedback, v0.1.3058): after Codex's native compaction, a
tool call on GitHub Copilot failed with an empty 400 "invalid_request_body".
Copilot had handed the call a 452-character opaque id (Base64, + and / in
it, no fc_ prefix). plainItemIDs, on every relay that checks ids
(validatesItemIDs, Copilot among them), sent any id over 64 as
boundItemID's sha256. That kept an id's own prefix only when it had one, so
an opaque id went as a bare 64-hex digest. Copilot refuses that. By hand,
the reporter got 200 with the original id and 200 with the id left out
(call_id kept). isnine found the same thing for a message on #4525/#5266:
left out 200, bare digest 400, msg_+hash 200. The bare digest dates from
dd809ea60 (v0.1.2652, 11-01). Before it, + and / were already turned into
"_" since d75ea9282 (10-10).

The id doesn't go back unchanged, because Copilot doesn't always take its
own long ids: isnine's 420-character ones were refused "string too long …
maximum length 64" (#4525). Leaving the id out was 200 in both reports. So:

- a message (typed or not) or function_call whose id is over 64 goes
  without its id (idOptional). OpenAI's schema makes both optional, and
  the call keeps its call_id, so its output still pairs with it.
- any other kind keeps an id, bound under the prefix its type says
  (rs_ for reasoning, openaiItemPrefix's ctc_/tsc_). Only a kind with no
  known prefix takes one from its id, and a bare digest is left only for an
  unknown kind whose id has no prefix.

Every route takes the same function: the relay's prepare (streaming,
non-streaming, compaction through serve, and Responses over a WebSocket,
whose frames are served as the POST), the ask-again after a refusal, the
Codex relay and the ChatGPT backend. OpenAI, Azure and the ChatGPT backend
issue ids of 64 at most, so an id over that is always another vendor's.
Those upstreams also take a message or call without an id, and they check
an id's kind prefix too ("Expected an ID that begins with 'tsc'"), so the
typed prefix fits them as well.

Tests:
- TestCopilotTakesItsOwnOpaqueCallID: a fake Copilot that takes its own
  ids or none, and answers any other id that is over 64 or lacks its kind's
  prefix with its empty 400, word for word. A 452-character Base64 call id
  goes through streaming and non-streaming, paired by call_id.
- TestPlainItemIDsBindsOtherKinds: another vendor's overlong reasoning,
  tool_search_call, custom_tool_call and unknown-kind ids are still bound to
  64 (rs_, tsc_, ctc_, own prefix), and foreign-character reasoning is still
  left out.
- TestPlainItemIDsBoundItemIDs is changed to match: the overlong message
  id is left out, and the "two ids alike go to two" check is on
  custom_tool_call. The parity reference (wasPlainItemIDs) follows the same
  rule.

Run (mote, -tags nogui): -run 'ItemID|CodexRewrites|OpaqueCallID|
BindsOtherKinds' ./internal/gateway ok, 13 tests listed as PASS. Broken by
hand (old plainItemIDs/boundItemID, new tests kept): both new tests red,
the call test with Copilot's empty 400 verbatim. Whole internal/gateway
package: ok (791s). go vet darwin/linux/windows on internal/gateway:
clean. gofmt -l: nothing.

Not tried: a real Copilot account (both reporters' by-hand results are
the evidence that a left-out id is taken). fc_+hash was not tried live.
A Copilot reasoning item whose own id has + or / is still left out as
another vendor's (as before this change). Its seal goes with it, and the
turn still goes through.
2026-11-06 00:07:18 +08:00
yetone 9a51d644d6 gateway: a compaction's summary late past 4 minutes is magpie's own, sent before Codex gives up (#5275)
hayden4608 on Discord (#5275, asked as urgent): Codex Desktop compacting a
~108k-token conversation on volcengine/deepseek-v4.1-flash. The ~3.1MB
summary request was still being written to Ark at 299s (TryNet Send
~299s, no first byte), Codex gave up at 300s (499), and only then did
magpie log "the reply ended before it was complete; compacting locally".
That local summary went to a request nobody was reading, and
compactFails.done cleared the conversation's count as if it had worked.
Codex sent the same history again, three times, 300s each, and the
conversation never got shorter.

- codexCompact gives the summary compactWithin (4 minutes, a minute
  short of Codex's 300s stream idle timeout, as agentQuietMost). Past it
  the vendor is no longer waited on (the ask's context ends with a
  sideTimedOut cause, so the usage log says "magpie stopped waiting: its
  compaction summary had no answer in 4m0s", not the agent canceling),
  and magpie's own summary (localSummary, saying "no summary came in
  4m0s") goes to Codex while it still waits. Checked after the first
  ask, the ask as plain text, and the as-text ask after tool calls, so
  a late first ask is never followed by another ask of the same body.
- A compaction Codex left before it was answered is counted a failure
  (499, "Codex left before the summary reached it") and nothing is
  written; done() is no longer called for it. After compactFailsMost in
  a row, the next is held with a 400 at once instead of another 300s.

Why the upload was slow: not shown to be magpie's. From here a 3.1MB
whitespace-padded chat request to ark.cn-beijing.volces.com/api/v3 was
read whole in ~1.5s by curl over HTTP/2 and HTTP/1.1, and Go's client
with vendorTransport's settings (HTTP/2, ping health) wrote it in 0.89s
(HTTP/1.1 0.17s) from mote. The reporter's ~10KB/s, and their own 4MiB
control not finishing in 40s by any route, point at the uplink or the
Shadowrocket TUN in their path. Not tried through a TUN.

Run (mote): TestCodexCompactLateSummaryCompactsLocallyInTime and
TestCodexCompactLeftBeforeAnsweredStillCounts green with the fix;
both red on the old code (the first: no answer before the client's 10s; the
second: a completed compaction written to a Codex that left, and the next
not held). go test -run Compact ./internal/gateway ok; go vet of
internal/gateway for darwin, linux and windows ok; gofmt clean.
Full suite: run after the push (go test -timeout 45m ./... on mote, log
teed), result on #5275.

Not tried: a real Codex Desktop session against a slow uplink; a
reporter-side stream_idle_timeout_ms shorter than 4 minutes (then Codex
still leaves first, and the count holds the conversation after 3).
2026-11-05 01:26:12 +08:00
yetone 34116ec012 gateway: Codex signed in to one account lists another account's models
bigfisheatsmall on X: Codex was kept signed in to ChatGPT account A, on
the Free plan. Account B (Team) was the only account on in magpie. dsh
listed B's models and Codex didn't. codexMerged added CodexListed(),
which leaves out every ChatGPT account's own models because it assumes
the backend lists them. But the backend list is fetched with Codex's own
sign-in (A, Free), so B's plan-only models were listed nowhere. Routing
already sent codex/<model> to B (codexAccounts).

- provider.CodexListedBeside(backend) lists an account's own model by
  magpie's id (codex/<slug>) when the sign-in's backend list lacks it.
  codexMerged uses it, and FitOwn keeps those entries.
- spawnChoices (spawn_agent's models) had the same gap. It now uses the
  same rule with the slugs in Codex's models cache.
- buildCodexListTag covers the accounts' own models, so another account
  gaining or losing one has Codex ask for the list again. Every Codex
  asks once after the update.
- TestSyncCatalogAgesCodexCache built its "current" tag by hand from
  CodexListed(). It now uses provider.CodexListTag(), the tag SyncCatalog
  compares against.

Tests (sandbox HOME, fake backend with per-plan lists):
TestCodexListHasAnotherAccountsModels covers the list, routing of
codex/gpt-6.1-sol to the Pro account, and spawn_agent's choices.
TestCodexListOneAccountNoneTwice checks that a single account gets no
codex/ duplicates.

Run on mote at this tree: go vet (darwin, windows, linux) on gateway,
provider and agent: ok. go test -count=1 on provider, agent and
codexcat: ok. go test -run 'Codex|Spawn' on gateway and gui: ok. Run at
the tree before the sync_test change and the buildCodexListTag tidy: the
full gateway package was ok (1224s). Agent was red only in
TestSyncCatalogAgesCodexCache, fixed above.

Broken by hand: on the old codexMerged, the new test fails with "Codex's
list lacks codex/gpt-6.1-sol: [gpt-6-luna gpt-5.6-terra gpt-5.6-luna]".
With only codex_spawn_models.go reverted, it fails with "spawn_agent's
models lack codex/gpt-6.1-sol".

Not tried: real accounts or a real Codex. Not a full go test ./... run.
Not tried: models the backend marks hidden. A Codex here for failover
alone (codexOwnOnly) is unchanged.
2026-11-04 22:00:42 +08:00
yetone 1e1068c86c codex: "Same as the lead" holds every subagent to the lead's model (cleverpigo on X)
cleverpigo (Windows, Codex App 26.1027.6604.0) had Codex's lead on
WorkBuddy's DeepSeek-V4.1-Flash, the subagent model on what the GUI called
"Same as the lead", and the Routing page still showed a subagent on
gpt-5.6-sol through Codex's own sign-in.

Cause: that setting, unset, never held a subagent to anything. Since
67c8f562c (mengxiao) a subagent keeps the model its lead names in
spawn_agent (codexFollowTo leaves subagents alone; codexSubagentPick
returns nil with nothing set), and Codex lists its own models first under
spawn_agent's model overrides, so the DeepSeek lead named gpt-5.6-sol.
Codex's side calls use luna, terra or codex-auto-review, not sol, so it
was the subagent, not a side call.

Now:
- "lead" (settings.CodexSubagentLead / provider.CodexSubagentLead) is a
  value of CodexSubagentModel: every Codex subagent goes on the model the
  lead's own turns last went on (codexLeads.lookup), whatever it names.
  The trace says so (SubagentPick.Lead) and Routing tells it as "the
  model its lead is on".
- A lead on one of Codex's own models is followed on the ChatGPT backend
  route only; in serve such a lead leaves the request as asked. With no
  lead turn seen, a subagent goes as asked.
- The GUI's picker offers "Lead's pick" (unset, mengxiao's case, as
  before) and "Same as the lead" (the new value); the texts say which one
  holds the subagents. en, zh, zh-TW, ja and de.
- No prompt text sent to a vendor changes.

Users who had it unset stay on Lead's pick; the label now says what it
does, and they pick Same as the lead to hold their subagents.

Docs: agent-wiring.md (subagent model field), gateway-routing.md
(CodexSubagentModel paragraph).

Ran, on mote through mote-run at this tree (base origin/main 50265256b):
- go test -tags nogui ./internal/gateway (whole package, -timeout 45m): ok
- go test -tags nogui ./internal/provider ./internal/settings
  ./internal/settingsapi: ok; -run Codex ./internal/agent ./internal/gui:
  ok; -run Budget ./internal/gui (TestCoreScriptBudget): ok
- go vet ./..., GOOS=windows go vet ./..., GOOS=linux go vet -tags nogui
  ./... (and -tags nogui darwin/windows): clean; gofmt -l: nothing
- node --test, both engines: codex-subagent-model (now picks Same as the
  lead and back, sheet row, Routing story of a lead-moved subagent, five
  languages), codex-subagents-lead, i18n-keys, routing-request-model,
  routing-sealed-task: pass. routing-story-shrinks is red in WebKit (4
  subtests, "held while under way"), the same alone at origin/main
  50265256b: #3954.

Broken by hand (in mote's copy only):
- lead lookup turned off in codexSubagentPick: both new tests red
  (TestCodexSubagentFollowsTheLeadWhenSet: "ChatGPT was asked for
  [gpt-5.6-sol]", the reporter's case).
- codexBackend's gate back to bare models only:
  TestCodexSubagentFollowsALeadOnCodexsOwnModel red.
- On the old code the tests don't build (no "lead" value), and
  SetCodexSubagentModel refused "lead".

Not tried: a real Codex App/CLI with a DeepSeek lead spawning a subagent,
and nothing on Windows (the change has no OS-specific path). The whole GUI
suite wasn't run: mote had two other sessions' full GUI suites going.
2026-11-03 23:12:33 +08:00
yetone 78667e9b77 gateway: a request in flight shows its model's context window
packinggoods on Discord: Routing's context window card said "the model's
window isn't known" for a request on remote-magpie/claude/claude-opus-5-5
that was still answering, though the remote magpie's list gives that
model's window. The window was put on a route's prompt only when the
request ended (calibrate at the route's end). A live request always
showed it as unknown, on every provider.

Now the window of the model a try goes to is read as the try goes out.
That is windowOf(c.p, c.model), the same call the route's end makes. It
is kept on the route (Route.window, unexported), and the prompt shows it
while the request is under way (livePrompt). This holds whether the
prompt is read before or after the try starts. A fallback to another
model updates it. At the end the answering model's window still comes
first, as before. Codex turns through magpie's Codex backend now work out
Codex's own window (CodexWindow, else models.dev) when the turn begins,
not when it ends, so they show it live too.

Run at this head (rebased on fb1f4856a), on mote:
- go test ./internal/gateway -run 'Window|Prompt|Context|Trace|Codex': ok
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok; gofmt clean
Run before the rebase (base 7d022bdb6; since then main changed only
gateway-key code in internal/gateway):
- go test -count=1 -timeout 45m ./internal/gateway: ok (724s)
- go vet (darwin, linux, windows) ./internal/gateway: ok

Broken by hand: TestLivePromptHasItsWindow, run on the old code, is red in
both subtests ("in flight: prompt &{Window:0 ...}, want the window
1000000", and Codex's 272000). The done route was right on the old code
too.

Not tried: a real remote magpie on another computer. The test serves its
/v1/models window through catalog.SaveLive, as the remote's list does.
2026-11-03 20:49:32 +08:00
JoeyWu-tech b59e4b747f gateway: a conversation on a new account leaves out the old one's seals (#3887)
hheei (#3887): a Codex conversation with a web search in it (OpenAI's
own web_search, a web_search_call in its history) failed on every turn
with "HTTP 400: Codex: Encrypted content could not be decrypted or
parsed. (code: invalid_encrypted_content)" once magpie had moved it to
another ChatGPT account of the same routing group: after its affinity
went cold ("why": "cold", over two hours on), or after the account it
was on was used up or rate limited.

What an account's turn wrote comes back sealed for that account
(encrypted_content): its reasoning, a web search, and with Codex's
output token replay on (codex-rs core/src/client.rs: only for a provider
named "OpenAI", which Codex signed in reaches magpie as) each message
and call. Codex hands it all back on every turn, and between ChatGPT
accounts, or a ChatGPT account and an OpenAI API key, magpie sends it as
it came (forVendor, 2a19245c). The account asked next can't read the
first's seals and says so. serve asked again without the reasoning only
(withoutReasoning), was refused again over the web search, had no
compaction to leave out, and passed the 400 on. What it remembered as
refused for the conversation's later turns (refusedSeals) was reasoning
and compactions only, so each later turn went the same way. The relay of
Codex's own sign-in (withoutUnreadable) left only the reasoning out as
well.

Now such a refusal is asked again without every seal but a compaction's
(withoutSeals): reasoning goes whole, as before, and any other item
keeps all but its encrypted_content (withoutItemSeal, the rest of it
byte for byte). refused records what was taken out for the key or
account that refused, and withoutRefused leaves it out of the
conversation's later requests there up front, reasoning whole and the
rest by its seal alone. What that one sealed itself still goes along,
and a request on the account that sealed what it carries goes as it
came, so a turn that doesn't move keeps OpenAI's cache and replay as
before. A compaction keeps its own step (withoutCompaction after a
second refusal, unless native compaction is on). The relay asks again
the same way after its 400. The retry is serve's, so it holds whatever
moved the conversation: an account used up, rate limited or resting, the
next member of a group, routing's own pick once the affinity went cold;
on the backend path (one of Codex's own models, signed in) and on
/v1/responses (the codex provider's model, a group of it) alike.
gateway-routing.md says so.

A refusal doesn't say whose seal it couldn't read, so the account asked
loses its own seals from an earlier stay in the conversation too, and
they are remembered as refused, as its reasoning already was.

Not changed, each as on main (#3934): a context_compaction
another account sealed stays in through both steps (keepsSeal has it,
compactionKinds doesn't); the relay keeps no record of what was refused,
so each later turn there is refused once and asked again, and a refusal
in its stream reaches Codex as it came; the relay's /responses/compact
isn't asked again; the Routing view still calls such a try "another
account's reasoning" (client.js and its translations).

What was run (tree 326b178e, on origin/main f8cd964a, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- TestForeignSealedItemsMoveToAnotherAccount, new: a conversation
  holding acct-1's sealed reasoning, web search, call and answer moves
  to acct-2 as acct-1 answers 429 or response.failed
  rate_limit_exceeded, signed in, as codex/gpt-5.5 and as group/g,
  acct-2 refusing with a 400 or in its stream (12 cases). acct-2 is
  asked with every seal, refuses, is asked again bare and answers, and
  the next turn asks it bare with its own seals on: ok
- TestForeignSealedItemsAfterAColdSwitch, new: the same conversation
  moved back to acct-1 by its affinity gone cold (Why "cold"), 6 cases:
  ok
- TestForeignSealedItemsRelayedToAnotherSignIn, new: Codex's own sign-in
  relayed as acct-2, the history sealed by acct-1: ok
- TestSealsTakenOutLeaveTheRest, new: the exact bytes withoutSeals and
  withoutRefused leave (a seal first, in the middle and last in its
  item; compactions keeping theirs; reasoning alone taken as
  withoutKinds took it), and nothing taken out for another account or
  conversation: ok
- the three new end-to-end tests with affinity.go, gateway.go,
  codex_backend.go and routing.go as on main (swapped in through go test
  -overlay, the checkout left as committed; the unit test left out, as
  it calls withoutSeals): 21 of 21 red. The 400 cases: "moved on: 400
  {"error":{"code":"invalid_encrypted_content","message":"Codex:
  Encrypted content could not be decrypted or
  parsed.","param":null,"type":"invalid_request_error"}}", and "gone
  cold: 400" with the same; in the stream: "moved on: 200" and "gone
  cold: 200", the response.failed invalid_encrypted_content passed on to
  Codex; the relay: "400 {"error":{"message":"Encrypted content could
  not be decrypted or parsed.", ...
  "code":"invalid_encrypted_content"}}"
- broken by hand, one at a time, each swapped in the same way, beside
  the tests already there for foreign seals, compactions, reasoning and
  output replay (TestForeignSeal*, TestForeignCompaction*,
  TestForeignReasoning*, TestCodexOwnModelAfterAnotherVendor,
  TestCodexSpentMovesToGrokWithSealedReasoning, TestCodexOutputReplay*),
  all green under each but where named:
  - serve's retry taking the reasoning only (withoutKinds(body,
    "reasoning")): TestForeignSealedItemsMoveToAnotherAccount (12 of 12)
    and TestForeignSealedItemsAfterAColdSwitch (6 of 6) red, "moved on:
    400" and "gone cold: 400" with the error as on main
  - the relay's taking the reasoning only:
    TestForeignSealedItemsRelayedToAnotherSignIn red, "400
    {"error":{"message":"Encrypted content could not be decrypted or
    parsed.",...}}"
  - refused recording reasoning and compactions only (seals as on main):
    the same 18 cases and TestSealsTakenOutLeaveTheRest red, the next
    turn refused once more, "then asked [{"acct-2" "message user,
    web_search_call 上海天气 gAAAA-acct-1-w1, function_call c1
    gAAAA-acct-1-f1, ..."} {"acct-2" ...}]", and "next turn:" with the
    seals left on
  - withoutRefused taking out reasoning and compactions only: the same
    19 red, with the same lines
  - withoutRefused dropping each refused item whole: the same 19 red,
    "then asked [{"acct-2" "message user, message assistant, message
    user, message assistant, message user, reasoning gAAAA-acct-2-r3,
    ..."}]", the searches and calls gone
  - withoutItemSeal writing the item out again (marshalPlain):
    TestSealsTakenOutLeaveTheRest red, "got {...}" with the web search's
    keys sorted,
    {"action":{...},"id":"ws_1",...,"type":"web_search_call"}
  - withoutItemSeal without its keepsSeal check:
    TestSealsTakenOutLeaveTheRest and TestForeignCompactionToGrok red,
    "grok was sent [["compaction:sealed-by-openai-compaction"
    "reasoning:sealed-by-openai"] []]": the compaction lost its seal in
    the first step instead of going in its own
- the related tests (TestForeign*, TestCodexOwnModel*, TestCodexSpent*,
  output replay, the rewrite equivalence tests, TestAffinity*,
  TestNativeCompaction*, TestRemoteMagpie*, TestGatewayKey*, groups and
  Codex accounts): 257 passed with their subtests, none skipped (Bun
  1.4.2)
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway (log
  kept), Bun 1.4.2: 5418 passed with their subtests, 3 skipped, and one
  red, TestPluginToldWhereTheAgentWorks (#3675): "not in one: the plugin
  was told "/tmp/TestPluginToldWhereTheAgentWorks191044475/005", git
  "yes"; want "/tmp/TestPluginToldWhereTheAgentWorks191044475/005",
  "no"". It is red the same alone, and with the four code files as on
  f8cd964a: this box has an empty /tmp/.git, and GitOnDisk counts a .git
  in any folder above.
- read against main's 7f0f71a0 (#2481) and fff05e55 (#2725), which
  change code beside this: 7f0f71a0 puts the route on two of the relay's
  record exits, which come after withoutUnreadable has chosen the body
  asked again; fff05e55 changes only whether Codex's compaction trigger
  is kept native (plannedCarrier), not serve's retry or the step it
  skips for a provider compacting natively (compactsNatively), so a
  trigger it now has magpie summarise goes through serve and the same
  retry. Neither changes what withoutSeals or withoutUnreadable do.
- go test -tags nogui -count=1 -timeout 45m ./... (log kept), Bun
  1.4.2: 69 packages ok and 7 red, none in what this changes; gateway's
  only red is TestPluginToldWhereTheAgentWorks (#3675), the new tests
  pass in it. The reds: agent TestInstalledVersion,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir (#3141), the two Reasonix tests (#3641) and
  TestWSLColdPlaceOpensNothing (#3924); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077,
  #3640); gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649); provider
  TestCodexAppServersOnHome (#3906), then "close of synctest channel
  from outside bubble" (#3632); tui
  TestTUIFetchesSubscriptionModels/agent (#3919).
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  build -tags nogui for linux and darwin, and go vet and go build for
  windows without the tag: exit 0 each. go vet and go build without the
  tag on linux: exit 1 (this box has no GTK or WebKitGTK dev packages).

Not tried: real ChatGPT or OpenAI accounts. Whether the ChatGPT backend
takes a web_search_call with neither its id (magpie's Codex account
route sends none, as on main) nor its seal; hheei's 200 was OpenAI's
Responses API with the id kept. Whether one account refuses another's
replayed message and call seals at all (the fake does; if it reads them,
they are still taken out on a hop, where the conversation's cache is
gone anyway). OpenAI refusing in the stream: the fake does, as xAI may;
hheei's refusal came as a 400. An OpenAI API key as the next member of a
group: forVendor keeps the seals for *openai.com only, so a fake on
127.0.0.1 can't stand in for it; it reaches the same retry in serve. Nor
magpie's summary of a Codex compaction after a move: codexCompact asks
through serve, so the same retry should apply, but no test drives it.

Ported onto origin/main 5ee5274bd from yinwu01/magpie 2d764b1c (posted
on #3887, sha256 d9185e84...). Conflicts resolved by hand: main had
since grown noteRefused (also used by reasoning_carry.go's
refuseCarried), so refused(key, who, sent, left) now hands it the seals
sent minus those left; foreignReasoning keeps main's broader pattern;
foreign_seal_test.go keeps main's TestForeignSealAzureSummary and
TestForeignSealGrokRelayCompactionBlob beside the four new tests; the
Affinity row and the new bullet in gateway-routing.md were merged into
main's text.

What was run for the port (mote, macOS, go1.26.8):
- go vet -tags nogui ./internal/gateway, and go test -tags nogui
  -count=1 -run 'TestForeign|TestSeals|TestCodexOutputReplay|
  TestCodexOwnModel|TestCodexSpent|TestRefused|TestReasoningCarr|
  TestWithout|TestNativeCompaction' ./internal/gateway: ok
- the three new end-to-end tests on 5ee5274bd (old code, the unit test
  left out as it calls withoutSeals): all red,
  TestForeignSealedItemsMoveToAnotherAccount and ...AfterAColdSwitch
  "moved on: 400 {...invalid_encrypted_content... Codex: Encrypted
  content could not be decrypted or parsed.}" and "gone cold: 400",
  ...RelayedToAnotherSignIn "400 {...Encrypted content could not be
  decrypted or parsed...}"

Batch run, at tree 104d75f0a (the twelve coffemon ports together, on
origin/main 7d022bdb6), mote, macOS, go1.26.8:
- go test -tags nogui -count=1 -timeout 45m on the packages the batch
  changes (agent, autostart, daemon, gateway, library, proc, provider,
  sessions, testenv, tui, gui): ok each.
- GUI, node --test with Playwright 1.62.0, Chromium and WebKit:
  library-*.test.cjs and i18n-keys.test.cjs, 1044 of 1044 pass.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... and go build ./...: ok at cdd7c8e46, the same
  batch on origin/main 00098f12b one rebase before.
- The whole go test ./... at cdd7c8e46: 86 packages ok, one red,
  internal/cli TestEveryRouteHasACommandOrIsNamed (GET
  /api/context/reply has no command), red on main too (#5026).
- Linux (wsl-run, Ubuntu 24.04, at 339055896, the batch on f4c664a09):
  proc, autostart, testenv, tui ok; agent: only TestGrokInstalled red
  (#3548); #4033's proc.Look reds (Zed, Copilot, Qoder, Cursor, Omp)
  pass.
- Windows (win-run, Windows 11, at 339055896): proc, autostart, testenv,
  tui ok; library and agent red in the same tests as on origin/main
  f4c664a09 (#4115, #1827, #4786; #5068, #5069, #5070 filed now).
- Rebased onto origin/main fb1f4856a (three commits, no file in
  common with the batch) and run again at the pushed tree: gofmt -l
  nothing, go build ./... and go vet ./... ok; go test -tags nogui
  sessions, agent, autostart, tui, proc, testenv ok; i18n-keys and
  library-* 1044 of 1044 pass.
- Not run before the push: the whole GUI suite (a run at cdd7c8e46 was
  cut off at 1170 of ~1174 tests when mote rebooted; it runs again after
  the tag and any red is filed).
2026-11-03 20:38:11 +08:00
yetone 694f4a6d65 gateway: a Codex turn of its own reads past 512 MB, to a sixteenth of the machine's memory (dallascao)
dallascao on Discord: generating images in Codex and revising them again
and again, magpie answered 413 "request body is over magpie's gateway
limit of 512 MB (decoded); the provider was not asked" on
127.0.0.1:3425/backend-api/codex/responses, while Codex signed in to
OpenAI directly went on. The count was right: Codex keeps each image it
generated in the conversation (a function_call_output input_image, a
~3 MB PNG as ~4 MB base64; codex-rs ext/image-generation to_response_item,
and history keeps image_generation_call results), and over HTTP sends the
conversation whole every turn, so ~130 images is 512 MB decoded. To
OpenAI directly Codex uses its WebSocket and sends a delta.

- Codex's own path (codexBackend, the Codex relay, the Responses
  WebSocket's read limit, keyLimited on CodexPath) reads to
  codexBodyLimit: a sixteenth of the machine's memory (memLimit, else
  proc.MemTotal), 512 MB at least, 2 GB at most. 16 GB: 1024 MB,
  24 GB: 1536 MB, 32 GB+: 2048 MB, 8 GB or unknown: 512 MB as before.
  It is still the bomb guard: nothing decodes past it, and the zstd
  decoder keeps its window bound.
- A turn for a magpie model ("provider/model") on that path is held to
  the 512 MB of every other route once its model is read: it is
  translated, at several times its size. Its 413 says one of Codex's own
  models takes up to codexBodyLimit; writeError's /compact hint stays.
- provider.codexNamesBad read tools/input/tool_choice with
  GetManyBytes, which copied the whole input (the body's size: 300 MB of
  a 300 MB turn in the alloc profile). It reads in place now.

Cost at the largest input (mote, a relayed gpt-5.5 turn of random
~3 MB images, heap objects sampled every 5ms, load ~350): 300 MB took
4.7s, 600 MB 7.7s, 1000 MB 11.9s, peak heap 1.5 to 2.1 GB past the
body's own bytes. The rest of the cost is io.ReadAll growing the decoded
body and fillJSONIn/exchangeOf; bodyRoom still runs a body bigger than
its room alone.

Run at the pushed head (mote): gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/gateway ./internal/provider ok;
go test -timeout 45m ./internal/provider ok, ./internal/gateway ok but
TestCompactionOverByteCapEveryTime, red in the full package run only
(#4862, filed before this; passes alone 3 of 3 here).
TestRequestBodyTooLarge/codex now sends codexBodyLimit+1.
- TestCodexGeneratedImagesPastOldLimit (16 GB machine fixture, a 516 MB
  turn of generated images in Codex's shape): reaches the fake ChatGPT
  backend whole in ~6s; the same turn for x/gpt-5 is 413 naming
  "one of Codex's own models takes up to 1024 MB".
- TestCodexBodyLimitFromMemory: 2/8/16/24/64 GiB and unknown memory.
Broken by hand: codexBackend reading with limit 0 (the old code) makes
TestCodexGeneratedImagesPastOldLimit red with the reporter's 413; the
magpie-model check turned off makes it red (404 from routing, not 413).

Not tried: the reporter's own session or a real Codex image-generation
run through magpie; a turn past 1 GB on a 16 GB machine; the WebSocket's
raised read limit has no test of its own.
2026-11-03 16:05:53 +08:00
yetone affa979d56 gateway: Codex's one account used up goes on to the Codex subscription's fallbacks
adorable_piglet on Discord: once the ChatGPT (Plus) account's quota ran
out, the Codex app couldn't send at all, and magpie never moved the turn
to the fallback they had set (their own API key, another provider).

Cause: with one ChatGPT account and nothing to route, a turn on Codex's
own sign-in is relayed as it came (codexUpstreamOn). The relay handed an
overload on to the subscription's fallbacks (codexFallBack), but a
quota, credit or rate refusal went to Codex as the backend said it, the
429 usage_limit_reached with its x-codex headers. Codex then stops.

Change: codexAccountOut names the refusals that are the account's, not
the request's: failure() quota, credit or rate, as a status or as a
stream's failure before any reply (response.failed, an error event, a
stream without Content-Type), and a 403 usage_not_included. Never a 401:
Codex renews its own sign-in on it. When the subscription has fallbacks
(codexFallsBack, never a compaction), such a refusal now goes on to them
once the credits retry and the automatic reset have been looked at, as
an overload does; the trace keeps the try's real failure kind. With no
fallback set, Codex still gets the backend's refusal.

What Codex's own client does: it greys Send from its own /wham usage
read. magpie already gets past that once the usage reading says used up
(codex.out with the app-server restart, #540, 9f641daea); this change is
the turn itself.

docs/subsystems/gateway-routing.md says it.

Run (mote, at this tree):
- go test -tags nogui ./internal/gateway -run 'TestCodexOneAccount|TestCodexOwnModel|TestCodexSpent': ok.
- New TestCodexOneAccountSpentFallsBack: all 7 codexSpent shapes red on
  the old code (Codex got the 429/403 or the failed stream), green now.
  TestCodexOneAccountSpentNoFallbackRelayed and
  TestCodexOneAccountSignInRefusedNotFallenBack hold the no-fallback and
  401 cases.
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok. gofmt clean.
- The whole internal/gateway package (-timeout 45m) was still running at
  push; the result is reported separately.

Broken by hand: codexAccountOut returning false: the 7 subtests red again.

Not tried: a real used-up ChatGPT account in the real Codex app.
2026-11-03 12:41:12 +08:00
yetoneandJunyu Zhou 8819beeb0e gateway: a display reads routing as it happens at /v1/magpie/route-events (#3387)
joe21_eee (sywyyhykkk on GitHub) wrote this for an ESP32 screen that
shows each agent's requests live: started, each try, the first content,
fallback, done. Ported from their route-events branch (42e1fa43f) with
the changes below.

What a display gets (route_events.go):
- GET /v1/magpie/route-events/snapshot: cursor, active, routes (every
  request the trace has that is still going).
- GET /v1/magpie/route-events?after=<cursor> (or Last-Event-ID): SSE,
  one "route" event a change, id = cursor, from a 512-change ring under
  trace.mu, so a short request is told step by step. 409
  snapshot_required for a cursor not this process's or too old, "event:
  reset" for a reader that fell behind, a heartbeat every 15s, a 10s
  write deadline.
- A route is routeActivity, an allow list: trace id (base 36), time,
  agent label, the provider of the seat the last try went to (never the
  seat id, which names an account or a key fingerprint), model, attempt,
  fallback, phase, status, failed, ms, ttft_ms. No session, account,
  key, folder, prompt, reply or error text.
- firstToken.onFirst tells the first content as it comes (serve and the
  ChatGPT backend's reads), written to an unexported Try.firstMs so the
  full trace's TTFT is unchanged.

Changed from the branch:
- No new key type. The branch added an "sk-magpie-route-" key, its CLI
  flag and its own Authenticate path through access, identifyCaller and
  corsGuard. main has read-only keys now (readOnlyGuard), and the feed
  is answered as /v1/magpie/usage is: this computer, and another machine
  with an enabled key while shared; a held key is refused (refuseHeld).
  Both GETs are in readOnlyRoutes, so the display gets
  `magpie gateway-key add Screen --read-only`. A full key already reads
  more than this (every call's usage). access, cli, cors.go and lan.go
  are untouched.
- A route the trace drops unfinished (drop: an unrouted request's
  stand-in once its own route begins; trim past twice traceKeep) is told
  request_dropped and marked offFeed. The branch kept its own active map
  that only "done" cleared, so a stand-in stayed going forever. The
  snapshot is read from t.routes, no second map.
- A stream ends when the gateway stops serving (Server.streamsEnding,
  closed first thing in ListenAndServe's drain). Before, an open stream
  held srv.Shutdown for its whole drain, 15 minutes on a handover.
- Revocation is access.On(KeyID) (identifyCaller swaps the secret out
  before handlers see it), asked at most once a second when there are
  changes and at every heartbeat, and remoteKeyed for a remote reader. A
  rotated key keeps its id, so its open stream goes on until it
  reconnects (said in the docs).

Docs: gateway-routing.md "Route events for a display" and the
read-only key's route list; reference.md beside the usage API.

Run at the pushed head on mote (Go 1.26.8):
- At daaafeb6e (rebased on ffc4aa684): gofmt -l internal/gateway empty;
  GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  ./internal/gateway ./internal/access ok; go test -race -run
  'TestRouteEvents|TestReadOnlyKeyEveryRoute' ./internal/gateway ok.
- At daaafeb6e, every package that imports the gateway: internal/agent,
  browsermcp, cli, davsync, imagemcp, library, settingsapi, tui,
  access and the root package ok. internal/gui: one red,
  TestMainWindowCorners/macOS_26_SDK, which is #3949 (mote runs macOS
  27; this change touches no GUI code).
- Before the rebase (eb779ce92 base; gateway and access are the same
  at ffc4aa684): go build ./..., go vet, and the whole internal/gateway
  package, -timeout 45m. All ok except TestCodexPoolSaysTheClientsVersion,
  which is #4807 (red in a full package run on mote, passes alone; it
  passes alone at origin/main bf05291e2 too).
- At the pushed head (rebased on 443e53d6b, which changed search.go):
  gofmt, go vet ./internal/gateway and the -race run above again, ok.
- Not run: go test ./... in full. Other sessions' suites had mote at
  load 60 to 120.

Broken by hand (each on mote, then restored), the test that went red:
- serve's onFirst line removed: TestRouteEventsLiveFallback.
- drop's request_dropped removed: TestRouteEventsDroppedRouteGoes.
- the offFeed check removed: TestRouteEventsDroppedRouteGoes.
- the streamsEnding case removed: TestRouteEventsEndWithTheGateway.
- refuseHeld skipped: TestRouteEventsTold.
- the access.On recheck skipped: TestRouteEventsReplayAndRevocation.
- the snapshot taken out of readOnlyRoutes: TestRouteEventsTold,
  ReplayAndRevocation, LiveFallback.
- the seat's id told for its provider: TestRouteEventsReplayAndRevocation.
- the handler's own local/sharedWith gate removed: still green, since
  lanGuard refuses another machine first when not shared. It stays, as
  usage's does.

Not tried: an ESP32 or any real display, a real gateway with real
agents (tests drive httptest servers and fake upstreams), a handover
between two real magpie processes.

Co-authored-by: Junyu Zhou <feijifeibudao@gmail.com>
2026-11-03 11:06:59 +08:00
vincent c86fa2a341 gateway: a relayed citation without the offsets OpenAI's schema wants is dropped, the thread healed (#4921)
A thread a routing group served once on Volcengine Ark (or another
vendor whose Responses endpoint writes its url_citations with no
start_index/end_index) never worked on a codex member again: magpie
relayed the reply's annotations as they came, Codex stored them, and
the ChatGPT backend refused every later replay of the history whole —
"Missing required parameter: 'input[221].content[0].annotations[0].
start_index'" — five retries a turn, on any codex member, through any
upgrade (#4921, the reporter's routing log and rollout). This is
#2855's defect with a different field: what magpie hands a client must
be something magpie could send again.

Such an annotation goes, at both seams, as the reasoning-item fix did:

- a whole reply streamed as the vendor's own events (responsesWholeEvents)
  drops it in every place a client reads a citation: its annotation
  events, the content part, the item and the reply the client keeps
  (dropOffsetlessCitations);
- the history Codex replays loses it on its way to the ChatGPT backend
  (withoutOffsetlessCitations, the same leaving-out as a reasoning
  item's text, #1411): to the backend by its own sign-in and compaction
  relay (codexUpstreamOn), to it as a group member or an openai.com or
  Azure upstream (the provider loop, beside withoutReasoningText), and
  asked again without it where a relay in front of it names the
  parameter (refusesCitationOffsets), marked so it is never sent one
  again — a thread already poisoned heals on its next turn, no new
  thread needed.

The text, and a citation that carries its offsets, go as the vendor
wrote them; a turn with no "annotations" in it is not decoded
(anyInputItem scan, itemCitesWithoutOffsets; the undecoded-turn test
holds, allocations and all).

Run: the three new tests fail on the base with the reporter's exact
400 and pass here (ablation: the tidy call and the rewrite's body
neutralized, tests kept); TestCodexRewritesAsBefore,
TestCodexRewritesLeaveTurnUndecoded and the fuzz hold the rewrite to
its scan; the citation/whole/reasoning neighborhood ok (23s); gofmt,
go vet (linux, windows) and go build -tags nogui clean.

Review: this is skygunner's version of the fix (fcea11649), not
ggbdpq's 57dc7b420. ggbdpq's stripped citations only for a request
that wasn't for a magpie model, so the reporter's own path (a routing
group's codex member, the history passed through) kept the bad
annotation. ggbdpq's parity table and verification of the report
were used to check this one.

Changed in review: annotationLacksOffsets looks only at url_citation
and container_file_citation, the two types OpenAI's schema gives
start_index and end_index. file_citation and file_path carry a single
index, so the patch dropped every one of them as "offsetless".
TestCitationsWithOneIndexKept (added in review) holds both kinds and
checks that a history with only file_citations is sent byte for byte.

Broken by hand at the reviewed head: annotationLacksOffsets made to
return false, all four citation tests red; the type check removed,
TestCitationsWithOneIndexKept red. Restored, green.

Run at the pushed tree (this stack of nine on origin/main 3c2dceb34),
on mote (macOS arm64, Go 1.26.8):
- go test -count=1 -timeout 45m ./internal/catalog/...
  ./internal/plugin/... ./internal/davsync/... ./internal/gateway/...:
  catalog, plugin and davsync ok; gateway red on one test only,
  TestCodexPoolSaysTheClientsVersion, the open #4807 (another test's
  Codex identity reaches it in a full package run). It passes run
  alone at this tree, 3 of 3.
- go vet ./... (darwin); GOOS=linux and GOOS=windows go vet -tags
  nogui ./...: ok. gofmt -l on every tracked .go file: clean.
- The hand breaks above ran on this stack before its rebase onto
  3c2dceb34. That commit changed member.go only, nothing these tests
  reach.
Not tried: the GUI suite, since no GUI file changed. Windows and Linux
test runs (the Claude bridge tests use a shell fake and skip on
Windows). No real vendor, Claude Code or network was used; every
case runs against fakes.
2026-11-03 07:43:18 +08:00
yetoneandggbdpq 4bac5eed26 usage: a request's row says what went up to the vendor, tries summed (#4456)
RunMintOn asked how much a long session sends upstream: a proxy counted
~900 MB up in 45 minutes, and no ledger row said what a request sent.

A row now has up_bytes, the bytes that went on the wire, every try and
every second ask summed (zstd's size for a ChatGPT turn), and
plain_bytes, the last try's body before compression. They are summed
in the request's context on its own goroutine, set in serve and, for
Codex's own turns that come from the mux and not through serve, in
codexUpstreamOn. Handed-on rows carry neither; rows from before carry
neither.

From ggbdpq's patch (via gua2100), two changes:
- the patch counted in codexUpstreamOn but set the context only in
  serve, so a Codex turn on its ChatGPT sign-in, the zstd case the
  issue is about, wrote 0 and 0 (TestCodexOwnTurnKeepsUpBytes);
- a second request inside one try (RetryOneAuth, RetryZhipuCoding,
  RetryOpenCodeFreeOnZen) went up uncounted; it counts now
  (TestLedgerCountsATrysSecondAsk).
Request bodies to other vendors stay as their client sent them; zstd
stays Codex's (the owner's call, on the issue).

Run at this tree on mote: go test ./internal/gateway -run
'UpBytes|TrysSecondAsk|OneAuth|Codex|Draw|Relay' -count=1: ok;
go test ./internal/usage ./internal/redact -count=1: ok. gofmt clean.
Broken by hand: no context in serve: TestLedgerKeepsUpBytes and
TestLedgerCountsATrysSecondAsk red; none in codexUpstreamOn:
TestCodexOwnTurnKeepsUpBytes red (row 0/0, backend got 79 of 8444);
the second ask not counted: TestLedgerCountsATrysSecondAsk red.
Not tried: a real session's numbers against a proxy's; the GUI shows
neither field yet.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-03 05:08:39 +08:00
ggbdpq f822689ada gateway: a relay's "referenced reasoning item" refusal is read as an unreadable item (#3062)
What changed: unreadableItem, the matcher that reads a 400 as "this input
item can't be read", now also takes the wording a Responses passthrough
relay answers in — "Referenced reasoning item 'rs_…' was not found or has
expired" — beside OpenAI's own ("Item with id 'rs_…' not found",
"encrypted content for item"). The refusal is recognized wherever the
matcher is read: the passthrough turn is asked again without the bare
reasoning (and the provider's model isn't sent them again), the ChatGPT
backend drops the named item and asks the rest again, and a compaction
refused so is asked again as text.

Why: a Codex thread behind such a relay (opencode.ai's OpenCode Go)
collects reasoning ids the relay can't resolve, two ways — a turn failed
over to a provider magpie translates leaves Codex reasoning items magpie
minted (an rs_ id and a summary, nothing sealed), which never existed on
the relay's store; and the relay seals its own reasoning only briefly, so
after a resume gap ids from its earlier replies read as expired. Codex
replays the whole history every turn, and the relay's 400, worded by the
relay and naming no input param, passed refusesInput unread — so the
thread 400s on every later turn. The reporter's repro now strips the
named bare item, asks again, and answers 200.

Run: TestRelayRefusedReasoningItemReadAsUnreadable and a TestRefusesInput
row for the reporter's exact body are red before the change and green
after; the bare-reasoning, foreign-seal and item-not-found families stay
green (also with -race, and under an ablation and a mutation of the new
wording, where the old wordings' tests stay green); gofmt clean; go vet
on darwin, linux and windows; builds with -tags nogui on the three. Full
./internal/gateway/ is green on the third run (511s); a first run hit go
test's default 10m timeout and a second failed only
TestAsyncGatewayResponseDoesNotHoldStream — a fixed-10s-guard streaming
hook test unrelated to this change, which passes 3/3 alone.

Generated-by: GLM-5.3-Flash (ZCode)

Landed from ggbdpq's branch (patch posted on the issue; sha256/patch-id
checked against the issue) by yetone, rebased on origin/main 2026-11-03.
Run at the pushed tree, on mote (macOS): go test -tags nogui -count=1 of
internal/gateway with -run over this batch's tests and their families
(PlainSchema, Antigravity, AutoMode, WebP, ClaudeTUI, NativeRelay,
Namespace, Grok, Zed, Codex, ClinePass, rewrite) ok; -race -count=3 of
the new tests ok; GOOS=linux and GOOS=windows go vet of internal/gateway
and gofmt -l clean. The full gateway-and-importers run, started at an
earlier base, was still running at the push; its reds get issues.
Broken by hand: the regexp change reverted, test kept:
TestRelayRefusedReasoningItemReadAsUnreadable red; restored, green.
Not tried against the reporter's relay; the fixture is its literal body.
2026-11-03 02:27:57 +08:00
yetone 5ec2375688 gateway: a call's HTTP headers both ways, masked, folded under its bodies
usrname1833 on Discord asked to see the raw request and response HTTP
headers (查看原始请求和原始响应的http头), to debug as with a capture.
magpie kept the client's request headers and its own response headers
only in the request archive, and nothing of what went upstream.

Now a call keeps its headers both ways (internal/gateway/wire_headers.go):
- the client's, as they reached magpie: headerLogged in Handler() clones
  them for every request that isn't a GET, HEAD or OPTIONS;
- each request magpie sent upstream for the call: method, address,
  headers, and the answer's status, protocol, headers and time, or the
  error. rpmTransport (under s.client) records it as it is sent;
  provider.SendsThroughPlugin records a plugin account's hand-off, shown
  as handed to the plugin, since the plugin's own request to its vendor
  is made in Bun and magpie doesn't see it (the view says so). The first
  8 tries are kept, the rest counted.
Recording copies each header map; nothing is masked or sorted as a
request goes. Secrets are taken out when the headers are read
(Call.Headers): by what each header is (new redact.SecretHeader, now
behind redact.ScrubHeader: Authorization, cookies, x-api-key, api-key,
any *-Key, *-Token, *-Secret, *-Auth, *-Signature, but Idempotency-Key
and a count of tokens such as anthropic-ratelimit-tokens-remaining),
any Bearer or Basic value, and redact.Scrub on the rest; an address
loses its password, a secret-named query value (?key=) and its fragment.
They live with the call in the 40-call ring; /api/gateway/call gives
them as "headers". The request archive keeps the upstream ones as
"upstream" beside the request's and response's headers, masked the same
way. No body is stored that wasn't before.

GUI: under a recent call's bodies on Gateway and a request's on Routing,
"HTTP headers" folds open the client's headers, then each upstream
request beside its answer (wireHeadersView, plugins/usage/page.js); the
archive's copy shows its upstream requests too. Strings in all four
languages. docs/subsystems/gui-shell.md describes it.

Also changed by SecretHeader: the request archive no longer masks a
rate-limit count header (…-tokens-remaining), which the old name rule
took for a token. (provider.SecretHeader, which backups use, is another
function and unchanged.)

Tests: TestRecentCallHeadersBothWays (a fake vendor; the client's key and
cookie, magpie's upstream key and the vendor's Set-Cookie all masked;
status, protocol and response headers kept), TestRecentCallHeadersEachTry
(a 429 then the next key, both kept in order), TestPluginHandOffHeaders,
TestScrubURL, TestSecretHeaderRealNames (real header names both ways),
TestArchiveOnThisComputer and TestRecentCallBodiesOnDemand extended,
call-headers.test.cjs (Gateway, Routing and the archive's copy; chromium
and webkit; en at 1100px, zh, zh-TW, ja, de at 380px and Routing at 440;
nothing out of the box, no left-border accent).

Run (on mote, macOS 27.2, through mote-run, unless named):
- Full suite at ebd22b1b4 (the same change on 5daba8337): gofmt -l
  empty, GOOS=windows go vet ./... ok, GOOS=linux go vet -tags nogui
  ./... ok, go test -count=1 -timeout 45m ./...: every package ok but
  four tests, none in this change's code, each filed:
  TestEveryRouteHasACommandOrIsNamed (internal/cli,
  /api/usage/checkin-account from e87140242, #4826),
  TestCodexPoolSaysTheClientsVersion (#4807: another test's Codex
  identity, passes alone, 3 of 3 here), TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27), TestClosingWindowMarksPageOutOfSight (passes
  alone; filed #4924).
- Rebased on a3768cdd1 (it changed internal/gateway, routing/client.js
  and i18n.js): gofmt, go vet, Linux (nogui) and Windows vet of
  internal/... ok; go test of internal/gateway, gui, redact, provider:
  ok but TestCodexPoolSaysTheClientsVersion (#4807, ok 3 of 3 alone
  with this change's gateway tests) and TestMainWindowCorners (#3949);
  TestCoreScriptBudget ok. GUI: call-headers, routing-bodies,
  recent-call-bodies, request-archive and i18n-keys, 58 of 58.
- Rebased again on 2c90922b0 (app.js and internal/provider, no file of
  this change): TestCoreScriptBudget and TestRecentCall* ok;
  i18n-keys plus call-headers 24 of 24 three times out of four at load
  ~130 on mote. The first try had 1 red of 24 whose name was lost
  (its output was grepped, not kept); it did not come back in 3 runs.
- At the pushed head, rebased on 898c314b7, then 3e61d814e and 8d4d8b2d5 (gateway search, redact; vet, internal/redact and the header tests again ok) (app.css, app.js, i18n.js,
  gui-shell.md and internal/gateway changed): gofmt, vet of gateway and
  gui ok; TestCoreScriptBudget, TestRecentCall*, TestRouteCall,
  TestPluginHandOffHeaders, TestArchiveOnThisComputer, TestScrubURL ok;
  i18n-keys, call-headers, routing-bodies, recent-call-bodies 54 of 54.
- call-headers.test.cjs 20 of 20 (chromium and webkit; en at 1100, zh,
  zh-TW, ja, de at 380; Routing at 440), screenshots looked over.
- GUI: not the whole suite. mote had three other sessions' full GUI
  suites running and the Linux box one, so 131 files the change can
  reach (gateway*, routing bodies/log/steady/story/time, recent*,
  call-*, request-archive, masking*, usage*, i18n*, gui-*, account-eye)
  ran on the Windows box: 1739 of 1862. Every red file was run again at
  5daba8337 on the same box: routing-bodies, gateway-card,
  gateway-systemone, masking-demo, usage-ledger's Requests and the rest
  are red there too (Windows WebKit and Windows-only), and account-eye,
  routing-log-icons, usage-ledger-leave and -probe pass alone at this
  change. call-headers' 4 webkit Routing reds on Windows are
  routing-bodies' own (".rt-day" never visible in Windows WebKit).

Broken by hand, each then put back:
- ScrubHeader back on the name rule: TestSecretHeaderRealNames red
  ("a count of tokens: [REDACTED]").
- rpm.go's upstreamBegins taken out: TestRecentCallHeadersBothWays,
  TestRecentCallHeadersEachTry, TestArchiveOnThisComputer and
  TestRecentCallBodiesOnDemand red.
- scrubHeaders off the sent headers: TestPluginHandOffHeaders red with
  the plugin's key shown.
- Gateway client.js's toggle taken out: the 5 chromium recent-call GUI
  tests red.

Not tried:
- The whole GUI suite (above), and the GUI on Linux.
- A real account or the real app: only fakes.
- What a plugin sends its vendor (made in Bun, not seen by magpie; the
  view says so), and headers Go's transport adds itself
  (Accept-Encoding, Content-Length).
- magpie's own requests (System One's decision, titles, search) keep no
  headers; a gateway served by another magpie shows none.

Asked by usrname1833 on Discord.
2026-11-03 02:25:23 +08:00
yetone 07f4d46c52 gateway: a Codex reply that ends early, and any failed call, is written to app.log
wjh66 (Discord, Windows, v0.1.2696) saw Codex on a ChatGPT sign-in with
gpt-6.1-sol show "reconnecting 5/5" and then `error decoding response
body`, and app.log around 15:27 held nothing about it. That text is
reqwest's for any read error in a body (a reset, a chunk cut short, a
timeout), so it says the connection broke mid-reply, not which side broke
it. The cause is not found; this change only makes the next report carry
evidence.

- record logs a failed call (status >= 400 or an error) when debug is off,
  once a minute per agent/provider/model/status/error, counting repeats.
- codexUpstream logs a reply that ended before its last event (or a
  non-SSE body cut by a read or write error): bytes passed on, whether
  OpenAI's stream failed or ended, and whether Codex went away, a write
  to it failed, or it was told response.failed.
- Shutdown with requests in flight says they are cut (Windows has no
  handover, so a quit or update cuts streams after shortDrain).

Run at this head (rebased on 4bd0d6f38; the new and stream-cut tests and vet run again after the rebase on mote and Windows, the full gateway run on Linux was at 4e764fc39):
- win-run: TestCodexReplyBrokenOffLogged, TestCodexClientGoneLogged,
  TestFailedCallLineOncePerMinute, TestCodexStreamCut* - ok.
- wsl-run: go test -tags nogui ./internal/gateway -timeout 45m - one red,
  TestCodexPoolSaysTheClientsVersion, which is #4807 (red on main too; the
  identity it sees is the machine's own Codex 0.165.0).
- mote-run: gofmt -l clean; go vet -tags nogui ./internal/gateway for
  darwin, GOOS=linux and GOOS=windows - ok.

Broken by hand: both new log.Print calls replaced with `_ = line`; the
two Codex tests went red ("no log line holds ...").

Not tried: a real Codex on Windows, a real cut from chatgpt.com, the
serveAgent (magpie's Codex accounts) path specifically, the full suite
on macOS or Windows.

Reported by wjh66.
2026-11-02 17:10:02 +08:00
yetone 58541e5b8c gateway: a turn that ended failed, cut or canceled says no task done (#4866)
emo172 (mochi) reported that "<agent> 已完成" was shown for Codex turns
that never finished. On Codex signed in with ChatGPT
(/backend-api/codex), three cases were recorded as a clean 200 and
ended the turn: Esc or a closed window mid-reply, a response.failed
under the backend's 200, and a response.incomplete. codexUpstreamOn
looked only at the status and codexStreamCut. codexStreamCut says ""
when sniff.failed is set, when the stream is whole, or when the
context is done. trace.go:790 then ended the turn with final true.

The fix is in the one place both turn paths share, the reply scan
(toolScan) every byte to the agent goes through, and turnFinal, which
now decides `final` at trace.go:790:
- A cut mark makes a reply unfinished: an error event in each wire
  format (Anthropic/Responses "type":"error", Chat/Gemini "error":{…}),
  a Responses reply failed, incomplete or cancelled, and a reply cut
  at its length (stop_reason max_tokens or
  model_context_window_exceeded, finish_reason length, finishReason
  MAX_TOKENS). Keys are matched with their quotes, so text or tool
  arguments that mention them escaped never match. "error":null on a
  success doesn't match.
- The agent's request being done before the reply's last event
  (response.completed, message_stop, a stop reason, [DONE]) makes it
  unfinished too. A client that hangs up after the last event, as
  Codex does, still ends its turn.
- A Responses tool_search_call that Codex runs itself
  ("execution":"client") counts as a tool call. It was missing from
  toolValues.

Codex direct also records what it saw, as the routed path does: 499
canceled when Codex went away mid-reply, and the backend's
response.failed as the row's error. Covered: the Codex HTTP and
upstream-socket paths, Codex's own socket to magpie
(response.interrupt), and routed Chat, Responses and Anthropic relays,
plugins included, since they go through captureResponseWriter.

Scene A, a model ending its turn with a question for the user: no
change. Nothing in the bytes tells "asks the user" from "done" without
reading the text, and a turn's end with the agent waiting on the user
is what the alert is for. Structured asks are tool calls and don't
alert already.

Tests (turndone_unfinished_test.go), from real event shapes:
- TestReplyScanUnfinished: 14 replies, each split at six points.
- TestTurnDoneCodexBackendUnfinished: failed, incomplete and canceled
  (the agent hangs up on its first write). No end, the route says
  error or 499, and a whole reply after each ends the turn.
- TestTurnDoneCodexSocketInterrupt.
- TestTurnDoneRoutedUnfinished: Chat error and length, Responses
  failed and incomplete, Anthropic error and max_tokens.

Run on mote:
- go test -timeout 45m ./internal/gateway at c08d02adf (this change
  on f849ccced): every test ok but TestCodexPoolSaysTheClientsVersion,
  which is #4807. That test takes another test's Codex identity
  (codex_cli_rs/0.165.0) in a package run. It passes alone 3 of 3
  here and on origin/main e7185daeb.
- After rebasing on e7185daeb (its gateway changes include
  codex_backend.go), at the pushed head:
  go test -run 'TurnDone|ToolScan|ReplyScan|Codex|Socket' ./internal/gateway
  is ok but the same #4807 red. The same -run on e7185daeb alone
  fails the same way.
- go vet ./internal/gateway, also with GOOS=linux and GOOS=windows: ok
- gofmt -l: clean

Broken by hand, the -run 'TurnDone|ToolScan|ReplyScan' tests on mote:
- With turnFinal's unfinished() check dropped, Codex incomplete and
  routed Chat length, Responses incomplete and Anthropic max_tokens go
  red.
- On the old code (both trace.go and codex_backend.go reverted), every
  Codex case and the socket interrupt go red too: 200 "" and an end
  said. Routed error events and Responses failed passed on the old
  code already, since serve records sniff.failed as the call's error.

The scan's cost: TestPluginStreamLargeReplies took 22.0s with the fix
and 21.9s on the old code, at load 78.

Not tried: a real Codex session pressing Esc against the live
backend, and the GUI notification itself (TurnDone is unchanged).

Reported by emo172.
2026-11-02 15:19:38 +08:00
yetone b4a9cd8db5 codex: a tool name the ChatGPT backend refuses goes as one it takes, and comes back as the agent's
wing3556 on Discord (11-02): a compaction through a Codex account failed
400 "Codex: Invalid response.create payload: Invalid 'input[83].name':
string does not match pattern. Expected a string that matches the
pattern '^[a-zA-Z0-9_.-]+\z'." The ChatGPT backend checks every tool
name in a request, a call's in input as well as a tool's in tools, and
refuses the whole request when one fails. A conversation can hold a call
by such a name: a model another provider served wrote one with a space,
a colon or non-ASCII in it, and the agent kept it beside its "no such
tool" answer. Every request that replayed it, the compaction above all,
then failed on Codex. Nothing on the way checked: buildResponses copies a
call's name as it is, and redaction keeps names as written.

What changed:
- provider.CodexToolName: a valid name stays as it is. Otherwise each
  refused byte becomes "_", the result is cut to 55 and gets "_" plus 8
  hex of its sha256, so it is the same on every request and two names
  never meet. CodexToolNames applies it to tools (namespace children
  too), function_call/custom_tool_call items, additional_tools and
  tool_search_output items, and tool_choice. A body with no bad name goes
  byte for byte.
- It runs where every request to the ChatGPT backend passes: codexBody
  (an account's, translated or relayed) and codexUpstreamOn (Codex's
  own sign-in, /responses and /responses/compact), beside DeclareSearch.
- A tool the agent declared under such a name is called back by its own
  name: translated replies through decoderFor (now given the request's
  tools; codexNamesBack), relayed Responses replies through nsTidy's new
  back map (codexRenamedIn).
- docs/subsystems/gateway-routing.md says so beside #1270's paragraph.

Not covered: namespaces, the OpenAI API (whose pattern has no "." and a
64 limit), Azure and Copilot Responses, filed as #4875.

Run on mote at this head:
- TestCodexToolNamesTheBackendTakes and TestCodexToolNamesKeepValid
  pass. The fake backend refuses a bad name with the reporter's 400 word
  for word; the test covers Claude Code's compaction on /v1/messages with
  four bad history names (sent twice, byte-equal), Chat with a declared
  "search:web" called back by that name, Responses relayed the same, and
  Codex's own /backend-api/codex/responses.
- go test ./internal/provider ./internal/gateway (-timeout 45m): provider ok;
  gateway ok but TestCodexPoolSaysTheClientsVersion, the red already
  filed as #4807 (full package run only, another test's Codex identity
  reaches it); it passes alone at this head.
- go vet ./... (darwin) and GOOS=linux/windows CGO_ENABLED=0 go vet
  -tags nogui ./...: ok. gofmt -l: clean.

Broken by hand:
- codexBody hook off: compaction red with the reporter's 400.
- codexUpstreamOn hook off, decoder restore off, passthrough restore off
  (together): the codex, chat and responses cases each red.

Not tried: wing3556's real conversation (we don't have its bytes, and
the agent is unknown; Claude Code is likely). No real ChatGPT account
was asked with a bad name, so whether the real backend also limits
length is unknown.
2026-11-02 15:15:21 +08:00
ggbdpq dd809ea60f gateway: an input item's id longer than the 64 an upstream that checks ids takes goes shorter, as its kind's prefix and the sha256 of the whole of it (#4525, #4527)
Codex carries every id an earlier turn came back with, and Copilot
gives its items ids hundreds of characters long: 420 as isnine's
sessions each showed (#4525), 444 as ghjkllasdf-fake's approval
session and its guardian review did (#4527), all of the characters
OpenAI takes an id of. plainItemIDs checked the characters only, so
every later turn went to Copilot as it came and was turned away
400 "Invalid 'input[N].id': string too long. Expected a string with
maximum length 64, but got a string with length 420 instead." — the
conversation stuck, a tool call never answered, Codex's automatic
approval review failing over it.

An id longer than the 64 goes as its kind's prefix ("msg_", "rs_")
and the sha256 of the whole of it, cut to fit: the same id to the
same shorter one every turn, and no two ids land on one, where a
plain cut could (ids of a vendor can begin alike). Copilot's own
reasoning, overlong but of the right characters, keeps its place
with its seal — an upstream that checks ids made that one, its
encrypted_content is its to read, unlike another vendor's, which
still goes as it did. A call's call_id was bound already
(BoundCallID); one shorter than 65 goes as it came.

What changed

- gateway: itemIDCap (64) and boundItemID, and plainItemIDs bounds
  an input item's id at them, on every relay that checks ids as
  OpenAI does — Copilot's /responses among them (validatesItemIDs)
- tests: an id checker that turns an overlong id away word for word
  as isnine got it; Codex's turn over a Copilot conversation of
  overlong ids asked twice, the same bound each turn; the 64/65
  boundary, determinism, idempotence, two ids that begin alike going
  to two; the parity harness holding plainItemIDs to it beside what
  it was

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-02 05:38:10 +08:00
yetone cbfbcb383b usage: a lead's answers are looked up in the blocks that name its conversation (#4370)
loggedAnswers, which leadFirst falls back to when affinity has lost a
Codex subagent's lead, read thirty days of the log into a Record a row
and kept the rows of one conversation. usage.VisitSessions reads only
those rows: a block whose Session and NativeSession strings don't name
the conversation is skipped, a row of another session is passed over by
its shape's string ids without becoming a Record, and a matched row's
strings are cloned out of the lent decode buffer. Each packed block's
sessions are kept once it is decoded (blockSessions, by weak pointer, so
no block the log let go is held), so a lookup decodes only the blocks the
conversation is in and the open tail. A page's copy with Codex
identities (which rewrite Session as a row is read) is read whole and
filtered on its records.

Run on mote (macOS 27.2), at load ~70:
- BenchmarkLeadLookup (40 blocks of 3000 rows, one conversation of 300):
  visit+filter 39-56ms and 2.9MB an op; VisitSessions 0.38-0.52ms and
  12KB.
- A copy of the owner's real usage.jsonl (8,853 rows, 1,270 sessions,
  18 blocks): every session looked up both ways gives the same records;
  6.9ms a lookup before, 3.4ms for the first and 0.39ms after, 14us for
  a conversation that isn't there.
- TestVisitSessionsIsVisitOfThoseSessions, red with the shape filter's
  session ids taken out; TestVisitSessionsRecordsKeepTheirStrings, red
  with the clone taken out; TestVisitSessionsSkipsBlocksOfOtherSessions,
  red with the known-sessions skip taken out.
- GOOS=windows go vet; GOOS=linux -tags nogui go vet: ok. gofmt -l: clean.
- go test -race of the new tests and the gateway tests of a lead's
  answers, in internal/usage and internal/gateway: ok (4.4s, 31.3s).
- go test ./internal/usage ./internal/gateway (whole packages) was
  still running on mote at load ~190 when this was pushed; its result
  goes on #4370.

Not tried: a real Codex subagent whose lead lost affinity; the lookup's
callers and filters are as they were, and the gateway's loggedAnswers
tests cover them.
2026-11-01 18:33:53 +08:00
yetone 2be5d206e1 gateway: a Codex summary request too large for the vendor is asked again as text, then compacted locally (celestial_eagle_99230 on Discord)
celestial_eagle_99230 (Discord #general, v0.1.2403) runs Codex on official
DeepSeek (DeepSeek-V4.1-Flash, 1M window) and gets "413 Request Entity Too
Large: Failed to buffer the request body: length limit exceeded". The turn
path was fixed by 2cca11176 (v0.1.2419): Codex gets context_length_exceeded
and compacts. But the compaction is the problem. Codex (openai/codex main,
compact_remote_v2.rs) sends its summary request through the same /responses
route, trims only by its token estimate against the catalog's 1M window, and
on ContextWindowExceeded does not trim and retry. A conversation that is
over DeepSeek's byte cap (base64 images and long tool outputs sent each
turn) is under 1M tokens, so the summary request was the same oversize
body. magpie passed the 413 (or overflow) back, compaction failed each
time, compactFails held later tries, and the session could neither compact
nor go on.

codexCompact now counts a 413 or an overflow on the summary request
(summaryTooLarge) with the failures it already asks again as text
(plainCompact: images left out, tool outputs over 4000 chars cut, at most
400K chars), then compacts without a model (localSummary) when that is
refused too. This is keyed on the status and overflow words, not on
DeepSeek: a summary request refused for its size means the same thing for
every vendor, and the old result (a session stuck) is never better. Any
other refusal goes back unchanged (TestCodexCompactOtherRefusalStays,
TestCodexCompactOtherFailuresStay), and a non-Codex client still gets the
413 as request_too_large (TestDeepSeekByteCapTurn's opencode case,
TestByteCapBeforeStreamStaysStatusForOthers).

DeepSeek probed without a key (no tokens): bodies of 1 to 40MB to
api.deepseek.com/chat/completions get 401 "Authentication Fails"; 80MB and
120MB get openresty's text/html 413 page. The reporter's text is axum's
body-limit error, which sits behind auth, so its value is unknown. DeepSeek's
docs list no 413 and no byte limit.

Run, mote (mote-run):
- Red at origin/main fb3942ee6 with only the new test file:
  TestCodexCompactTooLargeAsksSmaller (all 4: Chat/Responses x byte
  cap/overflow) got 413 "compaction: ... answered the summary request 413"
  or 400 context_length_exceeded; TestCodexCompactTooLargeCompactsLocally
  got 413. TestDeepSeekByteCapTurn passed (2cca11176's turn path).
- Green with the fix; broken by hand (summaryTooLarge returning false):
  all 4 AsksSmaller subtests and CompactsLocally red again.
- At the pushed head (rebased on 90c02326b): go test -count=1 -run
  'Codex|Compact|Overflow|ByteCap|TooLarge|DeepSeek|StreamError'
  ./internal/gateway ok (90s). go vet ./internal/gateway on darwin,
  GOOS=linux -tags nogui and GOOS=windows ok. gofmt -l clean.

Not tried: the whole internal/gateway package and ./... (mote was running
another session's 45m multi-package suite at load ~210, and one suite runs
at a time); a real Codex binary end to end (its compaction was read from
source); a real signed-in DeepSeek request (the cap's value is unknown).
2026-11-01 11:52:46 +08:00
yetone e4384fc3cd gateway: a Codex stream cut inside a line still has its failure read (#3377)
#3377's patch writes response.failed when the upstream cuts a Codex
stream mid-reply. When the cut lands inside a line, the half line was
still open, so the events streamError writes were read as more of that
line's data and the client never parsed the failure. A blank line now
goes first, ending the half event (as #2446 and #2580 do on the other
relays).

TestCodexStreamCutMidLineFailureParses cuts the stream inside a delta's
data and checks every event the client reads parses, apart from the half
line itself, and that response.failed is among them.

Landing record (yetone):
Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: the blank line removed:
TestCodexStreamCutMidLineFailureParses goes red; restored, green.
Not tried: a real cut inside a line from chatgpt.com.

#3377's patch writes response.failed when the upstream cuts a Codex
stream mid-reply. When the cut lands inside a line, the half line was
still open, so the events streamError writes were read as more of that
line's data and the client never parsed the failure. A blank line now
goes first, ending the half event (as #2446 and #2580 do on the other
relays).

TestCodexStreamCutMidLineFailureParses cuts the stream inside a delta's
data and checks every event the client reads parses, apart from the half
line itself, and that response.failed is among them.

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: the blank line removed:
TestCodexStreamCutMidLineFailureParses goes red; restored, green.
Not tried: a real cut inside a line from chatgpt.com.
2026-11-01 06:38:01 +08:00
yetoneandEdward4226 cbefb65987 gateway: a compaction summary answered 502 for ending short compacts locally too (#3526)
#3526's patch compacts locally when the summary ask ends short with an
error. The same cut can come back as a recorded 502 whose error says it
ended short (errEndedShort), with no error returned, and that still went
to the client as a 5xx. The local fallback now runs before the status
check, for both shapes (summaryEndedShort), and says why from the
recorded error. A 502 that says anything else still goes to the client
as it did. Edward4226 pointed at the 502 shape in the thread.

TestCodexCompactCutShapesCompactLocally covers a stream error, a 502
saying it ended short (compacts locally) and a 502 saying more (stays
502).

Landing record (yetone):
Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: summaryEndedShort made to return false: the "HTTP 502"
subtest goes red; restored, green.
Not tried: a real ChatGPT summary ask answered 502.

#3526's patch compacts locally when the summary ask ends short with an
error. The same cut can come back as a recorded 502 whose error says it
ended short (errEndedShort), with no error returned, and that still went
to the client as a 5xx. The local fallback now runs before the status
check, for both shapes (summaryEndedShort), and says why from the
recorded error. A 502 that says anything else still goes to the client
as it did. Edward4226 pointed at the 502 shape in the thread.

TestCodexCompactCutShapesCompactLocally covers a stream error, a 502
saying it ended short (compacts locally) and a 502 saying more (stays
502).

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: summaryEndedShort made to return false: the "HTTP 502"
subtest goes red; restored, green.
Not tried: a real ChatGPT summary ask answered 502.

Co-authored-by: Edward4226 <234070868+Edward4226@users.noreply.github.com>
Co-authored-by: Edward4226 <234070868+Edward4226@users.noreply.github.com>
2026-11-01 06:38:01 +08:00
ggbdpq 5b63dfd1a8 gateway: a Codex stream the upstream cut mid-reply is told to the client as its failure, and the row says why (#3377, Azir-11)
The ChatGPT backend cut every relayed stream about two minutes into the reply (121-125s, deltas flowing to the end): no response.completed, no error event, no usage, and Codex read a bare EOF, "stream disconnected before completion". Nothing in magpie bounds a stream that way — the gateway's client sets no Timeout, the upstream transport's only waits are ResponseHeaderTimeout (10 minutes, to the headers) and IdleConnTimeout (idle connections alone), the server sets no WriteTimeout, and the body's read deadline is dropped once the body is read — so the relay passed the cut on as it came, and was silent about it: the client's stream just ended, and the usage row recorded a clean 200 with nothing of why.

Now a relayed stream that ends mid-reply — SSE, no failure said, no last event reached, the client still there — is answered with the stream's response.failed saying how long it had gone and that the reply is lost, and the row records the 502 with it. What magpie cannot do is keep the upstream talking past its cut: the wall itself stands on the magpie-to-chatgpt.com leg (the reporter's direct Codex ran 480s and 719s on the same machine and network), and telling it apart is what the honest failure is for.

TestCodexStreamCutToldTheClient fails without the change: the fake upstream ends its stream after one delta, and the client heard no failure and the row said 200. go vet clean; go test -tags nogui ./internal/gateway/ passes in full.

Landing record (yetone):
Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: gua's (TestCodexStreamCutToldTheClient red without the
change). The mid-line case is broken by hand in this batch's #3377
follow-up.
Not tried: a real two-minute cut from chatgpt.com. magpie cannot keep
the upstream talking past it; this only makes the client and the row say
it happened. Codex's identity line and prompts are unchanged.

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: gua's (TestCodexStreamCutToldTheClient red without the
change). The mid-line case is broken by hand in this batch's #3377
follow-up.
Not tried: a real two-minute cut from chatgpt.com. magpie cannot keep
the upstream talking past it; this only makes the client and the row say
it happened. Codex's identity line and prompts are unchanged.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 06:38:01 +08:00
ggbdpq 6f041c292c gateway: a Codex compaction relayed to a vendor that isn't OpenAI's asks as system, not developer (#2955)
forVendor, the fitting a relayed Responses request gets before it goes to
a provider that isn't OpenAI's, now turns the developer messages of a
summary ask magpie made itself (codexCompact) into system ones, where
they stand (developerItemsAsSystem). Codex's own turns keep the role the
client sent, which a relay may be checking them by (#350, #1758), and
OpenAI's own API and the ChatGPT backend, which take developer as Codex
sends it, get the compaction as it came too.

Why: on a provider whose Responses endpoint fronts a chat-only vendor (a
relay of one; DeepSeek's preset names one base for chat and responses
alike), every Codex compaction failed there with 400 "developer is not
one of ['system', 'assistant', 'user', 'tool', 'function']", retried five
times, while the turns around it passed: the summary request is relayed
as Codex sent it (tools: [], #378), and the compaction carries a
developer message its turns don't. The translated route already lifts
such messages into the system prompt; the summary ask now says them as
system on the relayed route too, in place, so a thread's cached prefix
keeps its shape (#502) — what Zed's cloud is already given (ZedBody) and
what a Chat Completions upstream is given (developerAsSystem).

Run: TestCodexCompactDeveloperAsSystemOnAVendorRelay (red before, green
after; ablated and mutated), the compaction families (TestCodexCompact*,
TestLocalCompaction*, TestNativeCompaction*, TestVendorRelay*,
TestAdditionalTools*, TestCodexOpenAIFields*), the full gateway package,
-race over the families, go vet and go build of the package on darwin,
linux and windows.

Refs #2955

Landing record (yetone):
Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: developerItemsAsSystem made to return the body
unchanged: TestCodexCompactDeveloperAsSystemOnAVendorRelay goes red with
the fake vendor's 400 "developer is not one of"; restored, green.
Not tried: the reporter's vendor relay itself; the refusal is the fake
vendor's copy of its words.

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: developerItemsAsSystem made to return the body
unchanged: TestCodexCompactDeveloperAsSystemOnAVendorRelay goes red with
the fake vendor's 400 "developer is not one of"; restored, green.
Not tried: the reporter's vendor relay itself; the refusal is the fake
vendor's copy of its words.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 06:38:00 +08:00
ggbdpq 78632d4b84 gateway: a Codex compaction cut short with no candidate left compacts locally (#3526, Edward4226)
A summary wanted whole whose stream every candidate broke off reached
codexCompact as an error none of its fallback conditions name: not a
404, not an unreadable item, not "Upstream request failed", not
"response protection is unavailable". The relay ends such a stream with
a response.failed event saying "the reply ended before it was complete"
(#2274), and with nobody left to fail over to, that error fell out of
the 404/protection family and went to Codex as a 502. Codex asked the
same huge summary over, three times, each paying for the whole
conversation, until compactFails answered 400 and held it: the
conversation could neither compact nor go on. That is the no-candidate
case #2274 left, after it made a cut summary fail over where there was
someone to fail over to.

The summary is magpie's own then, as when no model can be asked at all
(#866, #1008, #1270 end so). The summary as text isn't tried either:
the cut was in what the model wrote, not in what it was asked, and that
would be another ask of the same huge prompt. The words before the cut
are never taken: the local summary is built from the request's own
items. A summary that failed halfway, or ended incomplete — the output
limit's own event — is still told to Codex as it came and still counts
the guard; only the bare break-off turns local. 401, 403, 429 and
request-shape refusals are untouched.

Run: TestCodexCompactCutAloneCompactsLocally (new) is red on the parent
with the issue's 502 ("the reply ended before it was complete, so there
is no summary") and green here — 200, one magpie compaction holding the
local handoff, the cut stream's words in none of it, the last ask the
fake saw still the original summary request (no plain-text retry). The
#2274 tests keep their shape: TestCodexCompactCutSummaryFailsOver (a
whole fallback summary still wins) green unchanged;
TestCodexCompactCutSummaryIsNoSummary now covers the halfway and
incomplete shapes alone (the cut one moved to the new test);
TestCodexCompactKeepsFailingIsHeld holds on the incomplete shape, which
still fails and rests nobody. Ablation: only codex_backend.go put back
to the parent, tests kept — the new test is red again, restored, green.
go test -tags nogui -p 2 -count=1 ./internal/gateway: ok (350.8s).
Targeted TestCodexCompact with -race -count=2: ok. ./internal/usage:
ok. gofmt -l clean; go vet -tags nogui on darwin, linux and windows
clean; CGO_ENABLED=0 go build -tags nogui on all three ok.
docs/subsystems/gateway-routing.md says the new terminal state.

Refs #3526

Landing record (yetone):
Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: gua's ablation (codex_backend.go back to its parent: the
new test goes red). The 502 shape is broken by hand in this batch's
#3526 follow-up.
Not tried: a real Codex compaction whose every candidate is cut short;
the cut is the fake upstream's.

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: gua's ablation (codex_backend.go back to its parent: the
new test goes red). The 502 shape is broken by hand in this batch's
#3526 follow-up.
Not tried: a real Codex compaction whose every candidate is cut short;
the cut is the fake upstream's.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 06:38:00 +08:00
yetone bb50f4ad94 gateway: a Codex passthrough member OpenAI doesn't know is left out and asked again
xuanwo on X: every new conversation in the Codex app (two agents) ended
at once with the ChatGPT backend's 400 "[ObjectParam]
[input[55].internal_chat_message_metadata_passthrough.content_token_count]
[unknown_parameter]". The member is new in the Codex app's bundled
build; no open-source Codex sends it (main 67f0994, npm 0.166.0), and
openai/codex#52313 was the same refusal of content_item_metadata in
0.163.0-alpha.1. magpie sends the passthrough as Codex wrote it to
OpenAI hosts and ChatGPT accounts (forVendor), so the refusal reached
the app. The reporter's own look at magpie's routing log: the main
conversation failed at input[49] and input[55], and a conversation
with no subagent failed the same way, so subagents aren't the cause.

The member is Codex's own attribution, not the conversation. A turn
turned away over one passthrough member, or the passthrough as a whole,
is asked once more without it on every item, with the other members
and every other byte kept as written. The provider isn't sent that
member again (unfit, as for a tool's strict). The signed-in Codex
relay's retry (withoutUnreadable) takes the same refusal.

Run (mote, go1.26.8):
- TestPassthroughMemberLeftOutWhereRefused, TestPassthroughRefusalWordings,
  TestWithoutPassthrough: ok.
- Broken by hand: with the retry turned off, TestPassthroughMemberLeftOut
  WhereRefused gets the reporter's exact 400 back.
- At d714c4216 + this: gofmt clean; go vet ./internal/gateway on
  darwin, linux and windows ok; go test ./internal/gateway -run
  'Passthrough|ToolStrict|Unreadable|Optional|LiteSubagent' ok.
- The whole internal/gateway package was still running at push (the
  owner's ship-at-once rule); its result is not in this record.

Not tried: the reporter's Codex app build. Its content_token_count isn't
in any build that can be downloaded, so the fixture is the refusal text
from their screenshot.
2026-11-01 03:45:10 +08:00
yetone 9551fadcb4 gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic
thinking deltas) while its usage counted no reasoning tokens was
recorded Reasoning 0, ReasoningHidden false: the same record as a reply
that never reasoned, and a tool-only one was timed with its reasoning
counted as answer. hidesReasoning now takes the usage's reasoning count
and marks such a reply ReasoningHidden, the record's existing "the
stream doesn't tell how much it reasoned". Reasoning stays the vendor's
0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden
512 is the one it already uses).

Who does this, from real bytes and docs: Anthropic's Messages usage has
no thinking count at all (output_tokens includes it), so every visible
Anthropic-protocol thinking reply was this case. The fixture
testdata/reasoning-uncounted-deepseek-anthropic.sse is DeepSeek's
Anthropic endpoint as it came on 2026-10-31 (deepseek-v4-pro, thinking
on): 33 thinking deltas, "391", usage output_tokens 35 and nothing else.
The owner's usage.jsonl has 12 kiro claude-haiku-4.5 rows with paced
first_reasoning_ms and reasoning 0, the same case through a plugin.
DeepSeek's Chat endpoint does count (completion_tokens_details), and
those rows are unchanged. No captured Chat vendor omits the count; the
Chat subtests are built from the shape, not a capture.

Siblings: Responses, Gemini and Code Assist were already marked hidden
whenever reasoning streamed (summaries). The Codex backend's two calls
pass its count too (no change for Responses; its call record now reads
the count after the sniffed usage is added). The Claude subscription
bridge counts thinking from the CLI and is unchanged.

What changes for a reader: Decode already leaves a hidden reply with no
text untimed, so a thinking + tool-call reply with no count tells no
speed now; one with text is timed as before (whole output from first
content). The GUI's decodeOf/ledDecode read the same flag; no GUI code
changed.

Run on mote at base d0a61b856, then again after rebasing onto
origin/main f1d0c0bfd (gateway and usage packages, gofmt, vet). Pushed on 5174c0970,
which changes only GUI files after that run:
- go test -tags nogui -timeout 45m -count=1 ./internal/gateway/...
  ./internal/usage/...: ok gateway 612s, ok usage 41s; at the
  rebased tree ok gateway 593s, ok usage 42s
- TestStreamedReasoningWithoutCount with the counted check taken out of
  hidesReasoning by hand: red in 4 of 6 subtests (anthropic, chat from
  anthropic, chat tool uncounted, anthropic from chat tool uncounted);
  green restored. "responses from anthropic" was already hidden on the
  old code (the translated Responses stream carries encrypted_content).
- gofmt -l internal/gateway internal/usage: clean; go vet for darwin,
  GOOS=linux and GOOS=windows on both packages: ok.
- node --test reasoning-speed.test.cjs usage-speed-every-row.test.cjs
  (Chromium and WebKit, five languages) on the Linux VM (wsl-run): 16
  pass, 0 fail. On mote the same run had 8 TimeoutErrors at load ~25,
  beside four other sessions' whole GUI suites running 18 to 30 hours;
  no GUI code changes here.

Not tried: a real Claude API key (Anthropic's own endpoint) and Zhipu,
vLLM or Ollama Chat streams; no full go test ./...; no Windows or Linux
run of the tests.
2026-10-31 17:46:51 +08:00
yetone 0956ca49d7 gateway: Codex's own sign-in asks again after a connection dropped with no reply
aetrox333 on Discord: on Codex, bare gpt-6-luna and gpt-6.1-terra
failed with 502 "OpenAI can't be reached (Post …: EOF)" after 43ms
every time, through a fake-IP proxy (chatgpt.com at 198.18.0.12),
while auto/gpt-6-luna and auto/gpt-6.1-terra answered 200 every time.

Cause: a bare Codex model goes to ChatGPT on Codex's own sign-in
(codexUpstreamOn), which ended the turn with 502 at the first transport
error. Go's transport sends a POST again by itself only on a reused
connection (replayable, #2136), so an EOF on a fresh one, a proxy
closing it before a byte of a reply, came straight back to Codex.
auto/ and codex/ go through the accounts loop, which takes the same
502 as passing and asks again after a pause on a new connection, or
asks the group's next member. Both routes share one client, transport,
proxy choice and HTTP/1.1; a recorded diff of the two requests showed
no difference that would change how a proxy treats them (the routed
one adds instructions, Openai-Beta, Session-Id and its own token).

Now a dropped or reset connection with no reply on the own sign-in's
/responses is asked again, retryPause<<n apart, up to lastRetries, as
an overload is (askAgain: the trace shows each try, Codex is kept
alive). The caller gone and a wait that ran out are not asked again.
After the last try Codex is told OpenAI can't be reached, as before.

Run (mote, at this head rebased on dca1d138c): gofmt -l; go vet
./internal/gateway on darwin, linux (-tags nogui) and windows;
go test ./internal/gateway -run 'Codex|Overload|Busy|Retry|Unreach|Socket'
ok 54s; the two new tests -count=3 ok.

Broken by hand: with the new branch turned off,
TestCodexOwnSignInAskedAgainAfterEOF fails with the reporter's exact
text ("OpenAI can't be reached (Post \"…/backend-api/codex/responses\":
EOF)"), and TestCodexOwnSignInEOFTold sees 1 try, not 3. The codex/
case in the first test passes on the old code too (the accounts loop
asked again already), which is the asymmetry reported.

Not tried: the real ChatGPT backend through a real Clash/Surge TUN
proxy; why the reporter's proxy drops the first connection is not
known, and a proxy that drops every connection still ends in 502 (now
after three tries). Whether the reporter's auto/ 200s came from Codex's
sign-in on a second try or from another member of the group is not
known. Magpie's own ChatGPT accounts relayed on this path (on != nil)
and the API-key route are left as they were; the full suite runs after
the push.
2026-10-31 11:55:55 +08:00
yetone b62fa332f3 provider: Send requests unmasked for subscriptions and plugin providers too (isee1_1)
isee1_1 on Discord uses a community translation plugin as a provider and
asked why "Send requests unmasked" (请求不脱敏) isn't offered for it.
698da36f3 (lc) left a signed-in account, a plugin's provider and another
magpie out because the switch was then for local addresses only, and none
of those is local. 380032cda (AcMilan) made it the user's word at any
address, with a caution while on for one not local, but kept the
exclusion. Nothing still stands behind it for a subscription or a plugin:
the setting lives with the account's model picks, and every route reads
SkipsRedaction. Another magpie stays excluded, as it masks on its own side.

- provider.SkipsRedaction: an account (subscription or plugin) skips when
  set; another magpie never. Save keeps Unredacted in the picks record,
  withPicks applies it (AlsoOn accounts too).
- gateway: serve, count_tokens, embeddings, Jev and the plugin's fetch
  already go by unredactedRoute (every fallback and group member must be
  set too). The Codex relay on a ChatGPT sign-in masked always: it now
  sends the turn whole when the Codex subscription is set
  (codexRouteUnmasked; only for the ChatGPT backend, not the Codex API
  key route), codexMaskRoute stands aside then, and ChatGPT web search
  (alphaSearchOn) goes unmasked only when every provider it is on is set.
  Speech and video stay masked whatever the switch (maskTextHits), as
  before, for every provider.
- GUI: the editor's Redaction row is shared (unmaskRow); a subscription
  or plugin provider has it too, its caution naming the provider while
  on, since its vendor is never local; saved with the account's body.
  Another magpie has none. No new strings; app.js stays in its budget.
- CLI help/show text, gateway-routing.md and the masking docs (en, zh,
  ja) say so.

Run (mote, through mote-run):
- go test ./internal/provider ./internal/cli: ok
- go test -timeout 45m ./internal/gateway: ok (676s)
- go test -run 'Budget|Redact|Unmask|I18n' ./internal/gui: ok
  (TestCoreScriptBudget at +45 bytes)
- GOOS=linux go vet ./internal/gateway ./internal/provider, GOOS=windows
  go vet ./internal/gateway ./internal/provider ./internal/cli: clean
  (GOOS=linux vet of internal/cli fails in wails without cgo, as on main)
- node --test provider-unmasked (chromium): 36/36; i18n-keys: 4/4.
  WebKit on mote can't launch (#4125); WebKit ran through wsl-run:
  the whole file in chromium and webkit, 72/72. At 440 in Linux WebKit
  the list's sticky foot covers the last row (another magpie's), so the
  test clicks that row as an event (#4484).
- gofmt -l: clean

Broken by hand:
- SkipsRedaction's account branch back to false: TestSkipsRedaction
  (an account, a plugin's provider), TestPluginProviderUnmaskedSwitch/set
  and TestCodexSignInUnmaskedSwitch/set go red.
- Unredacted dropped from Save's account whitelist: the plugin test's
  "saved as" goes red.
- codexRouteUnmasked forced off: TestCodexSignInUnmaskedSwitch/set red.
The unset and falls-back-to-a-vendor cases stay masked in each.

Not tried: a real plugin provider or a real Codex/Claude account with
the switch on (fakes only: the fake bun plugin and a fake ChatGPT
backend); the Claude bridge path; the full Go and GUI suites run after
the push.
2026-10-31 02:56:49 +08:00
yetone dafe4af822 gateway: the ChatGPT backend's "auto"/"default" tier is recorded as unknown (jjt on Discord)
The ChatGPT Codex backend says service_tier "auto" in response.created
and "default" in response.completed whether priority ran or not. jjt's
measurements on gpt-6.1-sol with a Plus account: Fast decodes at about
200 tok/s, without it about 110, and the reply says "default" both times
(real-priority.sse, speed-plus.txt). magpie copied that into tier_served,
so the usage log, its CSV and /v1/magpie/route said served = default for
requests that ran Fast.

servedTierAt (tier_record.go) leaves those two words empty when the
reply came from CodexBase's host. It is applied once per routed try, in
attempt (gateway.go, a defer, so every return path and the route's tries
see it), and on the relay of Codex's own sign-in (codexUpstreamOn).
OpenAI's API, where service_tier means what it says, keeps it as given:
a provider at api.openai.com and Codex with an sk- key relayed to it.
"priority" or "ultrafast" said by the ChatGPT backend is still kept.

Display: tier_served is shown by the CSV (an empty cell), the JSON log
and /v1/magpie/route (omitempty). No GUI page or TUI shows a tier
(grep of internal/gui/assets and internal/tui for tier_served,
tier_asked, tierServed: none), so no strings changed. docs/reference.md
and docs/subsystems/gateway-routing.md say it.

Tests:
- TestChatGPTBackendTierUnknown (new): the backend says auto, then
  default (jjt's events, cut to the fields read); a routed try asked
  priority and one asked nothing, and Codex's own sign-in relayed, all
  record "" in usage and the route.
- TestOpenAIAPITierKept (new): api.openai.com's "priority" and
  "default" kept, routed and through the sk- relay.
- TestTierRecordedPerTry: its "none asked" case on the ChatGPT backend
  now expects "" where it expected "default".

Run on mote (mote-run; the wider run at base cc81ad4ea, the tier run
again after the rebase, at this commit on c37b8b659: ok, 22 pass):
- go test ./internal/gateway -run 'Tier|ChatGPTBackend|OpenAIAPI'
  -count=1 -v: ok, 22 tests pass.
- go test ./internal/usage: ok. go test ./internal/gateway -run
  'Codex|Usage|Route|Tier': two reds, TestAntigravityTurnsCodexs-
  GPT5ThreadAwayOnce and TestCodexSpentGrokFailingIsTold, red the same
  on a fresh origin/main c37b8b659 and filed as #4362; the rest ok.
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: clean.
- gofmt -l internal/gateway: clean.
Broken by hand: servedTierAt returning t unchanged -> TestChatGPT-
BackendTierUnknown and TestTierRecordedPerTry red ("served default");
the host check removed -> TestOpenAIAPITierKept red (served "", want
"default"). Both green again with the fix.

Not tried: a real ChatGPT account through the built gateway; the full
Go suite (the coordinator asked for the targeted run under mote's load
of ~200); Windows and Linux test runs (vet only). No GUI file reads the
tier, so no GUI test was run.
2026-10-30 13:57:36 +08:00