Repository navigation
refactor(renderer): unify the window park-visibility primitive - #13778
Conversation
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`).
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThe 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 🚥 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 |
…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`).
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) andwindow-visibility-subscription-parking.ts(#13621) had each grown their own private copy of the same concept:isWindowVisible() || isDocumentVisibilityProvenStale(), subscribed viavisibilitychangeplusregisterStaleDocumentVisibilityRecovery(the stale latch flips to proven-visible without emitting avisibilitychange, so a listener on the event alone wedges hidden forever).Extracted to
src/renderer/src/lib/window-park-visibility.ts:getWindowParkVisible()— the predicatesubscribeWindowParkVisibility(onChange)— both signal sources, one disposerWINDOW_HIDE_PARK_GRACE_MSThe 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:
subscribealways applies thetypeof document !== 'undefined' && typeof document.addEventListener === 'function'guard. The parking side already had it; the hook did not. Unobservable in jsdom/happy-dom, strictly safer wheredocumentis absent.visibilitychange. That matters becauseregisterStaleDocumentVisibilityRecoveryinstalls the stale module's ownvisibilitychangehandler (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-goingvisibilitychangearriving 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_MSwas never a third constant.use-emulator-stream-window-visibility.tsis 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_MSis the shared grace window; the backoff multiplier stays entirely on the parking side.WINDOW_STREAM_PARK_DELAY_MSandWINDOW_VISIBILITY_SUBSCRIPTION_PARK_DELAY_MSboth 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
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:943looks structurally similar (document.visibilityState === 'visible' || isDocumentVisibilityProvenStale()) but sits inside the terminal hidden-delivery gate behind additional preconditions and treats anundefinedvisibilityStatedifferently fromisWindowVisible(). It is a delivery gate, not a park gate. Left alone.4.
useLayoutEffectin web-session-tabs-syncuseEffect->useLayoutEffectfor theactiveRuntimeEnvironmentIdRef/activeRuntimeWorktreeKeyRefwrites. 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:
installWindowVisibilitySubscriptionParkingcallsstartAll(false)at install, and both readers are gated onisVisibilityResume === true—onVisibilityResumeis only invoked underif (isVisibilityResume && restartingSpecIndexes.length > 0), andgetVisibilityResumePriorityis only reached through theisVisibilityResume ? sort(...) : ...branch. The real invariant is that resumes originate from thevisibilitychangelistener, 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.tsuse-window-stream-visibility.test.tsuse-remote-browser-stream-activation.test.tsemulator-device-frame-visibility.test.tsxemulator-screen-stream-content.test.tsxremote-browser-stream-lifecycle.test.tsweb-session-tabs-sync-window-visibility.test.tsxweb-session-tabs-sync-visibility-collision.test.tsxweb-session-tabs-sync.test.tsweb-session-tabs-sync-mirror-identity.test.tsweb-session-tabs-sync-remote-status-title-flap.test.tsPlus
oxlint,oxlint --config oxlint-code-quality-native-plugins.json --deny-warnings,oxlint --type-aware --deny-warnings, react-doctor, andcheck: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 🐋