Skip to content

fix(terminal): a close the host never heard must survive the reconnect - #16752

Merged
nwparker merged 1 commit into
mainfrom
nwparker/ssh-06-close-tombstone
Aug 28, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/ssh-06-close-tombstone

Conversation

@nwparker

@nwparker nwparker commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​738 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​737
Prod 19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​303 $\color{#cf222e}{\Huge{\mathbf{−}}}$​34 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​269

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:

  1. You close an SSH terminal tab.
  2. Orca tells the remote machine "kill that shell" — but the connection is already dead (laptop slept, Wi-Fi dropped, relay crashed). The message never arrives.
  3. The remote's own list still has that tab on it. Correctly — nobody ever told it otherwise.
  4. Next time you connect, Orca reads that list and puts the tab back. Also correctly — the remote is supposed to be the source of truth.
  5. The tab reopens, and it never goes away.

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:

"Every day I open orca and it opens more tabs daily at a linear scale."

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 concurrent claude processes on a single transcript.

Reproduction

tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts reproduces it deterministically: 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

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 runResurrectionCycles parameterized solely by the disruption, so the difference is attributable to that single variable:

Disruption Result
killed relay daemon drop2=2, resurrects — 6 of 6 runs
ssh.disconnect (orderly) passes, no resurrection

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 writer on 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:

pullSnapshot rev=0 tabs={}
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 chain:

  1. The client uploads the session containing the tab.
  2. The user closes the tab. The kill RPC rejects — the close never reaches the host (transport dead).
  3. The host's snapshot still lists it (rev 4).
  4. On reconnect the client pulls that snapshot and the merge restores the tab — correctly, by its own rule that the host is authoritative for what it knows.
  5. A pane mounts (a pane cannot mount for a tab absent from the store), respawns via 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:

Tab Close events observed Resurrected?
6305cc07 user + pty-exit No
ed56f66c user + pty-exit No
2036e760 user only YES

pty-exit is 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.

Candidate How it was eliminated
The reattach fence (mayCreate, #16751) Instrumented run: CREATING TAB 9 hits, reattach gate 0, BYPASS 0. restoreReattachedPtyRuntime is 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.
Lease inheritance (spawn-commit-persist.ts:76-84) Statically refuted. persistPtyBinding builds from args.tabId, never the lease row; and the tab-create gate at :97-103 is the same pair of expressions as the conditional spreads at :80-81, so any run that can emit CREATING TAB is one where the upsert supplied both fields and overwrote. The defect is real and latent — worth its own ticket — but cannot produce these events.
The lease as identity carrier Reader analysis. Only two readers of getSshRemotePtyLeases outside persistence: ssh-connection-handlers.ts:67,103 (reset/terminate only, never produces a tab) and orca-runtime.ts:8021 getRecentExpiredSshLease, 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 recycles pty-2 is what strands the lease.
kill.ts:82-84 skipping finishPtyShutdown on a non-already-gone error The implied fix — markSshRemotePtyLease(…, 'expired') in that branch — was implemented, changed nothing, and was reverted rather than shipped unproven.
A collision guard for upsertSshRemotePtyLease Built, tested, and removed: its own test passed with the guard disabled, i.e. vacuous. Telling "same lease" from "recycled id on a different shell" from lease state alone needs a relay-start identity — a twelfth per-tab identity concept. See #16751.

Measurement trap worth its own warning. An early probe reported inboundSnapshot tabs={} on all 5 occurrences and grep -cF <tab> over every inbound line → 0, which reads as proof the host never republishes the closed tab. That probe was on the push-notification path only. The pull path (workspace.get → getRemoteSnapshot) is the carrier, and it plainly lists the tab at rev 4. A push-path probe alone will exonerate the host every time. Both paths must be sampled before concluding anything about what the host serves.

Structural finding worth its own ticket: toAppSshPtyId is purely connectionId + relayPtyId. When the relay reissues pty-2 the 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.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 the redesign's Phase 3 deletes).

src/shared/closed-terminal-tab-tombstones.ts, 99 lines:

  • Recorded only on 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's user || cleanup.
  • Suppresses a host-sourced tab only when 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.
  • 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. It 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 exactly 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:

isSuppressedByClose forced to false, --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  ← resurrection reproduces on demand

suppression ON, five runs + one independent run by a second agent:
  0 occurrences of "resurrected the closed tab"

Provenance verified positively, not by mtime. closedTerminalTabTombstonesByTabId appears 13× across 3 renderer chunks including store-Do3KBvRE.js. For every red control run, mayCreate appeared 0× in out/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 different store-* chunk. The check was wrong, not the build.)

At the unit layer, disabling the same predicate:

 FAIL  remote-workspace-session-merge-close-tombstones.test.ts > does not re-insert a tombstoned tab the host still lists
 FAIL  … > does not re-add a tombstoned tab through the host-unknown branch
 FAIL  … > suppresses only the tombstoned tab, leaving its siblings and the pointers alone
      Tests  3 failed | 39 passed (42)

Restored:

 Test Files  4 passed (4)      Tests  24 passed (24)    # the four tombstone suites
 Test Files 41 passed (41)     Tests 287 passed (287)   # + workspace-session, terminal store, remote-workspace, profiles

$ pnpm tc → clean
$ pnpm test config/scripts/pr-e2e-gate-contract.test.mjs → 36 passed
$ pnpm run check:code-quality:changed → 0 new findings across 55 changed files
$ node config/scripts/check-max-lines-ratchet.mjs → OK, no new bypasses

The oracle spec: GREEN in the full lane

Both oracle tests pass at the stack tip. Full Docker-SSH lane at 49bb96e0b4c, clean tree:

BUILD_SHA=49bb96e0b4c135ce305a2f4dfe2d4b52e0b19cde   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] ssh-lost-kill-tab-resurrection.spec.ts:178 › does not resurrect tabs whose kill was lost to a killed relay daemon   PASSED
[13/20] ssh-lost-kill-tab-resurrection.spec.ts:190 › does not resurrect tabs closed while the host is disconnected          PASSED

grep -c "resurrected the closed tab"  (whole lane)  → 0

Note that the oracle passes without PR 7 in the build — mayCreate=3 confirms #16751's fence is present, and SshPtyAbsentFromRelayError is 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

Defect Status
Bug 1 The closed tab resurrects on reconnect This PR fixes it — oracle green, A/B below
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 PR 7 — nwparker/ssh-07-absent-from-relay. Not required for this PR's oracle to pass
Bug 3 After the daemon is killed and the client launches a replacement, the client's own SSH transport drops and does not complete a reconnect inside 60s — no "delay step 2/9", no handshake failure, nothing. ssh-connection.ts:1533 only logs on an SSH-level close Unfixed, own ticket. Cause of test 1's intermittent setup failure in isolation

The isolating discriminator for bug 3

[ssh-relay] Socket probe result: reads "DEAD" on every cycle of test 1 (daemon killed, client must launch a NEW relay) and "ALIVE" on every cycle of test 2 (daemon survived, client reconnects to the existing socket). Whenever a new daemon must be launched, the SSH transport drops afterwards and does not recover.

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_EXPIRED rejection is a red herring

It 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, following Relay channel lost …, triggering reconnect and waiting 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-84 theory 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:

isSuppressedByClose forced to false, --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          ← reproduces on demand

suppression ON: 0 occurrences of "resurrected the closed tab" across six runs
                plus the full-lane run above

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 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: createTab honours a caller-supplied id hint (src/renderer/src/store/terminals/terminal-tab-creation.ts:53-65, used by useIpcEvents for host-admitted tabs), so "tab ids are uuids that never recur" is NOT literally true in this codebase. The guarantee rests on closeReason === 'user' being the only writer, plus the live-local-tab check — not on id uniqueness.

Persistence: the tombstone had to survive a relaunch, and did not

closedTerminalTabTombstonesByTabId is declared on WorkspaceSessionState but was missing from workspaceSessionStateSchema — the load boundary for both partitions (normalize-loaded-state-collections.ts for local, 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 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.ts is the ratchet, in both directions: a satisfies 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.ts was one line under its 300-line limit, and max-lines disables and per-file bumps are both forbidden. Two value schemas moved to modules named for their contents — terminal-tab-id-schema.ts and terminal-surface-tombstone-schema.ts — and the closed-tab tombstone's schema is now colocated with its type in closed-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 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, 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 of orderedWorktreeIds and both sweeps cover the whole remote maps. What actually makes it safe is closeTab stripping the id from every worktree row before recording, plus the worktree match, plus closeReason === 'user' being the only writer. Real guarantee, different from the documented one.

Both fixes have failing-first proof:

× does not suppress a host tab whose id collides with an Object.prototype key
× does not suppress a tombstoned id under a DIFFERENT worktree

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:

  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 revert(ssh): back out #13326 and #13928 — reconnect loses every tab #14361 that is the wrong risk; dropped. This also removes the mixed-version regression its own body flags.
  3. Hydration replaces rather than unions 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.

Deliberately NOT done

Risk / blast radius

Renderer-side, client-local, no wire change. Blast radius is mergeDirectSshRemoteWorkspaceSession plus 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.ts records the new field as notRepoScoped / notTransferred residue — keyed by tab id and pruned by neither path, like remoteSessionIdsByTabId — bounded by the same TTL and cap, and a resolved host retires its own entries.

How to 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 src/renderer/src/hooks/remote-workspace-session-merge.ts and run (needs Docker):

pnpm test:e2e:ssh-docker -- tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts --repeat-each=2

End-to-end verification

Specs this PR routes to

$ git diff --name-only nwparker/ssh-05-reattach-fence..nwparker/ssh-06-close-tombstone \
    | node config/scripts/pr-e2e-source-routing.mjs
["tests/e2e/paired-remote-pane-layout-retry.spec.ts",
 "tests/e2e/ssh-cold-activation-restore.spec.ts",
 "tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts",
 "tests/e2e/ssh-reconnect-tab-destruction.spec.ts",
 "tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts"]

$ … | node config/scripts/pr-e2e-source-routing.mjs --ssh-source
true

Under main's router this routed to 3; #16746 adds ssh-cold-activation-restore and ssh-reconnect-tab-destruction — the two specs that guard this exact regression class. ssh-lost-kill-tab-resurrection.spec.ts is 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:

$ pnpm test:e2e:ssh-docker
BUILD_SHA=49bb96e0b4c135ce305a2f4dfe2d4b52e0b19cde   DIRTY=0
14 specs / 20 tests → 17 passed, 2 failed, 1 skipped (10.7m)

[12/20] ssh-lost-kill-tab-resurrection.spec.ts:178 › does not resurrect tabs whose kill
        was lost to a killed relay daemon                                      PASSED
[13/20] ssh-lost-kill-tab-resurrection.spec.ts:190 › does not resurrect tabs closed
        while the host is disconnected                                         PASSED

grep -c "resurrected the closed tab"  (whole lane)  → 0

✅ ssh-lost-kill-tab-resurrection.spec.ts — both tests PASSED at the stack tip.

Both [12/20] (killed relay daemon) and [13/20] (orderly disconnect) passed, and grep -c "resurrected the closed tab" over the whole lane returns 0. It passed without PR 7 in the build, so bug 2's fix is not required for it.

One caveat, so nobody is surprised: test 1 fails intermittently in isolated single-spec runs, where a separate unfixed defect (bug 3 — the client's SSH transport not reconnecting after a replacement relay daemon is launched) blocks its cycle-2 setup. The resurrection assertion itself has never failed with this fix in place. A reviewer who runs the spec alone and sees red is looking at bug 3, not at this fix. Full breakdown in "The oracle spec: GREEN in the full lane" above.

The two lane failures, resolved — and one is now exempted:

Spec main tip (isolated) tip (full lane) Outcome
ssh-docker-bulk-open-freeze-repro FAILED — harness TypeError: … reading 'workerIndex' at docker-ssh-relay-target.ts:226 — FAILED Not a flake — a 100% failure, and three further arity bugs behind it. Now exempted from the lane; repair tracked in #16764
ssh-port-forward-lifecycle PASSED PASSED (59.6s) FAILED at ssh-port-forward-lifecycle-evidence.ts:159 waiting on getByText('Ports') Flaky in-lane, not a regression

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 @headful spec and runs last. Called flaky in-lane rather than "unrelated": a real lane-ordering problem, pre-existing, and worth tracking.

Note on the recorded run: the 14-spec result above predates the bulk-open exemption. The lane now runs 13 specs; bulk-open is not among them. The other 13 results are unaffected — nothing about that spec's failure changes another's outcome, since the runner passes them all to one Playwright invocation with --workers=1 and each spec owns its own fixture container.

Neither is in this PR's routed spec set.

Build provenance

closedTerminalTabTombstonesByTabId is a new identifier — 0 occurrences in main's source:

$ cat out/renderer/assets/*.js | grep -c closedTerminalTabTombstonesByTabId
13          # App-CZkf3Bu7.js:6, store-uJWnDUOY.js:5, quick-commands-menu-events-SBDd6cXN.js:2

Measured on the lane build:

BUILD_SHA=49bb96e0b4c135ce305a2f4dfe2d4b52e0b19cde   DIRTY=0
tombstone=13   hasLocalTabsRow=2   hostAuthority=4   mayCreate=3

tombstone=13 is this PR's symbol; the other three prove the levels beneath it are in the same build. SshPtyAbsentFromRelayError is absent, confirming PR 7 is not present — so the green oracle above is not borrowing bug 2's fix.

Provenance trap, reproduced on this tree. Do not grep a single renderer chunk. grep -c <sym> out/renderer/assets/store-*.js | head -1 matched store-DtDSfs7_.js and reported 0 for a symbol present 13 times across store-uJWnDUOY.js, App-CZkf3Bu7.js and quick-commands-menu-events-SBDd6cXN.js. Always use cat out/renderer/assets/*.js | grep -c <sym>.

Also: renderer console.warn never reaches the app log. Only main-process stdio is forwarded by ORCA_E2E_FORWARD_APP_LOGS=1.

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.ts calls a dumpAuthority helper that logs topologyRev read through window.api.session.get(). terminalTopologyRevisionByRepoId is declared hostPrivate (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 print topologyRev: 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

  • Bug 3 — the SSH transport that does not reconnect after a replacement daemon is launched. Unfixed, out of scope, own ticket. It does not stop the oracle passing in the full lane, but it makes test 1 intermittent in isolation. Discriminator (measured in the isolated runs, not re-confirmed in the lane): [ssh-relay] Socket probe result: is "DEAD" on every cycle of test 1 and "ALIVE" on every cycle of test 2.
  • Bug 2 — the error-class rewrite at ssh-pty-session-reattach.ts:227-231, which flattens the relay's PTY "pty-1" not found into a bare SSH_SESSION_EXPIRED so attachStablePaneOwner:242's correct fallback never fires. Owned by nwparker/ssh-07-absent-from-relay, not this PR.
  • Five candidate fix locations were eliminated by measurement or reader analysis, including the one a reviewer is most likely to reach for (kill.ts:82-84). Each is tabulated with its disproof under Eliminated candidates so the trip does not get re-walked.
  • The orderly-disconnect path was never broken and is included only as the negative control that bounds the trigger.
  • Growth is 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.
  • The repro uses a killed relay daemon, which is more violent than the disconnect→close→reconnect path most users hit. The orderly variant does not reproduce, so the real-world trigger is specifically ungraceful loss — narrower than "any reconnect", and the fix is justified on that basis.
  • The tombstone is client-local and never reconciled across clients. A second client that never saw the close will still show the tab. Deliberate: making it cross the wire is exactly the fix(remote-workspace): stop closed SSH terminal tabs from resurrecting — add close tombstones #16571 divergence dropped here, because a host-sourced tombstone deleting a local tab is the wrong risk after revert(ssh): back out #13326 and #13928 — reconnect loses every tab #14361.
  • STA-3593 (host tabs never reaching the store) and the partition split-brain (SSH host session partitions are written but never read — tab lists round-trip as empty and remote sync permanently deletes them #12721/Renderer and runtime disagree on which partition owns SSH worktree session state #12723) are untouched.
  • createTab honours 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 on closeReason === '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 isSuppressedByClose to false (one character):

--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          ← reproduces on demand

suppression ON, five runs + one independent run:
  0 occurrences of "resurrected the closed tab"

unit, same predicate disabled:

 FAIL  …close-tombstones.test.ts > does not re-insert a tombstoned tab the host still lists
 FAIL  …close-tombstones.test.ts > does not re-add a tombstoned tab through the host-unknown branch
 FAIL  …close-tombstones.test.ts > suppresses only the tombstoned tab, leaving its siblings and the pointers alone
      Tests  3 failed | 39 passed (42)

Restored: 42 passed; 287 across the workspace-session, terminal-store, remote-workspace, shared-tombstone and profile suites.

@nwparker
nwparker force-pushed the nwparker/ssh-06-close-tombstone branch from 49bb96e to 917f192 Compare August 27, 2026 09:28
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from 546005d to 20db4da Compare August 27, 2026 09:49
@nwparker
nwparker force-pushed the nwparker/ssh-06-close-tombstone branch from 917f192 to 03d73fb Compare August 27, 2026 09:49
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from 20db4da to e9afc48 Compare August 27, 2026 09:53
@nwparker
nwparker force-pushed the nwparker/ssh-06-close-tombstone branch 2 times, most recently from 5ac2552 to dde7ca5 Compare August 27, 2026 10:02
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from e9afc48 to 562a6ce Compare August 27, 2026 10:07
@nwparker
nwparker force-pushed the nwparker/ssh-06-close-tombstone branch from dde7ca5 to bf0b963 Compare August 27, 2026 10:07
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from 562a6ce to c65bd84 Compare August 27, 2026 10:10
@nwparker
nwparker force-pushed the nwparker/ssh-06-close-tombstone branch from bf0b963 to 92de673 Compare August 27, 2026 10:10
@nwparker
nwparker force-pushed the nwparker/ssh-05-reattach-fence branch from c65bd84 to 1a69ed3 Compare August 28, 2026 02:45
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
nwparker force-pushed the nwparker/ssh-06-close-tombstone branch from 92de673 to f450562 Compare August 28, 2026 02:46
@nwparker
nwparker changed the base branch from nwparker/ssh-05-reattach-fence to main August 28, 2026 02:47
@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 54 minutes.

View limit details

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

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1cb082e6-96cc-4ea0-95e0-6a260ee40a53

📥 Commits

Reviewing files that changed from the base of the PR and between a7b1da9 and f450562.

📒 Files selected for processing (29)
  • config/scripts/run-ssh-docker-e2e.mjs
  • src/main/orca-profiles/profile-project-session-field-disposition.ts
  • src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts
  • src/renderer/src/hooks/remote-workspace-session-merge.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/lib/workspace-session-browser-history.test.ts
  • src/renderer/src/lib/workspace-session-closed-tab-tombstones.test.ts
  • src/renderer/src/lib/workspace-session-closed-tab-tombstones.ts
  • src/renderer/src/lib/workspace-session-editor-drafts.test.ts
  • src/renderer/src/lib/workspace-session-host-field-ownership.ts
  • src/renderer/src/lib/workspace-session-host-split.ts
  • src/renderer/src/lib/workspace-session-liveness.test.ts
  • src/renderer/src/lib/workspace-session-patch.ts
  • src/renderer/src/lib/workspace-session-relevant-fields.test.ts
  • src/renderer/src/lib/workspace-session.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/renderer/src/store/terminals/terminal-state.ts
  • src/renderer/src/store/terminals/terminal-tab-close-tombstone.test.ts
  • src/renderer/src/store/terminals/terminal-tab-close.ts
  • src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts
  • src/renderer/src/store/terminals/workspace-terminal-hydration.ts
  • src/shared/closed-terminal-tab-tombstones.test.ts
  • src/shared/closed-terminal-tab-tombstones.ts
  • src/shared/terminal-surface-tombstone-schema.ts
  • src/shared/terminal-tab-id-schema.ts
  • src/shared/workspace-session-schema-field-coverage.test.ts
  • src/shared/workspace-session-schema.ts
  • src/shared/workspace-session-state-types.ts
  • tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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)
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`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant