diff --git a/src/main/git/remove-worktree.test.ts b/src/main/git/remove-worktree.test.ts index c991a3b76..32b552b3f 100644 --- a/src/main/git/remove-worktree.test.ts +++ b/src/main/git/remove-worktree.test.ts @@ -124,6 +124,29 @@ branch refs/heads/main expectGitCallOrder(calls, 'git worktree prune', 'git branch -D feature/test') }) + it('preserves the branch when requested for a pre-existing local branch checkout', async () => { + mockGitCommands({ + 'git worktree list --porcelain': { + stdout: `worktree /repo +HEAD abc123 +branch refs/heads/main + +worktree /repo-feature +HEAD def456 +branch refs/heads/feature/test +` + } + }) + + await removeWorktree('/repo', '/repo-feature', false, { deleteBranch: false }) + + const calls = getGitCalls() + expect(calls).toEqual( + expect.arrayContaining(['git worktree remove /repo-feature', 'git worktree prune']) + ) + expect(calls).not.toContain('git branch -D feature/test') + }) + it('skips branch deletion when another worktree still points at the branch', async () => { mockGitCommands({ 'git worktree list --porcelain': { diff --git a/src/main/git/worktree.test.ts b/src/main/git/worktree.test.ts index ff77dd0c7..1b4d53bac 100644 --- a/src/main/git/worktree.test.ts +++ b/src/main/git/worktree.test.ts @@ -237,6 +237,18 @@ describe('addWorktree', () => { ]) }) + it('checks out a selected existing local branch without creating a new branch', async () => { + gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // worktree add + + await addWorktree('/repo', '/repo-feature', 'feature/test', 'feature/test', false, false, { + checkoutExistingBranch: true + }) + + expect(gitExecFileAsyncMock.mock.calls).toEqual([ + [['worktree', 'add', '/repo-feature', 'feature/test'], { cwd: '/repo' }] + ]) + }) + it('warns but does not throw when push.autoSetupRemote config fails', async () => { resolveRemoteBase() gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '' }) // worktree add diff --git a/src/main/git/worktree.ts b/src/main/git/worktree.ts index 5c39078f4..ed8a9e963 100644 --- a/src/main/git/worktree.ts +++ b/src/main/git/worktree.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines -- Why: this file keeps git worktree create/remove behavior together so local cleanup and creation invariants stay in one place. */ import { stat } from 'fs/promises' import { join, posix, win32 } from 'path' import { resolveWorktreeAddBaseRef } from '../../shared/worktree-base-ref' @@ -169,13 +170,14 @@ export async function addWorktree( branch: string, baseBranch?: string, refreshLocalBaseRef = false, - noCheckout = false + noCheckout = false, + options: { checkoutExistingBranch?: boolean } = {} ): Promise { // Why: Some users want Orca-created worktrees to make plain commands like // `git diff main...HEAD` work out of the box, while others do not want // worktree creation to mutate their local main/master ref at all. Keep this // behavior behind an explicit setting so the default stays conservative. - if (baseBranch && refreshLocalBaseRef) { + if (baseBranch && refreshLocalBaseRef && !options.checkoutExistingBranch) { // Why: We split on '/' instead of matching a hardcoded 'origin/' prefix because // callers may pass arbitrary remotes (e.g. 'upstream/main'), not just 'origin'. const slashIndex = baseBranch.indexOf('/') @@ -229,20 +231,29 @@ export async function addWorktree( if (noCheckout) { args.push('--no-checkout') } - // Why: --no-track keeps the new branch from inheriting the base ref's - // upstream, so `git status` doesn't report "behind by N" against the base - // pre-publish and tools/agents don't misread an unpublished branch as - // out-of-sync. First push sets the upstream — see push.autoSetupRemote - // below for the terminal ergonomics. - args.push('--no-track', '-b', branch, worktreePath) - if (baseBranch) { - const effectiveBase = await resolveWorktreeAddBaseRef(baseBranch, (qualifiedRef) => - hasWorktreeBaseCommitRef(repoPath, qualifiedRef) - ) - args.push(effectiveBase) + if (options.checkoutExistingBranch) { + // Why: -b would create a new branch instead of checking out the selected one. + args.push(worktreePath, branch) + } else { + // Why: --no-track keeps the new branch from inheriting the base ref's + // upstream, so `git status` doesn't report "behind by N" against the base + // pre-publish and tools/agents don't misread an unpublished branch as + // out-of-sync. First push sets the upstream — see push.autoSetupRemote + // below for the terminal ergonomics. + args.push('--no-track', '-b', branch, worktreePath) + if (baseBranch) { + const effectiveBase = await resolveWorktreeAddBaseRef(baseBranch, (qualifiedRef) => + hasWorktreeBaseCommitRef(repoPath, qualifiedRef) + ) + args.push(effectiveBase) + } } await gitExecFileAsync(args, { cwd: repoPath }) + if (options.checkoutExistingBranch) { + return + } + // SSH parity: src/relay/git-handler.ts addWorktree mirrors this exact // probe-and-write state machine. If you change the logic here, update // the relay handler in lockstep so local and SSH paths stay aligned. @@ -307,11 +318,20 @@ export async function addSparseWorktree( branch: string, directories: string[], baseBranch?: string, - refreshLocalBaseRef = false + refreshLocalBaseRef = false, + options: { checkoutExistingBranch?: boolean } = {} ): Promise { let created = false try { - await addWorktree(repoPath, worktreePath, branch, baseBranch, refreshLocalBaseRef, true) + await addWorktree( + repoPath, + worktreePath, + branch, + baseBranch, + refreshLocalBaseRef, + true, + options + ) created = true await gitExecFileAsync(['sparse-checkout', 'init', '--cone'], { cwd: worktreePath }) await gitExecFileAsync(['sparse-checkout', 'set', '--', ...directories], { cwd: worktreePath }) @@ -321,7 +341,9 @@ export async function addSparseWorktree( error instanceof Error ? (error as SparseWorktreeCreateError) : new Error(String(error)) if (created) { try { - await removeWorktree(repoPath, worktreePath, true) + await removeWorktree(repoPath, worktreePath, true, { + deleteBranch: !options.checkoutExistingBranch + }) } catch { wrapped.cleanupFailed = true // Why: the user needs to know that manual cleanup may be required — @@ -339,7 +361,8 @@ export async function addSparseWorktree( export async function removeWorktree( repoPath: string, worktreePath: string, - force = false + force = false, + options: { deleteBranch?: boolean } = {} ): Promise { const worktreesBeforeRemoval = await listWorktrees(repoPath) const removedWorktree = worktreesBeforeRemoval.find((worktree) => @@ -358,6 +381,9 @@ export async function removeWorktree( if (!branchName) { return } + if (options.deleteBranch === false) { + return + } // Why: `git worktree list` can still include stale sibling records until // `git worktree prune` runs. Re-list after prune so branch cleanup only skips diff --git a/src/main/github/pr-refresh-coordinator.test.ts b/src/main/github/pr-refresh-coordinator.test.ts index f7bff96cb..00d5692cb 100644 --- a/src/main/github/pr-refresh-coordinator.test.ts +++ b/src/main/github/pr-refresh-coordinator.test.ts @@ -342,6 +342,7 @@ describe('pr-refresh-coordinator', () => { '/repo', 'feature/test', null, + null, null ) expect(getPRForBranchOutcomeMock).toHaveBeenNthCalledWith( @@ -349,7 +350,8 @@ describe('pr-refresh-coordinator', () => { '/repo', 'feature/test', null, - 'ssh-1' + 'ssh-1', + null ) }) diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index a93074996..985125482 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -132,6 +132,53 @@ async function resolveCreateBranchNameSsh( return branchNameOverride } +function normalizeLocalBranchName(branchName: string | undefined): string { + return branchName?.replace(/^refs\/heads\//, '') ?? '' +} + +async function canCheckoutExistingLocalBranch( + repoPath: string, + branchName: string, + baseBranch: string +): Promise { + if (normalizeLocalBranchName(baseBranch) !== branchName) { + return false + } + try { + await gitExecFileAsync( + ['rev-parse', '--verify', '--quiet', `refs/heads/${branchName}^{commit}`], + { + cwd: repoPath + } + ) + } catch { + return false + } + const worktrees = await listWorktrees(repoPath) + return !worktrees.some((worktree) => normalizeLocalBranchName(worktree.branch) === branchName) +} + +async function canCheckoutExistingLocalBranchSsh( + provider: SshGitProvider, + repoPath: string, + branchName: string, + baseBranch: string +): Promise { + if (normalizeLocalBranchName(baseBranch) !== branchName) { + return false + } + try { + await provider.exec( + ['rev-parse', '--verify', '--quiet', `refs/heads/${branchName}^{commit}`], + repoPath + ) + } catch { + return false + } + const worktrees = await provider.listWorktrees(repoPath) + return !worktrees.some((worktree) => normalizeLocalBranchName(worktree.branch) === branchName) +} + async function ensureUniqueRemoteName(repoPath: string, preferred: string): Promise { const { stdout } = await gitExecFileAsync(['remote'], { cwd: repoPath }) const existing = new Set( @@ -627,18 +674,6 @@ export async function createRemoteWorktree( username ) - // Check branch conflict on remote - try { - const { stdout } = await provider.exec(['branch', '--list', '--all', branchName], repo.path) - if (stdout.trim()) { - throw new Error(`Branch "${branchName}" already exists. Pick a different worktree name.`) - } - } catch (e) { - if (e instanceof Error && e.message.includes('already exists')) { - throw e - } - } - // Compute worktree path relative to the repo's parent on the remote const remotePath = `${repo.path}/../${sanitizedName}` @@ -666,6 +701,26 @@ export async function createRemoteWorktree( ) } + const checkoutExistingBranch = await canCheckoutExistingLocalBranchSsh( + provider, + repo.path, + branchName, + baseBranch + ) + if (!checkoutExistingBranch) { + // Check branch conflict on remote + try { + const { stdout } = await provider.exec(['branch', '--list', '--all', branchName], repo.path) + if (stdout.trim()) { + throw new Error(`Branch "${branchName}" already exists. Pick a different worktree name.`) + } + } catch (e) { + if (e instanceof Error && e.message.includes('already exists')) { + throw e + } + } + } + const remoteTrackingBase = await resolveRemoteTrackingBaseSsh(provider, repo.path, baseBranch) if (remoteTrackingBase) { try { @@ -740,9 +795,12 @@ export async function createRemoteWorktree( // Create worktree via relay try { - await provider.addWorktree(repo.path, branchName, remotePath, { - base: baseBranch - }) + await provider.addWorktree( + repo.path, + branchName, + remotePath, + checkoutExistingBranch ? { checkoutExistingBranch } : { base: baseBranch } + ) } catch (err) { if ( err instanceof Error && @@ -796,6 +854,7 @@ export async function createRemoteWorktree( // window elapses. See smart-sort.ts `CREATE_GRACE_MS`. createdAt: now, baseRef: baseBranch, + ...(checkoutExistingBranch ? { preserveBranchOnDelete: true } : {}), ...(configuredPushTarget ? { pushTarget: configuredPushTarget } : {}), ...(requestedDisplayName ? { displayName: requestedDisplayName } @@ -980,6 +1039,8 @@ export async function createLocalWorktree( // conflict) cannot spin this loop indefinitely. const MAX_SUFFIX_ATTEMPTS = 100 let resolved = false + let checkoutExistingBranch = false + let selectedExistingLocalBranchName: string | null = null let lastBranchConflictKind: 'local' | 'remote' | null = null let lastExistingPR: Awaited> | null = null for (let suffix = 1; suffix <= MAX_SUFFIX_ATTEMPTS; suffix += 1) { @@ -993,16 +1054,26 @@ export async function createLocalWorktree( branchName = await resolveCreateBranchName( repo.path, - suffix === 1 && args.branchNameOverride - ? args.branchNameOverride - : args.branchNameOverride - ? `${args.branchNameOverride}-${suffix}` - : undefined, + selectedExistingLocalBranchName + ? selectedExistingLocalBranchName + : suffix === 1 && args.branchNameOverride + ? args.branchNameOverride + : args.branchNameOverride + ? `${args.branchNameOverride}-${suffix}` + : undefined, effectiveSanitizedName, settings, username ) - lastBranchConflictKind = await getBranchConflictKind(repo.path, branchName, baseBranch) + checkoutExistingBranch = await canCheckoutExistingLocalBranch(repo.path, branchName, baseBranch) + if (checkoutExistingBranch && !selectedExistingLocalBranchName) { + // Why: suffix retries may need a new path, but an existing branch checkout + // must keep using the user-selected branch instead of creating a sibling. + selectedExistingLocalBranchName = branchName + } + lastBranchConflictKind = checkoutExistingBranch + ? null + : await getBranchConflictKind(repo.path, branchName, baseBranch) if (lastBranchConflictKind) { continue } @@ -1013,7 +1084,7 @@ export async function createLocalWorktree( // forced us past the first suffix — at that point uniqueness matters // enough to justify the GitHub call. The common case (brand-new branch // name, no collisions) skips the network entirely. - if (suffix > 1) { + if (suffix > 1 && !checkoutExistingBranch) { lastExistingPR = null try { lastExistingPR = await getPRForBranch(repo.path, branchName) @@ -1084,22 +1155,45 @@ export async function createLocalWorktree( preparedPushTarget = await prepareWorktreePushTarget(repo.path, args.pushTarget, store, repo.id) } - await (sparseDirectories.length > 0 - ? addSparseWorktree( - repo.path, - worktreePath, - branchName, - sparseDirectories, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate - ) - : addWorktree( - repo.path, - worktreePath, - branchName, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate - )) + const existingBranchOption = { checkoutExistingBranch } + if (sparseDirectories.length > 0) { + await (checkoutExistingBranch + ? addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + existingBranchOption + ) + : addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate + )) + } else { + await (checkoutExistingBranch + ? addWorktree( + repo.path, + worktreePath, + branchName, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + false, + existingBranchOption + ) + : addWorktree( + repo.path, + worktreePath, + branchName, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate + )) + } let configuredPushTarget: GitPushTarget | undefined if (preparedPushTarget) { @@ -1136,6 +1230,7 @@ export async function createLocalWorktree( // worktree from ambient PTY bumps in other worktrees for CREATE_GRACE_MS. createdAt: now, baseRef: baseBranch, + ...(checkoutExistingBranch ? { preserveBranchOnDelete: true } : {}), ...(configuredPushTarget ? { pushTarget: configuredPushTarget } : {}), ...(requestedDisplayName ? { displayName: requestedDisplayName } diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 5cf596725..ff1e01e91 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -479,6 +479,114 @@ describe('registerWorktreeHandlers', () => { }) }) + it('checks out a selected existing local branch exactly', async () => { + listWorktreesMock + .mockResolvedValueOnce([ + { + path: '/workspace/repo', + head: 'main', + branch: 'refs/heads/main', + isBare: false, + isMainWorktree: true + } + ]) + .mockResolvedValueOnce([ + { + path: '/workspace/repo', + head: 'main', + branch: 'refs/heads/main', + isBare: false, + isMainWorktree: true + }, + { + path: '/workspace/fix-bug-0', + head: 'abc123', + branch: 'refs/heads/fix/bug-0', + isBare: false, + isMainWorktree: false + } + ]) + + const result = await handlers['worktrees:create'](null, { + repoId: 'repo-1', + name: 'fix/bug-0', + baseBranch: 'fix/bug-0', + branchNameOverride: 'fix/bug-0' + }) + + expect(getBranchConflictKindMock).not.toHaveBeenCalled() + expect(addWorktreeMock).toHaveBeenCalledWith( + '/workspace/repo', + '/workspace/fix-bug-0', + 'fix/bug-0', + 'fix/bug-0', + false, + false, + { checkoutExistingBranch: true } + ) + expect(store.setWorktreeMeta).toHaveBeenCalledWith( + 'repo-1::/workspace/fix-bug-0', + expect.objectContaining({ preserveBranchOnDelete: true }) + ) + expect(result).toEqual({ + worktree: expect.objectContaining({ + path: '/workspace/fix-bug-0', + branch: 'refs/heads/fix/bug-0' + }) + }) + }) + + it('suffixes only the path when an existing local branch checkout path already exists', async () => { + const mainWorktree = { + path: '/workspace/repo', + head: 'main', + branch: 'refs/heads/main', + isBare: false, + isMainWorktree: true + } + computeWorktreePathMock.mockImplementation((sanitizedName: string) => + sanitizedName === 'fix-bug-0' ? process.cwd() : `/workspace/${sanitizedName}` + ) + listWorktreesMock + .mockResolvedValueOnce([mainWorktree]) + .mockResolvedValueOnce([mainWorktree]) + .mockResolvedValueOnce([ + mainWorktree, + { + path: '/workspace/fix-bug-0-2', + head: 'abc123', + branch: 'refs/heads/fix/bug-0', + isBare: false, + isMainWorktree: false + } + ]) + + const result = await handlers['worktrees:create'](null, { + repoId: 'repo-1', + name: 'fix/bug-0', + baseBranch: 'fix/bug-0', + branchNameOverride: 'fix/bug-0' + }) + + expect(getBranchConflictKindMock).not.toHaveBeenCalled() + expect(getPRForBranchMock).not.toHaveBeenCalled() + expect(addWorktreeMock).toHaveBeenCalledWith( + '/workspace/repo', + '/workspace/fix-bug-0-2', + 'fix/bug-0', + 'fix/bug-0', + false, + false, + { checkoutExistingBranch: true } + ) + expect(result).toEqual({ + worktree: expect.objectContaining({ + path: '/workspace/fix-bug-0-2', + branch: 'refs/heads/fix/bug-0' + }) + }) + }) + it('suffixes branchNameOverride without flattening slashes when the first branch collides', async () => { getBranchConflictKindMock.mockImplementation(async (_repoPath: string, branch: string) => branch === 'feature/something' ? 'remote' : null @@ -2238,6 +2346,23 @@ describe('registerWorktreeHandlers', () => { ) }) + it('preserves the branch on remove for worktrees created from an existing local branch', async () => { + mockKnownFeatureWorktree() + removeWorktreeMock.mockResolvedValue(undefined) + store.getWorktreeMeta.mockReturnValue(makeWorktreeMeta({ preserveBranchOnDelete: true })) + + await handlers['worktrees:remove'](null, { + worktreeId: 'repo-1::/workspace/feature-wt' + }) + + expect(removeWorktreeMock).toHaveBeenCalledWith( + '/workspace/repo', + '/workspace/feature-wt', + false, + { deleteBranch: false } + ) + }) + it('removes an unused Orca-created fork remote after deleting its worktree', async () => { mockKnownFeatureWorktree() removeWorktreeMock.mockResolvedValue(undefined) diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index ee09b5dfb..75f5af4ba 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -616,10 +616,14 @@ export function registerWorktreeHandlers( worktreePath, registeredWorktrees ).path - const removedPushTarget = store.getWorktreeMeta(args.worktreeId)?.pushTarget + const removedMeta = store.getWorktreeMeta(args.worktreeId) + const removedPushTarget = removedMeta?.pushTarget + const deleteBranch = removedMeta?.preserveBranchOnDelete !== true if (repo.connectionId) { - await provider!.removeWorktree(canonicalWorktreePath, args.force) + await (deleteBranch + ? provider!.removeWorktree(canonicalWorktreePath, args.force) + : provider!.removeWorktree(canonicalWorktreePath, args.force, { deleteBranch })) await cleanupUnusedWorktreePushTargetRemoteSsh( provider!, repo.path, @@ -687,7 +691,11 @@ export function registerWorktreeHandlers( } try { - await removeWorktree(repo.path, canonicalWorktreePath, args.force ?? false) + await (deleteBranch + ? removeWorktree(repo.path, canonicalWorktreePath, args.force ?? false) + : removeWorktree(repo.path, canonicalWorktreePath, args.force ?? false, { + deleteBranch + })) } catch (error) { // If git no longer tracks this worktree, clean up the directory and metadata if (isOrphanedWorktreeError(error)) { diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index 0ff95daa3..3916ef62b 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -373,7 +373,7 @@ export class SshGitProvider implements IGitProvider { repoPath: string, branchName: string, targetDir: string, - options?: { base?: string } + options?: { base?: string; checkoutExistingBranch?: boolean } ): Promise { await this.mux.request('git.addWorktree', { repoPath, @@ -383,8 +383,12 @@ export class SshGitProvider implements IGitProvider { }) } - async removeWorktree(worktreePath: string, force?: boolean): Promise { - await this.mux.request('git.removeWorktree', { worktreePath, force }) + async removeWorktree( + worktreePath: string, + force?: boolean, + options?: { deleteBranch?: boolean } + ): Promise { + await this.mux.request('git.removeWorktree', { worktreePath, force, ...options }) } async exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> { diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index 1e698ce2c..34b321bd1 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -189,9 +189,13 @@ export type IGitProvider = { repoPath: string, branchName: string, targetDir: string, - options?: { base?: string } + options?: { base?: string; checkoutExistingBranch?: boolean } + ): Promise + removeWorktree( + worktreePath: string, + force?: boolean, + options?: { deleteBranch?: boolean } ): Promise - removeWorktree(worktreePath: string, force?: boolean): Promise isGitRepo(path: string): boolean isGitRepoAsync(dirPath: string): Promise<{ isRepo: boolean; rootPath: string | null }> exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index ba588bd3e..8113cb5a0 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -43,7 +43,8 @@ const { muxRequestMock, invalidateAuthorizedRootsCacheMock, createHostedReviewMock, - getHostedReviewCreationEligibilityMock + getHostedReviewCreationEligibilityMock, + getPRForBranchMock } = vi.hoisted(() => { // Why: SSH runtime tests register providers through the public dispatcher API, // so the mock needs the same registry semantics as the real module. @@ -75,7 +76,8 @@ const { muxRequestMock: vi.fn(), invalidateAuthorizedRootsCacheMock: vi.fn(), createHostedReviewMock: vi.fn(), - getHostedReviewCreationEligibilityMock: vi.fn() + getHostedReviewCreationEligibilityMock: vi.fn(), + getPRForBranchMock: vi.fn().mockResolvedValue(null) } }) @@ -139,6 +141,14 @@ vi.mock('../source-control/hosted-review-creation', () => ({ getHostedReviewCreationEligibility: getHostedReviewCreationEligibilityMock })) +vi.mock('../github/client', async (importOriginal) => { + const actual = (await importOriginal()) as Record + return { + ...actual, + getPRForBranch: getPRForBranchMock + } +}) + // Why: the CLI create-worktree path calls getDefaultBaseRef to resolve a // fallback base branch. Real resolution shells out to `git` against the // test's fabricated repo path, which has no refs, so we stub it to a @@ -209,6 +219,8 @@ afterEach(() => { title: null, body: null }) + getPRForBranchMock.mockReset() + getPRForBranchMock.mockResolvedValue(null) }) function syncSinglePty(runtime: OrcaRuntimeService, ptyId: string | null = 'pty-1'): void { @@ -865,6 +877,73 @@ describe('OrcaRuntimeService', () => { }) }) + it('checks out a selected existing local branch even when that branch already has a PR', async () => { + const runtime = new OrcaRuntimeService(store) + const createdWorktree = { + path: '/tmp/workspaces/fix-bug-0', + head: 'def', + branch: 'refs/heads/fix/bug-0', + isBare: false, + isMainWorktree: false + } + computeWorktreePathMock.mockReturnValue(createdWorktree.path) + ensurePathWithinWorkspaceMock.mockReturnValue(createdWorktree.path) + vi.mocked(getBranchConflictKind).mockClear() + getPRForBranchMock.mockResolvedValue({ + number: 42, + title: 'Existing PR', + state: 'open', + url: 'https://example.com/pr/42', + checksStatus: 'success', + updatedAt: '2026-05-21T00:00:00Z', + mergeable: 'UNKNOWN' + }) + vi.mocked(listWorktrees) + .mockResolvedValueOnce([ + { + path: TEST_REPO_PATH, + head: 'main', + branch: 'refs/heads/main', + isBare: false, + isMainWorktree: true + } + ]) + .mockResolvedValueOnce([createdWorktree]) + const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => { + if (args[0] === 'rev-parse' && args[1] === '--verify') { + return { stdout: 'branch-sha\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + + try { + const result = await runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'fix/bug-0', + baseBranch: 'fix/bug-0', + branchNameOverride: 'fix/bug-0' + }) + + expect(getBranchConflictKind).not.toHaveBeenCalled() + expect(getPRForBranchMock).not.toHaveBeenCalled() + expect(addWorktree).toHaveBeenCalledWith( + TEST_REPO_PATH, + createdWorktree.path, + 'fix/bug-0', + 'fix/bug-0', + false, + false, + { checkoutExistingBranch: true } + ) + expect(result.worktree).toMatchObject({ + path: createdWorktree.path, + branch: 'refs/heads/fix/bug-0' + }) + } finally { + gitSpy.mockRestore() + } + }) + it('creates SSH-backed worktrees through the SSH provider for mobile/runtime callers', async () => { vi.mocked(listWorktrees).mockClear() vi.mocked(addWorktree).mockClear() diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 985448b67..14504cf4f 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -583,6 +583,32 @@ async function resolveCreateBranchName( return branchNameOverride } +function normalizeLocalBranchName(branchName: string | undefined): string { + return branchName?.replace(/^refs\/heads\//, '') ?? '' +} + +async function canCheckoutExistingLocalBranch( + repoPath: string, + branchName: string, + baseBranch: string +): Promise { + if (normalizeLocalBranchName(baseBranch) !== branchName) { + return false + } + try { + await gitExecFileAsync( + ['rev-parse', '--verify', '--quiet', `refs/heads/${branchName}^{commit}`], + { + cwd: repoPath + } + ) + } catch { + return false + } + const worktrees = await listWorktrees(repoPath) + return !worktrees.some((worktree) => normalizeLocalBranchName(worktree.branch) === branchName) +} + type ResolvedWorktree = Worktree & { parentWorktreeId: string | null childWorktreeIds: string[] @@ -5936,23 +5962,32 @@ export class OrcaRuntimeService { ) } - const branchConflictKind = await getBranchConflictKind(repo.path, branchName, baseBranch) + const checkoutExistingBranch = await canCheckoutExistingLocalBranch( + repo.path, + branchName, + baseBranch + ) + const branchConflictKind = checkoutExistingBranch + ? null + : await getBranchConflictKind(repo.path, branchName, baseBranch) if (branchConflictKind) { throw new Error( `Branch "${branchName}" already exists ${branchConflictKind === 'local' ? 'locally' : 'on a remote'}.` ) } - let existingPR: Awaited> | null = null - try { - existingPR = await getPRForBranch(repo.path, branchName) - } catch { - // Why: worktree creation should not hard-fail on transient GitHub reachability - // issues because git state is still the source of truth for whether the - // worktree can be created locally. - } - if (existingPR) { - throw new Error(`Branch "${branchName}" already has PR #${existingPR.number}.`) + if (!checkoutExistingBranch) { + let existingPR: Awaited> | null = null + try { + existingPR = await getPRForBranch(repo.path, branchName) + } catch { + // Why: worktree creation should not hard-fail on transient GitHub reachability + // issues because git state is still the source of truth for whether the + // worktree can be created locally. + } + if (existingPR) { + throw new Error(`Branch "${branchName}" already has PR #${existingPR.number}.`) + } } let worktreePath = computeWorktreePath(sanitizedName, repo.path, settings) @@ -6012,22 +6047,45 @@ export class OrcaRuntimeService { ) } - await (sparseDirectories.length > 0 - ? addSparseWorktree( - repo.path, - worktreePath, - branchName, - sparseDirectories, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate - ) - : addWorktree( - repo.path, - worktreePath, - branchName, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate - )) + const existingBranchOption = { checkoutExistingBranch } + if (sparseDirectories.length > 0) { + await (checkoutExistingBranch + ? addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + existingBranchOption + ) + : addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate + )) + } else { + await (checkoutExistingBranch + ? addWorktree( + repo.path, + worktreePath, + branchName, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + false, + existingBranchOption + ) + : addWorktree( + repo.path, + worktreePath, + branchName, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate + )) + } let configuredPushTarget: GitPushTarget | undefined if (preparedPushTarget) { @@ -6064,6 +6122,7 @@ export class OrcaRuntimeService { createdAt: now, ...displayNameMeta, baseRef: baseBranch, + ...(checkoutExistingBranch ? { preserveBranchOnDelete: true } : {}), ...(configuredPushTarget ? { pushTarget: configuredPushTarget } : {}), ...(sparseDirectories.length > 0 ? { @@ -6850,7 +6909,10 @@ export class OrcaRuntimeService { } if (repo.connectionId) { const provider = requireSshGitProvider(repo.connectionId) - await provider.removeWorktree(worktree.path, force) + const deleteBranch = this.store.getWorktreeMeta(worktree.id)?.preserveBranchOnDelete !== true + await (deleteBranch + ? provider.removeWorktree(worktree.path, force) + : provider.removeWorktree(worktree.path, force, { deleteBranch })) await cleanupUnusedWorktreePushTargetRemoteSsh( provider, repo.path, @@ -6919,7 +6981,10 @@ export class OrcaRuntimeService { } try { - await removeWorktree(repo.path, worktree.path, force) + const deleteBranch = this.store.getWorktreeMeta(worktree.id)?.preserveBranchOnDelete !== true + await (deleteBranch + ? removeWorktree(repo.path, worktree.path, force) + : removeWorktree(repo.path, worktree.path, force, { deleteBranch })) } catch (error) { if (isOrphanedWorktreeError(error)) { if (await canSafelyRemoveOrphanedWorktreeDirectory(worktree.path, repo.path)) { diff --git a/src/relay/git-handler-worktree-ops.test.ts b/src/relay/git-handler-worktree-ops.test.ts index f36a6c363..d23eee18a 100644 --- a/src/relay/git-handler-worktree-ops.test.ts +++ b/src/relay/git-handler-worktree-ops.test.ts @@ -51,6 +51,35 @@ describe('removeWorktreeOp', () => { ]) }) + it('preserves the branch when removing an SSH worktree for an existing local branch', async () => { + const calls: string[] = [] + const git = vi.fn(async (args, cwd) => { + calls.push(`${cwd}$ ${args.join(' ')}`) + if (args[0] === 'rev-parse') { + return { stdout: '/repo/.git\n', stderr: '' } + } + if (args[0] === 'worktree' && args[1] === 'list') { + return { + stdout: worktreeList( + { path: '/repo', branch: 'main' }, + { path: '/repo-feature', branch: 'feature/test' } + ), + stderr: '' + } + } + return { stdout: '', stderr: '' } + }) + + await removeWorktreeOp(git, { worktreePath: '/repo-feature', deleteBranch: false }) + + expect(calls).toEqual([ + '/repo-feature$ rev-parse --git-common-dir', + '/repo$ worktree list --porcelain', + '/repo$ worktree remove /repo-feature', + '/repo$ worktree prune' + ]) + }) + it('keeps the branch when another SSH worktree still uses it', async () => { let listCount = 0 const git = vi.fn(async (args, _cwd) => { diff --git a/src/relay/git-handler-worktree-ops.ts b/src/relay/git-handler-worktree-ops.ts index 630305365..00b8ce823 100644 --- a/src/relay/git-handler-worktree-ops.ts +++ b/src/relay/git-handler-worktree-ops.ts @@ -16,6 +16,7 @@ export async function addWorktreeOp(git: GitExec, params: Record { - try { - await git(['rev-parse', '--verify', '--quiet', `${qualifiedRef}^{commit}`], repoPath) - return true - } catch { - return false - } - }) - : undefined + const effectiveBase = + base && !checkoutExistingBranch + ? await resolveWorktreeAddBaseRef(base, async (qualifiedRef) => { + try { + await git(['rev-parse', '--verify', '--quiet', `${qualifiedRef}^{commit}`], repoPath) + return true + } catch { + return false + } + }) + : undefined - const args = ['worktree', 'add', '--no-track', '-b', branchName, targetDir] + const args = checkoutExistingBranch + ? ['worktree', 'add', targetDir, branchName] + : ['worktree', 'add', '--no-track', '-b', branchName, targetDir] if (effectiveBase) { args.push(effectiveBase) } await git(args, repoPath) + if (checkoutExistingBranch) { + return + } + // Why: best-effort write so a deliberate user value (any scope) is // preserved and a real read failure is not silently overwritten. Final // catch is warn-only — if the remote host's git is <2.37 the value is @@ -84,6 +92,7 @@ export async function removeWorktreeOp( ): Promise { const worktreePath = params.worktreePath as string const force = params.force as boolean | undefined + const deleteBranch = params.deleteBranch !== false let repoPath = worktreePath try { @@ -113,6 +122,9 @@ export async function removeWorktreeOp( if (!branchName) { return } + if (!deleteBranch) { + return + } // Why: SSH worktree deletion should mirror local deletion. Dropping the // branch also removes its upstream config, which lets fork-remotes cleanup diff --git a/src/relay/git-handler.test.ts b/src/relay/git-handler.test.ts index c929c7014..42ea14ae9 100644 --- a/src/relay/git-handler.test.ts +++ b/src/relay/git-handler.test.ts @@ -790,6 +790,23 @@ describe('GitHandler', () => { expect(gitMock.mock.calls[3]?.[1]).toBe('/relay/wt') }) + it('checks out a selected existing local branch without creating a new branch', async () => { + const { localDispatcher, gitMock } = setupMockedHandler(['/relay/repo', '/relay/wt']) + gitMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) // worktree add + + await localDispatcher.callRequest('git.addWorktree', { + repoPath: '/relay/repo', + branchName: 'feature/test', + targetDir: '/relay/wt', + base: 'feature/test', + checkoutExistingBranch: true + }) + + expect(gitMock.mock.calls.map((c) => c[0])).toEqual([ + ['worktree', 'add', '/relay/wt', 'feature/test'] + ]) + }) + it('qualifies bare branch name as refs/heads/ when a same-named tag exists', async () => { // Why: repos that fetch with --tags can end up with a local tag named // 'main', making `git worktree add ... main` fail with "fatal: Ambiguous diff --git a/src/renderer/src/hooks/composer-branch-selection.test.ts b/src/renderer/src/hooks/composer-branch-selection.test.ts index e3224ac09..d80e611e7 100644 --- a/src/renderer/src/hooks/composer-branch-selection.test.ts +++ b/src/renderer/src/hooks/composer-branch-selection.test.ts @@ -33,4 +33,21 @@ describe('resolveComposerBranchSelection', () => { name: undefined }) }) + + it('replaces a typed branch prefix with the selected branch name', () => { + expect( + resolveComposerBranchSelection({ + refName: 'fix/bug-0', + localBranchName: 'fix/bug-0', + currentName: 'fix/bug', + lastAutoName: '' + }) + ).toEqual({ + baseBranch: 'fix/bug-0', + branchNameOverride: 'fix/bug-0', + branchAutoName: 'fix/bug-0', + name: 'fix/bug-0', + lastAutoName: 'fix/bug-0' + }) + }) }) diff --git a/src/renderer/src/hooks/composer-branch-selection.ts b/src/renderer/src/hooks/composer-branch-selection.ts index 042ab14ba..92ec11c6b 100644 --- a/src/renderer/src/hooks/composer-branch-selection.ts +++ b/src/renderer/src/hooks/composer-branch-selection.ts @@ -12,7 +12,12 @@ export function resolveComposerBranchSelection(args: { currentName: string lastAutoName: string }): ComposerBranchSelection { - const shouldAutoName = !args.currentName.trim() || args.currentName === args.lastAutoName + const trimmedCurrentName = args.currentName.trim() + const shouldAutoName = + !trimmedCurrentName || + args.currentName === args.lastAutoName || + args.localBranchName.startsWith(trimmedCurrentName) || + args.refName.startsWith(trimmedCurrentName) if (!shouldAutoName) { return { baseBranch: args.refName, diff --git a/src/shared/types.ts b/src/shared/types.ts index ff23181a1..78860ecb0 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -229,6 +229,8 @@ export type WorktreeMeta = { sparsePresetId?: string /** Intended create base for stale-base probes. Persisted metadata, not UI drift state. */ baseRef?: string + /** True when Orca checked out a pre-existing local branch that delete must not prune. */ + preserveBranchOnDelete?: boolean /** See {@link Worktree.pushTarget}. Persisted so refreshed worktree lists keep the target. */ pushTarget?: GitPushTarget /** User-assigned workspace board status for manual sidebar organization. */