Keep merged PRs visible after refreshes (#6456)

This commit is contained in:
Brennan Benson
2026-06-26 17:15:14 -07:00
committed by GitHub
parent e2bf3e4466
commit 8c81c30f6a
7 changed files with 695 additions and 36 deletions
@@ -81,7 +81,7 @@ import { normalizeHostedReviewHeadRef } from '../../../../shared/hosted-review-r
import { getHostedReviewCacheKey, refreshHostedReviewCard } from '@/store/slices/hosted-review'
import { toast } from 'sonner'
import { useConfirmationDialog } from '@/components/confirmation-dialog'
import { type ChecksPanelReview, gitHubPRToChecksPanelReview } from './checks-panel-review'
import { type ChecksPanelReview, selectChecksPanelReview } from './checks-panel-review'
import {
checksPanelAsyncResultKey,
checksPanelHostedReviewAsyncResultKey,
@@ -645,10 +645,14 @@ export default function ChecksPanel(): React.JSX.Element {
const linkedBitbucketPR = activeWorktree?.linkedBitbucketPR ?? null
const linkedAzureDevOpsPR = activeWorktree?.linkedAzureDevOpsPR ?? null
const linkedGiteaPR = activeWorktree?.linkedGiteaPR ?? null
const gitLabHostedReview = hostedReview?.provider === 'gitlab' ? hostedReview : null
const activeReview: ChecksPanelReview | null =
gitLabHostedReview ??
(linkedGitLabMR !== null ? null : pr ? gitHubPRToChecksPanelReview(pr) : null)
const activeReview: ChecksPanelReview | null = selectChecksPanelReview({
hostedReview,
pr,
linkedGitLabMR,
linkedBitbucketPR,
linkedAzureDevOpsPR,
linkedGiteaPR
})
const activeGitLabReview = isGitLabChecksPanelReview(activeReview) ? activeReview : null
const isGitLabReviewContext = Boolean(activeGitLabReview || linkedGitLabMR !== null)
const activeConflictReview = activeReview?.mergeable === 'CONFLICTING' ? activeReview : null
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { gitHubPRToChecksPanelReview } from './checks-panel-review'
import { gitHubPRToChecksPanelReview, selectChecksPanelReview } from './checks-panel-review'
import type { PRInfo } from '../../../../shared/types'
import type { HostedReviewInfo } from '../../../../shared/hosted-review'
function makePR(overrides: Partial<PRInfo> = {}): PRInfo {
return {
@@ -15,6 +16,20 @@ function makePR(overrides: Partial<PRInfo> = {}): PRInfo {
}
}
function makeGitLabReview(overrides: Partial<HostedReviewInfo> = {}): HostedReviewInfo {
return {
provider: 'gitlab',
number: 9,
title: 'GitLab MR',
state: 'open',
url: 'https://gitlab.com/acme/widgets/-/merge_requests/9',
status: 'pending',
updatedAt: '2026-06-02T00:00:00Z',
mergeable: 'UNKNOWN',
...overrides
}
}
describe('gitHubPRToChecksPanelReview', () => {
// Why: the right-sidebar merge presenter reads these fields off the converted
// review object. PR #4001 dropped them here, so review-required/merge-queue
@@ -45,3 +60,51 @@ describe('gitHubPRToChecksPanelReview', () => {
expect(review.headSha).toBe('abc123')
})
})
describe('selectChecksPanelReview', () => {
it('uses GitLab hosted review metadata ahead of GitHub PR cache', () => {
const review = makeGitLabReview({ number: 34 })
expect(
selectChecksPanelReview({
hostedReview: review,
pr: makePR({ number: 12 }),
linkedGitLabMR: 34,
linkedBitbucketPR: null,
linkedAzureDevOpsPR: null,
linkedGiteaPR: null
})
).toBe(review)
})
it('uses GitHub PR cache when no non-GitHub review is linked', () => {
const selected = selectChecksPanelReview({
hostedReview: null,
pr: makePR({ number: 12, state: 'merged' }),
linkedGitLabMR: null,
linkedBitbucketPR: null,
linkedAzureDevOpsPR: null,
linkedGiteaPR: null
})
expect(selected).toMatchObject({ provider: 'github', number: 12, state: 'merged' })
})
it.each([
{ provider: 'GitLab', linkedGitLabMR: 7 },
{ provider: 'Bitbucket', linkedBitbucketPR: 8 },
{ provider: 'Azure DevOps', linkedAzureDevOpsPR: 9 },
{ provider: 'Gitea', linkedGiteaPR: 10 }
])('does not surface GitHub PR cache when a $provider review is linked', (links) => {
expect(
selectChecksPanelReview({
hostedReview: null,
pr: makePR({ number: 12, state: 'merged' }),
linkedGitLabMR: links.linkedGitLabMR ?? null,
linkedBitbucketPR: links.linkedBitbucketPR ?? null,
linkedAzureDevOpsPR: links.linkedAzureDevOpsPR ?? null,
linkedGiteaPR: links.linkedGiteaPR ?? null
})
).toBeNull()
})
})
@@ -4,8 +4,40 @@ import { hostedReviewInfoFromGitHubPRInfo } from '../../../../shared/hosted-revi
export type ChecksPanelReview = HostedReviewInfo
export type ChecksPanelReviewSelectionInput = {
hostedReview: HostedReviewInfo | null | undefined
pr: PRInfo | null | undefined
linkedGitLabMR: number | null
linkedBitbucketPR: number | null
linkedAzureDevOpsPR: number | null
linkedGiteaPR: number | null
}
export function gitHubPRToChecksPanelReview(pr: PRInfo): ChecksPanelReview {
// Why: the checks panel must not maintain a second GitHub PR metadata mapper;
// merge-state fields drifting here regressed the right-sidebar action label.
return hostedReviewInfoFromGitHubPRInfo(pr)
}
export function selectChecksPanelReview({
hostedReview,
pr,
linkedGitLabMR,
linkedBitbucketPR,
linkedAzureDevOpsPR,
linkedGiteaPR
}: ChecksPanelReviewSelectionInput): ChecksPanelReview | null {
const gitLabHostedReview = hostedReview?.provider === 'gitlab' ? hostedReview : null
if (gitLabHostedReview) {
return gitLabHostedReview
}
const hasNonGitHubLinkedReview =
linkedGitLabMR !== null ||
linkedBitbucketPR !== null ||
linkedAzureDevOpsPR !== null ||
linkedGiteaPR !== null
if (hasNonGitHubLinkedReview) {
return null
}
return pr ? gitHubPRToChecksPanelReview(pr) : null
}
@@ -0,0 +1,190 @@
import { renderToStaticMarkup } from 'react-dom/server'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type {
GlobalSettings,
PRInfo,
Repo,
Worktree,
WorktreeCardProperty
} from '../../../../shared/types'
const fetchHostedReviewForBranch = vi.fn()
const fetchIssue = vi.fn()
const fetchLinearIssue = vi.fn()
const openModal = vi.fn()
const updateWorktreeMeta = vi.fn()
let worktreeCardProperties: WorktreeCardProperty[] = ['pr']
let hostedReviewCache: Record<string, unknown> = {}
let prCache: Record<string, unknown> = {}
let settings: Partial<GlobalSettings> | null = null
vi.mock('@/store', () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
deleteStateByWorktreeId: {},
fetchHostedReviewForBranch,
fetchIssue,
fetchLinearIssue,
gitConflictOperationByWorktree: {},
hostedReviewCache,
issueCache: {},
linearIssueCache: {},
openModal,
prCache,
projectGroups: [],
remoteBranchConflictByWorktreeId: {},
settings,
sshConnectionStates: new Map(),
sshTargetLabels: new Map(),
updateWorktreeMeta,
workspacePortScan: null,
worktreeCardProperties
})
}))
vi.mock('@/lib/worktree-activation', () => ({
activateAndRevealWorktree: vi.fn()
}))
vi.mock('@/components/ui/tooltip', () => ({
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipContent: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>
}))
vi.mock('./use-worktree-activity-status', () => ({
useWorktreeActivityStatus: () => 'active'
}))
vi.mock('./CacheTimer', () => ({
default: () => null,
usePromptCacheCountdownStartedAt: () => null
}))
vi.mock('./WorktreeCardAgents', () => ({
default: () => null
}))
vi.mock('./SshDisconnectedDialog', () => ({
SshDisconnectedDialog: () => null
}))
vi.mock('./WorktreeContextMenu', () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
CLOSE_ALL_CONTEXT_MENUS_EVENT: 'orca:test-close-context-menus',
WORKTREE_NATIVE_CONTEXT_MENU_ATTR: 'data-worktree-native-context-menu',
WORKTREE_CONTEXT_MENU_SCOPE_ATTR: 'data-orca-context-menu-scope'
}))
function makeRepo(): Repo {
return {
id: 'repo-1',
path: '/repo',
displayName: 'orca',
badgeColor: '#999999',
addedAt: 1
}
}
function makeWorktree(overrides: Partial<Worktree> = {}): Worktree {
return {
id: 'repo-1::/repo/worktrees/pr-456',
repoId: 'repo-1',
path: '/repo/worktrees/pr-456',
displayName: 'Fix stale GH PR',
branch: 'feature/local-branch',
head: 'abc123',
isBare: false,
isMainWorktree: false,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 1,
...overrides
}
}
function makePRInfo(overrides: Partial<PRInfo> = {}): PRInfo {
return {
number: 6340,
title: 'Merged PR still checked out',
state: 'merged',
url: 'https://github.com/acme/orca/pull/6340',
checksStatus: 'success',
updatedAt: '2026-05-17T00:00:00.000Z',
mergeable: 'MERGEABLE',
headSha: 'abc123',
...overrides
}
}
function renderWorktreeCardMarkup(element: ReactNode): string {
return renderToStaticMarkup(<>{element}</>)
}
describe('WorktreeCard merged PR fallback display', () => {
beforeEach(() => {
vi.clearAllMocks()
settings = { compactWorktreeCards: false, experimentalNewWorktreeCardStyle: false }
worktreeCardProperties = ['pr']
hostedReviewCache = {
'local::repo-1::feature/local-branch': {
data: null,
fetchedAt: 200
}
}
prCache = {}
})
it('shows cached merged PR when a newer hosted-review miss still matches the worktree head', async () => {
prCache = {
'repo-1::feature/local-branch': {
data: makePRInfo(),
fetchedAt: 100
}
}
const { default: WorktreeCard } = await import('./WorktreeCard')
const markup = renderWorktreeCardMarkup(
<WorktreeCard
worktree={makeWorktree({ linkedPR: null, head: 'abc123' })}
repo={makeRepo()}
isActive={false}
/>
)
expect(markup).toContain('Linked PR #6340')
expect(markup).not.toContain('Branch')
})
it('suppresses cached merged PR after a newer hosted-review miss when the worktree head moved', async () => {
prCache = {
'repo-1::feature/local-branch': {
data: makePRInfo({
title: 'Merged PR no longer checked out',
headSha: 'old-head'
}),
fetchedAt: 100
}
}
const { default: WorktreeCard } = await import('./WorktreeCard')
const markup = renderWorktreeCardMarkup(
<WorktreeCard
worktree={makeWorktree({ linkedPR: null, head: 'new-head' })}
repo={makeRepo()}
isActive={false}
/>
)
expect(markup).not.toContain('Linked PR #6340')
expect(markup).not.toContain('Merged PR no longer checked out')
})
})
@@ -36,7 +36,8 @@ import type {
Worktree,
Repo,
IssueInfo,
LinearIssue
LinearIssue,
PRInfo
} from '../../../../shared/types'
import { CONFLICT_OPERATION_LABELS } from './WorktreeCardHelpers'
import {
@@ -152,6 +153,20 @@ function isWebClient(): boolean {
return Boolean((window as unknown as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__)
}
function isCachedMergedBranchPRCurrentForWorktree(
cachedPR: PRInfo | null | undefined,
worktree: Worktree
): boolean {
return (
cachedPR?.state === 'merged' &&
typeof cachedPR.headSha === 'string' &&
cachedPR.headSha.length > 0 &&
typeof worktree.head === 'string' &&
worktree.head.length > 0 &&
cachedPR.headSha === worktree.head
)
}
function getDirectoryName(folderPath: string): string {
const normalized = folderPath.replace(/[\\/]+$/, '')
const parts = normalized.split(/[\\/]+/)
@@ -459,17 +474,23 @@ const WorktreeCard = React.memo(function WorktreeCard({
linkedGiteaPR !== null
// Why: ChecksPanel can discover a branch PR before hosted-review metadata
// warms, and transient older hosted-review misses can race with that cache.
// Newer hosted-review misses still win so stale PR cache cannot resurrect.
// A newer miss only yields to merged PR cache when the stored worktree head
// proves the cached PR still describes the checked-out commit.
const cachedBranchPR = prCacheEntry?.data
const cachedBranchPRFetchedAt = prCacheEntry?.fetchedAt
const cachedMergedBranchPRMatchesCurrentHead = isCachedMergedBranchPRCurrentForWorktree(
cachedBranchPR,
worktree
)
const useCachedBranchReview =
cachedBranchPR !== undefined &&
cachedBranchPR !== null &&
!hasNonGitHubLinkedReview &&
(hostedReview === undefined ||
(hostedReview === null &&
cachedBranchPRFetchedAt !== undefined &&
cachedBranchPRFetchedAt > (hostedReviewEntry?.fetchedAt ?? 0)))
((cachedBranchPRFetchedAt !== undefined &&
cachedBranchPRFetchedAt > (hostedReviewEntry?.fetchedAt ?? 0)) ||
cachedMergedBranchPRMatchesCurrentHead)))
const cachedBranchReview = useCachedBranchReview
? hostedReviewInfoFromGitHubPRInfo(cachedBranchPR)
: hostedReview
+313 -1
View File
@@ -17,7 +17,7 @@ import {
} from './github'
import { createHostedReviewSlice } from './hosted-review'
import type { AppState } from '../types'
import type { GitHubWorkItem, PRInfo } from '../../../../shared/types'
import type { GitHubWorkItem, PRInfo, Worktree } from '../../../../shared/types'
import type { HostedReviewInfo } from '../../../../shared/hosted-review'
import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE } from '../../../../shared/work-items'
import {
@@ -104,6 +104,29 @@ function makePR(overrides: Partial<PRInfo> = {}): PRInfo {
}
}
function makePRRefreshWorktree(overrides: Partial<Worktree> = {}): Worktree {
return {
id: 'wt-pr-refresh',
repoId: 'repo-1',
path: '/repo/worktrees/pr-refresh',
displayName: 'PR refresh',
branch: 'feature/pr-refresh',
head: 'head-oid',
isBare: false,
isMainWorktree: false,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 1,
...overrides
}
}
function githubSourceContext(
hostId: TaskSourceContext['hostId'],
repoId = 'source-repo-id'
@@ -1471,6 +1494,7 @@ describe('createGitHubSlice.fetchPRForBranch', () => {
afterEach(() => {
_clearGitHubPRRefreshStartedEntriesForTest()
vi.useRealTimers()
})
it('lets a forced refresh bypass a non-forced inflight request and keeps the newer result', async () => {
@@ -2044,6 +2068,150 @@ describe('createGitHubSlice.fetchPRForBranch', () => {
})
})
it('preserves cached merged PR data when a forced no-PR refresh matches the worktree head', async () => {
vi.useFakeTimers()
const store = createTestStore()
const repoPath = '/repo'
const repoId = 'repo-1'
const branch = 'feature/merged-pr-head-match'
const worktreeId = 'wt-merged-direct-match'
const cachedPR = makePR({
number: 12,
title: 'Merged PR still checked out',
state: 'merged',
headSha: 'merged-head'
})
store.setState({
repos: [{ id: repoId, path: repoPath, name: 'repo', kind: 'git' }],
worktreesByRepo: {
[repoId]: [
makePRRefreshWorktree({
id: worktreeId,
repoId,
branch,
head: 'merged-head'
})
]
},
prCache: {
[`${repoId}::${branch}`]: {
data: cachedPR,
fetchedAt: 1
}
}
} as unknown as Partial<AppState>)
mockApi.gh.refreshPRNow.mockResolvedValueOnce({ kind: 'no-pr', fetchedAt: 2 })
await expect(
store.getState().fetchPRForBranch(repoPath, branch, {
force: true,
repoId,
worktreeId
})
).resolves.toEqual(cachedPR)
expect(store.getState().prCache[`${repoId}::${branch}`]).toEqual({
data: cachedPR,
fetchedAt: 1
})
await vi.advanceTimersByTimeAsync(1000)
expect(mockApi.cache.setGitHub).not.toHaveBeenCalled()
})
it.each([
{
name: 'worktree id is missing',
worktreeId: undefined,
linkedPRNumber: undefined,
worktreesByRepo: {}
},
{
name: 'worktree cannot be found',
worktreeId: 'wt-missing',
linkedPRNumber: undefined,
worktreesByRepo: { 'repo-1': [] }
},
{
name: 'worktree head is empty',
worktreeId: 'wt-empty-head',
linkedPRNumber: undefined,
worktreesByRepo: {
'repo-1': [
makePRRefreshWorktree({
id: 'wt-empty-head',
branch: 'feature/merged-pr-stale-direct',
head: ''
})
]
}
},
{
name: 'cached PR head differs from worktree head',
worktreeId: 'wt-moved-head',
linkedPRNumber: undefined,
worktreesByRepo: {
'repo-1': [
makePRRefreshWorktree({
id: 'wt-moved-head',
branch: 'feature/merged-pr-stale-direct',
head: 'new-head'
})
]
}
},
{
name: 'an explicit linked PR lookup misses',
worktreeId: 'wt-linked-pr-miss',
linkedPRNumber: 12,
worktreesByRepo: {
'repo-1': [
makePRRefreshWorktree({
id: 'wt-linked-pr-miss',
branch: 'feature/merged-pr-stale-direct',
head: 'merged-head',
linkedPR: 12
})
]
}
}
])('clears cached merged PR data on forced no-PR refresh when $name', async (testCase) => {
const store = createTestStore()
const repoPath = '/repo'
const repoId = 'repo-1'
const branch = 'feature/merged-pr-stale-direct'
const cachedPR = makePR({
number: 12,
title: 'Stale merged PR',
state: 'merged',
headSha: 'merged-head'
})
store.setState({
repos: [{ id: repoId, path: repoPath, name: 'repo', kind: 'git' }],
worktreesByRepo: testCase.worktreesByRepo,
prCache: {
[`${repoId}::${branch}`]: {
data: cachedPR,
fetchedAt: 1
}
}
} as unknown as Partial<AppState>)
mockApi.gh.refreshPRNow.mockResolvedValueOnce({ kind: 'no-pr', fetchedAt: 2 })
await expect(
store.getState().fetchPRForBranch(repoPath, branch, {
force: true,
repoId,
worktreeId: testCase.worktreeId,
linkedPRNumber: testCase.linkedPRNumber
})
).resolves.toBeNull()
expect(store.getState().prCache[`${repoId}::${branch}`]).toEqual({
data: null,
fetchedAt: 2
})
})
it('uses a GitHub hosted-review cache entry as the fallback PR for direct refreshes', async () => {
const store = createTestStore()
const repoPath = '/repo'
@@ -2233,6 +2401,150 @@ describe('createGitHubSlice.fetchPRForBranch', () => {
})
})
it('preserves cached merged PR data when a no-PR refresh event matches the worktree head', () => {
vi.useFakeTimers()
const store = createTestStore()
const repoPath = '/repo'
const repoId = 'repo-1'
const branch = 'feature/event-merged-pr-head-match'
const cacheKey = `${repoId}::${branch}`
const worktreeId = 'wt-merged-event-match'
const cachedPR = makePR({
number: 12,
title: 'Merged event PR still checked out',
state: 'merged',
headSha: 'merged-head'
})
store.setState({
worktreesByRepo: {
[repoId]: [
makePRRefreshWorktree({
id: worktreeId,
repoId,
branch,
head: 'merged-head'
})
]
},
prCache: {
[cacheKey]: {
data: cachedPR,
fetchedAt: 1
}
}
} as unknown as Partial<AppState>)
store.getState().applyGitHubPRRefreshEvent({
sequence: 1,
aliases: [{ cacheKey, repoId, repoPath, branch, worktreeId }],
reason: 'visible',
outcome: { kind: 'no-pr', fetchedAt: 2 }
})
expect(store.getState().prCache[cacheKey]).toEqual({ data: cachedPR, fetchedAt: 1 })
vi.advanceTimersByTime(1000)
expect(mockApi.cache.setGitHub).not.toHaveBeenCalled()
})
it.each([
{
name: 'worktree id is missing',
worktreeId: undefined,
linkedPRNumber: undefined,
worktreesByRepo: {}
},
{
name: 'worktree cannot be found',
worktreeId: 'wt-missing-event',
linkedPRNumber: undefined,
worktreesByRepo: { 'repo-1': [] }
},
{
name: 'worktree head is empty',
worktreeId: 'wt-empty-event-head',
linkedPRNumber: undefined,
worktreesByRepo: {
'repo-1': [
makePRRefreshWorktree({
id: 'wt-empty-event-head',
branch: 'feature/event-merged-pr-stale',
head: ''
})
]
}
},
{
name: 'cached PR head differs from worktree head',
worktreeId: 'wt-moved-event-head',
linkedPRNumber: undefined,
worktreesByRepo: {
'repo-1': [
makePRRefreshWorktree({
id: 'wt-moved-event-head',
branch: 'feature/event-merged-pr-stale',
head: 'new-head'
})
]
}
},
{
name: 'an explicit linked PR lookup misses',
worktreeId: 'wt-linked-event-miss',
linkedPRNumber: 12,
worktreesByRepo: {
'repo-1': [
makePRRefreshWorktree({
id: 'wt-linked-event-miss',
branch: 'feature/event-merged-pr-stale',
head: 'merged-head',
linkedPR: 12
})
]
}
}
])('clears cached merged PR data on no-PR refresh event when $name', (testCase) => {
const store = createTestStore()
const repoPath = '/repo'
const repoId = 'repo-1'
const branch = 'feature/event-merged-pr-stale'
const cacheKey = `${repoId}::${branch}`
const cachedPR = makePR({
number: 12,
title: 'Stale merged event PR',
state: 'merged',
headSha: 'merged-head'
})
store.setState({
worktreesByRepo: testCase.worktreesByRepo,
prCache: {
[cacheKey]: {
data: cachedPR,
fetchedAt: 1
}
}
} as unknown as Partial<AppState>)
store.getState().applyGitHubPRRefreshEvent({
sequence: 1,
aliases: [
{
cacheKey,
repoId,
repoPath,
branch,
worktreeId: testCase.worktreeId,
linkedPRNumber: testCase.linkedPRNumber
}
],
reason: 'visible',
outcome: { kind: 'no-pr', fetchedAt: 2 }
})
expect(store.getState().prCache[cacheKey]).toEqual({ data: null, fetchedAt: 2 })
})
it('updates hosted review cache from GitHub PR refresh events', () => {
const store = createTestStore()
const repoPath = '/repo'
+62 -25
View File
@@ -1199,21 +1199,38 @@ function shouldWritePRCacheForHostedReviewSync(args: {
function shouldPreserveExistingPRForFallbackMiss(args: {
currentPR: PRInfo | null | undefined
nextPR: PRInfo | null
state: AppState
worktreeId?: string
linkedPRNumber?: number | null
fallbackPRNumber?: number | null
fallbackPRSource?: GitHubPRFallbackSource | null
}): boolean {
const worktree = args.worktreeId ? findWorktreeById(args.state, args.worktreeId) : null
const worktreeHead = worktree?.head
// Why: merged branch PRs are only safe to keep when cached PR metadata still
// matches the commit this stored worktree is actually on.
const preservesMergedPRForCurrentHead =
args.nextPR === null &&
args.linkedPRNumber == null &&
args.currentPR?.state === 'merged' &&
typeof args.currentPR.headSha === 'string' &&
args.currentPR.headSha.length > 0 &&
typeof worktreeHead === 'string' &&
worktreeHead.length > 0 &&
args.currentPR.headSha === worktreeHead
// Why: fallback PR numbers come from already-visible cache, not durable
// worktree metadata. A branch/fallback miss is weaker than the current exact
// PR context, except when the fallback is the hosted-review entry being
// refreshed; that entry must not protect itself from exact misses.
return (
const preservesFallbackPR =
args.nextPR === null &&
args.linkedPRNumber == null &&
args.fallbackPRNumber != null &&
args.fallbackPRSource !== 'hosted-review' &&
args.currentPR?.number === args.fallbackPRNumber
)
return preservesFallbackPR || preservesMergedPRForCurrentHead
}
function applyPRCacheResult(
@@ -1279,6 +1296,7 @@ function setGitHubPRResultCaches(
executionHostId?: string | null
pr: PRInfo | null
fetchedAt: number
worktreeId?: string
linkedPRNumber?: number | null
fallbackPRNumber?: number | null
fallbackPRSource?: GitHubPRFallbackSource | null
@@ -1310,27 +1328,30 @@ function setGitHubPRResultCaches(
args.connectionId,
args.executionHostId
)
const nextPRCache = applyPRCacheResult(
state.prCache,
args.prCacheKey,
args.pr,
args.fetchedAt,
shouldWritePRCacheForHostedReviewSync({
hostedReviewSyncAccepted: hostedReviewSync.accepted,
hostedReviewEntry: state.hostedReviewCache[hostedReviewCacheKey],
pr: args.pr,
linkedPRNumber: args.linkedPRNumber,
fallbackPRNumber: args.fallbackPRNumber
}),
shouldPreserveExistingPRForFallbackMiss({
currentPR: state.prCache[args.prCacheKey]?.data,
nextPR: args.pr,
state,
worktreeId: args.worktreeId,
linkedPRNumber: args.linkedPRNumber,
fallbackPRNumber: args.fallbackPRNumber,
fallbackPRSource: args.fallbackPRSource
})
)
return {
prCache: applyPRCacheResult(
state.prCache,
args.prCacheKey,
args.pr,
args.fetchedAt,
shouldWritePRCacheForHostedReviewSync({
hostedReviewSyncAccepted: hostedReviewSync.accepted,
hostedReviewEntry: state.hostedReviewCache[hostedReviewCacheKey],
pr: args.pr,
linkedPRNumber: args.linkedPRNumber,
fallbackPRNumber: args.fallbackPRNumber
}),
shouldPreserveExistingPRForFallbackMiss({
currentPR: state.prCache[args.prCacheKey]?.data,
nextPR: args.pr,
linkedPRNumber: args.linkedPRNumber,
fallbackPRNumber: args.fallbackPRNumber,
fallbackPRSource: args.fallbackPRSource
})
),
...(nextPRCache === state.prCache ? {} : { prCache: nextPRCache }),
...(hostedReviewSync.cache === state.hostedReviewCache
? {}
: { hostedReviewCache: hostedReviewSync.cache })
@@ -1349,6 +1370,8 @@ function applyGitHubPRResultToCaches(args: {
executionHostId?: string | null
pr: PRInfo | null
fetchedAt: number
state: AppState
worktreeId?: string
linkedPRNumber?: number | null
fallbackPRNumber?: number | null
fallbackPRSource?: GitHubPRFallbackSource | null
@@ -1398,6 +1421,8 @@ function applyGitHubPRResultToCaches(args: {
shouldPreserveExistingPRForFallbackMiss({
currentPR: args.prCache[args.prCacheKey]?.data,
nextPR: args.pr,
state: args.state,
worktreeId: args.worktreeId,
linkedPRNumber: args.linkedPRNumber,
fallbackPRNumber: args.fallbackPRNumber,
fallbackPRSource: args.fallbackPRSource
@@ -2913,6 +2938,7 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
}
if (prRequestGenerations.get(cacheKey) === generation) {
let skippedStaleLinkedPRLookup = false
let didUpdatePRCache = false
set((s) => {
// Why: unlinking a PR while an exact linked-PR lookup is in flight
// must prevent that older result from restoring the manual link UI.
@@ -2920,7 +2946,7 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
skippedStaleLinkedPRLookup = true
return {}
}
return setGitHubPRResultCaches(s, {
const updates = setGitHubPRResultCaches(s, {
prCacheKey: cacheKey,
repoPath,
branch,
@@ -2930,22 +2956,29 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
executionHostId: repo?.executionHostId,
pr,
fetchedAt: outcome.fetchedAt,
worktreeId: options?.worktreeId,
linkedPRNumber,
fallbackPRNumber,
fallbackPRSource,
requestStartedAt,
requestStartedEntry: requestStartedHostedReviewEntry
})
didUpdatePRCache = updates.prCache !== undefined
return updates
})
if (skippedStaleLinkedPRLookup) {
return null
}
debouncedSaveCache(get())
if (didUpdatePRCache) {
debouncedSaveCache(get())
}
}
if (
shouldPreserveExistingPRForFallbackMiss({
currentPR: get().prCache[cacheKey]?.data,
nextPR: pr,
state: get(),
worktreeId: options?.worktreeId,
linkedPRNumber,
fallbackPRNumber,
fallbackPRSource
@@ -3649,6 +3682,7 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
},
applyGitHubPRRefreshEvent: (event) => {
let didUpdatePRCache = false
set((s) => {
const nextSequences = { ...s.prRefreshSequences }
const prunedStates = pruneExpiredPRRefreshStates(s.prRefreshStates)
@@ -3775,12 +3809,15 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
executionHostId: aliasExecutionHostId,
pr: data,
fetchedAt: event.outcome.fetchedAt,
state: s,
worktreeId: alias.worktreeId,
linkedPRNumber: alias.linkedPRNumber,
fallbackPRNumber: alias.fallbackPRNumber,
fallbackPRSource: alias.fallbackPRSource,
requestStartedAt: event.requestStartedAt,
requestStartedEntry
})
didUpdatePRCache = didUpdatePRCache || nextCaches.prCache !== nextPRCache
nextPRCache = nextCaches.prCache
nextHostedReviewCache = nextCaches.hostedReviewCache
continue
@@ -3832,7 +3869,7 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
}
: {}
})
if (event.outcome && event.outcome.kind !== 'upstream-error') {
if (didUpdatePRCache && event.outcome && event.outcome.kind !== 'upstream-error') {
debouncedSaveCache(get())
}
},