From 6574e764d7afe0a18dbc41db00b4294321054a13 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 24 Jun 2026 00:21:56 -0700 Subject: [PATCH] Bound Windows PR refresh crash storms (#6203) Co-authored-by: Neil --- .../github/pr-refresh-coordinator.test.ts | 320 ++++++++++++++++++ src/main/github/pr-refresh-coordinator.ts | 152 ++++++++- src/main/ipc/github.test.ts | 52 +-- src/main/ipc/github.ts | 5 +- src/renderer/src/store/slices/github.test.ts | 120 +++++++ src/renderer/src/store/slices/github.ts | 59 ++-- 6 files changed, 644 insertions(+), 64 deletions(-) diff --git a/src/main/github/pr-refresh-coordinator.test.ts b/src/main/github/pr-refresh-coordinator.test.ts index 20d7b19ef..a341e097b 100644 --- a/src/main/github/pr-refresh-coordinator.test.ts +++ b/src/main/github/pr-refresh-coordinator.test.ts @@ -184,6 +184,326 @@ describe('pr-refresh-coordinator', () => { expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) }) + it('paces a burst of distinct active refreshes', async () => { + const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'upstream-error', + errorType: 'unknown', + message: 'missing upstream', + fetchedAt: Date.now() + }) + + for (let index = 0; index < 10; index += 1) { + enqueuePRRefresh( + makeCandidate({ + cacheKey: `/repo::feature/${index}`, + branch: `feature/${index}`, + worktreeId: `wt-${index}` + }), + 'active', + 80, + 1 + ) + } + + await vi.advanceTimersByTimeAsync(0) + + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3) + expect( + getPRForBranchOutcomeMock.mock.calls.map(([repoPath, branch]) => [repoPath, branch]) + ).toEqual([ + ['/repo', 'feature/9'], + ['/repo', 'feature/8'], + ['/repo', 'feature/7'] + ]) + + await vi.advanceTimersByTimeAsync(29_999) + + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3) + expect( + sendMock.mock.calls + .map(([, event]) => event) + .some((event) => event.reason === 'active' && event.status === 'queued') + ).toBe(true) + + await vi.advanceTimersByTimeAsync(1) + + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(6) + }) + + it('treats a same-key active reactivation as the latest active signal', async () => { + const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'upstream-error', + errorType: 'unknown', + message: 'missing upstream', + fetchedAt: Date.now() + }) + + for (let index = 0; index < 10; index += 1) { + enqueuePRRefresh( + makeCandidate({ + cacheKey: `/repo::feature/${index}`, + branch: `feature/${index}`, + worktreeId: `wt-${index}` + }), + 'active', + 80, + 1 + ) + } + await vi.advanceTimersByTimeAsync(0) + + enqueuePRRefresh( + makeCandidate({ + cacheKey: '/repo::feature/0', + branch: 'feature/0', + worktreeId: 'wt-0' + }), + 'active', + 80, + 1 + ) + await vi.advanceTimersByTimeAsync(30_000) + + expect(getPRForBranchOutcomeMock.mock.calls[3]?.[1]).toBe('feature/0') + }) + + it('does not let one capped active window block another window', async () => { + const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'upstream-error', + errorType: 'unknown', + message: 'missing upstream', + fetchedAt: Date.now() + }) + + for (let index = 0; index < 10; index += 1) { + enqueuePRRefresh( + makeCandidate({ + cacheKey: `/repo::feature/${index}`, + branch: `feature/${index}`, + worktreeId: `wt-${index}` + }), + 'active', + 80, + 1 + ) + } + enqueuePRRefresh( + makeCandidate({ + cacheKey: '/repo::feature/other-window', + branch: 'feature/other-window', + worktreeId: 'wt-other-window' + }), + 'active', + 80, + 2 + ) + + await vi.advanceTimersByTimeAsync(0) + + expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toContain( + 'feature/other-window' + ) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4) + }) + + it('does not let capped host active work block WSL or SSH active scopes', async () => { + const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'upstream-error', + errorType: 'unknown', + message: 'missing upstream', + fetchedAt: Date.now() + }) + + for (let index = 0; index < 10; index += 1) { + enqueuePRRefresh( + makeCandidate({ + cacheKey: `/repo::feature/${index}`, + branch: `feature/${index}`, + worktreeId: `wt-${index}` + }), + 'active', + 80, + 1 + ) + } + enqueuePRRefresh( + makeCandidate({ + cacheKey: 'wsl::repo-1::feature/wsl', + branch: 'feature/wsl', + localGitOptions: { wslDistro: 'Ubuntu' }, + worktreeId: 'wt-wsl' + }), + 'active', + 80, + 1 + ) + enqueuePRRefresh( + makeCandidate({ + cacheKey: 'ssh:ssh-1::repo-1::feature/ssh', + branch: 'feature/ssh', + connectionId: 'ssh-1', + worktreeId: 'wt-ssh' + }), + 'active', + 80, + 1 + ) + + await vi.advanceTimersByTimeAsync(0) + + const startedBranches = getPRForBranchOutcomeMock.mock.calls.map((call) => call[1]) + expect(startedBranches).toContain('feature/wsl') + expect(startedBranches).toContain('feature/ssh') + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(5) + }) + + it('does not let a capped active scope block ready visible work', async () => { + const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } = + await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'upstream-error', + errorType: 'unknown', + message: 'missing upstream', + fetchedAt: Date.now() + }) + + for (let index = 0; index < 10; index += 1) { + enqueuePRRefresh( + makeCandidate({ + cacheKey: `/repo::feature/${index}`, + branch: `feature/${index}`, + worktreeId: `wt-${index}` + }), + 'active', + 80, + 1 + ) + } + reportVisiblePRRefreshCandidates( + [ + makeCandidate({ + cacheKey: '/repo::feature/visible', + branch: 'feature/visible', + worktreeId: 'wt-visible' + }) + ], + 1, + 1 + ) + + await vi.advanceTimersByTimeAsync(0) + + expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toContain('feature/visible') + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4) + }) + + it('wakes for visible budget spacing before a capped active burst opens', async () => { + const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } = + await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'upstream-error', + errorType: 'unknown', + message: 'missing upstream', + fetchedAt: Date.now() + }) + + reportVisiblePRRefreshCandidates( + [ + makeCandidate({ + cacheKey: '/repo::feature/visible-first', + branch: 'feature/visible-first', + worktreeId: 'wt-visible-first' + }) + ], + 1, + 1 + ) + await vi.advanceTimersByTimeAsync(0) + + for (let index = 0; index < 10; index += 1) { + enqueuePRRefresh( + makeCandidate({ + cacheKey: `/repo::feature/${index}`, + branch: `feature/${index}`, + worktreeId: `wt-${index}` + }), + 'active', + 80, + 1 + ) + } + reportVisiblePRRefreshCandidates( + [ + makeCandidate({ + cacheKey: '/repo::feature/visible-second', + branch: 'feature/visible-second', + worktreeId: 'wt-visible-second' + }) + ], + 2, + 1 + ) + + await vi.advanceTimersByTimeAsync(0) + + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4) + + await vi.advanceTimersByTimeAsync(9_999) + + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4) + + await vi.advanceTimersByTimeAsync(1) + + expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toContain( + 'feature/visible-second' + ) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(5) + }) + + it('does not consume active burst slots for rate-limit pauses', async () => { + const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') + getRateLimitMock + .mockResolvedValueOnce({ ok: false }) + .mockResolvedValueOnce({ ok: false }) + .mockResolvedValueOnce({ ok: false }) + .mockResolvedValue({ ok: true }) + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'upstream-error', + errorType: 'unknown', + message: 'missing upstream', + fetchedAt: Date.now() + }) + + for (let index = 0; index < 6; index += 1) { + enqueuePRRefresh( + makeCandidate({ + cacheKey: `/repo::feature/${index}`, + branch: `feature/${index}`, + worktreeId: `wt-${index}` + }), + 'active', + 80, + 1 + ) + } + + await vi.advanceTimersByTimeAsync(0) + + const pausedEvents = sendMock.mock.calls + .map(([, event]) => event) + .filter((event) => event.status === 'paused' && event.skippedReason === 'rate-limit') + expect(pausedEvents).toHaveLength(3) + expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toEqual([ + 'feature/2', + 'feature/1', + 'feature/0' + ]) + }) + it('preserves an active refresh queued while a visible refresh is in flight', async () => { const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pr-refresh-coordinator.ts index 7dbb30f30..fc266ee5c 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pr-refresh-coordinator.ts @@ -21,7 +21,9 @@ type QueueEntry = { reason: GitHubPRRefreshReason priority: number dueAt: number + queuedAt: number bypassBackgroundBudget?: boolean + activeDelayNotified?: boolean windowId?: number } @@ -66,12 +68,16 @@ const POST_PUSH_DELAY_MS = 2_500 const BACKOFF_BASE_MS = 60_000 const BACKOFF_MAX_MS = 15 * 60_000 const DIAGNOSTIC_BREADCRUMB_MIN_INTERVAL_MS = 30_000 +const ACTIVE_BURST_WINDOW_MS = 30_000 +const ACTIVE_BURST_MAX = 3 let sequence = 0 +let queueOrder = 0 let draining = false let drainTimer: ReturnType | null = null const queue = new Map() const backgroundStarts: number[] = [] +const activeStartsByScope = new Map() const errorBackoff = new Map() let lastBackgroundStartAt = 0 const visibleByWindow = new Map }>() @@ -123,13 +129,23 @@ function recordPRRefreshQueueDiagnostic( }) } -export function clearVisiblePRRefreshWindow(windowId: number): void { - if (!visibleByWindow.delete(windowId)) { - return +function clearActiveBurstWindow(windowId: number): void { + const windowPrefix = `${windowId}::` + for (const scope of Array.from(activeStartsByScope.keys())) { + if (scope.startsWith(windowPrefix)) { + activeStartsByScope.delete(scope) + } + } +} + +export function clearVisiblePRRefreshWindow(windowId: number): void { + const hadVisibleRefreshes = visibleByWindow.delete(windowId) + clearActiveBurstWindow(windowId) + if (hadVisibleRefreshes) { + // Why: visible follow-ups are owned by the renderer that reported them. + // If that WebContents is destroyed, no later visibility report may arrive. + removeInvisibleVisibleRefreshes() } - // Why: visible follow-ups are owned by the renderer that reported them. - // If that WebContents is destroyed, no later visibility report may arrive. - removeInvisibleVisibleRefreshes() } function nextSequence(): number { @@ -137,6 +153,11 @@ function nextSequence(): number { return sequence } +function nextQueueOrder(): number { + queueOrder += 1 + return queueOrder +} + function broadcast(event: Omit, sequenceOverride?: number): void { const payload = { ...event, sequence: sequenceOverride ?? nextSequence() } as GitHubPRRefreshEvent for (const wc of webContents.getAllWebContents()) { @@ -358,6 +379,7 @@ function scheduleVisibleFollowUp( reason: 'visible', priority, dueAt: retryAt, + queuedAt: nextQueueOrder(), windowId }) // Why: this is a delayed retry, not active work; showing it as a spinner @@ -386,6 +408,7 @@ function scheduleVisibleFollowUp( reason: 'visible', priority, dueAt, + queuedAt: nextQueueOrder(), // Why: this manual one-shot fixes GitHub's transient UNKNOWN state; visible // spacing would otherwise delay it past the intended prompt retry window. bypassBackgroundBudget: pendingMergeabilityDueAt !== null, @@ -468,6 +491,80 @@ function nextBudgetDelay(): number { return Math.max(spacingDelay, windowDelay) } +function activeBurstScope(entry: QueueEntry): string { + const runtimeScope = entry.candidate.connectionId + ? `ssh:${entry.candidate.connectionId}` + : `local:${entry.candidate.localGitOptions?.wslDistro ?? 'host'}` + return `${entry.windowId ?? 'global'}::${runtimeScope}` +} + +function pruneActiveStarts(scope: string, now: number): number[] { + const activeStarts = activeStartsByScope.get(scope) ?? [] + while (activeStarts.length > 0 && now - activeStarts[0] >= ACTIVE_BURST_WINDOW_MS) { + activeStarts.shift() + } + if (activeStarts.length === 0) { + activeStartsByScope.delete(scope) + } else { + activeStartsByScope.set(scope, activeStarts) + } + return activeStarts +} + +function nextActiveBurstDelay(entry: QueueEntry): number { + const now = Date.now() + const activeStarts = pruneActiveStarts(activeBurstScope(entry), now) + if (activeStarts.length < ACTIVE_BURST_MAX) { + return 0 + } + return Math.max(1, ACTIVE_BURST_WINDOW_MS - (now - activeStarts[0])) +} + +function noteActiveStart(entry: QueueEntry): void { + const now = Date.now() + const scope = activeBurstScope(entry) + const activeStarts = pruneActiveStarts(scope, now) + activeStarts.push(now) + activeStartsByScope.set(scope, activeStarts) +} + +function activeOrder(a: QueueEntry, b: QueueEntry): number { + if (a.reason !== 'active' || b.reason !== 'active') { + return 0 + } + if (activeBurstScope(a) !== activeBurstScope(b)) { + return 0 + } + // Why: activation churn should refresh the worktree the user lands on before + // stale transient selections from the same window/runtime scope. + return b.queuedAt - a.queuedAt +} + +function entryDelay(entry: QueueEntry): number { + const activeBurstDelay = entry.reason === 'active' ? nextActiveBurstDelay(entry) : 0 + if (activeBurstDelay > 0) { + return activeBurstDelay + } + return isBudgetedQueueEntry(entry) ? nextBudgetDelay() : 0 +} + +function isActiveBurstDelayed(entry: QueueEntry): boolean { + return entry.reason === 'active' && nextActiveBurstDelay(entry) > 0 +} + +function nextQueuedWakeDelay(excludedKey: string): number | null { + const now = Date.now() + let nextDelay = Number.POSITIVE_INFINITY + for (const entry of queue.values()) { + if (entry.key === excludedKey) { + continue + } + const delay = entry.dueAt > now ? entry.dueAt - now : entryDelay(entry) + nextDelay = Math.min(nextDelay, delay) + } + return Number.isFinite(nextDelay) ? Math.max(0, nextDelay) : null +} + function scheduleDrain(delay = 0): void { if (drainTimer) { clearTimeout(drainTimer) @@ -484,7 +581,7 @@ function queuedEntriesByPriority(): QueueEntry[] { const aReady = a.dueAt <= now const bReady = b.dueAt <= now if (aReady && bReady) { - return b.priority - a.priority || a.dueAt - b.dueAt + return b.priority - a.priority || activeOrder(a, b) || a.dueAt - b.dueAt } if (aReady !== bReady) { return aReady ? -1 : 1 @@ -500,19 +597,37 @@ async function drainQueue(): Promise { draining = true try { while (queue.size > 0) { - const next = queuedEntriesByPriority()[0] + let next = queuedEntriesByPriority()[0] const waitMs = next.dueAt - Date.now() if (waitMs > 0) { scheduleDrain(waitMs) return } - const budgetDelay = isBudgetedQueueEntry(next) ? nextBudgetDelay() : 0 - if (budgetDelay > 0) { - diagnosticsCounters.backgroundPauses += 1 - recordPRRefreshQueueDiagnostic('background-pause', next.reason) - scheduleDrain(budgetDelay) - return + let delay = entryDelay(next) + if (delay > 0) { + const runnable = queuedEntriesByPriority().find( + (entry) => entry.dueAt <= Date.now() && entryDelay(entry) === 0 + ) + if (runnable && runnable.key !== next.key) { + next = runnable + delay = 0 + } else { + if (isActiveBurstDelayed(next) && !next.activeDelayNotified) { + next.activeDelayNotified = true + broadcast({ + aliases: Array.from(next.aliases.values()), + reason: next.reason, + status: 'queued' + }) + } + if (isBudgetedQueueEntry(next) && nextBudgetDelay() > 0) { + diagnosticsCounters.backgroundPauses += 1 + recordPRRefreshQueueDiagnostic('background-pause', next.reason) + } + scheduleDrain(Math.min(delay, nextQueuedWakeDelay(next.key) ?? delay)) + return + } } queue.delete(next.key) @@ -571,6 +686,11 @@ async function drainQueue(): Promise { if (isBudgetedQueueEntry(next)) { noteBackgroundStart() } + if (next.reason === 'active') { + // Why: activation is high priority, but tab/worktree churn can enqueue + // many distinct active refreshes that each probe local Git. + noteActiveStart(next) + } for (const bucket of buckets) { noteRateLimitSpend(bucket) } @@ -632,11 +752,14 @@ export function enqueuePRRefresh( const shouldPromoteExisting = priority > existing.priority || isManual(reason) || + (reason === 'active' && existing.reason === 'active') || (priority >= existing.priority && dueAt < existing.dueAt && bypassesFreshnessDelay(reason)) if (shouldPromoteExisting) { existing.priority = priority existing.reason = reason existing.dueAt = Math.min(existing.dueAt, dueAt) + existing.queuedAt = nextQueueOrder() + existing.activeDelayNotified = false existing.candidate = candidate existing.windowId = windowId ?? existing.windowId } @@ -650,6 +773,7 @@ export function enqueuePRRefresh( reason, priority, dueAt, + queuedAt: nextQueueOrder(), windowId }) } diff --git a/src/main/ipc/github.test.ts b/src/main/ipc/github.test.ts index d88912049..5b1612e85 100644 --- a/src/main/ipc/github.test.ts +++ b/src/main/ipc/github.test.ts @@ -384,38 +384,40 @@ describe('registerGitHubHandlers', () => { expect(refreshPRNowMock).not.toHaveBeenCalled() }) - it('filters invalid visible PR refresh candidates while keeping valid candidates', async () => { + it('skips stale visible PR refresh candidates without rejecting the batch', async () => { registerGitHubHandlers(store as never, stats as never) - await handlers['gh:reportVisiblePRRefreshCandidates']( - { sender: { id: 7, once: vi.fn() } }, - { - generation: 1, - candidates: [ - { - cacheKey: 'valid::feature/test', - repoPath: '/workspace/repo', - repoId: 'repo-1', - branch: 'feature/test', - repoKind: 'git' - }, - { - cacheKey: 'missing::feature/old', - repoPath: '/workspace/missing', - repoId: 'missing-repo', - branch: 'feature/old', - repoKind: 'git' - } - ] - } - ) + expect( + handlers['gh:reportVisiblePRRefreshCandidates']( + { sender: { id: 7, once: vi.fn() } }, + { + generation: 1, + candidates: [ + { + cacheKey: '/workspace/repo::feature/live', + repoPath: '/workspace/repo', + branch: 'feature/live', + repoKind: 'git', + repoId: 'repo-1' + }, + { + cacheKey: '/workspace/missing::feature/stale', + repoPath: '/workspace/missing', + branch: 'feature/stale', + repoKind: 'git', + repoId: 'repo-missing' + } + ] + } + ) + ).toBe(true) expect(reportVisiblePRRefreshCandidatesMock).toHaveBeenCalledWith( [ expect.objectContaining({ - cacheKey: 'valid::feature/test', repoPath: '/workspace/repo', - repoId: 'repo-1' + repoId: 'repo-1', + branch: 'feature/live' }) ], 1, diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts index 87b873e73..2a808f603 100644 --- a/src/main/ipc/github.ts +++ b/src/main/ipc/github.ts @@ -331,7 +331,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi ipcMain.handle( 'gh:enqueuePRRefresh', ( - _event, + event, args: { candidate: GitHubPRRefreshCandidate reason: GitHubPRRefreshReason @@ -342,7 +342,8 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi if (validation.kind === 'skipped') { return validation.result } - enqueuePRRefresh(validation.candidate, args.reason, args.priority ?? 0) + const senderWindowId = event?.sender?.id + enqueuePRRefresh(validation.candidate, args.reason, args.priority ?? 0, senderWindowId) return { kind: 'queued' } } ) diff --git a/src/renderer/src/store/slices/github.test.ts b/src/renderer/src/store/slices/github.test.ts index 823ed97e0..fb03f991c 100644 --- a/src/renderer/src/store/slices/github.test.ts +++ b/src/renderer/src/store/slices/github.test.ts @@ -3036,6 +3036,45 @@ describe('createGitHubSlice.refreshGitHubForWorktreeIfStale', () => { expect(mockApi.gh.refreshPRNow).toHaveBeenCalledTimes(1) }) + it('bounds rejected active PR refresh IPCs during worktree activation', async () => { + const store = createTestStore() + const repoPath = '/repo' + const branch = 'feature/test' + const worktreeId = 'wt-1' + const error = new Error('Access denied: unknown repository path') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + mockApi.gh.enqueuePRRefresh.mockRejectedValueOnce(error) + + store.setState({ + repos: [{ id: 'repo-1', path: repoPath, name: 'repo', kind: 'git' }], + worktreesByRepo: { + 'repo-1': [ + { + id: worktreeId, + repoId: 'repo-1', + path: '/repo/worktrees/test', + branch, + displayName: 'test', + isMainWorktree: false, + isBare: false, + isArchived: false + } + ] + }, + worktreeCardProperties: ['status', 'pr'] + } as unknown as Partial) + + try { + store.getState().refreshGitHubForWorktreeIfStale(worktreeId) + + await vi.waitFor(() => + expect(warn).toHaveBeenCalledWith('Failed to enqueue PR refresh:', error) + ) + } finally { + warn.mockRestore() + } + }) + it('enqueues active PR refresh with a GitHub hosted-review fallback number', () => { const store = createTestStore() const repoPath = '/repo' @@ -3527,6 +3566,49 @@ describe('createGitHubSlice.refreshAllGitHub', () => { }) }) + it('bounds rejected stale PR refresh IPCs', async () => { + const store = createTestStore() + const repoPath = '/repo' + const branch = 'feature/test' + const error = new Error('Access denied: unknown repository path') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + mockApi.gh.enqueuePRRefresh.mockRejectedValueOnce(error) + + store.setState({ + repos: [{ id: 'repo-1', path: repoPath, name: 'repo', kind: 'git' }], + groupBy: 'repo', + worktreeCardProperties: ['comment'], + activeWorktreeId: 'wt-1', + rightSidebarOpen: true, + rightSidebarTab: 'source-control', + worktreesByRepo: { + 'repo-1': [ + { + id: 'wt-1', + repoId: 'repo-1', + path: '/repo/worktrees/test', + branch, + displayName: 'test', + isMainWorktree: false, + isBare: false, + isArchived: false, + lastActivityAt: 1 + } + ] + } + } as unknown as Partial) + + try { + store.getState().refreshAllGitHub() + + await vi.waitFor(() => + expect(warn).toHaveBeenCalledWith('Failed to enqueue PR refresh:', error) + ) + } finally { + warn.mockRestore() + } + }) + it('refreshes runtime PR data directly instead of enqueueing local coordinator work', async () => { runtimeEnvironmentCall.mockResolvedValueOnce({ id: 'rpc-1', @@ -3696,6 +3778,44 @@ describe('createGitHubSlice.refreshGitHubForWorktree', () => { timeoutMs: 30_000 }) }) + + it('bounds rejected post-push PR refresh IPCs', async () => { + const store = createTestStore() + const repoPath = '/repo' + const branch = 'feature/test' + const worktreeId = 'wt-1' + const error = new Error('Access denied: unknown repository path') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + mockApi.gh.enqueuePRRefresh.mockRejectedValueOnce(error) + + store.setState({ + repos: [{ id: 'repo-1', path: repoPath, name: 'repo', kind: 'git' }], + worktreesByRepo: { + 'repo-1': [ + { + id: worktreeId, + repoId: 'repo-1', + path: '/repo/worktrees/test', + branch, + displayName: 'test', + isMainWorktree: false, + isBare: false, + isArchived: false + } + ] + } + } as unknown as Partial) + + try { + store.getState().refreshGitHubForWorktree(worktreeId) + + await vi.waitFor(() => + expect(warn).toHaveBeenCalledWith('Failed to enqueue PR refresh:', error) + ) + } finally { + warn.mockRestore() + } + }) }) describe('createGitHubSlice.fetchWorkItems source/error envelope', () => { diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index 495eaef72..9062068f2 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -170,6 +170,29 @@ function shouldEnqueueLocalPRRefresh(candidate: GitHubPRRefreshCandidate): boole return !candidate.connectionId || candidate.connectionState === 'connected' } +function enqueueLocalGitHubPRRefresh( + args: { + candidate: GitHubPRRefreshCandidate + reason: GitHubPRRefreshReason + priority: number + }, + onNotQueued?: () => void | Promise +): void { + const enqueue = window.api.gh.enqueuePRRefresh + if (!enqueue) { + return + } + // Why: main can reject stale/unknown local paths; renderer refresh triggers + // are best-effort and must not become unhandled rejection crash breadcrumbs. + void enqueue(args) + .then((queued) => + queued === false || queued?.kind === 'fallback' ? onNotQueued?.() : undefined + ) + .catch((err) => { + console.warn('Failed to enqueue PR refresh:', err) + }) +} + type GitHubWorkItemRequestContext = { repoId: string repoPath: string @@ -3437,26 +3460,16 @@ export const createGitHubSlice: StateCreator = (s if (!shouldEnqueueLocalPRRefresh(candidate)) { return } - const enqueue = window.api.gh.enqueuePRRefresh - if (enqueue) { - void enqueue({ candidate, reason, priority }) - .then((queued) => { - if (queued === false || queued.kind === 'fallback') { - return get().fetchPRForBranch(candidate.repoPath, candidate.branch, { - force: bypassesGitHubPRRefreshFreshness(reason), - repoId: candidate.repoId, - worktreeId: candidate.worktreeId, - linkedPRNumber: candidate.linkedPRNumber ?? null, - fallbackPRNumber: candidate.fallbackPRNumber ?? null, - fallbackPRSource: candidate.fallbackPRSource ?? null - }) - } - return null - }) - .catch((err) => { - console.warn('Failed to enqueue PR refresh:', err) - }) - } + enqueueLocalGitHubPRRefresh({ candidate, reason, priority }, async () => { + await get().fetchPRForBranch(candidate.repoPath, candidate.branch, { + force: bypassesGitHubPRRefreshFreshness(reason), + repoId: candidate.repoId, + worktreeId: candidate.worktreeId, + linkedPRNumber: candidate.linkedPRNumber ?? null, + fallbackPRNumber: candidate.fallbackPRNumber ?? null, + fallbackPRSource: candidate.fallbackPRSource ?? null + }) + }) }, reportVisibleGitHubPRRefreshCandidates: (worktreeIds, generation) => { @@ -3781,7 +3794,7 @@ export const createGitHubSlice: StateCreator = (s fallbackPRSource: candidate.fallbackPRSource ?? null }) } else if (shouldEnqueueLocalPRRefresh(candidate)) { - void window.api.gh.enqueuePRRefresh?.({ candidate, reason: 'swr', priority: 10 }) + enqueueLocalGitHubPRRefresh({ candidate, reason: 'swr', priority: 10 }) } } }, @@ -3854,7 +3867,7 @@ export const createGitHubSlice: StateCreator = (s fallbackPRSource: candidate.fallbackPRSource ?? null }) } else if (shouldEnqueueLocalPRRefresh(candidate)) { - void window.api.gh.enqueuePRRefresh?.({ candidate, reason: 'post-push', priority: 100 }) + enqueueLocalGitHubPRRefresh({ candidate, reason: 'post-push', priority: 100 }) } } } @@ -4052,7 +4065,7 @@ export const createGitHubSlice: StateCreator = (s fallbackPRSource: candidate.fallbackPRSource ?? null }) } else if (shouldEnqueueLocalPRRefresh(candidate)) { - void window.api.gh.enqueuePRRefresh?.({ candidate, reason: 'active', priority: 80 }) + enqueueLocalGitHubPRRefresh({ candidate, reason: 'active', priority: 80 }) } } }