Repository navigation
perf(main): park worktree metadata pollers while the window is hidden - #9849
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughWorktree polling now accepts a window-visibility contract. Base-directory and git-common polling use self-rescheduling timeouts, pause while hidden, and trigger forced scans when visibility resumes. Watcher wiring derives visibility from the active browser window and ignores events from disposed watches. Tests cover hidden-state suppression, resume behavior, headless and destroyed windows, HEAD updates, native stream forwarding, and cleanup. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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.
🧹 Nitpick comments (3)
src/main/ipc/worktree-base-directory-poller.ts (1)
260-308: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffOptional: extract the shared visibility-gated tick scaffold. All three loops repeat the same structure (
timer=null/disposed/park-on-hidden/tickingguard/reschedule +parkedWhileHiddenresume +unsubscribeteardown), diverging only in the per-tick body and the forced-scan flag. A smallcreateVisibilityGatedTicker({ pollIntervalMs, visibility, run })helper would remove the duplication and keep the concurrency/teardown invariants defined once.
src/main/ipc/worktree-base-directory-poller.ts#L260-L308: replace the inline tick/resume/unsubscribe with the shared ticker, passingrun(force) => poll(force).src/main/ipc/worktree-git-common-polling.ts#L243-L306: reuse the ticker, passing the git-common snapshot/diff body andforceIndexRead.src/main/ipc/worktree-git-common-watch.ts#L82-L137: reuse the ticker for the snapshot-diff body (no force flag).src/main/ipc/worktree-base-directory-poller.test.ts (1)
18-48: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate visibility-harness helper; extract to a shared test util.
createVisibilityHarness()here is structurally identical to the one added insrc/main/ipc/worktree-git-common-watch.test.ts(lines 28-56). Extracting a single shared helper (e.g. under a test-utils module) avoids drift between the two copies. While extracting, consider a short comment on thelistener === nextListenerguard (lines 33-35) explaining that it exists to prevent a stale unsubscribe call from clearing a listener registered by a later subscription.See consolidated comment for the paired site in
worktree-git-common-watch.test.ts.Source: Coding guidelines
src/main/ipc/worktree-git-common-watch.test.ts (1)
23-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate visibility-harness helper; extract to a shared test util.
Same
createVisibilityHarness()shape assrc/main/ipc/worktree-base-directory-poller.test.ts(lines 18-48). See consolidated comment.Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 5e603cfe-5299-4486-997c-bc8ce3a09107
📒 Files selected for processing (7)
src/main/ipc/worktree-base-directory-poller.test.tssrc/main/ipc/worktree-base-directory-poller.tssrc/main/ipc/worktree-base-directory-watcher.test.tssrc/main/ipc/worktree-base-directory-watcher.tssrc/main/ipc/worktree-git-common-polling.tssrc/main/ipc/worktree-git-common-watch.test.tssrc/main/ipc/worktree-git-common-watch.ts
8b8ccfd to
f784f65
Compare
|
Adversarial review pass (independent frontier model) found and I fixed one real regression, and cleared everything else: Fixed (was a real regression): an Pre-existing, out of scope (not introduced here): during the macOS dock-reactivation rebind gap the destroyed window is treated as visible, so a due tick can advance the baseline while Cleared: no timer-stall interleaving, lossless resume for all three pollers, per-watch visibility re-checked under the global signal, darwin native watcher fully ungated, gap-after-completion cadence + |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/ipc/worktree-base-directory-watcher.ts (1)
198-205: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocument the lifecycle rationale for these guards.
The disposed-watch check and active-watch visibility fallback are non-obvious TypeScript lifecycle constraints. Add concise comments explaining why these checks are required.
As per coding guidelines: “For non-obvious TypeScript code, add a concise comment explaining why the constraint exists, not how the code works.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 0c596968-a6b5-4e31-8e6b-b1a7036055e1
📒 Files selected for processing (7)
src/main/ipc/worktree-base-directory-poller.test.tssrc/main/ipc/worktree-base-directory-poller.tssrc/main/ipc/worktree-base-directory-watcher.test.tssrc/main/ipc/worktree-base-directory-watcher.tssrc/main/ipc/worktree-git-common-polling.tssrc/main/ipc/worktree-git-common-watch.test.tssrc/main/ipc/worktree-git-common-watch.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- src/main/ipc/worktree-base-directory-watcher.test.ts
- src/main/ipc/worktree-git-common-polling.ts
- src/main/ipc/worktree-base-directory-poller.test.ts
- src/main/ipc/worktree-git-common-watch.ts
- src/main/ipc/worktree-git-common-watch.test.ts
- src/main/ipc/worktree-base-directory-poller.ts
| if (currentWatch && !currentWatch.disposed) { | ||
| handleLocalWatchEvents(currentWatch, null, events) | ||
| } | ||
| handleLocalWatchEvents(currentWatch, null, events) | ||
| }, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -n -C 10 'activeWatches\.(set|delete|get)|subscribeTarget|unsubscribe|disposed' \
src/main/ipc/worktree-base-directory-watcher.ts
rg -n -C 12 'unsubscribe|callback|timer|disposed' \
src/main/ipc/worktree-base-directory-poller.tsRepository: stablyai/orca
Length of output: 14033
🏁 Script executed:
#!/bin/bash
sed -n '218,310p' src/main/ipc/worktree-base-directory-watcher.ts
sed -n '1,120p' src/main/ipc/worktree-base-directory-watcher.tsRepository: stablyai/orca
Length of output: 7476
🏁 Script executed:
sed -n '211,330p' src/main/ipc/worktree-base-directory-poller.tsRepository: stablyai/orca
Length of output: 3701
Bind the callback to the originating watch. target.key can be reused, so a stale poll result can be routed to a newly created watch with the same key; capture the watch reference or a per-subscription token before dispatching.
4dedb21 to
16455fd
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/main/ipc/worktree-base-directory-watcher.ts (1)
197-204: 🎯 Functional Correctness | 🟡 MinorBind poller callbacks to the originating watch, not only its key.
The callback now checks whether
activeWatches.get(target.key)exists and is not disposed, buttarget.keycan be reused while the previous subscription is still unwinding. A stale event from the old poller can therefore be delivered to the replacement watch. Capture the originating watch or a per-subscription token and require identity matching before callinghandleLocalWatchEvents; apply the same binding to the visibility callback.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 3e742e51-6464-44a8-89b3-ff42b9177e76
📥 Commits
Reviewing files that changed from the base of the PR and between 97922aae596583f85a1634454a8d4f08e8880d99 and 4dedb210c130fe90884c9a1d09d63bc0fb08a2d9.
📒 Files selected for processing (1)
src/main/ipc/worktree-base-directory-watcher.ts
The per-repo worktree metadata pollers ran 24/7 with no window-visibility gate (~50 fs.stat/sec at 20 repos on macOS while the window is hidden). Park the poll timers while the window is hidden and resume losslessly (immediate fresh-vs-retained snapshot diff) on reveal, via an injected WorktreePollerWindowVisibility mirroring the ssh-port-scanner pattern. Only the poll timers are gated; the darwin native worktrees/ fsevents watch and its teardown/re-arm lifecycle stay always-on (push-based, ~0 idle cost; #8732 race). A window is parked only once it has actually been shown and is now hidden: a live never-shown window (ORCA_E2E_HEADLESS keeps one) and null/destroyed windows stay always-visible, so a windowless/headless host never permanently parks the poller. Co-authored-by: Orca <[email protected]>
…out change Parking the pollers moved them from setInterval to a one-shot setTimeout chain, but scheduling the next tick a full pollIntervalMs AFTER each scan completed turned the cadence into gap-after-completion — every visible refresh landed ~one scan-duration late per tick. Measure from tick start and schedule max(0, interval - elapsed) so the cadence is start-to-start like the original interval, while keeping the one-shot chain that park/resume needs. Co-authored-by: Orca <[email protected]>
Date.now() is not monotonic: a backward wall-clock jump (NTP correction) during a scan makes (now - startedAt) negative, so the start-to-start delay pollIntervalMs - elapsed would exceed one interval by the adjustment — suppressing visible metadata refreshes for minutes/hours, unlike the former setInterval. Cap the computed delay at pollIntervalMs (upper) as well as 0 (lower) in all three pollers. Co-authored-by: Orca <[email protected]>
…ines The visibility-parking change pushed worktree-base-directory-watcher.ts to 303 code lines (limit 300). clearTimeout tolerates null/undefined, so the two truthy guards around it are redundant — remove them (coalescing null→undefined for the type). No behavior change; back under the limit without an eslint-disable. Co-authored-by: Orca <[email protected]>
16455fd to
a8f397a
Compare
…stablyai#9849) * perf(main): park worktree pollers while hidden The per-repo worktree metadata pollers ran 24/7 with no window-visibility gate (~50 fs.stat/sec at 20 repos on macOS while the window is hidden). Park the poll timers while the window is hidden and resume losslessly (immediate fresh-vs-retained snapshot diff) on reveal, via an injected WorktreePollerWindowVisibility mirroring the ssh-port-scanner pattern. Only the poll timers are gated; the darwin native worktrees/ fsevents watch and its teardown/re-arm lifecycle stay always-on (push-based, ~0 idle cost; stablyai#8732 race). A window is parked only once it has actually been shown and is now hidden: a live never-shown window (ORCA_E2E_HEADLESS keeps one) and null/destroyed windows stay always-visible, so a windowless/headless host never permanently parks the poller. Co-authored-by: Orca <[email protected]> * fix(main): keep start-to-start poller cadence after the interval→timeout change Parking the pollers moved them from setInterval to a one-shot setTimeout chain, but scheduling the next tick a full pollIntervalMs AFTER each scan completed turned the cadence into gap-after-completion — every visible refresh landed ~one scan-duration late per tick. Measure from tick start and schedule max(0, interval - elapsed) so the cadence is start-to-start like the original interval, while keeping the one-shot chain that park/resume needs. Co-authored-by: Orca <[email protected]> * fix(main): clamp poller reschedule delay to [0, pollIntervalMs] Date.now() is not monotonic: a backward wall-clock jump (NTP correction) during a scan makes (now - startedAt) negative, so the start-to-start delay pollIntervalMs - elapsed would exceed one interval by the adjustment — suppressing visible metadata refreshes for minutes/hours, unlike the former setInterval. Cap the computed delay at pollIntervalMs (upper) as well as 0 (lower) in all three pollers. Co-authored-by: Orca <[email protected]> * refactor(main): drop redundant notifyTimer guards to stay under max-lines The visibility-parking change pushed worktree-base-directory-watcher.ts to 303 code lines (limit 300). clearTimeout tolerates null/undefined, so the two truthy guards around it are redundant — remove them (coalescing null→undefined for the type). No behavior change; back under the limit without an eslint-disable. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
What
The per-repo worktree metadata pollers ran 24/7 with no window-visibility gate. At ~20 repos on macOS that's ~50
fs.statsyscalls/sec continuously, even while the Orca window is hidden/minimized — pure idle-battery drain. This parks the poll timers while the window is hidden and resumes losslessly when it becomes visible again.WorktreePollerWindowVisibility(mirrors the shippedssh-port-scannerpark/resume pattern). Production adapter follows eachActiveWatch.mainWindow; anull/destroyed window is treated as always visible so headless/orca serveand the macOS window-recreation gap never park.setIntervalto a one-shotsetTimeoutchain that checks visibility before the stat fan-out: if hidden, it parks (parkedWhileHidden = true, no reschedule) without touching the retained snapshot.onWindowBecameVisibleresumes with an immediate tick that diffs a fresh snapshot against the retained pre-hide snapshot (base forces a full scan; git-common forces the linked-index leaf read), so anything changed while hidden surfaces on reveal.worktrees/fsevents watcher, its teardown/re-arm lifecycle, and the directory-existence poll stay always-on (push-based, ~0 idle cost; parking it would risk the [Bug]: app crashes #8732 teardown heap-corruption race).ELI5
When Orca was hidden, it still poked your disk ~50 times a second per second to notice git changes across all your repos — for windows you couldn't even see, draining battery. Now it stops poking while hidden and, the moment you come back, does one fresh check that catches anything that changed while it was away. The always-on native file watcher (which is basically free) keeps running so nothing is missed on macOS.
Proof of zero regression
git worktree add/remove, commit, or HEAD move made while hidden is detected on reveal (covered by tests).null/destroyed window ⇒ always visible ⇒ polls normally, so a windowless host is never starved (tested).logs/HEADis still stat'd directly every tick.worktree-base-directory-poller.test.ts,worktree-git-common-watch.test.ts,worktree-base-directory-watcher.test.ts— 45/45 pass (verified in main worktree, not just the author's). New cases: no scans while hidden, hidden add/HEAD-move detected on reveal, null-window & destroyed-window exemptions, native watcher stays subscribed while hidden.pnpm typecheck:node: clean.oxlint+ max-lines ratchet: pass.Proof of perf improvement
While the window is hidden/minimized this parks ~50 local
fs.stat/sec at 20 repos (5 primary-metadata stats per 2s per repo, plus the Windows/Linux readdir + per-linked-worktree structural fan-out). The tests assert the poll body (onFullScan/snapshot) does not run while hidden — directly proving the syscalls stop — and that a reveal triggers exactly one immediate catch-up scan. Pure background/idle battery win; zero cost while visible, and the always-on native fsevents watch means no missed events on macOS.Made with Orca 🐋