Skip to content

fix(mobile): push the materialized handle to a pending-handle terminal (STA-4256) - #15355

Closed
brennanb2025 wants to merge 4 commits into
mainfrom
brennanb2025/fix-mobile-send-dead-0044
Closed

brennanb2025 wants to merge 4 commits into
mainfrom
brennanb2025/fix-mobile-send-dead-0044

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​352 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​352
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​38 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​38

ELI5

When you open a new agent session, the phone can be shown the tab before the terminal behind it exists. The phone asks "is it ready yet?" a bounded number of times and then stops asking. The desktop never volunteered the answer once the terminal did exist, so a pane that missed that window stayed on a spinner — and with no terminal to address, both the terminal composer and native chat had nothing to send to. This makes the desktop publish the moment the pane becomes addressable.

What Changed

  • touchMobileSessionTabsForMaterializedPty(pty): when a PTY becomes addressable, match its pane key against the published snapshot and re-emit only that worktree, and only when the published tab either names this ptyId or names none.
  • Called from the two lifecycle sites that can make an already-published pending pane addressable — onPtySpawned and registerPty — each guarded by paneWasAddressable so a duplicate or repeat registration does not re-publish.
  • The re-emit goes through touchMobileSessionTabsForWorktree, so it carries a bumped snapshotVersion — a re-emit at the same version is silently dropped by every client's monotonic gate.

Host-side only. No wire shape changes, no new fields, no new opcodes.

Why

toMobileSessionTabsResult publishes status: 'pending-handle' whenever a terminal tab has no live PTY. That is a promise to say something else later, and nothing kept it for the case where the tab is published before its PTY exists: touchMobileSessionSnapshotsForPty matches tabs on a ptyId the snapshot does not name yet, and no other path re-emits. PTY registration is the moment that resolves it, and it published nothing.

That was survivable while mobile polled indefinitely. #14916 (STA-4407) bounded the client's pending-handle recovery to PENDING_TERMINAL_HANDLE_RECOVERY_ATTEMPTS = 5 at the reconciler's 2s cadence, so a client that misses that window stops asking. Past that the pane is stranded: activeHandle stays null, resolveMobileTerminalInputGate returns canCompose: false, and there is no composer on either surface.

This is why the fix is host-side. The bound shipped in mobile 0.0.44, which is in App Store review and cannot be patched. Publishing the handle when the pane becomes addressable removes the client's dependence on polling at all, and it fixes every already-installed 0.0.44 client.

What this PR does NOT claim

Linked Issue

Fixes #

Visual Proof

Reproduced live on a paired iOS Simulator running the shipped 0.0.44 client (built from 64de8dd637) against an isolated Electron host at origin/main. A new Claude session, stranded with no composer at all:

before-stranded-pending-handle.png

Client diagnostics at that moment: pendingTerminalCount: 1, activeHandle: null. Host-side, the projection was asked for the handle exactly 5 times — at 1.6s, 3.4s, 5.4s, 7.4s, 9.4s — and then never again. That cadence is the client's 5-attempt budget expiring; it is not a measurement of how long a real PTY takes. Tapping Retry (retryPendingTerminalRecovery, which resets the budget) recovered instantly to activeHandle: "1f117a01", pendingTerminalCount: 0 — proving the handle was available and only the missing publication left the pane stuck.

Healthy path on the same rig for contrast — mobile sends reaching the PTY (each line was typed on the phone):

healthy-terminal-sends-land.png

Limitations, stated plainly: the rig materialized handles immediately, so the pending window was artificially induced by withholding the handle in the host. The stranding and the missing publication are real; the duration in that repro is synthetic. There is no live "after" — the rig registers PTYs through a path that bypasses registerPty, so no genuine pending window could be constructed with the fix in place. The fix is proven at the exact seam by the tests below instead, which drive the real OrcaRuntimeService through onPtySpawned/registerPty.

Testing

src/main/runtime/mobile-pending-handle-materialization.test.ts drives the real OrcaRuntimeService: publish a tab whose PTY has not registered, assert the client is told pending-handle, then take the pane through the lifecycle with no graph sync and no renderer republication at all.

Cases (10 total). The host has no timer and must not acquire one, so these pin that the publication is driven by the addressability transition, at each position relative to the client's 5-attempt ~2s budget:

Timing-relative

  1. Before — PTY addressable before the tab is published: the tab publishes ready and nothing is owed. Asserts no spurious materialization push.
  2. During — registration ~4s in, while the client is still polling: publishes.
  3. After — registration 30s later, past the budget, with intervening title/status churn bumping the version meanwhile: publishes, and beats the newest frame the client took, not the first one.

Lifecycle
4. Reconnect — paneWasAddressable must not latch: a pane that dies (onPtyExit) and comes back is owed the same publication.
5. onPtySpawned alone publishes nothing — the trigger is the registration that makes the pane addressable.
6. No push for an unrelated worktree once nothing is pending.
7. No bump on duplicate registration.
8. No push when the renderer published a different PTY identity (stale ptyId).
9. No touch of an unrelated parked pending pane in another worktree — touchMobileSessionTabsForWorktree called exactly once, with the right worktree.
10. No retention of deleted pending worktrees in the registration path.

Old-client compatibility is asserted inside case 3 via the same-epoch monotonic freshness gate every mirrored client applies (copied as a literal — a main-process test must not import a renderer/mobile module). A client that predates the #14916 bound still gates on exactly this, so a push it cannot accept is a push that never happened.

5 of the 10 go RED against pre-fix source — cases 1(after)/2(during)/4(reconnect) plus the original repro and the parked-pane isolation case:

FAIL > pushes when the PTY registers inside the client recovery window
  AssertionError: expected undefined to match object { status: 'ready' }
FAIL > pushes after the client recovery budget, past intervening republications
  AssertionError: expected undefined to match object { status: 'ready', … }
FAIL > pushes again when a reconnecting PTY makes the pane addressable a second time
  AssertionError: expected "touchMobileSessionTabsForWorktree" to be called with [ 'repo-1::/tmp/worktree-a' ]

undefined because pre-fix no event is emitted at all — which is the bug. The remaining five assert absence and pass pre-fix by construction; they are guards on the fix, not repros.

Regression runs (macOS): this file plus graph-sync-mobile-snapshot-gating.test.ts, client-session-tab-selection.test.ts, and orca-runtime.test.ts — 1228 passed, 1 skipped; tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts — 5 passed; oxlint — 0 warnings, 0 errors.

Platforms: exercised on macOS with a local PTY, direct (LAN) mobile transport. Not exercised on Windows/Linux, SSH, or Relay — the change sits above the PTY provider and keys only on pane key + worktree id, but it is untested there.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Claude Opus 4.5 (Claude Code) did the investigation, live repro, and tests.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Backwards compatibility: the point of the change. No wire shape moves — this is an existing frame on an existing path, carrying content old clients already poll for, so it is Rule 1 / Rule 3 safe per docs/reference/remote-wire-compatibility.md. Clients that still poll are unaffected; clients that stopped now get told.
  • Performance: the publication is targeted to one worktree and gated on paneWasAddressable, so a repeat registration costs nothing and an unrelated spawn costs a failed pane-key match. The emit is coalesced, not immediate.
  • Scope: deliberately limited to the missing lifecycle publication. No latency, Relay, SSH, or startup-optimization work rides along.
  • Remote SSH / folder workspaces: the change sits above the PTY provider and keys on pane key + worktree id, so SSH-hosted and folder workspaces take the same path. Not separately exercised.
  • Security: no new data crosses the wire; the republished snapshot is the same projection clients already receive.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)
    • oxlint and the targeted vitest suites were run locally and pass (see Testing). A full pnpm typecheck / pnpm build was deliberately not run — leaving those to CI.

Author

  • X / Twitter: @BrennanKB5

…l (STA-4256)

A terminal tab published as `pending-handle` promises the client that the host
will say something else later. Nothing kept that promise when the tab was
published before its PTY existed: `touchMobileSessionSnapshotsForPty` matches on
a ptyId the snapshot does not name yet, and no other path re-emits.

That was survivable while mobile polled indefinitely. #14916 (STA-4407) bounded
the client's pending-handle recovery to 5 attempts ~2s apart, so a client stops
asking ~10s after the tab appears. Past that the pane is stranded on the spinner
with `activeHandle: null`, which disables the terminal composer AND native chat
— starting a new agent session is the flow that crosses it.

Record which worktrees we published as `pending-handle`, and re-emit them when a
PTY registers. The push carries a bumped snapshotVersion, which is what a client
accepts; a re-emit at the same version is dropped by its monotonic gate.

Fixes clients that are already shipped and cannot be patched (mobile 0.0.44).
@coderabbitai

coderabbitai Bot commented Aug 18, 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: 3289d019-e7e0-4b06-8517-6cf3be7e5e2f

📥 Commits

Reviewing files that changed from the base of the PR and between 6386b54 and 7e2525a.

📒 Files selected for processing (2)
  • src/main/runtime/mobile-pending-handle-materialization.test.ts
  • src/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/mobile-pending-handle-materialization.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The runtime detects when PTY registration makes a matching pending mobile terminal addressable. It republishes the affected worktree only when addressability changes. Tests verify freshness filtering, ready terminal publication, snapshot version and epoch behavior, duplicate and unrelated registrations, PTY identity mismatches, worktree scoping, reconnects, and deleted worktrees.

Merge Risk: 🔵 Low · up to 7e252

The change restores mobile terminal composition by publishing a ready handle when a pending pane becomes addressable. It is mergeable with owner awareness because the addressability logic is duplicated and could drift in future changes, so follow-up consolidation is advisable.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, visual proof, and compatibility, but it omits the required linked GitHub issue. Add a valid issue reference after Fixes #; do not leave the Linked Issue section as an explanatory placeholder.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 clearly and concisely identifies the mobile pending-handle fix, which matches the primary change.
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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c4ccbb66-0712-4e97-ae92-52f9dff6ced2

📥 Commits

Reviewing files that changed from the base of the PR and between fe95698 and eba96b0.

📒 Files selected for processing (2)
  • src/main/runtime/mobile-pending-handle-materialization.test.ts
  • src/main/runtime/orca-runtime.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

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.

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.ts (1)

7923-7944: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider sharing the "resolved published ptyId for a tab" formula with findPtyForMobileTerminalTab.

Line 7937 recomputes tab.ptyId ?? tab.parentLayout?.ptyIdsByLeafId?.[tab.leafId] ?? null. This is the same formula that findPtyForMobileTerminalTab uses for snapshotPtyId elsewhere in this file. Both formulas answer the same question: which PTY does this tab currently reference.

Extract the formula into a small private helper, for example getMobileTerminalSnapshotPtyId(tab), and call it from both sites. If the two copies drift apart later, the drift can reintroduce a variant of the exact stuck pending-handle bug this method exists to fix.

♻️ Proposed extraction
+  private getMobileTerminalSnapshotPtyId(tab: RuntimeMobileSessionTerminalTab): string | null {
+    return tab.ptyId ?? tab.parentLayout?.ptyIdsByLeafId?.[tab.leafId] ?? null
+  }
+
   private touchMobileSessionTabsForMaterializedPty(pty: RuntimePtyWorktreeRecord): void {
     ...
     const matches = snapshot?.tabs.some((tab) => {
       if (tab.type !== 'terminal' || tab.parentTabId !== pane.tabId || tab.leafId !== pane.leafId) {
         return false
       }
-      const publishedPtyId = tab.ptyId ?? tab.parentLayout?.ptyIdsByLeafId?.[tab.leafId] ?? null
+      const publishedPtyId = this.getMobileTerminalSnapshotPtyId(tab)
       return publishedPtyId === null || publishedPtyId === pty.ptyId
     })
     ...
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2554a41e-3a74-49f7-8f64-f9c50a398928

📥 Commits

Reviewing files that changed from the base of the PR and between eba96b0 and 72e39a4.

📒 Files selected for processing (2)
  • src/main/runtime/mobile-pending-handle-materialization.test.ts
  • src/main/runtime/orca-runtime.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final review status: LAND

Reviewed and improved on pushed commit 72e39a492a2e256aaabac7fa3627c62de9e45055.

Review outcome

  • Opening readiness found one meaningful P2 perf/resource issue in the original implementation: a lifetime-retained global pending-worktree set caused cross-worktree republishing and stale growth.
  • Replaced it with an exact owning-worktree + tab + leaf + PTY identity match, triggered only when the pane becomes addressable.
  • Added focused coverage for the real minted PTY registration order, unrelated worktrees, duplicate registration, stale PTY identity, parked unrelated panes, and deleted snapshots.
  • Same-model senior clean-room re-review returned CLEAN after the fix.
  • Closing readiness returned CLEAN with zero P0/P1/P2 candidates. The implementation is narrowly scoped and aligns with established lifecycle/identity patterns.

Verification

  • Review/fix pass: 1,256 passed, 3 skipped.
  • Independent verification: 1,224 passed, 1 skipped.
  • Closing readiness: 124 passed, 2 skipped, plus 3 filtered SSH/restoration/host-partition tests.
  • Node typecheck, oxlint, formatting, max-lines, and git diff --check passed.
  • CI is fully green, including Node 24/26 test shards, cross-version wire compatibility, Git compatibility, macOS packaging, and Windows packaging.
  • Branch is clean and exactly matches the PR head.

Compatibility and performance

  • No RPC/wire shape, opcode, persisted state, dependency, or platform-specific behavior changes.
  • Work is bounded to the tabs in one owning worktree, once per addressability transition; there is no global scan, retained pending tracker, polling, or retry churn.
  • SSH/reconnect and folder-workspace paths use the same opaque worktree/pane identities. This is not an SSH- or Windows/WSL-specific issue, so separate remote-host UI validation was not required.

Visual QA

The existing genuine before-state and healthy-send screenshots remain attached in the PR description. An independent Grok Electron/native-mobile run verified the correct isolated worktree and loaded the native development build, but its pairing setup violated the mobile workspace-protection rule. I stopped the worker immediately, rejected all evidence from that run, cleaned its processes/profile/temporary data, and did not attach its screenshots. Native after-path visual QA is therefore blocked, not claimed; the exact transition is covered at the real OrcaRuntimeService lifecycle seam by the regression suite.

The PR description has been updated to match the final targeted implementation and this limitation. No further code changes are recommended before landing.

The host has no timer and must not acquire one. These pin that the publication
is driven by the addressability transition, at each position relative to the
client's 5-attempt ~2s recovery budget (#14916):

- before: PTY addressable first, so the tab publishes ready and nothing is owed
  — asserts no spurious materialization push
- during: registration inside the window still publishes
- after: registration 30s later still publishes, and beats the newest frame the
  client took rather than the first one, because intervening title/status churn
  bumps the version meanwhile

Also covers reconnect — `paneWasAddressable` must not latch, so a pane that dies
and comes back is owed the same publication — and old-client compatibility, via
the same-epoch monotonic freshness gate every mirrored client applies. A push an
old client cannot accept is a push that never happened.

3 of the 4 go RED against pre-fix source; the `before` case is a guard.
@coderabbitai

coderabbitai Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing this. It was opened as the fix for the mobile "cannot send / spinner forever" P0, and it is not that fix.

The actual P0 fix is #15463 (merged, 9b8dbd8930). That bug was a different mechanism entirely: a transient handle→PTY lookup failure made the host answer a lease-only terminal.subscribe with end on a live pane; the shipped 0.0.44 client reads three of those as "PTY gone" and then stops asking (MAX_REARM_ATTEMPTS = 3), leaving the composer locked on "Waiting for terminal…" until the app is backgrounded and reopened. Reproduced live and A/B-verified against the fix.

Why this PR is being closed rather than kept as a smaller fix: I could never reach the pending-handle state it targets without artificially forcing it.

Configurations tried, all pendingTerminalCount: 0:

  • new agent tab in the desktop's active worktree
  • new agent tab in a non-active worktree
  • new worktree + agent created from the phone
  • renderer-less headless orca serve, new workspace from the phone (91s)
  • PTY binding withheld 30s, then 90s (injected)

A correction to something I claimed earlier in this PR's discussion: I cited a pendingTerminalCount: 4 observation as evidence the state occurs naturally on the restore path. It does not — that run had ORCA_QA_BINDING_DELAY_MS=30000 active, and the host log shows the injection holding those exact bindings. Every observation of pending-handle I have was caused by my own fault injection.

So: the publication gap is real in code, and the tests here are honest (5 of 10 go RED against pre-fix source, driving the real OrcaRuntimeService through onPtySpawned/registerPty). What is missing is any evidence the state occurs in practice, and therefore any evidence this code ever runs. A green, mergeable PR whose title and history say "the mobile send fix" is too easy to mistake for the P0 later, which is the specific failure mode I want to avoid.

What would justify reopening: a report of a pane stuck on a spinner with the composer still enabled — that is the pending-handle signature, and it is visually distinct from the "Waiting for terminal…" lock that #15463 fixed. The branch and its tests are preserved and can be revived against that report.

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