Skip to content

fix(runtime): bound the connect phase against an unreachable host, at the transport - #20053

Merged
nwparker merged 8 commits into
mainfrom
nwparker/remote-connect-bound
Sep 17, 2026
Merged

nwparker merged 8 commits into
mainfrom
nwparker/remote-connect-bound

Conversation

@nwparker

@nwparker nwparker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​404 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​403
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​210 $\color{#cf222e}{\Huge{\mathbf{−}}}$​58 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​152

What breaks

A host that is powered off or firewalled black-holes the TCP SYN, so the socket neither opens nor errors. None of the Node-side remote-runtime transports set a connect bound, leaving the caller's whole-request timeout as the only one.

Measured on an unreachable paired host (win-lowspec, SYNs dropped):

command unreachable host reachable host
terminal list 60.19s 0.24s
worktree list 60.26s 0.24s
repo list 60.21s 0.24s
status 60.24s 0.24s

Every orca <cmd> --environment <unreachable> sat silent for 60s before failing with a generic runtime_timeout. The uniformity across four unrelated commands is the argument that this is the shared transport, not one command.

The fix

Pass handshakeTimeout at the three shared remote-runtime WebSocket construction sites. The value matches the bound the browser transport already used.

ws maps handshakeTimeout onto the http.request timeout, which Node implements as a socket inactivity timer: armed before DNS/connect and reset by connect completion and by every response chunk. So the bound is "12s with no bytes at all", not a 12s wall-clock budget — a slow-but-answering host is not cut off, while a silent one fails promptly. Measured against a wss:// endpoint that completes TCP and then goes silent, the timer is re-armed once and the failure lands at about twice the bound, which is why the message names no elapsed time.

Failures keep code remote_runtime_unavailable, so the existing transport-loss classification in terminal-process-inspection still applies. Per docs/reference/ssh-execution-boundary.md, the message names the endpoint and stops at unverifiable — loss of contact is never evidence that the host's work stopped.

The message is a contract, not copy

A connect failure must keep the phrase Could not connect to the remote Orca runtime, because two gates key on it and the path this bound made reachable has nothing else to go on:

  • subscribeRemoteRuntimeTransport reports a connect failure by rejecting the subscribe promise, and that rejection crosses ipcMain.handle, which keeps only the message. The renderer then classifies it with RECOVERABLE_MESSAGE_FRAGMENTS. A message outside that list reads as fatal: recovery.cancel() and a red banner instead of a retry.
  • REMOTE_RUNTIME_UNREACHABLE_RE gates the Tailscale remedy on the same phrase — the one actionable remedy for an unreachable host.

Before this bound existed the case reached the 15s subscription-start timer, whose message did match a fragment. A 12s bound fires first, so a wording outside the gates would have turned an auto-recovering pane into a dead-ended one (the #12650 shape). The phrase is now a named constant, and the corpus in remote-runtime-transport-error-agreement.test.ts carries the coded, hinted and code-stripped producers derived from the real helper.

The endpoint in the message needed three guards

Interpolating the endpoint created problems the message itself caused:

  • The Tailscale hint was idempotent by testing for tailscale anywhere in the message. A host called tailscale-box now puts the word there itself and suppressed its own remedy. The guard keys on the two hints instead.
  • isRemoteTerminalGoneMessage substring-matches terminal_gone / terminal_exited / no_connected_pty before the recoverable gate, and WHATWG URL accepts _ in a host. ws://terminal_gone.example:6768 turned loss of contact into a terminal-gone verdict. The host is rendered only when it matches a hostname or IP-literal grammar that cannot carry such a token.
  • The endpoint comes from a pasted pairing code, which is only length-capped. Scheme and host are rendered, nothing else, so a pasted wss://user:secret@host cannot reach a surface the user reads.

remoteRuntimeConnectOptions also refuses a non-positive or non-finite bound: ws and net both gate on a truthy timeout, so 0 left the connect completely unbounded while still satisfying the connect-bound ratchet.

The relay control socket keeps ONE bound, not two

An earlier revision of this branch added a transport handshakeTimeout to the relay control socket on the argument that connectDeadlineMs could not see a black-holed connect. That argument is false and the bound is gone.

RelayControlClient.connect() constructs the socket and arms connectTimer in the same synchronous call — new WebSocket() never blocks — and expireConnect fires from opening as well as proving. The class deadline was already a strict superset.

It was also inert. Production passes neither option, so the transport bound was derived from connectDeadlineMs and both timers were 15_000, armed in the same tick; the ws timer is an inactivity timer armed on the later socket event, so it could not win. Its only reachable effect was changing which string a stalled relay connect rejects with, and it narrowed an existing test's 20ms deadline into a handshake bound it could race.

What replaces it is a test that holds the real ground: a connect whose upgrade is never answered expires on the class deadline. Moving the timer arm after open, or narrowing expireConnect to proving, both turn it red — which is what a future reader needs before concluding the phase is uncovered and adding a second bound again.

Verification

End-to-end through the production request path against a black-holed address (ws://192.0.2.1:6768, TEST-NET-1), caller budget 60s:

elapsed code message
with the bound 12007ms remote_runtime_unavailable names the endpoint, ends at unverifiable
bound removed 60003ms runtime_timeout Timed out waiting for the remote Orca runtime to respond.

Suites (all real counts, logs grepped for FAIL rather than trusting the exit code):

  • src/shared + src/main/runtime/relay — 8463 passed, 1 expected fail, 123 skipped, 0 FAIL
  • src/renderer/src/components/terminal-pane + src/main/ipc + src/renderer/src/runtime + src/cli — 11088 passed, 11 skipped, 0 FAIL
  • src/main/browser — 1800 passed, 0 FAIL
  • tsc --noEmit -p config/tsconfig.node.json clean; oxlint clean; oxfmt --check clean on every changed file

Mutation-tested — each assertion was confirmed to go red when the regression it claims to catch is reintroduced:

mutation red
message phrase back to Could not reach … 5 tests / 3 files
drop handshakeTimeout from the subscribe transport ratchet + subscribe ordering test
narrow relay expireConnect to proving only relay connect-deadline test (30s timeout)
drop the could not connect alternative from the Tailscale regex 3 tests
drop the fragment from RECOVERABLE_MESSAGE_FRAGMENTS 4 tests
restore the word-based hint idempotency guard vendor-name-in-host test
interpolate the raw endpoint credential-redaction test
drop the non-positive bound guard bound-coercion test
drop the host grammar guard terminal-gone smuggling test

No fake timers anywhere; the two live-socket tests run a real ws inactivity timer (150ms) against a real loopback listener that never upgrades.

Not verified: no run against a real remote host over Tailscale or a relay cell, and no Electron UI journey — the renderer recovery behaviour is covered by unit tests over the real classifiers, not by driving the app.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 0340693e-c8c7-4b78-92ad-3f0507c63121

📥 Commits

Reviewing files that changed from the base of the PR and between deaee39 and ed28211.

📒 Files selected for processing (1)
  • src/shared/remote-runtime-connect-bound.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/shared/remote-runtime-connect-bound.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

The change adds a shared 12,000 ms WebSocket connect bound with validation and endpoint-sanitized failure messages. Remote runtime request and subscription transports use the shared options and error formatter. Subscription contract types move to a dedicated module. Tailscale hint deduplication checks generated hints exactly. Tests cover silent upgrades, timeout classification, recoverability, sanitization, relay timeouts, and transport error agreements.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to ed282

Remote runtime connections retain a positive handshake bound even when callers provide invalid timeout overrides, so the prior silent-connection risk is resolved.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a detailed problem statement, implementation rationale, verification results, and known limitations. However, it omits required template items, including the linked issue, Vis… Add a valid issue reference under Linked Issue. Add Visual Proof with attachments or write N/A with a reason. Complete the remaining required template sections and checklist items, including AI Disclosure, Review, Agent skill upstream bound…
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 14 files. 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 identifies the main change: adding a transport-level bound for the runtime connect phase against unreachable hosts. The trailing phrase "at the transport" is awkward but does not obs…
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.
Full details: Description check

Explanation

The description provides a detailed problem statement, implementation rationale, verification results, and known limitations. However, it omits required template items, including the linked issue, Visual Proof or an explicit N/A, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.

Resolution

Add a valid issue reference under Linked Issue. Add Visual Proof with attachments or write N/A with a reason. Complete the remaining required template sections and checklist items, including AI Disclosure, Review, Agent skill upstream boundary, Notes, and testing confirmations.

  • Fix all pre-merge checks with AI
✨ 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.

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

Important

The new "unreachable" failure message falls out of both downstream message-matching tables, so the exact scenario this PR fixes now loses its Tailscale remediation hint (and, in code-less paths, its recoverable classification). One inline comment with details.

Reviewed changes

  • remote-runtime-connect-bound.ts — new helper stamping handshakeTimeout, detecting the ws handshake-timeout error, and building a failure message that names the endpoint and stops at "unverifiable".
  • Three Node-side transports — request-socket, request-websocket, and subscription-transport now route construction through remoteRuntimeConnectOptions and map their onError through remoteRuntimeConnectFailureMessage.
  • Relay control socket — construction moved to relay-control-socket-factory.ts with the same bound; RelayControlClient delegates to it and gains a settable handshakeTimeoutMs.
  • Tests — a source-scanning ratchet that every covered new WebSocket( is bounded, plus behavioral tests pinning error identity for both the remote-runtime and relay control bounds.

The fix itself is sound: ws's handshakeTimeout genuinely bounds the TCP-connect stall (verified against node_modules/ws/lib/websocket.js:890, which raises exactly 'Opening handshake has timed out'), the three construction sites are all covered, and the ratchet plus mutation reasoning for the two non-redundant relay bounds is convincing.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the nwparker/remote-connect-bound branch from 564449e to be6ff36 Compare September 11, 2026 08:23

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: aed299ae-f9ed-4d74-acbf-9bf3e09b5354

📥 Commits

Reviewing files that changed from the base of the PR and between 6bb2b0c and be6ff36.

📒 Files selected for processing (8)
  • src/main/runtime/relay/relay-control-client.ts
  • src/main/runtime/relay/relay-control-connect-transport-bound.test.ts
  • src/main/runtime/relay/relay-control-socket-factory.ts
  • src/shared/remote-runtime-connect-bound.test.ts
  • src/shared/remote-runtime-connect-bound.ts
  • src/shared/remote-runtime-request-socket.ts
  • src/shared/remote-runtime-request-websocket.ts
  • src/shared/remote-runtime-subscription-transport.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment on lines +80 to +86
createRelayControlSocket(
url,
token,
options.handshakeTimeoutMs ??
options.connectDeadlineMs ??
RELAY_CONTROL_CONNECT_DEADLINE_MS
))

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Use REMOTE_RUNTIME_CONNECT_TIMEOUT_MS as the handshake fallback

RelayControlClient passes connectDeadlineMs to createRelayControlSocket when handshakeTimeoutMs is unset. The class timer starts before the socket opens and remains active through host proof. Production connections use this path without either override, so a black-holed transport can consume the full 15-second class deadline and leave no separate host-proof budget. Use options.handshakeTimeoutMs ?? REMOTE_RUNTIME_CONNECT_TIMEOUT_MS instead.


export function remoteRuntimeConnectOptions<TOptions extends ClientOptions>(
options?: TOptions,
connectTimeoutMs: number = REMOTE_RUNTIME_CONNECT_TIMEOUT_MS

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Validate connection timeout overrides in remoteRuntimeConnectOptions.

The exported openRemoteRuntimeWebSocket and RelayControlClient options can pass 0, non-finite, or negative values through this helper. With ws 8.21.3 on Node 24, 0 and NaN skip the truthy handshakeTimeout setup, while other invalid values reach Node's timer handling and do not provide the intended positive bound. Reject values unless Number.isFinite(connectTimeoutMs) && connectTimeoutMs > 0 so request, subscription, and relay sockets all receive a valid bound. Add regression coverage for zero, non-finite, and negative overrides.

@nwparker
nwparker force-pushed the nwparker/remote-connect-bound branch from be6ff36 to b21e9c4 Compare September 15, 2026 09:33
… host

A host that is powered off or firewalled black-holes the TCP SYN, so the
remote-runtime WebSocket neither opens nor errors. The Node-side transports
set no connect bound, leaving the caller's whole-request timeout as the only
one: every `orca <cmd> --environment <unreachable>` sat silent for 60s before
failing with a generic `runtime_timeout`.

Measured on an unreachable paired host (win-lowspec, SYNs dropped): terminal
list / worktree list / repo list / status each took 60.19-60.26s; the same
command against a reachable host answered in 0.24s. So this was the shared
transport, not one command.

Pass `handshakeTimeout` at the three shared remote-runtime WebSocket
construction sites, which `ws` applies across TCP connect and the HTTP
upgrade. The value matches the bound the browser transport already used.

The failure keeps code `remote_runtime_unavailable` so the existing
transport-loss classification in terminal-process-inspection still applies,
and the message names the endpoint and stops at "unverifiable" — per
docs/reference/ssh-execution-boundary.md, loss of contact is never evidence
that the host's work stopped.
The relay control socket was constructed with no `handshakeTimeout`, the same
gap fixed for the remote-runtime transports. It was not a live defect: the
class-level `connectDeadlineMs` (15s) also covers a stalled connect, and that
deadline does fire — its `unref()` is safe because the pending TCP connect is
itself a ref'd libuv handle that holds the event loop open. Measured in a bare
Node process: unref'd timer with an empty loop never fires (exit at 0ms), but
the same timer alongside a black-holed connect fired at 2003ms.

It was a defect waiting on a refactor. The two bounds cover different phases,
and the class deadline covers the connect phase only incidentally.

DO NOT REMOVE EITHER BOUND AS REDUNDANT. They are not. Proven by mutation:

- Remove the transport bound -> a stalled *connect* falls through to the class
  deadline, rejecting with `relay_control_connect_timeout` after the full
  deadline instead of the transport error.
- Remove the class deadline -> a stall during the *proving* phase (socket open,
  host proof never answered) is unbounded; the incumbent test hangs 30s.
  `handshakeTimeout` cannot see that phase at all.

Reuses `remoteRuntimeConnectOptions` rather than forking a second helper, and
moves the construction into `relay-control-socket-factory.ts` so a caller that
needs a relay control socket gets the bound instead of re-deriving an unbounded
one. `handshakeTimeoutMs` is settable apart from `connectDeadlineMs` so a test
can stall the connect alone and assert which bound produced the rejection —
error identity, not elapsed time.

The connect-bound ratchet now covers the relay site and asserts the site still
resolves, so an allowlist that silently stopped matching cannot pass vacuously.
main tightened typescript/consistent-type-assertions to assertionStyle:
never, which the rebase brings onto these added lines. Dropping the
generic default is not typeable, so each cast keeps its own rationale.
The connect bound's new wording dropped out of the two gates that classify
remote-transport failures by message text, and those gates are the only ones
that run on the path the bound made reachable.

`subscribeRemoteRuntimeTransport` reports a connect failure by *rejecting* the
subscribe promise, and that rejection crosses `ipcMain.handle`, which keeps only
the message. The renderer then classifies it with `RECOVERABLE_MESSAGE_FRAGMENTS`.
`Could not reach the remote Orca runtime at …` matched no fragment, so it read as
fatal: `recovery.cancel()` and a red banner instead of a retry. Before the bound
existed this case reached the 15s subscription-start timer, whose message did
match a fragment, so introducing a 12s bound turned an auto-recovering pane into
a dead-ended one — the #12650 shape.

The same wording also fell outside `REMOTE_RUNTIME_UNREACHABLE_RE`, so the
Tailscale remedy was dropped for precisely the unreachable-host failure it
exists for.

Keep the canonical phrase both gates already recognise rather than teaching each
gate a second synonym for one condition, and pin it: the phrase is now a named
constant, the corpus in `remote-runtime-transport-error-agreement.test.ts` grows
the coded, hinted and code-stripped producers derived from the real helper, and
a new subscribe-path test proves the connect bound (not the start timer) is what
fires and that its message still classifies as recoverable once the code is
gone. Verdict wording is unchanged: `unverifiable`, never a synonym for exited.

Also states the bound in seconds, corrects the module comment (`handshakeTimeout`
is a socket inactivity timer, so a slow-but-answering host is not cut off), and
splits the subscription contract types out to stay under `max-lines`.
The claim that `connectDeadlineMs` cannot see a black-holed connect is false.
`RelayControlClient.connect()` constructs the socket and arms `connectTimer` in
the same synchronous call — `new WebSocket()` never blocks — and `expireConnect`
fires from `opening` as well as `proving`. The class deadline was already a
strict superset of a transport `handshakeTimeout` on that socket.

It was also inert. Production passes neither option, so the transport bound was
derived from `connectDeadlineMs` and both timers were 15_000, armed in the same
tick; the ws timer is an inactivity timer armed on the later `socket` event, so
it could not win. Its only reachable effect was changing which string a stalled
relay connect rejects with, and it narrowed an existing test's 20ms deadline
into a handshake bound it could race.

So this removes the factory, the test-only `handshakeTimeoutMs` option and the
source-grep test whose premise was wrong, and replaces them with a test that
holds the real ground: a connect whose upgrade is never answered expires on the
class deadline. Moving the timer arm after `open`, or narrowing `expireConnect`
to `proving`, both turn it red — which is what a future reader needs before
concluding the phase is uncovered and adding a second bound again.

No behaviour change for a reachable relay, and none for the verdict: a stalled
connect still rejects and still reaches `unverifiable`, never `exited`.
…he fix

Putting the endpoint into the message created three problems the message itself
caused.

The Tailscale hint is idempotent by testing whether "tailscale" already appears
anywhere in the message. That held while the message was fixed copy. Now a host
called `tailscale-box` puts the word there itself, and the hint — the only
actionable remedy on an unreachable host — is suppressed for it. Key the guard
on the two hints instead of the word.

The endpoint comes from a pasted pairing code, which is only length-capped;
`normalizePairingUrl` rejects userinfo but nothing re-validates a stored offer.
Render scheme, host and port only, so a pasted `wss://user:secret@host` cannot
reach a surface the user reads.

And drop the elapsed time from the wording. `handshakeTimeout` is a socket
inactivity timer, so a `wss://` host that completes TCP and then goes silent
re-arms it once and fails at about twice the bound; measured at 2008ms against a
1000ms bound. "within 12s" would have been wrong there, and the endpoint is the
actionable part regardless.

Also refuse a non-positive or non-finite bound: `ws` and `net` both gate on a
truthy timeout, so `0` left the connect completely unbounded while still
satisfying the connect-bound ratchet.
…sage

`isRemoteTerminalGoneMessage` in the pty transport substring-matches
`terminal_gone` / `terminal_exited` / `no_connected_pty`, and it runs before the
recoverable-connection gate: a match retires the pane's terminal id and cancels
recovery. WHATWG URL accepts `_` in a special-scheme host, so once the failure
message carried the endpoint, `ws://terminal_gone.example:6768` turned loss of
contact into a terminal-gone verdict — the one conclusion
`docs/reference/ssh-execution-boundary.md` forbids.

Render the host only when it matches a hostname or IP-literal grammar that
cannot carry such a token, and fall back to naming no endpoint at all. A
well-formed host, including a bracketed IPv6 literal, is still shown.
@nwparker
nwparker force-pushed the nwparker/remote-connect-bound branch from 2c9640c to deaee39 Compare September 16, 2026 05:34

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

✅ No new issues found.

Reviewed changes

Reviewed the four commits since the prior pullfrog review (2c9640c → deaee39), which rework the connect-failure wording and harden the endpoint it now carries.

  • Connect failure stays inside both message gates — the timeout message now begins with Could not connect to the remote Orca runtime, matching RECOVERABLE_MESSAGE_FRAGMENTS and REMOTE_RUNTIME_UNREACHABLE_RE, so the code-stripped subscribe path keeps retrying and keeps the Tailscale remedy; corpus entries pin the coded and code-stripped producers.
  • Endpoint interpolation is redacted and grammar-guarded — endpointForDisplay shows scheme + host only, and DISPLAYABLE_ENDPOINT_HOST_RE refuses any host that could carry a terminal_gone / terminal_exited / no_connected_pty token.
  • Tailscale hint idempotency keyed on its own text — no longer tests for tailscale anywhere in the message, so a host named tailscale-box still earns the remedy.
  • Redundant relay transport bound removed — the class connectDeadlineMs already covers a black-holed connect; a new raw-net silent-upgrade test pins relay_control_connect_timeout.
  • Subscription option/callback types extracted into remote-runtime-subscription-contract.ts and re-exported, with a test-only connectTimeoutMs override.

Prior review feedback is addressed: the produced message now matches both downstream tables. Verified locally — the five touched test files (40 tests) and the renderer classification tests (40 tests) pass, and pnpm tc:node is clean.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 2531dc9 into main Sep 17, 2026
28 checks passed
@nwparker
nwparker deleted the nwparker/remote-connect-bound branch September 17, 2026 05:23
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
… the transport (stablyai#20053)

* fix(runtime): bound the remote-runtime connect against an unreachable host

A host that is powered off or firewalled black-holes the TCP SYN, so the
remote-runtime WebSocket neither opens nor errors. The Node-side transports
set no connect bound, leaving the caller's whole-request timeout as the only
one: every `orca <cmd> --environment <unreachable>` sat silent for 60s before
failing with a generic `runtime_timeout`.

Measured on an unreachable paired host (win-lowspec, SYNs dropped): terminal
list / worktree list / repo list / status each took 60.19-60.26s; the same
command against a reachable host answered in 0.24s. So this was the shared
transport, not one command.

Pass `handshakeTimeout` at the three shared remote-runtime WebSocket
construction sites, which `ws` applies across TCP connect and the HTTP
upgrade. The value matches the bound the browser transport already used.

The failure keeps code `remote_runtime_unavailable` so the existing
transport-loss classification in terminal-process-inspection still applies,
and the message names the endpoint and stops at "unverifiable" — per
docs/reference/ssh-execution-boundary.md, loss of contact is never evidence
that the host's work stopped.

* fix(relay): bound the control socket's connect phase at the transport

The relay control socket was constructed with no `handshakeTimeout`, the same
gap fixed for the remote-runtime transports. It was not a live defect: the
class-level `connectDeadlineMs` (15s) also covers a stalled connect, and that
deadline does fire — its `unref()` is safe because the pending TCP connect is
itself a ref'd libuv handle that holds the event loop open. Measured in a bare
Node process: unref'd timer with an empty loop never fires (exit at 0ms), but
the same timer alongside a black-holed connect fired at 2003ms.

It was a defect waiting on a refactor. The two bounds cover different phases,
and the class deadline covers the connect phase only incidentally.

DO NOT REMOVE EITHER BOUND AS REDUNDANT. They are not. Proven by mutation:

- Remove the transport bound -> a stalled *connect* falls through to the class
  deadline, rejecting with `relay_control_connect_timeout` after the full
  deadline instead of the transport error.
- Remove the class deadline -> a stall during the *proving* phase (socket open,
  host proof never answered) is unbounded; the incumbent test hangs 30s.
  `handshakeTimeout` cannot see that phase at all.

Reuses `remoteRuntimeConnectOptions` rather than forking a second helper, and
moves the construction into `relay-control-socket-factory.ts` so a caller that
needs a relay control socket gets the bound instead of re-deriving an unbounded
one. `handshakeTimeoutMs` is settable apart from `connectDeadlineMs` so a test
can stall the connect alone and assert which bound produced the rejection —
error identity, not elapsed time.

The connect-bound ratchet now covers the relay site and asserts the site still
resolves, so an allowlist that silently stopped matching cannot pass vacuously.

* fix(lint): carry SAFETY rationales for the connect-bound casts

main tightened typescript/consistent-type-assertions to assertionStyle:
never, which the rebase brings onto these added lines. Dropping the
generic default is not typeable, so each cast keeps its own rationale.

* fix(runtime): keep the bounded connect failure inside both message gates

The connect bound's new wording dropped out of the two gates that classify
remote-transport failures by message text, and those gates are the only ones
that run on the path the bound made reachable.

`subscribeRemoteRuntimeTransport` reports a connect failure by *rejecting* the
subscribe promise, and that rejection crosses `ipcMain.handle`, which keeps only
the message. The renderer then classifies it with `RECOVERABLE_MESSAGE_FRAGMENTS`.
`Could not reach the remote Orca runtime at …` matched no fragment, so it read as
fatal: `recovery.cancel()` and a red banner instead of a retry. Before the bound
existed this case reached the 15s subscription-start timer, whose message did
match a fragment, so introducing a 12s bound turned an auto-recovering pane into
a dead-ended one — the stablyai#12650 shape.

The same wording also fell outside `REMOTE_RUNTIME_UNREACHABLE_RE`, so the
Tailscale remedy was dropped for precisely the unreachable-host failure it
exists for.

Keep the canonical phrase both gates already recognise rather than teaching each
gate a second synonym for one condition, and pin it: the phrase is now a named
constant, the corpus in `remote-runtime-transport-error-agreement.test.ts` grows
the coded, hinted and code-stripped producers derived from the real helper, and
a new subscribe-path test proves the connect bound (not the start timer) is what
fires and that its message still classifies as recoverable once the code is
gone. Verdict wording is unchanged: `unverifiable`, never a synonym for exited.

Also states the bound in seconds, corrects the module comment (`handshakeTimeout`
is a socket inactivity timer, so a slow-but-answering host is not cut off), and
splits the subscription contract types out to stay under `max-lines`.

* fix(relay): drop the duplicate connect bound on the control socket

The claim that `connectDeadlineMs` cannot see a black-holed connect is false.
`RelayControlClient.connect()` constructs the socket and arms `connectTimer` in
the same synchronous call — `new WebSocket()` never blocks — and `expireConnect`
fires from `opening` as well as `proving`. The class deadline was already a
strict superset of a transport `handshakeTimeout` on that socket.

It was also inert. Production passes neither option, so the transport bound was
derived from `connectDeadlineMs` and both timers were 15_000, armed in the same
tick; the ws timer is an inactivity timer armed on the later `socket` event, so
it could not win. Its only reachable effect was changing which string a stalled
relay connect rejects with, and it narrowed an existing test's 20ms deadline
into a handshake bound it could race.

So this removes the factory, the test-only `handshakeTimeoutMs` option and the
source-grep test whose premise was wrong, and replaces them with a test that
holds the real ground: a connect whose upgrade is never answered expires on the
class deadline. Moving the timer arm after `open`, or narrowing `expireConnect`
to `proving`, both turn it red — which is what a future reader needs before
concluding the phase is uncovered and adding a second bound again.

No behaviour change for a reachable relay, and none for the verdict: a stalled
connect still rejects and still reaches `unverifiable`, never `exited`.

* fix(runtime): stop the endpoint in the failure message from undoing the fix

Putting the endpoint into the message created three problems the message itself
caused.

The Tailscale hint is idempotent by testing whether "tailscale" already appears
anywhere in the message. That held while the message was fixed copy. Now a host
called `tailscale-box` puts the word there itself, and the hint — the only
actionable remedy on an unreachable host — is suppressed for it. Key the guard
on the two hints instead of the word.

The endpoint comes from a pasted pairing code, which is only length-capped;
`normalizePairingUrl` rejects userinfo but nothing re-validates a stored offer.
Render scheme, host and port only, so a pasted `wss://user:secret@host` cannot
reach a surface the user reads.

And drop the elapsed time from the wording. `handshakeTimeout` is a socket
inactivity timer, so a `wss://` host that completes TCP and then goes silent
re-arms it once and fails at about twice the bound; measured at 2008ms against a
1000ms bound. "within 12s" would have been wrong there, and the endpoint is the
actionable part regardless.

Also refuse a non-positive or non-finite bound: `ws` and `net` both gate on a
truthy timeout, so `0` left the connect completely unbounded while still
satisfying the connect-bound ratchet.

* fix(runtime): keep the endpoint from smuggling a verdict into the message

`isRemoteTerminalGoneMessage` in the pty transport substring-matches
`terminal_gone` / `terminal_exited` / `no_connected_pty`, and it runs before the
recoverable-connection gate: a match retires the pane's terminal id and cancels
recovery. WHATWG URL accepts `_` in a special-scheme host, so once the failure
message carried the endpoint, `ws://terminal_gone.example:6768` turned loss of
contact into a terminal-gone verdict — the one conclusion
`docs/reference/ssh-execution-boundary.md` forbids.

Render the host only when it matches a hostname or IP-literal grammar that
cannot carry such a token, and fall back to naming no endpoint at all. A
well-formed host, including a bracketed IPv6 literal, is still shown.

* docs(runtime): say why this connect bound is not the relay's removed duplicate
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