Commit Graph
219 Commits
Author SHA1 Message Date
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
yetone 7632e1be1d redact: a text sent on a route goes on it as it went, the model's late finds too (vvrfxyz on X)
vvrfxyz on X: "脱敏功能是不是会降低缓存命中率 我开了脱敏后 dsh命中率暴跌".

Cause: the local model (AstrLink Guard, on by default) is waited for
2s a request (masking's defaultWait). A tool's output it hasn't read
by then goes with the rules' masking alone (pii.Partial). On the next
turn the model has read it, finds the names in it, and the same history
text now goes with {{PERSON_…}} in it. Everything from that message on
is a new prompt to the vendor, so its prefix cache misses. 50f52b540
(10-23) kept the known values of a text sent before as they went, but
not the model's finds.

Reproduced with real dsh 0.2.1-rc.2 (headless profile, sandbox HOME):
three turns in one session (read team.md, customers.csv and
notes/standup.md; check contracts.md; summarise the customers) through
a sandbox magpie with masking and the default model on, to a recording
Chat Completions upstream. dsh's own request bodies were recorded and
replayed in order, 3s apart, through a fresh sandbox magpie (found
cache cleared) on Linux (WSL2 magpie-desktop, -tags nogui).
- Old (origin/main without this change): "the local model read 5 of a request's
  7 texts in 2s". At request 7, message 6 (customers.csv's tool output)
  changed at byte 252: "1000,Fatima Rossi,Client 0 GmbH" became
  "1000,{{PERSON_2rmvxto6}},Client 0 GmbH". 4,793 of that request's
  18,380 history bytes were sent as before (26%). Over the whole
  conversation 97,815 of 111,402 resent bytes (87.8%) were the same.
  It happened on both runs.
- New: 108,378 of 108,378 (100%), the same Partial in the log.
- On mote (M5 Pro, CoreML) the model read everything inside 2s. Old
  code kept 100% of the prefix over the same 3 turns, and after a
  restart of magpie too (suspect 3, the key and the in-memory maps,
  was not the cause). Suspects 1 (known values) and 4 (re-encoding)
  were not the cause either: every other request kept its prefix byte
  for byte.

Fix:
- redact: sentKnownSpans becomes sentSpans. It remembers, per text and
  options, both the known values and the model's finds the text first
  went with (sentModel, sentKnown). The key now includes Options.Route,
  and for the model also the threshold, whether there is a model, and
  NamesByModel.
- learnLate: what the model finds in such a text since is made known
  (placeholder, scores) without being put in the text, so new text has
  it masked as before.
- The gateway gives masking each request's route (maskedFor,
  masking.WithRoute): the providers its model, the model's fallbacks or
  a group's members are served by, the same set unredactedRoute walks.
  Codex's own sign-in passes "codex", or the account's provider.
- A request with no route (search, embeddings, a text prompt) keeps
  the model's finds of now, and its known values as before.

Trade-off: a name the model reads late in a text sent before keeps
going as written on that route. That route's vendor was sent it as
written already. Within a route of several providers (fallbacks, a
group), a member that wasn't the first to get it may be sent it in
that form, as it could have been on the first turn's failover. In the
Linux replay, customers.csv's ~110 names stay as written on later
turns, where old code masked them from turn 2 on. The new turns'
masking is unchanged (the same placeholder counts in messages 9, 12
and 14). Another route, never sent the text, gets it masked with what
is known and found now. That is stricter than before for known values,
which were kept whatever the vendor. The alternative, waiting for the
model before any text goes, is what defaultWait was cut to 2s to stop
(shensmart, 10-28).

Tests:
- TestModelReadingLateKeepsTheSentPrefix (internal/masking): a model
  that reads a text only after its first request. Turn 2's history must
  be byte-identical, the name masked in new text, and masked on another
  route and with no route.
- TestMaskedPrefixKeptOnlyOnItsRoute (internal/gateway): a system
  prompt kept as written on its provider, masked on another.
- Broken by hand on mote, each red:
  - sentModel not remembered: "turn 2 rewrote message 2";
  - learnLate removed: "the new turn has the name the model found as
    written";
  - maskedFor returning ctx without a route: "another provider, never
    sent it, got the value as written".
  Each was green restored. TestMaskedConversationKeepsItsCachedPrefix
  and TestSentTextKeepsItsMasking stay green.

What was run, at this commit on origin/main 4b4c4a806, on mote
(after rebasing on e863f520c, which touches internal/gateway: gofmt, vet
of gateway/masking/redact, redact and masking whole, and gateway -run
"Mask|Redact|Sent|Effort|Route" ok again):
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
- Targeted at this head: go test ./internal/redact ./internal/masking
  ./internal/gateway (ok), with the two new tests and
  TestMaskedConversationKeepsItsCachedPrefix, TestSentTextKeepsItsMasking.
- Full suite (go test -timeout 45m ./...) was still running on mote at
  push (load ~110, other sessions), pushed per the ship-at-once rule; its
  result goes on the release and any red gets its own issue.
- GUI suite not run: no GUI file, API or string changed.

Not tried: vvrfxyz's own machine and vendor (DeepSeek's real cache_hit
counts), and Windows.
2026-10-30 10:26:50 +08:00
yetone ffa07395eb gateway: Codex talks Responses to magpie over a WebSocket, turns after the first as a delta (#4058)
Codex names previous_response_id and sends only the new input on its
WebSocket path alone; magpie answered the upgrade 426 (a87dc1ff2), so
Codex fell back to HTTP and re-sent the whole conversation, images
included, every turn (kevinzhow and neighbads on X).

/v1/responses, /responses and /backend-api/codex/responses now accept the
socket (responses_ws.go), with Codex's protocol (codex-rs 2f1e4f9,
responses_websocket.rs):
- each response.create frame is replayed as the POST it stands for through
  the outermost handler the upgrade came in on (socketEntry wraps Front and
  Handler), so the allow list, rebound Host check, key, corsGuard,
  keyLimited, routing, failover, usage and log judge every turn;
- previous_response_id resolves to the socket's own last two replies
  (input + output items); the provider gets the whole conversation, so a
  switch of account or provider mid-chain loses nothing. An id the socket
  doesn't hold is previous_response_not_found (Codex reconnects with
  everything);
- generate:false (warmup) is answered locally; response.interrupt cancels
  the turn (accepted + incomplete/interrupted, or failed); errors are
  Codex's error frame with status and the headers it acts on;
  response.metadata, codex.response.metadata (x-models-etag, magpie's tag)
  and codex.rate_limits are sent as the backend does;
- shutdown drains sockets with 1001 and refuses new ones 503.
Codex needs no config change: magpie's wiring points the built-in openai
provider at /backend-api/codex, which Codex already speaks WS to. Other
Codex backend paths still answer 426. Docs: gateway-routing (new section
"A Responses WebSocket"), providers-accounts, reference.

Run at the pushed head (rebased on origin/main 430005726), on mote:
gofmt -l clean; go vet ./internal/gateway for darwin, linux, windows;
go test -timeout 45m ./internal/gateway: ok (480s).

Real Codex (codex-cli 0.165.0, sandbox HOME/CODEX_HOME with a copy of the
owner's ChatGPT auth, sandbox magpie on 127.0.0.1:3481, gpt-5.6-luna, a
task with three tool calls). At the pushed head, built on mote: exit 0,
right answer, 5 turns on one socket, 4 continued, 75480 B received vs
278210 B sent on as whole requests, no fallback to HTTP. Before the
rebase, with a temporary per-turn log: exit 0, right answer. 5 turns on one socket,
4 continued with previous_response_id; frames 58073 B (first), then 4465,
3051, 3093 B, against 58.7-66.6 KB had each been a whole request. 70185 B
received over the socket vs 255379 B sent on as whole requests.

Broken by hand:
- serveResponsesSocket returning false (the old 426): 9 of the new tests
  red.
- turns sent straight to the Responses handler with the upgrade's
  post-guard context: TestResponsesSocketGuards red (a key turned off
  still served; a 700-token limit not held).

Not tried: images in a real run; Codex on Windows/Linux. Not done: the
leg magpie -> vendor still sends the whole conversation each turn (for
ChatGPT, keeping an upstream socket per client socket would save that);
the saving is Codex's upload to magpie. A socket's conversation does not
survive the socket or a restart (Codex then resends everything).
2026-10-30 08:51:03 +08:00
yetone 442897f414 gateway: masking time is kept when magpie's own time is unknown
A masked request's "Masking" part on the Routing page comes from
Route.Masking, which maskingMs capped at Own, magpie's own time before
the request went out. Own is known only when magpie's client wrote the
request and a first token came back, so a request that was masked but
went through a plugin, through Claude Code for a Claude subscription,
failed, or had no first token had its masking time dropped to 0, and
the page showed nothing for it (Discord, lute: some requests show the
masking and model time and some don't). The Codex backend path never
set it at all.

maskingMs now keeps all of the masking time when Own is unknown, and
still caps it at Own when Own is known. The Codex backend path sets it
on its route and its usage record. The usage page still shows Masking
only beside a known Own, as before.

Run (mote, go1.26.8):
- TestMaskingTimeKeptWhenOwnIsUnknown (a masked request the vendor
  refuses): red on the old redact_phase.go ("masking 0 ms, held
  120ms"), green with it.
- TestCodexOwnSignInKeepsItsMaskingTime: red without the codex
  backend lines ("route's masking 0 ms, held 120ms"), green with them.
- TestMaskingIsAPhaseWithItsTime, TestNoMaskingNoMaskingTime: ok.
- go test ./internal/gateway ./internal/usage -count=1 -timeout 45m with
  this and the next commit: ok (gateway 502s, usage 16s).
- go vet ./internal/gateway ./internal/usage for darwin, linux
  (-tags nogui), windows: ok. gofmt -l: clean.
2026-10-30 01:54:40 +08:00
yetone 5dc908f764 gateway: a turn on Codex's own sign-in says where its time went
The Routing page's "Where the time went" (magpie, network, vendor) is
drawn from a try's TryNet, which only the routed path (gateway.go)
recorded. A turn Codex sends on its own sign-in or its API key goes
through the Codex backend path (codex_backend.go), out through the same
Go client, and its try never had one, so those requests showed no time
split while routed ones did (Discord, lute: some requests show magpie's
and the model's time and some don't).

Each Codex backend try now traces its requests (netTrace) and records
its TryNet when it ends or is handed on for an overload; a request asked
again within the try (a reset spent, a dropped large one, an item taken
out) counts as its Before. A turn asked again for an overload gets a
fresh trace, and its TTFT/FirstText are now from its own Start, as
Try.TTFT is documented, so its "First token" part isn't inflated by the
tries before it.

Run (mote, go1.26.8):
- TestCodexOwnSignInTellsWhereItsTimeWent: red on the old
  codex_backend.go ("no timing for a turn on Codex's own sign-in"),
  green with the change.
- go test ./internal/gateway -run 'TestCodex|TestTryTellsWhereItsTimeWent|TestTryNet|Overload': ok.
- go test ./internal/gateway -count=1 -timeout 45m at this change
  (base 8cbd0a9c9): ok (527s).
- go vet ./internal/gateway for darwin, linux (-tags nogui), windows: ok.
- gofmt -l: clean.
Not tried: a real Codex sign-in through the GUI.
2026-10-30 01:54:40 +08:00
yetone fb2e11e288 agent: a Codex sign-in OpenAI refused to refresh for good counts as none (#4308)
jjt on Discord: Codex's ChatGPT sign-in was revoked, and magpie's
models were gone from Codex until they signed in again.

Cause: Codex keeps a revoked sign-in's auth.json as it was and remembers
the permanent refresh failure in memory alone (codex-rs
login/src/auth/manager.rs). magpie read auth.json alone
(codexChatGPTKnown), counted the sign-in and wired Codex beside it
(openai_base_url, requires_openai_auth). There, Codex's /models went to
the gateway, which passed OpenAI's 401 token_revoked through, so the
picker had no magpie model; and every turn, magpie's models too, failed
at Codex 0.162.1's workspace routing discovery
(/backend-api/wham/accounts/check, 401).

Change:
- provider: codexRefresh tells a refusal Codex takes as permanent
  (request_chatgpt_token_refresh: refresh_token_expired, _reused or
  _invalidated, a 400 invalid_grant, or a 401 - here only a 401 that
  carries an error code, read as oauth/error.rs reads it). When magpie's
  own refresh of Codex's sign-in (codexTokenRenewing, from the usage read
  that KeepOnAnAccountWithRoom runs) is refused that way, and the store
  still holds that refresh token, codex-signin-gone.json keeps the Codex
  home -> sha256 of the refused refresh token (no token stored). A
  successful refresh forgets it. Writes Touch the catalog so the agents
  resync; the loop's noteCodexGoneNow notices a sign-in made again
  elsewhere within minutes.
- agent: codexChatGPTKnown reads such a sign-in as none
  (provider.CodexSignInGone), as v0.1.2087 did for forced_login_method =
  "api": magpie is Codex's provider without requires_openai_auth, the
  user's auth.json stays. A record that can't be read is unknown (as
  magpie last wired it). Signing in again gives another refresh token,
  which the record doesn't name: Sync writes requires_openai_auth back.
- gateway: codexModels doesn't pass a revoked /models answer
  (provider.SignInRevoked) through: it lists Codex's cached models and
  magpie's. The desk file does the same while the live list says revoked
  (CodexListRevoked). Any other refusal (token_expired, 5xx) is as before.
- docs: agent-wiring and gateway-routing.

Run:
- real codex 0.162.1 (app-server over stdio, and exec) on mote, sandbox
  HOME/CODEX_HOME, fake OpenAI (chatgpt_base_url,
  CODEX_REFRESH_TOKEN_URL_OVERRIDE, provider.CodexBase) answering 401
  token_revoked and refresh_token_invalidated; no real network.
  - Old wiring beside the dead sign-in, old gateway: model/list had no
    magpie model (jjt's case). With the gateway change: fake/m1 listed,
    but exec -m fake/m1 fails at workspace routing discovery (401), and
    account/read errors too - why the wiring change is needed.
  - Uncommitted e2e in the agent package with magpie's own written
    config: Set("fake/m1") wrote it beside the sign-in; magpie's
    LoginUsage("codex") then heard the refresh refused, Sync rewrote it
    to model_provider = "magpie", model_catalog_json, no
    requires_openai_auth. account/read: {"account":null,
    "requiresOpenaiAuth":false}; model/list: fake/m1 plus Codex's
    models; exec -m fake/m1 answered "hi from magpie"; auth.json byte
    for byte the same.
- Red on the old code (broken by hand): without the codexChatGPTKnown
  check TestCodexGoneSignInIsNoChatGPT is red; without the
  noteCodexSignInGone call TestCodexSignInGoneWhenRefusedForGood is red;
  with codexRefreshGone true for every failure TestCodexRefreshGoneRule
  is red; TestCodexModelListRevokedSignIn and
  TestCodexDesktopCatalogRevokedSignIn are red on the old gateway.
  Taking out the store re-check in noteCodexSignInGone leaves the tests
  green: a token Codex rotated meanwhile is already held by the hash
  comparison, and the re-check only saves a needless record, log line
  and resync. Not guarded on its own.
- via mote-run, at this commit rebased on origin/main 1f03d7546:
  gofmt -l clean; go vet ./internal/provider ./internal/agent
  ./internal/gateway for darwin, linux (-tags nogui) and windows ok;
  go test -timeout 45m -p 1 of the three: provider ok (92.3s), agent ok
  (192.1s), gateway ok (530.9s). The first full run had the new provider
  test red: run after the other Codex tests it read their cached logins
  and listed none; it now has the resetRevoked/rememberLogins setup its
  siblings use.
  Rebased after the run onto 05a6087e1 (access: key model scope) and
  8cbd0a9c9 (GUI loading bird); neither touches the Codex paths, and
  this push wasn't run again on them.

Not tried: the real Codex desktop app (ChatGPT.app); signing in again
with the real binary (the unit test writes a new auth.json); the
keychain credential store; magpie's left-alone mode, where magpie
doesn't refresh Codex's sign-in, so nothing is recorded there;
Codex homes on Windows and in WSL.
2026-10-30 01:40:48 +08:00
yetone 9101bb8879 privacy: a request masking would change can go as written to a model you picked
jessyoungyu on X: when a masking rule hits, send the request to a
self-hosted model instead, so a prompt like 「百度这家公司怎么样」 gets an
answer about Baidu, not about a placeholder.

Settings › Privacy › Instead of masking, send to (settings
redactRouteTo). It is Off by default, and nothing changes for a user who
leaves it Off. It is picked in the app menu, and only models whose every
route is unmasked can be chosen: the provider is set to Send requests
unmasked, it is on this computer or the network, it has no account, and
any fallback or group member is unmasked too (gateway.MaskRoute, the
same rule as provider.SkipsRedaction). The setting is saved on its own
with POST /api/settings/redact-route, which checks it with MaskRoute.
The general settings save keeps the value.

Decisions:
- When a value would actually be masked on an agent's turn (maskHits.n
  > 0), serve sends the request to the chosen model unmasked. Warn-only
  hits don't count, and Block still answers 400.
- If that model fails, the request fails. It is never masked and re-sent
  to the model the agent asked for, and never goes to a cloud model with
  the unmasked text. Falling back to a masked cloud request would answer
  a different question in the background. The user picked this route
  because masking breaks the answer.
- Streaming works the same as on any route.
- The route is checked again on every request. A model that is gone or
  no longer unmasked, or that the caller's gateway key may not use,
  means the request is masked as before.
- Covered: agents' Messages, Chat, Responses and Gemini turns (serve,
  marked by serveAgent), count_tokens, Codex magpie-model turns, and
  Codex own-sign-in /responses (codexMaskRoute).
- Not covered: magpie's own asks (ownAsk clears the mark), embeddings,
  audio, images and video. These stay masked.

GUI: redactRouteRow lives in plugins/redact/settings.js and wraps
renderRedact, so app.js is byte-for-byte unchanged and the core budget
is not raised. Strings are added in zh, zh-TW, ja and de. Docs: gateway-routing.md,
gui-shell.md, and site/public/docs masking (en, zh, ja).

Tests: internal/gateway/mask_route_test.go
(TestMaskedRequestGoesToTheModelSet: unset, set, streamed, nothing to
mask, local fails, falls back to a vendor, no longer unmasked,
count_tokens; TestCodexSigninTurnGoesToTheModelSet;
TestMaskRouteTakesOnlyUnmaskedRoutes; TestMaskRouteOnlyForTheAgentsTurn);
internal/gui/redact_route_test.go; settings_keep_test.go;
internal/gui/tests/redact-route.test.cjs (every language, chromium and
webkit, 1100 and 640 wide).

Broken by hand, each red:
- serveAgent without the agent mark;
- MaskRoute taking any route (TestMaskedRequestGoesToTheModelSet,
  TestMaskRouteTakesOnlyUnmaskedRoutes; at the pushed head);
- the codex hook removed;
- count_tokens without the mark;
- ownAsk not clearing it;
- no key check;
- no reroute in serve;
- the GUI: no keep in the general save, no MaskRoute check on save, and
  the picker listing every model;
- the plugin script left out of index.html (redact-route.test.cjs 22 of
  24 red; at the pushed head).

Run on mote:
- at 221ede767's tree, this change on f5806ed21 (pushed on 44d697993,
  which adds only app.css lines and a Gateway page GUI test):
  go test -tags nogui ./internal/gui ./internal/settings ok (the core
  budget is green again since ec789445d; #4307, filed and closed);
  the mask-route tests in ./internal/gateway ok; GOOS=linux go vet
  -tags nogui ./internal/gui ./internal/gateway ok; GUI: node --test of
  redact-route, redact-*, privacy-*, mask-*, masking-*, settings-*,
  i18n-keys, account-discovery, sessions-reads and gui-de/ja/zh-tw:
  643 pass, 0 fail. gofmt -l clean.
- at the same change on af8f3a939, one rebase back (the only
  difference is index.html's script order and main's own commits):
  go test -timeout 45m ./internal/gateway (488s) ./internal/redact
  ./internal/settings ./internal/provider ok; GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./..., go vet ./... ok.
The whole Go suite was not run; every package this change touches was
run above.

Not tried: a real self-hosted model (Ollama) with a real agent. The
local model is a fake Chat server in the tests.
2026-10-30 00:46:45 +08:00
yetone 2768f04f9b gateway: a thread switched off a used-up Codex model compacts locally (hiwise_aigc)
hiwise_aigc on X (2115741641017565304): with Codex's allowance used up,
an existing thread switched to a magpie model failed every turn and
"还会走gpt模型", restarts or not; a new thread worked.

Cause, from codex-rs: before a turn on a model with a smaller window
(or a changed comp_hash), core/src/session/turn.rs
maybe_run_previous_model_inline_compact compacts the thread on the
PREVIOUS model (gpt-5.5) through the current provider, turn metadata
compaction.reason "model_downshift" / "comp_hash_changed", phase
pre_turn. compact_model_fallback.rs retries with the turn's model only
when the provider is_openai() (name "OpenAI"). Under the takeover
provider "magpie" there is no fallback: /v1/responses resolved bare
gpt-5.5 to the used-up codex account, codexCompact returned its 429,
and that was the turn's error, every turn. A new thread has no previous
model, so no compaction.

Fix: codexCompact, off CodexPath only, reads the compaction reason from
x-codex-turn-metadata (header, else client_metadata in the body). For
model_downshift / comp_hash_changed, a failed, errored or empty
compaction on the old model is answered with localSummary (magpie's own
magpie1 summary, no model), so the thread goes on on the model it was
switched to. The held-account check doesn't short-circuit it either.
context_limit (the thread's own model out of room) still says the
refusal, and CodexPath is left alone: Codex's "OpenAI" provider falls
back to the turn's model itself and gets a better summary there.
Prompts and base_instructions are not touched.

Run:
- TestCodexLeavingModelCompactsLocally: red on the old code (429 at
  codex_leaving_model_test.go:84), green now.
- Broken by hand: without the body client_metadata fallback the
  header-less case goes red; without the CodexPath scope the CodexPath
  case goes red (got 200).
- Sandbox repro (sandbox HOME + CODEX_HOME, fake upstream, live ~/.codex
  untouched): codex 0.162.1, takeover-like config with
  remote_compaction v2 and a model catalog (gpt-5.5 400k, magpie-x
  128k), a gpt-5.5 thread relabelled to provider magpie, resumed on
  magpie-x: POST /v1/responses model gpt-5.5 + compaction_trigger,
  reason model_downshift; a 429 failed the turn ("Error running remote
  compact task: You've hit your usage limit"); answered with a
  compaction item, as the gateway now does, the turn went on to
  magpie-x and completed. ChatGPT.app's bundled codex has the same
  model_downshift / comp_hash_changed path (strings).
- gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=linux
  -tags nogui and GOOS=windows (mote).
- go test -timeout 45m -count=1 ./internal/gateway ./internal/codexsummary
  on mote at this tree (parent 0745db932 = origin/main at push): ok
  gateway 474s, ok codexsummary.

Not tried: a real used-up ChatGPT account through a real gateway end to
end; ChatGPT.app's bundled codex 0.164-alpha run itself; Codex without
remote_compaction v2 (the memento "responses" implementation sends a
plain turn, not covered here). The local summary is lossy (the user's
messages and the last reply), the same one codexCompact already falls
back to.
2026-10-29 19:46:39 +08:00
yetone fc43c69e53 gateway: a Codex thread switched to another effort is shown and sent at it
zzzkl3994 (Discord #feedback): Codex switched from medium to xhigh
mid-session, and Routing still showed medium. Their rollout had
{"type":"configuration_update","reasoning":{"effort":"xhigh"}}.

What Codex sends, captured from the real codex 0.162.1 TUI in a sandbox
CODEX_HOME against a local Responses server (built-in openai provider
via openai_base_url, /model -> Extra high -> "s"):
- reasoning_effort_override off (the default): reasoning.effort at the
  top goes xhigh; no item.
- reasoning_effort_override on: the top stays at the thread's first
  (medium), and every turn carries a configuration_update after its user
  message, the last one {"effort":"xhigh"}. This is the reporter's case.

magpie read only the top, so for such a thread:
- Routing's route and try showed medium (requestEffort/bodyEffort);
- a Responses vendor not OpenAI's got the items taken out (forVendor)
  and was asked at medium;
- a translated request (parseResponses) was asked at medium;
- magpie's own pick (withEffort, a fixed member) set the top, which an
  upstream reading the items overrode.

Now the effort of a Responses request is its last configuration_update's
when it has one (effortUpdated):
- bodyEffort/requestEffort read it, so Routing, tries and usage say xhigh;
- parseResponses takes it as the request's effort;
- forVendor puts it at the top where it takes the items out;
- withBodyEffort and withFixedEffort rewrite the last update (the top
  stays, so the thread's prefix does too);
- withoutAnyReasoning drops the items with the reasoning ask.
OpenAI's API and the ChatGPT backend still get the body as Codex sent it.
No Codex prompt or base_instructions is touched.

Tests (codex_effort_change_test.go), built from the captured request:
- TestCodexEffortChangeShownAndSent: route and try at xhigh, a Responses
  relay asked xhigh with no item;
- TestCodexEffortChangeReachesChatVendor: Chat vendor asked xhigh;
- TestCodexEffortChangeReaders: readers, magpie's pick, a fixed effort,
  reasonless, and OpenAI/ChatGPT bodies byte for byte.
Red on the old code (fix files stashed, two stub funcs): all three fail,
route at "medium", sent medium.

Run at this head (rebased on 96a703a59), on mote:
- go vet ./internal/gateway, and GOOS=linux / GOOS=windows -tags nogui
- go test -timeout 45m ./internal/gateway: ok (844s), at
  cb8f6ecca. Then rebased onto adc618bbf, whose only gateway change is a
  new test file (plugin_kinds_test.go). At this head: go vet
  ./internal/gateway and -run "CodexEffortChange|PluginKind" ok

Not tried:
- a real Codex thread through magpie to a real non-OpenAI vendor (the
  bodies are from the captured TUI request);
- GUI files: none touched.

Not covered here: ysm119's max on Cursor and DeepSeek. The agent isn't
known and the cause isn't confirmed, so it's filed as #4253 with what
was checked.
2026-10-29 18:29:55 +08:00
yetone 34b2dd9b70 gateway: a used-up Codex sign-in, the one account, is heard on its relayed turns and served without a restart
unsplashz on Discord: Codex beside its ChatGPT sign-in, one Codex
account in magpie. When the account ran out, Codex couldn't send until it
was restarted, after which its turns went through magpie.

Cause. With Codex's sign-in the only account on, an own-model turn is
relayed to ChatGPT as Codex sent it (codexUpstreamOn, no account). That
path never kept the reply's x-codex-* / codex.rate_limits windows
(heardCodexLimits) and never asked for the account to be read again on a
usage_limit_reached refusal (codexMayBeUsedUp). Only turns served through
magpie's accounts did. So magpie learned the account was out at the next
look, one to five minutes on, and until then wrote no codex.out and left
the Codex app's app-server alone, its Send greyed. A Codex started
before codex.out also kept sending own-model turns to its built-in
provider, each relayed to the same refusal, until it was restarted.

Fix.
- codexUpstreamOn: for a /responses relay on magpie's ChatGPT account
  (codexRelayedAccount: the account signed with, or Codex's sign-in when
  the request's chatgpt-account-id names it), the reply's windows are
  heard, and a quota refusal calls codexMayBeUsedUp. codexServed now uses
  the same lookup.
- codexAccounts: while the sign-in is known out (CodexUsedUpKnown, the
  cached reading only) and the request signs as it, an own-model turn
  goes through routing as codex/<model>, as a restarted Codex's does.
  Another sign-in (a Codex in WSL) still goes as it came.

Run:
- go test ./internal/gateway -run 'TestCodexUsedUp|TestCodexRelayedWindowsHeard|TestCodexHeldSignInServedWithoutRestart|TestCodexOwnModel|TestCodexPaused|OneAccount' (mote): ok.
- GOOS=darwin/linux/windows go vet ./internal/gateway (mote): clean. gofmt -l: clean.
- go test ./... -timeout 45m -count=1 at 25fbbd03e on the Linux VM (wsl-run,
  mote had another session's full suite): 73 ok, internal/gateway ok
  (738s). Reds: ., internal/cli and internal/gui don't build there (no
  gtk4/webkitgtk-6.0 dev packages); internal/agent TestInstalledVersion,
  TestGrokInstalled, TestOmpDetectedWithPiDir, TestZedAppPath, all #4033
  (and #3548). The first three are red the same on origin/main e61e10535
  there; TestZedAppPath passes 3 of 3 alone on this branch.
- go test . ./internal/cli ./internal/gui ./internal/agent -timeout 45m at
  25fbbd03e on mote (load ~300, other sessions' suites): ., cli, agent ok.
  internal/gui: 12 real-window AppKit tests killed at their deadlines
  (#2645, #4125). Alone, TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie pass; the other 10 (TestDockJoinLeadsCommandTab,
  TestPanelCloseHidesIt, TestPanelJoinsFullScreenSpaces,
  TestPluginPageLoadsItsFilesInTheWindow, TestDockReopenKeepsTheWindowsSpace,
  TestMainWindowCorners, TestMainWindowRightToLeft,
  TestHandoverLeavesTheMenuBarIconForTheNextMagpie,
  TestTrayCellClickReleasedPanel, TestCoveredWindowStaysUp) are red the
  same on origin/main e61e10535 there. Nothing in gui is touched.
- Rebased on origin/main (12 commits, none in codex_backend.go):
  go test ./internal/gateway -run TestCodex at the pushed head on the
  Linux VM (mote stopped answering ssh): ok.

Broken by hand:
- codexMayBeUsedUp call removed: TestCodexUsedUpRelayedAsksAtOnce red
  (asked "", want me@example.com).
- heardCodexLimits call removed: TestCodexRelayedWindowsHeard red (heard []).
- held branch off in codexAccounts: TestCodexHeldSignInServedWithoutRestart
  red (held: "" false). Account-id guard removed: red (another sign-in
  routed as codex/gpt-5.5).

Not tried:
- A real used-up ChatGPT account, or the real Codex app. The real codex
  0.162.1 CLI in a sandbox CODEX_HOME against a fake backend never got
  past its workspace routing discovery (/wham/accounts/check), so no turn
  reached the fake.
- With one account and no fallbacks, the turn served through routing
  still ends in the account's 429 (worded by routing). It goes on only
  where routing has somewhere to send it, as for a restarted Codex.
2026-10-29 15:14:02 +08:00
yetone 0e2739743b codex: a reset set to go when the week runs out is spent before the credits
tongzhenbao on X: a Codex Pro account with "when its week runs out" on,
its week at 0% left, one reset held until 11-06 (after the week's own
reset on 11-03) and Use credits on. Overnight ~10k credits went and the
reset stayed; the card said "not auto-used" beside the switch on.

Cause: the week's auto-use ran only on a vendor refusal. autoReset in
routing needs a 429 usage_limit_reached on the last candidate, and the
relay's autoResetSignedIn the same on its 429. An account let spend its
credits is never refused for its week: ChatGPT answers on the credits,
and routing never benches it (full() and onCredits). So the week's reset
could only ever be spent with credits off.

Decision (product call delegated): a reset is free, credits cost money,
so a reset the user set to go when the week runs out goes before any
credits. resetBeforeCredits runs before a try is sent to a Codex account
on its credits whose last reading has its week used up, with the week's
switch on; AutoUseCodexReset reads the week again and keeps one a week
at most, so a second time in the same week goes on the credits. Hooked
in the routing loop and in codexUpstreamOn (the relay, signed-in or an
account). With no reset held, or the week's switch off, nothing changes.

The card's summary: with only the week's switch on it now says "auto-used
when the week runs out" (zh 周额度用完时自动使用), not "not auto-used",
with its title in all five languages. CLI help and auto-reset messages
say "or before its credits are spent". gateway-routing.md names it.

Siblings: the expiring switch already spends regardless of credits
(usedUp ignores them); the credits-off path (planned.held) is unchanged.

Run (mote, through mote-run, at this tree):
- go test ./internal/gateway -run 'TestCodexResetBeforeCredits|TestCodexAutoReset|TestCodexCredits|TestCodexNoCredits': ok
- broken by hand: gateway.go and codex_backend.go at origin/main:
  TestCodexResetBeforeCredits/relayed and /routed red (200, spent ""),
  the two negative cases green
- node --test codex-auto-reset, i18n-keys, codex-auto-reset-settings,
  codex-resets-used, panel-options-fold, quota-curve: 96/96 (chromium +
  webkit, en/zh/zh-TW/ja/de); codex-auto-reset red with origin/main's
  app.js ("· not auto-used")
- full suite, before the rebase onto 300b7eee0: wsl-run go test -timeout
  45m ./... ok for internal/gateway, provider, settings, tui and the rest;
  root, cli and gui don't build in WSL (no gtk4/webkitgtk-6.0), and
  internal/agent's fake-binary tests (TestInstalledVersion and four more)
  fail there with "Invalid argument"; on mote those packages are ok
  (., cli 49s, agent 179s)
- at the pushed head 7b6a0675f (on 300b7eee0), on mote: internal/gui,
  provider and cli; provider and cli ok, gui ok except TestMainWindowCorners,
  red the same on a clean 300b7eee0 copy on mote (macOS 27), #3949;
  TestCoreScriptBudget ok with no raise (app.js 1,311,588 of 1,311,735,
  after shortening resetsWords' change); the focused gateway tests and the
  six GUI files above again, ok and 96/96
Not tried: a real account with credits and a held reset at 0% week; the
owner's accounts have no reset at 0% to spend.
2026-10-29 08:17:12 +08:00
yetone b4267de595 gateway: a provider's fallback can be a routing group, routed as the group
01huadalang on Discord: "还有备用模型增加路由组的选择,现在只能选模型". A
provider's Fallback list held models only; a "group/<id>" entry resolved
to the group's first member alone. Now such an entry is served through the
group, as a request to the group would be:

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

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

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

Not tried: a real request through a real group fallback with real
accounts (the tests use fake upstreams); the Windows GUI; the TUI has no
fallback editor.
2026-10-29 05:19:28 +08:00
yetone 25bf394a72 gateway: a resumed Codex subagent goes back on the model it was spawned on
HoGee_xxl on X: a Codex subagent brought back with resume_agent ran on
the lead's model, not the one the lead spawned it on.

Codex's multi-agent V1 (the one magpie's own models ask for) builds the
resumed subagent's config from the lead's current turn:
codex-rs core/src/agent/child_config.rs build_agent_resume_config ->
build_agent_shared_config sets config.model to turn.model_info().slug,
and core/src/agent/control/spawn.rs resume_single_agent_from_rollout
starts the thread on that config without reading back the thread's
stored model. Neither the spawn_agent model nor [agents]
default_subagent_model is asked again. V2's ensure_v2_agent_loaded does
put a thread back on its stored model, so this follows Codex's own rule.

The gateway now notes the model each Codex subagent thread (thread_id in
x-codex-turn-metadata / client_metadata; session_id only on a Codex old
enough not to share it) first asked for, and puts a later request of
that thread asking for another back on it. Kept in codex-subagents.json
beside providers.json (0600, temp file and rename, the 512 latest, 30
days), so a resume after a restart is known. A model set for every
subagent (codexSubagentPick) still wins. No prompt or base_instructions
is touched.

Run (mote-run): go test ./internal/gateway -run 'TestCodexResumed|
TestCodexSubagentThreadOf|TestCodexSubagent|TestCodexFollow|
SessionMetadata|TestCodexSide' -count=1: ok.
Broken by hand: skipping the restore in codex_backend.go turns
TestCodexResumedSubagentKeepsItsSpawnModel red ("worker-1 asking gpt-5.5
went on gpt-5.5, want gpt-6-astra"); skipping the save turns its
after-restart step red.
Not tried: a real Codex resume_agent run against a real ChatGPT account.
2026-10-29 03:45:57 +08:00