Skip to content

perf(mobile): gate host polling on foreground/background - #9857

Merged
nwparker merged 2 commits into
mainfrom
nwparker/perf-13-mobile-poll-gate
Jul 22, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/perf-13-mobile-poll-gate

Conversation

@nwparker

@nwparker nwparker commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

What

The mobile host screen ran two 3-second polls while connected — the routed screen and the embedded sidebar — and each fired both worktree.ps (a full multi-repo process scan) AND repo.list, with no foreground/background gate. So a phone left connected pinged every 3s (host CPU + relay/cellular bytes + a radio wakeup) even during brief background windows while the socket stays parked.

This consolidates both poll sites into one startHostWorktreeRefresh lifecycle and AppState-gates the interval so both polls stop while backgrounded and refresh immediately on foreground return:

  • worktree.ps keeps its 3s cadence while foregrounded — it carries live per-worktree agent status / preview / unread that no push event replaces, so it is not removed.
  • repo.list stays on the interval as an AppState-gated convergence safety-net (it self-throttles to REPO_METADATA_REFRESH_MS = 60s, so it's ~1 request/min while foregrounded), plus a reposChanged/worktreesChanged fast-path and a reconnect-replay refetch.

The win is the foreground gate: while the app is backgrounded, both polls (and their radio wakeups) stop entirely; while foregrounded, behavior matches the old cadence.

ELI5

Your phone kept pinging the computer twice every 3 seconds — even in your pocket — for the live agent list and a rarely-changing repo icon/color list. Now both pings pause while the app is backgrounded and instantly catch up when you reopen it. The live list keeps its speed while you're looking, and the repo-icon list still refreshes on its own so a desktop settings change never leaves the phone stale.

Proof of zero regression

  • Repo metadata still converges (this was caught by adversarial review): desktop Settings repo edits (icon/color/name, repo removal) notify only the renderer IPC, not the runtime clientEvents stream mobile subscribes to — so repo.list cannot be purely event-driven without going stale on a foregrounded screen. It's kept on the (now gated) interval, self-throttled to 60s, exactly as before, so a foregrounded screen still converges within ≤60s. The event fast-path is additive.
  • The live worktree.ps poll (agent status/preview/unread) is preserved; optimistic reconciliation still gets periodic confirmations while foreground and an immediate one on foreground return.
  • Reconnect refetches everything (lifecycle mount-fetch on connState flip + same-instance ready-after-ready replay), covering "events aren't queued while disconnected."
  • Embedded-sidebar path (never focused) wired independently, gated the same way.
  • Verified in a deps-installed mobile checkout: pnpm typecheck clean, full mobile suite 2232 pass / 2 skipped (307 files), oxlint clean (within the frozen max-lines budget), oxfmt --check clean. Tests cover: interval polls (worktrees + repo.list) while active and skips both while backgrounded; immediate foreground refresh; reposChanged/worktreesChanged refetch; reconnect stream replay.

Proof of perf improvement

While backgrounded this stops the entire 3s poll loop (worktree.ps + repo.list + their radio wakeups) — the new tests assert neither snapshot is fetched while AppState !== 'active'. Foreground steady-state keeps exactly the prior cadence (worktree.ps every 3s, repo.list ≤ once/60s), now with faster runtime-origin repo/worktree convergence via the event fast-path. Net: a connected phone in your pocket stops waking its radio every 3s.

Follow-up (out of scope)

The cleaner long-term fix for the desktop-repo-edit case is to bridge the renderer-only notifyReposChanged to OrcaRuntimeService.notifyReposChanged() so mobile gets an instant runtime event and the periodic repo.list safety-net could drop further. Left as a separate desktop-side change to keep this PR mobile-only.

The mobile host screen ran two 3s polls (routed + embedded), each firing worktree.ps
AND repo.list, with no foreground/background gate — so a connected phone kept pinging
every 3s (worktree.ps is a full multi-repo process scan) plus a radio wakeup, including
brief background windows while the socket stays parked.

Consolidate both into one startHostWorktreeRefresh lifecycle and AppState-gate the
interval so BOTH polls stop while backgrounded and refresh immediately on foreground
return. worktree.ps keeps its 3s cadence while foregrounded (it carries live agent
status/preview/unread that no push event replaces). repo.list stays on the interval as
an AppState-gated, self-throttling (REPO_METADATA_REFRESH_MS=60s) convergence safety-net
— desktop Settings repo edits notify only the renderer, not the runtime clientEvents
stream, so it can't be made purely event-driven without going stale — and additionally
gets a reposChanged/worktreesChanged fast-path and reconnect-replay refetch.

Verified in a deps-installed mobile checkout: full mobile suite 2232 pass, typecheck,
oxlint (within the frozen max-lines budget), and oxfmt --check all clean.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the nwparker/perf-13-mobile-poll-gate branch from 46625fb to 4b41534 Compare July 22, 2026 04:12
@nwparker

Copy link
Copy Markdown
Contributor Author

Adversarial review caught one Major regression, now fixed: making repo.list purely event-driven left desktop Settings repo edits (icon/color/name, removal) stale on a foregrounded host screen, because those notify only the renderer IPC (repos.ts notifyReposChanged), not the runtime clientEvents stream mobile subscribes to. Restored the periodic repo.list on the (now AppState-gated) interval as a self-throttling (60s) convergence safety-net — preserving the battery win (both polls stop while backgrounded) while keeping the ≤60s convergence the old code had. Test updated to assert the interval polls repo metadata while foregrounded and skips it (and worktree.ps) while backgrounded. Full mobile suite 2232 pass + typecheck/lint/format clean.

@coderabbitai

coderabbitai Bot commented Jul 22, 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

Run ID: 33a11a3b-0081-4be2-8fe0-f24acb4619bc

📥 Commits

Reviewing files that changed from the base of the PR and between 4b41534 and adeb47c.

📒 Files selected for processing (1)
  • mobile/src/transport/use-worktree-resync.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • mobile/src/transport/use-worktree-resync.ts

📝 Walkthrough

Walkthrough

Adds centralized host worktree refresh orchestration with foreground polling, app-state handling, runtime event responses, and cleanup. The host screen uses this lifecycle for routed and embedded rendering, while repository metadata requests gain per-client in-flight and queued refresh handling. Reconnect and manual refresh behavior now use the updated callback options, and tests cover timers, app-state transitions, and runtime events.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it omits required template sections like Screenshots, Testing, AI Review Report, Security Audit, and Notes. Reformat the description to match the template and add the missing sections, including screenshots/no visual change, test checklist, review report, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: gating mobile host polling by foreground/background state.
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.
✨ 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.

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
mobile/src/transport/use-worktree-resync.ts (1)

30-41: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Manual refresh silently drops the repo-metadata refresh if a fetch is already in flight.

onRefresh's forced fetchRepoMetadata({ force: true }) (line 37) omits queueIfInFlight: true, unlike every other forced call site (host-worktree-refresh.ts's reposChanged/replay/foreground paths). If another fetch happens to be in flight when the user pulls to refresh, fetchRepoMetadata in index.tsx (lines 365-370) will see the in-flight guard, skip queuing since queueIfInFlight is falsy, and return without ever refreshing repo colors/icons for this pull-to-refresh — even though the spinner completes as if it succeeded.

🐛 Proposed fix
-      await fetchRepoMetadata({ force: true })
+      await fetchRepoMetadata({ force: true, queueIfInFlight: true })
🧹 Nitpick comments (4)
mobile/src/worktree/host-worktree-refresh.ts (1)

7-8: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Export the shared option types instead of re-declaring them per file.

RepoRefreshOptions/WorktreeRefreshOptions are file-local here, but the exact same shapes are duplicated inline in mobile/app/h/[hostId]/index.tsx (fetchRepoMetadata/fetchWorktrees callback signatures) and mobile/src/transport/use-worktree-resync.ts (hook argument types). Since this file defines the canonical contract consumed by both, export these types and import them at the other two call sites to prevent drift.

♻️ Proposed fix
-type WorktreeRefreshOptions = { allowDuringModal?: boolean }
-type RepoRefreshOptions = { force?: boolean; queueIfInFlight?: boolean }
+export type WorktreeRefreshOptions = { allowDuringModal?: boolean }
+export type RepoRefreshOptions = { force?: boolean; queueIfInFlight?: boolean }
mobile/src/worktree/host-worktree-refresh.test.ts (1)

104-116: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider adding a case for 'end' followed by a single 'ready'.

This test only covers two consecutive 'ready' events with no 'end' in between. Given the open question in host-worktree-refresh.ts about whether real reconnects go through 'end' first, a test asserting the expected behavior for 'end' → 'ready' (single) would pin down the intended semantics either way.

mobile/app/h/[hostId]/index.tsx (1)

371-372: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Local now shadows the outer now state variable.

const now = Date.now() (line 371) shadows the component-level now from useNow(30_000) (line 157) used for row timestamps. No functional bug today since this local now never escapes the callback, but the name collision invites future mistakes (e.g. accidentally reading the wrong now if this closure grows).

✏️ Proposed rename
-      const now = Date.now()
-      if (!options.force && now - repoMetadataFetchedAtRef.current < REPO_METADATA_REFRESH_MS) {
+      const nowMs = Date.now()
+      if (!options.force && nowMs - repoMetadataFetchedAtRef.current < REPO_METADATA_REFRESH_MS) {
mobile/src/transport/use-worktree-resync.ts (1)

20-26: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stale fetchRepoMetadata dependency, and possible duplicate reconnect worktrees fetch.

fetchRepoMetadata is still listed in the deps array (line 26) even though the body no longer calls it — harmless today (the ref-guard in fetchWorktrees/fetchRepoMetadata prevents duplicate in-flight work either way) but worth trimming since it's dead weight from the removed call.

Separately, fetchWorktrees({ allowDuringModal: true }) still fires here on every connState transition into 'connected' (line 24), while index.tsx's startWorktreeRefresh (lines 505-527) is now recreated on every connState change too (since fetchWorktrees/fetchRepoMetadata depend on connState), which itself calls fetchWorktrees() unconditionally at every recreation — including on the same connect transition. In practice the in-flight ref dedupes this, relying on effect execution order to avoid a real double RPC. Please confirm this overlap is intentional (the PR summary only calls out removing the duplicate repo.list, not worktree.ps).


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0e5868e1-c872-4635-bb7e-f52f0a7ffce4

📥 Commits

Reviewing files that changed from the base of the PR and between 586cf78 and 46625fb.

📒 Files selected for processing (4)
  • mobile/app/h/[hostId]/index.tsx
  • mobile/src/transport/use-worktree-resync.ts
  • mobile/src/worktree/host-worktree-refresh.test.ts
  • mobile/src/worktree/host-worktree-refresh.ts

Comment thread mobile/app/h/[hostId]/index.tsx Resolved
@nwparker nwparker changed the title perf(mobile): gate host polling on foreground and make repo metadata event-driven perf(mobile): gate host polling on foreground/background Jul 22, 2026
…fect

Address CodeRabbit nitpick: the reconnect effect no longer calls fetchRepoMetadata
(that refetch moved into startHostWorktreeRefresh), so it shouldn't remain in the
effect's dependency array.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker merged commit 4468d54 into main Jul 22, 2026
2 checks passed
@nwparker
nwparker deleted the nwparker/perf-13-mobile-poll-gate branch July 22, 2026 21:12
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* perf(mobile): gate host polling on foreground

The mobile host screen ran two 3s polls (routed + embedded), each firing worktree.ps
AND repo.list, with no foreground/background gate — so a connected phone kept pinging
every 3s (worktree.ps is a full multi-repo process scan) plus a radio wakeup, including
brief background windows while the socket stays parked.

Consolidate both into one startHostWorktreeRefresh lifecycle and AppState-gate the
interval so BOTH polls stop while backgrounded and refresh immediately on foreground
return. worktree.ps keeps its 3s cadence while foregrounded (it carries live agent
status/preview/unread that no push event replaces). repo.list stays on the interval as
an AppState-gated, self-throttling (REPO_METADATA_REFRESH_MS=60s) convergence safety-net
— desktop Settings repo edits notify only the renderer, not the runtime clientEvents
stream, so it can't be made purely event-driven without going stale — and additionally
gets a reposChanged/worktreesChanged fast-path and reconnect-replay refetch.

Verified in a deps-installed mobile checkout: full mobile suite 2232 pass, typecheck,
oxlint (within the frozen max-lines budget), and oxfmt --check all clean.

Co-authored-by: Orca <[email protected]>

* chore(mobile): drop stale fetchRepoMetadata dep from the reconnect effect

Address CodeRabbit nitpick: the reconnect effect no longer calls fetchRepoMetadata
(that refetch moved into startHostWorktreeRefresh), so it shouldn't remain in the
effect's dependency array.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
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