Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat: add reusable file manager component

Sergey Kozyrenkod9416363dd27
diff --git a/frontend/package.json b/frontend/package.json
index dbdabdd8..0d2ff692 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -23,6 +23,7 @@
"@monaco-editor/react": "^4.7.0",
"@radix-ui/react-accordion": "^1.2.11",
"@radix-ui/react-avatar": "^1.1.1",
+ "@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-collapsible": "^1.1.1",
"@radix-ui/react-context-menu": "^2.2.16",
"@radix-ui/react-dialog": "^1.1.15",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index f893e377..d92302e8 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -23,6 +23,9 @@ importers:
'@radix-ui/react-avatar':
specifier: ^1.1.1
+ '@radix-ui/react-checkbox':
+ specifier: ^1.3.3
'@radix-ui/react-collapsible':
specifier: ^1.1.1
@@ -1295,6 +1298,19 @@ packages:
'@types/react-dom':
optional: true
+ '@radix-ui/[email protected]':
+ resolution: {integrity: sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
'@radix-ui/[email protected]':
resolution: {integrity: sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==}
peerDependencies:
@@ -6718,6 +6734,22 @@ snapshots:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/[email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.3
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])
+ react: 19.2.5
+ react-dom: 19.2.5([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.14
+ '@types/react-dom': 19.2.3(@types/[email protected])
+
dependencies:
'@radix-ui/primitive': 1.1.3
diff --git a/frontend/src/components/file-manager/file-manager-actions.tsx b/frontend/src/components/file-manager/file-manager-actions.tsx
new file mode 100644
index 00000000..aec21885
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager-actions.tsx
@@ -0,0 +1,50 @@
+import { Copy, Download, Trash2 } from 'lucide-react';
+
+import type { FileManagerAction, FileNode } from './file-manager-types';
+
+/**
+ * Built-in download action.
+ *
+ * The `getDownloadHref` callback receives the file node and must return a fully-formed
+ * URL. For directories the browser is hinted to save the response as `${name}.zip` —
+ * the backend is responsible for actually returning a zip stream.
+ */
+export const downloadAction = (
+ getDownloadHref: (file: FileNode) => string,
+ options: { directoryArchiveExtension?: string } = {},
+): FileManagerAction => {
+ const archiveExtension = options.directoryArchiveExtension ?? 'zip';
+
+ return {
+ appliesToDirs: true,
+ getHref: getDownloadHref,
+ getHrefDownloadAttr: (file) => (file.isDir ? `${file.name}.${archiveExtension}` : file.name),
+ icon: Download,
+ id: '__builtin_download',
+ label: 'Download',
+ onSelect: () => {},
+ };
+};
+
+/** Built-in copy-path action. */
+export const copyPathAction = (onCopyPath: (file: FileNode) => void): FileManagerAction => ({
+ appliesToDirs: true,
+ icon: Copy,
+ id: '__builtin_copy_path',
+ label: 'Copy path',
+ onSelect: onCopyPath,
+});
+
+/**
+ * Built-in delete action. Always rendered with a leading separator and destructive variant.
+ * Caller is responsible for showing a confirmation dialog inside `onSelect`.
+ */
+export const deleteAction = (onDelete: (file: FileNode) => void): FileManagerAction => ({
+ appliesToDirs: true,
+ icon: Trash2,
+ id: '__builtin_delete',
+ label: 'Delete',
+ onSelect: onDelete,
+ separatorBefore: true,
+ variant: 'destructive',
+});
diff --git a/frontend/src/components/file-manager/file-manager-highlighted-name.tsx b/frontend/src/components/file-manager/file-manager-highlighted-name.tsx
new file mode 100644
index 00000000..bbc375d3
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager-highlighted-name.tsx
@@ -0,0 +1,46 @@
+import { Fragment, type ReactNode } from 'react';
+
+import { cn } from '@/lib/utils';
+
+interface FileManagerHighlightedNameProps {
+ className?: string;
+ name: string;
+ query?: string;
+}
+
+export const FileManagerHighlightedName = ({ className, name, query }: FileManagerHighlightedNameProps) => {
+ if (!query?.trim()) {
+ return <span className={cn('truncate', className)}>{name}</span>;
+ }
+
+ const lower = name.toLowerCase();
+ const lowerQuery = query.toLowerCase();
+ const segments: ReactNode[] = [];
+ let cursor = 0;
+
+ while (cursor < name.length) {
+ const matchIndex = lower.indexOf(lowerQuery, cursor);
+
+ if (matchIndex < 0) {
+ segments.push(<Fragment key={`t-${cursor}`}>{name.slice(cursor)}</Fragment>);
+ break;
+ }
+
+ if (matchIndex > cursor) {
+ segments.push(<Fragment key={`p-${cursor}`}>{name.slice(cursor, matchIndex)}</Fragment>);
+ }
+
+ segments.push(
+ <mark
+ className="bg-primary/20 text-foreground rounded-[2px]"
+ key={`m-${matchIndex}`}
+ >
+ {name.slice(matchIndex, matchIndex + lowerQuery.length)}
+ </mark>,
+ );
+
+ cursor = matchIndex + lowerQuery.length;
+ }
+
+ return <span className={cn('truncate', className)}>{segments}</span>;
+};
diff --git a/frontend/src/components/file-manager/file-manager-icons.tsx b/frontend/src/components/file-manager/file-manager-icons.tsx
new file mode 100644
index 00000000..1e72502b
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager-icons.tsx
@@ -0,0 +1,107 @@
+import {
+ File,
+ FileArchive,
+ FileAudio,
+ FileCode,
+ FileImage,
+ FileJson,
+ FileSpreadsheet,
+ FileText,
+ FileType,
+ FileVideo,
+ Folder,
+ FolderOpen,
+ type LucideIcon,
+} from 'lucide-react';
+
+export interface FileTypeIcon {
+ icon: LucideIcon;
+ tone: string;
+}
+
+interface GetFileTypeIconArgs {
+ isDir: boolean;
+ isOpen?: boolean;
+ name: string;
+}
+
+const EXT_MAP: Record<string, FileTypeIcon> = {
+ '7z': { icon: FileArchive, tone: 'text-amber-500' },
+ aac: { icon: FileAudio, tone: 'text-fuchsia-500' },
+ avi: { icon: FileVideo, tone: 'text-violet-500' },
+ bash: { icon: FileCode, tone: 'text-green-500' },
+ bz2: { icon: FileArchive, tone: 'text-amber-500' },
+ c: { icon: FileCode, tone: 'text-blue-400' },
+ cfg: { icon: FileText, tone: 'text-muted-foreground' },
+ conf: { icon: FileText, tone: 'text-muted-foreground' },
+ cpp: { icon: FileCode, tone: 'text-blue-400' },
+ cs: { icon: FileCode, tone: 'text-emerald-500' },
+ css: { icon: FileCode, tone: 'text-sky-500' },
+ csv: { icon: FileSpreadsheet, tone: 'text-emerald-500' },
+ doc: { icon: FileText, tone: 'text-blue-500' },
+ docx: { icon: FileText, tone: 'text-blue-500' },
+ env: { icon: FileText, tone: 'text-muted-foreground' },
+ flac: { icon: FileAudio, tone: 'text-fuchsia-500' },
+ flv: { icon: FileVideo, tone: 'text-violet-500' },
+ gif: { icon: FileImage, tone: 'text-purple-500' },
+ go: { icon: FileCode, tone: 'text-cyan-500' },
+ gz: { icon: FileArchive, tone: 'text-amber-500' },
+ h: { icon: FileCode, tone: 'text-blue-400' },
+ hpp: { icon: FileCode, tone: 'text-blue-400' },
+ htm: { icon: FileCode, tone: 'text-orange-500' },
+ html: { icon: FileCode, tone: 'text-orange-500' },
+ ico: { icon: FileImage, tone: 'text-purple-500' },
+ ini: { icon: FileText, tone: 'text-muted-foreground' },
+ java: { icon: FileCode, tone: 'text-orange-500' },
+ jpeg: { icon: FileImage, tone: 'text-purple-500' },
+ jpg: { icon: FileImage, tone: 'text-purple-500' },
+ js: { icon: FileCode, tone: 'text-yellow-500' },
+ json: { icon: FileJson, tone: 'text-yellow-500' },
+ jsx: { icon: FileCode, tone: 'text-blue-500' },
+ kt: { icon: FileCode, tone: 'text-purple-500' },
+ log: { icon: FileText, tone: 'text-muted-foreground' },
+ md: { icon: FileText, tone: 'text-slate-400' },
+ mdx: { icon: FileText, tone: 'text-slate-400' },
+ mkv: { icon: FileVideo, tone: 'text-violet-500' },
+ mov: { icon: FileVideo, tone: 'text-violet-500' },
+ mp3: { icon: FileAudio, tone: 'text-fuchsia-500' },
+ mp4: { icon: FileVideo, tone: 'text-violet-500' },
+ ogg: { icon: FileAudio, tone: 'text-fuchsia-500' },
+ pdf: { icon: FileType, tone: 'text-red-500' },
+ php: { icon: FileCode, tone: 'text-indigo-500' },
+ png: { icon: FileImage, tone: 'text-purple-500' },
+ ppt: { icon: FileText, tone: 'text-orange-600' },
+ pptx: { icon: FileText, tone: 'text-orange-600' },
+ py: { icon: FileCode, tone: 'text-yellow-500' },
+ rar: { icon: FileArchive, tone: 'text-amber-500' },
+ rb: { icon: FileCode, tone: 'text-red-500' },
+ rs: { icon: FileCode, tone: 'text-orange-500' },
+ sh: { icon: FileCode, tone: 'text-green-500' },
+ sql: { icon: FileCode, tone: 'text-cyan-500' },
+ svg: { icon: FileImage, tone: 'text-pink-500' },
+ swift: { icon: FileCode, tone: 'text-orange-500' },
+ tar: { icon: FileArchive, tone: 'text-amber-500' },
+ toml: { icon: FileJson, tone: 'text-rose-500' },
+ ts: { icon: FileCode, tone: 'text-blue-500' },
+ tsx: { icon: FileCode, tone: 'text-blue-500' },
+ txt: { icon: FileText, tone: 'text-muted-foreground' },
+ wav: { icon: FileAudio, tone: 'text-fuchsia-500' },
+ webm: { icon: FileVideo, tone: 'text-violet-500' },
+ webp: { icon: FileImage, tone: 'text-purple-500' },
+ xls: { icon: FileSpreadsheet, tone: 'text-emerald-500' },
+ xlsx: { icon: FileSpreadsheet, tone: 'text-emerald-500' },
+ xml: { icon: FileCode, tone: 'text-orange-400' },
+ yaml: { icon: FileJson, tone: 'text-rose-500' },
+ yml: { icon: FileJson, tone: 'text-rose-500' },
+ zip: { icon: FileArchive, tone: 'text-amber-500' },
+};
+
+export const getFileTypeIcon = ({ isDir, isOpen, name }: GetFileTypeIconArgs): FileTypeIcon => {
+ if (isDir) {
+ return { icon: isOpen ? FolderOpen : Folder, tone: 'text-blue-400' };
+ }
+
+ const ext = name.split('.').pop()?.toLowerCase() ?? '';
+
+ return EXT_MAP[ext] ?? { icon: File, tone: 'text-muted-foreground' };
+};
diff --git a/frontend/src/components/file-manager/file-manager-row.tsx b/frontend/src/components/file-manager/file-manager-row.tsx
new file mode 100644
index 00000000..2666c214
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager-row.tsx
@@ -0,0 +1,275 @@
+import { ChevronRight, MoreVertical } from 'lucide-react';
+import { type CSSProperties, memo, type MouseEvent as ReactMouseEvent, type ReactNode, useMemo } from 'react';
+
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuSeparator,
+ ContextMenuTrigger,
+} from '@/components/ui/context-menu';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { cn } from '@/lib/utils';
+
+import type { FileManagerAction, FileManagerInternalNode } from './file-manager-types';
+
+import { FileManagerHighlightedName } from './file-manager-highlighted-name';
+import { getFileTypeIcon } from './file-manager-icons';
+import { formatFileSize, formatModified } from './file-manager-utils';
+
+/** Marker on every interactive child of the row that should NOT bubble into a row click. */
+const SKIP_ROW_CLICK_ATTR = 'data-fm-skip-row-click';
+
+interface FileManagerRowProps {
+ actions: FileManagerAction[];
+ activeRowPath: null | string;
+ depth: number;
+ file: FileManagerInternalNode;
+ gridTemplate: string;
+ hasActions: boolean;
+ isExpanded: boolean;
+ isSelected: boolean;
+ onClick: (event: ReactMouseEvent, path: string) => void;
+ onFocusRow: (path: string) => void;
+ onToggleCheckbox: (path: string) => void;
+ onToggleExpand: (path: string, wasExpanded: boolean) => void;
+ searchQuery?: string;
+ showCheckbox: boolean;
+ showModified: boolean;
+ showSize: boolean;
+}
+
+/** 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 FileManagerRowImpl = ({
+ actions,
+ activeRowPath,
+ depth,
+ file,
+ gridTemplate,
+ hasActions,
+ isExpanded,
+ isSelected,
+ onClick,
+ onFocusRow,
+ onToggleCheckbox,
+ onToggleExpand,
+ searchQuery,
+ showCheckbox,
+ showModified,
+ showSize,
+}: FileManagerRowProps) => {
+ const { icon: Icon, tone } = useMemo(
+ () =>
+ file.groupIcon
+ ? { icon: file.groupIcon, tone: 'text-blue-400' }
+ : getFileTypeIcon({ isDir: file.isDir, isOpen: isExpanded, name: file.name }),
+ [file.groupIcon, file.isDir, file.name, isExpanded],
+ );
+
+ const visibleActions = useMemo(() => buildVisibleActions(actions, file), [actions, file]);
+
+ const handleRowClick = (event: ReactMouseEvent) => {
+ if (isClickInsideSkipZone(event.target)) {
+ return;
+ }
+
+ if (file.isDir) {
+ onToggleExpand(file.path, isExpanded);
+ }
+
+ onClick(event, file.path);
+ };
+
+ const renderActionItem = (
+ Component: typeof ContextMenuItem | typeof DropdownMenuItem,
+ action: FileManagerAction,
+ ) => {
+ const ActionIcon = action.icon;
+ const itemClassName = cn(
+ action.variant === 'destructive' &&
+ 'text-destructive focus:bg-destructive/10 focus:text-destructive',
+ );
+
+ if (action.getHref) {
+ return (
+ <Component
+ asChild
+ className={itemClassName}
+ key={action.id}
+ >
+ <a
+ download={action.getHrefDownloadAttr?.(file) ?? true}
+ href={action.getHref(file)}
+ >
+ {ActionIcon ? <ActionIcon className="size-4" /> : null}
+ {action.label}
+ </a>
+ </Component>
+ );
+ }
+
+ return (
+ <Component
+ className={itemClassName}
+ key={action.id}
+ onSelect={() => action.onSelect(file)}
+ >
+ {ActionIcon ? <ActionIcon className="size-4" /> : null}
+ {action.label}
+ </Component>
+ );
+ };
+
+ const renderActionItems = (kind: 'context' | 'dropdown'): ReactNode[] => {
+ const Item = kind === 'context' ? ContextMenuItem : DropdownMenuItem;
+ const Sep = kind === '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(renderActionItem(Item, action));
+ }
+
+ return items;
+ };
+
+ const dropdownItems = hasActions ? renderActionItems('dropdown') : [];
+ const contextItems = renderActionItems('context');
+ const isActiveRow = activeRowPath === file.path;
+
+ const rowStyle = {
+ '--fm-depth': depth,
+ gridTemplateColumns: gridTemplate,
+ } as CSSProperties & Record<'--fm-depth', number>;
+
+ const row = (
+ <div
+ aria-expanded={file.isDir ? isExpanded : undefined}
+ aria-selected={isSelected}
+ 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',
+ isSelected && 'bg-muted',
+ )}
+ data-path={file.path}
+ onClick={handleRowClick}
+ onFocus={() => onFocusRow(file.path)}
+ role="treeitem"
+ style={rowStyle}
+ tabIndex={isActiveRow ? 0 : -1}
+ >
+ {showCheckbox ? (
+ <span
+ className="flex items-center"
+ {...{ [SKIP_ROW_CLICK_ATTR]: '' }}
+ >
+ <Checkbox
+ aria-label={`Select ${file.name}`}
+ checked={isSelected}
+ onCheckedChange={() => onToggleCheckbox(file.path)}
+ onClick={(event) => event.stopPropagation()}
+ />
+ </span>
+ ) : (
+ <span
+ aria-hidden="true"
+ className="size-4"
+ />
+ )}
+
+ <div
+ className="flex min-w-0 items-center gap-1.5 pl-[calc(var(--fm-depth)*16px)]"
+ >
+ {file.isDir ? (
+ <span
+ aria-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]: '' }}
+ >
+ <ChevronRight className={cn('size-3.5 transition-transform', isExpanded && 'rotate-90')} />
+ </span>
+ ) : (
+ <span
+ aria-hidden="true"
+ className="size-4 shrink-0"
+ />
+ )}
+ <Icon className={cn('size-4 shrink-0', tone)} />
+ <FileManagerHighlightedName
+ className={cn('text-sm', file.isGroupRoot && 'font-semibold')}
+ name={file.name}
+ query={searchQuery}
+ />
+ </div>
+
+ {showSize && (
+ <span className="text-muted-foreground/80 shrink-0 text-xs tabular-nums">
+ {!file.isDir ? formatFileSize(file.size) : ''}
+ </span>
+ )}
+
+ {showModified && (
+ <span className="text-muted-foreground/80 shrink-0 text-xs tabular-nums">
+ {formatModified(file.modifiedAt)}
+ </span>
+ )}
+
+ {hasActions && (
+ <span {...{ [SKIP_ROW_CLICK_ATTR]: '' }}>
+ {dropdownItems.length > 0 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ aria-label="Row actions"
+ className="opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"
+ onClick={(event) => event.stopPropagation()}
+ size="icon-xs"
+ variant="ghost"
+ >
+ <MoreVertical className="size-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">{dropdownItems}</DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ </span>
+ )}
+ </div>
+ );
+
+ if (contextItems.length === 0) {
+ return row;
+ }
+
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger asChild>{row}</ContextMenuTrigger>
+ <ContextMenuContent>{contextItems}</ContextMenuContent>
+ </ContextMenu>
+ );
+};
+
+FileManagerRowImpl.displayName = 'FileManagerRow';
+
+export const FileManagerRow = memo(FileManagerRowImpl);
diff --git a/frontend/src/components/file-manager/file-manager-skeleton.tsx b/frontend/src/components/file-manager/file-manager-skeleton.tsx
new file mode 100644
index 00000000..b74d5e14
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager-skeleton.tsx
@@ -0,0 +1,52 @@
+import { Skeleton } from '@/components/ui/skeleton';
+import { cn } from '@/lib/utils';
+
+const ROOT_NAME_WIDTHS = ['w-28', 'w-36', 'w-24', 'w-32'];
+const NESTED_NAME_WIDTHS = ['w-44', 'w-36', 'w-28'];
+
+export const FileManagerSkeleton = () => (
+ <div className="bg-card overflow-hidden rounded-lg border">
+ <div className="bg-muted/30 flex items-center gap-3 border-b px-3 py-2">
+ <Skeleton className="size-4 shrink-0 rounded-sm" />
+ <Skeleton className="h-3 w-12" />
+ <div className="ml-auto flex items-center gap-3">
+ <Skeleton className="h-3 w-10" />
+ <Skeleton className="h-3 w-16" />
+ <div className="size-7" />
+ </div>
+ </div>
+ <div className="flex flex-col gap-px py-1">
+ <div className="flex items-center gap-3 px-3 py-1.5">
+ <Skeleton className="size-4 shrink-0 rounded-sm" />
+ <Skeleton className="size-3.5 shrink-0" />
+ <Skeleton className="size-4 shrink-0" />
+ <Skeleton className="h-4 w-20" />
+ </div>
+ {NESTED_NAME_WIDTHS.map((width, i) => (
+ <div
+ className="flex items-center gap-3 px-3 py-1.5 pl-9"
+ key={`n-${i}`}
+ >
+ <Skeleton className="size-4 shrink-0 rounded-sm" />
+ <Skeleton className="size-4 shrink-0" />
+ <Skeleton className={cn('h-4', width)} />
+ <Skeleton className="ml-auto h-3 w-10" />
+ <Skeleton className="h-3 w-16" />
+ </div>
+ ))}
+ {ROOT_NAME_WIDTHS.map((width, i) => (
+ <div
+ className="flex items-center gap-3 px-3 py-1.5"
+ key={`r-${i}`}
+ >
+ <Skeleton className="size-4 shrink-0 rounded-sm" />
+ <Skeleton className="size-3.5 shrink-0" />
+ <Skeleton className="size-4 shrink-0" />
+ <Skeleton className={cn('h-4', width)} />
+ <Skeleton className="ml-auto h-3 w-10" />
+ <Skeleton className="h-3 w-16" />
+ </div>
+ ))}
+ </div>
+ </div>
+);
diff --git a/frontend/src/components/file-manager/file-manager-types.ts b/frontend/src/components/file-manager/file-manager-types.ts
new file mode 100644
index 00000000..79940c40
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager-types.ts
@@ -0,0 +1,75 @@
+import type { ComponentType, ReactNode } from 'react';
+
+export interface FileManagerAction {
+ /** When true, action is shown for both files and directories. Defaults to false (files only). */
+ appliesToDirs?: boolean;
+ /**
+ * If provided, the action is rendered as an `<a href>` link instead of a button.
+ * Useful for native browser downloads.
+ */
+ getHref?: (file: FileNode) => string;
+ /**
+ * `download` attribute for the `<a>` (only meaningful with `getHref`). Browser
+ * uses it as a hint for the suggested filename — the actual content/extension
+ * is determined by the server.
+ */
+ getHrefDownloadAttr?: (file: FileNode) => string;
+ icon?: ComponentType<{ className?: string }>;
+ /** Stable identifier — used as React `key`. */
+ id: string;
+ label: string;
+ /** Triggered on item activation. Ignored when `getHref` is set. */
+ onSelect: (file: FileNode) => void;
+ /** When true, separator is rendered before this action. */
+ separatorBefore?: boolean;
+ variant?: 'default' | 'destructive';
+}
+
+export interface FileManagerInternalNode extends FileNode {
+ children: FileManagerInternalNode[];
+ depth: number;
+ groupIcon?: ComponentType<{ className?: string }>;
+ isGroupRoot?: boolean;
+}
+
+export interface FileManagerProps {
+ /** Single, ordered list of available row actions (built-in helpers live in `file-manager-actions`). */
+ actions?: FileManagerAction[];
+ className?: string;
+ /** Empty state node (rendered when files.length === 0 and not loading). */
+ emptyState?: ReactNode;
+ files: FileNode[];
+ isLoading?: boolean;
+ /**
+ * 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.
+ */
+ 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;
+}
+
+export interface FileManagerRootGroup {
+ defaultOpen?: boolean;
+ icon?: ComponentType<{ className?: string }>;
+ /** Stable identifier (also used for synthetic node id). */
+ id: string;
+ label: string;
+ /** Path prefix without trailing slash, e.g. `'uploads'` or `'container'`. */
+ pathPrefix: string;
+}
+
+export interface FileNode {
+ id: string;
+ isDir: boolean;
+ modifiedAt?: Date | string;
+ name: string;
+ path: string;
+ size?: number;
+}
diff --git a/frontend/src/components/file-manager/file-manager-utils.test.ts b/frontend/src/components/file-manager/file-manager-utils.test.ts
new file mode 100644
index 00000000..7123a1cd
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager-utils.test.ts
@@ -0,0 +1,322 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FileManagerInternalNode, FileManagerRootGroup, FileNode } from './file-manager-types';
+
+import {
+ buildFileManagerGridTemplate,
+ buildFileManagerTree,
+ collectAllFilePaths,
+ collectDirectoryPaths,
+ collectVisibleFlat,
+ dedupeOverlappingPaths,
+ filterFileManagerTree,
+ findNodeByPath,
+ formatFileSize,
+ formatModified,
+ normalizeRootGroups,
+ resolveSelectionModifier,
+} from './file-manager-utils';
+
+const file = (path: string, overrides: Partial<FileNode> = {}): FileNode => ({
+ id: path,
+ isDir: false,
+ name: path.split('/').pop() ?? path,
+ path,
+ ...overrides,
+});
+
+const dir = (path: string, overrides: Partial<FileNode> = {}): FileNode =>
+ file(path, { isDir: true, ...overrides });
+
+describe('formatFileSize', () => {
+ it('returns empty string when size is missing', () => {
+ expect(formatFileSize(undefined)).toBe('');
+ });
+
+ it('renders bytes for sizes < 1KB', () => {
+ expect(formatFileSize(0)).toBe('0 B');
+ expect(formatFileSize(1023)).toBe('1023 B');
+ });
+
+ it('renders 1.0 KB on the 1KB boundary', () => {
+ expect(formatFileSize(1024)).toBe('1.0 KB');
+ });
+
+ it('uses one decimal under 10 of a unit, none above', () => {
+ expect(formatFileSize(1024 * 5)).toBe('5.0 KB');
+ expect(formatFileSize(1024 * 99)).toBe('99 KB');
+ });
+
+ it('scales up to TB and stops there', () => {
+ expect(formatFileSize(1024 ** 4)).toBe('1.0 TB');
+ expect(formatFileSize(1024 ** 4 * 5000)).toMatch(/TB$/);
+ });
+});
+
+describe('formatModified', () => {
+ const NOW = new Date('2026-04-28T12:00:00Z').getTime();
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('returns empty for missing/invalid input', () => {
+ expect(formatModified(undefined)).toBe('');
+ expect(formatModified('not-a-date')).toBe('');
+ });
+
+ it('handles "just now"', () => {
+ expect(formatModified(new Date(NOW - 10_000))).toBe('just now');
+ });
+
+ it('formats minutes / hours / days within a week', () => {
+ expect(formatModified(new Date(NOW - 5 * 60_000))).toBe('5m ago');
+ expect(formatModified(new Date(NOW - 3 * 60 * 60_000))).toBe('3h ago');
+ expect(formatModified(new Date(NOW - 4 * 24 * 60 * 60_000))).toBe('4d ago');
+ });
+
+ it('falls back to locale date for older entries', () => {
+ const old = new Date(NOW - 14 * 24 * 60 * 60_000);
+
+ expect(formatModified(old)).toBe(old.toLocaleDateString());
+ });
+
+ it('accepts ISO strings', () => {
+ const iso = new Date(NOW - 10 * 60_000).toISOString();
+
+ expect(formatModified(iso)).toBe('10m ago');
+ });
+});
+
+describe('normalizeRootGroups', () => {
+ it('returns input reference when nothing needs trimming', () => {
+ const groups: FileManagerRootGroup[] = [
+ { id: 'a', label: 'A', pathPrefix: 'uploads' },
+ ];
+
+ expect(normalizeRootGroups(groups)).toBe(groups);
+ });
+
+ it('trims trailing slashes from pathPrefix', () => {
+ const groups: FileManagerRootGroup[] = [
+ { id: 'a', label: 'A', pathPrefix: 'uploads/' },
+ { id: 'b', label: 'B', pathPrefix: 'container///' },
+ ];
+ const normalized = normalizeRootGroups(groups);
+
+ expect(normalized).not.toBe(groups);
+ expect(normalized?.map((g) => g.pathPrefix)).toEqual(['uploads', 'container']);
+ });
+
+ it('passes through empty/undefined', () => {
+ expect(normalizeRootGroups(undefined)).toBeUndefined();
+ expect(normalizeRootGroups([])).toEqual([]);
+ });
+});
+
+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);
+ });
+
+ it('creates intermediate folders for nested files', () => {
+ const tree = buildFileManagerTree([file('foo/bar/baz.txt')]);
+
+ expect(tree).toHaveLength(1);
+ expect(tree[0]!.path).toBe('foo');
+ expect(tree[0]!.isDir).toBe(true);
+ expect(tree[0]!.children[0]!.path).toBe('foo/bar');
+ expect(tree[0]!.children[0]!.children[0]!.path).toBe('foo/bar/baz.txt');
+ });
+
+ it('places files into matching root groups', () => {
+ const groups: FileManagerRootGroup[] = [
+ { defaultOpen: true, id: 'uploads', label: 'Uploads', pathPrefix: 'uploads' },
+ { defaultOpen: true, id: 'container', label: 'Container', pathPrefix: 'container' },
+ ];
+ const tree = buildFileManagerTree(
+ [file('uploads/a.txt'), file('container/sub/b.txt'), file('orphan.txt')],
+ groups,
+ );
+
+ expect(tree).toHaveLength(2);
+ expect(tree[0]!.isGroupRoot).toBe(true);
+ expect(tree[0]!.children.map((c) => c.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');
+ });
+
+ it('promotes a real directory entry over a synthetic placeholder while keeping descendants', () => {
+ const tree = buildFileManagerTree([
+ file('foo/bar.txt'),
+ dir('foo', { id: 'real-foo', modifiedAt: '2026-04-01T00:00:00Z' }),
+ ]);
+
+ expect(tree).toHaveLength(1);
+ expect(tree[0]!.id).toBe('real-foo');
+ expect(tree[0]!.modifiedAt).toBe('2026-04-01T00:00:00Z');
+ expect(tree[0]!.children).toHaveLength(1);
+ expect(tree[0]!.children[0]!.path).toBe('foo/bar.txt');
+ });
+
+ it('tolerates trailing slashes in group pathPrefix', () => {
+ const tree = buildFileManagerTree(
+ [file('uploads/a.txt')],
+ [{ id: 'u', label: 'Uploads', pathPrefix: 'uploads/' }],
+ );
+
+ expect(tree[0]!.children[0]!.path).toBe('uploads/a.txt');
+ });
+
+ it('skips files outside any defined group', () => {
+ const tree = buildFileManagerTree(
+ [file('orphan.txt')],
+ [{ id: 'u', label: 'Uploads', pathPrefix: 'uploads' }],
+ );
+
+ expect(tree[0]!.children).toEqual([]);
+ });
+});
+
+describe('collectAllFilePaths', () => {
+ it('returns only file paths (no directories, no group roots)', () => {
+ const tree = buildFileManagerTree(
+ [file('a/b.txt'), file('a/c.txt'), file('d/e.txt')],
+ [
+ { id: 'a', label: 'A', pathPrefix: 'a' },
+ { id: 'd', label: 'D', pathPrefix: 'd' },
+ ],
+ );
+
+ expect(collectAllFilePaths(tree).sort()).toEqual(['a/b.txt', 'a/c.txt', 'd/e.txt']);
+ });
+
+ it('omits synthetic intermediate directories from the result', () => {
+ const tree = buildFileManagerTree([file('foo/bar/baz.txt')]);
+
+ expect(collectAllFilePaths(tree)).toEqual(['foo/bar/baz.txt']);
+ });
+});
+
+describe('collectVisibleFlat', () => {
+ it('walks only expanded directories', () => {
+ const tree = buildFileManagerTree([file('a/b.txt'), file('c.txt')]);
+ const expanded = new Set<string>();
+
+ expect(collectVisibleFlat(tree, expanded)).toEqual(['a', 'c.txt']);
+ expanded.add('a');
+ expect(collectVisibleFlat(tree, expanded)).toEqual(['a', 'a/b.txt', 'c.txt']);
+ });
+});
+
+describe('filterFileManagerTree', () => {
+ const tree: FileManagerInternalNode[] = buildFileManagerTree([
+ file('foo/bar.txt'),
+ file('foo/baz.md'),
+ file('readme.md'),
+ ]);
+
+ it('returns input unchanged when query is empty', () => {
+ expect(filterFileManagerTree(tree, '')).toBe(tree);
+ });
+
+ it('keeps matched files and their ancestors', () => {
+ const filtered = filterFileManagerTree(tree, 'bar');
+
+ expect(filtered).toHaveLength(1);
+ expect(filtered[0]!.path).toBe('foo');
+ expect(filtered[0]!.children.map((c) => c.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']);
+ });
+
+ it('matches case-insensitively against name and path', () => {
+ expect(filterFileManagerTree(tree, 'README')).toHaveLength(1);
+ expect(filterFileManagerTree(tree, 'README')[0]!.path).toBe('readme.md');
+ });
+});
+
+describe('collectDirectoryPaths', () => {
+ it('returns directory paths in DFS order', () => {
+ const tree = buildFileManagerTree([file('a/b/c.txt'), file('d.txt')]);
+
+ expect(collectDirectoryPaths(tree)).toEqual(['a', 'a/b']);
+ });
+});
+
+describe('resolveSelectionModifier', () => {
+ const makeEvent = (init: { ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean }) =>
+ ({
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ ...init,
+ }) as unknown as MouseEvent;
+
+ it('detects shift as range', () => {
+ expect(resolveSelectionModifier(makeEvent({ shiftKey: true }))).toBe('range');
+ });
+
+ it('detects meta/ctrl as toggle', () => {
+ expect(resolveSelectionModifier(makeEvent({ metaKey: true }))).toBe('toggle');
+ expect(resolveSelectionModifier(makeEvent({ ctrlKey: true }))).toBe('toggle');
+ });
+
+ it('falls back to single', () => {
+ expect(resolveSelectionModifier(makeEvent({}))).toBe('single');
+ });
+});
+
+describe('buildFileManagerGridTemplate', () => {
+ it('always includes checkbox column and name column', () => {
+ expect(buildFileManagerGridTemplate(false, false, false)).toBe('auto minmax(0,1fr)');
+ });
+
+ it('appends optional columns in order', () => {
+ expect(buildFileManagerGridTemplate(true, true, true)).toBe('auto minmax(0,1fr) auto auto auto');
+ });
+});
+
+describe('findNodeByPath', () => {
+ const tree = buildFileManagerTree([file('foo/bar.txt')]);
+
+ it('finds nested nodes', () => {
+ expect(findNodeByPath(tree, 'foo/bar.txt')?.path).toBe('foo/bar.txt');
+ });
+
+ it('returns undefined for missing paths', () => {
+ expect(findNodeByPath(tree, 'nope')).toBeUndefined();
+ });
+});
+
+describe('dedupeOverlappingPaths', () => {
+ it('drops descendants when an ancestor is selected', () => {
+ const result = dedupeOverlappingPaths(['foo/bar', 'foo', 'foo/baz/qux', 'other']);
+
+ expect(result.sort()).toEqual(['foo', 'other']);
+ });
+
+ it('preserves non-overlapping siblings', () => {
+ expect(dedupeOverlappingPaths(['a/b', 'a/c']).sort()).toEqual(['a/b', 'a/c']);
+ });
+
+ it('handles duplicates', () => {
+ expect(dedupeOverlappingPaths(['foo', 'foo'])).toEqual(['foo']);
+ });
+
+ it('does not match by prefix-only (foobar is not a child of foo)', () => {
+ expect(dedupeOverlappingPaths(['foo', 'foobar']).sort()).toEqual(['foo', 'foobar']);
+ });
+});
diff --git a/frontend/src/components/file-manager/file-manager-utils.ts b/frontend/src/components/file-manager/file-manager-utils.ts
new file mode 100644
index 00000000..3cdb371e
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager-utils.ts
@@ -0,0 +1,390 @@
+import type { MouseEvent as ReactMouseEvent } from 'react';
+
+import type { FileManagerInternalNode, FileManagerRootGroup, FileNode } from './file-manager-types';
+
+export const formatFileSize = (size?: number): string => {
+ if (size == null) {
+ return '';
+ }
+
+ if (size < 1024) {
+ return `${size} B`;
+ }
+
+ const units = ['KB', 'MB', 'GB', 'TB'];
+ let unitIndex = -1;
+ let value = size;
+
+ while (value >= 1024 && unitIndex < units.length - 1) {
+ value /= 1024;
+ unitIndex += 1;
+ }
+
+ return `${value.toFixed(value >= 10 ? 0 : 1)} ${units[unitIndex]}`;
+};
+
+export const formatModified = (modifiedAt?: Date | string): string => {
+ if (!modifiedAt) {
+ return '';
+ }
+
+ const date = typeof modifiedAt === 'string' ? new Date(modifiedAt) : modifiedAt;
+
+ if (Number.isNaN(date.getTime())) {
+ return '';
+ }
+
+ const now = Date.now();
+ const diffMs = now - date.getTime();
+ const diffMin = Math.round(diffMs / 60_000);
+
+ if (diffMin < 1) {
+ return 'just now';
+ }
+
+ if (diffMin < 60) {
+ return `${diffMin}m ago`;
+ }
+
+ const diffHours = Math.round(diffMin / 60);
+
+ if (diffHours < 24) {
+ return `${diffHours}h ago`;
+ }
+
+ const diffDays = Math.round(diffHours / 24);
+
+ if (diffDays < 7) {
+ return `${diffDays}d ago`;
+ }
+
+ return date.toLocaleDateString();
+};
+
+/** Strip trailing slashes from a `pathPrefix`. Empty / `'/'` collapse to `''`. */
+const stripTrailingSlash = (input: string): string => input.replace(/\/+$/, '');
+
+/**
+ * Normalize root groups once: trim trailing slashes from `pathPrefix`.
+ * Returning the original reference when nothing changed lets `useMemo` keep identity.
+ */
+export const normalizeRootGroups = (
+ rootGroups: FileManagerRootGroup[] | undefined,
+): FileManagerRootGroup[] | undefined => {
+ if (!rootGroups?.length) {
+ return rootGroups;
+ }
+
+ let mutated = false;
+ const normalized = rootGroups.map((group) => {
+ const trimmed = stripTrailingSlash(group.pathPrefix);
+
+ if (trimmed === group.pathPrefix) {
+ return group;
+ }
+
+ mutated = true;
+
+ return { ...group, pathPrefix: trimmed };
+ });
+
+ return mutated ? normalized : rootGroups;
+};
+
+const buildSyntheticGroupRoot = (group: FileManagerRootGroup): FileManagerInternalNode => ({
+ children: [],
+ depth: 0,
+ groupIcon: group.icon,
+ id: `__group__${group.id}`,
+ isDir: true,
+ isGroupRoot: true,
+ name: group.label,
+ path: group.pathPrefix,
+});
+
+const buildSyntheticFolder = (folderPath: string, folderName: string, depth: number): FileManagerInternalNode => ({
+ children: [],
+ depth,
+ id: `__dir__${folderPath}`,
+ isDir: true,
+ name: folderName,
+ path: folderPath,
+});
+
+const findGroupIndexForFile = (path: string, groups: FileManagerRootGroup[]): number =>
+ groups.findIndex((group) => path === group.pathPrefix || path.startsWith(`${group.pathPrefix}/`));
+
+export const buildFileManagerTree = (
+ files: FileNode[],
+ rootGroups?: FileManagerRootGroup[],
+): FileManagerInternalNode[] => {
+ const sorted = [...files].sort((a, b) => a.path.localeCompare(b.path));
+ const groups = normalizeRootGroups(rootGroups);
+ const roots: FileManagerInternalNode[] = groups?.length ? groups.map(buildSyntheticGroupRoot) : [];
+
+ // O(1) folder lookup by absolute path; replaces O(n) `siblings.find(...)`.
+ const folderByPath = new Map<string, FileManagerInternalNode>();
+
+ for (const file of sorted) {
+ const segments = file.path.split('/').filter(Boolean);
+
+ if (segments.length === 0) {
+ continue;
+ }
+
+ let siblings: FileManagerInternalNode[];
+ let startIndex: number;
+ let baseDepth: number;
+
+ if (groups?.length) {
+ const groupIndex = findGroupIndexForFile(file.path, groups);
+
+ if (groupIndex < 0) {
+ continue;
+ }
+
+ const groupRoot = roots[groupIndex];
+
+ if (!groupRoot) {
+ continue;
+ }
+
+ siblings = groupRoot.children;
+ startIndex = 1;
+ baseDepth = 1;
+ } else {
+ siblings = roots;
+ startIndex = 0;
+ baseDepth = 0;
+ }
+
+ for (let i = startIndex; i < segments.length - 1; i += 1) {
+ const folderName = segments[i] ?? '';
+ const folderPath = segments.slice(0, i + 1).join('/');
+
+ let folder = folderByPath.get(folderPath);
+
+ if (!folder) {
+ folder = buildSyntheticFolder(folderPath, folderName, baseDepth + (i - startIndex));
+ folderByPath.set(folderPath, folder);
+ siblings.push(folder);
+ }
+
+ siblings = folder.children;
+ }
+
+ const lastDepth = baseDepth + (segments.length - 1 - startIndex);
+ 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.
+ Object.assign(existingFolder, file, { children: existingFolder.children, depth: lastDepth });
+ } else {
+ const node: FileManagerInternalNode = { ...file, children: [], depth: lastDepth };
+
+ siblings.push(node);
+
+ if (file.isDir) {
+ folderByPath.set(file.path, node);
+ }
+ }
+ }
+
+ return roots;
+};
+
+/**
+ * Collect paths of *file* nodes only (no synthetic group roots, no directories).
+ * Used as the universe for "select all".
+ */
+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);
+ }
+ }
+
+ return result;
+};
+
+/** 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) {
+ collectAllNodePaths(node.children, result);
+ }
+ }
+
+ return result;
+};
+
+export const collectVisibleFlat = (
+ nodes: FileManagerInternalNode[],
+ expandedPaths: Set<string>,
+ result: string[] = [],
+): string[] => {
+ for (const node of nodes) {
+ result.push(node.path);
+
+ if (node.isDir && expandedPaths.has(node.path) && node.children.length > 0) {
+ collectVisibleFlat(node.children, expandedPaths, result);
+ }
+ }
+
+ return result;
+};
+
+/**
+ * Filter the tree so it only contains:
+ * - nodes whose `name` or `path` matches the query,
+ * - all descendants of a matching node (so the user sees what's inside a matching folder),
+ * - 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[] => {
+ const trimmed = query.trim();
+
+ if (!trimmed) {
+ return nodes;
+ }
+
+ const lower = trimmed.toLowerCase();
+
+ const filterNode = (
+ node: FileManagerInternalNode,
+ ancestorMatched: boolean,
+ ): FileManagerInternalNode | null => {
+ if (node.isGroupRoot) {
+ const keptChildren = node.children
+ .map((child) => filterNode(child, false))
+ .filter((child): child is FileManagerInternalNode => child !== null);
+
+ return keptChildren.length > 0 ? { ...node, children: keptChildren } : null;
+ }
+
+ const selfMatched =
+ ancestorMatched ||
+ node.name.toLowerCase().includes(lower) ||
+ node.path.toLowerCase().includes(lower);
+
+ if (!node.isDir) {
+ return selfMatched ? node : null;
+ }
+
+ const keptChildren = node.children
+ .map((child) => filterNode(child, selfMatched))
+ .filter((child): child is FileManagerInternalNode => child !== null);
+
+ if (selfMatched) {
+ return { ...node, children: keptChildren };
+ }
+
+ return keptChildren.length > 0 ? { ...node, children: keptChildren } : null;
+ };
+
+ return nodes
+ .map((node) => filterNode(node, false))
+ .filter((node): node is FileManagerInternalNode => node !== null);
+};
+
+/** 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 resolveSelectionModifier = (
+ event: KeyboardEvent | MouseEvent | ReactMouseEvent,
+): 'range' | 'single' | 'toggle' => {
+ if (event.shiftKey) {
+ return 'range';
+ }
+
+ if (event.metaKey || event.ctrlKey) {
+ return 'toggle';
+ }
+
+ return 'single';
+};
+
+export const buildFileManagerGridTemplate = (showSize: boolean, showModified: boolean, hasActions: boolean): string => {
+ const cols = ['auto', 'minmax(0,1fr)'];
+
+ if (showSize) {
+ cols.push('auto');
+ }
+
+ if (showModified) {
+ cols.push('auto');
+ }
+
+ if (hasActions) {
+ cols.push('auto');
+ }
+
+ return cols.join(' ');
+};
+
+/** Recursively locate a node by its absolute path. Returns `undefined` when missing. */
+export const findNodeByPath = (
+ nodes: FileManagerInternalNode[],
+ path: string,
+): FileManagerInternalNode | undefined => {
+ for (const node of nodes) {
+ if (node.path === path) {
+ return node;
+ }
+
+ if (node.children.length > 0) {
+ const found = findNodeByPath(node.children, path);
+
+ if (found) {
+ return found;
+ }
+ }
+ }
+
+ return undefined;
+};
+
+/**
+ * Drop paths whose ancestor is also in the set, so bulk operations don't double-process
+ * a directory and its descendants (caller deletes the parent only).
+ */
+export const dedupeOverlappingPaths = (paths: Iterable<string>): string[] => {
+ const sorted = [...paths].sort();
+ const result: string[] = [];
+
+ for (const path of sorted) {
+ const last = result[result.length - 1];
+
+ if (last && (path === last || path.startsWith(`${last}/`))) {
+ continue;
+ }
+
+ result.push(path);
+ }
+
+ return result;
+};
diff --git a/frontend/src/components/file-manager/file-manager.tsx b/frontend/src/components/file-manager/file-manager.tsx
new file mode 100644
index 00000000..0bd1e8aa
--- /dev/null
+++ b/frontend/src/components/file-manager/file-manager.tsx
@@ -0,0 +1,358 @@
+import { Trash2 } from 'lucide-react';
+import {
+ Fragment,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type ReactNode,
+ 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 { FileManagerRow } from './file-manager-row';
+import { FileManagerSkeleton } from './file-manager-skeleton';
+import {
+ buildFileManagerGridTemplate,
+ buildFileManagerTree,
+ collectAllFilePaths,
+ collectVisibleFlat,
+ dedupeOverlappingPaths,
+ filterFileManagerTree,
+ findNodeByPath,
+ normalizeRootGroups,
+} from './file-manager-utils';
+import { useFileManagerExpansion } from './use-file-manager-expansion';
+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,
+ emptyState,
+ files,
+ isLoading,
+ onBulkDelete,
+ rootGroups,
+ searchEmptyState,
+ searchQuery,
+ showModifiedColumn = true,
+ showSizeColumn = true,
+}: FileManagerProps) => {
+ const normalizedRootGroups = useMemo(() => normalizeRootGroups(rootGroups), [rootGroups]);
+
+ const fullTree = useMemo(
+ () => buildFileManagerTree(files, normalizedRootGroups),
+ [files, normalizedRootGroups],
+ );
+
+ const trimmedSearch = searchQuery?.trim() ?? '';
+ const isFiltering = trimmedSearch.length > 0;
+
+ const visibleTree = useMemo(
+ () => (isFiltering ? filterFileManagerTree(fullTree, trimmedSearch) : fullTree),
+ [fullTree, isFiltering, trimmedSearch],
+ );
+
+ const allFilePaths = useMemo(() => collectAllFilePaths(visibleTree), [visibleTree]);
+
+ const { expandedPaths, toggleExpand } = useFileManagerExpansion({
+ isFiltering,
+ normalizedRootGroups,
+ visibleTree,
+ });
+
+ const flatVisible = useMemo(() => collectVisibleFlat(visibleTree, expandedPaths), [visibleTree, expandedPaths]);
+
+ const {
+ clearSelection,
+ isAllSelected,
+ isSomeSelected,
+ onRowClick,
+ onToggleCheckbox,
+ selectedPaths,
+ setSelection,
+ toggleSelectAll,
+ } = useFileManagerSelection({ allFilePaths, flatVisible });
+
+ const showCheckbox = !!onBulkDelete;
+ const hasActions = !!actions?.length;
+ const gridTemplate = useMemo(
+ () => buildFileManagerGridTemplate(showSizeColumn, showModifiedColumn, hasActions),
+ [hasActions, showModifiedColumn, showSizeColumn],
+ );
+
+ 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(() => {
+ if (activeRowPath && flatVisible.includes(activeRowPath)) {
+ return activeRowPath;
+ }
+
+ return flatVisible[0] ?? null;
+ }, [activeRowPath, flatVisible]);
+
+ const focusRow = useCallback((path: null | string) => {
+ if (!path) {
+ return;
+ }
+
+ const next = containerRef.current?.querySelector<HTMLElement>(
+ `[role="treeitem"][data-path="${CSS.escape(path)}"]`,
+ );
+
+ next?.focus();
+ }, []);
+
+ const handleRowFocus = useCallback((path: string) => {
+ 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);
+
+ return;
+ default:
+ return;
+ }
+ },
+ [
+ clearSelection,
+ effectiveActiveRow,
+ expandedPaths,
+ flatVisible,
+ focusRow,
+ onToggleCheckbox,
+ showCheckbox,
+ toggleExpand,
+ toggleSelectAll,
+ visibleTree,
+ ],
+ );
+
+ 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}>
+ <FileManagerSkeleton />
+ </div>
+ );
+ }
+
+ if (files.length === 0) {
+ return <div className={className}>{emptyState}</div>;
+ }
+
+ if (isFiltering && visibleTree.length === 0) {
+ return <div className={className}>{searchEmptyState ?? 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>
+ );
+ };
+
+ return (
+ <div
+ className={cn('bg-card flex flex-col overflow-hidden rounded-lg border', className)}
+ onClick={(event) => {
+ if (event.target === event.currentTarget) {
+ clearSelection();
+ }
+ }}
+ 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 ? (
+ <Checkbox
+ aria-label="Select all"
+ checked={isAllSelected ? true : isSomeSelected ? 'indeterminate' : false}
+ onCheckedChange={toggleSelectAll}
+ />
+ ) : (
+ <span className="size-4" />
+ )}
+ <span>Name</span>
+ {showSizeColumn && <span>Size</span>}
+ {showModifiedColumn && <span>Modified</span>}
+ {hasActions && <span className="size-7" />}
+ </div>
+
+ <div
+ aria-label="File tree"
+ className="flex flex-1 flex-col overflow-y-auto py-1"
+ role="tree"
+ >
+ {visibleTree.map(renderNode)}
+ </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}`}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/components/file-manager/index.ts b/frontend/src/components/file-manager/index.ts
new file mode 100644
index 00000000..9010f9da
--- /dev/null
+++ b/frontend/src/components/file-manager/index.ts
@@ -0,0 +1,10 @@
+export { FileManager } from './file-manager';
+export { copyPathAction, deleteAction, downloadAction } from './file-manager-actions';
+export { getFileTypeIcon } from './file-manager-icons';
+export type { FileTypeIcon } from './file-manager-icons';
+export type {
+ FileManagerAction,
+ FileManagerProps,
+ FileManagerRootGroup,
+ FileNode,
+} from './file-manager-types';
diff --git a/frontend/src/components/file-manager/use-file-manager-expansion.ts b/frontend/src/components/file-manager/use-file-manager-expansion.ts
new file mode 100644
index 00000000..4a136caf
--- /dev/null
+++ b/frontend/src/components/file-manager/use-file-manager-expansion.ts
@@ -0,0 +1,75 @@
+import { useCallback, useMemo, useState } from 'react';
+
+import type { FileManagerInternalNode, FileManagerRootGroup } from './file-manager-types';
+
+import { 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. */
+ toggleExpand: (path: string, wasExpanded: boolean) => void;
+}
+
+interface UseFileManagerExpansionArgs {
+ isFiltering: boolean;
+ /** Already-normalized root groups (pathPrefix without trailing slash). */
+ normalizedRootGroups: FileManagerRootGroup[] | undefined;
+ visibleTree: FileManagerInternalNode[];
+}
+
+/**
+ * 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:
+ * 1) `rootGroups[].defaultOpen` — initial group expansion,
+ * 2) on-search auto-expansion of every directory inside the filtered tree.
+ */
+export const useFileManagerExpansion = ({
+ isFiltering,
+ normalizedRootGroups,
+ visibleTree,
+}: UseFileManagerExpansionArgs): UseFileManagerExpansion => {
+ const [overrides, setOverrides] = useState<Map<string, ExpansionOverride>>(() => new Map());
+
+ const expandedPaths = useMemo(() => {
+ const result = new Set<string>();
+
+ if (normalizedRootGroups?.length) {
+ for (const group of normalizedRootGroups) {
+ if (group.defaultOpen ?? true) {
+ result.add(group.pathPrefix);
+ }
+ }
+ }
+
+ if (isFiltering) {
+ for (const dirPath of collectDirectoryPaths(visibleTree)) {
+ result.add(dirPath);
+ }
+ }
+
+ for (const [path, override] of overrides) {
+ if (override === 'force-expanded') {
+ result.add(path);
+ } else {
+ result.delete(path);
+ }
+ }
+
+ return result;
+ }, [isFiltering, normalizedRootGroups, overrides, visibleTree]);
+
+ const toggleExpand = useCallback((path: string, wasExpanded: boolean) => {
+ setOverrides((prev) => {
+ const next = new Map(prev);
+
+ next.set(path, wasExpanded ? 'force-collapsed' : 'force-expanded');
+
+ return next;
+ });
+ }, []);
+
+ return { expandedPaths, toggleExpand };
+};
diff --git a/frontend/src/components/file-manager/use-file-manager-selection.ts b/frontend/src/components/file-manager/use-file-manager-selection.ts
new file mode 100644
index 00000000..26473d96
--- /dev/null
+++ b/frontend/src/components/file-manager/use-file-manager-selection.ts
@@ -0,0 +1,153 @@
+import { type MouseEvent as ReactMouseEvent, useCallback, useMemo, useRef, useState } from 'react';
+
+import { resolveSelectionModifier } from './file-manager-utils';
+
+interface UseFileManagerSelection {
+ clearSelection: () => void;
+ /** True when every selectable file is currently selected. */
+ readonly isAllSelected: boolean;
+ /** True when at least one — but not all — files are selected. */
+ readonly isSomeSelected: boolean;
+ /**
+ * Click handler honoring single / toggle / range semantics.
+ * Range computed against the supplied `flatVisible` order.
+ */
+ onRowClick: (event: ReactMouseEvent, path: string) => void;
+ /** Toggle a single path — used by checkboxes. */
+ onToggleCheckbox: (path: string) => void;
+ selectedPaths: Set<string>;
+ /** Replace entire selection. */
+ setSelection: (paths: Set<string>) => void;
+ /** Toggle "select all": clears if everything was selected, otherwise picks every file. */
+ toggleSelectAll: () => void;
+}
+
+interface UseFileManagerSelectionArgs {
+ /** Universe of selectable file paths in the *visible* tree. */
+ allFilePaths: string[];
+ /** Visible nodes in DFS order — used for shift-range selection. */
+ flatVisible: string[];
+}
+
+/**
+ * Selection state without `useEffect`: `rawSelectedPaths` may contain stale entries
+ * after files change; we derive a pruned `selectedPaths` during render. The pruned
+ * Set keeps reference identity when nothing was stripped, so memoized consumers
+ * downstream don't re-render needlessly.
+ */
+export const useFileManagerSelection = ({
+ allFilePaths,
+ flatVisible,
+}: UseFileManagerSelectionArgs): UseFileManagerSelection => {
+ const [rawSelectedPaths, setRawSelectedPaths] = useState<Set<string>>(() => new Set());
+ const lastClickedRef = useRef<null | string>(null);
+
+ const allFilePathsSet = useMemo(() => new Set(allFilePaths), [allFilePaths]);
+
+ const selectedPaths = useMemo(() => {
+ if (rawSelectedPaths.size === 0) {
+ return rawSelectedPaths;
+ }
+
+ let allValid = true;
+ const valid = new Set<string>();
+
+ for (const path of rawSelectedPaths) {
+ if (allFilePathsSet.has(path)) {
+ valid.add(path);
+ } else {
+ allValid = false;
+ }
+ }
+
+ return allValid ? rawSelectedPaths : valid;
+ }, [allFilePathsSet, rawSelectedPaths]);
+
+ const onRowClick = useCallback(
+ (event: ReactMouseEvent, path: string) => {
+ const modifier = resolveSelectionModifier(event);
+
+ setRawSelectedPaths((prev) => {
+ if (modifier === 'single') {
+ lastClickedRef.current = path;
+
+ return new Set([path]);
+ }
+
+ if (modifier === 'toggle') {
+ const next = new Set(prev);
+
+ if (next.has(path)) {
+ next.delete(path);
+ } else {
+ next.add(path);
+ }
+
+ lastClickedRef.current = path;
+
+ return next;
+ }
+
+ if (!lastClickedRef.current) {
+ lastClickedRef.current = path;
+
+ return new Set([path]);
+ }
+
+ const fromIdx = flatVisible.indexOf(lastClickedRef.current);
+ const toIdx = flatVisible.indexOf(path);
+
+ if (fromIdx < 0 || toIdx < 0) {
+ return new Set([path]);
+ }
+
+ const [a, b] = fromIdx <= toIdx ? [fromIdx, toIdx] : [toIdx, fromIdx];
+
+ return new Set(flatVisible.slice(a, b + 1));
+ });
+ },
+ [flatVisible],
+ );
+
+ const onToggleCheckbox = useCallback((path: string) => {
+ setRawSelectedPaths((prev) => {
+ const next = new Set(prev);
+
+ if (next.has(path)) {
+ next.delete(path);
+ } else {
+ next.add(path);
+ }
+
+ lastClickedRef.current = path;
+
+ return next;
+ });
+ }, []);
+
+ const isAllSelected = allFilePaths.length > 0 && selectedPaths.size === allFilePaths.length;
+ const isSomeSelected = selectedPaths.size > 0 && !isAllSelected;
+
+ const toggleSelectAll = useCallback(() => {
+ setRawSelectedPaths(() => (isAllSelected ? new Set() : new Set(allFilePaths)));
+ }, [allFilePaths, isAllSelected]);
+
+ const clearSelection = useCallback(() => {
+ setRawSelectedPaths((prev) => (prev.size === 0 ? prev : new Set()));
+ }, []);
+
+ const setSelection = useCallback((paths: Set<string>) => {
+ setRawSelectedPaths(paths);
+ }, []);
+
+ return {
+ clearSelection,
+ isAllSelected,
+ isSomeSelected,
+ onRowClick,
+ onToggleCheckbox,
+ selectedPaths,
+ setSelection,
+ toggleSelectAll,
+ };
+};
diff --git a/frontend/src/components/ui/checkbox.tsx b/frontend/src/components/ui/checkbox.tsx
new file mode 100644
index 00000000..c26e2ba2
--- /dev/null
+++ b/frontend/src/components/ui/checkbox.tsx
@@ -0,0 +1,26 @@
+import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
+import { Check } from 'lucide-react';
+import * as React from 'react';
+
+import { cn } from '@/lib/utils';
+
+const Checkbox = React.forwardRef<
+ React.ElementRef<typeof CheckboxPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <CheckboxPrimitive.Root
+ className={cn(
+ 'peer border-primary focus-visible:ring-ring data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground grid h-4 w-4 shrink-0 place-content-center rounded-sm border shadow focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50',
+ className,
+ )}
+ ref={ref}
+ {...props}
+ >
+ <CheckboxPrimitive.Indicator className={cn('grid place-content-center text-current')}>
+ <Check className="h-4 w-4" />
+ </CheckboxPrimitive.Indicator>
+ </CheckboxPrimitive.Root>
+));
+Checkbox.displayName = CheckboxPrimitive.Root.displayName;
+
+export { Checkbox };