diff --git a/src/main/github/pr-refresh-coordinator.test.ts b/src/main/github/pr-refresh-coordinator.test.ts index 618b73b0a..726784bae 100644 --- a/src/main/github/pr-refresh-coordinator.test.ts +++ b/src/main/github/pr-refresh-coordinator.test.ts @@ -55,6 +55,20 @@ function makePR(overrides: Partial = {}): PRInfo { } } +function deferred(): { + promise: Promise + resolve: (value: T) => void + reject: (error: unknown) => void +} { + let resolve!: (value: T) => void + let reject!: (error: unknown) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + describe('pr-refresh-coordinator', () => { beforeEach(() => { vi.resetModules() @@ -168,6 +182,113 @@ describe('pr-refresh-coordinator', () => { expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) }) + it('preserves an active refresh queued while a visible refresh is in flight', async () => { + const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } = + await import('./pr-refresh-coordinator') + const visibleOutcome = deferred<{ + kind: 'found' + pr: PRInfo + fetchedAt: number + }>() + getPRForBranchOutcomeMock.mockReturnValueOnce(visibleOutcome.promise).mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ checksStatus: 'success', state: 'merged' }), + fetchedAt: Date.now() + }) + + const candidate = makeCandidate() + reportVisiblePRRefreshCandidates([candidate], 1, 1) + await vi.advanceTimersByTimeAsync(0) + + enqueuePRRefresh({ ...candidate, cachedFetchedAt: Date.now() }, 'active', 80, 1) + visibleOutcome.resolve({ + kind: 'found', + pr: makePR({ checksStatus: 'pending' }), + fetchedAt: Date.now() + }) + await vi.advanceTimersByTimeAsync(0) + + const inFlightEvents = sendMock.mock.calls + .map(([, event]) => event) + .filter((event) => event.status === 'in-flight') + + expect(inFlightEvents.map((event) => event.reason)).toEqual(['visible', 'active']) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) + }) + + it('cancels queued work when a later enqueue marks the candidate invalid', async () => { + const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } = + await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ checksStatus: 'success' }), + fetchedAt: Date.now() + }) + + const candidate = makeCandidate() + reportVisiblePRRefreshCandidates([candidate], 1, 1) + await vi.advanceTimersByTimeAsync(0) + + enqueuePRRefresh( + { ...candidate, isArchived: true, cachedFetchedAt: Date.now() }, + 'active', + 80, + 1 + ) + await vi.advanceTimersByTimeAsync(10 * 60_000) + + const skippedEvents = sendMock.mock.calls + .map(([, event]) => event) + .filter((event) => event.status === 'skipped') + + expect(skippedEvents.at(-1)?.skippedReason).toBe('archived') + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + }) + + it('does not cancel other aliases when one coalesced PR alias becomes invalid', async () => { + const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } = + await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock + .mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ checksStatus: 'success' }), + fetchedAt: Date.now() + }) + .mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ checksStatus: 'success', state: 'merged' }), + fetchedAt: Date.now() + }) + + const first = makeCandidate({ + cacheKey: '/repo::feature/a', + branch: 'feature/a', + linkedPRNumber: 12, + worktreeId: 'wt-a' + }) + const second = makeCandidate({ + cacheKey: '/repo::feature/b', + branch: 'feature/b', + linkedPRNumber: 12, + worktreeId: 'wt-b' + }) + reportVisiblePRRefreshCandidates([first, second], 1, 1) + await vi.advanceTimersByTimeAsync(0) + + enqueuePRRefresh({ ...first, isArchived: true, cachedFetchedAt: Date.now() }, 'active', 80, 1) + enqueuePRRefresh({ ...second, cachedFetchedAt: Date.now() }, 'active', 80, 1) + await vi.advanceTimersByTimeAsync(0) + + const outcomeEvents = sendMock.mock.calls + .map(([, event]) => event) + .filter((event) => event.outcome) + + expect(outcomeEvents.at(-1)?.aliases.map((alias) => alias.cacheKey)).toEqual([ + '/repo::feature/b' + ]) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) + }) + it('preserves coalesced aliases across visible follow-up refreshes', async () => { const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') getPRForBranchOutcomeMock diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pr-refresh-coordinator.ts index bd87f61fd..e23303981 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pr-refresh-coordinator.ts @@ -173,6 +173,58 @@ function visibleCandidateAfterOutcome( } } +function setVisibleFollowUp(entry: QueueEntry): void { + const existing = queue.get(entry.key) + if (!existing) { + queue.set(entry.key, entry) + return + } + + for (const alias of entry.aliases.values()) { + existing.aliases.set(alias.cacheKey, alias) + } + + // Why: a user activation can arrive while a background refresh is awaiting gh. + // The background follow-up must not overwrite that pending active/manual work. + if ( + bypassesFreshnessDelay(existing.reason) || + existing.priority > entry.priority || + existing.dueAt <= entry.dueAt + ) { + return + } + + queue.set(entry.key, { + ...entry, + aliases: existing.aliases + }) +} + +function removeQueuedAliasForInvalidCandidate(key: string, alias: GitHubPRRefreshAlias): void { + const existing = queue.get(key) + if (!existing) { + return + } + + existing.aliases.delete(alias.cacheKey) + const replacementAlias = existing.aliases.values().next().value + if (!replacementAlias) { + queue.delete(key) + return + } + + if (existing.candidate.cacheKey === alias.cacheKey) { + existing.candidate = { + ...existing.candidate, + cacheKey: replacementAlias.cacheKey, + branch: replacementAlias.branch, + worktreeId: replacementAlias.worktreeId, + isArchived: false, + isBare: false + } + } +} + function scheduleVisibleFollowUp( key: string, candidate: GitHubPRRefreshCandidate, @@ -189,7 +241,7 @@ function scheduleVisibleFollowUp( const retryAt = Date.now() + Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.min(failures - 1, 4)) errorBackoff.set(key, { failures, retryAt }) - queue.set(key, { + setVisibleFollowUp({ key, candidate, aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), @@ -209,7 +261,7 @@ function scheduleVisibleFollowUp( // Why: coalesced linked-PR refreshes may represent several local branches. // Preserve every alias for the next visible follow-up so all cache entries // keep receiving periodic updates. - queue.set(key, { + setVisibleFollowUp({ key, candidate: followUpCandidate, aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), @@ -399,8 +451,10 @@ export function enqueuePRRefresh( branch: candidate.branch, worktreeId: candidate.worktreeId } + const key = refreshKey(candidate) const skippedReason = validateCandidate(candidate) if (skippedReason) { + removeQueuedAliasForInvalidCandidate(key, alias) broadcast({ aliases: [alias], reason, @@ -410,7 +464,6 @@ export function enqueuePRRefresh( return } - const key = refreshKey(candidate) const existing = queue.get(key) const freshDueAt = shouldSkipFresh(candidate, reason) ? freshRetryAt(candidate) : null const dueAt = freshDueAt ?? Date.now() + (reason === 'post-push' ? POST_PUSH_DELAY_MS : 0) @@ -487,6 +540,7 @@ export async function refreshPRNow(candidate: GitHubPRRefreshCandidate): Promise } const skippedReason = validateCandidate(candidate) if (skippedReason) { + removeQueuedAliasForInvalidCandidate(key, alias) const outcome: PRRefreshOutcome = { kind: 'upstream-error', errorType: 'unknown', diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 138020bcd..8098491c1 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -178,6 +178,7 @@ function App(): React.JSX.Element { initGitHubCache: s.initGitHubCache, refreshAllGitHub: s.refreshAllGitHub, reportVisibleGitHubPRRefreshCandidates: s.reportVisibleGitHubPRRefreshCandidates, + bumpGitHubPRVisibleRefreshGeneration: s.bumpGitHubPRVisibleRefreshGeneration, hydrateWorkspaceSession: s.hydrateWorkspaceSession, hydrateTabsSession: s.hydrateTabsSession, hydrateEditorSession: s.hydrateEditorSession, @@ -656,6 +657,7 @@ function App(): React.JSX.Element { const handler = (): void => { if (document.visibilityState === 'visible') { actions.refreshAllGitHub() + actions.bumpGitHubPRVisibleRefreshGeneration() } else { actions.reportVisibleGitHubPRRefreshCandidates([], Date.now()) } diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index 07f160ef4..af7bb77c1 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -52,6 +52,8 @@ export default function ChecksPanel(): React.JSX.Element { const pollIntervalRef = useRef(30_000) // start at 30s, backs off to 120s const prevChecksRef = useRef('') const conflictSummaryRefreshKeyRef = useRef(null) + const refreshRequestKeyRef = useRef(null) + const refreshContextKeyRef = useRef(null) // Why: the sidebar no longer uses key={activeWorktreeId} to force a full // remount on worktree switch (that caused an IPC storm on Windows). @@ -69,12 +71,18 @@ export default function ChecksPanel(): React.JSX.Element { setIsRefreshing(false) setEmptyRefreshing(false) conflictSummaryRefreshKeyRef.current = null + refreshRequestKeyRef.current = null } // Find active worktree and repo const branch = activeWorktree ? activeWorktree.branch.replace(/^refs\/heads\//, '') : '' const isFolder = repo ? isFolderRepo(repo) : false const prCacheKey = repo && branch ? `${repo.path}::${branch}` : '' + const refreshContextKey = `${activeWorktreeId ?? ''}::${repo?.path ?? ''}::${branch}` + if (refreshContextKey !== refreshContextKeyRef.current) { + refreshContextKeyRef.current = refreshContextKey + refreshRequestKeyRef.current = null + } const pr: PRInfo | null = prCacheKey ? (prCache[prCacheKey]?.data ?? null) : null const prRefreshState = useAppStore((s) => prCacheKey ? s.prRefreshStates[prCacheKey] : undefined @@ -262,12 +270,18 @@ export default function ChecksPanel(): React.JSX.Element { if (!repo || !branch) { return } + const requestKey = `${activeWorktreeId ?? ''}::${repo.path}::${branch}` + refreshRequestKeyRef.current = requestKey + const isCurrentRequest = (): boolean => refreshRequestKeyRef.current === requestKey setIsRefreshing(true) try { const refreshedPR = await fetchPRForBranch(repo.path, branch, { force: true, linkedPRNumber: linkedPR }) + if (!isCurrentRequest()) { + return + } if (refreshedPR) { // Why: call fetchPRChecks directly with the refreshed PR's headSha so // we don't pass the stale headSha captured by `fetchChecks`'s closure @@ -281,6 +295,9 @@ export default function ChecksPanel(): React.JSX.Element { { force: true } ).then( (result) => { + if (!isCurrentRequest()) { + return + } setChecks(result) const signature = JSON.stringify( result.map((c) => `${c.name}:${c.status}:${c.conclusion}`) @@ -292,27 +309,53 @@ export default function ChecksPanel(): React.JSX.Element { prevChecksRef.current = signature }, (err) => { + if (!isCurrentRequest()) { + return + } console.warn('Failed to fetch PR checks:', err) setChecks([]) } ) setChecksLoading(true) - const refreshedComments = fetchComments({ - force: true, - prNumberOverride: refreshedPR.number - }) + setCommentsLoading(true) + const refreshedComments = fetchPRComments(repo.path, refreshedPR.number, { + force: true + }).then( + (result) => { + if (isCurrentRequest()) { + setComments(result) + } + }, + (err) => { + if (!isCurrentRequest()) { + return + } + console.warn('Failed to fetch PR comments:', err) + setComments([]) + } + ) await Promise.all([ - refreshedChecks.finally(() => setChecksLoading(false)), - refreshedComments + refreshedChecks.finally(() => { + if (isCurrentRequest()) { + setChecksLoading(false) + } + }), + refreshedComments.finally(() => { + if (isCurrentRequest()) { + setCommentsLoading(false) + } + }) ]) } else { setChecks([]) setComments([]) } } finally { - setIsRefreshing(false) + if (isCurrentRequest()) { + setIsRefreshing(false) + } } - }, [repo, branch, linkedPR, fetchPRForBranch, fetchPRChecks, fetchComments]) + }, [repo, branch, activeWorktreeId, linkedPR, fetchPRForBranch, fetchPRChecks, fetchPRComments]) const handleEntryRefresh = useCallback( (options: { refreshChecks: boolean; refreshComments: boolean }) => { @@ -499,7 +542,6 @@ export default function ChecksPanel(): React.JSX.Element { : null const isQueuedPRRefresh = prRefreshState?.status === 'queued' const isInFlightPRRefresh = prRefreshState?.status === 'in-flight' - const isCheckingPR = isQueuedPRRefresh || isInFlightPRRefresh const isPausedPRRefresh = prRefreshState?.status === 'paused' return ( @@ -508,7 +550,7 @@ export default function ChecksPanel(): React.JSX.Element { {operationInProgress ? `${operationLabel} in progress` : isQueuedPRRefresh - ? 'Refresh queued' + ? 'Checking for pull request' : isInFlightPRRefresh ? 'Checking for pull request' : 'No pull request found'} @@ -517,7 +559,7 @@ export default function ChecksPanel(): React.JSX.Element { {operationInProgress ? 'PR checks will be available after the operation completes' : isQueuedPRRefresh - ? 'GitHub status will refresh shortly' + ? 'Waiting to refresh GitHub status for this branch' : isInFlightPRRefresh ? 'Refreshing GitHub status for this branch' : isPausedPRRefresh @@ -527,7 +569,7 @@ export default function ChecksPanel(): React.JSX.Element { {!operationInProgress && ( )} diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index d10498b45..ea7b80b3f 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -139,6 +139,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp ) const cardProps = useAppStore((s) => s.worktreeCardProperties) const sshConnectedGeneration = useAppStore((s) => s.sshConnectedGeneration) + const prVisibleRefreshGeneration = useAppStore((s) => s.prVisibleRefreshGeneration) // Drag is only meaningful when the user is grouping by repo. When inert // (groupBy !== 'repo'), the controller is still constructed for hook order @@ -412,7 +413,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp const visibleIdentity = visibleRows .map((row) => `${row.worktree.id}:${row.worktree.branch}:${row.worktree.linkedPR ?? ''}`) .join('|') - const key = `${visibleIdentity}:${sshConnectedGeneration}:${cardProps.join(',')}` + const key = `${visibleIdentity}:${sshConnectedGeneration}:${prVisibleRefreshGeneration}:${cardProps.join(',')}` if (!key || key === lastVisibleRefreshKeyRef.current) { return } @@ -423,6 +424,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp groupBy, reportVisibleGitHubPRRefreshCandidates, rows, + prVisibleRefreshGeneration, sshConnectedGeneration, virtualItems ]) diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index ed28196ba..59ad0d5e0 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -918,11 +918,6 @@ export function useIpcEvents(): void { } if (state.status === 'connected') { - // Why: the file explorer may have tried (and failed) to load the tree - // before the SSH connection was established. Bumping the generation - // lets it detect that providers are now available and retry. - store.bumpSshConnectedGeneration() - void Promise.all(remoteRepos.map((r) => store.fetchWorktrees(r.id))).then(() => { // Why: terminal panes that failed to spawn (no PTY provider on cold // start) sit inert. Bumping generation forces TerminalPane to remount diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index 4496e6443..cb47259ee 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -464,6 +464,7 @@ export type GitHubSlice = { commentsCache: Record> prRefreshSequences: Record prRefreshStates: Record + prVisibleRefreshGeneration: number // Why: keyed by repoPath + limit + query so the NewWorkspace page can render // from cache instantly on mount (and on hover-prefetch from sidebar buttons) // while a background refresh keeps the list fresh. @@ -502,6 +503,7 @@ export type GitHubSlice = { priority?: number ) => void reportVisibleGitHubPRRefreshCandidates: (worktreeIds: string[], generation: number) => void + bumpGitHubPRVisibleRefreshGeneration: () => void applyGitHubPRRefreshEvent: (event: GitHubPRRefreshEvent) => void /** * Why: returns cached work items immediately (null if none) and fires a @@ -649,6 +651,7 @@ export const createGitHubSlice: StateCreator = (s commentsCache: {}, prRefreshSequences: {}, prRefreshStates: {}, + prVisibleRefreshGeneration: 0, workItemsCache: {}, workItemsInvalidationNonce: 0, projectViewCache: {}, @@ -1525,6 +1528,10 @@ export const createGitHubSlice: StateCreator = (s } }, + bumpGitHubPRVisibleRefreshGeneration: () => { + set((s) => ({ prVisibleRefreshGeneration: s.prVisibleRefreshGeneration + 1 })) + }, + applyGitHubPRRefreshEvent: (event) => { set((s) => { const nextSequences = { ...s.prRefreshSequences } @@ -1617,7 +1624,9 @@ export const createGitHubSlice: StateCreator = (s const now = Date.now() const stalePRCandidates: { candidate: GitHubPRRefreshCandidate; score: number }[] = [] const shouldRefreshPRs = - state.worktreeCardProperties.includes('pr') || state.worktreeCardProperties.includes('ci') + state.groupBy === 'pr-status' || + state.worktreeCardProperties.includes('pr') || + state.worktreeCardProperties.includes('ci') for (const worktrees of Object.values(state.worktreesByRepo)) { for (const wt of worktrees) { diff --git a/src/renderer/src/store/slices/ssh.ts b/src/renderer/src/store/slices/ssh.ts index 96b6365d2..9f77e8eb3 100644 --- a/src/renderer/src/store/slices/ssh.ts +++ b/src/renderer/src/store/slices/ssh.ts @@ -35,7 +35,6 @@ export type SshSlice = { setSshTargetLabels: (labels: Map) => void enqueueSshCredentialRequest: (req: SshCredentialRequest) => void removeSshCredentialRequest: (requestId: string) => void - bumpSshConnectedGeneration: () => void setPortForwards: (targetId: string, forwards: PortForwardEntry[]) => void clearPortForwards: (targetId: string) => void setDetectedPorts: (targetId: string, ports: DetectedPort[]) => void @@ -70,8 +69,6 @@ export const createSshSlice: StateCreator = (set) => set((s) => ({ sshCredentialQueue: s.sshCredentialQueue.filter((req) => req.requestId !== requestId) })), - bumpSshConnectedGeneration: () => - set((s) => ({ sshConnectedGeneration: s.sshConnectedGeneration + 1 })), setPortForwards: (targetId, forwards) => set((s) => {