Repository navigation
fix(runtime): deliver subscription close when retiring a remote transport - #12384
Conversation
…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.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughRuntime 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)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
config/reliability-gates.jsonc (1)
1053-1056: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse issue or PR URLs for
motivatingLinks.
motivatingLinksexists only inconfig/reliability-gates.jsoncand 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 intestFilesonly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 99384360-b8df-42ae-84be-12896e556f7e
📒 Files selected for processing (4)
config/reliability-gates.jsoncsrc/main/ipc/runtime-environments.test.tssrc/main/ipc/runtime-environments.tstests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts
| 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 | ||
| } |
There was a problem hiding this comment.
🗄️ 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
fiRepository: 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.
| // 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 { |
There was a problem hiding this comment.
📐 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
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.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a6f18b5e-f907-4ec4-83c1-6bb85d4ca4af
📒 Files selected for processing (2)
config/reliability-gates.jsoncsrc/main/ipc/runtime-environments.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- config/reliability-gates.jsonc
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.
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:The per-subscription forwarder in
runtimeEnvironments:subscribegated every event ontransportIsCurrent(). 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 onready && subscription(observed asreuse-ready),sendFrame()reports success while writing into a socket main no longer owns,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
closeis 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'ssendcan 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.
Server-observable delta after a retirement: the client now performs bounded
session.tabs.listinventory calls and then opens a freshterminal.multiplexsubscription, 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.tsruns 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: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 at128x60while the pane was135x60.Validation
135x60. All three scenarios pass in 15.5s.src/main/ipc/runtime-environments.test.ts: one asserts the renderer receives exactly oneclosewhen 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.runtime-environments, preload subscription bridge, remote-runtime request connection integration, remote-runtime PTY transport, parse backpressure).typecheck:node,oxlint, max-lines ratchet, andcheck:reliability-gatesall clean.Reliability gate
Registers
runtime.streaming-subscription-close-deliveryinconfig/reliability-gates.jsonc— invariant, oracle, commands, assertion refs, red/green evidence, and the gaps below.Known gaps
runtimeEnvironments.disconnect. Real sleep/wake and network partitions almost certainly reach the same code path but are not yet exercised by this gate.Follow-up, deliberately not in this PR
Review surfaced a pre-existing gap this fix now makes reachable rather than silent.
runtime_manually_disconnectedis in neitherRECOVERABLE_CODESnorRECOVERABLE_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.resolvePanerejects with that code → rethrown (remote-runtime-pty-transport.ts:988) → classified non-recoverable →recovery.cancel()+ red error banner, whichretryRecovery()will not re-arm because it requires phasedisconnected.Web-surface tabs are unaffected — the error is absorbed by
waitForResubscribeHostSessionHandle, which lands indisconnectedwith 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_disconnectedto the shared recoverable set would also makecreateWithUnknownOutcomeRecoveryretry 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 existingTerminalRemoteRuntimeReconnectBannerrather 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.getSharedControlConnectionswaps its cached connection whenever the pairing key changes and callsconnection.close()directly (runtime-environment-request-connections.ts:109-111), bypassing retirement. A shared-control logical close deliberately skipsonClose(remote-runtime-shared-control-state.ts:101-118withnotifyClose: false) — which is exactly why the directnotifyClosed()incloseSubscriptionsForEnvironmentis 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:
preferredEndpointIdis assigned once at environment creation, nothing switches it, and the only re-pair path callsinvalidateRuntimeEnvironmentTransportimmediately. 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.