From a509e6e1a65e45aeeae6b7fb3c1a9289aa77f358 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Thu, 21 May 2026 23:15:25 -0700 Subject: [PATCH] perf: pause checks polling while hidden (#2607) --- .../components/right-sidebar/ChecksPanel.tsx | 47 +++---- .../window-visibility-timeout-poller.test.ts | 122 ++++++++++++++++++ .../lib/window-visibility-timeout-poller.ts | 79 ++++++++++++ 3 files changed, 217 insertions(+), 31 deletions(-) create mode 100644 src/renderer/src/lib/window-visibility-timeout-poller.test.ts create mode 100644 src/renderer/src/lib/window-visibility-timeout-poller.ts diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index ec4895d2c..001941ce0 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -38,6 +38,7 @@ import { checksPanelAsyncResultKey, shouldCommitChecksPanelAsyncResult } from './checks-panel-async-result-key' +import { installWindowVisibilityTimeoutPoller } from '@/lib/window-visibility-timeout-poller' export default function ChecksPanel(): React.JSX.Element { const activeWorktree = useActiveWorktree() @@ -51,9 +52,15 @@ export default function ChecksPanel(): React.JSX.Element { (s) => s.getHostedReviewCreationEligibility ) const enqueueGitHubPRRefresh = useAppStore((s) => s.enqueueGitHubPRRefresh) - const gitConflictOperationByWorktree = useAppStore((s) => s.gitConflictOperationByWorktree) - const gitStatusByWorktree = useAppStore((s) => s.gitStatusByWorktree) - const remoteStatusesByWorktree = useAppStore((s) => s.remoteStatusesByWorktree) + const conflictOperation = useAppStore((s) => + activeWorktreeId ? (s.gitConflictOperationByWorktree[activeWorktreeId] ?? 'unknown') : 'unknown' + ) + const hasUncommittedChanges = useAppStore((s) => + activeWorktreeId ? (s.gitStatusByWorktree[activeWorktreeId]?.length ?? 0) > 0 : false + ) + const remoteStatus = useAppStore((s) => + activeWorktreeId ? s.remoteStatusesByWorktree[activeWorktreeId] : undefined + ) const pushBranch = useAppStore((s) => s.pushBranch) const fetchUpstreamStatus = useAppStore((s) => s.fetchUpstreamStatus) const setRightSidebarOpen = useAppStore((s) => s.setRightSidebarOpen) @@ -88,7 +95,6 @@ export default function ChecksPanel(): React.JSX.Element { const [titleDraft, setTitleDraft] = useState('') const [titleSaving, setTitleSaving] = useState(false) const titleInputRef = useRef(null) - const pollRef = useRef | null>(null) const pollIntervalRef = useRef(30_000) // start at 30s, backs off to 120s const prevChecksRef = useRef('') const conflictSummaryRefreshKeyRef = useRef(null) @@ -135,13 +141,6 @@ export default function ChecksPanel(): React.JSX.Element { prCacheKey ? s.prRefreshStates[prCacheKey] : undefined ) const prNumber = pr?.number ?? null - const remoteStatus = activeWorktreeId ? remoteStatusesByWorktree[activeWorktreeId] : undefined - const hasUncommittedChanges = activeWorktreeId - ? (gitStatusByWorktree[activeWorktreeId]?.length ?? 0) > 0 - : false - const conflictOperation = activeWorktreeId - ? (gitConflictOperationByWorktree[activeWorktreeId] ?? 'unknown') - : 'unknown' // Why: select only timestamps (not whole cache records) so the entry-refresh // effect doesn't re-run on every cache mutation. See @@ -388,26 +387,12 @@ export default function ChecksPanel(): React.JSX.Element { // Reset backoff state on PR change pollIntervalRef.current = 30_000 prevChecksRef.current = '' - let cancelled = false - void fetchChecks() - - const schedulePoll = (): void => { - pollRef.current = setTimeout(() => { - void fetchChecks().then(() => { - if (!cancelled) { - schedulePoll() - } - }) - }, pollIntervalRef.current) - } - schedulePoll() - - return () => { - cancelled = true - if (pollRef.current) { - clearTimeout(pollRef.current) - } - } + // Why: PR check status is user-visible when the panel is open. Keep visible + // unfocused windows fresh, but stop timers and API work while hidden. + return installWindowVisibilityTimeoutPoller({ + run: () => fetchChecks(), + getDelayMs: () => pollIntervalRef.current + }) }, [fetchChecks, isPanelVisible, prNumber]) // Fetch comments once when PR changes (no polling — comments change infrequently). diff --git a/src/renderer/src/lib/window-visibility-timeout-poller.test.ts b/src/renderer/src/lib/window-visibility-timeout-poller.test.ts new file mode 100644 index 000000000..4cf1ae7d3 --- /dev/null +++ b/src/renderer/src/lib/window-visibility-timeout-poller.test.ts @@ -0,0 +1,122 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { installWindowVisibilityTimeoutPoller } from './window-visibility-timeout-poller' + +describe('installWindowVisibilityTimeoutPoller', () => { + beforeEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + }) + + it('runs immediately while visible and schedules the next poll after completion', async () => { + const run = vi.fn().mockResolvedValue(undefined) + const setTimeoutMock = vi.fn(() => 1 as unknown as ReturnType) + const clearTimeoutMock = vi.fn() + + vi.stubGlobal('window', { + addEventListener: vi.fn(), + removeEventListener: vi.fn() + }) + vi.stubGlobal('document', { + visibilityState: 'visible', + addEventListener: vi.fn(), + removeEventListener: vi.fn() + }) + + const cleanup = installWindowVisibilityTimeoutPoller({ + run, + getDelayMs: () => 3000, + setTimeoutFn: setTimeoutMock, + clearTimeoutFn: clearTimeoutMock + }) + + expect(run).toHaveBeenCalledTimes(1) + await Promise.resolve() + expect(setTimeoutMock).toHaveBeenCalledWith(expect.any(Function), 3000) + + cleanup() + expect(clearTimeoutMock).toHaveBeenCalledWith(1) + }) + + it('pauses while hidden and refreshes immediately when visible again', async () => { + let visibilityState: DocumentVisibilityState = 'hidden' + const documentListeners = new Map void>() + const run = vi.fn().mockResolvedValue(undefined) + const setTimeoutMock = vi.fn(() => 1 as unknown as ReturnType) + const clearTimeoutMock = vi.fn() + + vi.stubGlobal('window', { + addEventListener: vi.fn(), + removeEventListener: vi.fn() + }) + vi.stubGlobal('document', { + get visibilityState() { + return visibilityState + }, + addEventListener: vi.fn((event: string, listener: () => void) => { + documentListeners.set(event, listener) + }), + removeEventListener: vi.fn() + }) + + const cleanup = installWindowVisibilityTimeoutPoller({ + run, + getDelayMs: () => 3000, + setTimeoutFn: setTimeoutMock, + clearTimeoutFn: clearTimeoutMock + }) + + expect(run).not.toHaveBeenCalled() + expect(setTimeoutMock).not.toHaveBeenCalled() + + visibilityState = 'visible' + documentListeners.get('visibilitychange')?.() + expect(run).toHaveBeenCalledTimes(1) + await Promise.resolve() + expect(setTimeoutMock).toHaveBeenCalledTimes(1) + + visibilityState = 'hidden' + documentListeners.get('visibilitychange')?.() + expect(clearTimeoutMock).toHaveBeenCalledWith(1) + + cleanup() + }) + + it('does not overlap focus refreshes while a poll is in flight', async () => { + const windowListeners = new Map void>() + let resolveRun!: () => void + const run = vi.fn( + () => + new Promise((resolve) => { + resolveRun = resolve + }) + ) + const setTimeoutMock = vi.fn(() => 1 as unknown as ReturnType) + + vi.stubGlobal('window', { + addEventListener: vi.fn((event: string, listener: () => void) => { + windowListeners.set(event, listener) + }), + removeEventListener: vi.fn() + }) + vi.stubGlobal('document', { + visibilityState: 'visible', + addEventListener: vi.fn(), + removeEventListener: vi.fn() + }) + + const cleanup = installWindowVisibilityTimeoutPoller({ + run, + getDelayMs: () => 3000, + setTimeoutFn: setTimeoutMock + }) + + expect(run).toHaveBeenCalledTimes(1) + windowListeners.get('focus')?.() + expect(run).toHaveBeenCalledTimes(1) + + resolveRun() + await Promise.resolve() + expect(setTimeoutMock).toHaveBeenCalledTimes(1) + cleanup() + }) +}) diff --git a/src/renderer/src/lib/window-visibility-timeout-poller.ts b/src/renderer/src/lib/window-visibility-timeout-poller.ts new file mode 100644 index 000000000..5f05e9488 --- /dev/null +++ b/src/renderer/src/lib/window-visibility-timeout-poller.ts @@ -0,0 +1,79 @@ +import { isWindowVisible } from './window-visibility-interval' + +export type WindowVisibilityTimeoutPollerTimer = ReturnType + +export function installWindowVisibilityTimeoutPoller(args: { + run: () => Promise | void + getDelayMs: () => number + setTimeoutFn?: (callback: () => void, delayMs: number) => WindowVisibilityTimeoutPollerTimer + clearTimeoutFn?: (handle: WindowVisibilityTimeoutPollerTimer) => void +}): () => void { + const setTimeoutFn = + args.setTimeoutFn ?? + ((callback: () => void, delayMs: number): WindowVisibilityTimeoutPollerTimer => + setTimeout(callback, delayMs)) + const clearTimeoutFn = + args.clearTimeoutFn ?? + ((handle: WindowVisibilityTimeoutPollerTimer): void => clearTimeout(handle)) + let timeoutId: WindowVisibilityTimeoutPollerTimer | null = null + let disposed = false + let inFlight = false + + const clearScheduledPoll = (): void => { + if (!timeoutId) { + return + } + clearTimeoutFn(timeoutId) + timeoutId = null + } + + const schedulePoll = (): void => { + clearScheduledPoll() + if (disposed || !isWindowVisible()) { + return + } + timeoutId = setTimeoutFn(() => { + timeoutId = null + runAndSchedule() + }, args.getDelayMs()) + } + + function runAndSchedule(): void { + clearScheduledPoll() + if (disposed || !isWindowVisible() || inFlight) { + return + } + inFlight = true + void Promise.resolve(args.run()).finally(() => { + inFlight = false + schedulePoll() + }) + } + + const reconcileVisibility = (): void => { + if (isWindowVisible()) { + runAndSchedule() + } else { + clearScheduledPoll() + } + } + + runAndSchedule() + if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') { + window.addEventListener('focus', reconcileVisibility) + } + if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') { + document.addEventListener('visibilitychange', reconcileVisibility) + } + + return () => { + disposed = true + clearScheduledPoll() + if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { + window.removeEventListener('focus', reconcileVisibility) + } + if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') { + document.removeEventListener('visibilitychange', reconcileVisibility) + } + } +}