Show PR status for branch worktrees at a merged PR head (#6607)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-28 11:22:07 -07:00
committed by GitHub
co-authored by Orca
parent 6b1a4497db
commit a71b865867
19 changed files with 389 additions and 109 deletions
+21 -10
View File
@@ -1998,6 +1998,9 @@ const GITHUB_AUTO_MERGE_METHODS: Record<GitHubPRMergeMethod, 'MERGE' | 'SQUASH'
export type GitHubPRBranchLookupOptions = HostedReviewExecutionOptions & {
acceptMergedFallbackPR?: boolean
// Why: compare merged implicit PRs against the inspected worktree HEAD, not
// the main repo HEAD, without adding a worktree-scoped git call.
currentHeadOid?: string | null
}
function mapRestPRMergeable(pr: RestPullRequest): PRMergeableState {
@@ -2777,15 +2780,21 @@ export async function getPRForBranchOutcome(
let dataHeadRepo: OwnerRepo | null = headRepo
let currentHeadOidForMergedImplicit: string | null | undefined
const explicitCurrentHeadOid =
typeof options.currentHeadOid === 'string' && options.currentHeadOid.trim().length > 0
? options.currentHeadOid.trim()
: null
const hideMergedImplicitPR = async (candidate: PullRequestLookupData | null) => {
if (!candidate || !isMergedImplicitPR(candidate, linkedPRNumber)) {
return false
}
currentHeadOidForMergedImplicit ??= await getCurrentHeadOid(
repoPath,
connectionId,
localGitOptions
)
// Why: prefer the caller-supplied worktree HEAD; only shell out (against
// the main repo path) when no explicit oid is available, matching legacy
// behavior. This keeps merged-at-head PRs visible for secondary worktrees.
currentHeadOidForMergedImplicit ??=
explicitCurrentHeadOid !== null
? explicitCurrentHeadOid
: await getCurrentHeadOid(repoPath, connectionId, localGitOptions)
return shouldHideMergedImplicitPR(candidate, linkedPRNumber, currentHeadOidForMergedImplicit)
}
@@ -2867,14 +2876,16 @@ export async function getPRForBranchOutcome(
typeof fallbackPRNumber === 'number' &&
mergedBranchLookupNumber === fallbackPRNumber &&
data.number === fallbackPRNumber
const explicitHeadHidesMergedImplicitPR =
explicitCurrentHeadOid !== null &&
shouldHideMergedImplicitPR(data, linkedPRNumber, explicitCurrentHeadOid)
const shouldPreserveMergedFallback =
!explicitHeadHidesMergedImplicitPR &&
(fallbackConfirmedMergedBranch || options.acceptMergedFallbackPR === true)
// Why: a currently visible PR can be merged outside Orca; when the caller
// marks the fallback as visible review state, keep its lifecycle fresh even
// if GitHub no longer reports it by branch (for example deleted heads).
if (
(await hideMergedImplicitPR(data)) &&
!fallbackConfirmedMergedBranch &&
options.acceptMergedFallbackPR !== true
) {
if ((await hideMergedImplicitPR(data)) && !shouldPreserveMergedFallback) {
return { kind: 'no-pr', fetchedAt: Date.now() }
}
+1
View File
@@ -89,6 +89,7 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector
linkedBitbucketPR: args.linkedBitbucketPR ?? null,
linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null,
linkedGiteaPR: args.linkedGiteaPR ?? null,
currentHeadOid: args.currentHeadOid ?? null,
...(Object.keys(localGitOptions).length > 0 ? { localGitExecOptions: localGitOptions } : {})
})
if (review?.provider === 'github' && !stats.hasCountedPR(review.url)) {
+2
View File
@@ -10272,6 +10272,7 @@ export class OrcaRuntimeService {
async getHostedReviewForBranch(args: {
repoSelector: string
branch: string
currentHeadOid?: string | null
linkedGitHubPR?: number | null
fallbackGitHubPR?: number | null
linkedGitLabMR?: number | null
@@ -10285,6 +10286,7 @@ export class OrcaRuntimeService {
repoPath: repo.path,
connectionId: repo.connectionId ?? null,
branch: args.branch,
currentHeadOid: args.currentHeadOid ?? null,
linkedGitHubPR: args.linkedGitHubPR ?? null,
fallbackGitHubPR: args.linkedGitHubPR == null ? (args.fallbackGitHubPR ?? null) : null,
linkedGitLabMR: args.linkedGitLabMR ?? null,
@@ -36,6 +36,7 @@ describe('hosted review RPC methods', () => {
expect(runtime.getHostedReviewForBranch).toHaveBeenCalledWith({
repoSelector: 'C:\\repo',
branch: 'feature/windows',
currentHeadOid: null,
linkedGitHubPR: 12,
linkedGitLabMR: null,
linkedBitbucketPR: null,
@@ -5,6 +5,7 @@ import { requiredString } from '../schemas'
const HostedReviewForBranch = z.object({
repo: requiredString('Missing repo selector'),
branch: requiredString('Missing branch'),
currentHeadOid: z.string().nullable().optional(),
linkedGitHubPR: z.number().int().positive().nullable().optional(),
fallbackGitHubPR: z.number().int().positive().nullable().optional(),
linkedGitLabMR: z.number().int().positive().nullable().optional(),
@@ -52,6 +53,7 @@ export const HOSTED_REVIEW_METHODS: RpcMethod[] = [
return runtime.getHostedReviewForBranch({
repoSelector: params.repo,
branch: params.branch,
currentHeadOid: params.currentHeadOid ?? null,
linkedGitHubPR: params.linkedGitHubPR ?? null,
...(fallbackGitHubPR !== null ? { fallbackGitHubPR } : {}),
linkedGitLabMR: params.linkedGitLabMR ?? null,
+63 -14
View File
@@ -10,7 +10,7 @@ const {
getGiteaRepoSlugMock,
getMergeRequestForBranchMock,
getProjectSlugMock,
getPRForBranchMock,
getPRForBranchOutcomeMock,
getRepoSlugMock
} = vi.hoisted(() => ({
createGitHubPullRequestMock: vi.fn(),
@@ -22,7 +22,7 @@ const {
getGiteaRepoSlugMock: vi.fn(),
getMergeRequestForBranchMock: vi.fn(),
getProjectSlugMock: vi.fn(),
getPRForBranchMock: vi.fn(),
getPRForBranchOutcomeMock: vi.fn(),
getRepoSlugMock: vi.fn()
}))
@@ -39,7 +39,7 @@ vi.mock('../gitlab/merge-request-creation', () => ({
vi.mock('../github/client', () => ({
createGitHubPullRequest: createGitHubPullRequestMock,
getRepoSlug: getRepoSlugMock,
getPRForBranch: getPRForBranchMock
getPRForBranchOutcome: getPRForBranchOutcomeMock
}))
vi.mock('../bitbucket/client', () => ({
@@ -86,7 +86,7 @@ describe('forge provider interface', () => {
getGiteaRepoSlugMock.mockReset()
getMergeRequestForBranchMock.mockReset()
getProjectSlugMock.mockReset()
getPRForBranchMock.mockReset()
getPRForBranchOutcomeMock.mockReset()
getRepoSlugMock.mockReset()
})
@@ -247,14 +247,18 @@ describe('forge provider interface', () => {
})
it('adapts GitHub branch lookup through the shared provider contract', async () => {
getPRForBranchMock.mockResolvedValue({
number: 7,
title: 'Provider branch',
state: 'open',
url: 'https://github.com/team/orca/pull/7',
checksStatus: 'success',
updatedAt: '2026-05-29T00:00:00.000Z',
mergeable: 'MERGEABLE'
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'found',
fetchedAt: 1,
pr: {
number: 7,
title: 'Provider branch',
state: 'open',
url: 'https://github.com/team/orca/pull/7',
checksStatus: 'success',
updatedAt: '2026-05-29T00:00:00.000Z',
mergeable: 'MERGEABLE'
}
})
await expect(
@@ -269,8 +273,53 @@ describe('forge provider interface', () => {
number: 7,
status: 'success'
})
expect(getPRForBranchMock).toHaveBeenCalledWith('/repo', '', null, 'ssh-1', 7, {
acceptMergedFallbackPR: true
expect(getPRForBranchOutcomeMock).toHaveBeenCalledWith('/repo', '', null, 'ssh-1', 7, {
acceptMergedFallbackPR: true,
currentHeadOid: null
})
})
it('passes the worktree HEAD oid through to the GitHub lookup', async () => {
getPRForBranchOutcomeMock.mockResolvedValue({ kind: 'no-pr', fetchedAt: 1 })
await getForgeProviderById('github').getReviewForBranch({
repoPath: '/repo',
connectionId: null,
branch: 'feature/x',
githubCurrentHeadOid: 'abc1234'
})
expect(getPRForBranchOutcomeMock).toHaveBeenCalledWith('/repo', 'feature/x', null, null, null, {
currentHeadOid: 'abc1234'
})
})
it('returns null for a confirmed GitHub no-pr lookup', async () => {
getPRForBranchOutcomeMock.mockResolvedValue({ kind: 'no-pr', fetchedAt: 1 })
await expect(
getForgeProviderById('github').getReviewForBranch({
repoPath: '/repo',
connectionId: null,
branch: 'feature/x'
})
).resolves.toBeNull()
})
it('throws on a GitHub upstream error instead of reporting no review', async () => {
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'network',
message: 'connection reset',
fetchedAt: 1
})
await expect(
getForgeProviderById('github').getReviewForBranch({
repoPath: '/repo',
connectionId: null,
branch: 'feature/x'
})
).rejects.toThrow(/network/)
})
})
+34 -34
View File
@@ -21,7 +21,7 @@ import {
getGiteaRepoSlug
} from '../gitea/client'
import { createGiteaPullRequest } from '../gitea/pull-request-creation'
import { createGitHubPullRequest, getPRForBranch, getRepoSlug } from '../github/client'
import { createGitHubPullRequest, getPRForBranchOutcome, getRepoSlug } from '../github/client'
import { getMergeRequest, getMergeRequestForBranch, getProjectSlug } from '../gitlab/client'
import { createGitLabMergeRequest } from '../gitlab/merge-request-creation'
import {
@@ -48,6 +48,9 @@ export type ForgeReviewForBranchInput = ForgeProviderRepositoryContext & {
branch: string
linkedReviewNumber?: number | null
fallbackReviewNumber?: number | null
// GitHub-only: lets the GitHub provider keep merged-at-head PRs visible using
// the inspected worktree HEAD. Ignored by other providers.
githubCurrentHeadOid?: string | null
}
export type ForgeReviewByNumberInput = ForgeProviderRepositoryContext & {
@@ -103,6 +106,19 @@ const gitLabForgeProvider = {
createReview: createGitLabMergeRequest
} satisfies ForgeProvider
// Why: collapsing an upstream error into a null "no review" lets a transient
// gh/git failure poison the sidebar's hosted-review cache with a definitive
// miss. Surface the error so callers can preserve the last known review state,
// mirroring how the PR refresh coordinator keeps cache on upstream-error.
function unwrapGitHubPRForBranchOutcome(
outcome: Awaited<ReturnType<typeof getPRForBranchOutcome>>
): HostedReviewInfo | null {
if (outcome.kind === 'upstream-error') {
throw new Error(`GitHub PR lookup failed (${outcome.errorType}): ${outcome.message}`)
}
return outcome.kind === 'found' ? mapGitHubReview(outcome.pr) : null
}
const gitHubForgeProvider = {
id: 'github',
supportsReviewCreation: true,
@@ -112,41 +128,25 @@ const gitHubForgeProvider = {
const fallbackReviewNumber =
input.linkedReviewNumber == null ? (input.fallbackReviewNumber ?? null) : null
const executionArgs = hostedReviewExecutionArgs(input)
const pr =
fallbackReviewNumber !== null
? await getPRForBranch(
input.repoPath,
input.branch,
input.linkedReviewNumber ?? null,
input.connectionId,
fallbackReviewNumber,
{
...executionArgs[0],
acceptMergedFallbackPR: true
}
)
: executionArgs.length > 0
? await getPRForBranch(
input.repoPath,
input.branch,
input.linkedReviewNumber ?? null,
input.connectionId,
null,
...executionArgs
)
: await getPRForBranch(
input.repoPath,
input.branch,
input.linkedReviewNumber ?? null,
input.connectionId
)
return pr ? mapGitHubReview(pr) : null
const outcome = await getPRForBranchOutcome(
input.repoPath,
input.branch,
input.linkedReviewNumber ?? null,
input.connectionId,
fallbackReviewNumber,
{
...executionArgs[0],
...(fallbackReviewNumber !== null ? { acceptMergedFallbackPR: true } : {}),
currentHeadOid: input.githubCurrentHeadOid ?? null
}
)
return unwrapGitHubPRForBranchOutcome(outcome)
},
async getReviewByNumber(input) {
const executionArgs = hostedReviewExecutionArgs(input)
const pr =
const outcome =
executionArgs.length > 0
? await getPRForBranch(
? await getPRForBranchOutcome(
input.repoPath,
'',
input.number,
@@ -154,8 +154,8 @@ const gitHubForgeProvider = {
null,
...executionArgs
)
: await getPRForBranch(input.repoPath, '', input.number, input.connectionId)
return pr ? mapGitHubReview(pr) : null
: await getPRForBranchOutcome(input.repoPath, '', input.number, input.connectionId)
return unwrapGitHubPRForBranchOutcome(outcome)
},
createReview: createGitHubPullRequest
} satisfies ForgeProvider
+35 -24
View File
@@ -4,7 +4,7 @@ const {
getProjectSlugMock,
getMergeRequestForBranchMock,
getRepoSlugMock,
getPRForBranchMock,
getPRForBranchOutcomeMock,
getBitbucketRepoSlugMock,
getBitbucketPullRequestForBranchMock,
getAzureDevOpsRepoSlugMock,
@@ -15,7 +15,7 @@ const {
getProjectSlugMock: vi.fn(),
getMergeRequestForBranchMock: vi.fn(),
getRepoSlugMock: vi.fn(),
getPRForBranchMock: vi.fn(),
getPRForBranchOutcomeMock: vi.fn(),
getBitbucketRepoSlugMock: vi.fn(),
getBitbucketPullRequestForBranchMock: vi.fn(),
getAzureDevOpsRepoSlugMock: vi.fn(),
@@ -32,7 +32,7 @@ vi.mock('../gitlab/client', () => ({
vi.mock('../github/client', () => ({
getRepoSlug: getRepoSlugMock,
getPRForBranch: getPRForBranchMock,
getPRForBranchOutcome: getPRForBranchOutcomeMock,
createGitHubPullRequest: vi.fn()
}))
@@ -61,7 +61,7 @@ describe('getHostedReviewForBranch', () => {
getProjectSlugMock.mockReset()
getMergeRequestForBranchMock.mockReset()
getRepoSlugMock.mockReset()
getPRForBranchMock.mockReset()
getPRForBranchOutcomeMock.mockReset()
getBitbucketRepoSlugMock.mockReset()
getBitbucketPullRequestForBranchMock.mockReset()
getAzureDevOpsRepoSlugMock.mockReset()
@@ -100,20 +100,24 @@ describe('getHostedReviewForBranch', () => {
})
expect(getProjectSlugMock).toHaveBeenCalledWith('/repo', 'ssh-1')
expect(getMergeRequestForBranchMock).toHaveBeenCalledWith('/repo', 'feature', null, 'ssh-1')
expect(getPRForBranchMock).not.toHaveBeenCalled()
expect(getPRForBranchOutcomeMock).not.toHaveBeenCalled()
})
it('falls through to GitHub when origin is not GitLab', async () => {
getProjectSlugMock.mockResolvedValue(null)
getRepoSlugMock.mockResolvedValue({ owner: 'o', repo: 'r' })
getPRForBranchMock.mockResolvedValue({
number: 3,
title: 'GitHub branch',
state: 'open',
url: 'https://github.com/o/r/pull/3',
checksStatus: 'pending',
updatedAt: '2026-05-10T00:00:00.000Z',
mergeable: 'UNKNOWN'
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'found',
fetchedAt: 1,
pr: {
number: 3,
title: 'GitHub branch',
state: 'open',
url: 'https://github.com/o/r/pull/3',
checksStatus: 'pending',
updatedAt: '2026-05-10T00:00:00.000Z',
mergeable: 'UNKNOWN'
}
})
await expect(
@@ -127,7 +131,9 @@ describe('getHostedReviewForBranch', () => {
number: 3,
status: 'pending'
})
expect(getPRForBranchMock).toHaveBeenCalledWith('/repo', 'feature', 3, undefined)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledWith('/repo', 'feature', 3, undefined, null, {
currentHeadOid: null
})
})
it('routes local WSL project branch lookup through provider detection and the selected provider', async () => {
@@ -173,14 +179,18 @@ describe('getHostedReviewForBranch', () => {
it('uses fallback GitHub PR when branch is empty', async () => {
getProjectSlugMock.mockResolvedValue(null)
getRepoSlugMock.mockResolvedValue({ owner: 'o', repo: 'r' })
getPRForBranchMock.mockResolvedValue({
number: 42,
title: 'Detached GitHub branch',
state: 'open',
url: 'https://github.com/o/r/pull/42',
checksStatus: 'success',
updatedAt: '2026-05-10T00:00:00.000Z',
mergeable: 'MERGEABLE'
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'found',
fetchedAt: 1,
pr: {
number: 42,
title: 'Detached GitHub branch',
state: 'open',
url: 'https://github.com/o/r/pull/42',
checksStatus: 'success',
updatedAt: '2026-05-10T00:00:00.000Z',
mergeable: 'MERGEABLE'
}
})
await expect(
@@ -194,8 +204,9 @@ describe('getHostedReviewForBranch', () => {
number: 42,
status: 'success'
})
expect(getPRForBranchMock).toHaveBeenCalledWith('/repo', '', null, undefined, 42, {
acceptMergedFallbackPR: true
expect(getPRForBranchOutcomeMock).toHaveBeenCalledWith('/repo', '', null, undefined, 42, {
acceptMergedFallbackPR: true,
currentHeadOid: null
})
})
+2
View File
@@ -38,6 +38,7 @@ export async function getHostedReviewForBranch(
linkedBitbucketPR?: number | null
linkedAzureDevOpsPR?: number | null
linkedGiteaPR?: number | null
currentHeadOid?: string | null
} & HostedReviewExecutionOptions
): Promise<HostedReviewInfo | null> {
const branchName = input.branch.replace(/^refs\/heads\//, '')
@@ -68,6 +69,7 @@ export async function getHostedReviewForBranch(
connectionId: input.connectionId,
branch: branchName,
...(input.localGitExecOptions ? { localGitExecOptions: input.localGitExecOptions } : {}),
githubCurrentHeadOid: input.currentHeadOid ?? null,
...reviewLinkForProvider(input, provider.id)
})
}
@@ -1191,6 +1191,7 @@ export default function ChecksPanel(): React.JSX.Element {
repoId: repo.id,
linkedGitHubPR: linkedPR,
fallbackGitHubPR: fallbackGitHubPRNumber,
currentHeadOid: activeWorktree?.head ?? null,
linkedGitLabMR,
linkedBitbucketPR,
linkedAzureDevOpsPR,
@@ -1210,6 +1211,7 @@ export default function ChecksPanel(): React.JSX.Element {
isFolder,
isGitLabReviewContext,
isPanelVisible,
activeWorktree?.head,
linkedAzureDevOpsPR,
linkedBitbucketPR,
linkedGiteaPR,
@@ -2085,6 +2087,7 @@ export default function ChecksPanel(): React.JSX.Element {
repoId: repo.id,
linkedGitHubPR: linkedPR,
fallbackGitHubPR: fallbackGitHubPRNumber,
currentHeadOid: activeWorktree?.head ?? null,
linkedGitLabMR,
linkedBitbucketPR,
linkedAzureDevOpsPR,
@@ -2105,6 +2108,7 @@ export default function ChecksPanel(): React.JSX.Element {
},
[
activeGitLabReview,
activeWorktree?.head,
activeWorktreeId,
branch,
enqueueGitHubPRRefresh,
@@ -148,6 +148,7 @@ describe('WorktreeCard hosted review refresh', () => {
expect(fetchHostedReviewForBranch).toHaveBeenLastCalledWith('/repo', 'feature/branch', {
repoId: 'repo-1',
linkedGitHubPR: null,
currentHeadOid: 'abc123',
linkedGitLabMR: null,
linkedBitbucketPR: null,
linkedAzureDevOpsPR: null,
@@ -650,6 +650,7 @@ describe('WorktreeCard linked PR display', () => {
number: 6340,
title: 'Remove split terminal from onboarding checklist',
state: 'merged',
headSha: 'abc123',
checksStatus: 'success'
}),
fetchedAt: Date.now()
@@ -485,11 +485,28 @@ const WorktreeCard = React.memo(function WorktreeCard({
cachedBranchPR,
worktree
)
const cachedBranchFallbackGitHubPRNumber =
linkedGitHubPR === null &&
!hasNonGitHubLinkedReview &&
cachedBranchPR?.number !== undefined &&
(cachedBranchPR.state !== 'merged' || cachedMergedBranchPRMatchesCurrentHead)
? cachedBranchPR.number
: null
const cachedBranchPRCanDriveDisplay =
cachedBranchPR?.state !== 'merged' || cachedMergedBranchPRMatchesCurrentHead
const hostedReviewMatchesHeadMatchedCachedMergedPR =
cachedMergedBranchPRMatchesCurrentHead &&
cachedBranchPR !== null &&
cachedBranchPR !== undefined &&
hostedReview?.provider === 'github' &&
hostedReview.number === cachedBranchPR.number
const useCachedBranchReview =
cachedBranchPR !== undefined &&
cachedBranchPR !== null &&
!hasNonGitHubLinkedReview &&
cachedBranchPRCanDriveDisplay &&
(hostedReview === undefined ||
(cachedMergedBranchPRMatchesCurrentHead && !hostedReviewMatchesHeadMatchedCachedMergedPR) ||
(hostedReview === null &&
((cachedBranchPRFetchedAt !== undefined &&
cachedBranchPRFetchedAt > (hostedReviewEntry?.fetchedAt ?? 0)) ||
@@ -506,7 +523,9 @@ const WorktreeCard = React.memo(function WorktreeCard({
linkedGiteaPR,
{
reviewHintKey:
useCachedBranchReview && !hasLinkedReview ? '' : hostedReviewEntry?.linkedReviewHintKey
(useCachedBranchReview || cachedMergedBranchPRMatchesCurrentHead) && !hasLinkedReview
? ''
: hostedReviewEntry?.linkedReviewHintKey
}
)
const issue: IssueInfo | null | undefined = worktree.linkedIssue
@@ -636,6 +655,10 @@ const WorktreeCard = React.memo(function WorktreeCard({
void fetchHostedReviewForBranch(repo.path, branch, {
repoId: repo.id,
linkedGitHubPR: worktree.linkedPR ?? null,
...(cachedBranchFallbackGitHubPRNumber !== null
? { fallbackGitHubPR: cachedBranchFallbackGitHubPRNumber }
: {}),
currentHeadOid: worktree.head ?? null,
linkedGitLabMR,
linkedBitbucketPR,
linkedAzureDevOpsPR,
@@ -654,6 +677,8 @@ const WorktreeCard = React.memo(function WorktreeCard({
isFolder,
worktree.isBare,
worktree.linkedPR,
worktree.head,
cachedBranchFallbackGitHubPRNumber,
linkedGitLabMR,
linkedBitbucketPR,
linkedAzureDevOpsPR,
@@ -683,6 +708,10 @@ const WorktreeCard = React.memo(function WorktreeCard({
void fetchHostedReviewForBranch(repo.path, branch, {
repoId: repo.id,
linkedGitHubPR: worktree.linkedPR ?? null,
...(cachedBranchFallbackGitHubPRNumber !== null
? { fallbackGitHubPR: cachedBranchFallbackGitHubPRNumber }
: {}),
currentHeadOid: worktree.head ?? null,
linkedGitLabMR,
linkedBitbucketPR,
linkedAzureDevOpsPR,
@@ -697,6 +726,8 @@ const WorktreeCard = React.memo(function WorktreeCard({
isFolder,
worktree.isBare,
worktree.linkedPR,
worktree.head,
cachedBranchFallbackGitHubPRNumber,
linkedGitLabMR,
linkedBitbucketPR,
linkedAzureDevOpsPR,
@@ -3255,6 +3255,7 @@ describe('createGitHubSlice.fetchPRForBranch', () => {
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledTimes(1)
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledWith({
branch,
currentHeadOid: null,
linkedAzureDevOpsPR: null,
linkedBitbucketPR: null,
linkedGitHubPR: null,
+5 -1
View File
@@ -1038,8 +1038,12 @@ function buildPRRefreshCandidate(
true
)
const cachedFallbackPRNumber = cachedPR?.number ?? null
const cachedMergedPRMovedPastHead =
worktree.linkedPR == null && cachedPR?.state === 'merged' && cachedPR.headSha !== worktree.head
const fallbackPRNumber =
worktree.linkedPR == null ? (cachedFallbackPRNumber ?? hostedReviewFallbackPRNumber) : null
worktree.linkedPR == null && !cachedMergedPRMovedPastHead
? (cachedFallbackPRNumber ?? hostedReviewFallbackPRNumber)
: null
const fallbackPRSource: GitHubPRFallbackSource | null =
worktree.linkedPR != null || fallbackPRNumber == null
? null
@@ -158,7 +158,9 @@ describe('hosted review cache race protection', () => {
vi.setSystemTime(300)
rejectFetch(new Error('older lookup failed'))
await expect(request).resolves.toBeNull()
// Why: a failed lookup preserves (and returns) the last known review
// instead of caching a definitive miss that would blank the card.
await expect(request).resolves.toEqual(newerReview)
expect(store.getState().hostedReviewCache[cacheKey]).toEqual({
data: newerReview,
fetchedAt: 200,
@@ -169,6 +171,52 @@ describe('hosted review cache race protection', () => {
}
})
it('keeps the last known review when a refresh fails instead of caching a miss', async () => {
vi.useFakeTimers()
vi.setSystemTime(100)
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
const cachedReview = makeGitHubReview('Known PR status')
const cacheKey = getHostedReviewCacheKey(
'/repo',
'feature/keep-on-error',
null,
'repo-1',
null,
null,
true
)
let rejectFetch: (error: Error) => void = () => {}
const fetch = new Promise<HostedReviewInfo>((_resolve, reject) => {
rejectFetch = reject
})
mockApi.hostedReview.forBranch.mockReturnValueOnce(fetch)
const store = makeStore()
store.setState({
hostedReviewCache: {
[cacheKey]: { data: cachedReview, fetchedAt: 100, linkedReviewHintKey: 'github:42' }
}
})
try {
const request = store
.getState()
.fetchHostedReviewForBranch('/repo', 'feature/keep-on-error', { force: true })
vi.setSystemTime(300)
rejectFetch(new Error('transient gh failure'))
await expect(request).resolves.toEqual(cachedReview)
// Why: the cached review survives untouched; no fresh `data: null` miss is
// written, so the card keeps showing the PR and retries on the next poll.
expect(store.getState().hostedReviewCache[cacheKey]).toEqual({
data: cachedReview,
fetchedAt: 100,
linkedReviewHintKey: 'github:42'
})
} finally {
consoleError.mockRestore()
}
})
it('does not let a same-millisecond external cache write after request start be overwritten', async () => {
vi.useFakeTimers()
vi.setSystemTime(100)
@@ -274,6 +322,7 @@ describe('hosted review cache race protection', () => {
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledTimes(2)
expect(mockApi.hostedReview.forBranch).toHaveBeenNthCalledWith(2, {
branch: 'feature/inflight',
currentHeadOid: null,
linkedAzureDevOpsPR: null,
linkedBitbucketPR: null,
linkedGitHubPR: null,
@@ -3,7 +3,11 @@ hinted cache revalidation, provider discovery, and PR cache reconciliation. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'
import type { AppState } from '../types'
import { createHostedReviewSlice, refreshHostedReviewCard } from './hosted-review'
import {
createHostedReviewSlice,
getHostedReviewCacheKey,
refreshHostedReviewCard
} from './hosted-review'
import type { HostedReviewInfo } from '../../../../shared/hosted-review'
const runtimeRpc = vi.hoisted(() => ({
@@ -90,6 +94,7 @@ describe('hosted review slice', () => {
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledWith({
repoPath: '/repo',
branch: 'feature/gitlab',
currentHeadOid: null,
linkedGitHubPR: null,
linkedGitLabMR: 5,
linkedBitbucketPR: null,
@@ -203,6 +208,7 @@ describe('hosted review slice', () => {
repo: 'C:\\repo',
repoPath: 'C:\\repo',
branch: 'feature/windows',
currentHeadOid: null,
linkedGitHubPR: 12,
linkedGitLabMR: null,
linkedBitbucketPR: null,
@@ -509,4 +515,82 @@ describe('hosted review slice', () => {
await expect(plainFetch).resolves.toBeNull()
await expect(linkedFetch).resolves.toEqual(review)
})
it('refetches a fresh merged GitHub review when the worktree head advances', async () => {
const mergedAtHead: HostedReviewInfo = {
provider: 'github',
number: 7,
title: 'Merged at head',
state: 'merged',
url: 'https://github.com/acme/orca/pull/7',
status: 'success',
updatedAt: '2026-05-10T00:00:00.000Z',
mergeable: 'MERGEABLE',
headSha: 'aaaaaaa'
}
mockApi.hostedReview.forBranch.mockResolvedValueOnce(mergedAtHead).mockResolvedValueOnce(null)
const store = makeStore()
await expect(
store.getState().fetchHostedReviewForBranch('/repo', 'feature/merged', {
currentHeadOid: 'aaaaaaa'
})
).resolves.toEqual(mergedAtHead)
// Worktree advanced off the merged head: the branch-scoped cache is fresh,
// but the merged review is no longer valid for the new head, so refetch.
await expect(
store.getState().fetchHostedReviewForBranch('/repo', 'feature/merged', {
currentHeadOid: 'bbbbbbb'
})
).resolves.toBeNull()
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledTimes(2)
})
it('does not preserve a merged GitHub review after the worktree moves off its head', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
const cacheKey = getHostedReviewCacheKey(
'/repo',
'feature/merged',
null,
'repo-1',
null,
null,
true
)
const store = makeStore()
store.setState({
hostedReviewCache: {
[cacheKey]: {
data: {
provider: 'github',
number: 7,
title: 'Merged at head',
state: 'merged',
url: 'https://github.com/acme/orca/pull/7',
status: 'success',
updatedAt: '2026-05-10T00:00:00.000Z',
mergeable: 'MERGEABLE',
headSha: 'aaaaaaa'
},
fetchedAt: Date.now(),
linkedReviewHintKey: ''
}
}
})
mockApi.hostedReview.forBranch.mockRejectedValueOnce(new Error('transient gh failure'))
try {
// Head advanced to bbbbbbb; a failed lookup must not preserve the stale
// merged review for the old head.
await expect(
store.getState().fetchHostedReviewForBranch('/repo', 'feature/merged', {
force: true,
currentHeadOid: 'bbbbbbb'
})
).resolves.toBeNull()
} finally {
consoleError.mockRestore()
}
})
})
+47 -23
View File
@@ -22,7 +22,12 @@ import { getRepoExecutionHostId, parseExecutionHostId } from '../../../../shared
export { getHostedReviewCacheKey, linkedReviewHintKey } from './hosted-review-cache-identity'
type CacheEntry<T> = { data: T | null; fetchedAt: number; linkedReviewHintKey?: string }
type FetchOptions = { force?: boolean; repoId?: string; staleWhileRevalidate?: boolean }
type FetchOptions = {
force?: boolean
repoId?: string
staleWhileRevalidate?: boolean
currentHeadOid?: string | null
}
type CreateHostedReviewStoreInput = CreateHostedReviewInput & { repoId?: string | null }
const CACHE_TTL_MS = 60_000
@@ -91,6 +96,27 @@ function canReuseInflightHint(inflightHintKey: string, nextHintKey: string): boo
return inflightHintKey === nextHintKey
}
function isStaleMergedGitHubReviewForHead(
cached: CacheEntry<HostedReviewInfo> | undefined,
currentHeadOid: string | null | undefined
): boolean {
// Why: a merged GitHub PR is only shown when the worktree sits on its head.
// The cache key is branch-scoped, so a worktree that advanced off the merged
// head must not reuse (or, on failure, preserve) the now-stale merged review.
const head = typeof currentHeadOid === 'string' ? currentHeadOid.trim() : ''
if (head.length === 0) {
return false
}
const data = cached?.data
return (
data?.provider === 'github' &&
data.state === 'merged' &&
typeof data.headSha === 'string' &&
data.headSha.length > 0 &&
data.headSha !== head
)
}
function hasNewerHostedReviewCacheEntry(
cache: HostedReviewSlice['hostedReviewCache'],
cacheKey: string,
@@ -290,7 +316,14 @@ export const createHostedReviewSlice: StateCreator<AppState, [], [], HostedRevie
const hintKey = linkedReviewHintKey(options)
const linkedRefetch = shouldRefetchForLinkedHint(cached, hintKey)
const scopedResultRefetch = shouldRefetchGitHubScopedResultForNoHint(cached, hintKey)
if (!options?.force && !linkedRefetch && !scopedResultRefetch && isFresh(cached)) {
const staleMergedHeadRefetch = isStaleMergedGitHubReviewForHead(cached, options?.currentHeadOid)
if (
!options?.force &&
!linkedRefetch &&
!scopedResultRefetch &&
!staleMergedHeadRefetch &&
isFresh(cached)
) {
return cached.data
}
@@ -310,6 +343,7 @@ export const createHostedReviewSlice: StateCreator<AppState, [], [], HostedRevie
const args = {
branch,
...(options?.repoId !== undefined ? { repoId: options.repoId } : {}),
currentHeadOid: options?.currentHeadOid ?? null,
linkedGitHubPR: options?.linkedGitHubPR ?? null,
...(fallbackGitHubPR !== null ? { fallbackGitHubPR } : {}),
linkedGitLabMR: options?.linkedGitLabMR ?? null,
@@ -383,29 +417,19 @@ export const createHostedReviewSlice: StateCreator<AppState, [], [], HostedRevie
}
return review
} catch (error) {
// Why: a transient lookup failure (timeout, rate limit, gh/git error)
// must not be cached as a definitive "no review" miss — that blanks
// the sidebar card to branch-only and suppresses retry for the full
// cache TTL. Preserve the last known review and let the next visible
// poll retry instead.
console.error('Failed to fetch hosted review:', error)
if (requestGenerations.get(cacheKey) === generation) {
set((state) => {
if (
hasNewerHostedReviewCacheEntry(
state.hostedReviewCache,
cacheKey,
requestStartedAt,
requestStartedEntry
)
) {
return {}
}
return {
hostedReviewCache: withHostedReviewCacheEntry(state.hostedReviewCache, cacheKey, {
data: null,
fetchedAt: Date.now(),
linkedReviewHintKey: hintKey
})
}
})
const preserved = get().hostedReviewCache[cacheKey]
// Why: don't preserve a merged GitHub review the worktree has moved
// off of; that PR is only valid while checked out at its head.
if (isStaleMergedGitHubReviewForHead(preserved, options?.currentHeadOid)) {
return null
}
return null
return preserved?.data ?? null
} finally {
const activeRequest = inflightHostedReviewRequests.get(cacheKey)
if (activeRequest?.generation === generation) {
+2
View File
@@ -40,6 +40,8 @@ export type HostedReviewForBranchArgs = {
linkedBitbucketPR?: number | null
linkedAzureDevOpsPR?: number | null
linkedGiteaPR?: number | null
// The worktree's checked-out HEAD oid (GitHub merged-at-head visibility).
currentHeadOid?: string | null
}
export type HostedReviewSummary = {