Repository navigation
fix(ssh): hold premature transport 'connected' until the relay is ready - #10157
Conversation
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.
📝 WalkthroughWalkthroughThe SSH IPC handler now suppresses premature 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/main/ipc/ssh.ts (1)
561-583: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract 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 theif/else ifchain 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 winStrengthen the regression test with a positive assertion.
The test only asserts the absence of a
connectedbroadcast. Adding a positive check that adeploying-relaybroadcast did occur would confirm the new guard branch actually fired, rather thanconnectedbeing 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
📒 Files selected for processing (2)
src/main/ipc/ssh.test.tssrc/main/ipc/ssh.ts
…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.
What
Fixes the infinite reconnect bug: in the Create-worktree dialog, selecting an SSH host whose relay can't deploy (e.g. a
pn devbuild missing thelinux-x64relay package) sends the app into an unbounded reconnect loop — the dialog flickers between "Connecting SSH…" / connected / "Preparing SSH connection…" and the console spamsssh:connect/fs:readDir/gh:listWorkItems/linear:listIssuesfailures 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
doConnectcreates the relay session (state'idle'), thenconnectionManager.connect()drives the raw SSH transport to'connected'(ssh-connection.ts:1133) — beforeestablish()deploys the relay. That premature'connected'was forwarded verbatim to the renderer:The two existing backoffs (
scheduleReconnect,relayLostBackoff) never catch it because every cycle is a freshssh:connectIPC that rebuilds the session and resets the counters. The authoritative'connected'is broadcast directly bydoConnectafterestablish()succeeds (ssh.ts:936), so the premature one is pure noise — it's also why the connected-gated data reads (fs:readDiretc.) fire and fail with "Remote connection dropped".The fix
Hold the premature transport
'connected'at'deploying-relay'inonStateChangeuntil the relay session is actually'ready'. One branch insrc/main/ipc/ssh.ts:completedTransportReconnect=true; relay-lost/relay reconnects set arelayStateOverridefirst (caught by the earlierrelayReconnectAlreadyInFlightbranch).connectInFlightgate 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 failsdrives the realonStateChangecallback (via the connection-manager mock) with a failingdeployAndLaunchRelay, and asserts the renderer never receives a'connected'state.Before the fix (revert
ssh.tsonly) it fails, showing the exact premature broadcast:After the fix it passes (0
'connected'broadcasts; exactly oneconnect+ onedisconnectper 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:
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
src/main/ipc/ssh.test.tssrc/main/ssh/**+ ipc + renderer store /useIpcEvents/ connect-gate / pane-retry)pty-connection.test.ts(the renderer loop driver)tsc --noEmit -p config/tsconfig.node.jsonoxlint(changed files)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
connectInFlightgatepty-connection) suite green🤖 Generated with Claude Code
Made with Orca 🐋