Skip to content

fix(remote): recover and safely park paired terminals - #11416

Merged
OrcaWin merged 8 commits into
mainfrom
remote-orca-servers-load-issue
Jul 30, 2026
Merged

OrcaWin merged 8 commits into
mainfrom
remote-orca-servers-load-issue

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add a capability-gated, local-like lifecycle for paired Orca terminals: hidden client xterms and raw per-PTY streams are destroyed, while host PTYs and bounded authoritative history survive.
  • Restore parked terminals through the reattach coordinator from a requested 5,000-row host/provider snapshot, preserving PTY identity, output produced while parked, and continued live I/O.
  • Keep older paired hosts on the existing lossy hidden-manager limit/TTL fallback.
  • Preserve the earlier scoped stalled-stream recovery and explicit-Disconnect fencing, while adding stream-capacity backoff, full split-leaf watcher reconciliation, and bounded side-effect handoff cleanup.

Deterministic reproduction and causal chain

The headed paired-runtime harness reproduced the blank/deep-scrollback failure:

parked paired remount
  -> classified as an initial detached remote leaf
  -> transport.attach()
  -> only the current-screen replay arrived
  -> rows ~5963–5999 painted
  -> requested row 4000 was absent

The first candidate still failed because the initial current-screen replay won over the requested deep snapshot. The final fix routes only capability-approved parked paired remounts through reattach, waits for stream attachment, then asks the host for authoritative bounded history before releasing queued live bytes.

The same byte-identical six-terminal oracle is green against:

  • an isolated headed Orca desktop server plus separate paired web client;
  • an isolated headless orca serve host plus the same client flow.

Disabling terminal.paired-parking.v1 makes that oracle fail at its capability precondition, while the separate legacy fallback oracle remains green.

Behavior and tradeoff

  • Host PTY/process identity survives parking.
  • Client xterm state and its raw terminal multiplex stream do not survive parking.
  • Reveal restores up to the requested 5,000 rows from host-owned authoritative history, including output produced while parked.
  • History older than those 5,000 requested rows remains unavailable after parking.
  • Parked title/bell/agent facts use the singleton runtime client-event stream; parking does not add one raw stream per hidden PTY.
  • Hosts without the capability keep the prior lossy limit/TTL behavior, so mixed-version client/server pairs do not assume unsupported restoration.

Freeze/performance impact

The headed and headless oracles each create six real paired host PTYs with bounded high-output scrollback, ordinary-park five client xterms with the lossy retention budget disabled, and require:

  • exactly one mounted pane manager;
  • at least 55% staged xterm-cell release;
  • no more than 16 MiB heap growth;
  • under 500 ms renderer timer drift;
  • the same PTY after reveal;
  • row 4,000, parked-time output, and post-reveal I/O to paint.

This directly removes the known remote hidden-xterm retention pressure that can exacerbate multi-GB renderer/CPU freezes. It does not claim to fix every renderer freeze. The macOS display-only reveal/WebGL-atlas latency class remains separate.

Screenshots

No visual change.

Testing

  • pnpm run typecheck
  • pnpm run lint
    • full oxlint
    • native and type-aware quality audits
    • reliability-gate manifest
    • max-lines ratchet
    • localization catalog and coverage
  • Fresh Electron + web build through the paired E2E run
  • 16 focused files: 1,921 passed, one existing skip
  • Headed + headless paired parking oracle: 2 passed in 38.6 s
    • headless: 14.2 s
    • headed: 14.5 s
  • Capability-disabled first-paint + legacy fallback: 2 passed in 18.8 s
  • git diff --check

The focused reliability suite covers capability routing, provider-authoritative snapshots, reattach ordering, raw-stream release, side-effect delivery and timed cleanup, split-leaf remints, stream capacity/backoff, queued manual-disconnect fencing, and headless launch cleanup.

Security audit

  • No endpoint, pairing token, key, terminal command text, or pairing material is added to diagnostics.
  • The headed/headless fixtures consume readiness and pairing material in memory without printing or persisting it.
  • Restoration and recovery remain scoped to an already-authorized runtime and host-owned PTY; there is no local fallback.
  • No dependency or executable-download changes.

Remaining gaps

  • The real paired topology is validated on macOS; physical Windows, Linux, mixed-version binaries, live SSH, and production-scale 100-worktree runs remain follow-ups.
  • The live Windows incident proves a healthy host PTY and dead existing client stream, but lacks per-stream ACK counters; ACK starvation is deterministically reproduced, not proven to be its unique field trigger.
  • Historical trace archives are still needed to order and deduplicate the reported replay-wedge events against renderer heartbeat loss.
  • Host session-persistence failure can defer authoritative remote exit publication; the client intentionally does not infer death from transport uncertainty.

@coderabbitai

coderabbitai Bot commented Jul 29, 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

The change adds explicit runtime-environment connect and manual-disconnect fencing across IPC, preload, web, and renderer flows. Terminal subscription paths now distinguish retained-tail first paint from authoritative snapshot truncation. Remote terminal streams gain watchdog-based stall detection and recoverable stream restart behavior. Hidden remote worktree retention adds pending-spawn classification, parking diagnostics, E2E configuration, memory metrics, and paired-runtime coverage. Replay operations now record hashed identity and redacted PTY breadcrumb context, with updated reliability-gate definitions.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it omits the required AI Review Report section and a Notes section. Add an AI Review Report with risks checked and explicit macOS/Linux/Windows coverage, and include a Notes section for any platform-specific follow-up.
Docstring Coverage ⚠️ Warning Docstring coverage is 9.38% which is insufficient. The required threshold is 80.00%. 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 is concise and matches the main change: recovering and safely parking paired terminals.
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 💡 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.

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

🧹 Nitpick comments (4)
src/main/ipc/runtime-environment-connectivity-handlers.ts (1)

22-36: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider hoisting the fenced-response shape and the runtime_manually_disconnected code into shared code.

The identical envelope and literal code string are duplicated in src/renderer/src/web/web-preload-api.ts (manuallyDisconnectedResponse) and thrown as a bare string in src/main/ipc/runtime-environments.ts. A shared constant in src/shared/ would keep the desktop and web fences from drifting.

src/renderer/src/env.d.ts (1)

74-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse TerminalWorktreeParkingDebugVerdict.

Reference the exported .ts type instead of duplicating its anonymous shape in this declaration. As per coding guidelines, “Prefer regular .ts type declarations over .d.ts files when defining types.”

Source: Coding guidelines

src/main/runtime/rpc/methods/terminal.ts (1)

3025-3026: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

!sendBinary is unreachable here.

This block only runs after the if (!useBinaryStream) { … return } early return at Line 2564, and useBinaryStream requires Boolean(sendBinary) (Line 2470). So the second operand can never contribute and truncated is just initialOutputOverflowed. Consider dropping it (or hoisting the JSON-path fallback comment) to avoid implying a live fallback.

♻️ Simplify
-        truncated:
-          initialOutputOverflowed || (!sendBinary && isTerminalReadPayloadIncomplete(read)),
+        truncated: initialOutputOverflowed,
tests/e2e/paired-remote-terminal-stall-recovery.spec.ts (1)

44-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

shellQuote / fixtureCommand / callRuntime are copied verbatim into three new paired-runtime e2e specs. The shared root cause is that no tests/e2e/helpers/ module owns fixture-command construction or the paired-client runtime RPC call, so each spec re-implements the Windows-vs-POSIX quoting and the window.api.runtime.call unwrapper — three places to fix any quoting bug.

  • tests/e2e/paired-remote-terminal-stall-recovery.spec.ts#L44-L66: replace the local shellQuote/fixtureCommand/callRuntime with imports from the new helper module, passing the fixture path/args in.
  • tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts#L43-L65: same replacement; this copy is identical apart from the marker-less fixtureCommand() signature.
  • tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts#L48-L70: same replacement; this copy's fixtureCommand(marker) takes an extra arg, so give the shared helper a variadic args parameter.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 80f12b5b-5b28-471c-bfcd-418132d1ddda

📥 Commits

Reviewing files that changed from the base of the PR and between dde72f8 and dd9c6a0.

📒 Files selected for processing (34)
  • config/reliability-gates.jsonc
  • src/main/ipc/runtime-environment-connectivity-handlers.ts
  • src/main/ipc/runtime-environments.test.ts
  • src/main/ipc/runtime-environments.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-multiplex.test.ts
  • src/main/runtime/rpc/terminal-subscribe-buffer.test.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx
  • src/renderer/src/components/status-bar/SshStatusSegment.tsx
  • src/renderer/src/components/status-bar/runtime-environment-explicit-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/replay-guard.test.ts
  • src/renderer/src/components/terminal-pane/replay-guard.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.test.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.ts
  • src/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.ts
  • src/renderer/src/env.d.ts
  • src/renderer/src/lib/e2e-config.ts
  • src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts
  • src/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.ts
  • src/renderer/src/runtime/remote-terminal-stream-watchdog.ts
  • src/renderer/src/web/web-preload-api.test.ts
  • src/renderer/src/web/web-preload-api.ts
  • tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts
  • tests/e2e/helpers/headless-paired-runtime-host.ts
  • tests/e2e/helpers/paired-electron-client.ts
  • tests/e2e/helpers/paired-web-client-url.ts
  • tests/e2e/paired-remote-terminal-retention-memory.spec.ts
  • tests/e2e/paired-remote-terminal-stall-recovery.spec.ts
  • tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts
  • tests/e2e/paired-runtime-retention-metrics.ts

Comment thread src/renderer/src/i18n/locales/es.json Resolved
Comment thread src/renderer/src/web/web-preload-api.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR introduces a capability-gated parking lifecycle for paired (remote-runtime) terminals: when the host advertises terminal.paired-parking.v1, hiding a tab destroys the client xterm and raw multiplex stream while keeping the host PTY alive, then restores up to 5,000 rows of authoritative history on reveal via the reattach coordinator. Hosts without the capability fall back to the prior lossy hidden-manager limit/TTL path. The change also adds a stream-level stall watchdog with command-response and delivery-credit timeouts, backoff-gated retry on stream-limit errors, explicit manual-disconnect fencing for both Electron and web client paths, and bounded side-effect buffer cleanup with timer-backed TTLs.

  • Parking lifecycle: terminal-parked-tab-watchers.ts gains a reconcile path that tears down and restarts per-PTY watchers when the tab's primary PTY rotates; terminal-parked-pty-watcher.ts extracts per-PTY watcher startup with remote-PTY-aware exit subscriptions.
  • Reveal path: pty-connection.ts routes capability-approved paired park reveals through the reattach coordinator, fetching an authoritative host snapshot via serializeHiddenOutputSnapshot before releasing queued live bytes, superseding the prior SSH-main-model probe for remote PTYs.
  • Stall recovery + disconnect fencing: A two-tier watchdog (command-response at 10 s, delivery-credit at 30 s) is attached per multiplexed stream; capacity rejection gates retry through backoff; both Electron and web preload paths now track manuallyDisconnectedEnvironmentIds and return structured responses from queue factory invocations.

Confidence Score: 5/5

Safe to merge; the change is well-scoped behind a capability flag and the existing legacy path is untouched.

The parking lifecycle is gated on terminal.paired-parking.v1, so hosts that haven't opted in continue through the prior lossy path without any change in behaviour. The reattach coordinator ordering, attachment-ready wait, and disconnect-fence logic are all internally consistent and covered by a comprehensive test suite (unit + headed/headless E2E oracle). The three observations above are design tradeoffs and acknowledged gaps, not correctness regressions on any path the PR enables.

Files Needing Attention: The two-tier stall watchdog in remote-terminal-stream-watchdog.ts has the subtleties noted; the delivery timer reset behaviour and the dual-trip window are worth a second read-through before the watchdog is widened to more stream types.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/pty-connection.ts Routes capability-approved paired park reveals through the reattach coordinator; adds prefetched host snapshot path for remote PTYs on reveal, with correct ordering guards and fallback to null (not SSH model probe) for remote PTYs.
src/renderer/src/runtime/remote-terminal-stream-watchdog.ts New two-tier stall watchdog; delivery timer is not reset when additional bytes arrive while one is already armed, and a command-response probe does not suppress a concurrent delivery-credit trip.
src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts Integrates per-stream watchdog, capacity-rejection flag, and backoff retry; stream-limit error is handled via a sentinel flag before the end event, correctly routing retry through backoff.
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts Adds attachment-ready waiter set to gate serializeBuffer until the stream is fully attached; setAttachmentUnavailable correctly resolves all pending waiters with false on disconnect/destroy.
src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts Gains incremental reconciliation of parked watchers when PTY IDs change; correctly preserves titles for retained PTYs and clears titles for retired PTYs during restart-all paths.
src/renderer/src/components/terminal-pane/terminal-parked-pty-watcher.ts New file extracting per-PTY watcher startup; correctly skips subscribeToPtyExit for remote PTYs (exit events arrive via side-effect facts channel).
src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.ts New file with reconcileParkedWatcherPtyIds and stricter capturedIsCurrent validation requiring leaf+ptyId agreement.
src/renderer/src/web/web-preload-api.ts Adds manuallyDisconnectedEnvironmentIds fencing with structured responses from queue factory; disconnect now preserves activeEnvironment for reconnect while remove clears it.
src/main/ipc/runtime-environment-connectivity-handlers.ts New file extracting connectivity IPC handlers with pre- and post-call disconnect checks and a connect handler that clears the fence.
src/main/runtime/orca-runtime.ts Adds serializeAuthoritativeTerminalBuffer and splits sideEffect consumer availability to dispatch facts over both local IPC and the paired client event stream.

Reviews (5): Last reviewed commit: "fix(remote): harden terminal recovery li..." | Re-trigger Greptile

@OrcaWin
OrcaWin requested a review from brennanb2025 as a code owner July 30, 2026 00:49
@OrcaWin OrcaWin changed the title fix(remote): recover stalled terminal streams and bound retention fix(remote): recover and safely park paired terminals Jul 30, 2026
…oad-issue

# Conflicts:
#	config/reliability-gates.jsonc
#	src/main/runtime/rpc/methods/terminal.ts
#	src/main/runtime/rpc/terminal-multiplex.test.ts
#	src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts (1)

294-348: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Reconciliation restart can silently wipe a continuing pane's tracked title.

When reconcileParkedWatcherPtyIds flags restart: true because only some of a multi-leaf tab's PTYs left expectedPtyIds (e.g. one leaf is local/always-restorable and a sibling paired leaf's environment capability drops while parked), disposeParkedTabWatchers(tab.id) tears down every watcher for the tab — not just the retired one. The real startParkedTerminalByteWatcher dispose() unconditionally clears the runtime pane title slot whenever wroteRuntimeTitleSlot is true (regardless of whether the pane is actually leaving parked state). Since resolveParkedTerminalPaneCandidates reassigns the same paneId to a continuing pane (via the capturedPanesByTabId lookup), the immediately-following startParkedTabWatchers() reads initialTitle from the very slot that was just cleared, losing the continuing pane's last-known title.

This interaction isn't exercised by terminal-parked-tab-watchers.test.ts since startParkedTerminalByteWatcher (and its dispose behavior) is fully mocked there.

Consider disposing/restarting only the PTYs identified as changed (retired + newly-expected), leaving continuing entries in disposersByPtyId untouched, rather than a blanket dispose-all/restart-all — similar to how disposeParkedTerminalWatchersForPtyIds already does surgical disposal elsewhere in this file.

🧹 Nitpick comments (10)
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts (1)

3159-3162: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive the backoff window instead of hardcoding 249/1 ms.

The split advance encodes an implicit 250 ms first-backoff constant; if the transport's backoff base changes this test fails for a non-obvious reason. Importing/exporting the constant (or asserting >= base) keeps intent readable.

src/renderer/src/web/web-preload-api.ts (1)

3163-3183: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate manual-disconnect fencing logic across both call wrappers.

callRuntimeEnvelope and callEnvironmentEnvelope repeat the identical pre-check / in-closure-check / post-check fencing sequence around manuallyDisconnectedEnvironmentIds. Extracting this into a shared helper would prevent the two call sites from drifting if the fencing algorithm is ever adjusted.

♻️ Proposed extraction
+async function callFencedEnvelope<TResult = unknown>(
+  environment: RuntimeEnvironmentRecord,
+  method: string,
+  params: unknown,
+  timeoutMs: number | undefined
+): Promise<RuntimeRpcResponse<TResult>> {
+  if (manuallyDisconnectedEnvironmentIds.has(environment.id)) {
+    return manuallyDisconnectedResponse(environment)
+  }
+  const response = await runtimeCallQueuePool.enqueue(environment.id, method, () => {
+    if (manuallyDisconnectedEnvironmentIds.has(environment.id)) {
+      return Promise.resolve(manuallyDisconnectedResponse(environment))
+    }
+    return getClientForEnvironment(environment).call(method, params, { timeoutMs })
+  })
+  if (manuallyDisconnectedEnvironmentIds.has(environment.id)) {
+    return manuallyDisconnectedResponse(environment)
+  }
+  updateEnvironmentFromResponse(environment, response)
+  return response as RuntimeRpcResponse<TResult>
+}
+
 async function callRuntimeEnvelope<TResult = unknown>(
   method: string,
   params?: unknown,
   timeoutMs?: number
 ): Promise<RuntimeRpcResponse<TResult>> {
   const environment = requireActiveEnvironment()
-  if (manuallyDisconnectedEnvironmentIds.has(environment.id)) {
-    return manuallyDisconnectedResponse(environment)
-  }
-  const response = await runtimeCallQueuePool.enqueue(environment.id, method, () => {
-    if (manuallyDisconnectedEnvironmentIds.has(environment.id)) {
-      return Promise.resolve(manuallyDisconnectedResponse(environment))
-    }
-    return getClientForEnvironment(environment).call(method, params, { timeoutMs })
-  })
-  if (manuallyDisconnectedEnvironmentIds.has(environment.id)) {
-    return manuallyDisconnectedResponse(environment)
-  }
-  updateEnvironmentFromResponse(environment, response)
-  return response as RuntimeRpcResponse<TResult>
+  return callFencedEnvelope<TResult>(environment, method, params, timeoutMs)
 }

Also applies to: 3185-3206

src/renderer/src/web/web-preload-api.test.ts (1)

516-531: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assertion only checks one of eight resolved calls is fenced.

All 8 activeCalls resolve their underlying call() promise after disconnect() fires, so per the fencing logic in web-preload-api.ts, every one should hit the post-enqueue check and resolve to runtime_manually_disconnected — not just one. expect.arrayContaining([...]) only requires a single match, so a regression that lets some in-flight responses leak through unfenced would still pass this test.

✅ Tighter assertion
-      await expect(Promise.all(activeCalls)).resolves.toEqual(
-        expect.arrayContaining([
-          expect.objectContaining({
-            ok: false,
-            error: expect.objectContaining({ code: 'runtime_manually_disconnected' })
-          })
-        ])
-      )
+      await expect(Promise.all(activeCalls)).resolves.toEqual(
+        Array.from({ length: 8 }, () =>
+          expect.objectContaining({
+            ok: false,
+            error: expect.objectContaining({ code: 'runtime_manually_disconnected' })
+          })
+        )
+      )
src/main/runtime/orca-runtime.test.ts (1)

8491-8521: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Mislabeled source in the provider-history mock.

The mocked serializeProviderBuffer result sets source: 'headless', but this test is specifically verifying that authoritative provider history is preferred over the headless mirror — the fallback test below correctly uses source: 'headless' for the mirror case. Since source isn't asserted here it doesn't break the test, but it's a confusing fixture that could mislead readers about what source value the provider path actually returns.

✏️ Suggested fixture fix
       const serializeProviderBuffer = vi.fn().mockResolvedValue({
         data: 'authoritative screen\r\n',
         scrollbackAnsi: 'deep provider history\r\n',
         cols: 120,
         rows: 40,
         seq: 900,
-        source: 'headless'
+        source: 'provider'
       })
src/main/runtime/rpc/methods/terminal.ts (1)

2090-2098: 🩺 Stability & Availability | 🔵 Trivial

Capacity split looks correctly enforced.

Traced the pending-wait and active-stream checks against the pendingPtyWaitControllers/streams map mutations — no TOCTOU gap (checks and mutations run in the same synchronous block relative to the surrounding awaits) and pending-wait slots are always released in the finally block regardless of outcome, so no leak on active-limit rejection after a pending wait resolves.

One thing worth confirming: splitting the single combined cap into independent active (64) and pending (32) budgets raises the theoretical per-connection ceiling from 64 to up to 96 concurrent server-side resources (open stream slots + pending abort-controller/mount-request state). If this is intentional headroom for the paired-runtime stall-recovery flow, no action needed; otherwise it may be worth re-checking against server-side connection capacity planning.

Also applies to: 2149-2153

src/renderer/src/runtime/runtime-terminal-stream.ts (1)

99-106: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplify nested onSnapshot fallback condition.

The nested if (!options?.startAtLiveTail) { if (!options?.onSnapshot) { watcher(data) } } is equivalent to a single flattened condition and is slightly harder to scan.

♻️ Suggested simplification
       onSnapshot: (data, meta) => {
         options?.onSnapshot?.(data, meta)
-        if (!options?.startAtLiveTail) {
-          if (!options?.onSnapshot) {
-            watcher(data)
-          }
-        }
+        if (!options?.startAtLiveTail && !options?.onSnapshot) {
+          watcher(data)
+        }
       },
src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts (1)

230-246: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Tautological assertion doesn't test the remote-runtime exit-subscription skip.

ParkedTerminalByteWatcherOptions never has an onPtyExit field for any PTY kind, so not.toHaveProperty('onPtyExit') always passes and doesn't exercise the actual remote-runtime behavior difference — that subscribeToPtyExit is skipped (isRemoteRuntimePtyId(ptyId) ? () => {} : subscribeToPtyExit(...) in terminal-parked-tab-watchers.ts). Assert on exitSubscriptions instead to cover that branch.

✅ Proposed fix
     expect(startParkedTerminalByteWatcher).toHaveBeenCalledTimes(1)
     expect(startedWatchers[0].options).toMatchObject({
       ptyId: 'remote:env-1@@terminal-1'
     })
-    expect(startedWatchers[0].options).not.toHaveProperty('onPtyExit')
+    // Remote-runtime PTYs are retired authoritatively by the paired host,
+    // so no local exit sidecar should be registered for them.
+    expect(exitSubscriptions.find((entry) => entry.ptyId === 'remote:env-1@@terminal-1')).toBeUndefined()
   })
src/renderer/src/components/terminal-pane/pty-connection.ts (2)

7712-7727: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Skip the remote prefetch when an authoritative snapshot already arrived.

connectResult is known here, and the snapshot branch in applyReattachPayload takes strict precedence over prefetchedParkModelSnapshot. For a remote-runtime park-reveal that came back with connectResult.snapshot, this await serializeHiddenOutputSnapshot(...) round-trip is discarded work that delays first paint by a full host RPC.

♻️ Gate the remote prefetch on the absence of a snapshot
-      if (revealFollowsTerminalPark && (!hasStructuralReplay || isRemoteRuntimePtyId(ptyId))) {
+      if (
+        revealFollowsTerminalPark &&
+        !connectResult?.snapshot &&
+        (!hasStructuralReplay || isRemoteRuntimePtyId(ptyId))
+      ) {

772-781: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider reusing the shared capability selector.

selectPairedRuntimeParkingEnvironmentIds in terminal-hidden-view-parking.ts encodes the same runtimeStatusByEnvironmentId → capability check. Deriving this predicate from that helper keeps the paired-parking evidence rule in one place if the capability gate later gains conditions.

tests/e2e/helpers/paired-terminal-parking-oracle.ts (1)

153-192: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Lag probe leaks if the parking-verdict poll fails.

lagProbe.stop()/dispose() only run on the success path. When the expect.poll(...).toEqual(...) above throws, the probe handle stays alive and keeps sampling for the remainder of the run, which can distort later measurements and leaks a JSHandle. Wrap the probe lifetime in its own try/finally (or dispose it in the outer finally).


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c88221cc-8996-4744-89af-c8c0743b759e

📥 Commits

Reviewing files that changed from the base of the PR and between 5749bad and 802bdfd.

📒 Files selected for processing (44)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-multiplex.test.ts
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.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/components/terminal-pane/terminal-hidden-view-parking.test.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.ts
  • src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.test.ts
  • src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.ts
  • src/renderer/src/env.d.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts
  • src/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.ts
  • src/renderer/src/runtime/runtime-client-events.test.ts
  • src/renderer/src/runtime/runtime-client-events.ts
  • src/renderer/src/runtime/runtime-terminal-stream.ts
  • src/renderer/src/web/web-preload-api.test.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/protocol-version.ts
  • src/shared/runtime-client-events.ts
  • src/shared/terminal-multiplex-flow-control.ts
  • tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts
  • tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts
  • tests/e2e/helpers/headless-paired-runtime-host.ts
  • tests/e2e/helpers/paired-electron-client.ts
  • tests/e2e/helpers/paired-terminal-parking-fixture.ts
  • tests/e2e/helpers/paired-terminal-parking-oracle.ts
  • tests/e2e/paired-remote-terminal-retention-memory.spec.ts
  • tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json

Comment thread src/main/runtime/orca-runtime.ts Resolved

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/runtime/rpc/methods/terminal.ts (1)

1935-1957: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Close source range ledgers when detaching consumers.

detachSourceRangeConsumer transfers and cancels ranges, then leaves the ledger’s retainedBytes intact and the registry entry registered for the connection lifetime, so accumulated subscriptions can hit TERMINAL_MULTIPLEX_MAX_ACTIVE_STREAMS_PER_CONNECTION and make sourceRangeRegistry.open() returns stop accepting source-range consumers.

🔧 Proposed fix
   const transfer = ledger.beginTransfer()
   const ranges = transfer.frames.flatMap((frame) => frame.sourceRanges)
   try {
     runtime.cancelRemoteTerminalSourceRanges(identity, ranges, reason)
   } finally {
     transfer.commit()
+    ledger.close()
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 24483b0c-c8e2-4c68-85b0-f93c45b8236f

📥 Commits

Reviewing files that changed from the base of the PR and between 802bdfd and 1443e90.

📒 Files selected for processing (8)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-multiplex.test.ts
  • src/main/runtime/rpc/terminal-source-range-registry.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts

Comment thread config/reliability-gates.jsonc Resolved
@OrcaWin

OrcaWin commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up review pass is complete. An outside-diff parked-watcher title-loss issue was confirmed and fixed with surgical per-PTY reconciliation, so continuing remote PTYs keep their watchers and runtime titles while only changed PTYs are replaced.

Validation is green: 1,167 focused tests (1 existing skip), the 1,938-test paired-terminal reliability slice (1 existing skip), typecheck, lint, formatting for every changed file, git diff --check, the reliability-gate manifest, and the max-lines ratchet.

@OrcaWin
OrcaWin merged commit bf894ef into main Jul 30, 2026
58 of 60 checks passed
@OrcaWin

OrcaWin commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator Author

rc.1 incident follow-up and deterministic refresh reproduction

v1.4.162-rc.1 does not contain this PR: release commit 62c51e77b2 does not descend from the prior PR head b31ee22b6d, and terminal.paired-parking.v1 is absent.

The new screenshot failure (Refreshing remote runtime control transport.) now has a separate deterministic red/green reproduction:

  1. Hold the first encrypted shared-control WebSocket before its ready frame.
  2. Start an RPC and leave it pending on that pre-ready socket.
  3. Let a successful one-shot status.get call reconnectNow().
  4. The old implementation replaces the socket and rejects the RPC with the exact screenshot error.

The fix preserves ready waiters and pending calls only across this reachability-triggered refresh. The original deadline remains active; ordinary close/error/manual-disconnect paths still reject. The transport oracle requires exactly two connections, one host RPC, a successful response, zero pending calls, and zero retained request bytes. Red-before produced the exact error; the updated branch passes all 27 focused tests.

The RDP observation adds an independent lifecycle signal: opening the parked terminal on the Windows host caused the existing client terminal to recover. That means the host and PTY were reachable, but client recovery depended on mounting/waking the host renderer. The headed paired-runtime oracle now keeps the host on its original workspace and asserts zero target pane managers are mounted there throughout recovery. The client still restores row 4,000, output produced while parked, the same PTY identity, and continued live input/output.

Post-merge validation at 846fb8b433:

  • pnpm run typecheck
  • full pnpm run lint, reliability manifest, and max-lines ratchet
  • shared-control transport: 27/27
  • daemon router/history handoff: 31/31
  • headed + headless paired parking: 2/2
  • headed + headless ACK-starvation recovery: 2/2
  • fresh Electron E2E build and git diff --check

For affected rc.1 installations, the least-bad workaround is to fully start the server first and then restart the client. Opening the host terminal via RDP can wake this failure class, but it is not durable and should not be required after this fix.

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