Skip to content

perf(worktree): park the git-common existence poll while the window is hidden - #10528

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/p2-git-common-existence-poll
Jul 25, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/p2-git-common-existence-poll

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Problem

startGitCommonNarrowWatch (src/main/ipc/worktree-git-common-watch.ts) is the only watch entry point that never received the WorktreePollerWindowVisibility object. Every sibling takes one:

  • startSnapshotDiffPoller parks on isWindowVisible() and re-arms via onWindowBecameVisible
  • startGitCommonPolling (the non-darwin branch) is handed visibility and gates the same way

At the call site the two darwin watches start side by side — the primary-metadata poller got visibility, the narrow watch did not.

Inside, armExistencePoll ran a bare setInterval (2s default) that stats <common>/.git/worktrees every tick to detect the first linked worktree appearing. Nothing parked it when the window was hidden, so a repo with no linked worktree kept paying ~0.5 stat/sec forever with the app in the background — 0.5×N across N such repos.

Scope: macOS only. The narrow watch is the platform === 'darwin' branch of startGitCommonWatch; every other platform already goes through startGitCommonPolling, which is gated.

Fix

Thread WorktreePollerWindowVisibility into startGitCommonNarrowWatch and match startSnapshotDiffPoller's existing park/re-arm pattern rather than inventing a second mechanism:

  • the poll skips its work and clearIntervals itself on the first tick that observes a hidden window (and never arms at all if the window is already hidden)
  • onWindowBecameVisible re-checks immediately instead of waiting a full interval, then resumes the interval if the dir still isn't there
  • the create-event notification is preserved: a worktrees/ dir that appeared while hidden still upgrades to the native stream and emits {type:'create'} on show, so the repo's worktree list refreshes
  • the visibility listener is unsubscribed in the dispose path (no leak)

The existing subscribe-attempt body is extracted to tryUpgradeToNarrowWatch so the interval and the became-visible re-check share one path. No other restructuring.

Tests

src/main/ipc/worktree-git-common-watch.test.ts. The visibility harness now holds a set of listeners rather than one slot — the darwin path parks two independent watches, and a single slot silently dropped the narrow watch's registration. node:fs/promises#stat is wrapped with a delegating recorder so a test can assert on stat targets directly rather than on a proxy signal.

New cases:

  • parks the existence poll while the window is hidden — creates worktrees/ while hidden, asserts zero stats of that path, no subscribe, no events
  • re-checks on show and still reports a worktrees dir created while hidden — asserts nothing happened while hidden, then that show() stats synchronously (promptly, not an interval later), subscribes, and emits the create
  • drops both visibility subscriptions on dispose — listener count 2 → 0
  • resumes polling when the dir is still absent on show and keeps polling and reporting while the window stays visible — visible-path behavior unchanged (these are controls; they pass with and without the fix)

Revert check

Source change reverted, tests kept — 3 of the 5 new tests fail, and the 2 control tests pass as intended:

× parks the existence poll while the window is hidden
    AssertionError: expected [ Array(1) ] to have a length of +0 but got 1
    at worktree-git-common-watch.test.ts:257  (statCalls.filter(path => path === worktreesDir))
× re-checks on show and still reports a worktrees dir created while hidden
    AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
× drops both visibility subscriptions on dispose
    AssertionError: expected 1 to be 2

Tests  3 failed | 16 passed (19)

With the fix: Tests 19 passed (19).

pnpm run typecheck and pnpm run lint both exit 0.

…s hidden

startGitCommonNarrowWatch was the only watch entry point that never received
WorktreePollerWindowVisibility, so its `worktrees/` existence poll kept
stat'ing every repo without a linked worktree forever in the background
(0.5 stat/sec/repo at the 2s default). Its siblings — the primary-metadata
snapshot poller and the non-darwin git-common polling — already park.

Threads visibility through and matches the snapshot poller's park/re-arm
pattern: the poll stops on the first hidden tick, and re-checks immediately on
onWindowBecameVisible so a worktrees dir created while hidden still upgrades to
the native stream and emits its create event. The visibility listener is
dropped in the dispose path.

darwin-only: the narrow watch is the `platform === 'darwin'` branch.
@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Darwin worktree existence polling now receives window visibility state, pauses while hidden, and immediately retries when the window becomes visible. The watch removes its visibility listener during unsubscription. Tests add filesystem stat tracking, multi-listener visibility handling, and coverage for hidden polling, visible resumption, event forwarding, continued polling, and listener cleanup.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, but it does not follow the required template and is missing several required sections. Rewrite it using the repository template and add Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: pausing the git-common existence poll while the window is hidden.
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.

🧹 Nitpick comments (1)
src/main/ipc/worktree-git-common-watch.ts (1)

211-221: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Consider swallowing rejections on the void-ed upgrade promise.

tryUpgradeToNarrowWatch only rejects if the onEvents consumer throws, but .finally() re-throws it on a promise nobody handles — an unhandled rejection in the main process. Re-arming still happens either way.

♻️ Proposed guard
-    void tryUpgradeToNarrowWatch().finally(() => {
-      armExistencePoll()
-    })
+    void tryUpgradeToNarrowWatch()
+      .catch(() => {})
+      .finally(() => {
+        armExistencePoll()
+      })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2d3bc0b6-4816-417c-bc85-d25bef085691

📥 Commits

Reviewing files that changed from the base of the PR and between e1eca7f and 7fe8a13.

📒 Files selected for processing (2)
  • src/main/ipc/worktree-git-common-watch.test.ts
  • src/main/ipc/worktree-git-common-watch.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Re: CodeRabbit — "Consider swallowing rejections on the void-ed upgrade promise" (worktree-git-common-watch.ts:211-221)

Declining, with reasoning.

The observation is technically correct: tryUpgradeToNarrowWatch() can only reject if the onEvents consumer throws (trySubscribe catches everything itself and returns a boolean), and .finally() does propagate that rejection onto a promise that void leaves unhandled. But three things make the one-line .catch(() => {}) the wrong change here:

  1. The consequence is a log line, not a crash. The main process installs a global handler at src/main/startup/main-process-error-guards.ts:127 (installUnhandledRejectionLogging) that records the rejection via recordFatalMainProcessError and deliberately keeps the app alive — that guard exists precisely so one failed background promise cannot kill the app (issue [Bug]: macOS app exits during startup when restoring a persisted profile (v1.4.146) #9441). So this is not the Node-default process-exit hazard the suggestion implies.

  2. It is pre-existing, not introduced here. The pre-PR code was structurally identical:

    void trySubscribe()
      .then((installed) => { ... onEvents([{ type: 'create', path: worktreesDir }]) })
      .finally(() => { subscribing = false })

    An onEvents throw there rejected an equally unhandled void-ed chain. This PR moved that body into tryUpgradeToNarrowWatch; it did not create the hazard.

  3. Patching only this site would be misleading. The identical void tryUpgradeToNarrowWatch() call on the interval path (line 206) has exactly the same exposure and is untouched by the suggested diff. Guarding one of the two would read as "handled" while leaving the other live. If this is worth fixing it should be fixed for both call sites — and, consistently, for the sibling startSnapshotDiffPoller's void tick() at lines 132 and 135 — which is a separate change, not something to fold into a perf PR scoped to parking one poll.

Behavior is unaffected either way: armExistencePoll() in the .finally still runs on the rejecting path, and subscribing is reset by the finally block inside the async function, so no state is left corrupted.

Leaving as-is for scope. Verified alongside this: pnpm run typecheck and pnpm run lint exit 0, the max-lines ratchet reports no new bypasses, and CI verify is green.

@brennanb2025
brennanb2025 merged commit 70b4d12 into main Jul 25, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…s hidden (stablyai#10528)

startGitCommonNarrowWatch was the only watch entry point that never received
WorktreePollerWindowVisibility, so its `worktrees/` existence poll kept
stat'ing every repo without a linked worktree forever in the background
(0.5 stat/sec/repo at the 2s default). Its siblings — the primary-metadata
snapshot poller and the non-darwin git-common polling — already park.

Threads visibility through and matches the snapshot poller's park/re-arm
pattern: the poll stops on the first hidden tick, and re-checks immediately on
onWindowBecameVisible so a worktrees dir created while hidden still upgrades to
the native stream and emits its create event. The visibility listener is
dropped in the dispose path.

darwin-only: the narrow watch is the `platform === 'darwin'` branch.
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