Skip to content

fix(ssh): stop the absence fallback resuming an agent a replaced relay never held (STA-5698) - #16843

Closed
brennanb2025 wants to merge 2 commits into
mainfrom
brennan/sta-5698-bug-absence-fallback-re-runs
Closed

brennanb2025 wants to merge 2 commits into
mainfrom
brennan/sta-5698-bug-absence-fallback-re-runs

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

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, and resumeProviderSession.

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.status reports pid and uptimeMs (src/relay/relay-daemon.ts:128-131), and before this change uptimeMs had 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:

  • The daemon's start time is 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.
  • The binding's age is the SSH lease's 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.
  • If the daemon started after that moment, it demonstrably did not hold the PTY.

When that holds, main marks the SSH_SESSION_EXPIRED error the same way an identity mismatch is already marked, and the absence fallback:

  • still spawns the shell — the user asked for a terminal and is owed one;
  • declines launchAgent / command / resumeProviderSession;
  • raises the existing "previous session unavailable, started fresh" banner, so silence never reads as a successful restore.

A plain shell is a recoverable outcome. A duplicate agent racing an orphan over one worktree is not.

Deliberately narrow

  • The verdict never gates the spawn, and it is not a general "is the PTY alive" probe.
  • Only a relay that actually answers can produce it. A transport failure, a request timeout, a relay too old to report 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).
  • The relay.status call is bounded at 3s and only runs on the expiry path, after the relay has already answered once.
  • An identity mismatch is excluded: that id names a live PTY owned by another pane, which is not absence.

Wire compatibility

Client-side policy only, no wire change — relay.status already carries the fields, so this reaches old hosts unchanged (docs/reference/remote-wire-compatibility.md). Against a host too old to report uptimeMs, the verdict simply never fires and behaviour is identical to today.

Changes

Area Change
src/main/providers/ssh-relay-replacement-verdict.ts New. Asks relay.status, compares its start time against the lease's lastAttachedAt, marks the expiry. Every failure mode returns "no verdict".
src/main/providers/ssh-pty-errors.ts SSH_RELAY_REPLACED marker, alongside the existing SSH_PTY_IDENTITY_MISMATCH.
src/main/ipc/pty/{ipc,runtime}/spawn-execute.ts Ask for the verdict before the lease is expired, on both spawn pipelines.
src/main/persistence/.../ssh-pty-lease-operations.ts, ssh-lease-recovery-operations.ts getSshRemotePtyLease(targetId, ptyId) — a single-lease read using the same id normalisation as markSshRemotePtyLease.
src/renderer/.../relay-replaced-resume-suppression.ts New. Turns the marked expiry into the fallback's spawn arguments.
src/renderer/.../{deferred-session-attach,deferred-session-reattach-connect,reattach-result-handler}.ts Consume the verdict at all three absence-fallback sites (message-borne and result-borne).
src/renderer/.../fresh-spawn-{types,start}.ts notifyResumeUnavailable routes into the existing resume-unavailable banner rather than a second surface.
src/renderer/.../ipc-pty-connect.ts, pty-transport-types.ts Carry the marker onto the sessionExpired connect result.

deferred-session-attach.ts also collapses its two duplicated absence-fallback blocks into one local helper; that is what keeps it inside the max-lines budget.

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 no uptimeMs, 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 no launchAgent / resumeProviderSession / command / launchConfig / launchToken and raises the resume-unavailable banner — 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 tc and oxlint clean.

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 -9 on 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.status returned pid=1120, uptimeMs=270523 against a simultaneous remote clock sample of 1787859380091, putting its start at 1787859109568, about 159s after the lease was written at 1787858950290. 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:

  1. The orphan did not survive this death mode. kill -9 on 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 (the uncaughtException handler exiting without disposing PTYs), which is a different exit path and was not exercised here.
  2. The fallback did not re-run the agent in that run. The pane was in pendingActivationSpawn with 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 with ptys.active=0 and 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 launchAgent and resumeProviderSession. Once #16763 lands, that branch runs in main-process spawnForStablePane for 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 spawnForStablePane fallback as-is when that lands.

Residual risk

  • A backward system-clock jump between the last attach and the verdict could suppress a resume that was safe. The cost is a plain shell plus a banner, and the alternative machinery is not worth it.
  • Leases written by older builds may have no lastAttachedAt; those simply never produce a verdict.
  • The local (non-relay) daemon-restart case is untouched. relay.status is relay-only, and widening it is a separate change.

…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.
@coderabbitai

coderabbitai Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 43356

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the SSH relay-replacement fix and its effect on agent resume behavior.
Description check ✅ Passed 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 cle…
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.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7122d546-4bd4-48a9-81b5-6aa0845f99ea

📥 Commits

Reviewing files that changed from the base of the PR and between 9635e68 and 43356c5.

📒 Files selected for processing (17)
  • src/main/ipc/pty/ipc/spawn-execute.ts
  • src/main/ipc/pty/runtime/spawn-execute.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-pty-lease-operations.ts
  • src/main/persistence/loading-store/ssh-lease-recovery-operations.ts
  • src/main/providers/ssh-pty-errors.ts
  • src/main/providers/ssh-relay-replacement-verdict.test.ts
  • src/main/providers/ssh-relay-replacement-verdict.ts
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection-relay-replaced-resume-suppression.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deferred-session-attach.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.ts
  • src/renderer/src/components/terminal-pane/pty-connection/relay-replaced-resume-suppression.ts
  • src/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.

Comment on lines +35 to +45
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

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.

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

Suggested change
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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

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 kill -9 on the relay closed the pty master, the kernel delivered SIGHUP, and the shell and agent were gone in 0.3s. No orphan to collide with.

On Windows it is real, and for a different reason. Measured on Windows build 26200: after taskkill /F of a process owning a conpty, the shell died but a descendant survived. With one call to the addon's assignCurrentProcessToJob first, the whole tree was reaped at ~5s.

So the orphan is not something to detect on the client — it is something to prevent on the host:

  1. STA-5697 — the relay's uncaughtException handler cleans the socket and exits without disposing PTYs, even though the teardown already exists. A synchronous best-effort reap on that path removes the cause.
  2. Windows — the relay never joins a kill-on-close job (assignCurrentProcessToJob is called only from Orca's local main process), so a relay death that runs no handler reaps nothing. One call at daemon start, feature-detected.

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 pty.fork, POSIX_SPAWN_CLOEXEC_DEFAULT on macOS, bInheritHandles=false on Windows). Preventing the orphan is cheaper and certain.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant