Skip to content

fix(mobile): restore terminal input when reopening worktrees - #16239

Merged
brennanb2025 merged 6 commits into
stablyai:mainfrom
shaharmor:fix/mobile-worktree-reopen-input
Sep 4, 2026
Merged

brennanb2025 merged 6 commits into
stablyai:mainfrom
shaharmor:fix/mobile-worktree-reopen-input

Conversation

@shaharmor

Copy link
Copy Markdown
Contributor

ELI5

Returning to a worktree on iPhone no longer leaves its terminal zoomed out with a keyboard that cannot send input. The terminal now waits for the identity already attached to its live host connection instead of racing a second credential lookup.

What Changed

  • Mobile terminal subscriptions and input use the authenticated identity published with the shared host client.
  • Terminal controls stay non-sendable until that client/identity pair is bound.
  • Input that finishes during a host-client rebind is dropped rather than sent under the wrong identity.
  • Regression coverage pins atomic client/identity rebinding and session terminal wiring.

Why

A reopened worktree could hydrate its terminal before an asynchronous Keychain-backed host lookup repopulated the screen-local device token. The host rejected that identity-less subscription, so the terminal received neither phone-fit geometry nor mobile input ownership; tapping the tab title happened to retry after the token had loaded.

Publishing the connection identity from the same context entry as the client removes that race and keeps reconnect or route-reuse transitions fail-closed.

Linked Issue

Reported directly; no existing issue.

Visual Proof

N/A — there is no static visual change to capture. This fixes an iPhone worktree-reopen interaction; a full Xcode/iOS simulator is not installed on the validation machine.

Testing

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

Validated after rebasing onto current upstream/main:

  • pnpm --dir mobile test — 458 files passed; 3,674 tests passed, 3 skipped
  • pnpm --dir mobile typecheck — passed
  • pnpm --dir mobile lint — passed
  • pnpm --dir mobile format:check — passed
  • pnpm run check:max-lines-ratchet — passed with no new bypasses
  • git diff --check upstream/main...HEAD — passed

Review

  • Correctness: client and authenticated identity are published atomically; subscriptions and sends fail closed without the pair.
  • Security: no credential or wire-format change; terminal RPCs carry the same pairing identity already used to authenticate the connection.
  • Cross-platform: shared React Native paths remain platform-neutral; no platform-specific APIs were added.
  • SSH / remote / folder workspaces: execution ownership and RPC routing are unchanged; the fix applies to the host client regardless of workspace kind or execution host.
  • Performance: no new storage or network work; the terminal no longer depends on a second credential read for identity.
  • UI quality: no layout or style changes; composition remains available while sending is gated on a valid connection identity.
  • Review result: cross-model review found no current-scope runtime defect after validation; one non-blocking testing-depth concern remains covered by the route's existing source-contract test strategy.

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

Physical iOS validation remains the explicit gap. Mixed-version desktop/mobile compatibility is unchanged because the RPC payload values and shapes are unchanged.

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 (mobile-scoped equivalents pass; CI will run repository-wide checks)

Compound Engineering

@coderabbitai

coderabbitai Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 5f7f727b-10ce-4953-b26e-45d019a55332

📥 Commits

Reviewing files that changed from the base of the PR and between e8554a9 and b6055cb.

📒 Files selected for processing (1)
  • mobile/src/transport/client-context.tsx

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


📝 Walkthrough

Walkthrough

The transport context now stores and exposes the shared client's clientId for each host binding. The session foundation passes this value to terminal hooks. Terminal runtime synchronizes its identity reference with clientId and blocks sending without an identity. Terminal subscriptions skip when identity is unavailable and send clientId in requests. Lifecycle code no longer copies the host device token into session state. Tests verify rebinding and source-level identity handling.

Merge Risk: 🟡 Moderate · up to b6055

Terminal input may still be sent under a mismatched identity after a host rebind, which could affect commands entered immediately during reconnection. This should be resolved before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, implementation, rationale, testing, risk areas, and validation status. However, the required Linked Issue section does not contain an issue link or a Fixes #...… Add the linked issue reference in the required Fixes #... format. Add the AI Disclosure section, or state the applicable exemption if the author is an internal contributor.
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 12 files. 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 describes the main change: restoring terminal input when reopening mobile worktrees.
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.
Full details: Description check

Explanation

The description explains the problem, implementation, rationale, testing, risk areas, and validation status. However, the required Linked Issue section does not contain an issue link or a Fixes #... reference, and the AI Disclosure section is omitted.

  • Fix all pre-merge checks with AI

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
mobile/app/h/[hostId]/session/[worktreeId].tsx (1)

3044-3065: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Keep the RPC client and client ID from the same binding. If rebinding occurs while dictation waits for flushPendingLiveInputBeforeExternalSend, the old sendLiveTerminalInput closure can use the new clientRef.current with its old clientId. If rebinding occurs while terminal creation awaits its response, the initial prompt can use the old captured client with the new clientIdRef.current. Both paths can send under the wrong identity instead of dropping the delayed input.

  • mobile/app/h/[hostId]/session/[worktreeId].tsx#L3044-L3065: Read the client ID from the same current binding as rpc, or snapshot and validate both values before sending.
  • mobile/app/h/[hostId]/session/[worktreeId].tsx#L3783-L3791: Snapshot the client and client ID before the create request, then drop the initial prompt when either current ref no longer matches the snapshot.

Add a deferred-rebind regression test for both paths.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 28ba4c74-b4d9-44d8-a999-28f2a773171f

📥 Commits

Reviewing files that changed from the base of the PR and between afd76a4 and 2f480b2aff9d3f4654f21c4e47888bafcccde582.

📒 Files selected for processing (7)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/session/mobile-session-startup-source.test.ts
  • mobile/src/transport/client-context.test.ts
  • mobile/src/transport/client-context.tsx
  • mobile/src/transport/host-client-context-state.ts
  • mobile/src/transport/host-entry-opener.ts
  • mobile/src/transport/rpc-client-context-contract.ts

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

@brennanb2025

Copy link
Copy Markdown
Contributor

Review status: LAND AFTER REVIEW (native mobile QA remains blocked)

  • Start and end readiness-checklist passes: PASS, no proven P0/P1/P2 findings.
  • Same-model senior review/fix loop returned CLEAN. No meaningful source changes were warranted; the PR remains focused on atomically binding the authenticated client identity to the shared host client, gating terminal subscribe/send until that pair exists, and fencing stale accessory sends.
  • OSS precedent review found the stable per-client identity and event-driven terminal-input design aligned with standard terminal/mobile client patterns.
  • Validation passed: pnpm --dir mobile test (458 files, 3,674 passed, 3 skipped), pnpm --dir mobile typecheck, pnpm --dir mobile lint, pnpm --dir mobile format:check, and git diff --check.
  • Orchestrated Grok Electron pass confirmed the exact PR worktree identity and launched the mobile/iOS validation path. It reached the simulator/Expo launcher and pairing setup, but the native Orca Mobile reopen→type/send flow could not be completed because the simulator/dev-client path shut down/reopened into the Expo launcher and the worker became blocked waiting for the emulator response. No valid before/after screenshots were produced or attached, so I am not claiming end-to-end native repro proof.

Conclusion: the code review is clean and the implementation is the correct root-cause shape, but native iOS repro/visual proof is the remaining validation gap before calling this fully merge-verified.

@brennanb2025

Copy link
Copy Markdown
Contributor

Direct validation complete on PR #16239 (commit 2f480b2aff).

The native flow was initially blocked by an unavailable pairing endpoint, but succeeded after refreshing the simulator attachment and pairing through the supported flow. No pairing credentials are included here.

@brennanb2025

Copy link
Copy Markdown
Contributor

Follow-up status: GitHub currently reports the PR as CONFLICTING (mergeStateStatus: DIRTY) against its base branch. The reviewed commit itself is clean and all observed checks are passing; resolving the base-branch conflict still requires a maintainer rebase/merge decision and was left untouched to avoid expanding scope.

@brennanb2025
brennanb2025 force-pushed the fix/mobile-worktree-reopen-input branch from 2f480b2 to af62015 Compare September 3, 2026 22:13
@coderabbitai

coderabbitai Bot commented Sep 3, 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

Conflict resolution complete. I rebased the PR onto current main and pushed the resolved branch (af62015ff4). The original session route had been split on main, so the fix was ported into the current modular session hooks rather than reviving the obsolete monolithic route.

Validation after the rebase:

  • Targeted Vitest: 2 files, 30 tests passed.
  • Mobile TypeScript typecheck passed.
  • Oxlint and Oxfmt passed for all changed session files.
  • git diff --check passed.
  • GitHub now reports the PR as MERGEABLE; CI checks are pending.

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 4b8d0f68-78bc-4654-8daf-89c97ad1d59c

📥 Commits

Reviewing files that changed from the base of the PR and between c79e1c0 and af62015.

📒 Files selected for processing (10)
  • mobile/src/session/mobile-session-startup-source.test.ts
  • mobile/src/session/use-mobile-session-foundation.ts
  • mobile/src/session/use-mobile-session-lifecycle.ts
  • mobile/src/session/use-mobile-session-terminal-runtime.ts
  • mobile/src/session/use-mobile-session-terminal-subscription.ts
  • mobile/src/transport/client-context.test.ts
  • mobile/src/transport/client-context.tsx
  • mobile/src/transport/host-client-context-state.ts
  • mobile/src/transport/host-entry-opener.ts
  • mobile/src/transport/rpc-client-context-contract.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • mobile/src/transport/rpc-client-context-contract.ts
  • mobile/src/transport/client-context.tsx
  • mobile/src/transport/host-entry-opener.ts
  • mobile/src/transport/client-context.test.ts
  • mobile/src/transport/host-client-context-state.ts

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

},
[
client,
clientId,

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Expect: the rebind path unsubscribes existing handles and resubscribes them with the new clientId.
rg -n -P -C 12 '\b(clientId|subscribeToTerminal|unsubscribeTerminal|terminalUnsubsRef)\b' \
  mobile/src/session --glob 'use-mobile-session-*.ts'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '--- subscription hook outline ---'
ast-grep outline mobile/src/session/use-mobile-session-terminal-subscription.ts
echo '--- subscription hook: state, subscription, cleanup, dependencies ---'
rg -n -C 10 'terminalUnsubsRef|subscribingHandlesRef|useEffect|useCallback|subscribeToTerminal|unsubscribeTerminal|clientId' \
  mobile/src/session/use-mobile-session-terminal-subscription.ts
echo '--- stream display outline and identity-related effects ---'
ast-grep outline mobile/src/session/use-mobile-session-terminal-stream-display.ts
rg -n -C 12 'terminalUnsubsRef|subscribeToTerminal|unsubscribeTerminal|useEffect|clientId|client' \
  mobile/src/session/use-mobile-session-terminal-stream-display.ts

Repository: stablyai/orca

Length of output: 11164


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '--- native chat stream hook ---'
fd -i 'native-chat-terminal-stream|mobile-session.*(screen|route|hook)|use-mobile-session' mobile/src/session -t f | sort
echo '--- client identity and terminal subscription composition ---'
rg -n -C 12 'useMobileNativeChatTerminalStream|useMobileSessionTerminalSubscription|useMobileSessionTerminalStreamDisplay|clientId|terminalUnsubsRef' \
  mobile/src/session \
  --glob '*.ts' --glob '*.tsx' \
  | rg -v 'use-mobile-session-keyboard-state|use-mobile-session-terminal-list|use-mobile-session-tab-switching|use-mobile-session-tab-application|use-mobile-session-terminal-create-actions'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '--- native chat stream hook implementation ---'
cat -n mobile/src/session/use-mobile-native-chat-terminal-stream.ts
echo '--- cache cleanup callers and identity transitions ---'
rg -n -C 18 'clearTerminalCache|clientId' mobile/src/session \
  --glob '*.ts' --glob '*.tsx' \
  | grep -E 'clearTerminalCache|clientId|useEffect|return \(\)|unsubscribeTerminal|subscribeToTerminal' \
  | head -n 260
echo '--- controller composition ---'
rg -n -C 20 'useMobileSessionTerminalSubscription|useMobileSessionTerminalStreamDisplay|useMobileSessionTerminalSubscriptionFoundation|useMobileSessionFoundation' \
  mobile/src/session/use-mobile-session-controller.ts \
  mobile/src/session/use-mobile-session-*.tsx \
  mobile/src/session/use-mobile-session-*.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '--- native-chat action contract ---'
cat -n mobile/src/session/mobile-native-chat-terminal-stream.ts | sed -n '1,180p'
echo '--- startup effects and cleanup ---'
cat -n mobile/src/session/use-mobile-session-startup.ts | sed -n '1,125p'
echo '--- exact cache cleanup implementation ---'
cat -n mobile/src/session/use-mobile-session-terminal-subscription-foundation.ts | sed -n '29,90p'

Repository: stablyai/orca

Length of output: 12262


Rebind active terminal subscriptions when clientId changes.

useMobileNativeChatTerminalStream preserves an active non-lease stream, so an A → null → B transition can leave terminalUnsubsRef holding a stream bound to A. The new subscribeToTerminal closure then returns already-subscribed and cannot bind the stream to B. Unsubscribe active handles on identity changes, then resubscribe when clientId is available. Add a regression test for this transition.

@brennanb2025
brennanb2025 self-requested a review as a code owner September 3, 2026 22:50
@brennanb2025

Copy link
Copy Markdown
Contributor

Review status: ready for merge.

  • Resolved the merge conflict with origin/main and kept the PR scoped to the mobile terminal identity/lifecycle fix.
  • Fixed the CI static-analysis failure by extracting the host-client hooks and retaining the required RpcClient type import.
  • Fresh CI for b6055cb66f: PR Checks ✅, Mobile Checks ✅, PR test LoC ✅.
  • Final focused review/readiness checks are clean; mobile typecheck, oxlint, focused tests, and the full mobile suite pass.
  • Fixed-branch Electron validation passed, and a real paired mobile runtime was established with terminal creation/input exercised.

A/B note: I could not honestly reproduce the old failure on the parent build. Its paired-host/runtime path never became usable (the app remained unable to connect), so any apparent missing input would be indistinguishable from host unavailability. The old-build failure remains an explicit reproduction gap; the fixed branch behavior is validated independently.

@brennanb2025

Copy link
Copy Markdown
Contributor

Independent Fable review and A/B reproduction completed at HEAD b6055cb.

  • Natural simulator timing did not trigger the race: parent 6/6 reopen probes passed; PR 3/3 passed.
  • With an identical 1.5s delay injected into the parent’s Keychain-backed loadHosts() path, the reported failure reproduced deterministically: reopened terminal stayed blank at 2s/5s/20s, the stream’s first event was error, and the input probe never reached the PTY.
  • With that same delay on the PR build, the stream subscribed, the viewport refit, and the input probe was delivered. Generated webview engines were byte-identical, isolating the result to the RN-side change.
  • Root cause confirmed: the old subscription could send a null client identity while async host loading was still pending; the host rejects that identity. The PR couples clientId to the host-client entry and gates subscription/input until identity is present.
  • Independent code review found no in-scope defect. Mobile typecheck and 2,568 focused tests passed. No PR files were edited or pushed.

This is an induced reproduction of the production timing race, not a claim that the uninstrumented simulator naturally reproduced it.

@brennanb2025
brennanb2025 merged commit 7106101 into stablyai:main Sep 4, 2026
21 checks passed
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for the PR @shaharmor !

Jinwoo-H added a commit that referenced this pull request Sep 4, 2026
Resolves #16239's shared-client terminal identity against the hybrid split: the
hosted page has no native client, so identity readiness is a flag
(hostClientIdentityReady) rather than a non-null clientId, and the bridge
terminal operations keep their workspaceId/terminalId/clientId contract.
Adds getClientId to the disabled hosted client context and keeps the
mobile-web extra resource alongside main's new emoji shortcode dataset.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…i#16239)

* fix(mobile): restore terminal input when reopening worktrees

* test(mobile): update session parity facts

* refactor(mobile): split host client hooks

* chore: restore localization formatter scope

* fix(mobile): retain RpcClient type import

---------

Co-authored-by: Merge Sim <sim@local>
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.

2 participants