Skip to content

fix: Remote Orca Server reconnect liveness — recover mirrors, input routing, and creates after tunnel drops - #7827

Merged
Jinwoo-H merged 4 commits into
mainfrom
fix/7718-remote-runtime-reconnect-liveness
Jul 8, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
fix/7718-remote-runtime-reconnect-liveness

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Fixes #7718
Likely fixes #7489 — same root cause, Windows flavor unverified live.

Symptoms (Remote Orca Server, after a devtunnel/network drop-and-return)

  1. Mirrored tabs freeze — the client UI never updates again even though the host keeps changing.
  2. Tabs created from the client spawn on the host, then die ~10 seconds later (and never appear on the client).
  3. Keystrokes mis-route: typing reaches the host but lands on / mirrors from the wrong pane.
  4. [Bug]: Remote Severs on windows crash #7489 flavor (Mac client → Windows host): terminals refuse to open, split panes come up blank.

Root cause

The client has no client→server liveness probe, and shared-control reconnect is edge-triggered on a ws close that a half-open tunnel never delivers. The server reaps its end via a 15s ping/terminate sweep (ws-transport.ts), so the two sides diverge: the client keeps a zombie socket in ready state, every push/RPC goes into the void and times out per-request (a shared-control request timeout previously rejected just that request and left the zombie socket alive — unlike the cached request connection, which tears down on timeout).

Three secondary bugs kept things broken even once a reconnect did fire:

  • A. Replayed snapshots silently dropped. On reconnect the client replays its subscriptions and the server re-emits the current session-tabs snapshot — with an unchanged publicationEpoch/snapshotVersion (host didn't restart). The monotonic freshness gate shouldApplyWebSessionTabsSnapshot rejected it → mirrors stayed frozen forever.
  • B. Stale handles silently bound the wrong PTY. The multiplex transport resubscribed with the handle captured in its closure, and terminal.send prechecks + the multiplex subscribe frame resolved via the unguarded resolveLeafForHandle, which doesn't validate PTY/generation. Handles are re-minted when a pane's PTY changes, so an old handle could route input to / mirror output from a different terminal.
  • C. Create rollback killed live terminals. session.tabs.createTerminal waited 10s for the surface publish and on failure closed the freshly created tab unless a fully pane-key-registered live PTY backed it. A dead client connection (the response had nowhere to go) or a live shell without a registered pane key both fell through to notifier.closeTerminal — the "tab dies after ~10s".

Commits

  1. fix(remote-runtime): client-side socket liveness + reconnect replay tagging — new remote-runtime-socket-liveness monitor (ping every 10s, dead after 25s of silence — just under two server heartbeat periods) wired into the shared-control socket and the dedicated stream sockets (terminal.multiplex, browser.screencast); a dead socket is terminated so the existing handleSocketClosed → scheduleReconnect / onTransportClose → resubscribe paths run. Shared-control request timeouts now tear the socket down, mirroring RemoteRuntimeRequestConnection. Reconnect replays tag the first re-emitted response per subscription (client-side, post-parse) so freshness gates can accept it.
  2. fix(web-session-tabs): accept replayed snapshots — tagged replay responses clear the per-env/worktree freshness entry before the gate runs, making the replayed snapshot authoritative and re-priming ordering protection. Normal-operation out-of-order rejection is untouched (fixes A).
  3. fix(terminal): guard stale handles + re-derive mirror handles — new guarded resolveLiveLeafForHandle (throws terminal_handle_stale on PTY/generation mismatch; still lets a pre-spawn ptyId: null handle adopt its first PTY, preserving the mobile flow) used by terminal.send and the multiplex subscribe frame; the renderer transport re-derives host-mirror handles from a fresh session.tabs.list on transport close instead of resubscribing the stale closure value, and routes input-path errors through the existing stale-handle recovery (retire + re-attach on next snapshot) instead of a dead-end red banner (fixes B).
  4. fix(terminal): don't roll back live mobile-created terminals — the ws abort signal threads through session.tabs.createTerminal into the reply/surface waits (a dead connection cancels the wait with client_disconnected instead of triggering rollback), and the rollback guard is broadened: any connected PTY bound to the renderer tab keeps the tab alive even when the surface rescue can't publish it. True spawn failures still roll back (fixes C).

Backward compatibility

  • New client ↔ old server: liveness rides RFC 6455 ping/pong control frames, which every supported server answers automatically via the ws package — no protocol change, no new frame types. The replay tag is added client-side after wire parsing and never touches the wire. The guarded-resolver and create changes are server-side only.
  • Old client ↔ new server: terminal.send / multiplex subscribe now answer stale handles with terminal_handle_stale instead of silently resolving the wrong PTY; old desktop clients already classify that message as "terminal gone" and recover (isRemoteTerminalGoneMessage). Valid handles behave identically, including the mobile pre-spawn waitForLeafPtyId path. The abort-signal threading only changes behavior for connections that are already dead.
  • Web (browser) clients use their own transport, not the Node shared-control connection; they don't get the new tag and behave exactly as before.

Test evidence (all deterministic; suites green)

  • Half-open zombie (required scenario): real ws server with autoPong: false that completes the handshake then goes silent — no close, no pongs, no frames. Asserts the client heartbeat terminates the socket, reconnects, replays the subscription, and that the replayed response carries the tag while the initial-connect response does not (remote-runtime-shared-control-connection.test.ts). Same scenario for a dedicated stream socket asserting onError + single onClose so the multiplexer's resubscribe path runs (remote-runtime-client.test.ts).
  • Request-timeout teardown: a never-answered request rejects with timeout AND forces a reconnect that replays active subscriptions without closing them.
  • Freshness-gate bypass: same-epoch/same-version snapshot rejected during normal operation, accepted after the replay reset, with ordering protection re-primed and the reset scoped to the replayed env/worktree (web-session-tabs-sync.test.ts).
  • Stale handles: runtime-level tests prove the unguarded resolver silently adopts a replacement PTY while the guarded one throws terminal_handle_stale (and that a pre-spawn null-PTY handle still adopts); RPC-level tests prove terminal.send fails with terminal_handle_stale and multiplex answers a stale subscribe with an error frame + end without ever binding a PTY.
  • Mirror re-derivation: renderer transport tests prove a transport close re-derives the handle from the current snapshot (resubscribes with the re-minted handle, updates the pty id) and quietly retires the mirror when the host no longer publishes the surface.
  • Create robustness: aborting the connection mid-create settles immediately with client_disconnected and never calls closeTerminal; a surface-publish stall with a live shell (no registered pane key) times out WITHOUT killing the terminal. Existing rollback tests (true spawn failure, ghost tab) still pass unchanged.
  • Full gates: affected vitest suites green (including the full 577-test orca-runtime suite and the 718-test terminal/session set), pnpm typecheck, oxlint clean on all changed files, max-lines ratchet OK (split the shared-control connection's liveness/stability wiring into the open/stability modules instead of suppressing).

Not verified / remaining risks

  • No live two-instance verification. Simulating a genuine half-open tunnel (toxiproxy timeout toxic / pf blackhole) requires sudo, and the reporter's Mac→Windows devtunnel topology needs two machines — I could not reproduce that live here. The deterministic half-open tests above are the evidence; the [Bug]: Remote Severs on windows crash #7489 Windows-specific angle is unverified live.
  • If an intermediary (rather than the end server) answers ws pings itself, client liveness could see a half-open link as alive until the server's own 15s heartbeat pings stop flowing; inbound server pings/frames also count as liveness, so detection still happens once the server side goes quiet.
  • A request timeout on a genuinely slow-but-healthy server now resets the shared-control socket (subscriptions replay transparently); this matches the long-standing behavior of the cached terminal.send connection.
  • terminal.updateViewport and a few other low-stakes paths still use the unguarded resolver; a stale handle there resizes the adopted pane until the next snapshot re-derives the handle. Left out to keep this change scoped to the input/output hot paths.

Made with Orca 🐋

Jinwoo-H and others added 4 commits July 8, 2026 14:12
…play tagging

A half-open tunnel (devtunnel/NAT drop) never delivers a ws close, so the
client's edge-triggered reconnect never fired while the server reaped its end
via its 15s ping/terminate sweep: frozen mirrors, void RPCs, zombie sockets
(#7718, #7489).

- New remote-runtime-socket-liveness monitor: ping on a cadence (10s) and
  declare the socket dead when no inbound traffic arrives within 25s; wired
  into the shared-control socket (open module) and the dedicated stream
  sockets (terminal.multiplex / browser.screencast) so the existing
  close -> reconnect/resubscribe paths run.
- Shared-control request timeouts now tear the socket down (mirrors
  RemoteRuntimeRequestConnection) instead of leaving it 'ready'.
- Reconnect replays tag the first re-emitted response per subscription
  (_replayedAfterReconnect, added client-side after wire parsing) so snapshot
  freshness gates can accept the replayed snapshot.

Backward compatible: liveness rides RFC 6455 ping/pong, which every supported
server (and the ws package) answers automatically; the replay tag never
touches the wire.

Co-authored-by: Orca <[email protected]>
…nnect

After a shared-control reconnect the server re-emits each stream's current
snapshot with an UNCHANGED publicationEpoch/snapshotVersion (the host did not
restart), so the monotonic freshness gate shouldApplyWebSessionTabsSnapshot
dropped it and mirrored tabs stayed frozen until an app restart (#7718).

Responses tagged as reconnect replays now clear the per-env/worktree freshness
entry before the gate runs, making the replayed snapshot authoritative while
re-priming ordering protection for subsequent frames. Normal-operation
out-of-order rejection is unchanged — only tagged replays bypass.

Co-authored-by: Orca <[email protected]>
…handles on reconnect

Handles are re-minted when a pane's PTY/generation changes, but terminal.send
prechecks and terminal.multiplex subscribe resolved via the unguarded
resolveLeafForHandle — a stale handle silently bound to whatever PTY now
occupies the same pane, misrouting keystrokes and mirrored output after a
reconnect (#7718).

- New OrcaRuntimeService.resolveLiveLeafForHandle: throws
  terminal_handle_stale when a handle minted for a concrete PTY no longer
  matches the pane's PTY/generation; handles still awaiting their first PTY
  (ptyId null) may adopt it, preserving the mobile pre-spawn subscribe flow.
- terminal.send and the multiplex subscribe frame now use the guarded
  resolver; multiplex answers a stale subscribe with an explicit
  terminal_handle_stale stream error + end instead of binding the wrong PTY.
- Renderer remote PTY transport: on transport close, host-session mirrors
  re-derive their handle from the current session.tabs.list snapshot instead
  of resubscribing the stale closure value; input-path errors route through
  the stale-handle recovery (retire + wait for next snapshot) instead of a
  dead-end red banner.

Co-authored-by: Orca <[email protected]>
…ce-wait failures

session.tabs.createTerminal waited up to 10s for the surface publish and, on
timeout, closed the freshly created tab unless a fully pane-key-registered
live PTY backed it. Two ways that killed real terminals (#7718 symptom 2,
#7489 "terminals refuse to open"):

- a dead client connection let the wait run down and trigger rollback even
  though the renderer had spawned a real shell;
- a live shell whose pane key had not registered (or is not a terminal-leaf
  UUID) failed the rescue and fell through to rollback.

Now the ws abort signal threads through session.tabs.createTerminal into the
reply/surface waits (cancelling them with client_disconnected, never rolling
back), and the rollback guard is broadened: any connected PTY bound to the
renderer tab keeps the tab alive even when the surface rescue cannot publish
it. True spawn failures still roll back.

Also carries the regression tests for the stale-handle resolver from the
previous commit (same test file).

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b3ea3695-9126-43fb-8406-38d84d5a56af

📥 Commits

Reviewing files that changed from the base of the PR and between ea652a1 and eac6cd3.

📒 Files selected for processing (24)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/session-tabs.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts
  • src/main/runtime/rpc/terminal-multiplex.test.ts
  • src/main/runtime/rpc/terminal-send.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
  • src/shared/remote-runtime-client.test.ts
  • src/shared/remote-runtime-client.ts
  • src/shared/remote-runtime-request-websocket.ts
  • src/shared/remote-runtime-shared-control-connection.test.ts
  • src/shared/remote-runtime-shared-control-connection.ts
  • src/shared/remote-runtime-shared-control-open.ts
  • src/shared/remote-runtime-shared-control-requests.ts
  • src/shared/remote-runtime-shared-control-stability.ts
  • src/shared/remote-runtime-shared-control-state.ts
  • src/shared/remote-runtime-shared-control-subscriptions.ts
  • src/shared/remote-runtime-shared-control-types.ts
  • src/shared/remote-runtime-socket-liveness.ts
  • src/shared/runtime-subscription-replay.ts

📝 Walkthrough

Walkthrough

This PR adds stale terminal handle detection (resolveLiveLeafForHandle, terminal_handle_stale) to orca-runtime and terminal RPC methods, plus AbortSignal-based cancellation for mobile terminal creation to avoid incorrect rollback/timeout behavior. The renderer PTY transport now centralizes "terminal gone" error handling and re-derives handles after transport close instead of relying on stale state. Session tabs sync gains replay acceptance to bypass freshness gating after reconnects. A new shared socket-liveness monitor (ping/pong tracking, dead-connection detection) is integrated into the remote runtime client and shared-control connection, alongside reconnect-replay response tagging and refactored stable-reset timer handling. Extensive test coverage accompanies each change.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: fixing Remote Orca Server reconnect liveness and the related mirror, input, and create recovery paths.
Description check ✅ Passed The description directly matches the changeset, covering liveness detection, replay tagging, stale handle fixes, and create rollback behavior.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Jinwoo-H

Jinwoo-H commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

Live verification (deterministic half-open repro) — PASS

Verified on one machine with two real paired desktop instances routed through a freezable TCP proxy (existing sockets black-hole bytes but stay open — including swallowing the server-side heartbeat terminate so the client leg stays genuinely half-open, exactly like a dead devtunnel; new connections pass so reconnect can succeed).

Baseline on main (38e82b4) — all three #7718 symptoms reproduced:

  • Zombie: 110s after freeze the client still showed Connected; mirror frozen at the last pre-freeze tick; server reaped its side at +19s; shared-control ws never fired close, reconnect never ran. Request-level timeouts fired but never tore down the socket.
  • Lost input: echo typed into the frozen mirror never reached the server pty.
  • Dying create: new terminal timed out and rolled back.

This branch (eac6cd3) — same script:

  • Detection at +17s (25s budget): fresh reconnect through the proxy, reset toast, mirror resumed gap-free (tick counter continuous across the freeze boundary), tab list correct — replayed snapshot applied.
  • Input after recovery executed on the correct server pty (file created, marker echoed in the right terminal).
  • Create after recovery worked (Terminal 2 live on both sides); create during freeze rolled back client-side with no server orphan after thaw.
  • Happy-path soak: 3min11s continuous output, zero gaps, zero reconnects — the 10s liveness pings cause no false positives.

Residual notes: worst-case detection is the 25s liveness window (comparable to the server's own reaper); screencast stream shares the same liveness code but only terminal.multiplex was live-driven; repro was loopback (WAN jitter has less margin, but detection keys off any inbound activity).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Remote Orca Server issues [Bug]: Remote Severs on windows crash

2 participants