Skip to content

fix(mobile): stop a mobile reveal from minting a duplicate terminal tab - #11259

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/mobile-10486-dup-tab
Jul 29, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/mobile-10486-dup-tab

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Fixes #10486 — viewing a live host terminal from a paired phone no longer opens a second desktop tab showing the same session.

OrcaRuntime.focusTerminal reveals the PTY with the tab id baked into its env (ORCA_TAB_ID / ORCA_PANE_KEY), and the create-terminal handler in useIpcEvents is supposed to adopt the tab that already owns it. Ownership was only checked against tab.ptyId and the live ptyIdsByTabId map. When the worktree isn't open on the desktop no pane is mounted, so ptyIdsByTabId is empty and tab.ptyId holds at most one leaf's PTY — a split pane's second PTY lives only in the persisted terminalLayoutsByTabId row. Ownership missed, and createTab ran with an id that already existed; it mints a fresh uuid on collision, so a second tab appeared on the same session.

The issue as filed (a single-pane Codex terminal) was never broken — a single-pane tab matches on tab.ptyId. The reachable defect is the split-pane / partially-hydrated variant.

Changes

resolveTerminalTabPtyOwnership resolves a PTY through three bindings and ranks them:

  1. mounted — ptyIdsByTabId — a pane that is actually running it
  2. recorded — tab.ptyId or a persisted layout row
  3. the reveal's tabId hint, used only when nothing records the PTY, and as the tie-break when several do

Every binding is an exact match on the ptyId, so all of them outrank the hint. The hint is not a binding: main's pty.tabId comes from persistPtyBinding (written once at spawn, never rewritten) or from a graph sync off already-mounted leaves — so it is always a snapshot of a past renderer state and can never be fresher than the renderer's own records. It goes stale as soon as a pane is dragged to another tab. Same-tier conflicts stay ambiguous, so planMobileTerminalTabMount keeps failing closed exactly as #8597 intended.

onCreateTerminal adopts through that resolver and never throws on ambiguity — focusTerminal awaits revealTerminalSession with no catch, so a throw would surface on the phone. hintedPendingTab is gone: the hint fallback subsumes it, and its "adopt only if the hinted tab has no PTY at all" guard was what blocked the split-pane case.

Two costs worth naming rather than implying:

  • On the reveal path, "fail closed" on ambiguity means minting a tab — i.e. reproducing this bug. That's the right trade against adopting the wrong tab decisively, but it isn't free.
  • A layout row that outlived its pane, in a tab whose own layout is partially hydrated, would now be adopted where main minted a duplicate. I could not construct a producer for that state (detachTerminalLayoutLeaf prunes the source row, setTabLayout rewrites the whole snapshot, and ptyIds are uuid-suffixed so they can't be reused).

Out of scope, pre-existing: when the adopted tab's layout lacks the revealed leafId, the handler replaces the layout with a single-pane snapshot. That predates this PR and this change makes it strictly less reachable, not more — the new "leaves the hinted tab split intact" test is RED on main, which does collapse that tab.

Test plan

  • New mobile-terminal-reveal-tab-adoption.test.ts drives the real onCreateTerminal handler through a new ipc-events-test-harness.ts.
  • Anti-vacuity, measured both ways. Reverting only useIpcEvents.ts turns 6 of the 7 hook tests RED. Per-tier mutation audit over the three test files (baseline 30): hint fallback → 2 RED, layout-row tier → 11, mounted-pane tier → 6, tab.ptyId tier → 8, hint tie-break → 2. No branch is deletable with the suite green.
  • The two pre-existing tests I initially edited are back on their original names, fixtures and toBeNull() expectations, with separate positive cases added.
  • Gates: full root vitest suite at --maxWorkers=2, oxlint, oxfmt --check, tsc --noEmit (all three projects).

Reviewed adversarially over three rounds; the first two rounds found real defects in earlier revisions of this ordering, both fixed here.

Not verified live. Reproducing end-to-end needs a paired phone focusing a split pane in a worktree closed on the desktop; I validated at the IPC-handler level instead.

Supersedes #10556, which resolved ownership but let a stale layout row outrank a live binding, threw a user-visible "Ambiguous terminal tab ownership" on the un-caught mobile focus path, and had no coverage of its own useIpcEvents change.

ELI5

Your phone asked the desktop to show a terminal that was already open. The desktop couldn't tell which tab it belonged to, so it made a new one. Now it checks every place that records where a session lives, and trusts those over the label the session was born with — because that label goes stale if you drag the pane somewhere else.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3c4e9e84-feb8-435a-811d-e3b4c3da7a44

📥 Commits

Reviewing files that changed from the base of the PR and between 06b0d32d0a034c7fd27c7abf232d2bc271e60e66 and bf33f56.

📒 Files selected for processing (7)
  • src/renderer/src/hooks/ipc-events-test-harness.ts
  • src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/mobile-terminal-tab-mount.test.ts
  • src/renderer/src/lib/mobile-terminal-tab-mount.ts
  • src/renderer/src/lib/terminal-tab-for-pty-id.test.ts
  • src/renderer/src/lib/terminal-tab-for-pty-id.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/renderer/src/lib/mobile-terminal-tab-mount.test.ts
  • src/renderer/src/lib/terminal-tab-for-pty-id.test.ts
  • src/renderer/src/hooks/ipc-events-test-harness.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts

📝 Walkthrough

Walkthrough

The changes add shared PTY-to-tab ownership models and resolution logic covering mounted bindings, persisted layouts, hints, and ambiguity. Mobile tab mounting now consumes the shared ownership state. IPC terminal creation uses the resolver for tab reuse and split reveals. A reusable IPC-events test harness and tests cover mobile reveal adoption, stale layouts, missing hydration, conflicting hints, and ambiguous ownership.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary and testing, but it omits required template sections like Screenshots, AI Review Report, Security Audit, and Notes. Add the missing template sections, including screenshots or 'No visual change', AI review report, security audit, and notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% 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 accurately describes the main fix: preventing mobile reveals from creating duplicate terminal tabs.
Linked Issues check ✅ Passed The changes address #10486 by resolving terminal ownership before create-terminal can mint a duplicate tab, with tests covering the reported split-pane cases.
Out of Scope Changes check ✅ Passed The new resolver and test harness code are directly tied to fixing mobile terminal reveal ownership and do not introduce clear unrelated changes.
✨ 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.

🧹 Nitpick comments (1)
src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts (1)

10-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

revealSplitPaneFromMobile never triggers the split-reveal branch.

isSplitReveal in useIpcEvents.ts (Line 1429) requires ptyId && tabId && leafId && splitFromLeafId. This helper omits splitFromLeafId, so every test using it takes the non-split path. The reordered existingTab ?? splitTargetTab precedence and the "tab not found" throw at Lines 1433-1436 — the riskiest part of this diff — are unexercised despite the test names referencing split panes.

Consider adding splitFromLeafId: 'leaf-a' to one case (or a dedicated test) so the split path is covered.

♻️ Add a split-reveal case
     leafId?: string
+    splitFromLeafId?: string
     presentation?: 'background' | 'focused'
     title?: string
   }) => void

Then a dedicated test asserting the owning tab is reused and addSplitLeafToLayout is applied to it rather than to the hinted tab.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d320648f-d6ed-4fb2-a40e-bf19032705b5

📥 Commits

Reviewing files that changed from the base of the PR and between c8dba6d and 06b0d32d0a034c7fd27c7abf232d2bc271e60e66.

📒 Files selected for processing (7)
  • src/renderer/src/hooks/ipc-events-test-harness.ts
  • src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/mobile-terminal-tab-mount.test.ts
  • src/renderer/src/lib/mobile-terminal-tab-mount.ts
  • src/renderer/src/lib/terminal-tab-for-pty-id.test.ts
  • src/renderer/src/lib/terminal-tab-for-pty-id.ts

@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a duplicate terminal tab bug (#10486) where a mobile reveal of a split pane that has a second PTY recorded only in the persisted layout (not yet mounted) caused onCreateTerminal to miss ownership and call createTab against an already-existing tab id, minting a duplicate. The fix replaces the old two-source ownership check with a new resolveTerminalTabPtyOwnership that consults three tiers — live ptyIdsByTabId, persisted tab.ptyId/layout rows, and the env-baked hint — in priority order.

  • resolveTerminalTabPtyOwnership in terminal-tab-for-pty-id.ts implements mounted > recorded > hint precedence, returning owned, ambiguous, or none; resolveTerminalTabIdForPtyId is refactored as a no-hint wrapper and TerminalTabPtyOwnershipState extends both consumers.
  • useIpcEvents.ts replaces the two-source existingTab + hintedPendingTab logic with a single ownership call; ambiguity now creates a new tab silently rather than throwing on the un-caught mobile focus path.
  • New ipc-events-test-harness.ts and mobile-terminal-reveal-tab-adoption.test.ts drive the hook end-to-end; mobile-terminal-tab-mount.test.ts and terminal-tab-for-pty-id.test.ts are extended with per-tier mutation coverage.

Confidence Score: 5/5

Safe to merge; the ownership resolution is narrow and well-bounded, the ambiguity path degrades gracefully to creating a new tab rather than throwing, and the test suite covers all three tiers bidirectionally.

The change is self-contained: a new pure function replaces two ad-hoc ownership checks in one handler. All three binding tiers are exercised by mutation-audited tests, the hook is tested end-to-end through the real IPC handler, and the ambiguity path that previously could have thrown on the un-caught mobile focus path now fails closed silently.

Files Needing Attention: No files require special attention; the resolver logic and its call site in useIpcEvents are fully covered by the new test suite.

Important Files Changed

Filename Overview
src/renderer/src/lib/terminal-tab-for-pty-id.ts Core ownership resolver: three-tier logic (mounted → recorded → hint) is sound; tiebreak and ambiguity paths are well-covered by unit tests.
src/renderer/src/hooks/useIpcEvents.ts Replaces two-source ownership + hintedPendingTab with resolveTerminalTabPtyOwnership; ambiguity path now creates a tab silently, preventing an unhandled throw on the mobile focus path.
src/renderer/src/lib/mobile-terminal-tab-mount.ts Signature widened to TerminalTabPtyOwnershipState (adds ptyIdsByTabId); resolveTerminalTabIdForPtyId now correctly prefers a live binding over a stale layout row for background-mount planning.
src/renderer/src/hooks/ipc-events-test-harness.ts New harness correctly stubs useEffect synchronously, injects a store proxy, and captures the createTerminal IPC listener to drive the hook at the handler boundary.
src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts Seven end-to-end scenarios covering the fixed split-pane path, stale layout vs live map precedence, hint disagreement, and ambiguity-creates-tab behavior; confirms the hook never throws.
src/renderer/src/lib/terminal-tab-for-pty-id.test.ts Extended with livePtyIds parameter and 10 new resolveTerminalTabPtyOwnership tests; covers all three tiers, tiebreak, and ambiguity; also adds a live-binding test for the existing resolveTerminalTabIdForPtyId wrapper.
src/renderer/src/lib/mobile-terminal-tab-mount.test.ts Updated state helper to include ptyIdsByTabId; adds a test that mounted-pane ownership beats a stale layout row during background-mount planning.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[onCreateTerminal IPC] --> B{ptyId present?}
    B -- No --> C[kind: none]
    B -- Yes --> D[resolveTerminalTabPtyOwnership]

    D --> E[Scan worktree tabs]
    E --> F{ptyIdsByTabId includes ptyId?}
    F -- Yes --> G[mountedOwners.push tab]
    F -- No --> H{tab.ptyId eq ptyId or layout row?}
    H -- Yes --> I[recordedOwners.push tab]
    H -- No --> E2[next tab]
    G --> E2
    I --> E2

    E2 --> K{mountedOwners length GT 0?}
    K -- Yes --> L[owners = mountedOwners]
    K -- No --> M[owners = recordedOwners]

    L --> N{owners.length}
    M --> N

    N -- equals 1 --> O[kind: owned tabId = owners0]
    N -- GT 1 --> P{preferTabId in owners?}
    P -- Yes --> Q[kind: owned tabId = preferTabId]
    P -- No --> R[kind: ambiguous]
    N -- equals 0 --> S{preferTabId exists?}
    S -- Yes --> T[kind: owned - hint fallback]
    S -- No --> C

    O --> U{ownership.kind}
    Q --> U
    R --> U
    T --> U
    C --> U

    U -- owned --> V[existingTab = tab by tabId]
    U -- ambiguous or none --> W[existingTab = undefined]

    V --> X{reusedTab = existingTab or splitTargetTab}
    W --> X

    X -- reusedTab set --> Y[Adopt existing tab]
    X -- reusedTab null --> Z[createTab - mint new tab]
Loading

Reviews (2): Last reviewed commit: "fix(mobile): stop a mobile reveal from m..." | Re-trigger Greptile

Revealing a live PTY from a paired phone passes the tab id baked into
its env, but the create-terminal handler only recognised ownership via
tab.ptyId and the live ptyIdsByTabId map. With the worktree closed on
the desktop no pane is mounted, so ptyIdsByTabId is empty and tab.ptyId
holds at most one leaf's PTY -- a split pane's second PTY lives only in
the persisted layout. Ownership missed, and createTab ran with an id
that already existed; it mints a fresh uuid on collision, so a second
tab appeared on the same session (#10486).

Resolve ownership through the persisted layout as well. Every binding
consulted is an exact match on the ptyId, so all of them outrank the
reveal's tab id hint: that hint is written once when the PTY spawns and
is never rewritten, so it goes stale as soon as a pane is dragged to
another tab. A mounted pane outranks a recorded one, same-tier
conflicts stay ambiguous so the mobile mount planner keeps failing
closed, and the hint is what resolves a reveal that nothing records
yet -- which is also what keeps paneKey hook attribution intact.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/mobile-10486-dup-tab branch from 06b0d32 to bf33f56 Compare July 29, 2026 02:14
@brennanb2025
brennanb2025 merged commit 7477a01 into main Jul 29, 2026
26 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ab (stablyai#11259)

Revealing a live PTY from a paired phone passes the tab id baked into
its env, but the create-terminal handler only recognised ownership via
tab.ptyId and the live ptyIdsByTabId map. With the worktree closed on
the desktop no pane is mounted, so ptyIdsByTabId is empty and tab.ptyId
holds at most one leaf's PTY -- a split pane's second PTY lives only in
the persisted layout. Ownership missed, and createTab ran with an id
that already existed; it mints a fresh uuid on collision, so a second
tab appeared on the same session (stablyai#10486).

Resolve ownership through the persisted layout as well. Every binding
consulted is an exact match on the ptyId, so all of them outrank the
reveal's tab id hint: that hint is written once when the PTY spawns and
is never rewritten, so it goes stale as soon as a pane is dragged to
another tab. A mounted pane outranks a recorded one, same-tier
conflicts stay ambiguous so the mobile mount planner keeps failing
closed, and the hint is what resolves a reveal that nothing records
yet -- which is also what keeps paneKey hook attribution intact.
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]: Viewing an active terminal from mobile creates a duplicate desktop terminal tab

1 participant