Repository navigation
Keep terminals created from Orca Mobile alive when the desktop renderer is throttled or stalled - #7664
Conversation
…its snapshot publications A terminal created from a paired mobile/web client waited up to 10s for the renderer's graph-sync publication to surface the new tab; when the renderer was throttled or busy past that window, the timeout rollback destroyed the live agent session (history deleted, live id unregistered). Publish the tab surface main-side from the renderer's own PTY spawn, scoped to in-flight mobile creates, and keep the destructive rollback only for true spawn failure. Co-authored-by: Orca <[email protected]>
📝 WalkthroughWalkthroughThis PR threads a stable pane identity ( Changes
Sequence Diagram(s)See hidden review stack artifact for the mobile terminal create rescue flow diagram. Related Issues: Estimated code review effort: High Suggested labels: bug, area:terminal, area:mobile Suggested reviewers: (none specified) 🐰 A pane once lost in a timing race, 🚥 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.
🧹 Nitpick comments (2)
src/main/ipc/pty.ts (1)
2304-2318: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse the already-computed
metadataLeafIdinstead of re-deriving the leaf-id check.
metadataLeafId(typeof args.leafId === 'string' && isTerminalLeafId(args.leafId) ? args.leafId : null) is already computed a few lines above in this samespawnclosure (used formetadataPaneKey/spawnIdentityPaneKey). ThisregisterPtycall re-derives the identicaltypeof args.leafId === 'string' && isTerminalLeafId(args.leafId)predicate inline instead of reusing it — the sibling call site at Line 3197-3211 correctly reuses its precomputedmetadataLeafId. Keeping two copies of the same validation risks silent drift if the leaf-id validation rule ever changes in only one place.♻️ Proposed fix to reuse `metadataLeafId`
if (args.worktreeId) { runtime?.registerPty( result.id, args.worktreeId, args.connectionId ?? null, // Why: thread the validated pane identity so main can back a pending // mobile create from this live spawn even if graph-sync stalls (`#7587`). // Bound tabId like the sibling metadataPaneKey/spawnOptions.tabId here. typeof args.tabId === 'string' && isValidTerminalTabId(args.tabId) && args.tabId.length <= 512 && - typeof args.leafId === 'string' && - isTerminalLeafId(args.leafId) - ? { tabId: args.tabId, leafId: args.leafId } + metadataLeafId !== null + ? { tabId: args.tabId, leafId: metadataLeafId } : undefined ) }src/main/runtime/orca-runtime.test.ts (1)
18054-18413: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the repeated notifier mock into a shared helper.
All five new tests in this block construct an identical 13-field
runtime.setNotifier({...})object (only thecloseTerminalvariable differs), e.g. Lines 17977-17991, 18060-18074, 18134-18148, 18207-18221, 18328-18342. A smallcreateMockNotifier(closeTerminal = vi.fn())factory would remove ~65 duplicated lines and keep future notifier-interface changes to one place.♻️ Proposed helper
function createMockNotifier(closeTerminal = vi.fn()) { return { focusTerminal: vi.fn(), worktreesChanged: vi.fn(), reposChanged: vi.fn(), activateWorktree: vi.fn(), createTerminal: vi.fn(), revealTerminalSession: vi.fn(), splitTerminal: vi.fn(), renameTerminal: vi.fn(), closeTerminal, closeSessionTab: vi.fn(), sleepWorktree: vi.fn(), terminalFitOverrideChanged: vi.fn(), terminalDriverChanged: vi.fn() } }Then each test becomes
runtime.setNotifier(createMockNotifier(closeTerminal)).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: aa0c709b-eacc-4474-86f5-aa67ac324499
📒 Files selected for processing (4)
src/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.ts
… site and dedupe the mobile-create test notifier Co-authored-by: Orca <[email protected]>
…er is throttled or stalled (stablyai#7664) Co-authored-by: Orca <[email protected]>
Fixes #7587.
What changes
Creating a terminal from Orca Mobile (or any paired remote client) no longer destroys the just-spawned agent session when the desktop renderer's snapshot publications are delayed. Previously,
runCreateMobileSessionTerminalwaited up to 10s for the new tab to appear inmobileSessionTabsByWorktree— a map fed only by renderer graph-sync publications on this path — and on timeout rolled the tab back through the destructive close path (pty:killwithkeepHistory: false), deleting the session'sterminal-history/folder and unregistering its Claude live-session id. A hidden/occluded desktop window (Chromium background timer throttling; Orca keeps Electron's defaultbackgroundThrottling) or a busy renderer can park the 16ms publication coalescer past 10s, so every mobile create spawned a real agent session and reaped it ~10s later — exactly the reported behavior.Now the runtime publishes the tab surface main-side from the renderer's own PTY spawn (the
pty:spawnIPC already carries validatedtabId/leafId), scoped strictly to creates that are actively waiting: a pending-create registry keyed by(worktreeId, tabId)is checked when the renderer PTY registers, immediately after the tab-create reply, and as a last chance at timeout. The publish reusespublishPtyBackedMobileSessionTerminal— the same mechanism runtime-spawned terminals already use — and drainsgraphSyncCallbacksso the pending wait resolves promptly instead of after 10s.What does not change
Timed out waiting for terminal surface after creationerror. The timeout rescue is explicitly gated on a live PTY so a handle-less tab shell can never resolve as success.backgroundThrottlingchanges.touchMobileSessionSnapshotsForPtyare untouched;#7400(stale mobile snapshot contents) is adjacent but separate and not addressed here.Root cause and reproduction
Reproduced live before the fix on macOS HEAD with a paired physical iPhone driving the real
session.tabs.createTerminalRPC over the app's E2EE channel: with renderer graph-sync publications stalled (via the renderer module's ownsetRuntimeGraphSyncEnabled(false)kill switch — a faithful stand-in for a parked/throttled sync timer), the create failed at 10,566ms with the exact reported error, the Claude PTY'sterminal-history/folder was deleted, and its live id was unregistered. With publications flowing, 7/7 creates succeeded — including under agent title-churn storms and with the desktop focused on a different worktree. Both trigger variants (publication stall, and the freshness-guard version rejection hypothesized in the issue) collapse to the same dependency this PR removes.Process summary (Brennan's PR process)
src/main/runtime/orca-runtime.ts(extendedregisterPtybinding, pending-create registry,ensurePtyBackedMobileSurfaceForRendererTabhelper wired at three race sites, live-PTY-gated rescue before the rollback in the timeout catch),src/main/ipc/pty.ts(bothregisterPtycall sites pass the validated, length-boundedtabId/leafIdbinding), plus regression tests inorca-runtime.test.tsandpty.test.ts. One deviation from the design doc: the two pty.ts call-site roles were labeled in reverse; the binding applies at both, no behavior difference.registerPtybackward compatible at all call sites; exited PTYs not treated as live; mobile client contract satisfied withstatus: 'ready'+term_handle). When no prior snapshot exists the rescue publishes under aheadless:pty-backed:epoch that the merge logic actively preserves.connectionId) are unchanged.Reliability regression gate
Touched P0-capable classes: tab creation/binding, mobile/remote provider contract, PTY identity (read-only consumption of existing spawn args). Eight new deterministic tests:
#7400-style trigger, with the guard rejection asserted directly on the stored snapshot before the rescue.6.-8. IPC seam tests: both
registerPtycall sites thread the validated binding; a non-UUID leaf id yields no binding.Existing rollback and pending-surface materialization tests remain green and meaningful.
Risks and non-goals
targetGroupIdnot threaded); the renderer's reconciling publication corrects both. Stall-window-only, cosmetic.tabId/paneKeyat spawn (previously set on first data/graph-sync): (a) the agent-status pty-record fallback now attributes bound-but-leafless PTYs under the samepaneKeythe mounted leaf later uses (per status transition, stall-window only); (b)findPtyForMobileTerminalTab's worktree-only fallback no longer matches freshly-bound PTYs — stricter, more correct identity matching. CLI/headless spawns carry no tab identity, so their loose-match escape hatch is unchanged.#7400freshness-guard semantics,backgroundThrottling, mobile app changes.Perf audit
NO-REGRESSION. PTY-spawn hot path adds O(1) guards + one Map miss per spawn (startup bulk-restore unaffected; the pending registry is empty). The O(n) PTY scan is gated behind the pending-create registry check and runs only for in-flight mobile creates. The
graphSyncCallbacksdrain fires only when the helper actually publishes; callbacks are read-only self-removing closures (no re-entrancy). No new timers, polling, subscriptions, IPC, or storage writes; renderer process and startup untouched.Validation
pnpm tc(node/cli/web) — pass, re-run after every fix wave.pnpm vitest run … pty.test.ts orca-runtime.test.ts rpc/methods/session-tabs.test.ts— 796/796 pass (re-run independently by the lead; new tests re-run 3× with zero flake).oxlinton changed files — clean.Timed out waiting for terminal surface after creation; the session's history folder was deleted and its live id unregistered (file watcher captured the reap).session.tabs.createTerminal {agent:'claude'}resolved in 553ms withstatus:'ready'and aterm_handle; the session survived 45s+ with live id and history folder intact; the mobile UI showed the new Claude Code tab streaming the live session.Post-PR stabilization
verifyandtrack-community-prchecks pass (re-run green after the follow-up commit). CodeRabbit raised two trivial maintainability nitpicks (reuse the in-scopemetadataLeafIdat the controller spawn site; dedupe the repeated notifier mock in the new tests) — both applied infa7e9144c, re-validated (typecheck + 796/796 tests), no inline or actionable comments remain.Regression & back-compat review (independent)
Independent post-implementation review — fresh read of the diff plus three parallel verification sweeps (mobile RPC / group-placement, a full audit of every
tabId/paneKeyreader, and a tests + typecheck run). Verdict: no regressions found, backwards-compatible — safe to ship.Back-compat — safe. The entire diff is 4 files, all in
src/main/(desktop main process):ipc/pty.ts,runtime/orca-runtime.ts, and their tests. No changes tomobile/,shared/, RPC contracts, persisted schemas, or IPC message shapes. The newregisterPty4th argument is optional and internal to main, and the renderer→mainpty:spawnIPC already carriedtabId/leafId. Cross-version matrix: old mobile ↔ new desktop simply stops reaping the tab (a strict improvement — verified that all three mobilesession.tabs.createTerminalcall sites send unchanged params); new desktop ↔ old mobile is identical; there are no mobile-side changes, so new-mobile ↔ old-desktop is N/A. BothregisterPtycall sites also cover SSH/reattach terminals, which benefit most since slower spawns are more stall-prone.Correctness — no regressions. All 15 readers of
pty.tabId/pty.paneKeywere audited: the value written at spawn (makePaneKey(tabId, leafId)) is byte-identical to what graph-sync writes a few ms later; every reader either benefits from earlier population or keys onconnected/worktreeIdand is unaffected; and thetabId === null && paneKey === nullworktree-only adoption branch stays safe because the fix never populates identity for the daemon/restored PTYs that branch targets. The pty-backed surface resolves asstatus: 'ready'precisely because the recordedtabId/paneKeyis whatmobileTerminalTabMatchesPtyneeds to locate the live PTY whilethis.leavesis unsynced. Reconciliation reuses the provenpublishPtyBackedMobileSessionTerminal+syncMobileSessionTabsdedup path (no tab duplication); the helper is idempotent, scoped to in-flight creates, cleaned up infinally, and drains a copy ofgraphSyncCallbacks(re-entrancy-safe). Group-flash is a non-issue for mobile (never sendstargetGroupId) and is cosmetic + stall-window-only for the desktop-paired web client, which also passesactivate: true.Performance — neutral-to-positive. Healthy creates can resolve faster (main-side publish vs. waiting on the throttled graph-sync timer). Per-spawn cost is one O(1)
Map.getthat early-returns when no create is pending; the O(n) PTY scan runs only on the in-flight mobile-create path. No hot-path impact, no new timers/polling/IPC.Tests — green. 781 targeted tests pass; node-scoped typecheck (
typecheck:node, covers both changed files) is clean. Rescue paths, true-failure rollback, and theregisterPtybinding-validation bounds are all covered. One optional gap: no direct negative assertion that an ordinary renderer spawn with no in-flight create refrains from publishing (enforced in source by the pending-create registry scoping).