Skip to content

fix(agent-status): recover Codex subagent state after restart (STA-5329) - #16336

Closed
brennanb2025 wants to merge 20 commits into
mainfrom
brennanb2025/sta-5329-plan
Closed

brennanb2025 wants to merge 20 commits into
mainfrom
brennanb2025/sta-5329-plan

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1622 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1619
Prod 25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1313 $\color{#cf222e}{\Huge{\mathbf{−}}}$​290 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1023

ELI5

When Orca restarts during Codex work, relay hook events can be missed and subagent status can remain stale. This restores the state from relay/cache and transcript data so the status can recover.

Put plainly: each Orca terminal tab shows a little status for the agent inside it — working, waiting
on you, done — and for Codex it also lists the subagents that run spawned. That status is kept up to
date by live event messages. If Orca quits or restarts while a Codex run is in flight, the messages
sent while Orca was away are simply lost, and when Orca comes back the tab keeps showing whatever it
last saw: a finished run still marked "working", a run waiting on your input looking idle, an empty
subagent list for a run that has five.

Now, on the way back up, Orca rebuilds that status from Codex's own transcript file and from cached
records instead of waiting for events that will never arrive.

User-facing before / after

Before After
You quit and reopen Orca (or it restarts for an update) while a Codex run is in flight The tab's agent status stayed frozen at the last thing Orca saw before the restart — often wrong, and it never corrected itself Orca re-reads Codex's transcript and shows the run's actual current state
That run had spawned subagents The subagent list came back empty or stale The subagent roster is rebuilt from the transcript
The Codex run is on an SSH host and the connection restarts Status events lost across the restart stayed lost The remote side keeps a status cache and reconciles it when the connection returns
No restart happens — Unchanged; live events still drive the status exactly as before

When it bites

Codex users, on local machines and SSH hosts alike, whenever Orca restarts — quit and reopen, an app
update, a crash — while a Codex run is still going.

What Changed

  • Reconcile Codex relay and subagent state after restart.
  • Harden relay hook cache hydration and preserve reconciliation diagnostics.
  • Add focused transcript, relay-cache, server, and SSH integration coverage.

Why

A restart can interrupt hook delivery; rehydrating and reconciling persisted state keeps subagent status truthful after the app returns.

Linked Issue

STA-5329 (Linear)

Visual Proof

N/A — no new UI surface; this fixes relay/state reconciliation behavior.

Testing

No additional validation was run in this handoff; CI should run the branch tests.

Review

No QA evidence or screenshots attached.

Notes

The change is scoped to Codex subagent relay/state recovery and its focused coverage.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA evidence for exact head 49fee97a41effc6155bacbfab0bb8e80e4ccc60b: attached before/after uncropped screenshots from the real Orca Electron surface. The after state visibly shows the Codex working row (QA exact-head status - Codex) on brennanb2025/sta-5329-plan; backing agentStatusByPaneKey contained state: working, agentType: codex, and the pane/worktree IDs. Focused relay/cache and Codex transcript-reconciliation tests pass (21/21, Vitest with --testTimeout=10000); restart/cache reconciliation has no separate UI surface, so the screenshots cover rendered status presentation while the focused tests cover durable replay/reconciliation.

Before: https://github.com/user-attachments/assets/9584b418-99fc-4b3a-a877-d75b894b02c8
After: https://github.com/user-attachments/assets/f9bf6552-2b47-4a07-840e-81c04fdc96d2

@coderabbitai

coderabbitai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Codex transcript reconciliation after main-server and relay restarts. Persisted status cache entries are hydrated, validated, sanitized, and replayed. Reconciliation restores subagent state, tracks parent terminal status, retries unreadable transcripts, and persists unverifiable diagnostics. Diagnostic fields propagate through hook payloads, relay envelopes, SSH forwarding, and status snapshots. Relay HTTP handling, event application, cache persistence, and lifecycle cleanup use dedicated helpers. Tests cover recovery, cache hydration, diagnostic retention, authority transfer, and remote forwarding.

Merge Risk: 🟡 Moderate · up to f8ad4

Restart recovery now rebuilds Codex subagent status from persisted data, but the current implementation can retain agents from a previous transcript and present stale or misleading status after a path change. Reconciliation diagnostics may also be lost in mirrored panes, while related recovery edge cases remain open, so owner follow-up is needed before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 33 functions across 35 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description check ✅ Passed The description is mostly complete and covers the change, rationale, linked issue STA-5329, visual proof rationale, and scope. Testing details are limited, and the AI Disclosure, Agent skill upstream …
Title check ✅ Passed The title clearly and concisely describes the primary change: recovering Codex subagent state after an agent-status restart.
Full details: Description check

Explanation

The description is mostly complete and covers the change, rationale, linked issue STA-5329, visual proof rationale, and scope. Testing details are limited, and the AI Disclosure, Agent skill upstream boundary, and checklist sections are not completed.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

Comment @coderabbitai help to get the list of available commands.

@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.

Actionable comments posted: 6

🧹 Nitpick comments (2)
src/relay/agent-hook-status-cache.ts (1)

184-195: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider debouncing the synchronous full-cache write.

persistRelayHookStatusCache serializes the whole lastStatusByPaneKey map and performs a synchronous writeFileSync plus renameSync. applyRelayHookEvent calls it on every hook event, and clearPaneState calls it once per evicted pane. Codex and Claude emit PostToolUse per tool call, so a busy pane triggers repeated whole-file writes on the relay event loop. With the 256-pane cap the payload can be large.

A short debounce (or a write only when the serialized content changes) keeps the durability guarantee and removes the per-event I/O.

src/relay/relay-http-listener.ts (1)

8-23: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Close the server when startup fails.

onError rejects the promise but leaves the net.Server object with its internal state untouched. RelayAgentHookServer.start() reacts to EADDRINUSE by calling listenOn(0), which creates a second server, so the first one is abandoned without a close(). Call server.close() before you reject, so the failed instance releases its handle deterministically.

♻️ Proposed cleanup
     const onError = (error: Error): void => {
       server.off('listening', onListening)
+      server.close()
       reject(error)
     }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c6ed1b81-17a7-4666-8233-71fb2a5464c3

📥 Commits

Reviewing files that changed from the base of the PR and between cc48013 and 49fee97.

📒 Files selected for processing (19)
  • src/main/agent-hooks/server-codex-subagent-transcript.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/agent-hook-envelope-build.ts
  • src/relay/agent-hook-server-codex-subagent-transcript.test.ts
  • src/relay/agent-hook-server.test.ts
  • src/relay/agent-hook-server.ts
  • src/relay/agent-hook-status-cache.test.ts
  • src/relay/agent-hook-status-cache.ts
  • src/relay/relay-http-listener.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/agent-reconcile-diagnostic.ts
  • src/shared/agent-status-observation.ts
  • src/shared/codex-subagent-transcript-seeding.ts
  • src/shared/codex-subagent-transcript.test.ts
  • src/shared/codex-subagent-transcript.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment thread src/main/agent-hooks/server.ts Resolved
Comment thread src/relay/agent-hook-server.test.ts Resolved
Comment thread src/relay/agent-hook-server.ts Resolved
Comment thread src/relay/agent-hook-status-cache.ts Resolved
Comment thread src/shared/agent-hook-listener.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review verification for exact head 49fee97a41effc6155bacbfab0bb8e80e4ccc60b:

  • Orchestration review loop: CLEAN — the final independent reviewer found no actionable P0/P1/P2 findings.
  • pnpm exec vitest run --config config/vitest.config.ts <6 focused relay/agent-hook suites> --testTimeout=10000: PASS (6 files, 47/47 tests).
  • pnpm typecheck:node and pnpm typecheck:web: PASS.
  • Changed-file pnpm exec oxlint, pnpm exec oxlint --config config/oxlint-react-doctor.json, pnpm exec oxfmt --check, and git diff --check origin/main...HEAD: PASS (19 TS/TSX files checked).

Verification only; this is not a merge-ready claim. GitHub currently reports the PR as dirty/conflicted, and unresolved CodeRabbit findings remain.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-5329-plan branch from 49fee97 to acc7d1c Compare August 27, 2026 13:37
@coderabbitai

coderabbitai Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review verification for exact head acc7d1cbe0de1a2035b2009affb18998d732aa71:

  • Addressed all six current review findings: destination transfer re-arm, post-stop request guard, cache field sanitization, snapshot/transcript reconciliation, startup listener cleanup, and restart-test cleanup; relay cache writes are coalesced and flushed on stop.
  • Focused Vitest suites pass (5 files, 27 tests) plus relay restart/recovery suites (3 files, 26 tests); pnpm typecheck:node, pnpm typecheck:web, changed-file oxlint/oxfmt, and git diff --check pass.
  • Full touched-area sweep is green for agent-hook/relay suites; two unrelated pre-existing failures remain in pty-handler-spawn-environment.test.ts and pty-handler-startup-command-delivery.test.ts.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA / evidence for exact head acc7d1cbe0de1a2035b2009affb18998d732aa71:

  • Electron CDP validation attached to the intended worktree identity (Orca: brennanb2025/sta-5329-codex-status-restart-r1) and rendered the normal Orca shell without console errors; no workspace/agent pane was available in the isolated profile, so the restart-status row could not be exercised on-screen.
  • Durable restart/hook behavior is covered by the passing focused relay/main transcript tests (53 total), including dropped child completion, malformed cache metadata, post-stop continuation fencing, transfer re-arm, and diagnostic persistence.
  • Merge verdict: not merge-ready yet while CI is queued and the two unrelated full-sweep PTY test failures remain; no merge performed.

@brennanb2025

brennanb2025 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Exact-head review verification

Final head reviewed: d98f042b79e2fcd0bb4de12e037948a50d82c56a.

Review outcome

  • The full 39-file STA-5329 diff was reviewed against the live merge base with correctness, lifecycle/replay ordering, SSH/relay, mixed-version wire compatibility, performance/resource, mobile/backcompat, Windows/Linux, and scope lenses.
  • A same-model exact-head re-review was CLEAN. Focused coverage totaled 17 files / 144 tests, with pnpm tc:node, pnpm tc:web, changed-code scans, and git diff --check passing.
  • The PR-owned Node 24/26 shard regression was reproduced only at the prior PR head: a nonterminal relay replay was marking Claude status as restored/unconfirmed and erasing the live-observation fence. Commit d98f042b79 scopes that recovery marker to Codex, and the regression test now passes 14/14 under Node 24.20.0 and Node 26.5.0. CI confirms all eight Node 24 shards and all eight Node 26 shards pass.
  • Performance audit found no new unbounded polling, scan, listener, or cache growth. Restart reconciliation remains bounded to five attempts at one-second spacing with cleanup on session start, pane retirement, and shutdown. The shared 25 ms reconciliation admission gate can requeue simultaneous panes, but no user-visible regression was proven.
  • No mobile-facing surface changed. Optional host fields remain additive for mixed-version clients, and remote transcript access remains execution-host-owned.

Silent-revert check

  • The live GitHub merge result changes exactly the same 39 intended files as the PR diff; no file outside that set is changed relative to the merge result's first parent.
  • src/shared/runtime-client-export-parity.test.ts is unchanged by the PR merge and still contains TERMINAL_PTY_DEGRADATION_CAPABILITY, TERMINAL_UNAVAILABLE_ERROR_CODE, and terminalUnavailableMessage.
  • There are 0 unresolved review threads.

Settled CI and verdict

Settled rollup: 26 success, 8 skipped, 1 failure, 0 pending. The two previously failing test shards are green. The remaining red check is e2e / build e2e app.

That E2E failure is base-owned, not caused by STA-5329. A clean Linux/amd64 Node 24.20.0 reproduction from untouched origin/main (551fbb9ac76a75b813dce62753414d43beea3b90 at capture) used the base workflow's script-free install and failed identically in the plain-Node daemon guard because node-pty had no prebuilds/linux-x64/pty.node. The PR merge does not modify .github/workflows/e2e.yml, .github/actions/install-node-dependencies/action.yml, or electron.vite.config.ts relative to its current base; the failing install path was introduced by base commit 350423b7cb.

Verdict: not merge-ready while the base-owned E2E check remains red.

@brennanb2025

brennanb2025 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Exact-head QA evidence

Final head under test: d98f042b79e2fcd0bb4de12e037948a50d82c56a.

Electron restart validation

Validation used the $electron workflow with Playwright over CDP only. The isolated instance used /tmp/orca-pr16336-electron-profile.ogW41N, CDP 127.0.0.1:9337, renderer 127.0.0.1:5180, and reported exact identity pr-16336-evidence-r1 @ d98f042b79 with the expected devRepoRoot. No computer-use, accessibility, or OS-level input automation was used.

  1. A real local Codex hook and parent/child rollout pair rendered the parent and /root/exact_head_active_child as Working, with Detached HEAD @ d98f042 visible.
  2. The child completed while Orca was stopped. After restarting the same isolated profile, the child row was gone while backing state remained working, had no subagents, and was restoredUnconfirmed.
  3. The parent then completed while Orca was stopped. A second restart restored backing state done and visibly rendered Done, with no child row.

Before restart — live parent and child:

Live parent and child at d98f042b79

After restart — completed child removed, parent retained:

Completed child removed at d98f042b79

After second restart — missed parent completion restored:

Parent restored done at d98f042b79

The renderer reported 0 console errors throughout the flow.

Live Linux SSH changed-flow validation

The throwaway host was reachable with:

ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -i /tmp/pr16336-ssh-key -p 61951 [email protected]

It was Linux ARM64 with Node 22.23.1. Its installed relay version 0.1.0+ac9629399585 and SHA-256 matched the relay built from this exact head. A real remote Codex hook returned HTTP 204 and produced an authoritative cache with a working parent and live /root/ssh_restart_qa child. After completing the child and replacing only the verified relay PID, the SSH connection moved through reconnecting back to connected; the recovered cache had no child and retained codexAuthoritativeParentState: "working". After completing the parent and replacing only the next verified relay PID, reconnect again succeeded and the cache recovered state: "done" with codexAuthoritativeParentState: "done".

The isolated restored profile no longer owned the historical remote pane after its app restarts, so I do not claim a rendered SSH row; the live Linux transport, exact-head relay replacement, transcript reread, and authoritative cache transitions are the evidence for the SSH arm. Electron rendering is proven separately above.

CI attribution

All 16 Node 24/26 test shards pass at this head. The remaining e2e / build e2e app failure reproduced identically from untouched origin/main in a clean Linux/amd64 Node 24 container after pnpm install --frozen-lockfile --ignore-scripts: the plain-Node daemon guard could not load node-pty because prebuilds/linux-x64/pty.node was absent. This is current-base CI behavior, not a STA-5329 change.

QA verdict: the exact-head local and live-Linux restart flows pass, but the PR is not merge-ready while the base-owned E2E check is red.

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/agent-hooks/server.ts (1)

1722-1724: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Record unreadable parent transcripts.

When readJsonlCursor(state.parent) returns undefined, reconcileCodexSubagentTranscript converts it to []. The final retry check only inspects child unresolvedSince values. A missing parent transcript with no child records therefore leaves the restored entry without a transcript-unreadable diagnostic. Track parent readability and add a restart test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 061144b9-7e97-499b-9011-bec648b952ea

📥 Commits

Reviewing files that changed from the base of the PR and between acc7d1c and 2d55df8.

📒 Files selected for processing (7)
  • src/main/agent-hooks/server-codex-subagent-transcript.test.ts
  • src/main/agent-hooks/server.ts
  • src/relay/agent-hook-server.test.ts
  • src/relay/agent-hook-status-cache.test.ts
  • src/relay/agent-hook-status-cache.ts
  • src/shared/agent-hook-listener-relay-dependency.test.ts
  • src/shared/codex-subagent-transcript.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/agent-hooks/server.ts (2)

1692-1695: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Reject empty relay IDs before local reconciliation.

sanitizeHydratedEntry preserves connectionId: "" as a string, but this truthiness check treats it as local. A hydrated remote Codex entry can therefore make the main server read providerSession.transcriptPath on the SSH execution host's behalf and emit a local reconciliation result or transcript-unreadable diagnostic. Reject empty or whitespace connection IDs during hydration, and use an explicit entry.connectionId === null check for local reconciliation.

As per coding guidelines: all src/**/*.{ts,tsx} changes must consider SSH; the execution host owns everything that touches execution.

Source: Coding guidelines


1742-1749: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clear stale diagnostics after a successful transcript re-read.

When reconcileCodexSubagentTranscript reads a previously unreadable child successfully but nextPayload is unchanged, the update branch does not run. The persisted transcript-unreadable diagnostic remains visible. Clear the diagnostic when readability is restored and add a regression test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e27c33e3-e714-4a72-8d9c-094229fefa1e

📥 Commits

Reviewing files that changed from the base of the PR and between 2d55df8 and 3cbfcfd.

📒 Files selected for processing (5)
  • src/main/agent-hooks/server.ts
  • src/relay/agent-hook-request.ts
  • src/relay/agent-hook-server-cache-hydration.test.ts
  • src/relay/agent-hook-server.ts
  • src/shared/agent-hook-listener-relay-dependency.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.

@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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 181562c3-dfef-4140-9df2-380a4dc146f5

📥 Commits

Reviewing files that changed from the base of the PR and between 3cbfcfd and f8ad411.

📒 Files selected for processing (17)
  • src/main/agent-hooks/server-codex-subagent-transcript.test.ts
  • src/main/agent-hooks/server.ts
  • src/relay/agent-hook-event-application.ts
  • src/relay/agent-hook-server-cache-hydration.test.ts
  • src/relay/agent-hook-server.ts
  • src/relay/agent-hook-status-cache.test.ts
  • src/relay/agent-hook-status-cache.ts
  • src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts
  • src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts
  • src/renderer/src/hooks/ipc-events/agent-status-reconcile-diagnostic.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync-agent-status.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/shared/codex-subagent-transcript-paths.ts
  • src/shared/codex-subagent-transcript-seeding.ts
  • src/shared/codex-subagent-transcript.test.ts
  • src/shared/codex-subagent-transcript.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/relay/agent-hook-event-application.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent exact-head review — ef49c94f0100bbd40a416e3bbd7e9fbdaa8271c5

Review-thread disposition

The sole unresolved non-outdated concern was valid: “Preserve host diagnostics under client ownership. When clientOwnsEntry or a newer client row selects existing, nextEntry omits entry.reconcileDiagnostic, so host diagnostic set and clear updates do not reach the mirrored pane; copy entry.reconcileDiagnostic in that merge branch.” Commits 992834e438 and 685374fb39 preserve host diagnostic set/clear updates while fencing diagnostics from an older host turn; the failing-first renderer coverage is green. Evidence reply: #16336 (comment)

Silent-revert audit

Clean. Both merges from main have zero non-intentional deltas relative to their main parents, and the current runtime-client parity files are byte-identical to origin/main (6c0de76ced3292576390771a98016bd97ace18c2). src/shared/runtime-client-export-parity.test.ts still contains TERMINAL_PTY_DEGRADATION_CAPABILITY, TERMINAL_UNAVAILABLE_ERROR_CODE, and terminalUnavailableMessage; no main-owned fix was reverted.

Restart/lifecycle verdict

Two restart defects remained after the concurrent hardening commits and were fixed failing-first in ef49c94f01:

  • Parent task_complete no longer forces aggregate done while a child is still working or waiting; the existing bounded codexRosterEffectiveState contract (maximum 32 children) now determines the aggregate on relay and main restart reconciliation.
  • A nonterminal SSH relay cache replay is now restoredUnconfirmed until live evidence arrives, so loss/reconnect cannot masquerade as live truth. Transcript-unreadable/contact-loss cases remain unverifiable, and only transcript terminal evidence or process-exit evidence produces done/exited semantics.

Closed/retired panes remain fenced: the explicit cold-relay replay and closed-tab suppression suites pass, so an intentionally closed session is not resurrected.

Verification

  • Focused failing-first gates: 50/50 on the initial exact head; final exact-head touched matrix 49/49.
  • Full affected matrix: 19 files, 172/172 tests.
  • pnpm tc:node and pnpm tc:web: pass.
  • Direct Oxlint, React Doctor, Oxfmt, and git diff --check: pass. The aggregate changed-code-quality wrapper itself is incompatible with this host's Node 26 because pnpm's engine warning is parsed as JSON; its constituent scans pass directly and CI's Node 24 static-analysis/typecheck jobs cover the supported runtime.
  • Perf/reliability audit: clean; no new timer, subprocess, listener, or unbounded cache, and the added roster evaluation is capped at 32 entries.
  • Review-until-clean: two fix/re-review rounds, no remaining in-scope finding.

Live Linux SSH + Electron/CDP QA

Validated only in the isolated instance whose identity was review-16336-independent-r1 @ ef49c94f01 and whose devRepoRoot exactly matched this worktree. The throwaway SSH host was reachable with:

ssh -p 61939 -i /tmp/orca-pr16336-ssh.CxQ18N/id_ed25519 -o BatchMode=yes -o StrictHostKeyChecking=no [email protected] uname -a

It reported Linux arm64. Real remote hook posts returned HTTP 204; the remote relay cache retained a parent-complete/child-working aggregate. After restarting only the exact isolated Electron PID tree, main recovered the row as state: working, restoredUnconfirmed: true, and the rendered sidebar conservatively displayed Idle - Codex rather than asserting live or done. No computer-use, accessibility, OS-level input automation, broad kill, production Orca interaction, merge, approval, or close was performed.

Verdict

Code review is clean / merge-ready subject to exact-head CI settling green. Current hold is CI only.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Exact-head CI follow-up for ef49c94f01: the rollup has settled with four failures, so my merge verdict is not merge-ready until required CI is green.

  • tests node 24 1/8 and tests node 26 1/8 both fail the same server-interrupt-inference-guards.test.ts Claude background-metadata case (expected true, received false), outside the Codex restart-recovery paths changed here.
  • verify fails downstream of the test-job failure.
  • e2e / build e2e app fails while loading the Linux node-pty native module because prebuilds/linux-x64/pty.node is absent, before changed-flow execution.

The focused exact-head recovery matrix remains green (172/172 affected tests, including 49/49 lifecycle tests), along with tc:node, tc:web, lint/format checks, and the isolated Linux SSH restart flow documented in my prior comment. This follow-up does not waive the red required checks; they need to be rerun or repaired before merge.

@brennanb2025 brennanb2025 mentioned this pull request Aug 28, 2026
8 tasks done
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent exact-head review — content 32312c32a5, freshness merge a8c71cc05b

The last on-PR verdict was "not merge-ready until required CI is green" at ef49c94f01; the head then moved with zero on-PR evidence at the new SHA. This comment closes that gap with a fresh, independent review loop at exactly 32312c32a505a4c89052986275fe9ffdfe0a2da9.

What the current head actually is (merge integrity, proven by blob comparison)

32312c32a5 = merge of main e16f3943fd into d98f042b79. Per-file blob comparison: every one of the 39 PR-owned files is byte-identical to d98f042b79 (the head the re-saved 23:55Z review/QA comments name), and every non-PR file is byte-identical to the main parent — the merge introduced nothing and reverted nothing. The branch delta since the not-merge-ready ef49c94f01 is exactly one commit: d98f042b79, the one-line Codex scope guard on replay restoredUnconfirmed that fixed the PR-owned Node-shard regression.

Tests re-run at this head

All 16 PR-changed suites + the replay-guard oracle: 17 files, 144/144 tests pass locally (130 in the PR's own suites + 14 in server-interrupt-inference-guards.test.ts) — independently reproducing the recorded coverage figure.

Production hunks ablated (all four fix layers, each pin proven live)

  1. Replay scope guard (server.ts ~1525): removing agentType === 'codex' fails uses replayed Claude background metadata only before a live observation (13/14) — the exact Node-shard regression.
  2. Roster effective-state gate (server.ts restart reconciliation): reverting to parent-state-wins fails keeps a restored aggregate active until a child outlives the parent (7/8).
  3. Renderer diagnostic preservation (web-session-tabs-sync.ts client-ownership merge): removing the reconcileDiagnostic copy fails applies marker-only reconciliation diagnostic set and clear updates (7/8).
  4. Relay hydration validation (agent-hook-status-cache.ts sanitizeHydratedEntry): dropping the agentType check fails skips malformed durable entries while hydrating valid status and diagnostics (9/10).

#16751 overlap (the stale-green cause) — resolved and verified

This PR's green predated #16751 (a7b1da9e) touching src/main/ssh/ssh-relay-session.ts. The overlap is textual, not semantic: the PR adds three optional envelope fields in the agent-status decode; #16751 changes reattach pane-binding. At the fresh-run merge head a8c71cc05b (parents exactly 32312c32a5 + main 4bb337741c), the merged file is main-tip's version (mayCreate/authority gate/findTerminalTabIdForLeaf all present — main's fix still runs) plus exactly the PR's seven envelope lines; ALL other PR files byte-unchanged, all non-PR files byte-identical to main tip.

Independent adversarial re-review at this head (two-lane, full diff)

No P0/P1 found. Relay/renderer lane verdict: three P2s (real, none blocking) + one cosmetic:

  • P2 (hydration spread): sanitizeHydratedEntry (agent-hook-status-cache.ts) validates paneKey/payload/providerSession/reconcileDiagnostic/meta but spreads the rest of the raw entry (hookEventName, tabId, launchToken, codexSubagentsAuthoritative, …) untyped into the replayed event; a corrupt cache entry is retained and re-forwarded. Bounded: file lives in the user-owned endpoint dir, torn/invalid JSON degrades safely per-entry (tested), and both receiving clients field-pick with typeof checks — but the drop-hostile-entries contract is only met for the named fields.
  • P2 (cache file perms): persistRelayHookStatusCache mkdirs without mode and writes with umask-default perms, while endpoint publication deliberately pins 0700/0600; the first debounced cache write (25 ms after start) can be what creates the dir, so a crash-before-publication can leave a world-readable file holding prompts/lastAssistantMessage/launchTokens. Steady state self-heals via publication's chmod. Fix is two mode: options.
  • P2 (clearPaneState after stop): clearPaneState schedules a cache write with no this.server stopped-guard (applyEvent has one); a queued PTY-exit after stop()'s flush can overwrite the durable snapshot with an empty one if the process lives another 25 ms. Not P1 because graceful shutdown killed those PTYs anyway (empty matches reality) and the crash path — where recovery matters — runs no exit listeners.
  • Cosmetic: reconciliation's JSON.stringify equality can differ on key order for hydrated entries → at most one redundant persist+forward (5-attempt cap).

Same lane verified CLEAN: coalescing + flush-on-stop ordering (flush BEFORE cache clear), 256-pane cap enforced at apply AND hydration with size caps (8KB message / 16KB prompt / 32 subagents), corruption handling (missing/torn/wrong-version/garbage entries all degrade without throwing), wire compatibility (three new fields optional-additive on the existing notification, both mixed-version directions field-pick safely, reconcileDiagnostic: null clear round-trips, shed path drops the authoritative flag with the roster — preventing an authoritative-empty misread), renderer merge flap-freedom (diagnostic included in agentStatusEntryEqual, so preservation short-circuits before an epoch bump), and no listener/timer leaks (http listener closes failed servers; per-pane reconcile timers cleared on pane clear and stop).

Main-process lane verdict: four P2s (transient/latent, none blocking):

  • P2 (this is the known clearPaneKeyAliasesForPty finding, adjudicated below): the alias-only cleanup path is the one teardown that neither calls retireCodexPaneGeneration nor cancels the restart-reconcile timer (every other teardown does: transfer, retirement, clearPaneState, connection loss, stop). I verified the sharpest claimed consequence does NOT compose: in the branch that emits the renderer clear, clearPaneCacheState deletes the status row first, so a pending reconcile aborts on its current !== original reference guard before any write; the shouldClearStablePaneKey:false branch deliberately preserves a NEWER live PTY's row. Residual: one retained codexPaneGenerations entry per alias-only cleanup (bounded; wholesale-cleared at stop, superseded on pane reuse) and one wasted no-op timer fire (≤5 attempts, unref'd).
  • P2 (waiting-child mislabel): restart reconciliation derives a non-terminal parent state from the AGGREGATE (current.payload.state === 'waiting'), so an aggregate that was waiting because a CHILD was waiting can keep the pane 'waiting' after that child retires, until the next live hook. Transient attention-surface mislabel.
  • P2 (transfer-time flash): transferPaneAuthority schedules reconciliation unconditionally; a live working pane whose rollout hasn't flushed the new turn's task_started can briefly re-render 'done' until the next hook replaces the row. Sub-second, self-healing.
  • P2 (latent): non-SessionStart events inherit previous.reconcileDiagnostic, so a stale 'transcript-unreadable' diagnostic can ride live rows; currently invisible (no UI consumer reads the field yet) — worth clearing on the first accepted live event before a consumer lands.

Same lane verified CLEAN: bounded reconciliation (5 attempts / 1 s / 25 ms admission gate; SessionStart cancels + bumps generation BEFORE any write; live accepts always install a new object so stale replays cannot overwrite live observation), all transcript JSON.parse/fs wrapped, SSH boundary (reconciliation gated to connectionId === null; sanitizeHydratedEntry trims and REJECTS empty/whitespace connection IDs — the prior CodeRabbit finding is fixed; host results cross the wire only as validated optional fields, with codexSubagentsAuthoritative annulled when the roster was shed in transit), the ~1522 replay guard can only ADD restoredUnconfirmed to Codex replays with all downstream effects conservative, and the thread-id regex in resolveCodexChildTranscript blocks path traversal.

clearPaneKeyAliasesForPty P2 — recommendation: DEFER to an immediate small follow-up (the #16979 shape)

Reasoning: the residual impact is a small bounded memory retention plus a no-op timer fire — the stale-write race it looks like is double-fenced (row deletion + reference guard), which I verified by reading both guard sites. Fixing in place is ~10 production lines (mirror retirePaneAuthority: retireCodexPaneGeneration + clearCodexRestartReconcile + clearAssistantMessageRetry/clearCodexSubagentPoll for the legacy key, and for the stable key when shouldClearStablePaneKey) plus a failing-first test on _getCodexPaneGenerationCountForTests() — but it would invalidate this PR's finally-converged evidence chain (live Electron restart QA, Linux SSH relay validation, four ablation-proven fixes, and the fresh post-#16751 CI run) for a defect that cannot corrupt state. A follow-up PR also naturally absorbs the two sibling P2s above (waiting-child mislabel, transfer-time flash), which touch the same reconciliation code. If you prefer strict belongs-in-PR hygiene I can land it here instead — cost is one more commit + fresh run + delta re-review.

Fresh run (stale-green cure) — settled GREEN at a8c71cc05b

Update-branch merge head a8c71cc05bc4e9d82ac2fcb68454b71c342f9c91 (parents exactly 32312c32a5 + main 4bb337741c, containing #16751 and both 08-28 main-side CI fixes) settled at 21 success / 0 failed / 7 skipped, mergeState CLEAN. One transient red on the way: e2e / ssh docker watcher isolation failed its first attempt with a mid-suite Docker SSH relay transport drop (SSH connection lost, reconnecting…, handshake retry ladder engaged) taking down two port-forward/agent-title specs — infrastructure, not this PR: the byte-identical PR content passed the same job at 32312c32a5 hours earlier, and the job rerun on the same fresh merge ref (created 07:21Z against current main tip, so this is not the stale-merge-ref pattern) passed. Head re-verified stable via ls-remote after settle.

Wire/perf spot-checks

New envelope fields (codexSubagentsAuthoritative, codexAuthoritativeParentState, reconcileDiagnostic) are optional additive fields on an existing channel — old decoders drop them harmlessly, no new opcode. The relay durable cache write is coalesced (25 ms debounce, unref'd timer) with a synchronous flush at stop; hydration is capped at 256 panes; restart reconciliation stays bounded (5 attempts, 1 s spacing, 25 ms admission yield) with cleanup on pane retirement and generation bump.

Verdict

MERGE-READY at content 32312c32a5 (equivalently at freshness head a8c71cc05b): no P0/P1 in either review lane; seven P2s total, all bounded/transient/latent with named fixes, none release-blocking per the severity bar; all four fix layers ablation-pinned; the stale-green vs #16751 is cured by the fresh run below. Recommended follow-up PR: the clearPaneKeyAliasesForPty cleanup-symmetry fix + the two reconciliation-transient P2s + the relay cache perms/stopped-guard/hydration-spread trio.

No merge, approval, or close performed.

Resolves src/relay/agent-hook-server.ts against #17012, which landed on main
after this branch extracted applyEvent/handleRequest into their own modules.

Main's retired-pane-surface gate lived in the extracted body, so a plain
'keep ours' resolution would have dropped it: applyRelayEvent now takes
isPaneSurfaceRetired and drops a retired pane before caching or forwarding,
and agent-hook-event-application.test.ts pins it at its new home.

Options types move to agent-hook-server-options.ts to keep the server file
under max-lines.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Re-based onto current main — evidence pinning has moved

Head is now 4f28b1ca1c1f4bfe7eace5b7fcb31205205fc8d2 (was a8c71cc05b), caught up to main at 94e7586665.

What this costs, stated plainly

The live-QA evidence comment (#issuecomment-5449948331) pins its run to 32312c32a5 and the freshness merge a8c71cc05b. That pinning no longer names this head. The prior evidence chain — the converged run at 21 pass / 0 fail / 7 skip, and the review loop behind it — was re-based, not re-obtained: no QA run has been executed against 4f28b1ca1c. It needs a fresh CI run, and the live-QA evidence should be treated as pinned to a superseded head until someone re-runs it.

The conflict, and the main-side fix that nearly went missing

The only content conflict was src/relay/agent-hook-server.ts, against #17012 (fix(relay): stop advertising an agent session for a pane whose tab is gone), which landed on main after this branch extracted applyEvent and handleRequest into agent-hook-event-application.ts / agent-hook-request.ts.

#17012 has three parts in that file. Two merged cleanly (the isPaneSurfaceRetired option/field/constructor, and replayCachedPayloadsForPanes → selectReplayableCachedPanes). The third — the gate at the top of applyEvent that drops a retired pane before caching or forwarding it — lived inside the method body this branch had deleted, so a plain "keep ours" resolution would have silently reverted it while still compiling and still passing pnpm tc.

It has been ported to where that code now lives: applyRelayEvent takes isPaneSurfaceRetired and drops a retired pane before any caching or forwarding.

Proof it actually runs, rather than merely being present:

# gate deleted from applyRelayEvent
src/relay/agent-hook-retired-pane-suppression.test.ts   3 failed | 3 passed (6)
  × does not advertise an orphan agent whose tab was closed
  × forwards again once the pane key is bound by a new PTY
  × routes hook admission through the PTY handler and drops the cache on retirement

# gate restored
src/relay/agent-hook-retired-pane-suppression.test.ts   6 passed (6)

agent-hook-event-application.test.ts gains one test pinning the gate at its new home, so a future extraction cannot drop it the same way. It is red without the gate (1 failed | 2 passed) and green with it (3 passed).

evictCachedPanesOverCap from #17012 is not called here because this branch already caps at the same MAX_CACHED_PANES = 256 inside agent-hook-status-cache.ts; the eviction behaviour is unchanged, the call site simply differs.

clearPaneKeyAliasesForPty — main's double fence still runs

Verified explicitly, because this is the code path that has caught this repo before. Both halves survive:

  • Row deletion — src/main/agent-hooks/server.ts:2280-2291 (legacyPaneKeyAliases.delete, clearPaneCacheState for both the legacy and the stable key).
  • The current !== original guard — src/main/ipc/pty/provider/state-cleanup.ts:88-92 (stablePaneOwner && stablePaneOwner !== id → return false). This file is byte-identical to origin/main; git diff origin/main -- src/main/ipc/pty/provider/state-cleanup.ts is empty.

server-last-status-hydrate-validation, server-authority-evidence, and pty-restore-record-seeding pass on the merged tree (24 tests).

No main-side change moved this code, and no semantics changed. The deferred clearPaneKeyAliasesForPty P2 was not implemented — it remains an open decision.

Verification on the merged tree

  • pnpm tc clean (node + web + cli).
  • oxlint clean on src/relay/. Options types moved to src/relay/agent-hook-server-options.ts to keep agent-hook-server.ts under max-lines after the merge added lines — no disable, no bump.
  • src/relay/, src/main/agent-hooks/, src/main/ssh/, src/main/ipc/ — 689 files / 7413 tests passed, 33 skipped, 0 failed.

Every main-side line added to the three files changed on both sides was accounted for: ssh-relay-session.ts (16/16 present), ssh-relay-session-agent-hooks.integration.test.ts (6/6), and agent-hook-server.ts (all 30, four of them relocated as described above).

@greptile-apps

greptile-apps Bot commented Aug 28, 2026

Copy link
Copy Markdown

Greptile Summary

This PR adds restart recovery for Codex parent and subagent status by reconciling persisted relay and main-process state against rollout transcripts.

  • Persists and hydrates relay-side hook status, reconciliation diagnostics, and authoritative Codex transcript metadata.
  • Reconstructs parent and child state locally and on SSH relay hosts after restart.
  • Preserves reconciliation metadata through main-process and renderer status synchronization.
  • Adds coverage for transcript parsing, cache hydration, replay, field shedding, pane transfer, and SSH recovery.

Confidence Score: 5/5

The PR appears safe to merge based on the reviewed restart, replay, transcript-reconciliation, and renderer propagation paths.

No concrete changed-code failure with a realistic reachable trigger and actionable consequence remained after checking pane-state migration, relay shedding, restart fencing, and status propagation.

Important Files Changed

Filename Overview
src/main/agent-hooks/server.ts Adds local persisted-status reconciliation, generation fencing, diagnostic propagation, and remote authoritative-state ingestion.
src/relay/agent-hook-server.ts Integrates durable relay cache hydration and schedules Codex reconciliation for restored events.
src/relay/agent-hook-status-cache.ts Implements relay status-cache validation, persistence, hydration, and restart reconciliation scheduling.
src/relay/agent-hook-codex-reconciliation.ts Reconstructs authoritative Codex parent and child state from transcript evidence.
src/shared/codex-subagent-transcript.ts Extends bounded transcript parsing and child-rollout reconciliation for restart recovery.
src/shared/agent-hook-relay.ts Extends the relay contract with authoritative Codex state, diagnostics, replay provenance, and safe shed-field markers.
src/renderer/src/runtime/web-session-tabs-sync.ts Carries restored-state and reconciliation diagnostics through mirrored session status merging.
src/renderer/src/store/slices/agent-status.ts Stores reconciliation diagnostics alongside existing agent-status restoration metadata.
src/main/ssh/ssh-relay-session.ts Forwards the new relay reconciliation fields into main-process remote status ingestion.

Sequence Diagram

sequenceDiagram
  participant C as Codex
  participant H as Hook listener
  participant R as Relay cache
  participant M as Main process
  participant T as Transcript
  participant U as Renderer

  C->>H: Lifecycle hook
  H->>R: Cache normalized status
  R--xM: Restart or connection interruption
  R->>T: Reconcile parent and child rollout state
  T-->>R: Authoritative state and diagnostics
  R->>M: Replay reconciled envelope
  M->>M: Validate identity and reconcile status
  M->>U: Publish restored status
  C->>H: Subsequent live hook
  H->>M: Confirm current state
  M->>U: Clear restored uncertainty
Loading

Reviews (1): Last reviewed commit: "Merge branch 'main' into brennanb2025/st..." | Re-trigger Greptile

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Missed status messages now recover after a restart through #16685. The remaining case with no new status message needs checking in current code, so this older implementation can be retired while the recovery problem stays tracked.

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