Skip to content

fix(ssh): reap orphaned relay PTYs on reconnect before they exhaust the session cap - #9820

Closed
TrentFisher6 wants to merge 3 commits into
stablyai:mainfrom
TrentFisher6:fix/ssh-relay-pty-orphan-gc
Closed

TrentFisher6 wants to merge 3 commits into
stablyai:mainfrom
TrentFisher6:fix/ssh-relay-pty-orphan-gc

Conversation

@TrentFisher6

@TrentFisher6 TrentFisher6 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9819

Summary

On SSH remotes, relay PTY slots leak until every new terminal spawn fails with "Maximum number of PTY sessions reached (50)", and closing terminals/worktrees doesn't recover them. The relay daemon survives app restarts (reconnects cancel its grace window), slots are only freed by an explicit pty.shutdown, and nothing reconciled the relay's live PTY list with what the app still tracks. Terminals closed while the connection was down (lease tombstoned locally, remote PTY never killed), transient shutdown failures, and worktree teardown (which only sweeps the local provider) all leaked slots permanently. Full analysis in #9819.

User-visible change: after this fix, connecting or reconnecting to an SSH remote garbage-collects orphaned relay terminals, so long-running setups no longer hit the 50-session cap. No workflow or UI changes.

How it works

After reattachKnownPtys on both establish() and reconnect(), the session runs a best-effort orphan sweep:

  • lists the relay's PTYs and shuts down (immediate, no history) any entry the app no longer owns or holds a non-terminated/expired lease for
  • only reaps pane-bound PTYs (paneKey captured from ORCA_PANE_KEY at spawn) — bare relay shells such as remote-CLI sessions are never touched
  • skips entries younger than 30s so a spawn racing the sweep can never be reaped; the age (ageMs) is computed on the relay host's clock so local/remote clock skew can't weaken the guard, and the known set is built after listing so a spawn that lands mid-sweep counts as known
  • skips entries with no ageMs (relay predating this change) — age unknown, never reaped
  • every per-entry step (including id conversion) is inside a per-session try/catch; any failure logs and moves on, and the session always still reaches ready

To support this, the relay's pty.listProcesses now reports paneKey and ageMs (start time stamped in wireAndStore, covering both spawn and revive). Both fields are optional and additive; version skew in either direction degrades to "no reaping" rather than misbehavior.

Screenshots

image

Testing

  • pnpm lint — oxlint clean on every changed file; the full run fails only on a pre-existing switch-exhaustiveness error in src/renderer/src/components/skills/skill-freshness-group.tsx that reproduces identically on untouched origin/main in my environment
  • pnpm typecheck — clean
  • pnpm test — every suite touching this change passes (src/main/ssh, src/main/providers, src/relay/pty-handler.test.ts); the full run has 48 failures that reproduce identically on untouched origin/main in my environment (Node 26 vs the repo's required Node 24), all in files this PR does not touch
  • pnpm build — clean
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

New tests:

  • src/main/ssh/ssh-relay-session-orphan-pty-reap.test.ts: reaps orphans on establish and reconnect; spares bare shells, young spawns, unknown-age entries, and leased PTYs; a foreign-connection entry cannot abort the sweep or the session; a listProcesses failure still reaches ready
  • src/relay/pty-handler.test.ts: pty.listProcesses reports paneKey/ageMs

AI Review Report

Reviewed with Claude Code (Claude Fable 5), plus the CodeRabbit pass on this PR. Risks checked and outcomes:

  • Cross-platform (macOS/Linux/Windows): the relay change runs on remote hosts of all three platforms — it adds only Date.now() arithmetic and optional metadata fields; no paths, shortcuts, shell behavior, signals, or Electron platform differences are touched. The main-process sweep is platform-neutral. No renderer/UI changes.
  • SSH/remote/local compatibility: the sweep is SSH-provider-only and cannot touch local or daemon PTYs. Version skew both ways verified: old relay + new app → no ageMs → nothing reaped; new relay + old app → extra optional fields ignored.
  • Agent/integration compatibility: remote-CLI and any non-pane relay shells are exempt (no paneKey); agent panes in worktrees are pane-bound and correctly covered. The relay's per-instance socket means the sweep can only ever see PTYs created by this app install.
  • False-positive reaping (main risk): guarded three ways — pane-key requirement, relay-clock 30s age gate for in-flight spawns, and known-set computed after the relay listing. Flagged during review and fixed: the age gate originally compared a relay timestamp against the local clock (skew could weaken it); it now uses relay-computed ageMs.
  • Stability: CodeRabbit flagged that toRelaySshPtyId could throw outside the try/catch and tear down the session on a malformed entry — fixed by moving it inside the per-session try/catch, with a regression test.
  • Performance: one extra pty.listProcesses round-trip per connect/reconnect (not a hot path); shutdowns are sequential and bounded by the 50-session cap.

Security Audit

  • Input handling: session.id, paneKey, and ageMs come from the remote relay and are treated as untrusted — ids pass through the existing toRelaySshPtyId validation (throws on foreign connection ids, now safely contained per-entry), ageMs is type-checked, and paneKey is only used as an opaque presence marker and in a local console.warn.
  • Command execution: none added; the sweep only issues existing pty.shutdown RPCs back to the same relay the data came from.
  • Path handling / secrets / dependencies: none touched.
  • IPC: no new IPC surface; pty.listProcesses gains optional response fields only. markSshRemotePtyLease no-ops for unknown leases, so a hostile relay can't use the sweep to corrupt lease state beyond marking its own PTYs terminated.
  • Blast radius: worst case (all guards somehow bypassed) is a terminal the app owns being closed — the sweep can never touch other users' processes or other app installs' relays.

Notes

  • SSH-specific by design; local and WSL PTY providers are unaffected.
  • Old relays without ageMs are never reaped from — the fix fully activates once the relay redeploys (which happens automatically on version match failure).
  • Follow-up candidate (intentionally out of scope): make kill()'s close-while-disconnected path record a pending kill instead of tombstoning the lease, so orphans are prevented at the source rather than only GC'd.

🤖 Generated with Claude Code

ELI5

SSH relay PTY slots leaked across reconnects until new terminals hit the 50-session cap. On reconnect Orca reaps orphaned remote PTYs that the app no longer tracks so slots free up again.

@coderabbitai

coderabbitai Bot commented Jul 22, 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: 27a5b820-3538-4591-ac29-a032a96ed137

📥 Commits

Reviewing files that changed from the base of the PR and between bbe0d0db06606ad5c7791661313378a97a75597d and c8b5d701222b6467617deeb01fe587aaa97cf80d.

📒 Files selected for processing (7)
  • src/main/providers/pty-process-info.ts
  • src/main/providers/types.ts
  • src/main/ssh/ssh-relay-session-orphan-pty-reap.test.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/pty-handler.test.ts
  • src/relay/pty-handler.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/relay/pty-handler.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session-orphan-pty-reap.test.ts
  • src/relay/pty-handler.test.ts
  • src/main/ssh/ssh-relay-session.ts

📝 Walkthrough

Walkthrough

Adds pane-key and start-time metadata to PTY process records. SshRelaySession now performs age-gated orphan PTY reconciliation during establishment and reconnection, shutting down unknown pane-bound PTYs and terminating their leases while handling sweep failures without blocking readiness. New tests cover metadata reporting, orphan cleanup, exempt cases, reconnect behavior, provider failures, and updated provider mocks.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: reaping orphaned SSH relay PTYs on reconnect to avoid the session cap.
Description check ✅ Passed The description follows the template with summary, screenshots, testing, AI review, security audit, and notes.
Linked Issues check ✅ Passed The PR implements the linked fix: orphaned pane-bound relay PTYs are swept on establish/reconnect, with age and lease safeguards.
Out of Scope Changes check ✅ Passed No unrelated changes stand out; the new type/module and tests support the SSH relay PTY reaping work.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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: 8a58a338-6106-46a5-9a60-50a049e1e1e0

📥 Commits

Reviewing files that changed from the base of the PR and between 6e6b7d8 and db4267789521cdf73c4ef8610b34acefe23acf30.

📒 Files selected for processing (6)
  • src/main/providers/types.ts
  • src/main/ssh/ssh-relay-session-orphan-pty-reap.test.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/pty-handler.test.ts
  • src/relay/pty-handler.ts

Comment thread src/main/ssh/ssh-relay-session.ts Resolved
TrentFisher6 and others added 2 commits July 28, 2026 13:32
…he session cap

Nothing reconciled the relay's live PTY list with what the app still
tracks, so relay slots leaked until the 50-session cap blocked new
terminals ("Maximum number of PTY sessions reached (50)"):

- closing a terminal while the SSH connection is down tombstones the
  lease locally but never kills the remote PTY; reconnect then cancels
  the relay's grace window, so the orphan lives forever
- a transient pty.shutdown failure closes the pane with no retry
- worktree teardown only sweeps the local provider, never SSH relays

Fix: after reattachKnownPtys, list the relay's PTYs and shut down any
pane-bound entry (paneKey set) the app no longer owns or leases. Bare
relay shells (e.g. remote CLI) are never touched, and entries younger
than 30s are skipped so a spawn racing the sweep can't be reaped. The
relay now reports paneKey and startedAtMs in pty.listProcesses to
support this; the sweep is best-effort and never blocks session ready.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review follow-ups: keep toRelaySshPtyId inside the per-session try/catch
so one foreign/malformed entry can't abort the sweep or tear down the
session, and report relay-host-computed ageMs instead of startedAtMs so
local/remote clock skew can't defeat the young-spawn guard.

Co-Authored-By: Claude Fable 5 <[email protected]>
@TrentFisher6
TrentFisher6 force-pushed the fix/ssh-relay-pty-orphan-gc branch from c8b5d70 to cc4861b Compare July 28, 2026 20:35
Comment thread src/main/ssh/ssh-relay-session.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a relay PTY slot leak on SSH remotes where terminals closed while disconnected, transient shutdown failures, or worktree teardowns were not reflected back to the relay daemon, eventually exhausting the 50-session cap and blocking new terminal spawns.

  • Adds reapOrphanedRelayPtys() called after reattachKnownPtys on both establish() and reconnect(), which lists relay PTYs and shuts down pane-bound entries the app no longer tracks (by ownership registry or active lease), guarded against false positives via paneKey presence check, a relay-clock 30 s age gate, and a post-listing known-set build.
  • Extends the relay's ManagedPty and PtyProcessSummary types with optional paneKey and ageMs fields (stamped in wireAndStore covering both spawn and revive), enabling clients to identify pane-bound PTYs and age-gate reaping without being subject to local/remote clock skew.
  • Comprehensive new tests cover all guard paths (bare shells, young spawns, unknown-age entries, leased PTYs, foreign-connection entries, known-set build failures, and listProcesses failures) and verify the session always reaches ready.

Confidence Score: 5/5

Safe to merge — the sweep is entirely best-effort, isolated behind per-entry try/catch blocks, and cannot prevent the session from reaching ready under any failure mode.

The change is SSH-provider-scoped and touches no local, WSL, or renderer paths. Every guard against false-positive reaping is correctly implemented and independently tested.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/ssh/ssh-relay-session.ts Adds reapOrphanedRelayPtys() called after reattachKnownPtys on both establish and reconnect; correct ID-format handling, isolated per-entry try/catch, and known-set-build failure guard are all present and correct.
src/relay/pty-handler.ts Stamps startedAtMs via ??= in wireAndStore and adds paneKey/ageMs to listProcesses output; both fields are optional and additive.
src/main/providers/pty-process-info.ts Adds optional paneKey and ageMs to the shared PtyProcessInfo type; purely additive.
src/main/ssh/ssh-relay-session-orphan-pty-reap.test.ts New test file covering all guard paths and failure resiliency.
src/main/ssh/ssh-relay-session.test.ts Adds listProcesses and shutdown mocks to keep pre-existing tests passing.
src/relay/pty-handler.test.ts Verifies pty.listProcesses returns paneKey and ageMs correctly.

Reviews (2): Last reviewed commit: "fix(ssh): skip orphan sweep entirely whe..." | Re-trigger Greptile

Review follow-up: toRelaySshPtyId in the known-set construction could
throw on a corrupt ownership entry and escalate a harmless sweep into a
full connection teardown. Worse than aborting, a partial known set could
reap PTYs the app still owns — so any failure now skips the whole sweep.

Co-Authored-By: Claude Fable 5 <[email protected]>
@OrcaWin

OrcaWin commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

SSH still works: Orca connects to the host over SSH and routes workspace operations through the managed remote Orca server (orcad). These merges remove the legacy SSH relay, not SSH support.

Closing as obsolete after the merged SSH relay retirement in #27214 and #27215. This PR concerns the SSH relay PTY attach, recovery, replay, or lease lifecycle. #27214 removed the desktop relay connection/fallback path; #27215 deleted the SSH relay server, deployment assets, and relay-only tests. SSH hosts now use the managed Orca server (orcad), and unsupported hosts fail explicitly, so this relay-specific work is no longer planned. This closes the proposed relay implementation; it does not claim that any independent local, WSL, or managed-server behavior was 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

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SSH relay leaks orphaned PTY sessions until "Maximum number of PTY sessions reached (50)"

3 participants