Repository navigation
fix(terminal): stop orphaning live agent terminals across host restarts and graph syncs - #15644
Conversation
A paired-remote workspace's `web-terminal-*` tabs carry no local PTY handle until the host session-tab snapshot lands over the relay — at least one round trip after the startup/activation resume sweep runs. recordPaneIsOwnedByPreservedPane has no path that can own such a pane at that moment: stablePaneHasLivePty reads an empty ptyIdsByTabId, and paneWillConnectOnActivation is hard-false for mirror tabs. The sweep therefore read a LIVE remote agent as a dead pane and launched a replacement `codex resume <id>`. Codex refused with -32600 "already has an active writer" (the original process still held the session), and because launchSleepingAgentSession deletes the recovery record before the spawn, one failed attempt permanently stranded it: the user got a bare shell and the live agent became a tab-less ghost, visible only via `orca terminal list`. Local tabs only dodged this because reconnectPersistedTerminals optimistically republishes persisted pty ids in the same set() that flips workspaceSessionReady. Fix at the sequencing boundary. A still-published mirror pane whose host has not concluded a hydration pass has unverifiable liveness, and unverifiable never authorizes the duplicating action. The sweep now takes no action at all on such a record — no launch and no clear, since every later branch trusts the ownership verdict — and parks a replay keyed by runtime environment. Every conclusion of the mirror settles the latch and drains the parked sweep: the one-shot listAll (success, host error, invalid payload, transport error/timeout), the first frame of the global and active-worktree streams, and both of their failure paths. The latch is scoped to the runtime connection generation, so a host restart mid-session invalidates the previous verdict instead of leaving a stale "already concluded" behind. Once the mirror answers, the existing logic decides exactly as before: a live host PTY owns the pane; a retracted tab means the host pane is gone and the replacement fires. Local worktrees and non-mirror panes are untouched. Deliberate contract flip: worktree-reactivation-preserved-pane-replacement's "still appends a replacement for a web-mirror tab that cannot mount a local pane" pinned the buggy behavior. Its rationale — the client cannot mount that pane, so it cannot own recovery — is inverted: not being able to mount it is precisely why the client cannot know whether it is dead. That test now pins deferral for a still-published mirror tab, and a new sibling pins that the replacement still fires once the mirror retracts the tab, keeping the one-replacement-per-provider-session contract covered. Residual: an errored hydration conclusion settles the latch, so on a host that never answers the fallback behaves as it did before this change. Deferring there instead would wedge the resume permanently. Related: STA-3500 proposes the same deferral for direct SSH.
…rminals A terminal created through OrcaRuntimeService.createTerminal on a host whose desktop window is attached was unclassifiable by graph sync. shouldPreserveHeadlessMobileSessionTab can call a renderer-omitted terminal runtime-owned only via a headless-built publication epoch, hasLiveRuntimeSessionOwnedPtyBinding, or a serve-/ssh-shaped ptyId — and a CLI terminal had none: persistHostSessionBinding was gated on `getAvailableAuthoritativeWindow() === null`, so with a window attached it got neither a persisted tab nor runtimeSessionOwned, and its daemon-form ptyId (`<worktreeId>@@<shortUuid>`) is deliberately excluded from id-shape classification. publishPtyBackedMobileSessionTerminal also inherits the existing snapshot's publicationEpoch, so on a workspace the renderer had already published the CLI tab inherited the RENDERER epoch and the first disjunct could not save it either. Every renderer graph sync then dropped it — in the accept-merge, or by deleting the whole worktree snapshot in the prune loop — and paired clients clear their strip on the removal frame. Since any orca-cli dispatch drives a sync, the tab re-dropped on each one: the user's ghosted tab that reappeared and vanished again with no restart involved. Root cause is the ownership boundary, not the classifier. createTerminal is host-initiated by construction — CLI, mobile, paired clients and orchestration reach it, while the desktop renderer spawns its own tabs through pty:spawn — so such a pane never has a renderer session writer and must carry its own durable tab/leaf binding. It now always spawns with persistHostSessionBinding and takes runtime session ownership, which the per-call opt-in (now removed, along with its four redundant call sites) only ever granted by accident of window state. Chosen over teaching preservation to consult live daemon inventory: a live daemon PTY with no persisted tab is byte-identical to a renderer-closed tab whose PTY has not exited yet, so no classifier can separate them. The persisted workspace session IS that signal, and it is restart-durable, where the in-memory runtimeSessionOwned flag is zeroed by a host app restart. STA-4593 is preserved by construction rather than by a new carve-out: a user close de-persists the tab, releaseRuntimeSessionOwnershipForRendererRetiredTabs then releases ownership on the next renderer publication, and the tab prunes. An exited PTY still prunes because hasLiveRuntimeSessionOwnedPtyBinding requires connected === true. Both are pinned as controls. Host-local: no RPC params, stream opcodes or published content change, so mixed client/host versions are unaffected. Deliberate contract flip: orca-runtime.test's "keeps ordinary desktop background terminal persistence opt-in" was a scoping guard from #8646 (headless serve → desktop promotion), not an independently argued invariant. The renderer adopts under the pre-minted tabId that reveal passes it, so persisting early cannot fork a second tab — it only makes the host's own create durable. The test now pins that the binding is persisted whether or not a window is attached.
…he store Review found the resume deferral evaporated whenever a stream frame — rather than the one-shot listAll — was the first hydration signal. Both stream handlers settled the latch at the TOP of the handler, before the frame they had just received was applied: the global subscribeAll marked at the ok-check and applied ~80 lines later in the same synchronous body, and the active-worktree subscribe did the same. markHostSessionMirrorHydrated drains parked waiters synchronously, so the replayed sweep re-ran while ptyIdsByTabId was still empty, read the mirrored pane as dead, and launched the duplicate `codex resume` the deferral exists to prevent. The fix only ever held when listAll won the race. The one-shot path was already correct (apply, then mark), which is why the original replay tests passed — they modelled listAll's ordering, not the stream handlers'. Every frame-carrying conclusion now settles in the promise chain that applies it. Conclusions with no frame — a host error response, onError, a subscribe failure, a closed stream — still settle immediately, so nothing can wedge. Same change also fixes the granularity mismatch: evidence arrives per-worktree but the latch was per-environment, so the active-worktree stream's first frame released panes parked on background workspaces whose snapshots had not arrived. The latch now records both, and the caller picks by what the evidence actually covers: a full inventory (listAll, or the global stream's `snapshots` frame) settles the environment because absence from it is itself a verdict, while a single-worktree frame settles only its own worktree. Chosen over settling per-worktree everywhere, which would have wedged any workspace the host stopped publishing — absence would never conclude anything. The new regression drives the real production handlers through useWebSessionTabsSync with the one-shot listAll deliberately left pending, so a stream frame is the first signal. It fails without this change, appending the second resume tab exactly as the incident did.
…inal The safety argument for always persisting the host session binding is that a close drops it again — otherwise a durably closed CLI terminal stays preserved against renderer prunes and STA-4593's closed-tab resurrection returns through the CLI path. Every existing control handed the de-persist to the harness, so they would all have passed even if no close route performed it. This drives the real thing: create through the real createTerminal, close through closeMobileSessionTab, then assert the persisted binding is gone, runtimeSessionOwned is cleared, and the next renderer graph sync does not re-preserve the tab. It passes on the current fix — the assumption held — but it is now a pinned contract instead of an untested premise. No production change: the paired close already routes through closeHeadlessMobileTerminalTab, which clears runtime ownership and calls removePersistedHeadlessTerminalTab, and that de-persist advances the terminal topology revision so the membership rebase steps aside.
|
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:
📝 WalkthroughWalkthroughHost-created terminal creation now always persists host-session bindings and marks PTYs as runtime-session-owned. Runtime tests cover terminal creation, graph synchronization, close durability, and PTY preservation. Renderer code tracks host-session mirror hydration by connection, environment, and worktree. Sleeping-session recovery defers decisions while mirror ownership is unresolved and resumes after hydration. Tests cover replay, reactivation, liveness, reconnection, and snapshot ordering. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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: 2
🧹 Nitpick comments (4)
src/main/runtime/graph-sync-live-daemon-pty-tab-preservation.test.ts (1)
1-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReduce the incident narratives in test comments.
Keep the local invariant in one short comment. Move detailed incident history to an issue, ADR, or linked documentation.
src/main/runtime/graph-sync-live-daemon-pty-tab-preservation.test.ts#L1-L24: replace the multi-paragraph header with one sentence that states the preservation invariant.src/main/runtime/cli-terminal-create-host-session-binding.test.ts#L1-L11: replace the incident narrative with one sentence that states why the binding is required.src/main/runtime/orca-runtime.test.ts#L3302-L3303: keep only the changed persistence-contract statement.src/main/runtime/orca-runtime.test.ts#L14957-L14962: replace the incident history with a short explanation of the attached-window regression.As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”
Source: Coding guidelines
src/renderer/src/lib/worktree-reactivation-runtime-owned-resume-deferral.test.ts (1)
128-130: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReset the hydration module state in the test lifecycle.
The first test parks a waiter in the module-level
parkedWaitersByWorktreemap ofhost-session-mirror-hydration.ts.afterEachrestores the store but leaves that waiter parked. The waiter closure callsresumeSleepingAgentSessionsForWorktreeagainst whatever store state exists when it drains.No test in this file drains it today, so the file passes. A later test in this file that calls
markHostSessionMirrorHydratedwould fire the stale waiter against a reset store.src/renderer/src/lib/host-mirrored-pane-resume-replay.test.tsalready resets this state; matching it keeps the two files consistent.♻️ Proposed lifecycle reset
+import { resetHostSessionMirrorHydrationForTests } from '`@/runtime/host-session-mirror-hydration`' + +beforeEach(() => { + resetHostSessionMirrorHydrationForTests() +}) + afterEach(() => { useAppStore.setState(initialAppStoreState, true) + resetHostSessionMirrorHydrationForTests() })Add
beforeEachto thevitestimport list.src/renderer/src/runtime/host-session-mirror-hydration-frame-ordering.test.tsx (2)
87-91: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace the fixed microtask count with a condition-based wait.
settle()awaits exactly three microtasks. The production path under test chainsrecoverWebSessionTerminalOrphansBeforeApply(an async mock),Promise.all,.then, and.finally. The tick count needed to reach the.finallythat settles the latch depends on that chain's depth.Any added
awaitinweb-session-tabs-sync.tsshortens the observed window and the assertions start passing or failing for the wrong reason. This test exists to pin ordering, so its wait should not depend on a magic tick count.♻️ Proposed wait
-async function settle(): Promise<void> { - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() -} +// Why: the hydration latch settles in a `.finally` several links down the +// recovery chain, so wait on the observable effect, not a tick count. +async function settle(): Promise<void> { + await vi.waitFor(() => { + expect(mocks.recoverSnapshot).toHaveBeenCalled() + }) +}
settle()also runs before any frame is published (Line 270), where no recovery has been called. Split the initial mount wait from the post-publish wait, or gate the condition on the pending call count.
316-321: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the replacement tab, or trim the comment.
The comment states that "the replacement resume tab appears", but the only assertion checks that
sleepingAgentSessionsByPaneKey[backgroundPaneKey]is undefined. A cleared record proves the sweep ran; it does not prove a replacement tab was created. A regression that clears the record without recovering the pane would still pass.💚 Proposed assertion
expect( useAppStore.getState().sleepingAgentSessionsByPaneKey[backgroundPaneKey] ).toBeUndefined() + const backgroundTabs = tabIds(BG_WT) + expect(backgroundTabs).toHaveLength(1) + expect(backgroundTabs[0]).not.toBe(BG_MIRROR_TAB_ID)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0ee3c8e7-9b24-4d98-a4c8-6676f6a16d32
📒 Files selected for processing (12)
src/main/runtime/cli-terminal-create-host-session-binding.test.tssrc/main/runtime/graph-sync-live-daemon-pty-tab-preservation.test.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/renderer/src/lib/host-mirrored-pane-liveness.tssrc/renderer/src/lib/host-mirrored-pane-resume-replay.test.tssrc/renderer/src/lib/resume-sleeping-agent-session.tssrc/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.tssrc/renderer/src/lib/worktree-reactivation-runtime-owned-resume-deferral.test.tssrc/renderer/src/runtime/host-session-mirror-hydration-frame-ordering.test.tsxsrc/renderer/src/runtime/host-session-mirror-hydration.tssrc/renderer/src/runtime/web-session-tabs-sync.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
…y fence Round-3 review raised a resurrection risk built on a claim I made and got wrong: that persisting the host session binding pushes every repo into host-authoritative terminal membership. It does not. advanceTopologyFence (loading-store/store.ts:3284) deliberately declines to arm the fence while the repo's revision is still 0 and no split authority is established, so creating a host-initiated terminal in a fresh repo leaves the revision at 0. That matters because an armed fence makes rebaseWorkspaceSessionTerminalMembership treat every later renderer session write that omits a row as a stale replay and restore it, leaving the durable de-persist to ride the PTY exit — which is asynchronous and can fail outright. Had the create path armed the fence, a closed terminal whose kill never landed would have stayed persisted forever: a permanent, session-level twin of the closed-tab resurrection STA-4593 fixed at the snapshot layer. These pin the seam rather than the diff. A renderer close write durably removes the row it persisted, and it stays removed with the PTY still connected and no exit ever delivered (the kill-failure shape). A census covers the host-create binding shapes — plain, with an incarnation, with a startup cwd, and a second pane in the same tab — so arming the fence from the create path fails here. One test documents the PRE-EXISTING behavior on a repo whose fence was already armed by serve/SSH: there the row does survive a renderer close until an exit-driven retirement, which is independent of host-created terminals and applies to every tab in such a repo. No production change: the tests pass with and without the create-path fix, which is the point — they guard the assumption that fix depends on.
The header still asserted the widening claim my round-3 review got wrong — that persisting a host session binding pushes the repo into host-authoritative membership. It does not, and the tests below exist precisely because of that. Replaced with what a future reader actually needs: these guard the invariant the host-session-binding fix depends on rather than the fix itself, so they pass with that fix reverted by design, and the whole scenario sits one guard away — advanceTopologyFence's `currentRevision <= 0 && !establishesSplitAuthority` early return at persistence/loading-store/store.ts:3284-3293. Arming the fence from the create path fails them immediately. Without the note they read as vacuous and get deleted, which is the coverage worth keeping.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/main/runtime/host-terminal-close-persistence-durability.test.ts (1)
1-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten these block comments.
These comments are 12 and 10 lines long. Keep only the non-obvious invariant. Let the test names and assertions describe the test behavior.
As per coding guidelines, comments must be concise, non-obvious, and brief; prefer one line.
Also applies to: 110-119
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 744d6fb7-a188-486f-9794-b6b00faeea43
📒 Files selected for processing (1)
src/main/runtime/host-terminal-close-persistence-durability.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| it('a renderer close write durably removes the row it persisted', async () => { | ||
| const store = await makeStore() | ||
| store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) | ||
| store.setWorkspaceSession(rendererWriteWithout(store.getWorkspaceSession(), TAB)) | ||
| expect(store.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([]) | ||
| }) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Reopen the Store before asserting durability.
The assertion reads the same Store instance that accepted setWorkspaceSession. It does not verify that the removed tab survives module reset and Store recreation. Use makeStore() again before the assertion.
Proposed test change
store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY })
store.setWorkspaceSession(rendererWriteWithout(store.getWorkspaceSession(), TAB))
- expect(store.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([])
+ const reopenedStore = await makeStore()
+ expect(reopenedStore.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([])📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| it('a renderer close write durably removes the row it persisted', async () => { | |
| const store = await makeStore() | |
| store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) | |
| store.setWorkspaceSession(rendererWriteWithout(store.getWorkspaceSession(), TAB)) | |
| expect(store.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([]) | |
| }) | |
| it('a renderer close write durably removes the row it persisted', async () => { | |
| const store = await makeStore() | |
| store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) | |
| store.setWorkspaceSession(rendererWriteWithout(store.getWorkspaceSession(), TAB)) | |
| const reopenedStore = await makeStore() | |
| expect(reopenedStore.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([]) | |
| }) |
| it('no host-create binding shape arms a fresh repo fence', async () => { | ||
| for (const [index, extra] of [ | ||
| {}, | ||
| { incarnationId: '33333333-3333-4333-8333-333333333333' }, | ||
| { startupCwd: '/tmp/wt-cli' } | ||
| ].entries()) { | ||
| const store = await makeStore() | ||
| store.persistPtyBinding({ | ||
| worktreeId: WT, | ||
| tabId: `${TAB}-${index}`, | ||
| leafId: LEAF, | ||
| ptyId: `${PTY}-${index}`, | ||
| ...extra | ||
| }) | ||
| expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Isolate each binding shape with a fresh repository ID.
Each loop iteration reuses REPO_ID and WT. The second and third cases therefore do not test a fresh repository. Use a distinct repository and worktree ID per case.
Proposed test change
for (const [index, extra] of [
{},
{ incarnationId: '33333333-3333-4333-8333-333333333333' },
{ startupCwd: '/tmp/wt-cli' }
].entries()) {
const store = await makeStore()
+ const repoId = `${REPO_ID}-${index}`
+ const worktreeId = `${repoId}::/tmp/wt-cli`
store.persistPtyBinding({
- worktreeId: WT,
+ worktreeId,
tabId: `${TAB}-${index}`,
leafId: LEAF,
- ptyId: `${PTY}-${index}`,
+ ptyId: `${worktreeId}@@a1b2c3d4-${index}`,
...extra
})
- expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0)
+ expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[repoId] ?? 0).toBe(0)
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| it('no host-create binding shape arms a fresh repo fence', async () => { | |
| for (const [index, extra] of [ | |
| {}, | |
| { incarnationId: '33333333-3333-4333-8333-333333333333' }, | |
| { startupCwd: '/tmp/wt-cli' } | |
| ].entries()) { | |
| const store = await makeStore() | |
| store.persistPtyBinding({ | |
| worktreeId: WT, | |
| tabId: `${TAB}-${index}`, | |
| leafId: LEAF, | |
| ptyId: `${PTY}-${index}`, | |
| ...extra | |
| }) | |
| expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0) | |
| } | |
| it('no host-create binding shape arms a fresh repo fence', async () => { | |
| for (const [index, extra] of [ | |
| {}, | |
| { incarnationId: '33333333-3333-4333-8333-333333333333' }, | |
| { startupCwd: '/tmp/wt-cli' } | |
| ].entries()) { | |
| const store = await makeStore() | |
| const repoId = `${REPO_ID}-${index}` | |
| const worktreeId = `${repoId}::/tmp/wt-cli` | |
| store.persistPtyBinding({ | |
| worktreeId, | |
| tabId: `${TAB}-${index}`, | |
| leafId: LEAF, | |
| ptyId: `${worktreeId}@@a1b2c3d4-${index}`, | |
| ...extra | |
| }) | |
| expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[repoId] ?? 0).toBe(0) | |
| } |
The mirror latch releases into replaying a resume, which can spawn `codex resume` against a PTY the host still holds. A rejected listAll, an RPC error, a transport error or a closed stream is `unverifiable` — never evidence the host-owned PTY exited — so none of them may settle the latch, at either granularity. Parked waiters survive the reset and drain on the next real inventory; an environment that never reconnects has no execution host to relaunch on anyway. This also removes the scoped-stream handlers' environment-wide settle, which drained waiters for worktrees that stream says nothing about.
Orphan recovery can return null for a snapshot, and the frame guards can discard one; those worktrees were filtered out of the applied set but the `.finally` still settled the whole environment. That is "we asked, the host answered, and we threw the answer away" — the store still holds no PTY for the pane, so the drained replay reads an empty handle map and relaunches. A fully applied inventory still settles the environment, because absence from one is itself a verdict and it is what lets a genuinely retracted tab resume. A partial inventory settles only the worktrees it actually wrote, and a single worktree frame settles only if its patch landed.
…onment clearWebSessionTabsTrackingForEnvironment is both the re-pair path and the permanent-removal path, and the call site cannot tell them apart: an unmount or a workspaceSessionReady flap clears every environment too. Dropping waiters on the shared path would cancel owed recovery, so the residue stays — one inert closure per worktree that nothing can ever settle.
…ntime The worktree carried no hostId, so the deferral hit its "no execution host owns this workspace" early return and the test pinned only that nothing was appended — it never parked. With runtime ownership seeded it models the incident: park on activation, then replay the resume once the mirror hands down a verdict. Neutering the park call now fails the replay assertion.
The retraction case promised "the replacement resume tab appears" but only checked that the sleeping record was gone — a replay that cleared the record and launched nothing passed. It now pins the replacement tab and its resume claim; clearing without launching fails.
…drives The header claimed a create-path change such as passing expectedSourceBinding would fail these tests, but every case calls store.persistPtyBinding directly and none goes through createTerminal. It now claims only the store-fence invariant and names the tests that do own the create path.
Per AGENTS.md, comments carry the non-obvious WHY, not a walkthrough. The incident narrative, the module tour and the enumerated classification branches are all readable from the code they sit above.
hostId is an ExecutionHostId, and the listAll stub now takes the request it switches on.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3a150891-b1d3-4d4a-8c1c-ab530c66c1d9
📒 Files selected for processing (6)
src/main/runtime/graph-sync-live-daemon-pty-tab-preservation.test.tssrc/main/runtime/host-terminal-close-persistence-durability.test.tssrc/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.tssrc/renderer/src/runtime/host-session-mirror-hydration-frame-ordering.test.tsxsrc/renderer/src/runtime/host-session-mirror-hydration.tssrc/renderer/src/runtime/web-session-tabs-sync.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/runtime/host-terminal-close-persistence-durability.test.ts
- src/main/runtime/graph-sync-live-daemon-pty-tab-preservation.test.ts
- src/renderer/src/runtime/host-session-mirror-hydration.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
…entory Three of the four production releases were unpinned: no-oping listAll, the global single frame and the scoped frame left the whole suite green. Each new test delivers only its own path's frame and asserts the parked waiter actually replayed a claiming replacement tab.
…riant
Drops incident narrative, code walkthrough and reviewer-facing meta ("NOT
red-first", "do not delete as vacuous") from five headers; keeps only the
reasoning the code does not state itself.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/runtime/host-session-mirror-hydration-frame-ordering.test.tsx (1)
4-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReduce this file-level comment.
Keep one concise sentence that states the ordering invariant. The current comment explains test behavior in detail that the test cases already show.
As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 14007e51-b705-4bc9-bcdc-8559e1d4ed81
📒 Files selected for processing (5)
src/main/runtime/cli-terminal-create-host-session-binding.test.tssrc/main/runtime/graph-sync-live-daemon-pty-tab-preservation.test.tssrc/main/runtime/host-terminal-close-persistence-durability.test.tssrc/main/runtime/orca-runtime.tssrc/renderer/src/runtime/host-session-mirror-hydration-frame-ordering.test.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/runtime/cli-terminal-create-host-session-binding.test.ts
- src/main/runtime/host-terminal-close-persistence-durability.test.ts
- src/main/runtime/graph-sync-live-daemon-pty-tab-preservation.test.ts
- src/main/runtime/orca-runtime.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
…ph sync Paired host + paired Electron client, both real. The renderer publishes the workspace first so the `terminal.create` tab inherits its publication epoch, then a second renderer tab drives the graph sync any later dispatch would. Asserts both halves: the host snapshot still carries the CLI tab, and the client applied that same sync. Presence alone would pass on a stranded mirror — before the fix the client keeps the pre-prune frame forever.
… claim Shared oracle so the topologies stay byte-identical, and two independent signals: the host inventory keeps the tab naming its original daemon PTY, and a write through that handle is answered by the same fixture pid with a single READY line, so a respawn cannot pass as a survivor. Adds the renderer-epoch precondition, the daemon id-shape check that forces the vulnerable path, an unrelated-workspace control, and no-local-fallback and no-uncaught-error checks. Three-way on this oracle: main and branch-with-the-host-fix-removed both prune; only the branch retains. Four back-to-back creates plus a 12s gap still lose tab 1 on the branch, so the spec pins only the immediate-sync case and the gate records the rest as a known gap.
…tion Same oracle file as the desktop arm, so the two topologies cannot stand in for each other. This host cannot exhibit the defect — the gate it turns on is window-conditioned, and with no renderer there is no graph sync — so the spec asserts that (a headless epoch, never a renderer one) and then the claim that matters now the persist is unconditional: a later dispatch keeps every earlier host-created terminal bound to its original PTY and answering. Passes on both the merge-base and the branch, which is the parity result.
The passing test only held because its unrelated-workspace control was created before the target, which is itself a protector. Its name now says so, and the incident shape — a workspace's first host-created terminal, which is what the real CLI produces — is carried as a fixme beside it. fixme rather than fail: a fail test is satisfied by any failure, and this file has twice aborted in fixture setup, so fail would report success while measuring nothing. Header and gate now carry the measured table. Time is not a factor; the earlier timing-framed reading was wrong and is retracted.
A host-initiated create (`orca terminal create`) persists a tab the renderer has never seen. persistPtyBinding refused to advance the repo's terminal topology fence for the first such membership change (currentRevision <= 0), so rebaseWorkspaceSessionTerminalMembership stayed disabled and the renderer's next debounced session write — a tab list taken before the create — replaced the host tab out of persistence. Graph sync then read "absent from the publication AND from persistence" as a durable close, cleared runtimeSessionOwned, and pruned the running agent's tab. A split already establishes authority from revision 0; a host-admitted tab is the same class of event. Scope it to bindings carrying persistHostSessionBinding so renderer spawns racing their own writer keep renderer-owned membership.
…rer replay Drives the real Store: a host-admitted persistPtyBinding followed by the renderer replaying its pre-create tab list. Both directions are pinned — an un-flagged binding must leave renderer-owned membership alone, and the authoritative retirement path must still close the host-admitted tab.
…rding it as a gap The fixme is now green: the incident shape survives the next renderer graph sync, and reverting store.ts/pty.ts alone turns it red on SIGNAL 1. Also corrects the header. Its four-row matrix read a preceding host terminal and a clientMutationId as protectors; instrumentation showed the renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed. This oracle sees one sync, so a retained verdict means "not yet pruned", not "safe".
…s residual gaps The desktop journey now asserts both shapes, so the NARROW carve-out and the "protected shape" framing are gone; the coverage note records why that framing was wrong rather than deleting it silently. The macOS-only platform gap is unchanged. Adds two gaps this work identified but deliberately did not address: the retirement fence advancing the incoming session's revision, and the un-flagged SSH relay reattach binding.
The paired arm proved host-created tab retention through a mirrored client, which left open the reading that pairing was causal. It is not: shouldCreateInBackground is true for any create carrying a worktree selector with no focus request and rendererBacked !== true, so a plain local `orca terminal create` over the runtime socket lands on the same seam. Reverting store.ts/pty.ts turns the new spec red on SIGNAL 1 — the target absent from the host inventory — with no paired client anywhere in the topology. Also assert the second half of the incident. The sleeping-agent record outlives a pruned tab, so recordPaneIsOwnedByPreservedPane reads "no such tab" and the activation sweep forks the session into a ghost. A second record on a pane that genuinely does not exist must be replayed on the same reload, so the CLI pane's silence is evidence rather than a sweep that never ran; the reverted build replays both. createHostRendererTerminalTab and readHostInventoryWhenTabAppears move into the shared oracle so all three topologies are judged by identical code, and createHostCliTerminal now reports the host-minted leafId the pane key needs.
A bootstrap or wake respawn that rejects after the snapshot patch landed made applyActiveSnapshot reject, so the caller read a healthy host as no evidence and left resume waiters parked forever.
The replay dropped onSessionLaunched, so a navigation-suppressed resume tab was created activate:false and never background-mounted; its queued --resume never reached a PTY. skipClaimKeys stays dropped: it is a park-time snapshot.
…okkeeping after it A throw in the post-patch bookkeeping rejected before settleHydration was assigned, so an inventory already in the store settled nothing and left quiet worktrees parked on a healthy host. Same class as 84f68a1.
…ed patch Four review rounds each found a new settle site ordered wrongly against its store patch, so the ordering is now structural: applyWebSessionTabsStorePatch returns a settle receipt created only after the store write commits, and every call site (a required verdict names the worktrees the patch answers for, plus the full-inventory absence upgrade) invokes that receipt after finishRecovery. A frame rejected as stale settles through an explicit stale-frame receipt, backed by the equal/newer view already accepted into the store. This fixes the global singular-frame handler settling on a flag set before its patch (a throw between acceptance and the patch drained parked resume sweeps against state nobody wrote, forking live agents), and closes two settle gaps the receipt requirement surfaced: the visibility-resume tombstone repair and the eager post-create session.tabs.list both landed real evidence without ever releasing the worktrees they answered for.
…settle-site census Red-first against the prior code: a global singular frame whose acceptance bookkeeping throws before its patch relaunched a parked resume against state nobody wrote; the visibility-resume tombstone repair and the eager post-create list both left their parked worktrees wedged after landing real evidence. The stale-frame case pins the opposite edge: a rejection backed by the accepted view must still settle. The census test enforces the seam itself — mirror marks reachable only through the receipt constructors, every store patch call consuming its receipt, and the audited site counts — so a new call site fails until it adopts the contract.
…re false `shouldApplyWebSessionTabsSnapshot` returned false for two unrelated reasons, and every settle site read that boolean as staleness. One of them — the floating workspace, a local synthetic terminal the mirror never writes — has no accepted store view behind it, so settling on it drains parked resume waiters against state nobody wrote and lets the sweep launch a replacement `codex resume` against a session the host still holds. The predicate now returns a decision that carries `settlesHostMirror` beside `apply`, minted at each branch, so a future rejection branch cannot inherit a settle by defaulting. Four sites derive their verdict from it: both hand-built patchless receipts and both inventory `settles` lists, which named the floating worktree the patch had filtered out. Inventory counts exclude unmirrored frames too, so a host with a floating terminal keeps its environment-wide verdict. Splits the frame-ordering suite around the shared harness it outgrew.
…s receipt `applyWebSessionTabsStorePatch` warns instead of rethrowing when `useAppStore.setState` throws with `patchCommitted` already true, so the settle receipt survives. Nothing covered that branch, and it sits on the over-settle side: invert it, or set the flag before `buildPatch`, and a settle would fire for a patch that never landed. Drives the real handler with a store subscriber that throws exactly once after the commit, and asserts the parked resume drains. The `threw` and warn assertions keep the test from passing on a frame that never entered the catch.
The eager post-create session.tabs.list built its settle by hand, naming the worktree unconditionally on the grounds that a stale answer is covered by the accepted view. A frame is also discarded because the mirror never writes that workspace, and nothing accepted backs that one — settling on it drains parked resume work against state nobody wrote, so the sweep can fork a live agent. A patch verdict now names FRAMES carrying the decision their fate came from, and the receipt settles only the ones whose decision says the host answered. The settle is unwritable without a decision, so no site can restate the claim.
…ocation The census pinned that each applyWebSessionTabsStorePatch call CAPTURES its receipt, but nothing said the receipt is ever invoked. A site could capture and drop one and wedge its pane silently — the safe direction, but invisible. TypeScript cannot express a must-call obligation and the invocation is deliberately deferred to after finishRecovery, so this is textual: resolve the binding the receipt landed in and require the next call of that name with no fresh declaration of it in between. The resolved names are pinned too, so a binding this census misreads cannot settle on another identifier's call.
…rtable The inferred type of frameOrderingMocks reached into @vitest/spy internals, which the typecheck project cannot name (TS2883).
…A-4953) Opening a paired-runtime workspace mounted every persisted terminal row before the first authoritative session.tabs snapshot for the current connection. A row with no pty left anywhere can never be watcher-covered (terminal-parked-tab-watchers requires a non-null ptyId), so cold activation mounted it immediately and pty-connection took its FRESH SPAWN branch -- one new remote shell per restored row. Hold that class -- non-mirrored rows with no ptyId and no surviving layout-leaf pty -- until the host answers for the worktree, reading the canonical evidence merged #15644 already owns: host-session-mirror-hydration's generation-scoped latch, settled only from landed web-session-tabs store patches, plus the store's runtime connection generation. No parallel answer bookkeeping. The hold epoch is the host, not just the number: generations count per environment, so it carries environmentId too and a workspace that moves hosts starts a fresh window and inherits no verdict -- still under the same ceiling, still never re-holding a mounted row. Never held: the active tab, group actives (unified-tab id mapped to its terminal entityId), activity portals, pendingStartupByTabId rows, live tabs, and anything an earlier pass already mounted (no retroactive unmount). Local, SSH and folder workspaces resolve no environment and are never held. Unlike the resume/spawn gate, this one releases into *mounting*, where failing open is safe, so it is bounded: a 20s per-connection window (session.tabs RPC timeout + 5s) and a 60s ceiling across reconnects. A blank workspace cannot wedge. The allowed/deferred sets keep their identity while membership is unchanged; a settled hold runs on every render, and a fresh Set each time is a new prop identity for the memoized worktree surface tree. Also closes two untargeted background-mount paths that fanned the same rows into host spawns: the bootstrap mount in useIpcEvents now requests the surface only, and wake-sleeping-agents no longer falls back to a whole-worktree mount for a passive record whose tab id cannot be resolved. Registers the invariant as terminal-session.restored-spawn-hold in config/reliability-gates.jsonc (experimental/partial, macOS-only evidence).
Both sides appended a per-environment cleanup call to the same teardown, so the merge keeps both. stablyai#15644 clears the host session mirror hydration; this branch clears the park authority it records for that environment. Neither reads the other's state. No test covers either call at this site — the clear functions are exercised directly, not through the teardown that reaches them.
…ts and graph syncs (stablyai#15644) (cherry picked from commit da6b9d8)
Textual conflicts (7 files) resolved as semantic merges — both sides kept in every case; no side was dropped. Beyond the textual conflicts, main added four gates and one behaviour that this branch's new code violated. Fixed in this merge: - runtime-electron ratchet (#15968): the branch's `rpc/methods/browser-network-tunnel.ts` reached `ipc/ssh.ts`, dragging 20 Electron modules back into the runtime graph the orcad work had just emptied. The connection-manager accessor moves to `ssh/ssh-target-registry.ts` (the same extraction #15927 did for the other five accessors) and the dispatch reads it there; `wsl-browser-network-relay-launch.ts` reads the app root through the AppEnvironment port. Baseline back to 0 entries. - HTML side-preview focus (STA-5001, #15716): main keeps the source editor focused when the reserved preview split is still empty, by steering the visible tab. This branch's client-owned placement reconciler decides the active group on its own and bypassed that, refocusing the preview. It now takes the same fallback tab. - child_process / windowsHide / wsl.exe census gates: the WSL browser-network relay launcher moves onto `spawnProcess`, and the two Electron test launchers now spawn with `windowsHide`. The four sites that cannot migrate today are allowlisted with their reason (detached process-group kill, a non-all-pipes stdio shape, and a long-lived streaming wsl.exe child that `runWslProcess` cannot express). - max-lines: both sides grew `package-electron-runtime-contract.test.mjs`; the union crossed 600. This branch's two additions move to `config/scripts/client-hosted-browser-package-coverage.test.mjs`. Also ports four browser-create test files onto main's `applyWebSessionTabsSnapshot`/`decideWebSessionTabsSnapshot` split (#15644). Gates: typecheck 0 errors, `pnpm lint` exit 0, 6316/6369 test files green. The 12 remaining failures are pre-existing on one or both parents (5 packaging tests need a real `pnpm install`, global-fetch audit and 4 others fail on both parents) or flaky.
…A-4953) Opening a paired-runtime workspace mounted every persisted terminal row before the first authoritative session.tabs snapshot for the current connection. A row with no pty left anywhere can never be watcher-covered (terminal-parked-tab-watchers requires a non-null ptyId), so cold activation mounted it immediately and pty-connection took its FRESH SPAWN branch -- one new remote shell per restored row. Hold that class -- non-mirrored rows with no ptyId and no surviving layout-leaf pty -- until the host answers for the worktree, reading the canonical evidence merged #15644 already owns: host-session-mirror-hydration's generation-scoped latch, settled only from landed web-session-tabs store patches, plus the store's runtime connection generation. No parallel answer bookkeeping. The hold epoch is the host, not just the number: generations count per environment, so it carries environmentId too and a workspace that moves hosts starts a fresh window and inherits no verdict -- still under the same ceiling, still never re-holding a mounted row. Never held: the active tab, group actives (unified-tab id mapped to its terminal entityId), activity portals, pendingStartupByTabId rows, live tabs, and anything an earlier pass already mounted (no retroactive unmount). Local, SSH and folder workspaces resolve no environment and are never held. Unlike the resume/spawn gate, this one releases into *mounting*, where failing open is safe, so it is bounded: a 20s per-connection window (session.tabs RPC timeout + 5s) and a 60s ceiling across reconnects. A blank workspace cannot wedge. The allowed/deferred sets keep their identity while membership is unchanged; a settled hold runs on every render, and a fresh Set each time is a new prop identity for the memoized worktree surface tree. Also closes two untargeted background-mount paths that fanned the same rows into host spawns: the bootstrap mount in useIpcEvents now requests the surface only, and wake-sleeping-agents no longer falls back to a whole-worktree mount for a passive record whose tab id cannot be resolved. Registers the invariant as terminal-session.restored-spawn-hold in config/reliability-gates.jsonc (experimental/partial, macOS-only evidence).
…ts and graph syncs (stablyai#15644)
…ts and graph syncs (stablyai#15644)
ELI5
Your agents live in terminals that survive an app restart, because the PTY daemon keeps them running. Two separate bugs meant Orca lost track of those still-running agents.
Bug 1 — the client relaunched an agent that was still alive. When you're paired to a remote host, a mirrored tab has no local PTY handle until the host's snapshot arrives over the relay — one network round trip after the restore/activation sweep runs. The sweep read "no handle" as "the pane is dead", so it opened a new tab running
codex resume <id>. But the original process was still holding that session, so Codex refused with-32600 already has an active writerand you got a bare shell. Worse, the recovery record is deleted before the spawn, so one failed attempt stranded the session permanently — and the real agent kept running with no tab, visible only viaorca terminal list.Bug 2 — the host threw away the tab of a terminal that was still running. A terminal created through the runtime (orca CLI, mobile, paired clients, orchestration) got no persisted binding and no ownership flag when the host's window was attached, and its daemon-style pty id is deliberately not usable for classification. So when the renderer published its tab graph, the host couldn't tell that terminal was host-owned and pruned it — either dropping the tab or deleting the whole workspace snapshot. Since any orca CLI dispatch triggers a graph sync, the tab kept vanishing again, with no restart involved.
Fixes: the client now waits for the host to actually answer before deciding a remote pane is dead (unknown ≠ dead, and it takes no action meanwhile, so the recovery record survives); and host-initiated terminals now always persist their own binding, so they stay classifiable across restarts and syncs.
Reproduction
Both defects were proven red on
mainbefore any fix, and re-verified red in a clean throwaway worktree at6e25a90085after the tests were rewritten:graph-sync-live-daemon-pty-tab-preservation.test.ts+cli-terminal-create-host-session-binding.test.ts— 5 failed / 2 passed on main.worktree-reactivation-runtime-owned-resume-deferral.test.ts— 1 failed / 2 passed on main.A repro detail worth keeping:
publishPtyBackedMobileSessionTerminalinherits the existing snapshot's publication epoch. A harness that leaves a headless epoch in place does not reproduce Bug 2, because a headless epoch is preserved unconditionally. It only reproduces once the renderer has already published that worktree, so the CLI tab inherits the renderer epoch.Two deliberate contract flips
Both previously pinned the buggy behavior; neither was quietly weakened.
worktree-reactivation-preserved-pane-replacement.test.tsasserted a web-mirror tab always gets a replacement, reasoning that the client can't mount that pane so it can't own recovery. That reasoning is inverted: not being able to mount it is exactly why the client cannot know whether it's dead. It now pins deferral, and a new sibling test pins that the replacement still fires once the mirror retracts the tab — so one-replacement-per-provider-session stays covered.orca-runtime.test.ts"keeps ordinary desktop background terminal persistence opt-in" asserted a window-attached create does not persist. Traced to Fix recipe serve desktop promotion #8646, where it was a scoping guard for headless→desktop promotion, not an independently argued invariant.Why persist rather than teach the classifier
A live daemon PTY with no persisted tab is byte-identical to a renderer-closed tab whose PTY hasn't exited yet — no classifier can separate them. The persisted workspace session is the separating signal, and unlike the in-memory
runtimeSessionOwnedflag it survives a host restart. STA-4593 ("closed stays closed") therefore holds by construction rather than by a new carve-out, and is pinned by controls: a user close de-persists the tab and it prunes; an exited PTY still prunes.The two commits are coupled — do not merge only one
Confirmed against a user report that this fires frequently with no restart of either host or client, specifically when a remote agent starts using the orca CLI inside the remote workspace. That is Bug 2's trigger exactly:
createTerminalpublishes, the renderer graph syncs, and the prune runs.The two defects are not independent in that flow:
removed: trueframe.worktree-reactivation-preserved-pane-replacement.test.ts("appends the replacement once the mirror has retracted the web-mirror tab").codex resumeagainst the still-live session →-32600→ bare shell.In other words Bug 2 manufactures a false retraction, and Bug 1's fix trusts retraction as truthful. Shipping only the client-side deferral would leave the common, no-restart path fully broken, because that path never depends on the hydration window the deferral protects. Shipping only the host-side fix stops the false retractions but leaves the restart window open.
Both directions are now pinned: the host must not emit a removal frame for a live CLI terminal (
graph-sync-live-daemon-pty-tab-preservation.test.ts, realremoved:trueassertion), and the client must still relaunch on a genuine retraction.Mixed-version note
Host-local only. No RPC params, no stream opcodes, no change to what either side publishes — so an old client against a new host, or a new client against an old host, behaves exactly as before. Bug 1's fix is entirely client-side; Bug 2's is entirely host-side; neither depends on the other being deployed.
Blocking race found in review — fixed (commit 3)
Independent adversarial verification found that the deferral settled before the host's frame reached the store. Both stream handlers called
markHostSessionMirrorHydratedbefore applying the frame they had just received (global marked at :4333, applied ~:4416), and the waiter drain is synchronous — so the replayed sweep ran against a still-emptyptyIdsByTabId, concluded the pane was dead, and fired the duplicatecodex resumeanyway. The one-shotlistAllpath was correct, so the fix only held whenlistAllwon the race.The original replay tests could not catch it: they applied state before marking, modelling
listAll's ordering rather than the streams'.Fix: every frame-carrying conclusion now settles inside the promise chain that applies that frame. Conclusions with no frame (
response.ok === false,onError,onSubscribeError, closed stream) still settle immediately so nothing wedges. The positional constraint is documented in the latch module itself.Proof: a new order-faithful test drives the real handlers (
renderHook(useWebSessionTabsSync)→ mocked subscribe → productiononResponse) withlistAllheld unresolved, forcing a stream frame to be the first hydration signal. Reverting only the ordering change makes both cases fail with the incident's exact symptom — a second appendedcodex resumetab. Verified independently by the reviewer, not just self-reported.Related granularity fix: the latch is now two-granularity. Only a full inventory (
listAll, or the global stream'ssnapshotsframe) settles the whole environment, because absence from a full inventory is itself a verdict; a single-worktree frame settles only its own worktree. Settling per-worktree everywhere would have wedged — a worktree the host stopped publishing would never receive a frame, trading over-release for a silent never-resume.Honest residuals
An errored hydration settles the latch. If a host errors or times out instead of answering, the fallback behaves exactly as it does today — no better, no worse. Deferring on error instead would wedge auto-resume permanently. This is the one place strict "unverifiable never authorizes action" was traded against anti-wedge.
A mirror tab whose worktree resolves to no runtime environment defers forever. Nothing would ever drain it. The record survives so nothing is destroyed and manual resume works, but auto-resume never fires. I believe this shape doesn't occur in production, but it was not proven.
Ownership release depends on the renderer writing
[], not deleting the worktree key. Verified:closeTabwrites[](terminals.ts:1634); the only key-deleting path is full worktree teardown, where the PTYs die anyway. Flagged because this fix makes far more terminals runtime-owned, widening the blast radius if that ever changes.Persisting earlier advances
terminalTopologyRevisionByRepoIdbefore the renderer does. Documented intent ("host-admitted membership must outrank a stale renderer replay"), all persistence tests pass, but it is a real ordering change.Nothing detects
-32600and retries a reattach. Deliberately out of scope; still zero production hits for that string. Worth its own ticket.codex execone-shot sessions still resume interactively on restore. Confirmed there is noexec-awareness anywhere in the resume path — a real, separate defect, not addressed here.Incident attribution — observed, with one caveat. The reporting user's main agent terminal was itself created through the orca CLI (a local agent used the CLI to create the remote workspace and spawn the agent), which is exactly the unclassifiable host-created class Bug 2 targets; that agent then drove further CLI dispatches, each re-running the prune. They also report a "session restored" banner on affected tabs.
showSessionRestoredBanner: trueis set at exactly one queued-startup site (sleeping-agent-session-launch.ts:115), but review established the same banner is also shown independently by local cold-restore paths (pty-connection.ts:5430/:5432/:8585/:8587). A banner on a new bare-shell tab in a paired-remote workspace remains most consistent with the relaunch path, but it is strong evidence rather than proof. Host logs were never read.Not every
src/maindirectory was swept. The full sweep wedges on an unrelated stuck real-zsh spawn. Two failures seen during wedged runs were checked:shell-startup-feature-channelfails on a clean tree too (pre-existing, reads the machine's real ZDOTDIR), andrepro-13767is a known load flake that passes in isolation both with and without these changes.Verification
orca-runtime.test.ts: 1238 passed, 1 skipped.src/renderer/src/lib+src/renderer/src/runtime: 5069 passed, 1 skipped.check:code-quality:changed: 0 new findings.check:react-doctor:changed: 0 issues, exit 0. (Run separately — they are different gates.)A review pass caught one defect in the implementation before this PR: a raw
NULbyte in a template literal made a new.tsfile binary to git, so it rendered as "Binary files differ" instead of a reviewable diff. Fixed by using the\0escape and amended into the commit; a scan of every changed file in both commits now reports zero control bytes.Related
STA-4903 (ghost registry entries — different defect, separately owned), STA-3500 (proposes this same deferral for direct SSH), STA-3374, STA-4110, STA-2839.
🤖 Generated with Claude Code
Corrections made during review
runtime.createTerminal. That is wrong:src/main/ipc/worktree-remote.ts:320(worktree-create startup terminal) and:370(Setup terminal) are renderer-invoked and now become persisted + runtime-owned. Consequences were audited — no permanent resurrection, since the de-persist → ownership-release → prune chain runs before the preserving merge (orca-runtime.ts:33103) — but there is a transient window where a just-closed tab can flicker back in paired mirrors until the next sync. That window previously existed only for windowless hosts; this change extends it to windowed hosts.ipc/pty.ts:~4697now throws if acreateTerminalspawn ever lacks a valid worktreeId/tabId/leafId, where pre-fix it silently succeeded un-persisted. Being verified across orchestration, federation, and floating-terminal paths.Additional residuals from round 2
ipc/pty.tspersist guard was audited across orchestration, federation, floating-terminal and recovery paths: nocreateTerminalpath can reach it with a missing or invalid worktreeId/tabId/leafId, so unconditional persistence cannot introduce a throw.Rounds 4-5: the close/persistence seam, and a retracted finding
The author of the merged STA-4593 fix cross-reviewed this PR and raised a blocking concern: that always persisting host-created terminals would widen host-authoritative membership, so that a host-renderer UI close (a renderer write that omits the tab, with no revision bump) would have its tab restored — a session-level resurrection, the persistence-layer twin of the bug their PR fixed at the snapshot layer. They noted the PTY kill is asynchronous and can fail outright on Windows/WSL, making that window unbounded.
The premise turned out to be ours, and wrong.
advanceTopologyFence(persistence/loading-store/store.ts:3284-3293) declines to arm while a repo's revision is still 0 and no split authority is established, so persisting a host session binding on a fresh repo leavesterminalTopologyRevisionByRepoIdat 0. There is no widening. An earlier probe suggested otherwise only because it hand-set the prior revision to 1, which the create path never does. Re-verified against the realStore.Their downstream reasoning was correct and changed how this was tested: the dangerous case is a window inside the close, not a separate route, and safety rests on de-persist + release + the fence never being armed.
Census of every path that removes a terminal row — each either advances the fence or operates at revision 0 where the renderer write already wins: host-create persist (does not arm), host-renderer UI close (durably removes, verified during kill-lag and with the kill failing and no exit ever delivered), paired-client close, PTY-exit retirement, dead-PTY reattach retirement, sleeping-agent
exited, legacy tombstones (nothing writes new ones), split-leaf close (arms deliberately — the designed case). Not separately traced: worktree teardown, close-others/right/all, sleep, cross-group moves — all funnel through the same renderer session write, covered generically at revision 0.host-terminal-close-persistence-durability.test.ts(7 tests) passes with this PR's fix reverted, by design. These guard an invariant the fix depends on rather than pinning the diff. Safety here is one guard away: if anyone arms the fence from the create path, they fail immediately and the resurrection scenario becomes real.The STA-4593 resurrection suite stays green throughout, including the kill-failure case.
Not combined with #15624 (STA-4953)
That PR addresses a sibling defect of the same family (stale panes mounting before the authoritative snapshot, each mount spawning a remote shell). Its bug is real and independently reproduced. It is not absorbed here: combining the two would be worse than either alone — its mount gate withholds exactly the local PTY-less tab this PR's resume path creates, after that record has already been cleared, so agent resumes would silently vanish. Detailed findings were shared with its author separately.