Skip to content

Recover automatically instead of getting stuck on "Multiplexer disposed" when an SSH relay drops - #12216

Merged
AmethystLiang merged 4 commits into
mainfrom
nwparker/bugbash-11953
Aug 5, 2026
Merged

AmethystLiang merged 4 commits into
mainfrom
nwparker/bugbash-11953

Conversation

@nwparker

@nwparker nwparker commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

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:

  1. The session latched ready on a dead multiplexer. SshRelaySession.establish() (src/main/ssh/ssh-relay-session.ts:491) and reconnect() (:648) ran their last liveness gate before configureRelayGraceTime(). That call is mux.notify() → sendMessage → SshMultiplexerTransportWriter.enqueue, which can call this.fail(err) synchronously from the bounded control-lane admission cap (src/main/ssh/ssh-multiplexer-transport-writer.ts:84-88) or from writeEntry'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 called watchMuxForRelayLoss(mux) on an already-dead mux — where onDispose() returned a silent no-op — and set _state = 'ready' + _onReady (status bar "connected" via src/main/ipc/ssh.ts:1150-1156 on first connect and :828-851 on the reconnect path), while the pty/fs/git providers stayed registered against the dead mux. _onRelayLost never fired, so the bounded relay backoff at src/main/ipc/ssh.ts:719 never ran. Permanently wedged. Both sites now re-check mux.isDisposed() immediately after the notify (:493-494, :650-651) and take the existing failure path (establish() rethrows into the session catch that already runs teardownProviders, and the ssh:connect handler's catch then runs abandonFailedSshSession at ssh.ts:1157-1161; reconnect() routes into _onRelayLost at :684, i.e. the bounded exponential backoff). A third gate was added in reconnect() after reattachKnownPtys() (:642-643): that helper swallows every per-PTY failure, so a mux killed by the reattach burst itself would otherwise fall into the silent return and wedge the session in reconnecting with no relay-loss watcher.

  2. The dispose reason was dropped for post-dispose callers. request() and notifyWithSettlement() (now src/main/ssh/ssh-channel-multiplexer.ts:192-194 and :280-282) always threw the permanent-shutdown string 'Multiplexer disposed' with no code, even when dispose() had recorded connection_lost — which dispose() 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: watchMuxForRelayLoss fires _onRelayLost but 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 every fs:readDir / pty reattach in that window reported the permanent string. The reason is now recorded in a disposeReason field and a single disposedError() factory (:374-381) serves dispose(), request(), and notifyWithSettlement(). 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 at ssh-channel-multiplexer.test.ts is preserved).

  3. 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 !ssh at :87). Matched with includes(), not startsWith(), because the message reaches the toast IPC-wrapped as Error invoking remote method 'pty:…': Error: SSH connection lost, reconnecting... — the same reason isSshSessionExpiredError (pty-connection.ts:769-771) uses includes.

One forced follow-on: src/main/ssh/ssh-git-response-stream-reader.ts now registers its mux.onDispose subscriber after the abort-signal wiring. With immediate-fire onDispose, fail() runs during that call and drains unsubscribers; registering it first would leak a listener on the caller's AbortSignal for the signal's lifetime. Pure reorder (plus a comment), no new branch. ssh-filesystem-stream-reader.ts already 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 disposed on every fs:readDir and 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):

$ npx vitest run --config config/vitest.config.ts src/main/ssh/ssh-relay-session.bug-11953.test.ts src/main/ssh/ssh-channel-multiplexer.bug-11953.test.ts

 RUN  v4.1.5 /Users/nwparker/projects/orca/.claude/worktrees/wf_60c051cd-fbd-43

 ❯ src/main/ssh/ssh-channel-multiplexer.bug-11953.test.ts (3 tests | 3 failed) 7ms
     × reports a transient relay drop as a permanent dispose to later requests 5ms
     × reports a transient relay drop as a permanent dispose to notifyWithSettlement 1ms
     × drops relay-loss watchers registered after the mux already died 1ms
 ❯ src/main/ssh/ssh-relay-session.bug-11953.test.ts (1 test | 1 failed) 6ms
     × does not report ready when the relay channel dies on the last establish notify 5ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/main/ssh/ssh-channel-multiplexer.bug-11953.test.ts > bug-11953: dispose reason is lost for post-dispose callers > reports a transient relay drop as a permanent dispose to later requests
AssertionError: expected 'Multiplexer disposed' to be 'SSH connection lost, reconnecting...' // Object.is equality

Expected: "SSH connection lost, reconnecting..."
Received: "Multiplexer disposed"

 ❯ src/main/ssh/ssh-channel-multiplexer.bug-11953.test.ts:42:38
     40|     // Expected (matches ssh-filesystem-stream-reader.ts:255-263 and t…
     41|     // pending-request rejection inside dispose()).
     42|     expect((error as Error).message).toBe('SSH connection lost, reconn…
       |                                      ^
     43|     expect((error as Error & { code?: string }).code).toBe('CONNECTION…
     44|   })

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/4]⎯

 FAIL  src/main/ssh/ssh-channel-multiplexer.bug-11953.test.ts > bug-11953: dispose reason is lost for post-dispose callers > reports a transient relay drop as a permanent dispose to notifyWithSettlement
AssertionError: expected 'Multiplexer disposed' to be 'SSH connection lost, reconnecting...' // Object.is equality

Expected: "SSH connection lost, reconnecting..."
Received: "Multiplexer disposed"

 ❯ src/main/ssh/ssh-channel-multiplexer.bug-11953.test.ts:53:34
     51|
     52|     const result = settled.mock.calls[0]?.[0] as { ok: false; error: E…
     53|     expect(result.error.message).toBe('SSH connection lost, reconnecti…
       |                                  ^
     54|     expect(result.error.code).toBe('CONNECTION_LOST')
     55|   })

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/4]⎯

 FAIL  src/main/ssh/ssh-channel-multiplexer.bug-11953.test.ts > bug-11953: dispose reason is lost for post-dispose callers > drops relay-loss watchers registered after the mux already died
AssertionError: expected "vi.fn()" to be called with arguments: [ 'connection_lost' ]

Number of calls: 0

 ❯ src/main/ssh/ssh-channel-multiplexer.bug-11953.test.ts:69:25
     67|     mux.dispose('connection_lost')
     68|
     69|     expect(onRelayLost).toHaveBeenCalledWith('connection_lost')
       |                         ^
     70|   })
     71| })

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[3/4]⎯

 FAIL  src/main/ssh/ssh-relay-session.bug-11953.test.ts > bug-11953: session latches ready on a dead multiplexer > does not report ready when the relay channel dies on the last establish notify
AssertionError: expected 0 to be greater than 0
 ❯ src/main/ssh/ssh-relay-session.bug-11953.test.ts:165:86
    163|     // fire the relay-loss recovery path. Today it does neither, and t…
    164|     // provider stays registered against the disposed mux.
    165|     expect(onRelayLost.mock.calls.length + (session.getState() === 're…
       |                                                                                      ^
    166|       0
    167|     )

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[4/4]⎯


 Test Files  2 failed (2)
      Tests  4 failed (4)
   Start at  21:59:13
   Duration  3.80s (transform 2.98s, setup 0ms, import 3.81s, tests 13ms, environment 0ms)

The repro artifacts were reworked into permanent regression tests: the multiplexer cases folded into the existing dispose block of src/main/ssh/ssh-channel-multiplexer.test.ts (4 added cases), the session case rewritten as src/main/ssh/ssh-relay-session-relay-loss.test.ts with three cases (dead channel on the final establish() notify, the same on reconnect(), and a mux that dies during PTY reattach), and a new src/main/ssh/ssh-git-response-stream-reader.test.ts pinning the listener-leak reorder.

After (re-run on the PR head, macOS):

$ npx vitest run --config config/vitest.config.ts src/main/ssh/ssh-relay-session-relay-loss.test.ts src/main/ssh/ssh-git-response-stream-reader.test.ts

 RUN  v4.1.5

 Test Files  2 passed (2)
      Tests  4 passed (4)
   Duration  5.83s (transform 4.89s, setup 0ms, import 6.02s, tests 11ms, environment 0ms)
$ npx vitest run --config config/vitest.config.ts src/main/ssh/ssh-channel-multiplexer.test.ts -t "dispose"

 RUN  v4.1.5

 Test Files  1 passed (1)
      Tests  13 passed | 21 skipped (34)
   Duration  123ms (transform 40ms, setup 0ms, import 51ms, tests 7ms, environment 0ms)

The listener-leak guard was verified to actually guard: reverting only the ssh-git-response-stream-reader.ts reorder turns it red.

 FAIL  src/main/ssh/ssh-git-response-stream-reader.test.ts > requestGitStreamable on an already-dead multiplexer > rejects as a transient relay loss and leaves no listener on the caller signal
AssertionError: expected "removeEventListener" to be called 1 times, but got 0 times
 ❯ src/main/ssh/ssh-git-response-stream-reader.test.ts:28:28

 Test Files  1 failed (1)
      Tests  1 failed (1)

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:

$ npx vitest run --config config/vitest.config.ts src/main/ssh/ src/main/providers/

 Test Files  130 passed | 2 skipped (132)
      Tests  1872 passed | 13 skipped (1885)
   Duration  16.27s (transform 35.39s, setup 0ms, import 59.71s, tests 30.87s, environment 6ms)

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 full src/renderer/src/components/terminal-pane/ tree:

$ npx vitest run --config config/vitest.config.ts src/relay/ src/main/ipc/ssh.test.ts src/main/ipc/pty.test.ts src/main/agent-hooks/ src/renderer/src/components/terminal-pane/

 Test Files  355 passed (355)
      Tests  5147 passed | 3 skipped (5150)
   Duration  41.60s (transform 173.41s, setup 0ms, import 220.92s, tests 225.55s, environment 8.02s)

Total: 487 files, 7019 passing, 16 skipped, 0 failing.

Trade-offs

This is not zero-cost — there is one real user-visible behaviour change:

  • An ssh:connect whose 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 the ssh:connect rejection. 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 the reconnect() path there is no downside; the drop enters the existing bounded exponential backoff and recovers on its own.
  • The transient-drop terminal toast becomes amber instead of red and loses its "please file an issue" link. It is suppressed entirely only when the SSH reconnect banner happens to be up — src/main/ipc/ssh.ts:740-742 skips 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-762 still escalates to an explicit error override after RELAY_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 in ssh-git-response-stream-reader.ts described above; the WSL relay link (wsl-hook-relay-link.ts:56) is guarded by its own dead flag and subscribes to a mux constructed one statement earlier, so the path is unreachable there in practice.

Verification limits

  • Verified by unit tests only, executed on macOS. No manual end-to-end run against a live SSH remote, and nothing was exercised on Linux or Windows hosts (including the Windows-only WSL relay link, which is covered by its existing suite but not by a live run).
  • The relay-loss session tests drive a mocked 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.

  • macOS / Linux / Windows (local app): identical behaviour. 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.
  • Remote host platform: identical whether the remote is Linux, macOS, or Windows. joinRemotePath / hostPlatform.pathDelimiter are untouched, so there is no / vs \ or case-sensitivity exposure.
  • SSH-remote: this is squarely the SSH-remote path. The fix exists only so remote execution recovers instead of wedging; nothing here assumes local execution.
  • Folder workspaces (non-git): workspace-shape agnostic. SshRelaySession is keyed by targetId (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.
  • Git: no Git subcommand, option, or capability probe is added or changed, so the Git 2.25 baseline, GitCapabilityCache, and the leading--c global-option commands are untouched. SshGitProvider only benefits from getting an accurate CONNECTION_LOST code on a dropped relay. No provider-specific (GitHub/GitLab) surface is involved.

Performance

  • SshChannelMultiplexer: one nullable field, plus a small Error factory 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 per establish(), two per reconnect() (post-reattach and post-notify).
  • ssh-git-response-stream-reader: a statement reorder — same work, different order.
  • TerminalErrorToast: one String.prototype.includes per 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:readDir and 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.

  • Review loop count: 2 round(s)
  • Final verdict: CLEAN
  • The final round returned zero blocker/major findings from both lenses.

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-reattachKnownPtys and 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 }. registerProviders returns false precisely when ownsAttempt() 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 (the isDisposed() throw at :623-625 catches 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's onDispose callback stop duplicating the message/code mapping. That duplication predates this PR (the same mapping also lives in ssh-filesystem-stream-reader.ts:255-263) and is left as-is here.

Made with Orca 🐋

…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
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e02494c8-3093-414f-80ae-8aec203cebce

📥 Commits

Reviewing files that changed from the base of the PR and between 10ab781 and d79af19.

📒 Files selected for processing (2)
  • src/main/ssh/ssh-channel-multiplexer.ts
  • src/main/ssh/ssh-git-response-stream-reader.ts

📝 Walkthrough

Walkthrough

The 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies automatic SSH relay recovery from the reported multiplexer-disposed failure.
Description check ✅ Passed The description explains the user-visible change, implementation, testing, security, platform impact, risks, and follow-up considerations.
Linked Issues check ✅ Passed The changes address issue #11953 by preventing stale connected state, preserving connection-loss errors, and restoring relay-loss recovery.
Out of Scope Changes check ✅ Passed The code and tests remain within the SSH relay failure, recovery, error classification, and listener-cleanup objectives.
✨ 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between c9a37f5 and 7ab4f45.

📒 Files selected for processing (8)
  • src/main/ssh/ssh-channel-multiplexer.test.ts
  • src/main/ssh/ssh-channel-multiplexer.ts
  • src/main/ssh/ssh-git-response-stream-reader.test.ts
  • src/main/ssh/ssh-git-response-stream-reader.ts
  • src/main/ssh/ssh-relay-session-relay-loss.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/renderer/src/components/terminal-pane/TerminalErrorToast.test.ts
  • src/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]>
@AmethystLiang

Copy link
Copy Markdown
Contributor

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.
@AmethystLiang
AmethystLiang merged commit e233d6a into main Aug 5, 2026
40 checks passed
AmethystLiang added a commit that referenced this pull request Aug 5, 2026
…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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
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.

[Bug]: "Multiplexer disposed" — remote terminals and file tree break after reopening the app

2 participants