Repository navigation
fix(ssh): stop the absence fallback resuming an agent a replaced relay never held (STA-5698) - #16843
brennanb2025 wants to merge 2 commits into
Conversation
…y never held (STA-5698) When a stable pane's reattach fails with positive absence, the fallback spawns a fresh shell using the original request's options — including `launchAgent`, `command` and `resumeProviderSession`. On a cold restore that is right. After a relay daemon replacement it is not: the binding names a PTY from a previous daemon whose shell can still be alive as an orphan, so re-running the resume puts a second agent on the same worktree. `relay.status` already reports `uptimeMs`, and nothing consulted it. A daemon whose start time (our clock minus its uptime — a duration carries no skew) post-dates the last attach we recorded for that lease demonstrably did not hold that PTY. Main now asks exactly once, on the expiry path, and marks the `SSH_SESSION_EXPIRED` error the way an identity mismatch is already marked. The fallback then still spawns the shell the user asked for, declines the resume, and raises the existing "previous session unavailable, started fresh" banner. Deliberately narrow: the verdict never gates the spawn, and only a relay that actually answers can produce it. A transport failure, a timeout, a relay too old to report `uptimeMs`, or a lease with no attach on record all leave the fallback exactly as it was — loss of contact is never evidence. Client-side policy with no wire change, so it reaches old hosts unchanged.
📝 WalkthroughWalkthroughThe change detects when an SSH relay was replaced after the last PTY attachment. It records this state in expired-session errors and propagates it through IPC. Renderer recovery paths suppress agent resume for replaced relays, start a plain shell, and show the resume-unavailable banner. New tests cover relay uptime verdicts and PTY absence fallback behavior. Merge Risk: 🔵 Low · up to The PR prevents duplicate agent resumes after relay replacement, but its timing-based decision can be affected by status-response latency or clock uncertainty, causing either a valid resume to be replaced by a fresh shell or duplicate-resume protection to remain inactive. The impact is bounded to SSH recovery, but the timestamping behavior should be explicitly addressed or accepted. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed and on topic. It explains the problem, solution, scope, compatibility, testing, residual risk, and linked issue. It also describes the behavior change and test coverage clearly.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7122d546-4bd4-48a9-81b5-6aa0845f99ea
📒 Files selected for processing (17)
src/main/ipc/pty/ipc/spawn-execute.tssrc/main/ipc/pty/runtime/spawn-execute.tssrc/main/persistence/leasing-ssh-ptys/ssh-pty-lease-operations.tssrc/main/persistence/loading-store/ssh-lease-recovery-operations.tssrc/main/providers/ssh-pty-errors.tssrc/main/providers/ssh-relay-replacement-verdict.test.tssrc/main/providers/ssh-relay-replacement-verdict.tssrc/renderer/src/components/terminal-pane/ipc-pty-connect.tssrc/renderer/src/components/terminal-pane/pty-connection-relay-replaced-resume-suppression.test.tssrc/renderer/src/components/terminal-pane/pty-connection/deferred-session-attach.tssrc/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-connect.tssrc/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.tssrc/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-types.tssrc/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.tssrc/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.tssrc/renderer/src/components/terminal-pane/pty-connection/relay-replaced-resume-suppression.tssrc/renderer/src/components/terminal-pane/pty-transport-types.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| status = await args.requestHostRpc('relay.status', {}, { timeoutMs: RELAY_STATUS_TIMEOUT_MS }) | ||
| } catch { | ||
| return false | ||
| } | ||
| const uptimeMs = (status as { uptimeMs?: unknown } | null | undefined)?.uptimeMs | ||
| if (typeof uptimeMs !== 'number' || !Number.isFinite(uptimeMs) || uptimeMs < 0) { | ||
| return false | ||
| } | ||
| // Round-trip latency inflates the uptime we read, ageing the daemon — which can only ever | ||
| // withdraw the verdict, never invent one. | ||
| return (args.now ?? Date.now)() - uptimeMs > args.lastAttachedAtMs |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Capture the status request time before the RPC. Line 45 samples time after the response, so response latency can mark an older relay as replaced and suppress agent resume. Use a pre-request timestamp as the conservative start-time bound.
Proposed fix
+ const statusRequestedAt = (args.now ?? Date.now)()
let status: unknown
try {
status = await args.requestHostRpc('relay.status', {}, { timeoutMs: RELAY_STATUS_TIMEOUT_MS })
@@
- return (args.now ?? Date.now)() - uptimeMs > args.lastAttachedAtMs
+ return statusRequestedAt - uptimeMs > args.lastAttachedAtMs📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| status = await args.requestHostRpc('relay.status', {}, { timeoutMs: RELAY_STATUS_TIMEOUT_MS }) | |
| } catch { | |
| return false | |
| } | |
| const uptimeMs = (status as { uptimeMs?: unknown } | null | undefined)?.uptimeMs | |
| if (typeof uptimeMs !== 'number' || !Number.isFinite(uptimeMs) || uptimeMs < 0) { | |
| return false | |
| } | |
| // Round-trip latency inflates the uptime we read, ageing the daemon — which can only ever | |
| // withdraw the verdict, never invent one. | |
| return (args.now ?? Date.now)() - uptimeMs > args.lastAttachedAtMs | |
| const statusRequestedAt = (args.now ?? Date.now)() | |
| status = await args.requestHostRpc('relay.status', {}, { timeoutMs: RELAY_STATUS_TIMEOUT_MS }) | |
| } catch { | |
| return false | |
| } | |
| const uptimeMs = (status as { uptimeMs?: unknown } | null | undefined)?.uptimeMs | |
| if (typeof uptimeMs !== 'number' || !Number.isFinite(uptimeMs) || uptimeMs < 0) { | |
| return false | |
| } | |
| // Round-trip latency inflates the uptime we read, ageing the daemon — which can only ever | |
| // withdraw the verdict, never invent one. | |
| return statusRequestedAt - uptimeMs > args.lastAttachedAtMs |
|
Closing in favour of a different fix. Investigation summary: this PR detected a possible orphan by inference (relay uptime vs. the lease's last attach). Review blocked it because an age comparison convicts any younger relay, including after a host reboot where no orphan can exist, so every SSH pane on that host silently loses its agent resume. Two things changed the approach: A live repro could not produce the harm on Linux. It reproduced the precondition exactly — positive absence, a demonstrably younger daemon — but On Windows it is real, and for a different reason. Measured on Windows build 26200: after So the orphan is not something to detect on the client — it is something to prevent on the host:
Every guard considered — uptime, daemon nonce, host boot id, an inherited-fd liveness token — fails open in some cases and fails closed in others, and the fd-token design is not even buildable with the vendored node-pty (fixed 11-arg The renderer half of this PR (spawn the shell, decline the resume, banner) is not lost work — it is the correct outcome if a guard is ever justified. If prevention proves insufficient, the mechanism to build is a pid + start-time probe, which Orca already implements for its local daemon. |
Fixes STA-5698.
What was wrong
When a stable pane's reattach fails with positive absence — the relay answers for that exact PTY id and reports it absent — Orca falls back to a fresh spawn built from the original request's options. Those options still carry
launchAgent,command, andresumeProviderSession.On a cold restore that is exactly right. After a relay daemon replacement it is not. A restarted relay has no record of any pre-restart id, so it reports every one of them absent, and the pane's binding names a PTY the previous daemon created — whose shell can still be alive as an orphan (that orphan is the sibling ticket, STA-5697). Re-running the resume then starts a second agent against the same worktree.
The client could already tell and never looked:
relay.statusreportspidanduptimeMs(src/relay/relay-daemon.ts:128-131), and before this changeuptimeMshad exactly one reference in the tree — the producer.The fix
On the expiry path, main asks the relay once whether it post-dates the binding it was asked to restore:
Date.now() - uptimeMs. A duration carries no clock skew, so anchoring it to our own clock makes it directly comparable to a timestamp we wrote ourselves.lastAttachedAt— the last moment we positively attached that PTY. It is refreshed on every successful spawn/attach commit and, crucially, only for PTYs a reconnect actually reattached, so it never claims proof we do not have.When that holds, main marks the
SSH_SESSION_EXPIREDerror the same way an identity mismatch is already marked, and the absence fallback:launchAgent/command/resumeProviderSession;A plain shell is a recoverable outcome. A duplicate agent racing an orphan over one worktree is not.
Deliberately narrow
uptimeMs, or a lease with no attach on record all produce no verdict and leave the fallback byte-for-byte as it was. Loss of contact is never evidence (docs/reference/ssh-execution-boundary.md).relay.statuscall is bounded at 3s and only runs on the expiry path, after the relay has already answered once.Wire compatibility
Client-side policy only, no wire change —
relay.statusalready carries the fields, so this reaches old hosts unchanged (docs/reference/remote-wire-compatibility.md). Against a host too old to reportuptimeMs, the verdict simply never fires and behaviour is identical to today.Changes
src/main/providers/ssh-relay-replacement-verdict.tsrelay.status, compares its start time against the lease'slastAttachedAt, marks the expiry. Every failure mode returns "no verdict".src/main/providers/ssh-pty-errors.tsSSH_RELAY_REPLACEDmarker, alongside the existingSSH_PTY_IDENTITY_MISMATCH.src/main/ipc/pty/{ipc,runtime}/spawn-execute.tssrc/main/persistence/.../ssh-pty-lease-operations.ts,ssh-lease-recovery-operations.tsgetSshRemotePtyLease(targetId, ptyId)— a single-lease read using the same id normalisation asmarkSshRemotePtyLease.src/renderer/.../relay-replaced-resume-suppression.tssrc/renderer/.../{deferred-session-attach,deferred-session-reattach-connect,reattach-result-handler}.tssrc/renderer/.../fresh-spawn-{types,start}.tsnotifyResumeUnavailableroutes into the existingresume-unavailablebanner rather than a second surface.src/renderer/.../ipc-pty-connect.ts,pty-transport-types.tssessionExpiredconnect result.deferred-session-attach.tsalso collapses its two duplicated absence-fallback blocks into one local helper; that is what keeps it inside themax-linesbudget.Tests
Both new suites were confirmed to fail without the fix and pass with it.
src/main/providers/ssh-relay-replacement-verdict.test.ts— marks a younger relay; stays silent for an older relay, an unreachable relay, a relay with nouptimeMs, a lease with no attach, and no lease at all (and does not even issue the RPC in the last two).src/renderer/.../pty-connection-relay-replaced-resume-suppression.test.ts— drives the real pane connect path over SSH. Asserts the derived outcome: an unmarked expiry still resumes the agent (guarding against over-suppression), and a marked expiry spawns a shell carrying nolaunchAgent/resumeProviderSession/command/launchConfig/launchTokenand raises theresume-unavailablebanner — covered both for the message-borne and the result-borne expiry.Also green: cold-restore agent resume, direct-SSH reattach retry, sleeping-resume banner, SSH remote PTY leases, SSH PTY provider spawn + reattach incarnation, PTY persisted-incarnation repair, listener teardown/orphans, provider dispatch.
pnpm tcandoxlintclean.Reproduction
Run against a throwaway Linux Docker SSH target with a real repo, an isolated Electron dev instance driven over CDP, and a stub agent that logs its argv. Partially reproduced — the precondition reproduces exactly, the duplicate-agent end state did not fire in that particular pane state.
Reproduced. After
kill -9on the relay daemon, the replacement daemon answered for the exact PTY id and reported it absent —PTY "pty-2" not found→SSH_SESSION_EXPIRED: pty-2— so this is positive absence, not loss of contact. And the answering daemon was demonstrably younger than the binding:relay.statusreturnedpid=1120, uptimeMs=270523against a simultaneous remote clock sample of1787859380091, putting its start at1787859109568, about 159s after the lease was written at1787858950290. That is the predicate this PR adds, evaluating true on live data from a real relay replacement.Did not reproduce. Two things, both worth stating plainly:
kill -9on the daemon reaped its node-pty children — the stub agent (pid 875) and both shells were gone 0.3s later. The orphan the ticket describes comes from the sibling issue STA-5697 (theuncaughtExceptionhandler exiting without disposing PTYs), which is a different exit path and was not exercised here.pendingActivationSpawnwith a direct-SSH retry armed, so it kept re-attaching the dead session id instead of falling through to a fresh spawn; the new daemon ended withptys.active=0and the stub agent log had exactly one invocation, with no--resume. That is a real finding about the restore path, and it is separate from this ticket — it is the gap fix(ssh): a relay that reports a PTY absent must authorise a fresh spawn #16763 exists to close.So the harm is demonstrated as a reachable code path rather than as a live duplicate agent: the re-run branch is covered by the control case in the new renderer suite, which drives the real pane connect path and asserts that an unmarked expiry still spawns with
launchAgentandresumeProviderSession. Once #16763 lands, that branch runs in main-processspawnForStablePanefor every positive absence, unconditionally.Separately confirmed against a real profile: every SSH lease on disk carries
lastAttachedAt, so the guard's input is populated in practice rather than only in tests.Relationship to #16763
#16763 introduces the same fallback on the main-process SSH path and names this risk in its safety section. It is currently a draft and conflicting with main, so this PR is written against main, where the identical re-run already happens through the renderer's absence fallback. The verdict lives in main next to the relay handle and the lease, so it is available to #16763's
spawnForStablePanefallback as-is when that lands.Residual risk
lastAttachedAt; those simply never produce a verdict.relay.statusis relay-only, and widening it is a separate change.