Skip to content

Keep terminals created from Orca Mobile alive when the desktop renderer is throttled or stalled - #7664

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/7587
Jul 7, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/7587

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

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, runCreateMobileSessionTerminal waited up to 10s for the new tab to appear in mobileSessionTabsByWorktree — 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:kill with keepHistory: false), deleting the session's terminal-history/ folder and unregistering its Claude live-session id. A hidden/occluded desktop window (Chromium background timer throttling; Orca keeps Electron's default backgroundThrottling) 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:spawn IPC already carries validated tabId/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 reuses publishPtyBackedMobileSessionTerminal — the same mechanism runtime-spawned terminals already use — and drains graphSyncCallbacks so the pending wait resolves promptly instead of after 10s.

What does not change

  • True spawn failure (no live PTY for the created tab) still rolls back exactly as before, including the Timed out waiting for terminal surface after creation error. The timeout rescue is explicitly gated on a live PTY so a handle-less tab shell can never resolve as success.
  • Ordinary desktop tab creation never triggers main-side publication — the pending-create registry scoping means renderer snapshots remain authoritative for renderer tabs.
  • No RPC contract, mobile app, timeout value, or backgroundThrottling changes.
  • The mobile-snapshot freshness guard and touchMobileSessionSnapshotsForPty are 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.createTerminal RPC over the app's E2EE channel: with renderer graph-sync publications stalled (via the renderer module's own setRuntimeGraphSyncEnabled(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's terminal-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)

  • Design: scratch design doc reviewed by the session lead (the full design-review loop was explicitly skipped at Brennan's instruction). Fix direction: remove the create path's dependency on renderer publication timing (root cause), mirroring the existing runtime-spawned-terminal mechanism rather than tuning timeouts or disabling throttling.
  • Implementation: four files — src/main/runtime/orca-runtime.ts (extended registerPty binding, pending-create registry, ensurePtyBackedMobileSurfaceForRendererTab helper wired at three race sites, live-PTY-gated rescue before the rollback in the timeout catch), src/main/ipc/pty.ts (both registerPty call sites pass the validated, length-bounded tabId/leafId binding), plus regression tests in orca-runtime.test.ts and pty.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.
  • Completeness verification: COMPLETE — all six audit items PASS (three rescue sites traced end-to-end; registry cleaned on every exit path; rollback preserved for the no-live-PTY case; registerPty backward compatible at all call sites; exited PTYs not treated as live; mobile client contract satisfied with status: 'ready' + term_ handle). When no prior snapshot exists the rescue publishes under a headless:pty-backed: epoch that the merge logic actively preserves.
  • Headline behavior status: implemented — the full pipeline (mobile + → RPC → renderer tab create → PTY spawn → surface published → tab visible and persistent on mobile) survives a stalled renderer; no scope narrowing.
  • Broad app consistency: the mobile/web remote create path now matches the runtime-spawned-terminal path (main-side pty-backed publication at spawn). Desktop tab creation, headless/serve mode, and SSH-connected worktrees (binding travels through the same spawn args; PTY records keep connectionId) are unchanged.
  • Code review: 4-round review/fix loop (two fresh parallel reviewers per round). One Medium correctness finding caught and fixed (the timeout rescue could have returned a dead handle-less shell surface as success — now gated on a live PTY, with a dedicated gate-lock test), plus test-coverage and input-bounding Lows. A final confirmation round with two fresh parallel reviewers returned CLEAN / CLEAN.

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:

  1. "keeps a mobile-created terminal alive when the renderer never publishes the surface" — the core regression lock; hangs on pre-fix code, resolves in ~50ms fake time with the fix.
  2. "…when the renderer PTY spawn races ahead of the reply" — pins the immediate pre-wait check.
  3. "…when the renderer snapshot is rejected by the version guard" — the issue reporter's hypothesized #7400-style trigger, with the guard rejection asserted directly on the stored snapshot before the rescue.
  4. "…at the surface timeout when only a leaf-synced PTY backs the tab" — pins the catch-path last-chance rescue.
  5. "rolls back a mobile create when the materialize spawn fails and no live PTY backs the tab" — gate-lock proving the rescue cannot resolve a handle-less shell as success.
    6.-8. IPC seam tests: both registerPty call 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

  • Transient cosmetic window: if a stale in-flight renderer snapshot (ms-wide window; snapshots build from current store state, so none are queued) lands after the main-side publish under a renderer epoch, the pty-backed tab can briefly disappear from the mobile snapshot until the renderer's next publication. No reconciliation path closes the PTY or deletes history — verified. Strictly better than the pre-fix behavior (session destroyed).
  • A stalled SPLIT create publishes a flat (non-split) surface, and the rescue publishes into the active group (targetGroupId not threaded); the renderer's reconciling publication corrects both. Stall-window-only, cosmetic.
  • Two bounded, intentional behavior deltas from populating tabId/paneKey at spawn (previously set on first data/graph-sync): (a) the agent-status pty-record fallback now attributes bound-but-leafless PTYs under the same paneKey the 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.
  • Non-goals: #7400 freshness-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 graphSyncCallbacks drain 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).
  • oxlint on changed files — clean.
  • Live end-to-end validation (before/after on the same rig): dev desktop paired with a real Orca Mobile client over the app's own pairing deep-link + E2EE channel; renderer publications force-stalled via the module kill switch.
    • Pre-fix: create failed at 10,566ms with 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).
    • Post-fix, same stalled condition: session.tabs.createTerminal {agent:'claude'} resolved in 553ms with status:'ready' and a term_ 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.
    • Reconciliation: after re-enabling publications, the desktop adopted the same tab in its tab strip with the phone-control overlay attributing input to the mobile client.
    • Healthy-path control: create with publications flowing resolved in 337ms.
    • Supplementary independent QA (real mobile UI tap-through on an iOS Simulator): + → Terminal from the mobile session screen produced a persistent tab well past the old ~10s reap window.

Post-PR stabilization

verify and track-community-pr checks pass (re-run green after the follow-up commit). CodeRabbit raised two trivial maintainability nitpicks (reuse the in-scope metadataLeafId at the controller spawn site; dedupe the repeated notifier mock in the new tests) — both applied in fa7e9144c, 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/paneKey reader, 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 to mobile/, shared/, RPC contracts, persisted schemas, or IPC message shapes. The new registerPty 4th argument is optional and internal to main, and the renderer→main pty:spawn IPC already carried tabId/leafId. Cross-version matrix: old mobile ↔ new desktop simply stops reaping the tab (a strict improvement — verified that all three mobile session.tabs.createTerminal call sites send unchanged params); new desktop ↔ old mobile is identical; there are no mobile-side changes, so new-mobile ↔ old-desktop is N/A. Both registerPty call 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.paneKey were 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 on connected/worktreeId and is unaffected; and the tabId === null && paneKey === null worktree-only adoption branch stays safe because the fix never populates identity for the daemon/restored PTYs that branch targets. The pty-backed surface resolves as status: 'ready' precisely because the recorded tabId/paneKey is what mobileTerminalTabMatchesPty needs to locate the live PTY while this.leaves is unsynced. Reconciliation reuses the proven publishPtyBackedMobileSessionTerminal + syncMobileSessionTabs dedup path (no tab duplication); the helper is idempotent, scoped to in-flight creates, cleaned up in finally, and drains a copy of graphSyncCallbacks (re-entrancy-safe). Group-flash is a non-issue for mobile (never sends targetGroupId) and is cosmetic + stall-window-only for the desktop-paired web client, which also passes activate: 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.get that 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 the registerPty binding-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).

…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]>
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR threads a stable pane identity (tabId/leafId) into registerPty calls in both runtime-controller and renderer PTY spawn paths. orca-runtime.ts now accepts an optional binding and records pane metadata for mobile terminal creates, while the mobile create flow registers pending creates, attempts early PTY-backed publication, and falls back to rescue or closeTerminal on failure. Tests were added for pane identity propagation and mobile create timing and timeout cases.

Changes

Area Changes
PTY spawn (src/main/ipc/pty.ts) Two registerPty call sites now pass a validated { tabId, leafId } binding derived from IPC inputs.
Runtime core (src/main/runtime/orca-runtime.ts) registerPty signature extended with optional binding; adds pendingMobileTerminalCreatesByKey; mobile terminal create flow updated with proactive publish and rescue/rollback logic; two new private helpers added.
Tests New tests in pty.test.ts and orca-runtime.test.ts covering pane identity propagation and mobile terminal create rescue/rollback scenarios.

Sequence Diagram(s)

See hidden review stack artifact for the mobile terminal create rescue flow diagram.

Related Issues: #7587

Estimated code review effort: High

Suggested labels: bug, area:terminal, area:mobile

Suggested reviewers: (none specified)

🐰 A pane once lost in a timing race,
Now tags its tabId, leaf, and place —
When surfaces stall or PTYs delay,
Rescue steps in to save the day,
Or gently closes without a trace.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main user-visible change: keeping mobile-created terminals alive during renderer stalls.
Description check ✅ Passed The description is detailed and covers summary, testing, risks, and validation, though it does not follow the template headings exactly.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/main/ipc/pty.ts (1)

2304-2318: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse the already-computed metadataLeafId instead 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 same spawn closure (used for metadataPaneKey/spawnIdentityPaneKey). This registerPty call re-derives the identical typeof args.leafId === 'string' && isTerminalLeafId(args.leafId) predicate inline instead of reusing it — the sibling call site at Line 3197-3211 correctly reuses its precomputed metadataLeafId. 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 win

Extract the repeated notifier mock into a shared helper.

All five new tests in this block construct an identical 13-field runtime.setNotifier({...}) object (only the closeTerminal variable differs), e.g. Lines 17977-17991, 18060-18074, 18134-18148, 18207-18221, 18328-18342. A small createMockNotifier(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

📥 Commits

Reviewing files that changed from the base of the PR and between aa0993f and a601dbd.

📒 Files selected for processing (4)
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

… site and dedupe the mobile-create test notifier

Co-authored-by: Orca <[email protected]>
@brennanb2025
brennanb2025 merged commit ee64050 into main Jul 7, 2026
1 check passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Creating a Claude tab from mobile spawns it on the desktop, then reaps it ~10s later — mobile tab creation broken

1 participant