Files
magpie/docs/subsystems
JoeyWu-tech 47175a68ff gateway: an error in a kept-alive stream names the model the agent asked for (#3728)
jilen (#3728): fx asked magpie for codex/gpt-6.1-sol on
/v1/chat/completions and showed "system: InvalidChunk: Invalid Chat
Completions response at model (event 1).", while the usage log had the
vendor's 502, an EOF from chatgpt.com. No stream was saved, but fx's
InvalidChunk at event 1 says one had begun: magpie had kept fx alive
with the stream's headers and comments, so the failure went as an
event of that stream (streamError). The encoder streamError made, from
an empty Request, began the message before the error with a Chat chunk
whose "model" was "". fx takes a chunk with an empty model for a broken
one and stops there, so it never read the error after it. Anthropic's
message_start and Responses' response.created, response.in_progress
and response.failed went out with an empty model the same way.

keptAlive now keeps the model the request names when serve takes it,
as magpie spells it there: a flat id (a~m) is its catalog id, a dashed
Claude id its dotted one, and Codex's own model through magpie's
accounts codex/<model>. An effort the agent put on the model is kept on
it (a/m:high), the name it asked by. serve has it from the body it
already read for askedAt; on Codex's own sign-in (codexUpstreamOn) it
is the model Codex wrote, which its turn already read. Neither reads
the body again. streamError begins with that model, from failTo,
holdWriter.release and Codex's failWith. Gemini's error names no model,
as before. docs/subsystems/gateway-routing.md says so.

fx still shows no reason. Its Chat reader ends the stream with
ProviderError at an event with an "error" key and keeps nothing of it
(src/gateway/chat_completions_protocol.zig:723 in fx 0.0.14, :710 on
fx's main e71a663b); only an error status's body reaches its message.
So fx says ProviderError where it said InvalidChunk, and the vendor's
EOF is in the stream and magpie's usage log, not in fx.

Not changed: an error after a reply that already went, a loop cut's
(cutLoop), starts a message of its own after the vendor's, under a new
id. A model in it wouldn't help, fx stops at the new id: #3792. Nor the
error's shape: the encoders still begin a message ahead of it. fx looks
for an event's "error" before its id and model, so an error alone would
get past it too, but no other agent was tried on one; that is #3792's
question as well.

What was run (tree 908b9857, on origin/main 2beed3b0, go1.26.8,
linux/amd64):
- TestStreamErrorNamesTheModel, new: streamError in each protocol with
  the report's model and message. Chat's, Anthropic's and Responses'
  events name that model and no other, Gemini's none, and each has the
  message.
- TestKeptAliveChatErrorNamesTheModel, new: a Chat stream through serve,
  kept alive while the vendor says nothing, then the vendor gone with no
  reply (the EOF), or answering 502, 413, a 200 that isn't a stream, or
  a JSON 200 that is no reply. In each, the stream's first chunk names
  a/m and the error follows; the 413's says request_too_large. Asked
  for a/m:high, the vendor gone, the first chunk names a/m:high.
- TestKeptAliveChatOnCodexErrorNamesTheModel, new: the report's route, a
  Chat stream on magpie's codex provider (Codex's sign-in), the ChatGPT
  backend a local server that says nothing until the stream was kept
  alive and then hangs up, each time it is asked. The first chunk names
  codex/gpt-5.5, and the error after it has the backend's EOF.
- TestKeptAliveCodexErrorNamesTheModel, new: Codex on its own sign-in,
  the backend overloaded, Codex kept alive while the turn waits to be
  asked again, then the backend gone. Every model its events name is
  gpt-5.5, the model Codex asked for, and they name one.
- The four, -count=50: ok.
- -race -count=20 -cpu 1,2 over them and the stream tests beside them
  (TestStreamError*, TestGroupLastFailureInStreamSaysItPasses,
  TestStreamedByteCap, TestLoopEnds, TestLoopCutMidLine,
  TestCodexOneAccountOverload, the Quiet ones): ok, no race.
- Broken by hand, each red:
  - streamError's encoder made from an empty Request again:
    TestStreamErrorNamesTheModel, every case of
    TestKeptAliveChatErrorNamesTheModel,
    TestKeptAliveChatOnCodexErrorNamesTheModel and
    TestKeptAliveCodexErrorNamesTheModel.
  - serve's keptAlive with no model: every case of
    TestKeptAliveChatErrorNamesTheModel and
    TestKeptAliveChatOnCodexErrorNamesTheModel.
  - keptAlive given the model without its effort: the a/m:high case
    alone.
  - failTo naming none: the 413 case.
  - holdWriter.release naming none for a reply that is no reply: the
    JSON 200's case; for an error status: the vendor gone, a/m:high,
    the 502, the 200 that isn't a stream, and
    TestKeptAliveChatOnCodexErrorNamesTheModel.
  - Codex's keptAlive with no model, or its failWith naming none:
    TestKeptAliveCodexErrorNamesTheModel.
- A real run: magpie built at 2beed3b0 and at this tree (go build
  -tags nogui -buildvcs=false), magpie serve in a sandbox HOME, a
  provider (a local server) that holds its first answer 20s and then
  hangs up, or answers 502, and fx 0.0.14 asking it through
  /v1/chat/completions (fx ask, its settings' provider
  openai-chat-completions at the gateway), with --json and without.
  fx exits 1 after about 53s each time: InvalidChunk at 2beed3b0, all
  four times (hang-up and 502, --json and not), ProviderError at this
  tree, all four. curl asking the same: ": keepalive" lines, then a
  first chunk with "model":"" (2beed3b0) or "model":"up/m" (this
  tree), then the error with the vendor's EOF or 502.
- gofmt -l; go vet -tags nogui and go build -tags nogui for linux,
  windows 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).
- go test -tags nogui -count=1 -timeout 45m ./..., Bun 1.4.2 on PATH:
  67 ok, and 7 red, none in what this changes: agent
  TestCodexDriftReached (#3398); TestInstalledVersion,
  TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); davsync
  TestSyncTeraCloudStillSeesOtherWrites (#3420); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (#3640);
  gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649); provider's "close of synctest channel from outside bubble"
  from TestUnreadLoginsWriteErrorsKeepCredentials (#3632).

Not tried: the real chatgpt.com (it needs a ChatGPT account); the
ChatGPT backend was a local server that hangs up. fx's interactive
view, where the report's line came from.

Review (yetone/magpie maintainer agent), for jilen's #3728:
- Read every line. The only encoder built with an empty Request is
  streamError's; its five callers (failTo, holdWriter.release's two
  cases, cutLoop, Codex's failWith) are each given a model, cutLoop ""
  on purpose (#3792).
- Red by hand at c711c3391 on 1cbdda25b, macOS, go1.27: streamError
  back to &Request{}: all four new tests red; keptAlive built without
  model: the two Chat kept-alive tests red; Codex's kept.model unset:
  TestKeptAliveCodexErrorNamesTheModel red. Green restored.
- go test -tags nogui -race ./internal/gateway -run
  'NamesTheModel|TestStreamError': ok. Full go test -tags nogui
  -timeout 45m ./internal/gateway: ok (573s).
- gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet
  ./internal/gateway: ok.
- Real run: magpie serve (base and patched builds) in a sandbox HOME, a
  fake Chat vendor that holds 20s then answers 502, a streamed
  /v1/chat/completions for fakev/fake-model. Base: the kept-alive first
  chunk says "model":"", then the error. Patched: "model":
  "fakev/fake-model", then the same error.
- Rebased onto ab546a4ee (gateway changed since): gofmt, vet linux and
  windows, and go test ./internal/gateway -run
  'NamesTheModel|StreamError|KeptAlive|KeepAlive|Alive|Codex' again
  there: ok. The full package ran at the earlier base only.
- Not tried: fx itself, the real ChatGPT backend.
2026-10-27 16:05:50 +08:00
..

Subsystem design references

These pages describe current responsibilities, runtime paths, state, and contracts. Start with the subsystem relevant to your task, then follow its source links to verify the implementation you change.

Subsystem Reference
Built-in subscriptions moving to plugins Provider and plugin ownership
Built-in plugins: registry, lifecycle, plugins.yml, presets, settings schemas, the window's kernel (slots, error boundary, kit) Plugin runtime
Plugins that run on the gateway's requests and replies Gateway middleware
Tools that plugins give, offered to every agent as an MCP server Plugin tools
Plugins that await context recall and observe completed replies Asynchronous gateway request hooks
Claude subscription turns across Claude Code runs Claude subscription bridge
How the gateway picks a provider, key or account, and falls back Gateway routing and fallback
Gateway Session Aggregation Gateway Session Aggregation
Connecting an agent's config to the gateway, drift, disconnect, WSL twins Agent wiring
Providers, keys, subscription accounts, refresh and allowance Providers and accounts
Instructions, MCP servers, skills and RTK written into agents Library
Tray, panel, window, magpie web and the page's JSON API GUI app shell
Encrypted backups and setup synchronization over WebDAV, S3 or GitHub Sync and backup

A subsystem can span several packages or repositories. Its reference describes the behavior those parts provide together; it does not need to list every function.

Maintain a reference

Update the owning reference in the same PR when a change alters a documented responsibility, interface, state transition, runtime path, compatibility rule, or failure behavior. An internal refactor that preserves these contracts does not require a prose change.

Keep each fact in one reference and link to it from agent instructions or other pages. Link to source files and named symbols rather than copying implementation details that change frequently. Explain field meanings and constraints that signatures alone do not express.

For a new reference, include the responsibilities and boundaries, source of truth, main runtime paths, state transitions, important constraints, and existing verification commands. Include failure and compatibility behavior where relevant. Document current behavior separately from proposed changes; the proposal belongs in its issue or PR.

Describe a PR's semantic changes

For each affected subsystem, explain the observable change with its trigger and before/after behavior. Include changes to interfaces, state, compatibility, and failure behavior when relevant. Link the affected reference, implementation, and verification evidence. State when a refactor preserves the documented behavior.

For example, a change to plugin adoption should explain which migration state and account condition trigger it, which implementation handles requests before and after adoption, and which test exercises that transition.

This is an author-provided explanation that a reviewer verifies against the diff and surrounding code. It is not an automatically proven compatibility verdict.

Review a change

  1. Identify the affected subsystem and the actual runtime path, including plugin or built-in ownership.
  2. Compare the claimed before/after behavior with the base and head implementation. Trace relevant callers and state transitions beyond the changed lines.
  3. Check that changed contracts appear in the owning reference and that source links still resolve.
  4. Check that the cited tests or runtime evidence exercise the claimed behavior. Report checks that were not run.

A documentation update alone does not prove the implementation. Existing tests and runtime evidence remain necessary for behavior changes.