Skip to content

Codex chats keep working when Orca restarts (macOS and Linux) - #47783

Merged
brennanb2025 merged 270 commits into
mainfrom
brennanb2025/chat-relay-codex
Nov 27, 2026
Merged

brennanb2025 merged 270 commits into
mainfrom
brennanb2025/chat-relay-codex

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #47229 (review that first; this PR's base is its branch).

ELI5

Today, quitting or updating Orca stops every Codex chat that is working. With this change a Codex chat keeps working while Orca is closed, the same way terminals already do, and when Orca opens again the chat picks up exactly where it was: same agent, same running command, nothing lost or repeated.

Files Added Deleted Net
Test 20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3158 $\color{#cf222e}{\Huge{\mathbf{−}}}$​22 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3136
Prod 140 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​7681 $\color{#cf222e}{\Huge{\mathbf{−}}}$​414 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​7267

What Changed

Before: quitting Orca stopped each chat's Codex agent, marked the running turn as cut, and offered to continue it after the restart.

After (macOS and Linux): a chat's own Codex agent runs under Orca's terminal host. On quit the chat hands the agent to the host instead of stopping it, so the turn keeps running and nothing is marked as cut. On the next launch the chat reconnects to the same agent and catches up on everything it said while Orca was closed, in order. Approvals the agent asked for while Orca was closed show up as normal prompts. A chat nobody is using is still stopped after the user's chat idle-stop setting, by the same rule the open app uses: never while a turn runs, an approval waits, or the agent reports a background task (a background shell, a dev server, a subagent). If the terminal host had to stop an agent because its output could not be relayed, the chat shows why and the next message starts it again as today. Windows keeps today's behavior. So do chats on SSH and other remote hosts, bot chats and chats on the experimental shared Codex servers (off by default); keeping shared servers across a restart is a follow-up that must land before that setting can be turned on by default.

Mechanism:

  • App layer (provider-neutral): a child-process object backed by the host's relay calls, so the Codex connection takes it unchanged; quit detaches relayed chats; launch lists the host's relays once, keeps those chats out of crash cuts and restart offers, treats their recorded owner as one to reattach rather than an orphan to stop, and reattaches them. Output is acknowledged to the host only after the chat's history has saved it, so a crash mid-catch-up replays from the last saved line.
  • Codex: a reattached agent is already initialized, so that request is answered locally, new request ids start above the last ones the agent saw, and output since the last acknowledgement is replayed once the chat is ready instead of re-reading thread history.
  • Launch: only a local Codex chat that had an agent at its last run waits for the host's list of kept agents when it opens, and for at most 1.5 s; other chats never wait. If the host is late, a chat whose agent still runs under it opens as kept, and its first message asks the host again; if the host still hasn't answered, that message fails with a retryable error instead of starting a second agent.
  • Host: the relay applies the user's idle-stop policy only while no app is attached. At quit the app tells it what work is open; while detached it tracks turn and background-task starts and ends from the agent's own messages, named by provider-neutral rules each agent supplies. It also sends the agent's last error output with its exit. Stopping a kept agent (Stop, chat delete, idle stop) stops its process tree as when the app runs the agent itself. An agent whose launch reply never reached the app is stopped after a minute.

Why

Restarts and updates should not cost users their running work. Reattaching to the same process keeps the in-flight command, background shells, MCP servers and approvals intact, which a resumed thread cannot.

Linked Issue

Part of #46100 (the Codex part; other chat agents follow in their own PRs).

Visual Proof

Linux, unpackaged build of this branch. The screenshots are DOM renders, because the test window runs hidden.

Quit mid-reply, closed 24 minutes, relaunched. The 300-line reply that was streaming at quit shows whole in one row: no lines missing, none repeated, and no offer to continue. The same agent process stayed alive the whole time.

reply kept across quit

A long command keeps running across a quit. Its output filled the terminal host's 16 MiB buffer while Orca was closed. After the relaunch the running row shows its command and its saved output, and the command keeps going.

running command after relaunch

The same command finished in the same agent, exit 0 after 21 minutes, with no lost-output or interrupted notice.

command finished

macOS (M4 Air): updating Orca from one build to the next with a chat mid-turn keeps the same agent process. The reply continues as one block, and an approval that was pending at quit shows again as a normal prompt.

Testing

Real runs of an unpackaged build on Linux (14 rounds), plus an update run on macOS:

  • A Codex chat mid-turn survives quit and relaunch: same agent process, the running command keeps going, its output while Orca was closed appears in order with nothing repeated, and the turn ends normally.

  • An approval asked while Orca was closed shows as a normal prompt after relaunch.

  • A long command that prints tens of MB across a restart catches up and keeps streaming onto the same command row; the earlier output stays on view.

  • A chat left idle while Orca is closed is stopped after the idle-stop setting; one with a turn or background task running is not.

  • A chat whose reply finished while Orca was closed is not idle-stopped before the next launch shows the reply; after that, the idle stop works as usual and the next message starts a fresh agent.

  • A chat reopened after its output filled the terminal host's buffer shows the running command and its saved output, and the command finishes in the same agent.

  • A normal quit with no running turn offers no continuation after relaunch.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • Every added test fails without this change and avoids the test anti-patterns

Unit tests cover the parts where a silent regression would lose data: the daemon spool (memory keep, file spill, caps, cut reporting), acknowledgement only after save, replay after a cut, and Codex reattach rows.

  • codex-shared-server-pool.test.ts: the "never shares a server" case now checks that a custom-command chat (and one with sharing off) is never shared on Linux, macOS and Windows, instead of expecting the plain launch everywhere; on macOS and Linux a chat's own server is relayed on purpose. Windows still expects the plain launch.

Performance

Linux, this branch (H) against main (M). Each run took 120 one-second samples, alternating builds. Values are % of one core.

  • Idle, 4 Codex chats each after a finished turn: H equals M within the spread between runs.

    • Main process: H 0.97–1.01, M 1.05–1.23.
    • Main thread: H 0.62, M 0.59–0.71.
    • Terminal host: +0.01.
  • Streaming, a line every 0.2 s per chat, at three loads. The main-thread difference H−M is within the noise between runs:

    • 1 chat: +0.07.
    • 4 chats: +0.01.
    • 4 chats, larger lines: −0.03.
    • The terminal host, which now reads the agent's pipe, adds 0.11–0.21 points.
    • Acks to the terminal host ride one shared 1 s cadence per connection and go as one batched request, so their cost does not grow with the number of chats.
  • 24-hour cap: one timer per terminal host, not one per chat, and only for agents idle with unread output, with unknown work, or only waiting on an approval; agents with running work arm nothing, so a closed Orca adds no recurring wakeups. Adding or removing an agent costs the same however many are counted.

  • A chat waiting on a terminal host that can't answer: one shared timer serves every such chat. Once backed off it wakes at most every 5 minutes for all of them, so at most 12 wakeups an hour however many hosts. It runs only while a chat waits. A perf contract checks both. The agent checks behind it run 4 at a time, one per agent.

  • Launch: chats that can't have a kept agent open without waiting on the terminal host; restart offers don't wait for kept chats to reattach.

  • Ack floor: a Codex item's completion line (which carries its full text) is matched to its open item without being parsed.

  • Keep-alive lines: the daemon drops transport-only lines the provider names (a short line, matched by its top-level name) and neither forwards nor spools them. The daemon's read of the agent's pipe takes the place of the app's read of the same line, so wake-ups per keep-alive match today. A provider that names none pays one empty-set check per line.

  • Held replay after a reattach: handed on in slices of about 64 KiB, yielding between them. A 50,000-line replay ran as 272 slices, with the longest main-thread run 2.4 ms. Before, it was one 20.7 ms run, with a reader that does nothing.

  • Ack barrier: the check for unsaved streamed text no longer joins the text. With 16 MiB buffered, each ack took 0.61 ms and copied 16 MiB before; now it takes under 0.001 ms and copies nothing.

  • Acks follow what the chat's reader took: one number per line still waiting in the reader, and nothing extra per line once it is taken.

Risk

  • Scope: macOS and Linux chats whose own Codex agent runs locally. Windows, SSH and other remote-host chats, bot chats and shared Codex servers are unchanged.
  • Upgrade: a terminal host that doesn't offer the relay is detected at launch and chats start as today. Downgrade: an older app doesn't reattach; agents left by the newer app finish their open work and then stop by their idle rule.
  • Data: output is acknowledged only after the chat's history saved it, so a crash during catch-up replays from the last saved line. If a turn outgrows the host's caps while Orca is closed, the chat says output was cut and offers to continue, as a restart does today.
  • Back out: a plain revert. Agents a terminal host already keeps are then reattached by no app; they stop by the idle rule or the 24-hour cap.

Known limits:

  • Same as today (where quitting stops the agent): if a kept agent ends while Orca is closed, output the chat never saved is not recovered, and the chat recovers as it does today.
  • Same as today: if a kept agent dies while its chat is reopening, the open waits for a request timeout before the chat recovers.
  • Chats on SSH and other remote hosts keep today's launch: quitting Orca stops their agent, as before.
  • If Orca quits while a kept chat is still reopening, the agent goes back to the terminal host with its work unknown; it is stopped after 24 hours if no launch reattaches it first.
  • A detached agent with work still running (a turn that isn't waiting on an approval, or a background command such as a dev server) is never stopped while Orca is closed, like a terminal running the same command. One whose only open work is an approval waiting for an answer is stopped 24 hours after Orca closed: its output is kept, and the chat shows the approval as cancelled.
  • An agent with output no app has taken yet is never idle-stopped while Orca is closed, so the next launch shows it all. After 24 hours closed it is stopped and its output kept on disk (up to 16 MiB, for 7 days or until the chat is deleted), but that output isn't shown yet; a follow-up (STA-18240) adds that.
  • A reboot, or the terminal host exiting, while a chat holds output no app took loses that output.
  • Same as today: a command an agent detached into its own session (for example with setsid) is not stopped with the agent on Stop, chat delete or quit. Commands the agent runs as its own background work are stopped, and keep a closed chat from being idle-stopped; a detached one the agent doesn't report doesn't.
  • An agent whose output is held at the terminal host's 16 MiB spool cap waits there (paused) until the next launch, which replays it. A paused agent with its work still open counts as busy, so it is never stopped while Orca is closed; once its work had ended, the 24-hour cap above applies.
  • A reattach names at most the 64 most recently active subagents still running in a chat (the rest are logged): any others aren't registered for Stop and their next message may take a saved row's number. The agent, its output and the reopen are never affected.
  • A reopen looks at no more than 512 of the agent's loaded threads, reading the newest first under a 5-second limit with one short retry. A subagent that a very slow agent doesn't answer for in time, or that falls past those 512, isn't registered for Stop and its next message may take a saved row's number. A nested subagent can delay that one chat's reopen by up to about 10 seconds per level (STA-18479).
  • A subagent in the chat's latest turn shows its nickname on reopen, not the name it was spawned under (STA-18453). The replayed tail of an earlier turn can be credited to the running turn (STA-18454).
  • If Orca can't reconnect to a kept chat, the agent goes back to the terminal host with its open work unknown, so the 24-hour cap applies to it unless the chat is sent to before then. A background command running longer than that is stopped. If unread output outgrew what the host keeps at a detach, a task whose end was lost keeps the agent until the next launch (STA-18502).
  • A terminal host only treats a command as not yet started while its start approval waits if the app names that approval type when it hands the agent over; every Orca build that keeps agents running does. A client that leaves it out keeps such an agent past the 24-hour cap (kept, never lost).
  • A Codex chat whose launch carries a token from Orca's own tool relay keeps today's launch (quitting stops it), because that token and the relay's local port end with the app: bot chats, and, only with the MCP servers feature turned on, chats using a host MCP server that goes through Orca's relay (one with saved headers or Orca sign-in, or a shared command server).
  • With the idle stop set to never, no detached agent is stopped for being idle, including one holding unread output: it waits for the next launch.
  • A reopening chat keeps up to 64 MiB of the agent's output unsaved while it opens (four times the usual 16 MiB). If the agent prints more than that during the reopen, the oldest of it is lost (always on Orca's side, at the host only if Orca then crashes before the chat saves it); the chat continues on a new row after the gap. If the terminal host can't write its spool file, the hold is in memory only and capped at 1 MiB, so a crash during that reopen loses the held output past 1 MiB.
  • If the terminal host that kept a chat's agent can't be reached at launch, and Orca can't prove the agent ended, the chat waits as still running. Sending to it asks again at once. Otherwise Orca asks again as soon as that host reconnects, or on a backoff from a few seconds up to every 5 minutes while the chat is open (one shared check for all such chats; Brennan's choice). A host that is hung, or whose connection point was lost while its agent still runs, is tracked in STA-18721.
  • After a downgrade, an older Orca stops any kept agent whose kind it can't reattach, so that chat recovers as it does today rather than getting a second agent beside the kept one (STA-18721).
  • While Orca is stopping such agents at launch (each stop can take up to 30 seconds), a send to another kept chat whose agent just ended can wait until that finishes (STA-18721).
  • Rarely, when two checks overlap at launch, a restart offer can appear for a chat whose agent the terminal host had already stopped as idle. The next check removes it (STA-18721).

Level: High

Review

Review the Codex reattach (open, numbering, replay) and the host's relay lifecycle (idle stop, 24-hour cap, close) first; the rest is wiring.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Security: the relay directory is private to the user and checked on use; spools are deleted with their daemon. Cross-platform: macOS and Linux only; Windows unchanged. Remote SSH: unchanged (known limit above). Mobile: no change. Backwards compatibility: an older terminal host is detected at launch; one that predates naming agents keeps its relays listed. Performance: see above.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…ce after a torn write; spill reads retry, torn spill tails are cut, and dispose waits for spill work
…pill read counts as lost, undecodable lines are reported, dispose waits for disk at most 2s, and a removed relay is never kept by a timer
…n't be decoded or recorded is reported lost without dropping later lines; a disposed reader delivers nothing; a failing disk caps a held line at 256 MiB
…s line cap holds at its newline, a dropped line's spill file is removed, and a failed rebuild reports the line lost
…er-cap line skips its spill read, writes queued before a spool removal never land, a late spill write after dispose cleans up, and replay joins only the record that ends
…he agent with a named error instead of being skipped
…ne-too-large; the drop-and-skip path for huge lines is gone
…t during a takeover, settle a released attach's waits, fail an attach whose spool can't be read, release answers after they reach stdin, charge records by UTF-8 bytes, send the initialize answer as events, and bound client lines
…ay-core

# Conflicts:
#	src/main/daemon/server/daemon-request-router.ts
#	src/main/daemon/server/daemon-server.ts
… supersedes a replay in flight, and an old answer can't release a re-sent request
…a seen ended relay with nothing to ack is released, a launch after the shutdown fence is refused, every shutdown path waits for one relay cleanup, and an unreadable spool ends the agent with spool-unreadable
… during attach keeps the spool detached, and a missing or cut-short spool ends the agent with spool-unreadable and counts its lost records as acked
…ach reports only the replay it sent, and a spool missing any expected record ends the agent with spool-unreadable
…ry claims none, and replay counts and sends only rows the index says the file holds
…till unacked, so an acked or already-removed row never ends a healthy agent
…pire an ended relay a day after it ends even while attached, clean up a late failed spill write, parse an escaped resolve method, keep looking for the initialize answer, treat a stdout read error as end of output, bound queued input, count only running relays as killed, and always remove the spool path on dispose
…out read error without publishing a fragment, cap queued input including the write and announce refusals on the stream, clamp a cursor past the end at attach start, and catch any escaped printable character in keys
… request-only instead of announcing refusals, and remove the spill file whenever the line reader is disposed
…batch on relayAckWanted, agent lines are classified from their envelope prefix without a full parse, and large writes go in documented chunks
…eaves at once, so storage and dequeue stay within the cap
…gain at once when that start says hello, otherwise on one shared backoff to 5 min, uncapped while it waits and stopped when its last chat closes
…cadence, so wakeups don't multiply with starts
… that acts on a listing ends relays this build can't reattach, once
…ed only by close, deletion or a new run; a rebind that never opened its chat clears its undecided run; the retry timer only moves earlier, with one pass per wakeup
…estart offers read idle stops from the answer they heard; a failed rebind forgets only an undecided run nothing still asks about
… contract holds that a pending cleanup close is sent once at 100 and 1,000 fresh asks
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan at 74dc468 (final head)

Incremental scans r23 to r26, plus a confirming pass on 74dc468, cover:

  • the liveness revision;
  • the option C retry (one shared timer on a 5 min cadence, woken by the daemon's hello);
  • the exit-probe pool;
  • listing cleanup.

Each P0 and P1 they raised was fixed and confirmed by its raiser. Two perf contracts guard the bounds:

  • structured-agent-session-kept-open-reconciler.performance.test.ts: one timer however many chats and daemon starts wait, none once none waits, and at most 12 wakeups per hour for 20 staggered starts (97 when reverted);
  • provider-relay-launch-inventory.performance.test.ts: one cleanup close at 100 and 1,000 fresh asks.

Work in the last batch (r26)

New or changed work Trigger, population and bound
Cleanup sharing First owning ask scans R rows once and closes each unsupported row sequentially. W fresh asks during cleanup add no listing or cleanup pass. Each close has a 30-second request timeout; total cleanup can therefore take approximately U × 30 seconds. Observers initiate no cleanup.
Listing freshness and pruning Completion resets the two-second reuse window. Cache misses retain the existing O(I) pruning pass, adding one cleaning check per entry. Fresh reads resume after cleanup completes. Listing reads retain their three-second timeout.
Listing answer retention Each successful answer assigns the existing R-entry map to answer; no second map construction or payload copy. Idle-stop queries use two keyed lookups.
Shared spawn-token readback Concurrent placement asks for the same chat/relay share one pending read. For 100/1,000 chats with two overlapping asks each: 100/1,000 reads instead of 200/2,000. Linux reads/parses B environment bytes once per flight; macOS and Windows perform no environment read here. Entries retire on settlement. Storage is O(C), with caller continuations proportional to W.
Atomic placement One row/token publication per chat/relay after readback. Already-placed asks skip readback; post-await fencing suppresses obsolete publication.
Gone-answer fence One scalar fence update per accepted gone answer prevents older asks from placing a row. Existing conclusive-answer probe cancellation remains indexed by that chat’s interests and waiters.
Restart-offer idle-stop filtering Each of M markers gains constant-size placement inspection and keyed idle-stop lookup. Total added work is O(M); no additional daemon request or cleanup pass.
Failed-rebind forgetting One session check, one ask-map check and a verdict deletion. Missing probe-interest retirement is the finding above.
Verdict-module extraction Existing ask map, unknown set and sequence move to one module; they are not duplicated. Ask entries still retire when their in-flight count reaches zero. No new timer, storage write or heavy dependency.
Cleanup performance contract Inspected assertions issue 100/1,000 fresh asks while a close is pending, require one close, then require a newly listed unsupported relay to close after release. Not executed.
Cadence contract Fixed epoch and longer settling; checks all 20 waiting starts remain represented and distinct ask timestamps number 1–12 in the measured hour. Not executed. Production scheduling is unchanged: one timer, O(D) dispatch visits, a shared five-minute ceiling, and zero continuing retry wakeups without waiting chats. Ceiling cadence remains at most 12 wakes/hour, approximately 0.0033/s per reconciler, before and after this batch.
Question Disposition
Work before skip gates Observer cleanup and already-placed readback gates precede expensive work. Pending readback is now shared.
Ownership multiplication Active cleanup and token reads share their resource owner. Failed-rebind probe ownership is incomplete—the finding.
Thread and storage Main owns maps, scans and parsing. No added synchronous filesystem call, SQLite operation, persistence rewrite or migration.
Growth and progress Listing construction remains O(R); cleanup is sequential and shared. Abandoned probe admission scales with failed unopened chats.
Execution host Linux readback and macOS skip inspected. Existing Windows and remote-host relay exclusions remain. No native-host performance measurements.
Obsolete-work release Token entries settle and fenced asks cannot publish. Failed unopened chats no longer retire their probe interests.

r26's one P1 (a failed rebind leaving its exit-probe interest queued) is fixed in 74dc468. Confirming pass:

The P1 is resolved. A failed rebind with no adopted session and no ask in flight now removes the chat’s exit-probe interest and waiters. A probe drops from the queue or overflow when no other chat or waiter needs it. The cancellation uses the chat’s index, so it does not scan the full queue. Verdict cleanup · Probe cancellation

Git confirmed the requested head and that this one-line fix is the entire diff since the previous scan. No P0 or P1 remains in scope. The verdict is based on source inspection and Git comparison. Tests were not run.

@brennanb2025

brennanb2025 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status at 74dc468 (final)

The problem. Quitting or updating Orca stopped every running Codex chat agent mid-turn, so its work was cut and had to be resumed.

What users get. On macOS and Linux, a local Codex chat's agent keeps running under the terminal host while Orca is closed. Orca reattaches to it on relaunch: the turn keeps going, output that arrived while Orca was closed is replayed, and an approval held across the quit is asked again.

What changed in this last stretch (the liveness revision). Each run now records which daemon start holds it, and only that start's own answer decides whether the run is still going.

  • If that start can't answer, the chat waits as still running. Orca asks again:
    • when you send to it;
    • when the start reconnects;
    • otherwise on one shared backoff, up to every 5 minutes.
  • The run counts as ended only once both the daemon and the agent are proven gone (Brennan chose this retry: option C).
  • Quit hands a reattached agent back to its daemon.
  • Concurrent checks are fenced, so a late answer never overrides a newer one or outlives a closed chat.

Fixed after review (Codex audits r29 to r32, perf scans r23 to r26, Claude r29 to r32, and ACP's recheck 49 and Claude audit 51):

  • No stale "unknown" mark survives a close, deletion, new run or failed rebind.
  • Concurrent checks never lose a kept agent's Linux spawn token.
  • Agent exit checks run 4 at a time with a bounded queue.
  • Fresh checks share an unfinished cleanup and one token read.
  • An observe-only check has no side effects.
  • The retry stops when its last chat closes.

Verified on this head:

  • Gate: pnpm check:changed passes, 31/31.
  • Perf contracts:
    • One timer for any number of waiting chats and daemon starts, none once none waits, and at most 12 wakeups per hour for 20 staggered starts (97 when reverted). It passed 50/50 under node and 50/50 under the unit runner.
    • One cleanup close at 100 and 1,000 fresh asks.
  • Perf scan: clean at 74dc468 (comment above).
  • Regression audit: SAFE at 74dc468.
  • Claude review: READY TO MERGE at 74dc468.

QA: round 25, Omarchy Linux, on 4882b02, passed 7/7. The two commits after it don't change these flows: one test-only commit, and a one-line fix to the failed-rebind cleanup.

  • S1, five runs: a turn running sleep 60 survived a graceful quit and relaunch, with the target chat visible in 3 runs and another chat visible in 2. Each kept the same Codex process, finished exactly once, showed no restart offer, continue row or error row, recorded placement relayed, and left 0 stale-session settlements.
  • S6 A and B: an approval held across the quit was asked again once after relaunch, and Allow ran it in the same process.

S1, after relaunch, then finished:

S1 after relaunch
S1 done

S1 with another chat visible at relaunch:

S1 run 2 after relaunch

S6 A, the approval chat visible at relaunch:

S6 A asked again
S6 A after Allow

S6 B, another chat visible at relaunch:

S6 B asked again
S6 B after Allow

Deferred, each with its raiser's agreement (STA-18721, and in Known limits):

  • An older build stops kept agents it can't reattach after a downgrade.
  • A fresh check can read "kept" while a slow cleanup runs.
  • A rare stale restart offer for an agent already idle-stopped.
  • A once-per-outage scan before the shared cadence.

Base: this PR is stacked on #47229 (core), which brennan-ready reports READY at c0dd925.

(screenshot removed: contained real product data)

s1-1-after-done

(screenshot removed: contained real product data)

s6-a-after-relaunch

s6-a-after-allow

s6-b-after-relaunch

s6-b-after-allow

@brennanb2025
brennanb2025 marked this pull request as ready for review November 26, 2026 21:58
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan at 74dc468: version-bump surface

Line 84 records the open’s journal boundary. It reads the acknowledged cursor, adds one to calculate the first sequence after it, and stores that number in a private WeakMap for the session. It leaves the journal cursor untouched and emits zero subscriber frames at any subscriber count. The nearby publishRestored calls run independently of that value. Boundary capture · Cursor read · Restore publication

If the prior run is later proven gone, recovery uses the stored number as the since boundary for markQueueReopen. Source inspection confirmed the detector hit does not represent a version publication. Settlement · Queue recovery

…ay-codex

# Conflicts:
#	src/main/daemon/protocol/daemon-hello-protocol.ts
#	src/main/daemon/protocol/daemon-provider-relay-protocol.ts
#	src/main/daemon/provider-relay/daemon-provider-relays.ts
#	src/main/daemon/provider-relay/provider-relay-attachment.ts
#	src/main/daemon/provider-relay/provider-relay-host.ts
#	src/main/daemon/provider-relay/provider-relay-pending-requests.ts
#	src/main/daemon/provider-relay/provider-relay-requests.ts
#	src/main/daemon/provider-relay/provider-relay-spool-memory.ts
#	src/main/daemon/provider-relay/provider-relay-spool.ts
#	src/main/daemon/provider-relay/provider-relay.ts
#	src/main/daemon/provider-relay/testing/provider-relay-pending-requests.test.ts
#	src/main/daemon/provider-relay/testing/provider-relay-spool.test.ts
#	src/main/daemon/server/daemon-client-connections.ts
#	src/main/daemon/server/daemon-request-router.ts
#	src/main/daemon/transport/client/daemon-client-hello-handshake.ts
@brennanb2025
brennanb2025 changed the base branch from brennanb2025/chat-relay-core to main November 27, 2026 02:03
@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

This change adds daemon-managed provider relays and app-side support for launching, attaching to, and detaching provider processes. It adds relay acknowledgements, output replay, work tracking, idle-stop handling, and run-liveness checks. Session recovery now preserves journal state for kept writers and can rebind retained agents. Codex app-server sessions add relay reattachment, replay continuation, and restoration of kept turns and command output. Connector cloud options move to a separate module.

Merge Risk: High · up to f58c0

This change lets Codex chats survive an Orca restart on macOS and Linux, but several paths can lose or duplicate saved output, settle a still-running agent as ended, or leave a detached agent running past its limit. Restart recovery can also wait on the relay listing even for chats that cannot be kept. These issues are mostly edge cases but affect user data, so they should be fixed or explicitly accepted before merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title 'Codex chats keep working when Orca restarts (macOS and Linux)' matches the main change: a relay through Orca's terminal host lets local Codex agents keep running across quit and relaunch on…
Description check Passed The description follows the repository template closely. It includes ELI5, What Changed, Why, Linked Issue (Part of #46100, with no 'Fixes #' closing reference), Visual Proof with before/after media f…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title 'Codex chats keep working when Orca restarts (macOS and Linux)' matches the main change: a relay through Orca's terminal host lets local Codex agents keep running across quit and relaunch on macOS and Linux. It is specific and concise, and it names the platform scope. The title does not mention the relay mechanism, but the question only asks whether it describes the primary change, and it does.

Full details: Description check

Explanation

The description follows the repository template closely. It includes ELI5, What Changed, Why, Linked Issue (Part of #46100, with no 'Fixes #' closing reference), Visual Proof with before/after media for Linux and a macOS update run, Testing with manual and automated test checkboxes, Performance with a concrete measurement breakdown, Risk with level High and a back-out plan, Review notes, and a completed checklist. The main gap is that the Linked Issue section uses 'Part of #46100' rather than the 'Fixes #' form the template asks for. The Review section and the AI Disclosure section are also thin, and the Visual Proof section relies on DOM-render screenshots of a hidden test window that are not verifiable from the text. These gaps are non-critical, so the description is mostly complete.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Major comments: 23

src/main/daemon/provider-relay/provider-relay-spool.ts: 1

325-327: Major · Data Integrity & Integration · Heavy lift

Spills during attach can drop output that the file replay never reads.

During a replay, a held acknowledgement can set heldSpill to 'memory'. When held memory reaches memoryCap, the branch at provider-relay-spool.ts:325-327 moves those records to the file, even though mode is still 'replaying'. SpoolFile.write indexes them at once, but their append can land after the file reader has reached end of file. Attach waits for writes only before it captures fileLast, so the reader does not wait for them.

When the reader misses such a record, its countAfter check reports 'lost', and attach calls onFileLost. The memory tail then starts at file.highest and scans only memory, and those records are no longer in memory. Records above fileLast are therefore neither delivered nor covered by lostThrough. Attach completes with a loss notice, not with the output in sequence order.

Required behavior: every record appended during attach must be delivered in sequence order before attach hands off to live delivery, or the attach must report every undelivered record. The choice between these approaches is open. Either way, the spill at lines 325-327 must not move records that a replay still has to deliver without the replay accounting for them.

src/main/daemon/provider-relay/provider-relay-detached-cap.ts: 1

59-59: Major · Stability & Availability · Quick win

Count finished unread relays when idle-stop is disabled.

If idleStopMs is null, a detach with open: {} and unread output has tracking=true, unaccounted=false, and onlyWaiting=false. This condition does not count the relay. ProviderRelayIdleStop.arm also schedules no timer, so the relay never reaches the 24-hour cap.

Include finished unread relays in cap admission independently of the idle-stop timer. Keep the busy-work check in fire.

src/main/daemon/provider-relay/provider-relay-work-markers.ts: 1

288-289: Major · Stability & Availability · Quick win

Enforce the open-task bound before retaining more keys.

After 1,025 distinct start markers, tasks contains 1,025 keys. Setting overflowed does not stop later starts or rosters from retaining more keys. A long-lived detached agent can therefore grow daemon memory without bound. Known open work also keeps that agent exempt from the detached cap.

Limit retained keys to MAX_GROUP_TASKS on each insertion path. Keep overflowed=true when keys are omitted, so missing identities cannot permit an idle-stop.

src/main/provider-relay/relayed-managed-process.ts: 1

127-127: Major · Stability & Availability · Quick win

Do not report tree exit when close cannot confirm it.

If the close RPC fails and no exit arrives, close() returns { root: 'live', tree: null } after the wait. terminateTree() discards that result and returns 'exited'. This tells the caller that termination succeeded even though the agent can still be running. Return the tree verdict from close(), or map an unconfirmed result to the managed-process contract’s non-exit verdict. Keep returning 'exited' when exit is confirmed.

src/main/provider-relay/relayed-provider-consumption.ts: 1

34-39: Major · Data Integrity & Integration · Quick win

Take a record only after its handler returns successfully.

In countedRelayRecords, records.taken() runs in finally, so it also runs when onRecord throws. The cursor then moves past a record the chat never accepted. A claimed reader's upTo can include that seq, and taken() arms an ack for it. If the ack fires before the fatal close stops the output, the daemon can discard output the chat did not process, and that output is not replayed.

Call taken() only after onRecord returns. A throw then leaves the cursor before the failed record, so the record is replayed on reattach.

Suggested fix

     onRecord: (record, line) => {
-      try {
-        onRecord(record, line)
-      } finally {
-        records.taken()
-      }
+      onRecord(record, line)
+      records.taken()
     },
src/main/provider-relay/relayed-provider-child.ts: 1

303-305: Major · Stability & Availability · Heavy lift

A failed mid-turn reattach can end a kept agent's child without checking whether the daemon still runs it.

If the replacement stream closes while relayAttach is pending, the disconnect handler returns at line 277 because the state is reattaching. If that attach rejects, the catch at lines 303-305 ends the child with outcomeLost. The same catch also handles ensureConnected() failures and daemon pid mismatches, so a transient connection error ends the child the same way. The catch comment says the host is gone, but this path does not establish that.

The launch path treats a failed attach differently. reattachListed in app-provider-relays.ts asks the run's daemon start for its answer and throws KeptProviderRelayUnreachableError unless that answer proves the agent gone. The mid-turn path has no equivalent check. It also does not return the relay to the kept inventory, as keep() and quit detach do. If the daemon still holds the agent, the chat can lose its handle to that live work. Recovery at the next open depends on launch gating that this change does not show.

Settle the child as lost only when the daemon proves the agent ended. Otherwise keep the relay listed and resolve it through the run gate, as the launch path does. The same principle applies to any transient reattach failure.

src/main/provider-relay/relayed-provider-output.ts: 1

401-403: Major · Stability & Availability · Quick win

Retry a failed ack while the daemon is waiting for it.

settle() cancels the scheduled tick before answering the daemon's force request. If the ack fails before the daemon applies it, this catch leaves no retry scheduled. At the output cap, the daemon can be waiting for this ack before it sends more data, so new output cannot reliably trigger recovery.

Schedule a backoff retry while the request remains outstanding. Preserve the force mode for a held replay, and cancel the retry on stop.

src/main/provider-relay/relayed-provider-held-output.ts: 1

64-64: Major · Data Integrity & Integration · Quick win

Keep requests deduplicated after release hands them on.

next() advances the release cursor but leaves the request in pending. If release yields and a reconnect resets the buffer, restartAt() removes the deduplication entry for a request the chat already received. The daemon can then deliver that approval request again.

Store the pending sequence on the held request entry. Remove it from pending when next() hands on that entry. Leave requests that have not been handed on eligible for replay.

src/main/provider-relay/relayed-provider-input.ts: 1

47-51: Major · Functional Correctness · Heavy lift

Do not let a rejected relayed write leave the child's stdin unusable after reattach.

When a write starts in the attached state and the connection drops, sendRelayedInput reads the stale pre-write state. It rethrows the rejection without waiting for the reattach that the child has already started. The error then reaches the relayed child's stdin write callback. That callback is a Node Writable callback, so the error can destroy stdin. Later input can then fail even after the reattach succeeds.

The transport does not report whether the rejected frame reached the daemon, because rejectAll uses the same generic rejection for every pending request. A retry after reattach could therefore send the frame twice. The fix needs a policy choice. It must decide what happens to a frame whose delivery is unknown. It must also keep the relayed stdin usable after a transient write rejection. Waiting on the current reattached promise before rethrowing, with the stale check corrected, is one way to handle the wait. The retry policy for unknown delivery is still open.

src/main/provider-relay/app-provider-relays.ts: 1

225-226: Major · Data Integrity & Integration · Quick win

Check unread output at close time, not from the listing row.

When a reattach attach reports an exit for an agent that its integration does not open after it ends, reattachListed settles the chat as gone. The unread check at line 225 still uses info from the launch listing. If the listing shows nextSeq=11 and ackedSeq=10, the agent can emit sequence 11 after that listing and exit during the attach. The stale check then reports no unread output, and the branch closes the relay. The daemon removes the relay and disposes its spool, which can discard sequence 11 before the user sees it. The comment at line 224 states that a failed attach never drops unread output, so this path violates that contract.

Read the relay's current unread state immediately before the close call. Skip the close while output above ackedSeq remains.

src/main/provider-relay/provider-relay-kept-rebind.ts: 1

23-24: Major · Data Integrity & Integration · Quick win

Search an AggregateError's cause as well as its errors.

For new AggregateError([], 'start failed', { cause: new KeptProviderRelayUnreachableError('c') }), this branch returns false. It never checks cause.

The supplied failedAcquisitionSettlement consumer then selects exit-proven instead of unproven. Search both errors and cause with the existing depth limit.

src/main/provider-relay/provider-relay-launch-inventory.ts: 1

221-221: Major · Data Integrity & Integration · Heavy lift

Do not use cleanup state to freeze fresh relay listings.

If an unsupported relay's close remains pending, cached.cleaning forces every fresh ask to reuse the earlier snapshot. If a supported relay starts after that snapshot, a fresh liveness check for its recorded placement receives a map without that relay. decide then returns gone for a running agent.

Separate pending-close deduplication from listing freshness. Fresh asks must refresh a completed listing without sending duplicate closes for cleanup already in progress.

src/main/provider-relay/provider-relay-run-liveness.ts: 1

62-62: Major · Data Integrity & Integration · Heavy lift

Settle the gate's verdict only for the run it was asked about.

The gate at structured-agent-session-kept-open-reconciler.ts:64-76 calls settleNow(chatKey) for a gone verdict. It does not check that the chat still has the run that the verdict describes. Ask flow in provider-relay-run-liveness.ts:58-65 can finish after a replacement run is placed. Its stale gone is returned unchanged. settleNow then settles whichever session is open for the chat, using the current fence. If the replacement run has no child, it can be settled as ended while its agent still runs. This also allows a second agent to start for the chat.

Before the gate calls settleNow, check that the run from the record is still the chat's current run. Apply the same check to a kept release. Stale verdicts must not change the open session. Also check that settleNow does not clear opened or call closed for a session that the verdict did not describe.

Source: Learnings

src/main/native-chat/agent-session-wire/delivery/structured-agent-session-kept-open-reconciler.ts: 2

243-245: Major · Data Integrity & Integration · Heavy lift

Re-check session identity and disposal inside the serialized settlement.

retry reads the session and run record before it awaits the liveness check. After a gone verdict, settleNow reads the current session and fence instead of the session that the verdict describes. If the chat closes and reopens during the check, and the new session is adopted while its run is still unknown, the old verdict can settle the new session. The same verdict also removes the chat from retry.chats and waitingOn, so the new waiter stops being asked.

A settlement that starts after dispose() has the same gap. Neither retry nor settleNow checks disposed, and dispose() leaves sessions and opened intact. A settlement can therefore write after teardown has started.

Capture the session before the await. Inside the serialized settlement, apply the verdict only when the reconciler is not disposed and the current session is that same object. Apply the waiter removal under the same condition. Apply the same check on the gate path, which also reads the record before its await.

Source: Learnings


246-247: Major · Functional Correctness · Heavy lift

Reattach a kept chat before its queued sends are held.

On a kept verdict, the reconciler only releases the chat from waiting. It starts no reattach. The only caller of rebindKeptAgent runs at launch, for runs already listed then. A chat that becomes kept after launch therefore has no child. While the run stays kept, keptAgentPending returns true, so the queued drain skips the chat and its queued sends stay held.

Restore the child for a kept run through the same reattach path the launch continuation uses, before the chat is released from waiting. Otherwise a kept chat can keep queued sends held while its agent runs.

src/main/native-chat/agent-session-wire/host/structured-agent-session-host-runtime-state.ts: 1

266-271: Major · Data Integrity & Integration · Quick win

Read the awaited sink's live-text state in landed mode.

flushEventSink awaits the landed barrier of the sink returned at call time. The final return then calls sink() again. If adoptEventSink replaces that sink during the await, the method reports the replacement's live-text state. It does not report the state of the sink the barrier covered. The relay acknowledgement path uses this boolean as its gate. A replacement that carries no live text can therefore allow an acknowledgement while the awaited sink still holds unsaved streamed text. The method's own contract says the result must be false in that case.

Capture the sink once and use the captured sink for both the barrier and the live-text check:

Suggested fix

   async flushEventSink(sessionId: string, landed?: true): Promise<boolean> {
     const sink = () => this.currentEventSink(sessionId)
     const ok = Promise.resolve({ ok: true } as const)
-    await this.requireSuccessfulBarrier((landed ? sink()?.landed() : sink()?.drained()) ?? ok)
+    const target = sink()
+    await this.requireSuccessfulBarrier((landed ? target?.landed() : target?.drained()) ?? ok)
     if (!landed) {
       await this.childWork?.drainChildWork(sessionId)
       await this.requireSuccessfulBarrier(sink()?.drained() ?? ok)
     }
-    return !landed || !sink()?.hasLiveText()
+    return !landed || !target?.hasLiveText()
   }
src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-queue.ts: 1

181-182: Major · Data Integrity & Integration · Heavy lift

Do not authorize relay acknowledgements on writes that close() dropped.

landed() waits through acceptedSequence. close() drops buffered writes and advances settledSequence, so the wait succeeds for writes that never reached the journal. flushEventSink(id, true) then returns true once hasLiveText() is false. Termination can leave the closed sink current: host-lifetime closes it without discarding it. A later non-forced relay ack can then acknowledge lines whose writes were dropped. The comment in that path says those lines replay at the next launch, so a crash after such an ack loses them.

written() already rejects close-dropped writes. The durability path used for relay acknowledgements should apply the same rule, and should not force new work to flush. A remedy must not treat writes still pending in dispatch as dropped. The required behavior is that a non-forced acknowledgement must not succeed for admitted writes that close discarded.

src/main/native-chat/agent-session-wire/startup/structured-agent-session-kept-agent.ts: 1

59-62: Major · Data Integrity & Integration · Quick win

Recheck the child inside the serialized settlement and do not report gone when a child is live.

The session.child check at line 59 runs outside the lane that the settlement callback uses. An attach that already holds the lane can index a child while the callback waits. The callback then settles the current record although a live child owns the generation. settleGoneStructuredAgentSessionGeneration does not check the child or the session identity before it settles.

Move the session.child check inside the context.serialize callback. Keep the settlement only when context.sessions.get(sessionId) === session and session.child is still null. Also change the return value on the skipped path. Reporting gone there tells the caller that the chat was cut while the agent is live. The author must choose the outcome the caller expects for a live child, such as attached or unresolved. This comment does not prescribe that choice.

src/main/codex/structured/items/codex-kept-item-stream-text.ts: 2

19-19: Major · Data Integrity & Integration · Heavy lift

Check the result of the checkpoint flush before acknowledging hand-off.

bindCodexCheckpointLiveText discards the boolean returned by flush() on line 19. The sink calls this callback from flushLiveText, and that method ignores return values. barrier and written in the event sink queue then proceed to seal and wait for admitted writes without checking whether the checkpoint was saved. If checkpoint persistence fails during a hand-off, the path can continue to acknowledgement with output that the journal has not saved.

Return the flush result from the bound callback. Require the sink to treat a false result as a failed barrier, or retry until the save succeeds, before acknowledgement continues.


38-39: Major · Data Integrity & Integration · Heavy lift

Do not overwrite a complete saved command row with a truncated seed.

seedCodexKeptStreamText records the original text length even when the coalescer truncates the seed to fit the remaining total retention budget. The checkpoint then differs from the retained length, so the bound has() reports pending text. After a later delta for the same command, the forced flush saves the truncated snapshot over the complete row. Saved command output beyond the retention budget is lost.

The normal save path is gated by shouldPersist, so this loss comes only from the forced flush on hand-off or ask. The required behavior is that a seed must not replace a complete saved row with a truncated snapshot. Choose the enforcement point: refuse or hold a seed that the coalescer truncates, or prevent the forced save from writing a truncated snapshot over a complete row.

src/main/codex/structured/journal/codex-structured-journal-translation.ts: 1

222-222: Major · Data Integrity & Integration · Quick win

Keep the continuation identity until its tombstone is admitted.

retireCodexRelayContinuation removes the identity at codex-relay-continuation-retire.ts:27 before sink.tryAppendTombstone runs. If the sink refuses the tombstone with backpressure, the notification retry module replays the same notification. On replay the identity lookup misses, so the helper returns admitted and never writes the tombstone. The continuation row stays in the journal.

Remove the identity only after the tombstone is admitted. A refused retirement then remains retryable.

Suggested fix

   const identity = key === null ? undefined : items.identities.get(key)
   if (key === null || !identity) {
     return CODEX_JOURNAL_ADMITTED
   }
-  // Forgotten, so nothing writes to the retired row again.
-  items.identities.delete(key)
   if (!sink.tryAppendTombstone) {
+    // Forgotten, so nothing writes to the retired row again.
+    items.identities.delete(key)
     sink.appendTombstone(identity, { lifecycle: true })
     return CODEX_JOURNAL_ADMITTED
   }
-  return sink.tryAppendTombstone(identity, { lifecycle: true })
+  const admission = sink.tryAppendTombstone(identity, { lifecycle: true })
+  if (admission.accepted) {
+    // Forget only after the tombstone is admitted, so a refused retirement stays retryable.
+    items.identities.delete(key)
+  }
+  return admission
src/main/codex/structured/threads/codex-kept-turn-ordinals.ts: 2

176-176: Major · Functional Correctness · Quick win

Restore omitted carried commands as background work.

If command C belongs to an earlier turn and is absent from the latest turn, this fallback starts C without turnId. The command tracker therefore sets backgrounded=false, and its background-task selector excludes C. The latest turn's completion has already been observed, so it cannot correct that classification. C remains classified as foreground work until another turn ends or C exits. (raw.githubusercontent.com)

Add an explicit background-command restoration path. Preserve the existing start-before-completion handling for commands present in the latest turn.


49-49: Major · Data Integrity & Integration · Quick win

A failed saved-output read can let replayed output overwrite the saved prefix.

When itemBody rejects, the .catch(() => null) at line 49 turns the failure into the same result as a missing row. Nothing is seeded, so the stream starts from the replayed suffix. Its next save writes a body containing only that suffix under the command's existing item identity, and the previously acknowledged output can be replaced.

A read failure must not be treated as "no saved output." Hold the command until its own end when the read fails, as the truncated-head path already does. A missing row can still start with no seeded output.

Minor comments: 25

src/main/daemon/provider-relay/provider-relay-cut.ts: 1

13-14: Minor · Data Integrity & Integration · Quick win

Do not let a rejected cut ack replace the stored cut keys.

ProviderRelay.ack records the cut before spool.ack runs. The spool ignores an older ack (through < clientAcked) and leaves its state unchanged. ProviderRelayCut.record still sets this.keys = cutKeys ?? null. Because through keeps the greater value, a late cut ack with a lower boundary can leave the tracker at the higher boundary with the lower cut's keys. report then returns those keys with that boundary. The replay continuation uses these keys to decide which items the cut split, so it can select the wrong items.

Keep the cut tracker consistent with the spool. A cut ack must replace the stored keys only when the spool accepts it. A rejected or older ack must leave the stored keys unchanged.

src/shared/json-stream/json-value-property.ts: 1

14-14: Minor · Data Integrity & Integration · Quick win

Preserve __proto__ as a JSON data property.

For a parsed acknowledgement entry such as {"relayId":"r","seq":42,"__proto__":{"cut":true}}, Object.assign changes object's prototype. The entry has no own cut field, but ProviderRelayHost.ack reads flags.cut === true and enables that flag.

Use object spread or a null-prototype destination. Both preserve ordinary fields without converting nested JSON into acknowledgement flags.

src/main/daemon/provider-relay/provider-relay-idle-stop.ts: 1

219-220: Minor · Stability & Availability · Quick win

Restore cap accounting when detached work ends.

A detached relay can lose its cap entry and idle check after it reports unread output and then starts new work. The idle check registers the relay in counted and returns without setting waitingForLine (provider-relay-idle-stop.ts:302-305). If work starts, fire() removes the busy relay from counted at the 24-hour deadline (provider-relay-detached-cap.ts:155-158). When that work ends, observeAgentLine runs neither notification branch and schedules no check (provider-relay-idle-stop.ts:212-237). The relay then stays detached without a cap entry or idle timer. It keeps running until the user attaches or the relay is disarmed.

The trigger requires the new work to still run at the 24-hour deadline. The impact is a detached Codex process retained past its configured limit.

When detached work ends with unread output, the relay must return to cap accounting. Either re-register the relay or restart its idle check. The source comment at provider-relay-detached-cap.ts:154 describes this intended behavior. Add a test that covers work starting after an unread idle check, removal at the deadline, and the later end of that work.

src/main/provider-relay/relayed-provider-child.ts: 1

293-298: Minor · Stability & Availability · Quick win

Check the hand-off state after the reconnect wait, before relayAttach.

reattach() sets the child to reattaching and then waits for ensureConnected(). Its only state check runs before that wait. detach() does not reject the reattaching state, so a hand-off can finish during the wait. When the same daemon answers, reattach() still sends relayAttach for the child. The daemon can then keep the relay bound after the child has stopped consuming its output. The success path does not restore attached, so the child stays detached locally.

Return before reading the cursor or sending the attach when the child is handing off or is no longer reattaching:

Suggested fix

       await this.options.channel.client.ensureConnected()
       if (this.options.channel.daemonPid !== daemonPid) {
         throw new Error('A different terminal host answered')
       }
+      if (this.handingOff || this.state !== 'reattaching') {
+        return
+      }
       const fromSeq = this.output.restartAt()

The handingOff flag covers a hand-off that is still settling. The state check covers a completed hand-off. The finally block still resolves the reattach waiters.

src/main/provider-relay/relayed-managed-process.ts: 1

67-68: Minor · Data Integrity & Integration · Quick win

Gate an exit that predates the managed wrapper behind the output-taken check.

When relayExit arrives during child.start(), RelayedProviderChild marks the child exited before the final output is read. The launch path builds the managed wrapper only after start() resolves (app-provider-relays.ts:293). Line 68 then calls observe() at once. Any subscriber that registers through onExit receives the exit immediately (lines 118-124). A subscriber can act on the exit before it reads the final lines.

The child does not do this for its own exit. Its exit event waits for output.allTaken() (relayed-provider-child.ts:337-350). Route an exit that predates the wrapper through the same output-taken gate. Do not notify subscribers synchronously at construction.

src/main/provider-relay/relayed-provider-child.test.ts: 2

130-131: Minor · Maintainability & Code Quality · Quick win

Verify that reattach waits for the pending request too.

Both preamble events use 5 ms timers, and the only assertion checks initializeLine. The test still passes if start() waits for relayInitialize but ignores the reply's pending: [3]. Deliver the events separately. After relayInitialize, assert that start() is still pending. Then deliver relayPending and await completion.

Also applies to: 144-145


82-82: Minor · Maintainability & Code Quality · Quick win

Synchronize the negative exit assertions with exit processing.

Twenty event-loop turns do not establish that the child processed the exit and reached the wait for held output or reader consumption. If exit processing is late, the intermediate assertion can pass before that path runs. Observe the wait or control the dependency that lets exit processing advance, then check that exit has not fired.

Based on learnings, “Fixed delays do not synchronize with background completion,” including a fixed count of event-loop turns.

Also applies to: 119-119

Source: Learnings

src/main/provider-relay/relayed-provider-output.ts: 1

349-349: Minor · Data Integrity & Integration · Heavy lift

Do not acknowledge pushed records the reader has not taken on a forced held ack.

On a forced ack with held output, ackNow sets target from deliveredSeq (line 342), not from the consumed cursor. With no usable floor, keepFrom becomes heldFrom (lines 349, 352). When a reader has taken seq 1, a release has pushed seq 2, and seq 3 is held, the ack sends keepFrom = 3. The daemon then releases seq 2 even though the chat has not taken it. If Orca exits or restarts before the reader takes seq 2, the daemon cannot replay that line.

Keep every pushed record that the reader has not yet taken in the daemon's kept range. Limit keepFrom to no later than the first unread record, or cap target at the consumed cursor until the unread prefix drains. Keeping from seq 3 is correct only after the reader has taken and durably saved seq 2.

src/main/provider-relay/provider-relay-instance-signals.ts: 1

32-32: Minor · Functional Correctness · Quick win

Isolate each wake for the same daemon start.

If the first chat’s wake() throws, the loop stops before the next chat receives its reconnect signal. eachIsolated catches the exception around the entire client listener, not around each wake. Catch synchronous exceptions per wake so the remaining chats can reconcile on this hello.

src/main/provider-relay/relayed-provider-output.test.ts: 2

460-464: Minor · Functional Correctness · Quick win

Assert that the open request is retained and delivered only once.

The set can still have size one if relayPending delivers request 7 again and adds the same key back to the set. Check that request 7 is the surviving key, then submit it again and assert from seen that it was delivered exactly once. As per coding guidelines, a committed regression test must “fail if the fix is reverted.”

Source: Coding guidelines


433-433: Minor · Maintainability & Code Quality · Quick win

Move the ack coalescing contract to the performance suite.

This case counts durability calls and distinct waiting operations while the first barrier is blocked. pnpm test:perf:contracts does not select this file. Move the case to a *.performance.test.ts file and keep the hardcoded work bounds. As per coding guidelines, “Perf contracts: *.performance.test.* only.”

Source: Coding guidelines

src/main/daemon/transport/client/daemon-client-listener-registry.ts: 1

23-23: Minor · Functional Correctness · Quick win

Do not skip the next listener when a listener unsubscribes.

If listener A unsubscribes itself, splice moves listener B into A’s index. The live array iterator advances past that index, so B misses the connected notification. Iterate a stable set of registrations and preserve the rule that a listener removed before its turn is not called.

src/main/provider-relay/provider-relay-exit-probes.ts: 1

167-171: Minor · Functional Correctness · Quick win

Check the current() guard before consuming the cached exit proof.

agentProvenGone reads the cached proof with takeAgentExit before it checks asker.current(). A run can be fenced while daemonProvenGone is pending in provider-relay-run-liveness.ts. In that case the superseded call removes the proof and returns true, even though its ask is no longer current. A current ask for the same process then finds no cached proof, must probe again, and can return false at its deadline.

Run the current() guard first. A non-current ask then returns false without changing the cache, and the current ask can still use the proof.

Suggested fix

-  if (takeAgentExit(key)) {
-    return Promise.resolve(true)
-  }
   if (asker && !asker.current()) {
     return Promise.resolve(false)
   }
+  if (takeAgentExit(key)) {
+    return Promise.resolve(true)
+  }
src/main/provider-relay/provider-relay-run-placements.ts: 1

31-31: Minor · Data Integrity & Integration · Heavy lift

Do not persist a relayed launch as direct when the daemon identity changes during launch.

On the spawn path, child.start(0) awaits before the launch is recorded. If the client reconnects to a different daemon start during that await, noteProviderRelayRunPlacement skips the record because the echoed instance no longer matches identity.launchNonce. takeProviderRelayRunPlacement then returns { kind: 'direct' }, and the process commit stores it. The relayed run is recorded as started in this app. Placement decides how later liveness treats the run, so the run can be judged by the wrong rule.

Fix the mismatch branch so that a successful relay never persists as direct. Any pid and start time recorded for the run must come from the daemon that accepted the relay, not from the newer identity. The placement state used for the mismatch case is a design choice for the author.

src/main/native-chat/agent-session-wire/host/structured-agent-session-conversation-open.ts: 1

176-176: Minor · Stability & Availability · Quick win

Keep a kept-open chat in the retry set when gone-generation settlement fails.

settleGoneGeneration catches errors from the stale-state settlement and only logs them. settleGoneStructuredAgentSessionGeneration returns that result as success. The reconciler's settleNow removes the opened boundary whenever settle resolves. A failed gone-generation settlement therefore releases the chat from retry without settling the gone turn. Recovery still completes first, because the settle callback awaits it before resolving.

Require that a failed gone-generation settlement keep the chat in the retry set, as settleNow documents for failed settles. Keep the best-effort behavior for ordinary open. Choose the mechanism so that recovery still runs on each retry.

src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-kept-at-open.test.ts: 1

106-108: Minor · Stability & Availability · Quick win

Release spawned agents when a test fails.

If an assertion rejects before agent.kill('SIGKILL'), the spawned agent remains running until its 60-second timer expires. The hook at Line 123 only restores mocks.

Track spawned agents and terminate them in afterEach or finally. Await their exit. Preserve the send test's explicit exit synchronization.

src/main/native-chat/chat-deletion/orca-chat-delete.ts: 1

165-165: Minor · Stability & Availability · Heavy lift

A failed relay close must keep its cleanup responsibility.

deleteOrcaChat commits the deletion first, then calls dropListedProviderRelay without awaiting it. That function removes the kept relay from the app's map and starts relay.channel.close(...). A .catch(() => {}) discards any rejection. The function then returns { outcome: 'deleted' } before the close settles.

For a detached chat with no host session and no visible tab, stopChat skips the chat. The relay close is then the only attempt to stop its kept agent. If relayClose rejects, for example after a timeout or a dropped daemon connection, the app holds no record of the agent and reports success. The agent may keep running until it ends or the daemon stops it under its own idle-stop rules. This conflicts with the comment at line 164, which says the kept agent goes with the chat.

Keep the relay's cleanup responsibility until the close succeeds. For example, retain a retryable record rather than dropping the only handle. Deletion is already committed at line 151, so this path cannot refuse deletion at line 165. The fix must choose where a failed close is recorded and retried.

src/main/codex/app-server/codex-relay-reattach-rows.test.ts: 1

347-347: Minor · Functional Correctness · Quick win

Assert the exact final command output.

toContain('3') also passes if the completion replaces the output with 13. Read the final row's output field and assert that it equals 1\n2\n3\n. Keep the existing lookup by the saved row key so the test also checks that completion updates the same row.

src/main/codex/app-server/codex-app-server-connection.ts: 2

186-186: Minor · Data Integrity & Integration · Quick win

Invoke onReply for a cached initialize result.

On reattach, request('initialize', …, { onReply }) resolves from the cache without invoking onReply. A wire reply invokes the callback before the request promise settles. Invoke it with the cached result before resolving the promise. Leave the wire path unchanged so it still invokes the callback once.


326-327: Minor · Data Integrity & Integration · Quick win

Forward the supplied spawner on direct fallback.

The returned launcher advertises the same signature as spawnCodexAppServerConnection, but it ignores the third argument. If the relay is unavailable and a caller supplies a test spawner, the fallback can launch a real process instead. Accept and forward spawnImpl, defaulting it to spawnProcess. A successful relay launch still does not need the spawner.

src/main/codex/app-server/codex-relay-ack-floor.ts: 2

41-44: Minor · Data Integrity & Integration · Quick win

Match completions by their actual thread and item fields.

completedKey searches the entire frame for two substrings. A completion for item b on thread t can match open item a if it contains a nested id: "a". The next ack can then release a's start while a is still open. An actual completion with whitespace after a colon can also leave its start pinned.

Read params.threadId and params.item.id structurally and look up that pair. A targeted JSON scan can do this without decoding the completion's large text fields.


84-87: Minor · Data Integrity & Integration · Quick win

Keep a completed item's start held when the ending map is full.

When the ending map holds 256 entries, observe removes a completed item's start from open and does not add it to ending. floor then no longer accounts for that start. The returned floor can advance past the item before its completion has been taken. If the process restarts in that window, the item's started row can be discarded and cannot be replayed. The contract at line 101 requires that the start stay held until the end is taken or released.

The fix needs a policy choice: raise or remove the cap, keep the start in a separate structure, or hold the item in open when the ending map is full. Choose one that keeps the start held until either the end is taken or the start is released. Add a test that completes more items than the cap before any floor call, then checks that floor does not pass the start of the last completed item.

src/main/codex/app-server/codex-app-server-relay.ts: 1

75-75: Minor · Functional Correctness · Quick win

Match the envelope keys after JSON decoding in isCodexAnswerAbove.

The raw prefilter at line 75 requires the literal text "result" or "error". Valid JSON can spell those keys with escapes, for example \u0072esult. Such a line fails the prefilter and is held during a reattach, even though it is an answer above the floor. A request awaiting that answer can then time out before releaseOutput() runs.

The fix should accept any spelling that decodes to id, result, or error, and it should not reject based on raw substrings. Keep the method exclusion and the floor check unchanged.

src/main/codex/app-server/codex-relay-item-continuation.ts: 1

106-109: Minor · Functional Correctness · Quick win

Derive the close key from the same thread fields as the work markers.

settles reads only params.threadId. The work markers for thread/closed and turn/completed also accept params.thread.id. A close that carries only the nested field produces the key [t] in the marker, but settles returns null. The continuation then keeps [t] in open, and the open.size === 0 completion check cannot succeed. The cut item finishes only through its own completion, and a closed thread can send none. The rekeyed row can then stay partial.

Resolve the thread ID the same way the markers do: use params.threadId first, then params.thread.id.

Suggested fix

-type Params = { threadId?: unknown; itemId?: unknown; item?: { id?: unknown; type?: unknown } }
+type Params = {
+  threadId?: unknown
+  itemId?: unknown
+  item?: { id?: unknown; type?: unknown }
+  thread?: { id?: unknown }
+}
-      return (method === 'turn/completed' || method === 'thread/closed') &&
-        typeof params?.threadId === 'string'
-        ? JSON.stringify([params.threadId])
-        : null
+      const threadId =
+        typeof params?.threadId === 'string' ? params.threadId : params?.thread?.id
+      return (method === 'turn/completed' || method === 'thread/closed') &&
+        typeof threadId === 'string'
+        ? JSON.stringify([threadId])
+        : null
src/main/codex/structured/items/codex-structured-item-stream-bounds.ts: 1

39-39: Minor · Data Integrity & Integration · Quick win

Keep rejected patch snapshots from being evicted silently.

trimCodexPendingPatches removes the oldest pending patch when more than 128 keys are pending. That patch may be a snapshot whose journal write was rejected. The helper does not retry the write, and the caller does not learn of the removal. The newer insertion still returns accepted: true. The map comment says rejected snapshots are retained for retry, so this eviction conflicts with that stated behavior.

Under sustained sink rejection, the journal can miss an intermediate snapshot for a key that is evicted. A later patch for the same key recreates the state. A completion path outside this file may also persist the final state, which limits the loss. Confirm that path before you decide how serious the loss is.

Choose one of two fixes. Refuse admission for a new key when the map is at the count cap, so the caller receives backpressure. Or keep rejected snapshots and cap memory by another rule. Either fix must ensure that a rejected snapshot is not discarded silently.

Nitpick comments: 3

src/main/provider-relay/provider-relay-ack-batch.test.ts: 1

31-31: Trivial · Maintainability & Code Quality · Quick win

Move the work-count assertions to the performance contract suite.

These tests count requests in provider-relay-ack-batch.test.ts, which the dedicated performance suite does not select. If the contract is one shared timer, also count cadence registrations: two timers with the same deadline can still produce one batched request.

As per coding guidelines, “The only tests allowed to count work” are perf contracts, and a perf contract “lives in a *.performance.test.{ts,tsx,mjs} file” and “names, in a comment, the incident it guards (PR number).”

Also applies to: 45-45, 67-69

Source: Coding guidelines

src/main/provider-relay/provider-relay-launch-inventory.performance.test.ts: 1

59-59: Trivial · Maintainability & Code Quality · Quick win

Use fake clocks for this performance contract.

The test uses real setImmediate turns and the inventory's real deadlines. Install fake clocks and use controlled asynchronous clock advancement for flush. Keep the hardcoded close-count assertions.

As per coding guidelines, a performance contract “runs in seconds, with fake clocks.”

Source: Coding guidelines

src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-kept-ended-acquire.test.ts: 1

26-28: Trivial · Maintainability & Code Quality · Quick win

Check replay persistence before fresh dispatch.

The test does not check its replay-before-dispatch invariant. It can pass if the fresh agent receives the send before replayed-output reaches the journal.

Inside this dispatch mock, read the replayed item through the real journal and assert its saved content before returning admitted. Keep the generation and single-dispatch assertions.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Retargeted to main at f58c057

#47229 (core) merged to main as 4b7c4d4. This head is a merge of main into the branch, and the PR now targets main.

The reviews of 74dc468 still apply. This merge only brought main in:

  • This PR's own changes are unchanged. Its diff against main, and its diff against the old core base (c0dd925 to 74dc468), touch the same file set with an identical patch; only line offsets differ in one file, which main changed elsewhere.
  • The branch gained no commit of its own. Its only commit after 74dc468 is this merge.
  • Merge conflicts: fifteen core daemon files conflicted because the squash rewrote core's history. On main, each was byte-identical to core's c0dd925, so this PR's version of each, core plus its own changes, was kept.
  • Gate: pnpm check:changed against origin/main passed, 32/32.

So the regression audit (SAFE), the perf scan (clean, all four surfaces), the Claude review (READY) and QA (round 25, 7/7) on 74dc468 cover this head.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA screenshots for f58c057

QA round 25 (Omarchy Linux, 7 of 7 passed) ran on 4882b02. Since then this PR's own code changed only in a test and a one-line failed-rebind cleanup; the rest is the merge of main. None of that touches these flows, so the run still covers this head.

S1: a turn still running after a graceful quit and relaunch, then finishing in the same Codex process:

S1 after relaunch
S1 done

S6: an approval held across the quit, asked again after relaunch, then run after Allow:

S6 asked again
S6 after Allow

s1-1-after-relaunch

s1-1-after-done

s6-b-after-relaunch

s6-b-after-allow

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan confirmed at f58c057 (main merge)

The local origin/main and the configured remote’s advertised main both resolve to 181aa2eda0d. The literal diff against that ref lists 16,275 paths. I used 4b7c4d487fc, the verified second parent of the merge, for the retarget comparison.

Against that parent, both comparisons list the same 160 paths in the same order. The patches match after normalizing hunk offsets and the old and new blob IDs for codex-structured-journal-translation-turns.ts. Main added separate code to that file. Every PR hunk has identical context, additions, and deletions.

I verified that the 15 daemon paths match c0dd9250b1e on the main side and retain the reviewed branch blobs in the merge. The lockfile matches the main parent. Of the 90 previously covered production files, 89 match the reviewed head byte for byte. The one change, rpc-messages.ts, matches main and defers construction of three schemas until first use. Verification was read-only. No tests were run.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review receipts at f58c057

The regression audit reviewer and the perf-scan reviewer each checked f58c057 themselves against its main parent (4b7c4d4). Each found the file set and patch identical to the reviewed 74dc468 apart from line offsets.

  • Audit: SAFE for f58c057. The merge preserves the reviewed patch, including the exit-probe fix; the idle-stop race stays deferred to STA-18721.
  • Perf scan: clean at f58c057, on all four surfaces (comment above).

The Claude review (READY TO MERGE at 74dc468) and QA (round 25) cover the same PR code.

@brennanb2025
brennanb2025 merged commit b6ab4df into main Nov 27, 2026
152 of 185 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant