diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 3c42d1f5c..fddbde6e1 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -2483,6 +2483,7 @@ export async function getPRForBranchOutcome( : {}), ...(data.mergeStateStatus !== undefined ? { mergeStateStatus: data.mergeStateStatus } : {}), headSha: data.headRefOid, + ...(data.baseRefName ? { baseRefName: data.baseRefName } : {}), prRepo: dataRepo ?? undefined, headRepo: dataHeadRepo ?? undefined, conflictSummary diff --git a/src/main/github/pr-start-point.test.ts b/src/main/github/pr-start-point.test.ts index 24c129310..91d8e5ad0 100644 --- a/src/main/github/pr-start-point.test.ts +++ b/src/main/github/pr-start-point.test.ts @@ -26,8 +26,10 @@ describe('resolveGitHubPrStartPoint', () => { remoteUrl: 'git@github.com:contributor/orca.git' } }) - const fetchRemoteTrackingRef = vi.fn(async () => { - throw new Error('fatal: could not find remote ref') + const fetchRemoteTrackingRef = vi.fn(async (_remote: string, branch: string) => { + if (branch === 'feat/onboarding-model-choice-782') { + throw new Error('fatal: could not find remote ref') + } }) const gitExec = vi.fn(async (args: string[]) => { if (args[0] === 'rev-parse') { @@ -40,6 +42,7 @@ describe('resolveGitHubPrStartPoint', () => { repoPath: '/repo-root', prNumber: 1849, headRefName: 'feat/onboarding-model-choice-782', + baseRefName: 'main', gitExec, fetchRemoteTrackingRef, resolveRemote: async () => 'origin' @@ -49,9 +52,11 @@ describe('resolveGitHubPrStartPoint', () => { 'origin', 'feat/onboarding-model-choice-782' ) + expect(fetchRemoteTrackingRef).toHaveBeenCalledWith('origin', 'main') expect(gitExec).toHaveBeenCalledWith(['fetch', 'origin', 'refs/pull/1849/head']) expect(result).toEqual({ baseBranch: 'def456', + compareBaseRef: 'refs/remotes/origin/main', headSha: 'def456', branchNameOverride: 'feat/onboarding-model-choice-782', pushTarget: { @@ -124,6 +129,7 @@ describe('resolveGitHubPrStartPoint', () => { getWorkItemMock.mockResolvedValue({ type: 'pr', branchName: 'contributor/fix', + baseRefName: 'main', isCrossRepository: true }) getPullRequestPushTargetMock.mockResolvedValue({ @@ -152,6 +158,7 @@ describe('resolveGitHubPrStartPoint', () => { expect(getWorkItemMock).toHaveBeenCalledWith('/repo-root', 1738, 'pr', null) expect(result).toEqual({ baseBranch: 'abc123', + compareBaseRef: 'refs/remotes/origin/main', headSha: 'abc123', branchNameOverride: 'contributor/fix', pushTarget: { @@ -215,15 +222,18 @@ describe('resolveGitHubPrStartPoint', () => { repoPath: '/repo-root', prNumber: 42, headRefName: 'feature/add-feature', + baseRefName: 'develop', gitExec, fetchRemoteTrackingRef, resolveRemote: async () => 'origin' }) expect(fetchRemoteTrackingRef).toHaveBeenCalledWith('origin', 'feature/add-feature') + expect(fetchRemoteTrackingRef).toHaveBeenCalledWith('origin', 'develop') expect(gitExec).toHaveBeenCalledWith(['rev-parse', '--verify', 'origin/feature/add-feature']) expect(result).toEqual({ baseBranch: 'abc123', + compareBaseRef: 'refs/remotes/origin/develop', headSha: 'abc123', branchNameOverride: 'feature/add-feature', pushTarget: { remoteName: 'origin', branchName: 'feature/add-feature' } diff --git a/src/main/github/pr-start-point.ts b/src/main/github/pr-start-point.ts index 7740b4cbd..2a02c4f53 100644 --- a/src/main/github/pr-start-point.ts +++ b/src/main/github/pr-start-point.ts @@ -8,6 +8,7 @@ type ResolveGitHubPrStartPointArgs = { repoPath: string prNumber: number headRefName?: string + baseRefName?: string isCrossRepository?: boolean connectionId?: string | null gitExec: GitExec @@ -21,6 +22,7 @@ export async function resolveGitHubPrStartPoint( args: ResolveGitHubPrStartPointArgs ): Promise { let headRefName = args.headRefName?.trim() ?? '' + let baseRefName = args.baseRefName?.trim() ?? '' let isCrossRepository = args.isCrossRepository === true let pushTarget: GitPushTarget | undefined let maintainerCanModify: boolean | undefined @@ -50,6 +52,7 @@ export async function resolveGitHubPrStartPoint( return { error: `PR #${args.prNumber} not found.` } } headRefName = (item.branchName ?? '').trim() + baseRefName = (item.baseRefName ?? '').trim() if (!headRefName) { return { error: `PR #${args.prNumber} has no head branch.` } } @@ -69,6 +72,21 @@ export async function resolveGitHubPrStartPoint( return { error: error instanceof Error ? error.message : 'Could not resolve git remote.' } } + 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 fetchPullRequestHeadSha = async (): Promise<{ baseBranch: string } | { error: string }> => { const pullRef = `refs/pull/${args.prNumber}/head` try { @@ -100,11 +118,16 @@ export async function resolveGitHubPrStartPoint( if ('error' in result) { return result } + const compareBaseFetchError = await fetchCompareBaseRef() + if (compareBaseFetchError) { + return compareBaseFetchError + } // 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 } : {}), headSha: result.baseBranch, branchNameOverride: headRefName, ...(pushTarget ? { pushTarget } : {}), @@ -122,8 +145,13 @@ export async function resolveGitHubPrStartPoint( const result = await fetchPullRequestHeadSha() if (!('error' in result)) { await resolvePushTarget() + const compareBaseFetchError = await fetchCompareBaseRef() + if (compareBaseFetchError) { + return compareBaseFetchError + } return { ...result, + ...(compareBaseRef ? { compareBaseRef } : {}), headSha: result.baseBranch, branchNameOverride: headRefName, ...(pushTarget ? { pushTarget } : {}), @@ -147,9 +175,14 @@ export async function resolveGitHubPrStartPoint( if (!headSha) { return { error: `Empty SHA resolving PR #${args.prNumber} head.` } } + const compareBaseFetchError = await fetchCompareBaseRef() + if (compareBaseFetchError) { + return compareBaseFetchError + } return { baseBranch: headSha, + ...(compareBaseRef ? { compareBaseRef } : {}), headSha, branchNameOverride: headRefName, pushTarget: { remoteName: remote, branchName: headRefName } diff --git a/src/main/gitlab/mappers.ts b/src/main/gitlab/mappers.ts index 61ba93d27..55dffb89c 100644 --- a/src/main/gitlab/mappers.ts +++ b/src/main/gitlab/mappers.ts @@ -97,6 +97,7 @@ type GitLabMRRaw = { has_conflicts?: boolean detailed_merge_status?: string description?: string | null + target_branch?: string author?: { username?: string | null; avatar_url?: string | null } | null } @@ -110,6 +111,7 @@ export function mapMRInfo(data: GitLabMRRaw, pipelineStatus: CheckStatus): MRInf updatedAt: data.updated_at ?? data.updatedAt ?? '', mergeable: deriveMergeable(data), headSha: data.sha, + baseRefName: data.target_branch, // Why: detail-endpoint payloads include `description`; list endpoints // strip it. Pass through what's present rather than coercing missing // values to '' so downstream UIs can distinguish "no body authored" diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 24204477e..9320722f4 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -1572,9 +1572,9 @@ export async function createRemoteWorktree( const worktreeId = `${repo.id}::${created.path}` const now = Date.now() - // Why: persisted compare refs must survive local branches whose names look - // like remote labels, e.g. a local branch literally named "origin/main". - const metadataBaseRef = remoteTrackingBase?.ref ?? baseBranch + // Why: PR/MR-created worktrees can start from a head ref/SHA while Source + // Control must compare against the review target branch. + const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch let configuredPushTarget: GitPushTarget | undefined if (preparedPushTarget) { configuredPushTarget = await configureCreatedWorktreePushTargetSsh( @@ -2120,9 +2120,9 @@ export async function createLocalWorktree( const worktreeId = `${repo.id}::${created.path}` const now = Date.now() - // Why: persisted compare refs must survive local branches whose names look - // like remote labels, e.g. a local branch literally named "origin/main". - const metadataBaseRef = remoteTrackingBase?.ref ?? baseBranch + // Why: PR/MR-created worktrees can start from a head ref/SHA while Source + // Control must compare against the review target branch. + const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch const metaUpdates: Partial = { // Why: path-derived worktree IDs can be reused after external deletion. // Fresh creations must rotate instance identity so stale lineage cannot diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 5e74dc893..688d42a70 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -1060,6 +1060,7 @@ describe('registerWorktreeHandlers', () => { repoId: 'repo-1', name: 'fix-title', baseBranch: 'abc123', + compareBaseRef: 'refs/remotes/origin/main', branchNameOverride: 'feature/fix', linkedPR: 42, pushTarget: { remoteName: 'origin', branchName: 'feature/fix' } @@ -1076,9 +1077,54 @@ describe('registerWorktreeHandlers', () => { ['branch', '--set-upstream-to', 'origin/feature/fix', 'feature/fix'], { cwd: '/workspace/fix-title' } ) + expect(store.setWorktreeMeta).toHaveBeenCalledWith( + 'repo-1::/workspace/fix-title', + expect.objectContaining({ + baseRef: 'refs/remotes/origin/main', + linkedPR: 42 + }) + ) expect(getPRForBranchMock).toHaveBeenCalledWith('/workspace/repo', 'feature/fix') }) + it('persists an explicit compare base ahead of the checkout remote-tracking base', async () => { + runtimeStub.resolveRemoteTrackingBase.mockResolvedValueOnce({ + base: 'origin/source-branch', + remote: 'origin', + branch: 'source-branch', + ref: 'refs/remotes/origin/source-branch' + }) + runtimeStub.hasRemoteTrackingRef.mockResolvedValueOnce(true) + listWorktreesMock.mockResolvedValue([ + { + path: '/workspace/fix-title', + head: 'abc123', + branch: 'refs/heads/feature/fix', + isBare: false, + isMainWorktree: false + } + ]) + store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta) + + await handlers['worktrees:create'](null, { + repoId: 'repo-1', + name: 'fix-title', + baseBranch: 'origin/source-branch', + compareBaseRef: 'refs/remotes/origin/main', + branchNameOverride: 'feature/fix', + linkedGitLabMR: 7, + pushTarget: { remoteName: 'origin', branchName: 'feature/fix' } + }) + + expect(store.setWorktreeMeta).toHaveBeenCalledWith( + 'repo-1::/workspace/fix-title', + expect.objectContaining({ + baseRef: 'refs/remotes/origin/main', + linkedGitLabMR: 7 + }) + ) + }) + it('allows a selected Bitbucket PR branch override to match its remote push target', async () => { getBranchConflictKindMock.mockImplementation(async (_repoPath: string, branch: string) => branch === 'feature/bitbucket' ? 'remote' : null diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index a8356f394..4b70ae73e 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -1054,6 +1054,7 @@ export function registerWorktreeHandlers( repoId: string prNumber: number headRefName?: string + baseRefName?: string isCrossRepository?: boolean } ): Promise => { @@ -1090,6 +1091,7 @@ export function registerWorktreeHandlers( repoPath: repo.path, prNumber: args.prNumber, headRefName: args.headRefName, + baseRefName: args.baseRefName, isCrossRepository: args.isCrossRepository, connectionId: repo.connectionId ?? null, gitExec, @@ -1120,13 +1122,18 @@ export function registerWorktreeHandlers( repoId: string mrIid: number sourceBranch?: string + targetBranch?: string isCrossRepository?: boolean } - ): Promise<{ baseBranch: string; pushTarget?: GitPushTarget } | { error: string }> => { + ): Promise< + | { baseBranch: string; compareBaseRef?: string; pushTarget?: GitPushTarget } + | { error: string } + > => { return runtime.resolveManagedMrBase({ repoSelector: `id:${args.repoId}`, mrIid: args.mrIid, sourceBranch: args.sourceBranch, + targetBranch: args.targetBranch, isCrossRepository: args.isCrossRepository }) } diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 2609ebbbb..998f8a19d 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -15385,6 +15385,10 @@ describe('OrcaRuntimeService', () => { 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') { @@ -15401,13 +15405,21 @@ describe('OrcaRuntimeService', () => { repoSelector: 'id:repo-1', mrIid: 42, sourceBranch: 'contrib/fix', + targetBranch: 'main', isCrossRepository: true }) - expect(result).toEqual({ baseBranch: 'fork-mr-sha' }) + expect(result).toEqual({ + 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', 'origin', '+refs/heads/main:refs/remotes/origin/main'], + { cwd: TEST_REPO_PATH } + ) expect(gitSpy).toHaveBeenCalledWith(['rev-parse', '--verify', 'FETCH_HEAD'], { cwd: TEST_REPO_PATH }) @@ -15440,7 +15452,8 @@ describe('OrcaRuntimeService', () => { return { stdout: 'remote-fork-mr-sha\n', stderr: '' } } throw new Error(`unexpected git call: ${args.join(' ')}`) - }) + }), + fetchRemoteTrackingRef: vi.fn().mockResolvedValue(undefined) } registerSshGitProvider('ssh-1', provider as never) getGlabKnownHostsMock.mockResolvedValue(['gitlab.com', 'git.internal']) @@ -15450,14 +15463,24 @@ describe('OrcaRuntimeService', () => { repoSelector: 'id:repo-1', mrIid: 77, sourceBranch: 'contrib/remote-fix', + targetBranch: 'main', isCrossRepository: true }) - expect(result).toEqual({ baseBranch: 'remote-fork-mr-sha' }) + expect(result).toEqual({ + baseBranch: 'remote-fork-mr-sha', + compareBaseRef: 'refs/remotes/origin/main' + }) expect(provider.exec).toHaveBeenCalledWith( ['fetch', 'origin', 'refs/merge-requests/77/head'], '/remote/repo' ) + expect(provider.fetchRemoteTrackingRef).toHaveBeenCalledWith( + '/remote/repo', + 'origin', + 'main', + 'refs/remotes/origin/main' + ) expect(provider.exec).toHaveBeenCalledWith( ['rev-parse', '--verify', 'FETCH_HEAD'], '/remote/repo' diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index df0a98236..dedb64cf4 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -9949,6 +9949,7 @@ export class OrcaRuntimeService { repoSelector: string name: string baseBranch?: string + compareBaseRef?: string branchNameOverride?: string linkedIssue?: number | null linkedPR?: number | null @@ -10418,9 +10419,9 @@ export class OrcaRuntimeService { const worktreeId = `${repo.id}::${created.path}` const now = Date.now() - // Why: persisted compare refs must survive local branches whose names look - // like remote labels, e.g. a local branch literally named "origin/main". - const metadataBaseRef = remoteTrackingBase?.ref ?? baseBranch + // Why: PR/MR-created worktrees can start from a head ref/SHA while Source + // Control must compare against the review target branch. + const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch const displayNameMeta = requestedDisplayName ? { displayName: requestedDisplayName } : shouldSetDisplayName(effectiveRequestedName, branchName, effectiveSanitizedName) @@ -10722,6 +10723,7 @@ export class OrcaRuntimeService { args: { name: string baseBranch?: string + compareBaseRef?: string branchNameOverride?: string linkedIssue?: number | null linkedPR?: number | null @@ -10767,6 +10769,7 @@ export class OrcaRuntimeService { name: args.name, ...(args.displayName ? { displayName: args.displayName } : {}), ...(args.baseBranch ? { baseBranch: args.baseBranch } : {}), + ...(args.compareBaseRef ? { compareBaseRef: args.compareBaseRef } : {}), ...(args.branchNameOverride ? { branchNameOverride: args.branchNameOverride } : {}), ...(args.runHooks ? { setupDecision: 'run' as const } : {}), ...(!args.runHooks && args.setupDecision ? { setupDecision: args.setupDecision } : {}), @@ -11459,6 +11462,7 @@ export class OrcaRuntimeService { repoSelector: string prNumber: number headRefName?: string + baseRefName?: string isCrossRepository?: boolean }): Promise { if (!this.store) { @@ -11508,6 +11512,7 @@ export class OrcaRuntimeService { repoPath: repo.path, prNumber: args.prNumber, headRefName: args.headRefName, + baseRefName: args.baseRefName, isCrossRepository: args.isCrossRepository, connectionId: repo.connectionId ?? null, gitExec, @@ -11520,8 +11525,11 @@ export class OrcaRuntimeService { repoSelector: string mrIid: number sourceBranch?: string + targetBranch?: string isCrossRepository?: boolean - }): Promise<{ baseBranch: string; pushTarget?: GitPushTarget } | { error: string }> { + }): Promise< + { baseBranch: string; compareBaseRef?: string; pushTarget?: GitPushTarget } | { error: string } + > { if (!this.store) { throw new Error('runtime_unavailable') } @@ -11540,6 +11548,7 @@ export class OrcaRuntimeService { : (gitArgs: string[]) => gitExecFileAsync(gitArgs, { cwd: repo.path }) let sourceBranch = args.sourceBranch?.trim() ?? '' + let targetBranch = args.targetBranch?.trim() ?? '' let isCrossRepository = args.isCrossRepository === true if (!sourceBranch) { @@ -11574,6 +11583,7 @@ export class OrcaRuntimeService { return { error: `MR !${args.mrIid} not found.` } } sourceBranch = (item.branchName ?? '').trim() + targetBranch = (item.baseRefName ?? '').trim() if (!sourceBranch) { return { error: `MR !${args.mrIid} has no source branch.` } } @@ -11592,6 +11602,21 @@ export class OrcaRuntimeService { } catch (error) { return { error: error instanceof Error ? error.message : 'Could not resolve git remote.' } } + const compareBaseRef = targetBranch ? `refs/remotes/${remote}/${targetBranch}` : undefined + const fetchTargetBranch = async (): Promise<{ error: string } | null> => { + if (!targetBranch || !compareBaseRef) { + return null + } + try { + await (sshGitProvider + ? sshGitProvider.fetchRemoteTrackingRef(repo.path, remote, targetBranch, compareBaseRef) + : gitExec(['fetch', remote, `+refs/heads/${targetBranch}:${compareBaseRef}`])) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return { error: `Failed to fetch ${remote}/${targetBranch}: ${message.split('\n')[0]}` } + } + return null + } if (isCrossRepository) { const mrRef = `refs/merge-requests/${args.mrIid}/head` @@ -11613,7 +11638,11 @@ export class OrcaRuntimeService { if (!sha) { return { error: `Empty SHA resolving fork MR !${args.mrIid} head.` } } - return { baseBranch: sha } + const targetFetchError = await fetchTargetBranch() + if (targetFetchError) { + return targetFetchError + } + return { baseBranch: sha, ...(compareBaseRef ? { compareBaseRef } : {}) } } try { @@ -11633,7 +11662,15 @@ export class OrcaRuntimeService { } catch { return { error: `Remote ref ${remoteRef} does not exist after fetch.` } } - return { baseBranch: remoteRef, pushTarget: { remoteName: remote, branchName: sourceBranch } } + const targetFetchError = await fetchTargetBranch() + if (targetFetchError) { + return targetFetchError + } + return { + baseBranch: remoteRef, + ...(compareBaseRef ? { compareBaseRef } : {}), + pushTarget: { remoteName: remote, branchName: sourceBranch } + } } private async resolveGitLabIssueSourceRemote( diff --git a/src/main/runtime/rpc/methods/worktree-schemas.ts b/src/main/runtime/rpc/methods/worktree-schemas.ts index 72dc48dd6..0d3ffeab4 100644 --- a/src/main/runtime/rpc/methods/worktree-schemas.ts +++ b/src/main/runtime/rpc/methods/worktree-schemas.ts @@ -55,6 +55,7 @@ export const WorktreeCreate = z .pipe(z.string().min(1, 'Missing repo selector')), name: OptionalString, baseBranch: OptionalString, + compareBaseRef: OptionalString, branchNameOverride: OptionalString, linkedIssue: TriStateLinkedIssue, linkedPR: TriStateLinkedIssue, @@ -231,6 +232,7 @@ export const WorktreeResolvePrBase = z.object({ .transform((v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)) .pipe(z.number().int().positive('Missing PR number')), headRefName: OptionalString, + baseRefName: OptionalString, isCrossRepository: OptionalBoolean }) @@ -244,5 +246,6 @@ export const WorktreeResolveMrBase = z.object({ .transform((v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)) .pipe(z.number().int().positive('Missing MR number')), sourceBranch: OptionalString, + targetBranch: OptionalString, isCrossRepository: OptionalBoolean }) diff --git a/src/main/runtime/rpc/methods/worktree.ts b/src/main/runtime/rpc/methods/worktree.ts index bdfa9c766..5f09061dc 100644 --- a/src/main/runtime/rpc/methods/worktree.ts +++ b/src/main/runtime/rpc/methods/worktree.ts @@ -63,6 +63,7 @@ export const WORKTREE_METHODS: RpcMethod[] = [ repoSelector: params.repo, name: params.name ?? '', baseBranch: params.baseBranch, + compareBaseRef: params.compareBaseRef, branchNameOverride: params.branchNameOverride, linkedIssue: params.linkedIssue, linkedPR: params.linkedPR, @@ -172,6 +173,7 @@ export const WORKTREE_METHODS: RpcMethod[] = [ repoSelector: params.repo, prNumber: params.prNumber, headRefName: params.headRefName, + baseRefName: params.baseRefName, isCrossRepository: params.isCrossRepository }) }), @@ -183,6 +185,7 @@ export const WORKTREE_METHODS: RpcMethod[] = [ repoSelector: params.repo, mrIid: params.mrIid, sourceBranch: params.sourceBranch, + targetBranch: params.targetBranch, isCrossRepository: params.isCrossRepository }) }), diff --git a/src/main/source-control/forge-provider.ts b/src/main/source-control/forge-provider.ts index de9eb9be2..f9214c965 100644 --- a/src/main/source-control/forge-provider.ts +++ b/src/main/source-control/forge-provider.ts @@ -82,6 +82,7 @@ function mapGitLabReview(mr: MRInfo): HostedReviewInfo { updatedAt: mr.updatedAt, mergeable: mr.mergeable, ...(mr.headSha ? { headSha: mr.headSha } : {}), + ...(mr.baseRefName ? { baseRefName: mr.baseRefName } : {}), ...(mr.conflictSummary ? { conflictSummary: mr.conflictSummary } : {}) } } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 1d9863b73..3e056345f 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -936,6 +936,7 @@ export type PreloadApi = { repoId: string prNumber: number headRefName?: string + baseRefName?: string isCrossRepository?: boolean }) => Promise /** GitLab parallel of resolvePrBase. For same-project MRs returns @@ -945,8 +946,12 @@ export type PreloadApi = { repoId: string mrIid: number sourceBranch?: string + targetBranch?: string isCrossRepository?: boolean - }) => Promise<{ baseBranch: string; pushTarget?: GitPushTarget } | { error: string }> + }) => Promise< + | { baseBranch: string; compareBaseRef?: string; pushTarget?: GitPushTarget } + | { error: string } + > remove: (args: { worktreeId: string force?: boolean diff --git a/src/renderer/src/components/right-sidebar/SourceControl.compare-summary.test.ts b/src/renderer/src/components/right-sidebar/SourceControl.compare-summary.test.ts index 0994c5a32..72d8bac88 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.compare-summary.test.ts +++ b/src/renderer/src/components/right-sidebar/SourceControl.compare-summary.test.ts @@ -3,6 +3,7 @@ import { CompareSummary, CompareSummaryToolbarButton, resolveSourceControlBaseRef, + resolveSourceControlPickerBaseRef, shouldShowCompareSummary } from './SourceControl' import type { GitBranchCompareSummary } from '../../../../shared/types' @@ -80,12 +81,113 @@ describe('SourceControl compare summary', () => { expect( resolveSourceControlBaseRef({ worktreeBaseRef: 'refs/remotes/origin/main', + reviewBaseRefName: 'main', repoBaseRef: 'main', defaultBaseRef: 'origin/main' }) ).toBe('refs/remotes/origin/main') }) + it('repairs stale PR head SHA compare bases from linked review metadata', () => { + expect( + resolveSourceControlBaseRef({ + worktreeBaseRef: '06103ea1889e259fd771b93d206e14c9a4c66391', + reviewBaseRefName: 'main', + repoBaseRef: null, + defaultBaseRef: 'origin/main' + }) + ).toBe('origin/main') + }) + + it('keeps non-SHA worktree base refs ahead of review metadata', () => { + expect( + resolveSourceControlBaseRef({ + worktreeBaseRef: 'refs/remotes/upstream/release', + reviewBaseRefName: 'main', + repoBaseRef: null, + defaultBaseRef: 'origin/main' + }) + ).toBe('refs/remotes/upstream/release') + }) + + it('rewrites stale SHA compare bases using the configured remote style', () => { + expect( + resolveSourceControlBaseRef({ + worktreeBaseRef: '06103ea1889e259fd771b93d206e14c9a4c66391', + reviewBaseRefName: 'release/next', + repoBaseRef: null, + defaultBaseRef: 'refs/remotes/upstream/main' + }) + ).toBe('refs/remotes/upstream/release/next') + + expect( + resolveSourceControlBaseRef({ + worktreeBaseRef: '06103ea1889e259fd771b93d206e14c9a4c66391', + reviewBaseRefName: 'release', + repoBaseRef: null, + defaultBaseRef: 'upstream/main' + }) + ).toBe('upstream/release') + }) + + it('does not treat nested branch suffix matches as the review target', () => { + expect( + resolveSourceControlBaseRef({ + worktreeBaseRef: '06103ea1889e259fd771b93d206e14c9a4c66391', + reviewBaseRefName: 'main', + repoBaseRef: null, + defaultBaseRef: 'origin/release/main' + }) + ).toBe('origin/main') + + expect( + resolveSourceControlBaseRef({ + worktreeBaseRef: '06103ea1889e259fd771b93d206e14c9a4c66391', + reviewBaseRefName: 'main', + repoBaseRef: null, + defaultBaseRef: 'refs/remotes/upstream/release/main' + }) + ).toBe('refs/remotes/upstream/main') + }) + + it('keeps exact slash-containing target branch matches', () => { + expect( + resolveSourceControlBaseRef({ + worktreeBaseRef: '06103ea1889e259fd771b93d206e14c9a4c66391', + reviewBaseRefName: 'release/main', + repoBaseRef: null, + defaultBaseRef: 'origin/release/main' + }) + ).toBe('origin/release/main') + }) + + it('waits for a remote candidate before repairing stale SHA compare bases', () => { + expect( + resolveSourceControlBaseRef({ + worktreeBaseRef: '06103ea1889e259fd771b93d206e14c9a4c66391', + reviewBaseRefName: 'release', + repoBaseRef: null, + defaultBaseRef: null + }) + ).toBeNull() + }) + + it('shows the repaired pinned base ref in the base picker', () => { + expect( + resolveSourceControlPickerBaseRef({ + pinnedBaseRef: '06103ea1889e259fd771b93d206e14c9a4c66391', + effectiveBaseRef: 'origin/main' + }) + ).toBe('origin/main') + + expect( + resolveSourceControlPickerBaseRef({ + pinnedBaseRef: null, + effectiveBaseRef: 'origin/main' + }) + ).toBeUndefined() + }) + it('falls back to repo and default base refs when worktree metadata is absent', () => { expect( resolveSourceControlBaseRef({ diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index b06d62934..4de275e65 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -257,15 +257,100 @@ type CreatePrIntentNotice = { export function resolveSourceControlBaseRef(input: { worktreeBaseRef?: string | null + reviewBaseRefName?: string | null repoBaseRef?: string | null defaultBaseRef?: string | null }): string | null { - return ( - input.worktreeBaseRef?.trim() || - input.repoBaseRef?.trim() || - input.defaultBaseRef?.trim() || - null - ) + const worktreeBaseRef = input.worktreeBaseRef?.trim() || null + const hasReviewBaseRefName = Boolean(input.reviewBaseRefName?.trim()) + const reviewBaseRef = resolveHostedReviewCompareBaseRef(input.reviewBaseRefName, [ + input.repoBaseRef, + input.defaultBaseRef + ]) + if (worktreeBaseRef && isFullGitCommitOid(worktreeBaseRef) && hasReviewBaseRefName) { + return reviewBaseRef + } + return worktreeBaseRef || input.repoBaseRef?.trim() || input.defaultBaseRef?.trim() || null +} + +export function resolveSourceControlPickerBaseRef(input: { + pinnedBaseRef?: string | null + effectiveBaseRef?: string | null +}): string | undefined { + const pinnedBaseRef = input.pinnedBaseRef?.trim() + if (!pinnedBaseRef) { + return undefined + } + return input.effectiveBaseRef?.trim() || pinnedBaseRef +} + +function isFullGitCommitOid(value: string): boolean { + return /^[0-9a-f]{40}$/i.test(value) +} + +function resolveHostedReviewCompareBaseRef( + baseRefName: string | null | undefined, + candidates: (string | null | undefined)[] +): string | null { + const branch = baseRefName?.trim() + if (!branch) { + return null + } + for (const candidate of candidates) { + const trimmed = candidate?.trim() + if (!trimmed) { + continue + } + if (getCompareBaseCandidateBranchName(trimmed) === branch) { + return trimmed + } + } + for (const candidate of candidates) { + const rewritten = rewriteCompareBaseBranchFromCandidate(candidate, branch) + if (rewritten) { + return rewritten + } + } + return null +} + +function getCompareBaseCandidateBranchName(candidate: string): string { + const remoteRefPrefix = 'refs/remotes/' + if (candidate.startsWith(remoteRefPrefix)) { + const remoteAndBranch = candidate.slice(remoteRefPrefix.length) + const slashIndex = remoteAndBranch.indexOf('/') + return slashIndex > 0 ? remoteAndBranch.slice(slashIndex + 1) : remoteAndBranch + } + const headsRefPrefix = 'refs/heads/' + if (candidate.startsWith(headsRefPrefix)) { + return candidate.slice(headsRefPrefix.length) + } + const slashIndex = candidate.indexOf('/') + return slashIndex > 0 ? candidate.slice(slashIndex + 1) : candidate +} + +function rewriteCompareBaseBranchFromCandidate( + candidate: string | null | undefined, + branch: string +): string | null { + const trimmed = candidate?.trim() + if (!trimmed) { + return null + } + const remoteRefPrefix = 'refs/remotes/' + if (trimmed.startsWith(remoteRefPrefix)) { + const remoteAndBranch = trimmed.slice(remoteRefPrefix.length) + const slashIndex = remoteAndBranch.indexOf('/') + return slashIndex > 0 + ? `${remoteRefPrefix}${remoteAndBranch.slice(0, slashIndex)}/${branch}` + : null + } + const headsRefPrefix = 'refs/heads/' + if (trimmed.startsWith(headsRefPrefix)) { + return `${headsRefPrefix}${branch}` + } + const slashIndex = trimmed.indexOf('/') + return slashIndex > 0 ? `${trimmed.slice(0, slashIndex)}/${branch}` : null } const EMPTY_GIT_STATUS_ENTRIES: GitStatusEntry[] = [] @@ -1196,11 +1281,6 @@ function SourceControlInner(): React.JSX.Element { const normalizedWorktreeBaseRef = activeWorktree?.baseRef?.trim() || null const normalizedRepoBaseRef = activeRepo?.worktreeBaseRef?.trim() || null - const effectiveBaseRef = resolveSourceControlBaseRef({ - worktreeBaseRef: normalizedWorktreeBaseRef, - repoBaseRef: normalizedRepoBaseRef, - defaultBaseRef - }) const baseRefOwnedByWorktree = normalizedWorktreeBaseRef !== null const pinnedBaseRef = normalizedWorktreeBaseRef ?? normalizedRepoBaseRef const hasUncommittedEntries = entries.length > 0 @@ -1247,6 +1327,16 @@ function SourceControlInner(): React.JSX.Element { ? { provider: 'github', ...activePrFromQueue, status: activePrFromQueue.checksStatus } : (hostedReviewEntry?.data ?? null) : null + const effectiveBaseRef = resolveSourceControlBaseRef({ + worktreeBaseRef: normalizedWorktreeBaseRef, + reviewBaseRefName: hostedReview?.baseRefName, + repoBaseRef: normalizedRepoBaseRef, + defaultBaseRef + }) + const pickerBaseRef = resolveSourceControlPickerBaseRef({ + pinnedBaseRef, + effectiveBaseRef + }) const linkedGitHubPR = activeWorktree?.linkedPR ?? null const fallbackGitHubPRNumber = linkedGitHubPR == null ? (activePrFromQueue?.number ?? null) : null @@ -5471,7 +5561,7 @@ function SourceControlInner(): React.JSX.Element { { if (baseRefOwnedByWorktree && activeWorktreeId) { void updateWorktreeMeta(activeWorktreeId, { baseRef: ref }) diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index 4dc89edc3..e99d314ed 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -193,7 +193,8 @@ export type ComposerCardProps = { onBaseBranchMrSelect?: ( baseBranch: string, item: GitLabWorkItem, - pushTarget?: GitPushTarget + pushTarget?: GitPushTarget, + compareBaseRef?: string ) => void smartNameSelection: SmartWorkspaceNameSelection | null onClearSmartNameSelection: () => void @@ -237,7 +238,8 @@ export type ComposerCardProps = { baseBranch: string, item: GitHubWorkItem, pushTarget?: GitPushTarget, - branchNameOverride?: string + branchNameOverride?: string, + compareBaseRef?: string ) => void /** PR number selected via the Start-from picker (when applicable). Used so the * field can render "PR #N" copy. */ @@ -647,6 +649,9 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS const [baseBranch, setBaseBranch] = useState( persistDraft ? newWorkspaceDraft?.baseBranch : initialBaseBranch ) + const [compareBaseRef, setCompareBaseRef] = useState( + persistDraft ? newWorkspaceDraft?.compareBaseRef : undefined + ) const [branchNameOverride, setBranchNameOverride] = useState(undefined) const [branchNameOverridePreservesNameEdits, setBranchNameOverridePreservesNameEdits] = useState(false) @@ -1061,13 +1066,15 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS linkedPR, linkedGitLabIssue, linkedGitLabMR, - ...(baseBranch !== undefined ? { baseBranch } : {}) + ...(baseBranch !== undefined ? { baseBranch } : {}), + ...(compareBaseRef !== undefined ? { compareBaseRef } : {}) }) }, [ persistDraft, agentPrompt, attachmentPaths, baseBranch, + compareBaseRef, linkedIssue, linkedPR, linkedGitLabIssue, @@ -1850,6 +1857,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS // makes the field fall back to the new repo's effective base ref. if (!options.preserveStartFrom) { setBaseBranch(undefined) + setCompareBaseRef(undefined) setPushTarget(undefined) setBranchNameOverride(undefined) setForkPushWarning(null) @@ -1921,6 +1929,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS const handleBaseBranchChange = useCallback((next: string | undefined): void => { setBaseBranch(next) + setCompareBaseRef(undefined) setPushTarget(undefined) setBranchNameOverride(undefined) setForkPushWarning(null) @@ -1933,9 +1942,11 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS nextBaseBranch: string, item: GitHubWorkItem, nextPushTarget?: GitPushTarget, - nextBranchNameOverride?: string + nextBranchNameOverride?: string, + nextCompareBaseRef?: string ): void => { setBaseBranch(nextBaseBranch) + setCompareBaseRef(nextCompareBaseRef) setPushTarget(nextPushTarget) setBranchNameOverride(nextBranchNameOverride) setBranchNameOverridePreservesNameEdits(Boolean(nextBranchNameOverride)) @@ -1965,8 +1976,14 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS // semantics — except the note prefill uses GitLab's `!N` MR convention // so a glance at the worktree sidebar makes the provider obvious. const handleBaseBranchMrSelect = useCallback( - (nextBaseBranch: string, item: GitLabWorkItem, nextPushTarget?: GitPushTarget): void => { + ( + nextBaseBranch: string, + item: GitLabWorkItem, + nextPushTarget?: GitPushTarget, + nextCompareBaseRef?: string + ): void => { setBaseBranch(nextBaseBranch) + setCompareBaseRef(nextCompareBaseRef) setPushTarget(nextPushTarget) setBranchNameOverride(undefined) branchAutoNameRef.current = '' @@ -1996,9 +2013,11 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS const runRepo = selectedRepo ?? eligibleRepos.find((repo) => repo.id === item.repoId) applyLinkedWorkItem(item) if (item.type !== 'pr' || !runRepo) { + setCompareBaseRef(undefined) setPushTarget(undefined) return } + setCompareBaseRef(undefined) setPushTarget(undefined) const itemRepoSettings = getSettingsForRepoRuntimeOwner( { repos: [runRepo], settings }, @@ -2011,6 +2030,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS repoId: runRepo.id, prNumber: item.number, ...(item.branchName ? { headRefName: item.branchName } : {}), + ...(item.baseRefName ? { baseRefName: item.baseRefName } : {}), ...(item.isCrossRepository !== undefined ? { isCrossRepository: item.isCrossRepository } : {}) @@ -2022,6 +2042,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS repo: runRepo.id, prNumber: item.number, ...(item.branchName ? { headRefName: item.branchName } : {}), + ...(item.baseRefName ? { baseRefName: item.baseRefName } : {}), ...(item.isCrossRepository !== undefined ? { isCrossRepository: item.isCrossRepository } : {}) @@ -2032,6 +2053,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS .then((result) => { if ('error' in result) { setBaseBranch(undefined) + setCompareBaseRef(undefined) setPushTarget(undefined) toast.error(result.error) return @@ -2040,7 +2062,8 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS result.baseBranch, item, result.pushTarget, - result.branchNameOverride + result.branchNameOverride, + result.compareBaseRef ) // Why: a fork PR push lands on the contributor's fork; if they didn't // allow maintainer edits, GitHub will reject it. Warn up front. @@ -2048,6 +2071,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS }) .catch((error: unknown) => { setBaseBranch(undefined) + setCompareBaseRef(undefined) setPushTarget(undefined) toast.error( error instanceof Error @@ -2075,13 +2099,16 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS // workspace is created on another host for the same logical project. const runRepo = selectedRepo ?? eligibleRepos.find((repo) => repo.id === item.repoId) if (item.type !== 'mr' || !runRepo) { + setCompareBaseRef(undefined) return } + setCompareBaseRef(undefined) void window.api.worktrees .resolveMrBase({ repoId: runRepo.id, mrIid: item.number, ...(item.branchName ? { sourceBranch: item.branchName } : {}), + ...(item.baseRefName ? { targetBranch: item.baseRefName } : {}), ...(item.isCrossRepository !== undefined ? { isCrossRepository: item.isCrossRepository } : {}) @@ -2090,7 +2117,12 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS if ('error' in result) { return } - handleBaseBranchMrSelect(result.baseBranch, item, result.pushTarget) + handleBaseBranchMrSelect( + result.baseBranch, + item, + result.pushTarget, + result.compareBaseRef + ) }) }, [applyLinkedGitLabWorkItem, eligibleRepos, handleBaseBranchMrSelect, selectedRepo] @@ -2105,6 +2137,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS lastAutoName: lastAutoNameRef.current }) setBaseBranch(selection.baseBranch) + setCompareBaseRef(undefined) setPushTarget(undefined) setStartFromResetHint(null) setForkPushWarning(null) @@ -2154,6 +2187,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS setLinkedPR(null) setLinkedWorkItem(null) setBaseBranch(undefined) + setCompareBaseRef(undefined) setPushTarget(undefined) setBranchNameOverride(undefined) setForkPushWarning(null) @@ -2405,7 +2439,11 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS pendingFirstAgentMessageRename, undefined, linkedLinearIssueWorkspaceId, - linkedLinearIssueOrganizationUrlKey + linkedLinearIssueOrganizationUrlKey, + undefined, + undefined, + undefined, + compareBaseRef ) const worktree = result.worktree @@ -2474,6 +2512,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS branchNameOverride, branchNameOverridePreservesNameEdits, clearNewWorkspaceDraft, + compareBaseRef, createWorktree, applyWorktreeMeta, enableIssueAutomation, @@ -2715,6 +2754,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS name: workspaceName, ...(createDisplayName ? { displayName: createDisplayName } : {}), ...(selectedRepoIsGit && submitBaseBranch ? { baseBranch: submitBaseBranch } : {}), + ...(selectedRepoIsGit && compareBaseRef ? { compareBaseRef } : {}), setupDecision: effectiveSetupDecision, ...(selectedRepoIsGit && sparseEnabled ? { @@ -2768,6 +2808,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS }, [ baseBranch, + compareBaseRef, branchNameOverride, branchNameOverridePreservesNameEdits, clearNewWorkspaceDraft, diff --git a/src/renderer/src/lib/launch-work-item-direct.test.ts b/src/renderer/src/lib/launch-work-item-direct.test.ts index 27ad9aebd..8b1ad3069 100644 --- a/src/renderer/src/lib/launch-work-item-direct.test.ts +++ b/src/renderer/src/lib/launch-work-item-direct.test.ts @@ -139,6 +139,7 @@ describe('launchWorkItemDirect', () => { }) mocks.resolvePrBase.mockResolvedValue({ baseBranch: 'abc123', + compareBaseRef: 'refs/remotes/origin/main', headSha: 'abc123', branchNameOverride: 'feature/fix', pushTarget: { remoteName: 'origin', branchName: 'feature/fix' } @@ -242,7 +243,11 @@ describe('launchWorkItemDirect', () => { undefined, undefined, undefined, - undefined + undefined, + undefined, + undefined, + undefined, + 'refs/remotes/origin/main' ) }) @@ -284,6 +289,10 @@ describe('launchWorkItemDirect', () => { undefined, undefined, undefined, + undefined, + undefined, + undefined, + undefined, undefined ) }) diff --git a/src/renderer/src/lib/launch-work-item-direct.ts b/src/renderer/src/lib/launch-work-item-direct.ts index 5baab88f5..6724d6c15 100644 --- a/src/renderer/src/lib/launch-work-item-direct.ts +++ b/src/renderer/src/lib/launch-work-item-direct.ts @@ -143,6 +143,7 @@ export async function launchWorkItemDirect(args: LaunchWorkItemDirectArgs): Prom let resolvedBaseBranch = baseBranch let resolvedPushTarget: GitPushTarget | undefined let resolvedBranchNameOverride: string | undefined + let resolvedCompareBaseRef: string | undefined if (!resolvedBaseBranch && item.type === 'pr' && item.number) { try { // Why: direct "Use PR" launches bypass the Start-from picker, so they @@ -151,6 +152,7 @@ export async function launchWorkItemDirect(args: LaunchWorkItemDirectArgs): Prom resolvedBaseBranch = result.baseBranch resolvedPushTarget = result.pushTarget resolvedBranchNameOverride = result.branchNameOverride + resolvedCompareBaseRef = result.compareBaseRef } catch (error) { toast.error(error instanceof Error ? error.message : resolvePrHeadErrorMessage()) openModalFallback() @@ -187,7 +189,11 @@ export async function launchWorkItemDirect(args: LaunchWorkItemDirectArgs): Prom undefined, undefined, item.linearWorkspaceId, - item.linearOrganizationUrlKey + item.linearOrganizationUrlKey, + undefined, + undefined, + undefined, + resolvedCompareBaseRef ) worktreeId = result.worktree.id const worktreePath = result.worktree.path diff --git a/src/renderer/src/lib/pending-worktree-creation.ts b/src/renderer/src/lib/pending-worktree-creation.ts index 6209b3b07..74512c42d 100644 --- a/src/renderer/src/lib/pending-worktree-creation.ts +++ b/src/renderer/src/lib/pending-worktree-creation.ts @@ -36,6 +36,7 @@ export type WorktreeCreationRequest = { name: string displayName?: string baseBranch?: string + compareBaseRef?: string setupDecision: SetupDecision sparseCheckout?: CreateSparseCheckoutRequest telemetrySource?: WorkspaceCreateTelemetrySource diff --git a/src/renderer/src/lib/worktree-creation-flow.ts b/src/renderer/src/lib/worktree-creation-flow.ts index c4826fca9..f3da917d9 100644 --- a/src/renderer/src/lib/worktree-creation-flow.ts +++ b/src/renderer/src/lib/worktree-creation-flow.ts @@ -91,7 +91,8 @@ async function executeWorktreeCreation( request.linkedLinearIssueOrganizationUrlKey, request.linkedBitbucketPR, request.linkedAzureDevOpsPR, - request.linkedGiteaPR + request.linkedGiteaPR, + request.compareBaseRef ) } catch (error) { // Why: a missing entry means the user cancelled mid-flight — abandon diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index 0cdb90d81..357f7b1b1 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -650,6 +650,9 @@ export type UISlice = { // Why: repo-scoped start ref selected via the "Start from" picker. // Absent means "use the repo's effective base ref". baseBranch?: string + // Why: review-created worktrees can start from a head ref/SHA while Source + // Control must compare against the provider target branch. + compareBaseRef?: string } | null openTaskPage: ( data?: UISlice['taskPageData'], diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index d7f4c7dbd..b0f2171b4 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -146,7 +146,8 @@ export type WorktreeSlice = { linkedLinearIssueOrganizationUrlKey?: string | null, linkedBitbucketPR?: number | null, linkedAzureDevOpsPR?: number | null, - linkedGiteaPR?: number | null + linkedGiteaPR?: number | null, + compareBaseRef?: string ) => Promise /** Register an in-flight background creation and make it the active surface. */ beginPendingWorktreeCreation: (entry: PendingWorktreeCreation) => void diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 98e7031e8..25c504628 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -1553,7 +1553,8 @@ export const createWorktreeSlice: StateCreator linkedLinearIssueOrganizationUrlKey, linkedBitbucketPR, linkedAzureDevOpsPR, - linkedGiteaPR + linkedGiteaPR, + compareBaseRef ) => { const retryableConflictPatterns = [ /already exists locally/i, @@ -1588,6 +1589,7 @@ export const createWorktreeSlice: StateCreator repoId, name: candidateName, baseBranch, + ...(compareBaseRef ? { compareBaseRef } : {}), ...(branchNameOverride ? { branchNameOverride } : {}), setupDecision, sparseCheckout, @@ -1627,6 +1629,7 @@ export const createWorktreeSlice: StateCreator repo: repoId, name: candidateName, baseBranch, + ...(compareBaseRef ? { compareBaseRef } : {}), ...(branchNameOverride ? { branchNameOverride } : {}), setupDecision, sparseCheckout, diff --git a/src/renderer/src/web/web-preload-api.test.ts b/src/renderer/src/web/web-preload-api.test.ts index 1f1e76b21..44432ffaf 100644 --- a/src/renderer/src/web/web-preload-api.test.ts +++ b/src/renderer/src/web/web-preload-api.test.ts @@ -1126,6 +1126,104 @@ describe('web worktree preload API', () => { { method: 'worktree.list', params: { repo: 'repo-1', limit: 10_000 } } ]) }) + + it('forwards review compare-base fields through runtime worktree calls', async () => { + const runtimeCalls: { method: string; params: unknown }[] = [] + vi.doMock('./web-runtime-client', () => ({ + WebRuntimeClient: class { + call(method: string, params?: unknown): Promise> { + runtimeCalls.push({ method, params }) + if (method === 'worktree.resolvePrBase') { + return Promise.resolve({ + id: `call-${runtimeCalls.length}`, + ok: true, + result: { baseBranch: TEST_COMMIT_OID, compareBaseRef: 'refs/remotes/origin/main' }, + _meta: { runtimeId: 'runtime-1' } + }) + } + if (method === 'worktree.resolveMrBase') { + return Promise.resolve({ + id: `call-${runtimeCalls.length}`, + ok: true, + result: { + baseBranch: 'origin/source', + compareBaseRef: 'refs/remotes/origin/release' + }, + _meta: { runtimeId: 'runtime-1' } + }) + } + return Promise.resolve({ + id: `call-${runtimeCalls.length}`, + ok: true, + result: { + worktree: { id: 'repo-1::/workspace/review', path: '/workspace/review' } + }, + _meta: { runtimeId: 'runtime-1' } + }) + } + + close(): void {} + } + })) + + const globals = installBrowserGlobals('Linux') + writeStoredRuntimeEnvironment(globals.storage) + const { installWebPreloadApi } = await import('./web-preload-api') + installWebPreloadApi() + + await globals.window.api.worktrees.create({ + repoId: 'repo-1', + name: 'review-pr-42', + baseBranch: TEST_COMMIT_OID, + compareBaseRef: 'refs/remotes/origin/main', + setupDecision: 'inherit' + }) + await globals.window.api.worktrees.resolvePrBase({ + repoId: 'repo-1', + prNumber: 42, + headRefName: 'feature/fix', + baseRefName: 'main', + isCrossRepository: true + }) + await globals.window.api.worktrees.resolveMrBase({ + repoId: 'repo-1', + mrIid: 7, + sourceBranch: 'feature/mr', + targetBranch: 'release', + isCrossRepository: false + }) + + expect(runtimeCalls).toEqual([ + { + method: 'worktree.create', + params: expect.objectContaining({ + repo: 'repo-1', + baseBranch: TEST_COMMIT_OID, + compareBaseRef: 'refs/remotes/origin/main' + }) + }, + { + method: 'worktree.resolvePrBase', + params: { + repo: 'repo-1', + prNumber: 42, + headRefName: 'feature/fix', + baseRefName: 'main', + isCrossRepository: true + } + }, + { + method: 'worktree.resolveMrBase', + params: { + repo: 'repo-1', + mrIid: 7, + sourceBranch: 'feature/mr', + targetBranch: 'release', + isCrossRepository: false + } + } + ]) + }) }) describe('web file preload API', () => { diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 9742da1da..82c28d316 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1102,6 +1102,7 @@ function createWorktreesApi(): NonNullable['worktrees']> { repo: args.repoId, name: args.name, baseBranch: args.baseBranch, + compareBaseRef: args.compareBaseRef, branchNameOverride: args.branchNameOverride, linkedIssue: args.linkedIssue, linkedPR: args.linkedPR, @@ -1133,18 +1134,20 @@ function createWorktreesApi(): NonNullable['worktrees']> { baseBranch }) }, - resolvePrBase: async ({ repoId, prNumber, headRefName, isCrossRepository }) => + resolvePrBase: async ({ repoId, prNumber, headRefName, baseRefName, isCrossRepository }) => callRuntimeResult('worktree.resolvePrBase', { repo: repoId, prNumber, headRefName, + baseRefName, isCrossRepository }), - resolveMrBase: async ({ repoId, mrIid, sourceBranch, isCrossRepository }) => + resolveMrBase: async ({ repoId, mrIid, sourceBranch, targetBranch, isCrossRepository }) => callRuntimeResult('worktree.resolveMrBase', { repo: repoId, mrIid, sourceBranch, + targetBranch, isCrossRepository }), remove: async ({ worktreeId, force }) => { diff --git a/src/shared/gitlab-types.ts b/src/shared/gitlab-types.ts index b9961df6d..6b348247e 100644 --- a/src/shared/gitlab-types.ts +++ b/src/shared/gitlab-types.ts @@ -63,6 +63,8 @@ export type MRInfo = { authorAvatarUrl?: string | null /** GitLab MR head SHA — pipeline status is keyed off the head commit. */ headSha?: string + /** Target branch name for review-created worktree compare-base repair. */ + baseRefName?: string conflictSummary?: PRConflictSummary } diff --git a/src/shared/hosted-review.ts b/src/shared/hosted-review.ts index 1de83a314..2c704b60d 100644 --- a/src/shared/hosted-review.ts +++ b/src/shared/hosted-review.ts @@ -25,6 +25,8 @@ export type HostedReviewInfo = { mergeQueueRequired?: boolean | null mergeStateStatus?: string | null headSha?: string + /** Target branch name for review-created worktree compare-base repair. */ + baseRefName?: string conflictSummary?: PRConflictSummary } diff --git a/src/shared/types.ts b/src/shared/types.ts index 713128dd3..dffb9de18 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -494,6 +494,8 @@ export type GitPushTarget = { export type GitHubPrStartPoint = { baseBranch: string + /** Review target branch to use for Source Control compare after creating from a PR head SHA. */ + compareBaseRef?: string pushTarget?: GitPushTarget /** Verified PR head commit. Present when checkout can be tied to a stable SHA. */ headSha?: string @@ -1054,6 +1056,8 @@ export type PRInfo = { // Keeping the head SHA in cached PR metadata lets the checks panel poll the // correct commit without re-querying GitHub or guessing from local branch refs. headSha?: string + /** Target branch name for PR-created worktree compare-base repair. */ + baseRefName?: string prRepo?: GitHubRepositoryIdentity headRepo?: GitHubRepositoryIdentity conflictSummary?: PRConflictSummary @@ -1894,6 +1898,8 @@ export type CreateWorktreeArgs = { * Linear artifact whose title should remain readable in the sidebar. */ displayName?: string baseBranch?: string + /** Source Control compare target when it differs from the checkout start point. */ + compareBaseRef?: string /** Optional git branch to create, separate from the filesystem-safe worktree * name. Used when creating from an existing branch whose local branch name * legitimately contains `/` while the worktree directory must not. */