fix(sidebar): keep delete dialog height stable and show full ignored-files list (#42995)

* fix(sidebar): keep delete dialog height stable and show full ignored-files list

* Replace delete dialog file popovers with inline collapsible sections
This commit is contained in:
Neil
2026-11-16 00:42:46 -08:00
committed by GitHub
parent a5781b8c15
commit 930f032dff
17 changed files with 580 additions and 167 deletions
@@ -45,10 +45,35 @@ describe('readWorktreeAtRiskLocalFiles (real git)', () => {
await writeFile(join(worktreePath, '.env'), 'TOKEN=feature\n')
await symlink(join(worktreePath, '.env'), join(mainPath, '.env'))
await expect(read()).resolves.toEqual({ count: 1, samplePaths: ['.env'], complete: true })
await expect(read()).resolves.toEqual({
count: 1,
samplePaths: ['.env'],
paths: ['.env'],
complete: true
})
}
)
it('returns the full sorted at-risk path list beyond the 3-path inline sample', async () => {
await appendEntry('.gitignore', '.anti-slop-plugin/\n.tmp/\nscratch/\n')
await writeFile(join(worktreePath, '.env.local'), 'SECRET=1\n')
await mkdir(join(worktreePath, '.anti-slop-plugin'))
await writeFile(join(worktreePath, '.anti-slop-plugin', 'rule.json'), '{}')
await mkdir(join(worktreePath, '.tmp'))
await writeFile(join(worktreePath, '.tmp', 'dump.json'), '{}')
await mkdir(join(worktreePath, 'local'))
await writeFile(join(worktreePath, 'local', 'notes.txt'), 'draft\n')
await mkdir(join(worktreePath, 'scratch'))
await writeFile(join(worktreePath, 'scratch', 'todo.md'), 'todo\n')
await expect(read()).resolves.toEqual({
count: 5,
samplePaths: ['.env.local', '.anti-slop-plugin/', '.tmp/'],
paths: ['.env.local', '.anti-slop-plugin/', '.tmp/', 'local/', 'scratch/'],
complete: true
})
})
it('reports a directory past its comparison budget as unchecked, not safe', async () => {
await mkdir(join(worktreePath, 'local'))
await mkdir(join(mainPath, 'local'))
@@ -57,6 +82,17 @@ describe('readWorktreeAtRiskLocalFiles (real git)', () => {
await writeFile(join(mainPath, 'local', `${index}.txt`), 'same\n')
}
await expect(read()).resolves.toEqual({ count: 0, samplePaths: [], complete: false })
await expect(read()).resolves.toEqual({
count: 0,
samplePaths: [],
paths: [],
complete: false
})
})
async function appendEntry(relativePath: string, content: string): Promise<void> {
await writeFile(join(worktreePath, relativePath), content, { flag: 'a' })
git(['add', relativePath], worktreePath)
git(['commit', '-qm', 'extend gitignore'], worktreePath)
}
})
@@ -25,6 +25,7 @@ const MAX_VISITED_ENTRIES = 1_000
const MAX_COMPARED_BYTES = 32 * 1024 * 1024
const MAX_COMPARED_FILE_BYTES = 4 * 1024 * 1024
const SAMPLE_PATH_LIMIT = 3
const MAX_RETURNED_PATHS = 200
// Dependency, build and cache output that a fresh checkout regenerates.
const REGENERABLE_DIRECTORY_NAMES: ReadonlySet<string> = new Set([
@@ -100,11 +101,7 @@ export async function readWorktreeAtRiskLocalFiles(args: {
// Git's own timer starts after admission, so queueing behind other git work cannot cut the listing short.
const listing = await listIgnoredPaths(args.worktreePath, args.gitOptions, deadlineMs)
if (args.mainCheckoutPath === null) {
return {
count: listing.paths.length,
samplePaths: pickNotablePaths(listing.paths),
complete: listing.complete
}
return summarizeAtRiskPaths(listing.paths, listing.complete)
}
const signal = abortSignalWithTimeout(parentSignal, deadlineMs)
// File reads cannot all take a signal; racing the deadline keeps a stalled mount from hanging the scan.
@@ -148,11 +145,7 @@ export async function readWorktreeAtRiskLocalFiles(args: {
if (parentSignal?.aborted) {
throw createAbortError()
}
return {
count: atRiskPaths.length,
samplePaths: pickNotablePaths(atRiskPaths),
complete: listing.complete && !unverified
}
return summarizeAtRiskPaths(atRiskPaths, listing.complete && !unverified)
}
async function listIgnoredPaths(
@@ -315,14 +308,21 @@ function hasBudgetLeft(budget: ComparisonBudget): boolean {
return budget.entries > 0 && !budget.signal.aborted
}
function pickNotablePaths(paths: readonly string[]): string[] {
function summarizeAtRiskPaths(
paths: readonly string[],
complete: boolean
): WorktreeAtRiskLocalFiles {
const rank = (relativePath: string): number => (/(^|\/)\.env[^/]*\/?$/.test(relativePath) ? 0 : 1)
return [...paths]
.sort(
(left, right) =>
rank(left) - rank(right) ||
left.split('/').length - right.split('/').length ||
left.localeCompare(right)
)
.slice(0, SAMPLE_PATH_LIMIT)
const sorted = [...paths].sort(
(left, right) =>
rank(left) - rank(right) ||
left.split('/').length - right.split('/').length ||
left.localeCompare(right)
)
return {
count: paths.length,
samplePaths: sorted.slice(0, SAMPLE_PATH_LIMIT),
paths: sorted.slice(0, MAX_RETURNED_PATHS),
complete
}
}
@@ -2,6 +2,7 @@ import { defineFixture } from '../../../../component-fixtures/component-fixture'
import type { Repo } from '../../../../../../shared/repository/repo-types'
import type { Worktree } from '../../../../../../shared/worktree/types'
import type { GitStatusEntry } from '../../../../../../shared/git/status/git-status-types'
import type { WorktreeAtRiskLocalFiles } from '../../../../../../shared/worktree/removal/at-risk-local-files'
import DeleteWorktreeDialog from './DeleteWorktreeDialog'
const repo: Repo = {
@@ -38,32 +39,110 @@ const dirtyEntries: GitStatusEntry[] = Array.from({ length: 13 }, (_, index) =>
area: index % 3 === 0 ? 'untracked' : 'unstaged'
}))
function dialogFixture(entries: GitStatusEntry[], interact?: (frame: HTMLElement) => void) {
const cleanLocalFiles: WorktreeAtRiskLocalFiles = {
count: 0,
samplePaths: [],
paths: [],
complete: true
}
const atRiskLocalFiles: WorktreeAtRiskLocalFiles = {
count: 5,
samplePaths: ['.anti-slop-plugin/', '.tmp/', 'tests/e2e/.cross-version-checkouts/'],
paths: [
'.anti-slop-plugin/',
'.tmp/',
'tests/e2e/.cross-version-checkouts/',
'.env.local',
'scratch/migration-dump.sql'
],
complete: true
}
const manyAtRiskLocalFiles: WorktreeAtRiskLocalFiles = {
count: 14,
samplePaths: ['.env.local', '.anti-slop-plugin/', '.tmp/'],
paths: [
'.env.local',
'.env.development.local',
'.anti-slop-plugin/',
'.tmp/',
'local/',
'scratch/migration-dump.sql',
'scratch/perf-trace.json',
'tests/e2e/.cross-version-checkouts/',
'tests/fixtures/.local-snapshots/',
'packages/desktop/.orca-local/session-override.json',
'packages/cli/.local-config.yaml',
'scripts/private/bench-results.csv',
'docs/drafts/notes.md',
'tools/sandbox/state.db'
],
complete: true
}
function dialogFixture(options: {
entries: GitStatusEntry[]
localFiles?: WorktreeAtRiskLocalFiles | 'pending'
heightClassName?: string
interact?: (frame: HTMLElement) => void
}) {
return defineFixture({
width: 640,
store: {
repos: [repo],
worktreesByRepo: { [repo.id]: [worktree] },
gitStatusByWorktree: { [worktree.id]: entries },
gitStatusByWorktree: { [worktree.id]: options.entries },
activeModal: 'delete-worktree',
modalData: { worktreeId: worktree.id }
},
setup: () => {
const localFiles = options.localFiles ?? cleanLocalFiles
window.api.git.atRiskLocalFiles = () =>
localFiles === 'pending' ? new Promise(() => {}) : Promise.resolve(localFiles)
},
// The dialog portals to <body>; reserve room so the centered modal fits the frame.
render: () => (
<div className="h-[440px] bg-background">
<div className={`${options.heightClassName ?? 'h-[440px]'} bg-background`}>
<DeleteWorktreeDialog />
</div>
),
interact
interact: options.interact
})
}
export const dirty = dialogFixture(dirtyEntries)
export const checking = dialogFixture({ entries: [], localFiles: 'pending' })
export const clean = dialogFixture([])
export const clean = dialogFixture({ entries: [], localFiles: cleanLocalFiles })
export const alwaysDeleteMenu = dialogFixture(dirtyEntries, () => {
document
.querySelector<HTMLButtonElement>('[aria-label="More delete options"]')
?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }))
export const ignoredFiles = dialogFixture({ entries: [], localFiles: atRiskLocalFiles })
export const ignoredFilesOpen = dialogFixture({
entries: [],
localFiles: atRiskLocalFiles,
heightClassName: 'h-[540px]',
interact: () => {
document.querySelector<HTMLButtonElement>('[aria-label*="Show ignored paths"]')?.click()
}
})
export const ignoredFilesScrolling = dialogFixture({
entries: [],
localFiles: manyAtRiskLocalFiles,
heightClassName: 'h-[580px]',
interact: () => {
document.querySelector<HTMLButtonElement>('[aria-label*="Show ignored paths"]')?.click()
}
})
export const dirty = dialogFixture({ entries: dirtyEntries, localFiles: atRiskLocalFiles })
export const alwaysDeleteMenu = dialogFixture({
entries: dirtyEntries,
localFiles: cleanLocalFiles,
interact: () => {
document
.querySelector<HTMLButtonElement>('[aria-label="More delete options"]')
?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }))
}
})
@@ -1,7 +1,7 @@
// @protected-copy
import type { JSX } from 'react'
import { AlertTriangle, ChevronRight } from 'lucide-react'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import { useTranslate } from '@/i18n/use-translate'
import { STATUS_COLORS } from '../../../../lib/source-control/paths/git-path-decoration'
import { STATUS_LABELS } from '../../../../../../shared/git/status/git-status-labels'
@@ -9,6 +9,7 @@ import type {
DeleteWorktreeChangeCheckState,
DeleteWorktreeDirtyChangePreview
} from './delete-worktree-dirty-change-counts'
import { DeleteWorktreeRelativePath } from './delete-worktree-relative-path'
export function DeleteWorktreeDirtyChangeHint({
changeCount,
@@ -49,13 +50,6 @@ export function DeleteWorktreeDirtyChangeHint({
'Uncommitted changes will be lost'
)
const warningLabel = (
<>
<AlertTriangle className="size-3 shrink-0" />
<span className="min-w-0 truncate font-medium">{label}</span>
</>
)
if (!preview?.files.length) {
const detailsLabel =
checkState === 'checking'
@@ -66,85 +60,68 @@ export function DeleteWorktreeDirtyChangeHint({
return (
<div className="mt-0.5 flex h-4 min-w-0 items-center">
<div className="flex w-fit max-w-full items-center gap-1.5 text-destructive">
{warningLabel}
<AlertTriangle className="size-3 shrink-0" />
<span className="min-w-0 truncate font-medium">{label}</span>
{detailsLabel && <span className="shrink-0 text-muted-foreground">· {detailsLabel}</span>}
</div>
</div>
)
}
const loadedPathsLabel = t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.loadedChangedPaths',
'Loaded changed paths'
)
return (
<div className="mt-0.5 flex h-4 min-w-0 items-center">
<Popover>
<PopoverTrigger asChild>
<button
type="button"
aria-label={`${label}: ${t('auto.components.sidebar.DeleteWorktreeDirtyChangeHint.showLoadedPaths', 'Show loaded paths')}`}
className="flex h-4 w-fit max-w-full cursor-pointer items-center gap-1.5 rounded-sm text-destructive hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
{warningLabel}
<ChevronRight className="size-3 shrink-0" />
</button>
</PopoverTrigger>
<PopoverContent
align="start"
side="bottom"
aria-label={t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.loadedChangedPaths',
'Loaded changed paths'
)}
className="w-80 max-w-[calc(100vw-2rem)]"
wheelScroll
<Collapsible className="mt-0.5 min-w-0">
<CollapsibleTrigger asChild>
<button
type="button"
aria-label={`${label}: ${t('auto.components.sidebar.DeleteWorktreeDirtyChangeHint.showLoadedPaths', 'Show loaded paths')}`}
className="group flex h-4 w-full min-w-0 cursor-pointer items-center gap-1.5 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
<div className="scrollbar-sleek max-h-[var(--radix-popover-content-available-height)] overflow-y-auto p-3 text-xs">
<p className="mb-1 font-medium">
{t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.loadedChangedPaths',
'Loaded changed paths'
)}
</p>
<p className="text-muted-foreground">
{t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.loadedPathsNotice',
'Loaded paths may be incomplete or out of date.'
)}
</p>
<div
role="region"
aria-label={t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.loadedChangedPaths',
'Loaded changed paths'
)}
tabIndex={0}
className="scrollbar-sleek mt-1 max-h-40 min-w-0 overflow-y-auto"
>
<ul className="min-w-0 space-y-0.5 font-mono">
{preview.files.map((file) => (
<li key={file.path} className="flex min-w-0 items-baseline gap-2">
<span
className="w-3 shrink-0 font-semibold"
style={{ color: STATUS_COLORS[file.status] }}
aria-label={file.status}
>
{STATUS_LABELS[file.status]}
</span>
<div className="min-w-0 break-all text-foreground">
{file.path}
{file.hasUnresolvedConflict ? (
<span className="ml-2 font-sans text-destructive">
{t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.unresolvedConflict',
'Unresolved conflict'
)}
</span>
) : null}
</div>
</li>
))}
</ul>
</div>
<AlertTriangle className="size-3 shrink-0 text-destructive" />
<span className="min-w-0 truncate font-medium text-destructive group-hover:underline">
{label}
</span>
<ChevronRight className="ml-auto size-3.5 shrink-0 text-muted-foreground transition-all duration-150 group-hover:text-foreground group-data-[state=open]:rotate-90 motion-reduce:transition-none" />
</button>
</CollapsibleTrigger>
<CollapsibleContent animation="height">
<div className="pt-1.5">
<div
role="region"
aria-label={loadedPathsLabel}
tabIndex={0}
className="scrollbar-sleek max-h-40 min-w-0 overflow-y-auto rounded-sm border border-border/60 bg-background/60 px-2.5 py-1.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
<ul className="min-w-0 space-y-1 font-mono text-xs">
{preview.files.map((file) => (
<li key={file.path} className="flex min-w-0 items-baseline gap-2">
<span
className="w-3 shrink-0 font-semibold"
style={{ color: STATUS_COLORS[file.status] }}
aria-label={file.status}
>
{STATUS_LABELS[file.status]}
</span>
<div className="min-w-0 wrap-anywhere text-foreground">
<DeleteWorktreeRelativePath path={file.path} />
{file.hasUnresolvedConflict ? (
<span className="ml-2 font-sans text-destructive">
{t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.unresolvedConflict',
'Unresolved conflict'
)}
</span>
) : null}
</div>
</li>
))}
</ul>
{preview.remainingPathCount > 0 ? (
<p className="mt-1 text-muted-foreground">
<p className="mt-1.5 border-t border-border/50 pt-1 text-2xs text-muted-foreground">
{t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.moreLoadedPaths',
'and {{count}} more loaded paths',
@@ -155,9 +132,15 @@ export function DeleteWorktreeDirtyChangeHint({
)}
</p>
) : null}
<p className="mt-1 text-2xs text-muted-foreground">
{t(
'auto.components.sidebar.DeleteWorktreeDirtyChangeHint.loadedPathsNotice',
'Loaded paths may be incomplete or out of date.'
)}
</p>
</div>
</PopoverContent>
</Popover>
</div>
</div>
</CollapsibleContent>
</Collapsible>
)
}
@@ -1,5 +1,6 @@
import { useState } from 'react'
import { defineFixture } from '../../../../component-fixtures/component-fixture'
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
import type { Worktree } from '../../../../../../shared/worktree/types'
import { DeleteWorktreeLineageNotice } from './DeleteWorktreeLineageNotice'
@@ -29,8 +30,25 @@ function LineageNotice({ initialPreserve = false, canPreserve = true }) {
return (
<DeleteWorktreeLineageNotice
descendants={[child]}
changeCheckStatesByWorktreeId={new Map([[child.id, 'complete']])}
dirtyChangeCountsByWorktreeId={new Map([[child.id, 3]])}
dirtyChangePreviewsByWorktreeId={new Map()}
atRiskLocalFilesByIdentity={
new Map([
[
getWorktreeHostIdentity(child),
{
status: 'complete',
files: {
count: 2,
samplePaths: ['.env.local', '.tmp/'],
paths: ['.env.local', '.tmp/'],
complete: true
}
}
]
])
}
preserveChildren={preserve}
canPreserveChildren={canPreserve}
disabled={false}
@@ -10,7 +10,7 @@ import type { Worktree } from '../../../../../../shared/worktree/types'
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
import { DeleteWorktreeDirtyChangeHint } from './DeleteWorktreeDirtyChangeHint'
import { DeleteWorktreeLocalFilesHint } from './DeleteWorktreeLocalFilesHint'
import type { WorktreeAtRiskLocalFiles } from '../../../../../../shared/worktree/removal/at-risk-local-files'
import type { DeleteWorktreeLocalFilesState } from './use-delete-worktree-at-risk-local-files'
import type {
DeleteWorktreeChangeCheckState,
DeleteWorktreeDirtyChangePreview
@@ -25,7 +25,7 @@ type DeleteWorktreeLineageNoticeProps = {
dirtyChangeCountsByWorktreeId: ReadonlyMap<string, number>
dirtyChangePreviewsByWorktreeId: ReadonlyMap<string, DeleteWorktreeDirtyChangePreview>
changeCheckStatesByWorktreeId?: ReadonlyMap<string, DeleteWorktreeChangeCheckState>
atRiskLocalFilesByIdentity?: ReadonlyMap<string, WorktreeAtRiskLocalFiles>
atRiskLocalFilesByIdentity?: ReadonlyMap<string, DeleteWorktreeLocalFilesState>
preserveChildren: boolean
canPreserveChildren: boolean
disabled: boolean
@@ -135,7 +135,7 @@ export function DeleteWorktreeLineageNotice({
)}
/>
<DeleteWorktreeLocalFilesHint
files={atRiskLocalFilesByIdentity?.get(getWorktreeHostIdentity(child))}
state={atRiskLocalFilesByIdentity?.get(getWorktreeHostIdentity(child))}
/>
</>
)}
@@ -0,0 +1,66 @@
import { defineFixture } from '../../../../component-fixtures/component-fixture'
import type { WorktreeAtRiskLocalFiles } from '../../../../../../shared/worktree/removal/at-risk-local-files'
import { DeleteWorktreeLocalFilesHint } from './DeleteWorktreeLocalFilesHint'
const ROW_WIDTH = 376
const atRiskFiles: WorktreeAtRiskLocalFiles = {
count: 6,
samplePaths: ['.env.local', '.anti-slop-plugin/', '.tmp/'],
paths: [
'.env.local',
'.anti-slop-plugin/',
'.tmp/',
'scratch/migration-dump.sql',
'tests/e2e/.cross-version-checkouts/',
'packages/desktop/.orca-local/session-override.json'
],
complete: true
}
export const checking = defineFixture({
width: ROW_WIDTH,
render: () => <DeleteWorktreeLocalFilesHint state={{ status: 'checking' }} />
})
export const clean = defineFixture({
width: ROW_WIDTH,
render: () => (
<DeleteWorktreeLocalFilesHint
state={{
status: 'complete',
files: { count: 0, samplePaths: [], paths: [], complete: true }
}}
/>
)
})
export const unsupported = defineFixture({
width: ROW_WIDTH,
render: () => <DeleteWorktreeLocalFilesHint state={{ status: 'unsupported' }} />
})
export const unchecked = defineFixture({
width: ROW_WIDTH,
render: () => (
<DeleteWorktreeLocalFilesHint
state={{
status: 'complete',
files: { count: 0, samplePaths: [], paths: [], complete: false }
}}
/>
)
})
export const atRisk = defineFixture({
width: ROW_WIDTH,
render: () => <DeleteWorktreeLocalFilesHint state={{ status: 'complete', files: atRiskFiles }} />
})
export const atRiskWithPathsOpen = defineFixture({
width: ROW_WIDTH,
render: () => <DeleteWorktreeLocalFilesHint state={{ status: 'complete', files: atRiskFiles }} />,
interact: (frame) => {
frame.querySelector('button')?.click()
}
})
@@ -1,31 +1,139 @@
// @protected-copy
import type { JSX } from 'react'
import { AlertTriangle } from 'lucide-react'
import { AlertTriangle, ChevronRight, File, Folder } from 'lucide-react'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import { useTranslate } from '@/i18n/use-translate'
import { formatAtRiskLocalFileNames } from '@/lib/workspace/display/at-risk-local-files-label'
import type { WorktreeAtRiskLocalFiles } from '../../../../../../shared/worktree/removal/at-risk-local-files'
import { hasWorktreeAtRiskLocalFiles } from '../../../../../../shared/worktree/removal/at-risk-local-files'
import { DeleteWorktreeRelativePath, isDirectoryDisplayPath } from './delete-worktree-relative-path'
import type { DeleteWorktreeLocalFilesState } from './use-delete-worktree-at-risk-local-files'
export function DeleteWorktreeLocalFilesHint({
files
state
}: {
files: WorktreeAtRiskLocalFiles | undefined
state: DeleteWorktreeLocalFilesState | undefined
}): JSX.Element | null {
const t = useTranslate()
if (!files) {
if (!state) {
return null
}
const names = formatAtRiskLocalFileNames(files, t)
const label = names
? t('components.workspace.delete.ignoredFilesLost', 'Ignored files will be lost: {{names}}', {
names
if (state.status !== 'complete' || !hasWorktreeAtRiskLocalFiles(state.files)) {
const statusLabel =
state.status === 'complete'
? t('components.workspace.delete.ignoredFiles.none', 'No ignored local files')
: state.status === 'unsupported'
? t('components.workspace.delete.ignoredFiles.unavailable', 'Ignored files not checked')
: t('components.workspace.delete.ignoredFiles.checking', 'Checking ignored files…')
return (
<div className="mt-0.5 flex h-4 min-w-0 items-center text-muted-foreground">
<span className="truncate">{statusLabel}</span>
</div>
)
}
const { files } = state
const listedPaths = files.paths ?? files.samplePaths
if (files.count === 0 || listedPaths.length === 0) {
const uncheckedLabel = t(
'components.workspace.delete.ignoredFilesUnchecked',
'Ignored files could not be fully checked'
)
return (
<div className="mt-0.5 flex h-4 min-w-0 items-center gap-1.5 text-destructive">
<AlertTriangle className="size-3 shrink-0" />
<span className="min-w-0 truncate font-medium">{uncheckedLabel}</span>
</div>
)
}
const countLabel = files.complete
? t('components.workspace.delete.ignoredFiles.lost', '{{count}} ignored files will be lost', {
count: files.count,
defaultValue_one: '{{count}} ignored file will be lost'
})
: t(
'components.workspace.delete.ignoredFilesUnchecked',
'Ignored files could not be fully checked'
'components.workspace.delete.ignoredFiles.lostIncomplete',
'{{count}}+ ignored files will be lost',
{ count: files.count }
)
const inlinePreview = files.samplePaths.join(', ')
const remainingPathCount = Math.max(0, files.count - listedPaths.length)
const listLabel = t(
'components.workspace.delete.ignoredFiles.listLabel',
'Ignored local files that will be lost'
)
return (
<div className="mt-0.5 flex h-4 min-w-0 items-center gap-1.5 text-destructive" title={label}>
<AlertTriangle className="size-3 shrink-0" />
<span className="min-w-0 truncate font-medium">{label}</span>
</div>
<Collapsible className="mt-0.5 min-w-0">
<CollapsibleTrigger asChild>
<button
type="button"
aria-label={`${countLabel}: ${t('components.workspace.delete.ignoredFiles.showPaths', 'Show ignored paths')}`}
className="group flex h-4 w-full min-w-0 cursor-pointer items-center gap-1.5 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
<AlertTriangle className="size-3 shrink-0 text-destructive" />
<span className="min-w-0 truncate font-medium text-destructive group-hover:underline">
{countLabel}
</span>
{inlinePreview ? (
<span className="flex min-w-0 shrink-[9999] items-center gap-1 text-muted-foreground group-data-[state=open]:hidden">
<span aria-hidden="true" className="shrink-0">
·
</span>
<span className="min-w-0 truncate font-mono text-2xs">{inlinePreview}</span>
</span>
) : null}
<ChevronRight className="ml-auto size-3.5 shrink-0 text-muted-foreground transition-all duration-150 group-hover:text-foreground group-data-[state=open]:rotate-90 motion-reduce:transition-none" />
</button>
</CollapsibleTrigger>
<CollapsibleContent animation="height">
<div className="pt-1.5">
<div
role="region"
aria-label={listLabel}
tabIndex={0}
className="scrollbar-sleek max-h-40 min-w-0 overflow-y-auto rounded-sm border border-border/60 bg-background/60 px-2.5 py-1.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
<ul className="min-w-0 space-y-1 font-mono text-xs">
{listedPaths.map((relativePath) => {
const EntryIcon = isDirectoryDisplayPath(relativePath) ? Folder : File
return (
<li key={relativePath} className="flex min-w-0 items-start gap-2">
<EntryIcon
aria-hidden="true"
className="mt-0.5 size-3.5 shrink-0 text-muted-foreground"
/>
<span className="min-w-0 flex-1 wrap-anywhere text-foreground">
<DeleteWorktreeRelativePath path={relativePath} />
</span>
</li>
)
})}
</ul>
{remainingPathCount > 0 ? (
<p className="mt-1.5 border-t border-border/50 pt-1 text-2xs text-muted-foreground">
{t(
'components.workspace.delete.ignoredFiles.morePaths',
'and {{count}} more ignored paths',
{
count: remainingPathCount,
defaultValue_one: 'and {{count}} more ignored path'
}
)}
</p>
) : null}
{!files.complete ? (
<p className="mt-1.5 border-t border-border/50 pt-1 text-2xs text-muted-foreground">
{t(
'components.workspace.delete.ignoredFiles.incompleteNotice',
'Check stopped early; more ignored files in this worktree may also be deleted.'
)}
</p>
) : null}
</div>
</div>
</CollapsibleContent>
</Collapsible>
)
}
@@ -5,7 +5,7 @@ import type { Worktree } from '../../../../../../shared/worktree/types'
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
import { DeleteWorktreeDirtyChangeHint } from './DeleteWorktreeDirtyChangeHint'
import { DeleteWorktreeLocalFilesHint } from './DeleteWorktreeLocalFilesHint'
import type { WorktreeAtRiskLocalFiles } from '../../../../../../shared/worktree/removal/at-risk-local-files'
import type { DeleteWorktreeLocalFilesState } from './use-delete-worktree-at-risk-local-files'
import type {
DeleteWorktreeChangeCheckState,
DeleteWorktreeDirtyChangePreview
@@ -66,7 +66,7 @@ export function DeleteWorktreeTargetPreview({
dirtyChangeCountsByWorktreeId: ReadonlyMap<string, number>
dirtyChangePreviewsByWorktreeId: ReadonlyMap<string, DeleteWorktreeDirtyChangePreview>
changeCheckStatesByWorktreeId?: ReadonlyMap<string, DeleteWorktreeChangeCheckState>
atRiskLocalFilesByIdentity?: ReadonlyMap<string, WorktreeAtRiskLocalFiles>
atRiskLocalFilesByIdentity?: ReadonlyMap<string, DeleteWorktreeLocalFilesState>
}): JSX.Element | null {
const t = useTranslate()
const targetIdPrefix = useId()
@@ -117,7 +117,7 @@ export function DeleteWorktreeTargetPreview({
)}
/>
<DeleteWorktreeLocalFilesHint
files={atRiskLocalFilesByIdentity?.get(getWorktreeHostIdentity(item))}
state={atRiskLocalFilesByIdentity?.get(getWorktreeHostIdentity(item))}
/>
{itemDeleteError ? (
<div className="mt-1 whitespace-pre-wrap break-all text-destructive">
@@ -176,7 +176,7 @@ export function DeleteWorktreeTargetPreview({
)}
/>
<DeleteWorktreeLocalFilesHint
files={atRiskLocalFilesByIdentity?.get(getWorktreeHostIdentity(worktree))}
state={atRiskLocalFilesByIdentity?.get(getWorktreeHostIdentity(worktree))}
/>
</div>
)
@@ -0,0 +1,55 @@
import { Fragment, type JSX } from 'react'
export function isDirectoryDisplayPath(rawPath: string): boolean {
return rawPath.endsWith('/') || rawPath.endsWith('\\')
}
type DirectorySegment = {
prefixKey: string
text: string
}
function splitDirectoryAndLeaf(rawPath: string): {
directorySegments: DirectorySegment[]
leafName: string
} {
const isDirectory = isDirectoryDisplayPath(rawPath)
const trimmed = isDirectory ? rawPath.slice(0, -1) : rawPath
const lastSlashIndex = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
if (lastSlashIndex < 0) {
return { directorySegments: [], leafName: rawPath }
}
const directoryPrefix = trimmed.slice(0, lastSlashIndex + 1)
// Keep trailing separators on each segment so long paths wrap at `/` before mid-filename.
const matches = [...directoryPrefix.matchAll(/[^/\\]+[/\\]+/g)]
const directorySegments =
matches.length > 0
? matches.map((match) => ({
prefixKey: directoryPrefix.slice(0, (match.index ?? 0) + match[0].length),
text: match[0]
}))
: [{ prefixKey: directoryPrefix, text: directoryPrefix }]
return {
directorySegments,
leafName: rawPath.slice(lastSlashIndex + 1)
}
}
export function DeleteWorktreeRelativePath({ path }: { path: string }): JSX.Element {
const { directorySegments, leafName } = splitDirectoryAndLeaf(path)
return (
<>
{directorySegments.length > 0 ? (
<span className="text-muted-foreground">
{directorySegments.map((segment) => (
<Fragment key={segment.prefixKey}>
{segment.text}
<wbr />
</Fragment>
))}
</span>
) : null}
{leafName}
</>
)
}
@@ -1,18 +1,24 @@
import { useEffect, useEffectEvent, useState } from 'react'
import { useEffect, useEffectEvent, useMemo, useState } from 'react'
import { useAppStore } from '@/store'
import { getRuntimeWorktreeAtRiskLocalFiles } from '@/runtime/source-control/git/runtime-git-status-client'
import { RuntimeRpcCallError } from '@/runtime/rpc/calls/runtime-rpc-result'
import type { Repo } from '../../../../../../shared/repository/repo-types'
import type { Worktree } from '../../../../../../shared/worktree/types'
import {
hasWorktreeAtRiskLocalFiles,
type WorktreeAtRiskLocalFiles
} from '../../../../../../shared/worktree/removal/at-risk-local-files'
import type { WorktreeAtRiskLocalFiles } from '../../../../../../shared/worktree/removal/at-risk-local-files'
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
import { isFolderWorkspaceDelete } from './delete-worktree-dialog-copy'
import { resolveDeleteTargetGitContext } from './use-delete-worktree-status-hydration'
/** Ignored files each delete target would lose, by host identity; hosts that can't tell stay absent. */
export type DeleteWorktreeLocalFilesState =
| { status: 'checking' }
| { status: 'unsupported' }
| { status: 'complete'; files: WorktreeAtRiskLocalFiles }
const CHECKING_STATE: DeleteWorktreeLocalFilesState = { status: 'checking' }
const UNSUPPORTED_STATE: DeleteWorktreeLocalFilesState = { status: 'unsupported' }
const EMPTY_STATES = new Map<string, DeleteWorktreeLocalFilesState>()
/** Per-target ignored-file check state, pre-seeded on render so async completion never resizes the dialog. */
export function useDeleteWorktreeAtRiskLocalFiles({
isOpen,
deleteTargets,
@@ -21,50 +27,72 @@ export function useDeleteWorktreeAtRiskLocalFiles({
isOpen: boolean
deleteTargets: readonly Worktree[]
repoMap: ReadonlyMap<string, Repo>
}): ReadonlyMap<string, WorktreeAtRiskLocalFiles> {
}): ReadonlyMap<string, DeleteWorktreeLocalFilesState> {
const repos = useAppStore((state) => state.repos)
const generation = isOpen ? deleteTargets.map(getWorktreeHostIdentity).join('\n') : ''
const [result, setResult] = useState<{
const generation = isOpen
? deleteTargets
.map((target) =>
JSON.stringify({
identity: getWorktreeHostIdentity(target),
isMainWorktree: target.isMainWorktree,
isFolderWorkspace: isFolderWorkspaceDelete(repoMap, target),
context: resolveDeleteTargetGitContext(target, repos)
})
)
.sort()
.join('\n')
: ''
const [settled, setSettled] = useState<{
generation: string
files: Map<string, WorktreeAtRiskLocalFiles>
}>({ generation: '', files: new Map() })
states: Map<string, DeleteWorktreeLocalFilesState>
}>({ generation: '', states: new Map() })
const startScans = useEffectEvent((signal: AbortSignal) => {
for (const target of deleteTargets) {
if (target.isMainWorktree || isFolderWorkspaceDelete(repoMap, target)) {
continue
}
const gitContext = resolveDeleteTargetGitContext(target, repos)
if (!gitContext) {
continue
}
const identity = getWorktreeHostIdentity(target)
const publish = (files: WorktreeAtRiskLocalFiles): void =>
setResult((current) => ({
const publish = (state: DeleteWorktreeLocalFilesState): void =>
setSettled((current) => ({
generation,
files: new Map(current.generation === generation ? current.files : []).set(
states: new Map(current.generation === generation ? current.states : []).set(
identity,
files
state
)
}))
const gitContext = resolveDeleteTargetGitContext(target, repos)
if (!gitContext) {
publish(UNSUPPORTED_STATE)
continue
}
void getRuntimeWorktreeAtRiskLocalFiles(gitContext, signal)
.then((files) => {
if (!signal.aborted && hasWorktreeAtRiskLocalFiles(files)) {
publish(files)
if (!signal.aborted) {
publish({ status: 'complete', files })
}
})
.catch((error: unknown) => {
// Older hosts lack the method and keep today's dialog; any other failure is an unchecked result.
if (signal.aborted) {
return
}
const unsupported =
error instanceof RuntimeRpcCallError && error.code === 'method_not_found'
if (!signal.aborted && !unsupported) {
publish({ count: 0, samplePaths: [], complete: false })
}
publish(
unsupported
? UNSUPPORTED_STATE
: {
status: 'complete',
files: { count: 0, samplePaths: [], paths: [], complete: false }
}
)
})
}
})
// Store updates re-render the dialog with new array identities; each scan walks files, so run once per target set.
useEffect(() => {
setSettled({ generation, states: new Map() })
if (!isOpen) {
return
}
@@ -75,7 +103,19 @@ export function useDeleteWorktreeAtRiskLocalFiles({
}
}, [generation, isOpen])
return result.generation === generation ? result.files : EMPTY_FILES
return useMemo(() => {
if (!isOpen) {
return EMPTY_STATES
}
const currentSettled = settled.generation === generation ? settled.states : undefined
const next = new Map<string, DeleteWorktreeLocalFilesState>()
for (const target of deleteTargets) {
if (target.isMainWorktree || isFolderWorkspaceDelete(repoMap, target)) {
continue
}
const identity = getWorktreeHostIdentity(target)
next.set(identity, currentSettled?.get(identity) ?? CHECKING_STATE)
}
return next
}, [deleteTargets, generation, isOpen, repoMap, settled])
}
const EMPTY_FILES = new Map<string, WorktreeAtRiskLocalFiles>()
+6
View File
@@ -2213,6 +2213,12 @@
}
},
"delete": {
"ignoredFiles": {
"lost_one": "{{count}} ignored file will be lost",
"lost_other": "{{count}} ignored files will be lost",
"morePaths_one": "and {{count}} more ignored path",
"morePaths_other": "and {{count}} more ignored paths"
},
"unsavedEdits": {
"blocked_one": "Save or close {{count}} unsaved file in {{name}} first",
"blocked_other": "Save or close {{count}} unsaved files in {{name}} first",
+14 -2
View File
@@ -22111,8 +22111,20 @@
"reopen": "Reopen",
"reopenFailed": "Some files couldn't be reopened. Open a workspace and try Reopen again."
},
"ignoredFilesLost": "Ignored files will be lost: {{names}}",
"ignoredFilesUnchecked": "Ignored files could not be fully checked"
"ignoredFilesUnchecked": "Ignored files could not be fully checked",
"ignoredFiles": {
"none": "No ignored local files",
"unavailable": "Ignored files not checked",
"checking": "Checking ignored files…",
"lost_one": "{{count}} ignored file will be lost",
"lost_other": "{{count}} ignored files will be lost",
"lostIncomplete": "{{count}}+ ignored files will be lost",
"showPaths": "Show ignored paths",
"morePaths_one": "and {{count}} more ignored path",
"morePaths_other": "and {{count}} more ignored paths",
"listLabel": "Ignored local files that will be lost",
"incompleteNotice": "Check stopped early; more ignored files in this worktree may also be deleted."
}
},
"atRiskLocalFiles": {
"namesWithCount": "{{names}} +{{value0}}",
-1
View File
@@ -20993,7 +20993,6 @@
"reopen": "再度開く",
"reopenFailed": "一部のファイルを再度開けませんでした。ワークスペースを開いて、もう一度「再度開く」を試してください。"
},
"ignoredFilesLost": "無視されたファイルは失われます: {{names}}",
"ignoredFilesUnchecked": "無視されたファイルを完全には確認できませんでした"
},
"atRiskLocalFiles": {
-1
View File
@@ -21063,7 +21063,6 @@
"reopen": "重新打开",
"reopenFailed": "部分文件无法重新打开。请打开工作区,然后再次尝试“重新打开”"
},
"ignoredFilesLost": "Git 忽略的文件将丢失:{{names}}",
"ignoredFilesUnchecked": "无法完整检查 Git 忽略的文件"
},
"atRiskLocalFiles": {
@@ -837,6 +837,16 @@
"components.workspace.delete.changes.permanentLoss",
"components.workspace.delete.changes.unavailable",
"components.workspace.delete.changes.unavailableDetails",
"components.workspace.delete.ignoredFiles.checking",
"components.workspace.delete.ignoredFiles.incompleteNotice",
"components.workspace.delete.ignoredFiles.listLabel",
"components.workspace.delete.ignoredFiles.lost",
"components.workspace.delete.ignoredFiles.lostIncomplete",
"components.workspace.delete.ignoredFiles.morePaths",
"components.workspace.delete.ignoredFiles.none",
"components.workspace.delete.ignoredFiles.showPaths",
"components.workspace.delete.ignoredFiles.unavailable",
"components.workspace.delete.ignoredFilesUnchecked",
"components.workspace.delete.unsavedEdits.blocked",
"components.workspace.delete.unsavedEdits.discarded",
"components.workspace.delete.unsavedEdits.moreFiles",
@@ -4,6 +4,8 @@ export type WorktreeAtRiskLocalFiles = {
count: number
/** A few notable worktree-relative paths, `.env*` first; directories end in `/`. */
samplePaths: string[]
/** Sorted at-risk worktree-relative paths (up to path cap); absent on older hosts or compact summaries. */
paths?: string[]
/** False when a time or size cap or a failure cut the check short, so more files may be at risk. */
complete: boolean
}