Skip to content

fix(ssh): reconnect persisted PTYs after shutdown races - #8403

Merged
nwparker merged 6 commits into
stablyai:mainfrom
timsuchanek:fix/restore-ssh-pty-sessions
Jul 16, 2026
Merged

nwparker merged 6 commits into
stablyai:mainfrom
timsuchanek:fix/restore-ssh-pty-sessions

Conversation

@timsuchanek

@timsuchanek timsuchanek commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • preserve SSH reconnect targets when shutdown observes a transiently disconnected relay
  • derive startup reconnect targets from durable remote PTY session IDs as well as live SSH state
  • exclude runtime-owned (ephemeral-VM) targets and explicitly disconnected hosts from the eager startup dial
  • keep the patch writer's reconnect list in sync with terminal-field patches
  • add regression coverage for restart/update shutdown ordering, explicit-disconnect intent, runtime-owned exclusion (mutation-verified), and the patch-writer path

Root cause

Orca already persisted the surviving remote PTY ID after an SSH transport drop, but activeConnectionIdsAtShutdown only reflected the instantaneous connection-state map. If shutdown captured after the target became disconnected, startup had the PTY ID but did not reconnect the host needed to attach it.

Hardening added in review

  • Runtime-owned targets: session ids like ssh:runtime-ssh-*@@pty-N parse to runtime-owned connection ids that the old connected-states source could never contain (their state is never broadcast to the renderer). A renderer-driven startup ssh.connect to one would dispose the runtime layer's live VM relay session (doConnect tears down existing sessions). Excluded in the builder and filtered again at the App.tsx consumption boundary (main's windowless-promotion path can persist such ids independently).
  • User intent: an explicit Disconnect leaves status: 'disconnected' + a preserved relay session id — indistinguishable from the transient-drop shape by session data alone. Involuntary drops land in reconnecting/reconnection-failed/error, never disconnected, so the derivation requires a non-disconnected/auth-failed observed status. Excluded hosts still restore on tab focus via the deferred flow; only eagerness is withheld.
  • Patch-writer coherence: the list now derives from terminal fields too, so terminal-field patches recompute it alongside remoteSessionIdsByTabId — a crash between patches can no longer strand a stale target on disk.
  • Perf: the derivation takes the remote-session map as a required parameter (null = none), so the shutdown path never re-runs the repo/worktree scan (CodeRabbit's double-evaluation finding). Extracted to workspace-session-reconnect-targets.ts to stay within the max-lines budget.

Tests

  • workspace-session-liveness.test.ts: transient drop → included; explicit disconnect → excluded (session id still persisted); runtime-owned → excluded (mutation-verified: removing the guard fails the test)
  • workspace-session-patch.test.ts: terminal-field patches carry the derived reconnect list
  • Verified against a merge with current main: 419 tests across workspace-session/persistence/ssh-migration suites, web typecheck, oxlint, oxfmt, max-lines ratchet

@timsuchanek

Copy link
Copy Markdown
Contributor Author

@cubic-dev-ai please review

@AmethystLiang
AmethystLiang requested a review from Jinwoo-H July 13, 2026 16:47
@timsuchanek
timsuchanek marked this pull request as ready for review July 15, 2026 17:44
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c9c1e63f-bfe4-495b-9658-1e2a7db8865a

📥 Commits

Reviewing files that changed from the base of the PR and between d67ddf4 and be2c172.

📒 Files selected for processing (2)
  • src/renderer/src/lib/workspace-session-liveness.test.ts
  • src/renderer/src/lib/workspace-session-reconnect-targets.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/lib/workspace-session-reconnect-targets.ts
  • src/renderer/src/lib/workspace-session-liveness.test.ts

📝 Walkthrough

Walkthrough

Workspace shutdown persistence derives active SSH connection IDs from durable remote PTY session IDs alongside observed connection states. Payload and patch builders reuse computed terminal session data, while startup reconnect excludes runtime-owned targets. Tests cover reconnecting, explicitly disconnected, and runtime-owned SSH sessions.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary, root cause, hardening, and tests, but omits required screenshots, AI review report, security audit, and notes sections. Add the missing template sections, including screenshots/no visual change, testing checklist, AI review report, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main fix: restoring SSH reconnect targets after shutdown races.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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

Run ID: 3374f43b-aa7d-46de-a0cb-22a0f56892ef

📥 Commits

Reviewing files that changed from the base of the PR and between 26934b1 and e5cd298.

📒 Files selected for processing (2)
  • src/renderer/src/lib/workspace-session-liveness.test.ts
  • src/renderer/src/lib/workspace-session.ts

nwparker and others added 3 commits July 16, 2026 01:45
- exclude runtime-owned (ephemeral-VM) targets: a renderer-driven startup
  ssh.connect would dispose the runtime layer's live relay session
- exclude explicitly disconnected / auth-failed targets so startup never
  dials a host the user chose to leave offline (sessions still restore
  on tab focus via the deferred flow)
- avoid re-running buildTerminalSessionData via the default parameter
  when the remote-session map is legitimately empty (null sentinel)
- recompute activeConnectionIdsAtShutdown alongside terminal-field
  patches so a crash between patches cannot strand a stale target
- pin all of the above with tests, including the patch-writer path

Co-authored-by: Orca <[email protected]>
Main's windowless-promotion path can persist runtime-owned ids into
activeConnectionIdsAtShutdown; renderer must never dial those.

Co-authored-by: Orca <[email protected]>
Give the runtime-owned fixture a transient status so the status gate
alone cannot exclude it; verified by mutation (guard removal fails).

Co-authored-by: Orca <[email protected]>

@nwparker nwparker 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.

Reviewed adversarially (two independent verification passes, mutation-tested the new guards). The root-cause analysis is correct and the fix direction is right: activeConnectionIdsAtShutdown only reflected the instantaneous connection-state map, so a shutdown captured mid-relay-drop persisted the surviving PTY id but never reconnected its host, stranding the session until manual tab focus.

I pushed three hardening commits on top (thanks for maintainer-edit access):

1. d956bca — derivation hardening. The original union had three issues found in review:

  • Runtime-owned (ephemeral-VM) targets leaked into the eager-connect list. ssh:runtime-ssh-*@@pty-N session ids parse to runtime-owned connection ids, which the old connected-states source could never contain (their state changes are never broadcast to the renderer). Worse than a wasted call: doConnect doesn't guard runtime-owned ids and disposes any existing session, so a renderer-driven startup connect could tear down the runtime layer's live VM relay. Now excluded, pinned by a mutation-verified test.
  • Explicit user disconnects became auto-dials at next launch. An intentional Disconnect leaves status: 'disconnected' plus a preserved lastKnownRelayPtyIdByTabId entry — exactly the state shape of the new test — so the union couldn't distinguish user intent from a transient drop. Involuntary drops land in reconnecting/reconnection-failed/error, never disconnected, so the gate now requires a non-disconnected/auth-failed observed status. Sessions on excluded hosts still restore on tab focus via the deferred flow; only eagerness is withheld.
  • CodeRabbit's double-evaluation finding — when the map is legitimately empty (undefined), explicitly passing it re-triggered the default initializer's second full buildTerminalSessionData scan in the shutdown-critical path. Fixed with a null sentinel.

Also: the patch writer only recomputed the list on sshConnectionStates changes, but the list now derives from terminal fields too — closing all tabs of a disconnected host then crashing left a stale target on disk that startup would dial. The terminal-fields patch branch now carries the derived list (reusing its already-computed terminalSessionData, so no extra scan).

2. aa8f78d — consumption-side filter. Main's windowless-promotion path (persistWindowlessPtyBindingsForDesktopAttach) can persist runtime-owned ids into this list independently of the renderer builder, so App.tsx startup also filters them at the consumption boundary.

3. cb0eb89 — test pinning. The runtime-owned test fixture originally passed via the status gate alone (no status entry); it now carries a transient status so only the runtime-owned check can exclude it — verified by mutation (removing the guard fails the test).

Verified clean on a merge with current main: 419 tests across the workspace-session/persistence/ssh-migration suites, web-renderer typecheck, oxfmt. Known trade-off (accepted): a target whose automatic reconnect ended in auth-failed at shutdown (e.g. ssh-agent briefly unavailable) loses the eager dial but keeps full restore-on-focus — preferable to stacking credential dialogs at startup.

workspace-session.ts crossed the max-lines budget; the derivation is a
self-contained concern (session ids + live SSH state -> startup targets).
Parameter is now required (null = none) since every caller has the
terminal session data or must opt into the scan explicitly.

Co-authored-by: Orca <[email protected]>

@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

Run ID: 7b40285e-0d96-448a-be9a-32a395498a70

📥 Commits

Reviewing files that changed from the base of the PR and between cb0eb89 and d67ddf4.

📒 Files selected for processing (3)
  • src/renderer/src/lib/workspace-session-patch.ts
  • src/renderer/src/lib/workspace-session-reconnect-targets.ts
  • src/renderer/src/lib/workspace-session.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/workspace-session-patch.ts

…h too

A pane-level optimistic write can stamp a runtime-owned connection state;
the live 'connected' filter must apply the same exclusion as the
session-id union (CodeRabbit review finding). Pinned in the test on both
paths.

Co-authored-by: Orca <[email protected]>
@iridite

iridite commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Field report: after v1.4.144 shipped (which includes this PR), I'm seeing a notable increase in unexpected app exits where Electron Utility subprocesses receive SIGTERM with expectedTeardown: 'none' — 6 crashes on Jul 17 alone vs 7 across the prior 5 days combined.

I've opened #9191 with the full data. The key observations that may connect to this PR:

  1. Crashes happen at ~10-20 min after startup with zero user interaction (no SSH worktree switches). A background timer at a similar interval is the most likely trigger.
  2. terminal_replay_guard_wedged_release events (always paneId: 1, bursts of 4-9) happened 49 times across Jul 13-16 and stopped completely after v1.4.144. This suggests the terminal reconnection behavior changed — the wedge may have been fixed, or the failure mode shifted.

This may be unrelated to this PR's specific changes — but the timing is exact and the prior versions didn't show this crash frequency. Flagging here in case it helps narrow down the root cause.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(ssh): reconnect persisted PTYs after shutdown races

* fix(ssh): harden shutdown reconnect-target derivation

- exclude runtime-owned (ephemeral-VM) targets: a renderer-driven startup
  ssh.connect would dispose the runtime layer's live relay session
- exclude explicitly disconnected / auth-failed targets so startup never
  dials a host the user chose to leave offline (sessions still restore
  on tab focus via the deferred flow)
- avoid re-running buildTerminalSessionData via the default parameter
  when the remote-session map is legitimately empty (null sentinel)
- recompute activeConnectionIdsAtShutdown alongside terminal-field
  patches so a crash between patches cannot strand a stale target
- pin all of the above with tests, including the patch-writer path

Co-authored-by: Orca <[email protected]>

* fix(ssh): filter runtime-owned targets at startup reconnect consumption

Main's windowless-promotion path can persist runtime-owned ids into
activeConnectionIdsAtShutdown; renderer must never dial those.

Co-authored-by: Orca <[email protected]>

* test(ssh): pin runtime-owned exclusion independently of the status gate

Give the runtime-owned fixture a transient status so the status gate
alone cannot exclude it; verified by mutation (guard removal fails).

Co-authored-by: Orca <[email protected]>

* refactor(session): extract reconnect-target derivation to its own module

workspace-session.ts crossed the max-lines budget; the derivation is a
self-contained concern (session ids + live SSH state -> startup targets).
Parameter is now required (null = none) since every caller has the
terminal session data or must opt into the scan explicitly.

Co-authored-by: Orca <[email protected]>

* fix(ssh): exclude runtime-owned targets from the connected-states path too

A pane-level optimistic write can stamp a runtime-owned connection state;
the live 'connected' filter must apply the same exclusion as the
session-id union (CodeRabbit review finding). Pinned in the test on both
paths.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Neil <[email protected]>
Co-authored-by: Orca <[email protected]>
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