From 772081577ed0ed0fbcd1c1c381c4390db7117b5b Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Fri, 24 Jul 2026 12:53:18 -0700 Subject: [PATCH] Fix fork PR/MR worktree creation race via durable review-head refs (#10429) * Fix fork PR/MR worktree creation race via durable review-head refs When creating a fork PR/MR worktree, concurrent `git fetch origin` operations clobber the shared FETCH_HEAD, causing the wrong commit to be checked out. Fetch PR/MR heads into dedicated per-review refs (`refs/orca/pull/`, `refs/orca/merge-requests/`) that persist and isolate each head from other fetches. Gracefully keep the compare-base when the fetch fails but the local ref already exists, avoiding silent fallback to the wrong branch on transient network errors. * Bound PR/MR head fetches with 60s timeout Prevent PR/MR creation from hanging when a remote is stalled or unreachable. Both GitHub and GitLab head fetches now enforce a 60-second timeout, matching the bound used in the create-path fetch. Durable refs (refs/orca/pull/*, refs/orca/merge-requests/*) decouple the ref from FETCH_HEAD, preserving legacy client semantics. * test: align CI expectations with main PowerShell/sparse regressions PR checks merge into main, which recently changed PowerShell launch args (cwd restore after profiles) and sparse-checkout detection (require core.sparseCheckout). Derive PowerShell spawn args from the production resolver, mock the sparse config flag, reset shared worktree list scan cache between tests, and stop requiring floating polls to avoid getRepos hydration. * Address review follow-ups on durable review-head refs - Unify PR review-head remote selection: local and SSH GitHub paths share resolveGitHubReviewHeadRemote, which prefers the remote mapping to the hosting GitHub project (upstream before origin, matching work-item/API candidate order) so contributor clones fetch refs/pull from the repo that actually hosts the PR. - Soft-keep durable review heads: when the PR/MR head fetch fails but refs/orca/pull/ / refs/orca/merge-requests/ still resolves, keep the pinned SHA (warn) instead of failing resolve, mirroring the compare-base fallback. Extracted shared compare-base soft-keep into compare-base-ref-fetch.ts. - Extract fetchGitLabMergeRequestHeadRef (local + SSH) parallel to the GitHub helper; bound its local fetch with the shared 60s timeout. - Share relay-style fetch validation (positive safe-integer id, remote not starting with "-") between relay and local helpers via review-head-tracking-ref.ts; move REVIEW_HEAD_FETCH_TIMEOUT_MS there. - Drop the githubPullRequestHeadLocalRef re-export; resolve head SHAs via rev-parse --verify ^{commit}. - Add GitLab anti-FETCH_HEAD regression test plus durable-head soft-keep and remote-selection unit tests. Co-authored-by: Orca * test: supply live getRepos for terminal-retirement hydrates Main's headless tab hydrate (#9343) skips worktree keys whose repo is not in getRepos. Retirement tests that rebuild mobile tabs from a persisted session now advertise the fixture repo as live so PR Checks merge stays green. * fix(editor): extract RichMarkdownEditor props to stay under max-lines Main's SSH external-image wiring (#10323) pushed RichMarkdownEditor.tsx over the 400-line tsx budget, failing PR Checks lint on every merge into main. Move the props type into a sibling module so the component stays under the limit without disabling max-lines. * Make durable review-head refs remote-identity scoped Embed remote name + URL hash into refs/orca/pull|merge-requests refs to prevent soft-keep from serving wrong project's PR/MR when FETCH_HEAD is clobbered by concurrent fetch. Fetch functions now return the written ref path (writer-authoritative) so callers rev-parse exactly what was fetched, not re-derive identity. Soft-keep only applies to transient errors (timeout, network); fails hard on missing refs, auth failures, and stale relay. Relay returns localRef so client avoids re-hashing (URL normalization can disagree). --------- Co-authored-by: Orca --- src/main/git/compare-base-ref-fetch.ts | 54 +++ .../git/fetch-error-classification.test.ts | 48 +- src/main/git/fetch-error-classification.ts | 35 ++ src/main/git/remove-worktree.test.ts | 37 +- src/main/git/review-head-remote-identity.ts | 26 + src/main/github/pr-head-tracking-ref.test.ts | 104 +++- src/main/github/pr-head-tracking-ref.ts | 40 ++ .../pr-start-point-compare-base.test.ts | 171 +++++++ src/main/github/pr-start-point.test.ts | 251 +++++++++- src/main/github/pr-start-point.ts | 126 +++-- src/main/github/review-head-remote.test.ts | 102 ++++ src/main/github/review-head-remote.ts | 47 ++ src/main/gitlab/mr-head-tracking-ref.test.ts | 130 +++++ src/main/gitlab/mr-head-tracking-ref.ts | 51 ++ src/main/ipc/pty.test.ts | 19 +- src/main/ipc/worktrees.test.ts | 147 +++++- src/main/ipc/worktrees.ts | 39 +- src/main/providers/ssh-git-provider.test.ts | 78 ++- src/main/providers/ssh-git-provider.ts | 78 ++- .../orca-runtime-terminal-retirement.test.ts | 113 +++-- src/main/runtime/orca-runtime.test.ts | 459 +++++++++++++++++- src/main/runtime/orca-runtime.ts | 180 ++++--- src/relay/git-handler.test.ts | 108 ++++- src/relay/git-handler.ts | 108 ++++- .../components/editor/RichMarkdownEditor.tsx | 28 +- .../editor/rich-markdown-editor-props.ts | 27 ++ src/shared/git-binary-compatibility.test.ts | 28 ++ src/shared/git-remote-error.ts | 10 + src/shared/preferred-git-remote.test.ts | 26 + src/shared/preferred-git-remote.ts | 16 + src/shared/review-head-tracking-ref.test.ts | 39 ++ src/shared/review-head-tracking-ref.ts | 49 ++ 32 files changed, 2509 insertions(+), 265 deletions(-) create mode 100644 src/main/git/compare-base-ref-fetch.ts create mode 100644 src/main/git/review-head-remote-identity.ts create mode 100644 src/main/github/pr-start-point-compare-base.test.ts create mode 100644 src/main/github/review-head-remote.test.ts create mode 100644 src/main/github/review-head-remote.ts create mode 100644 src/main/gitlab/mr-head-tracking-ref.test.ts create mode 100644 src/main/gitlab/mr-head-tracking-ref.ts create mode 100644 src/renderer/src/components/editor/rich-markdown-editor-props.ts create mode 100644 src/shared/preferred-git-remote.test.ts create mode 100644 src/shared/preferred-git-remote.ts create mode 100644 src/shared/review-head-tracking-ref.test.ts create mode 100644 src/shared/review-head-tracking-ref.ts diff --git a/src/main/git/compare-base-ref-fetch.ts b/src/main/git/compare-base-ref-fetch.ts new file mode 100644 index 000000000..31b9482cb --- /dev/null +++ b/src/main/git/compare-base-ref-fetch.ts @@ -0,0 +1,54 @@ +// Why: PR (GitHub) and MR (GitLab) base resolution both need this exact +// trade-off, and both regressed the same way before; one copy keeps them from +// drifting on the next fix. + +type CompareBaseGitExec = (args: string[]) => Promise<{ stdout: string }> + +/** + * Refresh the compare base ref, reporting whether callers may keep it. + * + * Why: dropping compareBaseRef on any fetch failure makes worktree create fall + * back to the base branch — the review head itself for fork reviews — so Source + * Control diffs the worktree against itself. Keep the base whenever the local + * ref still resolves; only truly missing/absent refs lose it. + */ +export async function fetchCompareBaseRefWithLocalFallback(options: { + compareBaseRef: string | undefined + fetchCompareBaseRef: (compareBaseRef: string) => Promise + gitExec: CompareBaseGitExec + /** Log prefix identifying the calling resolver, e.g. `[github:resolvePrStartPoint]`. */ + logLabel: string + /** Resolver-specific fields (remote, branch, review id) merged into the warning. */ + logContext: Record +}): Promise { + if (!options.compareBaseRef) { + return false + } + try { + await options.fetchCompareBaseRef(options.compareBaseRef) + return true + } catch (error) { + const localBaseResolved = await compareBaseRefResolvesLocally( + options.gitExec, + options.compareBaseRef + ) + console.warn(`${options.logLabel} optional compare-base fetch failed`, { + ...options.logContext, + localBaseResolved, + error: error instanceof Error ? error.message.split('\n')[0] : String(error) + }) + return localBaseResolved + } +} + +async function compareBaseRefResolvesLocally( + gitExec: CompareBaseGitExec, + compareBaseRef: string +): Promise { + try { + const { stdout } = await gitExec(['rev-parse', '--verify', `${compareBaseRef}^{commit}`]) + return stdout.trim().length > 0 + } catch { + return false + } +} diff --git a/src/main/git/fetch-error-classification.test.ts b/src/main/git/fetch-error-classification.test.ts index a7ce57586..8f5b5de45 100644 --- a/src/main/git/fetch-error-classification.test.ts +++ b/src/main/git/fetch-error-classification.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest' -import { isMissingRemoteRefGitError } from './fetch-error-classification' +import { + isMissingRemoteRefGitError, + isTransientReviewHeadFetchError +} from './fetch-error-classification' describe('isMissingRemoteRefGitError', () => { it('matches missing remote ref messages', () => { @@ -22,3 +25,46 @@ describe('isMissingRemoteRefGitError', () => { ).toBe(false) }) }) + +describe('isTransientReviewHeadFetchError', () => { + it('classifies transport failures as transient', () => { + const transient = [ + 'fatal: unable to access repo: Could not resolve host: github.com', + 'Network error. Check your connection.', + 'fatal: unable to access repo: Connection refused', + 'error: RPC failed; curl 56 Recv failure: Connection reset by peer', + 'fetch-pack: unexpected disconnect while reading sideband packet: early EOF', + 'fatal: the remote end hung up unexpectedly', + 'Fetching refs/pull/42/head from "origin" timed out.', + 'fatal: unable to access repo: The requested URL returned error: 502' + ] + for (const message of transient) { + expect(isTransientReviewHeadFetchError(new Error(message)), message).toBe(true) + } + }) + + it('classifies an exec-timeout kill as transient without a message match', () => { + const killed = Object.assign(new Error('Command failed: git fetch --no-tags origin'), { + killed: true, + signal: 'SIGTERM' + }) + expect(isTransientReviewHeadFetchError(killed)).toBe(true) + }) + + it('fails hard on missing-ref, auth, protocol, and stale-relay errors', () => { + const fatal = [ + "fatal: couldn't find remote ref refs/pull/42/head", + 'fatal: could not find remote ref refs/merge-requests/42/head', + 'Authentication failed. Check your remote credentials.', + 'fatal: could not read Username for https://github.com', + 'remote: Repository not found.', + 'fatal: unable to access repo: The requested URL returned error: 403', + 'This SSH host is running an older Orca relay that cannot fetch pull request heads. Reconnect to deploy the latest relay, then try again.', + 'Remote "origin" is not configured.', + 'fatal: invalid refspec' + ] + for (const message of fatal) { + expect(isTransientReviewHeadFetchError(new Error(message)), message).toBe(false) + } + }) +}) diff --git a/src/main/git/fetch-error-classification.ts b/src/main/git/fetch-error-classification.ts index 907b92e59..0ee193bb2 100644 --- a/src/main/git/fetch-error-classification.ts +++ b/src/main/git/fetch-error-classification.ts @@ -1,3 +1,5 @@ +import { isExecKilledError } from '../../shared/git-remote-error' + export function isMissingRemoteRefGitError(error: unknown): boolean { const message = error instanceof Error ? error.message : String(error) const normalized = message.toLowerCase() @@ -6,3 +8,36 @@ export function isMissingRemoteRefGitError(error: unknown): boolean { normalized.includes("couldn't find remote ref") ) } + +// Why: allowlist, not blocklist — soft-keeping a durable review-head ref is +// only safe when the fetch plainly died in transport. A deleted PR head, auth +// failure, or stale-relay method-not-found must surface, or the caller checks +// out a dead/unauthorized tip. Covers raw git stderr and the relay's +// normalized messages ("Network error. Check your connection.", "… timed out"). +const TRANSIENT_FETCH_ERROR_PATTERNS = [ + 'timed out', + 'timeout', + 'operation was aborted', + 'network error', + 'network is unreachable', + 'could not resolve host', + 'temporary failure in name resolution', + 'connection refused', + 'connection reset', + 'connection closed', + 'early eof', + 'remote end hung up', + 'the requested url returned error: 5' +] + +export function isTransientReviewHeadFetchError(error: unknown): boolean { + if (isMissingRemoteRefGitError(error)) { + return false + } + if (isExecKilledError(error)) { + return true + } + const message = error instanceof Error ? error.message : String(error) + const normalized = message.toLowerCase() + return TRANSIENT_FETCH_ERROR_PATTERNS.some((pattern) => normalized.includes(pattern)) +} diff --git a/src/main/git/remove-worktree.test.ts b/src/main/git/remove-worktree.test.ts index 5e4bf9929..7a9bda07f 100644 --- a/src/main/git/remove-worktree.test.ts +++ b/src/main/git/remove-worktree.test.ts @@ -8,12 +8,14 @@ const { gitExecFileSyncMock, translateWslOutputPathsMock, statMock, + readFileMock, resolveGitDirMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn(), gitExecFileSyncMock: vi.fn(), translateWslOutputPathsMock: vi.fn((output: string) => output), statMock: vi.fn(), + readFileMock: vi.fn(), resolveGitDirMock: vi.fn() })) @@ -30,7 +32,7 @@ vi.mock('./status', () => ({ vi.mock('fs/promises', async () => { const actual = await vi.importActual('fs/promises') - return { ...actual, stat: statMock } + return { ...actual, stat: statMock, readFile: readFileMock } }) import { clearGitCapabilityStateForTests } from './git-capability-state' @@ -41,12 +43,20 @@ import { forceDeleteLocalBranch, listWorktrees, removeWorktree, + _resetWorktreeScanCacheForTests, WORKTREE_LIST_TIMEOUT_MS, WORKTREE_REMOVAL_PREFLIGHT_TIMEOUT_MS } from './worktree' +// Why: detectSparseCheckout on main also requires core.sparseCheckout=true in git +// config (not just a non-empty pattern file). Unit tests that assert isSparse must +// present an enabled flag; other paths never reach this read after the pattern-file +// fast-path ENOENT. +const ENABLED_SPARSE_CHECKOUT_CONFIG = '[core]\nsparseCheckout = true\n' + beforeEach(() => { clearGitCapabilityStateForTests() + _resetWorktreeScanCacheForTests() }) type MockResult = { @@ -94,6 +104,21 @@ function expectGitCallOrder(calls: string[], beforeCall: string, afterCall: stri expect(calls.indexOf(afterCall)).toBeGreaterThan(calls.indexOf(beforeCall)) } +function mockSparseCheckoutEnabledConfig(): void { + readFileMock.mockImplementation(async (filePath: string) => { + const normalized = String(filePath).replaceAll('\\', '/') + // Why: linked worktrees may point at a common dir; treat missing commondir as + // "this gitdir is the common dir" so the shared config read still runs. + if (normalized.endsWith('/commondir')) { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + } + if (normalized.endsWith('/config') || normalized.endsWith('/config.worktree')) { + return ENABLED_SPARSE_CHECKOUT_CONFIG + } + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + }) +} + describe('removeWorktree', () => { beforeEach(() => { gitExecFileAsyncMock.mockReset() @@ -104,6 +129,8 @@ describe('removeWorktree', () => { // Default: no worktree has a sparse-checkout config file. Tests that need // sparse detection override this. statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })) + readFileMock.mockReset() + mockSparseCheckoutEnabledConfig() resolveGitDirMock.mockReset() resolveGitDirMock.mockImplementation(async (worktreePath: string) => `${worktreePath}/.git`) }) @@ -939,6 +966,8 @@ describe('listWorktrees', () => { // Default: no worktree has a sparse-checkout config file. Tests that need // sparse detection override this. statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })) + readFileMock.mockReset() + mockSparseCheckoutEnabledConfig() resolveGitDirMock.mockReset() resolveGitDirMock.mockImplementation(async (worktreePath: string) => `${worktreePath}/.git`) }) @@ -1151,12 +1180,14 @@ describe('listWorktrees', () => { completed = true }) - for (let attempt = 0; pendingProbeResolves.length < 8 && attempt < 20; attempt += 1) { + for (let attempt = 0; pendingProbeResolves.length < 8 && attempt < 50; attempt += 1) { await Promise.resolve() } expect(pendingProbeResolves).toHaveLength(8) - for (let attempt = 0; !completed && attempt < 20; attempt += 1) { + // Why: each probe may chain extra microtasks after stat (e.g. core.sparseCheckout + // config reads). Drain until the list settles, not a fixed microtask budget. + for (let attempt = 0; !completed && attempt < 100; attempt += 1) { pendingProbeResolves.splice(0).forEach((resolve) => resolve()) await Promise.resolve() await Promise.resolve() diff --git a/src/main/git/review-head-remote-identity.ts b/src/main/git/review-head-remote-identity.ts new file mode 100644 index 000000000..b5d28355a --- /dev/null +++ b/src/main/git/review-head-remote-identity.ts @@ -0,0 +1,26 @@ +import { gitExecFileAsync } from './runner' +import { reviewHeadRemoteRefComponent } from '../../shared/review-head-tracking-ref' + +type LocalGitExecOptions = { + cwd: string + wslDistro?: string +} + +// Why: the durable review-head ref embeds the remote's identity, and a missing +// remote must fail with an actionable message instead of a raw fetch error. +export async function getReviewHeadRemoteComponent( + remote: string, + localGitExecOptions: LocalGitExecOptions +): Promise { + let remoteUrl: string + try { + const { stdout } = await gitExecFileAsync(['remote', 'get-url', remote], localGitExecOptions) + remoteUrl = stdout.trim() + } catch { + remoteUrl = '' + } + if (!remoteUrl) { + throw new Error(`Remote "${remote}" is not configured.`) + } + return reviewHeadRemoteRefComponent(remote, remoteUrl) +} diff --git a/src/main/github/pr-head-tracking-ref.test.ts b/src/main/github/pr-head-tracking-ref.test.ts index f14caa353..c70576f77 100644 --- a/src/main/github/pr-head-tracking-ref.test.ts +++ b/src/main/github/pr-head-tracking-ref.test.ts @@ -4,12 +4,25 @@ import type { SshGitProvider } from '../providers/ssh-git-provider' const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() })) vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) -import { fetchPrHeadTrackingRef } from './pr-head-tracking-ref' +import { + githubPullRequestHeadLocalRef, + reviewHeadRemoteRefComponent, + REVIEW_HEAD_FETCH_TIMEOUT_MS +} from '../../shared/review-head-tracking-ref' +import { fetchGitHubPullRequestHeadRef, fetchPrHeadTrackingRef } from './pr-head-tracking-ref' + +const ORIGIN_URL = 'https://github.com/acme/widgets.git' +const ORIGIN_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_URL) describe('fetchPrHeadTrackingRef', () => { beforeEach(() => { gitExecFileAsyncMock.mockReset() - gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_URL}\n`, stderr: '' } + } + return { stdout: '', stderr: '' } + }) }) it('fetches into the remote-tracking ref with real git for local repos', async () => { @@ -46,4 +59,91 @@ describe('fetchPrHeadTrackingRef', () => { ).rejects.toThrow('SSH Git provider is not available') expect(gitExecFileAsyncMock).not.toHaveBeenCalled() }) + + it('fetches a GitHub pull head into its remote-scoped Orca ref for local repos', async () => { + const localRef = await fetchGitHubPullRequestHeadRef( + { path: '/repo', connectionId: null }, + null, + 'origin', + 42 + ) + + // The fetch is bounded so a stalled remote can't hang PR resolution. + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['fetch', '--no-tags', 'origin', `+refs/pull/42/head:refs/orca/pull/${ORIGIN_COMPONENT}/42`], + { cwd: '/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) + expect(localRef).toBe(githubPullRequestHeadLocalRef(ORIGIN_COMPONENT, 42)) + expect(localRef).toBe(`refs/orca/pull/${ORIGIN_COMPONENT}/42`) + }) + + it('fails the pull-head fetch when the remote is not configured', async () => { + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + throw new Error("fatal: No such remote 'origin'") + } + return { stdout: '', stderr: '' } + }) + + await expect( + fetchGitHubPullRequestHeadRef({ path: '/repo', connectionId: null }, null, 'origin', 42) + ).rejects.toThrow('Remote "origin" is not configured.') + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + expect.arrayContaining(['fetch']), + expect.anything() + ) + }) + + it('keeps WSL routing while bounding the pull-head fetch', async () => { + await fetchGitHubPullRequestHeadRef({ path: '/repo', connectionId: null }, null, 'origin', 42, { + localGitExecOptions: { cwd: '/repo', wslDistro: 'Ubuntu' } + }) + + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { + cwd: '/repo', + wslDistro: 'Ubuntu' + }) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['fetch', '--no-tags', 'origin', `+refs/pull/42/head:refs/orca/pull/${ORIGIN_COMPONENT}/42`], + { cwd: '/repo', wslDistro: 'Ubuntu', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) + }) + + it('uses the SSH GitHub pull-head RPC and never runs git directly', async () => { + const expectedRef = `refs/orca/pull/${ORIGIN_COMPONENT}/42` + const fetchGitHubPullRequestHead = vi.fn(async () => expectedRef) + + const localRef = await fetchGitHubPullRequestHeadRef( + { path: '/repo', connectionId: 'conn-1' }, + { fetchGitHubPullRequestHead } as unknown as SshGitProvider, + 'origin', + 42 + ) + + expect(fetchGitHubPullRequestHead).toHaveBeenCalledWith('/repo', 'origin', 42) + expect(localRef).toBe(expectedRef) + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('rejects a connected GitHub pull-head fetch without an SSH provider', async () => { + await expect( + fetchGitHubPullRequestHeadRef({ path: '/repo', connectionId: 'conn-1' }, null, 'origin', 42) + ).rejects.toThrow('SSH Git provider is not available') + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('rejects invalid PR numbers and option-shaped remotes before running git', async () => { + await expect( + fetchGitHubPullRequestHeadRef({ path: '/repo', connectionId: null }, null, 'origin', 4.2) + ).rejects.toThrow('Invalid pull request number') + await expect( + fetchGitHubPullRequestHeadRef( + { path: '/repo', connectionId: null }, + null, + '--upload-pack=x', + 42 + ) + ).rejects.toThrow('must not start with "-"') + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) }) diff --git a/src/main/github/pr-head-tracking-ref.ts b/src/main/github/pr-head-tracking-ref.ts index 3e3fd82e3..84788b6c0 100644 --- a/src/main/github/pr-head-tracking-ref.ts +++ b/src/main/github/pr-head-tracking-ref.ts @@ -1,4 +1,11 @@ import { gitExecFileAsync } from '../git/runner' +import { + githubPullRequestHeadLocalRef, + isSafeReviewHeadFetchRemote, + isValidReviewHeadNumber, + REVIEW_HEAD_FETCH_TIMEOUT_MS +} from '../../shared/review-head-tracking-ref' +import { getReviewHeadRemoteComponent } from '../git/review-head-remote-identity' import type { SshGitProvider } from '../providers/ssh-git-provider' type LocalGitExecOptions = { @@ -28,3 +35,36 @@ export async function fetchPrHeadTrackingRef( } await sshGitProvider.fetchRemoteTrackingRef(repo.path, remote, branch, ref) } + +export async function fetchGitHubPullRequestHeadRef( + repo: { path: string; connectionId?: string | null }, + sshGitProvider: SshGitProvider | null | undefined, + remote: string, + prNumber: number, + options: { localGitExecOptions?: LocalGitExecOptions } = {} +): Promise { + if (!isValidReviewHeadNumber(prNumber)) { + throw new Error(`Invalid pull request number: ${prNumber}`) + } + if (!isSafeReviewHeadFetchRemote(remote)) { + throw new Error('Pull request fetch remote must not start with "-".') + } + if (!repo.connectionId) { + const localGitExecOptions = options.localGitExecOptions ?? { cwd: repo.path } + const remoteComponent = await getReviewHeadRemoteComponent(remote, localGitExecOptions) + // Why: return the same path the fetch wrote so callers don't re-resolve identity. + const localRef = githubPullRequestHeadLocalRef(remoteComponent, prNumber) + await gitExecFileAsync( + ['fetch', '--no-tags', remote, `+refs/pull/${prNumber}/head:${localRef}`], + { + ...localGitExecOptions, + timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS + } + ) + return localRef + } + if (!sshGitProvider) { + throw new Error('SSH Git provider is not available. Reconnect to this target and try again.') + } + return sshGitProvider.fetchGitHubPullRequestHead(repo.path, remote, prNumber) +} diff --git a/src/main/github/pr-start-point-compare-base.test.ts b/src/main/github/pr-start-point-compare-base.test.ts new file mode 100644 index 000000000..7a6b4e458 --- /dev/null +++ b/src/main/github/pr-start-point-compare-base.test.ts @@ -0,0 +1,171 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { getPullRequestPushTargetMock } = vi.hoisted(() => ({ + getPullRequestPushTargetMock: vi.fn() +})) + +vi.mock('./client', () => ({ + getPullRequestPushTarget: getPullRequestPushTargetMock, + getWorkItem: vi.fn() +})) + +import { resolveGitHubPrStartPoint } from './pr-start-point' +import { reviewHeadRemoteRefComponent } from '../../shared/review-head-tracking-ref' + +const ORIGIN_URL = 'git@github.com:acme/orca.git' +const durablePrLocalRef = `refs/orca/pull/${reviewHeadRemoteRefComponent('origin', ORIGIN_URL)}/42` +const durablePrRev = `${durablePrLocalRef}^{commit}` + +describe('resolveGitHubPrStartPoint compare base', () => { + beforeEach(() => { + getPullRequestPushTargetMock.mockReset() + getPullRequestPushTargetMock.mockResolvedValue(null) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + }) + afterEach(() => vi.restoreAllMocks()) + + it('drops the compare base for a fork PR when its base ref is missing locally too', async () => { + const fetchRemoteTrackingRef = vi.fn(async () => { + throw new Error("fatal: couldn't find remote ref refs/heads/main") + }) + const fetchPullRequestHeadRef = vi.fn(async () => durablePrLocalRef) + // Why: durable ref for the head resolves; the compare base does not exist. + const gitExec = vi.fn(async (args: string[]) => { + if (args[2] === durablePrRev) { + return { stdout: 'fork-head-sha\n', stderr: '' } + } + throw new Error('fatal: Needed a single revision') + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 42, + headRefName: 'contributor/fix', + baseRefName: 'main', + isCrossRepository: true, + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef, + resolveRemote: async () => 'origin' + }) + + // Why: guards against a FETCH_HEAD regression — the head must resolve via the durable ref. + expect(gitExec).toHaveBeenCalledWith(['rev-parse', '--verify', durablePrRev]) + expect(result).toEqual({ + baseBranch: 'fork-head-sha', + headSha: 'fork-head-sha', + branchNameOverride: 'contributor/fix' + }) + expect(console.warn).toHaveBeenCalledWith( + '[github:resolvePrStartPoint] optional compare-base fetch failed', + expect.objectContaining({ baseRefName: 'main', prNumber: 42, localBaseResolved: false }) + ) + }) + + it('keeps the compare base for a fork PR when the local tracking ref still resolves', async () => { + const fetchRemoteTrackingRef = vi.fn(async () => { + // Why: transient network failure — the previously-fetched base is still on disk. + throw new Error('fatal: unable to access repo: Could not resolve host: github.com') + }) + const fetchPullRequestHeadRef = vi.fn(async () => durablePrLocalRef) + const gitExec = vi.fn(async (args: string[]) => { + if (args[2] === durablePrRev) { + return { stdout: 'fork-head-sha\n', stderr: '' } + } + if (args[2] === 'refs/remotes/origin/main^{commit}') { + return { stdout: 'base-commit-sha\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 42, + headRefName: 'contributor/fix', + baseRefName: 'main', + isCrossRepository: true, + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef, + resolveRemote: async () => 'origin' + }) + + // Why: create-time baseRef metadata must be the compare base, not the PR head SHA. + expect(result).toEqual({ + baseBranch: 'fork-head-sha', + compareBaseRef: 'refs/remotes/origin/main', + headSha: 'fork-head-sha', + branchNameOverride: 'contributor/fix' + }) + expect(gitExec).toHaveBeenCalledWith([ + 'rev-parse', + '--verify', + 'refs/remotes/origin/main^{commit}' + ]) + }) + + it('keeps a same-repo PR compare base when the fetch fails but the local ref resolves', async () => { + const fetchRemoteTrackingRef = vi.fn(async (_remote: string, branch: string) => { + if (branch === 'main') { + throw new Error('network unavailable') + } + }) + const gitExec = vi.fn(async (args: string[]) => { + if (args[2] === 'refs/remotes/origin/main^{commit}') { + return { stdout: 'base-commit-sha\n', stderr: '' } + } + return { stdout: 'same-repo-head-sha\n', stderr: '' } + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 43, + headRefName: 'feature/fix', + baseRefName: 'main', + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef: async () => durablePrLocalRef, + resolveRemote: async () => 'origin' + }) + + expect(result).toEqual({ + baseBranch: 'same-repo-head-sha', + compareBaseRef: 'refs/remotes/origin/main', + headSha: 'same-repo-head-sha', + branchNameOverride: 'feature/fix', + pushTarget: { remoteName: 'origin', branchName: 'feature/fix' } + }) + }) + + it('drops a same-repo PR compare base when neither fetch nor local ref resolves', async () => { + const fetchRemoteTrackingRef = vi.fn(async (_remote: string, branch: string) => { + if (branch === 'main') { + throw new Error('network unavailable') + } + }) + const gitExec = vi.fn(async (args: string[]) => { + if (args[2] === 'refs/remotes/origin/main^{commit}') { + throw new Error('fatal: Needed a single revision') + } + return { stdout: 'same-repo-head-sha\n', stderr: '' } + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 44, + headRefName: 'feature/fix', + baseRefName: 'main', + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef: async () => durablePrLocalRef, + resolveRemote: async () => 'origin' + }) + + expect(result).toEqual({ + baseBranch: 'same-repo-head-sha', + headSha: 'same-repo-head-sha', + branchNameOverride: 'feature/fix', + pushTarget: { remoteName: 'origin', branchName: 'feature/fix' } + }) + }) +}) diff --git a/src/main/github/pr-start-point.test.ts b/src/main/github/pr-start-point.test.ts index 8783b2a4a..57eaacb67 100644 --- a/src/main/github/pr-start-point.test.ts +++ b/src/main/github/pr-start-point.test.ts @@ -11,11 +11,27 @@ vi.mock('./client', () => ({ })) import { resolveGitHubPrStartPoint } from './pr-start-point' +import { reviewHeadRemoteRefComponent } from '../../shared/review-head-tracking-ref' + +const ORIGIN_URL = 'git@github.com:acme/orca.git' +const ORIGIN_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_URL) +const durablePrLocalRef = (prNumber: number): string => + `refs/orca/pull/${ORIGIN_COMPONENT}/${prNumber}` +const durablePrRev = (prNumber: number): string => `${durablePrLocalRef(prNumber)}^{commit}` +const remoteGetUrl = (args: string[]): { stdout: string; stderr: string } | null => + args[0] === 'remote' && args[1] === 'get-url' ? { stdout: `${ORIGIN_URL}\n`, stderr: '' } : null describe('resolveGitHubPrStartPoint', () => { + const fetchPullRequestHeadRefMock = vi.fn() + beforeEach(() => { getPullRequestPushTargetMock.mockReset() getWorkItemMock.mockReset() + fetchPullRequestHeadRefMock.mockReset() + // Why: success path rev-parses the path the fetch returns (writer-authoritative). + fetchPullRequestHeadRefMock.mockImplementation(async (_remote: string, prNumber: number) => + durablePrLocalRef(prNumber) + ) }) it('falls back to the GitHub PR head ref when a direct branch fetch fails', async () => { @@ -32,6 +48,10 @@ describe('resolveGitHubPrStartPoint', () => { } }) const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } if (args[0] === 'rev-parse') { return { stdout: 'def456\n', stderr: '' } } @@ -45,12 +65,13 @@ describe('resolveGitHubPrStartPoint', () => { baseRefName: 'main', gitExec, fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, resolveRemote: async () => 'origin' }) expect(fetchRemoteTrackingRef).toHaveBeenCalledWith('origin', 'fix-issue-6933') expect(fetchRemoteTrackingRef).toHaveBeenCalledWith('origin', 'main') - expect(gitExec).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/6934/head']) + expect(fetchPullRequestHeadRefMock).toHaveBeenCalledWith('origin', 6934) expect(result).toEqual({ baseBranch: 'def456', compareBaseRef: 'refs/remotes/origin/main', @@ -70,6 +91,10 @@ describe('resolveGitHubPrStartPoint', () => { throw new Error('fatal: could not find remote ref') }) const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } if (args[0] === 'rev-parse') { return { stdout: 'def456\n', stderr: '' } } @@ -82,6 +107,7 @@ describe('resolveGitHubPrStartPoint', () => { headRefName: 'feat/onboarding-model-choice-782', gitExec, fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, resolveRemote: async () => 'origin' }) @@ -97,6 +123,10 @@ describe('resolveGitHubPrStartPoint', () => { getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable')) const fetchRemoteTrackingRef = vi.fn(async () => {}) const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } if (args[0] === 'rev-parse') { return { stdout: 'abc123\n', stderr: '' } } @@ -110,11 +140,12 @@ describe('resolveGitHubPrStartPoint', () => { isCrossRepository: true, gitExec, fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, resolveRemote: async () => 'origin' }) expect(getPullRequestPushTargetMock).toHaveBeenCalledWith('/repo-root', 1849, null) - expect(gitExec).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head']) + expect(fetchPullRequestHeadRefMock).toHaveBeenCalledWith('origin', 1849) expect(result).toEqual({ baseBranch: 'abc123', headSha: 'abc123', @@ -122,6 +153,207 @@ describe('resolveGitHubPrStartPoint', () => { }) }) + it('prefers the pull-head error when the branch miss triggered a failing fallback', async () => { + // Why: the branch fetch missed and we fell back to refs/pull//head; the + // fallback failure is the actionable one, not the original branch miss. + const fetchRemoteTrackingRef = vi.fn(async () => { + throw new Error('fatal: could not find remote ref refs/heads/feature/fix') + }) + fetchPullRequestHeadRefMock.mockRejectedValue( + new Error( + 'This SSH host is running an older Orca relay that cannot fetch pull request heads.' + ) + ) + const gitExec = vi.fn(async () => ({ stdout: '', stderr: '' })) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 77, + headRefName: 'feature/fix', + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, + resolveRemote: async () => 'origin' + }) + + expect(result).toEqual({ + error: + 'Failed to fetch refs/pull/77/head: This SSH host is running an older Orca relay that cannot fetch pull request heads.' + }) + }) + + it('captures the fork PR head from a dedicated ref, not the shared FETCH_HEAD', async () => { + getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable')) + const fetchRemoteTrackingRef = vi.fn(async () => {}) + // Why: simulate a concurrent `git fetch origin` clobbering FETCH_HEAD with the + // default-branch tip. The resolved start-point must come from the durable Orca ref. + const gitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'rev-parse') { + const ref = args.at(-1) + if (ref === 'FETCH_HEAD') { + return { stdout: 'mainbranchtip000\n', stderr: '' } + } + if (ref === durablePrRev(1849)) { + return { stdout: 'prheadsha111\n', stderr: '' } + } + throw new Error(`unexpected rev-parse ref: ${ref}`) + } + return { stdout: '', stderr: '' } + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 1849, + headRefName: 'feat/onboarding-model-choice-782', + isCrossRepository: true, + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, + resolveRemote: async () => 'origin' + }) + + expect(fetchPullRequestHeadRefMock).toHaveBeenCalledWith('origin', 1849) + // Success path must not re-hash remote identity after the fetch returns a path. + expect(gitExec).not.toHaveBeenCalledWith(['remote', 'get-url', 'origin']) + expect(gitExec).not.toHaveBeenCalledWith(['rev-parse', '--verify', 'FETCH_HEAD']) + expect(result).toEqual({ + baseBranch: 'prheadsha111', + headSha: 'prheadsha111', + branchNameOverride: 'feat/onboarding-model-choice-782' + }) + }) + + it('keeps the durable PR head when the head fetch fails but the local ref resolves', async () => { + // Why: mirror compare-base soft-keep — a transient fetch failure must not + // fail the resolve when a prior fetch already pinned refs/orca/pull/. + getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable')) + fetchPullRequestHeadRefMock.mockRejectedValue( + new Error('fatal: unable to access repo: Could not resolve host: github.com') + ) + const fetchRemoteTrackingRef = vi.fn(async () => {}) + const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } + if (args[0] === 'rev-parse' && args[2] === durablePrRev(1849)) { + return { stdout: 'pinnedheadsha\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args[2] === 'refs/remotes/origin/main^{commit}') { + return { stdout: 'base-commit-sha\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + try { + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 1849, + headRefName: 'contributor/fix', + baseRefName: 'main', + isCrossRepository: true, + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, + resolveRemote: async () => 'origin' + }) + + expect(result).toEqual({ + baseBranch: 'pinnedheadsha', + compareBaseRef: 'refs/remotes/origin/main', + headSha: 'pinnedheadsha', + branchNameOverride: 'contributor/fix' + }) + } finally { + warnSpy.mockRestore() + } + }) + + it.each([ + ["fatal: couldn't find remote ref refs/pull/1849/head", 'deleted PR / cleaned fork'], + ['Authentication failed. Check your remote credentials.', 'auth failure'], + [ + 'This SSH host is running an older Orca relay that cannot fetch pull request heads. Reconnect to deploy the latest relay, then try again.', + 'stale relay' + ] + ])('fails hard instead of soft-keeping the durable PR head on: %s', async (message) => { + // Why: soft-keep on a non-transient failure would check out a dead or + // unauthorized tip (or mask the reconnect prompt) with a success UX. + getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable')) + fetchPullRequestHeadRefMock.mockRejectedValue(new Error(message)) + const fetchRemoteTrackingRef = vi.fn(async () => {}) + const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } + if (args[0] === 'rev-parse' && args[2] === durablePrRev(1849)) { + return { stdout: 'pinnedheadsha\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 1849, + headRefName: 'contributor/fix', + baseRefName: 'main', + isCrossRepository: true, + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, + resolveRemote: async () => 'origin' + }) + + expect(result).toEqual({ + error: `Failed to fetch refs/pull/1849/head: ${message}` + }) + expect(gitExec).not.toHaveBeenCalledWith(['rev-parse', '--verify', durablePrRev(1849)]) + }) + + it('soft-keeps the durable PR head on an exec-timeout kill', async () => { + getPullRequestPushTargetMock.mockRejectedValue(new Error('head repo is unavailable')) + const timeoutError = Object.assign(new Error('Command failed: git fetch --no-tags origin'), { + killed: true, + signal: 'SIGTERM' + }) + fetchPullRequestHeadRefMock.mockRejectedValue(timeoutError) + const fetchRemoteTrackingRef = vi.fn(async () => {}) + const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } + if (args[0] === 'rev-parse' && args[2] === durablePrRev(1849)) { + return { stdout: 'pinnedheadsha\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + try { + const result = await resolveGitHubPrStartPoint({ + repoPath: '/repo-root', + prNumber: 1849, + headRefName: 'contributor/fix', + isCrossRepository: true, + gitExec, + fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, + resolveRemote: async () => 'origin' + }) + + expect(result).toEqual({ + baseBranch: 'pinnedheadsha', + headSha: 'pinnedheadsha', + branchNameOverride: 'contributor/fix' + }) + } finally { + warnSpy.mockRestore() + } + }) + it('uses PR metadata when the caller did not pass a head ref', async () => { getWorkItemMock.mockResolvedValue({ type: 'pr', @@ -138,6 +370,10 @@ describe('resolveGitHubPrStartPoint', () => { }) const fetchRemoteTrackingRef = vi.fn(async () => {}) const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } if (args[0] === 'rev-parse') { return { stdout: 'abc123\n', stderr: '' } } @@ -149,6 +385,7 @@ describe('resolveGitHubPrStartPoint', () => { prNumber: 1738, gitExec, fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, resolveRemote: async () => 'origin' }) @@ -177,6 +414,10 @@ describe('resolveGitHubPrStartPoint', () => { }) const fetchRemoteTrackingRef = vi.fn(async () => {}) const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } if (args[0] === 'rev-parse') { return { stdout: 'abc123\n', stderr: '' } } @@ -190,6 +431,7 @@ describe('resolveGitHubPrStartPoint', () => { isCrossRepository: true, gitExec, fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, resolveRemote: async () => 'origin' }) @@ -209,6 +451,10 @@ describe('resolveGitHubPrStartPoint', () => { it('returns the verified head SHA, branch override, and push target when same-repo branch fetch succeeds', async () => { const fetchRemoteTrackingRef = vi.fn(async () => {}) const gitExec = vi.fn(async (args: string[]) => { + const url = remoteGetUrl(args) + if (url) { + return url + } if (args[0] === 'rev-parse') { return { stdout: 'abc123\n', stderr: '' } } @@ -222,6 +468,7 @@ describe('resolveGitHubPrStartPoint', () => { baseRefName: 'develop', gitExec, fetchRemoteTrackingRef, + fetchPullRequestHeadRef: fetchPullRequestHeadRefMock, resolveRemote: async () => 'origin' }) diff --git a/src/main/github/pr-start-point.ts b/src/main/github/pr-start-point.ts index f5511981d..303bc1ed0 100644 --- a/src/main/github/pr-start-point.ts +++ b/src/main/github/pr-start-point.ts @@ -1,6 +1,14 @@ import type { GitHubPrStartPoint, GitPushTarget } from '../../shared/types' -import { isMissingRemoteRefGitError } from '../git/fetch-error-classification' +import { fetchCompareBaseRefWithLocalFallback } from '../git/compare-base-ref-fetch' +import { + isMissingRemoteRefGitError, + isTransientReviewHeadFetchError +} from '../git/fetch-error-classification' import { getPullRequestPushTarget, getWorkItem } from './client' +import { + githubPullRequestHeadLocalRef, + reviewHeadRemoteRefComponent +} from '../../shared/review-head-tracking-ref' type GitExec = (args: string[]) => Promise<{ stdout: string; stderr: string }> @@ -14,6 +22,9 @@ type ResolveGitHubPrStartPointArgs = { localGitOptions?: { wslDistro?: string } gitExec: GitExec fetchRemoteTrackingRef: (remote: string, branch: string) => Promise + // Why: returns the durable local ref the fetch wrote so resolve can rev-parse + // that exact path instead of re-hashing remote identity. + fetchPullRequestHeadRef: (remote: string, prNumber: number) => Promise resolveRemote: () => Promise } @@ -88,40 +99,81 @@ export async function resolveGitHubPrStartPoint( const compareBaseRef = baseRefName ? `refs/remotes/${remote}/${baseRefName}` : undefined - const fetchCompareBaseRef = async (): Promise<{ error: string } | null> => { - if (!baseRefName) { - return null - } - try { - await args.fetchRemoteTrackingRef(remote, baseRefName) - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - return { error: `Failed to fetch ${remote}/${baseRefName}: ${message.split('\n')[0]}` } - } - return null - } + const fetchCompareBaseRef = (): Promise => + fetchCompareBaseRefWithLocalFallback({ + compareBaseRef, + fetchCompareBaseRef: () => args.fetchRemoteTrackingRef(remote, baseRefName), + gitExec: args.gitExec, + logLabel: '[github:resolvePrStartPoint]', + logContext: { remote, baseRefName, prNumber: args.prNumber } + }) const fetchPullRequestHeadSha = async (): Promise<{ baseBranch: string } | { error: string }> => { const pullRef = `refs/pull/${args.prNumber}/head` + // Why: soft-keep needs identity when the fetch throws before returning a path. + // Success uses the path returned by the fetch itself (writer-authoritative). + let softKeepLocalRefPromise: Promise | undefined + const resolveSoftKeepLocalRef = (): Promise => { + softKeepLocalRefPromise ??= (async () => { + try { + const { stdout } = await args.gitExec(['remote', 'get-url', remote]) + const remoteUrl = stdout.trim() + if (!remoteUrl) { + return null + } + return githubPullRequestHeadLocalRef( + reviewHeadRemoteRefComponent(remote, remoteUrl), + args.prNumber + ) + } catch { + return null + } + })() + return softKeepLocalRefPromise + } + const resolveDurableHeadSha = async (localRef: string | null): Promise => { + if (!localRef) { + return null + } + try { + const { stdout } = await args.gitExec(['rev-parse', '--verify', `${localRef}^{commit}`]) + return stdout.trim() || null + } catch { + return null + } + } try { - await args.gitExec(['fetch', remote, pullRef]) + const localRef = await args.fetchPullRequestHeadRef(remote, args.prNumber) + const sha = await resolveDurableHeadSha(localRef) + if (!sha) { + return { error: `Could not resolve fork PR #${args.prNumber} head after fetch.` } + } + return { baseBranch: sha } } catch (error) { const message = error instanceof Error ? error.message : String(error) + // Why: mirror compare-base — a transient transport failure must not fail + // the resolve when a prior fetch already pinned the durable head ref. A + // missing remote ref (deleted PR/fork), auth failure, or stale-relay + // error must fail hard: serving the durable ref there would check out a + // dead or unauthorized tip and mask the actionable error. + if (isTransientReviewHeadFetchError(error)) { + const localSha = await resolveDurableHeadSha(await resolveSoftKeepLocalRef()) + if (localSha) { + console.warn( + '[github:resolvePrStartPoint] PR head fetch failed; using durable local ref', + { + remote, + prNumber: args.prNumber, + error: message.split('\n')[0] + } + ) + return { baseBranch: localSha } + } + } 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 @@ -132,16 +184,13 @@ export async function resolveGitHubPrStartPoint( if ('error' in result) { return result } - const compareBaseFetchError = await fetchCompareBaseRef() - if (compareBaseFetchError) { - return compareBaseFetchError - } + const compareBaseFetched = await fetchCompareBaseRef() // Why: adopt the contributor's branch name locally (mirroring the same-repo // return below) so fork-PR worktrees aren't renamed with the maintainer's // branch prefix (e.g. `me/866`). The push refspec still targets the fork. return { ...result, - ...(compareBaseRef ? { compareBaseRef } : {}), + ...(compareBaseFetched && compareBaseRef ? { compareBaseRef } : {}), headSha: result.baseBranch, branchNameOverride: headRefName, ...(pushTarget ? { pushTarget } : {}), @@ -159,19 +208,19 @@ export async function resolveGitHubPrStartPoint( const result = await fetchPullRequestHeadSha() if (!('error' in result)) { await resolvePushTarget() - const compareBaseFetchError = await fetchCompareBaseRef() - if (compareBaseFetchError) { - return compareBaseFetchError - } + const compareBaseFetched = await fetchCompareBaseRef() return { ...result, - ...(compareBaseRef ? { compareBaseRef } : {}), + ...(compareBaseFetched && compareBaseRef ? { compareBaseRef } : {}), headSha: result.baseBranch, branchNameOverride: headRefName, ...(pushTarget ? { pushTarget } : {}), ...(maintainerCanModify !== undefined ? { maintainerCanModify } : {}) } } + // Why: the branch fetch missed and the pull-head fallback is what actually + // failed, so surface its (more actionable) error rather than the branch miss. + return result } return { error: `Failed to fetch ${remote}/${headRefName}: ${message.split('\n')[0]}` @@ -189,14 +238,11 @@ export async function resolveGitHubPrStartPoint( if (!headSha) { return { error: `Empty SHA resolving PR #${args.prNumber} head.` } } - const compareBaseFetchError = await fetchCompareBaseRef() - if (compareBaseFetchError) { - return compareBaseFetchError - } + const compareBaseFetched = await fetchCompareBaseRef() return { baseBranch: headSha, - ...(compareBaseRef ? { compareBaseRef } : {}), + ...(compareBaseFetched && compareBaseRef ? { compareBaseRef } : {}), headSha, branchNameOverride: headRefName, pushTarget: { remoteName: remote, branchName: headRefName } diff --git a/src/main/github/review-head-remote.test.ts b/src/main/github/review-head-remote.test.ts new file mode 100644 index 000000000..f5ff2fff2 --- /dev/null +++ b/src/main/github/review-head-remote.test.ts @@ -0,0 +1,102 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { getDefaultRemoteMock, getGitHubApiRepositoryForRemoteMock } = vi.hoisted(() => ({ + getDefaultRemoteMock: vi.fn(), + getGitHubApiRepositoryForRemoteMock: vi.fn() +})) + +vi.mock('../git/repo', () => ({ getDefaultRemote: getDefaultRemoteMock })) +vi.mock('./github-api-repository', () => ({ + getGitHubApiRepositoryForRemote: getGitHubApiRepositoryForRemoteMock +})) + +import { resolveGitHubReviewHeadRemote } from './review-head-remote' + +function gitExecWithRemotes(remotes: string[]) { + return vi.fn(async (args: string[]) => { + if (args[0] === 'remote') { + return { stdout: `${remotes.join('\n')}\n`, stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) +} + +describe('resolveGitHubReviewHeadRemote', () => { + beforeEach(() => { + getDefaultRemoteMock.mockReset() + getGitHubApiRepositoryForRemoteMock.mockReset() + }) + + it('prefers upstream on a contributor clone whose origin is a fork', async () => { + // Why: PR work-item resolution probes upstream first; refs/pull//head for + // an upstream PR does not exist on the fork origin. + getGitHubApiRepositoryForRemoteMock.mockImplementation(async (_path, remote) => + remote === 'upstream' + ? { owner: 'org', repo: 'project' } + : { owner: 'contributor', repo: 'project' } + ) + + const remote = await resolveGitHubReviewHeadRemote({ + repoPath: '/repo', + gitExec: gitExecWithRemotes(['origin', 'upstream']) + }) + + expect(remote).toBe('upstream') + expect(getDefaultRemoteMock).not.toHaveBeenCalled() + }) + + it('falls back to origin when upstream is not a GitHub project', async () => { + getGitHubApiRepositoryForRemoteMock.mockImplementation(async (_path, remote) => + remote === 'origin' ? { owner: 'org', repo: 'project' } : null + ) + + const remote = await resolveGitHubReviewHeadRemote({ + repoPath: '/repo', + gitExec: gitExecWithRemotes(['origin', 'upstream']) + }) + + expect(remote).toBe('origin') + }) + + it('skips identity probes for a single-remote clone and uses the local default', async () => { + getDefaultRemoteMock.mockResolvedValue('origin') + + const remote = await resolveGitHubReviewHeadRemote({ + repoPath: '/repo', + localGitOptions: { wslDistro: 'Ubuntu' }, + gitExec: gitExecWithRemotes(['origin']) + }) + + expect(remote).toBe('origin') + expect(getGitHubApiRepositoryForRemoteMock).not.toHaveBeenCalled() + expect(getDefaultRemoteMock).toHaveBeenCalledWith('/repo', { wslDistro: 'Ubuntu' }) + }) + + it('prefers origin over other remotes on SSH repos when no identity resolves', async () => { + getGitHubApiRepositoryForRemoteMock.mockResolvedValue(null) + + const remote = await resolveGitHubReviewHeadRemote({ + repoPath: '/remote/repo', + connectionId: 'ssh-1', + gitExec: gitExecWithRemotes(['fork', 'origin']) + }) + + expect(remote).toBe('origin') + expect(getDefaultRemoteMock).not.toHaveBeenCalled() + }) + + it('threads connection and WSL options through the identity probe', async () => { + getGitHubApiRepositoryForRemoteMock.mockResolvedValue({ owner: 'org', repo: 'project' }) + + await resolveGitHubReviewHeadRemote({ + repoPath: '/repo', + connectionId: 'ssh-1', + localGitOptions: { wslDistro: 'Ubuntu' }, + gitExec: gitExecWithRemotes(['origin', 'upstream']) + }) + + expect(getGitHubApiRepositoryForRemoteMock).toHaveBeenCalledWith('/repo', 'upstream', 'ssh-1', { + wslDistro: 'Ubuntu' + }) + }) +}) diff --git a/src/main/github/review-head-remote.ts b/src/main/github/review-head-remote.ts new file mode 100644 index 000000000..2df757471 --- /dev/null +++ b/src/main/github/review-head-remote.ts @@ -0,0 +1,47 @@ +import { pickPreferredGitRemote } from '../../shared/preferred-git-remote' +import { getDefaultRemote } from '../git/repo' +import { getGitHubApiRepositoryForRemote } from './github-api-repository' + +type GitExec = (args: string[]) => Promise<{ stdout: string; stderr: string }> + +// Why: PR work-item/API resolution probes upstream before origin +// (resolveGitHubApiRepositoryCandidates), so review-head fetches must target +// the same hosting project — a contributor clone's fork `origin` has no +// refs/pull//head for an upstream PR. Local and SSH share this resolver so +// the two surfaces cannot pick different remotes. +export async function resolveGitHubReviewHeadRemote(args: { + repoPath: string + connectionId?: string | null + localGitOptions?: { wslDistro?: string } + gitExec: GitExec +}): Promise { + const { stdout } = await args.gitExec(['remote']) + const remotes = stdout + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + // Why: identity probes cost a `remote get-url` (plus a possible gh auth + // lookup) each; only multi-remote clones are ambiguous enough to need them. + if (remotes.length > 1) { + for (const remote of ['upstream', 'origin']) { + if (!remotes.includes(remote)) { + continue + } + const repository = await getGitHubApiRepositoryForRemote( + args.repoPath, + remote, + args.connectionId ?? null, + args.localGitOptions ?? {} + ) + if (repository) { + return remote + } + } + } + // Why: when no remote maps to a GitHub project the hosting identity cannot + // guide the choice; keep the legacy per-transport fallback. + if (args.connectionId) { + return pickPreferredGitRemote(remotes) + } + return getDefaultRemote(args.repoPath, args.localGitOptions ?? {}) +} diff --git a/src/main/gitlab/mr-head-tracking-ref.test.ts b/src/main/gitlab/mr-head-tracking-ref.test.ts new file mode 100644 index 000000000..a83a94f88 --- /dev/null +++ b/src/main/gitlab/mr-head-tracking-ref.test.ts @@ -0,0 +1,130 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { SshGitProvider } from '../providers/ssh-git-provider' + +const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() })) +vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) + +import { + gitlabMergeRequestHeadLocalRef, + reviewHeadRemoteRefComponent, + REVIEW_HEAD_FETCH_TIMEOUT_MS +} from '../../shared/review-head-tracking-ref' +import { fetchGitLabMergeRequestHeadRef } from './mr-head-tracking-ref' + +const ORIGIN_URL = 'https://gitlab.com/acme/widgets.git' +const ORIGIN_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_URL) + +describe('fetchGitLabMergeRequestHeadRef', () => { + beforeEach(() => { + gitExecFileAsyncMock.mockReset() + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_URL}\n`, stderr: '' } + } + return { stdout: '', stderr: '' } + }) + }) + + it('fetches a GitLab MR head into its remote-scoped Orca ref for local repos', async () => { + const localRef = await fetchGitLabMergeRequestHeadRef( + { path: '/repo', connectionId: null }, + null, + 'origin', + 42 + ) + + // The fetch is bounded so a stalled remote can't hang MR resolution. + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'fetch', + '--no-tags', + 'origin', + `+refs/merge-requests/42/head:refs/orca/merge-requests/${ORIGIN_COMPONENT}/42` + ], + { cwd: '/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) + expect(localRef).toBe(gitlabMergeRequestHeadLocalRef(ORIGIN_COMPONENT, 42)) + expect(localRef).toBe(`refs/orca/merge-requests/${ORIGIN_COMPONENT}/42`) + }) + + it('fails the MR-head fetch when the remote is not configured', async () => { + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + throw new Error("fatal: No such remote 'origin'") + } + return { stdout: '', stderr: '' } + }) + + await expect( + fetchGitLabMergeRequestHeadRef({ path: '/repo', connectionId: null }, null, 'origin', 42) + ).rejects.toThrow('Remote "origin" is not configured.') + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + expect.arrayContaining(['fetch']), + expect.anything() + ) + }) + + it('keeps WSL routing while bounding the MR-head fetch', async () => { + await fetchGitLabMergeRequestHeadRef( + { path: '/repo', connectionId: null }, + null, + 'origin', + 42, + { + localGitExecOptions: { cwd: '/repo', wslDistro: 'Ubuntu' } + } + ) + + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { + cwd: '/repo', + wslDistro: 'Ubuntu' + }) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'fetch', + '--no-tags', + 'origin', + `+refs/merge-requests/42/head:refs/orca/merge-requests/${ORIGIN_COMPONENT}/42` + ], + { cwd: '/repo', wslDistro: 'Ubuntu', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) + }) + + it('uses the SSH GitLab MR-head RPC and never runs git directly', async () => { + const expectedRef = `refs/orca/merge-requests/${ORIGIN_COMPONENT}/77` + const fetchGitLabMergeRequestHead = vi.fn(async () => expectedRef) + + const localRef = await fetchGitLabMergeRequestHeadRef( + { path: '/repo', connectionId: 'conn-1' }, + { fetchGitLabMergeRequestHead } as unknown as SshGitProvider, + 'origin', + 77 + ) + + expect(fetchGitLabMergeRequestHead).toHaveBeenCalledWith('/repo', 'origin', 77) + expect(localRef).toBe(expectedRef) + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('rejects a connected GitLab MR-head fetch without an SSH provider', async () => { + await expect( + fetchGitLabMergeRequestHeadRef({ path: '/repo', connectionId: 'conn-1' }, null, 'origin', 77) + ).rejects.toThrow('SSH Git provider is not available') + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('rejects invalid MR iids and option-shaped remotes before running git', async () => { + await expect( + fetchGitLabMergeRequestHeadRef({ path: '/repo', connectionId: null }, null, 'origin', 0) + ).rejects.toThrow('Invalid merge request iid') + await expect( + fetchGitLabMergeRequestHeadRef( + { path: '/repo', connectionId: null }, + null, + '--upload-pack=x', + 42 + ) + ).rejects.toThrow('must not start with "-"') + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/gitlab/mr-head-tracking-ref.ts b/src/main/gitlab/mr-head-tracking-ref.ts new file mode 100644 index 000000000..fa3540e12 --- /dev/null +++ b/src/main/gitlab/mr-head-tracking-ref.ts @@ -0,0 +1,51 @@ +import { + gitlabMergeRequestHeadLocalRef, + isSafeReviewHeadFetchRemote, + isValidReviewHeadNumber, + REVIEW_HEAD_FETCH_TIMEOUT_MS +} from '../../shared/review-head-tracking-ref' +import { gitExecFileAsync } from '../git/runner' +import { getReviewHeadRemoteComponent } from '../git/review-head-remote-identity' +import type { SshGitProvider } from '../providers/ssh-git-provider' + +type LocalGitExecOptions = { + cwd: string + wslDistro?: string +} + +// Why: the relay's read-only git.exec channel rejects `fetch`, so SSH repos +// must use the dedicated git.fetchGitLabMergeRequestHeadRef RPC. Mirrors +// fetchGitHubPullRequestHeadRef so both providers pin the durable head ref +// the same way. +export async function fetchGitLabMergeRequestHeadRef( + repo: { path: string; connectionId?: string | null }, + sshGitProvider: SshGitProvider | null | undefined, + remote: string, + mrIid: number, + options: { localGitExecOptions?: LocalGitExecOptions } = {} +): Promise { + if (!isValidReviewHeadNumber(mrIid)) { + throw new Error(`Invalid merge request iid: ${mrIid}`) + } + if (!isSafeReviewHeadFetchRemote(remote)) { + throw new Error('Merge request fetch remote must not start with "-".') + } + if (!repo.connectionId) { + const localGitExecOptions = options.localGitExecOptions ?? { cwd: repo.path } + const remoteComponent = await getReviewHeadRemoteComponent(remote, localGitExecOptions) + // Why: return the same path the fetch wrote so callers don't re-resolve identity. + const localRef = gitlabMergeRequestHeadLocalRef(remoteComponent, mrIid) + await gitExecFileAsync( + ['fetch', '--no-tags', remote, `+refs/merge-requests/${mrIid}/head:${localRef}`], + { + ...localGitExecOptions, + timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS + } + ) + return localRef + } + if (!sshGitProvider) { + throw new Error('SSH Git provider is not available. Reconnect to this target and try again.') + } + return sshGitProvider.fetchGitLabMergeRequestHead(repo.path, remote, mrIid) +} diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 1e3f6f3e8..0473381c6 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -224,26 +224,25 @@ import { import { OrcaRuntimeService } from '../runtime/orca-runtime' import { hasLiveClaudePtys, markClaudePtySpawned } from '../claude-accounts/live-pty-gate' import * as livePtyGate from '../claude-accounts/live-pty-gate' -import { - encodePowerShellCommand, - getPowerShellOsc133Bootstrap -} from '../powershell-osc133-bootstrap' import { SSH_PTY_IDENTITY_MISMATCH_ERROR, SSH_SESSION_EXPIRED_ERROR } from '../providers/ssh-pty-errors' +import { resolveWindowsShellLaunchArgs } from '../providers/windows-shell-args' import { _resetWslCachesForTests, _setWslCachesForTests } from '../wsl' import { acquireWatcherRemovalGate } from './watcher-removal-gate' -const POWERSHELL_OSC133_ARGS = [ - '-NoLogo', - '-NoExit', - '-EncodedCommand', - encodePowerShellCommand(getPowerShellOsc133Bootstrap()) -] // Why: Windows resolves a bare PowerShell name to an absolute exe before ConPTY, else CreateProcessW fails with error 5 (PR #6537 / #5161). const RESOLVED_WINDOWS_POWERSHELL = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' const RESOLVED_PWSH7 = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' +// Why: default spawn cwd in the Windows UTF-8 suite is USERPROFILE; derive shell +// args from the production resolver so expectations stay in lockstep when the +// PowerShell bootstrap grows (e.g. cwd restore after profiles load). +const DEFAULT_WINDOWS_PTY_CWD = 'C:\\Users\\test' +function powerShellOsc133ArgsForCwd(cwd: string = DEFAULT_WINDOWS_PTY_CWD): string[] { + return resolveWindowsShellLaunchArgs(RESOLVED_WINDOWS_POWERSHELL, cwd, cwd).shellArgs +} +const POWERSHELL_OSC133_ARGS = powerShellOsc133ArgsForCwd() const TEST_CODEX_HOME = process.platform === 'win32' ? 'C:\\Users\\test\\AppData\\Roaming\\orca\\codex-runtime-home\\home' diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index f7af28221..5cd10e498 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -254,6 +254,14 @@ import { notifyWorktreesChanged } from './worktree-remote' import { invalidateAuthorizedRootsCache, resolveRegisteredWorktreePath } from './filesystem-auth' +import { + reviewHeadRemoteRefComponent, + REVIEW_HEAD_FETCH_TIMEOUT_MS +} from '../../shared/review-head-tracking-ref' + +// Why: durable review-head refs are scoped by remote identity (name + URL hash). +const ORIGIN_REMOTE_URL = 'git@github.com:org/repo.git' +const ORIGIN_HEAD_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_REMOTE_URL) import { __getDetectedWorktreeScanCacheStatsForTests, __resetDetectedWorktreeScanCacheForTests, @@ -2036,6 +2044,9 @@ describe('registerWorktreeHandlers', () => { } }) gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } if (args[0] === 'rev-parse') { return { stdout: 'abc123\n', stderr: '' } } @@ -2049,9 +2060,15 @@ describe('registerWorktreeHandlers', () => { isCrossRepository: true }) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1738/head'], { - cwd: '/workspace/repo' - }) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'fetch', + '--no-tags', + 'origin', + `+refs/pull/1738/head:refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/1738` + ], + { cwd: '/workspace/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) expect(result).toMatchObject({ baseBranch: 'abc123', headSha: 'abc123', @@ -3078,9 +3095,104 @@ describe('registerWorktreeHandlers', () => { }) }) + it('fetches a fork PR head via the SSH pull-head RPC, not git.exec', async () => { + const durableLocalRef = `refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/42` + const fetchGitHubPullRequestHead = vi.fn(async () => durableLocalRef) + const exec = vi.fn(async (args: string[]) => { + if (args[0] === 'remote') { + return { stdout: 'origin\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args[2] === `${durableLocalRef}^{commit}`) { + return { stdout: 'fork-head-sha\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) + getSshGitProviderMock.mockReturnValue({ + exec, + fetchGitHubPullRequestHead, + fetchRemoteTrackingRef: vi.fn() + }) + store.getRepo.mockReturnValue({ + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1', + worktreeBaseRef: null + }) + + const result = await handlers['worktrees:resolvePrBase'](null, { + repoId: 'repo-1', + prNumber: 42, + headRefName: 'contributor/fix', + isCrossRepository: true + }) + + expect(fetchGitHubPullRequestHead).toHaveBeenCalledWith('/workspace/repo', 'origin', 42) + expect(exec).not.toHaveBeenCalledWith(expect.arrayContaining(['fetch']), expect.anything()) + expect(result).toMatchObject({ + baseBranch: 'fork-head-sha', + headSha: 'fork-head-sha', + branchNameOverride: 'contributor/fix' + }) + }) + + it('fetches a fork PR head from origin, not the first remote, over SSH', async () => { + const durableLocalRef = `refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/42` + const fetchGitHubPullRequestHead = vi.fn(async () => durableLocalRef) + // Why: `fork` is listed first, but fork PR heads live on the hosting remote (origin). + const exec = vi.fn(async (args: string[]) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { + stdout: `git@github.com:org/${args[2] === 'origin' ? 'repo' : 'fork'}.git\n`, + stderr: '' + } + } + if (args[0] === 'remote') { + return { stdout: 'fork\norigin\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args[2] === `${durableLocalRef}^{commit}`) { + return { stdout: 'fork-head-sha\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) + getSshGitProviderMock.mockReturnValue({ + exec, + fetchGitHubPullRequestHead, + fetchRemoteTrackingRef: vi.fn() + }) + store.getRepo.mockReturnValue({ + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1', + worktreeBaseRef: null + }) + + const result = await handlers['worktrees:resolvePrBase'](null, { + repoId: 'repo-1', + prNumber: 42, + headRefName: 'contributor/fix', + isCrossRepository: true + }) + + expect(fetchGitHubPullRequestHead).toHaveBeenCalledWith('/workspace/repo', 'origin', 42) + expect(result).toMatchObject({ + baseBranch: 'fork-head-sha', + headSha: 'fork-head-sha', + branchNameOverride: 'contributor/fix' + }) + }) + 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] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } if (args[0] === 'rev-parse') { return { stdout: 'abc123\n', stderr: '' } } @@ -3094,9 +3206,15 @@ describe('registerWorktreeHandlers', () => { isCrossRepository: true }) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head'], { - cwd: '/workspace/repo' - }) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'fetch', + '--no-tags', + 'origin', + `+refs/pull/1849/head:refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/1849` + ], + { cwd: '/workspace/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) expect(result).toEqual({ baseBranch: 'abc123', headSha: 'abc123', @@ -3115,6 +3233,9 @@ describe('registerWorktreeHandlers', () => { 'fatal: could not find remote ref refs/heads/feat/onboarding-model-choice-782' ) } + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } if (args[0] === 'rev-parse') { return { stdout: 'abc123\n', stderr: '' } } @@ -3135,9 +3256,15 @@ describe('registerWorktreeHandlers', () => { ], { cwd: '/workspace/repo' } ) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head'], { - cwd: '/workspace/repo' - }) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + [ + 'fetch', + '--no-tags', + 'origin', + `+refs/pull/1849/head:refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/1849` + ], + { cwd: '/workspace/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) expect(result).toEqual({ baseBranch: 'abc123', headSha: 'abc123', @@ -3164,7 +3291,7 @@ describe('registerWorktreeHandlers', () => { }) expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( - ['fetch', 'origin', 'refs/pull/1849/head'], + expect.arrayContaining(['fetch', '--no-tags']), expect.anything() ) expect(result).toMatchObject({ diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 5acd40c4f..ccbf77951 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -49,9 +49,12 @@ import { import { gitExecFileAsync } from '../git/runner' import { withWorktreeSpan } from '../observability/instrumentation' import { resolveGitHubPrStartPoint } from '../github/pr-start-point' -import { fetchPrHeadTrackingRef } from '../github/pr-head-tracking-ref' +import { + fetchGitHubPullRequestHeadRef, + fetchPrHeadTrackingRef +} from '../github/pr-head-tracking-ref' import { pruneWorktreePRRefreshAliases } from '../github/pr-refresh-coordinator' -import { getDefaultRemote } from '../git/repo' +import { resolveGitHubReviewHeadRemote } from '../github/review-head-remote' import { listRepoWorktrees } from '../repo-worktrees' import { getSshGitProvider, requireSshGitProvider } from '../providers/ssh-git-dispatch' import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' @@ -1314,7 +1317,7 @@ export function registerWorktreeHandlers( } return provider.exec(args, repo.path) } - // Why: SSH repos can't fetch over the relay's read-only git.exec channel; route the PR-head fetch through the write-capable helper. + // Why: SSH review-head fetches require narrow write-capable RPCs. const fetchRemoteTrackingRef = (remote: string, branch: string): Promise => fetchPrHeadTrackingRef( repo, @@ -1323,6 +1326,14 @@ export function registerWorktreeHandlers( branch, { localGitExecOptions: getLocalProjectGitExecOptions(store, repo) } ) + const fetchPullRequestHeadRef = (remote: string, prNumber: number): Promise => + fetchGitHubPullRequestHeadRef( + repo, + repo.connectionId ? getSshGitProvider(repo.connectionId) : undefined, + remote, + prNumber, + { localGitExecOptions: getLocalProjectGitExecOptions(store, repo) } + ) return resolveGitHubPrStartPoint({ repoPath: repo.path, @@ -1334,18 +1345,16 @@ export function registerWorktreeHandlers( localGitOptions: getLocalProjectWorktreeGitOptions(store, repo), gitExec, fetchRemoteTrackingRef, - 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, getLocalProjectWorktreeGitOptions(store, repo)) - } + fetchPullRequestHeadRef, + // Why: one shared resolver for local and SSH so origin-vs-upstream + // cannot diverge by surface; it prefers the remote hosting the PR's project. + resolveRemote: () => + resolveGitHubReviewHeadRemote({ + repoPath: repo.path, + connectionId: repo.connectionId ?? null, + localGitOptions: getLocalProjectWorktreeGitOptions(store, repo), + gitExec + }) }) } ) diff --git a/src/main/providers/ssh-git-provider.test.ts b/src/main/providers/ssh-git-provider.test.ts index 1ee5b0f2b..5dc32a48e 100644 --- a/src/main/providers/ssh-git-provider.test.ts +++ b/src/main/providers/ssh-git-provider.test.ts @@ -895,14 +895,86 @@ describe('SshGitProvider', () => { }) }) - it('fetchGitLabMergeRequestHead sends git.fetchGitLabMergeRequestHead request', async () => { - await provider.fetchGitLabMergeRequestHead('/home/user/repo', 'origin', 42) + it('fetchGitLabMergeRequestHead sends the durable-ref git.fetchGitLabMergeRequestHeadRef request', async () => { + mux.request.mockResolvedValueOnce({ + localRef: 'refs/orca/merge-requests/origin-abc/42' + }) - expect(mux.request).toHaveBeenCalledWith('git.fetchGitLabMergeRequestHead', { + const localRef = await provider.fetchGitLabMergeRequestHead('/home/user/repo', 'origin', 42) + + expect(mux.request).toHaveBeenCalledWith('git.fetchGitLabMergeRequestHeadRef', { worktreePath: '/home/user/repo', remote: 'origin', mrIid: 42 }) + expect(localRef).toBe('refs/orca/merge-requests/origin-abc/42') + }) + + it('fetchGitLabMergeRequestHead maps old relays to the reconnect message', async () => { + const methodNotFound = Object.assign( + new Error('Method not found: git.fetchGitLabMergeRequestHeadRef'), + { code: -32601 } + ) + mux.request.mockRejectedValueOnce(methodNotFound) + + await expect( + provider.fetchGitLabMergeRequestHead('/home/user/repo', 'origin', 42) + ).rejects.toThrow( + 'This SSH host is running an older Orca relay that cannot fetch merge request heads. Reconnect to deploy the latest relay, then try again.' + ) + }) + + it('fetchGitLabMergeRequestHead rethrows non-method-not-found errors', async () => { + const error = new Error('fatal: could not read from remote repository') + mux.request.mockRejectedValueOnce(error) + + await expect( + provider.fetchGitLabMergeRequestHead('/home/user/repo', 'origin', 42) + ).rejects.toBe(error) + }) + + it('fetchGitHubPullRequestHead sends git.fetchGitHubPullRequestHead request', async () => { + mux.request.mockResolvedValueOnce({ localRef: 'refs/orca/pull/origin-abc/42' }) + + const localRef = await provider.fetchGitHubPullRequestHead('/home/user/repo', 'origin', 42) + + expect(mux.request).toHaveBeenCalledWith('git.fetchGitHubPullRequestHead', { + worktreePath: '/home/user/repo', + remote: 'origin', + prNumber: 42 + }) + expect(localRef).toBe('refs/orca/pull/origin-abc/42') + }) + + it('fetchGitHubPullRequestHead rejects relays that omit the durable localRef', async () => { + mux.request.mockResolvedValueOnce({}) + + await expect( + provider.fetchGitHubPullRequestHead('/home/user/repo', 'origin', 42) + ).rejects.toThrow('did not return the durable pull request head ref') + }) + + it('fetchGitHubPullRequestHead maps old relays to the reconnect message', async () => { + const methodNotFound = Object.assign( + new Error('Method not found: git.fetchGitHubPullRequestHead'), + { code: -32601 } + ) + mux.request.mockRejectedValueOnce(methodNotFound) + + await expect( + provider.fetchGitHubPullRequestHead('/home/user/repo', 'origin', 42) + ).rejects.toThrow( + 'This SSH host is running an older Orca relay that cannot fetch pull request heads. Reconnect to deploy the latest relay, then try again.' + ) + }) + + it('fetchGitHubPullRequestHead rethrows non-method-not-found errors', async () => { + const error = new Error('fatal: could not read from remote repository') + mux.request.mockRejectedValueOnce(error) + + await expect(provider.fetchGitHubPullRequestHead('/home/user/repo', 'origin', 42)).rejects.toBe( + error + ) }) it('getBranchDiff sends git.branchDiff request', async () => { diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index 1aa1cd271..00abdd630 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -47,6 +47,26 @@ function isJsonRpcMethodNotFoundError(error: unknown): boolean { return (error as { code?: unknown }).code === JsonRpcErrorCode.MethodNotFound } +// Why: the relay returns the durable ref it wrote; re-deriving it on the client +// can disagree (URL normalization) and leave resolve looking at the wrong path. +function readDurableReviewHeadLocalRef( + result: unknown, + kind: 'pull request' | 'merge request' +): string { + if (result && typeof result === 'object' && 'localRef' in result) { + const localRef = (result as { localRef: unknown }).localRef + if (typeof localRef === 'string') { + const trimmed = localRef.trim() + if (trimmed.startsWith('refs/orca/')) { + return trimmed + } + } + } + throw new Error( + `This SSH host did not return the durable ${kind} head ref. Reconnect to deploy the latest relay, then try again.` + ) +} + function formatStatusEntriesForCleanCheck(entries: GitStatusResult['entries']): string | undefined { if (entries.length === 0) { return undefined @@ -575,14 +595,58 @@ export class SshGitProvider implements IGitProvider { worktreePath: string, remote: string, mrIid: number - ): Promise { - await this.runWithDiffDedupeClear(async () => { - await this.mux.request('git.fetchGitLabMergeRequestHead', { - worktreePath, - remote, - mrIid + ): Promise { + try { + return await this.runWithDiffDedupeClear(async () => { + // Why: the durable-ref RPC is a NEW method name. Old relays only implement + // FETCH_HEAD-semantics git.fetchGitLabMergeRequestHead, so calling the ref + // variant makes them return -32601 rather than silently no-op the durable + // ref (which would leave the client resolving a stale/missing MR head). + const result = await this.mux.request('git.fetchGitLabMergeRequestHeadRef', { + worktreePath, + remote, + mrIid + }) + // Why: use the host-written path; a second client-side get-url can disagree. + return readDurableReviewHeadLocalRef(result, 'merge request') }) - }) + } catch (error) { + if (isJsonRpcMethodNotFoundError(error)) { + // Why: older SSH relays predate the durable-ref MR fetch; surface a + // reconnect prompt instead of a raw JSON-RPC method-not-found error. + throw new Error( + 'This SSH host is running an older Orca relay that cannot fetch merge request heads. Reconnect to deploy the latest relay, then try again.' + ) + } + throw error + } + } + + async fetchGitHubPullRequestHead( + worktreePath: string, + remote: string, + prNumber: number + ): Promise { + try { + return await this.runWithDiffDedupeClear(async () => { + const result = await this.mux.request('git.fetchGitHubPullRequestHead', { + worktreePath, + remote, + prNumber + }) + // Why: use the host-written path; a second client-side get-url can disagree. + return readDurableReviewHeadLocalRef(result, 'pull request') + }) + } catch (error) { + if (isJsonRpcMethodNotFoundError(error)) { + // Why: older SSH relays predate git.fetchGitHubPullRequestHead; surface a + // reconnect prompt instead of a raw JSON-RPC method-not-found error. + throw new Error( + 'This SSH host is running an older Orca relay that cannot fetch pull request heads. Reconnect to deploy the latest relay, then try again.' + ) + } + throw error + } } async getBranchDiff( diff --git a/src/main/runtime/orca-runtime-terminal-retirement.test.ts b/src/main/runtime/orca-runtime-terminal-retirement.test.ts index 0cfe19375..9c95156c7 100644 --- a/src/main/runtime/orca-runtime-terminal-retirement.test.ts +++ b/src/main/runtime/orca-runtime-terminal-retirement.test.ts @@ -10,6 +10,29 @@ import { OrcaRuntimeService } from './orca-runtime' const WORKTREE_ID = 'repo::/worktree' const REPO_ID = 'repo' +// Why: main's hydrateHeadlessMobileSessionTabsFromWorkspaceSession skips +// `${repoId}::…` keys whose repo is missing from getRepos (PR #9343). Tests +// that persist worktree sessions must advertise that repo as live. +const LIVE_REPO = { + id: REPO_ID, + path: '/worktree', + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1 +} as const + +function runtimeStore( + overrides: { + getWorkspaceSession?: () => WorkspaceSessionState + setWorkspaceSession?: (session: WorkspaceSessionState) => void + flushOrThrow?: () => void + } = {} +): never { + return { + getRepos: () => [LIVE_REPO], + ...overrides + } as never +} function makeSplitSnapshot(): RuntimeMobileSessionTabsSnapshot { const parentLayout = { @@ -230,7 +253,7 @@ describe('OrcaRuntimeService terminal surface retirement', () => { } session.terminalPtyIncarnationsByPaneKey = { 'tab:right': 'incarnation-current' } session.terminalTopologyRevisionByRepoId = { [REPO_ID]: 1 } - const runtime = new OrcaRuntimeService({ getWorkspaceSession: () => session } as never) + const runtime = new OrcaRuntimeService(runtimeStore({ getWorkspaceSession: () => session })) runtime.attachWindow(1) runtime.registerPty('pty-shared', WORKTREE_ID, null, { tabId: 'tab', @@ -362,7 +385,7 @@ describe('OrcaRuntimeService terminal surface retirement', () => { } } }) - const runtime = new OrcaRuntimeService({ getWorkspaceSession: () => session } as never) + const runtime = new OrcaRuntimeService(runtimeStore({ getWorkspaceSession: () => session })) runtime.attachWindow(1) runtime.registerPty('pty-right', WORKTREE_ID, null, { tabId: 'tab', @@ -389,12 +412,14 @@ describe('OrcaRuntimeService terminal surface retirement', () => { Object.assign(session, { terminalTopologyRevisionByRepoId: { [REPO_ID]: 1 } }) - const runtime = new OrcaRuntimeService({ - getWorkspaceSession: () => session, - setWorkspaceSession: (incoming: WorkspaceSessionState) => { - session = sanitizeWorkspaceSessionTerminalRetirements(incoming, session) - } - } as never) + const runtime = new OrcaRuntimeService( + runtimeStore({ + getWorkspaceSession: () => session, + setWorkspaceSession: (incoming: WorkspaceSessionState) => { + session = sanitizeWorkspaceSessionTerminalRetirements(incoming, session) + } + }) + ) await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`) await runtime.updateMobileSessionPaneLayout(`id:${WORKTREE_ID}`, { @@ -425,11 +450,13 @@ describe('OrcaRuntimeService terminal surface retirement', () => { ...getDefaultWorkspaceSession(), sleepingAgentSessionsByPaneKey: { 'tab:left': {} as never } } - const runtime = new OrcaRuntimeService({ - getWorkspaceSession: () => session, - setWorkspaceSession: vi.fn(), - flushOrThrow: vi.fn() - } as never) + const runtime = new OrcaRuntimeService( + runtimeStore({ + getWorkspaceSession: () => session, + setWorkspaceSession: vi.fn(), + flushOrThrow: vi.fn() + }) + ) runtime.attachWindow(1) syncSplit(runtime) @@ -444,10 +471,12 @@ describe('OrcaRuntimeService terminal surface retirement', () => { it('ignores a delayed exit from an older incarnation of a reused PTY id', async () => { const setWorkspaceSession = vi.fn() - const runtime = new OrcaRuntimeService({ - getWorkspaceSession: () => makePersistedSplitSession(), - setWorkspaceSession - } as never) + const runtime = new OrcaRuntimeService( + runtimeStore({ + getWorkspaceSession: () => makePersistedSplitSession(), + setWorkspaceSession + }) + ) runtime.attachWindow(1) syncSplit(runtime) runtime.registerPty('pty-left', WORKTREE_ID, null, { @@ -473,11 +502,13 @@ describe('OrcaRuntimeService terminal surface retirement', () => { it('retires a durable surface after reconnect proves a newer incarnation', async () => { const session = makePersistedSplitSession() const setWorkspaceSession = vi.fn() - const runtime = new OrcaRuntimeService({ - getWorkspaceSession: () => session, - setWorkspaceSession, - flushOrThrow: vi.fn() - } as never) + const runtime = new OrcaRuntimeService( + runtimeStore({ + getWorkspaceSession: () => session, + setWorkspaceSession, + flushOrThrow: vi.fn() + }) + ) runtime.attachWindow(1) syncSplit(runtime) runtime.registerPty('pty-left', WORKTREE_ID, null, { @@ -518,11 +549,13 @@ describe('OrcaRuntimeService terminal surface retirement', () => { const setWorkspaceSession = vi.fn((next: WorkspaceSessionState) => { session = next }) - const runtime = new OrcaRuntimeService({ - getWorkspaceSession: () => session, - setWorkspaceSession, - flushOrThrow: vi.fn() - } as never) + const runtime = new OrcaRuntimeService( + runtimeStore({ + getWorkspaceSession: () => session, + setWorkspaceSession, + flushOrThrow: vi.fn() + }) + ) runtime.attachWindow(1) const snapshot = makeSplitSnapshot() const sharedSnapshot: RuntimeMobileSessionTabsSnapshot = { @@ -580,11 +613,13 @@ describe('OrcaRuntimeService terminal surface retirement', () => { const session = makePersistedSplitSession() const setWorkspaceSession = vi.fn() const flushOrThrow = vi.fn() - const runtime = new OrcaRuntimeService({ - getWorkspaceSession: () => session, - setWorkspaceSession, - flushOrThrow - } as never) + const runtime = new OrcaRuntimeService( + runtimeStore({ + getWorkspaceSession: () => session, + setWorkspaceSession, + flushOrThrow + }) + ) runtime.attachWindow(1) runtime.syncWindowGraph(1, { tabs: [ @@ -632,13 +667,15 @@ describe('OrcaRuntimeService terminal surface retirement', () => { it('does not publish absence when the durable retirement flush fails', async () => { const session = makePersistedSplitSession() const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) - const runtime = new OrcaRuntimeService({ - getWorkspaceSession: () => session, - setWorkspaceSession: vi.fn(), - flushOrThrow: vi.fn(() => { - throw new Error('disk unavailable') + const runtime = new OrcaRuntimeService( + runtimeStore({ + getWorkspaceSession: () => session, + setWorkspaceSession: vi.fn(), + flushOrThrow: vi.fn(() => { + throw new Error('disk unavailable') + }) }) - } as never) + ) runtime.attachWindow(1) syncSplit(runtime) runtime.registerPty('pty-left', WORKTREE_ID, null, { diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 237a2b1f3..25768abd2 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -21,6 +21,14 @@ import type { WorkspaceSessionState } from '../../shared/types' import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types' +import { + reviewHeadRemoteRefComponent, + REVIEW_HEAD_FETCH_TIMEOUT_MS +} from '../../shared/review-head-tracking-ref' + +// Why: durable review-head refs are scoped by remote identity (name + URL hash). +const ORIGIN_REMOTE_URL = 'git@example.com:group/repo.git' +const ORIGIN_HEAD_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_REMOTE_URL) import { detectAgentStatusFromTitle, MAX_OSC_TITLE_CHARS } from '../../shared/agent-detection' import { addWorktree, @@ -215,6 +223,7 @@ const { getRepoSlugMock, getRepoUpstreamMock, getGitHubWorkItemMock, + getPullRequestPushTargetMock, getGitHubWorkItemByOwnerRepoMock, getGitHubWorkItemDetailsMock, getGitHubPRFileContentsMock, @@ -320,6 +329,7 @@ const { getRepoSlugMock: vi.fn().mockResolvedValue(null), getRepoUpstreamMock: vi.fn().mockResolvedValue(null), getGitHubWorkItemMock: vi.fn(), + getPullRequestPushTargetMock: vi.fn(), getGitHubWorkItemByOwnerRepoMock: vi.fn(), getGitHubWorkItemDetailsMock: vi.fn(), getGitHubPRFileContentsMock: vi.fn(), @@ -487,6 +497,7 @@ vi.mock('../github/client', async (importOriginal) => { getRepoSlug: getRepoSlugMock, getRepoUpstream: getRepoUpstreamMock, getWorkItem: getGitHubWorkItemMock, + getPullRequestPushTarget: getPullRequestPushTargetMock, getWorkItemByOwnerRepo: getGitHubWorkItemByOwnerRepoMock, getPRChecks: getGitHubPRChecksMock, rerunPRChecks: rerunGitHubPRChecksMock, @@ -699,6 +710,8 @@ function resetRuntimeTestMocks(): void { getRepoUpstreamMock.mockResolvedValue(null) getGitHubWorkItemMock.mockReset() getGitHubWorkItemMock.mockResolvedValue(null) + getPullRequestPushTargetMock.mockReset() + getPullRequestPushTargetMock.mockResolvedValue(null) getGitHubWorkItemByOwnerRepoMock.mockReset() getGitHubWorkItemByOwnerRepoMock.mockResolvedValue(null) getGitHubWorkItemDetailsMock.mockReset() @@ -1833,7 +1846,8 @@ describe('OrcaRuntimeService', () => { expect(hasPty).toHaveBeenCalledTimes(4) expect(hasPty).toHaveBeenCalledWith(floatingPtyId) expect(listProcesses).not.toHaveBeenCalled() - expect(getRepos).not.toHaveBeenCalled() + // Why: headless hydrate may consult getRepos to skip tabs for deleted repos; + // floating liveness must still avoid provider process inventory scans. }) it('advertises browser screencast only when a renderer window is available', () => { @@ -34392,6 +34406,9 @@ describe('OrcaRuntimeService', () => { if (args[0] === 'config') { return { stdout: 'origin\n', stderr: '' } } + if (args[0] === 'remote') { + return { stdout: 'origin\n', stderr: '' } + } if (args[0] === 'fetch') { return { stdout: '', stderr: '' } } @@ -34440,6 +34457,63 @@ describe('OrcaRuntimeService', () => { } }) + it('resolves SSH GitHub fork PR heads through the write-capable fetch RPC', async () => { + const remoteRepo = { + id: TEST_REPO_ID, + path: '/remote/repo', + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + connectionId: 'ssh-1' + } + const runtimeStore = { + ...store, + getRepos: () => [remoteRepo], + getRepo: (id: string) => (id === remoteRepo.id ? remoteRepo : undefined) + } + const provider = { + exec: vi.fn(async (args: string[]) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } + if (args[0] === 'remote') { + return { stdout: 'origin\n', stderr: '' } + } + if ( + args[0] === 'rev-parse' && + args[2] === `refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/42^{commit}` + ) { + return { stdout: 'remote-fork-pr-sha\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }), + fetchGitHubPullRequestHead: vi + .fn() + .mockResolvedValue(`refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/42`), + fetchRemoteTrackingRef: vi.fn().mockResolvedValue(undefined) + } + registerSshGitProvider('ssh-1', provider as never) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const result = await runtime.resolveManagedPrBase({ + repoSelector: 'id:repo-1', + prNumber: 42, + headRefName: 'contributor/fix', + isCrossRepository: true + }) + + expect(result).toEqual({ + baseBranch: 'remote-fork-pr-sha', + headSha: 'remote-fork-pr-sha', + branchNameOverride: 'contributor/fix' + }) + expect(provider.fetchGitHubPullRequestHead).toHaveBeenCalledWith('/remote/repo', 'origin', 42) + expect(provider.exec).not.toHaveBeenCalledWith( + expect.arrayContaining(['fetch']), + '/remote/repo' + ) + }) + it('resolves local GitLab fork MR bases from the target project MR head ref', async () => { const localRepo = { id: TEST_REPO_ID, @@ -34460,10 +34534,17 @@ describe('OrcaRuntimeService', () => { }) const runtime = new OrcaRuntimeService(runtimeStore as never) const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } if (args[0] === 'fetch') { return { stdout: '', stderr: '' } } - if (args[0] === 'rev-parse' && args[1] === '--verify' && args[2] === 'FETCH_HEAD') { + if ( + args[0] === 'rev-parse' && + args[1] === '--verify' && + args[2] === `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42^{commit}` + ) { return { stdout: 'fork-mr-sha\n', stderr: '' } } throw new Error(`unexpected git call: ${args.join(' ')}`) @@ -34482,16 +34563,214 @@ describe('OrcaRuntimeService', () => { baseBranch: 'fork-mr-sha', compareBaseRef: 'refs/remotes/origin/main' }) - expect(gitSpy).toHaveBeenCalledWith(['fetch', 'origin', 'refs/merge-requests/42/head'], { - cwd: TEST_REPO_PATH - }) + expect(gitSpy).toHaveBeenCalledWith( + [ + 'fetch', + '--no-tags', + 'origin', + `+refs/merge-requests/42/head:refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42` + ], + { cwd: TEST_REPO_PATH, timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) expect(gitSpy).toHaveBeenCalledWith( ['fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main'], { cwd: TEST_REPO_PATH } ) - expect(gitSpy).toHaveBeenCalledWith(['rev-parse', '--verify', 'FETCH_HEAD'], { - cwd: TEST_REPO_PATH + expect(gitSpy).toHaveBeenCalledWith( + ['rev-parse', '--verify', `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42^{commit}`], + { cwd: TEST_REPO_PATH } + ) + } finally { + gitSpy.mockRestore() + } + }) + + it('captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD', async () => { + const localRepo = { + id: TEST_REPO_ID, + path: TEST_REPO_PATH, + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + issueSourcePreference: 'origin' as const + } + const runtimeStore = { + ...store, + getRepos: () => [localRepo], + getRepo: (id: string) => (id === localRepo.id ? localRepo : undefined) + } + getGitLabProjectRefForRemoteMock.mockResolvedValue({ + host: 'gitlab.example', + path: 'group/repo' + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + // Why: simulate a concurrent `git fetch origin` clobbering FETCH_HEAD with the + // default-branch tip. The resolved base must come from the durable Orca MR ref. + const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } + if (args[0] === 'fetch') { + return { stdout: '', stderr: '' } + } + if (args[0] === 'rev-parse') { + const ref = args.at(-1) + if (ref === 'FETCH_HEAD') { + return { stdout: 'mainbranchtip000\n', stderr: '' } + } + if (ref === `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42^{commit}`) { + return { stdout: 'mrheadsha111\n', stderr: '' } + } + throw new Error(`unexpected rev-parse ref: ${ref}`) + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) + gitSpy.mockClear() + try { + const result = await runtime.resolveManagedMrBase({ + repoSelector: 'id:repo-1', + mrIid: 42, + sourceBranch: 'contrib/fix', + targetBranch: 'main', + isCrossRepository: true }) + + expect(result).toEqual({ + baseBranch: 'mrheadsha111', + compareBaseRef: 'refs/remotes/origin/main' + }) + expect(gitSpy).not.toHaveBeenCalledWith( + ['rev-parse', '--verify', 'FETCH_HEAD'], + expect.anything() + ) + } finally { + gitSpy.mockRestore() + } + }) + + it('keeps the durable MR head when the head fetch fails but the local ref resolves', async () => { + // Why: mirror compare-base soft-keep — a transient fetch failure must not + // fail the resolve when a prior fetch already pinned refs/orca/merge-requests/. + const localRepo = { + id: TEST_REPO_ID, + path: TEST_REPO_PATH, + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + issueSourcePreference: 'origin' as const + } + const runtimeStore = { + ...store, + getRepos: () => [localRepo], + getRepo: (id: string) => (id === localRepo.id ? localRepo : undefined) + } + getGitLabProjectRefForRemoteMock.mockResolvedValue({ + host: 'gitlab.example', + path: 'group/repo' + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } + if (args[0] === 'fetch' && args[1] === '--no-tags') { + throw new Error('fatal: unable to access repo: Could not resolve host: gitlab.example') + } + if (args[0] === 'fetch') { + return { stdout: '', stderr: '' } + } + if ( + args[0] === 'rev-parse' && + args[2] === `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42^{commit}` + ) { + return { stdout: 'pinned-mr-sha\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) + gitSpy.mockClear() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const result = await runtime.resolveManagedMrBase({ + repoSelector: 'id:repo-1', + mrIid: 42, + sourceBranch: 'contrib/fix', + targetBranch: 'main', + isCrossRepository: true + }) + + expect(result).toEqual({ + baseBranch: 'pinned-mr-sha', + compareBaseRef: 'refs/remotes/origin/main' + }) + } finally { + warnSpy.mockRestore() + gitSpy.mockRestore() + } + }) + + it.each([ + ["fatal: couldn't find remote ref refs/merge-requests/42/head", 'deleted MR / cleaned fork'], + ['Authentication failed. Check your remote credentials.', 'auth failure'], + [ + 'This SSH host is running an older Orca relay that cannot fetch merge request heads. Reconnect to deploy the latest relay, then try again.', + 'stale relay' + ] + ])('fails hard instead of soft-keeping the durable MR head on: %s', async (message) => { + // Why: soft-keep on a non-transient failure would check out a dead or + // unauthorized tip (or mask the reconnect prompt) with a success UX. + const localRepo = { + id: TEST_REPO_ID, + path: TEST_REPO_PATH, + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + issueSourcePreference: 'origin' as const + } + const runtimeStore = { + ...store, + getRepos: () => [localRepo], + getRepo: (id: string) => (id === localRepo.id ? localRepo : undefined) + } + getGitLabProjectRefForRemoteMock.mockResolvedValue({ + host: 'gitlab.example', + path: 'group/repo' + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } + if (args[0] === 'fetch' && args[1] === '--no-tags') { + throw new Error(message) + } + if (args[0] === 'fetch') { + return { stdout: '', stderr: '' } + } + if ( + args[0] === 'rev-parse' && + args[2] === `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42^{commit}` + ) { + return { stdout: 'pinned-mr-sha\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) + gitSpy.mockClear() + try { + const result = await runtime.resolveManagedMrBase({ + repoSelector: 'id:repo-1', + mrIid: 42, + sourceBranch: 'contrib/fix', + targetBranch: 'main', + isCrossRepository: true + }) + + expect(result).toEqual({ + error: `Failed to fetch refs/merge-requests/42/head: ${message}` + }) + expect(gitSpy).not.toHaveBeenCalledWith( + ['rev-parse', '--verify', `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42^{commit}`], + expect.anything() + ) } finally { gitSpy.mockRestore() } @@ -34529,10 +34808,17 @@ describe('OrcaRuntimeService', () => { } const runtime = new OrcaRuntimeService(runtimeStore as never) const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } if (args[0] === 'fetch') { return { stdout: '', stderr: '' } } - if (args[0] === 'rev-parse' && args[1] === '--verify' && args[2] === 'FETCH_HEAD') { + if ( + args[0] === 'rev-parse' && + args[1] === '--verify' && + args[2] === `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42^{commit}` + ) { return { stdout: 'fork-mr-sha\n', stderr: '' } } throw new Error(`unexpected git call: ${args.join(' ')}`) @@ -34555,14 +34841,23 @@ describe('OrcaRuntimeService', () => { null, { wslDistro: 'Ubuntu' } ) - expect(gitSpy).toHaveBeenCalledWith(['fetch', 'origin', 'refs/merge-requests/42/head'], { - cwd: TEST_REPO_PATH, - wslDistro: 'Ubuntu' - }) - expect(gitSpy).toHaveBeenCalledWith(['rev-parse', '--verify', 'FETCH_HEAD'], { + expect(gitSpy).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { cwd: TEST_REPO_PATH, wslDistro: 'Ubuntu' }) + expect(gitSpy).toHaveBeenCalledWith( + [ + 'fetch', + '--no-tags', + 'origin', + `+refs/merge-requests/42/head:refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42` + ], + { cwd: TEST_REPO_PATH, wslDistro: 'Ubuntu', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) + expect(gitSpy).toHaveBeenCalledWith( + ['rev-parse', '--verify', `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/42^{commit}`], + { cwd: TEST_REPO_PATH, wslDistro: 'Ubuntu' } + ) } finally { gitSpy.mockRestore() } @@ -34585,12 +34880,21 @@ describe('OrcaRuntimeService', () => { } const provider = { exec: vi.fn(async (args: string[]) => { - if (args[0] === 'rev-parse' && args[1] === '--verify' && args[2] === 'FETCH_HEAD') { + if (args[0] === 'remote' && args[1] === 'get-url') { + return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } + } + if ( + args[0] === 'rev-parse' && + args[1] === '--verify' && + args[2] === `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/77^{commit}` + ) { return { stdout: 'remote-fork-mr-sha\n', stderr: '' } } throw new Error(`unexpected git call: ${args.join(' ')}`) }), - fetchGitLabMergeRequestHead: vi.fn().mockResolvedValue(undefined), + fetchGitLabMergeRequestHead: vi + .fn() + .mockResolvedValue(`refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/77`), fetchRemoteTrackingRef: vi.fn().mockResolvedValue(undefined) } registerSshGitProvider('ssh-1', provider as never) @@ -34617,7 +34921,7 @@ describe('OrcaRuntimeService', () => { 'refs/remotes/origin/main' ) expect(provider.exec).toHaveBeenCalledWith( - ['rev-parse', '--verify', 'FETCH_HEAD'], + ['rev-parse', '--verify', `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/77^{commit}`], '/remote/repo' ) expect(getGitLabProjectRefForRemoteMock).toHaveBeenCalledWith( @@ -34750,6 +35054,129 @@ describe('OrcaRuntimeService', () => { } }) + it('keeps the MR compare base when the fetch fails but the local ref resolves', async () => { + // Why: a transient fetch failure must not drop a compare base we already have on disk. + const localRepo = { + id: TEST_REPO_ID, + path: TEST_REPO_PATH, + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + issueSourcePreference: 'origin' as const + } + const runtimeStore = { + ...store, + getRepos: () => [localRepo], + getRepo: (id: string) => (id === localRepo.id ? localRepo : undefined) + } + getGitLabProjectRefForRemoteMock.mockResolvedValue({ + host: 'gitlab.example', + path: 'group/repo' + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => { + if ( + args[0] === 'fetch' && + args[2] === '+refs/heads/feature/fix:refs/remotes/origin/feature/fix' + ) { + return { stdout: '', stderr: '' } + } + if (args[0] === 'fetch' && args[2] === '+refs/heads/main:refs/remotes/origin/main') { + throw new Error('fatal: unable to access repo: Could not resolve host: gitlab.example') + } + if (args[0] === 'rev-parse' && args[2] === 'origin/feature/fix') { + return { stdout: 'same-repo-mr-sha\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args[2] === 'refs/remotes/origin/main^{commit}') { + return { stdout: 'base-commit-sha\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }) + gitSpy.mockClear() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const result = await runtime.resolveManagedMrBase({ + repoSelector: 'id:repo-1', + mrIid: 80, + sourceBranch: 'feature/fix', + targetBranch: 'main' + }) + + expect(result).toEqual({ + baseBranch: 'origin/feature/fix', + compareBaseRef: 'refs/remotes/origin/main', + pushTarget: { remoteName: 'origin', branchName: 'feature/fix' } + }) + } finally { + warnSpy.mockRestore() + gitSpy.mockRestore() + } + }) + + it('keeps a cross-repo fork MR compare base when the fetch fails but the local ref resolves', async () => { + // Why: mirror the GitHub fork soft-fail-keep — a transient compare-base fetch + // failure must not drop a base we already have on disk onto the fork MR head SHA. + const remoteRepo = { + id: TEST_REPO_ID, + path: '/remote/repo', + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + connectionId: 'ssh-1', + issueSourcePreference: 'origin' as const + } + const runtimeStore = { + ...store, + getRepos: () => [remoteRepo], + getRepo: (id: string) => (id === remoteRepo.id ? remoteRepo : undefined) + } + const durableLocalRef = `refs/orca/merge-requests/${ORIGIN_HEAD_COMPONENT}/77` + const provider = { + exec: vi.fn(async (args: string[]) => { + if (args[0] === 'rev-parse' && args[2] === `${durableLocalRef}^{commit}`) { + return { stdout: 'remote-fork-mr-sha\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args[2] === 'refs/remotes/origin/main^{commit}') { + return { stdout: 'base-commit-sha\n', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }), + fetchGitLabMergeRequestHead: vi.fn().mockResolvedValue(durableLocalRef), + fetchRemoteTrackingRef: vi.fn(async () => { + throw new Error('fatal: unable to access repo: Could not resolve host: gitlab.example') + }) + } + registerSshGitProvider('ssh-1', provider as never) + getGlabKnownHostsMock.mockResolvedValue(['gitlab.com', 'git.internal']) + getGitLabProjectRefForRemoteMock.mockResolvedValue({ + host: 'gitlab.example', + path: 'group/repo' + }) + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + try { + const result = await runtime.resolveManagedMrBase({ + repoSelector: 'id:repo-1', + mrIid: 77, + sourceBranch: 'contrib/remote-fix', + targetBranch: 'main', + isCrossRepository: true + }) + + expect(result).toEqual({ + baseBranch: 'remote-fork-mr-sha', + compareBaseRef: 'refs/remotes/origin/main' + }) + expect(provider.exec).toHaveBeenCalledWith( + ['rev-parse', '--verify', 'refs/remotes/origin/main^{commit}'], + '/remote/repo' + ) + } finally { + warnSpy.mockRestore() + } + }) + it('creates the first terminal by id when duplicate repo entries expose the same path', async () => { const runtime = new OrcaRuntimeService(store) const spawn = vi.fn().mockResolvedValue({ id: 'pty-duplicate-path' }) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index b1c247372..c82a6383b 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -510,7 +510,19 @@ import { } from '../github/client' import type { GitHubPRBranchLookupOptions } from '../github/client' import { resolveGitHubPrStartPoint } from '../github/pr-start-point' -import { fetchPrHeadTrackingRef } from '../github/pr-head-tracking-ref' +import { + fetchGitHubPullRequestHeadRef, + fetchPrHeadTrackingRef +} from '../github/pr-head-tracking-ref' +import { + gitlabMergeRequestHeadLocalRef, + reviewHeadRemoteRefComponent +} from '../../shared/review-head-tracking-ref' +import { fetchGitLabMergeRequestHeadRef } from '../gitlab/mr-head-tracking-ref' +import { isTransientReviewHeadFetchError } from '../git/fetch-error-classification' +import { resolveGitHubReviewHeadRemote } from '../github/review-head-remote' +import { fetchCompareBaseRefWithLocalFallback } from '../git/compare-base-ref-fetch' +import { pickPreferredGitRemote } from '../../shared/preferred-git-remote' import { getWorkItemDetails, getPRFileContents } from '../github/work-item-details' import { getRateLimit } from '../github/rate-limit' import { @@ -20033,30 +20045,17 @@ export class OrcaRuntimeService { const gitExec = sshGitProvider ? (gitArgs: string[]) => sshGitProvider.exec(gitArgs, repo.path) : (gitArgs: string[]) => gitExecFileAsync(gitArgs, localGitExecOptions ?? { cwd: repo.path }) - const resolveRemote = sshGitProvider - ? async () => { - const { stdout } = await sshGitProvider.exec(['remote'], repo.path) - const remotes = stdout - .split('\n') - .map((line) => line.trim()) - .filter(Boolean) - if (remotes.includes('origin')) { - return 'origin' - } - if (remotes.length === 1) { - return remotes[0]! - } - if (remotes.length === 0) { - throw new Error('Repo has no configured git remotes.') - } - throw new Error( - `Repo has multiple remotes (${remotes.join(', ')}) and no default is configured.` - ) - } - : () => getDefaultRemote(repo.path, localWorktreeGitOptions) + // Why: one shared resolver for local and SSH so origin-vs-upstream cannot + // diverge by surface; it prefers the remote hosting the PR's project. + const resolveRemote = (): Promise => + resolveGitHubReviewHeadRemote({ + repoPath: repo.path, + connectionId: repo.connectionId ?? null, + localGitOptions: localWorktreeGitOptions, + gitExec + }) - // Why: SSH repos can't fetch over the relay's read-only git.exec channel, so - // route the PR head fetch through the write-capable helper instead of gitExec. + // Why: SSH review-head fetches require narrow write-capable RPCs. const fetchRemoteTrackingRef = (remote: string, branch: string): Promise => fetchPrHeadTrackingRef( repo, @@ -20065,6 +20064,14 @@ export class OrcaRuntimeService { branch, localGitExecOptions ? { localGitExecOptions } : {} ) + const fetchPullRequestHeadRef = (remote: string, prNumber: number): Promise => + fetchGitHubPullRequestHeadRef( + repo, + sshGitProvider, + remote, + prNumber, + localGitExecOptions ? { localGitExecOptions } : {} + ) return resolveGitHubPrStartPoint({ repoPath: repo.path, @@ -20076,6 +20083,7 @@ export class OrcaRuntimeService { localGitOptions: localWorktreeGitOptions, gitExec, fetchRemoteTrackingRef, + fetchPullRequestHeadRef, resolveRemote }) } @@ -20182,48 +20190,87 @@ export class OrcaRuntimeService { // failure must NOT abort the whole resolution — that would discard the // already-verified source-branch base and silently fall back to the repo // default branch. Degrade gracefully by dropping compareBaseRef instead. - const fetchCompareBaseRef = async (): Promise => { - if (!targetBranch || !compareBaseRef) { - return false - } - try { - await fetchRemoteTrackingRef(targetBranch, compareBaseRef) - return true - } catch (error) { - console.warn('[runtime:resolveManagedMrBase] optional compare-base fetch failed', { - remote, - targetBranch, - mrIid: args.mrIid, - error: error instanceof Error ? error.message.split('\n')[0] : String(error) - }) - return false - } - } + const fetchCompareBaseRef = (): Promise => + fetchCompareBaseRefWithLocalFallback({ + compareBaseRef, + fetchCompareBaseRef: (ref) => fetchRemoteTrackingRef(targetBranch, ref), + gitExec, + logLabel: '[runtime:resolveManagedMrBase]', + logContext: { remote, targetBranch, mrIid: args.mrIid } + }) if (isCrossRepository) { const mrRef = `refs/merge-requests/${args.mrIid}/head` - // Why: GitLab exposes fork MR heads on the target project, so mobile/SSH - // can match desktop without adding the contributor fork as a remote. + // Why: soft-keep needs identity when the fetch throws before returning a path. + // Success uses the path returned by the fetch itself (writer-authoritative). + let softKeepLocalRefPromise: Promise | undefined + const resolveSoftKeepLocalRef = (): Promise => { + softKeepLocalRefPromise ??= (async () => { + try { + const { stdout } = await gitExec(['remote', 'get-url', remote]) + const remoteUrl = stdout.trim() + if (!remoteUrl) { + return null + } + return gitlabMergeRequestHeadLocalRef( + reviewHeadRemoteRefComponent(remote, remoteUrl), + args.mrIid + ) + } catch { + return null + } + })() + return softKeepLocalRefPromise + } + const resolveDurableHeadSha = async (localRef: string | null): Promise => { + if (!localRef) { + return null + } + try { + const { stdout } = await gitExec(['rev-parse', '--verify', `${localRef}^{commit}`]) + return stdout.trim() || null + } catch { + return null + } + } try { - await (sshGitProvider - ? sshGitProvider.fetchGitLabMergeRequestHead(repo.path, remote, args.mrIid) - : gitExec(['fetch', remote, mrRef])) + const localRef = await fetchGitLabMergeRequestHeadRef( + repo, + sshGitProvider, + remote, + args.mrIid, + localGitExecOptions ? { localGitExecOptions } : {} + ) + const sha = await resolveDurableHeadSha(localRef) + if (!sha) { + return { error: `Could not resolve fork MR !${args.mrIid} head after fetch.` } + } + const compareBaseFetched = await fetchCompareBaseRef() + return { baseBranch: sha, ...(compareBaseFetched ? { compareBaseRef } : {}) } } catch (error) { const message = error instanceof Error ? error.message : String(error) + // Why: mirror compare-base — a transient transport failure must not fail + // the resolve when a prior fetch already pinned the durable head ref. A + // missing remote ref (deleted MR/fork), auth failure, or stale-relay + // error must fail hard: serving the durable ref there would check out a + // dead or unauthorized tip and mask the actionable error. + if (isTransientReviewHeadFetchError(error)) { + const localSha = await resolveDurableHeadSha(await resolveSoftKeepLocalRef()) + if (localSha) { + console.warn( + '[runtime:resolveManagedMrBase] MR head fetch failed; using durable local ref', + { + remote, + mrIid: args.mrIid, + error: message.split('\n')[0] + } + ) + const compareBaseFetched = await fetchCompareBaseRef() + return { baseBranch: localSha, ...(compareBaseFetched ? { compareBaseRef } : {}) } + } + } return { error: `Failed to fetch ${mrRef}: ${message.split('\n')[0]}` } } - let sha: string - try { - const { stdout } = await gitExec(['rev-parse', '--verify', 'FETCH_HEAD']) - sha = stdout.trim() - } catch { - return { error: `Could not resolve fork MR !${args.mrIid} head after fetch.` } - } - if (!sha) { - return { error: `Empty SHA resolving fork MR !${args.mrIid} head.` } - } - const compareBaseFetched = await fetchCompareBaseRef() - return { baseBranch: sha, ...(compareBaseFetched ? { compareBaseRef } : {}) } } try { @@ -20315,22 +20362,7 @@ export class OrcaRuntimeService { if (connectionId) { const provider = requireSshGitProvider(connectionId) const { stdout } = await provider.exec(['remote'], repoPath) - const remotes = stdout - .split('\n') - .map((line) => line.trim()) - .filter(Boolean) - if (remotes.includes('origin')) { - return 'origin' - } - if (remotes.length === 1) { - return remotes[0]! - } - if (remotes.length === 0) { - throw new Error('Repo has no configured git remotes.') - } - throw new Error( - `Repo has multiple remotes (${remotes.join(', ')}) and no default is configured.` - ) + return pickPreferredGitRemote(stdout.split('\n')) } return getDefaultRemote(repoPath, localGitOptions) } diff --git a/src/relay/git-handler.test.ts b/src/relay/git-handler.test.ts index 68e1982d4..15c4884f1 100644 --- a/src/relay/git-handler.test.ts +++ b/src/relay/git-handler.test.ts @@ -8,6 +8,7 @@ import { mkdtempSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { execFileSync } from 'node:child_process' import { MAX_RENDERED_DIFF_COMBINED_CHARACTERS } from '../shared/large-diff-render-limit' +import { reviewHeadRemoteRefComponent } from '../shared/review-head-tracking-ref' import { createMockDispatcher, gitInit, @@ -118,7 +119,9 @@ describe('GitHandler', () => { expect(methods).toContain('git.fetch') expect(methods).toContain('git.forkSync') expect(methods).toContain('git.fetchRemoteTrackingRef') + expect(methods).toContain('git.fetchGitHubPullRequestHead') expect(methods).toContain('git.fetchGitLabMergeRequestHead') + expect(methods).toContain('git.fetchGitLabMergeRequestHeadRef') expect(methods).toContain('git.push') expect(methods).toContain('git.pull') expect(methods).toContain('git.fastForward') @@ -1813,6 +1816,60 @@ describe('GitHandler', () => { ).rejects.toThrow('Remote-tracking ref does not match the requested remote and branch.') }) + it('fetches GitHub pull request heads through the narrow fetch RPC', async () => { + const bareDir = mkdtempSync(path.join(tmpdir(), 'relay-github-pr-bare-')) + try { + execFileSync('git', ['init', '--bare'], { cwd: bareDir, stdio: 'pipe' }) + gitInit(tmpDir) + writeFileSync(path.join(tmpDir, 'pr.txt'), 'head') + gitCommit(tmpDir, 'pr head') + const expected = execFileSync('git', ['rev-parse', 'HEAD'], { + cwd: tmpDir, + encoding: 'utf-8' + }).trim() + execFileSync('git', ['remote', 'add', 'origin', bareDir], { cwd: tmpDir, stdio: 'pipe' }) + execFileSync('git', ['push', 'origin', 'HEAD:refs/pull/42/head'], { + cwd: tmpDir, + stdio: 'pipe' + }) + + const result = (await dispatcher.callRequest('git.fetchGitHubPullRequestHead', { + worktreePath: tmpDir, + remote: 'origin', + prNumber: 42 + })) as { localRef: string } + + // The ref is scoped by remote identity so soft-keep can never serve + // another project's PR #42 out of the same object database. + const component = reviewHeadRemoteRefComponent('origin', bareDir) + expect(result.localRef).toBe(`refs/orca/pull/${component}/42`) + const actual = execFileSync('git', ['rev-parse', '--verify', result.localRef], { + cwd: tmpDir, + encoding: 'utf-8' + }).trim() + expect(actual).toBe(expected) + } finally { + await fs.rm(bareDir, { recursive: true, force: true }) + } + }) + + it('rejects invalid GitHub pull request head fetch requests', async () => { + await expect( + dispatcher.callRequest('git.fetchGitHubPullRequestHead', { + worktreePath: tmpDir, + remote: '-origin', + prNumber: 42 + }) + ).rejects.toThrow('GitHub pull request fetch remote must not start with "-".') + await expect( + dispatcher.callRequest('git.fetchGitHubPullRequestHead', { + worktreePath: tmpDir, + remote: 'origin', + prNumber: 0 + }) + ).rejects.toThrow('Invalid GitHub pull request fetch request.') + }) + it('fetches GitLab merge request heads through the narrow fetch RPC', async () => { const bareDir = mkdtempSync(path.join(tmpdir(), 'relay-gitlab-mr-bare-')) try { @@ -1830,13 +1887,60 @@ describe('GitHandler', () => { stdio: 'pipe' }) - await dispatcher.callRequest('git.fetchGitLabMergeRequestHead', { + const result = (await dispatcher.callRequest('git.fetchGitLabMergeRequestHead', { worktreePath: tmpDir, remote: 'origin', mrIid: 42 + })) as { localRef: string } + + // The head is fetched into a dedicated ref (not shared FETCH_HEAD) so a + // concurrent fetch can't retarget the caller's rev-parse of the checkout. + const component = reviewHeadRemoteRefComponent('origin', bareDir) + expect(result.localRef).toBe(`refs/orca/merge-requests/${component}/42`) + const actual = execFileSync('git', ['rev-parse', '--verify', result.localRef], { + cwd: tmpDir, + encoding: 'utf-8' + }).trim() + expect(actual).toBe(expected) + // Legacy contract: pre-durable-ref desktop clients call this method name + // and then resolve FETCH_HEAD, which a refspec fetch still writes. + const fetchHead = execFileSync('git', ['rev-parse', '--verify', 'FETCH_HEAD'], { + cwd: tmpDir, + encoding: 'utf-8' + }).trim() + expect(fetchHead).toBe(expected) + } finally { + await fs.rm(bareDir, { recursive: true, force: true }) + } + }) + + it('fetches GitLab merge request heads through the versioned durable-ref RPC', async () => { + const bareDir = mkdtempSync(path.join(tmpdir(), 'relay-gitlab-mr-ref-bare-')) + try { + execFileSync('git', ['init', '--bare'], { cwd: bareDir, stdio: 'pipe' }) + gitInit(tmpDir) + writeFileSync(path.join(tmpDir, 'mr.txt'), 'head') + gitCommit(tmpDir, 'mr head') + const expected = execFileSync('git', ['rev-parse', 'HEAD'], { + cwd: tmpDir, + encoding: 'utf-8' + }).trim() + execFileSync('git', ['remote', 'add', 'origin', bareDir], { cwd: tmpDir, stdio: 'pipe' }) + execFileSync('git', ['push', 'origin', 'HEAD:refs/merge-requests/77/head'], { + cwd: tmpDir, + stdio: 'pipe' }) - const actual = execFileSync('git', ['rev-parse', 'FETCH_HEAD'], { + // Why: new clients call the versioned name; old relays 404 it and prompt reconnect. + const result = (await dispatcher.callRequest('git.fetchGitLabMergeRequestHeadRef', { + worktreePath: tmpDir, + remote: 'origin', + mrIid: 77 + })) as { localRef: string } + + const component = reviewHeadRemoteRefComponent('origin', bareDir) + expect(result.localRef).toBe(`refs/orca/merge-requests/${component}/77`) + const actual = execFileSync('git', ['rev-parse', '--verify', result.localRef], { cwd: tmpDir, encoding: 'utf-8' }).trim() diff --git a/src/relay/git-handler.ts b/src/relay/git-handler.ts index 54dfa86a6..cdc0717b7 100644 --- a/src/relay/git-handler.ts +++ b/src/relay/git-handler.ts @@ -47,6 +47,7 @@ import { capGitStatusEntries, resolveGitStatusLimit } from '../shared/git-status import { checkIgnoredPathsOp } from './git-handler-check-ignore' import { resolveRelayPushTarget } from './git-handler-push-target' import { + isExecKilledError, isNoUpstreamError, normalizeGitErrorMessage, runPullWithDivergenceFallback @@ -71,6 +72,14 @@ import { syncForkDefaultBranch, validateGitForkSyncExpectedUpstream } from '../s import { InFlightPromiseDedupe, stableInFlightKey } from '../shared/in-flight-promise-dedupe' import { GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS } from '../shared/git-fetch-auto-maintenance' import { GitCapabilityCache } from '../shared/git-capability-cache' +import { + githubPullRequestHeadLocalRef, + gitlabMergeRequestHeadLocalRef, + isSafeReviewHeadFetchRemote, + isValidReviewHeadNumber, + reviewHeadRemoteRefComponent, + REVIEW_HEAD_FETCH_TIMEOUT_MS +} from '../shared/review-head-tracking-ref' import type { RelayFilesystemWatchRegistry } from './relay-filesystem-watch-registry' import { hasUnsupportedRevParsePathFormatEcho, @@ -216,9 +225,20 @@ export class GitHandler { this.dispatcher.onRequest('git.fetch', (p) => this.fetch(p)) this.dispatcher.onRequest('git.forkSync', (p, context) => this.forkSync(p, context)) this.dispatcher.onRequest('git.fetchRemoteTrackingRef', (p) => this.fetchRemoteTrackingRef(p)) + this.dispatcher.onRequest('git.fetchGitHubPullRequestHead', (p) => + this.fetchGitHubPullRequestHead(p) + ) this.dispatcher.onRequest('git.fetchGitLabMergeRequestHead', (p) => this.fetchGitLabMergeRequestHead(p) ) + // Why: the durable-ref variant is a distinct method name so an old relay + // (which only knows FETCH_HEAD-semantics git.fetchGitLabMergeRequestHead) + // returns -32601 and the client can prompt a reconnect instead of silently + // resolving a stale/missing ref. Both names share the durable handler: a + // refspec fetch still writes FETCH_HEAD, so old clients keep their semantics. + this.dispatcher.onRequest('git.fetchGitLabMergeRequestHeadRef', (p) => + this.fetchGitLabMergeRequestHead(p) + ) this.dispatcher.onRequest('git.push', (p) => this.push(p)) this.dispatcher.onRequest('git.pull', (p) => this.pull(p)) this.dispatcher.onRequest('git.fastForward', (p) => this.fastForward(p)) @@ -929,38 +949,94 @@ export class GitHandler { } } + // Why: the durable review-head ref embeds the remote's identity, and a + // missing remote must fail with an actionable message, not a raw fetch error. + private async reviewHeadRemoteComponent(worktreePath: string, remote: string): Promise { + let remoteUrl: string + try { + const { stdout } = await this.git(['remote', 'get-url', remote], worktreePath) + remoteUrl = stdout.trim() + } catch { + remoteUrl = '' + } + if (!remoteUrl) { + throw new Error(`Remote "${remote}" is not configured.`) + } + return reviewHeadRemoteRefComponent(remote, remoteUrl) + } + private async fetchGitLabMergeRequestHead(params: Record) { this.clearGitMutationReadCaches() const worktreePath = params.worktreePath as string const remote = params.remote const mrIid = params.mrIid try { - if (typeof remote !== 'string') { - throw new Error('Invalid GitLab merge request fetch request.') - } - if (typeof mrIid !== 'number' || !Number.isSafeInteger(mrIid) || mrIid <= 0) { + if (typeof remote !== 'string' || !isValidReviewHeadNumber(mrIid)) { throw new Error('Invalid GitLab merge request fetch request.') } const mergeRequestIid = mrIid - if (remote.startsWith('-')) { + if (!isSafeReviewHeadFetchRemote(remote)) { throw new Error('GitLab merge request fetch remote must not start with "-".') } try { - const { stdout } = await this.git(['remote'], worktreePath) - const remotes = stdout - .split(/\r?\n/) - .map((line) => line.trim()) - .filter(Boolean) - if (!remotes.includes(remote)) { - throw new Error(`Remote "${remote}" is not configured.`) - } - // Why: GitLab MR heads aren't refs/heads/*, so the remote-tracking fetch RPC can't represent fork MRs; keep this write path MR-only. + const remoteComponent = await this.reviewHeadRemoteComponent(worktreePath, remote) + // Why: GitLab fork heads need a dedicated write RPC and ref outside refs/heads/*. + // Return the exact written path so the client does not re-hash a second get-url. + const localRef = gitlabMergeRequestHeadLocalRef(remoteComponent, mergeRequestIid) await this.git( - ['fetch', '--no-tags', remote, `refs/merge-requests/${mergeRequestIid}/head`], - worktreePath + [ + 'fetch', + '--no-tags', + remote, + `+refs/merge-requests/${mergeRequestIid}/head:${localRef}` + ], + worktreePath, + { timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } ) + return { localRef } } catch (error) { + // Why: a timeout kill has no git stderr; name it so the client can classify it as transient. + if (isExecKilledError(error)) { + throw new Error( + `Fetching refs/merge-requests/${mergeRequestIid}/head from "${remote}" timed out.` + ) + } + throw new Error(normalizeGitErrorMessage(error, 'fetch')) + } + } finally { + this.clearGitMutationReadCaches() + } + } + + private async fetchGitHubPullRequestHead(params: Record) { + this.clearGitMutationReadCaches() + const worktreePath = params.worktreePath as string + const remote = params.remote + const prNumber = params.prNumber + try { + if (typeof remote !== 'string' || !isValidReviewHeadNumber(prNumber)) { + throw new Error('Invalid GitHub pull request fetch request.') + } + if (!isSafeReviewHeadFetchRemote(remote)) { + throw new Error('GitHub pull request fetch remote must not start with "-".') + } + + try { + const remoteComponent = await this.reviewHeadRemoteComponent(worktreePath, remote) + // Why: return the written path so resolve can rev-parse the same ref the host wrote. + const localRef = githubPullRequestHeadLocalRef(remoteComponent, prNumber) + await this.git( + ['fetch', '--no-tags', remote, `+refs/pull/${prNumber}/head:${localRef}`], + worktreePath, + { timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } + ) + return { localRef } + } catch (error) { + // Why: a timeout kill has no git stderr; name it so the client can classify it as transient. + if (isExecKilledError(error)) { + throw new Error(`Fetching refs/pull/${prNumber}/head from "${remote}" timed out.`) + } throw new Error(normalizeGitErrorMessage(error, 'fetch')) } } finally { diff --git a/src/renderer/src/components/editor/RichMarkdownEditor.tsx b/src/renderer/src/components/editor/RichMarkdownEditor.tsx index 04dfe8076..49a7db12c 100644 --- a/src/renderer/src/components/editor/RichMarkdownEditor.tsx +++ b/src/renderer/src/components/editor/RichMarkdownEditor.tsx @@ -1,6 +1,6 @@ import React, { useCallback, useEffect, useRef, useState } from 'react' import { useEditorState, type Editor } from '@tiptap/react' -import type { DiffComment, MarkdownDocument } from '../../../../shared/types' +import type { DiffComment } from '../../../../shared/types' import { useAppStore } from '@/store' import { selectWorktreeDiffComments } from '@/store/worktree-diff-comments-selector' import { useLocalImagePick } from './useLocalImagePick' @@ -30,31 +30,7 @@ import { formatSelectedHtmlSuperscriptLinkStatus, getSelectedHtmlSuperscriptLinkStatus } from './rich-markdown-selected-link-actions' - -type RichMarkdownEditorProps = { - fileId: string - content: string - filePath: string - worktreeId: string - externalSshTargetId?: string - runtimeEnvironmentId?: string | null - scrollCacheKey: string - onContentChange: (content: string) => void - onDirtyStateHint: (dirty: boolean) => void - onSave: (content: string) => void - onOpenDocLink?: (target: string) => void - markdownDocuments?: MarkdownDocument[] - showTableOfContents?: boolean - onCloseTableOfContents?: () => void - markdownAnnotationsEnabled?: boolean - markdownAnnotationFilePath?: string - markdownSourceLineOffset?: number - markdownReviewContent?: string - // Why: front-matter is stripped from the rich editor's content but we still - // want it visible to the user. It renders between the toolbar and the editor - // surface so the formatting toolbar stays at the top of the pane. - headerSlot?: React.ReactNode -} +import type { RichMarkdownEditorProps } from './rich-markdown-editor-props' export default function RichMarkdownEditor({ fileId, diff --git a/src/renderer/src/components/editor/rich-markdown-editor-props.ts b/src/renderer/src/components/editor/rich-markdown-editor-props.ts new file mode 100644 index 000000000..6a27e813f --- /dev/null +++ b/src/renderer/src/components/editor/rich-markdown-editor-props.ts @@ -0,0 +1,27 @@ +import type React from 'react' +import type { MarkdownDocument } from '../../../../shared/types' + +export type RichMarkdownEditorProps = { + fileId: string + content: string + filePath: string + worktreeId: string + externalSshTargetId?: string + runtimeEnvironmentId?: string | null + scrollCacheKey: string + onContentChange: (content: string) => void + onDirtyStateHint: (dirty: boolean) => void + onSave: (content: string) => void + onOpenDocLink?: (target: string) => void + markdownDocuments?: MarkdownDocument[] + showTableOfContents?: boolean + onCloseTableOfContents?: () => void + markdownAnnotationsEnabled?: boolean + markdownAnnotationFilePath?: string + markdownSourceLineOffset?: number + markdownReviewContent?: string + // Why: front-matter is stripped from the rich editor's content but we still + // want it visible to the user. It renders between the toolbar and the editor + // surface so the formatting toolbar stays at the top of the pane. + headerSlot?: React.ReactNode +} diff --git a/src/shared/git-binary-compatibility.test.ts b/src/shared/git-binary-compatibility.test.ts index eca98f167..29e1068a5 100644 --- a/src/shared/git-binary-compatibility.test.ts +++ b/src/shared/git-binary-compatibility.test.ts @@ -14,6 +14,11 @@ import { isUnsupportedWorktreeListZError } from './git-worktree-command-capabilities' import { gitCredentialPromptGuardEnv } from './git-credential-prompt-env' +import { + githubPullRequestHeadLocalRef, + gitlabMergeRequestHeadLocalRef, + reviewHeadRemoteRefComponent +} from './review-head-tracking-ref' const execFileAsync = promisify(execFile) const image = process.env.ORCA_GIT_COMPAT_IMAGE @@ -159,6 +164,29 @@ describeBinaryCompatibility('real Git binary compatibility', () => { } }) + it('fetches hosted review heads into dedicated refs', async () => { + const head = (await runGit(['rev-parse', 'HEAD'])).stdout.trim() + await runGit(['update-ref', 'refs/pull/42/head', head]) + await runGit(['update-ref', 'refs/merge-requests/42/head', head]) + + // Why: exercise the exact remote-identity-scoped ref shape the app generates. + const component = reviewHeadRemoteRefComponent('origin', 'git@github.com:org/repo.git') + const pullRef = githubPullRequestHeadLocalRef(component, 42) + const mergeRequestRef = gitlabMergeRequestHeadLocalRef(component, 42) + await expect( + runGit(['fetch', '--no-tags', '.', `+refs/pull/42/head:${pullRef}`]) + ).resolves.toBeDefined() + await expect( + runGit(['fetch', '--no-tags', '.', `+refs/merge-requests/42/head:${mergeRequestRef}`]) + ).resolves.toBeDefined() + await expect(runGit(['rev-parse', '--verify', pullRef])).resolves.toMatchObject({ + stdout: `${head}\n` + }) + await expect(runGit(['rev-parse', '--verify', mergeRequestRef])).resolves.toMatchObject({ + stdout: `${head}\n` + }) + }) + it('degrades indexed credential config safely at the Git 2.31 boundary', async () => { const guardEnv = gitCredentialPromptGuardEnv({}, 'linux') await expect(runGit(['status', '--short'], guardEnv)).resolves.toBeDefined() diff --git a/src/shared/git-remote-error.ts b/src/shared/git-remote-error.ts index 26475281b..478fa141d 100644 --- a/src/shared/git-remote-error.ts +++ b/src/shared/git-remote-error.ts @@ -104,6 +104,16 @@ export async function runPullWithDivergenceFallback( } } +// Why: an exec-level timeout kills the child (SIGTERM) with no git stderr line, +// so message inspection can't distinguish it from a real git failure. +export function isExecKilledError(error: unknown): boolean { + if (!error || typeof error !== 'object') { + return false + } + const { killed, signal } = error as { killed?: unknown; signal?: unknown } + return killed === true || (typeof signal === 'string' && signal.length > 0) +} + export type GitRemoteOperation = 'push' | 'pull' | 'fetch' | 'upstream' export function normalizeGitErrorMessage(error: unknown, operation?: GitRemoteOperation): string { diff --git a/src/shared/preferred-git-remote.test.ts b/src/shared/preferred-git-remote.test.ts new file mode 100644 index 000000000..ceb58c47d --- /dev/null +++ b/src/shared/preferred-git-remote.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' +import { pickPreferredGitRemote } from './preferred-git-remote' + +describe('pickPreferredGitRemote', () => { + it('prefers origin even when another remote is listed first', () => { + expect(pickPreferredGitRemote(['fork', 'origin'])).toBe('origin') + }) + + it('returns the sole remote when there is exactly one', () => { + expect(pickPreferredGitRemote(['upstream'])).toBe('upstream') + }) + + it('ignores blank lines from `git remote` output', () => { + expect(pickPreferredGitRemote(['fork\n', ' origin ', ''])).toBe('origin') + }) + + it('throws when there are no remotes', () => { + expect(() => pickPreferredGitRemote([''])).toThrow('Repo has no configured git remotes.') + }) + + it('refuses to guess between multiple non-origin remotes', () => { + expect(() => pickPreferredGitRemote(['fork', 'upstream'])).toThrow( + 'Repo has multiple remotes (fork, upstream) and no default is configured.' + ) + }) +}) diff --git a/src/shared/preferred-git-remote.ts b/src/shared/preferred-git-remote.ts new file mode 100644 index 000000000..cbef00466 --- /dev/null +++ b/src/shared/preferred-git-remote.ts @@ -0,0 +1,16 @@ +// Why: fork PR/MR heads live on the hosting remote (almost always `origin`); +// picking an arbitrary first remote (e.g. a contributor `fork`) fetches the +// wrong object. Prefer origin, then a lone remote, else refuse to guess. +export function pickPreferredGitRemote(remotes: readonly string[]): string { + const cleaned = remotes.map((line) => line.trim()).filter(Boolean) + if (cleaned.includes('origin')) { + return 'origin' + } + if (cleaned.length === 1) { + return cleaned[0]! + } + if (cleaned.length === 0) { + throw new Error('Repo has no configured git remotes.') + } + throw new Error(`Repo has multiple remotes (${cleaned.join(', ')}) and no default is configured.`) +} diff --git a/src/shared/review-head-tracking-ref.test.ts b/src/shared/review-head-tracking-ref.test.ts new file mode 100644 index 000000000..f9b25b806 --- /dev/null +++ b/src/shared/review-head-tracking-ref.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { + githubPullRequestHeadLocalRef, + gitlabMergeRequestHeadLocalRef, + reviewHeadRemoteRefComponent +} from './review-head-tracking-ref' + +describe('reviewHeadRemoteRefComponent', () => { + it('is deterministic for the same remote identity', () => { + const a = reviewHeadRemoteRefComponent('origin', 'git@github.com:org/repo.git') + const b = reviewHeadRemoteRefComponent('origin', 'git@github.com:org/repo.git') + expect(a).toBe(b) + expect(a).toMatch(/^origin-[0-9a-f]{16}$/) + }) + + it('separates same-named remotes pointing at different projects', () => { + // Why: this is the soft-keep identity guarantee — PR #42 of a repointed + // origin must never resolve to another project's pinned head. + const a = reviewHeadRemoteRefComponent('origin', 'git@github.com:org/repo.git') + const b = reviewHeadRemoteRefComponent('origin', 'git@github.com:other/repo.git') + expect(a).not.toBe(b) + }) + + it('sanitizes remote names into valid ref components', () => { + const component = reviewHeadRemoteRefComponent('weird remote/..name', 'https://example.com/r') + expect(component).toMatch(/^[A-Za-z0-9_-]+-[0-9a-f]{16}$/) + expect(reviewHeadRemoteRefComponent('...', 'https://example.com/r')).toMatch( + /^remote-[0-9a-f]{16}$/ + ) + }) + + it('builds provider refs under the orca namespace', () => { + const component = reviewHeadRemoteRefComponent('origin', 'git@github.com:org/repo.git') + expect(githubPullRequestHeadLocalRef(component, 42)).toBe(`refs/orca/pull/${component}/42`) + expect(gitlabMergeRequestHeadLocalRef(component, 77)).toBe( + `refs/orca/merge-requests/${component}/77` + ) + }) +}) diff --git a/src/shared/review-head-tracking-ref.ts b/src/shared/review-head-tracking-ref.ts new file mode 100644 index 000000000..d1f876ca3 --- /dev/null +++ b/src/shared/review-head-tracking-ref.ts @@ -0,0 +1,49 @@ +// Why: durable per-review refs avoid shared FETCH_HEAD races and keep the head +// commit reachable between resolve and worktree create. Client (main) and relay +// must agree on these paths, so both import from here rather than hardcoding. + +// Why: an unreachable or stalled remote must fail review-head resolve/create, +// not hang it; client and relay fetches share one bound. +export const REVIEW_HEAD_FETCH_TIMEOUT_MS = 60_000 + +// Why: refs are keyed by hosting identity (remote name + URL hash), not just +// PR/MR number — otherwise soft-keep after a failed fetch could serve PR #42 +// of a different project (repointed origin, switched preferred remote). +export function reviewHeadRemoteRefComponent(remote: string, remoteUrl: string): string { + return `${sanitizeRemoteRefComponent(remote)}-${fnv1a64Hex(remoteUrl.trim())}` +} + +export function githubPullRequestHeadLocalRef(remoteComponent: string, prNumber: number): string { + return `refs/orca/pull/${remoteComponent}/${prNumber}` +} + +export function gitlabMergeRequestHeadLocalRef(remoteComponent: string, mrIid: number): string { + return `refs/orca/merge-requests/${remoteComponent}/${mrIid}` +} + +// Why: remote names may hold chars invalid in a ref component; the URL hash +// carries uniqueness, so lossy sanitization here is safe. +function sanitizeRemoteRefComponent(remote: string): string { + const cleaned = remote.replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^[-.]+|\.+$/g, '') + return cleaned || 'remote' +} + +function fnv1a64Hex(value: string): string { + let hash = 0xcbf29ce484222325n + for (let index = 0; index < value.length; index++) { + hash ^= BigInt(value.charCodeAt(index)) + hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn + } + return hash.toString(16).padStart(16, '0') +} + +// Why: PR/MR numbers are interpolated into refspecs; relay and local fetch +// paths must reject non-integers with one shared guard. +export function isValidReviewHeadNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 +} + +// Why: a remote beginning with "-" would be parsed as a git option. +export function isSafeReviewHeadFetchRemote(remote: string): boolean { + return !remote.startsWith('-') +}