fix: address review findings (#3866)
This commit is contained in:
@@ -2,7 +2,8 @@ import type {
|
||||
RuntimeWorktreeListResult,
|
||||
RuntimeWorktreePsResult,
|
||||
RuntimeWorktreeRecord,
|
||||
RuntimeWorktreeCreateResult
|
||||
RuntimeWorktreeCreateResult,
|
||||
RuntimeWorktreeRemoveResult
|
||||
} from '../../shared/runtime-types'
|
||||
import type { CommandHandler } from '../dispatch'
|
||||
import { formatWorktreeList, formatWorktreePs, formatWorktreeShow, printResult } from '../format'
|
||||
@@ -24,12 +25,26 @@ type HookWarningResult = {
|
||||
warning?: string
|
||||
}
|
||||
|
||||
type PreservedBranchResult = {
|
||||
preservedBranch?: {
|
||||
branchName: string
|
||||
}
|
||||
}
|
||||
|
||||
function printHookWarning(result: HookWarningResult, json: boolean): void {
|
||||
if (!json && result.warning) {
|
||||
console.error(`warning: ${result.warning}`)
|
||||
}
|
||||
}
|
||||
|
||||
function printPreservedBranchWarning(result: PreservedBranchResult, json: boolean): void {
|
||||
if (!json && result.preservedBranch) {
|
||||
console.error(
|
||||
`warning: local branch "${result.preservedBranch.branchName}" was kept because Git could not safely delete it`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function printLineageSummary(result: RuntimeWorktreeCreateResult, json: boolean): void {
|
||||
if (json) {
|
||||
return
|
||||
@@ -152,12 +167,13 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
|
||||
printResult(result, json, formatWorktreeShow)
|
||||
},
|
||||
'worktree rm': async ({ flags, client, cwd, json }) => {
|
||||
const result = await client.call<{ removed: boolean; warning?: string }>('worktree.rm', {
|
||||
const result = await client.call<RuntimeWorktreeRemoveResult>('worktree.rm', {
|
||||
worktree: await getRequiredWorktreeSelector(flags, 'worktree', cwd, client),
|
||||
force: flags.get('force') === true,
|
||||
runHooks: flags.get('run-hooks') === true
|
||||
})
|
||||
printHookWarning(result.result, json)
|
||||
printPreservedBranchWarning(result.result, json)
|
||||
printResult(result, json, (value) => `removed: ${value.removed}`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ vi.mock('fs/promises', async () => {
|
||||
import {
|
||||
addSparseWorktree,
|
||||
assertWorktreeCleanForRemoval,
|
||||
forceDeleteLocalBranch,
|
||||
listWorktrees,
|
||||
removeWorktree
|
||||
} from './worktree'
|
||||
@@ -117,11 +118,11 @@ branch refs/heads/main
|
||||
expect.arrayContaining([
|
||||
'git worktree remove /repo-feature',
|
||||
'git worktree prune',
|
||||
'git branch -d feature/test'
|
||||
'git branch -d -- feature/test'
|
||||
])
|
||||
)
|
||||
expectGitCallOrder(calls, 'git worktree remove /repo-feature', 'git worktree prune')
|
||||
expectGitCallOrder(calls, 'git worktree prune', 'git branch -d feature/test')
|
||||
expectGitCallOrder(calls, 'git worktree prune', 'git branch -d -- feature/test')
|
||||
})
|
||||
|
||||
it('preserves the branch when requested for a pre-existing local branch checkout', async () => {
|
||||
@@ -144,8 +145,8 @@ branch refs/heads/feature/test
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining(['git worktree remove /repo-feature', 'git worktree prune'])
|
||||
)
|
||||
expect(calls).not.toContain('git branch -d feature/test')
|
||||
expect(calls).not.toContain('git branch -D feature/test')
|
||||
expect(calls).not.toContain('git branch -d -- feature/test')
|
||||
expect(calls).not.toContain('git branch -D -- feature/test')
|
||||
})
|
||||
|
||||
it('skips branch deletion when another worktree still points at the branch', async () => {
|
||||
@@ -186,8 +187,8 @@ branch refs/heads/feature/test
|
||||
'git worktree list --porcelain'
|
||||
])
|
||||
)
|
||||
expect(calls).not.toContain('git branch -d feature/test')
|
||||
expect(calls).not.toContain('git branch -D feature/test')
|
||||
expect(calls).not.toContain('git branch -d -- feature/test')
|
||||
expect(calls).not.toContain('git branch -D -- feature/test')
|
||||
expectGitCallOrder(calls, 'git worktree remove /repo-feature', 'git worktree prune')
|
||||
})
|
||||
|
||||
@@ -223,10 +224,10 @@ branch refs/heads/main
|
||||
expect.arrayContaining([
|
||||
'git worktree remove /repo-feature',
|
||||
'git worktree prune',
|
||||
'git branch -d feature/test'
|
||||
'git branch -d -- feature/test'
|
||||
])
|
||||
)
|
||||
expectGitCallOrder(calls, 'git worktree prune', 'git branch -d feature/test')
|
||||
expectGitCallOrder(calls, 'git worktree prune', 'git branch -d -- feature/test')
|
||||
})
|
||||
|
||||
it('passes --force before the worktree path when forced removal is requested', async () => {
|
||||
@@ -281,7 +282,7 @@ branch refs/heads/main
|
||||
expect.arrayContaining([
|
||||
'git worktree remove c:\\workspaces\\delete-branch-ui-test',
|
||||
'git worktree prune',
|
||||
'git branch -d feature/test'
|
||||
'git branch -d -- feature/test'
|
||||
])
|
||||
)
|
||||
})
|
||||
@@ -305,13 +306,15 @@ HEAD abc123
|
||||
branch refs/heads/main
|
||||
`
|
||||
},
|
||||
'git branch -d feature/test': {
|
||||
'git branch -d -- feature/test': {
|
||||
error: new Error('branch delete failed'),
|
||||
stderr: 'branch delete failed'
|
||||
}
|
||||
})
|
||||
|
||||
await expect(removeWorktree('/repo', '/repo-feature')).resolves.toBeUndefined()
|
||||
await expect(removeWorktree('/repo', '/repo-feature')).resolves.toEqual({
|
||||
preservedBranch: { branchName: 'feature/test', head: 'def456' }
|
||||
})
|
||||
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
'[git] Preserved local branch "feature/test" after removing worktree (not fully merged)',
|
||||
@@ -320,6 +323,73 @@ branch refs/heads/main
|
||||
|
||||
warnSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('force-deletes a preserved branch only at its saved head', async () => {
|
||||
mockGitCommands({})
|
||||
|
||||
await forceDeleteLocalBranch('/repo', 'feature/test', 'def456')
|
||||
|
||||
const calls = getGitCalls()
|
||||
expect(calls).toContain('git worktree list --porcelain')
|
||||
expect(calls).toContain('git update-ref -d refs/heads/feature/test def456')
|
||||
expect(calls).toContain('git config --remove-section branch.feature/test')
|
||||
})
|
||||
|
||||
it('refuses to force-delete a preserved branch that is checked out again', async () => {
|
||||
mockGitCommands({
|
||||
'git worktree list --porcelain': {
|
||||
stdout: `worktree /repo-feature
|
||||
HEAD def456
|
||||
branch refs/heads/feature/test
|
||||
`
|
||||
}
|
||||
})
|
||||
|
||||
await expect(forceDeleteLocalBranch('/repo', 'feature/test', 'def456')).rejects.toThrow(
|
||||
'checked out in another worktree'
|
||||
)
|
||||
expect(getGitCalls()).not.toContain('git update-ref -d refs/heads/feature/test def456')
|
||||
})
|
||||
|
||||
it('restores a preserved branch when a concurrent checkout wins after deletion', async () => {
|
||||
mockGitCommands({
|
||||
'git worktree list --porcelain': {
|
||||
stdout: `worktree /repo
|
||||
HEAD abc123
|
||||
branch refs/heads/main
|
||||
`
|
||||
},
|
||||
'git worktree list --porcelain#2': {
|
||||
stdout: `worktree /repo-feature
|
||||
HEAD 0000000000000000000000000000000000000000
|
||||
branch refs/heads/feature/test
|
||||
`
|
||||
}
|
||||
})
|
||||
|
||||
await expect(forceDeleteLocalBranch('/repo', 'feature/test', 'def456')).rejects.toThrow(
|
||||
'checked out in another worktree'
|
||||
)
|
||||
expect(gitExecFileAsyncMock.mock.calls.map((call) => call[0])).toContainEqual([
|
||||
'update-ref',
|
||||
'refs/heads/feature/test',
|
||||
'def456',
|
||||
''
|
||||
])
|
||||
})
|
||||
|
||||
it('refuses to force-delete a preserved branch after its head changes', async () => {
|
||||
mockGitCommands({
|
||||
'git update-ref -d refs/heads/feature/test def456': {
|
||||
error: new Error('cannot lock ref')
|
||||
}
|
||||
})
|
||||
|
||||
await expect(forceDeleteLocalBranch('/repo', 'feature/test', 'def456')).rejects.toThrow(
|
||||
'changed after the workspace was deleted'
|
||||
)
|
||||
expect(getGitCalls()).not.toContain('git config --remove-section branch.feature/test')
|
||||
})
|
||||
})
|
||||
|
||||
describe('assertWorktreeCleanForRemoval', () => {
|
||||
@@ -576,7 +646,7 @@ branch refs/heads/main
|
||||
'git sparse-checkout set -- packages/web',
|
||||
'git worktree remove --force /repo-feature',
|
||||
'git worktree prune',
|
||||
'git branch -D feature/test'
|
||||
'git branch -D -- feature/test'
|
||||
])
|
||||
)
|
||||
expectGitCallOrder(
|
||||
@@ -584,6 +654,6 @@ branch refs/heads/main
|
||||
'git sparse-checkout set -- packages/web',
|
||||
'git worktree remove --force /repo-feature'
|
||||
)
|
||||
expectGitCallOrder(calls, 'git worktree prune', 'git branch -D feature/test')
|
||||
expectGitCallOrder(calls, 'git worktree prune', 'git branch -D -- feature/test')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -846,6 +846,7 @@ describe('addWorktree', () => {
|
||||
expect(gitExecFileAsyncMock.mock.calls.map((call) => call[0])).toContainEqual([
|
||||
'branch',
|
||||
'-D',
|
||||
'--',
|
||||
'feature/test'
|
||||
])
|
||||
})
|
||||
@@ -871,11 +872,13 @@ describe('removeWorktree', () => {
|
||||
gitExecFileAsyncMock.mockRejectedValueOnce(new Error('not fully merged')) // branch -d
|
||||
|
||||
// Should not throw — the unmerged branch is preserved, not force-deleted.
|
||||
await expect(removeWorktree('/repo', '/repo-feature', false)).resolves.toBeUndefined()
|
||||
await expect(removeWorktree('/repo', '/repo-feature', false)).resolves.toEqual({
|
||||
preservedBranch: { branchName: 'feature/test', head: 'def456' }
|
||||
})
|
||||
|
||||
const calls = gitExecFileAsyncMock.mock.calls.map((call) => call[0])
|
||||
expect(calls).toContainEqual(['branch', '-d', 'feature/test'])
|
||||
expect(calls).not.toContainEqual(['branch', '-D', 'feature/test'])
|
||||
expect(calls).toContainEqual(['branch', '-d', '--', 'feature/test'])
|
||||
expect(calls).not.toContainEqual(['branch', '-D', '--', 'feature/test'])
|
||||
})
|
||||
|
||||
it('deletes the branch when `branch -d` succeeds (fully merged)', async () => {
|
||||
@@ -890,6 +893,7 @@ describe('removeWorktree', () => {
|
||||
expect(gitExecFileAsyncMock.mock.calls.map((call) => call[0])).toContainEqual([
|
||||
'branch',
|
||||
'-d',
|
||||
'--',
|
||||
'feature/test'
|
||||
])
|
||||
})
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
import { stat } from 'fs/promises'
|
||||
import { join, posix, win32 } from 'path'
|
||||
import { resolveWorktreeAddBaseRef } from '../../shared/worktree-base-ref'
|
||||
import type { GitWorktreeInfo, LocalBaseRefRefreshResult } from '../../shared/types'
|
||||
import type {
|
||||
GitWorktreeInfo,
|
||||
LocalBaseRefRefreshResult,
|
||||
RemoveWorktreeResult
|
||||
} from '../../shared/types'
|
||||
import { gitExecFileAsync, translateWslOutputPaths } from './runner'
|
||||
import { resolveGitDir } from './status'
|
||||
import { hasWorktreeBaseCommitRef } from './worktree-base-ref-probe'
|
||||
@@ -460,12 +464,13 @@ export async function removeWorktree(
|
||||
// and must be removed outright. User-initiated deletes leave it false so unmerged
|
||||
// commits are preserved.
|
||||
options: { deleteBranch?: boolean; forceBranchDelete?: boolean } = {}
|
||||
): Promise<void> {
|
||||
): Promise<RemoveWorktreeResult> {
|
||||
const worktreesBeforeRemoval = await listWorktrees(repoPath)
|
||||
const removedWorktree = worktreesBeforeRemoval.find((worktree) =>
|
||||
areWorktreePathsEqual(worktree.path, worktreePath)
|
||||
)
|
||||
const branchName = normalizeLocalBranchRef(removedWorktree?.branch ?? '')
|
||||
const branchHead = removedWorktree?.head ?? ''
|
||||
|
||||
const args = ['worktree', 'remove']
|
||||
if (force) {
|
||||
@@ -476,10 +481,10 @@ export async function removeWorktree(
|
||||
await gitExecFileAsync(['worktree', 'prune'], { cwd: repoPath })
|
||||
|
||||
if (!branchName) {
|
||||
return
|
||||
return {}
|
||||
}
|
||||
if (options.deleteBranch === false) {
|
||||
return
|
||||
return {}
|
||||
}
|
||||
|
||||
// Why: `git worktree list` can still include stale sibling records until
|
||||
@@ -490,7 +495,7 @@ export async function removeWorktree(
|
||||
(worktree) => normalizeLocalBranchRef(worktree.branch) === branchName
|
||||
)
|
||||
if (branchStillInUse) {
|
||||
return
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -502,7 +507,8 @@ export async function removeWorktree(
|
||||
// force-deleted. forceBranchDelete opts into `-D` for failed-creation rollback,
|
||||
// where the fresh branch has no user work to protect.
|
||||
const deleteFlag = options.forceBranchDelete ? '-D' : '-d'
|
||||
await gitExecFileAsync(['branch', deleteFlag, branchName], { cwd: repoPath })
|
||||
await gitExecFileAsync(['branch', deleteFlag, '--', branchName], { cwd: repoPath })
|
||||
return {}
|
||||
} catch (error) {
|
||||
// Expected when the branch still has unmerged/unpublished commits: keep it.
|
||||
// Deleting a worktree must never silently discard commits.
|
||||
@@ -510,9 +516,69 @@ export async function removeWorktree(
|
||||
`[git] Preserved local branch "${branchName}" after removing worktree (not fully merged)`,
|
||||
error
|
||||
)
|
||||
return { preservedBranch: { branchName, ...(branchHead ? { head: branchHead } : {}) } }
|
||||
}
|
||||
}
|
||||
|
||||
export async function forceDeleteLocalBranch(
|
||||
repoPath: string,
|
||||
branchName: string,
|
||||
expectedHead: string,
|
||||
runGit: (args: string[], cwd: string) => Promise<{ stdout: string; stderr: string }> = (
|
||||
args,
|
||||
cwd
|
||||
) => gitExecFileAsync(args, { cwd })
|
||||
): Promise<void> {
|
||||
if (!branchName || branchName.includes('\0')) {
|
||||
throw new Error('Invalid branch name')
|
||||
}
|
||||
if (!expectedHead) {
|
||||
throw new Error(
|
||||
`Cannot force-delete local branch "${branchName}" without the commit Git preserved.`
|
||||
)
|
||||
}
|
||||
if (await isLocalBranchCheckedOut(repoPath, branchName, runGit)) {
|
||||
throw new Error(`Local branch "${branchName}" is checked out in another worktree.`)
|
||||
}
|
||||
// Why: stale toast actions must not delete a branch that moved after Git
|
||||
// preserved it. `update-ref` deletes only if the ref still has expectedHead.
|
||||
try {
|
||||
await runGit(['update-ref', '-d', `refs/heads/${branchName}`, expectedHead], repoPath)
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Local branch "${branchName}" changed after the workspace was deleted. Review it before deleting it.`
|
||||
)
|
||||
}
|
||||
if (await isLocalBranchCheckedOut(repoPath, branchName, runGit)) {
|
||||
try {
|
||||
await runGit(['update-ref', `refs/heads/${branchName}`, expectedHead, ''], repoPath)
|
||||
} catch (restoreError) {
|
||||
console.warn(
|
||||
`[git] Failed to restore local branch "${branchName}" after concurrent checkout`,
|
||||
restoreError
|
||||
)
|
||||
}
|
||||
throw new Error(`Local branch "${branchName}" is checked out in another worktree.`)
|
||||
}
|
||||
try {
|
||||
await runGit(['config', '--remove-section', `branch.${branchName}`], repoPath)
|
||||
} catch {
|
||||
// Best-effort parity with `git branch -D`; stale config is harmless and
|
||||
// should not make the already-deleted ref look like a failed delete.
|
||||
}
|
||||
}
|
||||
|
||||
async function isLocalBranchCheckedOut(
|
||||
repoPath: string,
|
||||
branchName: string,
|
||||
runGit: (args: string[], cwd: string) => Promise<{ stdout: string; stderr: string }>
|
||||
): Promise<boolean> {
|
||||
const { stdout } = await runGit(['worktree', 'list', '--porcelain'], repoPath)
|
||||
return parseWorktreeList(stdout).some(
|
||||
(worktree) => normalizeLocalBranchRef(worktree.branch) === branchName
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert a worktree is clean enough for non-force removal.
|
||||
*/
|
||||
|
||||
@@ -13,6 +13,7 @@ const {
|
||||
addWorktreeMock,
|
||||
addSparseWorktreeMock,
|
||||
removeWorktreeMock,
|
||||
forceDeleteLocalBranchMock,
|
||||
getGitUsernameMock,
|
||||
getDefaultBaseRefMock,
|
||||
getDefaultRemoteMock,
|
||||
@@ -58,6 +59,7 @@ const {
|
||||
addWorktreeMock: vi.fn(),
|
||||
addSparseWorktreeMock: vi.fn(),
|
||||
removeWorktreeMock: vi.fn(),
|
||||
forceDeleteLocalBranchMock: vi.fn(),
|
||||
getGitUsernameMock: vi.fn(),
|
||||
getDefaultBaseRefMock: vi.fn(),
|
||||
getDefaultRemoteMock: vi.fn(),
|
||||
@@ -98,7 +100,8 @@ vi.mock('../git/worktree', () => ({
|
||||
assertWorktreeCleanForRemoval: assertWorktreeCleanForRemovalMock,
|
||||
addWorktree: addWorktreeMock,
|
||||
addSparseWorktree: addSparseWorktreeMock,
|
||||
removeWorktree: removeWorktreeMock
|
||||
removeWorktree: removeWorktreeMock,
|
||||
forceDeleteLocalBranch: forceDeleteLocalBranchMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/runner', () => ({
|
||||
@@ -233,6 +236,7 @@ describe('registerWorktreeHandlers', () => {
|
||||
addWorktreeMock,
|
||||
addSparseWorktreeMock,
|
||||
removeWorktreeMock,
|
||||
forceDeleteLocalBranchMock,
|
||||
getGitUsernameMock,
|
||||
getDefaultBaseRefMock,
|
||||
getDefaultRemoteMock,
|
||||
@@ -372,6 +376,7 @@ describe('registerWorktreeHandlers', () => {
|
||||
)
|
||||
ensurePathWithinWorkspaceMock.mockImplementation((targetPath: string) => targetPath)
|
||||
listWorktreesMock.mockResolvedValue([])
|
||||
forceDeleteLocalBranchMock.mockResolvedValue(undefined)
|
||||
|
||||
// Why: createLocalWorktree routes `git fetch` through
|
||||
// `runtime.fetchRemoteWithCache` (§3.3 Lifecycle). A minimal stub
|
||||
@@ -3200,6 +3205,49 @@ describe('registerWorktreeHandlers', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('force-deletes a branch that was preserved by safe worktree removal', async () => {
|
||||
mockKnownFeatureWorktree()
|
||||
removeWorktreeMock.mockResolvedValue({
|
||||
preservedBranch: { branchName: 'feature/test', head: 'def456' }
|
||||
})
|
||||
|
||||
await handlers['worktrees:remove'](null, {
|
||||
worktreeId: 'repo-1::/workspace/feature-wt'
|
||||
})
|
||||
const result = await handlers['worktrees:forceDeletePreservedBranch'](null, {
|
||||
worktreeId: 'repo-1::/workspace/feature-wt',
|
||||
branchName: 'feature/test',
|
||||
expectedHead: 'def456'
|
||||
})
|
||||
|
||||
expect(result).toEqual({ deleted: true })
|
||||
expect(forceDeleteLocalBranchMock).toHaveBeenCalledWith(
|
||||
'/workspace/repo',
|
||||
'feature/test',
|
||||
'def456'
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects stale preserved-branch cleanup actions with an old head', async () => {
|
||||
mockKnownFeatureWorktree()
|
||||
removeWorktreeMock.mockResolvedValue({
|
||||
preservedBranch: { branchName: 'feature/test', head: 'new456' }
|
||||
})
|
||||
|
||||
await handlers['worktrees:remove'](null, {
|
||||
worktreeId: 'repo-1::/workspace/feature-wt'
|
||||
})
|
||||
|
||||
await expect(
|
||||
handlers['worktrees:forceDeletePreservedBranch'](null, {
|
||||
worktreeId: 'repo-1::/workspace/feature-wt',
|
||||
branchName: 'feature/test',
|
||||
expectedHead: 'old123'
|
||||
})
|
||||
).rejects.toThrow('No preserved branch cleanup is pending')
|
||||
expect(forceDeleteLocalBranchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('removes an unused Orca-created fork remote after deleting its worktree', async () => {
|
||||
mockKnownFeatureWorktree()
|
||||
removeWorktreeMock.mockResolvedValue(undefined)
|
||||
@@ -3533,18 +3581,18 @@ describe('registerWorktreeHandlers', () => {
|
||||
const first = handlers['worktrees:remove'](null, {
|
||||
worktreeId: 'repo-1::/workspace/feature-wt',
|
||||
force: true
|
||||
}) as Promise<void>
|
||||
}) as Promise<unknown>
|
||||
const second = handlers['worktrees:remove'](null, {
|
||||
worktreeId: 'repo-1::/workspace/feature-wt',
|
||||
force: true
|
||||
}) as Promise<void>
|
||||
}) as Promise<unknown>
|
||||
|
||||
await started
|
||||
await Promise.resolve()
|
||||
expect(removeWorktreeMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
finishRemoval()
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([undefined, undefined])
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([{}, {}])
|
||||
expect(store.removeWorktreeMeta).toHaveBeenCalledTimes(1)
|
||||
expect(deleteWorktreeHistoryDirMock).toHaveBeenCalledTimes(1)
|
||||
expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1)
|
||||
@@ -3567,7 +3615,7 @@ describe('registerWorktreeHandlers', () => {
|
||||
|
||||
const first = handlers['worktrees:remove'](null, {
|
||||
worktreeId: 'repo-1::/workspace/feature-wt'
|
||||
}) as Promise<void>
|
||||
}) as Promise<unknown>
|
||||
|
||||
await started
|
||||
await expect(
|
||||
@@ -3579,7 +3627,7 @@ describe('registerWorktreeHandlers', () => {
|
||||
|
||||
expect(removeWorktreeMock).toHaveBeenCalledTimes(1)
|
||||
finishRemoval()
|
||||
await expect(first).resolves.toBeUndefined()
|
||||
await expect(first).resolves.toEqual({})
|
||||
})
|
||||
|
||||
it('still rejects forced unregistered delete paths that exist on disk', async () => {
|
||||
|
||||
+152
-14
@@ -12,10 +12,12 @@ import type {
|
||||
CreateWorktreeResult,
|
||||
DetectedWorktree,
|
||||
DetectedWorktreeListResult,
|
||||
ForceDeleteWorktreeBranchResult,
|
||||
GitPushTarget,
|
||||
GitWorktreeInfo,
|
||||
OrcaHooks,
|
||||
Repo,
|
||||
RemoveWorktreeResult,
|
||||
Worktree,
|
||||
WorktreeMeta
|
||||
} from '../../shared/types'
|
||||
@@ -26,6 +28,7 @@ import {
|
||||
} from '../../shared/worktree-ownership'
|
||||
import {
|
||||
assertWorktreeCleanForRemoval,
|
||||
forceDeleteLocalBranch,
|
||||
listWorktrees as listGitWorktrees,
|
||||
removeWorktree
|
||||
} from '../git/worktree'
|
||||
@@ -199,7 +202,66 @@ async function runRemoteArchiveHook(
|
||||
|
||||
type WorktreeRemovalInFlight = {
|
||||
optionsKey: string
|
||||
promise: Promise<void>
|
||||
promise: Promise<RemoveWorktreeResult>
|
||||
}
|
||||
|
||||
type PreservedBranchCleanupTarget = {
|
||||
branchName: string
|
||||
head: string
|
||||
pushTarget?: GitPushTarget
|
||||
}
|
||||
|
||||
const preservedBranchCleanupByWorktreeId = new Map<string, PreservedBranchCleanupTarget>()
|
||||
|
||||
function rememberPreservedBranchCleanupTarget(
|
||||
worktreeId: string,
|
||||
result: RemoveWorktreeResult | undefined,
|
||||
fallbackHead: string | undefined,
|
||||
pushTarget: GitPushTarget | undefined
|
||||
): void {
|
||||
if (result?.preservedBranch) {
|
||||
const head = result.preservedBranch.head ?? fallbackHead
|
||||
if (!head) {
|
||||
throw new Error(
|
||||
`Cannot safely offer force-delete for preserved branch "${result.preservedBranch.branchName}" without its saved commit.`
|
||||
)
|
||||
}
|
||||
preservedBranchCleanupByWorktreeId.set(worktreeId, {
|
||||
branchName: result.preservedBranch.branchName,
|
||||
head,
|
||||
...(pushTarget ? { pushTarget } : {})
|
||||
})
|
||||
return
|
||||
}
|
||||
preservedBranchCleanupByWorktreeId.delete(worktreeId)
|
||||
}
|
||||
|
||||
function preserveBranchHeadFallback(
|
||||
result: RemoveWorktreeResult | undefined,
|
||||
fallbackHead: string | undefined
|
||||
): RemoveWorktreeResult {
|
||||
if (!result?.preservedBranch || result.preservedBranch.head || !fallbackHead) {
|
||||
return result ?? {}
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
preservedBranch: {
|
||||
...result.preservedBranch,
|
||||
head: fallbackHead
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getPreservedBranchCleanupTarget(
|
||||
worktreeId: string,
|
||||
branchName: string,
|
||||
expectedHead: string
|
||||
): PreservedBranchCleanupTarget {
|
||||
const target = preservedBranchCleanupByWorktreeId.get(worktreeId)
|
||||
if (!target || target.branchName !== branchName || target.head !== expectedHead) {
|
||||
throw new Error(`No preserved branch cleanup is pending for "${branchName}".`)
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
const loggedUnavailableSshGitProviders = new Set<string>()
|
||||
@@ -547,6 +609,7 @@ export function registerWorktreeHandlers(
|
||||
ipcMain.removeHandler('worktrees:resolvePrBase')
|
||||
ipcMain.removeHandler('worktrees:resolveMrBase')
|
||||
ipcMain.removeHandler('worktrees:remove')
|
||||
ipcMain.removeHandler('worktrees:forceDeletePreservedBranch')
|
||||
ipcMain.removeHandler('worktrees:updateMeta')
|
||||
ipcMain.removeHandler('worktrees:listLineage')
|
||||
ipcMain.removeHandler('worktrees:updateLineage')
|
||||
@@ -911,7 +974,7 @@ export function registerWorktreeHandlers(
|
||||
// Why: stale toast actions, double-clicks, and Space/sidebar races can
|
||||
// target the same worktree concurrently. Share the destructive backend
|
||||
// operation so only one path touches Git and the filesystem.
|
||||
const removal = (async (): Promise<void> => {
|
||||
const removal = (async (): Promise<RemoveWorktreeResult> => {
|
||||
const { repoId, worktreePath } = parseWorktreeId(args.worktreeId)
|
||||
const repo = store.getRepo(repoId)
|
||||
if (!repo) {
|
||||
@@ -933,8 +996,9 @@ export function registerWorktreeHandlers(
|
||||
})
|
||||
store.removeWorktreeMeta(args.worktreeId)
|
||||
deleteWorktreeHistoryDir(args.worktreeId)
|
||||
preservedBranchCleanupByWorktreeId.delete(args.worktreeId)
|
||||
notifyWorktreesChanged(mainWindow, repoId)
|
||||
return
|
||||
return {}
|
||||
}
|
||||
|
||||
// Why: the renderer-supplied worktreeId contains a filesystem path.
|
||||
@@ -1011,8 +1075,9 @@ export function registerWorktreeHandlers(
|
||||
runtime.clearOptimisticReconcileToken(args.worktreeId)
|
||||
store.removeWorktreeMeta(args.worktreeId)
|
||||
deleteWorktreeHistoryDir(args.worktreeId)
|
||||
preservedBranchCleanupByWorktreeId.delete(args.worktreeId)
|
||||
notifyWorktreesChanged(mainWindow, repoId)
|
||||
return
|
||||
return {}
|
||||
}
|
||||
if (args.force && (await isAlreadyRemovedWorktreePath(repo, worktreePath))) {
|
||||
// Why: Force-delete can be retried from stale UI after a prior delete
|
||||
@@ -1038,8 +1103,9 @@ export function registerWorktreeHandlers(
|
||||
runtime.clearOptimisticReconcileToken(args.worktreeId)
|
||||
store.removeWorktreeMeta(args.worktreeId)
|
||||
deleteWorktreeHistoryDir(args.worktreeId)
|
||||
preservedBranchCleanupByWorktreeId.delete(args.worktreeId)
|
||||
notifyWorktreesChanged(mainWindow, repoId)
|
||||
return
|
||||
return {}
|
||||
}
|
||||
throw new Error(`Refusing to delete unregistered worktree path: ${worktreePath}`)
|
||||
}
|
||||
@@ -1074,9 +1140,13 @@ export function registerWorktreeHandlers(
|
||||
}
|
||||
}
|
||||
|
||||
await (deleteBranch
|
||||
const rawRemovalResult = await (deleteBranch
|
||||
? provider!.removeWorktree(canonicalWorktreePath, args.force)
|
||||
: provider!.removeWorktree(canonicalWorktreePath, args.force, { deleteBranch }))
|
||||
const removalResult = preserveBranchHeadFallback(
|
||||
rawRemovalResult,
|
||||
registeredWorktree.head
|
||||
)
|
||||
await cleanupUnusedWorktreePushTargetRemoteSsh(
|
||||
provider!,
|
||||
repo.path,
|
||||
@@ -1084,11 +1154,17 @@ export function registerWorktreeHandlers(
|
||||
removedPushTarget,
|
||||
store
|
||||
)
|
||||
rememberPreservedBranchCleanupTarget(
|
||||
args.worktreeId,
|
||||
removalResult,
|
||||
registeredWorktree.head,
|
||||
removedPushTarget
|
||||
)
|
||||
runtime.clearOptimisticReconcileToken(args.worktreeId)
|
||||
store.removeWorktreeMeta(args.worktreeId)
|
||||
deleteWorktreeHistoryDir(args.worktreeId)
|
||||
notifyWorktreesChanged(mainWindow, repoId)
|
||||
return
|
||||
return removalResult ?? {}
|
||||
}
|
||||
|
||||
// Why: `git worktree remove` (non-force) refuses to delete a worktree
|
||||
@@ -1133,12 +1209,16 @@ export function registerWorktreeHandlers(
|
||||
})
|
||||
}
|
||||
|
||||
let removalResult: RemoveWorktreeResult | undefined
|
||||
try {
|
||||
await (deleteBranch
|
||||
? removeWorktree(repo.path, canonicalWorktreePath, args.force ?? false)
|
||||
: removeWorktree(repo.path, canonicalWorktreePath, args.force ?? false, {
|
||||
deleteBranch
|
||||
}))
|
||||
removalResult = preserveBranchHeadFallback(
|
||||
await (deleteBranch
|
||||
? removeWorktree(repo.path, canonicalWorktreePath, args.force ?? false)
|
||||
: removeWorktree(repo.path, canonicalWorktreePath, args.force ?? false, {
|
||||
deleteBranch
|
||||
})),
|
||||
registeredWorktree.head
|
||||
)
|
||||
} catch (error) {
|
||||
// If git no longer tracks this worktree, clean up the directory and metadata
|
||||
if (isOrphanedWorktreeError(error)) {
|
||||
@@ -1166,9 +1246,10 @@ export function registerWorktreeHandlers(
|
||||
runtime.clearOptimisticReconcileToken(args.worktreeId)
|
||||
store.removeWorktreeMeta(args.worktreeId)
|
||||
deleteWorktreeHistoryDir(args.worktreeId)
|
||||
preservedBranchCleanupByWorktreeId.delete(args.worktreeId)
|
||||
invalidateAuthorizedRootsCache()
|
||||
notifyWorktreesChanged(mainWindow, repoId)
|
||||
return
|
||||
return {}
|
||||
}
|
||||
throw new Error(
|
||||
formatWorktreeRemovalError(error, canonicalWorktreePath, args.force ?? false)
|
||||
@@ -1180,16 +1261,23 @@ export function registerWorktreeHandlers(
|
||||
removedPushTarget,
|
||||
store
|
||||
)
|
||||
rememberPreservedBranchCleanupTarget(
|
||||
args.worktreeId,
|
||||
removalResult,
|
||||
registeredWorktree.head,
|
||||
removedPushTarget
|
||||
)
|
||||
runtime.clearOptimisticReconcileToken(args.worktreeId)
|
||||
store.removeWorktreeMeta(args.worktreeId)
|
||||
deleteWorktreeHistoryDir(args.worktreeId)
|
||||
invalidateAuthorizedRootsCache()
|
||||
|
||||
notifyWorktreesChanged(mainWindow, repoId)
|
||||
return removalResult ?? {}
|
||||
})()
|
||||
worktreeRemovalsInFlight.set(args.worktreeId, { optionsKey, promise: removal })
|
||||
try {
|
||||
await removal
|
||||
return await removal
|
||||
} finally {
|
||||
if (worktreeRemovalsInFlight.get(args.worktreeId)?.promise === removal) {
|
||||
worktreeRemovalsInFlight.delete(args.worktreeId)
|
||||
@@ -1198,6 +1286,56 @@ export function registerWorktreeHandlers(
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'worktrees:forceDeletePreservedBranch',
|
||||
async (
|
||||
_event,
|
||||
args: { worktreeId: string; branchName: string; expectedHead: string }
|
||||
): Promise<ForceDeleteWorktreeBranchResult> => {
|
||||
const { repoId } = parseWorktreeId(args.worktreeId)
|
||||
const cleanupTarget = getPreservedBranchCleanupTarget(
|
||||
args.worktreeId,
|
||||
args.branchName,
|
||||
args.expectedHead
|
||||
)
|
||||
const repo = store.getRepo(repoId)
|
||||
if (!repo) {
|
||||
throw new Error(`Repo not found: ${repoId}`)
|
||||
}
|
||||
if (isFolderRepo(repo)) {
|
||||
throw new Error('Folder workspaces do not have local Git branches.')
|
||||
}
|
||||
|
||||
if (repo.connectionId) {
|
||||
const provider = requireSshGitProvider(repo.connectionId)
|
||||
await forceDeleteLocalBranch(
|
||||
repo.path,
|
||||
cleanupTarget.branchName,
|
||||
cleanupTarget.head,
|
||||
(argv, cwd) => provider.exec(argv, cwd)
|
||||
)
|
||||
await cleanupUnusedWorktreePushTargetRemoteSsh(
|
||||
provider,
|
||||
repo.path,
|
||||
args.worktreeId,
|
||||
cleanupTarget.pushTarget,
|
||||
store
|
||||
)
|
||||
} else {
|
||||
await forceDeleteLocalBranch(repo.path, cleanupTarget.branchName, cleanupTarget.head)
|
||||
await cleanupUnusedWorktreePushTargetRemote(
|
||||
repo.path,
|
||||
args.worktreeId,
|
||||
cleanupTarget.pushTarget,
|
||||
store
|
||||
)
|
||||
}
|
||||
|
||||
preservedBranchCleanupByWorktreeId.delete(args.worktreeId)
|
||||
return { deleted: true }
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'worktrees:updateMeta',
|
||||
(_event, args: { worktreeId: string; updates: Partial<WorktreeMeta> }) => {
|
||||
|
||||
@@ -12,7 +12,8 @@ import type {
|
||||
GitConflictOperation,
|
||||
GitPushTarget,
|
||||
GitUpstreamStatus,
|
||||
GitWorktreeInfo
|
||||
GitWorktreeInfo,
|
||||
RemoveWorktreeResult
|
||||
} from '../../shared/types'
|
||||
import type { GitHistoryOptions, GitHistoryResult } from '../../shared/git-history'
|
||||
import { buildHostedRemoteFileUrl } from '../git/hosted-remote-url'
|
||||
@@ -433,8 +434,12 @@ export class SshGitProvider implements IGitProvider {
|
||||
worktreePath: string,
|
||||
force?: boolean,
|
||||
options?: { deleteBranch?: boolean; forceBranchDelete?: boolean }
|
||||
): Promise<void> {
|
||||
await this.mux.request('git.removeWorktree', { worktreePath, force, ...options })
|
||||
): Promise<RemoveWorktreeResult> {
|
||||
return ((await this.mux.request('git.removeWorktree', {
|
||||
worktreePath,
|
||||
force,
|
||||
...options
|
||||
})) ?? {}) as RemoveWorktreeResult
|
||||
}
|
||||
|
||||
async worktreeIsClean(worktreePath: string): Promise<{ clean: boolean; stdout?: string }> {
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
GitPushTarget,
|
||||
GitUpstreamStatus,
|
||||
GitWorktreeInfo,
|
||||
RemoveWorktreeResult,
|
||||
SearchOptions,
|
||||
SearchResult
|
||||
} from '../../shared/types'
|
||||
@@ -211,7 +212,7 @@ export type IGitProvider = {
|
||||
worktreePath: string,
|
||||
force?: boolean,
|
||||
options?: { deleteBranch?: boolean; forceBranchDelete?: boolean }
|
||||
): Promise<void>
|
||||
): Promise<RemoveWorktreeResult>
|
||||
renameCurrentBranch?(worktreePath: string, newBranch: string): Promise<void>
|
||||
isGitRepo(path: string): boolean
|
||||
isGitRepoAsync(dirPath: string): Promise<{ isRepo: boolean; rootPath: string | null }>
|
||||
|
||||
@@ -69,6 +69,7 @@ const {
|
||||
MOCK_GIT_WORKTREES,
|
||||
addWorktreeMock,
|
||||
removeWorktreeMock,
|
||||
forceDeleteLocalBranchMock,
|
||||
computeWorktreePathMock,
|
||||
ensurePathWithinWorkspaceMock,
|
||||
sshGitProviders,
|
||||
@@ -118,6 +119,7 @@ const {
|
||||
],
|
||||
addWorktreeMock: vi.fn(),
|
||||
removeWorktreeMock: vi.fn(),
|
||||
forceDeleteLocalBranchMock: vi.fn(),
|
||||
computeWorktreePathMock: vi.fn(),
|
||||
ensurePathWithinWorkspaceMock: vi.fn(),
|
||||
sshGitProviders,
|
||||
@@ -161,7 +163,8 @@ vi.mock('../git/worktree', () => ({
|
||||
listWorktrees: vi.fn().mockResolvedValue(MOCK_GIT_WORKTREES),
|
||||
assertWorktreeCleanForRemoval: vi.fn().mockResolvedValue(undefined),
|
||||
addWorktree: addWorktreeMock,
|
||||
removeWorktree: removeWorktreeMock
|
||||
removeWorktree: removeWorktreeMock,
|
||||
forceDeleteLocalBranch: forceDeleteLocalBranchMock
|
||||
}))
|
||||
|
||||
vi.mock('../terminal-history', () => ({
|
||||
@@ -314,6 +317,8 @@ afterEach(() => {
|
||||
vi.mocked(assertWorktreeCleanForRemoval).mockReset()
|
||||
vi.mocked(assertWorktreeCleanForRemoval).mockResolvedValue(undefined)
|
||||
vi.mocked(removeWorktree).mockReset()
|
||||
vi.mocked(forceDeleteLocalBranchMock).mockReset()
|
||||
vi.mocked(forceDeleteLocalBranchMock).mockResolvedValue(undefined)
|
||||
sshGitProviders.clear()
|
||||
getSshGitProviderMock.mockReset()
|
||||
getSshGitProviderMock.mockImplementation((connectionId: string) =>
|
||||
@@ -9205,7 +9210,7 @@ describe('OrcaRuntimeService', () => {
|
||||
archive: 'pnpm worktree:archive'
|
||||
}
|
||||
})
|
||||
vi.mocked(removeWorktree).mockResolvedValue(undefined)
|
||||
vi.mocked(removeWorktree).mockResolvedValue({})
|
||||
|
||||
const result = await runtime.removeManagedWorktree(TEST_WORKTREE_ID)
|
||||
|
||||
@@ -9217,6 +9222,41 @@ describe('OrcaRuntimeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('force-deletes a branch that was preserved by runtime worktree removal', async () => {
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
vi.mocked(removeWorktree).mockResolvedValue({
|
||||
preservedBranch: { branchName: 'feature/test', head: 'def456' }
|
||||
})
|
||||
|
||||
await runtime.removeManagedWorktree(TEST_WORKTREE_ID)
|
||||
const result = await runtime.forceDeletePreservedBranch(
|
||||
TEST_WORKTREE_ID,
|
||||
'feature/test',
|
||||
'def456'
|
||||
)
|
||||
|
||||
expect(result).toEqual({ deleted: true })
|
||||
expect(forceDeleteLocalBranchMock).toHaveBeenCalledWith(
|
||||
TEST_REPO_PATH,
|
||||
'feature/test',
|
||||
'def456'
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects stale preserved-branch runtime cleanup actions with an old head', async () => {
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
vi.mocked(removeWorktree).mockResolvedValue({
|
||||
preservedBranch: { branchName: 'feature/test', head: 'new456' }
|
||||
})
|
||||
|
||||
await runtime.removeManagedWorktree(TEST_WORKTREE_ID)
|
||||
|
||||
await expect(
|
||||
runtime.forceDeletePreservedBranch(TEST_WORKTREE_ID, 'feature/test', 'old123')
|
||||
).rejects.toThrow('No preserved branch cleanup is pending')
|
||||
expect(forceDeleteLocalBranchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('coalesces concurrent runtime worktree removals for the same worktree id', async () => {
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
const removeStarted = deferred<void>()
|
||||
@@ -9224,6 +9264,7 @@ describe('OrcaRuntimeService', () => {
|
||||
vi.mocked(removeWorktree).mockImplementation(async () => {
|
||||
removeStarted.resolve()
|
||||
await finishRemoval.promise
|
||||
return {}
|
||||
})
|
||||
|
||||
const first = runtime.removeManagedWorktree(TEST_WORKTREE_ID, true)
|
||||
@@ -9244,6 +9285,7 @@ describe('OrcaRuntimeService', () => {
|
||||
vi.mocked(removeWorktree).mockImplementation(async () => {
|
||||
removeStarted.resolve()
|
||||
await finishRemoval.promise
|
||||
return {}
|
||||
})
|
||||
|
||||
const first = runtime.removeManagedWorktree(TEST_WORKTREE_ID)
|
||||
@@ -9533,7 +9575,7 @@ describe('OrcaRuntimeService', () => {
|
||||
}
|
||||
})
|
||||
vi.mocked(runHook).mockResolvedValue({ success: true, output: '' })
|
||||
vi.mocked(removeWorktree).mockResolvedValue(undefined)
|
||||
vi.mocked(removeWorktree).mockResolvedValue({})
|
||||
|
||||
await runtime.removeManagedWorktree(TEST_WORKTREE_ID, false, true)
|
||||
|
||||
@@ -9562,7 +9604,7 @@ describe('OrcaRuntimeService', () => {
|
||||
terminalFitOverrideChanged: vi.fn(),
|
||||
terminalDriverChanged: vi.fn()
|
||||
})
|
||||
vi.mocked(removeWorktree).mockResolvedValue(undefined)
|
||||
vi.mocked(removeWorktree).mockResolvedValue({})
|
||||
|
||||
const token = runtime.recordOptimisticReconcileToken(TEST_WORKTREE_ID)
|
||||
await runtime.removeManagedWorktree(TEST_WORKTREE_ID)
|
||||
@@ -10125,6 +10167,7 @@ describe('OrcaRuntimeService', () => {
|
||||
})
|
||||
vi.mocked(removeWorktree).mockImplementation(async () => {
|
||||
callOrder.push('git-removeWorktree')
|
||||
return {}
|
||||
})
|
||||
|
||||
const runtime = new OrcaRuntimeService(store, undefined, {
|
||||
@@ -10173,7 +10216,7 @@ describe('OrcaRuntimeService', () => {
|
||||
const runtime = new OrcaRuntimeService(store, undefined, {
|
||||
getLocalProvider: () => currentProvider as never
|
||||
})
|
||||
vi.mocked(removeWorktree).mockResolvedValue(undefined)
|
||||
vi.mocked(removeWorktree).mockResolvedValue({})
|
||||
|
||||
// Simulate daemon-init swapping the provider after construction.
|
||||
currentProvider = postDaemonProvider
|
||||
|
||||
@@ -33,12 +33,14 @@ import type {
|
||||
CreateWorktreeResult,
|
||||
DetectedWorktree,
|
||||
DetectedWorktreeListResult,
|
||||
ForceDeleteWorktreeBranchResult,
|
||||
GitPushTarget,
|
||||
GitWorktreeInfo,
|
||||
GitHubOwnerRepo,
|
||||
GlobalSettings,
|
||||
PersistedUIState,
|
||||
Repo,
|
||||
RemoveWorktreeResult,
|
||||
StatsSummary,
|
||||
Worktree,
|
||||
WorktreeLineage,
|
||||
@@ -317,6 +319,7 @@ import {
|
||||
addWorktree,
|
||||
addSparseWorktree,
|
||||
assertWorktreeCleanForRemoval,
|
||||
forceDeleteLocalBranch,
|
||||
removeWorktree
|
||||
} from '../git/worktree'
|
||||
import type { AddWorktreeResult } from '../git/worktree'
|
||||
@@ -771,7 +774,13 @@ type RuntimeWorktreeRemovalTarget = {
|
||||
|
||||
type RuntimeWorktreeRemovalInFlight = {
|
||||
optionsKey: string
|
||||
promise: Promise<{ warning?: string }>
|
||||
promise: Promise<RemoveWorktreeResult & { warning?: string }>
|
||||
}
|
||||
|
||||
type PreservedBranchCleanupTarget = {
|
||||
branchName: string
|
||||
head: string
|
||||
pushTarget?: GitPushTarget
|
||||
}
|
||||
|
||||
function getRuntimeWorktreeRemovalOptionsKey(force: boolean, runHooks: boolean): string {
|
||||
@@ -1311,6 +1320,7 @@ export class OrcaRuntimeService {
|
||||
private canonicalFetchKeyCache = new Map<string, string>()
|
||||
private optimisticReconcileTokens = new Map<string, string>()
|
||||
private removeManagedWorktreeInFlight = new Map<string, RuntimeWorktreeRemovalInFlight>()
|
||||
private preservedBranchCleanupByWorktreeId = new Map<string, PreservedBranchCleanupTarget>()
|
||||
private readonly getLocalProviderFn: (() => IPtyProvider) | null
|
||||
private accountServices: RuntimeAccountServices | null = null
|
||||
private commitMessageAgentEnv: CommitMessageAgentEnvironmentResolvers | null = null
|
||||
@@ -8872,11 +8882,108 @@ export class OrcaRuntimeService {
|
||||
deleteWorktreeHistoryDir(worktreeId)
|
||||
}
|
||||
|
||||
private rememberPreservedBranchCleanupTarget(
|
||||
worktreeId: string,
|
||||
result: RemoveWorktreeResult | undefined,
|
||||
fallbackHead: string | undefined,
|
||||
pushTarget: GitPushTarget | undefined
|
||||
): void {
|
||||
if (result?.preservedBranch) {
|
||||
const head = result.preservedBranch.head ?? fallbackHead
|
||||
if (!head) {
|
||||
throw new Error(
|
||||
`Cannot safely offer force-delete for preserved branch "${result.preservedBranch.branchName}" without its saved commit.`
|
||||
)
|
||||
}
|
||||
this.preservedBranchCleanupByWorktreeId.set(worktreeId, {
|
||||
branchName: result.preservedBranch.branchName,
|
||||
head,
|
||||
...(pushTarget ? { pushTarget } : {})
|
||||
})
|
||||
return
|
||||
}
|
||||
this.preservedBranchCleanupByWorktreeId.delete(worktreeId)
|
||||
}
|
||||
|
||||
private preserveBranchHeadFallback(
|
||||
result: RemoveWorktreeResult | undefined,
|
||||
fallbackHead: string | undefined
|
||||
): RemoveWorktreeResult {
|
||||
if (!result?.preservedBranch || result.preservedBranch.head || !fallbackHead) {
|
||||
return result ?? {}
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
preservedBranch: {
|
||||
...result.preservedBranch,
|
||||
head: fallbackHead
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async forceDeletePreservedBranch(
|
||||
worktreeSelector: string,
|
||||
branchName: string,
|
||||
expectedHead: string
|
||||
): Promise<ForceDeleteWorktreeBranchResult> {
|
||||
if (!this.store) {
|
||||
throw new Error('runtime_unavailable')
|
||||
}
|
||||
const removalTarget = parseExactWorktreeIdSelector(worktreeSelector)
|
||||
const cleanupTarget = removalTarget
|
||||
? this.preservedBranchCleanupByWorktreeId.get(removalTarget.id)
|
||||
: undefined
|
||||
if (
|
||||
!removalTarget ||
|
||||
!cleanupTarget ||
|
||||
cleanupTarget.branchName !== branchName ||
|
||||
cleanupTarget.head !== expectedHead
|
||||
) {
|
||||
throw new Error(`No preserved branch cleanup is pending for "${branchName}".`)
|
||||
}
|
||||
|
||||
const repo = this.store.getRepo(removalTarget.repoId)
|
||||
if (!repo) {
|
||||
throw new Error('repo_not_found')
|
||||
}
|
||||
if (isFolderRepo(repo)) {
|
||||
throw new Error('Folder workspaces do not have local Git branches.')
|
||||
}
|
||||
|
||||
if (repo.connectionId) {
|
||||
const provider = requireSshGitProvider(repo.connectionId)
|
||||
await forceDeleteLocalBranch(
|
||||
repo.path,
|
||||
cleanupTarget.branchName,
|
||||
cleanupTarget.head,
|
||||
(argv, cwd) => provider.exec(argv, cwd)
|
||||
)
|
||||
await cleanupUnusedWorktreePushTargetRemoteSsh(
|
||||
provider,
|
||||
repo.path,
|
||||
removalTarget.id,
|
||||
cleanupTarget.pushTarget,
|
||||
this.store
|
||||
)
|
||||
} else {
|
||||
await forceDeleteLocalBranch(repo.path, cleanupTarget.branchName, cleanupTarget.head)
|
||||
await cleanupUnusedWorktreePushTargetRemote(
|
||||
repo.path,
|
||||
removalTarget.id,
|
||||
cleanupTarget.pushTarget,
|
||||
this.store
|
||||
)
|
||||
}
|
||||
|
||||
this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id)
|
||||
return { deleted: true }
|
||||
}
|
||||
|
||||
async removeManagedWorktree(
|
||||
worktreeSelector: string,
|
||||
force = false,
|
||||
runHooks = false
|
||||
): Promise<{ warning?: string }> {
|
||||
): Promise<RemoveWorktreeResult & { warning?: string }> {
|
||||
if (!this.store) {
|
||||
throw new Error('runtime_unavailable')
|
||||
}
|
||||
@@ -8893,7 +9000,7 @@ export class OrcaRuntimeService {
|
||||
|
||||
// Why: runtime callers can race the same workspace through CLI/mobile
|
||||
// retries. Share one destructive Git/filesystem operation per worktree ID.
|
||||
const removal = (async (): Promise<{ warning?: string }> => {
|
||||
const removal = (async (): Promise<RemoveWorktreeResult & { warning?: string }> => {
|
||||
const repo = store.getRepo(removalTarget.repoId)
|
||||
if (!repo) {
|
||||
throw new Error('repo_not_found')
|
||||
@@ -8916,6 +9023,7 @@ export class OrcaRuntimeService {
|
||||
})
|
||||
}
|
||||
this.removeWorktreeMetadataAndHistory(store, removalTarget.id)
|
||||
this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id)
|
||||
this.invalidateResolvedWorktreeCache()
|
||||
this.notifier?.worktreesChanged(repo.id)
|
||||
return {}
|
||||
@@ -8990,6 +9098,7 @@ export class OrcaRuntimeService {
|
||||
}
|
||||
this.clearOptimisticReconcileToken(removalTarget.id)
|
||||
this.removeWorktreeMetadataAndHistory(store, removalTarget.id)
|
||||
this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id)
|
||||
this.invalidateResolvedWorktreeCache()
|
||||
invalidateAuthorizedRootsCache()
|
||||
this.notifier?.worktreesChanged(repo.id)
|
||||
@@ -9015,6 +9124,7 @@ export class OrcaRuntimeService {
|
||||
))
|
||||
this.clearOptimisticReconcileToken(removalTarget.id)
|
||||
this.removeWorktreeMetadataAndHistory(store, removalTarget.id)
|
||||
this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id)
|
||||
this.invalidateResolvedWorktreeCache()
|
||||
invalidateAuthorizedRootsCache()
|
||||
this.notifier?.worktreesChanged(repo.id)
|
||||
@@ -9025,9 +9135,13 @@ export class OrcaRuntimeService {
|
||||
const canonicalWorktreePath = registeredWorktree.path
|
||||
const deleteBranch = removedMeta?.preserveBranchOnDelete !== true
|
||||
if (repo.connectionId) {
|
||||
await (deleteBranch
|
||||
const rawRemovalResult = await (deleteBranch
|
||||
? provider!.removeWorktree(canonicalWorktreePath, force)
|
||||
: provider!.removeWorktree(canonicalWorktreePath, force, { deleteBranch }))
|
||||
const removalResult = this.preserveBranchHeadFallback(
|
||||
rawRemovalResult,
|
||||
registeredWorktree.head
|
||||
)
|
||||
await cleanupUnusedWorktreePushTargetRemoteSsh(
|
||||
provider!,
|
||||
repo.path,
|
||||
@@ -9035,12 +9149,18 @@ export class OrcaRuntimeService {
|
||||
removedPushTarget,
|
||||
store
|
||||
)
|
||||
this.rememberPreservedBranchCleanupTarget(
|
||||
removalTarget.id,
|
||||
removalResult,
|
||||
registeredWorktree.head,
|
||||
removedPushTarget
|
||||
)
|
||||
this.clearOptimisticReconcileToken(removalTarget.id)
|
||||
this.removeWorktreeMetadataAndHistory(store, removalTarget.id)
|
||||
this.invalidateResolvedWorktreeCache()
|
||||
invalidateAuthorizedRootsCache()
|
||||
this.notifier?.worktreesChanged(repo.id)
|
||||
return {}
|
||||
return removalResult ?? {}
|
||||
}
|
||||
|
||||
const hooks = getEffectiveHooks(repo)
|
||||
@@ -9095,10 +9215,14 @@ export class OrcaRuntimeService {
|
||||
})
|
||||
}
|
||||
|
||||
let removalResult: RemoveWorktreeResult | undefined
|
||||
try {
|
||||
await (deleteBranch
|
||||
? removeWorktree(repo.path, canonicalWorktreePath, force)
|
||||
: removeWorktree(repo.path, canonicalWorktreePath, force, { deleteBranch }))
|
||||
removalResult = this.preserveBranchHeadFallback(
|
||||
await (deleteBranch
|
||||
? removeWorktree(repo.path, canonicalWorktreePath, force)
|
||||
: removeWorktree(repo.path, canonicalWorktreePath, force, { deleteBranch })),
|
||||
registeredWorktree.head
|
||||
)
|
||||
} catch (error) {
|
||||
if (isOrphanedWorktreeError(error)) {
|
||||
if (await canSafelyRemoveOrphanedWorktreeDirectory(canonicalWorktreePath, repo.path)) {
|
||||
@@ -9121,6 +9245,7 @@ export class OrcaRuntimeService {
|
||||
)
|
||||
this.clearOptimisticReconcileToken(removalTarget.id)
|
||||
this.removeWorktreeMetadataAndHistory(store, removalTarget.id)
|
||||
this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id)
|
||||
this.invalidateResolvedWorktreeCache()
|
||||
invalidateAuthorizedRootsCache()
|
||||
this.notifier?.worktreesChanged(repo.id)
|
||||
@@ -9137,12 +9262,19 @@ export class OrcaRuntimeService {
|
||||
removedPushTarget,
|
||||
store
|
||||
)
|
||||
this.rememberPreservedBranchCleanupTarget(
|
||||
removalTarget.id,
|
||||
removalResult,
|
||||
registeredWorktree.head,
|
||||
removedPushTarget
|
||||
)
|
||||
this.clearOptimisticReconcileToken(removalTarget.id)
|
||||
this.removeWorktreeMetadataAndHistory(store, removalTarget.id)
|
||||
this.invalidateResolvedWorktreeCache()
|
||||
invalidateAuthorizedRootsCache()
|
||||
this.notifier?.worktreesChanged(repo.id)
|
||||
return {
|
||||
...removalResult,
|
||||
...(warning ? { warning } : {})
|
||||
}
|
||||
})()
|
||||
|
||||
@@ -162,6 +162,17 @@ export const WorktreeRemove = WorktreeSelector.extend({
|
||||
runHooks: OptionalBoolean
|
||||
})
|
||||
|
||||
export const WorktreeForceDeleteBranch = WorktreeSelector.extend({
|
||||
branchName: z
|
||||
.unknown()
|
||||
.transform((v) => (typeof v === 'string' ? v : ''))
|
||||
.pipe(z.string().min(1, 'Missing branch name')),
|
||||
expectedHead: z
|
||||
.unknown()
|
||||
.transform((v) => (typeof v === 'string' ? v : ''))
|
||||
.pipe(z.string().min(1, 'Missing expected branch head'))
|
||||
})
|
||||
|
||||
export const WorktreeResolvePrBase = z.object({
|
||||
repo: z
|
||||
.unknown()
|
||||
|
||||
@@ -2,6 +2,7 @@ import { defineMethod, type RpcMethod } from '../core'
|
||||
import {
|
||||
WorktreeCreate,
|
||||
WorktreeDetectedListParams,
|
||||
WorktreeForceDeleteBranch,
|
||||
WorktreeListParams,
|
||||
WorktreePsParams,
|
||||
WorktreeRemove,
|
||||
@@ -166,5 +167,11 @@ export const WORKTREE_METHODS: RpcMethod[] = [
|
||||
)
|
||||
return { removed: true, ...result }
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'worktree.forceDeleteBranch',
|
||||
params: WorktreeForceDeleteBranch,
|
||||
handler: async (params, { runtime }) =>
|
||||
runtime.forceDeletePreservedBranch(params.worktree, params.branchName, params.expectedHead)
|
||||
})
|
||||
]
|
||||
|
||||
@@ -286,6 +286,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([
|
||||
'ui.set',
|
||||
'worktree.activate',
|
||||
'worktree.create',
|
||||
'worktree.forceDeleteBranch',
|
||||
'worktree.ps',
|
||||
'worktree.show',
|
||||
'worktree.resolveMrBase',
|
||||
|
||||
@@ -26,6 +26,7 @@ import type {
|
||||
CustomPet,
|
||||
DetectedWorktreeListResult,
|
||||
DirEntry,
|
||||
ForceDeleteWorktreeBranchResult,
|
||||
FsChangedPayload,
|
||||
GhosttyImportPreview,
|
||||
GlobalSettings,
|
||||
@@ -107,6 +108,7 @@ import type {
|
||||
WorktreeLineage,
|
||||
WorktreeMeta,
|
||||
WorktreeRemoteBranchConflictEvent,
|
||||
RemoveWorktreeResult,
|
||||
WorktreeSetupLaunch,
|
||||
WorktreeStartupLaunch,
|
||||
WorkspaceSessionState
|
||||
@@ -742,7 +744,16 @@ export type PreloadApi = {
|
||||
sourceBranch?: string
|
||||
isCrossRepository?: boolean
|
||||
}) => Promise<{ baseBranch: string; pushTarget?: GitPushTarget } | { error: string }>
|
||||
remove: (args: { worktreeId: string; force?: boolean; skipArchive?: boolean }) => Promise<void>
|
||||
remove: (args: {
|
||||
worktreeId: string
|
||||
force?: boolean
|
||||
skipArchive?: boolean
|
||||
}) => Promise<RemoveWorktreeResult>
|
||||
forceDeletePreservedBranch: (args: {
|
||||
worktreeId: string
|
||||
branchName: string
|
||||
expectedHead: string
|
||||
}) => Promise<ForceDeleteWorktreeBranchResult>
|
||||
updateMeta: (args: { worktreeId: string; updates: Partial<WorktreeMeta> }) => Promise<Worktree>
|
||||
listLineage: () => Promise<Record<string, WorktreeLineage>>
|
||||
updateLineage: (args: {
|
||||
|
||||
+14
-2
@@ -14,6 +14,7 @@ import type {
|
||||
BrowserViewportOverride,
|
||||
CreateWorktreeArgs,
|
||||
CustomPet,
|
||||
ForceDeleteWorktreeBranchResult,
|
||||
FsChangedPayload,
|
||||
GetRateLimitResult,
|
||||
GitHubPRRefreshCandidate,
|
||||
@@ -36,6 +37,7 @@ import type {
|
||||
FloatingTerminalCwdRequest,
|
||||
MarkdownDocument,
|
||||
SearchResult,
|
||||
RemoveWorktreeResult,
|
||||
WorktreeBaseStatusEvent,
|
||||
WorktreeRemoteBranchConflictEvent
|
||||
} from '../shared/types'
|
||||
@@ -591,8 +593,18 @@ const api = {
|
||||
}): Promise<{ baseBranch: string; pushTarget?: unknown } | { error: string }> =>
|
||||
ipcRenderer.invoke('worktrees:resolveMrBase', args),
|
||||
|
||||
remove: (args: { worktreeId: string; force?: boolean; skipArchive?: boolean }): Promise<void> =>
|
||||
ipcRenderer.invoke('worktrees:remove', args),
|
||||
remove: (args: {
|
||||
worktreeId: string
|
||||
force?: boolean
|
||||
skipArchive?: boolean
|
||||
}): Promise<RemoveWorktreeResult> => ipcRenderer.invoke('worktrees:remove', args),
|
||||
|
||||
forceDeletePreservedBranch: (args: {
|
||||
worktreeId: string
|
||||
branchName: string
|
||||
expectedHead: string
|
||||
}): Promise<ForceDeleteWorktreeBranchResult> =>
|
||||
ipcRenderer.invoke('worktrees:forceDeletePreservedBranch', args),
|
||||
|
||||
updateMeta: (args: {
|
||||
worktreeId: string
|
||||
|
||||
@@ -155,7 +155,7 @@ describe('removeWorktreeOp', () => {
|
||||
'/repo$ worktree remove /repo-feature',
|
||||
'/repo$ worktree prune',
|
||||
'/repo$ worktree list --porcelain',
|
||||
'/repo$ branch -d feature/test'
|
||||
'/repo$ branch -d -- feature/test'
|
||||
])
|
||||
})
|
||||
|
||||
@@ -184,11 +184,13 @@ describe('removeWorktreeOp', () => {
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
// The unmerged-branch refusal must be swallowed, not propagated.
|
||||
await expect(removeWorktreeOp(git, { worktreePath: '/repo-feature' })).resolves.toBeUndefined()
|
||||
// The unmerged-branch refusal must be surfaced without failing workspace removal.
|
||||
await expect(removeWorktreeOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({
|
||||
preservedBranch: { branchName: 'feature/test', head: '1' }
|
||||
})
|
||||
|
||||
expect(git).toHaveBeenCalledWith(['branch', '-d', 'feature/test'], expect.any(String))
|
||||
expect(git).not.toHaveBeenCalledWith(['branch', '-D', 'feature/test'], expect.any(String))
|
||||
expect(git).toHaveBeenCalledWith(['branch', '-d', '--', 'feature/test'], expect.any(String))
|
||||
expect(git).not.toHaveBeenCalledWith(['branch', '-D', '--', 'feature/test'], expect.any(String))
|
||||
})
|
||||
|
||||
it('force-deletes the just-created branch during failed sparse setup rollback', async () => {
|
||||
@@ -219,8 +221,8 @@ describe('removeWorktreeOp', () => {
|
||||
forceBranchDelete: true
|
||||
})
|
||||
|
||||
expect(git).toHaveBeenCalledWith(['branch', '-D', 'feature/test'], expect.any(String))
|
||||
expect(git).not.toHaveBeenCalledWith(['branch', '-d', 'feature/test'], expect.any(String))
|
||||
expect(git).toHaveBeenCalledWith(['branch', '-D', '--', 'feature/test'], expect.any(String))
|
||||
expect(git).not.toHaveBeenCalledWith(['branch', '-d', '--', 'feature/test'], expect.any(String))
|
||||
})
|
||||
|
||||
it('skips branch deletion entirely when deleteBranch is false', async () => {
|
||||
@@ -279,8 +281,8 @@ describe('removeWorktreeOp', () => {
|
||||
|
||||
await removeWorktreeOp(git, { worktreePath: '/repo-feature' })
|
||||
|
||||
expect(git).not.toHaveBeenCalledWith(['branch', '-d', 'feature/test'], expect.any(String))
|
||||
expect(git).not.toHaveBeenCalledWith(['branch', '-D', 'feature/test'], expect.any(String))
|
||||
expect(git).not.toHaveBeenCalledWith(['branch', '-d', '--', 'feature/test'], expect.any(String))
|
||||
expect(git).not.toHaveBeenCalledWith(['branch', '-D', '--', 'feature/test'], expect.any(String))
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* the oxlint max-lines (300) limit.
|
||||
*/
|
||||
import * as path from 'path'
|
||||
import type { RemoveWorktreeResult } from '../shared/types'
|
||||
import { resolveWorktreeAddBaseRef } from '../shared/worktree-base-ref'
|
||||
import type { GitExec } from './git-handler-ops'
|
||||
import { parseWorktreeList } from './git-handler-utils'
|
||||
@@ -121,7 +122,7 @@ export async function addWorktreeOp(git: GitExec, params: Record<string, unknown
|
||||
export async function removeWorktreeOp(
|
||||
git: GitExec,
|
||||
params: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
): Promise<RemoveWorktreeResult> {
|
||||
const worktreePath = params.worktreePath as string
|
||||
const force = params.force as boolean | undefined
|
||||
const deleteBranch = params.deleteBranch !== false
|
||||
@@ -143,6 +144,7 @@ export async function removeWorktreeOp(
|
||||
areRelayWorktreePathsEqual(worktree.path, worktreePath)
|
||||
)
|
||||
const branchName = normalizeLocalBranchRef(removedWorktree?.branch ?? '')
|
||||
const branchHead = removedWorktree?.head ?? ''
|
||||
|
||||
const args = ['worktree', 'remove']
|
||||
if (force) {
|
||||
@@ -153,10 +155,10 @@ export async function removeWorktreeOp(
|
||||
await git(['worktree', 'prune'], repoPath)
|
||||
|
||||
if (!branchName) {
|
||||
return
|
||||
return {}
|
||||
}
|
||||
if (!deleteBranch) {
|
||||
return
|
||||
return {}
|
||||
}
|
||||
|
||||
// Why: SSH worktree deletion should mirror local deletion. Dropping the
|
||||
@@ -167,7 +169,7 @@ export async function removeWorktreeOp(
|
||||
(worktree) => normalizeLocalBranchRef(worktree.branch ?? '') === branchName
|
||||
)
|
||||
if (branchStillInUse) {
|
||||
return
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -175,19 +177,22 @@ export async function removeWorktreeOp(
|
||||
// refuses to delete a branch with commits not merged into its upstream or
|
||||
// HEAD, so unpublished work on a remote worktree is preserved rather than
|
||||
// force-deleted. forceBranchDelete is reserved for failed create rollback.
|
||||
await git(['branch', forceBranchDelete ? '-D' : '-d', branchName], repoPath)
|
||||
await git(['branch', forceBranchDelete ? '-D' : '-d', '--', branchName], repoPath)
|
||||
return {}
|
||||
} catch (error) {
|
||||
// Expected when the branch still has unmerged/unpublished commits: keep it.
|
||||
console.warn(
|
||||
`relay removeWorktree: preserved local branch "${branchName}" after removing worktree (not fully merged)`,
|
||||
error
|
||||
)
|
||||
return { preservedBranch: { branchName, ...(branchHead ? { head: branchHead } : {}) } }
|
||||
}
|
||||
}
|
||||
|
||||
type RelayWorktreeInfo = {
|
||||
path: string
|
||||
branch?: string
|
||||
head?: string
|
||||
}
|
||||
|
||||
async function listRelayWorktrees(git: GitExec, repoPath: string): Promise<RelayWorktreeInfo[]> {
|
||||
@@ -196,6 +201,7 @@ async function listRelayWorktrees(git: GitExec, repoPath: string): Promise<Relay
|
||||
return parseWorktreeList(stdout)
|
||||
.map((worktree) => ({
|
||||
path: typeof worktree.path === 'string' ? worktree.path : '',
|
||||
head: typeof worktree.head === 'string' ? worktree.head : undefined,
|
||||
branch: typeof worktree.branch === 'string' ? worktree.branch : undefined
|
||||
}))
|
||||
.filter((worktree) => worktree.path.length > 0)
|
||||
|
||||
@@ -5,9 +5,12 @@ import type * as AgentStatusModule from '@/lib/agent-status'
|
||||
import { getDefaultSettings } from '../../../../shared/constants'
|
||||
import { createCompatibleRuntimeStatusResponseIfNeeded } from '../../runtime/runtime-compatibility-test-fixture'
|
||||
import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
// Mock sonner (imported by repos.ts)
|
||||
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
|
||||
vi.mock('sonner', () => ({
|
||||
toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() }
|
||||
}))
|
||||
|
||||
// Mock agent-status (imported by terminal-helpers)
|
||||
vi.mock('@/lib/agent-status', async (importOriginal) => {
|
||||
@@ -24,6 +27,7 @@ const mockApi = {
|
||||
list: vi.fn().mockResolvedValue([]),
|
||||
create: vi.fn().mockResolvedValue({}),
|
||||
remove: vi.fn().mockResolvedValue(undefined),
|
||||
forceDeletePreservedBranch: vi.fn().mockResolvedValue({ deleted: true }),
|
||||
updateMeta: vi.fn().mockResolvedValue({})
|
||||
},
|
||||
repos: {
|
||||
@@ -75,6 +79,7 @@ describe('removeWorktree cascade', () => {
|
||||
vi.clearAllMocks()
|
||||
clearRuntimeCompatibilityCacheForTests()
|
||||
mockApi.worktrees.remove.mockResolvedValue(undefined)
|
||||
mockApi.worktrees.forceDeletePreservedBranch.mockResolvedValue({ deleted: true })
|
||||
mockApi.runtimeEnvironments.call.mockReset()
|
||||
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) =>
|
||||
Promise.resolve(
|
||||
@@ -156,6 +161,50 @@ describe('removeWorktree cascade', () => {
|
||||
expect(s.activeTabTypeByWorktree[worktreeId]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('warns when workspace removal keeps the local branch', async () => {
|
||||
const store = createTestStore()
|
||||
const worktreeId = 'repo1::/path/wt1'
|
||||
mockApi.worktrees.remove.mockResolvedValueOnce({
|
||||
preservedBranch: { branchName: 'feature/test', head: 'def456' }
|
||||
})
|
||||
|
||||
seedStore(store, {
|
||||
worktreesByRepo: {
|
||||
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/path/wt1' })]
|
||||
}
|
||||
})
|
||||
|
||||
const result = await store.getState().removeWorktree(worktreeId)
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
preservedBranch: { branchName: 'feature/test', head: 'def456' }
|
||||
})
|
||||
expect(toast.warning).toHaveBeenCalledWith('Workspace deleted, branch kept', {
|
||||
description:
|
||||
'Git could not safely delete "feature/test", so Orca kept it to avoid losing local commits.',
|
||||
action: {
|
||||
label: 'Force Delete Branch',
|
||||
onClick: expect.any(Function)
|
||||
}
|
||||
})
|
||||
|
||||
const action = vi.mocked(toast.warning).mock.calls.at(-1)?.[1]?.action as
|
||||
| { onClick?: () => void }
|
||||
| undefined
|
||||
action?.onClick?.()
|
||||
await vi.waitFor(() => {
|
||||
expect(mockApi.worktrees.forceDeletePreservedBranch).toHaveBeenCalledWith({
|
||||
worktreeId,
|
||||
branchName: 'feature/test',
|
||||
expectedHead: 'def456'
|
||||
})
|
||||
})
|
||||
expect(toast.success).toHaveBeenCalledWith('Local branch deleted', {
|
||||
description: 'Deleted "feature/test".'
|
||||
})
|
||||
})
|
||||
|
||||
it('sets delete state with dirty/untracked error and canForceDelete=true on failure', async () => {
|
||||
const store = createTestStore()
|
||||
const worktreeId = 'repo1::/path/wt1'
|
||||
|
||||
@@ -3,7 +3,9 @@ import type {
|
||||
CreateSparseCheckoutRequest,
|
||||
DetectedWorktree,
|
||||
DetectedWorktreeListResult,
|
||||
ForceDeleteWorktreeBranchResult,
|
||||
GitPushTarget,
|
||||
RemoveWorktreeResult,
|
||||
SetupDecision,
|
||||
TuiAgent,
|
||||
WorkspaceCreateTelemetrySource,
|
||||
@@ -102,7 +104,12 @@ export type WorktreeSlice = {
|
||||
removeWorktree: (
|
||||
worktreeId: string,
|
||||
force?: boolean
|
||||
) => Promise<{ ok: true } | { ok: false; error: string }>
|
||||
) => Promise<({ ok: true } & RemoveWorktreeResult) | { ok: false; error: string }>
|
||||
forceDeletePreservedBranch: (
|
||||
worktreeId: string,
|
||||
branchName: string,
|
||||
expectedHead: string
|
||||
) => Promise<({ ok: true } & ForceDeleteWorktreeBranchResult) | { ok: false; error: string }>
|
||||
clearWorktreeDeleteState: (worktreeId: string) => void
|
||||
updateWorktreeMeta: (worktreeId: string, updates: Partial<WorktreeMeta>) => Promise<void>
|
||||
updateWorktreesMeta: (
|
||||
|
||||
@@ -56,6 +56,7 @@ const mockApi = {
|
||||
),
|
||||
listLineage: vi.fn().mockResolvedValue({}),
|
||||
remove: vi.fn().mockResolvedValue(undefined),
|
||||
forceDeletePreservedBranch: vi.fn().mockResolvedValue({ deleted: true }),
|
||||
resolvePrBase: vi.fn(),
|
||||
updateMeta: vi.fn().mockResolvedValue(undefined),
|
||||
updateLineage: vi.fn().mockResolvedValue(null)
|
||||
|
||||
@@ -7,9 +7,11 @@ import type {
|
||||
TerminalPaneLayoutNode,
|
||||
LocalBaseRefRefreshResult,
|
||||
Repo,
|
||||
ForceDeleteWorktreeBranchResult,
|
||||
Worktree,
|
||||
WorkspaceVisibleTabType,
|
||||
GitPushTarget,
|
||||
RemoveWorktreeResult,
|
||||
WorktreeLineage,
|
||||
WorktreeMeta
|
||||
} from '../../../../shared/types'
|
||||
@@ -86,6 +88,28 @@ function showLocalBaseRefRefreshToast(result: LocalBaseRefRefreshResult | undefi
|
||||
})
|
||||
}
|
||||
|
||||
function showPreservedBranchToast(
|
||||
result: RemoveWorktreeResult | undefined,
|
||||
onForceDelete: (branchName: string, expectedHead: string) => void
|
||||
): void {
|
||||
const preservedBranch = result?.preservedBranch
|
||||
const branch = preservedBranch?.branchName
|
||||
if (!branch) {
|
||||
return
|
||||
}
|
||||
const expectedHead = preservedBranch.head
|
||||
const action = expectedHead
|
||||
? {
|
||||
label: 'Force Delete Branch',
|
||||
onClick: () => onForceDelete(branch, expectedHead)
|
||||
}
|
||||
: undefined
|
||||
toast.warning('Workspace deleted, branch kept', {
|
||||
description: `Git could not safely delete "${branch}", so Orca kept it to avoid losing local commits.`,
|
||||
...(action ? { action } : {})
|
||||
})
|
||||
}
|
||||
|
||||
function arraysShallowEqual(a: string[] | undefined, b: string[] | undefined): boolean {
|
||||
if (a === b) {
|
||||
return true
|
||||
@@ -1138,9 +1162,9 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
|
||||
const skipArchive = trustDecision === 'skip'
|
||||
|
||||
const target = getActiveRuntimeTarget(get().settings)
|
||||
await (target.kind === 'local'
|
||||
const removalResult = await (target.kind === 'local'
|
||||
? window.api.worktrees.remove({ worktreeId, force, skipArchive })
|
||||
: callRuntimeRpc(
|
||||
: callRuntimeRpc<RemoveWorktreeResult>(
|
||||
target,
|
||||
'worktree.rm',
|
||||
{ worktree: worktreeId, force, runHooks: !skipArchive },
|
||||
@@ -1364,7 +1388,12 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
|
||||
}
|
||||
})
|
||||
get().removeWorkspaceSpaceWorktrees?.([worktreeId])
|
||||
return { ok: true as const }
|
||||
showPreservedBranchToast(removalResult, (branch, expectedHead) => {
|
||||
void get().forceDeletePreservedBranch(worktreeId, branch, expectedHead)
|
||||
})
|
||||
return removalResult?.preservedBranch
|
||||
? { ok: true as const, preservedBranch: removalResult.preservedBranch }
|
||||
: { ok: true as const }
|
||||
} catch (err) {
|
||||
// Why: git refusing a non-force delete for dirty/untracked files is a
|
||||
// handled user decision point surfaced by the delete toast, not an app error.
|
||||
@@ -1384,6 +1413,34 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
|
||||
}
|
||||
},
|
||||
|
||||
forceDeletePreservedBranch: async (worktreeId, branchName, expectedHead) => {
|
||||
try {
|
||||
const target = getActiveRuntimeTarget(get().settings)
|
||||
const result = await (target.kind === 'local'
|
||||
? window.api.worktrees.forceDeletePreservedBranch({
|
||||
worktreeId,
|
||||
branchName,
|
||||
expectedHead
|
||||
})
|
||||
: callRuntimeRpc<ForceDeleteWorktreeBranchResult>(
|
||||
target,
|
||||
'worktree.forceDeleteBranch',
|
||||
{ worktree: worktreeId, branchName, expectedHead },
|
||||
{ timeoutMs: 15_000 }
|
||||
))
|
||||
toast.success('Local branch deleted', {
|
||||
description: `Deleted "${branchName}".`
|
||||
})
|
||||
return { ok: true as const, ...result }
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err.message : String(err)
|
||||
toast.error('Failed to delete branch', {
|
||||
description: error
|
||||
})
|
||||
return { ok: false as const, error }
|
||||
}
|
||||
},
|
||||
|
||||
clearWorktreeDeleteState: (worktreeId) => {
|
||||
set((s) => {
|
||||
if (!s.deleteStateByWorktreeId[worktreeId]) {
|
||||
|
||||
@@ -6,11 +6,13 @@ import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope'
|
||||
import type {
|
||||
DetectedWorktreeListResult,
|
||||
DirEntry,
|
||||
ForceDeleteWorktreeBranchResult,
|
||||
GlobalSettings,
|
||||
MemorySnapshot,
|
||||
OnboardingState,
|
||||
PersistedUIState,
|
||||
Repo,
|
||||
RemoveWorktreeResult,
|
||||
SearchResult,
|
||||
StatsSummary,
|
||||
Worktree,
|
||||
@@ -982,8 +984,14 @@ function createWorktreesApi(): NonNullable<Partial<PreloadApi>['worktrees']> {
|
||||
}),
|
||||
remove: async ({ worktreeId, force }) => {
|
||||
invalidateRuntimeWorktreeCaches()
|
||||
await callRuntimeResult('worktree.rm', { worktree: worktreeId, force })
|
||||
return callRuntimeResult<RemoveWorktreeResult>('worktree.rm', { worktree: worktreeId, force })
|
||||
},
|
||||
forceDeletePreservedBranch: ({ worktreeId, branchName, expectedHead }) =>
|
||||
callRuntimeResult<ForceDeleteWorktreeBranchResult>('worktree.forceDeleteBranch', {
|
||||
worktree: worktreeId,
|
||||
branchName,
|
||||
expectedHead
|
||||
}),
|
||||
updateMeta: async ({ worktreeId, updates }) =>
|
||||
(
|
||||
await callRuntimeResult<{ worktree: Worktree }>('worktree.set', {
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
BrowserSessionProfile,
|
||||
BrowserSessionProfileSource,
|
||||
GitWorktreeInfo,
|
||||
RemoveWorktreeResult,
|
||||
Repo,
|
||||
TabGroupLayoutNode,
|
||||
TerminalColorOverrides,
|
||||
@@ -418,6 +419,11 @@ export type RuntimeWorktreeCreateResult = {
|
||||
warning?: string
|
||||
}
|
||||
|
||||
export type RuntimeWorktreeRemoveResult = RemoveWorktreeResult & {
|
||||
removed: boolean
|
||||
warning?: string
|
||||
}
|
||||
|
||||
export type RuntimeWorktreePsResult = {
|
||||
worktrees: RuntimeWorktreePsSummary[]
|
||||
totalCount: number
|
||||
|
||||
@@ -1402,6 +1402,19 @@ export type CreateWorktreeResult = {
|
||||
localBaseRefRefresh?: LocalBaseRefRefreshResult
|
||||
}
|
||||
|
||||
export type PreservedWorktreeBranch = {
|
||||
branchName: string
|
||||
head?: string
|
||||
}
|
||||
|
||||
export type RemoveWorktreeResult = {
|
||||
preservedBranch?: PreservedWorktreeBranch
|
||||
}
|
||||
|
||||
export type ForceDeleteWorktreeBranchResult = {
|
||||
deleted: true
|
||||
}
|
||||
|
||||
export type LocalBaseRefRefreshResult = {
|
||||
status: 'updated' | 'skipped_dirty_worktree' | 'skipped_not_fast_forward' | 'skipped_error'
|
||||
baseRef: string
|
||||
|
||||
Reference in New Issue
Block a user