Skip to content

fix(ssh): stop reconnect from grafting ghost terminal panes (STA-3077) - #12264

Closed
AmethystLiang wants to merge 13 commits into
mainfrom
jinjing/sta-3077-ssh-remote-environment-not-restored-after-login-on-rocky
Closed

AmethystLiang wants to merge 13 commits into
mainfrom
jinjing/sta-3077-ssh-remote-environment-not-restored-after-login-on-rocky

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes STA-3077 / #11729.

On the line numbers below. Cites in Root cause and RC0 describe the code as it was on
main
— they are the diagnosis, and they stop being findable at those offsets once this branch is
applied. Cites in the later sections are against this branch's head. Every cite names its symbol, so
a stale offset degrades to a grep rather than to a wrong claim.

The symptom

"SSH remote environment not restored after login" — reconnecting an SSH-backed workspace adds
terminal panes the user never opened, and the remote host accumulates shells nobody is using
(the reporter's own count went 2 → 19 → 20 relay PTYs across three reconnects).

In one sentence: an SSH pane's remote-PTY lease is keyed only by (targetId, ptyId), so nothing
ever 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.
reattachKnownPtys is 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 next
reconnect 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:

const existingIndex = this.state.sshRemotePtyLeases.findIndex(
  (entry) => entry.targetId === normalizedLease.targetId && entry.ptyId === normalizedLease.ptyId
)

worktreeId, tabId and leafId ride on the row (src/shared/ssh-types.ts:147-158) but participate
in no uniqueness rule anywhere. Two upserts for the same pane with different ptyId produce two
attached rows. And there is no per-lease retirement path to undo it: removeSshRemotePtyLease
(persistence.ts:7152) has exactly one caller — the spawn-persist rollback at
src/main/ipc/pty.ts:5561 — and the only other removal is the plural
removeSshRemotePtyLeases(targetId) used by SSH-target deletion (src/main/ipc/ssh.ts:138). Lease
count 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 recorded
pane key
(managed.attachIdentity ?? { paneKey: managed.paneKey, ... }) — and two PTYs minted for
the 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 different
failure. 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 Store can see two leases for one pane.

RC3 — the reattach binding write creates UI. restoreReattachedPtyRuntime
(ssh-relay-session.ts:2112-2136) calls store.persistPtyBinding(...) at :2124. That method has
four 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 are
deliberate and load-bearing for the spawn path — the comments cite the Issue #217 force-quit race,
where pty:spawn beats the renderer's debounced layout writer. None of it is appropriate on reattach,
where the pane either already exists or is gone for good.

RC3's precondition, stated because it is the single most misread fact in this investigation.
The graft at :6707 is gated on !layoutContainsLeafId(layout.root, args.leafId)
(persistence.ts:1699-1707, recursive). A stale lease reattaching onto a leaf that still exists
does not graft — it falls through to the plain layout.ptyIdsByLeafId[leafId] = ptyId write at
:6720-6723 and adds no pane. So duplicate leases on a live leaf produce a ptyId overwrite, not an
extra pane. An extra pane requires the leafId to be absent from the durable layout. That is why
the fix has two independent halves: one owns unbounded lease growth, the other owns the pane count,
and neither substitutes for the other.

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 — handlePtyReattachFailure returns without retiring
it. 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), the
singular 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 sibling
updateSshRemotePtyLeaseStates guards both directions (:7097 refuses attached over a
terminated/expired row, :7100 refuses detached over anything not attached) — so the invariant
exists, it is just not where every caller inherits it. abandonPtySourceRecovery
(ssh-relay-session.ts:2575) writes 'detached' unconditionally over whatever it finds, returning a
correctly retired lease to the reattach-eligible set. Observed directly during a SIGSTOP experiment:
expired → detached on a second reconnect. This is why a fix aimed only at RC4 can ship fully green
and 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 leaves
with four leases each, one with a single lease. Read at millisecond precision, one reconnect resolves
into four beats:

wave 1   .274 / .296 / .318           pty-1  pty-2  pty-3          reattach, cycle-1 leases
wave 2   .592 / .617 / .638           pty-4  pty-5  pty-6          reattach, cycle-2 leases
   └─ terminated .746 / .758 / .770                                ← a synchronized sweep, ~12 ms apart
wave 3   .781 / .803 / .824           pty-7  pty-8  pty-9          reattach, cycle-3 leases
wave 4  03.143 / .176 / .209 / .245   pty-10 pty-11 pty-12 pty-13  createdAt == lastAttachedAt: FRESH MINTS

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 terminated filter correctly excluded. pty-4 was
attached 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.
upsertSshRemotePtyLease ends in this.flush() (persistence.ts:7053) and the spawn path calls it
synchronously (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-5526 names 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 :237 never runs, and a later session.flush() cannot rescue a patch main never received. The gate
is 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 (:222 store.getState(), :233
buildWorkspaceSessionPatch(fresh, changed)) rather than from a captured diff, so any later mutation
of 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:

  1. RC3's precondition gets manufactured. An ungraceful death inside that window leaves a lease
    whose leaf the durable layout never recorded — which is precisely the absent-leaf state the graft
    requires.
  2. A pane close during a reconnect leaves the screen but is never durably recorded.
  3. "Absent from the durable layout" is therefore never trustworthy evidence for a destructive
    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).

# Commit What it can destroy
1 persistPtyBinding gains mayCreate: false; reattach may no longer create pane structure nothing — it can only decline to create
2 Two Store retirement primitives, and no third way to retire a lease nothing on its own; it constrains everything after
3 Pane-keyed supersede, terminal-state guard on the singular setter, orphan reaping, load-time migration a remote shell, via the reaper
4 Failed-attach exits converge on one retirement decision; a relay generation reset retires that target's leases a lease row only
5 Durable close intent recorded before the kill RPC a remote shell, but only on explicit user intent
6 The two e2e specs nothing
7 Relay incarnation token; bulk retirement pays one sync flush instead of N narrows #4 — retires strictly fewer leases
8 A revived lease no longer inherits the retired row's reap flag narrows #3
9 The reap drain is armed only inside the incarnation that minted the flags narrows #3 and #5

Commits 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, and
only the creating branches, already sets terminalMembershipChanged = true, so that flag is the
pane-existence predicate — already computed, already correct, and maintained by whoever edits the
function next. The function also already owns its rollback (cloneWorkspaceSessionState at :6625,
restoreSession() at :6640-6649). Under mayCreate: false a would-be-creating write restores,
skips the flush, and returns 'refused': skip registerPty, leave the lease detached, log, retry
next 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-6695 and
:6738-6743) and both need the guard, or there is a hole on exactly the legacy pane ids; and the clone
at :6625 precedes 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 (tiebreaking
createdAt then ptyId — the snapshot has three rows inside one second, so this must be specified and
tested, 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 null so the
whole row is filtered out at :3631-3633. Every test for a new durable field must round-trip
through 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 Store methods; nothing else writes
lease state directly.

Primitive Reaps the remote PTY? Callers
retireLeaseAndReap(targetId, ptyId, reason) yes — sets pendingRemoteShutdown supersede, close intent, migration
retireLeaseSparingPty(targetId, ptyId, reason) structurally cannot failed-attach exits, generation reset

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:329 says so outright, and the identity fence at :1610 exists for it — so
pty-1 in a new generation may be another pane's live shell. The identity-mismatch case is the
sharp one: pty-handler.ts:1597-1607 runs a liveness probe first and routes a dead PTY to a plain
not-found, so reaching the fence at :1610-1619 proves the remote process is alive and belongs to
another pane. Handing its id to the reaper would kill working sessions.

"Structurally cannot" is stronger than "does not" on purpose: retireLeaseSparingPty must neither
accept nor expose pendingRemoteShutdown in any form, so a future caller cannot opt in by passing a
flag. 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.
pendingRemoteShutdown asserts "relay id pty-N is ours to kill" — a claim that is only true of the
relay process that minted it, because the next incarnation restarts pty-N numbering 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.status proves 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 still
fails 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 from relay.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. The
fallback 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 fresh
spawn on a reset relay lands on a retired row's key. upsertSshRemotePtyLease merges over the
existing row, so retirement metadata was inherited by the new binding — handing a live pane's lease a
pendingRemoteShutdown it 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 after
    ssh.connect() returned
    already showed 3 SSH panes → 1, unchanged through 45 s, with zero
    reattach-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 churn
    that 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 no
    longer 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 of
    the 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 that
    reconstructs panes from a persisted root, and its single call site
    (use-terminal-pane-lifecycle.ts:1475) sits in a useEffect keyed [tabId, cwd]. So the pane comes
    back 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. ed00ab0f34 restored relay consumer ownership after an
    app 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 while
    eleven 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:kill is deliberately
    unchanged, 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 any
    of 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 cannot
contain renderer pane truth for an SSH worktree.
The renderer's session writer resolves an SSH-backed
worktree to the local host id — buildHostIdByWorktreeId ends in
return parsed?.kind === 'runtime' ? parsed.id : LOCAL_EXECUTION_HOST_ID
(src/renderer/src/lib/workspace-session-host-persistence.ts:204-208); only runtime:* is
partitioned out.
And main's own store code says where local lives, three times:
persistence.ts:569 ("'local' (the legacy workspaceSession blob) is dropped so the two surfaces
never diverge"), :581 ("a local/invalid key here is legacy noise that must not shadow the canonical
partition"), :3620 ("'local' stays in workspaceSession for downgrade compat"), with the parser
continue-ing on a local key at :582-584. The local partition is structurally absent from
workspaceSessionsByHostId.

(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:4610 and :4668 — and one main-side consumer
reads it, Store.clearSshRemotePtyBindingsForLeases, which unions it with the local session to clear
bindings 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). So afterClose === beforeClose there is
the 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) returns state.workspaceSession only for
LOCAL_EXECUTION_HOST_ID and state.workspaceSessionsByHostId[hostId] for every remote one. Hardcoding
either 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 searches
both partitions, reports which one answered, and both specs assert non-null before asserting
anything about the contents. A layout read that silently returns null forever turns every downstream
assertion 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 — Store invariants. Pane-keyed supersede across a different ptyId; legacy rows without a
complete identity are exempt and untouched; terminal states are terminal in fact, including the
specific 'detached'-over-'expired' write observed resurrecting a lease; retireLeaseSparingPty
leaves the reap queue empty; every new durable field round-trips through normalize.

Unit — mayCreate: false. One test per creating branch asserting 'refused' and an unchanged
session — covering both flush points and the legacy-leafId path — plus the non-creating rebind
asserting 'bound' with behavior identical to today.

Unit — retirement dispositions. Failed attach: transport-ish failure → detached, retry next
cycle, no retirement; relay says not-found → expired; identity mismatch → expired with the reap
queue 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.status failed),
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.ts drives the close-while-severed case that the seeded shape
below 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/detached in any sample, that the closed PTY id never appears in any pane's
dataset.ptyId, that the pane count never exceeds the post-close count, and that the id is gone from
ptyIdsByLeafId. The freeze is not incidental: a graceful disconnect unregisters the provider, so
pty:kill takes the tombstone fast-path and never issues the RPC that has to fail for this to be a
test of anything.

ssh-relay-redeploy-stale-pty-binding.spec.ts covers the generation-reset half. Both specs resolve the
tab from the renderer, not from a lease row — the lease's tabId is 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:

  • The freeze replaced a race, and only because the race was not runnable. RC3's natural producer is
    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.
  • If you seed leases instead, two traps make the test silently vacuous. Seed the profile-scoped
    store (profiles/<profileId>/orca-data.json), not path.join(userDataDir, 'orca-data.json') — the
    latter is a pre-migration path, and a run that used it returned "leasesAfter": null. And seed
    relay-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 attach
    time and the test asserts against a fan-out that never considered it.
  • Failure injection is mandatory. A clean reconnect loop passes on the unfixed build, because
    without a reattach failure no duplicate lease is minted.
  • Any close-related oracle must remount. Panes are reconstructed from the persisted root only by
    replayTerminalLayout, whose one call site is keyed [tabId, cwd], so a stranded leaf is invisible
    until 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.
  • The relay-death spec must not assert that panes are restored. They are genuinely dead; that
    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 🐋

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

SSH 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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed and on-topic but omits explicit Screenshots, AI Review Report, Security Audit, Notes, and completed testing checklist sections. Add the missing template sections, state whether visual artifacts exist, summarize AI and security reviews including cross-platform checks, and mark completed tests.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary SSH reconnect bug involving ghost terminal panes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Flush the incarnation removal even when no lease row was removed.

removeSshRemotePtyLeases clears sshRelayIncarnations for the target, but the flush is gated on this.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 of src/main/persistence.test.ts warns 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 win

Consider 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: when persistPtyBinding returns 'refused', restoreReattachedPtyRuntime must skip runtime.registerPty and the caller must leave the lease out of markSshRemotePtyLeasesAttachedAsync. That pair is the core of the no-ghost-pane fix, and a regression would be silent.

A test that stubs persistPtyBinding to 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 win

Reuse the shared createMockDeps fixture instead of maintaining parallel store mocks. src/main/ssh/ssh-relay-session-test-fixtures.ts already exports a createMockDeps that 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 future Store method 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 through as unknown as Store.

  • src/main/ssh/ssh-relay-session-terminal-error.test.ts#L110-L118: delete the local createMockDeps and import it from ./ssh-relay-session-test-fixtures; the shared version returns a superset of this file's fields, including mockWindow.
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts#L159-L167: build the store inside createSession from the shared fixture's mockStore rather than redeclaring it; note the local copy also omits persistPtyBinding, which the shared fixture provides.
src/main/persistence.ts (2)

1636-1642: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider bounding token length.

Neighbouring normalizers bound persisted strings (leafId at 256, retiredReason at 512). token comes 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 win

Avoid synchronous flush on SSH reconnect path writes.

setSshRelayIncarnation, clearAllSshRemotePtyLeaseReapFlags, and retireAllLeasesSparingPtys are reachable from reconnect/incarnation handling and each calls the synchronous full-state flush(), while live establish/reconnect paths already use flushDurableStateOrThrowAsync to avoid main-thread stalls on stalled profile mounts.

src/main/persistence.test.ts (1)

9836-9847: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add 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 asserts getSshRelayIncarnation returns null.

src/main/runtime/orca-runtime.test.ts (1)

2962-2985: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add the positive counterpart for a relay-driven expiry.

This test proves that an 'expired' lease carrying retiredReason is refused. It does not prove that an 'expired' lease without retiredReason still 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 calls createRuntimeWithSshLease(..., 'expired') with no reason and asserts recovery succeeds.

tests/e2e/helpers/docker-ssh-relay-processes.ts (1)

153-173: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse this helper in terminateDockerSshRelay.

terminateDockerSshRelay (Line 186) already runs the identical integer check and /proc validation chain, and differs only in the signal name. Route it through signalDockerSshRelay so 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9e42b5f and 31e77ac.

📒 Files selected for processing (25)
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/ssh.test.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session-lease-retirement.test.ts
  • src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts
  • src/main/ssh/ssh-relay-session-terminal-error.test.ts
  • src/main/ssh/ssh-relay-session-test-fixtures.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/relay.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-pi-coalesce.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-pi-spinner.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/shared/ssh-types.ts
  • src/shared/types.ts
  • tests/e2e/helpers/docker-ssh-relay-processes.ts
  • tests/e2e/helpers/persisted-terminal-layout.ts
  • tests/e2e/ssh-reconnect-no-ghost-pane-graft.spec.ts
  • tests/e2e/ssh-relay-redeploy-stale-pty-binding.spec.ts

Comment thread src/main/persistence.test.ts Resolved
Comment thread src/main/ssh/ssh-relay-session.ts Resolved
@dbachko

dbachko commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Thanks, this was a really bad bug

AmethystLiang and others added 13 commits August 5, 2026 01:57
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]>
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.
@AmethystLiang
AmethystLiang force-pushed the jinjing/sta-3077-ssh-remote-environment-not-restored-after-login-on-rocky branch from 31e77ac to 7679eff Compare August 5, 2026 22:26
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/persistence.test.ts (1)

9889-9889: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Strengthen the token-less assertion so it cannot pass on a null record.

getSshRelayIncarnation('target-2') returns null when 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c2a326 and 7679eff.

📒 Files selected for processing (31)
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/ssh.test.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session-lease-retirement.test.ts
  • src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts
  • src/main/ssh/ssh-relay-session-terminal-error.test.ts
  • src/main/ssh/ssh-relay-session-test-fixtures.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/relay.ts
  • src/renderer/src/components/sidebar/WorktreeCardSshHostControl.test.tsx
  • src/renderer/src/components/sidebar/WorktreeCardSshHostControl.tsx
  • src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-pi-coalesce.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-pi-spinner.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/shared/ssh-types.ts
  • src/shared/types.ts
  • tests/e2e/helpers/docker-ssh-relay-processes.ts
  • tests/e2e/helpers/persisted-terminal-layout.ts
  • tests/e2e/ssh-reconnect-no-ghost-pane-graft.spec.ts
  • tests/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

@nwparker

nwparker commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Your root-cause analysis here is what made #13111 possible — RC1 (lease identity has no pane key, and removeSshRemotePtyLease has exactly one caller so lease count is monotonically non-decreasing), RC2 (reattach fans out over every non-terminated lease; the relay fence compares each PTY against its own recorded pane key so both duplicates pass), and RC3 (the reattach write goes through a creating store method). I verified all three still reproduce on current main and cited them in the code comments.

#13111 is a smaller take on the same defect — ~180 production lines, rebased on current main — plus a fix for the duplicate-agent family (#12448, #11006, #12699): restoreRequired was reported as SSH_SESSION_EXPIRED, and the reattach handler treated every error as proof the session was gone, so a transport fault respawned a shell that resumed the same agent session into one transcript.

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.

@OrcaWin

OrcaWin commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

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.

@OrcaWin OrcaWin closed this Oct 11, 2026
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.

4 participants