Skip to content

fix(ssh): handle owner displacement and graceful shutdown - #12367

Merged
AmethystLiang merged 8 commits into
mainfrom
ssh-unable-to-connect-issue
Aug 4, 2026
Merged

AmethystLiang merged 8 commits into
mainfrom
ssh-unable-to-connect-issue

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix SSH reconnect lockouts by allowing a reconnect with valid logical-owner proof to displace a half-open incumbent, while serializing overlapping owner publications behind a bounded retry. Also fence reset-created transports once committed app shutdown has started.

What changed

  • Keep ownerLease stable for the lifetime of one logical ownership claim.
  • Keep ownerGeneration as the per-admission delivery fencing epoch.
  • Match recovery on lease, client instance, and authenticated principal; an older generation can identify the same claim but receives a fresh generation when admitted.
  • Preserve the two-phase publication fence and use coded -32042 retry while one owner response is settling.
  • Revoke and close a displaced incumbent only after the replacement grant publishes.
  • Re-check the committed shutdown gate before ssh:resetRelay opens a replacement transport.
  • Drain active SSH sessions and bounded in-flight work during quit.

Reliability contract

  • Invariant (agent-session.provider-ownership): one published SSH PTY owner generation has write authority at a time; reconnecting the same logical owner cannot be permanently rejected merely because another grant publication is settling.
  • Failure source: network loss or sleep can leave the incumbent socket half-open, and closely spaced reconnect attempts can overlap while the first replacement response is still publishing.
  • Oracle: deterministic session and relay tests hold the first replacement response pending, require the second attempt to receive the coded pending refusal, settle the first response, then require the second attempt to succeed using its original proof with a higher fencing generation. Rollback and connection-close interleavings retain the incumbent.
  • Gate: agent-session.provider-ownership tracks the single-owner authority contract; terminal-performance.output-backpressure-budget covers the SSH relay response-settlement, generation-fencing, and reconnect paths. Both gates remain experimental/partial.
  • Provider/platform coverage: direct SSH/relay is covered by deterministic tests. Local PTY, daemon PTY, WSL routing, folder workspaces, and Git providers are unaffected. The wire shape and persisted schema are unchanged, so older mobile clients see no new required field. Relay builds succeed for macOS, Linux, Windows, x64, and arm64.
  • Performance budget: matching and admission remain O(1); no polling, scans, subprocesses, or unbounded state were added. The new pending-publication retry is capped at three seconds and stops when attempt authority or the channel is lost.
  • Diagnostics: pending publication has a stable numeric code; relay loss, displacement, and terminal version failures keep their existing bounded logs and surfaced status.
  • Residual gaps: no live physical half-open SSH connection is exercised locally. Final quit-snapshot ordering, full SSH-local shutdown budgeting, explicit held-owner taxonomy, and recovery-contract cleanup remain follow-up work.

Verification

  • 719 focused ownership, dispatcher, relay, recovery, shutdown, and persistence tests
  • Node typecheck
  • Changed-code quality gate
  • Max-lines ratchet
  • Relay build for all supported target bundles
  • Existing PR package and Windows package checks

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The changes add bounded SSH shutdown handling to the application quit sequence. SSH work is fenced during shutdown, active sessions are detached, transports are disconnected, and in-flight operations are drained. Owner recovery now retries pending publication errors with lifecycle guards. PTY consumer sessions validate hello data, track displaced owners, support rollback-safe takeovers, and clean up displaced relay clients. Tests cover shutdown races, recovery retries, durability, validation, and owner displacement.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description has a detailed summary and verification, but it omits the required Screenshots, Testing, AI Review Report, Security Audit, and Notes sections. Add all required template sections, including test checkboxes, UI-change status, AI review and cross-platform checks, security audit findings, and notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 21.05% 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 summarizes the main SSH owner-displacement and graceful-shutdown changes.
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 💡 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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0f935f15-bc70-4a5e-88d6-c14c60f54858

📥 Commits

Reviewing files that changed from the base of the PR and between 98e8d1c and a510744.

📒 Files selected for processing (14)
  • src/main/index.ts
  • src/main/ipc/ssh.test.ts
  • src/main/ipc/ssh.ts
  • src/main/ssh/ssh-owner-recovery-retry.test.ts
  • src/main/ssh/ssh-owner-recovery-retry.ts
  • src/main/ssh/ssh-relay-session-recovery-durability.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/dispatcher.ts
  • src/relay/relay-pty-consumer-owner-displacement.test.ts
  • src/relay/ssh-pty-consumer-session-adapter.ts
  • src/shared/pty-consumer-session-contract.ts
  • src/shared/pty-consumer-session-hello.ts
  • src/shared/pty-consumer-session.test.ts
  • src/shared/pty-consumer-session.ts

Comment thread src/main/ipc/ssh.test.ts Resolved
Comment thread src/main/ipc/ssh.ts Resolved

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/ipc/ssh.ts (1)

1317-1318: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Fence the reset transport immediately before it opens.

Line 1318 only fences reset admission. If shutdown starts while doResetRelay() waits for inFlightConnect.promise, doResetRelay() can later call connectionManager.connect(target) without checking the gate again. That transport can open after the bounded join and final drain.

Check quitTeardownStartGate immediately before the fallback connectionManager.connect(target) call. Add a shutdown-race test for a reset paused behind an in-flight connect.

Proposed fix
 const existingConn = connectionManager!.getConnection(targetId)
-const conn = existingConn ?? (await connectionManager!.connect(target))
+let conn = existingConn
+if (!conn) {
+  assertSshConnectsNotFenced()
+  conn = await connectionManager!.connect(target)
+}

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7a882aea-152a-451a-9d3e-1e7d9ca84fd4

📥 Commits

Reviewing files that changed from the base of the PR and between a510744 and 8ea9d53.

📒 Files selected for processing (7)
  • src/main/index.ts
  • src/main/ipc/ssh.test.ts
  • src/main/ipc/ssh.ts
  • src/main/quit-teardown-start-gate.ts
  • src/main/ssh/ssh-relay-session-recovery-durability.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/relay-pty-consumer-owner-displacement.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/index.ts
  • src/main/ssh/ssh-relay-session.ts

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/ipc/ssh.ts (1)

1109-1113: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Handle cancelled doConnect after connectionManager.connect() completes.

The manager deletes and disconnects a cancelled in-flight connect when it later resolves. But doConnect then checks ownsSession() and rethrows createCancelledConnectAttemptError() at the later call site, so that cleanup may be undone by the surrounding error branch instead of leaving the transport disconnected. Close and remove only the exact connection that resolved late, and still clean up its session/transport when session.establish() resumes after invalidation. Cover the delayed resolution case in the connect-fence shutdown drain tests.

🧹 Nitpick comments (2)
src/shared/pty-consumer-session.test.ts (1)

254-302: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider consolidating the two overlapping-recovery tests.

The two tests differ only in the settlement call (commitPublication vs rollbackPublication) and the expected displacedOwner.connectionId. A describe.each or it.each table would remove the duplicated setup and make the contract difference explicit.

Also consider asserting the state of the losing owner after the retry. In the commit case, connection-1 should already be gone. In the rollback case, connection-2 should no longer hold the owner grant. Neither test checks that today.

src/relay/relay-pty-consumer-owner-displacement.test.ts (1)

298-308: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The captured settlement can point at the wrong frame.

firstReconnectSettlement is reassigned on every write to the first reconnect client. Line 335 settles whichever write happened last. If the dispatcher writes a keepalive or any other frame to that client before line 335, the test settles the wrong frame and the assertions become misleading rather than failing clearly.

Consider capturing only the first unsettled write, or asserting the frame identity before settling.

♻️ Capture the first pending settlement only
     const firstReconnectClientId = dispatcher.attachClient(
       (data, settle) => {
         firstReconnectWrites.push(Buffer.from(data))
-        firstReconnectSettlement = settle
+        firstReconnectSettlement ??= settle
         return true
       },

Also applies to: 335-335


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f1236fc7-59aa-41b2-9558-befe1fee330e

📥 Commits

Reviewing files that changed from the base of the PR and between 460f3cf1c40af5b42f7b721ba97518ca47e8a78e and a5574a8bfa1d7b07b7d5e0c92dafc2a67879bc35.

📒 Files selected for processing (5)
  • src/main/ipc/ssh.test.ts
  • src/main/ipc/ssh.ts
  • src/relay/relay-pty-consumer-owner-displacement.test.ts
  • src/shared/pty-consumer-session.test.ts
  • src/shared/pty-consumer-session.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/pty-consumer-session.ts
  • src/main/ipc/ssh.test.ts

@AmethystLiang
AmethystLiang force-pushed the ssh-unable-to-connect-issue branch from a5574a8 to 2a27589 Compare August 4, 2026 05:20
SSH connections can reconnect with valid session proof after network loss or
device sleep. When the incumbent owner is still half-open, allow the
reconnecting client to displace it outright rather than wait for socket closure
— a window that may never close. Retain displaced deliveries for the new owner
to rotate. During app shutdown, drain SSH sessions without terminating recovery
operations, and retry pending owner grants in case a replacement commits mid-drain.
Make QuitTeardownStartGate a shared singleton so SSH connects use the
same shutdown fence as the main quit path. Track test-connection probes
to ensure they complete before final teardown. Guard owner displacement
to prevent stale owners from clearing recovery state claimed by newer
owners.
Test was using tick-based Promise.resolve() loops which don't guarantee
the async operation has started. Replace with signal-based synchronization
that waits for the actual lease flush. Also add nullish-coalescing to
error code check to prevent crashes if error is null or undefined.
@AmethystLiang
AmethystLiang force-pushed the ssh-unable-to-connect-issue branch from 2a27589 to ca529a9 Compare August 4, 2026 06:00
@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai Fixing. Will be in the next commit

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Thanks. I will check the update when the next commit is available.

You are interacting with an AI system.

When a connect is cancelled after its transport has opened, that cancelled
attempt still owns the transport and must close it — otherwise it leaks. Add
disconnectConnection() to close by identity (not by target ID) so a cancelled
attempt closes only the transport it minted, without tearing down its
replacement's live transport. Track priorConnection to detect whether this
attempt opened a new transport or reused an existing one, and close only on
abandonment if this attempt owns the session.
When an owner reconnects with a new proof while an old one is still live,
the old proof is now fenced with SUPERSEDED_ERROR instead of retrying
indefinitely. The relay also closes stale transports to signal that their
recovery generation has been overtaken by a newer one.

This ensures overlapping reconnect scenarios complete with the newest proof
rather than getting blocked by stale recovery attempts.
When the relay closes stdin/stdout to signal EOF to the SSH peer, the OS
can recycle those fds (0 and 1) for new sockets or files. If Node still
treats process.stdin/stdout as those numbers, subsequent operations
corrupt socket clients and trigger shutdown errors. Re-pin the fds by
opening /dev/null to keep them occupied and prevent recycling.
@AmethystLiang
AmethystLiang merged commit 00867f0 into main Aug 4, 2026
40 checks passed
AmethystLiang added a commit that referenced this pull request Aug 4, 2026
* fix(ssh): handle owner displacement and graceful shutdown

SSH connections can reconnect with valid session proof after network loss or
device sleep. When the incumbent owner is still half-open, allow the
reconnecting client to displace it outright rather than wait for socket closure
— a window that may never close. Retain displaced deliveries for the new owner
to rotate. During app shutdown, drain SSH sessions without terminating recovery
operations, and retry pending owner grants in case a replacement commits mid-drain.

* fix(ssh): handle owner displacement and graceful shutdown

Make QuitTeardownStartGate a shared singleton so SSH connects use the
same shutdown fence as the main quit path. Track test-connection probes
to ensure they complete before final teardown. Guard owner displacement
to prevent stale owners from clearing recovery state claimed by newer
owners.

* fix(ssh): fix flaky test sync and add error code safety check

Test was using tick-based Promise.resolve() loops which don't guarantee
the async operation has started. Replace with signal-based synchronization
that waits for the actual lease flush. Also add nullish-coalescing to
error code check to prevent crashes if error is null or undefined.

* fix(ssh): fence reset transport opens during shutdown

* fix(ssh): keep recovery leases stable across reconnects

* fix(ssh): close transports owned by cancelled connect attempts

When a connect is cancelled after its transport has opened, that cancelled
attempt still owns the transport and must close it — otherwise it leaks. Add
disconnectConnection() to close by identity (not by target ID) so a cancelled
attempt closes only the transport it minted, without tearing down its
replacement's live transport. Track priorConnection to detect whether this
attempt opened a new transport or reused an existing one, and close only on
abandonment if this attempt owns the session.

* fix(ssh): fence old owner proofs and close superseded transports

When an owner reconnects with a new proof while an old one is still live,
the old proof is now fenced with SUPERSEDED_ERROR instead of retrying
indefinitely. The relay also closes stale transports to signal that their
recovery generation has been overtaken by a newer one.

This ensures overlapping reconnect scenarios complete with the newest proof
rather than getting blocked by stale recovery attempts.

* fix(relay): re-pin stdin/stdout fds after closing to prevent recycling

When the relay closes stdin/stdout to signal EOF to the SSH peer, the OS
can recycle those fds (0 and 1) for new sockets or files. If Node still
treats process.stdin/stdout as those numbers, subsequent operations
corrupt socket clients and trigger shutdown errors. Re-pin the fds by
opening /dev/null to keep them occupied and prevent recycling.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…2367)

* fix(ssh): handle owner displacement and graceful shutdown

SSH connections can reconnect with valid session proof after network loss or
device sleep. When the incumbent owner is still half-open, allow the
reconnecting client to displace it outright rather than wait for socket closure
— a window that may never close. Retain displaced deliveries for the new owner
to rotate. During app shutdown, drain SSH sessions without terminating recovery
operations, and retry pending owner grants in case a replacement commits mid-drain.

* fix(ssh): handle owner displacement and graceful shutdown

Make QuitTeardownStartGate a shared singleton so SSH connects use the
same shutdown fence as the main quit path. Track test-connection probes
to ensure they complete before final teardown. Guard owner displacement
to prevent stale owners from clearing recovery state claimed by newer
owners.

* fix(ssh): fix flaky test sync and add error code safety check

Test was using tick-based Promise.resolve() loops which don't guarantee
the async operation has started. Replace with signal-based synchronization
that waits for the actual lease flush. Also add nullish-coalescing to
error code check to prevent crashes if error is null or undefined.

* fix(ssh): fence reset transport opens during shutdown

* fix(ssh): keep recovery leases stable across reconnects

* fix(ssh): close transports owned by cancelled connect attempts

When a connect is cancelled after its transport has opened, that cancelled
attempt still owns the transport and must close it — otherwise it leaks. Add
disconnectConnection() to close by identity (not by target ID) so a cancelled
attempt closes only the transport it minted, without tearing down its
replacement's live transport. Track priorConnection to detect whether this
attempt opened a new transport or reused an existing one, and close only on
abandonment if this attempt owns the session.

* fix(ssh): fence old owner proofs and close superseded transports

When an owner reconnects with a new proof while an old one is still live,
the old proof is now fenced with SUPERSEDED_ERROR instead of retrying
indefinitely. The relay also closes stale transports to signal that their
recovery generation has been overtaken by a newer one.

This ensures overlapping reconnect scenarios complete with the newest proof
rather than getting blocked by stale recovery attempts.

* fix(relay): re-pin stdin/stdout fds after closing to prevent recycling

When the relay closes stdin/stdout to signal EOF to the SSH peer, the OS
can recycle those fds (0 and 1) for new sockets or files. If Node still
treats process.stdin/stdout as those numbers, subsequent operations
corrupt socket clients and trigger shutdown errors. Re-pin the fds by
opening /dev/null to keep them occupied and prevent recycling.
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