Improve git remote selection (#2207)

This commit is contained in:
Jinjing
2026-05-17 21:00:15 -07:00
committed by GitHub
parent 29b8e36c39
commit c7ddfd17d1
21 changed files with 969 additions and 290 deletions
+23
View File
@@ -174,4 +174,27 @@ describe('getPRChecks', () => {
{ cwd: '/repo-root', env: { ...process.env, GH_PROMPT_DISABLED: '1' } }
)
})
it('uses explicit PR repo for check-runs and gh pr checks fallback', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'widgets' })
ghExecFileAsyncMock
.mockRejectedValueOnce(new Error('gh: No commit found for SHA: stale-head (HTTP 422)'))
.mockResolvedValueOnce({
stdout: JSON.stringify([{ name: 'lint', state: 'PASS', link: 'https://example.com/lint' }])
})
await getPRChecks('/repo-root', 42, 'stale-head', { owner: 'acme', repo: 'widgets' })
expect(getOwnerRepoMock).not.toHaveBeenCalled()
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
1,
['api', '--cache', '60s', 'repos/acme/widgets/commits/stale-head/check-runs?per_page=100'],
{ cwd: '/repo-root' }
)
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
2,
['pr', 'checks', '42', '--json', 'name,state,link', '--repo', 'acme/widgets'],
{ cwd: '/repo-root' }
)
})
})
+232 -131
View File
@@ -11,6 +11,7 @@ const {
getOwnerRepoMock,
getIssueOwnerRepoMock,
getOwnerRepoForRemoteMock,
resolvePRRepositoryCandidatesMock,
getRemoteUrlForRepoMock,
gitExecFileAsyncMock,
rateLimitGuardMock,
@@ -25,6 +26,7 @@ const {
getOwnerRepoMock: vi.fn(),
getIssueOwnerRepoMock: vi.fn(),
getOwnerRepoForRemoteMock: vi.fn(),
resolvePRRepositoryCandidatesMock: vi.fn(),
getRemoteUrlForRepoMock: vi.fn(),
gitExecFileAsyncMock: vi.fn(),
rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })),
@@ -46,6 +48,7 @@ vi.mock('./gh-utils', () => ({
getOwnerRepo: getOwnerRepoMock,
getIssueOwnerRepo: getIssueOwnerRepoMock,
getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
resolvePRRepositoryCandidates: resolvePRRepositoryCandidatesMock,
getRemoteUrlForRepo: getRemoteUrlForRepoMock,
gitExecFileAsync: gitExecFileAsyncMock,
ghRepoExecOptions: ghRepoExecOptionsMock,
@@ -82,7 +85,9 @@ import {
getPRComments,
getPRForBranch,
getPullRequestPushTarget,
mergePR,
resolveReviewThread,
updatePRTitle,
_resetOwnerRepoCache
} from './client'
@@ -93,6 +98,11 @@ describe('getPRForBranch', () => {
getOwnerRepoMock.mockReset()
getIssueOwnerRepoMock.mockReset()
getOwnerRepoForRemoteMock.mockReset()
resolvePRRepositoryCandidatesMock.mockReset()
resolvePRRepositoryCandidatesMock.mockImplementation(async (repoPath, connectionId) => {
const origin = await getOwnerRepoMock(repoPath, connectionId)
return { candidates: origin ? [origin] : [], headRepo: origin }
})
getRemoteUrlForRepoMock.mockReset()
gitExecFileAsyncMock.mockReset()
rateLimitGuardMock.mockReset()
@@ -113,16 +123,13 @@ describe('getPRForBranch', () => {
{
number: 42,
title: 'Fix PR discovery',
state: 'OPEN',
url: 'https://github.com/acme/widgets/pull/42',
statusCheckRollup: [],
updatedAt: '2026-03-28T00:00:00Z',
isDraft: false,
mergeable: 'MERGEABLE',
baseRefName: 'main',
headRefName: 'feature/test',
baseRefOid: 'base-oid',
headRefOid: 'head-oid'
state: 'open',
html_url: 'https://github.com/acme/widgets/pull/42',
updated_at: '2026-03-28T00:00:00Z',
draft: false,
mergeable: true,
base: { ref: 'main', sha: 'base-oid' },
head: { ref: 'feature/test', sha: 'head-oid' }
}
])
})
@@ -131,25 +138,110 @@ describe('getPRForBranch', () => {
expect(getOwnerRepoMock).toHaveBeenCalledWith('/repo-root', undefined)
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
[
'pr',
'list',
'--repo',
'acme/widgets',
'--head',
'feature/test',
'--state',
'all',
'--limit',
'1',
'--json',
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid'
],
['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'],
{ cwd: '/repo-root' }
)
expect(pr?.number).toBe(42)
expect(pr?.state).toBe('open')
expect(pr?.mergeable).toBe('MERGEABLE')
expect(pr?.prRepo).toEqual({ owner: 'acme', repo: 'widgets' })
expect(pr?.headRepo).toEqual({ owner: 'acme', repo: 'widgets' })
})
it('resolves fork PRs from the upstream PR repo with the origin head owner', async () => {
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
candidates: [
{ owner: 'stablyai', repo: 'orca' },
{ owner: 'fork', repo: 'orca' }
],
headRepo: { owner: 'fork', repo: 'orca' }
})
ghExecFileAsyncMock.mockResolvedValueOnce({
stdout: JSON.stringify([
{
number: 1738,
title: 'Fork PR',
state: 'open',
html_url: 'https://github.com/stablyai/orca/pull/1738',
updated_at: '2026-03-28T00:00:00Z',
draft: false,
mergeable_state: 'clean',
base: { ref: 'main', sha: 'base-oid' },
head: { ref: 'feature/test', sha: 'head-oid' }
}
])
})
const pr = await getPRForBranch('/repo-root', 'feature/test')
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
['api', 'repos/stablyai/orca/pulls?head=fork%3Afeature%2Ftest&state=all&per_page=1'],
{ cwd: '/repo-root' }
)
expect(pr).toMatchObject({
number: 1738,
prRepo: { owner: 'stablyai', repo: 'orca' },
headRepo: { owner: 'fork', repo: 'orca' }
})
})
it('looks up a linked PR number across PR repo candidates', async () => {
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
candidates: [
{ owner: 'stablyai', repo: 'orca' },
{ owner: 'fork', repo: 'orca' }
],
headRepo: { owner: 'fork', repo: 'orca' }
})
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: 'linked-head-oid\n', stderr: '' })
ghExecFileAsyncMock
.mockRejectedValueOnce(new Error('HTTP 404: Not Found'))
.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 99,
title: 'Linked fork PR',
state: 'OPEN',
url: 'https://github.com/fork/orca/pull/99',
statusCheckRollup: [],
updatedAt: '2026-03-28T00:00:00Z',
isDraft: false,
mergeable: 'MERGEABLE',
baseRefName: 'main',
headRefName: 'feature/test',
baseRefOid: 'base-oid',
headRefOid: 'linked-head-oid'
})
})
const pr = await getPRForBranch('/repo-root', 'feature/test', 99)
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
1,
[
'pr',
'view',
'99',
'--repo',
'stablyai/orca',
'--json',
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid'
],
{ cwd: '/repo-root' }
)
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
2,
[
'pr',
'view',
'99',
'--repo',
'fork/orca',
'--json',
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid'
],
{ cwd: '/repo-root' }
)
expect(pr?.prRepo).toEqual({ owner: 'fork', repo: 'orca' })
})
it('prefers exact linked PR lookup when the repo identity is known', async () => {
@@ -242,20 +334,7 @@ describe('getPRForBranch', () => {
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
2,
[
'pr',
'list',
'--repo',
'acme/widgets',
'--head',
'feature/test',
'--state',
'all',
'--limit',
'1',
'--json',
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid'
],
['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'],
{ cwd: '/repo-root' }
)
expect(pr?.number).toBe(42)
@@ -301,20 +380,7 @@ describe('getPRForBranch', () => {
)
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
2,
[
'pr',
'list',
'--repo',
'acme/widgets',
'--head',
'feature/test',
'--state',
'all',
'--limit',
'1',
'--json',
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid'
],
['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'],
{ cwd: '/repo-root' }
)
expect(pr?.number).toBe(42)
@@ -351,20 +417,7 @@ describe('getPRForBranch', () => {
})
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
3,
[
'pr',
'list',
'--repo',
'acme/widgets',
'--head',
'feature/test',
'--state',
'all',
'--limit',
'1',
'--json',
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid'
],
['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'],
{ cwd: '/repo-root' }
)
expect(pr?.number).toBe(42)
@@ -401,26 +454,13 @@ describe('getPRForBranch', () => {
})
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
3,
[
'pr',
'list',
'--repo',
'acme/widgets',
'--head',
'feature/test',
'--state',
'all',
'--limit',
'1',
'--json',
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid'
],
['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'],
{ cwd: '/repo-root' }
)
expect(pr?.number).toBe(42)
})
it('does not spend branch discovery calls when exact linked PR REST fallback is rate limited', async () => {
it('continues to branch discovery when exact linked PR REST fallback is rate limited', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
ghExecFileAsyncMock
.mockRejectedValueOnce(new Error('GraphQL: API rate limit already exceeded'))
@@ -444,34 +484,37 @@ describe('getPRForBranch', () => {
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['api', 'repos/acme/widgets/pulls/99'], {
cwd: '/repo-root'
})
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
3,
['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'],
{ cwd: '/repo-root' }
)
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3)
expect(pr).toBeNull()
})
it('falls back to REST branch lookup when gh pr list is GraphQL rate limited', async () => {
it('uses REST branch lookup directly when origin head repo is known', async () => {
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
ghExecFileAsyncMock
.mockRejectedValueOnce(new Error('GraphQL: API rate limit already exceeded'))
.mockResolvedValueOnce({
stdout: JSON.stringify([
{
number: 43,
title: 'REST branch lookup',
state: 'open',
html_url: 'https://github.com/acme/widgets/pull/43',
updated_at: '2026-03-28T00:00:00Z',
draft: false,
mergeable: true,
head: { ref: 'feature/test', sha: 'rest-head-oid' },
base: { ref: 'main', sha: 'rest-base-oid' }
}
])
})
ghExecFileAsyncMock.mockResolvedValueOnce({
stdout: JSON.stringify([
{
number: 43,
title: 'REST branch lookup',
state: 'open',
html_url: 'https://github.com/acme/widgets/pull/43',
updated_at: '2026-03-28T00:00:00Z',
draft: false,
mergeable: true,
head: { ref: 'feature/test', sha: 'rest-head-oid' },
base: { ref: 'main', sha: 'rest-base-oid' }
}
])
})
const pr = await getPRForBranch('/repo-root', 'feature/test')
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
2,
1,
['api', 'repos/acme/widgets/pulls?head=acme%3Afeature%2Ftest&state=all&per_page=1'],
{ cwd: '/repo-root' }
)
@@ -529,16 +572,13 @@ describe('getPRForBranch', () => {
{
number: 42,
title: 'Fix PR discovery',
state: 'OPEN',
url: 'https://github.com/acme/widgets/pull/42',
statusCheckRollup: [],
updatedAt: '2026-03-28T00:00:00Z',
isDraft: false,
mergeable: 'CONFLICTING',
baseRefName: 'main',
headRefName: 'feature/test',
baseRefOid: 'base-oid',
headRefOid: 'head-oid'
state: 'open',
html_url: 'https://github.com/acme/widgets/pull/42',
updated_at: '2026-03-28T00:00:00Z',
draft: false,
mergeable_state: 'dirty',
base: { ref: 'main', sha: 'base-oid' },
head: { ref: 'feature/test', sha: 'head-oid' }
}
])
})
@@ -566,16 +606,13 @@ describe('getPRForBranch', () => {
{
number: 42,
title: 'Fix PR discovery',
state: 'OPEN',
url: 'https://github.com/acme/widgets/pull/42',
statusCheckRollup: [],
updatedAt: '2026-03-28T00:00:00Z',
isDraft: false,
mergeable: 'CONFLICTING',
baseRefName: 'main',
headRefName: 'feature/test',
baseRefOid: 'base-oid',
headRefOid: 'head-oid'
state: 'open',
html_url: 'https://github.com/acme/widgets/pull/42',
updated_at: '2026-03-28T00:00:00Z',
draft: false,
mergeable_state: 'dirty',
base: { ref: 'main', sha: 'base-oid' },
head: { ref: 'feature/test', sha: 'head-oid' }
}
])
})
@@ -600,16 +637,13 @@ describe('getPRForBranch', () => {
{
number: 42,
title: 'Fix PR discovery',
state: 'OPEN',
url: 'https://github.com/acme/widgets/pull/42',
statusCheckRollup: [],
updatedAt: '2026-03-28T00:00:00Z',
isDraft: false,
mergeable: 'CONFLICTING',
baseRefName: 'main',
headRefName: 'feature/test',
baseRefOid: 'base-oid',
headRefOid: 'head-oid'
state: 'open',
html_url: 'https://github.com/acme/widgets/pull/42',
updated_at: '2026-03-28T00:00:00Z',
draft: false,
mergeable_state: 'dirty',
base: { ref: 'main', sha: 'base-oid' },
head: { ref: 'feature/test', sha: 'head-oid' }
}
])
})
@@ -768,6 +802,11 @@ describe('GitHub GraphQL rate-limit guard', () => {
getOwnerRepoMock.mockReset()
getIssueOwnerRepoMock.mockReset()
getOwnerRepoForRemoteMock.mockReset()
resolvePRRepositoryCandidatesMock.mockReset()
resolvePRRepositoryCandidatesMock.mockImplementation(async (repoPath, connectionId) => {
const origin = await getOwnerRepoMock(repoPath, connectionId)
return { candidates: origin ? [origin] : [], headRepo: origin }
})
getRemoteUrlForRepoMock.mockReset()
gitExecFileAsyncMock.mockReset()
rateLimitGuardMock.mockReset()
@@ -810,6 +849,68 @@ describe('GitHub GraphQL rate-limit guard', () => {
expect(noteRateLimitSpendMock).not.toHaveBeenCalled()
})
it('uses explicit PR repo for comments when a fork PR is discovered', async () => {
rateLimitGuardMock.mockReturnValue({
blocked: true,
remaining: 4,
limit: 5000,
resetAt: 1_800_000_000
})
ghExecFileAsyncMock
.mockResolvedValueOnce({
stdout: JSON.stringify([
{
id: 10,
user: { login: 'octo', avatar_url: 'https://avatar', type: 'User' },
body: 'top-level',
created_at: '2026-04-01T00:00:00Z',
html_url: 'https://github.com/stablyai/orca/pull/7#issuecomment-10'
}
])
})
.mockResolvedValueOnce({ stdout: '[]' })
await getPRComments('/repo-root', 7, { prRepo: { owner: 'stablyai', repo: 'orca' } }, undefined)
expect(getOwnerRepoMock).not.toHaveBeenCalled()
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
1,
['api', '--cache', '60s', 'repos/stablyai/orca/issues/7/comments?per_page=100'],
{ cwd: '/repo-root' }
)
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
2,
['api', '--cache', '60s', 'repos/stablyai/orca/pulls/7/reviews?per_page=100'],
{ cwd: '/repo-root' }
)
})
it('uses explicit PR repo for merge and title mutations', async () => {
ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
await expect(
mergePR('/repo-root', 7, 'squash', undefined, { owner: 'stablyai', repo: 'orca' })
).resolves.toEqual({ ok: true })
await expect(
updatePRTitle('/repo-root', 7, 'New title', undefined, { owner: 'stablyai', repo: 'orca' })
).resolves.toBe(true)
expect(getOwnerRepoMock).not.toHaveBeenCalled()
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
1,
['pr', 'merge', '7', '--squash', '--repo', 'stablyai/orca'],
expect.objectContaining({
cwd: '/repo-root',
env: expect.objectContaining({ GH_PROMPT_DISABLED: '1' })
})
)
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
2,
['pr', 'edit', '7', '--title', 'New title', '--repo', 'stablyai/orca'],
{ cwd: '/repo-root' }
)
})
it('blocks review-thread resolve mutations before spawning gh when GraphQL is low', async () => {
rateLimitGuardMock.mockReturnValue({
blocked: true,
+101 -57
View File
@@ -37,6 +37,7 @@ import {
getOwnerRepo,
getIssueOwnerRepo,
getOwnerRepoForRemote,
resolvePRRepositoryCandidates,
resolveIssueSource,
classifyGhError,
classifyListIssuesError,
@@ -1451,13 +1452,14 @@ function mapRestPullRequest(pr: RestPullRequest): PullRequestLookupData {
}
async function getRestPRForBranch(
ownerRepo: OwnerRepo,
prRepo: OwnerRepo,
headOwner: string,
branchName: string,
ghOptions: ReturnType<typeof ghRepoExecOptions>
): Promise<PullRequestLookupData | null> {
const head = encodeURIComponent(`${ownerRepo.owner}:${branchName}`)
const head = encodeURIComponent(`${headOwner}:${branchName}`)
const { stdout } = await ghExecFileAsync(
['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls?head=${head}&state=all&per_page=1`],
['api', `repos/${prRepo.owner}/${prRepo.repo}/pulls?head=${head}&state=all&per_page=1`],
ghOptions
)
const list = JSON.parse(stdout) as RestPullRequest[]
@@ -1465,6 +1467,32 @@ async function getRestPRForBranch(
return pr ? mapRestPullRequest(pr) : null
}
async function getFallbackPRListForBranch(
prRepo: OwnerRepo,
branchName: string,
ghOptions: ReturnType<typeof ghRepoExecOptions>
): Promise<PullRequestLookupData | null> {
const { stdout } = await ghExecFileAsync(
[
'pr',
'list',
'--repo',
`${prRepo.owner}/${prRepo.repo}`,
'--head',
branchName,
'--state',
'all',
'--limit',
'1',
'--json',
PR_LOOKUP_JSON_FIELDS
],
ghOptions
)
const list = JSON.parse(stdout) as PullRequestLookupData[]
return list[0] ?? null
}
async function getRestPRByNumber(
ownerRepo: OwnerRepo,
number: number,
@@ -1522,18 +1550,15 @@ async function exactPRMatchesWorktreeHead(
data: PullRequestLookupData,
connectionId?: string | null
): Promise<boolean> {
if (!branchName || data.headRefName === branchName) {
return true
}
if (connectionId || !data.headRefOid) {
return false
}
try {
const { stdout } = await gitExecFileAsync(['rev-parse', 'HEAD'], { cwd: repoPath })
return stdout.trim() === data.headRefOid
} catch {
return false
if (!connectionId && data.headRefOid) {
try {
const { stdout } = await gitExecFileAsync(['rev-parse', 'HEAD'], { cwd: repoPath })
return stdout.trim() === data.headRefOid
} catch {
return false
}
}
return !branchName || data.headRefName === branchName
}
function isNotFoundGhError(err: unknown): boolean {
@@ -1564,22 +1589,39 @@ export async function getPRForBranch(
): Promise<PRInfo | null> {
// Strip refs/heads/ prefix if present
const branchName = branch.replace(/^refs\/heads\//, '')
if (!branchName && typeof linkedPRNumber !== 'number') {
return null
}
const context = githubRepoContext(repoPath, connectionId)
const ghOptions = ghRepoExecOptions(context)
await acquire()
try {
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const { candidates, headRepo } = await resolvePRRepositoryCandidates(repoPath, connectionId)
let data: PullRequestLookupData | null = null
let dataRepo: OwnerRepo | null = null
let exactLinkedData: PullRequestLookupData | null = null
let exactLinkedRepo: OwnerRepo | null = null
if (ownerRepo && typeof linkedPRNumber === 'number') {
data = await getPRByNumber(ownerRepo, linkedPRNumber, ghOptions)
if (data && !(await exactPRMatchesWorktreeHead(repoPath, branchName, data, connectionId))) {
// Why: linked PR metadata is user-editable. If the stored number still
// resolves but no longer matches this worktree, let branch lookup correct it.
exactLinkedData = data
data = null
if (typeof linkedPRNumber === 'number') {
for (const candidate of candidates) {
try {
const linkedData = await getPRByNumber(candidate, linkedPRNumber, ghOptions)
if (!linkedData) {
continue
}
if (await exactPRMatchesWorktreeHead(repoPath, branchName, linkedData, connectionId)) {
data = linkedData
dataRepo = candidate
break
}
// Why: linked PR metadata is user-editable. If the stored number still
// resolves but no longer matches this worktree, let branch lookup correct it.
exactLinkedData ??= linkedData
exactLinkedRepo ??= candidate
} catch {
// Candidate probing is best-effort; another repo may own the PR.
}
}
}
@@ -1587,33 +1629,28 @@ export async function getPRForBranch(
// An empty --head filter causes gh to return an arbitrary PR — skip the
// branch lookup and rely on the linkedPR fallback below if available.
if (!data && branchName) {
if (ownerRepo) {
try {
const { stdout } = await ghExecFileAsync(
[
'pr',
'list',
'--repo',
`${ownerRepo.owner}/${ownerRepo.repo}`,
'--head',
branchName,
'--state',
'all',
'--limit',
'1',
'--json',
PR_LOOKUP_JSON_FIELDS
],
ghOptions
)
const list = JSON.parse(stdout) as PullRequestLookupData[]
data = list[0] ?? null
} catch (err) {
// Why: `gh pr list/view` uses GraphQL and can hit that quota while
// REST is still available. Falling back prevents a real PR from
// rendering as "No pull request found" during GraphQL outages.
if (!isNotFoundGhError(err)) {
data = await getRestPRForBranch(ownerRepo, branchName, ghOptions)
if (candidates.length > 0) {
for (const candidate of candidates) {
try {
data = headRepo
? await getRestPRForBranch(candidate, headRepo.owner, branchName, ghOptions)
: await getFallbackPRListForBranch(candidate, branchName, ghOptions)
if (data) {
dataRepo = candidate
break
}
} catch (err) {
if (!headRepo && !isNotFoundGhError(err)) {
try {
data = await getRestPRForBranch(candidate, candidate.owner, branchName, ghOptions)
if (data) {
dataRepo = candidate
break
}
} catch {
// Continue to the next candidate below.
}
}
}
}
} else {
@@ -1625,7 +1662,7 @@ export async function getPRForBranch(
}
}
if (!data && !ownerRepo && typeof linkedPRNumber === 'number') {
if (!data && candidates.length === 0 && typeof linkedPRNumber === 'number') {
const args = ['pr', 'view', String(linkedPRNumber), '--json', PR_LOOKUP_JSON_FIELDS]
try {
const { stdout } = await ghExecFileAsync(args, ghOptions)
@@ -1641,6 +1678,7 @@ export async function getPRForBranch(
if (!data && exactLinkedData) {
data = exactLinkedData
dataRepo = exactLinkedRepo
}
if (!data) {
@@ -1665,6 +1703,8 @@ export async function getPRForBranch(
updatedAt: data.updatedAt,
mergeable: (data.mergeable as PRMergeableState) ?? 'UNKNOWN',
headSha: data.headRefOid,
prRepo: dataRepo ?? undefined,
headRepo: headRepo ?? undefined,
conflictSummary
}
} catch {
@@ -1683,11 +1723,12 @@ export async function getPRChecks(
repoPath: string,
prNumber: number,
headSha?: string,
prRepo?: OwnerRepo | null,
options?: { noCache?: boolean },
connectionId?: string | null
): Promise<PRCheckDetail[]> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
const fallbackToPRChecks = async (): Promise<PRCheckDetail[]> => {
const fallbackArgs = ['pr', 'checks', String(prNumber), '--json', 'name,state,link']
if (ownerRepo) {
@@ -1784,6 +1825,7 @@ export async function rerunPRChecks(
repoPath,
prNumber,
options.headSha,
ownerRepo,
{ noCache: true },
connectionId
)
@@ -1908,11 +1950,11 @@ query($owner: String!, $repo: String!, $pr: Int!) {
export async function getPRComments(
repoPath: string,
prNumber: number,
options?: { noCache?: boolean },
options?: { noCache?: boolean; prRepo?: OwnerRepo | null },
connectionId?: string | null
): Promise<PRComment[]> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ownerRepo = options?.prRepo ?? (await getOwnerRepo(repoPath, connectionId))
await acquire()
try {
if (ownerRepo) {
@@ -2345,10 +2387,11 @@ export async function mergePR(
repoPath: string,
prNumber: number,
method: 'merge' | 'squash' | 'rebase' = 'squash',
connectionId?: string | null
connectionId?: string | null,
prRepo?: OwnerRepo | null
): Promise<{ ok: true } | { ok: false; error: string }> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
await acquire()
try {
// Don't use --delete-branch: it tries to delete the local branch which
@@ -2447,10 +2490,11 @@ export async function updatePRTitle(
repoPath: string,
prNumber: number,
title: string,
connectionId?: string | null
connectionId?: string | null,
prRepo?: OwnerRepo | null
): Promise<boolean> {
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId))
const ownerRepo = await getOwnerRepo(repoPath, connectionId)
const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId))
await acquire()
try {
const args = ['pr', 'edit', String(prNumber), '--title', title]
+53
View File
@@ -20,8 +20,10 @@ import {
classifyListIssuesError,
getIssueOwnerRepo,
getOwnerRepo,
getOwnerRepoForRemote,
parseGitHubRemoteIdentity,
parseGitHubOwnerRepo,
resolvePRRepositoryCandidates,
resolveIssueSource
} from './gh-utils'
@@ -136,6 +138,57 @@ describe('github owner/repo resolution', () => {
await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'local', repo: 'orca' })
await expect(getOwnerRepo('/repo', 'ssh-1')).resolves.toEqual({ owner: 'remote', repo: 'orca' })
})
it('resolves PR candidates as upstream then origin and de-dupes matching slugs', async () => {
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'git@github.com:Acme/Orca.git\n' })
.mockResolvedValueOnce({ stdout: 'git@github.com:acme/orca.git\n' })
await expect(resolvePRRepositoryCandidates('/repo')).resolves.toEqual({
candidates: [{ owner: 'Acme', repo: 'Orca' }],
headRepo: { owner: 'acme', repo: 'orca' }
})
})
it('ignores non-GitHub upstream while keeping origin as the head repo', async () => {
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'git@example.com:Acme/Orca.git\n' })
.mockResolvedValueOnce({ stdout: 'git@github.com:fork/orca.git\n' })
await expect(resolvePRRepositoryCandidates('/repo')).resolves.toEqual({
candidates: [{ owner: 'fork', repo: 'orca' }],
headRepo: { owner: 'fork', repo: 'orca' }
})
})
it('expires cached remote owner/repo entries after the TTL', async () => {
vi.useFakeTimers()
try {
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'git@github.com:old/orca.git\n' })
.mockResolvedValueOnce({ stdout: 'git@github.com:new/orca.git\n' })
await expect(getOwnerRepoForRemote('/repo', 'origin')).resolves.toEqual({
owner: 'old',
repo: 'orca'
})
await expect(getOwnerRepoForRemote('/repo', 'origin')).resolves.toEqual({
owner: 'old',
repo: 'orca'
})
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(30_001)
await expect(getOwnerRepoForRemote('/repo', 'origin')).resolves.toEqual({
owner: 'new',
repo: 'orca'
})
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
} finally {
vi.useRealTimers()
}
})
})
describe('resolveIssueSource', () => {
+52 -5
View File
@@ -137,7 +137,14 @@ export function ghRepoExecOptions(context: GitHubRepoContext): {
return context.connectionId ? {} : { cwd: context.repoPath }
}
const ownerRepoCache = new Map<string, OwnerRepo | null>()
const OWNER_REPO_CACHE_TTL_MS = 30_000
type OwnerRepoCacheEntry = {
value: OwnerRepo | null
expiresAt: number
}
const ownerRepoCache = new Map<string, OwnerRepoCacheEntry>()
/** @internal — exposed for tests only */
export function _resetOwnerRepoCache(): void {
@@ -190,20 +197,27 @@ export async function getOwnerRepoForRemote(
): Promise<OwnerRepo | null> {
const context = githubRepoContext(repoPath, connectionId)
const cacheKey = `${context.connectionId ?? 'local'}\0${context.repoPath}\0${remoteName}`
if (ownerRepoCache.has(cacheKey)) {
return ownerRepoCache.get(cacheKey)!
const cached = ownerRepoCache.get(cacheKey)
if (cached && cached.expiresAt > Date.now()) {
return cached.value
}
if (cached) {
ownerRepoCache.delete(cacheKey)
}
try {
const remoteUrl = await getRemoteUrlForRepo(context, remoteName)
const result = remoteUrl ? parseGitHubOwnerRepo(remoteUrl) : null
if (result) {
ownerRepoCache.set(cacheKey, result)
ownerRepoCache.set(cacheKey, {
value: result,
expiresAt: Date.now() + OWNER_REPO_CACHE_TTL_MS
})
return result
}
} catch {
// ignore — non-GitHub remote or no remote
}
ownerRepoCache.set(cacheKey, null)
ownerRepoCache.set(cacheKey, { value: null, expiresAt: Date.now() + OWNER_REPO_CACHE_TTL_MS })
return null
}
@@ -225,6 +239,39 @@ export async function getIssueOwnerRepo(
return getOwnerRepoForRemote(repoPath, 'origin', connectionId)
}
export type PRRepositoryCandidates = {
candidates: OwnerRepo[]
headRepo: OwnerRepo | null
}
function ownerRepoKey(ownerRepo: OwnerRepo): string {
return `${ownerRepo.owner.toLowerCase()}/${ownerRepo.repo.toLowerCase()}`
}
export async function resolvePRRepositoryCandidates(
repoPath: string,
connectionId?: string | null
): Promise<PRRepositoryCandidates> {
const upstream = await getOwnerRepoForRemote(repoPath, 'upstream', connectionId)
const origin = await getOwnerRepoForRemote(repoPath, 'origin', connectionId)
const seen = new Set<string>()
const candidates: OwnerRepo[] = []
for (const candidate of [upstream, origin]) {
if (!candidate) {
continue
}
const key = ownerRepoKey(candidate)
if (seen.has(key)) {
continue
}
seen.add(key)
candidates.push(candidate)
}
return { candidates, headRepo: origin }
}
export type ResolvedIssueSource = {
source: OwnerRepo | null
/** True when the user preferred `upstream` but the upstream remote is no
@@ -158,6 +158,13 @@ describe('getWorkItemDetails PR file viewed state', () => {
['src/viewed.ts', 'VIEWED'],
['src/changed.ts', 'DISMISSED']
])
expect(getPRChecksMock).toHaveBeenCalledWith('/repo-root', 42, 'head-sha', undefined, undefined)
expect(getPRChecksMock).toHaveBeenCalledWith(
'/repo-root',
42,
'head-sha',
null,
undefined,
undefined
)
})
})
+2 -2
View File
@@ -741,8 +741,8 @@ export async function getWorkItemDetails(
const [mentionParticipants, checks] = await Promise.all([
getMentionParticipants(repoPath, item, comments, participants, connectionId),
shas?.headSha
? getPRChecks(repoPath, item.number, shas.headSha, undefined, connectionId)
: getPRChecks(repoPath, item.number, undefined, undefined, connectionId)
? getPRChecks(repoPath, item.number, shas.headSha, null, undefined, connectionId)
: getPRChecks(repoPath, item.number, undefined, null, undefined, connectionId)
])
return {