Skip to content

fix(mobile): restore the last-open tab when returning to a worktree on mobile - #9801

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/fix-mobile-worktree-reopen
Jul 22, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/fix-mobile-worktree-reopen

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Returning to a worktree on mobile opened the first tab instead of the tab the phone last had open.

Root cause

The host tracks each paired device's tab selection in ClientSessionTabSelectionStore — in memory only. Any host restart (desktop relaunch, serve restart) wiped it. The per-device projection then deliberately ignores host focus ("a new paired device starts from deterministic topology") and falls back to tabs[0], so the phone always landed on the first tab — not even the desktop's active tab.

Reproduced live in the iOS simulator against a dev desktop:

  1. Phone activates Terminal 3 in a 3-tab worktree (desktop active = Terminal 2), leaves the worktree.
  2. Same-run return and even a full mobile app cold restart correctly restore Terminal 3 (host memory intact).
  3. Restart the desktop, re-enter the worktree on the phone → Terminal 1 (bug).

Fix (host-side)

  • Persist per-device selections in the Store under mobileClientTabSelectionsByDeviceId (deviceId → worktreeId → selection); the runtime hydrates them at construction and writes back on every activate/forget.
  • Guard project() so an early empty snapshot right after restart can't wipe a hydrated selection before tabs hydrate.
  • Prune entries on repo/worktree removal (pruneWorktreeStateForRepo, existing forgetWorktree) and on device revoke (existing forgetClientNavigationState).
  • Malformed persisted payloads normalize to empty instead of throwing.

Host-side (rather than phone-side AsyncStorage) keeps the host the single owner of per-device navigation state, fixes all paired devices at once, and needs no mobile release. Phones talking to older desktops behave as before.

Tests

  • client-session-tab-selection.test.ts: persist → rebuild (restart) round-trip, forget persistence + no-op-write guard, empty-snapshot guard, malformed-payload normalization.
  • multi-client-navigation-isolation.integration.test.ts: activation persists through the store contract; a second runtime over the same store restores the device's tab while a fresh device still gets deterministic topology.
  • persistence.test.ts: disk round-trip across createStore() reloads, corrupt-payload fallback, repo-removal pruning.

QA (live, iOS sim + dev desktop)

With the fix: phone on Terminal 3 → desktop killed and relaunched → phone leaves + re-enters worktree → Terminal 3 restored (screenshotted at every step; selection visible in orca-data.json). Before the fix the same flow landed on Terminal 1.

pnpm typecheck, oxlint, max-lines ratchet, and the touched suites (401 tests) all pass.

Notes / follow-ups

  • A remote runtime constructed without a Store (store: null) keeps today's in-memory-only behavior.
  • Not covered here: mobile-side flash if the phone re-enters before the host finishes hydrating tabs — existing pending-activation logic already handles the common case.
  • Selections are keyed by deviceId, so re-pairing a phone starts navigation memory fresh (consistent with all other per-device state).
  • A phone paired to an older desktop build keeps today's first-tab behavior until that host updates; a phone-side fallback was considered and deliberately skipped (mobile release lag, and it would fight the host-authoritative projection). Worth revisiting only if it shows up in the wild.

…ores the last open tab

A phone's tab selection lived only in the host's in-memory
ClientSessionTabSelectionStore. Any host restart wiped it, and the
per-device projection then fell back to deterministic topology, so
returning to a worktree on mobile always landed on the first tab
instead of the tab last opened on the phone.

Persist the per-device selections in the Store (keyed deviceId ->
worktreeId), hydrate them when the runtime constructs, and guard
projection so an early empty snapshot after restart cannot wipe a
hydrated selection before tabs arrive. Selections are pruned with the
worktree/repo and on device revoke, and malformed persisted payloads
degrade to empty instead of throwing.
@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@brennanb2025, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 1 minute

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a9f38eff-930e-4b68-8dce-45c5bfb35b06

📥 Commits

Reviewing files that changed from the base of the PR and between 5e70fec and 58c6cb6.

📒 Files selected for processing (6)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/client-session-tab-selection-persistence.ts
  • src/main/runtime/client-session-tab-selection.test.ts
  • src/main/runtime/client-session-tab-selection.ts
  • src/main/runtime/orca-runtime.ts
📝 Walkthrough

Walkthrough

Adds persisted per-device mobile client tab selections keyed by worktree. Persisted payloads are normalized during loading, selections are pruned when worktrees are removed, and Store APIs expose reading and writing the state. Runtime initialization hydrates selections and persists activation or deletion changes. Empty snapshots no longer overwrite hydrated selections. Tests cover malformed payloads, reloads, pruning, deletion persistence, and device-specific restoration.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: restoring the last-open mobile tab after returning to a worktree.
Description check ✅ Passed The description is detailed and covers problem, fix, tests, QA, and follow-ups, but it omits several template sections.
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.

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

Run ID: d77082f0-f474-455f-8f35-9932b9aa270c

📥 Commits

Reviewing files that changed from the base of the PR and between b25c298 and a26fd44.

📒 Files selected for processing (7)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/client-session-tab-selection.test.ts
  • src/main/runtime/client-session-tab-selection.ts
  • src/main/runtime/multi-client-navigation-isolation.integration.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/shared/types.ts

Comment on lines +9420 to +9428
store.removeProject('r1')

expect(store.getMobileClientTabSelections()['device-a']).toEqual({
'other-repo::/tmp/wt': {
activeTabId: 'tab-2',
activeGroupId: null,
activeTabIdByGroupId: {}
}
})

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 | 🟡 Minor | ⚡ Quick win

Verify repository pruning survives a reload.

The assertion only checks in-memory state. Flush after removeProject, recreate the Store, and assert the removed worktree selection is still absent; otherwise a missing save after pruning is not covered.

Comment on lines +196 to +213
it('drops malformed persisted payloads instead of hydrating them', () => {
expect(
normalizePersistedMobileClientTabSelections({
'device-a': {
'wt-1': { activeTabId: 'tab-1', activeGroupId: null, activeTabIdByGroupId: { g: 'tab' } },
'wt-bad': { activeTabId: 42, activeGroupId: null, activeTabIdByGroupId: { g: 7 } }
},
'device-bad': 'nope',
'device-empty': {}
})
).toEqual({
'device-a': {
'wt-1': { activeTabId: 'tab-1', activeGroupId: null, activeTabIdByGroupId: { g: 'tab' } }
}
})
expect(normalizePersistedMobileClientTabSelections(null)).toEqual({})
expect(normalizePersistedMobileClientTabSelections('garbage')).toEqual({})
})

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 | 🟡 Minor | ⚡ Quick win

Reject array-shaped persisted payloads.

This only covers primitive invalid device values. Arrays also pass the normalizer’s object checks, so an array containing a valid selection is accepted under a numeric worktree key. Add regression cases for root/device arrays and reject them with Array.isArray(...).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Manual QA and review follow-up

Validated the production user flow with an isolated current-worktree Electron host and Orca Mobile on an iPhone 17 Pro simulator (iOS 26.5):

  1. Paired the simulator to the Electron host over the local network.
  2. Opened the PR worktree with three terminal tabs and selected Terminal 3 on mobile.
  3. Left the worktree, fully stopped the host, and confirmed mobile entered reconnect state.
  4. Relaunched the same host/profile, reopened the worktree from mobile, and confirmed Terminal 3 was restored.

Evidence

Desktop host with three tabs:

desktop host with three tabs

Mobile connected to the PR worktree:

mobile connected to PR worktree

Terminal 3 selected before restart:

Terminal 3 selected before restart

Host fully stopped and mobile reconnecting:

mobile reconnect state

Terminal 3 restored after host restart:

Terminal 3 restored after restart

Review fixes pushed

  • Persist only hydrated or explicitly user-selected sessions. Worktree-list topology projections no longer inflate the persisted payload for every listed worktree.
  • Prune persisted selections for folder workspaces removed directly or through project-group deletion, including empty device buckets.
  • Reject array-shaped malformed persistence payloads at every object boundary.
  • Strengthen repo/folder cleanup tests with flush-and-reload verification.

Verification

  • 403 focused persistence/navigation tests passed.
  • Full TypeScript typecheck passed.
  • Changed-file oxlint, type-aware switch exhaustiveness, oxfmt, diff check, and max-lines ratchet passed.
  • Backcompat review: no mobile protocol, RPC, route, AsyncStorage, provider, Git, or SSH contract changes. The persisted field remains host-internal and additive, and missing/malformed state degrades to existing deterministic topology behavior.
  • Performance review: persistence stays event-driven, serialization is bounded to real selections, and cleanup only scans the small per-device persisted selection map.

The repository-wide lint still reports an unrelated existing switch-exhaustiveness error in src/renderer/src/components/skills/skill-freshness-group.tsx; all files changed by this PR pass the equivalent checks.

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

Run ID: 80287154-dfec-440e-b944-3897267edd2f

📥 Commits

Reviewing files that changed from the base of the PR and between a26fd44 and 5e70fec.

📒 Files selected for processing (4)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/client-session-tab-selection.test.ts
  • src/main/runtime/client-session-tab-selection.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/persistence.test.ts
  • src/main/runtime/client-session-tab-selection.ts

Comment thread src/main/persistence.ts Resolved
@brennanb2025
brennanb2025 merged commit 24b8fcc into main Jul 22, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…n mobile (stablyai#9801)

* fix(mobile): persist per-device tab selection so worktree return restores the last open tab

A phone's tab selection lived only in the host's in-memory
ClientSessionTabSelectionStore. Any host restart wiped it, and the
per-device projection then fell back to deterministic topology, so
returning to a worktree on mobile always landed on the first tab
instead of the tab last opened on the phone.

Persist the per-device selections in the Store (keyed deviceId ->
worktreeId), hydrate them when the runtime constructs, and guard
projection so an early empty snapshot after restart cannot wipe a
hydrated selection before tabs arrive. Selections are pruned with the
worktree/repo and on device revoke, and malformed persisted payloads
degrade to empty instead of throwing.

* fix(mobile): harden persisted tab selection cleanup

* fix(mobile): preserve tab selection across worktree rename
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