Skip to content

fix: preserve live agent PTYs through graph hydration - #11789

Merged
Jinwoo-H merged 1 commit into
mainfrom
fix-live-agent-resume-hydration-race
Aug 3, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
fix-live-agent-resume-hydration-race

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Decision summary

This PR should own the live background-terminal duplication incident. It prevents renderer uncertainty from creating a second PTY or provider resume process by adopting the exact runtime-owned stable pane through host-side attachOnly. #11819 repairs missing renderer projections; it does not arbitrate process ownership.

The deterministic Electron oracle is red on affected main and a literal ownership-fix revert, green on this candidate, and covers the original Agent PTY, Setup PTY, an unrelated canary, first activation, remount, exact process identity, runtime output, mounted viewport output, keyboard input, and zero launch/resume/interruption.

Original problem

Orca could create a second PTY and provider resume process when a renderer first mounted a workspace whose Agent and Setup PTYs were already alive and owned by the host runtime. The canonical workspace session still named the originals, but missing or delayed renderer projection state was treated as permission to recover them. Replacements reused the same tab and leaf identities, hid the writable originals, duplicated transcript output, and could end with Conversation interrupted.

Invariant: a runtime-owned live PTY has exclusive stable ownership of its host, workspace, tab, leaf, and provider process. First mount, activation, hydration, remount, and reconnect must adopt that exact owner, preserve live input and output, and create zero replacement PTYs or provider resume commands. Fresh recovery is allowed only after exact not-found or death proof.

Authoritative ownership fix

The host runtime creates background PTYs and durable tab and leaf bindings, while renderer mount historically chose attach, reattach, or fresh spawn from renderer-local state. This PR moves that decision to the authoritative host boundary:

  • resolve the exact host, workspace, tab, and leaf owner from runtime and durable session state;
  • use daemon and provider attachOnly to adopt the existing PTY without launch or resume work;
  • preserve handle, PTY, incarnation, provider sequence, process, and provider-session identity;
  • permit fresh spawn only after exact attach-not-found retires the dead owner and lifecycle/path fences still pass;
  • adopt before auth, Agent Teams, history, TCC, host-env preparation, claims, capability checks, or fresh-launch telemetry;
  • serialize renderer and runtime materialization by exact connection, workspace, and pane key;
  • settle claims and reservations on every abort/error and preserve adopted ownership if a later binding write fails.

Unknown or missing renderer state is never proof that a host PTY is dead.

Linux renderer-delivery investigation

Fresh Linux run 30781951546, job 91588479137, proved terminal.read received the exact PID-bearing marker from the original mounted PTY while neither the xterm full buffer nor viewport contained it.

Diagnostic run 30784062230, job 91594521168, placed the failure boundary between renderer dispatch and xterm parse/ACK: the exact PTY had data and replay handlers; its dispatcher received all 115 characters; document and main target state were visible/active/not hidden; no target hidden drop occurred; main sent 115 characters, ACKed 0, and retained 115 in flight; and both full buffer and viewport lacked the marker while the viewport was at bottom. This disproved stale document visibility and main hidden gating.

A deterministic renderer contract then proved a separate same-generation duplicate-deferral hazard. onReattachDetermined now begins a barrier only when that generation has no owner. The contract forces explicit reattach, immediate credit-bearing live bytes, authoritative snapshot parsing, ordered xterm delivery, and ACK settlement. It is red with the one-line guard reverted and green on the candidate.

Linux tracing showed that guard was necessary but not the remaining E2E cause. Run 91597327211 stopped after begin-explicit; run 91597953084 reached structural-start, payload-parsed, fit-start, and fit-wait, but never fit-complete or deferral finish. Chromium withheld requestAnimationFrame for the hidden Electron window, so the nominally bounded safe-fit retry never advanced and immediate live bytes remained deferred indefinitely.

The causal product fix races the existing rAF layout retry with a timer fallback. It preserves replay-before-live serialization, retries only through the existing bounded budget, and releases deferred output when a hidden window withholds animation frames. It does not wait for document visibility, pane activity, or a later user action. The immediate post-bind send remains unchanged.

Diagnostic head 88ac4541a719bc8771b36c3182f9e443bb95162b then delivered the exact remount marker to both authoritative terminal.read and the mounted xterm viewport in Linux CI. That run failed later because the hidden-window xterm accessibility tree was stale and omitted even this already-proven viewport marker. The final oracle uses independent authoritative host output plus mounted viewport output for that accepted-write checkpoint. All temporary trace fields and failure logging are absent from the final tree.

Deterministic cross-boundary oracle

Current oracle: tests/e2e/live-background-terminal-mount-authority.spec.ts
SHA-256: e8e0f013273256762eb3bf5e9216bc6141d73d64fbf083786cb4fa5b2fa58b9a

The real Electron topology creates a background runtime-owned Codex Agent PTY, Setup PTY, and unrelated canary; removes only target renderer projections; mounts and activates the workspace; then reloads and remounts the renderer. It captures runtime, renderer epoch, daemon PID, worktree, tab, leaf, PTY, incarnation, provider process PID/session, and command identities. Independent signals are exact runtime/process inventory plus authoritative host output and mounted xterm output. It asserts zero replacement launch, resume, signal, interruption, or canary mutation.

Command:

env CI=1 pnpm exec playwright test tests/e2e/live-background-terminal-mount-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1

Ownership causal matrix

Revision Result
code-equivalent main 922268af10932937d35ee25c6a2af50f5a4aabb6 RED: inventory grew from 3 to 5 live writable PTYs; Agent and Setup gained replacement owners; mounted identity changed
candidate ownership fix 1fd0c24bbc75ec2b4b6393fbea603be090d54fda GREEN: exactly 3 live PTYs; original Agent/Setup identities and visible I/O survived mount/remount; zero replacement or resume
literal ownership-fix revert 5ad4a6f01420b6661272d42fab4ac6b13a5b692e RED with the same replacement behavior

The hidden-window fit contract is green on the current scheduler and times out red when the timer fallback is literally reverted. The explicit-reattach delivery-credit contract is green on the current guard and red when that guard is literally reverted.

Focused contracts and review

Focused contracts cover daemon attach-only semantics, local-provider reattach, runtime-owned persistence, renderer adoption/replay, remote-runtime transport, host scoping, git worktrees, and folder workspaces. Adversarial regressions prove adoption wins before claim/create work, concurrent renderer/runtime adoption coalesces across provider attach and publication, and proven-dead folder ownership still passes the path fence before recovery.

Three existing same-workspace read-only reviews of the ownership product tree were clean: adversarial, performance/reliability, and deterministic-oracle review. Greptile's prior review rated it safe to merge; its fresh review could not run because repository credits are exhausted. A fresh CodeRabbit review is requested on the final head.

Validation

  • focused renderer delivery/fit contracts: 551 passed;
  • full focused authority matrix: 2,392 passed, 1 skipped across 9 suites;
  • full pnpm typecheck: passed;
  • full pnpm lint, reliability-gate manifest, max-lines ratchet, and code-quality audits: passed;
  • changed-file oxfmt --check and git diff --check: passed;
  • rebuilt Electron headless live-mount oracle: passed;
  • force-headed macOS Electron live-mount oracle: passed;
  • Linux diagnostic CI proved the original remount marker reaches host output and mounted viewport with the timer fallback;
  • final-head changed Linux E2E and Windows native smoke: passed;
  • diagnostic overlay and the disproven stale-visibility gate assertion are absent;
  • reliability gate requires same-generation explicit reattach to drain the authoritative snapshot before immediate live bytes and ACK their delivery credit;
  • exact final head: e708853b0af52c02751fedb0349dea6fff9fffde.

Alternatives and tradeoffs

Renderer-only projection repair cannot prevent a process created across the host boundary. Renderer-local recovery guards cannot distinguish unknown from dead. Cleanup after spawn is too late because the duplicate provider process already ran. Waiting for visibility/activity would defer correct early output and conceal the race, so the fix instead makes the existing bounded fit continuation advance under hidden-window scheduling.

The main downside is additional attach/create arbitration and protocol surface. A transport failure now fails closed and can delay recovery until authority is available; that is safer than launching a duplicate. Protocol compatibility is versioned, exact-key maps are bounded and cleared, and attach-only paths skip fresh-spawn preparation.

Remaining gaps and CI

No physical Windows desktop user journey, WSL, live SSH host, or paired-runtime E2E was run for this final renderer delta. Final-head Windows native smoke passed; SSH and paired authority remain contract-covered, and folder workspaces are covered by ownership/path-fence contracts rather than a separate headed journey.

Fresh merge-ref CI for e708853b0af52c02751fedb0349dea6fff9fffde completed with 46 passing and 5 intentionally skipped checks, zero failures or pending checks. The changed Linux E2E, Windows native smoke, and aggregate verify are green; GitHub reports MERGEABLE and CLEAN. This review task did not merge the PR.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a live PTY duplication bug where a renderer mounting a workspace with already-running Agent and Setup PTYs could create a second PTY and provider resume process instead of adopting the existing ones. The root cause was that renderer-local layout state (missing projections, stale ptyIdsByTabId) was treated as permission to recover/spawn even when the host runtime owned live PTYs.

  • Introduces an attachOnly flag propagated through the protocol stack (daemon v31, DaemonPtyAdapter, LocalPtyProvider, terminal-host-create-contract) so that missing ownership rejects instead of creating a new process, and gates on STABLE_PANE_ATTACH_ONLY_DAEMON_PROTOCOL_VERSION for wire compatibility.
  • Adds claimRuntimePaneCreate / pendingRuntimePaneCreatesByOwnerKey and stablePaneAdoptionsByOwnerKey to serialize runtime and renderer pane adoption/creation by a three-part owner key [connectionId, worktreeId, paneKey], correctly isolating identical pane coordinates across hosts and worktrees.
  • Fixes a persistence-failure regression: adopted (isReattach) PTY ownership is now preserved on persist errors rather than being torn down and the process shut down.

Confidence Score: 5/5

Safe to merge. The change moves process-creation authority to the host boundary and prevents the renderer from spawning duplicate PTYs against still-alive runtime-owned sessions.

The arbitration logic in resolveStablePaneOwner and attachStablePaneOwner is well-structured: runtime and persisted state are cross-checked before any attach attempt, owner-conflict and host-mismatch conditions throw rather than silently proceeding, and the attach-only path fails closed with a versioned protocol gate for older daemons. The adoption-before-resume sequencing in orca-runtime.ts correctly skips agent-teams planning, auth, telemetry, and spawn-command registration for adopted PTYs. The ownership preservation fix on persistence failure prevents tearing down a live adopted PTY when a binding write fails. The three-part reservation key correctly scopes coalescing to a connection+worktree+pane coordinate rather than just pane, preventing multi-host collisions. Coverage is extensive: 439 focused contract tests, 2,572 full-matrix tests, and a deterministic Electron E2E oracle that is red on main and green on this candidate.

Files Needing Attention: No files require special attention. The most complex surface is src/main/ipc/pty.ts, but the two independent spawn handlers follow the same stable-pane resolution and adoption pattern symmetrically, and both are exercised by the focused contract suite.

Important Files Changed

Filename Overview
src/main/ipc/pty.ts Core change: adds stable-pane adoption infrastructure (resolveStablePaneOwner, attachStablePaneOwner, spawnForStablePane, adoptStablePane, claimRuntimePaneCreate), renames reservation map to include connection+worktree key for multi-host correctness, guards side-effects (telemetry, spawn command, claude launch) behind !stablePaneOwner, and fixes adopted-ownership loss on persistence failure.
src/main/runtime/orca-runtime.ts Adds claimStablePaneCreate and adoptStablePane to RuntimePtyController; calls adoptStablePane before agent-teams plan, auth, and provider spawn; adds connected: boolean to resolveTerminalPane return so disconnected daemon panes are not treated as live owners.
src/main/daemon/daemon-pty-adapter.ts Version-gates attachOnly on STABLE_PANE_ATTACH_ONLY_DAEMON_PROTOCOL_VERSION (v31) and skips history-restore probe for attach-only requests, correctly forwarding the flag to the daemon wire message.
src/main/providers/local-pty-provider.ts Extends normalizeLocalCallerSessionId with allowNumeric to accept numeric PIDs during attach-only; throws 'Session not found' immediately for attachOnly with a missing session instead of falling through to a fresh spawn.
src/renderer/src/components/terminal-pane/pty-connection.ts Handles connectResult.isReattach early in the spawn promise chain to settle the serializer and complete reattach-live-data deferral without re-delivering startup commands; moves stale-visibility recovery registration before PTY handler binding so early activation can flush occlusion state.
src/main/ipc/pty.test.ts Adds ~825 lines of focused contract tests: claim serialization, concurrent runtime/renderer adoption coalescing, stable-pane live-owner adoption (git worktree and folder workspace), dead-owner retirement, incarnation conflict detection, and persistence failure with adopted ownership preserved.
tests/e2e/live-background-terminal-mount-authority.spec.ts New 829-line Electron E2E oracle: creates background Agent and Setup PTYs before renderer mount, then asserts zero replacement PTYs after first activation and remount, verifying exact PTY/process/incarnation/handle identity and visible live I/O in the mounted xterm viewport.

Sequence Diagram

sequenceDiagram
    participant Runtime as OrcaRuntime
    participant IPC as pty.ts IPC
    participant Adapter as DaemonPtyAdapter
    participant Daemon as DaemonServer
    participant Renderer as Renderer pty-connection

    Note over Runtime,Renderer: Background PTYs already alive in daemon

    Runtime->>IPC: claimStablePaneCreate(worktreeId, tabId, leafId)
    IPC-->>Runtime: release token

    Renderer->>IPC: pty:spawn(tabId, leafId, worktreeId)
    IPC->>IPC: Check pendingRuntimePaneCreatesByOwnerKey - waits

    Runtime->>IPC: adoptStablePane(tabId, leafId, worktreeId)
    IPC->>IPC: resolveStablePaneOwner from runtime and store
    IPC->>Adapter: "spawn with attachOnly=true, sessionId=ptyId"
    Adapter->>Daemon: "createOrAttach with attachOnly=true"
    Daemon-->>Adapter: "isNew=false"
    Adapter-->>IPC: "id=ptyId, isReattach=true"
    IPC-->>Runtime: StablePaneAdoption result and owner

    Runtime->>IPC: release claim token
    Note over IPC: Renderer unblocks
    IPC->>IPC: resolveStablePaneOwner finds existing owner
    IPC->>Adapter: attachStablePaneOwner, no fresh spawn
    IPC-->>Renderer: "id=ptyId, isReattach=true, stablePaneOwner"

    Renderer->>Renderer: handleReattachResult and finishReattachLiveDataDeferral
    Note over Renderer: Live PTY IO preserved, zero replacement PTYs created
Loading

Reviews (10): Last reviewed commit: "fix: preserve runtime-owned terminal pan..." | Re-trigger Greptile

Comment thread src/main/ipc/pty.ts Resolved
Comment thread src/main/daemon/daemon-pty-adapter.ts Resolved
Comment thread src/main/providers/ssh-pty-liveness.ts Resolved
@coderabbitai

coderabbitai Bot commented Jul 31, 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

The change adds daemon protocol version 31 and attach-only PTY adoption. IPC and runtime paths coordinate stable-pane claims, adopt existing owners, preserve PTY identities, retire stale persistence, and distinguish reattachments from fresh spawns. Renderer transport defers live data during reattachment and reports reattach state before delivery. Renderer lifecycle recovery now uses exact main-frame navigation events, dispatcher readiness, watchdog handling, and missed-reset reconciliation. Reliability gates and end-to-end tests cover identity preservation, live I/O, reload remounting, and canary isolation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.00% which is insufficient. The required threshold is 80.00%. 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.
Title check ✅ Passed The title clearly summarizes the primary change: preserving live Agent PTYs during renderer graph hydration.
Description check ✅ Passed The description thoroughly covers scope, testing, review, platform validation, and gaps, but omits dedicated Screenshots and Security Audit sections.
✨ 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: 9

Caution

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

⚠️ Outside diff range comments (1)
config/reliability-gates.jsonc (1)

1992-1995: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Update runtimeBudget for the expanded command set.

scope still reads local renderer state test and p95Seconds stays 15. The gate now registers 13 commands that span renderer, main IPC, daemon, SSH, and runtime suites, plus a Docker SSH reload claim. The current budget no longer describes the registered work and can hide a runtime regression.

Set a scope string and p95 that cover all registered lanes.

📝 Proposed edit
       "runtimeBudget": {
-        "p95Seconds": 15,
-        "scope": "local renderer state test"
+        "p95Seconds": 60,
+        "scope": "focused renderer hydration, terminal-pane, main IPC/daemon/SSH liveness, and runtime authority tests"
       },
🧹 Nitpick comments (7)
src/main/providers/ssh-pty-liveness.ts (2)

96-99: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Coalesced callers inherit the first caller's remaining budget.

probe returns the in-flight promise, and the 1s caller budget lives inside probeSshPtyLiveness. A second caller that arrives 900ms later therefore resolves after about 100ms, and a caller that arrives after the first timeout receives null immediately. DaemonPtyAdapter.probePtyLiveness differs here: it arms a fresh 1s race per call while still sharing one request.

Both behaviors are safe because null means unknown and the late notification still fires. Confirm the shortened budget is intended for SSH, or align it with the daemon adapter.


100-121: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add one line that explains the token fence.

The token identity check in isCurrent is the mechanism that stops a late answer from mutating livePtyIds after invalidate or dispose. That intent is not obvious from the code.

♻️ Proposed comment
     const token = {}
+    // Why: a late answer must be dropped once invalidate/dispose replaced or cleared this token.
     this.tokens.set(id, token)
src/main/daemon/degraded-daemon-pty-provider.test.ts (1)

188-190: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Also re-trigger the legacy adapter after unsubscribe.

The test only re-triggers current. A combined unsubscribe that skipped the legacy adapter would still pass. The router test at src/main/daemon/daemon-pty-router.test.ts Lines 212-213 triggers both.

💚 Proposed assertion
   unsubscribe()
   current.triggerLivenessAuthority('after-unsubscribe')
+  legacy.triggerLivenessAuthority('after-unsubscribe')
   expect(changed).toEqual(['daemon-pane', 'legacy-pane'])
src/main/daemon/daemon-pty-adapter.ts (1)

889-945: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Drop the liveness probe when the session exits.

livenessPtyLivenessById is only cleared when the same probe completes/fails; the daemon exit cleanup at src/main/daemon/daemon-pty-adapter.ts:2342-2364 leaves it for event.sessionId. Add this.livenessProbesById.delete(event.sessionId) in the exit path so a late probe answer from the retired incarnation cannot trigger a new liveness announcement.

src/main/ipc/pty.ts (1)

6273-6316: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract one shared liveness resolver for the three probe call sites.

Provider resolution plus "prefer probePtyLiveness, else hasPty, else null" now appears three times: the runtime controller at lines 4682-4691, pty:hasPty at lines 6273-6285, and pty:probePtyLiveness at lines 6296-6309. If one site later changes its fallback or its error handling, the runtime path and the renderer path report different liveness for the same PTY.

Extract a single function that resolves the provider and returns boolean | null, then call it from all three sites.

♻️ Proposed shared helper
+async function resolveExactPtyLiveness(id: string): Promise<boolean | null> {
+  const ownedConnectionId = ptyOwnership.get(id)
+  const parsedSshId = ownedConnectionId === undefined ? parseAppSshPtyId(id) : null
+  const provider = parsedSshId
+    ? sshProviders.get(parsedSshId.connectionId)
+    : tryGetProviderForPty(id)
+  if (!provider) {
+    return null
+  }
+  try {
+    return provider.probePtyLiveness
+      ? await provider.probePtyLiveness(id)
+      : (provider.hasPty?.(id) ?? null)
+  } catch {
+    // Why: liveness may only close panes on an authoritative false.
+    return null
+  }
+}

Then the handlers reduce to:

-  ipcMain.handle('pty:hasPty', async (_event, args: { id: string }): Promise<boolean | null> => {
-    const ownedConnectionId = ptyOwnership.get(args.id)
-    ...
-  })
+  ipcMain.handle('pty:hasPty', async (_event, args: { id: string }): Promise<boolean | null> =>
+    resolveExactPtyLiveness(args.id)
+  )
src/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.test.ts (1)

120-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Isolate the module-level registry between tests.

terminal-pane-authority-recovery.ts keeps registrations, unsubscribeStore, and storeSubscriptionEpoch at module scope. All three tests await import the same module instance, so state carries over and the manual storeHarness.subscribe.mockClear() / unsubscribeStore.mockClear() calls only mask that coupling. The suite then depends on execution order and on test 1 disposing every registration.

Reset the module registry and the mocks in a beforeEach so each test starts from a clean subscription state.

♻️ Proposed refactor: reset modules per test
-import { expect, it, vi } from 'vitest'
+import { beforeEach, expect, it, vi } from 'vitest'
+beforeEach(() => {
+  vi.resetModules()
+  storeHarness.subscribers.clear()
+  storeHarness.subscribe.mockClear()
+  storeHarness.unsubscribeStore.mockClear()
+})

Then remove the per-test mockClear() calls at the start of the second and third tests.

Also applies to: 217-219

src/renderer/src/lib/sleeping-agent-pane-ownership.ts (1)

112-138: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Share the stable-pane resolution step with recordPaneIsOwnedByPreservedPane.

getPreservedStablePaneRecoveryTabId repeats the pane-key parse, tab lookup, hasMatchingStablePaneLayout check and hasRestorableStablePanePty check that the stable branch of recordPaneIsOwnedByPreservedPane also performs. Recovery eligibility and pane ownership must agree. If one copy changes later, the resume coordinator can both defer a record and treat its pane as owned. Extract one helper that resolves { tabId, leafId, tab } plus the layout and PTY checks, then use it in both functions.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 532f2117-6a1b-4e08-a451-53bb46f235eb

📥 Commits

Reviewing files that changed from the base of the PR and between 79251d7 and c15e01f.

📒 Files selected for processing (51)
  • config/reliability-gates.jsonc
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-liveness-probe.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/degraded-daemon-pty-provider.test.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/providers/ssh-pty-liveness.test.ts
  • src/main/providers/ssh-pty-liveness.ts
  • src/main/providers/ssh-pty-notification-routing.ts
  • src/main/providers/ssh-pty-provider-output-state.ts
  • src/main/providers/ssh-pty-provider.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/live-agent-resume-hydration-race.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session-provider-claim.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.ts
  • src/renderer/src/lib/sleeping-agent-pane-ownership.ts
  • src/renderer/src/lib/sleeping-agent-provider-claim-index.test.ts
  • src/renderer/src/lib/sleeping-agent-recovery-claims.ts
  • src/renderer/src/lib/sleeping-agent-recovery-dispatch-barrier.ts
  • src/renderer/src/lib/sleeping-agent-recovery-request-generation.ts
  • src/renderer/src/lib/sleeping-agent-recovery-topology-state.ts
  • src/renderer/src/lib/sleeping-agent-recovery-topology.test.ts
  • src/renderer/src/lib/sleeping-agent-recovery-topology.ts
  • src/renderer/src/runtime/runtime-client-events.test.ts
  • src/renderer/src/runtime/runtime-client-events.ts
  • src/renderer/src/runtime/runtime-terminal-authority-events.test.ts
  • src/renderer/src/runtime/runtime-terminal-authority-events.ts
  • src/shared/protocol-version.ts
  • src/shared/runtime-client-events.ts
  • tests/e2e/agent-session-live-force-exit-resume.spec.ts

Comment thread config/reliability-gates.jsonc Resolved
Comment thread config/reliability-gates.jsonc Resolved
Comment thread src/main/daemon/daemon-pty-router.ts Resolved
Comment thread src/main/ipc/pty.ts Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/renderer/src/hooks/useIpcEvents.ts Resolved

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

🧹 Nitpick comments (2)
src/main/ipc/pty.test.ts (1)

2820-2826: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the repeated single-account settings literal into a helper.

The block that builds a codexManagedAccounts array with one account-1 entry pointing at TEST_CODEX_HOME repeats verbatim across several new tests. Extract a small factory, for example buildSingleManagedAccountSettings(TEST_CODEX_HOME), and reuse it at each call site. This reduces duplication and keeps the account shape consistent if it changes later.

♻️ Proposed helper
function buildSingleManagedAccountSettings(managedHomePath: string) {
  return () => ({
    codexManagedAccounts: [
      {
        id: 'account-1',
        managedHomePath,
        managedHomeRuntime: 'host'
      }
    ]
  })
}

Then replace each inline (() => ({ codexManagedAccounts: [...] })) as never call with buildSingleManagedAccountSettings(TEST_CODEX_HOME) as never.

Also applies to: 2856-2862, 3133-3139, 3239-3246, 3267-3274, 3312-3319, 3350-3357

src/renderer/src/runtime/runtime-terminal-authority-events.test.ts (1)

84-84: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert per-listener call counts instead of the total.

The summed count of 100 also passes if one listener receives all 100 events. Assert that every listener receives exactly one call to prove pane-identity scoping.

♻️ Proposed assertion change
-  expect(listeners.reduce((count, listener) => count + listener.mock.calls.length, 0)).toBe(100)
+  expect(listeners.map((listener) => listener.mock.calls.length)).toEqual(
+    listeners.map(() => 1)
+  )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 02a2275f-77fa-4f5f-bbcd-f576b84b45c8

📥 Commits

Reviewing files that changed from the base of the PR and between c15e01f and 7ee57c5.

📒 Files selected for processing (22)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/live-agent-resume-hydration-race.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session-provider-claim.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.test.ts
  • src/renderer/src/runtime/runtime-capability-check-coalescing.test.ts
  • src/renderer/src/runtime/runtime-capability-check-coalescing.ts
  • src/renderer/src/runtime/runtime-rpc-client.ts
  • src/renderer/src/runtime/runtime-terminal-authority-events.test.ts
  • src/renderer/src/runtime/runtime-terminal-authority-events.ts
  • src/shared/protocol-version.ts
  • src/shared/runtime-client-events.ts
🚧 Files skipped from review as they are similar to previous changes (10)
  • src/renderer/src/lib/resume-sleeping-agent-session-provider-claim.test.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/live-agent-resume-hydration-race.test.ts
  • src/shared/runtime-client-events.ts
  • src/main/ipc/pty.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts

@OrcaWin
OrcaWin marked this pull request as draft July 31, 2026 23:20
@OrcaWin
OrcaWin marked this pull request as ready for review July 31, 2026 23:20

@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

Caution

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

⚠️ Outside diff range comments (2)
src/renderer/src/store/slices/agent-status.ts (1)

610-630: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Publish the removed sleeping pane keys from the terminal manual-sleep path.

src/renderer/src/store/slices/terminals.ts still replaces sleeping records and then publishes only the newly captured sleepingAgentSessionRecords keys. This path needs the removedPaneKeys result from removeSleepingRecordsReplacedByManualWorktreeSleep in addition to the retained/new sleeping pane keys, so authority consumers know the topology was lowered for those removed pane keys too.

src/renderer/src/store/slices/terminals.ts (1)

1979-2052: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Topology publish calls bypass their own set() no-op guards at four sites. Each site's set() call has a genuine return s (or return {}) branch that preserves the state reference on purpose — Zustand's standard signal for "nothing changed" — but the following publishTerminalPaneAuthorityTopologyChange(...) call still fires unconditionally, re-queuing a real, existing identity as a recovery candidate even when nothing changed. Guarded siblings in this same PR (clearDirectSshTargetPtyBindings, invalidateStaleDirectSshTargetPtyBindings, retryDirectSshTargetPanes, reconcileWorktreeTabModel, purgeStaleRuntimeHostState) already establish the fix pattern: track whether the set() call produced a real change and gate the publish on it.

  • src/renderer/src/store/slices/terminals.ts#L1979-L2052: gate the updateTabTitle publish so it does not fire when isDecorativeAgentTitleFrameChange filtering or the currentTab.title === nextTitle branch leaves the label unchanged; this is the highest-frequency site since it runs on live PTY title output.
  • src/renderer/src/store/slices/terminals.ts#L2132-L2152: gate the clearTabLaunchAgent publish so it does not fire when !currentTab?.launchAgent.
  • src/renderer/src/store/slices/terminals.ts#L2996-L3028: gate the settleDirectSshPaneRetry publish so it does not fire on the three stale-authority/exhausted-attempt/no-settlement return s branches.
  • src/renderer/src/store/slices/worktrees.ts#L5396-L5476: gate both the setActiveWorktree publish and the nested prepareTerminalTabs publish on their respective hasStateChange/no-op results, restoring the fan-out protection the existing "so session persistence/runtime sync don't fan out" comment already documents.
🧹 Nitpick comments (2)
src/renderer/src/store/slices/direct-ssh-terminal-retry.test.ts (1)

102-119: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Release both listeners in a finally block.

The topology listener registry is module-scoped. If the assertion at Line 114 fails, Lines 115-116 never run, and the listener stays registered for the remaining tests in the run. The sibling test at Lines 89-96 already uses try/finally. Use the same structure here.

♻️ Proposed cleanup
-    expect(store.getState().invalidateStaleDirectSshTargetPtyBindings(authority())).toBe(1)
-    unsubscribe()
-    unsubscribeTopology()
+    try {
+      expect(store.getState().invalidateStaleDirectSshTargetPtyBindings(authority())).toBe(1)
+    } finally {
+      unsubscribe()
+      unsubscribeTopology()
+    }
src/renderer/src/store/slices/ssh-target-terminal-cleanup.ts (1)

120-122: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add one line explaining the omitted pendingActivationSpawn.

The destructure-and-void idiom removes pendingActivationSpawn from the rebuilt tab. The reason is not visible at this site. One short comment states why the flag must not survive target removal.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f6918672-4a87-42f9-a1d1-28a929858b8f

📥 Commits

Reviewing files that changed from the base of the PR and between 7ee57c5 and 6d72ee9.

📒 Files selected for processing (24)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.ts
  • src/renderer/src/lib/live-agent-resume-hydration-race.test.ts
  • src/renderer/src/lib/sleeping-agent-recovery-topology-state.ts
  • src/renderer/src/lib/sleeping-agent-recovery-topology.test.ts
  • src/renderer/src/lib/sleeping-agent-recovery-topology.ts
  • src/renderer/src/runtime/web-runtime-session.ts
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/renderer/src/store/slices/direct-ssh-terminal-retry.test.ts
  • src/renderer/src/store/slices/ssh-target-cleanup.ts
  • src/renderer/src/store/slices/ssh-target-terminal-cleanup.ts
  • src/renderer/src/store/slices/ssh.test.ts
  • src/renderer/src/store/slices/ssh.ts
  • src/renderer/src/store/slices/tabs.ts
  • src/renderer/src/store/slices/terminal-authority-hydration-publication.test.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/renderer/src/store/terminal-pane-authority-topology-events.ts
💤 Files with no reviewable changes (1)
  • src/renderer/src/lib/sleeping-agent-recovery-topology-state.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.ts
  • src/renderer/src/lib/sleeping-agent-recovery-topology.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/lib/live-agent-resume-hydration-race.test.ts
  • config/reliability-gates.jsonc
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts

@OrcaWin
OrcaWin force-pushed the fix-live-agent-resume-hydration-race branch 7 times, most recently from cff503c to 6aadb37 Compare August 3, 2026 04:09
@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Final merge-readiness head: 6aadb37d3bdb7d943a48b815e6ae5608c2011236 (rebased onto f3e087ec06).

Fresh Linux run 30781951546/job 91588479137 proved host terminal.read received the exact original-PTY marker while mounted xterm did not. The observation overlay narrowed this to a visible/active PTY being hidden-gated before renderer dispatch. The new deterministic contract forces document.visibilityState=hidden, activation input before deferred handler binding, then immediate exact-PTY output: literal fix revert is red; candidate is green. The product change only registers the existing stale-visibility observer before deferred binding—no activation wait, polling, timer, or delayed early-output send.

Post-rebase local validation: focused authority matrix 2,381 passed / 1 skipped; typecheck, full lint/static/max-lines/reliability gates, rebuilt headless E2E, and forced-headed E2E passed. Fresh-head CI and Greptile are running.

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

@OrcaWin: I will review the final merge-readiness head, including the visibility-gating change and the PTY authority recovery paths.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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

🧹 Nitpick comments (1)
config/reliability-gates.jsonc (1)

2198-2211: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Newly registered commands lack matching evidenceRuns in two gates. Both gates add commands and widen runtimeBudget.scope, but keep an evidenceRuns list that covers only one command, so the declared scope and the oracle claims have no recorded measurement. The three other gates added in this PR (terminal-session.layout-pty-ownership at Lines 1347-1366, terminal-scroll.streaming-refocus-intent at Lines 3273-3292, and terminal-render.atlas-recovery-fanout at Lines 7625-7653) pair every command with a run, which establishes the intended convention.

  • config/reliability-gates.jsonc#L2198-L2211: add one run for the 8-file focused authority suite at Line 2143 and one for the Electron mount-and-reload journey at Line 2144, so the 180-second runtimeBudget.scope at Lines 2210-2211 is backed by measurements.
  • config/reliability-gates.jsonc#L5061-L5071: add runs for tests/e2e/terminal-cold-activation-deferral.spec.ts (Line 5030) and tests/e2e/ssh-cold-activation-restore.spec.ts (Line 5031), plus the focused vitest suite at Line 5027; both specs already have recorded runs under terminal-provider.ssh-remote-reattach-contract at Lines 5492-5500 and 5555-5563.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b25dbb02-7583-42e0-b9d5-15d4ffc542c4

📥 Commits

Reviewing files that changed from the base of the PR and between b08a8e9 and 6aadb37d3bdb7d943a48b815e6ae5608c2011236.

📒 Files selected for processing (12)
  • config/reliability-gates.jsonc
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/main/daemon/daemon-protocol-version.test.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-server-attach-only.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/terminal-host-agent-session-claim.ts
  • src/main/daemon/terminal-host-attach-only.test.ts
  • src/main/daemon/terminal-host-create-contract.ts
  • src/main/daemon/types.ts
💤 Files with no reviewable changes (1)
  • src/main/daemon/terminal-host-agent-session-claim.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/daemon/daemon-pty-adapter.ts

Comment on lines +736 to +738
if (!p.attachOnly) {
await this.preparePtySpawnUnlessCanceled(p.sessionId, clientId)
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the same strict boolean check for spawn preparation.

A raw request with attachOnly: "false" skips preparePtySpawn here. Line 757 does not forward that value as attachOnly, so TerminalHost.createOrAttach can create a new session without preparation. Normalize the flag once with p.attachOnly === true, then use that value for both decisions.

Proposed fix
-          if (!p.attachOnly) {
+          const attachOnly = p.attachOnly === true
+          if (!attachOnly) {
             await this.preparePtySpawnUnlessCanceled(p.sessionId, clientId)
           }
...
-            ...(p.attachOnly === true ? { attachOnly: true } : {}),
+            ...(attachOnly ? { attachOnly: true } : {}),

@OrcaWin
OrcaWin force-pushed the fix-live-agent-resume-hydration-race branch 3 times, most recently from eb8c60a to 630aaf9 Compare August 3, 2026 04:32

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Greptile has paused reviews on this repository — it used its 2000 free open-source review credits for this billing period. Reviews resume automatically on August 28. To continue before then, an organization admin can keep reviews running past the free credits — those bill as normal usage.

@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

Please review exact final head 630aaf9322e0392c88923b2af90978b835a092ee, especially the same-generation reattach deferral ownership guard and replay-before-live delivery-credit contract. Read-only review only; do not merge.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

@OrcaWin: I will review head 630aaf9322e0392c88923b2af90978b835a092ee. I will focus on the same-generation reattach deferral ownership guard and the replay-before-live delivery-credit contract. I will not merge or modify the branch.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@OrcaWin
OrcaWin force-pushed the fix-live-agent-resume-hydration-race branch from 630aaf9 to b9ef1bd Compare August 3, 2026 04:41

@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: 3

🧹 Nitpick comments (6)
tests/e2e/live-background-terminal-mount-authority.spec.ts (3)

86-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Collapse readSpawnLedger into readJsonLines.

readSpawnLedger duplicates readJsonLines. Define it in terms of the generic reader.

♻️ Proposed refactor
-function readSpawnLedger(): SpawnEvent[] {
-  if (!existsSync(spawnLedgerPath)) {
-    return []
-  }
-  return readFileSync(spawnLedgerPath, 'utf8')
-    .split(/\r?\n/)
-    .filter(Boolean)
-    .map((line) => JSON.parse(line) as SpawnEvent)
-}
-
 function readJsonLines<T>(filePath: string): T[] {
   if (!existsSync(filePath)) {
     return []
   }
   return readFileSync(filePath, 'utf8')
     .split(/\r?\n/)
     .filter(Boolean)
     .map((line) => JSON.parse(line) as T)
 }
+
+function readSpawnLedger(): SpawnEvent[] {
+  return readJsonLines<SpawnEvent>(spawnLedgerPath)
+}

117-124: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Isolate the seed commit from developer Git configuration.

git commit inherits the developer global configuration. If commit.gpgsign is enabled, the commit fails and the test fails during setup. Disable signing and hooks for the seed commit.

♻️ Proposed refactor
   execFileSync(
     'git',
-    ['-c', 'user.name=Orca E2E', '-c', '[email protected]', 'commit', '-m', 'seed'],
+    [
+      '-c',
+      'user.name=Orca E2E',
+      '-c',
+      '[email protected]',
+      '-c',
+      'commit.gpgsign=false',
+      'commit',
+      '--no-verify',
+      '-m',
+      'seed'
+    ],
     { cwd: repoPath }
   )

476-486: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Keep the click failure reason in the test output.

typeIntoTerminal converts a click failure into false. The caller then reports only expect(false).toBe(true). The underlying locator error is lost. Attach the error text to the assertion.

♻️ Proposed refactor
-async function typeIntoTerminal(page: Page, tabId: string, marker: string): Promise<boolean> {
+async function typeIntoTerminal(page: Page, tabId: string, marker: string): Promise<void> {
   const terminal = page.locator(`[data-terminal-tab-id=${JSON.stringify(tabId)}] .xterm:visible`)
-  try {
-    await terminal.click()
-  } catch {
-    return false
-  }
+  await expect(terminal, `Terminal pane must be clickable: ${tabId}`).toBeVisible()
+  await terminal.click()
   await page.keyboard.type(marker, { delay: 20 })
   await page.keyboard.press('Enter')
-  return true
 }

Update the three call sites to await typeIntoTerminal(...) without the boolean assertion.

src/main/ipc/pty.ts (1)

508-536: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Make the returned release closure idempotent.

claimRuntimePaneCreate returns a closure that decrements claim.count on every call. A caller that releases twice (for example an error path plus a finally) drops the count below the real number of in-flight creates and resolves the barrier early, so a concurrent pty:spawn stops waiting. Add a one-shot guard in the closure.

♻️ Proposed one-shot release guard
 function claimRuntimePaneCreate(ownerKey: string): () => void {
+  let released = false
+  const releaseOnce = (claim: PendingRuntimePaneCreate) => (): void => {
+    if (released) {
+      return
+    }
+    released = true
+    releaseRuntimePaneCreate(ownerKey, claim)
+  }
   const existing = pendingRuntimePaneCreatesByOwnerKey.get(ownerKey)
   if (existing) {
     existing.count += 1
-    return () => releaseRuntimePaneCreate(ownerKey, existing)
+    return releaseOnce(existing)
   }
   let resolve!: () => void
   const claim = {
     count: 1,
     promise: new Promise<void>((done) => {
       resolve = done
     }),
     resolve: () => resolve()
   }
   pendingRuntimePaneCreatesByOwnerKey.set(ownerKey, claim)
-  return () => releaseRuntimePaneCreate(ownerKey, claim)
+  return releaseOnce(claim)
 }
src/main/runtime/orca-runtime.ts (1)

1540-1602: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the adopted stable-pane payload into a named type.

The object shape at Lines 1549-1559 and Lines 1587-1597 is duplicated verbatim. If one declaration changes, the other still compiles and adoption silently degrades, because both claimStablePaneCreate and adoptStablePane are optional members.

♻️ Proposed refactor
+type AdoptedStablePane = {
+  result: PtySpawnResult
+  owner: {
+    handle?: string
+    tabId: string
+    leafId: string
+    ptyId: string
+    incarnationId?: string
+  }
+  materialized?: true
+}
+
 type RuntimePtyController = {
   claimStablePaneCreate?(args: {
     worktreeId: string
     connectionId: string | null
     tabId: string
     leafId: string
   }): () => void
   adoptStablePane?(opts: {
     cols: number
     rows: number
     cwd?: string
     connectionId: string | null
     worktreeId: string
     preAllocatedHandle: string
     tabId: string
     leafId: string
-  }): Promise<{
-    result: PtySpawnResult
-    owner: {
-      handle?: string
-      tabId: string
-      leafId: string
-      ptyId: string
-      incarnationId?: string
-    }
-    materialized?: true
-  } | null>
+  }): Promise<AdoptedStablePane | null>

Then use adoptedStablePane?: AdoptedStablePane in the spawn options.

src/main/ipc/pty.test.ts (1)

8339-8350: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Include connected on runtime pane mocks and cover connected: false.

resolveStablePaneOwner treats connected === false as a discarded runtime candidate. The mocks in src/main/ipc/pty.test.ts return objects without this field, so they only exercise the fail-open branch. Add connected: true to the successful mocks, such as at lines 8339, 8522, and 9138, and cover connected: false so the rejected branch is exercised.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ba6e7574-add9-4a70-9d68-6f46b03f405d

📥 Commits

Reviewing files that changed from the base of the PR and between 6aadb37d3bdb7d943a48b815e6ae5608c2011236 and 630aaf9322e0392c88923b2af90978b835a092ee.

📒 Files selected for processing (29)
  • config/reliability-gates.jsonc
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/main/daemon/daemon-protocol-version.test.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-server-attach-only.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/terminal-host-agent-session-claim.ts
  • src/main/daemon/terminal-host-attach-only.test.ts
  • src/main/daemon/terminal-host-create-contract.ts
  • src/main/daemon/types.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/shared/local-build-compatibility-contract.json
  • src/shared/local-build-compatibility-contract.ts
  • src/shared/runtime-types.ts
  • tests/e2e/live-background-terminal-mount-authority.spec.ts
💤 Files with no reviewable changes (1)
  • src/main/daemon/terminal-host-agent-session-claim.ts
🚧 Files skipped from review as they are similar to previous changes (14)
  • src/main/daemon/daemon-protocol-version.test.ts
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/main/daemon/terminal-host-attach-only.test.ts
  • src/main/daemon/terminal-host-create-contract.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-server-attach-only.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/main/daemon/types.ts
  • config/reliability-gates.jsonc
  • src/main/daemon/daemon-server.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts

Comment thread src/main/ipc/pty.ts Resolved
Comment thread src/main/ipc/pty.ts Resolved
@OrcaWin
OrcaWin force-pushed the fix-live-agent-resume-hydration-race branch 3 times, most recently from 88ac454 to a500ddc Compare August 3, 2026 05:00
@OrcaWin

OrcaWin commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

Please review exact head a500ddc5737ad9149e5e0e23517e63861687e5ef, especially the hidden-window rAF timer fallback, same-generation explicit-reattach snapshot/live ordering with delivery-credit ACK, and removal of all temporary diagnostics. Read-only review only; do not merge.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

@OrcaWin: I will review exact head a500ddc5737ad9149e5e0e23517e63861687e5ef. I will focus on the specified delivery and fallback behavior. I will not modify or merge the branch.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

commit="a500ddc573a1e2bf216a3bc781bf0bdf6ce1039a"

git cat-file -e "${commit}^{commit}"
git show --no-ext-diff --no-renames --format=fuller --stat "$commit"
printf '\n--- changed files ---\n'
git diff-tree --no-commit-id --name-status -r "$commit"

printf '\n--- focused diff: renderer terminal delivery and lifecycle files ---\n'
git diff --no-ext-diff --no-renames "${commit}^" "$commit" -- \
  src/renderer/src/components/terminal-pane/pty-connection.ts \
  src/renderer/src/components/terminal-pane/pty-connection.test.ts \
  src/renderer/src/components/terminal-pane/pty-transport.ts \
  src/renderer/src/components/terminal-pane/pty-transport.test.ts \
  src/main/ipc/pty.ts \
  src/main/ipc/pty.test.ts

printf '\n--- focused source outlines ---\n'
for file in \
  src/renderer/src/components/terminal-pane/pty-connection.ts \
  src/renderer/src/components/terminal-pane/pty-connection.test.ts \
  src/renderer/src/components/terminal-pane/pty-transport.ts \
  src/main/ipc/pty.ts
do
  if [ -f "$file" ]; then
    echo "### $file"
    ast-grep outline "$file" --items all || true
  fi
done

printf '\n--- candidate diagnostic markers in changed source files ---\n'
git diff-tree --no-commit-id --name-only -r "$commit" \
  | while IFS= read -r file; do
      case "$file" in
        *.ts|*.tsx|*.js|*.jsx)
          rg -n -i -C 2 'temporary|diagnostic|debug|console\.(log|debug|info|warn)|trace' "$file" || true
          ;;
      esac
    done

Length of output: 2047


🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo="stablyai/orca"
commit="a500ddc573a1e2bf216a3bc781bf0bdf6ce1039a"

printf '%s\n' '--- requested commit lookup ---'
gh api "repos/${repo}/commits/${commit}" \
  --jq '{sha, html_url, parents: [.parents[].sha], message: .commit.message, committed_at: .commit.committer.date}' \
  || true

printf '%s\n' '--- pull request current head ---'
gh api "repos/${repo}/pulls/11789" \
  --jq '{number, state, head: {ref: .head.ref, sha: .head.sha, repo: .head.repo.full_name}, base: {ref: .base.ref, sha: .base.sha}}'

printf '%s\n' '--- pull request commits containing the requested revision, if present ---'
gh api --paginate "repos/${repo}/pulls/11789/commits?per_page=100" \
  --jq '.[] | select(.sha == "'"$commit"'") | {sha, html_url, message: .commit.message}' \
  || true

Length of output: 1568


@OrcaWin: I cannot review the specified exact head. GitHub does not recognize a500ddc573a1e2bf216a3bc781bf0bdf6ce1039a and returns HTTP 422.

Pull request #11789 currently has head a500ddc5737ad9149e5e0e23517e63861687e5ef. The requested SHA is not in the pull request commit list.

Please provide a valid exact SHA, or confirm that I should review the current pull request head.

You are interacting with an AI system.

@OrcaWin
OrcaWin force-pushed the fix-live-agent-resume-hydration-race branch from a500ddc to 82e0eaa Compare August 3, 2026 05:06
@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

Please confirm exact final head 82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf. Since the prior request, the only delta is the E2E harness using click({ force: true }) on the exact visible xterm after reload so Linux does not stall in Playwright preflight; exact PTY input receipt remains asserted. Read-only review only; do not merge.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

commit="82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf"
repo="stablyai/orca"
pr="11789"

printf '%s\n' '--- exact commit ---'
git cat-file -e "${commit}^{commit}"
git show --no-ext-diff --no-renames --format=fuller --stat "$commit"

printf '%s\n' '--- pull request head ---'
gh api "repos/${repo}/pulls/${pr}" \
  --jq '{number, state, head_sha: .head.sha, head_ref: .head.ref, base_sha: .base.sha}'

printf '%s\n' '--- parent and changed paths ---'
git show --no-ext-diff --no-renames --format='%H%n%P%n%s' --name-status "$commit"

printf '%s\n' '--- exact commit diff ---'
git diff --no-ext-diff --no-renames "${commit}^" "$commit" -- \
  tests/e2e/live-background-terminal-mount-authority.spec.ts

printf '%s\n' '--- E2E test outline ---'
ast-grep outline tests/e2e/live-background-terminal-mount-authority.spec.ts --items all

printf '%s\n' '--- focused click and PTY input assertion context ---'
rg -n -C 12 \
  'click\s*\(\s*\{\s*force:\s*true\s*\}\s*\)|exact.*PTY|input.*receipt|received.*input|keyboard|reload' \
  tests/e2e/live-background-terminal-mount-authority.spec.ts

Length of output: 45180


🏁 Script executed:

#!/bin/bash
set -euo pipefail

previous="a500ddc5737ad9149e5e0e23517e63861687e5ef"
current="82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf"
file="tests/e2e/live-background-terminal-mount-authority.spec.ts"

printf '%s\n' '--- prior-head ancestry ---'
git cat-file -e "${previous}^{commit}"
git merge-base --is-ancestor "$previous" "$current"
printf 'prior_is_ancestor=true\n'
git log --oneline --ancestry-path "${previous}..${current}"

printf '%s\n' '--- changed paths since prior head ---'
git diff --no-ext-diff --no-renames --name-status "$previous" "$current"

printf '%s\n' '--- focused delta since prior head ---'
git diff --no-ext-diff --no-renames -U20 "$previous" "$current" -- "$file"

printf '%s\n' '--- post-reload input call path ---'
sed -n '740,820p' "$file"

printf '%s\n' '--- all exact-PTY write assertions ---'
rg -n -C 5 'typeIntoTerminal\(|assertExactPtyReceivedMarker\(' "$file"

Length of output: 1231


🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo="stablyai/orca"
pr="11789"
previous="a500ddc5737ad9149e5e0e23517e63861687e5ef"
current="82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf"
file="tests/e2e/live-background-terminal-mount-authority.spec.ts"

printf '%s\n' '--- current commit and immediate parent ---'
gh api "repos/${repo}/commits/${current}" \
  --jq '{sha, parents: [.parents[].sha], message: .commit.message}'

printf '%s\n' '--- prior commit lookup ---'
gh api "repos/${repo}/commits/${previous}" \
  --jq '{sha, parents: [.parents[].sha], message: .commit.message}' \
  || true

printf '%s\n' '--- matching prior SHA in PR history ---'
gh api --paginate "repos/${repo}/pulls/${pr}/commits?per_page=100" \
  --jq '.[] | select(.sha == "'"${previous}"'") | {sha, message: .commit.message}' \
  || true

printf '%s\n' '--- PR commits near current head ---'
gh api --paginate "repos/${repo}/pulls/${pr}/commits?per_page=100" \
  --jq '.[] | {sha, message: (.commit.message | split("\n")[0])}' \
  | tail -n 12

parent=$(gh api "repos/${repo}/commits/${current}" --jq '.parents[0].sha')
printf '%s\n' '--- immediate-parent E2E delta ---'
gh api "repos/${repo}/compare/${parent}...${current}" \
  --jq '.files[] | select(.filename == "'"${file}"'") | .patch'

printf '%s\n' '--- requested-head post-reload exact-PTY input checks ---'
gh api "repos/${repo}/contents/${file}?ref=${current}" \
  --jq '.content' | tr -d '\n' | base64 -d \
  | sed -n '740,820p'

Length of output: 39264


🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo="stablyai/orca"
previous="a500ddc5737ad9149e5e0e23517e63861687e5ef"
current="82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf"
file="tests/e2e/live-background-terminal-mount-authority.spec.ts"
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

printf '%s\n' '--- changed-file lists for sibling commits ---'
for ref in "$previous" "$current"; do
  echo "### $ref"
  gh api "repos/${repo}/commits/${ref}" --jq '.files[] | [.status, .filename] | `@tsv`'
done

printf '%s\n' '--- complete sibling tree diff summary ---'
gh api "repos/${repo}/compare/${previous}...${current}" \
  --jq '{status, ahead_by, behind_by, total_commits, files: [.files[] | {filename, status, additions, deletions}]}'

for ref in "$previous" "$current"; do
  gh api "repos/${repo}/contents/${file}?ref=${ref}" --jq '.content' \
    | tr -d '\n' | base64 -d > "${tmpdir}/${ref}.ts"
done

printf '%s\n' '--- E2E sibling source diff ---'
diff -u \
  --label "${file}@${previous}" "${tmpdir}/${previous}.ts" \
  --label "${file}@${current}" "${tmpdir}/${current}.ts" \
  || test "$?" -eq 1

Length of output: 11238


@OrcaWin: Confirmed exact head 82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf. It is the current head of PR #11789.

I found no issues in the final-head delta.

The delta from a500ddc5737ad9149e5e0e23517e63861687e5ef is limited to the E2E input helper. It replaces the swallowed normal-click failure with await terminal.click({ force: true }) on the selected visible xterm.

The test still verifies that post-reload input reaches the original exact PTY ID. It also verifies that no other PTY receives the marker. The replay-before-live checks and writeAccepted delivery-credit check remain before the remount keyboard-input assertions.

This was a read-only review. I did not merge or modify the branch.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@OrcaWin
OrcaWin force-pushed the fix-live-agent-resume-hydration-race branch from 82e0eaa to e708853 Compare August 3, 2026 05:12
@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

Please confirm exact final head e708853b0af52c02751fedb0349dea6fff9fffde. Since your clean 82e0eaaf… review, the only delta replaces post-reload hidden-window accessibility-tree assertions (proven stale even after xterm viewport advancement) with authoritative host output plus mounted xterm viewport assertions. Exact PTY input routing and end-of-journey interruption checks remain. Read-only review only; do not merge.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo="stablyai/orca"
pr="11789"
previous="82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf"
current="e708853b0af52c02751fedb0349dea6fff9fffde"
file="tests/e2e/live-background-terminal-mount-authority.spec.ts"

printf '%s\n' '--- requested commit ---'
git cat-file -e "${current}^{commit}"
git show --no-ext-diff --no-renames --format=fuller --stat "$current"

printf '%s\n' '--- pull request head ---'
gh api "repos/${repo}/pulls/${pr}" \
  --jq '{number, state, head_sha: .head.sha, head_ref: .head.ref, base_sha: .base.sha}'

printf '%s\n' '--- ancestry and changed paths since prior reviewed head ---'
git cat-file -e "${previous}^{commit}"
if git merge-base --is-ancestor "$previous" "$current"; then
  printf 'previous_is_ancestor=true\n'
else
  printf 'previous_is_ancestor=false\n'
fi
git diff --no-ext-diff --no-renames --name-status "$previous" "$current"
git log --oneline --ancestry-path "${previous}..${current}" || true

printf '%s\n' '--- focused E2E delta ---'
git diff --no-ext-diff --no-renames -U25 "$previous" "$current" -- "$file"

printf '%s\n' '--- E2E test outline ---'
ast-grep outline "$file" --items all

printf '%s\n' '--- host-output, viewport, input-routing, and interruption contexts ---'
rg -n -C 10 \
  'accessibility|aria|host.*output|terminal\.read|viewport|typeIntoTerminal\(|assertExactPtyReceivedMarker\(|interrupt|SIGINT|signal|reload' \
  "$file"

printf '%s\n' '--- current commit changed-file diff ---'
git diff --no-ext-diff --no-renames -U12 "${current}^" "$current"

Length of output: 104459


🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo="stablyai/orca"
pr="11789"
previous="82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf"
current="e708853b0af52c02751fedb0349dea6fff9fffde"
file="tests/e2e/live-background-terminal-mount-authority.spec.ts"

printf '%s\n' '--- exact commit and current PR head ---'
gh api "repos/${repo}/commits/${current}" \
  --jq '{sha, parents: [.parents[].sha], message: (.commit.message | split("\n")[0])}'
gh api "repos/${repo}/pulls/${pr}" \
  --jq '{number, state, head_sha: .head.sha, head_ref: .head.ref}'

printf '%s\n' '--- paths changed from prior reviewed head ---'
git diff --no-ext-diff --no-renames --name-status "$previous" "$current"

printf '%s\n' '--- final-commit E2E diff only ---'
git diff --no-ext-diff --no-renames -U18 "${current}^" "$current" -- "$file"

printf '%s\n' '--- post-reload section ---'
start=$(rg -n 'await orcaPage\.reload\(\)' "$file" | head -n1 | cut -d: -f1)
end=$(rg -n 'await assertNoInterruption\(client, \[agent!, setup!\]\)' "$file" | tail -n1 | cut -d: -f1)
sed -n "${start},${end}p" "$file"

printf '%s\n' '--- post-reload accessibility references ---'
sed -n "${start},${end}p" "$file" | rg -n 'accessibility|terminalAccessibility' || true

printf '%s\n' '--- retained critical assertions ---'
rg -n -C 3 \
  'function terminalViewportText|function assertExactPtyReceivedMarker|function assertNoInterruption|remountAgent|remountSetup|assertNoInterruption|signalLedgerPath' \
  "$file"

Length of output: 47176


@OrcaWin: Confirmed exact head e708853b0af52c02751fedb0349dea6fff9fffde. It is the current head of PR #11789.

I found no issues in the final-head delta.

The delta since 82e0eaaf90cab2b7488d1983fc7b8427bc17cfbf changes only tests/e2e/live-background-terminal-mount-authority.spec.ts.

The post-reload checks no longer use the xterm accessibility tree. They now require both:

  • Authoritative host output from terminal.read.
  • The matching output in the mounted xterm viewport through terminalViewportText(...).

The test retains exact PTY input-routing checks for the remounted Agent and Setup PTYs through assertExactPtyReceivedMarker(...). It also retains final live-inventory, renderer and persisted binding, launch-ledger, no-interruption, and no-signal assertions.

This was a read-only review. I did not modify or merge the branch.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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

🧹 Nitpick comments (10)
src/main/ipc/pty.test.ts (4)

8628-8641: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Attach a rejection handler when adoptStablePane starts inside the mock.

runtime.beginPtyRegistration creates runtimeSecondAdoption synchronously. The test then polls with vi.waitFor before it awaits the promise at Line 8640. If adoptStablePane rejects during that window, Node reports an unhandled rejection and can fail an unrelated test in the same file. Attach a no-op catch at creation time and keep the original promise for the await.

♻️ Proposed fix to avoid an unhandled rejection window
       runtime.beginPtyRegistration.mockImplementation(() => {
-        runtimeSecondAdoption ??= spawnController.adoptStablePane(adoptionArgs)
+        if (!runtimeSecondAdoption) {
+          const adoption = spawnController.adoptStablePane(adoptionArgs)
+          // Why: the await below happens after a waitFor poll; swallow only the duplicate rejection.
+          adoption.catch(() => {})
+          runtimeSecondAdoption = adoption
+        }
       })

8426-8427: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Consider splitting this case into two tests.

The body covers two independent contracts: adoption of a completed runtime owner during the first mount, and serialization of a runtime adoption that starts inside renderer publication. A failure in the second phase currently reports under a title that describes the first. Extract the shared provider, store, and runtime fixtures into a factory, then assert each contract in its own it.each case.


11662-11673: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add coverage for same-document main-frame navigation.

This case only varies isMainFrame. Both events pass isSameDocument: false. The reset contract also depends on isSameDocument. An in-page hash change or a history.pushState call on the main frame emits did-start-navigation with isSameDocument: true and must not reset delivery. Add an assertion that handleRendererNavigation({ isMainFrame: true, isSameDocument: true }) keeps rendererLifecycleResetCount at 1 and keeps the gate open.

♻️ Proposed additional assertion
       handleRendererNavigation({ isMainFrame: false, isSameDocument: false })
+      // Same-document main-frame navigation must not reset delivery.
+      handleRendererNavigation({ isMainFrame: true, isSameDocument: true })
       expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({

11528-11528: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the stale handleRendererLoading locals.

These sites now invoke a did-start-navigation listener, but the local name still says "loading". Line 11648 uses handleRendererNavigation and Line 13447 uses resetRenderer. Align the remaining sites on one term so a failing assertion names the event it exercises.

tests/e2e/live-background-terminal-mount-authority.spec.ts (6)

86-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Collapse readSpawnLedger into readJsonLines.

readSpawnLedger repeats the exact body of readJsonLines with a fixed path and type. Reuse the generic reader.

♻️ Proposed refactor
-function readSpawnLedger(): SpawnEvent[] {
-  if (!existsSync(spawnLedgerPath)) {
-    return []
-  }
-  return readFileSync(spawnLedgerPath, 'utf8')
-    .split(/\r?\n/)
-    .filter(Boolean)
-    .map((line) => JSON.parse(line) as SpawnEvent)
-}
-
 function readJsonLines<T>(filePath: string): T[] {
   if (!existsSync(filePath)) {
     return []
   }
   return readFileSync(filePath, 'utf8')
     .split(/\r?\n/)
     .filter(Boolean)
     .map((line) => JSON.parse(line) as T)
 }
+
+function readSpawnLedger(): SpawnEvent[] {
+  return readJsonLines<SpawnEvent>(spawnLedgerPath)
+}

216-252: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the inert expected field from the polled snapshot.

The expected object echoes the inputs and is compared against the same literal values. It always matches and adds no assertion power. The sleeping object already asserts paneKey, tabId, worktreeId, and providerSessionId.

♻️ Proposed refactor
-        ({ paneKey, providerSessionId, worktreeId }) => {
+        ({ paneKey }) => {
           const state = window.__store?.getState()
           const live = state?.agentStatusByPaneKey[paneKey]
           const sleeping = state?.sleepingAgentSessionsByPaneKey[paneKey]
           return {
             liveProviderSessionId: live?.providerSession?.id ?? null,
             sleeping: sleeping
               ? {
                   paneKey: sleeping.paneKey,
                   tabId: sleeping.tabId,
                   worktreeId: sleeping.worktreeId,
                   origin: sleeping.origin,
                   providerSessionId: sleeping.providerSession.id,
                   agentCommand: sleeping.launchConfig?.agentCommand ?? null
                 }
-              : null,
-            expected: { paneKey, providerSessionId, worktreeId }
+              : null
           }
         },
         { paneKey, providerSessionId: PROVIDER_SESSION_ID, worktreeId }
       )
     )
     .toEqual({
       liveProviderSessionId: PROVIDER_SESSION_ID,
       sleeping: {
         paneKey,
         tabId: agent.tabId,
         worktreeId,
         origin: 'live',
         providerSessionId: PROVIDER_SESSION_ID,
         agentCommand: 'codex'
-      },
-      expected: { paneKey, providerSessionId: PROVIDER_SESSION_ID, worktreeId }
+      }
     })

407-413: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the repo-id derivation and fail fast when the repo is missing.

Lines 409 and 430 both parse the repo id with worktreeId.split('::')[0] and fall back to null. If the composite id format changes, both sites silently set the active repo to null. The test then fails later at a pane-manager timeout instead of at the real cause.

Extract one helper that resolves the repo and throws a named error when it is absent.

♻️ Proposed refactor
+function activateRepoForWorktree(
+  state: NonNullable<ReturnType<NonNullable<typeof window.__store>['getState']>>,
+  worktreeId: string
+): void {
+  const repoId = worktreeId.split('::')[0]
+  const repo = state.repos.find((candidate) => candidate.id === repoId)
+  if (!repo) {
+    throw new Error(`Repo not found for worktree: ${worktreeId}`)
+  }
+  state.setActiveRepo(repo.id)
+}

Define the helper inside the page context (or inline it in both page.evaluate callbacks, since page.evaluate cannot close over Node-scope functions), then replace both derivations:

       const next = store.getState()
-      next.setActiveRepo(
-        next.repos.find((repo) => repo.id === worktreeId.split('::')[0])?.id ?? null
-      )
+      activateRepoForWorktree(next, worktreeId)
       next.setActiveTabForWorktree(worktreeId, activeTabId)

462-474: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

terminalViewportText reads only the visible viewport, so late assertions can miss scrolled output.

The helper reads pane.terminal.rows lines starting at buffer.viewportY. If the pane scrolls after the marker line leaves the viewport, expect.poll never observes the marker and the test times out. The fake agent and setup processes emit few lines, so the current risk is low. Reading the full buffer removes the dependency on viewport position.

♻️ Proposed refactor
     const buffer = pane.terminal.buffer.active
     return Array.from(
-      { length: pane.terminal.rows },
-      (_, row) => buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? ''
+      { length: buffer.length },
+      (_, row) => buffer.getLine(row)?.translateToString(true) ?? ''
     ).join('\n')

If the intent is to assert that the output is visible on screen, keep the viewport read and rename the helper to state that constraint.


630-651: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Move the settled mountedPtyId check out of the poll.

mountedAgentPtyId is captured on line 628 and never changes inside the poll callback. Polling it adds no retry value and merges a settled fact into a 10-second retry loop, which obscures which sub-assertion failed. Lines 664-666 assert the equivalent setup fact directly.

♻️ Proposed refactor
   const mountedAgentPtyId = await waitForActivePanePtyId(orcaPage)
+  expect(mountedAgentPtyId).toBe(agent!.ptyId)
   await enableTerminalAccessibility(orcaPage, agent!.tabId)
   await expect
     .poll(
       async () => ({
-        mountedPtyId: mountedAgentPtyId,
         liveInventory: (await readWorktreeTerminals(client, worktreeId)).map(liveTerminalIdentity),
@@
     .toEqual({
-      mountedPtyId: agent!.ptyId,
       liveInventory: originals.map(liveTerminalIdentity),

627-825: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Segment the test body with test.step.

The test spans roughly 310 lines and covers adoption, keyboard input, canary isolation, reload, and remount. A failure reports one long test name. test.step labels each phase and names the failing phase in the report and trace.

Suggested phases: adopt agent and Setup PTYs, assert agent input routing, assert Setup input routing, assert canary isolation, reload and assert delivery reset, assert remount identity and live I/O.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a4b26223-8e07-4f62-8ec0-e49f41ba78a9

📥 Commits

Reviewing files that changed from the base of the PR and between 630aaf9322e0392c88923b2af90978b835a092ee and e708853.

📒 Files selected for processing (31)
  • config/reliability-gates.jsonc
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/main/daemon/daemon-protocol-version.test.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-server-attach-only.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/terminal-host-agent-session-claim.ts
  • src/main/daemon/terminal-host-attach-only.test.ts
  • src/main/daemon/terminal-host-create-contract.ts
  • src/main/daemon/types.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/lib/pane-manager/pane-fit-continuation-retry.ts
  • src/renderer/src/lib/pane-manager/pane-fit.test.ts
  • src/shared/local-build-compatibility-contract.json
  • src/shared/local-build-compatibility-contract.ts
  • src/shared/runtime-types.ts
  • tests/e2e/live-background-terminal-mount-authority.spec.ts
💤 Files with no reviewable changes (1)
  • src/main/daemon/terminal-host-agent-session-claim.ts
🚧 Files skipped from review as they are similar to previous changes (26)
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/terminal-host-create-contract.ts
  • src/shared/local-build-compatibility-contract.json
  • src/main/daemon/types.ts
  • src/shared/local-build-compatibility-contract.ts
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/shared/runtime-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/main/providers/pty-provider-contract.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/daemon/terminal-host-attach-only.test.ts
  • src/main/daemon/daemon-server.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/main/daemon/daemon-server-attach-only.test.ts
  • src/main/daemon/daemon-protocol-version.test.ts
  • src/main/runtime/orca-runtime.ts
  • config/reliability-gates.jsonc
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/main/ipc/pty.ts

Comment on lines +22 to +42
let settled = false
let timer: ReturnType<typeof setTimeout> | null = null
const finish = (): void => {
if (cancelled || settled) {
return
}
settled = true
run()
}
const rafId = requestAnimationFrame(() => {
if (!cancelled) {
if (!cancelled && !settled) {
// Why: FitAddon must observe committed CSS, and synchronous rAF test
// shims must not recursively consume the whole retry budget inline.
timer = setTimeout(run, LAYOUT_SETTLE_MS)
if (timer !== null) {
clearTimeout(timer)
}
timer = setTimeout(finish, LAYOUT_SETTLE_MS)
}
})
// Why: Chromium can indefinitely throttle rAF for a hidden Electron window; the fit budget must still release deferred PTY output.
timer = setTimeout(finish, LAYOUT_SETTLE_MS * 2)

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
git ls-files | rg '^src/renderer/src/lib/pane-manager/pane-fit-continuation-retry\.ts$' || true

echo "== file outline =="
ast-grep outline src/renderer/src/lib/pane-manager/pane-fit-continuation-retry.ts || true

echo "== relevant file contents =="
cat -n src/renderer/src/lib/pane-manager/pane-fit-continuation-retry.ts

echo "== search tests/usages =="
rg -n "pane-fit-continuation-retry|fitContinuation|LAYOUT_SETTLE_MS|requestAnimationFrame|cancelAnimationFrame" src/renderer/src lib .github 2>/dev/null || true

Repository: stablyai/orca

Length of output: 50369


🌐 Web query:

MDN cancelAnimationFrame documentation return value requestAnimationFrame cancelled callback

💡 Result:

The window.cancelAnimationFrame method returns undefined [1][2]. It does not return any value because its purpose is to cancel a previously scheduled animation frame request, not to provide status information about the cancellation [1][3]. Regarding your other points: Return value of requestAnimationFrame: The window.requestAnimationFrame method returns a unique long integer (a request ID) [4][5][6]. This ID is used to identify the specific callback in the animation frame list and is passed as an argument to cancelAnimationFrame to perform the cancellation [4][5]. Callback cancellation: The requestAnimationFrame callback function itself does not receive any information or arguments indicating that it has been cancelled [7]. Once a callback is successfully cancelled using its associated ID, it simply never executes [7]. If you call cancelAnimationFrame(id) while the callback is already executing, or after it has already finished executing, the call is a no-op (it has no effect) [7]. Because the callback is removed from the execution queue once cancelled, it is not possible for the callback to run and "know" that it was cancelled [7].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== fixture files in pane-manager =="
git ls-files 'src/renderer/src/lib/pane-manager/*.{ts,tsx,js,jsx}' | sed -n '1,80p'

echo "== pane-fit.spec/test search =="
rg -n "timeout wins|fallback|rAF|RAF|animation frame|cancelAnimationFrame|pane-fit-continuation-retry|armPaneFitContinuationRetry" \
  src/renderer/src/lib/pane-manager src/renderer/src --glob '*.{ts,tsx,test.ts,test.tsx,spec.ts,spec.tsx}' || true

echo "== focused test files =="
for f in $(git ls-files 'src/renderer/src/lib/pane-manager/*test.*' | rg 'fit|repa|scroll|split|lifecycle|terminal'); do
  echo "--- $f"
  wc -l "$f"
done

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== pane-fit.test.ts first relevant section =="
sed -n '1,240p' src/renderer/src/lib/pane-manager/pane-fit.test.ts

echo "== focused usages of retry helpers =="
rg -n -C 3 "armPaneFitContinuationRetry|clearPaneFitContinuationRetry|scheduleRetryTick|LAYOUT_SETTLE_MS" src/renderer/src/lib/pane-manager/pane-fit.ts src/renderer/src/lib/pane-manager/pane-reveal-fit.ts || true

Repository: stablyai/orca

Length of output: 12272


Cancel the animation frame when the timeout path settles first.

When the hidden-window timeout calls finish, the requestAnimationFrame callback remains queued in environments that throttle rAF. The duplicate-execution guard does not remove it. Move cancelAnimationFrame(rafId) into finish; add/keep a regression covering the timeout-wins case.

@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Merge-ready review complete on exact head e708853b0af52c02751fedb0349dea6fff9fffde — not merged.

  • Cause: authoritative replay parsed, then hidden Linux Electron withheld rAF at the reattach safe-fit continuation, leaving immediate live bytes deferred and un-ACKed. The scheduler now races rAF with a timer through the existing bounded retry budget; it does not wait for visibility/activity.
  • Contract: same-generation explicit reattach drains the authoritative snapshot before immediate live bytes and ACKs delivery credit. The duplicate-owner guard and hidden-rAF fallback are both green; literal reverts are red/time out.
  • Oracle: exact Agent, Setup, and canary PTY/process identities survive first mount and reload; authoritative host output and mounted viewport output agree; keyboard input reaches only the original PTY; launch/resume/signal/interruption counts remain zero.
  • Local: focused renderer 551/551; authority matrix 2,392 passed, 1 skipped; typecheck; full lint/reliability/max-lines audits; format/diff checks; rebuilt headless and force-headed Electron journeys all passed.
  • Fresh merge-ref CI: 46 passed, 5 intentionally skipped, 0 failed, 0 pending, including changed Linux E2E, Windows native smoke, static analysis, typecheck, packages, all test shards, and aggregate verify.
  • Final read-only CodeRabbit confirmation found no issues and verified the two-signal post-reload oracle plus retained exact-PTY/no-interruption/no-signal checks: fix: preserve live agent PTYs through graph hydration #11789 (comment)
  • Temporary diagnostics and the disproven stale-document-visibility gate assertion are absent. The reliability gate now records the proven explicit-reattach invariant.
  • Local HEAD, remote branch, and PR head match; worktree is clean. GitHub reports MERGEABLE / CLEAN.

@Jinwoo-H
Jinwoo-H merged commit cd68a8b into main Aug 3, 2026
51 checks passed
@Jinwoo-H
Jinwoo-H deleted the fix-live-agent-resume-hydration-race branch August 3, 2026 18:11
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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.

2 participants