fix: allow duplicate review worktrees (#6812)

This commit is contained in:
Neil
2026-06-29 18:02:10 -07:00
committed by GitHub
parent 8c49426224
commit 669ff13467
7 changed files with 697 additions and 407 deletions
+95 -67
View File
@@ -109,6 +109,11 @@ import {
getLocalProjectGitExecOptions,
getLocalProjectWorktreeGitOptions
} from '../project-runtime-git-options'
import {
getBranchNameOverrideCandidate,
getWorktreeCreateCandidate,
WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS
} from '../worktree-create-candidates'
const SSH_WORKTREE_CREATE_FETCH_FRESHNESS_MS = 30_000
const SSH_WORKTREE_CREATE_FETCH_CACHE_MAX = 512
@@ -718,6 +723,36 @@ async function hasSshRemoteBranchConflict(
}
}
async function hasSshLocalBranchConflict(
provider: SshGitProvider,
repoPath: string,
branchName: string
): Promise<boolean> {
try {
const { stdout } = await provider.exec(
['rev-parse', '--verify', '--quiet', `refs/heads/${branchName}^{commit}`],
repoPath
)
return stdout.trim().length > 0
} catch {
return false
}
}
async function getSshBranchConflictKind(
provider: SshGitProvider,
repoPath: string,
branchName: string,
allowedBaseRef: string
): Promise<'local' | 'remote' | null> {
if (await hasSshLocalBranchConflict(provider, repoPath, branchName)) {
return 'local'
}
return (await hasSshRemoteBranchConflict(provider, repoPath, branchName, allowedBaseRef))
? 'remote'
: null
}
type SelectedReviewBranchInput = Pick<
CreateWorktreeArgs,
| 'branchNameOverride'
@@ -836,7 +871,7 @@ async function remotePathExists(
fsProvider: IFilesystemProvider | null | undefined,
pathValue: string
): Promise<boolean> {
if (!fsProvider) {
if (!fsProvider?.stat) {
return false
}
try {
@@ -1419,19 +1454,6 @@ export async function createRemoteWorktree(
// commit author identity rather than hosted-account usernames.
const username = await getSshGitUsername(provider, repo.path)
const branchName = await resolveCreateBranchNameSsh(
provider,
repo.path,
args.branchNameOverride,
sanitizedName,
settings,
username
)
let remotePath = computeRemoteWorktreePath(sanitizedName, repo.path, worktreePathSettings, {
useConfiguredAbsolutePath: hasRepoWorktreeBasePath(repo)
})
// Determine base branch
// Why: previously fell back to a hardcoded 'origin/main' when
// symbolic-ref failed. That silently handed addWorktree a ref that may
@@ -1446,34 +1468,55 @@ export async function createRemoteWorktree(
}
const { baseBranch, remoteTrackingBase } = basePlan
const checkoutExistingBranch = await canCheckoutExistingLocalBranchSsh(
provider,
repo.path,
branchName,
baseBranch
)
if (!checkoutExistingBranch) {
if (await hasSshRemoteBranchConflict(provider, repo.path, branchName, baseBranch)) {
const selectedReview = isAllowedPushTargetRemoteConflict('remote', branchName, args)
let branchName = ''
let checkoutExistingBranch = false
let remotePath = ''
let selectedExistingLocalBranchName: string | null = null
let lastBranchConflictKind: 'local' | 'remote' | null = null
let remotePathResolved = false
// Why: duplicate PR/MR checkouts still need a workspace; suffix the local
// branch/path while preserving the review metadata and push target.
for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) {
effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix)
effectiveRequestedName = args.name.trim()
? getWorktreeCreateCandidate(args.name, suffix)
: effectiveSanitizedName
branchName = await resolveCreateBranchNameSsh(
provider,
repo.path,
selectedExistingLocalBranchName ??
getBranchNameOverrideCandidate(args.branchNameOverride, suffix),
effectiveSanitizedName,
settings,
username
)
checkoutExistingBranch = await canCheckoutExistingLocalBranchSsh(
provider,
repo.path,
branchName,
baseBranch
)
if (checkoutExistingBranch && !selectedExistingLocalBranchName) {
// Why: once a user-selected branch is safe to reuse, path retries should
// keep that branch exact instead of creating a sibling branch.
selectedExistingLocalBranchName = branchName
}
lastBranchConflictKind = checkoutExistingBranch
? null
: await getSshBranchConflictKind(provider, repo.path, branchName, baseBranch)
if (lastBranchConflictKind) {
const selectedReview = isAllowedPushTargetRemoteConflict(
lastBranchConflictKind,
branchName,
args
)
? await getSelectedHostedReviewForBranch(repo, branchName, args).catch(() => null)
: null
if (!selectedReview?.matchesSelected) {
throw new Error(
`Branch "${branchName}" already exists on a remote. Pick a different worktree name.`
)
continue
}
lastBranchConflictKind = null
}
}
let remotePathResolved = !args.branchNameOverride
for (let suffix = 1; args.branchNameOverride && suffix < 100; suffix += 1) {
effectiveSanitizedName = suffix === 1 ? sanitizedName : `${sanitizedName}-${suffix}`
effectiveRequestedName =
suffix === 1
? args.name
: args.name.trim()
? `${args.name}-${suffix}`
: effectiveSanitizedName
remotePath = computeRemoteWorktreePath(
effectiveSanitizedName,
repo.path,
@@ -1488,6 +1531,11 @@ export async function createRemoteWorktree(
}
}
if (!remotePathResolved) {
if (lastBranchConflictKind) {
throw new Error(
`Branch "${branchName}" already exists ${lastBranchConflictKind === 'local' ? 'locally' : 'on a remote'}. Pick a different worktree name.`
)
}
throw new Error(
`Could not find an available remote worktree path for "${sanitizedName}". Pick a different worktree name.`
)
@@ -1946,35 +1994,26 @@ export async function createLocalWorktree(
let branchName = ''
let worktreePath = ''
// Why: silently resolve branch/path/PR name collisions by appending -2/-3/etc.
// instead of failing and forcing the user back to the name picker. This is
// especially important for the new-workspace flow where the user may not have
// direct control over the branch name. Bounded by MAX_SUFFIX_ATTEMPTS so a
// misconfigured environment (e.g. a mock or stub that always reports a
// 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<ReturnType<typeof getPRForBranch>> | null = null
let lastExistingReviewNumber: number | null = null
for (let suffix = 1; suffix <= MAX_SUFFIX_ATTEMPTS; suffix += 1) {
effectiveSanitizedName = suffix === 1 ? sanitizedName : `${sanitizedName}-${suffix}`
effectiveRequestedName =
suffix === 1
? requestedName
: requestedName.trim()
? `${requestedName}-${suffix}`
: effectiveSanitizedName
// Why: create-from-review can provide an exact branch override that already
// exists locally; suffix both branch and path instead of blocking the user.
for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) {
effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix)
effectiveRequestedName = requestedName.trim()
? getWorktreeCreateCandidate(requestedName, suffix)
: effectiveSanitizedName
lastExistingReviewNumber = null
branchName = await resolveCreateBranchName(
repo.path,
selectedExistingLocalBranchName
? selectedExistingLocalBranchName
: args.branchNameOverride
? args.branchNameOverride
: undefined,
: getBranchNameOverrideCandidate(args.branchNameOverride, suffix),
effectiveSanitizedName,
settings,
username,
@@ -2016,7 +2055,6 @@ export async function createLocalWorktree(
lastBranchConflictKind = null
} else if (lastExistingPR) {
lastExistingReviewNumber = lastExistingPR.number
break
}
} else if (selectedReview) {
let hostedReview: Awaited<ReturnType<typeof getSelectedHostedReviewForBranch>> = null
@@ -2029,18 +2067,11 @@ export async function createLocalWorktree(
lastBranchConflictKind = null
} else if (hostedReview) {
lastExistingReviewNumber = hostedReview.number
break
}
}
}
}
if (lastBranchConflictKind) {
// Why: PR resolver-provided branch names are exact branch identity.
// Retrying with a suffixed branch would silently detach the worktree
// from the PR being opened.
if (args.branchNameOverride) {
break
}
continue
}
@@ -2062,10 +2093,7 @@ export async function createLocalWorktree(
// GitHub API may be unreachable, rate-limited, or token missing
}
if (lastExistingPR && !isMatchingSelectedGitHubPr(lastExistingPR, args, branchName)) {
if (args.branchNameOverride) {
lastExistingReviewNumber = lastExistingPR.number
break
}
lastExistingReviewNumber = lastExistingPR.number
continue
}
}
+228 -113
View File
@@ -1206,26 +1206,37 @@ describe('registerWorktreeHandlers', () => {
})
})
it('does not suffix branchNameOverride when the requested branch collides', async () => {
it('suffixes branchNameOverride when the requested branch collides', async () => {
getBranchConflictKindMock.mockImplementation(async (_repoPath: string, branch: string) =>
branch === 'feature/something' ? 'remote' : null
)
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/feature-something-2',
head: 'abc123',
branch: 'refs/heads/feature/something-2',
isBare: false,
isMainWorktree: false
}
])
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'feature/something',
branchNameOverride: 'feature/something'
})
).rejects.toThrow(
'Branch "feature/something" already exists on a remote. Pick a different worktree name.'
)
await handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'feature/something',
branchNameOverride: 'feature/something'
})
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
['check-ref-format', '--branch', 'feature/something'],
['check-ref-format', '--branch', 'feature/something-2'],
{ cwd: '/workspace/repo' }
)
expect(addWorktreeMock).not.toHaveBeenCalled()
expect(addWorktreeMock).toHaveBeenCalledWith(
'/workspace/repo',
'/workspace/feature-something-2',
'feature/something-2',
'origin/main',
false
)
})
it('allows a resolver-provided PR branch override to match its remote push target', async () => {
@@ -1376,10 +1387,19 @@ describe('registerWorktreeHandlers', () => {
expect(getPRForBranchMock).not.toHaveBeenCalled()
})
it('rejects a selected Bitbucket PR branch when the existing PR is different', async () => {
it('suffixes a selected Bitbucket PR branch when the existing PR is different', async () => {
getBranchConflictKindMock.mockImplementation(async (_repoPath: string, branch: string) =>
branch === 'feature/bitbucket' ? 'remote' : null
)
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/bitbucket-title-2',
head: 'abc123',
branch: 'refs/heads/feature/bitbucket-2',
isBare: false,
isMainWorktree: false
}
])
getHostedReviewForBranchMock.mockResolvedValueOnce({
provider: 'bitbucket',
number: 12,
@@ -1391,67 +1411,104 @@ describe('registerWorktreeHandlers', () => {
mergeable: 'UNKNOWN'
})
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'bitbucket-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/bitbucket',
linkedBitbucketPR: 11,
pushTarget: { remoteName: 'origin', branchName: 'feature/bitbucket' }
})
).rejects.toThrow(
'Branch "feature/bitbucket" already has PR #12. Pick a different worktree name.'
)
await handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'bitbucket-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/bitbucket',
linkedBitbucketPR: 11,
pushTarget: { remoteName: 'origin', branchName: 'feature/bitbucket' }
})
expect(addWorktreeMock).not.toHaveBeenCalled()
expect(addWorktreeMock).toHaveBeenCalledWith(
'/workspace/repo',
'/workspace/bitbucket-title-2',
'feature/bitbucket-2',
'abc123',
false
)
expect(store.setWorktreeMeta).toHaveBeenCalledWith(
'repo-1::/workspace/bitbucket-title-2',
expect.objectContaining({ linkedBitbucketPR: 11 })
)
})
it('rejects a matching push target branch without selected PR metadata', async () => {
it('suffixes a matching push target branch without selected PR metadata', async () => {
getBranchConflictKindMock.mockImplementation(async (_repoPath: string, branch: string) =>
branch === 'feature/fix' ? 'remote' : null
)
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
])
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
).rejects.toThrow(
'Branch "feature/fix" already exists on a remote. Pick a different worktree name.'
await handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
expect(addWorktreeMock).toHaveBeenCalledWith(
'/workspace/repo',
'/workspace/fix-title-2',
'feature/fix-2',
'abc123',
false
)
expect(addWorktreeMock).not.toHaveBeenCalled()
})
it('rejects a matching push target branch when selected PR metadata has no PR number', async () => {
it('suffixes a matching push target branch when selected PR metadata has no PR number', async () => {
getBranchConflictKindMock.mockImplementation(async (_repoPath: string, branch: string) =>
branch === 'feature/fix' ? 'remote' : null
)
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
])
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: null,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
).rejects.toThrow(
'Branch "feature/fix" already exists on a remote. Pick a different worktree name.'
await handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: null,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
expect(addWorktreeMock).toHaveBeenCalledWith(
'/workspace/repo',
'/workspace/fix-title-2',
'feature/fix-2',
'abc123',
false
)
expect(addWorktreeMock).not.toHaveBeenCalled()
})
it('rejects a matching push target branch when the existing PR is different', async () => {
it('suffixes a matching push target branch when the existing PR is different', async () => {
getBranchConflictKindMock.mockImplementation(async (_repoPath: string, branch: string) =>
branch === 'feature/fix' ? 'remote' : null
)
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
])
getPRForBranchMock.mockResolvedValueOnce({
number: 43,
title: 'Different PR',
@@ -1462,42 +1519,57 @@ describe('registerWorktreeHandlers', () => {
mergeable: 'UNKNOWN'
})
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: 42,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
).rejects.toThrow('Branch "feature/fix" already has PR #43. Pick a different worktree name.')
await handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: 42,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
expect(getPRForBranchMock).toHaveBeenCalledWith('/workspace/repo', 'feature/fix')
expect(addWorktreeMock).not.toHaveBeenCalled()
expect(addWorktreeMock).toHaveBeenCalledWith(
'/workspace/repo',
'/workspace/fix-title-2',
'feature/fix-2',
'abc123',
false
)
})
it('rejects a selected PR remote conflict when the PR lookup fails', async () => {
it('suffixes a selected PR remote conflict when the PR lookup fails', async () => {
getBranchConflictKindMock.mockImplementation(async (_repoPath: string, branch: string) =>
branch === 'feature/fix' ? 'remote' : null
)
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
])
getPRForBranchMock.mockRejectedValueOnce(new Error('gh unavailable'))
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: 42,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
).rejects.toThrow(
'Branch "feature/fix" already exists on a remote. Pick a different worktree name.'
)
await handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: 42,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
expect(getPRForBranchMock).toHaveBeenCalledWith('/workspace/repo', 'feature/fix')
expect(addWorktreeMock).not.toHaveBeenCalled()
expect(addWorktreeMock).toHaveBeenCalledWith(
'/workspace/repo',
'/workspace/fix-title-2',
'feature/fix-2',
'abc123',
false
)
})
it('checks out an unused existing PR branch only when it is at the resolved head SHA', async () => {
@@ -1556,7 +1628,7 @@ describe('registerWorktreeHandlers', () => {
)
})
it('rejects an existing PR branch when its tip differs from the resolved head SHA', async () => {
it('suffixes an existing PR branch when its tip differs from the resolved head SHA', async () => {
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix^{commit}')) {
return { stdout: 'old123\n', stderr: '' }
@@ -1567,19 +1639,30 @@ describe('registerWorktreeHandlers', () => {
return { stdout: '', stderr: '' }
})
getBranchConflictKindMock.mockResolvedValueOnce('local')
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
])
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix'
})
).rejects.toThrow(
'Branch "feature/fix" already exists locally. Pick a different worktree name.'
await handlers['worktrees:create'](null, {
repoId: 'repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix'
})
expect(addWorktreeMock).toHaveBeenCalledWith(
'/workspace/repo',
'/workspace/fix-title-2',
'feature/fix-2',
'abc123',
false
)
expect(addWorktreeMock).not.toHaveBeenCalled()
})
it('persists a sanitized artifact title as the worktree display name', async () => {
@@ -3091,12 +3174,15 @@ describe('registerWorktreeHandlers', () => {
if (args[0] === 'remote') {
return { stdout: 'origin\n', stderr: '' }
}
if (args[0] === 'rev-parse') {
if (args[0] === 'rev-parse' && args[1] === '--git-path') {
return {
stdout: '/remote/repo/.git/worktrees/improve-dashboard/orca/setup-runner.sh\n',
stderr: ''
}
}
if (args[0] === 'rev-parse') {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
}),
fetchRemoteTrackingRef: vi.fn().mockResolvedValue(undefined),
@@ -3299,6 +3385,15 @@ describe('registerWorktreeHandlers', () => {
isMainWorktree: true
}
])
.mockResolvedValueOnce([
{
path: '/remote/repo',
head: 'main',
branch: 'refs/heads/main',
isBare: false,
isMainWorktree: true
}
])
.mockResolvedValueOnce([
{
path: '/remote/fix-title-2',
@@ -3348,7 +3443,7 @@ describe('registerWorktreeHandlers', () => {
})
})
it('blocks SSH worktree creation when the requested branch already exists on a remote', async () => {
it('suffixes SSH worktree creation when the requested branch already exists on a remote', async () => {
const repo = {
id: 'repo-ssh',
path: '/remote/repo',
@@ -3372,6 +3467,9 @@ describe('registerWorktreeHandlers', () => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/something^{commit}')) {
throw new Error('missing local branch')
}
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/something-2^{commit}')) {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
}),
fetchRemoteTrackingRef: vi.fn().mockResolvedValue(undefined),
@@ -3379,9 +3477,9 @@ describe('registerWorktreeHandlers', () => {
removeWorktree: vi.fn().mockResolvedValue(undefined),
listWorktrees: vi.fn().mockResolvedValue([
{
path: '/remote/feature-something',
path: '/remote/feature-something-2',
head: 'abc123',
branch: 'refs/heads/feature/something',
branch: 'refs/heads/feature/something-2',
isBare: false,
isMainWorktree: false
}
@@ -3396,18 +3494,21 @@ describe('registerWorktreeHandlers', () => {
getSshGitProviderMock.mockReturnValue(provider)
getActiveMultiplexerMock.mockReturnValue(mux)
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-ssh',
name: 'feature-something',
branchNameOverride: 'feature/something'
})
).rejects.toThrow('Branch "feature/something" already exists on a remote.')
await handlers['worktrees:create'](null, {
repoId: 'repo-ssh',
name: 'feature-something',
branchNameOverride: 'feature/something'
})
expect(provider.addWorktree).not.toHaveBeenCalled()
expect(provider.addWorktree).toHaveBeenCalledWith(
'/remote/repo',
'feature/something-2',
'/remote/feature-something-2',
{ base: 'origin/main' }
)
})
it('blocks SSH worktree creation when a slashed remote owns the requested branch', async () => {
it('suffixes SSH worktree creation when a slashed remote owns the requested branch', async () => {
const repo = {
id: 'repo-ssh',
path: '/remote/repo',
@@ -3428,12 +3529,23 @@ describe('registerWorktreeHandlers', () => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/something^{commit}')) {
throw new Error('missing local branch')
}
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/something-2^{commit}')) {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
}),
fetchRemoteTrackingRef: vi.fn().mockResolvedValue(undefined),
addWorktree: vi.fn().mockResolvedValue(undefined),
removeWorktree: vi.fn().mockResolvedValue(undefined),
listWorktrees: vi.fn().mockResolvedValue([])
listWorktrees: vi.fn().mockResolvedValue([
{
path: '/remote/feature-something-2',
head: 'abc123',
branch: 'refs/heads/feature/something-2',
isBare: false,
isMainWorktree: false
}
])
}
const mux = {
request: vi.fn().mockResolvedValue(undefined),
@@ -3444,15 +3556,18 @@ describe('registerWorktreeHandlers', () => {
getSshGitProviderMock.mockReturnValue(provider)
getActiveMultiplexerMock.mockReturnValue(mux)
await expect(
handlers['worktrees:create'](null, {
repoId: 'repo-ssh',
name: 'feature-something',
branchNameOverride: 'feature/something'
})
).rejects.toThrow('Branch "feature/something" already exists on a remote.')
await handlers['worktrees:create'](null, {
repoId: 'repo-ssh',
name: 'feature-something',
branchNameOverride: 'feature/something'
})
expect(provider.addWorktree).not.toHaveBeenCalled()
expect(provider.addWorktree).toHaveBeenCalledWith(
'/remote/repo',
'feature/something-2',
'/remote/feature-something-2',
{ base: 'origin/main' }
)
})
it('unsets SSH branch base config before removing a sparse worktree after setup failure', async () => {
+173 -89
View File
@@ -2288,6 +2288,8 @@ describe('OrcaRuntimeService', () => {
it('does not create runtime local worktrees when remote-tracking base refresh fails', async () => {
const runtime = new OrcaRuntimeService(store)
computeWorktreePathMock.mockReturnValue('/tmp/workspaces/cli-refresh-fails')
ensurePathWithinWorkspaceMock.mockReturnValue('/tmp/workspaces/cli-refresh-fails')
const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => {
if (args[0] === 'remote') {
return { stdout: 'origin\n', stderr: '' }
@@ -2605,11 +2607,21 @@ describe('OrcaRuntimeService', () => {
}
})
it('rejects an existing PR when a matching push target lacks selected PR metadata', async () => {
it('suffixes an existing PR when a matching push target lacks selected PR metadata', async () => {
const runtime = new OrcaRuntimeService(store)
computeWorktreePathMock.mockReturnValue('/tmp/workspaces/fix-title')
ensurePathWithinWorkspaceMock.mockReturnValue('/tmp/workspaces/fix-title')
const createdWorktree = {
path: '/tmp/workspaces/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
computeWorktreePathMock.mockImplementation(
(sanitizedName: string) => `/tmp/workspaces/${sanitizedName}`
)
ensurePathWithinWorkspaceMock.mockImplementation((pathValue: string) => pathValue)
vi.mocked(getBranchConflictKind).mockResolvedValueOnce(null)
vi.mocked(listWorktrees).mockResolvedValueOnce([createdWorktree])
getPRForBranchMock.mockResolvedValueOnce({
number: 42,
title: 'Existing PR',
@@ -2623,63 +2635,96 @@ describe('OrcaRuntimeService', () => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix^{commit}')) {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
})
try {
await expect(
runtime.createManagedWorktree({
repoSelector: 'id:repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
).rejects.toThrow('Branch "feature/fix" already has PR #42.')
expect(getPRForBranchMock).toHaveBeenCalledWith(TEST_REPO_PATH, 'feature/fix')
expect(addWorktree).not.toHaveBeenCalled()
} finally {
gitSpy.mockRestore()
}
})
it('rejects a matching push target branch when selected PR metadata has no PR number', async () => {
const runtime = new OrcaRuntimeService(store)
computeWorktreePathMock.mockReturnValue('/tmp/workspaces/fix-title')
ensurePathWithinWorkspaceMock.mockReturnValue('/tmp/workspaces/fix-title')
vi.mocked(getBranchConflictKind).mockResolvedValueOnce('remote')
const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix^{commit}')) {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix-2^{commit}')) {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
})
try {
await expect(
runtime.createManagedWorktree({
repoSelector: 'id:repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: null,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
).rejects.toThrow('Branch "feature/fix" already exists on a remote.')
await runtime.createManagedWorktree({
repoSelector: 'id:repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
expect(getPRForBranchMock).not.toHaveBeenCalled()
expect(addWorktree).not.toHaveBeenCalled()
expect(getPRForBranchMock).toHaveBeenCalledWith(TEST_REPO_PATH, 'feature/fix')
expect(addWorktree).toHaveBeenCalledWith(
TEST_REPO_PATH,
createdWorktree.path,
'feature/fix-2',
'abc123',
false
)
} finally {
gitSpy.mockRestore()
}
})
it('rejects a matching push target branch when the existing PR is different', async () => {
it('suffixes a matching push target branch when selected PR metadata has no PR number', async () => {
const runtime = new OrcaRuntimeService(store)
computeWorktreePathMock.mockReturnValue('/tmp/workspaces/fix-title')
ensurePathWithinWorkspaceMock.mockReturnValue('/tmp/workspaces/fix-title')
const createdWorktree = {
path: '/tmp/workspaces/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
computeWorktreePathMock.mockImplementation(
(sanitizedName: string) => `/tmp/workspaces/${sanitizedName}`
)
ensurePathWithinWorkspaceMock.mockImplementation((pathValue: string) => pathValue)
vi.mocked(getBranchConflictKind).mockResolvedValueOnce('remote')
vi.mocked(listWorktrees).mockResolvedValueOnce([createdWorktree])
const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix^{commit}')) {
throw new Error('missing local branch')
}
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix-2^{commit}')) {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
})
try {
await runtime.createManagedWorktree({
repoSelector: 'id:repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: null,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
expect(addWorktree).toHaveBeenCalledWith(
TEST_REPO_PATH,
createdWorktree.path,
'feature/fix-2',
'abc123',
false
)
} finally {
gitSpy.mockRestore()
}
})
it('suffixes a matching push target branch when the existing PR is different', async () => {
const runtime = new OrcaRuntimeService(store)
const createdWorktree = {
path: '/tmp/workspaces/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
computeWorktreePathMock.mockImplementation(
(sanitizedName: string) => `/tmp/workspaces/${sanitizedName}`
)
ensurePathWithinWorkspaceMock.mockImplementation((pathValue: string) => pathValue)
vi.mocked(getBranchConflictKind).mockResolvedValueOnce('remote')
vi.mocked(listWorktrees).mockResolvedValueOnce([createdWorktree])
getPRForBranchMock.mockResolvedValueOnce({
number: 43,
title: 'Different PR',
@@ -2693,55 +2738,79 @@ describe('OrcaRuntimeService', () => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix^{commit}')) {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
})
try {
await expect(
runtime.createManagedWorktree({
repoSelector: 'id:repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: 42,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
).rejects.toThrow('Branch "feature/fix" already has PR #43.')
expect(getPRForBranchMock).toHaveBeenCalledWith(TEST_REPO_PATH, 'feature/fix')
expect(addWorktree).not.toHaveBeenCalled()
} finally {
gitSpy.mockRestore()
}
})
it('rejects a selected PR remote conflict when the PR lookup fails', async () => {
const runtime = new OrcaRuntimeService(store)
computeWorktreePathMock.mockReturnValue('/tmp/workspaces/fix-title')
ensurePathWithinWorkspaceMock.mockReturnValue('/tmp/workspaces/fix-title')
vi.mocked(getBranchConflictKind).mockResolvedValueOnce('remote')
getPRForBranchMock.mockRejectedValueOnce(new Error('gh unavailable'))
const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix^{commit}')) {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix-2^{commit}')) {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
})
try {
await expect(
runtime.createManagedWorktree({
repoSelector: 'id:repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: 42,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
).rejects.toThrow('Could not verify selected PR branch "feature/fix". Try again.')
await runtime.createManagedWorktree({
repoSelector: 'id:repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: 42,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
expect(getPRForBranchMock).toHaveBeenCalledWith(TEST_REPO_PATH, 'feature/fix')
expect(addWorktree).not.toHaveBeenCalled()
expect(addWorktree).toHaveBeenCalledWith(
TEST_REPO_PATH,
createdWorktree.path,
'feature/fix-2',
'abc123',
false
)
} finally {
gitSpy.mockRestore()
}
})
it('suffixes a selected PR remote conflict when the PR lookup fails', async () => {
const runtime = new OrcaRuntimeService(store)
const createdWorktree = {
path: '/tmp/workspaces/fix-title-2',
head: 'abc123',
branch: 'refs/heads/feature/fix-2',
isBare: false,
isMainWorktree: false
}
computeWorktreePathMock.mockImplementation(
(sanitizedName: string) => `/tmp/workspaces/${sanitizedName}`
)
ensurePathWithinWorkspaceMock.mockImplementation((pathValue: string) => pathValue)
vi.mocked(getBranchConflictKind).mockResolvedValueOnce('remote')
vi.mocked(listWorktrees).mockResolvedValueOnce([createdWorktree])
getPRForBranchMock.mockRejectedValueOnce(new Error('gh unavailable'))
const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args) => {
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix^{commit}')) {
throw new Error('missing local branch')
}
if (args[0] === 'rev-parse' && args.includes('refs/heads/feature/fix-2^{commit}')) {
throw new Error('missing local branch')
}
return { stdout: '', stderr: '' }
})
try {
await runtime.createManagedWorktree({
repoSelector: 'id:repo-1',
name: 'fix-title',
baseBranch: 'abc123',
branchNameOverride: 'feature/fix',
linkedPR: 42,
pushTarget: { remoteName: 'origin', branchName: 'feature/fix' }
})
expect(getPRForBranchMock).toHaveBeenCalledWith(TEST_REPO_PATH, 'feature/fix')
expect(addWorktree).toHaveBeenCalledWith(
TEST_REPO_PATH,
createdWorktree.path,
'feature/fix-2',
'abc123',
false
)
} finally {
gitSpy.mockRestore()
}
@@ -2818,6 +2887,15 @@ describe('OrcaRuntimeService', () => {
ensurePathWithinWorkspaceMock.mockImplementation((pathValue: string) => pathValue)
vi.mocked(getBranchConflictKind).mockClear()
vi.mocked(listWorktrees)
.mockResolvedValueOnce([
{
path: TEST_REPO_PATH,
head: 'main',
branch: 'refs/heads/main',
isBare: false,
isMainWorktree: true
}
])
.mockResolvedValueOnce([
{
path: TEST_REPO_PATH,
@@ -3404,12 +3482,15 @@ describe('OrcaRuntimeService', () => {
if (args[0] === 'fetch') {
return { stdout: '', stderr: '' }
}
if (args[0] === 'rev-parse') {
if (args[0] === 'rev-parse' && args[1] === '--git-path') {
return {
stdout: '/remote/repo/.git/worktrees/mobile-setup/orca/setup-runner.sh\n',
stderr: ''
}
}
if (args[0] === 'rev-parse') {
throw new Error('missing local branch')
}
throw new Error(`unexpected git call: ${args.join(' ')}`)
}),
addWorktree: vi.fn().mockResolvedValue(undefined),
@@ -3557,12 +3638,15 @@ describe('OrcaRuntimeService', () => {
if (args[0] === 'fetch') {
return { stdout: '', stderr: '' }
}
if (args[0] === 'rev-parse') {
if (args[0] === 'rev-parse' && args[1] === '--git-path') {
return {
stdout: '/remote/repo/.git/worktrees/mobile-setup-split/orca/setup-runner.sh\n',
stderr: ''
}
}
if (args[0] === 'rev-parse') {
throw new Error('missing local branch')
}
throw new Error(`unexpected git call: ${args.join(' ')}`)
}),
addWorktree: vi.fn().mockResolvedValue(undefined),
+101 -81
View File
@@ -614,6 +614,11 @@ import {
configureCreatedWorktreePushTarget,
prepareWorktreePushTarget
} from '../ipc/worktree-remote'
import {
getBranchNameOverrideCandidate,
getWorktreeCreateCandidate,
WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS
} from '../worktree-create-candidates'
import { normalizeSparseDirectories } from '../ipc/sparse-checkout-directories'
import type { Store } from '../persistence'
import type { StatsCollector } from '../stats/collector'
@@ -12625,14 +12630,6 @@ export class OrcaRuntimeService {
const sanitizedName = sanitizeWorktreeName(args.name)
let effectiveSanitizedName = sanitizedName
const username = getGitUsername(repo.path)
const branchName = await resolveCreateBranchName(
repo.path,
args.branchNameOverride,
sanitizedName,
settings,
username,
localWorktreeGitOptions
)
const baseBranch =
args.baseBranch ||
@@ -12650,32 +12647,93 @@ export class OrcaRuntimeService {
)
}
const checkoutExistingBranch = await canCheckoutExistingLocalBranch(
repo.path,
branchName,
baseBranch,
...localWorktreeGitOptionArgs
)
let branchConflictKind = checkoutExistingBranch
? null
: await getBranchConflictKind(
repo.path,
branchName,
baseBranch,
...localWorktreeGitOptionArgs
)
const allowedPushTargetRemoteConflict =
branchConflictKind && isAllowedPushTargetRemoteConflict(branchConflictKind, branchName, args)
if (branchConflictKind && !allowedPushTargetRemoteConflict) {
throw new Error(
`Branch "${branchName}" already exists ${branchConflictKind === 'local' ? 'locally' : 'on a remote'}.`
const workspaceRoot = computeWorkspaceRoot(repo.path, worktreePathSettings)
// Why: CLI-managed WSL worktrees live under ~/orca/workspaces inside the
// distro filesystem through computeWorkspaceRoot. If home lookup fails,
// still validate against the effective workspace dir.
let branchName = ''
let checkoutExistingBranch = false
let selectedExistingLocalBranchName: string | null = null
let branchConflictKind: 'local' | 'remote' | null = null
let worktreePath = ''
let worktreePathResolved = false
// Why: runtime/mobile create-from-review callers should get a new workspace
// even when the PR branch or review branch name is already in use.
for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) {
effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix)
effectiveRequestedName = args.name.trim()
? getWorktreeCreateCandidate(args.name, suffix)
: effectiveSanitizedName
branchName = await resolveCreateBranchName(
repo.path,
selectedExistingLocalBranchName ??
getBranchNameOverrideCandidate(args.branchNameOverride, suffix),
effectiveSanitizedName,
settings,
username,
localWorktreeGitOptions
)
}
checkoutExistingBranch = await canCheckoutExistingLocalBranch(
repo.path,
branchName,
baseBranch,
...localWorktreeGitOptionArgs
)
if (checkoutExistingBranch && !selectedExistingLocalBranchName) {
// Why: once a user-selected branch is safe to reuse, path retries should
// keep that branch exact instead of creating a sibling branch.
selectedExistingLocalBranchName = branchName
}
branchConflictKind = checkoutExistingBranch
? null
: await getBranchConflictKind(
repo.path,
branchName,
baseBranch,
...localWorktreeGitOptionArgs
)
const allowedPushTargetRemoteConflict =
branchConflictKind &&
isAllowedPushTargetRemoteConflict(branchConflictKind, branchName, args)
let selectedReviewConflictMatched = false
if (branchConflictKind) {
if (allowedPushTargetRemoteConflict) {
let existingPR: Awaited<ReturnType<typeof getPRForBranch>> | null = null
const selectedReview = getSelectedReviewBranch(args)
if (selectedReview?.provider === 'github') {
try {
existingPR = await getLocalGitHubPrForBranch(
repo.path,
branchName,
localWorktreeGitOptions
)
} catch {
// Retry with a suffixed branch when selected review verification is unavailable.
}
if (isMatchingSelectedGitHubPr(existingPR, args, branchName)) {
branchConflictKind = null
selectedReviewConflictMatched = true
}
} else if (selectedReview) {
const hostedReview = await getSelectedHostedReviewForBranch(
repo,
branchName,
args,
hostedReviewExecutionContext
).catch(() => null)
if (hostedReview?.matchesSelected) {
branchConflictKind = null
selectedReviewConflictMatched = true
}
}
}
if (branchConflictKind) {
continue
}
}
if (!checkoutExistingBranch) {
let existingPR: Awaited<ReturnType<typeof getPRForBranch>> | null = null
const selectedReview = getSelectedReviewBranch(args)
if (selectedReview?.provider === 'github' || !allowedPushTargetRemoteConflict) {
if (!checkoutExistingBranch && !selectedReviewConflictMatched) {
let existingPR: Awaited<ReturnType<typeof getPRForBranch>> | null = null
try {
existingPR = await getLocalGitHubPrForBranch(
repo.path,
@@ -12683,66 +12741,28 @@ export class OrcaRuntimeService {
localWorktreeGitOptions
)
} catch {
if (allowedPushTargetRemoteConflict) {
throw new Error(`Could not verify selected PR branch "${branchName}". Try again.`)
}
// 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.
// Why: GitHub reachability should not block creating a suffixed
// workspace; git conflicts still decide whether this candidate works.
}
if (existingPR && !isMatchingSelectedGitHubPr(existingPR, args, branchName)) {
continue
}
}
if (allowedPushTargetRemoteConflict) {
if (selectedReview?.provider === 'github') {
if (!isMatchingSelectedGitHubPr(existingPR, args, branchName)) {
if (existingPR) {
throw new Error(`Branch "${branchName}" already has PR #${existingPR.number}.`)
}
throw new Error(`Branch "${branchName}" already exists on a remote.`)
}
} else if (selectedReview) {
const hostedReview = await getSelectedHostedReviewForBranch(
repo,
branchName,
args,
hostedReviewExecutionContext
).catch(() => null)
if (!hostedReview?.matchesSelected) {
if (hostedReview) {
throw new Error(`Branch "${branchName}" already has PR #${hostedReview.number}.`)
}
throw new Error(`Branch "${branchName}" already exists on a remote.`)
}
}
}
if (existingPR && !isMatchingSelectedGitHubPr(existingPR, args, branchName)) {
throw new Error(`Branch "${branchName}" already has PR #${existingPR.number}.`)
}
}
const workspaceRoot = computeWorkspaceRoot(repo.path, worktreePathSettings)
// Why: CLI-managed WSL worktrees live under ~/orca/workspaces inside the
// distro filesystem through computeWorkspaceRoot. If home lookup fails,
// still validate against the effective workspace dir.
let worktreePath = ''
let worktreePathResolved = !args.branchNameOverride
for (let suffix = 1; suffix < 100; suffix += 1) {
effectiveSanitizedName = suffix === 1 ? sanitizedName : `${sanitizedName}-${suffix}`
effectiveRequestedName =
suffix === 1
? args.name
: args.name.trim()
? `${args.name}-${suffix}`
: effectiveSanitizedName
worktreePath = ensurePathWithinWorkspace(
computeWorktreePath(effectiveSanitizedName, repo.path, worktreePathSettings),
workspaceRoot
)
if (!args.branchNameOverride || !(await pathExists(worktreePath))) {
if (!(await pathExists(worktreePath))) {
worktreePathResolved = true
break
}
}
if (!worktreePathResolved) {
if (branchConflictKind) {
throw new Error(
`Branch "${branchName}" already exists ${branchConflictKind === 'local' ? 'locally' : 'on a remote'}.`
)
}
throw new Error(
`Could not find an available worktree path for "${sanitizedName}". Pick a different worktree name.`
)
+12
View File
@@ -0,0 +1,12 @@
export const WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS = 100
export function getWorktreeCreateCandidate(value: string, suffix: number): string {
return suffix === 1 ? value : `${value}-${suffix}`
}
export function getBranchNameOverrideCandidate(
branchNameOverride: string | undefined,
suffix: number
): string | undefined {
return branchNameOverride ? getWorktreeCreateCandidate(branchNameOverride, suffix) : undefined
}
+77 -44
View File
@@ -3008,40 +3008,53 @@ describe('createWorktree base status merge', () => {
)
})
it('does not suffix branchNameOverride when local IPC reports a branch conflict', async () => {
it('retries a suffixed branchNameOverride when local IPC reports a branch conflict', async () => {
const store = createTestStore()
const error = new Error(
'Branch "feature/something" already exists. Pick a different worktree name.'
)
const wt = makeWorktree({
id: 'repo1::/path/feature-something-2',
repoId: 'repo1',
path: '/path/feature-something-2',
branch: 'feature/something-2'
})
mockApi.worktrees.create.mockRejectedValueOnce(error)
mockApi.worktrees.create.mockResolvedValueOnce({ worktree: wt })
await expect(
store
.getState()
.createWorktree(
'repo1',
'feature/something',
'origin/main',
'inherit',
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
'feature/something'
)
).rejects.toThrow(error.message)
await store
.getState()
.createWorktree(
'repo1',
'feature/something',
'origin/main',
'inherit',
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
'feature/something'
)
expect(mockApi.worktrees.create).toHaveBeenCalledTimes(1)
expect(mockApi.worktrees.create).toHaveBeenCalledWith(
expect(mockApi.worktrees.create).toHaveBeenCalledTimes(2)
expect(mockApi.worktrees.create).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
name: 'feature/something',
branchNameOverride: 'feature/something'
})
)
expect(mockApi.worktrees.create).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
name: 'feature/something-2',
branchNameOverride: 'feature/something-2'
})
)
})
it('does not overwrite a newer reconcile status with the initial checking status', async () => {
@@ -3755,36 +3768,47 @@ describe('worktree remote runtime mutations', () => {
expect(runtimeEnvironmentCall).not.toHaveBeenCalled()
})
it('does not suffix branchNameOverride when runtime create reports a branch conflict', async () => {
it('retries a suffixed branchNameOverride when runtime create reports a branch conflict', async () => {
const store = createTestStore()
const wt = makeWorktree({
id: 'repo1::/path/feature-something-2',
repoId: 'repo1',
path: '/path/feature-something-2',
branch: 'feature/something-2'
})
runtimeEnvironmentCall.mockRejectedValueOnce(new Error('Branch already exists on a remote'))
runtimeEnvironmentCall.mockResolvedValueOnce({
id: 'rpc-create',
ok: true,
result: { worktree: wt },
_meta: { runtimeId: 'runtime-remote' }
})
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as never,
worktreesByRepo: { repo1: [] }
} as Partial<AppState>)
await expect(
store
.getState()
.createWorktree(
'repo1',
'feature/something',
'origin/main',
'skip',
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
'feature/something'
)
).rejects.toThrow('Branch already exists on a remote')
await store
.getState()
.createWorktree(
'repo1',
'feature/something',
'origin/main',
'skip',
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
'feature/something'
)
expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(1)
expect(runtimeEnvironmentCall).toHaveBeenCalledWith(
expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(2)
expect(runtimeEnvironmentCall).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
params: expect.objectContaining({
name: 'feature/something',
@@ -3792,6 +3816,15 @@ describe('worktree remote runtime mutations', () => {
})
})
)
expect(runtimeEnvironmentCall).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
params: expect.objectContaining({
name: 'feature/something-2',
branchNameOverride: 'feature/something-2'
})
})
)
})
it('removes worktrees through the active remote runtime environment', async () => {
+11 -13
View File
@@ -2584,18 +2584,15 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
]
const nextCandidateName = (current: string, attempt: number): string =>
attempt === 0 ? current : `${current}-${attempt + 1}`
const isBranchNameOverrideConflict = (error: Error): boolean =>
Boolean(
branchNameOverride &&
(/^Branch ".+" already exists\./i.test(error.message) ||
/already exists locally/i.test(error.message) ||
/already exists on a remote/i.test(error.message) ||
/already has pr #\d+/i.test(error.message))
)
try {
for (let attempt = 0; attempt < 25; attempt += 1) {
const candidateName = nextCandidateName(name, attempt)
// Why: older runtimes may still reject exact PR branch overrides on
// collision, so the renderer retries both branch and worktree names.
const candidateBranchNameOverride = branchNameOverride
? nextCandidateName(branchNameOverride, attempt)
: undefined
try {
// Why: Manual sort is user-authored order. Stamp new workspaces
// deliberately at the top instead of relying on sortOrder fallback.
@@ -2610,7 +2607,9 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
name: candidateName,
baseBranch,
...(compareBaseRef ? { compareBaseRef } : {}),
...(branchNameOverride ? { branchNameOverride } : {}),
...(candidateBranchNameOverride
? { branchNameOverride: candidateBranchNameOverride }
: {}),
setupDecision,
sparseCheckout,
...(displayName ? { displayName } : {}),
@@ -2651,7 +2650,9 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
name: candidateName,
baseBranch,
...(compareBaseRef ? { compareBaseRef } : {}),
...(branchNameOverride ? { branchNameOverride } : {}),
...(candidateBranchNameOverride
? { branchNameOverride: candidateBranchNameOverride }
: {}),
setupDecision,
sparseCheckout,
...(displayName ? { displayName } : {}),
@@ -2747,9 +2748,6 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
const shouldRetry = retryableConflictPatterns.some((pattern) => pattern.test(message))
if (error instanceof Error && isBranchNameOverrideConflict(error)) {
throw error
}
if (!shouldRetry || attempt === 24) {
throw error
}