Allow preserving child workspaces on deletion

This commit is contained in:
Jinjing
2026-11-08 15:00:42 -08:00
parent a30768edd0
commit 1a54cd2dbc
14 changed files with 751 additions and 117 deletions
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import React, { useCallback, useMemo, useRef, useState } from 'react'
import {
Dialog,
DialogContent,
@@ -42,6 +42,8 @@ import { RemovalUnsavedFilesNotice } from './RemovalUnsavedFilesNotice'
import { confirmUnsavedDiscard } from '@/store/slices/worktrees/teardown/removed-workspace-unsaved-files'
import { useDeleteWorktreeDialogTargets } from './use-delete-worktree-dialog-targets'
import { collectRemovalUnsavedFiles } from '@/components/editor/save/flush/removal-unsaved-editor-files'
import { useDetachWorktreeDeleteChildren } from './use-detach-worktree-delete-children'
import { useDeleteWorktreeDialogDismissal } from './use-delete-worktree-dialog-dismissal'
const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
const t = useTranslate()
@@ -74,12 +76,17 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
: [],
[modalData.worktreeIds, worktreeId]
)
const { worktreeDeleteIdentities, lineageDeleteIdentities, resolveConfirmedTargets } =
useConfirmedWorktreeDeleteTargets({
worktreeIdentityData: modalData.worktreeDeleteIdentities,
lineageIdentityData: modalData.lineageDeleteIdentities,
closeModal
})
const {
worktreeDeleteIdentities,
lineageDeleteIdentities,
lineagePreserveIdentities,
resolveConfirmedTargets
} = useConfirmedWorktreeDeleteTargets({
worktreeIdentityData: modalData.worktreeDeleteIdentities,
lineageIdentityData: modalData.lineageDeleteIdentities,
preservationIdentityData: modalData.lineagePreserveIdentities,
closeModal
})
const deleteStateTargets = useMemo(
() =>
worktreeDeleteIdentities.length > 0
@@ -115,15 +122,31 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
() =>
!isBatchDelete && worktree
? getWorkspaceDeleteLineage(worktree, allWorktrees, worktreeLineageById)
: { descendants: [], deleteAllTargets: [] },
: { descendants: [], directChildren: [], deleteAllTargets: [] },
[allWorktrees, isBatchDelete, worktree, worktreeLineageById]
)
const confirmButtonRef = useRef<HTMLButtonElement>(null)
// Git cannot remove the original clone with worktree remove; block it before the force-delete dead end.
const isMainWorktree = !isBatchDelete && (worktree?.isMainWorktree ?? false)
const childWorkspaceCount = lineageDelete.descendants.length
const {
preserveChildren,
setPreserveChildren,
isDetachingChildren,
detachError,
canPreserveChildren,
detachChildren
} = useDetachWorktreeDeleteChildren({
isOpen,
parent: worktree,
lineage: lineageDelete,
isFolderWorkspace: isFolderWorkspaceDelete,
confirmedIdentities: lineagePreserveIdentities,
resolveConfirmedTargets
})
const canDeleteAllLineage =
!isMainWorktree && !isBatchDelete && lineageDelete.deleteAllTargets.length > 1
const deleteAllLineage = canDeleteAllLineage && !preserveChildren
const lineageFolderWorkspaceDeleteCount = useMemo(
() => countFolderWorkspaceDeletes(repoMap, lineageDelete.deleteAllTargets),
[lineageDelete.deleteAllTargets, repoMap]
@@ -140,8 +163,8 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
!isBatchDelete && modalData.allowSkipConfirm !== false && childWorkspaceCount === 0
const [isSavingForcePreference, setIsSavingForcePreference] = useState(false)
const deleteTargets = useMemo(
() => (canDeleteAllLineage ? lineageDelete.deleteAllTargets : worktrees),
[canDeleteAllLineage, lineageDelete.deleteAllTargets, worktrees]
() => (deleteAllLineage ? lineageDelete.deleteAllTargets : worktrees),
[deleteAllLineage, lineageDelete.deleteAllTargets, worktrees]
)
const deleteStates = useMemo(
() =>
@@ -153,7 +176,7 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
const deleteState = worktree
? getDeleteStateForWorktreeHost(worktree, deleteStateByWorktreeId)
: undefined
const isDeleting = deleteStates.some((state) => state.isDeleting)
const isDeleting = isDetachingChildren || deleteStates.some((state) => state.isDeleting)
const unsavedTargets = useMemo(
() => deleteTargets.map(({ id, hostId }) => ({ id, hostId })),
[deleteTargets]
@@ -185,54 +208,17 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
([key, state]) => state !== 'complete' && !dirtyChanges.counts.has(key)
)
useEffect(() => {
if (isOpen && worktreeIds.length > 0 && worktrees.length === 0 && !isDeleting) {
for (const target of deleteStateTargets) {
clearWorktreeDeleteState(target.id, target.hostId)
}
closeModal()
}
}, [
clearWorktreeDeleteState,
closeModal,
deleteStateTargets,
isDeleting,
const handleOpenChange = useDeleteWorktreeDialogDismissal({
isOpen,
worktreeIds,
worktreeIds.length,
worktrees.length
])
const handleOpenChange = useCallback(
(open: boolean) => {
if (open || isSavingForcePreference) {
return
}
const state = useAppStore.getState().deleteStateByWorktreeId
const currentTarget = deleteStateTargets.find((target) => target.id === worktreeId)
const currentState = currentTarget
? getDeleteStateForWorktreeHost(currentTarget, state)
: undefined
if (isBatchDelete) {
for (const target of deleteStateTargets) {
if (!getDeleteStateForWorktreeHost(target, state)?.isDeleting) {
clearWorktreeDeleteState(target.id, target.hostId)
}
}
} else if (worktreeId && !currentState?.isDeleting) {
clearWorktreeDeleteState(worktreeId, currentTarget?.hostId)
}
closeModal()
},
[
clearWorktreeDeleteState,
closeModal,
deleteStateTargets,
isBatchDelete,
isSavingForcePreference,
worktreeId
]
)
isDeleting,
isSaving: isSavingForcePreference || isDetachingChildren,
isBatchDelete,
worktreeId,
worktreeCount: worktrees.length,
deleteStateTargets,
clearWorktreeDeleteState,
closeModal
})
const persistSkipConfirmPreference = useCallback(
(): Promise<void> =>
@@ -311,6 +297,10 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
})
}
const handleDetachAndDelete = (): void => {
void detachChildren(() => handleDelete(canForceDelete))
}
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogContent
@@ -339,7 +329,7 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
showUnknownChangeLossWarning={hasUnknownChangeState}
targetClassName={deleteCopy.targetClassName}
targetName={isBatchDelete ? undefined : worktree?.displayName}
description={canDeleteAllLineage ? lineageDeleteDescription : deleteCopy.description}
description={deleteAllLineage ? lineageDeleteDescription : deleteCopy.description}
/>
</DialogHeader>
@@ -366,6 +356,10 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
changeCheckStatesByWorktreeId={dirtyChanges.checkStates}
dirtyChangeCountsByWorktreeId={dirtyChanges.counts}
dirtyChangePreviewsByWorktreeId={dirtyChanges.previews}
preserveChildren={preserveChildren}
canPreserveChildren={canPreserveChildren}
disabled={isDeleting}
onPreserveChildrenChange={setPreserveChildren}
/>
)}
</div>
@@ -373,22 +367,29 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
<DeleteWorktreeWarningPanels
isMainWorktree={isMainWorktree}
mainWorktreeBlocker={deleteCopy.mainWorktreeBlocker}
deleteError={deleteError}
deleteError={detachError ?? deleteError}
/>
<DialogFooter>
<DeleteWorktreeDialogFooter
isMainWorktree={isMainWorktree}
isDeleting={isDeleting || isSavingForcePreference}
isDetachingChildren={isDetachingChildren}
canForceDelete={canForceDelete}
isBatchDelete={isBatchDelete}
worktreeCount={worktrees.length}
canDeleteAllLineage={canDeleteAllLineage}
canDeleteAllLineage={deleteAllLineage}
lineageDeleteTargetCount={lineageDelete.deleteAllTargets.length}
onCancel={() => handleOpenChange(false)}
onForceDelete={() => handleDelete(true)}
onForceDelete={preserveChildren ? handleDetachAndDelete : () => handleDelete(true)}
onSavingChange={setIsSavingForcePreference}
onDelete={canDeleteAllLineage ? handleDeleteAll : () => handleDelete(false)}
onDelete={
preserveChildren
? handleDetachAndDelete
: canDeleteAllLineage
? handleDeleteAll
: () => handleDelete(false)
}
onAlwaysDelete={allowSkipConfirm ? persistSkipConfirmPreference : undefined}
confirmButtonRef={confirmButtonRef}
/>
@@ -10,6 +10,7 @@ import { deleteWorkspacesCountLabel } from '../context-menu/workspace-batch-acti
export function DeleteWorktreeDialogFooter({
isMainWorktree,
isDeleting,
isDetachingChildren = false,
canForceDelete,
isBatchDelete,
worktreeCount,
@@ -24,6 +25,7 @@ export function DeleteWorktreeDialogFooter({
}: {
isMainWorktree: boolean
isDeleting: boolean
isDetachingChildren?: boolean
canForceDelete: boolean
isBatchDelete: boolean
worktreeCount: number
@@ -38,20 +40,22 @@ export function DeleteWorktreeDialogFooter({
confirmButtonRef: Ref<HTMLButtonElement>
}): JSX.Element {
const t = useTranslate()
const label = isDeleting
? canForceDelete
? t('auto.components.sidebar.DeleteWorktreeDialogFooter.forceDeleting', 'Force Deleting...')
: t('auto.components.sidebar.DeleteWorktreeDialogFooter.deleting', 'Deleting...')
: isBatchDelete
? deleteWorkspacesCountLabel(worktreeCount, t)
: canDeleteAllLineage
? deleteWorkspacesCountLabel(lineageDeleteTargetCount, t)
: canForceDelete
? t('auto.components.sidebar.DeleteWorktreeDialogFooter.forceDelete', 'Force Delete')
: t(
'auto.components.sidebar.DeleteWorktreeDialogFooter.deleteWorkspace',
'Delete Workspace'
)
const label = isDetachingChildren
? t('worktree.delete.detachingChildren', 'Detaching children...')
: isDeleting
? canForceDelete
? t('auto.components.sidebar.DeleteWorktreeDialogFooter.forceDeleting', 'Force Deleting...')
: t('auto.components.sidebar.DeleteWorktreeDialogFooter.deleting', 'Deleting...')
: isBatchDelete
? deleteWorkspacesCountLabel(worktreeCount, t)
: canDeleteAllLineage
? deleteWorkspacesCountLabel(lineageDeleteTargetCount, t)
: canForceDelete
? t('auto.components.sidebar.DeleteWorktreeDialogFooter.forceDelete', 'Force Delete')
: t(
'auto.components.sidebar.DeleteWorktreeDialogFooter.deleteWorkspace',
'Delete Workspace'
)
return (
<>
@@ -0,0 +1,50 @@
import { useState } from 'react'
import { defineFixture } from '../../../../component-fixtures/component-fixture'
import type { Worktree } from '../../../../../../shared/worktree/types'
import { DeleteWorktreeLineageNotice } from './DeleteWorktreeLineageNotice'
const child: Worktree = {
id: 'repo::/workspaces/feature-child',
instanceId: 'child-instance',
repoId: 'repo',
path: '/workspaces/feature-child',
displayName: 'Review the workspace deletion flow',
head: 'abc123',
branch: 'feature-child',
isBare: false,
isMainWorktree: false,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0
}
function LineageNotice({ initialPreserve = false, canPreserve = true }) {
const [preserve, setPreserve] = useState(initialPreserve)
return (
<DeleteWorktreeLineageNotice
descendants={[child]}
dirtyChangeCountsByWorktreeId={new Map([[child.id, 3]])}
dirtyChangePreviewsByWorktreeId={new Map()}
preserveChildren={preserve}
canPreserveChildren={canPreserve}
disabled={false}
onPreserveChildrenChange={setPreserve}
/>
)
}
export const deleteChildren = defineFixture({ width: 400, render: () => <LineageNotice /> })
export const keepChildren = defineFixture({
width: 400,
render: () => <LineageNotice initialPreserve />
})
export const nestedChildren = defineFixture({
width: 400,
render: () => <LineageNotice canPreserve={false} />
})
@@ -14,6 +14,7 @@ import type {
DeleteWorktreeDirtyChangePreview
} from './delete-worktree-dirty-change-counts'
import { useTranslate } from '@/i18n/use-translate'
import { Checkbox } from '@/components/ui/checkbox'
type DeleteWorktreeLineageNoticeProps = {
descendants: readonly Worktree[]
@@ -22,6 +23,10 @@ type DeleteWorktreeLineageNoticeProps = {
dirtyChangeCountsByWorktreeId: ReadonlyMap<string, number>
dirtyChangePreviewsByWorktreeId: ReadonlyMap<string, DeleteWorktreeDirtyChangePreview>
changeCheckStatesByWorktreeId?: ReadonlyMap<string, DeleteWorktreeChangeCheckState>
preserveChildren: boolean
canPreserveChildren: boolean
disabled: boolean
onPreserveChildrenChange: (preserve: boolean) => void
}
export function DeleteWorktreeLineageNotice({
@@ -30,7 +35,11 @@ export function DeleteWorktreeLineageNotice({
repoMap,
dirtyChangeCountsByWorktreeId,
dirtyChangePreviewsByWorktreeId,
changeCheckStatesByWorktreeId
changeCheckStatesByWorktreeId,
preserveChildren,
canPreserveChildren,
disabled,
onPreserveChildrenChange
}: DeleteWorktreeLineageNoticeProps): JSX.Element | null {
const t = useTranslate()
const projects = useAppStore((s) => s.projects)
@@ -65,20 +74,28 @@ export function DeleteWorktreeLineageNotice({
<Workflow className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="font-medium text-foreground">
{t(
'auto.components.sidebar.DeleteWorktreeLineageNotice.a940f3c96e',
'Child workspaces will be deleted'
)}
{preserveChildren
? t('worktree.delete.childrenPreservedTitle', 'Child workspaces will be kept')
: t(
'auto.components.sidebar.DeleteWorktreeLineageNotice.a940f3c96e',
'Child workspaces will be deleted'
)}
</div>
<div className="mt-1 text-muted-foreground">
{t(
'auto.components.sidebar.DeleteWorktreeLineageNotice.alsoDeletesChildren',
'Deleting this workspace also deletes {{count}} child workspaces.',
{
count: childWorkspaceCount,
defaultValue_one: 'Deleting this workspace also deletes {{count}} child workspace.'
}
)}
{preserveChildren
? t(
'worktree.delete.childrenPreservedDescription',
'Direct children will become top-level workspaces. Their files, terminals, and nested children will be kept.'
)
: t(
'auto.components.sidebar.DeleteWorktreeLineageNotice.alsoDeletesChildren',
'Deleting this workspace also deletes {{count}} child workspaces.',
{
count: childWorkspaceCount,
defaultValue_one:
'Deleting this workspace also deletes {{count}} child workspace.'
}
)}
{foreignProjects.length > 0 ? ` (${foreignProjects.join(', ')})` : null}
</div>
{/* Constrain grid min-content width so nowrap paths cannot widen the modal. */}
@@ -92,17 +109,19 @@ export function DeleteWorktreeLineageNotice({
) : null}
</div>
<div className="truncate text-muted-foreground">{child.path}</div>
<DeleteWorktreeDirtyChangeHint
checkState={changeCheckStatesByWorktreeId?.get(
child.hostId ? getWorktreeHostIdentity(child) : child.id
)}
changeCount={dirtyChangeCountsByWorktreeId.get(
child.hostId ? getWorktreeHostIdentity(child) : child.id
)}
preview={dirtyChangePreviewsByWorktreeId.get(
child.hostId ? getWorktreeHostIdentity(child) : child.id
)}
/>
{!preserveChildren && (
<DeleteWorktreeDirtyChangeHint
checkState={changeCheckStatesByWorktreeId?.get(
child.hostId ? getWorktreeHostIdentity(child) : child.id
)}
changeCount={dirtyChangeCountsByWorktreeId.get(
child.hostId ? getWorktreeHostIdentity(child) : child.id
)}
preview={dirtyChangePreviewsByWorktreeId.get(
child.hostId ? getWorktreeHostIdentity(child) : child.id
)}
/>
)}
</div>
))}
{descendants.length > 4 ? (
@@ -115,6 +134,22 @@ export function DeleteWorktreeLineageNotice({
</div>
) : null}
</div>
<label className="mt-3 flex items-center gap-2 text-foreground">
<Checkbox
checked={preserveChildren}
disabled={disabled || !canPreserveChildren}
onCheckedChange={(checked) => onPreserveChildrenChange(checked === true)}
/>
{t('worktree.delete.detachChildren', 'Detach and keep child workspaces')}
</label>
{!canPreserveChildren && (
<p className="mt-1 text-muted-foreground">
{t(
'worktree.delete.nestedChildrenCannotBeKept',
'Child workspace folders inside this workspace must be moved outside it before they can be kept.'
)}
</p>
)}
</div>
</div>
</div>
@@ -107,7 +107,11 @@ export function runWorktreeDelete(worktreeId: string, options: WorktreeDeleteOpt
worktreeDeleteIdentities: toWorktreeDeleteIdentities([target]),
...(hasLineageChildren
? {
lineageDeleteIdentities: toWorktreeDeleteIdentities(deleteLineage.deleteAllTargets)
lineageDeleteIdentities: toWorktreeDeleteIdentities(deleteLineage.deleteAllTargets),
lineagePreserveIdentities: toWorktreeDeleteIdentities([
target,
...deleteLineage.descendants
])
}
: {}),
...(hasLineageChildren ? { allowSkipConfirm: false } : {})
@@ -175,7 +179,11 @@ export function runWorktreeBatchDelete(
? {
lineageDeleteIdentities: toWorktreeDeleteIdentities(
singleTargetLineage.deleteAllTargets
)
),
lineagePreserveIdentities: toWorktreeDeleteIdentities([
targets[0],
...singleTargetLineage.descendants
])
}
: {}),
...(options.forceConfirm || singleTargetHasLineageChildren
@@ -0,0 +1,92 @@
import type { AppState } from '@/store/types'
import { forEachWithConcurrency } from '../../../../../../shared/map-with-concurrency'
import { isPathInsideOrEqual } from '../../../../../../shared/cross-platform-path'
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
import type { Worktree } from '../../../../../../shared/worktree/types'
export function canPreserveWorkspaceDeleteChildren(
parent: Worktree,
descendants: readonly Worktree[],
isFolderWorkspace: boolean
): boolean {
return (
isFolderWorkspace ||
descendants.every(
(child) =>
(child.hostId !== undefined &&
parent.hostId !== undefined &&
child.hostId !== parent.hostId) ||
!isPathInsideOrEqual(parent.path, child.path)
)
)
}
export async function detachWorktreeDeleteChildren(
children: readonly Worktree[],
updateWorktreeLineage: AppState['updateWorktreeLineage'],
resolveCurrentChild: (child: Worktree) => Worktree | null,
assertDetached: () => void
): Promise<void> {
let failure: { reason: unknown } | undefined
await forEachWithConcurrency(children, 4, async (child) => {
if (failure) {
return
}
try {
const current = resolveCurrentChild(child)
if (!current) {
return
}
await updateWorktreeLineage(current.id, {
noParent: true,
...(current.hostId ? { executionHostId: current.hostId } : {})
})
} catch (reason) {
failure ??= { reason }
}
})
if (failure) {
throw failure.reason
}
assertDetached()
}
export function workspaceDeleteTargetsMatch(
expected: readonly Worktree[],
current: readonly Worktree[]
): boolean {
const expectedInstances = new Map(
expected.map((target) => [getWorktreeHostIdentity(target), target.instanceId])
)
return current.every(
(target) =>
expectedInstances.has(getWorktreeHostIdentity(target)) &&
expectedInstances.get(getWorktreeHostIdentity(target)) === target.instanceId
)
}
export function captureWorkspaceDeleteRowLookup(
initialRows: AppState['worktreesByRepo'],
targets: readonly Worktree[]
) {
const expected = new Set(targets.map(getWorktreeHostIdentity))
const positions = new Map<string, { repoId: string; index: number }>()
for (const [repoId, rows] of Object.entries(initialRows)) {
rows.forEach((row, index) => {
const identity = getWorktreeHostIdentity(row)
if (expected.has(identity)) {
positions.set(identity, { repoId, index })
}
})
}
return (currentRows: AppState['worktreesByRepo'], target: Worktree): Worktree | undefined => {
const identity = getWorktreeHostIdentity(target)
const position = positions.get(identity)
const current = position ? currentRows[position.repoId]?.[position.index] : undefined
return current &&
getWorktreeHostIdentity(current) === identity &&
current.instanceId === target.instanceId
? current
: undefined
}
}
@@ -11,10 +11,12 @@ import { showWorkspaceListChangedToast } from '../../worktree-list/listing/stale
export function useConfirmedWorktreeDeleteTargets({
worktreeIdentityData,
lineageIdentityData,
preservationIdentityData,
closeModal
}: {
worktreeIdentityData: unknown
lineageIdentityData: unknown
preservationIdentityData: unknown
closeModal: () => void
}) {
const worktreeDeleteIdentities = useMemo(
@@ -25,11 +27,21 @@ export function useConfirmedWorktreeDeleteTargets({
() => readWorktreeDeleteIdentities(lineageIdentityData),
[lineageIdentityData]
)
const lineagePreserveIdentities = useMemo(
() => readWorktreeDeleteIdentities(preservationIdentityData ?? lineageIdentityData),
[preservationIdentityData, lineageIdentityData]
)
const resolveConfirmedTargets = useCallback(
(identities: readonly WorktreeDeleteIdentity[], expectedCount: number) => {
(
identities: readonly WorktreeDeleteIdentity[],
expectedCount: number,
options: { includeMainWorktrees?: boolean } = {}
) => {
const state = useAppStore.getState()
const targets = resolveWorktreeBatchDeleteTargets(identities, (worktreeId, hostId) =>
getWorktreeOnHostFromState(state, worktreeId, hostId)
const targets = resolveWorktreeBatchDeleteTargets(
identities,
(worktreeId, hostId) => getWorktreeOnHostFromState(state, worktreeId, hostId),
options
)
if (!targets || targets.length !== expectedCount) {
showWorkspaceListChangedToast()
@@ -41,5 +53,10 @@ export function useConfirmedWorktreeDeleteTargets({
[closeModal]
)
return { worktreeDeleteIdentities, lineageDeleteIdentities, resolveConfirmedTargets }
return {
worktreeDeleteIdentities,
lineageDeleteIdentities,
lineagePreserveIdentities,
resolveConfirmedTargets
}
}
@@ -0,0 +1,60 @@
import { useCallback, useEffect } from 'react'
import { useAppStore } from '@/store'
import type { AppState } from '@/store/types'
import type { Worktree } from '../../../../../../shared/worktree/types'
import { getDeleteStateForWorktreeHost } from './worktree-delete-state-host-match'
export function useDeleteWorktreeDialogDismissal({
isOpen,
isDeleting,
isSaving,
isBatchDelete,
worktreeId,
worktreeCount,
deleteStateTargets,
clearWorktreeDeleteState,
closeModal
}: {
isOpen: boolean
isDeleting: boolean
isSaving: boolean
isBatchDelete: boolean
worktreeId: string
worktreeCount: number
deleteStateTargets: readonly Pick<Worktree, 'id' | 'hostId'>[]
clearWorktreeDeleteState: AppState['clearWorktreeDeleteState']
closeModal: () => void
}) {
useEffect(() => {
if (isOpen && deleteStateTargets.length > 0 && worktreeCount === 0 && !isDeleting) {
for (const target of deleteStateTargets) {
clearWorktreeDeleteState(target.id, target.hostId)
}
closeModal()
}
}, [clearWorktreeDeleteState, closeModal, deleteStateTargets, isDeleting, isOpen, worktreeCount])
return useCallback(
(open: boolean) => {
if (open || isSaving) {
return
}
const state = useAppStore.getState().deleteStateByWorktreeId
const currentTarget = deleteStateTargets.find((target) => target.id === worktreeId)
const currentState = currentTarget
? getDeleteStateForWorktreeHost(currentTarget, state)
: undefined
if (isBatchDelete) {
for (const target of deleteStateTargets) {
if (!getDeleteStateForWorktreeHost(target, state)?.isDeleting) {
clearWorktreeDeleteState(target.id, target.hostId)
}
}
} else if (worktreeId && !currentState?.isDeleting) {
clearWorktreeDeleteState(worktreeId, currentTarget?.hostId)
}
closeModal()
},
[clearWorktreeDeleteState, closeModal, deleteStateTargets, isBatchDelete, isSaving, worktreeId]
)
}
@@ -0,0 +1,159 @@
import { useState } from 'react'
import { useTranslate } from '@/i18n/use-translate'
import { useAppStore } from '@/store'
import { getIndexedAllWorktrees } from '@/store/slices/worktrees/listing/worktree-catalog-index'
import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields'
import { isValidResolvedWorktreeLineageEdge } from '../../../../../../shared/resolved-worktree-lineage'
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
import type { Worktree } from '../../../../../../shared/worktree/types'
import type { WorktreeDeleteIdentity } from './worktree-delete-request'
import {
getWorkspaceDeleteLineage,
getWorkspaceDeleteLineageRecord
} from './workspace-delete-lineage'
import {
canPreserveWorkspaceDeleteChildren,
captureWorkspaceDeleteRowLookup,
detachWorktreeDeleteChildren,
workspaceDeleteTargetsMatch
} from './detach-worktree-delete-children'
export function useDetachWorktreeDeleteChildren({
isOpen,
parent,
lineage,
isFolderWorkspace,
confirmedIdentities,
resolveConfirmedTargets
}: {
isOpen: boolean
parent: Worktree | null | undefined
lineage: ReturnType<typeof getWorkspaceDeleteLineage>
isFolderWorkspace: boolean
confirmedIdentities: readonly WorktreeDeleteIdentity[]
resolveConfirmedTargets: (
identities: readonly WorktreeDeleteIdentity[],
expectedCount: number,
options?: { includeMainWorktrees?: boolean }
) => Worktree[] | null
}) {
const t = useTranslate()
const [preserveChildren, setPreserve] = useState(false)
const [isDetachingChildren, setIsDetachingChildren] = useState(false)
const [detachError, setDetachError] = useState<string | null>(null)
const canPreserveChildren =
!!parent && canPreserveWorkspaceDeleteChildren(parent, lineage.descendants, isFolderWorkspace)
if (!isOpen && (preserveChildren || detachError)) {
setPreserve(false)
setDetachError(null)
}
const detachChildren = async (onDetached: () => void): Promise<void> => {
if (isDetachingChildren || !canPreserveChildren || !parent) {
return
}
const confirmedTargets = resolveConfirmedTargets(
confirmedIdentities,
confirmedIdentities.length,
{ includeMainWorktrees: true }
)
if (!confirmedTargets) {
return
}
const changedError = () =>
new Error(
t(
'worktree.delete.childrenChanged',
'Child workspaces changed. Review the workspace list and try again.'
)
)
const assertCurrentTargets = (detached: boolean) => {
const targets = resolveConfirmedTargets(confirmedIdentities, confirmedTargets.length, {
includeMainWorktrees: true
})
const state = useAppStore.getState()
const currentParent = targets?.find(
(target) => getWorktreeHostIdentity(target) === getWorktreeHostIdentity(parent)
)
if (
!targets ||
!currentParent ||
!canPreserveWorkspaceDeleteChildren(
currentParent,
targets.filter((target) => target !== currentParent),
isFolderWorkspace
)
) {
throw changedError()
}
const currentLineage = getWorkspaceDeleteLineage(
currentParent,
getIndexedAllWorktrees(selectWorktreesByRepo(state)),
state.worktreeLineageById
)
if (
!workspaceDeleteTargetsMatch(confirmedTargets, currentLineage.descendants) ||
(detached && currentLineage.descendants.length > 0)
) {
throw changedError()
}
return currentLineage
}
setIsDetachingChildren(true)
setDetachError(null)
try {
const currentLineage = assertCurrentTargets(false)
const currentRow = captureWorkspaceDeleteRowLookup(
useAppStore.getState().worktreesByRepo,
confirmedTargets
)
await detachWorktreeDeleteChildren(
currentLineage.directChildren,
useAppStore.getState().updateWorktreeLineage,
(child) => {
const state = useAppStore.getState()
const current = currentRow(state.worktreesByRepo, child)
const currentParent = currentRow(state.worktreesByRepo, parent)
if (
!current ||
current.instanceId !== child.instanceId ||
!currentParent ||
currentParent.instanceId !== parent.instanceId ||
!canPreserveWorkspaceDeleteChildren(currentParent, [current], isFolderWorkspace)
) {
throw changedError()
}
const edge = getWorkspaceDeleteLineageRecord(current, state.worktreeLineageById)
return edge && isValidResolvedWorktreeLineageEdge(current, currentParent, edge)
? current
: null
},
() => assertCurrentTargets(true)
)
onDetached()
} catch (error) {
setDetachError(
t(
'worktree.delete.detachFailed',
'Could not detach all child workspaces. The parent was not deleted. {{error}}',
{ error: error instanceof Error ? error.message : String(error) }
)
)
} finally {
setIsDetachingChildren(false)
}
}
return {
preserveChildren,
setPreserveChildren: (preserve: boolean) => {
setPreserve(preserve)
setDetachError(null)
},
isDetachingChildren,
detachError,
canPreserveChildren,
detachChildren
}
}
@@ -1,4 +1,7 @@
import { describe, expect, it } from 'vitest'
// @vitest-environment happy-dom
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
LOCAL_EXECUTION_HOST_ID,
toRuntimeExecutionHostId,
@@ -8,6 +11,31 @@ import {
import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types'
import type { Worktree } from '../../../../../../shared/worktree/types'
import { getWorkspaceDeleteLineage } from './workspace-delete-lineage'
import {
resolveWorktreeBatchDeleteTargets,
toWorktreeDeleteIdentities
} from './worktree-delete-request'
import { getWorktreeOnHostFromState } from '@/store/workspaces/selection/worktree-on-host-selector'
import { useDetachWorktreeDeleteChildren } from './use-detach-worktree-delete-children'
import {
canPreserveWorkspaceDeleteChildren,
workspaceDeleteTargetsMatch
} from './detach-worktree-delete-children'
const mocks = vi.hoisted(() => {
const worktreesByRepo: Record<string, Worktree[]> = {}
const worktreeLineageById: Record<string, WorktreeLineage> = {}
return {
state: {
worktreesByRepo,
worktreeLineageById,
updateWorktreeLineage: vi.fn<(id: string) => Promise<void>>()
}
}
})
vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.state } }))
afterEach(cleanup)
function makeWorktree(id: string, path: string): Worktree {
return {
@@ -58,6 +86,7 @@ describe('getWorkspaceDeleteLineage', () => {
})
expect(lineage.descendants.map((worktree) => worktree.id)).toEqual(['child', 'grandchild'])
expect(lineage.directChildren.map((worktree) => worktree.id)).toEqual(['child'])
expect(lineage.deleteAllTargets.map((worktree) => worktree.id)).toEqual([
'grandchild',
'child',
@@ -68,7 +97,7 @@ describe('getWorkspaceDeleteLineage', () => {
it('orders an exact inline-only legacy descendant before its parent', () => {
const parent = makeWorktree('parent', '/workspaces/parent')
const child = makeWorktree('child', '/workspaces/parent/child')
const inlineChild = { ...child, lineage: makeLineage(child, parent) } as Worktree
const inlineChild = { ...child, lineage: makeLineage(child, parent) }
const lineage = getWorkspaceDeleteLineage(parent, [parent, inlineChild], {})
@@ -79,7 +108,7 @@ describe('getWorkspaceDeleteLineage', () => {
it('keeps a stale side-map child authoritative over valid inline lineage', () => {
const parent = makeWorktree('parent', '/workspaces/parent')
const child = makeWorktree('child', '/workspaces/parent/child')
const inlineChild = { ...child, lineage: makeLineage(child, parent) } as Worktree
const inlineChild = { ...child, lineage: makeLineage(child, parent) }
const lineage = getWorkspaceDeleteLineage(parent, [parent, inlineChild], {
[child.id]: {
@@ -152,7 +181,7 @@ describe('getWorkspaceDeleteLineage', () => {
const sshChild = {
...sshChildBase,
lineage: makeLineage(sshChildBase, sshParent)
} as Worktree
}
const lineage = getWorkspaceDeleteLineage(
sshParent,
@@ -184,3 +213,156 @@ describe('getWorkspaceDeleteLineage', () => {
).toEqual(['parent'])
})
})
describe('preserving children during workspace deletion', () => {
it('includes a main-worktree child in preservation confirmation without allowing its deletion', () => {
const parent = makeWorktree('parent', '/workspaces/parent')
const child = { ...makeWorktree('main', '/workspaces/main'), isMainWorktree: true }
const lineage = getWorkspaceDeleteLineage(parent, [parent, child], {
[child.id]: makeLineage(child, parent)
})
const requests = [parent, ...lineage.descendants]
const lookup = (id: string) => requests.find((row) => row.id === id)
expect(lineage.directChildren.map((row) => row.id)).toEqual(['main'])
expect(resolveWorktreeBatchDeleteTargets(requests, lookup)?.map((row) => row.id)).toEqual([
'parent'
])
expect(
resolveWorktreeBatchDeleteTargets(requests, lookup, { includeMainWorktrees: true })?.map(
(row) => row.id
)
).toEqual(['parent', 'main'])
})
it('refuses to preserve a folder child physically inside a Git parent on the same host', () => {
const parent: Worktree = {
...makeWorktree('parent', 'C:\\workspaces\\parent'),
hostId: LOCAL_EXECUTION_HOST_ID
}
const child = makeWorktree('folder:child', 'C:\\workspaces\\parent\\child')
expect(canPreserveWorkspaceDeleteChildren(parent, [child], false)).toBe(false)
expect(canPreserveWorkspaceDeleteChildren(parent, [child], true)).toBe(true)
})
it('permits sibling directories and an identically located child on a different host', () => {
const parent: Worktree = {
...makeWorktree('parent', '/workspaces/parent'),
hostId: LOCAL_EXECUTION_HOST_ID
}
const sibling = makeWorktree('child', '/workspaces/parent-sibling')
const remote = { ...makeWorktree('remote', '/workspaces/parent/child'), hostId: SSH_HOST }
expect(canPreserveWorkspaceDeleteChildren(parent, [sibling, remote], false)).toBe(true)
})
it('treats an unstamped child as potentially belonging to its paired parent host', () => {
const parent = { ...makeWorktree('parent', '/workspaces/parent'), hostId: SSH_HOST }
const child = makeWorktree('child', '/workspaces/parent/child')
expect(canPreserveWorkspaceDeleteChildren(parent, [child], false)).toBe(false)
})
it('rejects unconfirmed descendants and same-ID replacements while allowing completed detachments', () => {
const child = { ...makeWorktree('child', '/workspaces/child'), hostId: SSH_HOST }
const grandchild = { ...makeWorktree('grandchild', '/workspaces/grandchild'), hostId: SSH_HOST }
expect(workspaceDeleteTargetsMatch([child, grandchild], [grandchild])).toBe(true)
expect(workspaceDeleteTargetsMatch([child], [{ ...child, instanceId: 'replacement' }])).toBe(
false
)
expect(
workspaceDeleteTargetsMatch([child], [{ ...child, hostId: LOCAL_EXECUTION_HOST_ID }])
).toBe(false)
expect(workspaceDeleteTargetsMatch([child], [grandchild])).toBe(false)
})
})
function renderPreservation(
parent: Worktree,
rows: Worktree[],
edges: Record<string, WorktreeLineage>
) {
mocks.state.worktreesByRepo = { 'repo-1': rows }
mocks.state.worktreeLineageById = edges
mocks.state.updateWorktreeLineage.mockReset().mockImplementation(async (id) => {
const next = { ...mocks.state.worktreeLineageById }
delete next[id]
mocks.state.worktreeLineageById = next
mocks.state.worktreesByRepo = {
'repo-1': mocks.state.worktreesByRepo['repo-1'].map((row) =>
row.id === id ? { ...row, lineage: null } : row
)
}
})
const lineage = getWorkspaceDeleteLineage(parent, rows, edges)
return renderHook(() =>
useDetachWorktreeDeleteChildren({
isOpen: true,
parent,
lineage,
isFolderWorkspace: false,
confirmedIdentities: toWorktreeDeleteIdentities([parent, ...lineage.descendants]),
resolveConfirmedTargets: (identities, expectedCount, options) => {
const targets = resolveWorktreeBatchDeleteTargets(
identities,
(id, hostId) => getWorktreeOnHostFromState(mocks.state, id, hostId),
options
)
return targets?.length === expectedCount ? targets : null
}
})
)
}
describe('detaching before parent deletion', () => {
it('keeps a newer parent assignment made after the dialog rendered', async () => {
const parent = makeWorktree('parent', '/workspaces/parent')
const child = makeWorktree('child', '/workspaces/child')
const other = makeWorktree('other', '/workspaces/other')
const hook = renderPreservation(parent, [parent, child, other], {
child: makeLineage(child, parent)
})
mocks.state.worktreeLineageById = { child: makeLineage(child, other) }
const deleted: string[] = []
await act(async () => hook.result.current.detachChildren(() => deleted.push('parent')))
expect(mocks.state.worktreeLineageById.child.parentWorktreeId).toBe('other')
expect(deleted).toEqual(['parent'])
expect(hook.result.current.detachError).toBeNull()
})
it('uses the child host inline edge when the bare map belongs to a twin', async () => {
const parent = { ...makeWorktree('parent', '/workspaces/parent'), hostId: SSH_HOST }
const childBase = { ...makeWorktree('child', '/workspaces/child'), hostId: SSH_HOST }
const child = { ...childBase, lineage: makeLineage(childBase, parent) }
const hook = renderPreservation(parent, [parent, child], {
child: { ...makeLineage(child, parent), worktreeInstanceId: 'local-twin-instance' }
})
const deleted: string[] = []
await act(async () => hook.result.current.detachChildren(() => deleted.push('parent')))
expect(deleted).toEqual(['parent'])
expect(hook.result.current.detachError).toBeNull()
})
it('keeps the parent when a child detachment fails', async () => {
const parent: Worktree = {
...makeWorktree('parent', '/workspaces/parent'),
hostId: LOCAL_EXECUTION_HOST_ID
}
const child = makeWorktree('child', '/workspaces/child')
const hook = renderPreservation(parent, [parent, child], { child: makeLineage(child, parent) })
mocks.state.updateWorktreeLineage.mockRejectedValueOnce(new Error('Host disconnected'))
const deleted: string[] = []
await act(async () => hook.result.current.detachChildren(() => deleted.push('parent')))
expect(deleted).toEqual([])
expect(hook.result.current.detachError).not.toBeNull()
expect(mocks.state.worktreeLineageById.child.parentWorktreeId).toBe('parent')
})
})
@@ -4,10 +4,20 @@ import { getProjectedWorktreeLineageChildrenByParentId } from '../../../../../..
import { lineageStoreKeyOfRow } from '../../../../../../shared/worktree/cross-store-lineage-resolution'
type WorkspaceDeleteLineage = {
directChildren: Worktree[]
descendants: Worktree[]
deleteAllTargets: Worktree[]
}
export function getWorkspaceDeleteLineageRecord(
worktree: Worktree,
lineageById: Record<string, WorktreeLineage>
): WorktreeLineage | null | undefined {
const projected = lineageById[worktree.id]
const inline = (worktree as Worktree & { lineage?: WorktreeLineage | null }).lineage
return projected?.worktreeInstanceId === worktree.instanceId ? projected : inline
}
export function getWorkspaceDeleteLineage(
parent: Worktree,
worktrees: readonly Worktree[],
@@ -30,9 +40,7 @@ export function getWorkspaceDeleteLineage(
}
const lineageForSelectedRows: Record<string, WorktreeLineage> = {}
for (const worktree of worktreeById.values()) {
const projected = lineageById[worktree.id]
const inline = (worktree as Worktree & { lineage?: WorktreeLineage | null }).lineage
const lineage = projected?.worktreeInstanceId === worktree.instanceId ? projected : inline
const lineage = getWorkspaceDeleteLineageRecord(worktree, lineageById)
if (lineage) {
lineageForSelectedRows[worktree.id] = lineage
}
@@ -70,6 +78,7 @@ export function getWorkspaceDeleteLineage(
visit(parent.id)
return {
directChildren: childrenByParentId.get(parent.id) ?? [],
descendants,
// Delete nested children first so Git cannot remove them as untracked content under the parent.
deleteAllTargets: [...childFirstTargets, parent]
@@ -44,7 +44,8 @@ export type WorktreeDeleteTargetLookup = (
export function resolveWorktreeBatchDeleteTargets(
requestedWorktrees: readonly string[] | readonly WorktreeDeleteIdentity[],
lookupTarget: WorktreeDeleteTargetLookup
lookupTarget: WorktreeDeleteTargetLookup,
options: { includeMainWorktrees?: boolean } = {}
): Worktree[] | null {
// Deduplicate by ID and host so a same-ID twin cannot disappear from the confirmed batch.
const uniqueRequests = Array.from(
@@ -64,7 +65,7 @@ export function resolveWorktreeBatchDeleteTargets(
if (typeof request !== 'string' && (!target || target.instanceId !== request.instanceId)) {
return null
}
if (target && !target.isMainWorktree) {
if (target && (options.includeMainWorktrees || !target.isMainWorktree)) {
targets.push(target)
}
}
+10 -1
View File
@@ -22629,7 +22629,16 @@
"confirm": "Delete all listed worktrees",
"preservedBranches": "Some nested worktree branches were kept"
},
"setupTerminalTitle": "Setup"
"setupTerminalTitle": "Setup",
"delete": {
"detachingChildren": "Detaching children...",
"childrenPreservedTitle": "Child workspaces will be kept",
"childrenPreservedDescription": "Direct children will become top-level workspaces. Their files, terminals, and nested children will be kept.",
"detachChildren": "Detach and keep child workspaces",
"nestedChildrenCannotBeKept": "Child workspace folders inside this workspace must be moved outside it before they can be kept.",
"childrenChanged": "Child workspaces changed. Review the workspace list and try again.",
"detachFailed": "Could not detach all child workspaces. The parent was not deleted. {{error}}"
}
},
"projectBoard": {
"noColumnField": "This board view has no single-select or iteration field to group by, so Orca is listing items instead.",
@@ -1019,6 +1019,13 @@
"workspaceDeletion.moreActions",
"workspaceDeletion.moreDeleteOptions",
"workspaceDeletion.preferenceSaveFailed",
"worktree.delete.childrenChanged",
"worktree.delete.childrenPreservedDescription",
"worktree.delete.childrenPreservedTitle",
"worktree.delete.detachChildren",
"worktree.delete.detachFailed",
"worktree.delete.detachingChildren",
"worktree.delete.nestedChildrenCannotBeKept",
"worktree.nestedRemoval.cancel",
"worktree.nestedRemoval.confirm",
"worktree.nestedRemoval.deleting",