Clear a worktree's merged pull request after it switches to a different branch (#7460)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -801,7 +801,7 @@ describe('getPRForBranch', () => {
|
||||
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
['api', 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100'],
|
||||
['api', 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=1'],
|
||||
expect.anything()
|
||||
)
|
||||
expect(pr).toMatchObject({
|
||||
@@ -929,6 +929,209 @@ describe('getPRForBranch', () => {
|
||||
})
|
||||
})
|
||||
|
||||
function mockMergedLinkedPRLookup(prNumber = 7447) {
|
||||
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
|
||||
candidates: [{ owner: 'acme', repo: 'widgets' }],
|
||||
headRepo: { owner: 'acme', repo: 'widgets' }
|
||||
})
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: prNumber,
|
||||
title: 'Merged linked PR',
|
||||
state: 'MERGED',
|
||||
url: `https://github.com/acme/widgets/pull/${prNumber}`,
|
||||
statusCheckRollup: [],
|
||||
updatedAt: '2026-07-03T21:27:36Z',
|
||||
isDraft: false,
|
||||
mergeable: 'MERGEABLE',
|
||||
baseRefName: 'main',
|
||||
headRefName: 'old-linked-branch',
|
||||
baseRefOid: 'base-oid',
|
||||
headRefOid: 'aaaa1111aaaa1111'
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
it('stamps confirmedContainedHeadOid for a linked merged PR when HEAD is its commit', async () => {
|
||||
mockMergedLinkedPRLookup()
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([{ number: 7447 }])
|
||||
})
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, {
|
||||
currentHeadOid: 'bbbb2222bbbb2222'
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({
|
||||
kind: 'found',
|
||||
pr: {
|
||||
number: 7447,
|
||||
state: 'merged',
|
||||
confirmedContainedHeadOid: 'bbbb2222bbbb2222'
|
||||
}
|
||||
})
|
||||
expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe(
|
||||
undefined
|
||||
)
|
||||
})
|
||||
|
||||
it('stamps headDivergedFromMergedPRAtOid for a linked merged PR with a definite miss', async () => {
|
||||
mockMergedLinkedPRLookup()
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([{ number: 42 }])
|
||||
})
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, {
|
||||
currentHeadOid: 'bbbb2222bbbb2222'
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({
|
||||
kind: 'found',
|
||||
pr: {
|
||||
number: 7447,
|
||||
state: 'merged',
|
||||
headDivergedFromMergedPRAtOid: 'bbbb2222bbbb2222'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('stamps linked merged divergence when a later membership page proves absence', async () => {
|
||||
mockMergedLinkedPRLookup()
|
||||
// Page 1 is full and omits the linked PR (truncated), but page 2 is short and
|
||||
// still omits it — that pair definitively proves the head is not contained.
|
||||
const fullPage = Array.from({ length: 100 }, (_, index) => ({ number: 1000 + index }))
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify(fullPage) })
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([{ number: 2000 }]) })
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, {
|
||||
currentHeadOid: 'bbbb2222bbbb2222'
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({
|
||||
kind: 'found',
|
||||
pr: { number: 7447, state: 'merged', headDivergedFromMergedPRAtOid: 'bbbb2222bbbb2222' }
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves linked merged divergence unset when membership pages stay full to the cap', async () => {
|
||||
mockMergedLinkedPRLookup()
|
||||
// Every page up to the cap is full and omits the linked PR, so absence can
|
||||
// never be proven — the probe must stay unknown rather than clear the link.
|
||||
const fullPage = Array.from({ length: 100 }, (_, index) => ({ number: 1000 + index }))
|
||||
for (let page = 0; page < 5; page += 1) {
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: JSON.stringify(fullPage) })
|
||||
}
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, {
|
||||
currentHeadOid: 'bbbb2222bbbb2222'
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } })
|
||||
expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe(
|
||||
undefined
|
||||
)
|
||||
})
|
||||
|
||||
it('stamps linked merged divergence via the PR url when no repo candidates resolve', async () => {
|
||||
// Fallback path: no resolved candidates, so `gh pr view` returns the PR with
|
||||
// dataRepo=null. The membership probe must still run against the repo derived
|
||||
// from the PR's own URL so a diverged merged linked PR can clear.
|
||||
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ candidates: [], headRepo: null })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 7447,
|
||||
title: 'Merged linked PR',
|
||||
state: 'MERGED',
|
||||
url: 'https://github.com/acme/widgets/pull/7447',
|
||||
statusCheckRollup: [],
|
||||
updatedAt: '2026-07-03T21:27:36Z',
|
||||
isDraft: false,
|
||||
mergeable: 'MERGEABLE',
|
||||
baseRefName: 'main',
|
||||
headRefName: 'old-linked-branch',
|
||||
baseRefOid: 'base-oid',
|
||||
headRefOid: 'aaaa1111aaaa1111'
|
||||
})
|
||||
})
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([{ number: 2000 }]) })
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, {
|
||||
currentHeadOid: 'bbbb2222bbbb2222'
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({
|
||||
kind: 'found',
|
||||
pr: { number: 7447, state: 'merged', headDivergedFromMergedPRAtOid: 'bbbb2222bbbb2222' }
|
||||
})
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
['api', 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=1'],
|
||||
expect.anything()
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves linked merged divergence unset when the membership probe is rate-limited', async () => {
|
||||
mockMergedLinkedPRLookup()
|
||||
rateLimitGuardMock.mockImplementation((bucket?: string) =>
|
||||
bucket === 'core'
|
||||
? { blocked: true, remaining: 0, limit: 5000, resetAt: 0 }
|
||||
: { blocked: false }
|
||||
)
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, {
|
||||
currentHeadOid: 'bbbb2222bbbb2222'
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } })
|
||||
expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe(
|
||||
undefined
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('leaves linked merged divergence unset when the membership probe throws', async () => {
|
||||
mockMergedLinkedPRLookup()
|
||||
ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 422: No commit found'))
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, {
|
||||
currentHeadOid: 'bbbb2222bbbb2222'
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } })
|
||||
expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe(
|
||||
undefined
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves linked merged divergence unset when the membership probe returns a non-array payload', async () => {
|
||||
mockMergedLinkedPRLookup()
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({ message: 'Server Error' })
|
||||
})
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, {
|
||||
currentHeadOid: 'bbbb2222bbbb2222'
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } })
|
||||
expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe(
|
||||
undefined
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves linked merged divergence unset without a current head oid', async () => {
|
||||
mockMergedLinkedPRLookup()
|
||||
|
||||
const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null)
|
||||
|
||||
expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } })
|
||||
expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe(
|
||||
undefined
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('prefers branch lookup over a fallback PR number', async () => {
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock
|
||||
|
||||
+50
-12
@@ -62,7 +62,10 @@ import {
|
||||
type LocalGitExecOptions,
|
||||
type OwnerRepo
|
||||
} from './gh-utils'
|
||||
import { isCommitPartOfMergedPR } from './merged-pr-commit-membership'
|
||||
import {
|
||||
isCommitPartOfMergedPR,
|
||||
type MergedPRCommitMembership
|
||||
} from './merged-pr-commit-membership'
|
||||
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
|
||||
import {
|
||||
hasHostedReviewLocalGitOptions,
|
||||
@@ -2771,6 +2774,15 @@ export async function getPRForBranch(
|
||||
return outcome.kind === 'found' ? outcome.pr : null
|
||||
}
|
||||
|
||||
// Why: the exact-linked fallback (`gh pr view` with no resolved repo candidates)
|
||||
// returns dataRepo=null, which would leave the merged-PR membership probe unable
|
||||
// to run. Derive the PR's own repo from its web URL so a diverged merged linked
|
||||
// PR can still be confirmed and cleared. Host-agnostic to cover GitHub Enterprise.
|
||||
function ownerRepoFromPullRequestUrl(url: string): OwnerRepo | null {
|
||||
const match = url.match(/^https?:\/\/[^/\s]+\/([^/\s]+)\/([^/\s]+)\/pull\/\d+/)
|
||||
return match ? { owner: match[1], repo: match[2] } : null
|
||||
}
|
||||
|
||||
export async function getPRForBranchOutcome(
|
||||
repoPath: string,
|
||||
branch: string,
|
||||
@@ -2810,24 +2822,49 @@ export async function getPRForBranchOutcome(
|
||||
? options.currentHeadOid.trim()
|
||||
: null
|
||||
let confirmedContainedHeadOid: string | null = null
|
||||
let headDivergedFromMergedPRAtOid: string | null = null
|
||||
const mergedPRContainsHead = async (
|
||||
candidate: PullRequestLookupData,
|
||||
candidateRepo: OwnerRepo | null,
|
||||
headOid: string | null
|
||||
): Promise<boolean> => {
|
||||
): Promise<MergedPRCommitMembership> => {
|
||||
if (!candidateRepo || !headOid) {
|
||||
return false
|
||||
return 'unknown'
|
||||
}
|
||||
const contained = await isCommitPartOfMergedPR({
|
||||
const membership = await isCommitPartOfMergedPR({
|
||||
ownerRepo: candidateRepo,
|
||||
prNumber: candidate.number,
|
||||
commitOid: headOid,
|
||||
ghOptions
|
||||
})
|
||||
if (contained) {
|
||||
if (membership === 'contained') {
|
||||
confirmedContainedHeadOid = headOid
|
||||
}
|
||||
return contained
|
||||
return membership
|
||||
}
|
||||
const recordLinkedMergedPRDivergence = async (
|
||||
candidate: PullRequestLookupData | null,
|
||||
candidateRepo: OwnerRepo | null
|
||||
): Promise<void> => {
|
||||
if (
|
||||
typeof linkedPRNumber !== 'number' ||
|
||||
!candidate ||
|
||||
mapPRState(candidate.state, candidate.isDraft) !== 'merged' ||
|
||||
explicitCurrentHeadOid === null ||
|
||||
candidate.headRefOid === explicitCurrentHeadOid
|
||||
) {
|
||||
return
|
||||
}
|
||||
const membership = await mergedPRContainsHead(
|
||||
candidate,
|
||||
candidateRepo ?? ownerRepoFromPullRequestUrl(candidate.url),
|
||||
explicitCurrentHeadOid
|
||||
)
|
||||
if (membership === 'not-contained') {
|
||||
// explicitCurrentHeadOid is non-null here (guarded above); record the
|
||||
// exact head so consumers only clear the worktree that actually diverged.
|
||||
headDivergedFromMergedPRAtOid = explicitCurrentHeadOid
|
||||
}
|
||||
}
|
||||
const hideMergedImplicitPR = async (
|
||||
candidate: PullRequestLookupData | null,
|
||||
@@ -2850,11 +2887,10 @@ export async function getPRForBranchOutcome(
|
||||
// merges, web-committed suggestions). A head that is one of the PR's own
|
||||
// commits is the same line of work, not a reused branch name — keep the
|
||||
// merged PR visible instead of offering "create a pull request".
|
||||
return !(await mergedPRContainsHead(
|
||||
candidate,
|
||||
candidateRepo,
|
||||
currentHeadOidForMergedImplicit
|
||||
))
|
||||
return (
|
||||
(await mergedPRContainsHead(candidate, candidateRepo, currentHeadOidForMergedImplicit)) !==
|
||||
'contained'
|
||||
)
|
||||
}
|
||||
|
||||
if (typeof linkedPRNumber === 'number') {
|
||||
@@ -2942,6 +2978,7 @@ export async function getPRForBranchOutcome(
|
||||
}
|
||||
return { kind: 'no-pr', fetchedAt: Date.now() }
|
||||
}
|
||||
await recordLinkedMergedPRDivergence(data, dataRepo)
|
||||
const fallbackConfirmedMergedBranch =
|
||||
typeof fallbackPRNumber === 'number' &&
|
||||
mergedBranchLookupNumber === fallbackPRNumber &&
|
||||
@@ -2949,7 +2986,7 @@ export async function getPRForBranchOutcome(
|
||||
const explicitHeadHidesMergedImplicitPR =
|
||||
explicitCurrentHeadOid !== null &&
|
||||
shouldHideMergedImplicitPR(data, linkedPRNumber, explicitCurrentHeadOid) &&
|
||||
!(await mergedPRContainsHead(data, dataRepo, explicitCurrentHeadOid))
|
||||
(await mergedPRContainsHead(data, dataRepo, explicitCurrentHeadOid)) !== 'contained'
|
||||
// Why no lazy-HEAD re-check on preservation: fallback numbers come from
|
||||
// callers that already gated them on head equality or confirmed
|
||||
// containment; re-hiding against the main-repo HEAD would blank
|
||||
@@ -3003,6 +3040,7 @@ export async function getPRForBranchOutcome(
|
||||
...(data.mergeStateStatus !== undefined ? { mergeStateStatus: data.mergeStateStatus } : {}),
|
||||
headSha: data.headRefOid,
|
||||
...(confirmedContainedHeadOid ? { confirmedContainedHeadOid } : {}),
|
||||
...(headDivergedFromMergedPRAtOid ? { headDivergedFromMergedPRAtOid } : {}),
|
||||
...(data.baseRefName ? { baseRefName: data.baseRefName } : {}),
|
||||
prRepo: dataRepo ?? undefined,
|
||||
headRepo: dataHeadRepo ?? undefined,
|
||||
|
||||
@@ -11,8 +11,15 @@ type GhExecOptions = Parameters<typeof ghExecFileAsync>[1]
|
||||
const MEMBERSHIP_CACHE_MAX_ENTRIES = 200
|
||||
const MEMBERSHIP_DEFINITIVE_TTL_MS = 6 * 60 * 60 * 1000
|
||||
const MEMBERSHIP_ERROR_TTL_MS = 5 * 60 * 1000
|
||||
const COMMIT_PULLS_PAGE_SIZE = 100
|
||||
// Why: a worktree HEAD is associated with ~1 PR, so page 1 is short in practice
|
||||
// and this cap is never reached; it only bounds the pathological case of a commit
|
||||
// linked to hundreds of PRs, where staying 'unknown' is the safe answer.
|
||||
const COMMIT_PULLS_MAX_PAGES = 5
|
||||
|
||||
const membershipCache = new Map<string, { value: boolean; expiresAt: number }>()
|
||||
export type MergedPRCommitMembership = 'contained' | 'not-contained' | 'unknown'
|
||||
|
||||
const membershipCache = new Map<string, { value: MergedPRCommitMembership; expiresAt: number }>()
|
||||
|
||||
function pruneMergedPRCommitMembershipCache(now = Date.now()): void {
|
||||
for (const [cacheKey, cached] of membershipCache) {
|
||||
@@ -38,17 +45,17 @@ export function resetMergedPRCommitMembershipCacheForTest(): void {
|
||||
* commit belongs to that PR's history rather than merely sharing a branch name.
|
||||
* A worktree sitting on such a commit is on the PR's own line of work (for
|
||||
* example behind web-committed suggestions or an update-branch merge), not a
|
||||
* reused branch name. Conservative on any failure: returns false.
|
||||
* reused branch name. Conservative on any failure: returns unknown.
|
||||
*/
|
||||
export async function isCommitPartOfMergedPR(args: {
|
||||
ownerRepo: OwnerRepo
|
||||
prNumber: number
|
||||
commitOid: string
|
||||
ghOptions: GhExecOptions
|
||||
}): Promise<boolean> {
|
||||
}): Promise<MergedPRCommitMembership> {
|
||||
const oid = args.commitOid.trim().toLowerCase()
|
||||
if (!/^[0-9a-f]{4,64}$/.test(oid) || !Number.isInteger(args.prNumber)) {
|
||||
return false
|
||||
return 'unknown'
|
||||
}
|
||||
const owner = args.ownerRepo.owner
|
||||
const repo = args.ownerRepo.repo
|
||||
@@ -59,38 +66,78 @@ export async function isCommitPartOfMergedPR(args: {
|
||||
if (cached && cached.expiresAt > now) {
|
||||
return cached.value
|
||||
}
|
||||
// Why blocked → uncached false: keep the merged PR hidden without burning
|
||||
// budget; the next poll re-asks once the rate-limit window recovers.
|
||||
// Why blocked stays unknown: hiding a transient branch match is safe, but
|
||||
// callers must not clear a durable linked PR when the probe never ran.
|
||||
if (rateLimitGuard('core').blocked) {
|
||||
return false
|
||||
return 'unknown'
|
||||
}
|
||||
try {
|
||||
noteRateLimitSpend('core')
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['api', `repos/${owner}/${repo}/commits/${oid}/pulls?per_page=100`],
|
||||
args.ghOptions
|
||||
)
|
||||
const parsed = JSON.parse(stdout) as unknown
|
||||
const value =
|
||||
Array.isArray(parsed) &&
|
||||
parsed.some(
|
||||
// Why paginate: a full page that omits the target PR may just be truncated (a
|
||||
// commit can belong to many PRs). Reading only page 1 and calling it
|
||||
// 'not-contained' would wrongly clear a durable link; calling it 'unknown'
|
||||
// would never clear one that genuinely diverged. Walk pages until the PR is
|
||||
// found (contained) or a short page proves absence (not-contained); only the
|
||||
// pathological all-full case up to the cap stays 'unknown'.
|
||||
for (let page = 1; page <= COMMIT_PULLS_MAX_PAGES; page += 1) {
|
||||
if (page > 1 && rateLimitGuard('core').blocked) {
|
||||
membershipCache.set(cacheKey, {
|
||||
value: 'unknown',
|
||||
expiresAt: now + MEMBERSHIP_ERROR_TTL_MS
|
||||
})
|
||||
return 'unknown'
|
||||
}
|
||||
noteRateLimitSpend('core')
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
[
|
||||
'api',
|
||||
`repos/${owner}/${repo}/commits/${oid}/pulls?per_page=${COMMIT_PULLS_PAGE_SIZE}&page=${page}`
|
||||
],
|
||||
args.ghOptions
|
||||
)
|
||||
const parsed = JSON.parse(stdout) as unknown
|
||||
// Why: a non-array success payload is a shape mismatch, not an empty page;
|
||||
// caching it as definitive not-contained could wrongly clear a durable link.
|
||||
if (!Array.isArray(parsed)) {
|
||||
membershipCache.set(cacheKey, {
|
||||
value: 'unknown',
|
||||
expiresAt: now + MEMBERSHIP_ERROR_TTL_MS
|
||||
})
|
||||
return 'unknown'
|
||||
}
|
||||
const entries = parsed
|
||||
const contained = entries.some(
|
||||
(entry) =>
|
||||
typeof entry === 'object' &&
|
||||
entry !== null &&
|
||||
(entry as { number?: unknown }).number === args.prNumber
|
||||
)
|
||||
if (contained) {
|
||||
membershipCache.set(cacheKey, {
|
||||
value: 'contained',
|
||||
expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS
|
||||
})
|
||||
return 'contained'
|
||||
}
|
||||
if (entries.length < COMMIT_PULLS_PAGE_SIZE) {
|
||||
membershipCache.set(cacheKey, {
|
||||
value: 'not-contained',
|
||||
expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS
|
||||
})
|
||||
return 'not-contained'
|
||||
}
|
||||
}
|
||||
membershipCache.set(cacheKey, {
|
||||
value,
|
||||
expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS
|
||||
})
|
||||
return value
|
||||
} catch {
|
||||
// Why: the common failure is 422 for a commit never pushed to GitHub —
|
||||
// definitive "new local work" today, but a push can change it; retry later.
|
||||
membershipCache.set(cacheKey, {
|
||||
value: false,
|
||||
value: 'unknown',
|
||||
expiresAt: now + MEMBERSHIP_ERROR_TTL_MS
|
||||
})
|
||||
return false
|
||||
return 'unknown'
|
||||
} catch {
|
||||
// Why: 422 often means "new local work" today, but a later push can make
|
||||
// the answer knowable; preserve durable links until a probe succeeds.
|
||||
membershipCache.set(cacheKey, {
|
||||
value: 'unknown',
|
||||
expiresAt: now + MEMBERSHIP_ERROR_TTL_MS
|
||||
})
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,6 +116,25 @@ describe('pr-refresh-coordinator', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('copies the candidate worktree head onto broadcast aliases', async () => {
|
||||
const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator')
|
||||
getPRForBranchOutcomeMock.mockResolvedValueOnce({
|
||||
kind: 'found',
|
||||
pr: makePR({ state: 'merged' }),
|
||||
fetchedAt: Date.now()
|
||||
})
|
||||
|
||||
reportVisiblePRRefreshCandidates([makeCandidate({ currentHeadOid: 'worktree-head-oid' })], 1, 1)
|
||||
await vi.runOnlyPendingTimersAsync()
|
||||
|
||||
// Why: the renderer clear of a diverged merged linked PR is head-scoped, so
|
||||
// the broadcast alias must carry the request-time head it was probed against.
|
||||
const outcomeEvent = sendMock.mock.calls
|
||||
.map(([, event]) => event)
|
||||
.find((event) => event.outcome)
|
||||
expect(outcomeEvent?.aliases[0]?.currentHeadOid).toBe('worktree-head-oid')
|
||||
})
|
||||
|
||||
it('does not show visible background refreshes as queued', async () => {
|
||||
const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator')
|
||||
getPRForBranchOutcomeMock.mockResolvedValueOnce({
|
||||
@@ -633,6 +652,103 @@ describe('pr-refresh-coordinator', () => {
|
||||
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('probes with the survivor head after the representative alias is invalidated', async () => {
|
||||
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
|
||||
getPRForBranchOutcomeMock.mockResolvedValue({
|
||||
kind: 'found',
|
||||
pr: makePR({ state: 'merged' }),
|
||||
fetchedAt: Date.now()
|
||||
})
|
||||
|
||||
const survivor = makeCandidate({
|
||||
cacheKey: '/repo::feature/b',
|
||||
branch: 'feature/b',
|
||||
linkedPRNumber: 12,
|
||||
worktreeId: 'wt-b',
|
||||
currentHeadOid: 'head-b'
|
||||
})
|
||||
const representative = makeCandidate({
|
||||
cacheKey: '/repo::feature/a',
|
||||
branch: 'feature/a',
|
||||
linkedPRNumber: 12,
|
||||
worktreeId: 'wt-a',
|
||||
currentHeadOid: 'head-a'
|
||||
})
|
||||
|
||||
// Enqueue the survivor first, then the representative (active coalescing
|
||||
// promotes the latter to representative), then invalidate the representative
|
||||
// so the still-queued entry rebinds to the survivor before draining.
|
||||
enqueuePRRefresh(survivor, 'active', 80, 1)
|
||||
enqueuePRRefresh(representative, 'active', 80, 1)
|
||||
enqueuePRRefresh({ ...representative, isArchived: true }, 'active', 80, 1)
|
||||
await vi.runOnlyPendingTimersAsync()
|
||||
|
||||
const probedHeads = getPRForBranchOutcomeMock.mock.calls.map((call) => call[5]?.currentHeadOid)
|
||||
expect(probedHeads).toContain('head-b')
|
||||
expect(probedHeads).not.toContain('head-a')
|
||||
})
|
||||
|
||||
it('probes with the survivor head after the representative worktree is pruned', async () => {
|
||||
const { enqueuePRRefresh, pruneWorktreePRRefreshAliases } =
|
||||
await import('./pr-refresh-coordinator')
|
||||
getPRForBranchOutcomeMock.mockResolvedValue({
|
||||
kind: 'found',
|
||||
pr: makePR({ state: 'merged' }),
|
||||
fetchedAt: Date.now()
|
||||
})
|
||||
|
||||
const survivor = makeCandidate({
|
||||
cacheKey: '/repo::feature/b',
|
||||
branch: 'feature/b',
|
||||
linkedPRNumber: 12,
|
||||
worktreeId: 'wt-b',
|
||||
currentHeadOid: 'head-b'
|
||||
})
|
||||
const representative = makeCandidate({
|
||||
cacheKey: '/repo::feature/a',
|
||||
branch: 'feature/a',
|
||||
linkedPRNumber: 12,
|
||||
worktreeId: 'wt-a',
|
||||
currentHeadOid: 'head-a'
|
||||
})
|
||||
|
||||
enqueuePRRefresh(survivor, 'active', 80, 1)
|
||||
enqueuePRRefresh(representative, 'active', 80, 1)
|
||||
pruneWorktreePRRefreshAliases('wt-a')
|
||||
await vi.runOnlyPendingTimersAsync()
|
||||
|
||||
const probedHeads = getPRForBranchOutcomeMock.mock.calls.map((call) => call[5]?.currentHeadOid)
|
||||
expect(probedHeads).toContain('head-b')
|
||||
expect(probedHeads).not.toContain('head-a')
|
||||
})
|
||||
|
||||
it('refreshes the representative head when the same worktree re-reports a moved head', async () => {
|
||||
const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator')
|
||||
getPRForBranchOutcomeMock.mockResolvedValue({
|
||||
kind: 'found',
|
||||
pr: makePR({ state: 'merged' }),
|
||||
fetchedAt: Date.now()
|
||||
})
|
||||
|
||||
// Same worktree/branch, moved head, coalescing visible→visible (no promote):
|
||||
// the representative head must track the newest report before the drain.
|
||||
reportVisiblePRRefreshCandidates(
|
||||
[makeCandidate({ linkedPRNumber: 12, worktreeId: 'wt-a', currentHeadOid: 'head-a' })],
|
||||
1,
|
||||
1
|
||||
)
|
||||
reportVisiblePRRefreshCandidates(
|
||||
[makeCandidate({ linkedPRNumber: 12, worktreeId: 'wt-a', currentHeadOid: 'head-b' })],
|
||||
2,
|
||||
1
|
||||
)
|
||||
await vi.runOnlyPendingTimersAsync()
|
||||
|
||||
const probedHeads = getPRForBranchOutcomeMock.mock.calls.map((call) => call[5]?.currentHeadOid)
|
||||
expect(probedHeads).toContain('head-b')
|
||||
expect(probedHeads).not.toContain('head-a')
|
||||
})
|
||||
|
||||
it('includes request start time on manual refresh events', async () => {
|
||||
const { refreshPRNow } = await import('./pr-refresh-coordinator')
|
||||
getPRForBranchOutcomeMock.mockResolvedValueOnce({
|
||||
|
||||
@@ -188,7 +188,11 @@ export function pruneWorktreePRRefreshAliases(worktreeId: string): void {
|
||||
...entry.candidate,
|
||||
cacheKey: replacementAlias.cacheKey,
|
||||
branch: replacementAlias.branch,
|
||||
worktreeId: replacementAlias.worktreeId
|
||||
worktreeId: replacementAlias.worktreeId,
|
||||
// Why: the probe now represents the replacement worktree, so it must
|
||||
// use that worktree's head — otherwise divergence is stamped for the
|
||||
// removed worktree's head and the survivor's link is never cleared.
|
||||
currentHeadOid: replacementAlias.currentHeadOid ?? null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -321,6 +325,7 @@ function aliasFromCandidate(candidate: GitHubPRRefreshCandidate): GitHubPRRefres
|
||||
branch: candidate.branch,
|
||||
worktreeId: candidate.worktreeId,
|
||||
connectionId: candidate.connectionId ?? null,
|
||||
currentHeadOid: candidate.currentHeadOid ?? null,
|
||||
linkedPRNumber: candidate.linkedPRNumber ?? null,
|
||||
fallbackPRNumber:
|
||||
candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null,
|
||||
@@ -393,6 +398,10 @@ function removeQueuedAliasForInvalidCandidate(key: string, alias: GitHubPRRefres
|
||||
cacheKey: replacementAlias.cacheKey,
|
||||
branch: replacementAlias.branch,
|
||||
worktreeId: replacementAlias.worktreeId,
|
||||
// Why: the probe now represents the replacement worktree, so it must use
|
||||
// that worktree's head — otherwise divergence is stamped for the pruned
|
||||
// candidate's head and the survivor's link is never cleared.
|
||||
currentHeadOid: replacementAlias.currentHeadOid ?? null,
|
||||
isArchived: false,
|
||||
isBare: false
|
||||
}
|
||||
@@ -809,6 +818,18 @@ export function enqueuePRRefresh(
|
||||
existing.activeDelayNotified = false
|
||||
existing.candidate = candidate
|
||||
existing.windowId = windowId ?? existing.windowId
|
||||
} else if (existing.candidate.worktreeId === candidate.worktreeId) {
|
||||
// Why: a non-promoting coalesce (e.g. visible→visible) keeps the existing
|
||||
// representative, but the representative drives the probe head. If its own
|
||||
// worktree moved head/branch, refresh those probe inputs so divergence is
|
||||
// stamped for the current head — otherwise the head-scoped clear never
|
||||
// matches and a merged linked PR lingers after a branch switch.
|
||||
existing.candidate = {
|
||||
...existing.candidate,
|
||||
cacheKey: candidate.cacheKey,
|
||||
branch: candidate.branch,
|
||||
currentHeadOid: candidate.currentHeadOid ?? null
|
||||
}
|
||||
}
|
||||
} else {
|
||||
diagnosticsCounters.enqueued += 1
|
||||
|
||||
Reference in New Issue
Block a user