Fix PR lookup for tracked upstream branches (#3484)
* Fix PR lookup for tracked upstream branches * fix: handle upstream PR lookup over SSH Co-authored-by: Orca <help@stably.ai> --------- Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com> Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -19,6 +19,7 @@ const {
|
||||
noteRateLimitSpendMock,
|
||||
ghRepoExecOptionsMock,
|
||||
githubRepoContextMock,
|
||||
getSshGitProviderMock,
|
||||
acquireMock,
|
||||
releaseMock
|
||||
} = vi.hoisted(() => ({
|
||||
@@ -40,6 +41,7 @@ const {
|
||||
repoPath,
|
||||
connectionId: connectionId ?? null
|
||||
})),
|
||||
getSshGitProviderMock: vi.fn(),
|
||||
acquireMock: vi.fn(),
|
||||
releaseMock: vi.fn()
|
||||
}))
|
||||
@@ -78,6 +80,10 @@ vi.mock('../git/runner', () => ({
|
||||
gitExecFileAsync: gitExecFileAsyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../providers/ssh-git-dispatch', () => ({
|
||||
getSshGitProvider: getSshGitProviderMock
|
||||
}))
|
||||
|
||||
vi.mock('./rate-limit', () => ({
|
||||
getRateLimit: getRateLimitMock,
|
||||
rateLimitGuard: rateLimitGuardMock,
|
||||
@@ -118,6 +124,7 @@ describe('getPRForBranch', () => {
|
||||
noteRateLimitSpendMock.mockReset()
|
||||
ghRepoExecOptionsMock.mockClear()
|
||||
githubRepoContextMock.mockClear()
|
||||
getSshGitProviderMock.mockReset()
|
||||
acquireMock.mockReset()
|
||||
releaseMock.mockReset()
|
||||
acquireMock.mockResolvedValue(undefined)
|
||||
@@ -604,6 +611,197 @@ describe('getPRForBranch', () => {
|
||||
expect(pr).toMatchObject({ number: 42, title: 'Fallback PR lookup' })
|
||||
})
|
||||
|
||||
it('falls back to the tracked upstream branch when the local branch name differs', async () => {
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([]) })
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 78,
|
||||
title: 'Upstream branch PR',
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/acme/widgets/pull/78',
|
||||
updated_at: '2026-03-28T00:00:00Z',
|
||||
draft: false,
|
||||
mergeable: true,
|
||||
base: { ref: 'main', sha: 'base-oid' },
|
||||
head: { ref: 'contributor/original', sha: 'upstream-head-oid' }
|
||||
}
|
||||
])
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 78,
|
||||
title: 'Hydrated upstream branch PR',
|
||||
state: 'OPEN',
|
||||
url: 'https://github.com/acme/widgets/pull/78',
|
||||
statusCheckRollup: [],
|
||||
updatedAt: '2026-03-28T00:00:00Z',
|
||||
isDraft: false,
|
||||
mergeable: 'MERGEABLE',
|
||||
baseRefName: 'main',
|
||||
headRefName: 'contributor/original',
|
||||
baseRefOid: 'base-oid',
|
||||
headRefOid: 'upstream-head-oid'
|
||||
})
|
||||
})
|
||||
gitExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: 'origin/contributor/original\n',
|
||||
stderr: ''
|
||||
})
|
||||
|
||||
const pr = await getPRForBranch('/repo-root', 'local-created-from-pr')
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
['rev-parse', '--abbrev-ref', '--symbolic-full-name', 'local-created-from-pr@{upstream}'],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
['api', 'repos/acme/widgets/pulls?head=acme%3Alocal-created-from-pr&state=all&per_page=1'],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
['api', 'repos/acme/widgets/pulls?head=acme%3Acontributor%2Foriginal&state=all&per_page=1'],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
[
|
||||
'pr',
|
||||
'view',
|
||||
'78',
|
||||
'--repo',
|
||||
'acme/widgets',
|
||||
'--json',
|
||||
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,reviewDecision,mergeStateStatus,autoMergeRequest,baseRefName,headRefName,baseRefOid,headRefOid'
|
||||
],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(pr).toMatchObject({
|
||||
number: 78,
|
||||
title: 'Hydrated upstream branch PR',
|
||||
headSha: 'upstream-head-oid'
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the tracked upstream remote owner for fork branch lookup', async () => {
|
||||
resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({
|
||||
candidates: [
|
||||
{ owner: 'stablyai', repo: 'orca' },
|
||||
{ owner: 'origin-owner', repo: 'orca' }
|
||||
],
|
||||
headRepo: { owner: 'origin-owner', repo: 'orca' }
|
||||
})
|
||||
getOwnerRepoForRemoteMock.mockResolvedValueOnce({ owner: 'fork-owner', repo: 'orca' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([]) })
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([]) })
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 78,
|
||||
title: 'Fork upstream branch PR',
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/stablyai/orca/pull/78',
|
||||
updated_at: '2026-03-28T00:00:00Z',
|
||||
draft: false,
|
||||
mergeable: true,
|
||||
base: { ref: 'main', sha: 'base-oid' },
|
||||
head: { ref: 'contributor/original', sha: 'upstream-head-oid' }
|
||||
}
|
||||
])
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 78,
|
||||
title: 'Hydrated fork upstream branch PR',
|
||||
state: 'OPEN',
|
||||
url: 'https://github.com/stablyai/orca/pull/78',
|
||||
statusCheckRollup: [],
|
||||
updatedAt: '2026-03-28T00:00:00Z',
|
||||
isDraft: false,
|
||||
mergeable: 'MERGEABLE',
|
||||
baseRefName: 'main',
|
||||
headRefName: 'contributor/original',
|
||||
baseRefOid: 'base-oid',
|
||||
headRefOid: 'upstream-head-oid'
|
||||
})
|
||||
})
|
||||
gitExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: 'fork/contributor/original\n',
|
||||
stderr: ''
|
||||
})
|
||||
|
||||
const pr = await getPRForBranch('/repo-root', 'local-created-from-pr')
|
||||
|
||||
expect(getOwnerRepoForRemoteMock).toHaveBeenCalledWith('/repo-root', 'fork', undefined)
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
[
|
||||
'api',
|
||||
'repos/stablyai/orca/pulls?head=fork-owner%3Acontributor%2Foriginal&state=all&per_page=1'
|
||||
],
|
||||
{ cwd: '/repo-root' }
|
||||
)
|
||||
expect(pr).toMatchObject({
|
||||
number: 78,
|
||||
title: 'Hydrated fork upstream branch PR',
|
||||
prRepo: { owner: 'stablyai', repo: 'orca' },
|
||||
headRepo: { owner: 'fork-owner', repo: 'orca' }
|
||||
})
|
||||
})
|
||||
|
||||
it('checks the tracked upstream branch through the SSH git provider', async () => {
|
||||
const sshGitProvider = {
|
||||
exec: vi.fn().mockResolvedValue({
|
||||
stdout: 'origin/contributor/original\n',
|
||||
stderr: ''
|
||||
})
|
||||
}
|
||||
getSshGitProviderMock.mockReturnValue(sshGitProvider)
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
getOwnerRepoForRemoteMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([]) })
|
||||
.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 78,
|
||||
title: 'SSH upstream branch PR',
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/acme/widgets/pull/78',
|
||||
updated_at: '2026-03-28T00:00:00Z',
|
||||
draft: false,
|
||||
mergeable: true,
|
||||
base: { ref: 'main', sha: 'base-oid' },
|
||||
head: { ref: 'contributor/original', sha: 'upstream-head-oid' }
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
const pr = await getPRForBranch(
|
||||
'/remote/repo-root',
|
||||
'local-created-from-pr',
|
||||
undefined,
|
||||
'ssh-1'
|
||||
)
|
||||
|
||||
expect(sshGitProvider.exec).toHaveBeenCalledWith(
|
||||
['rev-parse', '--abbrev-ref', '--symbolic-full-name', 'local-created-from-pr@{upstream}'],
|
||||
'/remote/repo-root'
|
||||
)
|
||||
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
['api', 'repos/acme/widgets/pulls?head=acme%3Acontributor%2Foriginal&state=all&per_page=1'],
|
||||
{}
|
||||
)
|
||||
expect(pr).toMatchObject({ number: 78, title: 'SSH upstream branch PR' })
|
||||
})
|
||||
|
||||
it('uses linked PR number as the source of truth when provided', async () => {
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
ghExecFileAsyncMock.mockResolvedValueOnce({
|
||||
|
||||
+121
-43
@@ -36,6 +36,7 @@ import { tmpdir } from 'os'
|
||||
import { getPRConflictSummary } from './conflict-summary'
|
||||
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
|
||||
import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths'
|
||||
import { splitRemoteBranchName } from '../../shared/git-effective-upstream'
|
||||
import {
|
||||
execFileAsync,
|
||||
ghExecFileAsync,
|
||||
@@ -55,6 +56,7 @@ import {
|
||||
getRemoteUrlForRepo,
|
||||
type OwnerRepo
|
||||
} from './gh-utils'
|
||||
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
|
||||
export { _resetOwnerRepoCache } from './gh-utils'
|
||||
export {
|
||||
getIssue,
|
||||
@@ -1891,6 +1893,98 @@ async function getFallbackPRListForBranch(
|
||||
return list[0] ?? null
|
||||
}
|
||||
|
||||
type TrackedUpstreamBranch = {
|
||||
remoteName: string
|
||||
branchName: string
|
||||
}
|
||||
|
||||
function parseTrackedUpstreamBranch(
|
||||
upstreamRef: string,
|
||||
branchName: string
|
||||
): TrackedUpstreamBranch | null {
|
||||
const parsed = splitRemoteBranchName(upstreamRef.trim())
|
||||
if (!parsed || parsed.branchName === branchName) {
|
||||
return null
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
async function getTrackedUpstreamBranch(
|
||||
repoPath: string,
|
||||
branchName: string,
|
||||
connectionId?: string | null
|
||||
): Promise<TrackedUpstreamBranch | null> {
|
||||
const args = ['rev-parse', '--abbrev-ref', '--symbolic-full-name', `${branchName}@{upstream}`]
|
||||
try {
|
||||
const provider = connectionId ? getSshGitProvider(connectionId) : null
|
||||
const result = provider
|
||||
? await provider.exec(args, repoPath)
|
||||
: await gitExecFileAsync(args, { cwd: repoPath })
|
||||
return parseTrackedUpstreamBranch(result.stdout, branchName)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function lookupPRByBranchName(args: {
|
||||
candidates: OwnerRepo[]
|
||||
headRepo: OwnerRepo | null
|
||||
branchName: string
|
||||
ghOptions: GhExecOptions
|
||||
}): Promise<{ data: PullRequestLookupData | null; dataRepo: OwnerRepo | null }> {
|
||||
if (args.candidates.length > 0) {
|
||||
for (const candidate of args.candidates) {
|
||||
try {
|
||||
const branchData = args.headRepo
|
||||
? await getRestPRForBranch(
|
||||
candidate,
|
||||
args.headRepo.owner,
|
||||
args.branchName,
|
||||
args.ghOptions
|
||||
)
|
||||
: await getFallbackPRListForBranch(candidate, args.branchName, args.ghOptions)
|
||||
// Why: REST/list branch lookup identifies the PR cheaply; exact
|
||||
// `gh pr view` carries review, merge queue, and auto-merge state.
|
||||
const data = await hydrateBranchLookupWithExactPR(candidate, branchData, args.ghOptions)
|
||||
if (data) {
|
||||
return { data, dataRepo: candidate }
|
||||
}
|
||||
} catch (err) {
|
||||
if (args.headRepo) {
|
||||
throw err
|
||||
}
|
||||
const branchData = await getRestPRForBranch(
|
||||
candidate,
|
||||
candidate.owner,
|
||||
args.branchName,
|
||||
args.ghOptions
|
||||
)
|
||||
const data = await hydrateBranchLookupWithExactPR(candidate, branchData, args.ghOptions)
|
||||
if (data) {
|
||||
return { data, dataRepo: candidate }
|
||||
}
|
||||
}
|
||||
}
|
||||
return { data: null, dataRepo: null }
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['pr', 'view', args.branchName, '--json', PR_LOOKUP_JSON_FIELDS],
|
||||
args.ghOptions
|
||||
)
|
||||
return {
|
||||
data: normalizePullRequestLookupData(JSON.parse(stdout) as PullRequestLookupData),
|
||||
dataRepo: null
|
||||
}
|
||||
} catch (err) {
|
||||
if (isNoPullRequestError(err)) {
|
||||
return { data: null, dataRepo: null }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function getRestPRByNumber(
|
||||
ownerRepo: OwnerRepo,
|
||||
number: number,
|
||||
@@ -2051,6 +2145,7 @@ export async function getPRForBranchOutcome(
|
||||
const { candidates, headRepo } = await resolvePRRepositoryCandidates(repoPath, connectionId)
|
||||
let data: PullRequestLookupData | null = null
|
||||
let dataRepo: OwnerRepo | null = null
|
||||
let dataHeadRepo: OwnerRepo | null = headRepo
|
||||
|
||||
if (typeof linkedPRNumber === 'number') {
|
||||
const exactLookup = await lookupPRByNumber({
|
||||
@@ -2063,49 +2158,32 @@ export async function getPRForBranchOutcome(
|
||||
} else if (branchName) {
|
||||
// During a rebase the worktree is in detached HEAD and branch is empty.
|
||||
// An empty --head filter causes gh to return an arbitrary PR.
|
||||
if (candidates.length > 0) {
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const branchData = headRepo
|
||||
? await getRestPRForBranch(candidate, headRepo.owner, branchName, ghOptions)
|
||||
: await getFallbackPRListForBranch(candidate, branchName, ghOptions)
|
||||
// Why: REST/list branch lookup identifies the PR cheaply; exact
|
||||
// `gh pr view` carries review, merge queue, and auto-merge state.
|
||||
data = await hydrateBranchLookupWithExactPR(candidate, branchData, ghOptions)
|
||||
if (data) {
|
||||
dataRepo = candidate
|
||||
break
|
||||
}
|
||||
} catch (err) {
|
||||
if (headRepo) {
|
||||
throw err
|
||||
} else {
|
||||
const branchData = await getRestPRForBranch(
|
||||
candidate,
|
||||
candidate.owner,
|
||||
branchName,
|
||||
ghOptions
|
||||
)
|
||||
data = await hydrateBranchLookupWithExactPR(candidate, branchData, ghOptions)
|
||||
if (data) {
|
||||
dataRepo = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(
|
||||
['pr', 'view', branchName, '--json', PR_LOOKUP_JSON_FIELDS],
|
||||
const branchLookup = await lookupPRByBranchName({
|
||||
candidates,
|
||||
headRepo,
|
||||
branchName,
|
||||
ghOptions
|
||||
})
|
||||
data = branchLookup.data
|
||||
dataRepo = branchLookup.dataRepo
|
||||
if (!data) {
|
||||
// Why: worktrees can have a short local branch tracking a differently
|
||||
// named remote PR head; after the local miss, try that configured head.
|
||||
const upstreamBranch = await getTrackedUpstreamBranch(repoPath, branchName, connectionId)
|
||||
if (upstreamBranch) {
|
||||
const upstreamHeadRepo =
|
||||
(await getOwnerRepoForRemote(repoPath, upstreamBranch.remoteName, connectionId)) ??
|
||||
headRepo
|
||||
const upstreamLookup = await lookupPRByBranchName({
|
||||
candidates,
|
||||
headRepo: upstreamHeadRepo,
|
||||
branchName: upstreamBranch.branchName,
|
||||
ghOptions
|
||||
)
|
||||
data = normalizePullRequestLookupData(JSON.parse(stdout))
|
||||
} catch (err) {
|
||||
if (isNoPullRequestError(err)) {
|
||||
data = null
|
||||
} else {
|
||||
throw err
|
||||
})
|
||||
data = upstreamLookup.data
|
||||
dataRepo = upstreamLookup.dataRepo
|
||||
if (data) {
|
||||
dataHeadRepo = upstreamHeadRepo
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2151,7 +2229,7 @@ export async function getPRForBranchOutcome(
|
||||
...(data.mergeStateStatus !== undefined ? { mergeStateStatus: data.mergeStateStatus } : {}),
|
||||
headSha: data.headRefOid,
|
||||
prRepo: dataRepo ?? undefined,
|
||||
headRepo: headRepo ?? undefined,
|
||||
headRepo: dataHeadRepo ?? undefined,
|
||||
conflictSummary
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user