Files
magpie/docs/subsystems
JoeyWu-tech bec9df0888 sessions: a provider move leaves a thread a Codex has open (#3751)
#3751's second half; 67b12956 fixed the half about lengths. A Codex
thread moved to another provider, by the Sessions page's Move
(MoveCodexProvider, #887) or as Codex steps off magpie (bringBack's
MoveCodexThreads), has each of its rollouts written whole into a temp
file that then takes its place. The move took no Codex lock and left
alone only a thread written to in the last minute. A Codex that resumed
the thread (the app-server, as run below; a resumed TUI too, by Codex's
source) keeps its rollout open to append to for as long as it has the
thread, so what it wrote after a move went into the file the rename had
put aside: a turn the upstream answered was in neither the rollout nor
what Codex sent after its next resume.

moveCodexPaths now holds the thread as Codex holds one it writes to,
archives or deletes (rollout/src/writer_lock.rs, acquire; thread-store
holds it through a whole archive, unarchive or delete): under
thread-writer-locks/.coordination.lock it makes and locks
thread-writer-locks/<thread>.lock, then lets the coordination lock go
and keeps the thread's lock from before a file is copied to the trash
until the thread's row in the state database has moved. Letting go takes
the lock file away under the coordination lock, as Codex's guard does. A
Codex that resumes the thread meanwhile is turned away by Codex itself
("already has an active writer"), so the files and the row move together
and a rollback is written under no Codex. A thread a Codex has open is
left as it was: its files, their time and its row, with no copy kept.

Its error, "a Codex has the session open", is ErrActive too, so it goes
where a thread written to in the last minute goes: MoveCodexThreads
leaves it for its next call, and the Sessions page's reply marks it
active, so the page says "{title} is still being written to; close it in
Codex and try again in a minute" ("{n} sessions ..." for several), in
en, zh, zh-TW, ja and de. No new words and no GUI file changed: app.js
grows 0 bytes. There is no CLI for the move. The minute is the page's
own: codex exec lets the thread go as it exits (the interactive TUI
wasn't tried), but Codex 0.164.0's app-server keeps a thread loaded, and
held, until 30 minutes after it went idle with nothing showing it
(thread_unload_delay_secs, 1800 by default), or until it ends. So a
thread the Codex app has shown can be refused for up to half an hour
after it is closed there, or until the app quits. Those words are left
as they are (#3986).

A Codex home without thread-writer-locks (a Codex from before them)
has no lock to take, and its threads move as before, with the
last-minute check alone. None is made there: PortCodexRollouts reads a
home with one as one whose Codex holds its threads, and would then
rewrite rollouts under a Codex that doesn't. A lock folder that can't
be read, or a lock file that can't be opened, refuses the move with
its error. The coordination lock is waited for at most 10s
(filelock.Wait), under storeMu and mu as the row's 5s busy_timeout
already is; not had by then, the thread counts as held, as in
editRollout.

editRollout, the port's writer, isn't used: it publishes one file under
the coordination lock alone, while a thread's files (a revert's, a
packed twin) and its row move together, and its edit can't refuse a
longer id in a paginated rollout as 67b12956's rewriteCodexProvider
does. rewriteCodexProvider is unchanged, so the padding and that
refusal stay as they were.

A thread bringBack leaves keeps its row on magpie, so the next bringBack
picks it again (codexThreadsOn) and moves it once its Codex has let go:
it isn't left for good. bringBack runs at Disconnect and in Codex's
Sync, which SyncCatalog runs: at the GUI's start, after a provider,
plugin or model list is saved or fetched, and when the catalog is
fetched again (catalog.KeepFresh, at least daily in the GUI and in
magpie serve). Until then the thread stays on magpie, as one written to
in the last minute does now, so for up to about a day while magpie runs.
At a Disconnect magpie also restarts the Codex app's app-server
(KeepCodexAppOnItsProvider, every 3s), which lets the thread go; when
that comes after bringBack's move, the thread waits for the next Sync.
When Codex goes back to openai, or another id of magpie's length,
RelabelCodexThreads first writes a plain rollout's provider in place,
held or not; MoveCodexThreads meets a held thread there only for what
that skips, a packed rollout mostly. For an id of another length it
moves them all.

RelabelCodexThreads takes no lock either. It writes the id over in the
first line, in place, so a Codex appending to the file loses nothing:
tried below, the turn after it was kept and the row stayed as it wrote
it. It is left as it is.

The port's paragraph in docs/subsystems/gateway-routing.md, where
67b12956 put the move's lengths, says so, and so do the comments of
MoveCodexProvider, MoveCodexThreads and bringBack.

What was run (tree d652ce94, on origin/main 74dcf40a, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- TestMoveCodexProviderLeavesAnOpenThread (new): a thread's writer lock
  held as a resumed Codex holds it. The Move is refused with ErrActive;
  the file, its time and the row are as they were, nothing is kept in
  the trash and no temp file is left. With the lock let go (its file
  left behind, as a Codex that ended leaves it), the Move goes through
  and the lock file is gone.
- TestMoveCodexProviderHoldsTheThread (new): looked at from a trigger
  on the row's update, as the Move writes the row, the thread's lock is
  held and the file names the new provider already; the lock file is
  gone after.
- TestMoveCodexThreadsLeavesAnOpenThread (new): two threads on magpie,
  one held. The other moves; the held one keeps its file and row, with
  no copy and no error, and the next call moves it once let go. A home
  without thread-writer-locks moves its thread as before, and gets
  none.
- The three with 74dcf40a's codex_provider.go: red, "err <nil>, want
  ErrActive", "as the row was written: no lock file", and both threads
  moved.
- -race -count=10, the three and every move and port test of
  internal/sessions (TestCodexProviderIn, TestMoveCodexProvider,
  TestMoveCodexProviderPacked, TestMoveCodexProviderKeepsBytePlaces,
  TestMoveCodexThreads, TestMoveCodexThreadsNone,
  TestPortCodexRollouts and its KeepsBytePlaces, LeavesAnOpenThread,
  LongerLine and RepairsForks, TestPortLineDropsClaudeBlocks,
  TestPortLineLeavesOthers): 16 tests, 10 runs each, ok. -race
  -count=3: internal/agent's TestCodexThreadsComeBackOffMagpie and
  TestCodexThreadsFollowMagpieIn (bringBack, bringOver) and
  internal/gateway's TestPortedCompactionReadsTheSame, ok.
- Broken by hand, each alone in a scratch worktree at this tree, the
  eight move tests run, each red:
  - no lock taken: all three new tests, as at 74dcf40a.
  - the row written for a thread left: both LeavesAnOpenThread tests
    ("its row moved to ..., its files didn't"), and MoveCodexThreads
    never finds the thread again ("after its Codex let go: [] <nil>").
  - the lock taken after the copy to the trash: both
    LeavesAnOpenThread tests ("a copy kept of a thread left as it
    was").
  - the lock let go after the files, before the row:
    TestMoveCodexProviderHoldsTheThread.
  - the error not ErrActive: TestMoveCodexProviderLeavesAnOpenThread
    ("err a Codex has the session open, want ErrActive") and
    TestMoveCodexThreadsLeavesAnOpenThread (the held thread's error
    returned, "thread ...: a Codex has the session open").
  - the lock file left when the move lets go: both
    TestMoveCodexProvider tests.
  - thread-writer-locks made in a home without one:
    TestMoveCodexThreadsLeavesAnOpenThread.
  The other move tests stayed green under each.
- Codex CLI 0.164.0, real, with gw-c's #3616 move-open harness: a
  sandbox HOME and CODEX_HOME, loopback only, a fake Responses
  upstream, and MoveCodexThreads from fake-provider to fake through a
  test binary built from each tree. Two turns on a thread T; a codex
  app-server resumes T (T's lock file appears in thread-writer-locks),
  waits 80s and has a turn; at 70s, the move.
  - 74dcf40a: the move moved T, file and row. The turn completed and
    the upstream got it, but the rollout has it 0 times, and Codex
    resuming T on fake sent turns 1 and 2 without it.
  - here: the move moved nothing, file and row on fake-provider. The
    turn is in the rollout (2 lines). With the app-server gone (its
    lock file gone) and the rollout a minute old, the move moved T
    (files 1, db 1), and thread-writer-locks had only
    .coordination.lock after it. Codex resuming T on fake sent turns 1
    and 2 and the turn the app-server had.
  Each tree ran twice: in the first runs the move after the app-server
  came within the minute after its turn, which left T here; the script
  now waits the minute out.
- Codex CLI 0.164.0, the same sandbox: with T's lock file made and
  flocked under the coordination lock by another process, as
  holdCodexThread does, codex exec resume T exits 1 with "thread/resume
  failed: thread ... already has an active writer" and sends nothing;
  once it is let go and the file taken away, the resume runs.
- Codex CLI 0.164.0, the move-open run with RelabelCodexThreads from
  fake to fak2 (one length) at 70s: T relabelled at once, the turn in
  the rollout (2 lines), the row still fak2 after it, and Codex
  resuming T on fak2 sent the turn.
- gofmt -l clean. tools/vetset.sh: go vet -tags nogui for linux,
  windows and darwin, go vet for windows, go build -tags nogui for
  linux and darwin, and go build for windows, exit 0 each; untagged
  linux vet and build exit 1 (no GTK or WebKitGTK dev packages on this
  box).
- go test -tags nogui -count=1 -timeout 45m ./... (log kept), Bun
  1.4.2: 68 packages ok and 8 red, sessions ok; each red on the list of
  reds already filed: agent (#3141, #3398, #3641, and
  TestWSLColdPlaceOpensNothing, #3924), davsync TestSync (#3420), edit
  and testenv (umask 077, #3640), gateway
  TestPluginToldWhereTheAgentWorks (#3675), gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649), provider TestCodexAppServersOnHome (#3906), then "close of
  synctest channel from outside bubble" (#3632), tui
  TestTUIFetchesSubscriptionModels/agent (#3919)
- On origin/main 1a804859 with this commit cherry-picked (a scratch
  worktree, not this tree): go test ./internal/sessions ok; go test -run
  Codex ./internal/agent, only TestCodexDriftReached red (#3398)
Not run: the GUI tests, i18n-keys among them; no GUI file changed.

Not tried: Windows, where magpie's lock is LockFileEx on one byte and
Codex's on the whole file (as for the port), and macOS; the Codex app
itself, whose app-server was driven over stdio here as the app drives
one; a thread of a Codex in a WSL distro moved from Windows, where the
lock taken may not be the distro's; a file system without locks, where
the move is refused as held.

Review (yetone, at this commit on origin/main bb5e68cea, go1.26.8):
- Checked against Codex's codex-rs/rollout/src/writer_lock.rs: acquire
  takes thread-writer-locks/.coordination.lock, creates and try-locks
  <thread_id>.lock and lets coordination go; its guard's drop takes
  coordination again, closes the file, removes it and lets go. The move
  does the same, and leaves a home without the folder alone.
- On main, the three new tests red on macOS (mote): "err <nil>, want
  ErrActive", "as the row was written: no lock file", both threads
  moved. With this change, ok.
- Broken by hand, each red: letGo called at once (HoldsTheThread);
  os.Remove dropped ("lock file is left", both MoveCodexProvider
  tests); threadOpen's Is false (LeavesAnOpenThread x2); the lock
  folder always made (MoveCodexThreads, "thread-writer-locks made where
  Codex keeps none").
- macOS (mote): go test -tags nogui ./internal/sessions
  ./internal/filelock ./internal/agent ok; -race -count=10 -run
  'TestMoveCodex|TestPortCodex' ./internal/sessions ok (at d0a61b856);
  gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows for sessions and agent ok.
- Windows (xiaomi-gpu, win-run) and Linux (WSL magpie-desktop,
  wsl-run): go test -run 'TestMoveCodex|TestPortCodex'
  ./internal/sessions ok (at d0a61b856).
Not tried by the review: a real Codex CLI or app holding a thread
during a move, on any system; a WSL distro's Codex moved from Windows.

At the pushed tree (rebased on origin/main 7e0fe83d4), macOS (mote):
gofmt clean; go vet darwin, GOOS=windows and GOOS=linux -tags nogui for
sessions ok; go test -tags nogui ./internal/sessions ./internal/agent
ok; -run Budget ./internal/gui ok.
2026-10-31 18:52:01 +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
One MCP server, magpie, given to every agent in place of the Library's servers MCP router
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.