Close PR refresh stale-state gaps

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo-H
2026-05-14 02:50:03 -04:00
co-authored by Orca
parent 8d0a11b4ee
commit 4aca41adfe
8 changed files with 248 additions and 32 deletions
@@ -55,6 +55,20 @@ function makePR(overrides: Partial<PRInfo> = {}): PRInfo {
}
}
function deferred<T>(): {
promise: Promise<T>
resolve: (value: T) => void
reject: (error: unknown) => void
} {
let resolve!: (value: T) => void
let reject!: (error: unknown) => void
const promise = new Promise<T>((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
+57 -3
View File
@@ -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',
+2
View File
@@ -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())
}
@@ -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<string>('')
const conflictSummaryRefreshKeyRef = useRef<string | null>(null)
const refreshRequestKeyRef = useRef<string | null>(null)
const refreshContextKeyRef = useRef<string | null>(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 && (
<button
className="mt-3 px-3 py-1 text-xs font-medium rounded-md border border-border bg-accent/50 text-foreground hover:bg-accent transition-colors disabled:opacity-50"
disabled={emptyRefreshing || isCheckingPR || isPausedPRRefresh}
disabled={emptyRefreshing}
onClick={() => {
if (!activeWorktreeId) {
return
@@ -538,13 +580,7 @@ export default function ChecksPanel(): React.JSX.Element {
})
}}
>
{isQueuedPRRefresh
? 'Queued'
: emptyRefreshing || isInFlightPRRefresh
? 'Refreshing...'
: isPausedPRRefresh
? 'Paused'
: 'Refresh'}
{emptyRefreshing ? 'Refreshing...' : 'Refresh'}
</button>
)}
</div>
@@ -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
])
-5
View File
@@ -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
+10 -1
View File
@@ -464,6 +464,7 @@ export type GitHubSlice = {
commentsCache: Record<string, CacheEntry<PRComment[]>>
prRefreshSequences: Record<string, number>
prRefreshStates: Record<string, PRRefreshState>
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<AppState, [], [], GitHubSlice> = (s
commentsCache: {},
prRefreshSequences: {},
prRefreshStates: {},
prVisibleRefreshGeneration: 0,
workItemsCache: {},
workItemsInvalidationNonce: 0,
projectViewCache: {},
@@ -1525,6 +1528,10 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
}
},
bumpGitHubPRVisibleRefreshGeneration: () => {
set((s) => ({ prVisibleRefreshGeneration: s.prVisibleRefreshGeneration + 1 }))
},
applyGitHubPRRefreshEvent: (event) => {
set((s) => {
const nextSequences = { ...s.prRefreshSequences }
@@ -1617,7 +1624,9 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (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) {
-3
View File
@@ -35,7 +35,6 @@ export type SshSlice = {
setSshTargetLabels: (labels: Map<string, string>) => 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<AppState, [], [], SshSlice> = (set) =>
set((s) => ({
sshCredentialQueue: s.sshCredentialQueue.filter((req) => req.requestId !== requestId)
})),
bumpSshConnectedGeneration: () =>
set((s) => ({ sshConnectedGeneration: s.sshConnectedGeneration + 1 })),
setPortForwards: (targetId, forwards) =>
set((s) => {