diff --git a/src/main/git/fetch-error-classification.test.ts b/src/main/git/fetch-error-classification.test.ts new file mode 100644 index 000000000..a7ce57586 --- /dev/null +++ b/src/main/git/fetch-error-classification.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { isMissingRemoteRefGitError } from './fetch-error-classification' + +describe('isMissingRemoteRefGitError', () => { + it('matches missing remote ref messages', () => { + expect( + isMissingRemoteRefGitError( + new Error('fatal: could not find remote ref refs/heads/feature/test') + ) + ).toBe(true) + expect( + isMissingRemoteRefGitError( + new Error("fatal: couldn't find remote ref refs/heads/feature/test") + ) + ).toBe(true) + }) + + it('does not match auth or network failures', () => { + expect(isMissingRemoteRefGitError(new Error('fatal: Authentication failed'))).toBe(false) + expect( + isMissingRemoteRefGitError(new Error('fatal: unable to access repo: Could not resolve host')) + ).toBe(false) + }) +}) diff --git a/src/main/git/fetch-error-classification.ts b/src/main/git/fetch-error-classification.ts new file mode 100644 index 000000000..907b92e59 --- /dev/null +++ b/src/main/git/fetch-error-classification.ts @@ -0,0 +1,8 @@ +export function isMissingRemoteRefGitError(error: unknown): boolean { + const message = error instanceof Error ? error.message : String(error) + const normalized = message.toLowerCase() + return ( + normalized.includes('could not find remote ref') || + normalized.includes("couldn't find remote ref") + ) +} diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts index 01a787393..a13d62506 100644 --- a/src/main/github/client-work-items.test.ts +++ b/src/main/github/client-work-items.test.ts @@ -350,4 +350,47 @@ describe('listWorkItems', () => { } ]) }) + + it('marks fork PRs as cross-repository when REST payload only includes head.label', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ stdout: '[]' }) + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 1849, + title: 'Fork PR with missing head repo', + state: 'open', + html_url: 'https://github.com/stablyai/orca/pull/1849', + updated_at: '2026-04-01T00:00:00Z', + user: { login: 'contributor' }, + head: { + ref: 'feat/onboarding-model-choice-782', + repo: null, + label: 'contributor:feat/onboarding-model-choice-782' + }, + base: { ref: 'main' } + } + ]) + }) + + const { items } = await listWorkItems('/repo-root', 10) + expect(items).toEqual([ + { + id: 'pr:1849', + type: 'pr', + number: 1849, + title: 'Fork PR with missing head repo', + state: 'open', + url: 'https://github.com/stablyai/orca/pull/1849', + labels: [], + updatedAt: '2026-04-01T00:00:00Z', + author: 'contributor', + branchName: 'feat/onboarding-model-choice-782', + baseRefName: 'main', + isCrossRepository: true + } + ]) + }) }) diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index 4ea209b66..864ba558c 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -793,6 +793,48 @@ describe('getPRForBranch', () => { }) expect(gitExecFileAsyncMock).not.toHaveBeenCalled() }) + + it('probes additional PR repo candidates when the first lookup is not found', async () => { + resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ + candidates: [ + { owner: 'fork', repo: 'orca' }, + { owner: 'stablyai', repo: 'orca' } + ], + headRepo: { owner: 'fork', repo: 'orca' } + }) + getOwnerRepoForRemoteMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) + ghExecFileAsyncMock + .mockRejectedValueOnce(new Error('HTTP 404: Not Found')) + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + head: { + ref: 'feature/test', + repo: { + full_name: 'fork/orca', + name: 'orca', + clone_url: 'https://github.com/fork/orca.git', + ssh_url: 'git@github.com:fork/orca.git', + owner: { login: 'fork' } + } + } + }) + }) + + await expect(getPullRequestPushTarget('/repo-root', 1849)).resolves.toEqual({ + remoteName: 'origin', + branchName: 'feature/test' + }) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 1, + ['api', 'repos/fork/orca/pulls/1849'], + { cwd: '/repo-root' } + ) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 2, + ['api', 'repos/stablyai/orca/pulls/1849'], + { cwd: '/repo-root' } + ) + }) }) describe('GitHub GraphQL rate-limit guard', () => { diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 5c93a5052..33aa7efb4 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -119,19 +119,38 @@ export async function getPullRequestPushTarget( ): Promise { const context = githubRepoContext(repoPath, connectionId) const ghOptions = ghRepoExecOptions(context) - const ownerRepo = await getOwnerRepo(repoPath, connectionId) - if (!ownerRepo) { + const { candidates } = await resolvePRRepositoryCandidates(repoPath, connectionId) + if (candidates.length === 0) { return null } await acquire() try { - const [{ stdout: prStdout }, origin] = await Promise.all([ - ghExecFileAsync(['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${prNumber}`], { - ...ghOptions - }), - getOwnerRepoForRemote(repoPath, 'origin', connectionId) - ]) + let prStdout = '' + for (const candidate of candidates) { + try { + const { stdout } = await ghExecFileAsync( + ['api', `repos/${candidate.owner}/${candidate.repo}/pulls/${prNumber}`], + { + ...ghOptions + } + ) + prStdout = stdout + break + } catch (error) { + // Why: in fork workflows `origin` is often the contributor fork while + // the PR number belongs to `upstream`; probe all known PR repos before + // deciding this PR number is unavailable. + if (isNotFoundGhError(error)) { + continue + } + throw error + } + } + if (!prStdout) { + return null + } + const origin = await getOwnerRepoForRemote(repoPath, 'origin', connectionId) const pr = JSON.parse(prStdout) as { head?: { ref?: string @@ -275,7 +294,8 @@ function extractHeadOwnerLogin(item: Record): string | null { } // REST API `pull_request` shape: head.repo.owner.login if (typeof item.head === 'object' && item.head !== null) { - const repo = (item.head as { repo?: unknown }).repo + const head = item.head as { repo?: unknown; user?: unknown; label?: unknown } + const repo = head.repo if (typeof repo === 'object' && repo !== null) { const owner = (repo as { owner?: unknown }).owner if (typeof owner === 'object' && owner !== null) { @@ -285,6 +305,21 @@ function extractHeadOwnerLogin(item: Record): string | null { } } } + // Why: when a fork is deleted or made inaccessible, GitHub can return + // `head.repo = null` but still include `head.user`/`head.label`. + const user = head.user + if (typeof user === 'object' && user !== null) { + const login = (user as { login?: unknown }).login + if (typeof login === 'string' && login.trim()) { + return login + } + } + if (typeof head.label === 'string') { + const owner = head.label.split(':', 1)[0]?.trim() + if (owner) { + return owner + } + } } return null } diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index d2d9f4ddb..afeb41f55 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -652,6 +652,93 @@ describe('registerWorktreeHandlers', () => { }) }) + it('resolves a fork PR base even when push-target discovery fails', async () => { + getPullRequestPushTargetMock.mockRejectedValueOnce(new Error('lookup failed')) + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'rev-parse') { + return { stdout: 'abc123\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + + const result = await handlers['worktrees:resolvePrBase'](null, { + repoId: 'repo-1', + prNumber: 1849, + headRefName: 'feat/onboarding-model-choice-782', + isCrossRepository: true + }) + + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head'], { + cwd: '/workspace/repo' + }) + expect(result).toEqual({ baseBranch: 'abc123' }) + }) + + it('falls back to refs/pull//head when branch fetch fails for a PR', async () => { + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if ( + args[0] === 'fetch' && + args[2] === + '+refs/heads/feat/onboarding-model-choice-782:refs/remotes/origin/feat/onboarding-model-choice-782' + ) { + throw new Error( + 'fatal: could not find remote ref refs/heads/feat/onboarding-model-choice-782' + ) + } + if (args[0] === 'rev-parse') { + return { stdout: 'abc123\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + + const result = await handlers['worktrees:resolvePrBase'](null, { + repoId: 'repo-1', + prNumber: 1849, + headRefName: 'feat/onboarding-model-choice-782' + }) + + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'fetch', + 'origin', + '+refs/heads/feat/onboarding-model-choice-782:refs/remotes/origin/feat/onboarding-model-choice-782' + ], + { cwd: '/workspace/repo' } + ) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head'], { + cwd: '/workspace/repo' + }) + expect(result).toEqual({ baseBranch: 'abc123' }) + }) + + it('does not fall back to refs/pull//head when branch fetch hits a network failure', async () => { + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if ( + args[0] === 'fetch' && + args[2] === + '+refs/heads/feat/onboarding-model-choice-782:refs/remotes/origin/feat/onboarding-model-choice-782' + ) { + throw new Error('fatal: unable to access repo: Could not resolve host: github.com') + } + return { stdout: '', stderr: '' } + }) + + const result = await handlers['worktrees:resolvePrBase'](null, { + repoId: 'repo-1', + prNumber: 1849, + headRefName: 'feat/onboarding-model-choice-782' + }) + + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + ['fetch', 'origin', 'refs/pull/1849/head'], + expect.anything() + ) + expect(result).toEqual({ + error: + 'Failed to fetch origin/feat/onboarding-model-choice-782: fatal: unable to access repo: Could not resolve host: github.com' + }) + }) + it('persists linked issue, PR, and selected agent metadata during remote create', async () => { const repo = { id: 'repo-ssh', diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 1ac4e4821..0d9af0c99 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -21,6 +21,7 @@ import { } from '../git/worktree' import { gitExecFileAsync } from '../git/runner' import { getDefaultRemote } from '../git/repo' +import { isMissingRemoteRefGitError } from '../git/fetch-error-classification' import { getPullRequestPushTarget, getWorkItem } from '../github/client' import { getProjectRef as getGlabProjectRef, getGlabKnownHosts } from '../gitlab/gl-utils' import { getWorkItemByProjectRef as getGitLabWorkItemByProjectRef } from '../gitlab/client' @@ -470,15 +471,12 @@ export function registerWorktreeHandlers( (await getPullRequestPushTarget(repo.path, args.prNumber, repo.connectionId ?? null)) ?? undefined } catch (error) { - return { - error: - error instanceof Error - ? error.message - : `Could not resolve PR #${args.prNumber} head push target.` - } - } - if (!pushTarget) { - return { error: `Could not resolve PR #${args.prNumber} head push target.` } + // Why: a missing/unreadable fork head repo should not block creating + // a workspace from the PR commit; we can still fetch refs/pull//head. + console.warn( + `[worktrees:resolvePrBase] Could not resolve PR #${args.prNumber} head push target.`, + error + ) } } @@ -505,7 +503,9 @@ export function registerWorktreeHandlers( // derived from the workspace name, so there's no tracking ref to set // up, which makes SHA semantics ("branch from this commit") cleaner // than returning a ref that would go stale on force-push. - if (isCrossRepository) { + const resolvePullHeadBase = async (): Promise< + { baseBranch: string; pushTarget?: CreateWorktreeArgs['pushTarget'] } | { error: string } + > => { const pullRef = `refs/pull/${args.prNumber}/head` try { await gitExec(['fetch', remote, pullRef]) @@ -528,6 +528,10 @@ export function registerWorktreeHandlers( return { baseBranch: sha, ...(pushTarget ? { pushTarget } : {}) } } + if (isCrossRepository) { + return await resolvePullHeadBase() + } + try { await gitExec([ 'fetch', @@ -536,6 +540,16 @@ export function registerWorktreeHandlers( ]) } catch (error) { const message = error instanceof Error ? error.message : String(error) + // Why: some PR payloads omit fork metadata (e.g. deleted head repo), + // so we may misclassify a fork as same-repo. Falling back to + // refs/pull//head still resolves the PR commit in that case, but + // auth/network failures should not pay for another fetch. + if (isMissingRemoteRefGitError(error)) { + const fallback = await resolvePullHeadBase() + if (!('error' in fallback)) { + return fallback + } + } return { error: `Failed to fetch ${remote}/${headRefName}: ${message.split('\n')[0]}` } diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index a844d97d3..b98a0bd83 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -8,6 +8,7 @@ import { } from '../../shared/agent-detection' import type { AgentStatus } from '../../shared/agent-detection' import { gitExecFileAsync, wslAwareSpawn } from '../git/runner' +import { isMissingRemoteRefGitError } from '../git/fetch-error-classification' import { isWslPath, parseWslPath, getWslHome } from '../wsl' import { randomUUID } from 'crypto' import { basename, isAbsolute, join } from 'path' @@ -6237,15 +6238,12 @@ export class OrcaRuntimeService { try { pushTarget = (await getPullRequestPushTarget(repo.path, args.prNumber)) ?? undefined } catch (error) { - return { - error: - error instanceof Error - ? error.message - : `Could not resolve PR #${args.prNumber} head push target.` - } - } - if (!pushTarget) { - return { error: `Could not resolve PR #${args.prNumber} head push target.` } + // Why: missing fork metadata can block push-target discovery, but we + // can still create from refs/pull//head. + console.warn( + `[runtime.resolveManagedPrBase] Could not resolve PR #${args.prNumber} head push target.`, + error + ) } } @@ -6256,7 +6254,9 @@ export class OrcaRuntimeService { return { error: error instanceof Error ? error.message : 'Could not resolve git remote.' } } - if (isCrossRepository) { + const resolvePullHeadBase = async (): Promise< + { baseBranch: string; pushTarget?: GitPushTarget } | { error: string } + > => { const pullRef = `refs/pull/${args.prNumber}/head` try { await gitExecFileAsync(['fetch', remote, pullRef], { cwd: repo.path }) @@ -6278,6 +6278,10 @@ export class OrcaRuntimeService { } } + if (isCrossRepository) { + return await resolvePullHeadBase() + } + try { await gitExecFileAsync( ['fetch', remote, `+refs/heads/${headRefName}:refs/remotes/${remote}/${headRefName}`], @@ -6285,6 +6289,15 @@ export class OrcaRuntimeService { ) } catch (error) { const message = error instanceof Error ? error.message : String(error) + // Why: if cross-repo metadata is missing (e.g. deleted head repo), + // a branch fetch can fail even though refs/pull//head exists. Keep + // network/auth failures on the original error path to avoid extra fetches. + if (isMissingRemoteRefGitError(error)) { + const fallback = await resolvePullHeadBase() + if (!('error' in fallback)) { + return fallback + } + } return { error: `Failed to fetch ${remote}/${headRefName}: ${message.split('\n')[0]}` } }