Skip to content

fix(runtime): deliver subscription close when retiring a remote transport - #12384

Merged
Jinwoo-H merged 8 commits into
mainfrom
OrcaWin/remote-runtime-subscription-close-delivery
Aug 4, 2026
Merged

Jinwoo-H merged 8 commits into
mainfrom
OrcaWin/remote-runtime-subscription-close-delivery

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Revisiting an older remote workspace could leave its terminals blank and completely unresponsive: no output, keystrokes never reaching the shell, and the TUI rendering at the host's width inside a wider client pane (empty space on the right). Creating a new terminal in the same workspace worked, and flipping to another terminal and back sometimes brought the missing output in — which is what makes this look like a rendering bug when it isn't.

Root cause

invalidateRuntimeEnvironmentTransport() retires an environment's transport by advancing a per-environment transport generation first, then closing that environment's streaming subscriptions:

advanceRuntimeEnvironmentTransportGeneration(environmentId)  // generation++
closeRemoteRuntimeRequestConnection(environmentId)
clearSharedControlSupport(environmentId)
closeSubscriptionsForEnvironment(environmentId)              // sockets close here

The per-subscription forwarder in runtimeEnvironments:subscribe gated every event on transportIsCurrent(). That guard exists so a retired peer cannot leak stale state after a same-id re-pair — correct for payload frames, but it also swallowed the { type: 'close' } event, which is the renderer's only teardown signal.

So the renderer kept a subscription handle it believed was open:

  • RemoteRuntimeTerminalMultiplexer.ensureConnected() short-circuits on ready && subscription (observed as reuse-ready),
  • sendFrame() reports success while writing into a socket main no longer owns,
  • the host never answers subscribed.

Every consequence follows from that one dead pipe. Output never arrives. Input never lands. The desktop viewport claim rides the same stream, so the PTY stays at the host's grid — the geometry symptom. And because the renderer only discards a multiplexer once no stream is using it (closeIfIdle), flipping tabs can drain it to idle and force a fresh connection, which is exactly the reported "it shows up after switching tabs" workaround.

Fix

close is a lifecycle terminator, not a payload, so it is now always delivered — at most once, and never to a destroyed sender. Data-bearing frames keep the generation guard unchanged. Environment-wide retirement notifies explicitly so it does not depend on a given transport's close callback firing.

Once the renderer hears close, it releases the multiplexer and rebuilds on the next subscribe — machinery that already existed and already runs for ordinary network drops.

The retirement sweep is also now isolated per subscription. It previously had none, so a throw from any one teardown abandoned the rest — they stayed mapped with live sockets and the disconnect IPC itself rejected, stranding exactly the dead handles the sweep exists to retire. close() was already a throw site; delivering the close notice added a second, since Electron's send can throw on a disposed render frame.

Compatibility

No wire-protocol surface: the diff touches one runtime source file and no protocol, capability, RPC-method, or envelope code. Main and renderer ship in the same bundle, so there is no mixed-version surface and no negotiation needed.

  • New client + old server — works, fix fully effective.
  • New server + old client — old client keeps the bug. This is a client-side defect; upgrading the server does not fix it.

Server-observable delta after a retirement: the client now performs bounded session.tabs.list inventory calls and then opens a fresh terminal.multiplex subscription, where previously it sent nothing. Both methods predate the protocol-2 compatibility floor, and the sequence is identical to what an ordinary network reconnect already produces.

Reproduction

tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts runs a real headed Orca host as the remote server plus a separate real paired Orca desktop client, and probes three reveal scenarios against one host:

scenario before
hidden tab, still mounted → reveal pass
cold-parked tab → reveal pass
cold-parked tab → runtime disconnect/reconnect → reveal fail

Each scenario records four independent signals: buffer restored, host receipt of the typed marker (through an out-of-band sink file written by the fixture, not the terminal buffer), live paint without a tab flip, and PTY-vs-pane grid convergence.

Failing state on main: recoveryState: "connecting" indefinitely, bufferLength: 0, the marker never in the host sink, a tab flip not recovering it, and the PTY stranded at 128x60 while the pane was 135x60.

pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts \
  --config tests/playwright.config.ts --project electron-headless --workers=1

Validation

  • Red → green: the reconnect scenario now restores, accepts input, paints live, and converges to 135x60. All three scenarios pass in 15.5s.
  • Contract tests in src/main/ipc/runtime-environments.test.ts: one asserts the renderer receives exactly one close when a disconnect retires its stream; the other asserts a retired transport's late payload is still suppressed and its late close does not re-send. Reverting the source fix turns the first one red. 50/50 pass.
  • 176 related unit tests pass (runtime-environments, preload subscription bridge, remote-runtime request connection integration, remote-runtime PTY transport, parse backpressure).
  • typecheck:node, oxlint, max-lines ratchet, and check:reliability-gates all clean.

Reliability gate

Registers runtime.streaming-subscription-close-delivery in config/reliability-gates.jsonc — invariant, oracle, commands, assertion refs, red/green evidence, and the gaps below.

Known gaps

  • The transport drop here is an explicit runtimeEnvironments.disconnect. Real sleep/wake and network partitions almost certainly reach the same code path but are not yet exercised by this gate.
  • Paired-server evidence is macOS host + macOS client. A Windows host run is worth adding, since ConPTY and host window lifecycle sit outside this harness.
  • Browser screencast and mobile subscribers share the fixed contract but have no dedicated reveal journey.

Follow-up, deliberately not in this PR

Review surfaced a pre-existing gap this fix now makes reachable rather than silent. runtime_manually_disconnected is in neither RECOVERABLE_CODES nor RECOVERABLE_MESSAGE_FRAGMENTS (src/shared/remote-runtime-client-error-classification.ts:3-20). So after a manual Disconnect, a non-web-surface remote worktree pane now takes: close delivered → scheduleResubscribeAfterTransportClose → resolvePersistedHostPane() → terminal.resolvePane rejects with that code → rethrown (remote-runtime-pty-transport.ts:988) → classified non-recoverable → recovery.cancel() + red error banner, which retryRecovery() will not re-arm because it requires phase disconnected.

Web-surface tabs are unaffected — the error is absorbed by waitForResubscribeHostSessionHandle, which lands in disconnected with a working retry. E2E scenario S3's decoy panes cover that path.

Before this fix that same pane froze silently instead, so this is not a regression introduced here. It is left out on purpose: adding runtime_manually_disconnected to the shared recoverable set would also make createWithUnknownOutcomeRecovery retry terminal creation against a deliberately disconnected server instead of failing fast, so it needs its own reasoning and tests. The likely right shape is routing manual disconnect to the existing TerminalRemoteRuntimeReconnectBanner rather than the fatal error surface.

Second follow-up: a latent hole in the same bug class

Round-2 review confirmed the bug class — renderer holding a subscription handle main no longer owns — is closed on every path reachable today. But the closure rests on an invariant nothing enforces: every pairing-key change must route through invalidateRuntimeEnvironmentTransport.

getSharedControlConnection swaps its cached connection whenever the pairing key changes and calls connection.close() directly (runtime-environment-request-connections.ts:109-111), bypassing retirement. A shared-control logical close deliberately skips onClose (remote-runtime-shared-control-state.ts:101-118 with notifyClose: false) — which is exactly why the direct notifyClosed() in closeSubscriptionsForEnvironment is load-bearing rather than belt-and-braces. On that swap route no close fires at all, so shared-control subscribers (session.tabs.subscribe, runtime.clientEvents.subscribe, accounts.subscribe, notifications.subscribe, files.watch) would go silently dead rather than closed.

Not reachable today: preferredEndpointId is assigned once at environment creation, nothing switches it, and the only re-pair path calls invalidateRuntimeEnvironmentTransport immediately. But adding endpoint failover or a second access endpoint — LAN ↔ Tailscale, which the multi-endpoint schema clearly anticipates — would silently reopen this with no test to catch it. Worth pinning the invariant near that call site when someone next touches endpoint selection.

OrcaWin added 2 commits August 3, 2026 21:50
…port

invalidateRuntimeEnvironmentTransport advances the per-environment transport
generation before closing that environment's streaming subscriptions, and the
per-subscription forwarder gated every event on transportIsCurrent(). That
guard protects payload frames from a retired peer, but it also swallowed the
{type:'close'} event -- the renderer's only teardown signal.

The renderer therefore kept a dead subscription handle open: the terminal
multiplexer's ensureConnected() short-circuits on ready && subscription,
sendFrame() reports success into a socket main no longer owns, and the host
never answers 'subscribed'. Revealing a remote terminal after a reconnect left
the pane in 'connecting' with an empty buffer, keystrokes never reaching the
host PTY, and the viewport claim never landing so the PTY stayed at the host's
grid.

Close is a lifecycle terminator, not a payload: deliver it regardless of
transport generation (at most once, never to a destroyed sender) while data
frames keep the guard. Environment-wide retirement notifies directly, since a
shared-control logical close never calls back.

Adds a paired-server E2E journey (real host + real paired desktop client) that
probes three reveal scenarios with four independent signals each, and main-IPC
contract tests for close delivery and stale-payload suppression. Registers the
runtime.streaming-subscription-close-delivery reliability gate.
Review follow-ups. The E2E's decoy tabs are what keep a wedged multiplexer
alive (closeIfIdle only releases at zero streams), so a future refactor there
could silently turn the pre-fix red state green -- say so in the spec header.
Only the close-delivery unit test reproduces the bug; the stale-payload test is
a forward guard on the retained generation gate, so label them accordingly.
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review 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
📝 Walkthrough

Walkthrough

Runtime subscriptions now retain an idempotent renderer close notifier. Runtime cleanup emits one terminal close event, while stale payloads and duplicate callbacks are suppressed. IPC tests cover disconnection and retired transports. A paired remote-terminal test covers hidden-mounted, cold-parked, and reconnect-while-parked reveal scenarios, including buffer restoration, input, painting, and geometry convergence. A reliability gate defines evidence, budgets, promotion criteria, known gaps, and demotion rules.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main fix: delivering subscription close events when retiring remote transports.
Description check ✅ Passed The description clearly covers the problem, root cause, fix, compatibility, reproduction, validation, reliability gate, known gaps, and follow-up work.
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.

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

🧹 Nitpick comments (1)
config/reliability-gates.jsonc (1)

1053-1056: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use issue or PR URLs for motivatingLinks.

motivatingLinks exists only in config/reliability-gates.jsonc and other gates use link-style references. Replace both repository-relative values with the motivating issue or pull request URL, or omit them if the gate has no motivating discussion link. Keep the spec path in testFiles only.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 99384360-b8df-42ae-84be-12896e556f7e

📥 Commits

Reviewing files that changed from the base of the PR and between ce8b778 and 233eb46.

📒 Files selected for processing (4)
  • config/reliability-gates.jsonc
  • src/main/ipc/runtime-environments.test.ts
  • src/main/ipc/runtime-environments.ts
  • tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts

Comment on lines +146 to +151
if (payload.type === 'close') {
// Why: retirement advances the generation before closing, so gating
// close on it stranded the renderer with a dead subscription.
notifyClosed()
return
}

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Trace renderer consumption of subscriptionEvent close payloads.
set -euo pipefail

rg -n -C 10 "runtimeEnvironments:subscriptionEvent" --glob '!**/*.test.*'

# Locate the close handling in the renderer multiplexer.
rg -nP -C 8 "\btype\s*===\s*'close'|handleClose\s*\(" --type=ts --glob 'src/renderer/**' --glob 'src/preload/**'

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files named runtime-environments =="
fd -i 'runtime-environments' .

echo "== relevant occurrences =="
rg -n -C 8 "transportIsCurrent|subscription\.close|notifyClosed|Runtime environment pairing|subscriptionId|runtimeEnvironments:subscriptionEvent|runtimeEnvironments:subscribe" --glob '!**/*.test.*' .

echo "== target file outline/sections if present =="
if [ -f src/main/ipc/runtime-environments.ts ]; then
  wc -l src/main/ipc/runtime-environments.ts
  sed -n '1,240p' src/main/ipc/runtime-environments.ts
fi

Repository: stablyai/orca

Length of output: 50370


Suppress close events for pre-registration subscribe failures.

subscribeRuntimeEnvironmentFromPreload() registers the subscriptionId before ipc.invoke() and then releases it when the promise rejects, but the main handler still emits a close event with that same subscriptionId; the preload dispatcher then calls onClose() after the mapping is gone. Treat this path as a local cleanup failure so the renderer receives no spurious close event.

Comment on lines +340 to +347
// Why: the paired client inherits this from the launching process; a reused
// Playwright worker would otherwise leak the shortened delay into later specs.
const previousParkDelay = process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS
process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = String(PARK_DELAY_MS)
const client = await launchPairedElectronClient(offer, testInfo, 'parked-reveal')
const createdTerminals: string[] = []
const results: ScenarioResult[] = []
try {

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

A launch failure leaks the park-delay override into later specs.

Line 343 sets ORCA_E2E_TERMINAL_PARKING_DELAY_MS, and line 344 calls launchPairedElectronClient before the try block at line 347. If that launch rejects, the finally at Lines 460-471 never runs and the override stays set for the remainder of the worker process. This defeats the purpose stated in the comment at Lines 340-341.

Move the launch inside the try and guard the client cleanup.

🛡️ Proposed fix to keep the override restore reachable
   const previousParkDelay = process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS
   process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = String(PARK_DELAY_MS)
-  const client = await launchPairedElectronClient(offer, testInfo, 'parked-reveal')
+  let client: PairedElectronClient | undefined
   const createdTerminals: string[] = []
   const results: ScenarioResult[] = []
   try {
+    client = await launchPairedElectronClient(offer, testInfo, 'parked-reveal')
     const worktreeId = await orcaPage.evaluate(() => {
     } else {
       process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = previousParkDelay
     }
+    if (!client) {
+      return
+    }
     for (const terminal of createdTerminals) {
       await callEnvironment(client.page, client.environmentId, 'terminal.closeTab', {
         terminal
       }).catch(() => undefined)
     }
     await client.dispose()

Every use of client inside the try body then needs no change, because TypeScript narrows it after the assignment.

Also applies to: 460-472

OrcaWin added 3 commits August 3, 2026 22:07
Round-2 review follow-ups.

The spec header named an invariant nothing enforced: each scenario's flip decoy
must still be mounted at reveal, since pre-fix closeIfIdle is the only remaining
release path and it needs zero streams. It held only via the most-recently-hidden
park exemption, so narrowing that exemption would have silently turned the
pre-fix red state green. Assert it instead. The header also read as if
closeIfIdle were the general release rule; handleClose discards at any stream
count, so scope the claim to the pre-fix state it describes.

Gate corrections: mobile does not share this contract (no Electron IPC, no
subscriptionEvent or terminal.multiplex references under mobile/), so drop it
from knownGaps; browser screencast does. flakeHistory claimed three consecutive
paired-server passes while evidenceRuns recorded one -- record all three.
…rement

closeSubscriptionsForEnvironment swept an environment's subscriptions with no
isolation, so a throw from any one teardown abandoned the rest -- they stayed
mapped with live sockets and the disconnect IPC itself rejected, stranding
exactly the dead handles the sweep exists to retire. close() was already a throw
site; delivering the close notice added a second, since Electron's send can
throw on a disposed render frame.

Guard each close independently and make notifyClosed non-throwing, latching
before the send so re-entry still cannot duplicate it. Regression test asserts
both subscriptions close and both close events land when the first throws; it is
red without the isolation.
The send guard added with the teardown isolation had no coverage -- deleting it
left all 51 tests green. Sequence it protects: subscription A closes cleanly,
its close notification throws because the render frame is disposed, and the
unguarded throw aborts the sweep before B closes or is told. Test makes the
renderer reject only A's notification and asserts the disconnect still completes
both transports and delivers B's close; it is red without the guard.

Gate oracle and coverageNotes described only the original two tests.

@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: a6f18b5e-f907-4ec4-83c1-6bb85d4ca4af

📥 Commits

Reviewing files that changed from the base of the PR and between ca4aa88 and 0ad2c7b.

📒 Files selected for processing (2)
  • config/reliability-gates.jsonc
  • src/main/ipc/runtime-environments.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • config/reliability-gates.jsonc

OrcaWin added 3 commits August 3, 2026 22:20
notifyClosed sat outside the sweep's guard, so the isolation rested on the
claim that nothing inside it would ever throw. Its send is guarded, but its
liveness probe is not, and any line added there later silently reproduces the
abandoned-siblings defect with no test to catch it.

Guard the two teardown steps independently -- neither can skip the other, in
either order. Regression test throws from the WebContents liveness probe and
asserts both transports still close; red without the guard.
The outer sweep guard added in a0e821a subsumed this test's failure mode:
a throwing send inside notifyClosed is now caught by the sweep, so the test
stayed green without the inner guard it claimed to pin, and the gate asserted
otherwise.

Retarget it to the notifyClosed call site that has no surrounding guard -- the
transport callback -- where a host-initiated close on a disposed render frame
would otherwise throw through onClose into the WebSocket close handler. That
restores one test per guard and covers a call site nothing exercised.
evidenceRuns[0] still described three teardown-isolation contracts; there are
two, plus the transport-path containment test the oracle now names separately.
Free text, no behavioral surface.
@Jinwoo-H
Jinwoo-H merged commit 0db12fe into main Aug 4, 2026
45 checks passed
@Jinwoo-H
Jinwoo-H deleted the OrcaWin/remote-runtime-subscription-close-delivery branch August 4, 2026 02:44
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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.

2 participants