Repository navigation
fix: preserve live agent PTYs through graph hydration - #11789
Conversation
Greptile SummaryThis 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
Confidence Score: 5/5Safe 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.
|
| 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
Reviews (10): Last reviewed commit: "fix: preserve runtime-owned terminal pan..." | Re-trigger Greptile
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
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 winUpdate
runtimeBudgetfor the expanded command set.
scopestill readslocal renderer state testandp95Secondsstays 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 valueCoalesced callers inherit the first caller's remaining budget.
probereturns the in-flight promise, and the 1s caller budget lives insideprobeSshPtyLiveness. A second caller that arrives 900ms later therefore resolves after about 100ms, and a caller that arrives after the first timeout receivesnullimmediately.DaemonPtyAdapter.probePtyLivenessdiffers here: it arms a fresh 1s race per call while still sharing one request.Both behaviors are safe because
nullmeans 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 valueAdd one line that explains the token fence.
The token identity check in
isCurrentis the mechanism that stops a late answer from mutatinglivePtyIdsafterinvalidateordispose. 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 valueAlso 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 atsrc/main/daemon/daemon-pty-router.test.tsLines 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 winDrop the liveness probe when the session exits.
livenessPtyLivenessByIdis only cleared when the same probe completes/fails; the daemonexitcleanup atsrc/main/daemon/daemon-pty-adapter.ts:2342-2364leaves it forevent.sessionId. Addthis.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 winExtract one shared liveness resolver for the three probe call sites.
Provider resolution plus "prefer
probePtyLiveness, elsehasPty, else null" now appears three times: the runtime controller at lines 4682-4691,pty:hasPtyat lines 6273-6285, andpty:probePtyLivenessat 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 winIsolate the module-level registry between tests.
terminal-pane-authority-recovery.tskeepsregistrations,unsubscribeStore, andstoreSubscriptionEpochat module scope. All three testsawait importthe same module instance, so state carries over and the manualstoreHarness.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
beforeEachso 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 winShare the stable-pane resolution step with
recordPaneIsOwnedByPreservedPane.
getPreservedStablePaneRecoveryTabIdrepeats the pane-key parse, tab lookup,hasMatchingStablePaneLayoutcheck andhasRestorableStablePanePtycheck that the stable branch ofrecordPaneIsOwnedByPreservedPanealso 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
📒 Files selected for processing (51)
config/reliability-gates.jsoncsrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-pty-liveness-probe.tssrc/main/daemon/daemon-pty-router.test.tssrc/main/daemon/daemon-pty-router.tssrc/main/daemon/degraded-daemon-pty-provider.test.tssrc/main/daemon/degraded-daemon-pty-provider.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/providers/pty-provider-contract.tssrc/main/providers/ssh-pty-liveness.test.tssrc/main/providers/ssh-pty-liveness.tssrc/main/providers/ssh-pty-notification-routing.tssrc/main/providers/ssh-pty-provider-output-state.tssrc/main/providers/ssh-pty-provider.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/terminal.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.test.tssrc/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.tssrc/renderer/src/hooks/useIpcEvents.test.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/lib/live-agent-resume-hydration-race.test.tssrc/renderer/src/lib/resume-sleeping-agent-session-provider-claim.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.tssrc/renderer/src/lib/sleeping-agent-pane-ownership.tssrc/renderer/src/lib/sleeping-agent-provider-claim-index.test.tssrc/renderer/src/lib/sleeping-agent-recovery-claims.tssrc/renderer/src/lib/sleeping-agent-recovery-dispatch-barrier.tssrc/renderer/src/lib/sleeping-agent-recovery-request-generation.tssrc/renderer/src/lib/sleeping-agent-recovery-topology-state.tssrc/renderer/src/lib/sleeping-agent-recovery-topology.test.tssrc/renderer/src/lib/sleeping-agent-recovery-topology.tssrc/renderer/src/runtime/runtime-client-events.test.tssrc/renderer/src/runtime/runtime-client-events.tssrc/renderer/src/runtime/runtime-terminal-authority-events.test.tssrc/renderer/src/runtime/runtime-terminal-authority-events.tssrc/shared/protocol-version.tssrc/shared/runtime-client-events.tstests/e2e/agent-session-live-force-exit-resume.spec.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/main/ipc/pty.test.ts (1)
2820-2826: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the repeated single-account settings literal into a helper.
The block that builds a
codexManagedAccountsarray with oneaccount-1entry pointing atTEST_CODEX_HOMErepeats verbatim across several new tests. Extract a small factory, for examplebuildSingleManagedAccountSettings(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 nevercall withbuildSingleManagedAccountSettings(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 winAssert 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
📒 Files selected for processing (22)
config/reliability-gates.jsoncsrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/terminal.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/renderer/src/hooks/useIpcEvents.test.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/lib/live-agent-resume-hydration-race.test.tssrc/renderer/src/lib/resume-sleeping-agent-session-provider-claim.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.test.tssrc/renderer/src/runtime/runtime-capability-check-coalescing.test.tssrc/renderer/src/runtime/runtime-capability-check-coalescing.tssrc/renderer/src/runtime/runtime-rpc-client.tssrc/renderer/src/runtime/runtime-terminal-authority-events.test.tssrc/renderer/src/runtime/runtime-terminal-authority-events.tssrc/shared/protocol-version.tssrc/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
There was a problem hiding this comment.
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 winPublish the removed sleeping pane keys from the terminal manual-sleep path.
src/renderer/src/store/slices/terminals.tsstill replaces sleeping records and then publishes only the newly capturedsleepingAgentSessionRecordskeys. This path needs theremovedPaneKeysresult fromremoveSleepingRecordsReplacedByManualWorktreeSleepin 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 winTopology publish calls bypass their own set() no-op guards at four sites. Each site's
set()call has a genuinereturn s(orreturn {}) branch that preserves the state reference on purpose — Zustand's standard signal for "nothing changed" — but the followingpublishTerminalPaneAuthorityTopologyChange(...)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 theset()call produced a real change and gate the publish on it.
src/renderer/src/store/slices/terminals.ts#L1979-L2052: gate theupdateTabTitlepublish so it does not fire whenisDecorativeAgentTitleFrameChangefiltering or thecurrentTab.title === nextTitlebranch 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 theclearTabLaunchAgentpublish so it does not fire when!currentTab?.launchAgent.src/renderer/src/store/slices/terminals.ts#L2996-L3028: gate thesettleDirectSshPaneRetrypublish so it does not fire on the three stale-authority/exhausted-attempt/no-settlementreturn sbranches.src/renderer/src/store/slices/worktrees.ts#L5396-L5476: gate both thesetActiveWorktreepublish and the nestedprepareTerminalTabspublish on their respectivehasStateChange/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 winRelease both listeners in a
finallyblock.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 valueAdd one line explaining the omitted
pendingActivationSpawn.The destructure-and-
voididiom removespendingActivationSpawnfrom 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
📒 Files selected for processing (24)
config/reliability-gates.jsoncsrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.test.tssrc/renderer/src/components/terminal-pane/terminal-pane-authority-recovery.tssrc/renderer/src/lib/live-agent-resume-hydration-race.test.tssrc/renderer/src/lib/sleeping-agent-recovery-topology-state.tssrc/renderer/src/lib/sleeping-agent-recovery-topology.test.tssrc/renderer/src/lib/sleeping-agent-recovery-topology.tssrc/renderer/src/runtime/web-runtime-session.tssrc/renderer/src/runtime/web-session-tabs-sync.test.tssrc/renderer/src/runtime/web-session-tabs-sync.tssrc/renderer/src/store/slices/agent-status.tssrc/renderer/src/store/slices/direct-ssh-terminal-retry.test.tssrc/renderer/src/store/slices/ssh-target-cleanup.tssrc/renderer/src/store/slices/ssh-target-terminal-cleanup.tssrc/renderer/src/store/slices/ssh.test.tssrc/renderer/src/store/slices/ssh.tssrc/renderer/src/store/slices/tabs.tssrc/renderer/src/store/slices/terminal-authority-hydration-publication.test.tssrc/renderer/src/store/slices/terminals.tssrc/renderer/src/store/slices/worktrees.tssrc/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
cff503c to
6aadb37
Compare
|
Final merge-readiness head: Fresh Linux run 30781951546/job 91588479137 proved host 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 |
|
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
config/reliability-gates.jsonc (1)
2198-2211: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNewly registered
commandslack matchingevidenceRunsin two gates. Both gates add commands and widenruntimeBudget.scope, but keep anevidenceRunslist 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-ownershipat Lines 1347-1366,terminal-scroll.streaming-refocus-intentat Lines 3273-3292, andterminal-render.atlas-recovery-fanoutat 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-secondruntimeBudget.scopeat Lines 2210-2211 is backed by measurements.config/reliability-gates.jsonc#L5061-L5071: add runs fortests/e2e/terminal-cold-activation-deferral.spec.ts(Line 5030) andtests/e2e/ssh-cold-activation-restore.spec.ts(Line 5031), plus the focused vitest suite at Line 5027; both specs already have recorded runs underterminal-provider.ssh-remote-reattach-contractat 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.jsoncsrc/main/daemon/daemon-foreground-confirmation-protocol.test.tssrc/main/daemon/daemon-protocol-version.test.tssrc/main/daemon/daemon-protocol-version.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-server-attach-only.test.tssrc/main/daemon/daemon-server.tssrc/main/daemon/terminal-host-agent-session-claim.tssrc/main/daemon/terminal-host-attach-only.test.tssrc/main/daemon/terminal-host-create-contract.tssrc/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
| if (!p.attachOnly) { | ||
| await this.preparePtySpawnUnlessCanceled(p.sessionId, clientId) | ||
| } |
There was a problem hiding this comment.
🎯 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 } : {}),eb8c60a to
630aaf9
Compare
There was a problem hiding this comment.
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.
|
@coderabbitai review Please review exact final head |
|
✅ Action performedReview finished.
|
630aaf9 to
b9ef1bd
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (6)
tests/e2e/live-background-terminal-mount-authority.spec.ts (3)
86-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCollapse
readSpawnLedgerintoreadJsonLines.
readSpawnLedgerduplicatesreadJsonLines. 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 winIsolate the seed commit from developer Git configuration.
git commitinherits the developer global configuration. Ifcommit.gpgsignis 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 valueKeep the click failure reason in the test output.
typeIntoTerminalconverts a click failure intofalse. The caller then reports onlyexpect(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 valueMake the returned release closure idempotent.
claimRuntimePaneCreatereturns a closure that decrementsclaim.counton every call. A caller that releases twice (for example an error path plus afinally) drops the count below the real number of in-flight creates and resolves the barrier early, so a concurrentpty:spawnstops 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 winExtract 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
claimStablePaneCreateandadoptStablePaneare 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?: AdoptedStablePanein thespawnoptions.src/main/ipc/pty.test.ts (1)
8339-8350: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winInclude
connectedon runtime pane mocks and coverconnected: false.
resolveStablePaneOwnertreatsconnected === falseas a discarded runtime candidate. The mocks insrc/main/ipc/pty.test.tsreturn objects without this field, so they only exercise the fail-open branch. Addconnected: trueto the successful mocks, such as at lines 8339, 8522, and 9138, and coverconnected: falseso 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.jsoncsrc/main/daemon/daemon-foreground-confirmation-protocol.test.tssrc/main/daemon/daemon-protocol-version.test.tssrc/main/daemon/daemon-protocol-version.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-server-attach-only.test.tssrc/main/daemon/daemon-server.tssrc/main/daemon/terminal-host-agent-session-claim.tssrc/main/daemon/terminal-host-attach-only.test.tssrc/main/daemon/terminal-host-create-contract.tssrc/main/daemon/types.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/providers/local-pty-provider.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/pty-provider-contract.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/shared/local-build-compatibility-contract.jsonsrc/shared/local-build-compatibility-contract.tssrc/shared/runtime-types.tstests/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
88ac454 to
a500ddc
Compare
|
@coderabbitai review Please review exact head |
|
✅ Action performedReview finished.
|
|
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
doneLength 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}' \
|| trueLength of output: 1568
Pull request Please provide a valid exact SHA, or confirm that I should review the current pull request head. You are interacting with an AI system. |
a500ddc to
82e0eaa
Compare
|
@coderabbitai review Please confirm exact final head |
🧩 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.tsLength 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 1Length of output: 11238
I found no issues in the final-head delta. The delta from 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 This was a read-only review. I did not merge or modify the branch. ✅ Action performedReview finished.
|
82e0eaa to
e708853
Compare
|
@coderabbitai review Please confirm exact final head |
🧩 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
I found no issues in the final-head delta. The delta since The post-reload checks no longer use the xterm accessibility tree. They now require both:
The test retains exact PTY input-routing checks for the remounted Agent and Setup PTYs through This was a read-only review. I did not modify or merge the branch. ✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (10)
src/main/ipc/pty.test.ts (4)
8628-8641: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAttach a rejection handler when
adoptStablePanestarts inside the mock.
runtime.beginPtyRegistrationcreatesruntimeSecondAdoptionsynchronously. The test then polls withvi.waitForbefore it awaits the promise at Line 8640. IfadoptStablePanerejects 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 tradeoffConsider 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.eachcase.
11662-11673: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd coverage for same-document main-frame navigation.
This case only varies
isMainFrame. Both events passisSameDocument: false. The reset contract also depends onisSameDocument. An in-page hash change or ahistory.pushStatecall on the main frame emitsdid-start-navigationwithisSameDocument: trueand must not reset delivery. Add an assertion thathandleRendererNavigation({ isMainFrame: true, isSameDocument: true })keepsrendererLifecycleResetCountat 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 valueRename the stale
handleRendererLoadinglocals.These sites now invoke a
did-start-navigationlistener, but the local name still says "loading". Line 11648 useshandleRendererNavigationand Line 13447 usesresetRenderer. 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 valueCollapse
readSpawnLedgerintoreadJsonLines.
readSpawnLedgerrepeats the exact body ofreadJsonLineswith 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 valueRemove the inert
expectedfield from the polled snapshot.The
expectedobject echoes the inputs and is compared against the same literal values. It always matches and adds no assertion power. Thesleepingobject already assertspaneKey,tabId,worktreeId, andproviderSessionId.♻️ 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 valueExtract 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 tonull. If the composite id format changes, both sites silently set the active repo tonull. 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.evaluatecallbacks, sincepage.evaluatecannot 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
terminalViewportTextreads only the visible viewport, so late assertions can miss scrolled output.The helper reads
pane.terminal.rowslines starting atbuffer.viewportY. If the pane scrolls after the marker line leaves the viewport,expect.pollnever 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 valueMove the settled
mountedPtyIdcheck out of the poll.
mountedAgentPtyIdis 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 winSegment 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.steplabels 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.jsoncsrc/main/daemon/daemon-foreground-confirmation-protocol.test.tssrc/main/daemon/daemon-protocol-version.test.tssrc/main/daemon/daemon-protocol-version.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-server-attach-only.test.tssrc/main/daemon/daemon-server.tssrc/main/daemon/terminal-host-agent-session-claim.tssrc/main/daemon/terminal-host-attach-only.test.tssrc/main/daemon/terminal-host-create-contract.tssrc/main/daemon/types.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/providers/local-pty-provider.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/pty-provider-contract.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/renderer/src/lib/pane-manager/pane-fit-continuation-retry.tssrc/renderer/src/lib/pane-manager/pane-fit.test.tssrc/shared/local-build-compatibility-contract.jsonsrc/shared/local-build-compatibility-contract.tssrc/shared/runtime-types.tstests/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
| 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) |
There was a problem hiding this comment.
🩺 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 || trueRepository: 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:
- 1: https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
- 2: https://github.com/mdn/content/blob/main/files/en-us/web/api/window/cancelanimationframe/index.md
- 3: https://devdoc.net/web/developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame.html
- 4: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame
- 5: https://github.com/mdn/content/blob/main/files/en-us/web/api/window/requestanimationframe/index.md
- 6: https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/requestAnimationFrame
- 7: https://stackoverflow.com/questions/76707017/does-cancelanimationframe-clear-any-existing-requestanimationframe-queues
🏁 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"
doneRepository: 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 || trueRepository: 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.
|
Merge-ready review complete on exact head
|
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:
attachOnlyto adopt the existing PTY without launch or resume work;Unknown or missing renderer state is never proof that a host PTY is dead.
Linux renderer-delivery investigation
Fresh Linux run
30781951546, job91588479137, provedterminal.readreceived the exact PID-bearing marker from the original mounted PTY while neither the xterm full buffer nor viewport contained it.Diagnostic run
30784062230, job91594521168, 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.
onReattachDeterminednow 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
91597327211stopped afterbegin-explicit; run91597953084reachedstructural-start,payload-parsed,fit-start, andfit-wait, but neverfit-completeor deferral finish. Chromium withheldrequestAnimationFramefor 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
88ac4541a719bc8771b36c3182f9e443bb95162bthen delivered the exact remount marker to both authoritativeterminal.readand 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.tsSHA-256:
e8e0f013273256762eb3bf5e9216bc6141d73d64fbf083786cb4fa5b2fa58b9aThe 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:
Ownership causal matrix
922268af10932937d35ee25c6a2af50f5a4aabb61fd0c24bbc75ec2b4b6393fbea603be090d54fda5ad4a6f01420b6661272d42fab4ac6b13a5b692eThe 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
pnpm typecheck: passed;pnpm lint, reliability-gate manifest, max-lines ratchet, and code-quality audits: passed;oxfmt --checkandgit diff --check: passed;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
e708853b0af52c02751fedb0349dea6fff9fffdecompleted 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 reportsMERGEABLEandCLEAN. This review task did not merge the PR.