Skip to content

refactor(renderer): unify the window park-visibility primitive - #13778

Merged
nwparker merged 1 commit into
mainfrom
nwparker/unify-window-visibility-parking
Aug 11, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/unify-window-visibility-parking

Conversation

@nwparker

@nwparker nwparker commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Deferred follow-up to the four visibility-gating perf PRs (#13608, #13621, #13622, #13634). Pure refactor — no behaviour change, no test file touched.

1. One park-visibility primitive, two thin consumers

use-window-stream-visibility.ts (#13608) and window-visibility-subscription-parking.ts (#13621) had each grown their own private copy of the same concept: isWindowVisible() || isDocumentVisibilityProvenStale(), subscribed via visibilitychange plus registerStaleDocumentVisibilityRecovery (the stale latch flips to proven-visible without emitting a visibilitychange, so a listener on the event alone wedges hidden forever).

Extracted to src/renderer/src/lib/window-park-visibility.ts:

  • getWindowParkVisible() — the predicate
  • subscribeWindowParkVisibility(onChange) — both signal sources, one disposer
  • WINDOW_HIDE_PARK_GRACE_MS

The two consumers stay shaped for their callers: the hook feeds the pair straight into useSyncExternalStore; the parking installer calls them imperatively. Neither consumer's exported surface changed, which is why no test needed editing.

Two incidental deltas, both in the safe direction:

  • The unified subscribe always applies the typeof document !== 'undefined' && typeof document.addEventListener === 'function' guard. The parking side already had it; the hook did not. Unobservable in jsdom/happy-dom, strictly safer where document is absent.
  • Registration order is now the parking side's: stale recovery first, then visibilitychange. That matters because registerStaleDocumentVisibilityRecovery installs the stale module's own visibilitychange handler (which clears the latch) on first registration. Registering first means the latch is cleared before our callback reads it — the hook previously had this backwards, so a real hidden-going visibilitychange arriving while the latch was set could have been read as visible.

2. The park-delay constants — shared base, not independent values

I went with (a): one shared base, hysteresis layered only on the parking side.

First, a correction to the premise: EMULATOR_STREAM_PARK_DELAY_MS was never a third constant. use-emulator-stream-window-visibility.ts is a pure re-export shim — WINDOW_STREAM_PARK_DELAY_MS as EMULATOR_STREAM_PARK_DELAY_MS. So there were exactly two literals.

The argument for keeping them separate is that #13621's value is now the base of an adaptive delay (doubling to 8x = 4s after a quickly-undone park, resetting after a hide that outlasts the ceiling) while #13608's is fixed. True, but it argues about the wrong layer. Both numbers answer the same question — how long must a hide last before I believe the user actually left? — and that answer is a property of user behaviour (a cmd-tab round trip), not of the resource being parked. The thing that genuinely differs is the cost of resuming, and that is already expressed separately and explicitly: WINDOW_VISIBILITY_SUBSCRIPTION_PARK_DELAY_BACKOFF_LIMIT = 8, documented as "resuming re-enumerates every host". Streams pay a lower resume cost and layer no backoff.

So: WINDOW_HIDE_PARK_GRACE_MS is the shared grace window; the backoff multiplier stays entirely on the parking side. WINDOW_STREAM_PARK_DELAY_MS and WINDOW_VISIBILITY_SUBSCRIPTION_PARK_DELAY_MS both keep their names and paths (call sites read better naming the site) but now derive from the base instead of agreeing by coincidence, each with a one-line WHY.

Option (b) was also unattractive mechanically: renaming the exported constants to advertise independence would have forced edits to five test files, which per the refactor rule is a smell rather than a licence.

3. Deliberately NOT folded in

  • perf(native-chat): suspend hidden transcript streams #13622 Native Chat and perf(editor): stop hidden panels duplicating remote reloads #13634 editor panels gate on renderer-authoritative Zustand routing state (isVisible && isWorktreeActive), not on OS visibility. Folding those into an OS-visibility abstraction would make a pane that is merely routed away look like a hidden window, and vice versa. Left alone.
  • pty-connection.ts:943 looks structurally similar (document.visibilityState === 'visible' || isDocumentVisibilityProvenStale()) but sits inside the terminal hidden-delivery gate behind additional preconditions and treats an undefined visibilityState differently from isWindowVisible(). It is a delivery gate, not a park gate. Left alone.

4. useLayoutEffect in web-session-tabs-sync

useEffect -> useLayoutEffect for the activeRuntimeEnvironmentIdRef / activeRuntimeWorktreeKeyRef writes. Passive effects flush after paint, so a resume firing in that gap reads the previous worktree's key — bounded and self-healing (resume stagger order, one omission fence one generation off), but free to close.

The comment above that block was checked and was indeed wrong. It claimed the refs were "declared first so the refs commit before the effects whose resume callbacks read them". The install effect reads neither ref: installWindowVisibilitySubscriptionParking calls startAll(false) at install, and both readers are gated on isVisibilityResume === true — onVisibilityResume is only invoked under if (isVisibilityResume && restartingSpecIndexes.length > 0), and getVisibilityResumePriority is only reached through the isVisibilityResume ? sort(...) : ... branch. The real invariant is that resumes originate from the visibilitychange listener, the stale-visibility recovery callback, or the park timer — all outside React render/commit — so the refs are always committed by then. Comment rewritten to say that.

Testing

Focused suites only (no full pnpm test/typecheck — concurrent agents). 198 tests, all passing unmodified:

  • window-visibility-subscription-parking.test.ts
  • use-window-stream-visibility.test.ts
  • use-remote-browser-stream-activation.test.ts
  • emulator-device-frame-visibility.test.tsx
  • emulator-screen-stream-content.test.tsx
  • remote-browser-stream-lifecycle.test.ts
  • web-session-tabs-sync-window-visibility.test.tsx
  • web-session-tabs-sync-visibility-collision.test.tsx
  • web-session-tabs-sync.test.ts
  • web-session-tabs-sync-mirror-identity.test.ts
  • web-session-tabs-sync-remote-status-title-flap.test.ts

Plus oxlint, oxlint --config oxlint-code-quality-native-plugins.json --deny-warnings, oxlint --type-aware --deny-warnings, react-doctor, and check:max-lines-ratchet (no suppression added or bumped; the parking module got 12 lines shorter).

Nothing here touches IPC, RPC params, stream opcodes, published content, git invocation, or path handling — remote wire compatibility, SSH hosts, folder workspaces, and Windows/Linux are unaffected.

Made with Orca 🐋

The stream-gating hook (#13608) and the subscription parking installer
(#13621) each reimplemented `isWindowVisible() || isDocumentVisibilityProvenStale()`
plus its visibilitychange + stale-recovery subscription, and each carried
its own 500ms park delay that agreed only by coincidence.

Extract both into `lib/window-park-visibility.ts` and leave the two
consumers as thin wrappers: `useWindowStreamVisible` feeds the snapshot
and subscribe into `useSyncExternalStore`, the parking installer calls
them imperatively. The subscribe now always uses the defensive
`typeof document` guard the parking side already had, and registers
stale recovery before the visibilitychange listener so the stale latch
is cleared before the callback reads it.

Both park delays now derive from one `WINDOW_HIDE_PARK_GRACE_MS`: they
debounce the same signal against the same user behaviour (a quick
app-switch round trip). The parking side's 8x reveal-side backoff stays
where it is - that models its own resume cost, not the grace window.

Renderer-authoritative gating (#13622 native chat, #13634 editor panels)
is deliberately left alone; it keys off Zustand routing state, not OS
visibility.

Also switch the active-runtime ref writes in web-session-tabs-sync to
`useLayoutEffect` so no resume event can land between paint and the
passive flush, and correct the stale comment above them - the install
effect reads neither ref (both readers are gated on `isVisibilityResume`).
@coderabbitai

coderabbitai Bot commented Aug 11, 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 Plus

Run ID: 4feea64d-8cf6-4e57-a284-0f75c3c71f79

📥 Commits

Reviewing files that changed from the base of the PR and between b3965f3 and 577b837.

📒 Files selected for processing (4)
  • src/renderer/src/hooks/use-window-stream-visibility.ts
  • src/renderer/src/lib/window-park-visibility.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
  • src/renderer/src/runtime/window-visibility-subscription-parking.ts

📝 Walkthrough

Walkthrough

The renderer now uses shared window-park visibility helpers for stream visibility and subscription parking. The helpers combine native visibility changes with stale-document recovery and define a shared 500 ms grace period. Subscription parking uses the shared visibility state for initialization, reconciliation, delayed checks, and cleanup. Runtime identity refs are committed with useLayoutEffect before visibility callbacks can read them.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a detailed summary and focused test results, but it omits or incompletely addresses several required template sections. Add the required Screenshots, AI Review Report, Security Audit, and Notes sections; state “No visual change” and explain each unchecked test.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: unifying the renderer window park-visibility primitive.
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.

@nwparker
nwparker merged commit 0aa7d0b into main Aug 11, 2026
45 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#13778)

The stream-gating hook (stablyai#13608) and the subscription parking installer
(stablyai#13621) each reimplemented `isWindowVisible() || isDocumentVisibilityProvenStale()`
plus its visibilitychange + stale-recovery subscription, and each carried
its own 500ms park delay that agreed only by coincidence.

Extract both into `lib/window-park-visibility.ts` and leave the two
consumers as thin wrappers: `useWindowStreamVisible` feeds the snapshot
and subscribe into `useSyncExternalStore`, the parking installer calls
them imperatively. The subscribe now always uses the defensive
`typeof document` guard the parking side already had, and registers
stale recovery before the visibilitychange listener so the stale latch
is cleared before the callback reads it.

Both park delays now derive from one `WINDOW_HIDE_PARK_GRACE_MS`: they
debounce the same signal against the same user behaviour (a quick
app-switch round trip). The parking side's 8x reveal-side backoff stays
where it is - that models its own resume cost, not the grace window.

Renderer-authoritative gating (stablyai#13622 native chat, stablyai#13634 editor panels)
is deliberately left alone; it keys off Zustand routing state, not OS
visibility.

Also switch the active-runtime ref writes in web-session-tabs-sync to
`useLayoutEffect` so no resume event can land between paint and the
passive flush, and correct the stale comment above them - the install
effect reads neither ref (both readers are gated on `isVisibilityResume`).
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