Repository navigation
perf(mobile): gate host polling on foreground/background - #9857
Conversation
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]>
46625fb to
4b41534
Compare
|
Adversarial review caught one Major regression, now fixed: making |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds 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)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
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 winManual refresh silently drops the repo-metadata refresh if a fetch is already in flight.
onRefresh's forcedfetchRepoMetadata({ force: true })(line 37) omitsqueueIfInFlight: true, unlike every other forced call site (host-worktree-refresh.ts'sreposChanged/replay/foreground paths). If another fetch happens to be in flight when the user pulls to refresh,fetchRepoMetadatainindex.tsx(lines 365-370) will see the in-flight guard, skip queuing sincequeueIfInFlightis 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 winExport the shared option types instead of re-declaring them per file.
RepoRefreshOptions/WorktreeRefreshOptionsare file-local here, but the exact same shapes are duplicated inline inmobile/app/h/[hostId]/index.tsx(fetchRepoMetadata/fetchWorktreescallback signatures) andmobile/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 valueConsider 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 inhost-worktree-refresh.tsabout 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 valueLocal
nowshadows the outernowstate variable.
const now = Date.now()(line 371) shadows the component-levelnowfromuseNow(30_000)(line 157) used for row timestamps. No functional bug today since this localnownever escapes the callback, but the name collision invites future mistakes (e.g. accidentally reading the wrongnowif 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 valueStale
fetchRepoMetadatadependency, and possible duplicate reconnect worktrees fetch.
fetchRepoMetadatais still listed in the deps array (line 26) even though the body no longer calls it — harmless today (the ref-guard infetchWorktrees/fetchRepoMetadataprevents 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 everyconnStatetransition into'connected'(line 24), whileindex.tsx'sstartWorktreeRefresh(lines 505-527) is now recreated on everyconnStatechange too (sincefetchWorktrees/fetchRepoMetadatadepend onconnState), which itself callsfetchWorktrees()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 duplicaterepo.list, notworktree.ps).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 0e5868e1-c872-4635-bb7e-f52f0a7ffce4
📒 Files selected for processing (4)
mobile/app/h/[hostId]/index.tsxmobile/src/transport/use-worktree-resync.tsmobile/src/worktree/host-worktree-refresh.test.tsmobile/src/worktree/host-worktree-refresh.ts
…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]>
* 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]>
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) ANDrepo.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
startHostWorktreeRefreshlifecycle and AppState-gates the interval so both polls stop while backgrounded and refresh immediately on foreground return:worktree.pskeeps 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.liststays on the interval as an AppState-gated convergence safety-net (it self-throttles toREPO_METADATA_REFRESH_MS= 60s, so it's ~1 request/min while foregrounded), plus areposChanged/worktreesChangedfast-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
clientEventsstream mobile subscribes to — sorepo.listcannot 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.worktree.pspoll (agent status/preview/unread) is preserved; optimistic reconciliation still gets periodic confirmations while foreground and an immediate one on foreground return.ready-after-readyreplay), covering "events aren't queued while disconnected."pnpm typecheckclean, full mobile suite 2232 pass / 2 skipped (307 files),oxlintclean (within the frozen max-lines budget),oxfmt --checkclean. Tests cover: interval polls (worktrees + repo.list) while active and skips both while backgrounded; immediate foreground refresh;reposChanged/worktreesChangedrefetch; 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
notifyReposChangedtoOrcaRuntimeService.notifyReposChanged()so mobile gets an instant runtime event and the periodicrepo.listsafety-net could drop further. Left as a separate desktop-side change to keep this PR mobile-only.