Repository navigation
Recover automatically instead of getting stuck on "Multiplexer disposed" when an SSH relay drops - #12216
Conversation
…connect Three coupled defects made a dropped SSH relay look like a permanent bug: 1. SshRelaySession.establish()/reconnect() ran their last liveness gate before configureRelayGraceTime(), whose mux.notify() can dispose the mux synchronously (writer control-lane admission cap, or a throwing transport). The session then latched _state='ready' + _onReady (status bar "connected") while watchMuxForRelayLoss() silently no-op'd on the dead mux, so the bounded relay backoff in ipc/ssh.ts never ran and the fs/pty/git providers stayed registered against a dead multiplexer. Both sites now re-check mux.isDisposed() after the notify and take the existing failure path. 2. SshChannelMultiplexer.request()/notifyWithSettlement() always reported the permanent-shutdown string 'Multiplexer disposed' with no code, even when the recorded dispose reason was connection_lost. The reason is now recorded and a shared disposedError() factory serves dispose(), request(), notifyWithSettlement(), so a transient drop reports 'SSH connection lost, reconnecting...' / CONNECTION_LOST. onDispose() on an already-disposed mux now fires the handler synchronously with that reason instead of returning a silent no-op (without retaining it). 3. TerminalErrorToast no longer renders a transient relay drop in the red "please file an issue" style. The marker is matched with includes() because the message reaches the toast IPC-wrapped. ssh-git-response-stream-reader registers its onDispose subscriber after the abort wiring, since an already-dead mux now fails synchronously there and the cleanup must be able to drop the caller's abort listener. Closes #11953
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe SSH channel multiplexer now records disposal reasons and generates reason-specific errors. Late disposal handlers receive the recorded reason immediately. Git stream requests clean up abort listeners when disposal occurs synchronously. Relay session establishment and reconnect reject synchronous relay loss before entering the ready state. Terminal error handling recognizes IPC-wrapped relay-loss messages and filters reconnect-owned errors. Tests cover multiplexer disposal, stream cleanup, relay recovery, and terminal filtering. 🚥 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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e0fad101-9b3c-4504-85f6-738350a058a1
📒 Files selected for processing (8)
src/main/ssh/ssh-channel-multiplexer.test.tssrc/main/ssh/ssh-channel-multiplexer.tssrc/main/ssh/ssh-git-response-stream-reader.test.tssrc/main/ssh/ssh-git-response-stream-reader.tssrc/main/ssh/ssh-relay-session-relay-loss.test.tssrc/main/ssh/ssh-relay-session.tssrc/renderer/src/components/terminal-pane/TerminalErrorToast.test.tssrc/renderer/src/components/terminal-pane/TerminalErrorToast.tsx
reconnect()'s post-reattach gate bare-returned when ownsAttempt() went false, and reattachKnownPtys swallows every per-PTY error, so a control-lane failure during a large reattach burst disposed the mux without ever reaching the catch: providers stayed bound to the dead mux, no relay-loss watcher was installed, and the session wedged in 'reconnecting' until restart. Take the failure path when our own mux is the one that died so ssh.ts's bounded backoff retries. Co-authored-by: Orca <[email protected]>
|
reviewing |
Introduce verifyRelayAttempt() to detect mux disposal at each setup phase (consumer session, home resolution, provider registration, PTY reattach). Routes mid-setup connection loss into relay-loss recovery instead of hanging in reconnecting state.
Multiple sites were duplicating the disposal error creation logic with specific message and code values. The renderer uses these to distinguish temporary disconnects (show reconnection overlay) from permanent shutdown (show error toast), so all producers must use the same factory to avoid silent UI degradation.
…ed" when an SSH relay drops (#12216) * fix(ssh): recover instead of wedging when the relay channel dies mid-connect Three coupled defects made a dropped SSH relay look like a permanent bug: 1. SshRelaySession.establish()/reconnect() ran their last liveness gate before configureRelayGraceTime(), whose mux.notify() can dispose the mux synchronously (writer control-lane admission cap, or a throwing transport). The session then latched _state='ready' + _onReady (status bar "connected") while watchMuxForRelayLoss() silently no-op'd on the dead mux, so the bounded relay backoff in ipc/ssh.ts never ran and the fs/pty/git providers stayed registered against a dead multiplexer. Both sites now re-check mux.isDisposed() after the notify and take the existing failure path. 2. SshChannelMultiplexer.request()/notifyWithSettlement() always reported the permanent-shutdown string 'Multiplexer disposed' with no code, even when the recorded dispose reason was connection_lost. The reason is now recorded and a shared disposedError() factory serves dispose(), request(), notifyWithSettlement(), so a transient drop reports 'SSH connection lost, reconnecting...' / CONNECTION_LOST. onDispose() on an already-disposed mux now fires the handler synchronously with that reason instead of returning a silent no-op (without retaining it). 3. TerminalErrorToast no longer renders a transient relay drop in the red "please file an issue" style. The marker is matched with includes() because the message reaches the toast IPC-wrapped. ssh-git-response-stream-reader registers its onDispose subscriber after the abort wiring, since an already-dead mux now fails synchronously there and the cleanup must be able to drop the caller's abort listener. Closes #11953 * fix(ssh): treat a mux killed during PTY reattach as relay loss reconnect()'s post-reattach gate bare-returned when ownsAttempt() went false, and reattachKnownPtys swallows every per-PTY error, so a control-lane failure during a large reattach burst disposed the mux without ever reaching the catch: providers stayed bound to the dead mux, no relay-loss watcher was installed, and the session wedged in 'reconnecting' until restart. Take the failure path when our own mux is the one that died so ssh.ts's bounded backoff retries. Co-authored-by: Orca <[email protected]> * fix(ssh): recover when relay dies during setup instead of wedging Introduce verifyRelayAttempt() to detect mux disposal at each setup phase (consumer session, home resolution, provider registration, PTY reattach). Routes mid-setup connection loss into relay-loss recovery instead of hanging in reconnecting state. * Extract SSH disposal error factory Multiple sites were duplicating the disposal error creation logic with specific message and code values. The renderer uses these to distinguish temporary disconnects (show reconnection overlay) from permanent shutdown (show error toast), so all producers must use the same factory to avoid silent UI degradation. --------- Co-authored-by: Orca <[email protected]> Co-authored-by: Jinjing <[email protected]>
…ed" when an SSH relay drops (stablyai#12216) * fix(ssh): recover instead of wedging when the relay channel dies mid-connect Three coupled defects made a dropped SSH relay look like a permanent bug: 1. SshRelaySession.establish()/reconnect() ran their last liveness gate before configureRelayGraceTime(), whose mux.notify() can dispose the mux synchronously (writer control-lane admission cap, or a throwing transport). The session then latched _state='ready' + _onReady (status bar "connected") while watchMuxForRelayLoss() silently no-op'd on the dead mux, so the bounded relay backoff in ipc/ssh.ts never ran and the fs/pty/git providers stayed registered against a dead multiplexer. Both sites now re-check mux.isDisposed() after the notify and take the existing failure path. 2. SshChannelMultiplexer.request()/notifyWithSettlement() always reported the permanent-shutdown string 'Multiplexer disposed' with no code, even when the recorded dispose reason was connection_lost. The reason is now recorded and a shared disposedError() factory serves dispose(), request(), notifyWithSettlement(), so a transient drop reports 'SSH connection lost, reconnecting...' / CONNECTION_LOST. onDispose() on an already-disposed mux now fires the handler synchronously with that reason instead of returning a silent no-op (without retaining it). 3. TerminalErrorToast no longer renders a transient relay drop in the red "please file an issue" style. The marker is matched with includes() because the message reaches the toast IPC-wrapped. ssh-git-response-stream-reader registers its onDispose subscriber after the abort wiring, since an already-dead mux now fails synchronously there and the cleanup must be able to drop the caller's abort listener. Closes stablyai#11953 * fix(ssh): treat a mux killed during PTY reattach as relay loss reconnect()'s post-reattach gate bare-returned when ownsAttempt() went false, and reattachKnownPtys swallows every per-PTY error, so a control-lane failure during a large reattach burst disposed the mux without ever reaching the catch: providers stayed bound to the dead mux, no relay-loss watcher was installed, and the session wedged in 'reconnecting' until restart. Take the failure path when our own mux is the one that died so ssh.ts's bounded backoff retries. Co-authored-by: Orca <[email protected]> * fix(ssh): recover when relay dies during setup instead of wedging Introduce verifyRelayAttempt() to detect mux disposal at each setup phase (consumer session, home resolution, provider registration, PTY reattach). Routes mid-setup connection loss into relay-loss recovery instead of hanging in reconnecting state. * Extract SSH disposal error factory Multiple sites were duplicating the disposal error creation logic with specific message and code values. The renderer uses these to distinguish temporary disconnects (show reconnection overlay) from permanent shutdown (show error toast), so all producers must use the same factory to avoid silent UI degradation. --------- Co-authored-by: Orca <[email protected]> Co-authored-by: Jinjing <[email protected]>
Summary
An SSH remote could show "connected" in the status bar while every remote terminal write and every file-tree read failed with
Error: Multiplexer disposed, permanently, until the app was restarted.Three coupled defects:
The session latched
readyon a dead multiplexer.SshRelaySession.establish()(src/main/ssh/ssh-relay-session.ts:491) andreconnect()(:648) ran their last liveness gate beforeconfigureRelayGraceTime(). That call ismux.notify()→sendMessage→SshMultiplexerTransportWriter.enqueue, which can callthis.fail(err)synchronously from the bounded control-lane admission cap (src/main/ssh/ssh-multiplexer-transport-writer.ts:84-88) or fromwriteEntry's catch on a throwing transport (:181-187) →onFailure→handleProtocolError→dispose('connection_lost')(src/main/ssh/ssh-channel-multiplexer.ts:586-588). The session then calledwatchMuxForRelayLoss(mux)on an already-dead mux — whereonDispose()returned a silent no-op — and set_state = 'ready'+_onReady(status bar "connected" viasrc/main/ipc/ssh.ts:1150-1156on first connect and:828-851on the reconnect path), while the pty/fs/git providers stayed registered against the dead mux._onRelayLostnever fired, so the bounded relay backoff atsrc/main/ipc/ssh.ts:719never ran. Permanently wedged. Both sites now re-checkmux.isDisposed()immediately after the notify (:493-494,:650-651) and take the existing failure path (establish()rethrows into the session catch that already runsteardownProviders, and thessh:connecthandler's catch then runsabandonFailedSshSessionatssh.ts:1157-1161;reconnect()routes into_onRelayLostat:684, i.e. the bounded exponential backoff). A third gate was added inreconnect()afterreattachKnownPtys()(:642-643): that helper swallows every per-PTY failure, so a mux killed by the reattach burst itself would otherwise fall into the silentreturnand wedge the session inreconnectingwith no relay-loss watcher.The dispose reason was dropped for post-dispose callers.
request()andnotifyWithSettlement()(nowsrc/main/ssh/ssh-channel-multiplexer.ts:192-194and:280-282) always threw the permanent-shutdown string'Multiplexer disposed'with nocode, even whendispose()had recordedconnection_lost— whichdispose()itself mapped correctly for its own pending-request and writer rejections, and which both stream readers already follow (ssh-filesystem-stream-reader.ts:255-263). This matters beyond defect 1:watchMuxForRelayLossfires_onRelayLostbut does not tear down providers (ssh-relay-session.ts:818-828), so on the ordinary relay-loss path the fs/pty/git providers stay bound to the disposed mux for the whole backoff delay and everyfs:readDir/ pty reattach in that window reported the permanent string. The reason is now recorded in adisposeReasonfield and a singledisposedError()factory (:374-381) servesdispose(),request(), andnotifyWithSettlement().onDispose()on an already-disposed mux now invokes the handler synchronously with the recorded reason instead of returning a no-op (without retaining the handler, so the anti-leak contract atssh-channel-multiplexer.test.tsis preserved).The renderer called a transient drop a bug to report.
TerminalErrorToast.isSshError/isSshReconnectOwnedTerminalError(src/renderer/src/components/terminal-pane/TerminalErrorToast.tsx:16-27) did not recognise relay-lost text, so it rendered in the red "If this persists, please file an issue" style (that link is gated on!sshat:87). Matched withincludes(), notstartsWith(), because the message reaches the toast IPC-wrapped asError invoking remote method 'pty:…': Error: SSH connection lost, reconnecting...— the same reasonisSshSessionExpiredError(pty-connection.ts:769-771) usesincludes.One forced follow-on:
src/main/ssh/ssh-git-response-stream-reader.tsnow registers itsmux.onDisposesubscriber after the abort-signal wiring. With immediate-fireonDispose,fail()runs during that call and drainsunsubscribers; registering it first would leak a listener on the caller'sAbortSignalfor the signal's lifetime. Pure reorder (plus a comment), no new branch.ssh-filesystem-stream-reader.tsalready registers its dispose subscriber last and needs no change.Closes #11953
Scope caveat: the issue has no repro ("IDK"), and the reporter's exact close-and-reopen sequence was not reproduced live. This fixes the mechanism that produces exactly the reported state — a "connected" status bar over a dead multiplexer, with
Multiplexer disposedon everyfs:readDirand terminal write and no automatic recovery — and makes the transient case both self-healing and honestly labelled. It is not a confirmation that this was the only way to reach that state.ELI5
When Orca connects to a remote machine over SSH, the very last thing it does before saying "connected" is send one small setup message. If the connection happened to die at exactly that moment, Orca still put up the green "connected" badge — but everything behind it was already dead, and Orca never noticed, so it never tried to reconnect. Remote terminals and the file tree just failed forever with a confusing message until you restarted the app. Now Orca checks one more time right after that last message, and if the connection is gone it either fails the connect honestly or starts its normal automatic retry. Separately, when the connection drops it now says "SSH connection lost, reconnecting…" instead of a scary internal error with a "please file an issue" link.
Fix proof
Before (the throwaway repro artifacts — not part of this diff — run against
origin/main):The repro artifacts were reworked into permanent regression tests: the multiplexer cases folded into the existing
disposeblock ofsrc/main/ssh/ssh-channel-multiplexer.test.ts(4 added cases), the session case rewritten assrc/main/ssh/ssh-relay-session-relay-loss.test.tswith three cases (dead channel on the finalestablish()notify, the same onreconnect(), and a mux that dies during PTY reattach), and a newsrc/main/ssh/ssh-git-response-stream-reader.test.tspinning the listener-leak reorder.After (re-run on the PR head, macOS):
The listener-leak guard was verified to actually guard: reverting only the
ssh-git-response-stream-reader.tsreorder turns it red.No regressions
Every suite that neighbours a touched file, or imports what changed.
src/main/ssh/+src/main/providers/— the whole relay-session family, the multiplexer suites, the transport writer, both stream readers, the pty/fs/git providers:src/relay/(the integration suites that drive the real multiplexer end to end),src/main/ipc/ssh.test.ts,src/main/ipc/pty.test.ts,src/main/agent-hooks/(WSL relay link + guest plugin install), and the fullsrc/renderer/src/components/terminal-pane/tree:Total: 487 files, 7019 passing, 16 skipped, 0 failing.
Trade-offs
This is not zero-cost — there is one real user-visible behaviour change:
ssh:connectwhose relay channel dies in the final establish window now fails the connect instead of appearing to succeed. Previously it reported "connected" and then silently wedged; now the transport is torn down and the error surfaces through thessh:connectrejection. That is strictly better than the silent wedge and matches the existing contract for a relay lost during provider registration (ssh-relay-session.ts:475-476), but it is a behaviour change: a class of connect attempts that used to show a green badge now shows a failure, and there is no automatic retry on that path — the user has to hit connect again. On thereconnect()path there is no downside; the drop enters the existing bounded exponential backoff and recovers on its own.src/main/ipc/ssh.ts:740-742skips the override publish when a redeploy timer is already armed, so the amber toast is the realistic outcome, not silence. If the relay never comes back,ssh.ts:750-762still escalates to an explicit error override afterRELAY_LOST_MAX_ATTEMPTS, so a genuinely broken link stays loud — it is just no longer mislabeled as a bug to file.onDispose()on an already-disposed mux now fires synchronously. For the two stream readers this is strictly earlier and better (they previously waited for the request to reject). It forced the one-line reorder inssh-git-response-stream-reader.tsdescribed above; the WSL relay link (wsl-hook-relay-link.ts:56) is guarded by its owndeadflag and subscribes to a mux constructed one statement earlier, so the path is unreachable there in practice.Verification limits
SshChannelMultiplexer, not the real transport; the real synchronous-dispose paths (writer admission cap, throwing transport) are covered separately by the multiplexer suites rather than end to end in one test.Cross-platform
No platform-dependent code is touched. No keyboard shortcuts (no
metaKey/ctrlKey), no Electron accelerators, no shortcut labels, no filesystem path construction. The session and multiplexer changes are pure main-process state-machine logic; the renderer change is a substring constant.mux.isDisposed()and the dispose-reason field carry no platform semantics. The Windows-only WSL relay link is covered under Trade-offs and is unaffected in practice;src/main/agent-hooks/is green.joinRemotePath/hostPlatform.pathDelimiterare untouched, so there is no/vs\or case-sensitivity exposure.SshRelaySessionis keyed bytargetId(an SSH target), never by workspace, so folder workspaces and git worktrees on the remote are affected identically and neither is special-cased. No code path here asks whether a workspace is a git repo.GitCapabilityCache, and the leading--cglobal-option commands are untouched.SshGitProvideronly benefits from getting an accurateCONNECTION_LOSTcode on a dropped relay. No provider-specific (GitHub/GitLab) surface is involved.Performance
SshChannelMultiplexer: one nullable field, plus a smallErrorfactory on paths that already allocated exactly the same Errors.dispose()allocates the same number of Errors as before (one per pending request, one for the writer).SshRelaySession: one added boolean field read perestablish(), two perreconnect()(post-reattach and post-notify).ssh-git-response-stream-reader: a statement reorder — same work, different order.TerminalErrorToast: oneString.prototype.includesper error line, only when a terminal error toast renders. No extra renders, no new state.No new timers, listeners, polling, allocations in hot loops, or IPC traffic. In the failure case the change reduces work: the session tears down instead of leaving keepalive-free dead providers registered while every subsequent
fs:readDirand pty write round-trips into a dead multiplexer.Security
No change. No new IPC channels or handlers, no changes to IPC payload shapes or validation. No command execution and no shell/argument construction added or modified. No path handling — no path is built, joined, normalised, or resolved in this diff. No change to the auth surface: credentials, key handling, the relay handshake, and endpoint credential checks are untouched.
The one adjacent consideration is error-message content: post-dispose callers can now receive
'SSH connection lost, reconnecting...'instead of'Multiplexer disposed'. Both are fixed literals — no host, path, user, or credential material is added to any message reaching the renderer.AI Review Report
Reviewed by independent subagents in a loop until clean, across two hostile lenses — correctness/regressions and cross-platform + remote + performance.
Non-blocking notes (1), recorded for transparency:
src/main/ssh/ssh-relay-session.ts:615-621— The PR closes the two windows where a mid-reconnect mux death used to be swallowed (post-reattachKnownPtysand post-configureRelayGraceTime), but leaves the identical window one branch earlier:const registered = await this.registerProviders(mux, ownsAttempt, connectionIncarnation); if (!registered) { if (!mux.isDisposed()) mux.dispose(); return }.registerProvidersreturnsfalseprecisely whenownsAttempt()goes false — which includes "the mux just died" — so that path still returns silently without firing_onRelayLost. It is strictly less likely than the windows this PR closes (theisDisposed()throw at:623-625catches the common ordering) and was left alone to keep the diff focused; worth a follow-up.Remediation applied between rounds: 1 pass(es). Findings judged false-positive were rejected with evidence rather than coded around. Separately, one CodeRabbit review comment is open and not addressed in this diff: it proposes exporting a shared disposal-error factory so
ssh-channel-multiplexer.disposedError()and the git stream reader'sonDisposecallback stop duplicating the message/code mapping. That duplication predates this PR (the same mapping also lives inssh-filesystem-stream-reader.ts:255-263) and is left as-is here.Made with Orca 🐋