Repository navigation
fix(terminal): a close the host never heard must survive the reconnect - #16752
Merged
Merged
Conversation
This was referenced Aug 27, 2026
Merged
nwparker
force-pushed
the
nwparker/ssh-06-close-tombstone
branch
from
August 27, 2026 09:28
49bb96e to
917f192
Compare
nwparker
force-pushed
the
nwparker/ssh-05-reattach-fence
branch
from
August 27, 2026 09:49
546005d to
20db4da
Compare
nwparker
force-pushed
the
nwparker/ssh-06-close-tombstone
branch
from
August 27, 2026 09:49
917f192 to
03d73fb
Compare
nwparker
force-pushed
the
nwparker/ssh-05-reattach-fence
branch
from
August 27, 2026 09:53
20db4da to
e9afc48
Compare
nwparker
force-pushed
the
nwparker/ssh-06-close-tombstone
branch
2 times, most recently
from
August 27, 2026 10:02
5ac2552 to
dde7ca5
Compare
nwparker
force-pushed
the
nwparker/ssh-05-reattach-fence
branch
from
August 27, 2026 10:07
e9afc48 to
562a6ce
Compare
nwparker
force-pushed
the
nwparker/ssh-06-close-tombstone
branch
from
August 27, 2026 10:07
dde7ca5 to
bf0b963
Compare
nwparker
force-pushed
the
nwparker/ssh-05-reattach-fence
branch
from
August 27, 2026 10:10
562a6ce to
c65bd84
Compare
nwparker
force-pushed
the
nwparker/ssh-06-close-tombstone
branch
from
August 27, 2026 10:10
bf0b963 to
92de673
Compare
nwparker
force-pushed
the
nwparker/ssh-05-reattach-fence
branch
from
August 28, 2026 02:45
c65bd84 to
1a69ed3
Compare
An enterprise user: "Every day I open orca and it opens more tabs daily at a linear scale." Three reports over a week, told on 08-19 that a PR had fixed it, reported twice more after. STA-4658 (P0), GH #12447, #15136, #10342, #9585. One install held 39 zombie tab records. The revived tab's sleeping-agent record still holds the pre-close session id, so it boots `claude --resume <old id>` -- two agents on one transcript. ## The chain, measured Reproduced deterministically in `ssh-lost-kill-tab-resurrection.spec.ts`: close an SSH tab, kill the relay daemon in the container so `pty.kill` rejects with a transport-class error, reconnect. drop 2 resurrected the closed tab <id>: baseline=1 drop1=1 drop2=2 (closed tab returned) drop3=1 The trigger is narrow and had to be measured rather than assumed: killed relay daemon reproduces **6 of 6 runs**; an orderly `ssh.disconnect` **passes**. Only an ungraceful loss -- network partition, host reboot, relay crash, a laptop sleeping mid-session -- strands the close with the RPC rejecting on a transport-class error. Both variants live in the spec behind one `runResurrectionCycles` parameterized solely by the disruption, so the difference is attributable to that single variable. What actually carries the tab back, from the pull path (`workspace.get` -> `getRemoteSnapshot`, `remote-workspace-relay-sync.ts:29`): pullSnapshot rev=3 tabs={repo:["16c4a3e1","06aba6b6"]} pullSnapshot rev=4 tabs={repo:["16c4a3e1","ff72768e"]} <- ff72768e IS the resurrected tab pullSnapshot rev=5 tabs={repo:["16c4a3e1","ff72768e","da21b76c"]} The client uploaded the session containing the tab; the user closed it; the kill RPC rejected so the close never reached the host; the host's snapshot still lists it; the client pulls it back and the merge restores it -- **correctly, by its own rule that the host is authoritative for what it knows.** A pane then mounts, respawns, and takes the recycled pty id. Client-side correlation from the same run, two controls and one positive in one run differing in exactly one variable: | Tab | Close events observed | Resurrected? | |---|---|---| | `6305cc07` | `user` + `pty-exit` | No | | `ed56f66c` | `user` + `pty-exit` | No | | `2036e760` | `user` only | **YES** | ## The fix `src/shared/closed-terminal-tab-tombstones.ts` (99 lines). A client-recorded close is first-party intent and must survive until the host acknowledges it. Per `docs/reference/ssh-execution-boundary.md` the remote verdict is `unverifiable` -- which may not authorise declaring the process dead, but equally must not authorise resurrecting the tab. This is SSH-v3 principle P2, "durable tombstones with a monotonic per-scope revision", reusing the existing `RemoteWorkspaceSnapshot.revision` rather than adding a twelfth per-tab identity field (the codebase carries eleven, 784 refs, that SSH-v3 Phase 3 deletes). - **Recorded** only on `closeReason === 'user'` (`terminal-tab-close.ts:69`). - **Suppresses** a host-sourced tab only when `tabId in tombstones && !currentTabsById.has(tabId)` -- a live local tab always wins, because deleting a live pane is the one outcome the merge exists to avoid. - **Retires** on positive acknowledgement: `!hostKnownTabIds.has(tabId) && hostRevision > observed`. Strictly newer, so a pull already in flight at close time cannot ack a close it predates. - Three never-retire guards: no revision retires nothing; a worktree the snapshot has no row for retires nothing; the first omitting snapshot only stamps the watermark. - TTL (30d) + cap (500) are **backstops** for a target the user never returns to, not the mechanism. - **Client-local only** -- never crosses the wire, so there is no mixed-version exposure. - Suppression is scoped to `replaceWorktreeIds`, which is what makes the live-tab check meaningful. A final whole-map sweep over the assembled `tabsByWorktree` would break that (a live tab is absent from `currentTabsById` outside the scope and would look suppressible); it is deliberately not there, and the comment at the top of the function says so. ## Evidence The load-bearing evidence is an A/B control on one tree, not the oracle's assertion. Flipping `isSuppressedByClose` to `false` -- one character -- reproduces the resurrection on demand: --repeat-each=2: 1) drop 2 resurrected the closed tab ab0e305d-…: baseline=1 drop1=1 drop2=2 2) drop 2 resurrected the closed tab 51533e34-…: baseline=1 drop1=1 drop2=2 2 failed With suppression on: **0 occurrences of "resurrected the closed tab" across five runs plus one independent run by a second agent.** Provenance verified positively, not by mtime: `closedTerminalTabTombstonesByTabId` appears 13x across 3 renderer chunks including `store-Do3KBvRE.js`; for every red control run `mayCreate` appeared 0 times in `out/main/index.js`. At the unit layer, disabling the same predicate: 3 failed | 39 passed. Restored: 42 passed; 287 across the workspace-session, terminal-store, remote-workspace, shared-tombstone and profile suites; 24 in the four tombstone suites. ## The oracle spec: GREEN in the full lane `ssh-lost-kill-tab-resurrection.spec.ts` passes both tests at this commit. Full Docker-SSH lane, clean tree: BUILD_SHA=49bb96e0b4c DIRTY=0 PROVENANCE tombstone=13 hasLocalTabsRow=2 hostAuthority=4 mayCreate=3 14 specs / 20 tests -> 17 passed, 2 failed, 1 skipped (10.7m) [12/20] :178 does not resurrect tabs whose kill was lost to a killed relay daemon PASSED [13/20] :190 does not resurrect tabs closed while the host is disconnected PASSED grep -c "resurrected the closed tab" (whole lane) -> 0 It passes WITHOUT PR 7 in the build (`mayCreate` present, `SshPtyAbsentFromRelayError` absent), so the bug-2 fix below is not required for it. Test 1 fails intermittently in ISOLATED single-spec runs, where a third defect blocks its cycle-2 setup. The resurrection assertion itself has never failed with this fix in place -- the intermittent failure is always a setup failure, never a resurrected tab. A reviewer running the spec alone may see it red; that is not this fix regressing. Three defects sit under STA-3374 and should not be conflated: - Bug 1 -- the closed tab resurrects. Fixed here. - Bug 2 -- `ssh-pty-session-reattach.ts:227-231` rewrites the relay's `PTY "pty-1" not found` into a bare `SSH_SESSION_EXPIRED`, so `isPtyAlreadyGoneError`'s `/PTY ".+" not found/` cannot match and `attachStablePaneOwner:242`'s already-correct fallback never runs. Owned by PR 7 (`nwparker/ssh-07-absent-from-relay`). Not required for the oracle above. - Bug 3 -- after the daemon is killed and the client launches a replacement, the client's OWN SSH transport drops and does not reconnect within 60s: no "delay step 2/9", no handshake failure, nothing. `ssh-connection.ts:1533` only logs on an SSH-level close. Unfixed, its own ticket. This is what makes test 1 intermittent in isolation. Discriminator for bug 3, measured in the isolated runs (the lane above ran without `ORCA_E2E_FORWARD_APP_LOGS=1`, so it was not re-confirmed there): `[ssh-relay] Socket probe result:` reads "DEAD" on every cycle of test 1 (daemon killed, a NEW relay must be launched) and "ALIVE" on every cycle of test 2 (daemon survived). Whenever a new daemon must be launched, the SSH transport drops afterwards and does not recover. An earlier reading blamed `kill.ts:82-84` for skipping `finishPtyShutdown` on a non-already-gone error. That was eliminated by direct test: the implied fix, `markSshRemotePtyLease(…, 'expired')` in that branch, was implemented, changed nothing, and was reverted rather than shipped unproven. Recorded so the path is not re-walked. The `SSH_SESSION_EXPIRED` rejection is real but fires during cycle 1 for the baseline pane, after which cycle 1 completes; the 60s silence begins only after `Relay channel lost ..., triggering reconnect`. The spec is claimed by the Docker-SSH lane, and that lane does not gate merges today. ## Persistence: the tombstone must survive a relaunch `closedTerminalTabTombstonesByTabId` is declared on `WorkspaceSessionState` but was missing from `workspaceSessionStateSchema` (`src/shared/workspace-session-schema.ts`), which is the load boundary for BOTH partitions -- `normalize-loaded-state-collections.ts` for `local` and `workspace-session-partitions.ts` for `ssh:<target>`. Zod strips unknown keys and the write side does not validate, so the map reached disk and was discarded on the next launch. Measured with the repo's own parser: input : closedTerminalTabTombstonesByTabId: { 'tab-1': {...} } ok = true tombstones after parse = undefined That made the fix ineffective in the exact reported scenario: close an SSH tab with the transport down, QUIT, relaunch, reconnect -- the merge runs with an empty map, the host still lists the tab, and it resurrects. "Every day I open orca and it opens more tabs" is a claim about restarts. Neither the green oracle nor the A/B control could see it: both run entirely inside one app process. It also made the 30-day TTL and the 500 cap unreachable. Fixed by adding the field with a `salvagingRecord` matching its sibling `terminalSurfaceTombstonesByPaneKey`, so one malformed entry drops that entry rather than the map. `workspace-session-schema.ts` was one line under its 300-line max-lines limit, so adding the field required room rather than a suppression (the project forbids max-lines disables and per-file bumps). Two value schemas were extracted to modules named after what they contain: `terminal-tab-id-schema.ts` and `terminal-surface-tombstone-schema.ts`. The closed-tab tombstone's own schema is colocated with its type in `closed-terminal-tab-tombstones.ts`, which is where it belongs -- omitting it from the session schema is exactly the drift that caused this bug. `workspace-session-schema-field-coverage.test.ts` is the ratchet. Two sibling tables already pin themselves with `satisfies Record<keyof WorkspaceSessionState, ...>`; this schema had no such guard and is the one that fell behind. The new file adds both halves -- a `satisfies` list that makes a forgotten field a compile error, and a runtime assertion that names it -- plus a `parseWorkspaceSession` round-trip. Without the schema entry: 3 failed. With it: 3 passed. ## A host tab the user never closed could be deleted `tabId in closedTerminalTabTombstonesByTabId` answers true for every `Object.prototype` key even on an EMPTY map, because the map is a plain object from `Object.fromEntries`. A host tab whose id is `toString` was filtered from the reconciled list, blocked from the host-unknown branch, and stripped of its layout and session id. Tab ids are validated only as non-empty and colon-free, and `createTab` honours caller-supplied id hints, so the id is reachable rather than theoretical. This was the only path in either direction that could delete a tab the user never closed. Now `Object.hasOwn`, as the same file already uses elsewhere. Suppression is also scoped structurally: `isSuppressedByClose` compares the tombstone's stored `worktreeId`, which it already carried, so it cannot reach another workspace's tab. The two sweeps that have no worktree in scope (`terminalLayoutsByTabId`, `remoteSessionIdsByTabId`) now consult the set of ids this merge actually suppressed rather than re-deriving a verdict without that scope. The scope comment at the top of the function was also wrong and is corrected. It claimed every use of suppression sits inside `replaceWorktreeIds`; it does not -- the tabs pass walks all of `orderedWorktreeIds` and the two sweeps cover the whole remote maps. What actually makes it safe is that `closeTab` strips the id from every worktree row before recording the tombstone, plus the worktree match above, plus `closeReason === 'user'` being the only writer. Real guarantee, different from the documented one. ## Divergences from open PR #16571 #16571 implements the same concept. Three deliberate changes: 1. It never retires on acknowledgement -- TTL+cap only, so it never converges. Ack retirement added. 2. It crosses the wire and lets a HOST-sourced tombstone delete a LOCAL tab in a final whole-map sweep. After #14361 that is the wrong risk; dropped. This also removes the mixed-version regression its own body flags. 3. Its hydration unions rather than replaces the map -- a union resurrects every tombstone the merge just retired, so it never converges. Its `activeTabId` nulling is also dropped as redundant: `workspace-terminal-hydration.ts:99-105,126-138` already revalidates both pointers against the tab rows it just built, and nulling twice would add a second rule that has to stay in step with the first. ## Can a tab the user did NOT close disappear? No, but the guarantee needs stating precisely. The only writer is `recordClosedTerminalTabTombstone` (`terminal-tab-close.ts:69`), reachable only on `closeReason === 'user'`; suppression additionally requires the tab not be live locally. Reopen (`recently-closed-tabs.ts:122-166`) calls `createTab` and restores cwd/shell/title/color/position, never the old id. **Caveat, stated because the slogan is not literally true:** `createTab` honours a caller-supplied id hint (`terminal-tab-creation.ts:53-65`, used by `useIpcEvents` for host-admitted tabs), so "tab ids are uuids that never recur" does not hold in this codebase. The guarantee rests on the `closeReason === 'user'` writer plus the live-local-tab check, not on id uniqueness. ## Risk Renderer-side, client-local, no wire change. The blast radius is `mergeDirectSshRemoteWorkspaceSession` and the persisted session field. Worst case if the ack logic were wrong in the retiring direction: a tombstone outlives its usefulness and suppresses a host tab whose id the host re-issues -- bounded by the live-local-tab check, the 30d TTL and the 500 cap. Worst case in the other direction is today's behaviour. `profile-project-session-field-disposition.ts` records the new field as `notRepoScoped` / `notTransferred` residue, bounded by the same TTL and cap. ## Verify pnpm test src/shared/closed-terminal-tab-tombstones.test.ts \ src/renderer/src/lib/workspace-session-closed-tab-tombstones.test.ts \ src/renderer/src/store/terminals/terminal-tab-close-tombstone.test.ts \ src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts To reproduce the bug this fixes, set `isSuppressedByClose` to `() => false` in `remote-workspace-session-merge.ts` and run `pnpm test:e2e:ssh-docker -- tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts --repeat-each=2`.
nwparker
force-pushed
the
nwparker/ssh-06-close-tombstone
branch
from
August 28, 2026 02:46
92de673 to
f450562
Compare
Contributor
|
Warning Review limit reachedNext included review available in 54 minutes. View limit detailsLimit details: You’ve used all 10 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (29)
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 |
This was referenced Aug 28, 2026
fix(remote-workspace): stop closed SSH terminal tabs from resurrecting — add close tombstones
#16571
Closed
Closed
This was referenced Aug 28, 2026
Merged
This was referenced Aug 29, 2026
paidaxingyo666
pushed a commit
to paidaxingyo666/Manta
that referenced
this pull request
Aug 30, 2026
stablyai#16752) An enterprise user: "Every day I open orca and it opens more tabs daily at a linear scale." Three reports over a week, told on 08-19 that a PR had fixed it, reported twice more after. STA-4658 (P0), GH stablyai#12447, stablyai#15136, stablyai#10342, stablyai#9585. One install held 39 zombie tab records. The revived tab's sleeping-agent record still holds the pre-close session id, so it boots `claude --resume <old id>` -- two agents on one transcript. ## The chain, measured Reproduced deterministically in `ssh-lost-kill-tab-resurrection.spec.ts`: close an SSH tab, kill the relay daemon in the container so `pty.kill` rejects with a transport-class error, reconnect. drop 2 resurrected the closed tab <id>: baseline=1 drop1=1 drop2=2 (closed tab returned) drop3=1 The trigger is narrow and had to be measured rather than assumed: killed relay daemon reproduces **6 of 6 runs**; an orderly `ssh.disconnect` **passes**. Only an ungraceful loss -- network partition, host reboot, relay crash, a laptop sleeping mid-session -- strands the close with the RPC rejecting on a transport-class error. Both variants live in the spec behind one `runResurrectionCycles` parameterized solely by the disruption, so the difference is attributable to that single variable. What actually carries the tab back, from the pull path (`workspace.get` -> `getRemoteSnapshot`, `remote-workspace-relay-sync.ts:29`): pullSnapshot rev=3 tabs={repo:["16c4a3e1","06aba6b6"]} pullSnapshot rev=4 tabs={repo:["16c4a3e1","ff72768e"]} <- ff72768e IS the resurrected tab pullSnapshot rev=5 tabs={repo:["16c4a3e1","ff72768e","da21b76c"]} The client uploaded the session containing the tab; the user closed it; the kill RPC rejected so the close never reached the host; the host's snapshot still lists it; the client pulls it back and the merge restores it -- **correctly, by its own rule that the host is authoritative for what it knows.** A pane then mounts, respawns, and takes the recycled pty id. Client-side correlation from the same run, two controls and one positive in one run differing in exactly one variable: | Tab | Close events observed | Resurrected? | |---|---|---| | `6305cc07` | `user` + `pty-exit` | No | | `ed56f66c` | `user` + `pty-exit` | No | | `2036e760` | `user` only | **YES** | ## The fix `src/shared/closed-terminal-tab-tombstones.ts` (99 lines). A client-recorded close is first-party intent and must survive until the host acknowledges it. Per `docs/reference/ssh-execution-boundary.md` the remote verdict is `unverifiable` -- which may not authorise declaring the process dead, but equally must not authorise resurrecting the tab. This is SSH-v3 principle P2, "durable tombstones with a monotonic per-scope revision", reusing the existing `RemoteWorkspaceSnapshot.revision` rather than adding a twelfth per-tab identity field (the codebase carries eleven, 784 refs, that SSH-v3 Phase 3 deletes). - **Recorded** only on `closeReason === 'user'` (`terminal-tab-close.ts:69`). - **Suppresses** a host-sourced tab only when `tabId in tombstones && !currentTabsById.has(tabId)` -- a live local tab always wins, because deleting a live pane is the one outcome the merge exists to avoid. - **Retires** on positive acknowledgement: `!hostKnownTabIds.has(tabId) && hostRevision > observed`. Strictly newer, so a pull already in flight at close time cannot ack a close it predates. - Three never-retire guards: no revision retires nothing; a worktree the snapshot has no row for retires nothing; the first omitting snapshot only stamps the watermark. - TTL (30d) + cap (500) are **backstops** for a target the user never returns to, not the mechanism. - **Client-local only** -- never crosses the wire, so there is no mixed-version exposure. - Suppression is scoped to `replaceWorktreeIds`, which is what makes the live-tab check meaningful. A final whole-map sweep over the assembled `tabsByWorktree` would break that (a live tab is absent from `currentTabsById` outside the scope and would look suppressible); it is deliberately not there, and the comment at the top of the function says so. ## Evidence The load-bearing evidence is an A/B control on one tree, not the oracle's assertion. Flipping `isSuppressedByClose` to `false` -- one character -- reproduces the resurrection on demand: --repeat-each=2: 1) drop 2 resurrected the closed tab ab0e305d-…: baseline=1 drop1=1 drop2=2 2) drop 2 resurrected the closed tab 51533e34-…: baseline=1 drop1=1 drop2=2 2 failed With suppression on: **0 occurrences of "resurrected the closed tab" across five runs plus one independent run by a second agent.** Provenance verified positively, not by mtime: `closedTerminalTabTombstonesByTabId` appears 13x across 3 renderer chunks including `store-Do3KBvRE.js`; for every red control run `mayCreate` appeared 0 times in `out/main/index.js`. At the unit layer, disabling the same predicate: 3 failed | 39 passed. Restored: 42 passed; 287 across the workspace-session, terminal-store, remote-workspace, shared-tombstone and profile suites; 24 in the four tombstone suites. ## The oracle spec: GREEN in the full lane `ssh-lost-kill-tab-resurrection.spec.ts` passes both tests at this commit. Full Docker-SSH lane, clean tree: BUILD_SHA=49bb96e0b4c DIRTY=0 PROVENANCE tombstone=13 hasLocalTabsRow=2 hostAuthority=4 mayCreate=3 14 specs / 20 tests -> 17 passed, 2 failed, 1 skipped (10.7m) [12/20] :178 does not resurrect tabs whose kill was lost to a killed relay daemon PASSED [13/20] :190 does not resurrect tabs closed while the host is disconnected PASSED grep -c "resurrected the closed tab" (whole lane) -> 0 It passes WITHOUT PR 7 in the build (`mayCreate` present, `SshPtyAbsentFromRelayError` absent), so the bug-2 fix below is not required for it. Test 1 fails intermittently in ISOLATED single-spec runs, where a third defect blocks its cycle-2 setup. The resurrection assertion itself has never failed with this fix in place -- the intermittent failure is always a setup failure, never a resurrected tab. A reviewer running the spec alone may see it red; that is not this fix regressing. Three defects sit under STA-3374 and should not be conflated: - Bug 1 -- the closed tab resurrects. Fixed here. - Bug 2 -- `ssh-pty-session-reattach.ts:227-231` rewrites the relay's `PTY "pty-1" not found` into a bare `SSH_SESSION_EXPIRED`, so `isPtyAlreadyGoneError`'s `/PTY ".+" not found/` cannot match and `attachStablePaneOwner:242`'s already-correct fallback never runs. Owned by PR 7 (`nwparker/ssh-07-absent-from-relay`). Not required for the oracle above. - Bug 3 -- after the daemon is killed and the client launches a replacement, the client's OWN SSH transport drops and does not reconnect within 60s: no "delay step 2/9", no handshake failure, nothing. `ssh-connection.ts:1533` only logs on an SSH-level close. Unfixed, its own ticket. This is what makes test 1 intermittent in isolation. Discriminator for bug 3, measured in the isolated runs (the lane above ran without `ORCA_E2E_FORWARD_APP_LOGS=1`, so it was not re-confirmed there): `[ssh-relay] Socket probe result:` reads "DEAD" on every cycle of test 1 (daemon killed, a NEW relay must be launched) and "ALIVE" on every cycle of test 2 (daemon survived). Whenever a new daemon must be launched, the SSH transport drops afterwards and does not recover. An earlier reading blamed `kill.ts:82-84` for skipping `finishPtyShutdown` on a non-already-gone error. That was eliminated by direct test: the implied fix, `markSshRemotePtyLease(…, 'expired')` in that branch, was implemented, changed nothing, and was reverted rather than shipped unproven. Recorded so the path is not re-walked. The `SSH_SESSION_EXPIRED` rejection is real but fires during cycle 1 for the baseline pane, after which cycle 1 completes; the 60s silence begins only after `Relay channel lost ..., triggering reconnect`. The spec is claimed by the Docker-SSH lane, and that lane does not gate merges today. ## Persistence: the tombstone must survive a relaunch `closedTerminalTabTombstonesByTabId` is declared on `WorkspaceSessionState` but was missing from `workspaceSessionStateSchema` (`src/shared/workspace-session-schema.ts`), which is the load boundary for BOTH partitions -- `normalize-loaded-state-collections.ts` for `local` and `workspace-session-partitions.ts` for `ssh:<target>`. Zod strips unknown keys and the write side does not validate, so the map reached disk and was discarded on the next launch. Measured with the repo's own parser: input : closedTerminalTabTombstonesByTabId: { 'tab-1': {...} } ok = true tombstones after parse = undefined That made the fix ineffective in the exact reported scenario: close an SSH tab with the transport down, QUIT, relaunch, reconnect -- the merge runs with an empty map, the host still lists the tab, and it resurrects. "Every day I open orca and it opens more tabs" is a claim about restarts. Neither the green oracle nor the A/B control could see it: both run entirely inside one app process. It also made the 30-day TTL and the 500 cap unreachable. Fixed by adding the field with a `salvagingRecord` matching its sibling `terminalSurfaceTombstonesByPaneKey`, so one malformed entry drops that entry rather than the map. `workspace-session-schema.ts` was one line under its 300-line max-lines limit, so adding the field required room rather than a suppression (the project forbids max-lines disables and per-file bumps). Two value schemas were extracted to modules named after what they contain: `terminal-tab-id-schema.ts` and `terminal-surface-tombstone-schema.ts`. The closed-tab tombstone's own schema is colocated with its type in `closed-terminal-tab-tombstones.ts`, which is where it belongs -- omitting it from the session schema is exactly the drift that caused this bug. `workspace-session-schema-field-coverage.test.ts` is the ratchet. Two sibling tables already pin themselves with `satisfies Record<keyof WorkspaceSessionState, ...>`; this schema had no such guard and is the one that fell behind. The new file adds both halves -- a `satisfies` list that makes a forgotten field a compile error, and a runtime assertion that names it -- plus a `parseWorkspaceSession` round-trip. Without the schema entry: 3 failed. With it: 3 passed. ## A host tab the user never closed could be deleted `tabId in closedTerminalTabTombstonesByTabId` answers true for every `Object.prototype` key even on an EMPTY map, because the map is a plain object from `Object.fromEntries`. A host tab whose id is `toString` was filtered from the reconciled list, blocked from the host-unknown branch, and stripped of its layout and session id. Tab ids are validated only as non-empty and colon-free, and `createTab` honours caller-supplied id hints, so the id is reachable rather than theoretical. This was the only path in either direction that could delete a tab the user never closed. Now `Object.hasOwn`, as the same file already uses elsewhere. Suppression is also scoped structurally: `isSuppressedByClose` compares the tombstone's stored `worktreeId`, which it already carried, so it cannot reach another workspace's tab. The two sweeps that have no worktree in scope (`terminalLayoutsByTabId`, `remoteSessionIdsByTabId`) now consult the set of ids this merge actually suppressed rather than re-deriving a verdict without that scope. The scope comment at the top of the function was also wrong and is corrected. It claimed every use of suppression sits inside `replaceWorktreeIds`; it does not -- the tabs pass walks all of `orderedWorktreeIds` and the two sweeps cover the whole remote maps. What actually makes it safe is that `closeTab` strips the id from every worktree row before recording the tombstone, plus the worktree match above, plus `closeReason === 'user'` being the only writer. Real guarantee, different from the documented one. ## Divergences from open PR stablyai#16571 stablyai#16571 implements the same concept. Three deliberate changes: 1. It never retires on acknowledgement -- TTL+cap only, so it never converges. Ack retirement added. 2. It crosses the wire and lets a HOST-sourced tombstone delete a LOCAL tab in a final whole-map sweep. After stablyai#14361 that is the wrong risk; dropped. This also removes the mixed-version regression its own body flags. 3. Its hydration unions rather than replaces the map -- a union resurrects every tombstone the merge just retired, so it never converges. Its `activeTabId` nulling is also dropped as redundant: `workspace-terminal-hydration.ts:99-105,126-138` already revalidates both pointers against the tab rows it just built, and nulling twice would add a second rule that has to stay in step with the first. ## Can a tab the user did NOT close disappear? No, but the guarantee needs stating precisely. The only writer is `recordClosedTerminalTabTombstone` (`terminal-tab-close.ts:69`), reachable only on `closeReason === 'user'`; suppression additionally requires the tab not be live locally. Reopen (`recently-closed-tabs.ts:122-166`) calls `createTab` and restores cwd/shell/title/color/position, never the old id. **Caveat, stated because the slogan is not literally true:** `createTab` honours a caller-supplied id hint (`terminal-tab-creation.ts:53-65`, used by `useIpcEvents` for host-admitted tabs), so "tab ids are uuids that never recur" does not hold in this codebase. The guarantee rests on the `closeReason === 'user'` writer plus the live-local-tab check, not on id uniqueness. ## Risk Renderer-side, client-local, no wire change. The blast radius is `mergeDirectSshRemoteWorkspaceSession` and the persisted session field. Worst case if the ack logic were wrong in the retiring direction: a tombstone outlives its usefulness and suppresses a host tab whose id the host re-issues -- bounded by the live-local-tab check, the 30d TTL and the 500 cap. Worst case in the other direction is today's behaviour. `profile-project-session-field-disposition.ts` records the new field as `notRepoScoped` / `notTransferred` residue, bounded by the same TTL and cap. ## Verify pnpm test src/shared/closed-terminal-tab-tombstones.test.ts \ src/renderer/src/lib/workspace-session-closed-tab-tombstones.test.ts \ src/renderer/src/store/terminals/terminal-tab-close-tombstone.test.ts \ src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts To reproduce the bug this fixes, set `isSuppressedByClose` to `() => false` in `remote-workspace-session-merge.ts` and run `pnpm test:e2e:ssh-docker -- tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts --repeat-each=2`. (cherry picked from commit 2b39165)
3 of 4 tasks
enrick-dev
pushed a commit
to enrick-dev/orca
that referenced
this pull request
Oct 15, 2026
stablyai#16752) An enterprise user: "Every day I open orca and it opens more tabs daily at a linear scale." Three reports over a week, told on 08-19 that a PR had fixed it, reported twice more after. STA-4658 (P0), GH stablyai#12447, stablyai#15136, stablyai#10342, stablyai#9585. One install held 39 zombie tab records. The revived tab's sleeping-agent record still holds the pre-close session id, so it boots `claude --resume <old id>` -- two agents on one transcript. ## The chain, measured Reproduced deterministically in `ssh-lost-kill-tab-resurrection.spec.ts`: close an SSH tab, kill the relay daemon in the container so `pty.kill` rejects with a transport-class error, reconnect. drop 2 resurrected the closed tab <id>: baseline=1 drop1=1 drop2=2 (closed tab returned) drop3=1 The trigger is narrow and had to be measured rather than assumed: killed relay daemon reproduces **6 of 6 runs**; an orderly `ssh.disconnect` **passes**. Only an ungraceful loss -- network partition, host reboot, relay crash, a laptop sleeping mid-session -- strands the close with the RPC rejecting on a transport-class error. Both variants live in the spec behind one `runResurrectionCycles` parameterized solely by the disruption, so the difference is attributable to that single variable. What actually carries the tab back, from the pull path (`workspace.get` -> `getRemoteSnapshot`, `remote-workspace-relay-sync.ts:29`): pullSnapshot rev=3 tabs={repo:["16c4a3e1","06aba6b6"]} pullSnapshot rev=4 tabs={repo:["16c4a3e1","ff72768e"]} <- ff72768e IS the resurrected tab pullSnapshot rev=5 tabs={repo:["16c4a3e1","ff72768e","da21b76c"]} The client uploaded the session containing the tab; the user closed it; the kill RPC rejected so the close never reached the host; the host's snapshot still lists it; the client pulls it back and the merge restores it -- **correctly, by its own rule that the host is authoritative for what it knows.** A pane then mounts, respawns, and takes the recycled pty id. Client-side correlation from the same run, two controls and one positive in one run differing in exactly one variable: | Tab | Close events observed | Resurrected? | |---|---|---| | `6305cc07` | `user` + `pty-exit` | No | | `ed56f66c` | `user` + `pty-exit` | No | | `2036e760` | `user` only | **YES** | ## The fix `src/shared/closed-terminal-tab-tombstones.ts` (99 lines). A client-recorded close is first-party intent and must survive until the host acknowledges it. Per `docs/reference/ssh-execution-boundary.md` the remote verdict is `unverifiable` -- which may not authorise declaring the process dead, but equally must not authorise resurrecting the tab. This is SSH-v3 principle P2, "durable tombstones with a monotonic per-scope revision", reusing the existing `RemoteWorkspaceSnapshot.revision` rather than adding a twelfth per-tab identity field (the codebase carries eleven, 784 refs, that SSH-v3 Phase 3 deletes). - **Recorded** only on `closeReason === 'user'` (`terminal-tab-close.ts:69`). - **Suppresses** a host-sourced tab only when `tabId in tombstones && !currentTabsById.has(tabId)` -- a live local tab always wins, because deleting a live pane is the one outcome the merge exists to avoid. - **Retires** on positive acknowledgement: `!hostKnownTabIds.has(tabId) && hostRevision > observed`. Strictly newer, so a pull already in flight at close time cannot ack a close it predates. - Three never-retire guards: no revision retires nothing; a worktree the snapshot has no row for retires nothing; the first omitting snapshot only stamps the watermark. - TTL (30d) + cap (500) are **backstops** for a target the user never returns to, not the mechanism. - **Client-local only** -- never crosses the wire, so there is no mixed-version exposure. - Suppression is scoped to `replaceWorktreeIds`, which is what makes the live-tab check meaningful. A final whole-map sweep over the assembled `tabsByWorktree` would break that (a live tab is absent from `currentTabsById` outside the scope and would look suppressible); it is deliberately not there, and the comment at the top of the function says so. ## Evidence The load-bearing evidence is an A/B control on one tree, not the oracle's assertion. Flipping `isSuppressedByClose` to `false` -- one character -- reproduces the resurrection on demand: --repeat-each=2: 1) drop 2 resurrected the closed tab ab0e305d-…: baseline=1 drop1=1 drop2=2 2) drop 2 resurrected the closed tab 51533e34-…: baseline=1 drop1=1 drop2=2 2 failed With suppression on: **0 occurrences of "resurrected the closed tab" across five runs plus one independent run by a second agent.** Provenance verified positively, not by mtime: `closedTerminalTabTombstonesByTabId` appears 13x across 3 renderer chunks including `store-Do3KBvRE.js`; for every red control run `mayCreate` appeared 0 times in `out/main/index.js`. At the unit layer, disabling the same predicate: 3 failed | 39 passed. Restored: 42 passed; 287 across the workspace-session, terminal-store, remote-workspace, shared-tombstone and profile suites; 24 in the four tombstone suites. ## The oracle spec: GREEN in the full lane `ssh-lost-kill-tab-resurrection.spec.ts` passes both tests at this commit. Full Docker-SSH lane, clean tree: BUILD_SHA=49bb96e0b4c DIRTY=0 PROVENANCE tombstone=13 hasLocalTabsRow=2 hostAuthority=4 mayCreate=3 14 specs / 20 tests -> 17 passed, 2 failed, 1 skipped (10.7m) [12/20] :178 does not resurrect tabs whose kill was lost to a killed relay daemon PASSED [13/20] :190 does not resurrect tabs closed while the host is disconnected PASSED grep -c "resurrected the closed tab" (whole lane) -> 0 It passes WITHOUT PR 7 in the build (`mayCreate` present, `SshPtyAbsentFromRelayError` absent), so the bug-2 fix below is not required for it. Test 1 fails intermittently in ISOLATED single-spec runs, where a third defect blocks its cycle-2 setup. The resurrection assertion itself has never failed with this fix in place -- the intermittent failure is always a setup failure, never a resurrected tab. A reviewer running the spec alone may see it red; that is not this fix regressing. Three defects sit under STA-3374 and should not be conflated: - Bug 1 -- the closed tab resurrects. Fixed here. - Bug 2 -- `ssh-pty-session-reattach.ts:227-231` rewrites the relay's `PTY "pty-1" not found` into a bare `SSH_SESSION_EXPIRED`, so `isPtyAlreadyGoneError`'s `/PTY ".+" not found/` cannot match and `attachStablePaneOwner:242`'s already-correct fallback never runs. Owned by PR 7 (`nwparker/ssh-07-absent-from-relay`). Not required for the oracle above. - Bug 3 -- after the daemon is killed and the client launches a replacement, the client's OWN SSH transport drops and does not reconnect within 60s: no "delay step 2/9", no handshake failure, nothing. `ssh-connection.ts:1533` only logs on an SSH-level close. Unfixed, its own ticket. This is what makes test 1 intermittent in isolation. Discriminator for bug 3, measured in the isolated runs (the lane above ran without `ORCA_E2E_FORWARD_APP_LOGS=1`, so it was not re-confirmed there): `[ssh-relay] Socket probe result:` reads "DEAD" on every cycle of test 1 (daemon killed, a NEW relay must be launched) and "ALIVE" on every cycle of test 2 (daemon survived). Whenever a new daemon must be launched, the SSH transport drops afterwards and does not recover. An earlier reading blamed `kill.ts:82-84` for skipping `finishPtyShutdown` on a non-already-gone error. That was eliminated by direct test: the implied fix, `markSshRemotePtyLease(…, 'expired')` in that branch, was implemented, changed nothing, and was reverted rather than shipped unproven. Recorded so the path is not re-walked. The `SSH_SESSION_EXPIRED` rejection is real but fires during cycle 1 for the baseline pane, after which cycle 1 completes; the 60s silence begins only after `Relay channel lost ..., triggering reconnect`. The spec is claimed by the Docker-SSH lane, and that lane does not gate merges today. ## Persistence: the tombstone must survive a relaunch `closedTerminalTabTombstonesByTabId` is declared on `WorkspaceSessionState` but was missing from `workspaceSessionStateSchema` (`src/shared/workspace-session-schema.ts`), which is the load boundary for BOTH partitions -- `normalize-loaded-state-collections.ts` for `local` and `workspace-session-partitions.ts` for `ssh:<target>`. Zod strips unknown keys and the write side does not validate, so the map reached disk and was discarded on the next launch. Measured with the repo's own parser: input : closedTerminalTabTombstonesByTabId: { 'tab-1': {...} } ok = true tombstones after parse = undefined That made the fix ineffective in the exact reported scenario: close an SSH tab with the transport down, QUIT, relaunch, reconnect -- the merge runs with an empty map, the host still lists the tab, and it resurrects. "Every day I open orca and it opens more tabs" is a claim about restarts. Neither the green oracle nor the A/B control could see it: both run entirely inside one app process. It also made the 30-day TTL and the 500 cap unreachable. Fixed by adding the field with a `salvagingRecord` matching its sibling `terminalSurfaceTombstonesByPaneKey`, so one malformed entry drops that entry rather than the map. `workspace-session-schema.ts` was one line under its 300-line max-lines limit, so adding the field required room rather than a suppression (the project forbids max-lines disables and per-file bumps). Two value schemas were extracted to modules named after what they contain: `terminal-tab-id-schema.ts` and `terminal-surface-tombstone-schema.ts`. The closed-tab tombstone's own schema is colocated with its type in `closed-terminal-tab-tombstones.ts`, which is where it belongs -- omitting it from the session schema is exactly the drift that caused this bug. `workspace-session-schema-field-coverage.test.ts` is the ratchet. Two sibling tables already pin themselves with `satisfies Record<keyof WorkspaceSessionState, ...>`; this schema had no such guard and is the one that fell behind. The new file adds both halves -- a `satisfies` list that makes a forgotten field a compile error, and a runtime assertion that names it -- plus a `parseWorkspaceSession` round-trip. Without the schema entry: 3 failed. With it: 3 passed. ## A host tab the user never closed could be deleted `tabId in closedTerminalTabTombstonesByTabId` answers true for every `Object.prototype` key even on an EMPTY map, because the map is a plain object from `Object.fromEntries`. A host tab whose id is `toString` was filtered from the reconciled list, blocked from the host-unknown branch, and stripped of its layout and session id. Tab ids are validated only as non-empty and colon-free, and `createTab` honours caller-supplied id hints, so the id is reachable rather than theoretical. This was the only path in either direction that could delete a tab the user never closed. Now `Object.hasOwn`, as the same file already uses elsewhere. Suppression is also scoped structurally: `isSuppressedByClose` compares the tombstone's stored `worktreeId`, which it already carried, so it cannot reach another workspace's tab. The two sweeps that have no worktree in scope (`terminalLayoutsByTabId`, `remoteSessionIdsByTabId`) now consult the set of ids this merge actually suppressed rather than re-deriving a verdict without that scope. The scope comment at the top of the function was also wrong and is corrected. It claimed every use of suppression sits inside `replaceWorktreeIds`; it does not -- the tabs pass walks all of `orderedWorktreeIds` and the two sweeps cover the whole remote maps. What actually makes it safe is that `closeTab` strips the id from every worktree row before recording the tombstone, plus the worktree match above, plus `closeReason === 'user'` being the only writer. Real guarantee, different from the documented one. ## Divergences from open PR stablyai#16571 stablyai#16571 implements the same concept. Three deliberate changes: 1. It never retires on acknowledgement -- TTL+cap only, so it never converges. Ack retirement added. 2. It crosses the wire and lets a HOST-sourced tombstone delete a LOCAL tab in a final whole-map sweep. After stablyai#14361 that is the wrong risk; dropped. This also removes the mixed-version regression its own body flags. 3. Its hydration unions rather than replaces the map -- a union resurrects every tombstone the merge just retired, so it never converges. Its `activeTabId` nulling is also dropped as redundant: `workspace-terminal-hydration.ts:99-105,126-138` already revalidates both pointers against the tab rows it just built, and nulling twice would add a second rule that has to stay in step with the first. ## Can a tab the user did NOT close disappear? No, but the guarantee needs stating precisely. The only writer is `recordClosedTerminalTabTombstone` (`terminal-tab-close.ts:69`), reachable only on `closeReason === 'user'`; suppression additionally requires the tab not be live locally. Reopen (`recently-closed-tabs.ts:122-166`) calls `createTab` and restores cwd/shell/title/color/position, never the old id. **Caveat, stated because the slogan is not literally true:** `createTab` honours a caller-supplied id hint (`terminal-tab-creation.ts:53-65`, used by `useIpcEvents` for host-admitted tabs), so "tab ids are uuids that never recur" does not hold in this codebase. The guarantee rests on the `closeReason === 'user'` writer plus the live-local-tab check, not on id uniqueness. ## Risk Renderer-side, client-local, no wire change. The blast radius is `mergeDirectSshRemoteWorkspaceSession` and the persisted session field. Worst case if the ack logic were wrong in the retiring direction: a tombstone outlives its usefulness and suppresses a host tab whose id the host re-issues -- bounded by the live-local-tab check, the 30d TTL and the 500 cap. Worst case in the other direction is today's behaviour. `profile-project-session-field-disposition.ts` records the new field as `notRepoScoped` / `notTransferred` residue, bounded by the same TTL and cap. ## Verify pnpm test src/shared/closed-terminal-tab-tombstones.test.ts \ src/renderer/src/lib/workspace-session-closed-tab-tombstones.test.ts \ src/renderer/src/store/terminals/terminal-tab-close-tombstone.test.ts \ src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts To reproduce the bug this fixes, set `isSuppressedByClose` to `() => false` in `remote-workspace-session-merge.ts` and run `pnpm test:e2e:ssh-docker -- tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts --repeat-each=2`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack: 6 of 6 — based on #16751. This is the headline fix.
ELI5 — this is the fix for "every day I open orca it opens more tabs"
What you saw: every morning, one more tab than yesterday, forever.
Why it happened:
Nobody's code was wrong in isolation. Your close simply evaporated between the two of them.
The fix: when you close a tab, Orca now writes down "the user closed this" and keeps that note until the remote machine actually confirms it. The note wins over the remote's stale list. Once the remote catches up, the note is thrown away.
The bit that nearly slipped through: the note was being saved to disk but silently discarded on every app launch, because it was missing one line in the file that validates saved data. That would have made it work for one session and fail you again the next morning — the exact "every day" pattern you reported. Caught in review, not by a test, so there's now a check that makes forgetting that line a compile error.
How we know it works: flip the one line off and the tab comes back 2 out of 2 runs. Leave it on and it never comes back — 0 resurrections across six runs plus a full 19-test suite.
Symptom
An enterprise user, three reports over a week:
They were told on 08-19 that a PR had fixed it, and reported it twice more after. STA-4658 (P0, os:macos), GH #12447, #15136, #10342, #9585. One install held 39 zombie tab records.
It is not only cosmetic. The revived tab's sleeping-agent record still holds the pre-close session id, so it boots
claude --resume <old id>— two agents writing one transcript. STA-3498 observed up to five concurrentclaudeprocesses on a single transcript.Reproduction
tests/e2e/ssh-lost-kill-tab-resurrection.spec.tsreproduces it deterministically: close an SSH tab → kill the relay daemon in the container sopty.killrejects with a transport-class error → reconnect.Two runs, different tab ids, byte-identical shape.
The trigger is narrower than "any reconnect", and this had to be measured rather than assumed. Both variants live in the spec behind one
runResurrectionCyclesparameterized solely by the disruption, so the difference is attributable to that single variable:drop2=2, resurrects — 6 of 6 runsssh.disconnect(orderly)An orderly disconnect either lands the kill or terminates the lease through the disconnect path. Only an ungraceful loss — network partition, host reboot, relay crash, a laptop sleeping mid-session without a clean disconnect — strands the close with the RPC rejecting on a transport-class error. All plausible for "every day"; the fix is justified on that narrower basis. Corroborating from a Slack thread: the reporting user says "if i close my laptop, my claude/codex sessions are interrupted" on a remote SSH env, and separately hit
thread <uuid> already has an active writeron reattach — exactly the orphaned-remote-writer shape.Root cause
The pull path carries the closed tab back (
workspace.get→getRemoteSnapshot,src/main/ipc/remote-workspace-relay-sync.ts:29). Measured:The chain:
spawnIpcPty(ipc-pty-spawn-request.ts:33), and takes the recycled pty id.Client-side correlation from a single instrumented run — two controls and one positive, differing in exactly one variable:
6305cc07user+pty-exited56f66cuser+pty-exit2036e760useronlypty-exitis what would have driven the removal all the way to the host. When the transport is dead it never arrives.Eliminated candidates — recorded so nobody re-walks them
Every one of these is a plausible fix location that a reviewer may reasonably propose. Each was eliminated by measurement or by reader analysis, not by argument. They all missed for the same reason: they are downstream of the real defect, and by the time they see it the tab is legitimately present in local state, because the close never completed.
mayCreate, #16751)CREATING TAB9 hits,reattach gate0,BYPASS0.restoreReattachedPtyRuntimeis never called in this scenario — the fence is on a path this bug does not take. It is a real fix for a different defect; see #16751, which says so itself.spawn-commit-persist.ts:76-84)persistPtyBindingbuilds fromargs.tabId, never the lease row; and the tab-create gate at:97-103is the same pair of expressions as the conditional spreads at:80-81, so any run that can emitCREATING TABis one where the upsert supplied both fields and overwrote. The defect is real and latent — worth its own ticket — but cannot produce these events.getSshRemotePtyLeasesoutside persistence:ssh-connection-handlers.ts:67,103(reset/terminate only, never produces a tab) andorca-runtime.ts:8021getRecentExpiredSshLease, which is queried with(worktreeId, tabId, leafId)as input and so cannot supply identity. The lease is a co-symptom of the relay restart, not the carrier — the same restart that recyclespty-2is what strands the lease.kill.ts:82-84skippingfinishPtyShutdownon a non-already-gone errormarkSshRemotePtyLease(…, 'expired')in that branch — was implemented, changed nothing, and was reverted rather than shipped unproven.upsertSshRemotePtyLeaseStructural finding worth its own ticket:
toAppSshPtyIdis purelyconnectionId + relayPtyId. When the relay reissuespty-2the app-level id is byte-identical — the closed pane's durable binding and the new shell's binding are the same string. No id-based disambiguation exists anywhere in this stack once the relay's counter resets, which is why every id-keyed defence in this area is structurally unable to work.The fix, and why this shape
A user-initiated close is first-party intent and must survive until the host acknowledges it. Per
docs/reference/ssh-execution-boundary.mdthe remote verdict isunverifiable— which may not authorise declaring the process dead, but equally must not authorise resurrecting the tab. This is SSH-v3 principle P2, "durable tombstones with a monotonic per-scope revision", reusing the existingRemoteWorkspaceSnapshot.revisionrather than adding a twelfth per-tab identity field (the codebase carries eleven, 784 refs, that the redesign's Phase 3 deletes).src/shared/closed-terminal-tab-tombstones.ts, 99 lines:closeReason === 'user'(src/renderer/src/store/terminals/terminal-tab-close.ts:69) — narrowed from fix(remote-workspace): stop closed SSH terminal tabs from resurrecting — add close tombstones #16571'suser || cleanup.tabId in tombstones && !currentTabsById.has(tabId). A live local tab always wins: deleting a live pane is the one outcome the merge exists to avoid.!hostKnownTabIds.has(tabId) && hostRevision > observed. Strictly newer, so a pull already in flight at close time cannot ack a close it predates.replaceWorktreeIds, which is what makes the live-tab check meaningful. A final whole-map sweep over the assembledtabsByWorktreewould break exactly that (a live tab is absent fromcurrentTabsByIdoutside the scope and would look suppressible). It is deliberately not there, and the comment at the top of the function says so.Evidence
The load-bearing evidence is an A/B control on one tree, not the oracle's assertion. Flipping
isSuppressedByClosetofalse— one character — reproduces the resurrection on demand:Provenance verified positively, not by mtime.
closedTerminalTabTombstonesByTabIdappears 13× across 3 renderer chunks includingstore-Do3KBvRE.js. For every red control run,mayCreateappeared 0× inout/main/index.js, establishing those runs were against a build without the PR-5 fence. (A first provenance grep read 0 — it had matched a differentstore-*chunk. The check was wrong, not the build.)At the unit layer, disabling the same predicate:
Restored:
The oracle spec: GREEN in the full lane
Both oracle tests pass at the stack tip. Full Docker-SSH lane at
49bb96e0b4c, clean tree:Note that the oracle passes without PR 7 in the build —
mayCreate=3confirms #16751's fence is present, andSshPtyAbsentFromRelayErroris absent — so the bug-2 fix below is not required for this to hold.An honest note on test 1's stability
Test 1 fails intermittently in isolated single-spec runs, where a third defect blocks its cycle-2 setup. It passes in the full lane, where it completed every cycle. The resurrection assertion itself has never failed with this fix in place — the intermittent failure is always a setup failure, never a resurrected tab.
Stated so nobody is surprised in either direction: a reviewer who runs the spec in isolation may see it go red, and that is not this fix regressing.
The three defects under STA-3374, kept distinct
ssh-pty-session-reattach.ts:227-231rewrites the relay'sPTY "pty-1" not foundinto a bareSSH_SESSION_EXPIRED, soisPtyAlreadyGoneError's/PTY ".+" not found/cannot match andattachStablePaneOwner:242's already-correct fallback never runsnwparker/ssh-07-absent-from-relay. Not required for this PR's oracle to passssh-connection.ts:1533only logs on an SSH-level closeThe isolating discriminator for bug 3
Scope of that measurement: it was observed in the isolated single-spec runs where bug 3 reproduced. The full lane above ran without
ORCA_E2E_FORWARD_APP_LOGS=1, so main-process stdout was not captured and the probe was not re-confirmed there. Reported as measured, not as re-verified.Why the
SSH_SESSION_EXPIREDrejection is a red herringIt is real, but it is not what fails cycle 2 in the isolated runs. Log ordering settles it: the rejection fires during cycle 1's reconnect for the baseline pane —
spawn() called … pty-1→pty.attach FAILED … PTY "pty-1" not found→Error occurred in handler for 'pty:spawn'— and then cycle 1 completes ([auth cycle1-after-reconnect] storeTabs:1). The 60s silence begins only afterwards, followingRelay channel lost …, triggering reconnectandwaiting 15000ms. The failure screenshot shows the pane rendering the "Relay channel lost. Reconnecting…" placeholder: the tab never gets a PTY because the host is unreachable, not because a stale lease misrouted its spawn.The
kill.ts:82-84theory was tested directly as well and eliminated — see Eliminated candidates above.The A/B control, which still matters
The green oracle is the headline evidence. The A/B remains the stronger causal statement, because it varies exactly one character:
A green test says "the bug did not occur". The A/B says "this line is why". Both are here.
The spec is claimed by the Docker-SSH lane (required by the gate-contract assertion added in #16746), and that lane does not gate merges today (
pr.yml:796-821, deliberate, pinned by the contract).Can a tab the user did NOT close disappear?
No — but the guarantee needs stating precisely, because the obvious slogan is false.
The only writer is
recordClosedTerminalTabTombstone(terminal-tab-close.ts:69), reachable only oncloseReason === 'user'. Suppression additionally requires the tab not be live locally. Reopen (recently-closed-tabs.ts:122-166) callscreateTaband restores cwd/shell/title/color/position, never the old id.Persistence: the tombstone had to survive a relaunch, and did not
closedTerminalTabTombstonesByTabIdis declared onWorkspaceSessionStatebut was missing fromworkspaceSessionStateSchema— the load boundary for both partitions (normalize-loaded-state-collections.tsforlocal,workspace-session-partitions.tsforssh:<target>). Zod strips unknown keys and the write side does not validate, so the map reached disk and was discarded on the next launch. Measured with the repo's own parser:That made the headline fix ineffective in the reported scenario. Close an SSH tab with the transport down → tombstone recorded → quit → relaunch → connect → the merge runs with an empty map → the host still lists the tab → it resurrects. "Every day I open orca and it opens more tabs" is a claim about restarts. It also made the 30-day TTL and 500 cap unreachable.
Neither the green oracle nor the A/B control could see it — both run entirely inside one app process. Without the schema entry: 3 failed. With it: 3 passed.
workspace-session-schema-field-coverage.test.tsis the ratchet, in both directions: asatisfies Record<keyof WorkspaceSessionState, true>list that makes a forgotten field a compile error, plus a runtime assertion that names it — which also catches the reverse case, list updated but schema not. Two sibling tables already pin themselves this way; this schema was the unguarded third, which is why it fell behind.Why this PR adds two small files.
workspace-session-schema.tswas one line under its 300-line limit, andmax-linesdisables and per-file bumps are both forbidden. Two value schemas moved to modules named for their contents —terminal-tab-id-schema.tsandterminal-surface-tombstone-schema.ts— and the closed-tab tombstone's schema is now colocated with its type inclosed-terminal-tab-tombstones.ts. That colocation is the structural fix, not a workaround: separating a type from its schema is what caused this bug in the first place.A host tab the user never closed could be deleted
tabId in closedTerminalTabTombstonesByTabIdanswerstruefor everyObject.prototypekey even on an empty map, because the map is a plain object fromObject.fromEntries. A host tab whose id istoStringwas filtered from the reconciled list, blocked from the host-unknown branch, and stripped of its layout and session id. Tab ids are validated only as non-empty and colon-free, andcreateTabhonours caller-supplied id hints, so the id is reachable rather than theoretical. This was the only path in either direction that could delete a tab the user never closed.Now
Object.hasOwn, as the same file already uses elsewhere. Suppression is also scoped structurally —isSuppressedByClosecompares the tombstone's storedworktreeId, so it cannot reach another workspace's tab — and the two sweeps that have no worktree in scope (terminalLayoutsByTabId,remoteSessionIdsByTabId) now consult the set of ids this merge actually suppressed rather than re-deriving a verdict without that scope.The scope comment at the top of the function was also wrong and is corrected. It claimed every use of suppression sits inside
replaceWorktreeIds; it does not — the tabs pass walks all oforderedWorktreeIdsand both sweeps cover the whole remote maps. What actually makes it safe iscloseTabstripping the id from every worktree row before recording, plus the worktree match, pluscloseReason === 'user'being the only writer. Real guarantee, different from the documented one.Both fixes have failing-first proof:
Divergences from open PR #16571
#16571 implements the same concept (
closedTerminalTabTombstonesByTabId,mergeClosedTerminalTabTombstones,normalizeClosedTabTombstonesByTabId) and now has a deterministic repro proving it is needed. The core is ported with three deliberate changes:Its
activeTabIdnulling is also dropped as redundant:workspace-terminal-hydration.ts:99-105,126-138already revalidates both pointers against the tab rows it just built, and nulling twice would add a second rule that has to stay in step with the first.Deliberately NOT done
tabsByWorktree— see the scoping note above.ssh-pty-session-reattach.ts:227-231, owned bynwparker/ssh-07-absent-from-relay) and the SSH transport that never reconnects after a new daemon is launched (unfixed, own ticket). Neither is touched here. See the RED-oracle section.Risk / blast radius
Renderer-side, client-local, no wire change. Blast radius is
mergeDirectSshRemoteWorkspaceSessionplus one persisted session field.Worst case if the ack logic were wrong in the retiring direction: a tombstone outlives its usefulness and suppresses a host tab whose id the host re-issues — bounded by the live-local-tab check, the 30-day TTL and the 500 cap. Worst case in the other direction is today's behaviour.
src/main/orca-profiles/profile-project-session-field-disposition.tsrecords the new field asnotRepoScoped/notTransferredresidue — keyed by tab id and pruned by neither path, likeremoteSessionIdsByTabId— bounded by the same TTL and cap, and a resolved host retires its own entries.How to verify
To reproduce the bug this fixes, set
isSuppressedByCloseto() => falseinsrc/renderer/src/hooks/remote-workspace-session-merge.tsand run (needs Docker):End-to-end verification
Specs this PR routes to
Under
main's router this routed to 3; #16746 addsssh-cold-activation-restoreandssh-reconnect-tab-destruction— the two specs that guard this exact regression class.ssh-lost-kill-tab-resurrection.spec.tsis new here and is added to the lane runner in the same commit, as the gate contract requires.Lane result
Full Docker-SSH lane at the stack tip, which covers this PR's routed set:
The two lane failures, resolved — and one is now exempted:
mainssh-docker-bulk-open-freeze-reproTypeError: … reading 'workerIndex'atdocker-ssh-relay-target.ts:226ssh-port-forward-lifecyclessh-port-forward-lifecycle-evidence.ts:159waiting ongetByText('Ports')Port-forward was re-run at the same commit and build and passed in 59.6s. It is green on
main, green at the tip in isolation, and red only inside the full lane — it is the set's one@headfulspec and runs last. Called flaky in-lane rather than "unrelated": a real lane-ordering problem, pre-existing, and worth tracking.Neither is in this PR's routed spec set.
Build provenance
closedTerminalTabTombstonesByTabIdis a new identifier — 0 occurrences inmain's source:Measured on the lane build:
tombstone=13is this PR's symbol; the other three prove the levels beneath it are in the same build.SshPtyAbsentFromRelayErroris absent, confirming PR 7 is not present — so the green oracle above is not borrowing bug 2's fix.This exact trap already bit once in this campaign — a first provenance grep read 0 and was wrong about the build, not the code. The all-chunk form is what produced the 13 above.
Reading the lane output: one probe that measures nothing
ssh-lost-kill-tab-resurrection.spec.tscalls adumpAuthorityhelper that logstopologyRevread throughwindow.api.session.get().terminalTopologyRevisionByRepoIdis declaredhostPrivate(src/renderer/src/lib/workspace-session-host-field-ownership.ts:51), so that call returns it absent on every run regardless of its real value. The probe will always printtopologyRev: null, and that is a measurement artifact — not evidence the revision is 0. Flagging it rather than editing a spec in a PR that cannot re-run it.What is NOT covered
[ssh-relay] Socket probe result:is"DEAD"on every cycle of test 1 and"ALIVE"on every cycle of test 2.ssh-pty-session-reattach.ts:227-231, which flattens the relay'sPTY "pty-1" not foundinto a bareSSH_SESSION_EXPIREDsoattachStablePaneOwner:242's correct fallback never fires. Owned bynwparker/ssh-07-absent-from-relay, not this PR.kill.ts:82-84). Each is tabulated with its disproof under Eliminated candidates so the trip does not get re-walked.1 → 2 → 1, not monotonic. The repro proves the resurrection chain; it does not by itself prove "linearly more tabs daily". The link to the user report rests on the mechanism plus the ticket cluster, not on a measured daily slope.createTabhonours a caller-supplied id hint (terminal-tab-creation.ts:53-65), so "tab ids are uuids that never recur" is not literally true. The guarantee rests oncloseReason === 'user'being the only writer plus the live-local-tab check. Repeated here because it is the one assumption that would break the safety argument.Failing-first test
Yes, at both layers — and the e2e A/B is the load-bearing one.
e2e, flipping
isSuppressedByClosetofalse(one character):unit, same predicate disabled:
Restored: 42 passed; 287 across the workspace-session, terminal-store, remote-workspace, shared-tombstone and profile suites.