perf: pause checks polling while hidden (#2607)

This commit is contained in:
Neil
2026-05-21 23:15:25 -07:00
committed by GitHub
parent 9a41f5bc9b
commit a509e6e1a6
3 changed files with 217 additions and 31 deletions
@@ -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<HTMLInputElement>(null)
const pollRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const pollIntervalRef = useRef(30_000) // start at 30s, backs off to 120s
const prevChecksRef = useRef<string>('')
const conflictSummaryRefreshKeyRef = useRef<string | null>(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).
@@ -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<typeof setTimeout>)
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<string, () => void>()
const run = vi.fn().mockResolvedValue(undefined)
const setTimeoutMock = vi.fn(() => 1 as unknown as ReturnType<typeof setTimeout>)
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<string, () => void>()
let resolveRun!: () => void
const run = vi.fn(
() =>
new Promise<void>((resolve) => {
resolveRun = resolve
})
)
const setTimeoutMock = vi.fn(() => 1 as unknown as ReturnType<typeof setTimeout>)
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()
})
})
@@ -0,0 +1,79 @@
import { isWindowVisible } from './window-visibility-interval'
export type WindowVisibilityTimeoutPollerTimer = ReturnType<typeof setTimeout>
export function installWindowVisibilityTimeoutPoller(args: {
run: () => Promise<void> | 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)
}
}
}