From e8533f32cafba8bb7653922e12b368110bd3a467 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 25 Jun 2026 11:44:25 -0700 Subject: [PATCH] Keep PR checks status in sync (#6328) Co-authored-by: Orca --- .../components/right-sidebar/ChecksPanel.tsx | 137 ++++++++- ...ecks-panel-ambiguous-github-review.test.ts | 44 +++ .../checks-panel-ambiguous-github-review.ts | 22 ++ .../checks-panel-empty-state.test.ts | 75 +++++ .../right-sidebar/checks-panel-empty-state.ts | 27 ++ ...checks-panel-pr-refresh-breadcrumb.test.ts | 74 +++++ .../checks-panel-pr-refresh-breadcrumb.ts | 97 +++++++ .../sidebar/WorktreeCard.pr-display.test.tsx | 54 +++- .../src/components/sidebar/WorktreeCard.tsx | 25 +- .../sidebar/WorktreeCardStatusSlot.tsx | 18 +- src/renderer/src/i18n/locales/en.json | 4 +- src/renderer/src/i18n/locales/es.json | 4 +- src/renderer/src/i18n/locales/ja.json | 4 +- src/renderer/src/i18n/locales/ko.json | 4 +- src/renderer/src/i18n/locales/zh.json | 4 +- .../github-pr-refresh-states-leak.test.ts | 264 +++++++++++++++++- src/renderer/src/store/slices/github.ts | 150 +++++++++- 17 files changed, 975 insertions(+), 32 deletions(-) create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.test.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.test.ts create mode 100644 src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index 9f54c3c84..bdf547c77 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -14,6 +14,8 @@ import { } from 'lucide-react' import { useAppStore, type AppState } from '@/store' import { + buildGitHubPRRefreshStateClearToken, + getGitHubPRRefreshStateExpiryAt, mergePRCommentIntoList, prChecksCacheSuffix, prCommentsCacheSuffix @@ -94,6 +96,8 @@ import { getChecksPanelEmptyStateCopy, shouldShowChecksPanelPublishBranchAction } from './checks-panel-empty-state' +import { hasAmbiguousGitHubHostedReviewForChecksPanel } from './checks-panel-ambiguous-github-review' +import { recordChecksPanelPRRefreshBreadcrumb } from './checks-panel-pr-refresh-breadcrumb' import { cancelRuntimeGeneratePullRequestFields, generateRuntimePullRequestFields, @@ -372,6 +376,7 @@ export default function ChecksPanel(): React.JSX.Element { const prCache = useAppStore((s) => s.prCache) const fetchPRForBranch = useAppStore((s) => s.fetchPRForBranch) const fetchHostedReviewForBranch = useAppStore((s) => s.fetchHostedReviewForBranch) + const expireGitHubPRRefreshState = useAppStore((s) => s.expireGitHubPRRefreshState) const getHostedReviewCreationEligibility = useAppStore( (s) => s.getHostedReviewCreationEligibility ) @@ -559,6 +564,7 @@ export default function ChecksPanel(): React.JSX.Element { // Done during render (not useEffect) so the reset takes effect on the same // paint as the context change; useEffect would leave one stale render. const [prevPanelContextKey, setPrevPanelContextKey] = useState(panelContextKey) + const [prRefreshStateNow, setPrRefreshStateNow] = useState(() => Date.now()) if (panelContextKey !== prevPanelContextKey) { setPrevPanelContextKey(panelContextKey) setEditingTitle(false) @@ -572,6 +578,7 @@ export default function ChecksPanel(): React.JSX.Element { setIsRefreshing(false) setEmptyRefreshing(false) setConflictDetailsRefreshing(false) + setPrRefreshStateNow(Date.now()) createPrInFlightRef.current = null setIsCreatingPr(false) setCreatePrError(null) @@ -619,10 +626,16 @@ export default function ChecksPanel(): React.JSX.Element { refreshContextKeyRef.current = refreshContextKey refreshRequestKeyRef.current = null } - const pr: PRInfo | null = prCacheKey ? (prCache[prCacheKey]?.data ?? null) : null + const prCacheEntry = prCacheKey ? prCache[prCacheKey] : undefined + const pr: PRInfo | null = prCacheEntry?.data ?? null const hostedReview = useAppStore((s) => hostedReviewCacheKey ? (s.hostedReviewCache[hostedReviewCacheKey]?.data ?? null) : null ) + const hasAmbiguousGitHubHostedReview = hasAmbiguousGitHubHostedReviewForChecksPanel({ + hostedReview, + prCacheEntry, + prCacheKey + }) // Fetch PR data when the active worktree/branch changes. // Why: branch lookup is lossy for fork/deleted-head PRs; reuse a known PR // number from metadata or the visible cache whenever we have one. @@ -640,10 +653,61 @@ export default function ChecksPanel(): React.JSX.Element { const isGitLabReviewContext = Boolean(activeGitLabReview || linkedGitLabMR !== null) const activeConflictReview = activeReview?.mergeable === 'CONFLICTING' ? activeReview : null const prRefreshState = useAppStore((s) => + prCacheKey ? s.getEffectiveGitHubPRRefreshState(prCacheKey, prRefreshStateNow) : undefined + ) + const rawPRRefreshState = useAppStore((s) => prCacheKey ? s.prRefreshStates[prCacheKey] : undefined ) const prNumber = pr?.number ?? null + useEffect(() => { + const expiryAt = getGitHubPRRefreshStateExpiryAt(rawPRRefreshState) + if (!prCacheKey || expiryAt === null) { + return + } + const timeout = window.setTimeout( + () => { + setPrRefreshStateNow(Date.now()) + const storeState = useAppStore.getState() + const rawState = storeState.prRefreshStates[prCacheKey] + const token = buildGitHubPRRefreshStateClearToken( + rawState, + storeState.prRefreshSequences, + prCacheKey + ) + if (!token) { + return + } + // Why: time alone does not publish Zustand updates; this timeout clears + // abandoned active refresh UI without treating expiry as no-PR evidence. + recordChecksPanelPRRefreshBreadcrumb({ + event: 'stale_cleared', + provider: 'github', + repoId: repo?.id, + worktreeId: activeWorktreeId, + branch, + prCacheKey, + prNumber, + prState: pr?.state, + prChecksStatus: pr?.checksStatus, + refreshState: rawState + }) + storeState.expireGitHubPRRefreshState(prCacheKey, token) + }, + Math.max(0, expiryAt - Date.now() + 1) + ) + return () => window.clearTimeout(timeout) + }, [ + activeWorktreeId, + branch, + pr?.checksStatus, + pr?.state, + prCacheKey, + prNumber, + rawPRRefreshState, + repo?.id + ]) + // Why: select only timestamps (not whole cache records) so the entry-refresh // effect doesn't re-run on every cache mutation. See // docs/refresh-on-checks-tab.md. @@ -1775,8 +1839,23 @@ export default function ChecksPanel(): React.JSX.Element { const refreshRequestKey = `${activeWorktreeId ?? ''}::${prCacheKey}::${branch}::${Date.now()}::${Math.random()}` refreshRequestKeyRef.current = refreshRequestKey const isCurrentRequest = (): boolean => refreshRequestKeyRef.current === refreshRequestKey + const refreshStartedAt = Date.now() + const refreshProvider = isGitLabReviewContext ? 'gitlab' : 'github' + let refreshOutcome = 'started' setIsRefreshing(true) setGitStatusRefreshNonce((value) => value + 1) + recordChecksPanelPRRefreshBreadcrumb({ + event: 'start', + provider: refreshProvider, + repoId: repo.id, + worktreeId: activeWorktreeId, + branch, + prCacheKey, + prNumber: activeGitLabReview?.number ?? prNumber, + prState: activeGitLabReview?.state ?? pr?.state, + prChecksStatus: pr?.checksStatus, + refreshState: prCacheKey ? useAppStore.getState().prRefreshStates[prCacheKey] : null + }) try { if (isGitLabReviewContext) { const refreshedReview = await refreshHostedReviewCard(fetchHostedReviewForBranch, { @@ -1801,19 +1880,35 @@ export default function ChecksPanel(): React.JSX.Element { headShaOverride: refreshedGitLabReview.headSha, commitAsCurrent: true }) + refreshOutcome = 'review' } else { setChecks([]) setComments([]) + refreshOutcome = 'no-review' } return } - const refreshedPR = await fetchPRForBranch(repo.path, branch, { - force: true, - repoId: repo.id, - worktreeId: activeWorktreeId ?? undefined, - linkedPRNumber: linkedPR, - fallbackPRNumber: fallbackGitHubPRNumber - }) + const refreshStoreState = useAppStore.getState() + const rawPRRefreshState = refreshStoreState.prRefreshStates[prCacheKey] + const startedPRRefreshToken = buildGitHubPRRefreshStateClearToken( + rawPRRefreshState, + refreshStoreState.prRefreshSequences, + prCacheKey + ) + let refreshedPR: PRInfo | null = null + try { + refreshedPR = await fetchPRForBranch(repo.path, branch, { + force: true, + repoId: repo.id, + worktreeId: activeWorktreeId ?? undefined, + linkedPRNumber: linkedPR, + fallbackPRNumber: fallbackGitHubPRNumber + }) + } finally { + if (startedPRRefreshToken) { + expireGitHubPRRefreshState(prCacheKey, startedPRRefreshToken) + } + } if (!isCurrentRequest()) { return } @@ -1832,6 +1927,7 @@ export default function ChecksPanel(): React.JSX.Element { return } if (refreshedPR) { + refreshOutcome = 'pr' const prRequestKey = checksPanelAsyncResultKey( prCacheKey, branch, @@ -1914,8 +2010,27 @@ export default function ChecksPanel(): React.JSX.Element { } else if (isCurrentRequest()) { setChecks([]) setComments([]) + refreshOutcome = 'no-pr' } + } catch (error) { + refreshOutcome = 'error' + throw error } finally { + recordChecksPanelPRRefreshBreadcrumb({ + event: 'done', + provider: refreshProvider, + repoId: repo.id, + worktreeId: activeWorktreeId, + branch, + prCacheKey, + prNumber: activeGitLabReview?.number ?? prNumber, + prState: activeGitLabReview?.state ?? pr?.state, + prChecksStatus: pr?.checksStatus, + refreshState: prCacheKey ? useAppStore.getState().prRefreshStates[prCacheKey] : null, + outcome: refreshOutcome, + durationMs: Date.now() - refreshStartedAt, + currentRequest: isCurrentRequest() + }) if (isCurrentRequest()) { setIsRefreshing(false) } @@ -1926,8 +2041,10 @@ export default function ChecksPanel(): React.JSX.Element { activeWorktreeId, activeGitLabReview, prNumber, + pr?.checksStatus, pr?.headSha, pr?.prRepo, + pr?.state, prCacheKey, linkedPR, fallbackGitHubPRNumber, @@ -1941,6 +2058,7 @@ export default function ChecksPanel(): React.JSX.Element { fetchPRChecks, fetchPRComments, fetchHostedReviewForBranch, + expireGitHubPRRefreshState, isCurrentAsyncResult ]) @@ -3297,7 +3415,8 @@ export default function ChecksPanel(): React.JSX.Element { hasUpstream: publishActionRemoteStatus?.hasUpstream, hasCurrentBranch: Boolean(branch), reviewLabel: emptyReviewLabel, - reviewShortLabel: emptyReviewShortLabel + reviewShortLabel: emptyReviewShortLabel, + hasAmbiguousGitHubHostedReview }) return (
diff --git a/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.test.ts b/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.test.ts new file mode 100644 index 000000000..db51fd6ef --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { hasAmbiguousGitHubHostedReviewForChecksPanel } from './checks-panel-ambiguous-github-review' + +describe('hasAmbiguousGitHubHostedReviewForChecksPanel', () => { + it('treats missing PR cache as ambiguous when a GitHub hosted review exists', () => { + expect( + hasAmbiguousGitHubHostedReviewForChecksPanel({ + hostedReview: { provider: 'github' }, + prCacheEntry: undefined, + prCacheKey: 'repo::feature' + }) + ).toBe(true) + }) + + it('treats cached no-PR data as ambiguous when a GitHub hosted review exists', () => { + expect( + hasAmbiguousGitHubHostedReviewForChecksPanel({ + hostedReview: { provider: 'github' }, + prCacheEntry: { data: null }, + prCacheKey: 'repo::feature' + }) + ).toBe(true) + }) + + it('does not treat existing PR cache data as ambiguous', () => { + expect( + hasAmbiguousGitHubHostedReviewForChecksPanel({ + hostedReview: { provider: 'github' }, + prCacheEntry: { data: { number: 12 } }, + prCacheKey: 'repo::feature' + }) + ).toBe(false) + }) + + it('does not treat non-GitHub hosted reviews as ambiguous', () => { + expect( + hasAmbiguousGitHubHostedReviewForChecksPanel({ + hostedReview: { provider: 'gitlab' }, + prCacheEntry: { data: null }, + prCacheKey: 'repo::feature' + }) + ).toBe(false) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.ts b/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.ts new file mode 100644 index 000000000..bca25a7a2 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-ambiguous-github-review.ts @@ -0,0 +1,22 @@ +type HostedReviewProviderLike = { + provider?: string | null +} + +type PRCacheEntryLike = { + data?: unknown +} + +/** + * Flags GitHub-hosted review metadata whose matching PR cache may still be unknown. + */ +export function hasAmbiguousGitHubHostedReviewForChecksPanel(input: { + hostedReview: HostedReviewProviderLike | null | undefined + prCacheEntry: PRCacheEntryLike | null | undefined + prCacheKey: string +}): boolean { + return ( + input.hostedReview?.provider === 'github' && + input.prCacheKey !== '' && + input.prCacheEntry?.data == null + ) +} diff --git a/src/renderer/src/components/right-sidebar/checks-panel-empty-state.test.ts b/src/renderer/src/components/right-sidebar/checks-panel-empty-state.test.ts index d81e46351..40738435a 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-empty-state.test.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-empty-state.test.ts @@ -104,6 +104,81 @@ describe('getChecksPanelEmptyStateCopy', () => { description: 'Create a merge request to start checks and review.' }) }) + + it('uses neutral copy when GitHub hosted-review data exists without PR cache', () => { + expect( + getChecksPanelEmptyStateCopy({ + operationLabel: null, + prRefreshStatus: undefined, + hostedReviewBlockedReason: null, + hasUpstream: true, + hasAmbiguousGitHubHostedReview: true + }) + ).toEqual({ + title: 'Pull request status unavailable', + description: 'Refresh GitHub status for this branch to load checks and review.' + }) + }) + + it('does not show no-PR copy for paused ambiguous GitHub hosted-review data', () => { + expect( + getChecksPanelEmptyStateCopy({ + operationLabel: null, + prRefreshStatus: 'paused', + hostedReviewBlockedReason: null, + hasUpstream: true, + hasAmbiguousGitHubHostedReview: true + }).title + ).toBe('Pull request status unavailable') + }) + + it('keeps refresh errors for ambiguous GitHub hosted-review data', () => { + expect( + getChecksPanelEmptyStateCopy({ + operationLabel: null, + prRefreshStatus: 'error', + hostedReviewBlockedReason: null, + hasUpstream: true, + hasAmbiguousGitHubHostedReview: true + }).title + ).toBe('Could not refresh pull request') + }) + + it('uses neutral copy for ambiguous GitHub hosted-review data before unpublished branch copy', () => { + expect( + getChecksPanelEmptyStateCopy({ + operationLabel: null, + prRefreshStatus: undefined, + hostedReviewBlockedReason: 'no_upstream', + hasUpstream: false, + hasAmbiguousGitHubHostedReview: true + }).title + ).toBe('Pull request status unavailable') + }) + + it('uses neutral copy for ambiguous GitHub hosted-review data before remote fallback publish copy', () => { + expect( + getChecksPanelEmptyStateCopy({ + operationLabel: null, + prRefreshStatus: undefined, + hostedReviewBlockedReason: undefined, + hasUpstream: false, + hasAmbiguousGitHubHostedReview: true + }).title + ).toBe('Pull request status unavailable') + }) + + it('uses neutral copy for ambiguous GitHub hosted-review data before unpushed commit copy', () => { + expect( + getChecksPanelEmptyStateCopy({ + operationLabel: null, + prRefreshStatus: undefined, + hostedReviewBlockedReason: 'needs_push', + hasUpstream: true, + hasAmbiguousGitHubHostedReview: true + }).title + ).toBe('Pull request status unavailable') + }) }) describe('shouldShowChecksPanelPublishBranchAction', () => { diff --git a/src/renderer/src/components/right-sidebar/checks-panel-empty-state.ts b/src/renderer/src/components/right-sidebar/checks-panel-empty-state.ts index 0810c0ffe..1432ae8e1 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-empty-state.ts +++ b/src/renderer/src/components/right-sidebar/checks-panel-empty-state.ts @@ -11,6 +11,7 @@ type ChecksPanelEmptyStateInput = { hasCurrentBranch?: boolean reviewLabel?: 'pull request' | 'merge request' reviewShortLabel?: 'PR' | 'MR' + hasAmbiguousGitHubHostedReview?: boolean } type ChecksPanelEmptyStateCopy = { @@ -18,6 +19,9 @@ type ChecksPanelEmptyStateCopy = { description: string } +/** + * Chooses neutral empty-state copy when GitHub review status is still ambiguous. + */ export function getChecksPanelEmptyStateCopy( input: ChecksPanelEmptyStateInput ): ChecksPanelEmptyStateCopy { @@ -39,6 +43,26 @@ export function getChecksPanelEmptyStateCopy( } const blockedReason = input.hostedReviewBlockedReason + // Why: hosted-review metadata with missing PR cache data is ambiguous, so + // avoid showing "no PR" or publish guidance until GitHub status is refreshed. + if ( + input.hasAmbiguousGitHubHostedReview === true && + (input.prRefreshStatus === 'paused' || + input.prRefreshStatus === 'skipped' || + input.prRefreshStatus === undefined) + ) { + return { + title: translate( + 'auto.components.right.sidebar.checks.panel.empty.state.3322603418', + 'Pull request status unavailable' + ), + description: translate( + 'auto.components.right.sidebar.checks.panel.empty.state.b597440265', + 'Refresh GitHub status for this branch to load checks and review.' + ) + } + } + if ( shouldShowChecksPanelPublishBranchAction({ hostedReviewBlockedReason: blockedReason, @@ -137,6 +161,9 @@ export function getChecksPanelEmptyStateCopy( } } +/** + * Separates local-only branch guidance from hosted-review refresh uncertainty. + */ export function shouldShowChecksPanelPublishBranchAction(input: { hostedReviewBlockedReason: HostedReviewCreationBlockedReason | undefined hasUpstream: boolean | undefined diff --git a/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.test.ts b/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.test.ts new file mode 100644 index 000000000..325c74092 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it, vi } from 'vitest' +import type { PRRefreshState } from '@/store/slices/github' +import { + buildChecksPanelPRRefreshBreadcrumbData, + recordChecksPanelPRRefreshBreadcrumb +} from './checks-panel-pr-refresh-breadcrumb' + +const { recordRendererCrashBreadcrumbMock } = vi.hoisted(() => ({ + recordRendererCrashBreadcrumbMock: vi.fn() +})) + +vi.mock('@/lib/crash-diagnostics', () => ({ + recordRendererCrashBreadcrumb: recordRendererCrashBreadcrumbMock +})) + +describe('checks panel PR refresh breadcrumbs', () => { + it('records refresh state timing without raw branch or cache key values', () => { + const refreshState: PRRefreshState = { + status: 'in-flight', + reason: 'manual', + updatedAt: 130_000 + } + + const data = buildChecksPanelPRRefreshBreadcrumbData({ + event: 'stale_cleared', + provider: 'github', + repoId: 'repo-1', + worktreeId: 'worktree-1', + branch: 'feature/customer-ticket', + prCacheKey: '/private/repo::feature/customer-ticket', + prNumber: 42, + prState: 'OPEN', + prChecksStatus: 'pending', + refreshState, + now: 250_000 + }) + + expect(data).toMatchObject({ + provider: 'github', + repoId: 'repo-1', + worktreeId: 'worktree-1', + branchLength: 23, + prNumber: 42, + prState: 'OPEN', + prChecksStatus: 'pending', + refreshStatus: 'in-flight', + refreshReason: 'manual', + refreshAgeMs: 120_000, + refreshExpiresInMs: 0 + }) + expect(data.branchHash).toMatch(/^[0-9a-f]{8}$/) + expect(data.prCacheKeyHash).toMatch(/^[0-9a-f]{8}$/) + expect(Object.values(data)).not.toContain('feature/customer-ticket') + expect(Object.values(data)).not.toContain('/private/repo::feature/customer-ticket') + }) + + it('emits the expected crash breadcrumb name', () => { + recordChecksPanelPRRefreshBreadcrumb({ + event: 'done', + provider: 'gitlab', + outcome: 'review', + durationMs: 25, + currentRequest: true, + now: 1_000 + }) + + expect(recordRendererCrashBreadcrumbMock).toHaveBeenCalledWith('checks_panel_pr_refresh_done', { + provider: 'gitlab', + outcome: 'review', + durationMs: 25, + currentRequest: true + }) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts b/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts new file mode 100644 index 000000000..d2925dc64 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/checks-panel-pr-refresh-breadcrumb.ts @@ -0,0 +1,97 @@ +import { recordRendererCrashBreadcrumb } from '@/lib/crash-diagnostics' +import { getGitHubPRRefreshStateExpiryAt, type PRRefreshState } from '@/store/slices/github' +import type { + CrashReportBreadcrumbData, + CrashReportDetailValue +} from '../../../../shared/crash-reporting' + +type ChecksPanelPRRefreshBreadcrumbEvent = 'start' | 'done' | 'stale_cleared' +type ChecksPanelReviewProvider = 'github' | 'gitlab' + +type ChecksPanelPRRefreshBreadcrumbArgs = { + event: ChecksPanelPRRefreshBreadcrumbEvent + provider: ChecksPanelReviewProvider + repoId?: string | null + worktreeId?: string | null + branch?: string | null + prCacheKey?: string | null + prNumber?: number | null + prState?: string | null + prChecksStatus?: string | null + refreshState?: PRRefreshState | null + outcome?: string | null + durationMs?: number | null + currentRequest?: boolean + now?: number +} + +const BREADCRUMB_NAMES: Record = { + start: 'checks_panel_pr_refresh_start', + done: 'checks_panel_pr_refresh_done', + stale_cleared: 'checks_panel_pr_refresh_stale_cleared' +} + +export function recordChecksPanelPRRefreshBreadcrumb( + args: ChecksPanelPRRefreshBreadcrumbArgs +): void { + recordRendererCrashBreadcrumb( + BREADCRUMB_NAMES[args.event], + buildChecksPanelPRRefreshBreadcrumbData(args) + ) +} + +export function buildChecksPanelPRRefreshBreadcrumbData( + args: ChecksPanelPRRefreshBreadcrumbArgs +): CrashReportBreadcrumbData { + const now = args.now ?? Date.now() + const refreshState = args.refreshState ?? null + return compactBreadcrumbData({ + provider: args.provider, + repoId: args.repoId, + worktreeId: args.worktreeId, + branchHash: args.branch ? hashString(args.branch) : undefined, + branchLength: args.branch?.length, + prCacheKeyHash: args.prCacheKey ? hashString(args.prCacheKey) : undefined, + prNumber: args.prNumber, + prState: args.prState, + prChecksStatus: args.prChecksStatus, + refreshStatus: refreshState?.status, + refreshReason: refreshState?.reason, + refreshAgeMs: + refreshState && Number.isFinite(refreshState.updatedAt) + ? Math.max(0, now - refreshState.updatedAt) + : undefined, + refreshExpiresInMs: getRefreshExpiresInMs(refreshState, now), + outcome: args.outcome, + durationMs: args.durationMs, + currentRequest: args.currentRequest + }) +} + +function getRefreshExpiresInMs(state: PRRefreshState | null, now: number): number | undefined { + const expiryAt = getGitHubPRRefreshStateExpiryAt(state ?? undefined) + return expiryAt === null ? undefined : Math.max(0, expiryAt - now) +} + +function compactBreadcrumbData( + data: Record +): CrashReportBreadcrumbData { + const compacted: CrashReportBreadcrumbData = {} + for (const [key, value] of Object.entries(data)) { + if (typeof value === 'string' || typeof value === 'boolean' || value === null) { + compacted[key] = value + } else if (typeof value === 'number' && Number.isFinite(value)) { + compacted[key] = value + } + } + return compacted +} + +function hashString(value: string): string { + let hash = 0x811c9dc5 + for (let index = 0; index < value.length; index += 1) { + hash ^= value.charCodeAt(index) + hash = Math.imul(hash, 0x01000193) + } + return (hash >>> 0).toString(16).padStart(8, '0') +} diff --git a/src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx b/src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx index dbf90b0fa..f3bc4768b 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx @@ -2,7 +2,13 @@ import { renderToStaticMarkup } from 'react-dom/server' import type { ReactNode } from 'react' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { HostedReviewInfo } from '../../../../shared/hosted-review' -import type { GlobalSettings, Repo, Worktree, WorktreeCardProperty } from '../../../../shared/types' +import type { + GlobalSettings, + PRInfo, + Repo, + Worktree, + WorktreeCardProperty +} from '../../../../shared/types' import { COMPACT_WORKTREE_CARD_PROPERTIES } from '../../../../shared/worktree-card-properties' import type { WorkspacePortScanResult } from '../../../../shared/workspace-ports' @@ -14,6 +20,7 @@ const updateWorktreeMeta = vi.fn() let worktreeCardProperties: WorktreeCardProperty[] = ['status'] let hostedReviewCache: Record = {} +let prCache: Record = {} let workspacePortScan: WorkspacePortScanResult | null = null let settings: Partial | null = null @@ -29,6 +36,7 @@ vi.mock('@/store', () => ({ issueCache: {}, linearIssueCache: {}, openModal, + prCache, projectGroups: [], remoteBranchConflictByWorktreeId: {}, settings, @@ -121,6 +129,19 @@ function makeHostedReview(overrides: Partial = {}): HostedRevi } } +function makePRInfo(overrides: Partial = {}): PRInfo { + return { + number: 456, + title: 'Fix stale GH PR', + state: 'open', + url: 'https://github.com/acme/orca/pull/456', + checksStatus: 'success', + updatedAt: '2026-05-17T00:00:00.000Z', + mergeable: 'MERGEABLE', + ...overrides + } +} + function renderWorktreeCardMarkup(element: ReactNode): string { return renderToStaticMarkup(<>{element}) } @@ -140,6 +161,7 @@ describe('WorktreeCard linked PR display', () => { vi.clearAllMocks() worktreeCardProperties = ['status'] hostedReviewCache = {} + prCache = {} workspacePortScan = null settings = null }) @@ -616,4 +638,34 @@ describe('WorktreeCard linked PR display', () => { expect(markup).not.toContain('Linked PR #456') expect(markup).not.toContain('CI checks') }) + + it('uses branch PR cache for the status slot before hosted-review metadata warms', async () => { + settings = { experimentalNewWorktreeCardStyle: true } + worktreeCardProperties = ['status'] + prCache = { + 'repo-1::feature/local-branch': { + data: makePRInfo({ + number: 6340, + title: 'Remove split terminal from onboarding checklist', + state: 'merged', + checksStatus: 'success' + }), + fetchedAt: Date.now() + } + } + const { default: WorktreeCard } = await import('./WorktreeCard') + + const markup = renderWorktreeCardMarkup( + + ) + + expect(markup).toContain('PR: Merged') + expect(markup).toContain('text-purple-600/70') + expect(markup).not.toContain('Branch') + expect(markup).not.toContain('lucide-git-branch') + }) }) diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx index 07a0b887f..7945c35a1 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx @@ -3,6 +3,7 @@ import React, { useEffect, useCallback, useState } from 'react' import { useAppStore } from '@/store' import { getHostedReviewCacheKey } from '@/store/slices/hosted-review' import { issueCacheKey as getIssueCacheKey } from '@/store/slices/github' +import { getGitHubPRCacheKey } from '@/store/slices/github-cache-key' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip' @@ -29,6 +30,7 @@ import { cn } from '@/lib/utils' import { activateWorktreeFromSidebar } from '@/lib/sidebar-worktree-activation' import { isFolderRepo } from '../../../../shared/repo-kind' import type { HostedReviewInfo } from '../../../../shared/hosted-review' +import { hostedReviewInfoFromGitHubPRInfo } from '../../../../shared/hosted-review-github' import type { GitHubWorkItem, Worktree, @@ -398,6 +400,17 @@ const WorktreeCard = React.memo(function WorktreeCard({ repo.executionHostId ) : '' + const prCacheKey = + repo && branch + ? getGitHubPRCacheKey( + repo.path, + repo.id, + branch, + settings, + repo.connectionId, + repo.executionHostId + ) + : '' const issueCacheKey = repo && worktree.linkedIssue ? getIssueCacheKey( @@ -417,6 +430,7 @@ const WorktreeCard = React.memo(function WorktreeCard({ const hostedReviewEntry = useAppStore((s) => hostedReviewCacheKey ? s.hostedReviewCache[hostedReviewCacheKey] : undefined ) + const prCacheEntry = useAppStore((s) => (prCacheKey ? s.prCache?.[prCacheKey] : undefined)) const issueEntry = useAppStore((s) => (issueCacheKey ? s.issueCache[issueCacheKey] : undefined)) const linearIssueEntry = useAppStore((s) => linearIssueCacheKey ? s.linearIssueCache[linearIssueCacheKey] : undefined @@ -427,19 +441,26 @@ const WorktreeCard = React.memo(function WorktreeCard({ const hostedReview: HostedReviewInfo | null | undefined = hostedReviewEntry !== undefined ? hostedReviewEntry.data : undefined + // Why: ChecksPanel can discover a branch PR before hosted-review metadata + // warms. The sidebar status slot should not fall back to "branch" while + // the branch PR cache already knows the review state. + const cachedBranchReview = + hostedReview === undefined && prCacheEntry?.data + ? hostedReviewInfoFromGitHubPRInfo(prCacheEntry.data) + : hostedReview const linkedGitLabMR = worktree.linkedGitLabMR ?? null const linkedBitbucketPR = worktree.linkedBitbucketPR ?? null const linkedAzureDevOpsPR = worktree.linkedAzureDevOpsPR ?? null const linkedGiteaPR = worktree.linkedGiteaPR ?? null const prDisplay = getWorktreeCardPrDisplay( - hostedReview, + cachedBranchReview, worktree.linkedPR, linkedGitLabMR, linkedBitbucketPR, linkedAzureDevOpsPR, linkedGiteaPR, { - reviewHintKey: hostedReviewEntry?.linkedReviewHintKey + reviewHintKey: hostedReviewEntry?.linkedReviewHintKey ?? (prCacheEntry?.data ? '' : undefined) } ) const issue: IssueInfo | null | undefined = worktree.linkedIssue diff --git a/src/renderer/src/components/sidebar/WorktreeCardStatusSlot.tsx b/src/renderer/src/components/sidebar/WorktreeCardStatusSlot.tsx index eeff2b9c5..7dfec9d08 100644 --- a/src/renderer/src/components/sidebar/WorktreeCardStatusSlot.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCardStatusSlot.tsx @@ -65,15 +65,6 @@ function overlayNewCardUnreadStatus( function getReviewStatusTooltip(review: WorktreeCardPrDisplay): string { const label = getReviewLabel(review) - if (review.status === 'failure') { - return `${label} checks: Failed` - } - if (review.status === 'pending') { - return `${label} checks: Pending` - } - if (review.status === 'success') { - return `${label} checks: Passing` - } if (review.state === 'merged') { return `${label}: Merged` } @@ -83,6 +74,15 @@ function getReviewStatusTooltip(review: WorktreeCardPrDisplay): string { if (review.state === 'draft') { return `${label}: Draft` } + if (review.status === 'failure') { + return `${label} checks: Failed` + } + if (review.status === 'pending') { + return `${label} checks: Pending` + } + if (review.status === 'success') { + return `${label} checks: Passing` + } return `${label}: Open` } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 57eb0df34..96fb4c21c 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -8945,6 +8945,7 @@ }, "empty": { "state": { + "3322603418": "Pull request status unavailable", "5b0cfae9a5": "Create a {{value0}} to start checks and review.", "13e1c7d5ed": "No {{value0}} found", "d372072df1": "GitHub refresh is paused by the current rate-limit budget", @@ -8959,7 +8960,8 @@ "f8543140cc": "Publish this branch before creating a {{value0}}.", "41252bc53f": "Branch not published", "05e4aec17b": "{{value0}} checks will be available after the operation completes", - "d77c513c1e": "{{value0}} in progress" + "d77c513c1e": "{{value0}} in progress", + "b597440265": "Refresh GitHub status for this branch to load checks and review." } } } diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 019906660..9dddf512b 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -8945,6 +8945,7 @@ }, "empty": { "state": { + "3322603418": "Pull request status unavailable", "5b0cfae9a5": "Cree un {{value0}} para iniciar comprobaciones y revisiones.", "13e1c7d5ed": "No se encontró {{value0}}", "d372072df1": "La actualización de GitHub está pausada por el presupuesto de límite de velocidad actual", @@ -8959,7 +8960,8 @@ "f8543140cc": "Publique esta rama antes de crear un {{value0}}.", "41252bc53f": "Sucursal no publicada", "05e4aec17b": "{{value0}} cheques estarán disponibles una vez completada la operación.", - "d77c513c1e": "{{value0}} en progreso" + "d77c513c1e": "{{value0}} en progreso", + "b597440265": "Refresh GitHub status for this branch to load checks and review." } } } diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 27eb51852..98a63a019 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -8945,6 +8945,7 @@ }, "empty": { "state": { + "3322603418": "Pull request status unavailable", "5b0cfae9a5": "{{value0}} を作成してチェックとレビューを開始します。", "13e1c7d5ed": "{{value0}} が見つかりませんでした", "d372072df1": "現在のレート制限予算により GitHub の更新が一時停止されています", @@ -8959,7 +8960,8 @@ "f8543140cc": "{{value0}} を作成する前に、このブランチを公開してください。", "41252bc53f": "ブランチは公開されていません", "05e4aec17b": "{{value0}} チェックは操作の完了後に利用可能になります", - "d77c513c1e": "{{value0}} が進行中です" + "d77c513c1e": "{{value0}} が進行中です", + "b597440265": "Refresh GitHub status for this branch to load checks and review." } } } diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 8f4501add..db5eb893f 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -8945,6 +8945,7 @@ }, "empty": { "state": { + "3322603418": "Pull request status unavailable", "5b0cfae9a5": "체크와 리뷰를 시작하려면 {{value0}}을(를) 만드세요.", "13e1c7d5ed": "{{value0}}을(를) 찾을 수 없습니다.", "d372072df1": "현재 속도 제한 예산으로 인해 GitHub 새로 고침이 일시 중지되었습니다.", @@ -8959,7 +8960,8 @@ "f8543140cc": "{{value0}}을 만들기 전에 이 브랜치를 게시하세요.", "41252bc53f": "게시되지 않은 브랜치", "05e4aec17b": "{{value0}} 검사는 작업이 완료된 후에 사용할 수 있습니다.", - "d77c513c1e": "{{value0}} 진행 중" + "d77c513c1e": "{{value0}} 진행 중", + "b597440265": "Refresh GitHub status for this branch to load checks and review." } } } diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 9d4f9cd8d..9aab7faec 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -8945,6 +8945,7 @@ }, "empty": { "state": { + "3322603418": "Pull request status unavailable", "5b0cfae9a5": "创建 {{value0}} 以开始检查和评审。", "13e1c7d5ed": "未找到 {{value0}}", "d372072df1": "GitHub 刷新因当前速率限制预算而暂停", @@ -8959,7 +8960,8 @@ "f8543140cc": "在创建 {{value0}} 之前发布此分支。", "41252bc53f": "分支未发布", "05e4aec17b": "{{value0}} 检查将在操作完成后可用", - "d77c513c1e": "{{value0}} 正在进行中" + "d77c513c1e": "{{value0}} 正在进行中", + "b597440265": "Refresh GitHub status for this branch to load checks and review." } } } diff --git a/src/renderer/src/store/slices/github-pr-refresh-states-leak.test.ts b/src/renderer/src/store/slices/github-pr-refresh-states-leak.test.ts index d9d1a91ec..740968671 100644 --- a/src/renderer/src/store/slices/github-pr-refresh-states-leak.test.ts +++ b/src/renderer/src/store/slices/github-pr-refresh-states-leak.test.ts @@ -25,14 +25,15 @@ const MAX_ENTRIES = 2000 // prRefreshStates entry shapes (the module's PRRefreshState type is not exported). type SeedState = { - status: 'in-flight' | 'error' + status: 'queued' | 'in-flight' | 'paused' | 'skipped' | 'error' reason: GitHubPRRefreshReason updatedAt: number + pausedUntil?: number message?: string } function inFlightState(): SeedState { - return { status: 'in-flight', reason: 'visible', updatedAt: 0 } + return { status: 'in-flight', reason: 'visible', updatedAt: Date.now() } } function errorState(): SeedState { @@ -150,4 +151,263 @@ describe('prRefreshStates stays bounded (leak regression)', () => { expect(states['seed-1']).toBeUndefined() expect(states['newcomer']).toBeDefined() }) + + it('hides expired active states through the effective reader without mutating during read', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + try { + const store = createTestStore() + store.setState({ + prRefreshStates: { + stale: { status: 'in-flight', reason: 'visible', updatedAt: 1_000_000 - 121_000 }, + fresh: { status: 'in-flight', reason: 'visible', updatedAt: 1_000_000 - 10_000 } + } + }) + + expect(store.getState().getEffectiveGitHubPRRefreshState('stale', 1_000_000)).toBeUndefined() + expect(store.getState().getEffectiveGitHubPRRefreshState('fresh', 1_000_000)).toMatchObject({ + status: 'in-flight' + }) + expect(store.getState().prRefreshStates.stale).toBeDefined() + } finally { + vi.useRealTimers() + } + }) + + it('expires paused states after pausedUntil grace and rejects missing pause timestamps', () => { + const store = createTestStore() + store.setState({ + prRefreshStates: { + currentPause: { + status: 'paused', + reason: 'visible', + updatedAt: 1_000, + pausedUntil: 2_000 + }, + missingPause: { status: 'paused', reason: 'visible', updatedAt: 1_000 } + } + }) + + expect(store.getState().getEffectiveGitHubPRRefreshState('currentPause', 2_004)).toMatchObject({ + status: 'paused' + }) + expect(store.getState().getEffectiveGitHubPRRefreshState('currentPause', 7_001)).toBeUndefined() + expect(store.getState().getEffectiveGitHubPRRefreshState('missingPause', 1_500)).toBeUndefined() + }) + + it('prunes expired active states on refreshAll without writing a PR miss', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + try { + const store = createTestStore() + store.setState({ + prRefreshStates: { + stale: { status: 'queued', reason: 'visible', updatedAt: 1_000_000 - 121_000 }, + settled: { status: 'error', reason: 'visible', updatedAt: 1, message: 'boom' } + }, + prCache: { + stale: { data: null, fetchedAt: 1 } + }, + repos: [], + worktreesByRepo: {} + } as unknown as Partial) + + store.getState().refreshAllGitHub() + + expect(store.getState().prRefreshStates.stale).toBeUndefined() + expect(store.getState().prRefreshStates.settled).toBeDefined() + expect(store.getState().prCache.stale).toEqual({ data: null, fetchedAt: 1 }) + } finally { + vi.useRealTimers() + } + }) + + it('manual expiry does not remove a newer active state for the same cache key', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + try { + const store = createTestStore() + const token = { + sequence: 1, + status: 'in-flight' as const, + updatedAt: 1_000_000 - 121_000 + } + store.setState({ + prRefreshSequences: { branch: 2 }, + prRefreshStates: { + branch: { status: 'in-flight', reason: 'manual', updatedAt: 1_000_000 } + } + }) + + store.getState().expireGitHubPRRefreshState('branch', token, 1_000_000) + + expect(store.getState().prRefreshStates.branch).toMatchObject({ + status: 'in-flight', + updatedAt: 1_000_000 + }) + } finally { + vi.useRealTimers() + } + }) + + it('manual expiry does not notify subscribers when the token no longer matches', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + try { + const store = createTestStore() + const subscriber = vi.fn() + const unsubscribe = store.subscribe(subscriber) + store.setState({ + prRefreshSequences: { branch: 2 }, + prRefreshStates: { + branch: { status: 'in-flight', reason: 'manual', updatedAt: 1_000_000 } + } + }) + subscriber.mockClear() + + store.getState().expireGitHubPRRefreshState( + 'branch', + { + sequence: 1, + status: 'in-flight', + updatedAt: 1_000_000 - 121_000 + }, + 1_000_000 + ) + + expect(subscriber).not.toHaveBeenCalled() + unsubscribe() + } finally { + vi.useRealTimers() + } + }) + + it('manual expiry does not notify subscribers for an active state that is still fresh', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + try { + const store = createTestStore() + const subscriber = vi.fn() + store.setState({ + prRefreshSequences: { branch: 1 }, + prRefreshStates: { + branch: { status: 'in-flight', reason: 'manual', updatedAt: 1_000_000 } + } + }) + const unsubscribe = store.subscribe(subscriber) + + store.getState().expireGitHubPRRefreshState( + 'branch', + { + sequence: 1, + status: 'in-flight', + updatedAt: 1_000_000 + }, + 1_000_000 + ) + + expect(subscriber).not.toHaveBeenCalled() + unsubscribe() + } finally { + vi.useRealTimers() + } + }) + + it('manual expiry notifies subscribers when it removes the captured stale active state', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + try { + const store = createTestStore() + const subscriber = vi.fn() + store.setState({ + prRefreshSequences: { branch: 1 }, + prRefreshStates: { + branch: { status: 'in-flight', reason: 'manual', updatedAt: 1_000_000 - 121_000 } + } + }) + const unsubscribe = store.subscribe(subscriber) + + store.getState().expireGitHubPRRefreshState( + 'branch', + { + sequence: 1, + status: 'in-flight', + updatedAt: 1_000_000 - 121_000 + }, + 1_000_000 + ) + + expect(subscriber).toHaveBeenCalledTimes(1) + expect(store.getState().prRefreshStates.branch).toBeUndefined() + unsubscribe() + } finally { + vi.useRealTimers() + } + }) + + it('expires the stale active state captured by a rejected forced PR refresh', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + try { + const store = createTestStore() + const repoPath = '/repo' + const branch = 'feature/rejected-refresh' + const cacheKey = `${repoPath}::${branch}` + mockApi.gh.refreshPRNow.mockRejectedValueOnce(new Error('stale repo path')) + store.setState({ + prRefreshSequences: { [cacheKey]: 1 }, + prRefreshStates: { + [cacheKey]: { status: 'in-flight', reason: 'manual', updatedAt: 1_000_000 - 121_000 } + } + }) + + await expect( + store.getState().fetchPRForBranch(repoPath, branch, { force: true }) + ).resolves.toBeNull() + + expect(store.getState().prRefreshStates[cacheKey]).toBeUndefined() + expect(store.getState().prCache[cacheKey]).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + it('accepts a late terminal outcome after the active status timed out', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + try { + const store = createTestStore() + const repoPath = '/repo' + const branch = 'feature/late-outcome' + const cacheKey = `${repoPath}::${branch}` + + store.getState().applyGitHubPRRefreshEvent(statusEvent(cacheKey, 1)) + vi.setSystemTime(1_000_000 + 121_000) + expect(store.getState().getEffectiveGitHubPRRefreshState(cacheKey)).toBeUndefined() + + store.getState().applyGitHubPRRefreshEvent({ + sequence: 1, + reason: 'visible', + aliases: [{ cacheKey, repoPath, branch }], + outcome: { + kind: 'found', + pr: { + number: 12, + title: 'Late PR', + state: 'open', + url: 'https://github.com/acme/orca/pull/12', + checksStatus: 'pending', + updatedAt: '2026-03-28T00:00:00Z', + mergeable: 'UNKNOWN' + }, + fetchedAt: 1_000_000 + 121_000 + } + }) + + expect(store.getState().prCache[cacheKey]?.data).toMatchObject({ title: 'Late PR' }) + expect(store.getState().prRefreshStates[cacheKey]).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) }) diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index 9062068f2..2eb728491 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -629,7 +629,7 @@ type RepoScopedFetchOptions = FetchOptions & { repoId?: string } -type PRRefreshState = { +export type PRRefreshState = { status: 'queued' | 'in-flight' | 'paused' | 'skipped' | 'error' reason: GitHubPRRefreshReason updatedAt: number @@ -637,6 +637,15 @@ type PRRefreshState = { message?: string } +export type PRRefreshStateClearToken = { + sequence: number + status: PRRefreshState['status'] + updatedAt: number +} + +const PR_REFRESH_ACTIVE_STALE_MS = 120_000 +const PR_REFRESH_PAUSED_GRACE_MS = 5_000 + function bypassesGitHubPRRefreshFreshness(reason: GitHubPRRefreshReason): boolean { return reason === 'manual' || reason === 'active' || reason === 'post-push' } @@ -1464,6 +1473,88 @@ function capPrRefreshSequences( // realistic usage never reaches. Evicted entries self-heal on the next refresh event. const MAX_PR_REFRESH_STATE_ENTRIES = 2000 const SETTLED_PR_REFRESH_STATUSES = new Set(['error', 'skipped']) +const ACTIVE_PR_REFRESH_STATUSES = new Set([ + 'queued', + 'in-flight', + 'paused' +]) + +function isPRRefreshStateExpired(state: PRRefreshState, now: number): boolean { + const expiryAt = getGitHubPRRefreshStateExpiryAt(state) + return expiryAt !== null && now > expiryAt +} + +/** + * Captures the exact refresh snapshot a later timeout or request is allowed to clear. + */ +export function buildGitHubPRRefreshStateClearToken( + state: PRRefreshState | undefined, + sequences: Record, + cacheKey: string +): PRRefreshStateClearToken | null { + if (!state) { + return null + } + return { + sequence: sequences[cacheKey] ?? 0, + status: state.status, + updatedAt: state.updatedAt + } +} + +/** + * Returns the wall-clock expiry for transient refresh states; settled states persist. + */ +export function getGitHubPRRefreshStateExpiryAt(state: PRRefreshState | undefined): number | null { + if (!state) { + return null + } + if (state.status === 'queued' || state.status === 'in-flight') { + return Number.isFinite(state.updatedAt) ? state.updatedAt + PR_REFRESH_ACTIVE_STALE_MS : 0 + } + if (state.status === 'paused') { + return Number.isFinite(state.pausedUntil) + ? (state.pausedUntil ?? 0) + PR_REFRESH_PAUSED_GRACE_MS + : 0 + } + return null +} + +function isExpiredActivePRRefreshState(state: PRRefreshState, now: number): boolean { + return ACTIVE_PR_REFRESH_STATUSES.has(state.status) && isPRRefreshStateExpired(state, now) +} + +/** + * Reads refresh state for UI selectors while hiding stale active entries from view. + */ +export function getEffectiveGitHubPRRefreshState( + states: Record, + cacheKey: string, + now = Date.now() +): PRRefreshState | undefined { + const state = states[cacheKey] + if (!state || isExpiredActivePRRefreshState(state, now)) { + return undefined + } + return state +} + +function pruneExpiredPRRefreshStates( + states: Record, + now = Date.now() +): Record { + let next: Record | null = null + for (const [cacheKey, state] of Object.entries(states)) { + if (!isExpiredActivePRRefreshState(state, now)) { + continue + } + if (!next) { + next = { ...states } + } + delete next[cacheKey] + } + return next ?? states +} function capPrRefreshStates( states: Record, @@ -1614,6 +1705,12 @@ export type GitHubSlice = { reportVisibleGitHubPRRefreshCandidates: (worktreeIds: string[], generation: number) => void bumpGitHubPRVisibleRefreshGeneration: () => void applyGitHubPRRefreshEvent: (event: GitHubPRRefreshEvent) => void + getEffectiveGitHubPRRefreshState: (cacheKey: string, now?: number) => PRRefreshState | undefined + expireGitHubPRRefreshState: ( + cacheKey: string, + token: PRRefreshStateClearToken, + now?: number + ) => void /** * Why: returns cached work items immediately (null if none) and fires a * background refresh when stale. Callers can render the cached list while @@ -1806,6 +1903,40 @@ export const createGitHubSlice: StateCreator = (s workItemsInvalidationNonce: 0, projectViewCache: {}, + getEffectiveGitHubPRRefreshState: (cacheKey, now) => + getEffectiveGitHubPRRefreshState(get().prRefreshStates, cacheKey, now), + + expireGitHubPRRefreshState: (cacheKey, token, now = Date.now()) => { + const currentState = get() + const currentRefreshState = currentState.prRefreshStates[cacheKey] + if ( + !currentRefreshState || + !ACTIVE_PR_REFRESH_STATUSES.has(currentRefreshState.status) || + !isExpiredActivePRRefreshState(currentRefreshState, now) || + (currentState.prRefreshSequences[cacheKey] ?? 0) !== token.sequence || + currentRefreshState.status !== token.status || + currentRefreshState.updatedAt !== token.updatedAt + ) { + return + } + set((s) => { + const state = s.prRefreshStates[cacheKey] + if ( + !state || + !ACTIVE_PR_REFRESH_STATUSES.has(state.status) || + !isExpiredActivePRRefreshState(state, now) || + (s.prRefreshSequences[cacheKey] ?? 0) !== token.sequence || + state.status !== token.status || + state.updatedAt !== token.updatedAt + ) { + return s + } + const nextStates = { ...s.prRefreshStates } + delete nextStates[cacheKey] + return { prRefreshStates: nextStates } + }) + }, + fetchProjectViewTable: async (args, options) => { const target = getActiveRuntimeTarget(get().settings) const sourceScope = projectViewSourceScope(get().settings) @@ -2709,6 +2840,12 @@ export const createGitHubSlice: StateCreator = (s const generation = (prRequestGenerations.get(cacheKey) ?? 0) + 1 const requestStartedAt = Date.now() const requestStartedHostedReviewEntry = get().hostedReviewCache[hostedReviewCacheKey] + const requestStartedPRRefreshState = get().prRefreshStates[cacheKey] + const requestStartedPRRefreshToken = buildGitHubPRRefreshStateClearToken( + requestStartedPRRefreshState, + get().prRefreshSequences, + cacheKey + ) prRequestGenerations.set(cacheKey, generation) const request = (async () => { @@ -2828,6 +2965,9 @@ export const createGitHubSlice: StateCreator = (s prRequestGenerations.delete(cacheKey) } } + if (requestStartedPRRefreshToken) { + get().expireGitHubPRRefreshState(cacheKey, requestStartedPRRefreshToken) + } } })() @@ -3511,10 +3651,11 @@ export const createGitHubSlice: StateCreator = (s applyGitHubPRRefreshEvent: (event) => { set((s) => { const nextSequences = { ...s.prRefreshSequences } - const nextStates = { ...s.prRefreshStates } + const prunedStates = pruneExpiredPRRefreshStates(s.prRefreshStates) + const nextStates = { ...prunedStates } let nextPRCache = s.prCache let nextHostedReviewCache = s.hostedReviewCache ?? {} - let changed = false + let changed = prunedStates !== s.prRefreshStates for (const alias of event.aliases) { const aliasExecutionHostId = getRefreshAliasExecutionHostId(alias) @@ -3706,7 +3847,8 @@ export const createGitHubSlice: StateCreator = (s issueCache: evictStaleEntries(s.issueCache), checksCache: evictStaleEntries(s.checksCache), workItemsCache: evictStaleEntries(s.workItemsCache), - projectViewCache: evictStaleEntries(s.projectViewCache) + projectViewCache: evictStaleEntries(s.projectViewCache), + prRefreshStates: pruneExpiredPRRefreshStates(s.prRefreshStates) })) // Why: prRequestGenerations tracks only live inflight fetches and is