Repository navigation
fix(ssh): stop reconnect from grafting ghost terminal panes (STA-3077) - #12264
AmethystLiang wants to merge 13 commits into
Conversation
📝 WalkthroughWalkthroughSSH PTY leases now persist retirement reasons, shutdown-pending state, relay incarnations, and reap flags. Relay sessions retire leases across incarnation changes, reap orphaned PTYs, and persist bindings without creating missing panes. The PTY kill handler retires leases before shutdown RPCs and clears reap flags after successful cleanup. Renderer cleanup handles asynchronous kill failures. Persistence, runtime recovery, IPC, relay, UI, and Docker-backed regression tests cover these behaviors. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/persistence.ts (1)
7563-7577: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winFlush the incarnation removal even when no lease row was removed.
removeSshRemotePtyLeasesclearssshRelayIncarnationsfor the target, but the flush is gated onthis.state.sshRemotePtyLeases.length !== before. If the target has a recorded incarnation and zero lease rows, the removal stays in memory only. A crash before the next save restores the stale identity, which is the exact condition the comment at Line 9844 ofsrc/main/persistence.test.tswarns about: a stale identity retires the first reconnect's fresh leases.🐛 Proposed fix
removeSshRemotePtyLeases(targetId: string): void { this.state.sshRemotePtyLeases ??= [] this.supersededByLeaseInsert.delete(targetId) - this.state.sshRelayIncarnations = this.state.sshRelayIncarnations?.filter( - (entry) => entry.targetId !== targetId - ) + const incarnationsBefore = this.state.sshRelayIncarnations?.length ?? 0 + this.state.sshRelayIncarnations = this.state.sshRelayIncarnations?.filter( + (entry) => entry.targetId !== targetId + ) + const incarnationRemoved = (this.state.sshRelayIncarnations?.length ?? 0) !== incarnationsBefore this.clearSshRemotePtyBindingsForTarget(targetId) const before = this.state.sshRemotePtyLeases.length this.state.sshRemotePtyLeases = this.state.sshRemotePtyLeases.filter( (lease) => lease.targetId !== targetId ) - if (this.state.sshRemotePtyLeases.length !== before) { + if (this.state.sshRemotePtyLeases.length !== before || incarnationRemoved) { this.flush() } }
🧹 Nitpick comments (7)
src/main/ssh/ssh-relay-session-lease-retirement.test.ts (1)
119-190: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider covering the refused-bind path.
The suite covers the reap and incarnation branches thoroughly. One new production branch has no test here or in
src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts: whenpersistPtyBindingreturns'refused',restoreReattachedPtyRuntimemust skipruntime.registerPtyand the caller must leave the lease out ofmarkSshRemotePtyLeasesAttachedAsync. That pair is the core of the no-ghost-pane fix, and a regression would be silent.A test that stubs
persistPtyBindingto return'refused'and asserts both negatives would close the gap.src/main/ssh/ssh-relay-session-terminal-error.test.ts (1)
110-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse the shared
createMockDepsfixture instead of maintaining parallel store mocks.src/main/ssh/ssh-relay-session-test-fixtures.tsalready exports acreateMockDepsthat builds this exact Store mock, yet both files keep their own copy. This PR had to add the same nine lease and incarnation methods to all three by hand. Every futureStoremethod the session calls will need the same three-way edit, and a missed copy fails at runtime with "not a function" rather than at type-check, because each mock is cast throughas unknown as Store.
src/main/ssh/ssh-relay-session-terminal-error.test.ts#L110-L118: delete the localcreateMockDepsand import it from./ssh-relay-session-test-fixtures; the shared version returns a superset of this file's fields, includingmockWindow.src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts#L159-L167: build the store insidecreateSessionfrom the shared fixture'smockStorerather than redeclaring it; note the local copy also omitspersistPtyBinding, which the shared fixture provides.src/main/persistence.ts (2)
1636-1642: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider bounding
tokenlength.Neighbouring normalizers bound persisted strings (
leafIdat 256,retiredReasonat 512).tokencomes from the remote relay and has no bound here, so a malformed or oversized value persists verbatim into the state file. A cap keeps the profile size predictable.♻️ Proposed bound
- // Dropping this on load would silently demote every comparison to the clock-based fallback. - ...(typeof raw.token === 'string' && raw.token.length > 0 ? { token: raw.token } : {}) + // Dropping this on load would silently demote every comparison to the clock-based fallback. + ...(typeof raw.token === 'string' && + raw.token.length > 0 && + raw.token.length <= SSH_RELAY_INCARNATION_TOKEN_MAX_LENGTH + ? { token: raw.token } + : {})
7510-7521: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAvoid synchronous flush on SSH reconnect path writes.
setSshRelayIncarnation,clearAllSshRemotePtyLeaseReapFlags, andretireAllLeasesSparingPtysare reachable from reconnect/incarnation handling and each calls the synchronous full-stateflush(), while live establish/reconnect paths already useflushDurableStateOrThrowAsyncto avoid main-thread stalls on stalled profile mounts.src/main/persistence.test.ts (1)
9836-9847: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winAdd the no-lease case for incarnation removal.
This test upserts a lease before
removeSshRemotePtyLeases, so the flush in that method is triggered by the lease removal. A target that has a recorded incarnation and no lease rows takes the ungated path and the incarnation removal is never written to disk. Add a case that removes leases for a target with an incarnation but no lease rows, then reloads and assertsgetSshRelayIncarnationreturnsnull.src/main/runtime/orca-runtime.test.ts (1)
2962-2985: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd the positive counterpart for a relay-driven expiry.
This test proves that an
'expired'lease carryingretiredReasonis refused. It does not prove that an'expired'lease withoutretiredReasonstill recovers. The distinction between the two is the whole point of the field, per the comment at Line 2964. A change that refuses every'expired'lease would keep this test green. Add a case that callscreateRuntimeWithSshLease(..., 'expired')with no reason and asserts recovery succeeds.tests/e2e/helpers/docker-ssh-relay-processes.ts (1)
153-173: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReuse this helper in
terminateDockerSshRelay.
terminateDockerSshRelay(Line 186) already runs the identical integer check and/procvalidation chain, and differs only in the signal name. Route it throughsignalDockerSshRelayso the validation lives in one place.♻️ Proposed consolidation
export function terminateDockerSshRelay( target: DockerSshRelayTarget, snapshot: DockerSshRelayProcessSnapshot ): void { - const { relayPid } = snapshot - if (!Number.isInteger(relayPid)) { - throw new Error('Docker SSH relay process ID must be an integer') - } - execDockerSshRelayTargetCommand( - target, - [ - `proc=/proc/${relayPid}`, - '[ -r "$proc/cmdline" ]', - 'argv=()', - 'mapfile -d \'\' -t argv < "$proc/cmdline"', - '[ "${argv[1]##*/}" = relay.js ]', - '[[ " ${argv[*]:2} " = *" --detached "* ]]', - `kill -TERM ${relayPid}` - ].join(' && ') - ) + signalDockerSshRelay(target, snapshot.relayPid, 'TERM') }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e69b4db9-8407-48eb-b267-d448f01cd993
📒 Files selected for processing (25)
src/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/ipc/ssh.test.tssrc/main/persistence.test.tssrc/main/persistence.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/ssh/ssh-relay-session-agent-hooks.integration.test.tssrc/main/ssh/ssh-relay-session-lease-retirement.test.tssrc/main/ssh/ssh-relay-session-reconnect-incarnation.test.tssrc/main/ssh/ssh-relay-session-terminal-error.test.tssrc/main/ssh/ssh-relay-session-test-fixtures.tssrc/main/ssh/ssh-relay-session.tssrc/relay/relay.tssrc/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.tssrc/renderer/src/components/terminal-pane/pty-transport-pi-coalesce.test.tssrc/renderer/src/components/terminal-pane/pty-transport-pi-spinner.test.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/shared/ssh-types.tssrc/shared/types.tstests/e2e/helpers/docker-ssh-relay-processes.tstests/e2e/helpers/persisted-terminal-layout.tstests/e2e/ssh-reconnect-no-ghost-pane-graft.spec.tstests/e2e/ssh-relay-redeploy-stale-pty-binding.spec.ts
|
Thanks, this was a really bad bug |
Reconnecting an SSH worktree could add terminals the user never opened.
`restoreReattachedPtyRuntime` calls `Store.persistPtyBinding`, which is a
*creating* write: when the lease's leafId is absent from the durable layout
it splits the root and grafts a new leaf, resurrecting a pane as a side
effect of reattaching its PTY.
Add `persistPtyBinding(args, hostId, { mayCreate: false })`. The predicate
already existed inside the function — `terminalMembershipChanged` is set by
the four creating branches and only those — so the mode reuses it and the
function's own `restoreSession()` rollback rather than duplicating a
non-creating writer. Both flush points are guarded, including the legacy
non-terminal-leafId early return.
A refusal is deliberately non-destructive: it skips `registerPty`, leaves the
lease `detached`, and retires nothing. An absence in one durable store can
justify "do not create"; it can never justify "destroy" — the local partition
is not trustworthy as proof of pane deletion, because writes are dropped for
the duration of a reconnect's snapshot apply and a pane can be live on screen
having been restored from the remote host.
Reorder `persistPtyBinding` before `registerPty`, since `registerPty`
publishes a mobile surface and would otherwise create the UI a refusal
exists to prevent. A persistence *throw* still binds: under `mayCreate:
false` the refusal check precedes both flush points, so reaching a flush
proves membership did not change and the pane exists.
Part 1 of 5, ordered by blast radius. This commit can only decline to
create; it destroys nothing and ships safely on its own.
…7, part 2/5) Every future retirement goes through exactly one of two Store methods, split by what the evidence actually proves rather than by which handler produced it: - retireLeaseAndReap — the pane is provably gone, so the remote PTY is ours to kill. Sets pendingRemoteShutdown. - retireLeaseSparingPty — the row is wrong about the PTY it names. Cannot reach pendingRemoteShutdown by construction, because a reset relay reuses pty-N and the id may already be another pane's live shell. Retirement is terminal: re-retiring is refused, so a spared lease can never later acquire a reap flag. Both retirement fields are added to the type and to normalizeSshRemotePtyLease here rather than in part 3. That normalizer is a strict allowlist, so a field landing without it would work in every in-process test and vanish on the first restart — precisely the durable case the flag exists for. The round-trip test reloads through normalize instead of set-then-read. No callers yet; this commit only constrains what comes after.
… (3/5) STA-3077 part 3 of 5. One pane may hold at most one live SSH lease, and a retirement that proves the pane is gone hands its remote PTY to a reaper. - D1a: an incoming lease write supersedes any other live lease for the same pane, flagging the loser for reaping. Transactional with the insert. - D1b: lease states advance monotonically by finality, replacing the ad-hoc directional guards some callers remembered and others forgot. `expired` -> `terminated` stays legal so a relay-expired lease the user then closes is not stranded visible to the 30s recovery consumers. - M1: collapse each pane to one live lease at load, so profiles already poisoned by past fan-outs heal without waiting for a reconnect. - D3: drain `pendingRemoteShutdown` rows on each successful connect, oldest first, capped at 32 per connect and dropped after 7 days. A flagged id this connection is live on is spared, not killed: a reset relay restarts `pty-N` numbering, so a flag minted in an earlier generation can name another pane's shell. - F8: dropping a lease whose spawn failed to persist also undoes the supersede it caused, so a failed spawn cannot retire a working pane's lease.
D6 — reattach failure had one exit that always ran the local teardown. Split it
into three, keyed on what the relay actually proved:
(A) transport-ish failure: nothing proves the remote PTY is gone, so keep the
grace window and retry — unchanged behaviour, now explicit.
(B) identity mismatch: the relay proved this id names a *different* pane's live
PTY. Retire the wrong row and stop. The old code fell through to the local
teardown, and after the identity fence `ssh:<target>@@pty-N` is that other
pane's app id too — so clearProviderPtyState/deletePtyOwnership/pty:exit
were tearing down a working pane.
(C) plainly missing: this pane's remote PTY really is gone, so the local
teardown is correct.
Both retirements go through retireLeaseSparingPty (I6): the row is wrong, but
nothing here authorizes killing the process it named.
D7 — ask the relay who it is before trusting any lease. `relay.status` is
answered by the detached daemon that owns the PTYs (`relay.js --connect` is a
pure byte pipe), so a pid + uptime-derived start time identifies the incarnation
without depending on the two machines' clocks agreeing. A change means every
lease for that target names a PTY in a dead id space; retire them all, spare the
processes. Fails open in every direction — an unavailable RPC, an unparseable
reply, or no stored identity is a no-op, never a retirement.
Also closes the `'expired'` overload: that state is written both by the relay
expiring a PTY and by our own retirements, and only the first is evidence the
remote shell is gone. getRecentExpiredSshLease now requires retiredReason to be
absent, so an Orca-written retirement can never authorize recreating the pane —
which is exactly how D6/D7's retirements would otherwise mint the duplicates
they exist to prevent.
Tests: 6 D6/D7 cases in the renamed lease-retirement suite (identity mismatch
spares the live pane it names, incarnation change retires the target, same
incarnation tolerates RPC latency, unavailable relay.status is a no-op, first
identity is recorded without retiring), 3 store cases, and the runtime tripwire.
D4. `pty:kill` rethrows a failed shutdown on purpose so the user can retry, but the rethrow also skipped `finishPtyShutdown` — so a close attempted while the transport was wedged left the pane's `SshRemotePtyLease` non-terminated. `reattachKnownPtys` reattaches every non-terminated lease regardless of whether the renderer still has a pane for it, so the next reconnect grafted the closed pane back as a ghost (RC5). Retire the lease *before* the RPC (`retireLeaseAndReap`), so whether the close sticks no longer depends on whether the transport answers. On success, clear the reap flag: the remote PTY is provably gone, so the next connect's D3 drain has nothing to chase. On failure the flag stays set and D3 reaps the orphan — the remote shell is not leaked by the retirement. The tombstone fast-path is deliberately untouched. It makes no RPC, so it needs no pre-RPC intent, and double-writing there would change a path that is already safe. `markSshRemotePtyLease` no-ops when the state already matches, so `finishPtyShutdown`'s later `'terminated'` write cannot clobber `retiredReason`. Reason string is `'pty kill requested'`, not "closed by user": hibernation (`terminals.ts`, `keepHistory: true`) reaches the same handler, and a user-attributed reason would be a misleading diagnostic. Hibernation kills are still genuine kills — the process dies and a fresh lease is minted on restart — so retiring is correct there too. Renderer: `disconnect()` stays fire-and-forget (the close must not block on a wedged transport) but now catches, since main records the intent durably before its RPC and a rejection is only a report. Tests: the wedged-relay case rejects with CONNECTION_LOST — not an "already gone" error — so it exercises the rethrow that RC5 needs. Four `kill: vi.fn()` renderer mocks returned `undefined` while the real preload contract returns `Promise<void>`; the mocks were the ones lying. `ssh.test.ts`'s mock store was missing the D3/D7 methods added in 3/5 and 4/5. Co-authored-by: Orca <[email protected]>
Two Docker-SSH specs, both gated on ORCA_E2E_SSH_DOCKER=1 and skipped on Windows (they use POSIX SSH tooling). ssh-reconnect-no-ghost-pane-graft: closes a pane while the relay is frozen (SIGSTOP) so the shutdown RPC fails against a still-registered provider — the only demonstrated way to reach the rethrow that used to skip finishPtyShutdown. Asserts the close is durable anyway (D4), that reattach never walks the retired lease back to attached/detached (D1b), and that the pane never returns. A graceful disconnect cannot substitute: it unregisters the provider, so pty:kill takes the tombstone fast-path and makes no RPC at all. ssh-relay-redeploy-stale-pty-binding: SIGTERMs the relay, then asserts leases minted by the destroyed generation end up non-restorable and that no visible pane still displays a binding into the dead generation. Both read persisted layouts through a shared reader that searches every workspace-session partition rather than hardcoding one. Layouts live in `workspaceSession` for the local execution host and in `workspaceSessionsByHostId[hostId]` for remote ones, so a hardcoded partition silently returns null forever and turns every layout assertion into a tautology — which is exactly what the redeploy spec's leaf-count guard was doing. Both specs now fail loudly if no partition holds the tab. The relay freeze/unfreeze helpers validate /proc/<pid>/cmdline is the detached relay before signalling, so a pid recycled by the container cannot be hit. Co-authored-by: Orca <[email protected]>
Two review findings on D7. 1. The pid + derived-start pair could retire every lease on a relay that never restarted. `derivedStartAt` is `localNow - relayUptimeMs`, so remote clock skew cancels — but an NTP step on either host moves it arbitrarily far past the 30s tolerance, and the resulting false positive drops every pane's reattach. The relay now mints a token at startup and returns it from `relay.status`; when both readings carry one it decides alone, needing no clock. pid + start time stays as the fallback for a relay still running from a pre-token deploy, which is also why a stored token may not rule against a token-less reading. That token also fixes the reverse gap: a restart that reuses the pid inside the start tolerance used to read as the same incarnation. 2. `retireAllLeasesSparingPtys` flushed per lease, and `flush()` is a synchronous full-state write. D7 fires on the reconnect path holding every pane's lease, so N panes meant N blocking writes. Retirement now mutates in memory and flushes once — mirroring how `markSshRemotePtyLeases` already batches. The three comments describing the tolerance contradicted each other on whether it covers clock skew; they now say the same true thing. Co-authored-by: Orca <[email protected]>
Leases are keyed by (targetId, ptyId) and a reset relay restarts pty-N numbering, so a fresh spawn can land on a retired row. The upsert spread carried that row's pendingRemoteShutdown onto the new binding, aiming the next connect's reap drain at a live pane's shell. Co-authored-by: Orca <[email protected]>
…d it pendingRemoteShutdown means "this relay id is ours to kill", which is only true of the relay process that minted it — the next incarnation restarts pty-N numbering, so the same id can name another client's live shell. Arm the drain only when relay.status proves the incarnation is unchanged; otherwise abandon the flags and leak the shell. Co-authored-by: Orca <[email protected]>
Co-authored-by: Orca <[email protected]>
Record the new relay incarnation only after retiring stale leases. Recording first creates a crash window where the next connect sees "unchanged" and never retires the old incarnation's leases, leaving ghost panes. Also add test coverage for invalid persisted incarnation data and improve e2e test guards to prevent false positives.
When removing leases for a relay target with no remaining lease rows, the incarnation removal was kept in memory and not flushed to disk. On the next store load, the stale incarnation was restored, causing the fresh leases from the reconnect to be immediately retired. Gate the flush on incarnation removal as well as lease removal so the removal persists durably.
A post-attach refusal leaves the PTY attached with no consumer, re-pinned on every reconnect. Check bind (dry-run) before attach to refuse early, keeping the lease detached for re-evaluation. Persist reap flag on remote kill while disconnected so drain honours it at next proven-same-incarnation connect. Fix SSH control double-click bubble. Add durable incarnation tracking for redeploy test assertions.
31e77ac to
7679eff
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/persistence.test.ts (1)
9889-9889: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winStrengthen the token-less assertion so it cannot pass on a null record.
getSshRelayIncarnation('target-2')returnsnullwhen no record exists.expect(null).not.toHaveProperty('token')passes. The assertion therefore cannot distinguish "the record has no token" from "the record was dropped". Assert the record first, then the missing token.♻️ Proposed assertion tightening
- // A token-less relay must stay token-less, not gain an empty one. - expect(reloaded.getSshRelayIncarnation('target-2')).not.toHaveProperty('token') + // A token-less relay must stay token-less, not gain an empty one. + const tokenless = reloaded.getSshRelayIncarnation('target-2') + expect(tokenless).toEqual({ targetId: 'target-2', pid: 7, derivedStartAt: 1_900_000 }) + expect(tokenless).not.toHaveProperty('token')
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9cf97f4c-912a-45bb-8cbd-5a87b4735ea7
📒 Files selected for processing (31)
src/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/ipc/ssh.test.tssrc/main/persistence.test.tssrc/main/persistence.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/ssh/ssh-relay-session-agent-hooks.integration.test.tssrc/main/ssh/ssh-relay-session-lease-retirement.test.tssrc/main/ssh/ssh-relay-session-reconnect-incarnation.test.tssrc/main/ssh/ssh-relay-session-terminal-error.test.tssrc/main/ssh/ssh-relay-session-test-fixtures.tssrc/main/ssh/ssh-relay-session.tssrc/relay/relay.tssrc/renderer/src/components/sidebar/WorktreeCardSshHostControl.test.tsxsrc/renderer/src/components/sidebar/WorktreeCardSshHostControl.tsxsrc/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.tssrc/renderer/src/components/terminal-pane/pty-transport-pi-coalesce.test.tssrc/renderer/src/components/terminal-pane/pty-transport-pi-spinner.test.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/shared/ssh-types.tssrc/shared/types.tstests/e2e/helpers/docker-ssh-relay-processes.tstests/e2e/helpers/persisted-terminal-layout.tstests/e2e/ssh-reconnect-no-ghost-pane-graft.spec.tstests/e2e/ssh-relay-redeploy-stale-pty-binding.spec.ts
🚧 Files skipped from review as they are similar to previous changes (22)
- src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts
- src/main/ssh/ssh-relay-session-terminal-error.test.ts
- src/renderer/src/components/terminal-pane/pty-transport.ts
- src/renderer/src/components/terminal-pane/pty-transport-pi-spinner.test.ts
- src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
- src/main/ssh/ssh-relay-session-test-fixtures.ts
- src/main/ipc/ssh.test.ts
- src/shared/ssh-types.ts
- src/main/ipc/pty.ts
- src/shared/types.ts
- src/relay/relay.ts
- src/renderer/src/components/terminal-pane/pty-transport-pi-coalesce.test.ts
- src/main/runtime/orca-runtime.test.ts
- tests/e2e/helpers/persisted-terminal-layout.ts
- tests/e2e/helpers/docker-ssh-relay-processes.ts
- src/main/runtime/orca-runtime.ts
- src/renderer/src/components/terminal-pane/pty-transport.test.ts
- tests/e2e/ssh-reconnect-no-ghost-pane-graft.spec.ts
- src/main/ssh/ssh-relay-session-lease-retirement.test.ts
- src/main/ssh/ssh-relay-session.ts
- src/main/persistence.ts
- src/main/ipc/pty.test.ts
|
Your root-cause analysis here is what made #13111 possible — RC1 (lease identity has no pane key, and #13111 is a smaller take on the same defect — ~180 production lines, rebased on current Flagging it here so we don't land conflicting fixes. Your RC4 — a failed reattach never retiring its lease, leaving a permanent zombie that re-enters every future fan-out — is not addressed by mine and is worth keeping on the table. |
|
Thank you @AmethystLiang. Your root-cause analysis here led to #13326, which fixed STA-3077, and the relay lease and reattach code this PR changed has since been removed with the SSH relay (#27214/#27215). Terminals now live on Orca's managed remote server. Closing as fixed. |
Fixes STA-3077 / #11729.
The symptom
In one sentence: an SSH pane's remote-PTY lease is keyed only by
(targetId, ptyId), so nothingever retires the lease a pane leaves behind; every reconnect reattaches all of them, and the reattach
path writes through a creating store method that splits the layout root to graft the missing leaf
back in.
Both halves of the ticket title are literally true at different moments, and they feed each other.
reattachKnownPtysis the last blocking gate before a reconnecting session reaches'ready'(
src/main/ssh/ssh-relay-session.ts:633→:641), so every stale lease enlarges the fan-out the nextreconnect must complete. Loss on cycle N becomes duplication on cycle N+1.
Root cause
RC1 — the lease store has no pane key.
Store.upsertSshRemotePtyLease(
src/main/persistence.ts:7022-7054) finds an existing row by identity alone:worktreeId,tabIdandleafIdride on the row (src/shared/ssh-types.ts:147-158) but participatein no uniqueness rule anywhere. Two upserts for the same pane with different
ptyIdproduce twoattachedrows. And there is no per-lease retirement path to undo it:removeSshRemotePtyLease(
persistence.ts:7152) has exactly one caller — the spawn-persist rollback atsrc/main/ipc/pty.ts:5561— and the only other removal is the pluralremoveSshRemotePtyLeases(targetId)used by SSH-target deletion (src/main/ipc/ssh.ts:138). Leasecount is monotonically non-decreasing.
RC2 — reattach fans out over every lease, and the relay's fence structurally cannot help.
reattachKnownPtys(ssh-relay-session.ts:1848-1918) filters on state only (:1853-1854:state !== 'terminated' && state !== 'expired'), so orphans are included. The relay's identity fence(
src/relay/pty-handler.ts:1608-1619) compares the incoming pane key against the PTY's own recordedpane key (
managed.attachIdentity ?? { paneKey: managed.paneKey, ... }) — and two PTYs minted forthe same pane each recorded that pane's key, so both pass.
attachIdentityMismatches(
pty-handler.ts:332, JSDoc:327-331) fires on cross-generation id collisions, a differentfailure. The fence guards relay-id reuse, not pane cardinality, and there is no "at most one live PTY
per pane" check on either side of the wire. Only
Storecan see two leases for one pane.RC3 — the reattach binding write creates UI.
restoreReattachedPtyRuntime(
ssh-relay-session.ts:2112-2136) callsstore.persistPtyBinding(...)at:2124. That method hasfour creating branches: mint a tab (
persistence.ts:6666-6685), mint a root leaf (:6700-6705),split the root and graft the leaf (
:6706-6719), mint a layout (:6724-6734). All four aredeliberate and load-bearing for the spawn path — the comments cite the Issue #217 force-quit race,
where
pty:spawnbeats the renderer's debounced layout writer. None of it is appropriate on reattach,where the pane either already exists or is gone for good.
RC4 — a failed reattach mints the duplicate. The lease stays non-terminated while the renderer
fresh-spawns for the same pane. RC4b: when the relay reports an identity mismatch — proving the
row names a PTY that now belongs to someone else —
handlePtyReattachFailurereturns without retiringit. That lease can never attach and is never retired: a permanent zombie re-entering the fan-out on
every future reconnect. RC4b is why the count grows without bound instead of oscillating.
RC5 — retirement is not durable.
markSshRemotePtyLease(persistence.ts:7123-7150), thesingular setter every retirement path uses, has no terminal-state guard: it short-circuits only on
lease.state === state(:7132) and otherwise assigns unconditionally at:7139. Its plural siblingupdateSshRemotePtyLeaseStatesguards both directions (:7097refusesattachedover aterminated/expired row,
:7100refusesdetachedover anything notattached) — so the invariantexists, it is just not where every caller inherits it.
abandonPtySourceRecovery(
ssh-relay-session.ts:2575) writes'detached'unconditionally over whatever it finds, returning acorrectly retired lease to the reattach-eligible set. Observed directly during a SIGSTOP experiment:
expired→detachedon a second reconnect. This is why a fix aimed only at RC4 can ship fully greenand regress silently later.
The evidence
A maintainer's pre-migration store held 15 rows for one worktree. Two are residue from a Docker e2e
harness and carry a different
targetId, leaving 13 real leases across four leaves — three leaveswith four leases each, one with a single lease. Read at millisecond precision, one reconnect resolves
into four beats:
Three PTYs minted weeks apart were all reattached onto one leaf by a single reconnect — that is the
accumulation, and it is what this artifact proves. Every leaf ended with exactly four leases, though
the mint occasions are not aligned across leaves: one leaf's second mint came 27 seconds after its
first, in the same session, while the other two waited 12 days. So this is per-leaf accumulation, not
a synchronized per-reconnect wave.
(Read these at millisecond precision or not at all — at minute granularity all thirteen rows collapse
to "07-06 22:47" and pty-4/5/6 look like leases the
terminatedfilter correctly excluded. pty-4 wasattached at .592 and terminated at .746: an outcome of the sweep, not an exclusion from it.)
Two limits on this artifact, stated so nobody over-reads it. First, wave 4's four fresh mints are
not established as RC4's signature: pty-13's leaf held no prior lease, so reattach cannot have
minted it, and once a pane-driven spawn exists in that 102 ms window it explains all four. RC4 rests
instead on code reading plus a second machine's live store, where two leaves that did already hold
leases each minted a duplicate 19 s and 63 s later. Second, this table evidences lease
accumulation, not pane multiplication — waves 1–3 land on a single shared leaf, and a reattach
onto a leaf that already exists overwrites a binding rather than adding a pane. Pane multiplication is
evidenced by RC4b/RC4c and by the graft's absent-leaf path, not here.
RC0 — one write window, three consequences
A lease is durable the instant it is written; the layout that gives it meaning is not.
upsertSshRemotePtyLeaseends inthis.flush()(persistence.ts:7053) and the spawn path calls itsynchronously (
pty.ts:5511-5519). The layout write is doubly debounced — 150 ms in the renderer(
src/renderer/src/lib/session-write-subscriber.ts:163), then 1 s up to 5 s in main(
persistence.ts:3819-3820).pty.ts:5524-5526names this window in its own comment.Worse than late: during a remote-workspace snapshot apply the write is dropped, not deferred.
The subscriber gates on
!isRemoteWorkspaceSnapshotApplyInProgress()(
src/renderer/src/App.tsx:1262); when the gate is closed it clears the pending change set and returns(
session-write-subscriber.ts:201-208, and again at:227-229) — after advancing its baseline at:197(prev = next). So the next comparison sees no change, nothing re-emits it,persist({ patch })at
:237never runs, and a latersession.flush()cannot rescue a patch main never received. The gateis held for a 30 s reconnect deadline plus a 1 s tail
(
src/renderer/src/hooks/remote-workspace-snapshot-apply.ts:21,:20).The loss is not unconditional, and the precise version is more damning than the blanket one: the
timer rebuilds its payload from live state (
:222store.getState(),:233buildWorkspaceSessionPatch(fresh, changed)) rather than from a captured diff, so any later mutationof the same field carries the earlier one forward. What is permanently lost is a mutation that
settles during the freeze and is never touched again — which is exactly a pane close, because a
closed pane generates no further layout events.
Three consequences follow, and each one misled part of this investigation:
whose leaf the durable layout never recorded — which is precisely the absent-leaf state the graft
requires.
action. This is the governing rule of the whole change: an absence can justify "do not create";
it can never justify "destroy."
Nothing in this PR closes that window. What this PR does is stop acting destructively on its output.
What each commit does, and what it can destroy
Five commits, ordered by blast radius, so each boundary is independently revertable and the riskiest
code lands last against the safest foundation. Four more follow: the e2e specs, and three fixes found
by the review rounds (each described in The reap flag has a scope above).
persistPtyBindinggainsmayCreate: false; reattach may no longer create pane structureStoreretirement primitives, and no third way to retire a leaseCommits 7–9 only ever withhold a destructive action, so the safety argument for 1–5 is not weakened
by reading them: each one strictly shrinks the set of remote PTYs this change is willing to kill.
Commit 1 is non-destructive and shippable alone, which is what makes this ordering worth following
rather than merely tidy. It needs no new predicate: every creating branch in
persistPtyBinding, andonly the creating branches, already sets
terminalMembershipChanged = true, so that flag is thepane-existence predicate — already computed, already correct, and maintained by whoever edits the
function next. The function also already owns its rollback (
cloneWorkspaceSessionStateat:6625,restoreSession()at:6640-6649). UndermayCreate: falsea would-be-creating write restores,skips the flush, and returns
'refused': skipregisterPty, leave the leasedetached, log, retrynext reconnect. No retirement and no remote shutdown — refusing to create is the only safe action
on an absence.
Two implementation notes a reviewer should check: there are two flush points (
:6690-6695and:6738-6743) and both need the guard, or there is a hole on exactly the legacy pane ids; and the cloneat
:6625precedes the incarnation write at:6650-6660, so a refusal correctly rolls that back too.Commit 3 also heals existing profiles. Every affected user already has duplicate leases on disk, so
a fix that only prevents future duplication leaves them broken. A load-time reconcile groups
non-terminated leases with a complete pane identity, keeps the newest by
updatedAt(tiebreakingcreatedAtthenptyId— the snapshot has three rows inside one second, so this must be specified andtested, not left to sort stability), retires the rest, and flags them for reaping. It is idempotent and
runs unconditionally on every load for every profile, so it is a no-op on clean stores rather than
something gated on a heuristic.
Both new durable fields must be taught to
normalizeSshRemotePtyLease(persistence.ts:1585-1610).That normalizer is a strict allowlist that rebuilds the row field by field, and it fails two ways,
neither loud: an unlisted field is silently dropped on load (works in memory, works in every in-process
test, dead after restart), and a value outside a validated literal union makes it return
nullso thewhole row is filtered out at
:3631-3633. Every test for a new durable field must round-tripthrough normalize — construct, persist, reload, assert. A set-then-read test passes in both failure
modes and proves nothing.
Why there are two retirement primitives
Everything that retires a lease goes through exactly one of two
Storemethods; nothing else writeslease state directly.
retireLeaseAndReap(targetId, ptyId, reason)pendingRemoteShutdownretireLeaseSparingPty(targetId, ptyId, reason)The constraint that makes this non-negotiable: retiring must never enqueue a relay pty id for
shutdown when the evidence is about the binding. A reset relay reuses
pty-N—src/relay/pty-handler.ts:329says so outright, and the identity fence at:1610exists for it — sopty-1in a new generation may be another pane's live shell. The identity-mismatch case is thesharp one:
pty-handler.ts:1597-1607runs a liveness probe first and routes a dead PTY to a plainnot-found, so reaching the fence at
:1610-1619proves the remote process is alive and belongs toanother pane. Handing its id to the reaper would kill working sessions.
"Structurally cannot" is stronger than "does not" on purpose:
retireLeaseSparingPtymust neitheraccept nor expose
pendingRemoteShutdownin any form, so a future caller cannot opt in by passing aflag. This design reaches the id-reuse trap at two independent call sites, and prose alone would leave
it to both of them to remember.
The split is by what the evidence is about, not by which handler produced it: "the pane is gone,
proven positively" → retire and reap; "the lease is wrong about its PTY" → retire and never touch the
process; "nothing (a timeout, a dead channel)" → no retirement at all, retry next cycle.
The reap flag has a scope, and it is one relay incarnation
The two-primitive split above is necessary but not sufficient, and review round 3 is what surfaced why.
pendingRemoteShutdownasserts "relay idpty-Nis ours to kill" — a claim that is only true of therelay process that minted it, because the next incarnation restarts
pty-Nnumbering from scratch.A flag is minted at connect N and drained at connect N+1, so a relay restart in between silently
re-points it at whatever holds that id now, which may be another client's live shell. That hazard is
independent of which primitive set the flag: it reaches the load-time migration, the pane-keyed
supersede, and the durable close intent alike, so guarding any one of them individually would have
fixed a third of it.
So the drain is armed only when
relay.statusproves the incarnation is unchanged. Unknown,unparseable, unreachable, changed, or no stored incarnation at all → the flags for that target are
abandoned before the drain runs (
disarmReapDrain,ssh-relay-session.ts:1943). Retirement stillfails open — an unavailable RPC retires nothing — but reaping fails closed, because the two
failure modes are not symmetric: abandoning a flag leaks a remote shell, honouring a stale one kills a
live pane.
That identity check needs to survive clocks it does not control, so the relay now mints a
randomUUID()incarnation token at startup and returns it fromrelay.status(
src/relay/relay.ts). When both readings carry a token the comparison is exact and needs no clock;pid+ derived start time (±30 s) remains only for a relay still running from a pre-token deploy. Thefallback alone was wrong in both directions — an NTP step on either host retires every lease on a relay
that never restarted, and a recycled pid inside the tolerance passes as "same process".
A related one-line rule, from the same round: a lease row is keyed
(targetId, ptyId), so a freshspawn on a reset relay lands on a retired row's key.
upsertSshRemotePtyLeasemerges over theexisting row, so retirement metadata was inherited by the new binding — handing a live pane's lease a
pendingRemoteShutdownit never earned. A revive to a live state now clears both retirement fields.What this does NOT fix
The loss half, as reproduced, is NOT fixed. An instrumented run settles this independently:
SIGTERM the relay while the SSH transport stays up → the replacement relay destroys every remote
shell. The session reached
'ready'promptly, and the first sample 27 ms afterssh.connect()returned already showed 3 SSH panes → 1, unchanged through 45 s, with zeroreattach-failure log lines. No fan-out invariant was violated and the panes went anyway.
Relay death destroys the remote shells, and nothing in this PR restores them. The 300 s grace
window protects against Orca detaching, not against the relay process dying. A destroyed shell
cannot be brought back, so the honest fixes are a dead-but-respawnable pane presentation or fewer
relay deaths — both larger than this change, and both requiring a UI decision nobody has made.
Commit 4 closes a different piece of the same repro (the stale leases the dead generation leaves
behind) without closing the loss itself.
The reattach fan-out can still gate
'ready'. Deferred deliberately: removing the relay churnthat currently reaps zombie leases by accident would extend the life of leases that can never
attach, so that follow-up must not ship before commit 4.
A pane close is still removed from the screen before it is durable. The visual teardown is
unconditional and upstream of the kill, and the kill stays deliberately non-blocking — a close must
not wait on a wedged transport. What changed is that the intent no longer depends on the RPC: main
retires the lease before the shutdown call (
pty.ts), so a throw on a severed transport can nolonger leave a live lease behind, and the renderer now at least reports the rejection instead of
dropping it silently (
pty-transport.ts:982). Net: the lease is right; the pixels are still ahead ofthe disk.
The stranded leaf resurfaces only on mount or remount.
replayTerminalLayout(
src/renderer/src/components/terminal-pane/layout-serialization.ts:234-273) is the only site thatreconstructs panes from a persisted root, and its single call site
(
use-terminal-pane-lifecycle.ts:1475) sits in auseEffectkeyed[tabId, cwd]. So the pane comesback when the user switches tabs or worktrees away and back, or relaunches — not during a
background reconnect while the pane stays mounted. That matches the ticket title ("not restored after
login" = reopen-after-reconnect), and it means any test for this must remount; asserting pane
count immediately after a reconnect passes on a broken build.
This may be the reported symptom's actual cause, but the minimal fix is a renderer-side ordering
change in an otherwise entirely main-process PR, and whether the pane should stay, return with an
error affordance, or be re-added on reconnect is an open UX call. Sibling PR.
PR fix(ssh): restore relay ownership after app restart #11860 is not a duplicate of this.
ed00ab0f34restored relay consumer ownership after anapp restart; it touched neither the lease upsert nor the reattach binding, and its oracle
structurally cannot catch duplication — the restart test uses one tab and asserts a single PTY
survives (
tests/e2e/ssh-cold-activation-restore.spec.ts:213-311), which passes cheerfully whileeleven extra PTYs accumulate beside it.
The load-time migration cannot heal an existing RC4b zombie. It collapses duplicates: a pane
with two live leases keeps the newest and retires the rest. A zombie that is the only row for its
triple is the newest for that triple, so it survives the reconcile untouched. Those clean up on the
first reconnect after this ships, when the failed-attach exits prove the row mismatched — one cycle
later than the duplicates, and never at all for a target the user does not reconnect.
Three remote-shell leaks are accepted, in exchange for never killing a live pane. (a) A refused
reattach leaves its remote PTY running — strictly better than the ghost pane it replaces, but the
shell is still there. (b) The graceful-disconnect tombstone fast-path in
pty:killis deliberatelyunchanged, so a close taken through it does not record a reap. (c) Every disarmed drain abandons its
flags outright. All three follow the same rule: an absence justifies declining to act, never
destroying. With a grace period of 0 (never expire) these shells persist until the relay dies.
The reap drain still fans out on the connect path. Up to 32 concurrent shutdowns are awaited
before the session settles. The same path already awaits per-lease attaches under the same mux
timeout, so this adds no new class of stall — but a deadline around the fan-out is a follow-up, not
something this PR does.
Do not "fix" this by raising the timeouts. A bloated lease set genuinely can prevent a reconnect
from settling (10 s per attempt,
src/main/providers/ssh-pty-provider.ts:199; two retries;concurrency 8,
ssh-relay-session.ts:117) — but that is a rate argument, not a cause. Raising anyof the three lengthens time-to-visible-breakage without removing the defect. Nothing in the chain is
distro-dependent; Rocky 9.4 is incidental.
Retracted measurement — do not re-run it
An earlier round of this investigation reported durable-state evidence that a closed pane's leaf
survived in the layout ("measured 2/2"). That reading is void and is retracted here so nobody
re-derives it and reports a false confirmation.
It read the layout from
raw.workspaceSessionsByHostId['ssh:<targetId>']. That partition cannotcontain renderer pane truth for an SSH worktree. The renderer's session writer resolves an SSH-backed
worktree to the local host id —
buildHostIdByWorktreeIdends inreturn parsed?.kind === 'runtime' ? parsed.id : LOCAL_EXECUTION_HOST_ID(
src/renderer/src/lib/workspace-session-host-persistence.ts:204-208); onlyruntime:*ispartitioned out. And main's own store code says where local lives, three times:
persistence.ts:569("'local' (the legacyworkspaceSessionblob) is dropped so the two surfacesnever diverge"),
:581("a local/invalid key here is legacy noise that must not shadow the canonicalpartition"),
:3620("'local' stays inworkspaceSessionfor downgrade compat"), with the parsercontinue-ing on alocalkey at:582-584. The local partition is structurally absent fromworkspaceSessionsByHostId.(The
ssh:*partition is not unused, just not renderer pane truth: four main-side writers feed it —pty.ts:4415-4418,pty.ts:5542,orca-runtime.ts:4610and:4668— and one main-side consumerreads it,
Store.clearSshRemotePtyBindingsForLeases, which unions it with the local session to clearbindings that name a retiring lease. That consumer sits on this PR's retirement path, so retirements
drive binding-clears against this mirror too.)
What that key does hold is a spawn-fed mirror written only by main (
pty.ts:5541-5545;orca-runtime.ts:4630-4635, host resolved at:4600-4614). SoafterClose === beforeClosethere isthe expected reading under every hypothesis, including a perfectly recorded close. It proves
nothing in either direction — a void measurement is not weak evidence.
The rule this section originally drew — "always read
raw.workspaceSession" — is itself too strong,and is corrected here. Which partition owns a tab depends on its execution host:
Store.getWorkspaceSession(hostId)returnsstate.workspaceSessiononly forLOCAL_EXECUTION_HOST_IDandstate.workspaceSessionsByHostId[hostId]for every remote one. Hardcodingeither side risks the same vacuous read in the other direction, which is why both e2e specs here go
through
readPersistedTerminalLayout(tests/e2e/helpers/persisted-terminal-layout.ts): it searchesboth partitions, reports which one answered, and both specs assert non-null before asserting
anything about the contents. A layout read that silently returns
nullforever turns every downstreamassertion into a tautology, so the guard is the load-bearing part.
(That the two resolvers disagree at all is a real latent defect — an unbounded parallel tabs/layout
tree that nothing reads and nothing prunes — and is filed separately. Do not "make the partitions
consistent" here; doing it without first fixing the read side would break the one main-side write that
currently reaches the renderer.)
Test plan, and the honest state of the e2e
Unit —
Storeinvariants. Pane-keyed supersede across a differentptyId; legacy rows without acomplete identity are exempt and untouched; terminal states are terminal in fact, including the
specific
'detached'-over-'expired'write observed resurrecting a lease;retireLeaseSparingPtyleaves the reap queue empty; every new durable field round-trips through normalize.
Unit —
mayCreate: false. One test per creating branch asserting'refused'and an unchangedsession — covering both flush points and the legacy-
leafIdpath — plus the non-creating rebindasserting
'bound'with behavior identical to today.Unit — retirement dispositions. Failed attach: transport-ish failure →
detached, retry nextcycle, no retirement; relay says not-found →
expired; identity mismatch →expiredwith the reapqueue asserted empty — that last one is the branch where the remote process is proven alive and
belongs to someone else. Generation reset: identity match → no-op; identity differs → every lease for
the target retired via the sparing primitive, reap queue empty; RPC unavailable / errored / no prior
identity → retires nothing, as three separate cases, because failing open is the entire safety
property.
Unit — incarnation identity and drain arming. A matching token keeps every lease however far
the derived start has drifted (the NTP-step case the pid+time fallback gets wrong); a new token retires
even when the pid was reused inside the ±30 s tolerance (the recycled-pid case it also gets wrong); a
token-less reading against a stored token falls back rather than retiring, since that pairing means an
older deploy, not a new process — and asserts the stored identity does not gain an empty token. The
drain is asserted disarmed in all three unproven cases (changed / no previous /
relay.statusfailed),with the fake store answering the claim out of the same flag set it clears — otherwise the drain would
reap from a queue that clearing had already emptied and the ordering would prove nothing. Round-trip
through normalize covers a lease reviving onto a retired row's key, and the per-target scoping of the
flag clear.
E2E — Docker SSH (
ORCA_E2E_SSH_DOCKER=1), two specs.ssh-reconnect-no-ghost-pane-graft.spec.tsdrives the close-while-severed case that the seeded shapebelow cannot: SIGSTOP the relay, close a pane, disconnect (which tears down the mux and invalidates the
pending shutdown), unfreeze, reconnect, then sample for 20 s at 2 s intervals. It asserts the close
intent went durable despite the failed RPC, that the retired lease never reappears as
attached/detachedin any sample, that the closed PTY id never appears in any pane'sdataset.ptyId, that the pane count never exceeds the post-close count, and that the id is gone fromptyIdsByLeafId. The freeze is not incidental: a graceful disconnect unregisters the provider, sopty:killtakes the tombstone fast-path and never issues the RPC that has to fail for this to be atest of anything.
ssh-relay-redeploy-stale-pty-binding.spec.tscovers the generation-reset half. Both specs resolve thetab from the renderer, not from a lease row — the lease's
tabIdis one of the things under test,so keying the spec on it could mask the bug — and both read layouts through the partition-searching
helper described above.
Honest state of the e2e, stated because it changes how much the green means:
an ungraceful death inside a ~1.15–5 s durable-write window; racing that with a SIGKILL was flaky in
every attempt, and the "disconnect, close a pane, reconnect" shape proposed as an everyday trigger
came back negative (the graceful path takes the tombstone fast-path and terminates the lease
cleanly). SIGSTOP makes the same condition deterministic — the transport is severed for exactly as
long as the test needs — so the spec is a real repro rather than a seeded precondition. What it does
not do is reproduce the field's own producer; it reproduces a condition with the same signature.
store (
profiles/<profileId>/orca-data.json), notpath.join(userDataDir, 'orca-data.json')— thelatter is a pre-migration path, and a run that used it returned
"leasesAfter": null. And seedrelay-form ids (
pty-N), not app ids: leases store the relay form(
getRelayPtyIdForSshLeaseStorage), so an app-form id in a seeded lease is never matched at attachtime and the test asserts against a fan-out that never considered it.
without a reattach failure no duplicate lease is minted.
replayTerminalLayout, whose one call site is keyed[tabId, cwd], so a stranded leaf is invisibleuntil a tab/worktree switch or a relaunch. Asserting pane count straight after a reconnect passes on
a broken build — a distinct trap from the partition-read one above, and both were live in the same
spec.
assertion would be false by design. It asserts the in-scope things: the surviving pane does not retain
a binding to a destroyed PTY, and the dead generation's leases are retired.
Made with Orca 🐋