diff --git a/src/cli/runtime/transport.test.ts b/src/cli/runtime/transport.test.ts index cd9f369aa..732ef3e0e 100644 --- a/src/cli/runtime/transport.test.ts +++ b/src/cli/runtime/transport.test.ts @@ -42,9 +42,11 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => { }) socket.once('data', (data) => { const request = JSON.parse(String(data).trim()) as { id: string } + // Why: full-suite load can delay short timers; keep the response past + // the client timeout while leaving enough margin between keepalives. keepalive = setInterval(() => { socket.write('{"_keepalive":true}\n') - }, 15) + }, 50) setTimeout(() => { if (keepalive) { clearInterval(keepalive) @@ -58,7 +60,7 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => { _meta: { runtimeId: 'runtime-1' } })}\n` ) - }, 90) + }, 500) }) }) servers.add(server) @@ -75,7 +77,7 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => { metadata, 'terminal.wait', undefined, - 40 + 200 ) expect(response).toMatchObject({ diff --git a/src/main/github/pr-start-point.test.ts b/src/main/github/pr-start-point.test.ts new file mode 100644 index 000000000..d4c8dfe98 --- /dev/null +++ b/src/main/github/pr-start-point.test.ts @@ -0,0 +1,166 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { getPullRequestPushTargetMock, getWorkItemMock } = vi.hoisted(() => ({ + getPullRequestPushTargetMock: vi.fn(), + getWorkItemMock: vi.fn() +})) + +vi.mock('./client', () => ({ + getPullRequestPushTarget: getPullRequestPushTargetMock, + getWorkItem: getWorkItemMock +})) + +import { resolveGitHubPrStartPoint } from './pr-start-point' + +describe('resolveGitHubPrStartPoint', () => { + beforeEach(() => { + getPullRequestPushTargetMock.mockReset() + getWorkItemMock.mockReset() + }) + + it('falls back to the GitHub PR head ref when a direct branch fetch fails', async () => { + getPullRequestPushTargetMock.mockResolvedValue({ + remoteName: 'pr-contributor-orca', + branchName: 'feat/onboarding-model-choice-782', + remoteUrl: 'git@github.com:contributor/orca.git' + }) + const gitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'fetch' && String(args[2]).startsWith('+refs/heads/')) { + throw new Error('fatal: could not find remote ref') + } + if (args[0] === 'rev-parse') { + return { stdout: 'def456\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 1849, + headRefName: 'feat/onboarding-model-choice-782', + gitExec, + resolveRemote: async () => 'origin' + }) + + expect(gitExec).toHaveBeenCalledWith([ + 'fetch', + 'origin', + '+refs/heads/feat/onboarding-model-choice-782:refs/remotes/origin/feat/onboarding-model-choice-782' + ]) + expect(gitExec).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head']) + expect(result).toEqual({ + baseBranch: 'def456', + pushTarget: { + remoteName: 'pr-contributor-orca', + branchName: 'feat/onboarding-model-choice-782', + remoteUrl: 'git@github.com:contributor/orca.git' + } + }) + }) + + it('keeps the PR head ref fallback when push-target discovery also fails', async () => { + getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable')) + const gitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'fetch' && String(args[2]).startsWith('+refs/heads/')) { + throw new Error('fatal: could not find remote ref') + } + if (args[0] === 'rev-parse') { + return { stdout: 'def456\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 1849, + headRefName: 'feat/onboarding-model-choice-782', + gitExec, + resolveRemote: async () => 'origin' + }) + + expect(getPullRequestPushTargetMock).toHaveBeenCalledWith('/repo-root', 1849, null) + expect(result).toEqual({ baseBranch: 'def456' }) + }) + + it('resolves an inaccessible fork PR even when push-target discovery fails', async () => { + getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable')) + const gitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'rev-parse') { + return { stdout: 'abc123\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 1849, + headRefName: 'feat/onboarding-model-choice-782', + isCrossRepository: true, + gitExec, + resolveRemote: async () => 'origin' + }) + + expect(getPullRequestPushTargetMock).toHaveBeenCalledWith('/repo-root', 1849, null) + expect(gitExec).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head']) + expect(result).toEqual({ baseBranch: 'abc123' }) + }) + + it('uses PR metadata when the caller did not pass a head ref', async () => { + getWorkItemMock.mockResolvedValue({ + type: 'pr', + branchName: 'contributor/fix', + isCrossRepository: true + }) + getPullRequestPushTargetMock.mockResolvedValue({ + remoteName: 'pr-contributor-orca', + branchName: 'contributor/fix', + remoteUrl: 'git@github.com:contributor/orca.git' + }) + const gitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'rev-parse') { + return { stdout: 'abc123\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 1738, + gitExec, + resolveRemote: async () => 'origin' + }) + + expect(getWorkItemMock).toHaveBeenCalledWith('/repo-root', 1738, 'pr', null) + expect(result).toEqual({ + baseBranch: 'abc123', + pushTarget: { + remoteName: 'pr-contributor-orca', + branchName: 'contributor/fix', + remoteUrl: 'git@github.com:contributor/orca.git' + } + }) + }) + + it('returns a tracking ref and push target when same-repo branch fetch succeeds', async () => { + const gitExec = vi.fn(async () => ({ stdout: '', stderr: '' })) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 42, + headRefName: 'feature/add-feature', + gitExec, + resolveRemote: async () => 'origin' + }) + + expect(gitExec).toHaveBeenCalledWith([ + 'fetch', + 'origin', + '+refs/heads/feature/add-feature:refs/remotes/origin/feature/add-feature' + ]) + expect(gitExec).toHaveBeenCalledWith(['rev-parse', '--verify', 'origin/feature/add-feature']) + expect(result).toEqual({ + baseBranch: 'origin/feature/add-feature', + pushTarget: { remoteName: 'origin', branchName: 'feature/add-feature' } + }) + }) +}) diff --git a/src/main/github/pr-start-point.ts b/src/main/github/pr-start-point.ts new file mode 100644 index 000000000..16ba1a3e7 --- /dev/null +++ b/src/main/github/pr-start-point.ts @@ -0,0 +1,135 @@ +import type { GitPushTarget } from '../../shared/types' +import { isMissingRemoteRefGitError } from '../git/fetch-error-classification' +import { getPullRequestPushTarget, getWorkItem } from './client' + +type GitExec = (args: string[]) => Promise<{ stdout: string; stderr: string }> + +type ResolveGitHubPrStartPointArgs = { + repoPath: string + prNumber: number + headRefName?: string + isCrossRepository?: boolean + connectionId?: string | null + gitExec: GitExec + resolveRemote: () => Promise +} + +type ResolveGitHubPrStartPointResult = + | { baseBranch: string; pushTarget?: GitPushTarget } + | { error: string } + +export async function resolveGitHubPrStartPoint( + args: ResolveGitHubPrStartPointArgs +): Promise { + let headRefName = args.headRefName?.trim() ?? '' + let isCrossRepository = args.isCrossRepository === true + let pushTarget: GitPushTarget | undefined + + const resolvePushTarget = async (): Promise => { + if (pushTarget) { + return + } + try { + pushTarget = + (await getPullRequestPushTarget(args.repoPath, args.prNumber, args.connectionId ?? null)) ?? + undefined + } catch { + // Why: deleted/inaccessible fork metadata can prevent push-target + // discovery, but GitHub still exposes the PR head ref for checkout. + pushTarget = undefined + } + } + + if (!headRefName) { + const item = await getWorkItem(args.repoPath, args.prNumber, 'pr', args.connectionId ?? null) + if (!item || item.type !== 'pr') { + return { error: `PR #${args.prNumber} not found.` } + } + headRefName = (item.branchName ?? '').trim() + if (!headRefName) { + return { error: `PR #${args.prNumber} has no head branch.` } + } + if (item.isCrossRepository === true) { + isCrossRepository = true + } + } + + if (isCrossRepository) { + await resolvePushTarget() + } + + let remote: string + try { + remote = await args.resolveRemote() + } catch (error) { + return { error: error instanceof Error ? error.message : 'Could not resolve git remote.' } + } + + const fetchPullRequestHeadSha = async (): Promise<{ baseBranch: string } | { error: string }> => { + const pullRef = `refs/pull/${args.prNumber}/head` + try { + await args.gitExec(['fetch', remote, pullRef]) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return { + error: `Failed to fetch ${pullRef}: ${message.split('\n')[0]}` + } + } + let sha: string + try { + const { stdout } = await args.gitExec(['rev-parse', '--verify', 'FETCH_HEAD']) + sha = stdout.trim() + } catch { + return { error: `Could not resolve fork PR #${args.prNumber} head after fetch.` } + } + if (!sha) { + return { error: `Empty SHA resolving fork PR #${args.prNumber} head.` } + } + return { baseBranch: sha } + } + + // Why: fork PR heads live on a remote we don't have configured, so + // `git fetch ` would fail. GitHub exposes every + // PR head (fork or same-repo) as refs/pull//head on the upstream repo. + if (isCrossRepository) { + const result = await fetchPullRequestHeadSha() + if ('error' in result) { + return result + } + return { ...result, ...(pushTarget ? { pushTarget } : {}) } + } + + try { + await args.gitExec([ + 'fetch', + remote, + `+refs/heads/${headRefName}:refs/remotes/${remote}/${headRefName}` + ]) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + // Why: missing fork metadata can make a fork PR look like a same-repo + // branch. Only that missing-ref case should fall back to refs/pull. + if (isMissingRemoteRefGitError(error)) { + const result = await fetchPullRequestHeadSha() + if (!('error' in result)) { + await resolvePushTarget() + return { ...result, ...(pushTarget ? { pushTarget } : {}) } + } + } + return { + error: `Failed to fetch ${remote}/${headRefName}: ${message.split('\n')[0]}` + } + } + + const remoteRef = `${remote}/${headRefName}` + try { + await args.gitExec(['rev-parse', '--verify', remoteRef]) + } catch { + return { error: `Remote ref ${remoteRef} does not exist after fetch.` } + } + + return { + baseBranch: remoteRef, + pushTarget: { remoteName: remote, branchName: headRefName } + } +} diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 0d9af0c99..5148956f7 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -21,8 +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 { resolveGitHubPrStartPoint } from '../github/pr-start-point' import { getProjectRef as getGlabProjectRef, getGlabKnownHosts } from '../gitlab/gl-utils' import { getWorkItemByProjectRef as getGitLabWorkItemByProjectRef } from '../gitlab/client' import { listRepoWorktrees, createFolderWorktree } from '../repo-worktrees' @@ -444,128 +443,26 @@ export function registerWorktreeHandlers( return provider.exec(args, repo.path) } - let headRefName = args.headRefName?.trim() ?? '' - let isCrossRepository = args.isCrossRepository === true - let pushTarget: CreateWorktreeArgs['pushTarget'] | undefined - - // Skip the gh lookup when both hints are present (picker already has them). - if (!headRefName) { - // Why: the caller already knows this is a PR number, so scope the - // lookup to `type: 'pr'` and skip the speculative issue-first probe - // that would hit the upstream issue tracker for fork checkouts. - const item = await getWorkItem(repo.path, args.prNumber, 'pr', repo.connectionId ?? null) - if (!item || item.type !== 'pr') { - return { error: `PR #${args.prNumber} not found.` } - } - headRefName = (item.branchName ?? '').trim() - if (!headRefName) { - return { error: `PR #${args.prNumber} has no head branch.` } - } - if (item.isCrossRepository === true) { - isCrossRepository = true - } - } - if (isCrossRepository) { - try { - pushTarget = - (await getPullRequestPushTarget(repo.path, args.prNumber, repo.connectionId ?? null)) ?? - undefined - } catch (error) { - // 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 - ) - } - } - - let remote: string - try { - if (repo.connectionId) { - const { stdout } = await gitExec(['remote']) - remote = - stdout - .split('\n') - .map((line) => line.trim()) - .find(Boolean) ?? 'origin' - } else { - remote = await getDefaultRemote(repo.path) - } - } catch (error) { - return { error: error instanceof Error ? error.message : 'Could not resolve git remote.' } - } - - // Why: fork PR heads live on a remote we don't have configured, so - // `git fetch ` would fail. GitHub exposes every - // PR head (fork or same-repo) as refs/pull//head on the upstream - // repo. Fetch that and snapshot the SHA — the new worktree branch is - // 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. - const resolvePullHeadBase = async (): Promise< - { baseBranch: string; pushTarget?: CreateWorktreeArgs['pushTarget'] } | { error: string } - > => { - const pullRef = `refs/pull/${args.prNumber}/head` - try { - await gitExec(['fetch', remote, pullRef]) - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - return { - error: `Failed to fetch ${pullRef}: ${message.split('\n')[0]}` + return resolveGitHubPrStartPoint({ + repoPath: repo.path, + prNumber: args.prNumber, + headRefName: args.headRefName, + isCrossRepository: args.isCrossRepository, + connectionId: repo.connectionId ?? null, + gitExec, + resolveRemote: async () => { + if (repo.connectionId) { + const { stdout } = await gitExec(['remote']) + return ( + stdout + .split('\n') + .map((line) => line.trim()) + .find(Boolean) ?? 'origin' + ) } + return getDefaultRemote(repo.path) } - let sha: string - try { - const { stdout } = await gitExec(['rev-parse', '--verify', 'FETCH_HEAD']) - sha = stdout.trim() - } catch { - return { error: `Could not resolve fork PR #${args.prNumber} head after fetch.` } - } - if (!sha) { - return { error: `Empty SHA resolving fork PR #${args.prNumber} head.` } - } - return { baseBranch: sha, ...(pushTarget ? { pushTarget } : {}) } - } - - if (isCrossRepository) { - return await resolvePullHeadBase() - } - - try { - await gitExec([ - 'fetch', - remote, - `+refs/heads/${headRefName}:refs/remotes/${remote}/${headRefName}` - ]) - } 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]}` - } - } - - const remoteRef = `${remote}/${headRefName}` - try { - await gitExec(['rev-parse', '--verify', remoteRef]) - } catch { - return { error: `Remote ref ${remoteRef} does not exist after fetch.` } - } - - if (!pushTarget) { - pushTarget = { remoteName: remote, branchName: headRefName } - } - return { baseBranch: remoteRef, pushTarget } + }) } ) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index b98a0bd83..2631ca36b 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -8,7 +8,6 @@ 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' @@ -97,7 +96,6 @@ import type { AgentBrowserBridge } from '../browser/agent-browser-bridge' import { BrowserError } from '../browser/cdp-bridge' import { getPRForBranch, - getPullRequestPushTarget, getRepoSlug, getWorkItem, listWorkItems, @@ -121,6 +119,7 @@ import { listLabels, listAssignableUsers } from '../github/client' +import { resolveGitHubPrStartPoint } from '../github/pr-start-point' import { getWorkItemDetails, getPRFileContents } from '../github/work-item-details' import { getRateLimit } from '../github/rate-limit' import type { @@ -6216,102 +6215,14 @@ export class OrcaRuntimeService { return { error: 'Folder mode does not support creating worktrees.' } } - let headRefName = args.headRefName?.trim() ?? '' - let isCrossRepository = args.isCrossRepository === true - let pushTarget: GitPushTarget | undefined - - if (!headRefName) { - const item = await getWorkItem(repo.path, args.prNumber, 'pr') - if (!item || item.type !== 'pr') { - return { error: `PR #${args.prNumber} not found.` } - } - headRefName = (item.branchName ?? '').trim() - if (!headRefName) { - return { error: `PR #${args.prNumber} has no head branch.` } - } - if (item.isCrossRepository === true) { - isCrossRepository = true - } - } - - if (isCrossRepository) { - try { - pushTarget = (await getPullRequestPushTarget(repo.path, args.prNumber)) ?? undefined - } catch (error) { - // 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 - ) - } - } - - let remote: string - try { - remote = await getDefaultRemote(repo.path) - } catch (error) { - return { error: error instanceof Error ? error.message : 'Could not resolve git remote.' } - } - - 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 }) - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - return { error: `Failed to fetch ${pullRef}: ${message.split('\n')[0]}` } - } - try { - const { stdout } = await gitExecFileAsync(['rev-parse', '--verify', 'FETCH_HEAD'], { - cwd: repo.path - }) - const sha = stdout.trim() - if (!sha) { - return { error: `Empty SHA resolving fork PR #${args.prNumber} head.` } - } - return { baseBranch: sha, ...(pushTarget ? { pushTarget } : {}) } - } catch { - return { error: `Could not resolve fork PR #${args.prNumber} head after fetch.` } - } - } - - if (isCrossRepository) { - return await resolvePullHeadBase() - } - - try { - await gitExecFileAsync( - ['fetch', remote, `+refs/heads/${headRefName}:refs/remotes/${remote}/${headRefName}`], - { cwd: repo.path } - ) - } 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]}` } - } - - const remoteRef = `${remote}/${headRefName}` - try { - await gitExecFileAsync(['rev-parse', '--verify', remoteRef], { cwd: repo.path }) - } catch { - return { error: `Remote ref ${remoteRef} does not exist after fetch.` } - } - - return { - baseBranch: remoteRef, - pushTarget: pushTarget ?? { remoteName: remote, branchName: headRefName } - } + return resolveGitHubPrStartPoint({ + repoPath: repo.path, + prNumber: args.prNumber, + headRefName: args.headRefName, + isCrossRepository: args.isCrossRepository, + gitExec: (gitArgs) => gitExecFileAsync(gitArgs, { cwd: repo.path }), + resolveRemote: () => getDefaultRemote(repo.path) + }) } async removeManagedWorktree( diff --git a/src/renderer/src/lib/ensure-hooks-confirmed.test.ts b/src/renderer/src/lib/ensure-hooks-confirmed.test.ts index 8c3653beb..cf2546f18 100644 --- a/src/renderer/src/lib/ensure-hooks-confirmed.test.ts +++ b/src/renderer/src/lib/ensure-hooks-confirmed.test.ts @@ -41,11 +41,6 @@ function createTestState(overrides?: Partial): { return { state, pending } } -async function flush(): Promise { - await new Promise((resolve) => setTimeout(resolve, 0)) - await new Promise((resolve) => setTimeout(resolve, 0)) -} - describe('ensureHooksConfirmed', () => { beforeEach(() => { hooksCheckMock.mockReset() @@ -86,9 +81,8 @@ describe('ensureHooksConfirmed', () => { }) const promise = ensureHooksConfirmed(state, 'repo-1', 'setup') - await flush() - expect(pending).toHaveLength(1) + await vi.waitFor(() => expect(pending).toHaveLength(1)) expect(pending[0].data.scriptContent).toBe('new script') // The dialog uses this flag to tell the user we're re-prompting *because* // orca.yaml changed, not because they've never approved this hook. @@ -151,9 +145,8 @@ describe('ensureHooksConfirmed', () => { }) const promise = ensureHooksConfirmed(state, 'repo-1', 'setup') - await flush() - expect(pending).toHaveLength(1) + await vi.waitFor(() => expect(pending).toHaveLength(1)) expect(pending[0].data).toMatchObject({ repoId: 'repo-1', repoName: 'Repo One',