Skip to content

fix(ssh): hold premature transport 'connected' until the relay is ready - #10157

Merged
nwparker merged 1 commit into
mainfrom
nwparker/infinite-reconnect-bug
Jul 24, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/infinite-reconnect-bug

Conversation

@nwparker

@nwparker nwparker commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

What

Fixes the infinite reconnect bug: in the Create-worktree dialog, selecting an SSH host whose relay can't deploy (e.g. a pn dev build missing the linux-x64 relay package) sends the app into an unbounded reconnect loop — the dialog flickers between "Connecting SSH…" / connected / "Preparing SSH connection…" and the console spams ssh:connect / fs:readDir / gh:listWorkItems / linear:listIssues failures forever.

ELI5

When you connect to a remote machine, two things happen in order: (1) the SSH pipe opens, then (2) we deploy a small "relay" program on the far side that actually lets the app do work. The bug: we told the whole UI "connected!" the instant the pipe opened — before the relay existed. The UI believed it and reloaded all the remote terminals, which each tried to connect again… which flashed "connected!" again… forever. It's like flipping the "OPEN" sign the moment you unlock the door but before the lights and register are on — customers pour in, find nothing works, leave, and the door keeps re-flashing "OPEN."

The fix: don't show "connected" until the relay is actually up. If the relay can't deploy, the host settles into a normal disconnected state with a manual Connect button instead of thrashing.

Root cause

doConnect creates the relay session (state 'idle'), then connectionManager.connect() drives the raw SSH transport to 'connected' (ssh-connection.ts:1133) — before establish() deploys the relay. That premature 'connected' was forwarded verbatim to the renderer:

main: raw transport 'connected'  ──►  onStateChange else-branch broadcasts 'connected'
renderer (useIpcEvents.ts:2775): bump tab.generation for stranded remote panes
  └─► Terminal.tsx:2169 keys pane by tab.id:tab.generation ─► REMOUNT
        └─► pane connect gate (status ≠ connected) ─► pty-connection.ts:800 window.api.ssh.connect
              └─► raw transport 'connected' again ─► (loop)

The two existing backoffs (scheduleReconnect, relayLostBackoff) never catch it because every cycle is a fresh ssh:connect IPC that rebuilds the session and resets the counters. The authoritative 'connected' is broadcast directly by doConnect after establish() succeeds (ssh.ts:936), so the premature one is pure noise — it's also why the connected-gated data reads (fs:readDir etc.) fire and fail with "Remote connection dropped".

The fix

Hold the premature transport 'connected' at 'deploying-relay' in onStateChange until the relay session is actually 'ready'. One branch in src/main/ipc/ssh.ts:

} else if (
  state.status === 'connected' &&
  session !== undefined &&
  sessionState !== 'ready' &&
  !completedTransportReconnect &&
  connectInFlight.has(targetId)
) {
  // hold at 'deploying-relay' — doConnect broadcasts the authoritative 'connected' after establish()
  broadcastSshState(getCurrentMainWindow, targetId, { targetId, status: 'deploying-relay', ... })
}
  • Reconnect paths are untouched: transport reconnects carry completedTransportReconnect=true; relay-lost/relay reconnects set a relayStateOverride first (caught by the earlier relayReconnectAlreadyInFlight branch).
  • The connectInFlight gate scopes the hold to a live connect (which is guaranteed to follow up with an authoritative 'connected' or a terminal state), so a stray transport-blip 'connected' on a session left 'idle' by a version mismatch is never wedged — see the adversarial review below.

This one change eliminates both the reconnect loop and all four console-spam clusters, because every symptom is downstream of a status the renderer should never have seen.

Proof of fix

New regression test does not broadcast a premature connected when relay deploy fails drives the real onStateChange callback (via the connection-manager mock) with a failing deployAndLaunchRelay, and asserts the renderer never receives a 'connected' state.

Before the fix (revert ssh.ts only) it fails, showing the exact premature broadcast:

AssertionError: expected [ [ 'ssh:state-changed', {state:{status:'connected', supportsFolderDownload:true, …}} ] ] to deeply equal []

After the fix it passes (0 'connected' broadcasts; exactly one connect + one disconnect per IPC → no main-side loop).

Adversarial review (found + fixed a real edge case)

A panel of adversarial reviewers tried to refute the fix from 5 angles. Four cleared the success/reconnect/loop/perf paths; two independently found the same real regression, now fixed:

A relay version mismatch during a relay reconnect leaves the session 'idle' in activeSessions (only doConnect deletes it). A later transport blip then delivers a raw 'connected' with no connect in flight — the naive hold would wedge the UI at 'deploying-relay' forever, disabling every Connect/Reset control.

Fixed by the connectInFlight.has(targetId) gate, and guarded by a second load-bearing test (does not hold a stray connected as deploying-relay when no connect is in flight) — it fails if the gate is removed.

Proof of no regressions / no perf issues

Check Result
src/main/ipc/ssh.test.ts 43 passed (incl. 2 new regression tests)
Broad SSH suite (src/main/ssh/** + ipc + renderer store / useIpcEvents / connect-gate / pane-retry) 968 passed, 10 skipped
pty-connection.test.ts (the renderer loop driver) 466 passed
tsc --noEmit -p config/tsconfig.node.json clean (exit 0)
oxlint (changed files) clean

Perf: broadcast count per failing connect is unchanged (4 → 4); the change is that the loop total drops from unbounded → one cycle, so the renderer no longer runs fetchWorktrees / fetchWorktreeLineage / pane remounts every iteration. The added branch is three boolean checks on an infrequent callback.

Test plan

  • Repro test fails before fix, passes after
  • Wedge-regression test fails without the connectInFlight gate
  • Full SSH + relay + connection suites green
  • Loop driver (pty-connection) suite green
  • Typecheck + lint clean

🤖 Generated with Claude Code

Made with Orca 🐋

An SSH connect whose relay deploy fails permanently (e.g. a dev build
missing the platform relay package) drove an unbounded reconnect loop.
doConnect creates the relay session ('idle'), then connectionManager.
connect() drives the raw transport to 'connected' before the relay
establishes. That premature 'connected' was forwarded to the renderer,
which treats it as "host fully up": applySshConnectionStateChange bumps
tab.generation for stranded remote panes -> remounts TerminalPane -> the
pane connect gate re-invokes window.api.ssh.connect -> restarts the whole
cycle forever (and spams connected-gated reads that fail with "Remote
connection dropped").

Hold the premature 'connected' at 'deploying-relay' in onStateChange until
the relay session is 'ready'. doConnect still broadcasts the authoritative
'connected' directly after establish() succeeds. Gate on connectInFlight so
the hold is scoped to a live connect and never wedges a stray transport-blip
'connected' on a session left 'idle' by a relay version mismatch.
@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The SSH IPC handler now suppresses premature connected renderer states while relay deployment is active, emitting deploying-relay when a connect is in flight and the relay is not ready. Tests cover permanent relay deployment failure and a relay version-mismatch reconnect path that later permits a normal connected state.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the bug and fix, but it omits required template sections like Summary, Screenshots, AI Review Report, and Security Audit. Rewrite it using the repo template and add the missing sections, including screenshots/no visual change, the testing checklist, cross-platform AI review, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the SSH fix to delay connected state until the relay is ready.
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.
✨ Finishing Touches
📝 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.

🧹 Nitpick comments (2)
src/main/ipc/ssh.ts (1)

561-583: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the new guard condition into a named boolean for consistency.

The two sibling branches above already name their conditions (shouldReconnectRelay, relayReconnectAlreadyInFlight). This new 5-clause inline condition is the most complex of the three (flagged as high complexity) but is the only one left unnamed, making the if/else if chain harder to scan.

♻️ Suggested refactor
+      const isPrematureConnectDuringRelayDeploy =
+        state.status === 'connected' &&
+        session !== undefined &&
+        sessionState !== 'ready' &&
+        !completedTransportReconnect &&
+        connectInFlight.has(targetId)
+
       if (shouldReconnectRelay) {
         ...
       } else if (relayReconnectAlreadyInFlight) {
         return
-      } else if (
-        state.status === 'connected' &&
-        session !== undefined &&
-        sessionState !== 'ready' &&
-        !completedTransportReconnect &&
-        connectInFlight.has(targetId)
-      ) {
+      } else if (isPrematureConnectDuringRelayDeploy) {
         clearRelayStateOverride(targetId)
         broadcastSshState(getCurrentMainWindow, targetId, {
src/main/ipc/ssh.test.ts (1)

743-756: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Strengthen the regression test with a positive assertion.

The test only asserts the absence of a connected broadcast. Adding a positive check that a deploying-relay broadcast did occur would confirm the new guard branch actually fired, rather than connected being suppressed for an unrelated reason.

✅ Suggested addition
     const connectedBroadcasts = mockWindow.webContents.send.mock.calls.filter(
       ([channel, payload]) =>
         channel === 'ssh:state-changed' &&
         (payload as { state?: SshConnectionState }).state?.status === 'connected'
     )
     expect(connectedBroadcasts).toEqual([])
+
+    const deployingRelayBroadcasts = mockWindow.webContents.send.mock.calls.filter(
+      ([channel, payload]) =>
+        channel === 'ssh:state-changed' &&
+        (payload as { state?: SshConnectionState }).state?.status === 'deploying-relay'
+    )
+    expect(deployingRelayBroadcasts.length).toBeGreaterThan(0)
   })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f238c593-92f7-4693-b3ee-506fecb37b95

📥 Commits

Reviewing files that changed from the base of the PR and between 8a23618 and 8d87f3f.

📒 Files selected for processing (2)
  • src/main/ipc/ssh.test.ts
  • src/main/ipc/ssh.ts

@nwparker
nwparker merged commit 645ed9a into main Jul 24, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…dy (stablyai#10157)

An SSH connect whose relay deploy fails permanently (e.g. a dev build
missing the platform relay package) drove an unbounded reconnect loop.
doConnect creates the relay session ('idle'), then connectionManager.
connect() drives the raw transport to 'connected' before the relay
establishes. That premature 'connected' was forwarded to the renderer,
which treats it as "host fully up": applySshConnectionStateChange bumps
tab.generation for stranded remote panes -> remounts TerminalPane -> the
pane connect gate re-invokes window.api.ssh.connect -> restarts the whole
cycle forever (and spams connected-gated reads that fail with "Remote
connection dropped").

Hold the premature 'connected' at 'deploying-relay' in onStateChange until
the relay session is 'ready'. doConnect still broadcasts the authoritative
'connected' directly after establish() succeeds. Gate on connectInFlight so
the hold is scoped to a live connect and never wedges a stray transport-blip
'connected' on a session left 'idle' by a relay version mismatch.
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