Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
refactor(file-manager): polish API, accessibility, and naming
Sergey Kozyrenkof35d2cc0ae1b
diff --git a/frontend/src/components/file-manager/file-manager-bulk-actions-bar.tsx b/frontend/src/components/file-manager/file-manager-bulk-actions-bar.tsxnew file mode 100644index 00000000..840ec46f--- /dev/null+++ b/frontend/src/components/file-manager/file-manager-bulk-actions-bar.tsx@@ -0,0 +1,101 @@+import { Trash2 } from 'lucide-react';+import { useCallback, useState } from 'react';++import ConfirmationDialog from '@/components/shared/confirmation-dialog';+import { Button } from '@/components/ui/button';++import type { FileManagerLabels, FileNode } from './file-manager-types';++import { dedupeOverlappingPaths, pluralizeItemsEnglish } from './file-manager-utils';++interface FileManagerBulkActionsBarProps {+ files: FileNode[];+ labels: FileManagerLabels;+ onBulkDelete?: (files: FileNode[]) => Promise<void> | void;+ onClearSelection: () => void;+ onSelectionChange: (paths: Set<string>) => void;+ selectedPaths: Set<string>;+}++/**+ * Footer that appears when at least one row is selected. Hosts the cancel/delete+ * controls and owns the bulk-delete confirmation dialog state, so the parent doesn't+ * have to coordinate it.+ */+export const FileManagerBulkActionsBar = ({+ files,+ labels,+ onBulkDelete,+ onClearSelection,+ onSelectionChange,+ selectedPaths,+}: FileManagerBulkActionsBarProps) => {+ const [isConfirmOpen, setIsConfirmOpen] = useState(false);++ const handleConfirm = useCallback(async () => {+ if (!onBulkDelete) {+ return;+ }++ const dedupedPaths = new Set(dedupeOverlappingPaths(selectedPaths));+ const filesToDelete = files.filter((file) => dedupedPaths.has(file.path));++ await onBulkDelete(filesToDelete);+ onSelectionChange(new Set());+ }, [files, onBulkDelete, onSelectionChange, selectedPaths]);++ const handleOpenChange = useCallback((isOpen: boolean) => {+ if (!isOpen) {+ setIsConfirmOpen(false);+ }+ }, []);++ if (selectedPaths.size === 0) {+ return null;+ }++ const pluralize = labels.pluralizeItems ?? pluralizeItemsEnglish;+ const countLabel = pluralize(selectedPaths.size);+ const selectedText = labels.selectedLabel?.(selectedPaths.size) ?? `${selectedPaths.size} selected`;+ const cancelText = labels.bulkCancel ?? 'Cancel';+ const confirmText = labels.bulkConfirm ?? 'Delete';+ const titleText = labels.bulkTitle?.(countLabel) ?? `Delete ${countLabel}`;+ const descriptionText =+ labels.bulkDescription?.(countLabel) ?? `This will delete ${countLabel}. This action cannot be undone.`;++ return (+ <>+ <div className="bg-background flex items-center justify-between gap-2 border-t px-3 py-2">+ <span className="text-muted-foreground text-sm">{selectedText}</span>+ <div className="flex items-center gap-2">+ <Button+ onClick={onClearSelection}+ size="sm"+ variant="ghost"+ >+ {cancelText}+ </Button>+ {onBulkDelete && (+ <Button+ onClick={() => setIsConfirmOpen(true)}+ size="sm"+ variant="destructive"+ >+ <Trash2 className="size-4" />+ {confirmText}+ </Button>+ )}+ </div>+ </div>++ <ConfirmationDialog+ confirmText={confirmText}+ description={descriptionText}+ handleConfirm={handleConfirm}+ handleOpenChange={handleOpenChange}+ isOpen={isConfirmOpen}+ title={titleText}+ />+ </>+ );+};diff --git a/frontend/src/components/file-manager/file-manager-row.tsx b/frontend/src/components/file-manager/file-manager-row.tsxindex 2666c214..926a1cc9 100644--- a/frontend/src/components/file-manager/file-manager-row.tsx+++ b/frontend/src/components/file-manager/file-manager-row.tsx@@ -23,54 +23,67 @@ import type { FileManagerAction, FileManagerInternalNode } from './file-manager-import { FileManagerHighlightedName } from './file-manager-highlighted-name';import { getFileTypeIcon } from './file-manager-icons';-import { formatFileSize, formatModified } from './file-manager-utils';+import { formatModified as defaultFormatModified, formatFileSize } from './file-manager-utils';-/** Marker on every interactive child of the row that should NOT bubble into a row click. */+/**+ * Marker on every interactive child of the row that should NOT bubble into a row click.+ * Detected via `closest()` in the row's click handler — descendants don't need to call+ * `event.stopPropagation()` themselves.+ */const SKIP_ROW_CLICK_ATTR = 'data-fm-skip-row-click';+const skipRowClickProps = { [SKIP_ROW_CLICK_ATTR]: '' };interface FileManagerRowProps {- actions: FileManagerAction[];+ actions: readonly FileManagerAction[];activeRowPath: null | string;- depth: number;file: FileManagerInternalNode;+ formatModified?: (modifiedAt: Date | string | undefined) => string;gridTemplate: string;hasActions: boolean;+ isCheckboxVisible: boolean;isExpanded: boolean;+ isModifiedVisible: boolean;isSelected: boolean;+ isSizeVisible: boolean;onClick: (event: ReactMouseEvent, path: string) => void;onFocusRow: (path: string) => void;onToggleCheckbox: (path: string) => void;onToggleExpand: (path: string, wasExpanded: boolean) => void;+ /** 1-based position of the row inside its parent's child list (for `aria-posinset`). */+ posInSet: number;searchQuery?: string;- showCheckbox: boolean;- showModified: boolean;- showSize: boolean;+ /** Total number of siblings the row is part of (for `aria-setsize`). */+ setSize: number;}/** Returns `true` when the click originated from an element opted-out of row activation. */const isClickInsideSkipZone = (target: EventTarget | null): boolean =>target instanceof HTMLElement && !!target.closest(`[${SKIP_ROW_CLICK_ATTR}]`);-const buildVisibleActions = (actions: FileManagerAction[], file: FileManagerInternalNode): FileManagerAction[] =>- actions.filter((action) => action.appliesToDirs || !file.isDir);+const buildVisibleActions = (+ actions: readonly FileManagerAction[],+ file: FileManagerInternalNode,+): FileManagerAction[] => actions.filter((action) => action.appliesToDirs || !file.isDir);const FileManagerRowImpl = ({actions,activeRowPath,- depth,file,+ formatModified = defaultFormatModified,gridTemplate,hasActions,+ isCheckboxVisible,isExpanded,+ isModifiedVisible,isSelected,+ isSizeVisible,onClick,onFocusRow,onToggleCheckbox,onToggleExpand,+ posInSet,searchQuery,- showCheckbox,- showModified,- showSize,+ setSize,}: FileManagerRowProps) => {const { icon: Icon, tone } = useMemo(() =>@@ -100,8 +113,7 @@ const FileManagerRowImpl = ({) => {const ActionIcon = action.icon;const itemClassName = cn(- action.variant === 'destructive' &&- 'text-destructive focus:bg-destructive/10 focus:text-destructive',+ action.variant === 'destructive' && 'text-destructive focus:bg-destructive/10 focus:text-destructive',);if (action.getHref) {@@ -134,17 +146,17 @@ const FileManagerRowImpl = ({);};- const renderActionItems = (kind: 'context' | 'dropdown'): ReactNode[] => {- const Item = kind === 'context' ? ContextMenuItem : DropdownMenuItem;- const Sep = kind === 'context' ? ContextMenuSeparator : DropdownMenuSeparator;+ const renderActionItems = (menuKind: 'context' | 'dropdown'): ReactNode[] => {+ const MenuItem = menuKind === 'context' ? ContextMenuItem : DropdownMenuItem;+ const MenuSeparator = menuKind === 'context' ? ContextMenuSeparator : DropdownMenuSeparator;const items: ReactNode[] = [];for (const action of visibleActions) {if (action.separatorBefore && items.length > 0) {- items.push(<Sep key={`sep-${action.id}`} />);+ items.push(<MenuSeparator key={`separator-${action.id}`} />);}- items.push(renderActionItem(Item, action));+ items.push(renderActionItem(MenuItem, action));}return items;@@ -155,17 +167,20 @@ const FileManagerRowImpl = ({const isActiveRow = activeRowPath === file.path;const rowStyle = {- '--fm-depth': depth,+ '--fm-depth': file.depth,gridTemplateColumns: gridTemplate,} as CSSProperties & Record<'--fm-depth', number>;const row = (<divaria-expanded={file.isDir ? isExpanded : undefined}+ aria-level={file.depth + 1}+ aria-posinset={posInSet}aria-selected={isSelected}+ aria-setsize={setSize}className={cn('group hover:bg-muted/50 grid cursor-pointer items-center gap-3 px-3 py-1.5 transition-colors outline-none',- 'focus-visible:bg-muted/70 focus-visible:ring-1 focus-visible:ring-ring',+ 'focus-visible:bg-muted/70 focus-visible:ring-ring focus-visible:ring-1',isSelected && 'bg-muted',)}data-path={file.path}@@ -175,16 +190,15 @@ const FileManagerRowImpl = ({style={rowStyle}tabIndex={isActiveRow ? 0 : -1}>- {showCheckbox ? (+ {isCheckboxVisible ? (<spanclassName="flex items-center"- {...{ [SKIP_ROW_CLICK_ATTR]: '' }}+ {...skipRowClickProps}><Checkboxaria-label={`Select ${file.name}`}checked={isSelected}onCheckedChange={() => onToggleCheckbox(file.path)}- onClick={(event) => event.stopPropagation()}/></span>) : (@@ -194,18 +208,13 @@ const FileManagerRowImpl = ({/>)}- <div- className="flex min-w-0 items-center gap-1.5 pl-[calc(var(--fm-depth)*16px)]"- >+ <div className="flex min-w-0 items-center gap-1.5 pl-[calc(var(--fm-depth)*16px)]">{file.isDir ? (<spanaria-hidden="true"className="text-muted-foreground hover:bg-muted -mx-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded transition-colors"- onClick={(event) => {- event.stopPropagation();- onToggleExpand(file.path, isExpanded);- }}- {...{ [SKIP_ROW_CLICK_ATTR]: '' }}+ onClick={() => onToggleExpand(file.path, isExpanded)}+ {...skipRowClickProps}><ChevronRight className={cn('size-3.5 transition-transform', isExpanded && 'rotate-90')} /></span>@@ -223,27 +232,26 @@ const FileManagerRowImpl = ({/></div>- {showSize && (+ {isSizeVisible && (<span className="text-muted-foreground/80 shrink-0 text-xs tabular-nums">{!file.isDir ? formatFileSize(file.size) : ''}</span>)}- {showModified && (+ {isModifiedVisible && (<span className="text-muted-foreground/80 shrink-0 text-xs tabular-nums">{formatModified(file.modifiedAt)}</span>)}{hasActions && (- <span {...{ [SKIP_ROW_CLICK_ATTR]: '' }}>+ <span {...skipRowClickProps}>{dropdownItems.length > 0 ? (<DropdownMenu><DropdownMenuTrigger asChild><Buttonaria-label="Row actions"className="opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"- onClick={(event) => event.stopPropagation()}size="icon-xs"variant="ghost">diff --git a/frontend/src/components/file-manager/file-manager-skeleton.tsx b/frontend/src/components/file-manager/file-manager-skeleton.tsxindex b74d5e14..718f6f7d 100644--- a/frontend/src/components/file-manager/file-manager-skeleton.tsx+++ b/frontend/src/components/file-manager/file-manager-skeleton.tsx@@ -22,10 +22,10 @@ export const FileManagerSkeleton = () => (<Skeleton className="size-4 shrink-0" /><Skeleton className="h-4 w-20" /></div>- {NESTED_NAME_WIDTHS.map((width, i) => (+ {NESTED_NAME_WIDTHS.map((width, index) => (<divclassName="flex items-center gap-3 px-3 py-1.5 pl-9"- key={`n-${i}`}+ key={`nested-${index}`}><Skeleton className="size-4 shrink-0 rounded-sm" /><Skeleton className="size-4 shrink-0" />@@ -34,10 +34,10 @@ export const FileManagerSkeleton = () => (<Skeleton className="h-3 w-16" /></div>))}- {ROOT_NAME_WIDTHS.map((width, i) => (+ {ROOT_NAME_WIDTHS.map((width, index) => (<divclassName="flex items-center gap-3 px-3 py-1.5"- key={`r-${i}`}+ key={`root-${index}`}><Skeleton className="size-4 shrink-0 rounded-sm" /><Skeleton className="size-3.5 shrink-0" />diff --git a/frontend/src/components/file-manager/file-manager-tree-node.tsx b/frontend/src/components/file-manager/file-manager-tree-node.tsxnew file mode 100644index 00000000..34de3fde--- /dev/null+++ b/frontend/src/components/file-manager/file-manager-tree-node.tsx@@ -0,0 +1,108 @@+import { Fragment, type MouseEvent as ReactMouseEvent } from 'react';++import type { FileManagerAction, FileManagerInternalNode } from './file-manager-types';++import { FileManagerRow } from './file-manager-row';++interface FileManagerTreeNodeProps {+ actions: readonly FileManagerAction[];+ activeRowPath: null | string;+ expandedPaths: Set<string>;+ formatModified?: (modifiedAt: Date | string | undefined) => string;+ gridTemplate: string;+ hasActions: boolean;+ isCheckboxVisible: boolean;+ isModifiedVisible: boolean;+ isSizeVisible: boolean;+ node: FileManagerInternalNode;+ onClick: (event: ReactMouseEvent, path: string) => void;+ onFocusRow: (path: string) => void;+ onToggleCheckbox: (path: string) => void;+ onToggleExpand: (path: string, wasExpanded: boolean) => void;+ /** 1-based position of the node inside its parent's child list (for `aria-posinset`). */+ posInSet: number;+ searchQuery?: string;+ selectedPaths: Set<string>;+ /** Total number of siblings the node is part of (for `aria-setsize`). */+ setSize: number;+}++/**+ * Recursive tree node renderer. The component itself is not memoized — `FileManagerRow`+ * is, which is where per-row reconciliation savings actually matter. Extracting the+ * recursion into a component (instead of an inline `renderNode` function) keeps+ * `FileManager` lean and gives React DevTools a real boundary to inspect.+ */+export const FileManagerTreeNode = ({+ actions,+ activeRowPath,+ expandedPaths,+ formatModified,+ gridTemplate,+ hasActions,+ isCheckboxVisible,+ isModifiedVisible,+ isSizeVisible,+ node,+ onClick,+ onFocusRow,+ onToggleCheckbox,+ onToggleExpand,+ posInSet,+ searchQuery,+ selectedPaths,+ setSize,+}: FileManagerTreeNodeProps) => {+ const isExpanded = expandedPaths.has(node.path);+ const isSelected = selectedPaths.has(node.path);+ const renderChildren = node.isDir && isExpanded && node.children.length > 0;++ return (+ <Fragment>+ <FileManagerRow+ actions={actions}+ activeRowPath={activeRowPath}+ file={node}+ formatModified={formatModified}+ gridTemplate={gridTemplate}+ hasActions={hasActions}+ isCheckboxVisible={isCheckboxVisible && !node.isGroupRoot}+ isExpanded={isExpanded}+ isModifiedVisible={isModifiedVisible}+ isSelected={isSelected}+ isSizeVisible={isSizeVisible}+ onClick={onClick}+ onFocusRow={onFocusRow}+ onToggleCheckbox={onToggleCheckbox}+ onToggleExpand={onToggleExpand}+ posInSet={posInSet}+ searchQuery={searchQuery}+ setSize={setSize}+ />+ {renderChildren &&+ node.children.map((child, index) => (+ <FileManagerTreeNode+ actions={actions}+ activeRowPath={activeRowPath}+ expandedPaths={expandedPaths}+ formatModified={formatModified}+ gridTemplate={gridTemplate}+ hasActions={hasActions}+ isCheckboxVisible={isCheckboxVisible}+ isModifiedVisible={isModifiedVisible}+ isSizeVisible={isSizeVisible}+ key={child.id}+ node={child}+ onClick={onClick}+ onFocusRow={onFocusRow}+ onToggleCheckbox={onToggleCheckbox}+ onToggleExpand={onToggleExpand}+ posInSet={index + 1}+ searchQuery={searchQuery}+ selectedPaths={selectedPaths}+ setSize={node.children.length}+ />+ ))}+ </Fragment>+ );+};diff --git a/frontend/src/components/file-manager/file-manager-types.ts b/frontend/src/components/file-manager/file-manager-types.tsindex 79940c40..ef30a772 100644--- a/frontend/src/components/file-manager/file-manager-types.ts+++ b/frontend/src/components/file-manager/file-manager-types.ts@@ -25,6 +25,12 @@ export interface FileManagerAction {variant?: 'default' | 'destructive';}+/** Optional column toggles. Both columns default to visible. */+export interface FileManagerColumnsConfig {+ isModifiedVisible?: boolean;+ isSizeVisible?: boolean;+}+export interface FileManagerInternalNode extends FileNode {children: FileManagerInternalNode[];depth: number;@@ -32,14 +38,48 @@ export interface FileManagerInternalNode extends FileNode {isGroupRoot?: boolean;}+/**+ * All user-facing strings. Pass to `FileManager` via the `labels` prop to localize.+ * Every field is optional; defaults are English.+ */+export interface FileManagerLabels {+ /** Cancel button in the bulk-actions bar. */+ bulkCancel?: string;+ /** Confirm button in the bulk-delete dialog. */+ bulkConfirm?: string;+ /** Description of the bulk-delete dialog. Receives the already-pluralized count label. */+ bulkDescription?: (countLabel: string) => string;+ /** Title of the bulk-delete dialog. Receives the already-pluralized count label. */+ bulkTitle?: (countLabel: string) => string;+ columnModified?: string;+ columnName?: string;+ columnSize?: string;+ /**+ * Custom formatter for the "Modified" column. Receives the raw `modifiedAt`+ * and must return a display string (or empty string for no value). When omitted,+ * the default English relative formatter is used.+ */+ formatModified?: (modifiedAt: Date | string | undefined) => string;+ /** Pluralized "N item" / "N items" used for the dialog title and description. */+ pluralizeItems?: (count: number) => string;+ /** aria-label for the header "select all" checkbox. */+ selectAllAriaLabel?: string;+ /** Label rendered in the bulk bar, e.g. "3 selected". */+ selectedLabel?: (count: number) => string;+}+export interface FileManagerProps {/** Single, ordered list of available row actions (built-in helpers live in `file-manager-actions`). */- actions?: FileManagerAction[];+ actions?: readonly FileManagerAction[];className?: string;+ /** Per-column visibility flags. Defaults: `{ isSizeVisible: true, isModifiedVisible: true }`. */+ columns?: FileManagerColumnsConfig;/** Empty state node (rendered when files.length === 0 and not loading). */emptyState?: ReactNode;files: FileNode[];isLoading?: boolean;+ /** Localizable user-facing strings. */+ labels?: FileManagerLabels;/*** Callback invoked when bulk delete is confirmed. The list is already deduped:* if both a directory and one of its descendants were selected, only the directory is included.@@ -47,12 +87,8 @@ export interface FileManagerProps {onBulkDelete?: (files: FileNode[]) => Promise<void> | void;/** Synthetic top-level groups (e.g. Uploads / Container). When omitted, root is flat. */rootGroups?: FileManagerRootGroup[];- /** Empty state node rendered when `searchQuery` is set but yields no results. */- searchEmptyState?: ReactNode;- /** When set, the tree is filtered to nodes matching the query (and their ancestors), and matches are highlighted. */- searchQuery?: string;- showModifiedColumn?: boolean;- showSizeColumn?: boolean;+ /** Search query and matching empty state. Provide `query` to enable filtering. */+ search?: FileManagerSearchConfig;}export interface FileManagerRootGroup {@@ -65,6 +101,14 @@ export interface FileManagerRootGroup {pathPrefix: string;}+/** Search-related props, grouped because `query` and `emptyState` always travel together. */+export interface FileManagerSearchConfig {+ /** Empty state node rendered when `query` is set but yields no results. */+ emptyState?: ReactNode;+ /** When set, the tree is filtered to nodes matching the query (and their ancestors), and matches are highlighted. */+ query?: string;+}+export interface FileNode {id: string;isDir: boolean;diff --git a/frontend/src/components/file-manager/file-manager-utils.test.ts b/frontend/src/components/file-manager/file-manager-utils.test.tsindex 7123a1cd..79cb1d4c 100644--- a/frontend/src/components/file-manager/file-manager-utils.test.ts+++ b/frontend/src/components/file-manager/file-manager-utils.test.ts@@ -5,7 +5,9 @@ import type { FileManagerInternalNode, FileManagerRootGroup, FileNode } from './import {buildFileManagerGridTemplate,buildFileManagerTree,+ clamp,collectAllFilePaths,+ collectAllNodePaths,collectDirectoryPaths,collectVisibleFlat,dedupeOverlappingPaths,@@ -13,8 +15,11 @@ import {findNodeByPath,formatFileSize,formatModified,+ getCheckboxState,normalizeRootGroups,+ pluralizeItemsEnglish,resolveSelectionModifier,+ walkTree,} from './file-manager-utils';const file = (path: string, overrides: Partial<FileNode> = {}): FileNode => ({@@ -25,8 +30,7 @@ const file = (path: string, overrides: Partial<FileNode> = {}): FileNode => ({...overrides,});-const dir = (path: string, overrides: Partial<FileNode> = {}): FileNode =>- file(path, { isDir: true, ...overrides });+const dir = (path: string, overrides: Partial<FileNode> = {}): FileNode => file(path, { isDir: true, ...overrides });describe('formatFileSize', () => {it('returns empty string when size is missing', () => {@@ -95,9 +99,7 @@ describe('formatModified', () => {describe('normalizeRootGroups', () => {it('returns input reference when nothing needs trimming', () => {- const groups: FileManagerRootGroup[] = [- { id: 'a', label: 'A', pathPrefix: 'uploads' },- ];+ const groups: FileManagerRootGroup[] = [{ id: 'a', label: 'A', pathPrefix: 'uploads' }];expect(normalizeRootGroups(groups)).toBe(groups);});@@ -110,7 +112,7 @@ describe('normalizeRootGroups', () => {const normalized = normalizeRootGroups(groups);expect(normalized).not.toBe(groups);- expect(normalized?.map((g) => g.pathPrefix)).toEqual(['uploads', 'container']);+ expect(normalized?.map((group) => group.pathPrefix)).toEqual(['uploads', 'container']);});it('passes through empty/undefined', () => {@@ -123,8 +125,8 @@ describe('buildFileManagerTree', () => {it('builds a flat tree without groups', () => {const tree = buildFileManagerTree([file('a.txt'), file('b.txt')]);- expect(tree.map((n) => n.path)).toEqual(['a.txt', 'b.txt']);- expect(tree.every((n) => !n.isGroupRoot)).toBe(true);+ expect(tree.map((node) => node.path)).toEqual(['a.txt', 'b.txt']);+ expect(tree.every((node) => !node.isGroupRoot)).toBe(true);});it('creates intermediate folders for nested files', () => {@@ -149,7 +151,7 @@ describe('buildFileManagerTree', () => {expect(tree).toHaveLength(2);expect(tree[0]!.isGroupRoot).toBe(true);- expect(tree[0]!.children.map((c) => c.path)).toEqual(['uploads/a.txt']);+ expect(tree[0]!.children.map((child) => child.path)).toEqual(['uploads/a.txt']);expect(tree[1]!.children[0]!.path).toBe('container/sub');expect(tree[1]!.children[0]!.children[0]!.path).toBe('container/sub/b.txt');});@@ -177,10 +179,7 @@ describe('buildFileManagerTree', () => {});it('skips files outside any defined group', () => {- const tree = buildFileManagerTree(- [file('orphan.txt')],- [{ id: 'u', label: 'Uploads', pathPrefix: 'uploads' }],- );+ const tree = buildFileManagerTree([file('orphan.txt')], [{ id: 'u', label: 'Uploads', pathPrefix: 'uploads' }]);expect(tree[0]!.children).toEqual([]);});@@ -233,13 +232,13 @@ describe('filterFileManagerTree', () => {expect(filtered).toHaveLength(1);expect(filtered[0]!.path).toBe('foo');- expect(filtered[0]!.children.map((c) => c.path)).toEqual(['foo/bar.txt']);+ expect(filtered[0]!.children.map((child) => child.path)).toEqual(['foo/bar.txt']);});it('keeps all descendants of a matched directory', () => {const filtered = filterFileManagerTree(tree, 'foo');- expect(filtered[0]!.children.map((c) => c.path).sort()).toEqual(['foo/bar.txt', 'foo/baz.md']);+ expect(filtered[0]!.children.map((child) => child.path).sort()).toEqual(['foo/bar.txt', 'foo/baz.md']);});it('matches case-insensitively against name and path', () => {@@ -320,3 +319,77 @@ describe('dedupeOverlappingPaths', () => {expect(dedupeOverlappingPaths(['foo', 'foobar']).sort()).toEqual(['foo', 'foobar']);});});++describe('walkTree', () => {+ const tree = buildFileManagerTree([file('a/b/c.txt'), file('a/d.txt'), file('e.txt')]);++ it('walks every node by default', () => {+ expect(walkTree(tree).sort()).toEqual(['a', 'a/b', 'a/b/c.txt', 'a/d.txt', 'e.txt'].sort());+ });++ it('stops descending when `descend` returns false', () => {+ expect(walkTree(tree, { descend: (node) => !(node.path === 'a/b') }).sort()).toEqual(+ ['a', 'a/b', 'a/d.txt', 'e.txt'].sort(),+ );+ });++ it('skips nodes when `include` returns false', () => {+ expect(walkTree(tree, { include: (node) => !node.isDir }).sort()).toEqual(+ ['a/b/c.txt', 'a/d.txt', 'e.txt'].sort(),+ );+ });++ it('powers all collect* helpers consistently', () => {+ expect(collectAllFilePaths(tree).sort()).toEqual(['a/b/c.txt', 'a/d.txt', 'e.txt']);+ expect(collectAllNodePaths(tree).sort()).toEqual(['a', 'a/b', 'a/b/c.txt', 'a/d.txt', 'e.txt'].sort());+ expect(collectDirectoryPaths(tree).sort()).toEqual(['a', 'a/b']);+ });+});++describe('clamp', () => {+ it('returns value when in range', () => {+ expect(clamp(0, 5, 10)).toBe(5);+ });++ it('clamps to min', () => {+ expect(clamp(0, -3, 10)).toBe(0);+ });++ it('clamps to max', () => {+ expect(clamp(0, 99, 10)).toBe(10);+ });++ it('returns min when min > max (degenerate input)', () => {+ // `Math.min(value, max)` runs first, then `Math.max(min, ...)` wins.+ expect(clamp(10, 5, 0)).toBe(10);+ });+});++describe('getCheckboxState', () => {+ it('returns true when all selected', () => {+ expect(getCheckboxState(true, false)).toBe(true);+ });++ it('returns indeterminate when some but not all selected', () => {+ expect(getCheckboxState(false, true)).toBe('indeterminate');+ });++ it('returns false when nothing selected', () => {+ expect(getCheckboxState(false, false)).toBe(false);+ });++ it('prefers all-selected over some-selected if both somehow set', () => {+ expect(getCheckboxState(true, true)).toBe(true);+ });+});++describe('pluralizeItemsEnglish', () => {+ it('uses singular for 1', () => {+ expect(pluralizeItemsEnglish(1)).toBe('1 item');+ });++ it('uses plural for 0 and >1', () => {+ expect(pluralizeItemsEnglish(0)).toBe('0 items');+ expect(pluralizeItemsEnglish(5)).toBe('5 items');+ });+});diff --git a/frontend/src/components/file-manager/file-manager-utils.ts b/frontend/src/components/file-manager/file-manager-utils.tsindex 3cdb371e..2849a412 100644--- a/frontend/src/components/file-manager/file-manager-utils.ts+++ b/frontend/src/components/file-manager/file-manager-utils.ts@@ -158,14 +158,14 @@ export const buildFileManagerTree = (baseDepth = 0;}- for (let i = startIndex; i < segments.length - 1; i += 1) {- const folderName = segments[i] ?? '';- const folderPath = segments.slice(0, i + 1).join('/');+ for (let index = startIndex; index < segments.length - 1; index += 1) {+ const folderName = segments[index] ?? '';+ const folderPath = segments.slice(0, index + 1).join('/');let folder = folderByPath.get(folderPath);if (!folder) {- folder = buildSyntheticFolder(folderPath, folderName, baseDepth + (i - startIndex));+ folder = buildSyntheticFolder(folderPath, folderName, baseDepth + (index - startIndex));folderByPath.set(folderPath, folder);siblings.push(folder);}@@ -177,8 +177,9 @@ export const buildFileManagerTree = (const existingFolder = folderByPath.get(file.path);if (existingFolder) {- // Promote a synthetic folder placeholder into the real `FileNode` while- // keeping any children that were attached to it earlier in the loop.+ // Promote a synthetic folder placeholder into a real `FileNode`, keeping any+ // children attached earlier in the loop. `file` is `FileNode` (no `children`+ // field per the type), so the spread can't clobber the descendants.Object.assign(existingFolder, file, { children: existingFolder.children, depth: lastDepth });} else {const node: FileManagerInternalNode = { ...file, children: [], depth: lastDepth };@@ -194,54 +195,56 @@ export const buildFileManagerTree = (return roots;};+interface WalkTreeOptions {+ /** Predicate deciding whether to descend into the node's children. Default: always. */+ descend?: (node: FileManagerInternalNode) => boolean;+ /** Predicate deciding whether to include the node in the result. Default: always. */+ include?: (node: FileManagerInternalNode) => boolean;+}++const ALWAYS = (): true => true;+/**- * Collect paths of *file* nodes only (no synthetic group roots, no directories).- * Used as the universe for "select all".+ * Single DFS walker that powers all `collect*` helpers. Pure: returns a freshly+ * allocated array. Internally uses a private accumulator to avoid `concat`+ * allocations on deep trees, but the buffer is never exposed to callers.*/-export const collectAllFilePaths = (nodes: FileManagerInternalNode[], result: string[] = []): string[] => {- for (const node of nodes) {- if (!node.isGroupRoot && !node.isDir) {- result.push(node.path);- }-- if (node.children.length > 0) {- collectAllFilePaths(node.children, result);- }- }+export const walkTree = (+ nodes: FileManagerInternalNode[],+ { descend = ALWAYS, include = ALWAYS }: WalkTreeOptions = {},+): string[] => {+ const result: string[] = [];- return result;-};+ const visit = (current: FileManagerInternalNode[]): void => {+ for (const node of current) {+ if (include(node)) {+ result.push(node.path);+ }-/** Collect paths of every selectable node (files + real directories), used for bulk-delete validation. */-export const collectAllNodePaths = (nodes: FileManagerInternalNode[], result: string[] = []): string[] => {- for (const node of nodes) {- if (!node.isGroupRoot) {- result.push(node.path);+ if (node.children.length > 0 && descend(node)) {+ visit(node.children);+ }}+ };- if (node.children.length > 0) {- collectAllNodePaths(node.children, result);- }- }+ visit(nodes);return result;};-export const collectVisibleFlat = (- nodes: FileManagerInternalNode[],- expandedPaths: Set<string>,- result: string[] = [],-): string[] => {- for (const node of nodes) {- result.push(node.path);+/**+ * Collect paths of *file* nodes only (no synthetic group roots, no directories).+ * Used as the universe for "select all".+ */+export const collectAllFilePaths = (nodes: FileManagerInternalNode[]): string[] =>+ walkTree(nodes, { include: (node) => !node.isGroupRoot && !node.isDir });- if (node.isDir && expandedPaths.has(node.path) && node.children.length > 0) {- collectVisibleFlat(node.children, expandedPaths, result);- }- }+/** Collect paths of every selectable node (files + real directories), used for bulk-delete validation. */+export const collectAllNodePaths = (nodes: FileManagerInternalNode[]): string[] =>+ walkTree(nodes, { include: (node) => !node.isGroupRoot });- return result;-};+export const collectVisibleFlat = (nodes: FileManagerInternalNode[], expandedPaths: Set<string>): string[] =>+ walkTree(nodes, { descend: (node) => node.isDir && expandedPaths.has(node.path) });/*** Filter the tree so it only contains:@@ -250,10 +253,7 @@ export const collectVisibleFlat = (* - all ancestors of any match (so the path is preserved).* Synthetic group roots are never matched by name/path; they're kept only if any descendant matches.*/-export const filterFileManagerTree = (- nodes: FileManagerInternalNode[],- query: string,-): FileManagerInternalNode[] => {+export const filterFileManagerTree = (nodes: FileManagerInternalNode[], query: string): FileManagerInternalNode[] => {const trimmed = query.trim();if (!trimmed) {@@ -262,10 +262,7 @@ export const filterFileManagerTree = (const lower = trimmed.toLowerCase();- const filterNode = (- node: FileManagerInternalNode,- ancestorMatched: boolean,- ): FileManagerInternalNode | null => {+ const filterNode = (node: FileManagerInternalNode, ancestorMatched: boolean): FileManagerInternalNode | null => {if (node.isGroupRoot) {const keptChildren = node.children.map((child) => filterNode(child, false))@@ -275,9 +272,7 @@ export const filterFileManagerTree = (}const selfMatched =- ancestorMatched ||- node.name.toLowerCase().includes(lower) ||- node.path.toLowerCase().includes(lower);+ ancestorMatched || node.name.toLowerCase().includes(lower) || node.path.toLowerCase().includes(lower);if (!node.isDir) {return selfMatched ? node : null;@@ -300,19 +295,11 @@ export const filterFileManagerTree = (};/** Collects paths of all directory nodes (including synthetic group roots) for auto-expansion. */-export const collectDirectoryPaths = (nodes: FileManagerInternalNode[], result: string[] = []): string[] => {- for (const node of nodes) {- if (node.isDir) {- result.push(node.path);-- if (node.children.length > 0) {- collectDirectoryPaths(node.children, result);- }- }- }-- return result;-};+export const collectDirectoryPaths = (nodes: FileManagerInternalNode[]): string[] =>+ walkTree(nodes, {+ descend: (node) => node.isDir,+ include: (node) => node.isDir,+ });export const resolveSelectionModifier = (event: KeyboardEvent | MouseEvent | ReactMouseEvent,@@ -347,10 +334,7 @@ export const buildFileManagerGridTemplate = (showSize: boolean, showModified: bo};/** Recursively locate a node by its absolute path. Returns `undefined` when missing. */-export const findNodeByPath = (- nodes: FileManagerInternalNode[],- path: string,-): FileManagerInternalNode | undefined => {+export const findNodeByPath = (nodes: FileManagerInternalNode[], path: string): FileManagerInternalNode | undefined => {for (const node of nodes) {if (node.path === path) {return node;@@ -388,3 +372,22 @@ export const dedupeOverlappingPaths = (paths: Iterable<string>): string[] => {return result;};++/** Clamp `value` into the inclusive `[min, max]` range. */+export const clamp = (min: number, value: number, max: number): number => Math.max(min, Math.min(value, max));++/** Translate `(isAllSelected, isSomeSelected)` into the tri-state value the Checkbox understands. */+export const getCheckboxState = (isAllSelected: boolean, isSomeSelected: boolean): 'indeterminate' | boolean => {+ if (isAllSelected) {+ return true;+ }++ if (isSomeSelected) {+ return 'indeterminate';+ }++ return false;+};++/** Default English pluralization for "N item" / "N items". Override via `labels.pluralizeItems`. */+export const pluralizeItemsEnglish = (count: number): string => `${count} ${count === 1 ? 'item' : 'items'}`;diff --git a/frontend/src/components/file-manager/file-manager.tsx b/frontend/src/components/file-manager/file-manager.tsxindex 0bd1e8aa..eb528768 100644--- a/frontend/src/components/file-manager/file-manager.tsx+++ b/frontend/src/components/file-manager/file-manager.tsx@@ -1,62 +1,48 @@-import { Trash2 } from 'lucide-react';-import {- Fragment,- type KeyboardEvent as ReactKeyboardEvent,- type ReactNode,- useCallback,- useMemo,- useRef,- useState,-} from 'react';+import { type MouseEvent as ReactMouseEvent, useCallback, useMemo, useRef, useState } from 'react';-import ConfirmationDialog from '@/components/shared/confirmation-dialog';-import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';import { cn } from '@/lib/utils';-import type { FileManagerAction, FileManagerInternalNode, FileManagerProps } from './file-manager-types';+import type { FileManagerAction, FileManagerProps } from './file-manager-types';-import { FileManagerRow } from './file-manager-row';+import { FileManagerBulkActionsBar } from './file-manager-bulk-actions-bar';import { FileManagerSkeleton } from './file-manager-skeleton';+import { FileManagerTreeNode } from './file-manager-tree-node';import {buildFileManagerGridTemplate,buildFileManagerTree,collectAllFilePaths,collectVisibleFlat,- dedupeOverlappingPaths,filterFileManagerTree,- findNodeByPath,+ getCheckboxState,normalizeRootGroups,} from './file-manager-utils';import { useFileManagerExpansion } from './use-file-manager-expansion';+import { useFileManagerKeyboardNavigation } from './use-file-manager-keyboard';import { useFileManagerSelection } from './use-file-manager-selection';const EMPTY_ACTIONS: readonly FileManagerAction[] = Object.freeze([]);-const pluralize = (count: number, single: string, plural: string): string =>- `${count} ${count === 1 ? single : plural}`;-export const FileManager = ({actions,className,+ columns,emptyState,files,isLoading,+ labels,onBulkDelete,rootGroups,- searchEmptyState,- searchQuery,- showModifiedColumn = true,- showSizeColumn = true,+ search,}: FileManagerProps) => {+ const isSizeVisible = columns?.isSizeVisible ?? true;+ const isModifiedVisible = columns?.isModifiedVisible ?? true;+const normalizedRootGroups = useMemo(() => normalizeRootGroups(rootGroups), [rootGroups]);- const fullTree = useMemo(- () => buildFileManagerTree(files, normalizedRootGroups),- [files, normalizedRootGroups],- );+ const fullTree = useMemo(() => buildFileManagerTree(files, normalizedRootGroups), [files, normalizedRootGroups]);- const trimmedSearch = searchQuery?.trim() ?? '';+ const trimmedSearch = search?.query?.trim() ?? '';const isFiltering = trimmedSearch.length > 0;const visibleTree = useMemo(@@ -85,20 +71,18 @@ export const FileManager = ({toggleSelectAll,} = useFileManagerSelection({ allFilePaths, flatVisible });- const showCheckbox = !!onBulkDelete;+ const isCheckboxVisible = !!onBulkDelete;const hasActions = !!actions?.length;const gridTemplate = useMemo(- () => buildFileManagerGridTemplate(showSizeColumn, showModifiedColumn, hasActions),- [hasActions, showModifiedColumn, showSizeColumn],+ () => buildFileManagerGridTemplate(isSizeVisible, isModifiedVisible, hasActions),+ [hasActions, isModifiedVisible, isSizeVisible],);- const [bulkConfirmOpen, setBulkConfirmOpen] = useState(false);-// ── roving tabindex / keyboard navigation ────────────────────────────────const [activeRowPath, setActiveRowPath] = useState<null | string>(null);const containerRef = useRef<HTMLDivElement | null>(null);- const effectiveActiveRow = useMemo(() => {+ const resolvedActiveRow = useMemo(() => {if (activeRowPath && flatVisible.includes(activeRowPath)) {return activeRowPath;}@@ -122,114 +106,29 @@ export const FileManager = ({setActiveRowPath(path);}, []);- const handleKeyDown = useCallback(- (event: ReactKeyboardEvent<HTMLDivElement>) => {- if (event.key === 'Escape') {- clearSelection();-- return;- }-- if (!effectiveActiveRow || flatVisible.length === 0) {- return;- }-- const idx = flatVisible.indexOf(effectiveActiveRow);-- const moveTo = (nextIdx: number) => {- const nextPath = flatVisible[Math.max(0, Math.min(nextIdx, flatVisible.length - 1))] ?? null;-- setActiveRowPath(nextPath);- focusRow(nextPath);- };-- switch (event.key) {- case ' ':- case 'Spacebar':- event.preventDefault();-- if (showCheckbox) {- onToggleCheckbox(effectiveActiveRow);- }-- return;- case 'A':- case 'a':- if (event.ctrlKey || event.metaKey) {- event.preventDefault();- toggleSelectAll();- }-- return;- case 'ArrowDown':- event.preventDefault();- moveTo(idx + 1);-- return;- case 'ArrowLeft':- case 'ArrowRight': {- const node = findNodeByPath(visibleTree, effectiveActiveRow);-- if (!node?.isDir) {- return;- }-- const isExpanded = expandedPaths.has(node.path);- const wantsExpand = event.key === 'ArrowRight';-- if (wantsExpand !== isExpanded) {- event.preventDefault();- toggleExpand(node.path, isExpanded);- }-- return;- }-- case 'ArrowUp':- event.preventDefault();- moveTo(idx - 1);-- return;- case 'End':- event.preventDefault();- moveTo(flatVisible.length - 1);-- return;- case 'Home':- event.preventDefault();- moveTo(0);+ const handleKeyDown = useFileManagerKeyboardNavigation({+ expandedPaths,+ flatVisible,+ focusRow,+ isCheckboxVisible,+ onClearSelection: clearSelection,+ onSelectAll: toggleSelectAll,+ onSetActiveRow: setActiveRowPath,+ onToggleCheckbox,+ onToggleExpand: toggleExpand,+ resolvedActiveRow,+ visibleTree,+ });- return;- default:- return;+ const handleContainerClick = useCallback(+ (event: ReactMouseEvent<HTMLDivElement>) => {+ if (event.target === event.currentTarget) {+ clearSelection();}},- [- clearSelection,- effectiveActiveRow,- expandedPaths,- flatVisible,- focusRow,- onToggleCheckbox,- showCheckbox,- toggleExpand,- toggleSelectAll,- visibleTree,- ],+ [clearSelection],);- const handleBulkDeleteConfirm = useCallback(async () => {- if (!onBulkDelete) {- return;- }-- const dedupedPaths = new Set(dedupeOverlappingPaths(selectedPaths));- const filesToDelete = files.filter((file) => dedupedPaths.has(file.path));-- await onBulkDelete(filesToDelete);- setSelection(new Set());- }, [files, onBulkDelete, selectedPaths, setSelection]);-if (isLoading) {return (<div className={className}>@@ -243,115 +142,85 @@ export const FileManager = ({}if (isFiltering && visibleTree.length === 0) {- return <div className={className}>{searchEmptyState ?? emptyState}</div>;+ return <div className={className}>{search?.emptyState ?? emptyState}</div>;}- const selectedCountLabel = pluralize(selectedPaths.size, 'item', 'items');-- const renderNode = (node: FileManagerInternalNode): ReactNode => {- const isExpanded = expandedPaths.has(node.path);- const isSelected = selectedPaths.has(node.path);-- return (- <Fragment key={node.id}>- <FileManagerRow- actions={actions ?? (EMPTY_ACTIONS as FileManagerAction[])}- activeRowPath={effectiveActiveRow}- depth={node.depth}- file={node}- gridTemplate={gridTemplate}- hasActions={hasActions}- isExpanded={isExpanded}- isSelected={isSelected}- onClick={onRowClick}- onFocusRow={handleRowFocus}- onToggleCheckbox={onToggleCheckbox}- onToggleExpand={toggleExpand}- searchQuery={trimmedSearch || undefined}- showCheckbox={showCheckbox && !node.isGroupRoot}- showModified={showModifiedColumn}- showSize={showSizeColumn}- />- {node.isDir && isExpanded && node.children.length > 0 && node.children.map(renderNode)}- </Fragment>- );- };+ const effectiveActions = actions ?? EMPTY_ACTIONS;+ const effectiveLabels = labels ?? {};+ const formatModified = effectiveLabels.formatModified;return (<divclassName={cn('bg-card flex flex-col overflow-hidden rounded-lg border', className)}- onClick={(event) => {- if (event.target === event.currentTarget) {- clearSelection();- }- }}+ onClick={handleContainerClick}onKeyDown={handleKeyDown}ref={containerRef}><div- aria-hidden="true"className="bg-muted/30 text-muted-foreground grid items-center gap-3 border-b px-3 py-2 text-xs font-medium"style={{ gridTemplateColumns: gridTemplate }}>- {showCheckbox ? (+ {isCheckboxVisible ? (<Checkbox- aria-label="Select all"- checked={isAllSelected ? true : isSomeSelected ? 'indeterminate' : false}+ aria-label={effectiveLabels.selectAllAriaLabel ?? 'Select all'}+ checked={getCheckboxState(isAllSelected, isSomeSelected)}onCheckedChange={toggleSelectAll}/>) : (- <span className="size-4" />+ <span+ aria-hidden="true"+ className="size-4"+ />+ )}+ <span aria-hidden="true">{effectiveLabels.columnName ?? 'Name'}</span>+ {isSizeVisible && <span aria-hidden="true">{effectiveLabels.columnSize ?? 'Size'}</span>}+ {isModifiedVisible && <span aria-hidden="true">{effectiveLabels.columnModified ?? 'Modified'}</span>}+ {hasActions && (+ <span+ aria-hidden="true"+ className="size-7"+ />)}- <span>Name</span>- {showSizeColumn && <span>Size</span>}- {showModifiedColumn && <span>Modified</span>}- {hasActions && <span className="size-7" />}</div><divaria-label="File tree"+ aria-multiselectable={isCheckboxVisible || undefined}className="flex flex-1 flex-col overflow-y-auto py-1"role="tree">- {visibleTree.map(renderNode)}+ {visibleTree.map((node, index) => (+ <FileManagerTreeNode+ actions={effectiveActions}+ activeRowPath={resolvedActiveRow}+ expandedPaths={expandedPaths}+ formatModified={formatModified}+ gridTemplate={gridTemplate}+ hasActions={hasActions}+ isCheckboxVisible={isCheckboxVisible}+ isModifiedVisible={isModifiedVisible}+ isSizeVisible={isSizeVisible}+ key={node.id}+ node={node}+ onClick={onRowClick}+ onFocusRow={handleRowFocus}+ onToggleCheckbox={onToggleCheckbox}+ onToggleExpand={toggleExpand}+ posInSet={index + 1}+ searchQuery={trimmedSearch || undefined}+ selectedPaths={selectedPaths}+ setSize={visibleTree.length}+ />+ ))}</div>- {selectedPaths.size > 0 && (- <div className="bg-background flex items-center justify-between gap-2 border-t px-3 py-2">- <span className="text-muted-foreground text-sm">{selectedPaths.size} selected</span>- <div className="flex items-center gap-2">- <Button- onClick={clearSelection}- size="sm"- variant="ghost"- >- Cancel- </Button>- {onBulkDelete && (- <Button- onClick={() => setBulkConfirmOpen(true)}- size="sm"- variant="destructive"- >- <Trash2 className="size-4" />- Delete- </Button>- )}- </div>- </div>- )}-- <ConfirmationDialog- confirmText="Delete"- description={`This will delete ${selectedCountLabel}. This action cannot be undone.`}- handleConfirm={handleBulkDeleteConfirm}- handleOpenChange={(isOpen) => {- if (!isOpen) {- setBulkConfirmOpen(false);- }- }}- isOpen={bulkConfirmOpen}- title={`Delete ${selectedCountLabel}`}+ <FileManagerBulkActionsBar+ files={files}+ labels={effectiveLabels}+ onBulkDelete={onBulkDelete}+ onClearSelection={clearSelection}+ onSelectionChange={setSelection}+ selectedPaths={selectedPaths}/></div>);diff --git a/frontend/src/components/file-manager/index.ts b/frontend/src/components/file-manager/index.tsindex 9010f9da..100b7721 100644--- a/frontend/src/components/file-manager/index.ts+++ b/frontend/src/components/file-manager/index.ts@@ -4,6 +4,7 @@ export { getFileTypeIcon } from './file-manager-icons';export type { FileTypeIcon } from './file-manager-icons';export type {FileManagerAction,+ FileManagerLabels,FileManagerProps,FileManagerRootGroup,FileNode,diff --git a/frontend/src/components/file-manager/use-file-manager-expansion.ts b/frontend/src/components/file-manager/use-file-manager-expansion.tsindex 4a136caf..3b47bd54 100644--- a/frontend/src/components/file-manager/use-file-manager-expansion.ts+++ b/frontend/src/components/file-manager/use-file-manager-expansion.ts@@ -4,12 +4,15 @@ import type { FileManagerInternalNode, FileManagerRootGroup } from './file-managimport { collectDirectoryPaths } from './file-manager-utils';-type ExpansionOverride = 'force-collapsed' | 'force-expanded';-interface UseFileManagerExpansion {/** Effective set of expanded directory paths (auto-expansion + user overrides). */expandedPaths: Set<string>;- /** Toggle expansion of a directory; persists as a user override. */+ /**+ * Toggle expansion of a directory based on the state the caller is currently+ * displaying. Passing `wasExpanded` is intentional — it captures the user's+ * intent ("invert what I see") and lets the callback stay stable across renders,+ * which keeps memoized rows from invalidating on every expansion change.+ */toggleExpand: (path: string, wasExpanded: boolean) => void;}@@ -22,7 +25,8 @@ interface UseFileManagerExpansionArgs {/*** Expansion state without `useEffect`: we never store the full set in state.- * Instead we keep a small map of *user-driven* overrides on top of two automatic sources:+ * Instead we keep a small map of *user-driven* overrides (path -> isExpanded) on top+ * of two automatic sources:* 1) `rootGroups[].defaultOpen` — initial group expansion,* 2) on-search auto-expansion of every directory inside the filtered tree.*/@@ -31,7 +35,7 @@ export const useFileManagerExpansion = ({normalizedRootGroups,visibleTree,}: UseFileManagerExpansionArgs): UseFileManagerExpansion => {- const [overrides, setOverrides] = useState<Map<string, ExpansionOverride>>(() => new Map());+ const [overrides, setOverrides] = useState<Map<string, boolean>>(() => new Map());const expandedPaths = useMemo(() => {const result = new Set<string>();@@ -50,8 +54,8 @@ export const useFileManagerExpansion = ({}}- for (const [path, override] of overrides) {- if (override === 'force-expanded') {+ for (const [path, isExpanded] of overrides) {+ if (isExpanded) {result.add(path);} else {result.delete(path);@@ -65,7 +69,7 @@ export const useFileManagerExpansion = ({setOverrides((prev) => {const next = new Map(prev);- next.set(path, wasExpanded ? 'force-collapsed' : 'force-expanded');+ next.set(path, !wasExpanded);return next;});diff --git a/frontend/src/components/file-manager/use-file-manager-keyboard.ts b/frontend/src/components/file-manager/use-file-manager-keyboard.tsnew file mode 100644index 00000000..66c42a15--- /dev/null+++ b/frontend/src/components/file-manager/use-file-manager-keyboard.ts@@ -0,0 +1,137 @@+import { type KeyboardEvent as ReactKeyboardEvent, useCallback } from 'react';++import type { FileManagerInternalNode } from './file-manager-types';++import { clamp, findNodeByPath } from './file-manager-utils';++interface UseFileManagerKeyboardNavigationArgs {+ expandedPaths: Set<string>;+ /** Visible nodes in DFS order — universe of focusable rows. */+ flatVisible: string[];+ focusRow: (path: null | string) => void;+ isCheckboxVisible: boolean;+ onClearSelection: () => void;+ onSelectAll: () => void;+ onSetActiveRow: (path: null | string) => void;+ onToggleCheckbox: (path: string) => void;+ onToggleExpand: (path: string, wasExpanded: boolean) => void;+ /** Currently focused row, or `null` if nothing is focused. */+ resolvedActiveRow: null | string;+ visibleTree: FileManagerInternalNode[];+}++/**+ * Keyboard handler implementing the WAI-ARIA Tree pattern:+ * Arrow Up/Down → move focus, Home/End → jump to ends, Arrow Left/Right → collapse/expand+ * directories, Space → toggle the row's checkbox (only when checkboxes are shown),+ * Ctrl/Cmd+A → select all, Escape → clear selection.+ */+export const useFileManagerKeyboardNavigation = ({+ expandedPaths,+ flatVisible,+ focusRow,+ isCheckboxVisible,+ onClearSelection,+ onSelectAll,+ onSetActiveRow,+ onToggleCheckbox,+ onToggleExpand,+ resolvedActiveRow,+ visibleTree,+}: UseFileManagerKeyboardNavigationArgs) =>+ useCallback(+ (event: ReactKeyboardEvent<HTMLDivElement>) => {+ if (event.key === 'Escape') {+ onClearSelection();++ return;+ }++ if (!resolvedActiveRow || flatVisible.length === 0) {+ return;+ }++ const index = flatVisible.indexOf(resolvedActiveRow);++ const moveTo = (nextIndex: number) => {+ const nextPath = flatVisible[clamp(0, nextIndex, flatVisible.length - 1)] ?? null;++ onSetActiveRow(nextPath);+ focusRow(nextPath);+ };++ switch (event.key) {+ case ' ':+ case 'Spacebar':+ event.preventDefault();++ if (isCheckboxVisible) {+ onToggleCheckbox(resolvedActiveRow);+ }++ return;+ case 'A':+ case 'a':+ if (event.ctrlKey || event.metaKey) {+ event.preventDefault();+ onSelectAll();+ }++ return;+ case 'ArrowDown':+ event.preventDefault();+ moveTo(index + 1);++ return;+ case 'ArrowLeft':+ case 'ArrowRight': {+ const node = findNodeByPath(visibleTree, resolvedActiveRow);++ if (!node?.isDir) {+ return;+ }++ const isExpanded = expandedPaths.has(node.path);+ const wantsExpand = event.key === 'ArrowRight';++ if (wantsExpand !== isExpanded) {+ event.preventDefault();+ onToggleExpand(node.path, isExpanded);+ }++ return;+ }++ case 'ArrowUp':+ event.preventDefault();+ moveTo(index - 1);++ return;+ case 'End':+ event.preventDefault();+ moveTo(flatVisible.length - 1);++ return;+ case 'Home':+ event.preventDefault();+ moveTo(0);++ return;+ default:+ return;+ }+ },+ [+ expandedPaths,+ flatVisible,+ focusRow,+ isCheckboxVisible,+ onClearSelection,+ onSelectAll,+ onSetActiveRow,+ onToggleCheckbox,+ onToggleExpand,+ resolvedActiveRow,+ visibleTree,+ ],+ );diff --git a/frontend/src/components/file-manager/use-file-manager-selection.ts b/frontend/src/components/file-manager/use-file-manager-selection.tsindex 26473d96..5fec7757 100644--- a/frontend/src/components/file-manager/use-file-manager-selection.ts+++ b/frontend/src/components/file-manager/use-file-manager-selection.ts@@ -67,14 +67,16 @@ export const useFileManagerSelection = ({(event: ReactMouseEvent, path: string) => {const modifier = resolveSelectionModifier(event);- setRawSelectedPaths((prev) => {- if (modifier === 'single') {- lastClickedRef.current = path;+ if (modifier === 'single') {+ lastClickedRef.current = path;+ setRawSelectedPaths(new Set([path]));- return new Set([path]);- }+ return;+ }- if (modifier === 'toggle') {+ if (modifier === 'toggle') {+ lastClickedRef.current = path;+ setRawSelectedPaths((prev) => {const next = new Set(prev);if (next.has(path)) {@@ -83,33 +85,39 @@ export const useFileManagerSelection = ({next.add(path);}- lastClickedRef.current = path;-return next;- }+ });- if (!lastClickedRef.current) {- lastClickedRef.current = path;+ return;+ }- return new Set([path]);- }+ const anchor = lastClickedRef.current;- const fromIdx = flatVisible.indexOf(lastClickedRef.current);- const toIdx = flatVisible.indexOf(path);+ if (!anchor) {+ lastClickedRef.current = path;+ setRawSelectedPaths(new Set([path]));++ return;+ }- if (fromIdx < 0 || toIdx < 0) {- return new Set([path]);- }+ const fromIndex = flatVisible.indexOf(anchor);+ const toIndex = flatVisible.indexOf(path);- const [a, b] = fromIdx <= toIdx ? [fromIdx, toIdx] : [toIdx, fromIdx];+ if (fromIndex < 0 || toIndex < 0) {+ setRawSelectedPaths(new Set([path]));- return new Set(flatVisible.slice(a, b + 1));- });+ return;+ }++ const [startIndex, endIndex] = fromIndex <= toIndex ? [fromIndex, toIndex] : [toIndex, fromIndex];++ setRawSelectedPaths(new Set(flatVisible.slice(startIndex, endIndex + 1)));},[flatVisible],);const onToggleCheckbox = useCallback((path: string) => {+ lastClickedRef.current = path;setRawSelectedPaths((prev) => {const next = new Set(prev);@@ -119,8 +127,6 @@ export const useFileManagerSelection = ({next.add(path);}- lastClickedRef.current = path;-return next;});}, []);diff --git a/frontend/src/features/flows/files/flow-files.tsx b/frontend/src/features/flows/files/flow-files.tsxindex 90cdfb45..b7343403 100644--- a/frontend/src/features/flows/files/flow-files.tsx+++ b/frontend/src/features/flows/files/flow-files.tsx@@ -289,17 +289,10 @@ const FlowFiles = () => {});}, []);- const getDownloadHrefForFile = useCallback(- (file: FileNode) => buildDownloadHref(flowId, file),- [flowId],- );+ const getDownloadHrefForFile = useCallback((file: FileNode) => buildDownloadHref(flowId, file), [flowId]);const fileManagerActions = useMemo<FileManagerAction[]>(- () => [- downloadAction(getDownloadHrefForFile),- copyPathAction(handleCopyPath),- deleteAction(setFileToDelete),- ],+ () => [downloadAction(getDownloadHrefForFile), copyPathAction(handleCopyPath), deleteAction(setFileToDelete)],[getDownloadHrefForFile, handleCopyPath],);@@ -316,16 +309,12 @@ const FlowFiles = () => {setIsUploading(true);try {- const response = await api.post<FlowFilesResponse, FormData>(- `/flows/${flowId}/files/`,- formData,- {- // Browser sets the multipart boundary automatically when Content-Type is unset.- headers: { 'Content-Type': undefined },- // Uploads can take longer than the default 30s — disable timeout for this call.- timeout: 0,- },- );+ const response = await api.post<FlowFilesResponse, FormData>(`/flows/${flowId}/files/`, formData, {+ // Browser sets the multipart boundary automatically when Content-Type is unset.+ headers: { 'Content-Type': undefined },+ // Uploads can take longer than the default 30s — disable timeout for this call.+ timeout: 0,+ });const data = unwrapApiResponse(response);const uploadedCount = data.files?.length ?? selectedFiles.length;@@ -651,8 +640,7 @@ const FlowFiles = () => {isLoading={isInitialLoading}onBulkDelete={handleBulkDelete}rootGroups={ROOT_GROUPS}- searchEmptyState={noMatchesState}- searchQuery={debouncedSearch}+ search={{ emptyState: noMatchesState, query: debouncedSearch }}/><PullDialog