Repository navigation
fix(ssh): let an expired lease reattach its orphan instead of stranding it - #17965
Conversation
There was a problem hiding this comment.
Caution
This PR removes the wrong safeguard. expired does double duty — "client lost its route" and "relay id was recycled onto a different shell" — and the change keeps bindings for both, but only carves out the supersession producer. The relay-id-recycled writer (ssh-pending-pty-kill-replay.ts) and the relay-reset writer (doResetRelay) previously relied on markSshRemotePtyLease(..., 'expired') clearing the persisted binding to keep the pane off whatever process now holds the recycled id, and the adoption path that now re-attaches has no identity fence for SSH.
Reviewed changes
leaseStateWithdrawsBinding—ssh-pty-lease-operations.tsgates bothshouldClearBindingssites onterminatedonly, soexpiredno longer clears bindings.supersedeSiblingLeasesForPanekeeps its own explicitclearBindingsForLeases(supersession still scrubs).sshRemotePtyLeaseWithdrawsBinding—terminal-binding-recovery.tsmakesisRestorablePtyBinding/hasRestorableSshRemotePtyLeasetreatexpiredas restorable.- Tests — retargets the clear-on-expired cases to
terminated, addsexpired-retention counterparts, and pins both directions inssh-expired-lease-pane-readoption.test.ts.
🚨 Recycled IDs re-enter the unfenced adoption path
The expired state is written by three distinct producers, and only one of them is safe to re-place a binding on two of them is the exact "different shell" case the codebase guards elsewhere.
supersedeSiblingLeasesForPane clears its superseded bindings explicitly, so it is fine. But:
ssh-pending-pty-kill-replay.tsretire(..., 'relay-id-recycled')marksexpiredspecifically because "leaving this lease active hands the user's old pane to whatever process now holds the recycled id." Its in-code comment documents that the reattach filter plus the binding clear are what keep the pane off the recycled shell. This change deletes the binding-clear half and does not replace it.doResetRelay(ssh-connection-handlers.ts:68-71) force-kills the relay onssh:resetRelayand marks every non-terminated/non-expired leaseexpired; it clears provider state and ownership but not the persisted pane binding. Previously theexpiredwrite did that. Now the stale binding survives into the fresh relay, whose PTYs renumber frompty-1(see the NOTE already atssh-pty-lease-operations.ts:134-138).
The orphan recovery this PR relies on goes through adoptStablePane → attachStablePaneOwner → provider.spawn({ attachOnly: true, sessionId: owner.ptyId }). That path never reads lease state (resolvePersistedStablePaneOwner reads only tabsByWorktree/terminalLayoutsByTabId, see stable-owner.ts:34-64), and it forwards no identity fence to the SSH attach: attachStablePaneOwner's spawnOptions are only { cols, rows, cwd }, so reattachSshPtySession receives no paneKey/tabId/env, and expectedIncarnationId is ignored by the SSH attach path (the relay's pty.attach relies on expectedPaneKey/expectedTabId, which the relay-session reattach path supplies via expectedIdentityForLease but adoption does not). The post-attach check at stable-owner.ts:269-277 compares result.incarnationId against owner.runtimeIncarnationId, which is empty after an app restart, so a recycled id binds silently.
Consequence: after a relay reset (or the relay-id-recycled retirement), a restored pane re-attaches to a different shell than it previously owned — the 2→19→20 fan-out / wrong-shell binding this class of guard exists to prevent. The pre-PR behavior converged to a fresh spawn (correct); the post-PR behavior binds the wrong process.
Technical details
# Recycled relay id re-enters adoption path after binding retention
## Affected sites
- `src/main/persistence/leasing-ssh-ptys/ssh-pty-lease-operations.ts:104-106` — `leaseStateWithdrawsBinding` returns `terminated` only; the clear-on-`expired` that the `relay-id-recycled` and reset writers relied on is gone.
- `src/main/ssh/ssh-pending-pty-kill-replay.ts:50-55` — `relay-id-recycled` → `expired`, comment documents the binding-clear as the pane-facing guard.
- `src/main/ipc/ssh-connection-handlers.ts:68-71` — `doResetRelay` marks leases `expired` without clearing the persisted binding.
- `src/main/ipc/pty/pane/stable-owner.ts:212-233` — `attachStablePaneOwner` forwards no `paneKey`/`tabId`/`env`; `expectedIncarnationId` is only consumed by the local daemon resolver, not the SSH attach.
- `src/main/providers/ssh-pty-session-reattach.ts:192-213` — SSH `pty.attach` fenced only by `expectedPaneKey`/`expectedTabId`, which adoption does not set.
## Required outcome
- A restored pane must never bind a recycled relay id onto a different shell. Either (a) split the recycled-id/reset writers out of `expired` into a state that still withdraws the binding (or a `supersededBy`/recycled marker), or (b) make the adoption path consult lease state / forward a relay-enforced identity fence (persisted incarnation or `expectedPaneKey`+`expectedTabId`) for SSH re-attach so a recycled id is rejected rather than bound.
## Open questions for the human
- Is the relay-reset path (`doResetRelay`) in scope for this fix, or is reset expected to leave no pane to restore?
- Does the relay's `pty.attach` accept and enforce an `expectedIncarnationId` (or a persisted-incarnation variant of `expectedPaneKey`) that adoption could forward, or does the split-state approach remain the only lever?DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| * Supersession is the one place `expired` still scrubs a binding, and it does so explicitly in | ||
| * `supersedeSiblingLeasesForPane`: there a NEWER lease for the same pane is the evidence. | ||
| */ | ||
| function leaseStateWithdrawsBinding(state: SshRemotePtyLease['state']): boolean { |
There was a problem hiding this comment.
Making leaseStateWithdrawsBinding return terminated only removes the clear-on-expired that two non-supersession writers depended on as their pane-facing guard: retire(..., 'relay-id-recycled') in ssh-pending-pty-kill-replay.ts and doResetRelay in ssh-connection-handlers.ts. Those mark expired precisely because the relay id was recycled / the relay was killed, and the retained binding then reaches attachStablePaneOwner, whose SSH attach carries no identity fence (no paneKey/tabId/env, expectedIncarnationId ignored by the SSH path). The supersession carve-out below is documented, but these two producers are not.
There was a problem hiding this comment.
Reviewed changes
deferred-session-reattach-connect.ts— merges the twopty-connect-limitsimports into one line (base lint fix). Pure import consolidation; no behavior change.
No new findings in this delta. The [!CAUTION] concern from the prior pullfrog review is unchanged and still stands — b085c98 does not touch the SSH lease/attach path it covers.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
cee0f16 to
e3007b9
Compare
7bd3d08 to
037e6b1
Compare
e3007b9 to
3b63dd8
Compare
… the pane `expired` never means the remote shell exited. Every writer records that the CLIENT lost its route — a superseded sibling, a recycled relay id, a persistPtyBinding refusal made *after* pty.attach proved the shell alive, a failed reattach indistinguishable from a relay restart, a relay reset whose kill may not have landed. docs/reference/ssh-execution-boundary.md grades all of those `unverifiable`. Three readers treated it as death, and together they made the pane unable to reach a process that is still running: - `isRestorablePtyBinding` / `hasRestorableSshRemotePtyLease` refused to replay a durable binding a renderer snapshot had omitted. - `markSshRemotePtyLease(s)` wiped the persisted pane->pty binding, which is what makes `resolvePersistedStablePaneOwner` return null, `adoptStablePane` give up, and `createTerminal` cold-spawn a replacement. The user's terminal comes back empty and the running job is orphaned and invisible. Only `terminated` now withdraws a binding: it is the operator-close state (`ssh:terminateSessions`) and the one written after a host-acknowledged stop. This authorizes a reattach ATTEMPT, never a respawn, so #17957's gates are untouched and in fact fire less often — where the pane previously went straight to a fresh spawn it now attaches first. A genuinely dead shell still converges: `attachStablePaneOwner` retires the binding on `isPtyAlreadyGoneError` (the relay's own absence answer, not a message match) and falls through to a fresh spawn, so no pane retries forever. Supersession keeps its own binding scrub in `supersedeSiblingLeasesForPane`, where a NEWER lease for the same pane is the evidence — the 2 -> 19 -> 20 reattach fan-out stays fixed.
037e6b1 to
b2ecc7f
Compare
…tell them apart `expired` was one word doing two unrelated jobs — "a newer lease won this pane" and "reattach lost contact" — so `reattachKnownPtys` had to exclude all of them. That kept the 2 -> 19 -> 20 fan-out fixed at the cost of never bulk-reattaching a genuine orphan; those recovered only through the slower `adoptStablePane` path. The blocker cited in #17965 does not apply. The STA-3077 note guards `upsertSshRemotePtyLease`'s match against a RECYCLED `pty-N` after a relay restart. `supersedeSiblingLeasesForPane` is a different path and already holds `winner.ptyId` when it expires a predecessor, so recording which lease won needs no relay-start identity. `SshRemotePtyLease` gains two optional marks, each meaning exactly one thing: - `supersededBy` — the winner's stored-form ptyId, written only by supersession. - `relayIdRecycled` — written only by the pending-stop replay's `relay-id-recycled` retirement. That retirement wrote `expired` *purely* to keep the lease out of the reattach that runs one step later ("hands the user's old pane to whatever process now holds the recycled id"), and the reattach fences on paneKey/tabId, never on incarnation. Relaxing the filter without this would have silently reopened that hole. Bulk reattach now skips a lease carrying either mark and re-adopts the rest, via one shared `sshRemotePtyLeaseAllowsReattach`. `terminated` is untouched. Recycled-id safety: both marks are dropped whenever the id is re-upserted `attached`/`detached`, so a relay that renumbered onto a new shell cannot inherit its predecessor's mark. Supersession also stamps an ALREADY-expired predecessor for the same pane — same evidence, and it is what bounds the reattach set, since otherwise every past orphan for that pane would stay reattachable forever. Its `updatedAt` deliberately stays put: bumping it would make a stale lease look recent to `getRecentExpiredSshLease`. Persistence: the lease loader is a strict whitelist, so both fields are named in `normalizeSshRemotePtyLease` or they would be stripped on every launch. Absence reads as "orphan", which is the only thing an older build could have meant, and an older build ignores keys it has never heard of (remote-wire Rule 1).
…tell them apart (#17966) `expired` was one word doing two unrelated jobs — "a newer lease won this pane" and "reattach lost contact" — so `reattachKnownPtys` had to exclude all of them. That kept the 2 -> 19 -> 20 fan-out fixed at the cost of never bulk-reattaching a genuine orphan; those recovered only through the slower `adoptStablePane` path. The blocker cited in #17965 does not apply. The STA-3077 note guards `upsertSshRemotePtyLease`'s match against a RECYCLED `pty-N` after a relay restart. `supersedeSiblingLeasesForPane` is a different path and already holds `winner.ptyId` when it expires a predecessor, so recording which lease won needs no relay-start identity. `SshRemotePtyLease` gains two optional marks, each meaning exactly one thing: - `supersededBy` — the winner's stored-form ptyId, written only by supersession. - `relayIdRecycled` — written only by the pending-stop replay's `relay-id-recycled` retirement. That retirement wrote `expired` *purely* to keep the lease out of the reattach that runs one step later ("hands the user's old pane to whatever process now holds the recycled id"), and the reattach fences on paneKey/tabId, never on incarnation. Relaxing the filter without this would have silently reopened that hole. Bulk reattach now skips a lease carrying either mark and re-adopts the rest, via one shared `sshRemotePtyLeaseAllowsReattach`. `terminated` is untouched. Recycled-id safety: both marks are dropped whenever the id is re-upserted `attached`/`detached`, so a relay that renumbered onto a new shell cannot inherit its predecessor's mark. Supersession also stamps an ALREADY-expired predecessor for the same pane — same evidence, and it is what bounds the reattach set, since otherwise every past orphan for that pane would stay reattachable forever. Its `updatedAt` deliberately stays put: bumping it would make a stale lease look recent to `getRecentExpiredSshLease`. Persistence: the lease loader is a strict whitelist, so both fields are named in `normalizeSshRemotePtyLease` or they would be stripped on every launch. Absence reads as "orphan", which is the only thing an older build could have meant, and an older build ignores keys it has never heard of (remote-wire Rule 1).
`getRecentExpiredSshLease` compared the stored lease ptyId (relay form, written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never held and `recoverTerminalPane` refused every real SSH pane. Normalize with the same tolerant helper the binding reader already uses, now shared as `toComparableRelaySshPtyId`. Switching the path on is only safe on top of #17957 (respawn gated on the runtime liveness verdict), #17965 (`expired` no longer withdraws bindings) and #17966 (supersession and id recycling carry their own marks). `recoverTerminalPane` additionally refuses a lease those marks disqualify, so it acts only on an `expired` lease that means "reattach gave up". The path's outcome is a reattach, not a respawn: `createTerminal` calls `adoptStablePane` first, which attaches attach-only to the retained binding and only falls through to a fresh shell once the host itself answers that the PTY is absent.
…17969) `getRecentExpiredSshLease` compared the stored lease ptyId (relay form, written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never held and `recoverTerminalPane` refused every real SSH pane. Normalize with the same tolerant helper the binding reader already uses, now shared as `toComparableRelaySshPtyId`. Switching the path on is only safe on top of #17957 (respawn gated on the runtime liveness verdict), #17965 (`expired` no longer withdraws bindings) and #17966 (supersession and id recycling carry their own marks). `recoverTerminalPane` additionally refuses a lease those marks disqualify, so it acts only on an `expired` lease that means "reattach gave up". The path's outcome is a reattach, not a respawn: `createTerminal` calls `adoptStablePane` first, which attaches attach-only to the retained binding and only falls through to a fresh shell once the host itself answers that the PTY is absent.
#17965 authorized reattach from `expired` but the state machine refused the transition back, so a lease that reattached and proved itself alive stayed `expired` forever. That silently exempted a demonstrably running remote shell from `ssh:reset` (skips `expired`), from the SSH_TERMINATE_RECONNECT_REQUIRED ownership fence in `ssh:terminateSessions` (marks it not-owned), and from the quit-time `detached` sweep, and made it permanently ineligible to win supersession so its own successors never retired their predecessors. Only the id-qualified caller carries per-pty proof: markSshRemotePtyLeases AttachedAsync is fed the relay's `attachedLeaseIds`, so an unqualified bulk mark over a whole target still cannot revive `expired`. `terminated` stays absorbing. Re-entering `attached` drops supersededBy/relayIdRecycled, since route retirement belongs to the shell that lost the pane and this one just proved it is not that shell — the same invariant upsertSshRemotePtyLease enforces.
…and unstick expired leases (#18013) * fix(ssh): match an expired lease on where its leaf lives now, not its frozen tab A lease freezes tabId at write time, but detachTerminalPaneToTab moves a live pane, so the stored tab is the one the pane LEFT. getRecentExpiredSshLease required lease.tabId === tabId, which is wrong in both directions: a viewer on a stale mirror matched under the abandoned coordinates (and resolvePersistedStable PaneOwner then reads an empty layout for that tab, so adoptStablePane is skipped entirely and a fresh shell is spawned over a possibly-live one, binding the same leaf in two tabs), while a viewer using the pane's real coordinates matched nothing and got terminal_not_recoverable. Resolve the leaf's current tab the way restoreReattachedPtyRuntime already does and compare against that, falling back to the frozen tabId only when nothing can say where the leaf lives. Both workspace partitions are read because SSH spawns bind into ssh:<target> while reattach binds into local. * fix(ssh): let a proven reattach take an expired lease back to attached #17965 authorized reattach from `expired` but the state machine refused the transition back, so a lease that reattached and proved itself alive stayed `expired` forever. That silently exempted a demonstrably running remote shell from `ssh:reset` (skips `expired`), from the SSH_TERMINATE_RECONNECT_REQUIRED ownership fence in `ssh:terminateSessions` (marks it not-owned), and from the quit-time `detached` sweep, and made it permanently ineligible to win supersession so its own successors never retired their predecessors. Only the id-qualified caller carries per-pty proof: markSshRemotePtyLeases AttachedAsync is fed the relay's `attachedLeaseIds`, so an unqualified bulk mark over a whole target still cannot revive `expired`. `terminated` stays absorbing. Re-entering `attached` drops supersededBy/relayIdRecycled, since route retirement belongs to the shell that lost the pane and this one just proved it is not that shell — the same invariant upsertSshRemotePtyLease enforces. * fix(ssh): make the pane-recovery liveness gate refuse without positive evidence of life The gate refused only `live` and `unverifiable` and passed on `null` — but the register is an in-memory Map, so `null` is equally what a fresh app start, a never-asked host and a certified death look like. Absence of evidence was reading as authorization to spawn a shell over a possibly-live remote process: `!pty.connected` is cleared for every PTY a dropped relay owned, and `expired` only ever says the CLIENT lost its route. - `exited` is now RETAINED rather than deleted, so the register is three-valued in the map as well as in the type. Its one writer is a host-delivered exit frame — an exit with a real code, or an explicit `hostExitConfirmed` — which records the certificate instead of merely dropping the doubt. - `recoverTerminalPane` refuses on `live` and `unverifiable`, and deliberately does NOT demand a positive `exited`. The only answer that ever reaches this gate is a reachable relay reporting no such id, and that is a union: pty.attach throws not-found for an unknown id with no liveness check, and a relay restart makes every previously minted id unknown (ids carry a per-start `ptyIdMintEpoch`). No writer of `exited` co-occurs with a reattachable `expired` lease either — a host-delivered exit frame tombstones the lease `terminated` — so requiring one would close the gate permanently. - `handlePtyReattachFailure`'s not-found branch publishes `code: -1` to the renderer and does not call `runtime.onPtyExit`. The relay's not-found answer is not a death certificate, and #17963's ratchet on the same branch pins that. - The inventory's `observed === false` hunk keeps dropping doubt rather than asserting a death: `pty.listProcesses` returns the relay's CURRENT session map, so a restarted relay omits every previously minted id whether or not those shells died — the same union, one hop away. A live or unprovable pane refuses; a disowned one still recovers. No wire change. The gate's ratchets live in terminal-pane-recovery-liveness-gate.test.ts: config/vitest.config.ts — the config CI runs — matches only `*.test.ts`, so cases placed under orca-runtime-tests/*.spec.ts would never execute. * fix(ssh): gate paired-viewer pane recovery on the narrowed session-gone predicate isSshSessionGoneError landed on the IPC transport, which never calls terminal.recoverPane. The one caller that does — recoverExpiredHostPane in the paired-viewer transport — still triggered on a bare SSH_SESSION_EXPIRED substring, so the identity-mismatch reply (the relay found a LIVE PTY under that id owned by another pane, which is evidence of presence) still asked the HUB to replace the pane, putting a second agent on one transcript. Main already refuses the respawn on that same reply; this makes the two agree. A pane whose shell genuinely died is unaffected: plain SSH_SESSION_EXPIRED still matches. The mismatch reply now surfaces as an error instead of a respawn. * test(persistence): update the reattach ratchet for expired-lease reclaim markSshRemotePtyLeasesAttachedAsync is id-qualified, so a named pty that proved itself alive now returns to attached instead of staying expired.
…ng it (stablyai#17965) * fix(ssh): let an expired lease permit a reattach instead of unbinding the pane `expired` never means the remote shell exited. Every writer records that the CLIENT lost its route — a superseded sibling, a recycled relay id, a persistPtyBinding refusal made *after* pty.attach proved the shell alive, a failed reattach indistinguishable from a relay restart, a relay reset whose kill may not have landed. docs/reference/ssh-execution-boundary.md grades all of those `unverifiable`. Three readers treated it as death, and together they made the pane unable to reach a process that is still running: - `isRestorablePtyBinding` / `hasRestorableSshRemotePtyLease` refused to replay a durable binding a renderer snapshot had omitted. - `markSshRemotePtyLease(s)` wiped the persisted pane->pty binding, which is what makes `resolvePersistedStablePaneOwner` return null, `adoptStablePane` give up, and `createTerminal` cold-spawn a replacement. The user's terminal comes back empty and the running job is orphaned and invisible. Only `terminated` now withdraws a binding: it is the operator-close state (`ssh:terminateSessions`) and the one written after a host-acknowledged stop. This authorizes a reattach ATTEMPT, never a respawn, so stablyai#17957's gates are untouched and in fact fire less often — where the pane previously went straight to a fresh spawn it now attaches first. A genuinely dead shell still converges: `attachStablePaneOwner` retires the binding on `isPtyAlreadyGoneError` (the relay's own absence answer, not a message match) and falls through to a fresh spawn, so no pane retries forever. Supersession keeps its own binding scrub in `supersedeSiblingLeasesForPane`, where a NEWER lease for the same pane is the evidence — the 2 -> 19 -> 20 reattach fan-out stays fixed. * test(persistence): split SSH remote PTY binding partition cases into their own file
…tell them apart (stablyai#17966) `expired` was one word doing two unrelated jobs — "a newer lease won this pane" and "reattach lost contact" — so `reattachKnownPtys` had to exclude all of them. That kept the 2 -> 19 -> 20 fan-out fixed at the cost of never bulk-reattaching a genuine orphan; those recovered only through the slower `adoptStablePane` path. The blocker cited in stablyai#17965 does not apply. The STA-3077 note guards `upsertSshRemotePtyLease`'s match against a RECYCLED `pty-N` after a relay restart. `supersedeSiblingLeasesForPane` is a different path and already holds `winner.ptyId` when it expires a predecessor, so recording which lease won needs no relay-start identity. `SshRemotePtyLease` gains two optional marks, each meaning exactly one thing: - `supersededBy` — the winner's stored-form ptyId, written only by supersession. - `relayIdRecycled` — written only by the pending-stop replay's `relay-id-recycled` retirement. That retirement wrote `expired` *purely* to keep the lease out of the reattach that runs one step later ("hands the user's old pane to whatever process now holds the recycled id"), and the reattach fences on paneKey/tabId, never on incarnation. Relaxing the filter without this would have silently reopened that hole. Bulk reattach now skips a lease carrying either mark and re-adopts the rest, via one shared `sshRemotePtyLeaseAllowsReattach`. `terminated` is untouched. Recycled-id safety: both marks are dropped whenever the id is re-upserted `attached`/`detached`, so a relay that renumbered onto a new shell cannot inherit its predecessor's mark. Supersession also stamps an ALREADY-expired predecessor for the same pane — same evidence, and it is what bounds the reattach set, since otherwise every past orphan for that pane would stay reattachable forever. Its `updatedAt` deliberately stays put: bumping it would make a stale lease look recent to `getRecentExpiredSshLease`. Persistence: the lease loader is a strict whitelist, so both fields are named in `normalizeSshRemotePtyLease` or they would be stripped on every launch. Absence reads as "orphan", which is the only thing an older build could have meant, and an older build ignores keys it has never heard of (remote-wire Rule 1).
…tablyai#17969) `getRecentExpiredSshLease` compared the stored lease ptyId (relay form, written through `toStoredPtyId` -> `toRelaySshPtyId`) raw against the runtime's app-form `pty.ptyId`, so `'pty-3' === 'ssh:target@@pty-3'` never held and `recoverTerminalPane` refused every real SSH pane. Normalize with the same tolerant helper the binding reader already uses, now shared as `toComparableRelaySshPtyId`. Switching the path on is only safe on top of stablyai#17957 (respawn gated on the runtime liveness verdict), stablyai#17965 (`expired` no longer withdraws bindings) and stablyai#17966 (supersession and id recycling carry their own marks). `recoverTerminalPane` additionally refuses a lease those marks disqualify, so it acts only on an `expired` lease that means "reattach gave up". The path's outcome is a reattach, not a respawn: `createTerminal` calls `adoptStablePane` first, which attaches attach-only to the retained binding and only falls through to a fresh shell once the host itself answers that the PTY is absent.
…and unstick expired leases (stablyai#18013) * fix(ssh): match an expired lease on where its leaf lives now, not its frozen tab A lease freezes tabId at write time, but detachTerminalPaneToTab moves a live pane, so the stored tab is the one the pane LEFT. getRecentExpiredSshLease required lease.tabId === tabId, which is wrong in both directions: a viewer on a stale mirror matched under the abandoned coordinates (and resolvePersistedStable PaneOwner then reads an empty layout for that tab, so adoptStablePane is skipped entirely and a fresh shell is spawned over a possibly-live one, binding the same leaf in two tabs), while a viewer using the pane's real coordinates matched nothing and got terminal_not_recoverable. Resolve the leaf's current tab the way restoreReattachedPtyRuntime already does and compare against that, falling back to the frozen tabId only when nothing can say where the leaf lives. Both workspace partitions are read because SSH spawns bind into ssh:<target> while reattach binds into local. * fix(ssh): let a proven reattach take an expired lease back to attached stablyai#17965 authorized reattach from `expired` but the state machine refused the transition back, so a lease that reattached and proved itself alive stayed `expired` forever. That silently exempted a demonstrably running remote shell from `ssh:reset` (skips `expired`), from the SSH_TERMINATE_RECONNECT_REQUIRED ownership fence in `ssh:terminateSessions` (marks it not-owned), and from the quit-time `detached` sweep, and made it permanently ineligible to win supersession so its own successors never retired their predecessors. Only the id-qualified caller carries per-pty proof: markSshRemotePtyLeases AttachedAsync is fed the relay's `attachedLeaseIds`, so an unqualified bulk mark over a whole target still cannot revive `expired`. `terminated` stays absorbing. Re-entering `attached` drops supersededBy/relayIdRecycled, since route retirement belongs to the shell that lost the pane and this one just proved it is not that shell — the same invariant upsertSshRemotePtyLease enforces. * fix(ssh): make the pane-recovery liveness gate refuse without positive evidence of life The gate refused only `live` and `unverifiable` and passed on `null` — but the register is an in-memory Map, so `null` is equally what a fresh app start, a never-asked host and a certified death look like. Absence of evidence was reading as authorization to spawn a shell over a possibly-live remote process: `!pty.connected` is cleared for every PTY a dropped relay owned, and `expired` only ever says the CLIENT lost its route. - `exited` is now RETAINED rather than deleted, so the register is three-valued in the map as well as in the type. Its one writer is a host-delivered exit frame — an exit with a real code, or an explicit `hostExitConfirmed` — which records the certificate instead of merely dropping the doubt. - `recoverTerminalPane` refuses on `live` and `unverifiable`, and deliberately does NOT demand a positive `exited`. The only answer that ever reaches this gate is a reachable relay reporting no such id, and that is a union: pty.attach throws not-found for an unknown id with no liveness check, and a relay restart makes every previously minted id unknown (ids carry a per-start `ptyIdMintEpoch`). No writer of `exited` co-occurs with a reattachable `expired` lease either — a host-delivered exit frame tombstones the lease `terminated` — so requiring one would close the gate permanently. - `handlePtyReattachFailure`'s not-found branch publishes `code: -1` to the renderer and does not call `runtime.onPtyExit`. The relay's not-found answer is not a death certificate, and stablyai#17963's ratchet on the same branch pins that. - The inventory's `observed === false` hunk keeps dropping doubt rather than asserting a death: `pty.listProcesses` returns the relay's CURRENT session map, so a restarted relay omits every previously minted id whether or not those shells died — the same union, one hop away. A live or unprovable pane refuses; a disowned one still recovers. No wire change. The gate's ratchets live in terminal-pane-recovery-liveness-gate.test.ts: config/vitest.config.ts — the config CI runs — matches only `*.test.ts`, so cases placed under orca-runtime-tests/*.spec.ts would never execute. * fix(ssh): gate paired-viewer pane recovery on the narrowed session-gone predicate isSshSessionGoneError landed on the IPC transport, which never calls terminal.recoverPane. The one caller that does — recoverExpiredHostPane in the paired-viewer transport — still triggered on a bare SSH_SESSION_EXPIRED substring, so the identity-mismatch reply (the relay found a LIVE PTY under that id owned by another pane, which is evidence of presence) still asked the HUB to replace the pane, putting a second agent on one transcript. Main already refuses the respawn on that same reply; this makes the two agree. A pane whose shell genuinely died is unaffected: plain SSH_SESSION_EXPIRED still matches. The mismatch reply now surfaces as an error instead of a respawn. * test(persistence): update the reattach ratchet for expired-lease reclaim markSshRemotePtyLeasesAttachedAsync is id-qualified, so a named pty that proved itself alive now returns to attached instead of staying expired.

Stacked on #17957 — review that first. Closes the reverse expression of the bug #17957 fixed.
ELI5
#17957 stopped Orca respawning a shell that was still alive. This fixes the same conflation pointing the other way: a shell that is still alive gets declared unrestorable, so the pane can never reattach to it. The user's terminal comes back empty and their running job is orphaned — still burning CPU on the remote host, invisible and unreachable.
The cause is one word doing two jobs. The SSH lease state
'expired'never means the shell exited — all 8 writers were audited in this sweep and zero attest exit.ssh-connection-handlers.ts:126already says so: "'expired' records that reattach gave up, never that the remote shell died — those are precisely the orphans." Three readers didn't honor it.An
expiredlease now permits a reattach attempt (exactly what an orphan needs) while still not authorizing a respawn. Those are different actions and the code conflated them.Changes
terminal-binding-recovery.ts—isRestorablePtyBindingandhasRestorableSshRemotePtyLeaseboth now consult onesshRemotePtyLeaseWithdrawsBinding(lease), true only forterminated.ssh-pty-lease-operations.ts:151/:239— bothshouldClearBindingssites now callleaseStateWithdrawsBinding(state),terminated-only.supersedeSiblingLeasesForPane's ownclearBindingsForLeases(line 88). That is the one placeexpiredlegitimately scrubs a binding, because there a newer lease for the same pane is the evidence — so the 2→19→20 lease fan-out fix stays intact.persistence-host-partitioned-sessions.test.tspinned cross-partition clearing onexpired; retargeted toterminated(keeping the cross-partition coverage) and added theexpired-retention counterpart.A genuinely dead shell still cleans up — on stronger evidence than before
Keeping the binding buys a reattach attempt:
adoptStablePane→attachStablePaneOwner→provider.spawn({attachOnly:true}).isPtyAlreadyGoneError(which requiresSshPtyAbsentFromRelayError/isSshPtyNotFoundError, not a message match) →runtime.onPtyExit+retirePersistedStablePaneOwner+ fall through to a fresh spawn.No forever-retry loop, no stuck pane.
Why this cannot regress #17957
The change strictly reduces respawns: where the pane previously found
nulland went straight tocreateTerminal's fresh spawn, it now attaches first.recoverTerminalPane's gates read runtime state, not the persisted binding, and are untouched — as are #17958's id comparison, #17955'sisProvenProcessExit, and the two defects in #17962/#17963.User-facing regressions
None expected. Negative controls pin every unchanged behavior, green before and after:
terminatedstill clears bindings — single writer, bulk writer, both host partitions.terminatedstill blocks binding replay;drops the persisted owner after the lease is terminatedstill passes, so an operator close still goes null.stable-pane-relay-absence-respawn.test.ts(8) — dead shell retires + respawns; lost link / timeout / unverifiable daemon cleanup keep the binding and refuse to respawn.ssh-reattach-pane-cardinality.test.ts(15) — supersession, andholds the live lease count flat across ten reconnects.orca-runtime.test.ts(1223) — includes fix(ssh): stop respawning panes on client-side-only absence evidence #17957's gates and the pinneddoes not recover a pane whose authoritative SSH lease was terminated.Testing
Fail-before, verbatim:
Pass-after:
Test Files 8 passed (8) / Tests 1306 passed | 1 skipped (1307).tc:nodeandtc:webclean;check:code-quality:changed0 new findings across 24 files.Full-repo sweeps show 6 pre-existing/load-related failures in unrelated subsystems (
run-electron-vite-dev,git-admission-storm-measurement,git-command-timeout-behavior,managed-hook-runtime,legacy-wsl-runtime-auth-drain-apply-script) — four pass in isolation, andrun-electron-vite-dev's two reproduce on the base commit with these changes stashed. Renderer: 1 failure (AgentMapWorkspaceContextMenu) that passes in isolation.Two more readers of the same conflation, deliberately left alone
ssh-relay-session.ts:2276(reattachKnownPtys) and:1986filterexpiredout of the relay's bulk reattach set.:2276is defensible as written:expiredalso carries superseded siblings, and reattaching those is exactly the 2→19→20 fan-outsupersedeSiblingLeasesForPaneexists to prevent. It cannot be flipped without first splitting supersession out ofexpired.Consequence: after an app restart the orphan is recovered through the
adoptStablePanepath, not the relay's bulk reattach. That path is what this PR restores and what the new test pins.Splitting supersession into its own lease state (or a
supersededByfield) would let:2276be corrected too — but that needs the relay-start identity the STA-3077 note atssh-pty-lease-operations.ts:118-122says the lease does not yet carry. Toward the SSH/remote consolidation, that is the shape of the real fix.