Repository navigation
fix(remote): scope renderer throttling to paired terminal publication - #11581
Conversation
Greptile SummaryThis PR fixes a paired remote desktop session bug where opening or closing a terminal on a backgrounded host window would hit the 10-second
Confidence Score: 5/5Safe to merge — the fix is narrowly scoped to paired create/close operations, all async paths release the throttle in finally blocks, and destroyed-target safety is explicitly handled. The new RendererPublicationThrottle class is small and its three invariants (leading-edge disable, last-lease restore, skip-on-destroyed) are all unit-tested. The two integration points in orca-runtime.ts wrap lease acquisition in try/finally, so a rejection or abort never leaks an unthrottled renderer. The pairedRendererSessionOwnedPtyIds recovery set is consistently cleaned up at disconnect, PTY drop, and rollback paths. No existing auth or IPC surfaces were changed. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/main/window/renderer-publication-throttle.ts | New core class: reference-counted lease manager for Electron background throttling. Logic is correct — released flag enforces idempotency, map deletion before the isDestroyed guard ensures no stale entries even when the renderer is torn down mid-lease. |
| src/main/runtime/orca-runtime.ts | Integrates RendererPublicationThrottle into create and close paths; lease wrapped in try/finally so release is guaranteed. Adds pairedRendererSessionOwnedPtyIds for post-reload surface recovery and createRuntimeOwnedMobileSessionTerminal rename. |
| src/main/runtime/rpc/methods/session-tab-close-methods.ts | Threads clientNavigationId through to closeMobileSessionTab so the throttle is acquired during whole-tab close for paired clients; unpaired closes are unaffected. |
| src/renderer/src/store/slices/terminals.ts | Adds an early-return guard preventing web clients from creating local folder terminal tabs; only the floating terminal worktree is allowed. |
| tests/e2e/paired-remote-terminal-stall-recovery.spec.ts | E2E test extended with a second observer client, host minimize/restore helpers, latency assertions (create and close must complete within PUBLICATION_DEADLINE_MS=10s), and pixel-level visual marker checks. |
Reviews (3): Last reviewed commit: "fix(remote): preserve paired terminal in..." | Re-trigger Greptile
📝 WalkthroughWalkthroughAdds paired renderer-session tracking for mobile terminal PTYs. Renderer-backed creation now validates graph epochs, supports abort signals, handles disconnected or destroyed clients, and falls back to runtime-owned creation. The runtime restores missing paired terminal snapshots and tracks ownership through PTY lifecycle events. Close operations use renderer publication throttling and tolerate prior persisted-tab removal. Tests cover creation, recovery, cancellation, publication leasing, closure, and PTY cleanup. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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: 1
🧹 Nitpick comments (1)
src/main/window/remote-client-renderer-throttle.ts (1)
1-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the module-level rationale comment.
This comment includes a detailed implementation narrative, source path, timeout text, and platform behavior. Keep only the non-obvious contract so the module remains easier to scan.
Suggested revision
-// Why: the host renderer publishes new terminal surfaces and tab snapshots to a -// paired client through setTimeout-coalesced graph syncs (see -// src/renderer/src/runtime/sync-runtime-graph.ts). Electron background-throttles -// a hidden/occluded window's renderer on every platform, so a remote host left -// in the background stalls session open/close for its paired client — the 10s -// "Timed out waiting for terminal surface after creation" host deadline — even -// though main-process PTY I/O (live keystrokes) stays fast. Keep the renderer -// unthrottled while at least one remote client is connected, and restore the -// throttled default once the last one disconnects so an unattended host still -// saves power. +// Keep the renderer unthrottled while remote clients are connected so +// background-hosted session synchronization can meet its deadline.As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6096d681-02d6-4134-94e5-b00715b3746d
📥 Commits
Reviewing files that changed from the base of the PR and between ab665a3 and 84cc0a770d76cc55bf3d28fcef9a9e26c28926fa.
📒 Files selected for processing (5)
src/main/runtime/orca-runtime.tssrc/main/runtime/runtime-rpc.tssrc/main/window/createMainWindow.tssrc/main/window/remote-client-renderer-throttle.test.tssrc/main/window/remote-client-renderer-throttle.ts
A paired desktop host left in the background could not open or close agent sessions for its remote/relay client: the action stalled and eventually failed with the host-side "Timed out waiting for terminal surface after creation" (10s) error, while an already-live terminal's keystrokes stayed fast. Root cause: creating/closing a session routes through the host renderer's setTimeout-coalesced graph sync to publish the terminal surface, but the host window runs with Electron background throttling (the hidden-window default, reaffirmed on macOS). When the window is backgrounded/occluded, those renderer timers are throttled to a crawl and the surface publication misses the 10s deadline. Live keystrokes are unaffected because PTY I/O flows through the main process, never the renderer. Keep the authoritative renderer unthrottled while at least one remote client is connected and restore the throttled power-saving default once the last one disconnects. Connect/disconnect are driven from the shared MobileSocketWiring onReady/onClose, so both direct-WS and cloud-relay clients are covered; headless serve has no window and is a safe no-op. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Address automated review nits on stablyai#11581: - Trim the module-level rationale comment to the non-obvious contract, matching the repo's concise-comment guideline. - Drop the dead `detachedThrottle` variable from the reapply test; the detached-target scenario is already covered by the lazy-resolution test, so the case now asserts only what it exercises. No behavior change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Keep headed paired terminal creation and close renderer-owned so host inventory, input routing, ACK recovery, and cleanup retain the established lifecycle. Hold a reference-counted background-throttle lease only while the renderer publishes a paired operation, and epoch-fence async resolution so renderer reloads reject before any request or PTY spawn. Preserve headless main ownership and prevent paired clients from falling back to a local terminal.
7eb4ad0 to
279ecc1
Compare
OrcaWin
left a comment
There was a problem hiding this comment.
Validated the final operation-scoped renderer publication lease on current main. Focused runtime/session/throttle suites: 1,076 passed, 1 skipped; node/web typechecks, lint, and E2E build passed. Three isolated real headed macOS minimized-host runs passed with two paired clients, authoritative inventory, input/output, ACK-starved restart with unchanged PTY identity, convergence, repaint, and close cleanup. Latest create/close publication: 70.2/74.0 ms; throttling restored after each operation. Unauthorized/unpaired no-spawn, graph-epoch TOCTOU, folder/SSH routing, cleanup, security, and bounded-resource behavior audited. Native Windows/WSL not claimed.
There was a problem hiding this comment.
Actionable comments posted: 1
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/orca-runtime.ts (1)
24701-24720: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winGate the new graph-epoch capture on renderer availability.
captureReadyGraphEpoch()throwsruntime_unavailableunlessgraphStatus === 'ready'. Both new call sites capture the epoch before the code that handles a host with no renderer graph, so a headlessorca servehost now fails paths it previously served.
src/main/runtime/orca-runtime.ts#L24701-L24720: capture the epoch only whengetAvailableAuthoritativeWindow()returns a window, and make the matchingassertStableReadyGraphcall conditional, so thecreateRuntimeOwnedMobileSessionTerminalfallback at Line 24721 stays reachable.src/main/runtime/orca-runtime.ts#L7338-L7350: replace theoptions.clientNavigationIdcondition with the same renderer-availability check, so the headless close branches below (closeHeadlessMobileTerminalTab) stay reachable for paired clients.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3245158c-2c86-471e-85f7-2700b738cba6
📥 Commits
Reviewing files that changed from the base of the PR and between 7eb4ad08d35e110ce401ed305380f4fa1745e7fd and 279ecc1.
📒 Files selected for processing (2)
src/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.ts
| clientNavigationId?: string | ||
| } = {} | ||
| ): Promise<RuntimeMobileSessionTabCloseResult> { | ||
| const graphEpoch = options.clientNavigationId ? this.captureReadyGraphEpoch() : null | ||
| const explicitWorktreeId = this.getValidatedExplicitWorktreeIdSelector(worktreeSelector) | ||
| const worktreeId = | ||
| explicitWorktreeId ?? (await this.resolveWorktreeSelector(worktreeSelector)).id | ||
| this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) | ||
| const observedPtyIds = await this.refreshMobileSessionPtyRecords() | ||
| if (graphEpoch !== null) { | ||
| this.assertStableReadyGraph(graphEpoch) | ||
| } | ||
| this.restoreLivePairedRendererSessionOwnedMobileTerminals(worktreeId) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Trace clientNavigationId propagation into closeMobileSessionTab.
set -euo pipefail
rg -n -C 6 'closeMobileSessionTab' --type=ts
rg -n -C 4 'refuseUnattributedMobileSessionTabClose|clientNavigationId' --type=ts -g '!**/*.test.ts' | head -n 200Repository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Tracked TS files count:\n'
git ls-files '*.ts' '*.tsx' | wc -l
printf '\nFind orca-runtime and related occurrences with no type filter:\n'
rg -n -C 4 'closeMobileSessionTab|captureReadyGraphEpoch|assertGraphReady|assertStableReadyGraph|refuseUnattributedMobileSessionTabClose|clientNavigationId|getAvailableAuthoritativeWindow' . --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' | head -n 300
printf '\nLocate file:\n'
git ls-files | grep -F 'src/main/runtime/orca-runtime.ts' || trueRepository: stablyai/orca
Length of output: 25638
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'orca-runtime size:\n'
wc -l src/main/runtime/orca-runtime.ts
printf '\nRelevant closeMobileSessionTab implementation:\n'
sed -n '7300,7535p' src/main/runtime/orca-runtime.ts | cat -n
printf '\nMobile session tab listeners / caller methods around registration:\n'
sed -n '2660,2765p' src/main/runtime/orca-runtime.ts | cat -n
rg -n -C 8 'mobileSessionTabListeners|listMobileSessionTabs|addMobileSessionTab|refuseUnattributedMobileSessionTabClose|RuntimeMobileSessionTabsOptions|clientNavigationId' src/main/runtime/orca-runtime.ts src/shared src/main | head -n 400
printf '\nSearch for closeMobileSessionTab text across tracked files:\n'
rg -n -C 4 'closeMobileSessionTab\(' . --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' || trueRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Capture/Assert graph implementation:\n'
rg -n -C 6 'captureReadyGraphEpoch|assertGraphReady|assertStableReadyGraph|graphStatus' src/main/runtime/orca-runtime.ts src/shared src/main | head -n 260
printf '\nAll closeMobileSessionTab method/property references:\n'
rg -n -C 4 'closeMobileSessionTab(?!\w)|refuseUnattributedMobileSessionTabClose\(' . --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' | head -n 240
printf '\nDiff summary:\n'
git diff --stat HEAD~1..HEAD 2>/dev/null || git diff --stat
printf '\nDiff for close functions context:\n'
git diff -- src/main/runtime/orca-runtime.ts | rg -n -C 8 'closeMobileSessionTab|refuseUnattributedMobileSessionTabClose|captureReadyGraphEpoch|clientNavigationId' || true
printf '\nStatic probe from source text only:\n'
python3 - <<'PY'
from pathlib import Path
p=Path('src/main/runtime/orca-runtime.ts')
s=p.read_text()
for needle in ['closeMobileSessionTab(', 'refuseUnattributedMobileSessionTabClose(', 'captureReadyGraphEpoch()', 'assertGraphReady()', 'assertStableReadyGraph(', 'options.clientNavigationId ? this.captureReadyGraphEpoch()']:
idx = s.find(needle)
print(f"{needle}: {idx}")
print('clientNavigationId in closeMobileSessionTab options:', '`#38`' in s[80285:80305])
print('captureReadyGraphEpoch before headless hydration in closeMobileSessionTab:', '`#42`' in s[80370:80388])
PY
printf '\nInspect graph status state definitions/usages:\n'
rg -n -C 4 '\bgraphStatus\b|graphStatus.*ready|unavailable|RuntimeGraphStatus|graphStatus' src/shared src/main runtime --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' | head -n 240Repository: stablyai/orca
Length of output: 19960
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Method definitions:\n'
rg -n 'async (?:(?:closeMobileSessionTab|refuseUnattributedMobileSessionTabClose)\s*\()' src/main/runtime/orca-runtime.ts src/main src/shared tests --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**'
printf '\nCapturing implementation:\n'
rg -n -C 8 'captureReadyGraphEpoch|assertGraphReady|assertStableReadyGraph' src/main/runtime/orca-runtime.ts
printf '\nMethod bodies around closeMobileSessionTab and refuseUnattributedMobileSessionTabClose:\n'
sed -n '7306,7328p' src/main/runtime/orca-runtime.ts | cat -n
sed -n '7331,7348p' src/main/runtime/orca-runtime.ts | cat -n
printf '\nAll closeMobileSessionTab references with pcre2:\n'
rg --pcre2 -n -C 4 'closeMobileSessionTab(?!\w)|refuseUnattributedMobileSessionTabClose\(' . --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**'
printf '\nCall graph via static TS references to RuntimeGraphStatus and graphReady assertion:\n'
rg -n -C 4 'captureReadyGraphEpoch\(\)|assertStableReadyGraph|assertGraphReady\(' src/main/runtime/orca-runtime.tsRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Session tab close RPC methods:\n'
sed -n '1,110p' src/main/runtime/rpc/methods/session-tab-close-methods.ts | cat -n
printf '\nType definitions for close methods params/options:\n'
rg -n -C 8 'RuntimeSessionTab.Close|session-tabs.close|sessionTabClose|clientNavigationId|RuntimeMobileSessionTabCloseOptions|RuntimeMobileSessionTabCloseResult|requiresIntent' src/shared src/main/runtime/rpc src/main/runtime src/main --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' | head -n 260
printf '\nClient side usage of close methods/options:\n'
rg -n -C 6 'session-tabs.close|closeMobileSessionTab|clientNavigationId|requiresIntent|useRuntime|invoke.*close|runtime\.close' src --glob '*.ts' --glob '*.tsx' | head -n 260
printf '\nFull closeMobileSessionTab tail:\n'
sed -n '7331,7560p' src/main/runtime/orca-runtime.ts | cat -nRepository: stablyai/orca
Length of output: 50372
Gate captureReadyGraphEpoch() on renderer availability.
Paired session.tabs.close and session.tabs.closeLifecycle pass clientNavigationId, so headless hosts with graphStatus === 'unavailable' reject captureReadyGraphEpoch() before reaching headless close handling. Use the same available-window check as the renderer throttle branch, or skip the epochs for headless paired closes.
🛡️ Proposed gate on renderer availability
- const graphEpoch = options.clientNavigationId ? this.captureReadyGraphEpoch() : null
+ // Why: only a renderer-backed close can be invalidated by a graph epoch change.
+ const graphEpoch =
+ options.clientNavigationId && this.getAvailableAuthoritativeWindow()
+ ? this.captureReadyGraphEpoch()
+ : null📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| clientNavigationId?: string | |
| } = {} | |
| ): Promise<RuntimeMobileSessionTabCloseResult> { | |
| const graphEpoch = options.clientNavigationId ? this.captureReadyGraphEpoch() : null | |
| const explicitWorktreeId = this.getValidatedExplicitWorktreeIdSelector(worktreeSelector) | |
| const worktreeId = | |
| explicitWorktreeId ?? (await this.resolveWorktreeSelector(worktreeSelector)).id | |
| this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) | |
| const observedPtyIds = await this.refreshMobileSessionPtyRecords() | |
| if (graphEpoch !== null) { | |
| this.assertStableReadyGraph(graphEpoch) | |
| } | |
| this.restoreLivePairedRendererSessionOwnedMobileTerminals(worktreeId) | |
| clientNavigationId?: string | |
| } = {} | |
| ): Promise<RuntimeMobileSessionTabCloseResult> { | |
| // Why: only a renderer-backed close can be invalidated by a graph epoch change. | |
| const graphEpoch = | |
| options.clientNavigationId && this.getAvailableAuthoritativeWindow() | |
| ? this.captureReadyGraphEpoch() | |
| : null | |
| const explicitWorktreeId = this.getValidatedExplicitWorktreeIdSelector(worktreeSelector) | |
| const worktreeId = | |
| explicitWorktreeId ?? (await this.resolveWorktreeSelector(worktreeSelector)).id | |
| this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) | |
| const observedPtyIds = await this.refreshMobileSessionPtyRecords() | |
| if (graphEpoch !== null) { | |
| this.assertStableReadyGraph(graphEpoch) | |
| } | |
| this.restoreLivePairedRendererSessionOwnedMobileTerminals(worktreeId) |
…stablyai#11581) * fix(remote): unthrottle host renderer while serving a paired client A paired desktop host left in the background could not open or close agent sessions for its remote/relay client: the action stalled and eventually failed with the host-side "Timed out waiting for terminal surface after creation" (10s) error, while an already-live terminal's keystrokes stayed fast. Root cause: creating/closing a session routes through the host renderer's setTimeout-coalesced graph sync to publish the terminal surface, but the host window runs with Electron background throttling (the hidden-window default, reaffirmed on macOS). When the window is backgrounded/occluded, those renderer timers are throttled to a crawl and the surface publication misses the 10s deadline. Live keystrokes are unaffected because PTY I/O flows through the main process, never the renderer. Keep the authoritative renderer unthrottled while at least one remote client is connected and restore the throttled power-saving default once the last one disconnects. Connect/disconnect are driven from the shared MobileSocketWiring onReady/onClose, so both direct-WS and cloud-relay clients are covered; headless serve has no window and is a safe no-op. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(remote): tidy renderer-throttle comment and test per review Address automated review nits on stablyai#11581: - Trim the module-level rationale comment to the non-obvious contract, matching the repo's concise-comment guideline. - Drop the dead `detachedThrottle` variable from the reapply test; the detached-target scenario is already covered by the lazy-resolution test, so the case now asserts only what it exercises. No behavior change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(remote): scope paired terminal publication throttling Keep headed paired terminal creation and close renderer-owned so host inventory, input routing, ACK recovery, and cleanup retain the established lifecycle. Hold a reference-counted background-throttle lease only while the renderer publishes a paired operation, and epoch-fence async resolution so renderer reloads reject before any request or PTY spawn. Preserve headless main ownership and prevent paired clients from falling back to a local terminal. * test(e2e): verify minimized host terminal repaint * fix(remote): preserve paired terminal inventory through graph gaps --------- Co-authored-by: fanyunqian.1 <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: OrcaWin <[email protected]>
Summary
A paired desktop client could time out opening or closing a terminal when the host Electron window was genuinely minimized or occluded. Live terminal I/O stayed responsive because PTY traffic is main-process owned, while create/close completion still waits for renderer-owned workspace and terminal publication.
The final fix keeps renderer ownership and acquires a main-process
RendererPublicationThrottlelease only for authenticated paired create and whole-tab close transactions. The lease temporarily callssetBackgroundThrottling(false)and always restorestruewhen the operation settles. It is not disabled for the lifetime of a client connection.Renderer authority remains explicit:
Testing
truebefore and after each operation.No UI change.
Security, performance, and platform audit
Authentication remains at the existing paired RPC boundary; no new command, path, secret, dependency, or client-controlled IPC surface was added. Operation leases and paired PTY tracking are bounded and cleaned up on all lifecycle exits. Idle connected clients keep Electron's normal power-saving behavior; only the short publication transaction is unthrottled.
The real headed evidence is macOS. The implementation uses Electron's cross-platform API and contains no new platform-specific path, but native Windows and WSL are not claimed.