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
feat(file-manager): extensible bulk actions API and additive shift-click selection
Sergey Kozyrenko0c6557906693
diff --git a/frontend/src/components/file-manager/file-manager-actions.tsx b/frontend/src/components/file-manager/file-manager-actions.tsxindex b555d704..7e853a10 100644--- a/frontend/src/components/file-manager/file-manager-actions.tsx+++ b/frontend/src/components/file-manager/file-manager-actions.tsx@@ -1,6 +1,6 @@-import { Copy, Download, Trash2 } from 'lucide-react';+import { BookmarkPlus, ClipboardCopy, Copy, Download, FileSymlink, Trash2 } from 'lucide-react';-import type { FileManagerAction, FileNode } from './file-manager-types';+import type { FileManagerAction, FileManagerBulkAction, FileNode } from './file-manager-types';/*** Built-in download action.@@ -47,3 +47,110 @@ export const deleteAction = (onDelete: (file: FileNode) => void): FileManagerActonSelect: onDelete,separatorBefore: true,});++// ── Bulk-action helpers ─────────────────────────────────────────────────────+//+// Each helper produces a `FileManagerBulkAction` with sensible defaults; the+// caller passes any callback / config it needs and lets the bar handle the+// rendering, confirmation and dedup. Mirrors the row-action helpers above so+// consumers compose `bulkActions={[bulkXAction(...), bulkYAction(...)]}` the+// same way they compose `actions={[xAction(...), yAction(...)]}`.++interface BulkDeleteOptions {+ /** Confirm-dialog body formatter. Default: "This will delete N items. This action cannot be undone." */+ confirmDescription?: (countLabel: string) => string;+ /** Confirm-button label. Default: action `label`. */+ confirmText?: string;+ /** Confirm-dialog title formatter. Default: "Delete N items". */+ confirmTitle?: (countLabel: string) => string;+ /** Trigger label in the bar. Default: "Delete". */+ label?: string;+}++/**+ * Built-in bulk delete. Wraps the destructive variant + confirm dialog so callers+ * just supply the API call. Always shown as a standalone (non-overflow) button so+ * the destructive intent stays visible.+ */+export const bulkDeleteAction = (+ onDelete: (files: FileNode[]) => Promise<void> | void,+ options: BulkDeleteOptions = {},+): FileManagerBulkAction => {+ const label = options.label ?? 'Delete';++ return {+ confirm: {+ confirmText: options.confirmText ?? label,+ description:+ options.confirmDescription ??+ ((countLabel) => `This will delete ${countLabel}. This action cannot be undone.`),+ title: options.confirmTitle ?? ((countLabel) => `Delete ${countLabel}`),+ },+ icon: Trash2,+ id: '__builtin_bulk_delete',+ label,+ onSelect: onDelete,+ variant: 'destructive',+ };+};++/**+ * Built-in "copy paths" bulk action. Joins every selected file's `path` with `\n`+ * and hands the resulting string to `onCopy`. Lives in the overflow menu by default+ * so it doesn't crowd the bar — pass `overflow: false` to promote it to a button.+ */+export const bulkCopyPathsAction = (+ onCopy: (paths: string[]) => Promise<void> | void,+ options: { label?: string; overflow?: boolean } = {},+): FileManagerBulkAction => ({+ icon: ClipboardCopy,+ id: '__builtin_bulk_copy_paths',+ label: options.label ?? 'Copy paths',+ onSelect: (files) => onCopy(files.map((file) => file.path)),+ overflow: options.overflow ?? true,+});++/**+ * Built-in "move to…" bulk action. The host opens its own destination picker+ * inside `onMove` (we don't ship a path-picker UI inside the file-manager).+ */+export const bulkMoveAction = (+ onMove: (files: FileNode[]) => void,+ options: { label?: string; overflow?: boolean } = {},+): FileManagerBulkAction => ({+ icon: FileSymlink,+ id: '__builtin_bulk_move',+ label: options.label ?? 'Move to…',+ onSelect: onMove,+ overflow: options.overflow,+});++/**+ * Built-in "copy to…" bulk action. The host opens its own destination picker+ * inside `onCopy`.+ */+export const bulkCopyAction = (+ onCopy: (files: FileNode[]) => void,+ options: { label?: string; overflow?: boolean } = {},+): FileManagerBulkAction => ({+ icon: Copy,+ id: '__builtin_bulk_copy',+ label: options.label ?? 'Copy to…',+ onSelect: onCopy,+ overflow: options.overflow,+});++/**+ * Built-in "save as resource" bulk action used by Flow Files. Identical shape to+ * `bulkMoveAction` — the host opens its own promote dialog inside `onPromote`.+ */+export const bulkPromoteAction = (+ onPromote: (files: FileNode[]) => void,+ options: { label?: string; overflow?: boolean } = {},+): FileManagerBulkAction => ({+ icon: BookmarkPlus,+ id: '__builtin_bulk_promote',+ label: options.label ?? 'Save as resources',+ onSelect: onPromote,+ overflow: options.overflow,+});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.tsxindex 840ec46f..4041811c 100644--- a/frontend/src/components/file-manager/file-manager-bulk-actions-bar.tsx+++ b/frontend/src/components/file-manager/file-manager-bulk-actions-bar.tsx@@ -1,67 +1,138 @@-import { Trash2 } from 'lucide-react';-import { useCallback, useState } from 'react';+import { MoreHorizontal } from 'lucide-react';+import { type ComponentType, useCallback, useMemo, useState } from 'react';import ConfirmationDialog from '@/components/shared/confirmation-dialog';import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { cn } from '@/lib/utils';-import type { FileManagerLabels, FileNode } from './file-manager-types';+import type { FileManagerBulkAction, FileManagerLabels, FileNode } from './file-manager-types';-import { dedupeOverlappingPaths, pluralizeItemsEnglish } from './file-manager-utils';+import { dedupeOverlappingPaths, formatFileSize, pluralizeItemsEnglish } from './file-manager-utils';interface FileManagerBulkActionsBarProps {+ actions: readonly FileManagerBulkAction[];files: FileNode[];labels: FileManagerLabels;- onBulkDelete?: (files: FileNode[]) => Promise<void> | void;onClearSelection: () => void;- onSelectionChange: (paths: Set<string>) => void;selectedPaths: Set<string>;+ /** Cumulative byte count of the deduped selection. `0` suppresses the size suffix. */+ selectionTotalBytes: number;+}++interface ResolvedAction {+ action: FileManagerBulkAction;+ isDisabled: boolean;}/**- * 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.+ * Footer that appears when at least one row is selected. Drives the cancel+ * control plus an arbitrary list of host-supplied bulk actions:+ *+ * - Each action is rendered as a button (or pushed into the trailing `…`+ * overflow menu when `overflow: true`).+ * - Actions with a `confirm` config trigger the shared ConfirmationDialog+ * before invoking `onSelect`. The dialog state is owned here so each host+ * doesn't have to wire its own.+ * - The selection list is **deduped** before being handed to `onSelect` so+ * a directory never ships together with one of its descendants — the+ * caller deletes / moves / etc. only the parent.*/export const FileManagerBulkActionsBar = ({+ actions,files,labels,- onBulkDelete,onClearSelection,- onSelectionChange,selectedPaths,+ selectionTotalBytes,}: FileManagerBulkActionsBarProps) => {- const [isConfirmOpen, setIsConfirmOpen] = useState(false);+ const [pendingAction, setPendingAction] = useState<FileManagerBulkAction | null>(null);++ // Resolve the deduped FileNode[] once per render — every action callback,+ // confirm-dialog title and isDisabled / isHidden predicate share it, so+ // recomputing per call would be wasteful.+ const dedupedFiles = useMemo(() => {+ if (selectedPaths.size === 0) {+ return [];+ }++ const dedupedPathSet = new Set(dedupeOverlappingPaths(selectedPaths));++ return files.filter((file) => dedupedPathSet.has(file.path));+ }, [files, selectedPaths]);++ const visibleActions = useMemo<ResolvedAction[]>(+ () =>+ actions+ .filter((action) => !action.isHidden?.(dedupedFiles))+ .map((action) => ({+ action,+ isDisabled: action.isDisabled?.(dedupedFiles) ?? false,+ })),+ [actions, dedupedFiles],+ );++ const inlineActions = useMemo(() => visibleActions.filter((entry) => !entry.action.overflow), [visibleActions]);+ const overflowActions = useMemo(() => visibleActions.filter((entry) => entry.action.overflow), [visibleActions]);++ const runAction = useCallback(+ async (action: FileManagerBulkAction) => {+ // `dedupedFiles` is captured at click time — the state used by the+ // bar at that moment matches what the host receives, even if the+ // selection mutates while an async confirm is open.+ await action.onSelect(dedupedFiles);+ },+ [dedupedFiles],+ );++ const handleActionClick = useCallback(+ (action: FileManagerBulkAction) => {+ if (action.confirm) {+ setPendingAction(action);++ return;+ }++ void runAction(action);+ },+ [runAction],+ );const handleConfirm = useCallback(async () => {- if (!onBulkDelete) {+ if (!pendingAction) {return;}- const dedupedPaths = new Set(dedupeOverlappingPaths(selectedPaths));- const filesToDelete = files.filter((file) => dedupedPaths.has(file.path));+ await runAction(pendingAction);+ // ConfirmationDialog auto-closes after a fulfilled `handleConfirm`,+ // but we own `pendingAction` separately so the dialog tree fully+ // unmounts on the next tick.+ setPendingAction(null);+ }, [pendingAction, runAction]);- await onBulkDelete(filesToDelete);- onSelectionChange(new Set());- }, [files, onBulkDelete, onSelectionChange, selectedPaths]);-- const handleOpenChange = useCallback((isOpen: boolean) => {+ const handleConfirmOpenChange = useCallback((isOpen: boolean) => {if (!isOpen) {- setIsConfirmOpen(false);+ setPendingAction(null);}}, []);- if (selectedPaths.size === 0) {+ if (selectedPaths.size === 0 || actions.length === 0) {return null;}const pluralize = labels.pluralizeItems ?? pluralizeItemsEnglish;const countLabel = pluralize(selectedPaths.size);- const selectedText = labels.selectedLabel?.(selectedPaths.size) ?? `${selectedPaths.size} selected`;+ const baseSelectedText = labels.selectedLabel?.(selectedPaths.size) ?? `${selectedPaths.size} selected`;+ const sizeSuffix = (labels.formatSelectionSize ?? formatFileSize)(selectionTotalBytes);+ const selectedText = sizeSuffix ? `${baseSelectedText} · ${sizeSuffix}` : baseSelectedText;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.`;+ const moreActionsText = labels.bulkMoreActions ?? 'More actions';return (<>@@ -75,27 +146,102 @@ export const FileManagerBulkActionsBar = ({>{cancelText}</Button>- {onBulkDelete && (- <Button- onClick={() => setIsConfirmOpen(true)}- size="sm"- variant="destructive"- >- <Trash2 className="size-4" />- {confirmText}- </Button>++ {inlineActions.map(({ action, isDisabled }) => (+ <BulkActionButton+ action={action}+ isDisabled={isDisabled}+ key={action.id}+ onClick={handleActionClick}+ />+ ))}++ {overflowActions.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ aria-label={moreActionsText}+ size="icon-sm"+ variant="outline"+ >+ <MoreHorizontal className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {overflowActions.map(({ action, isDisabled }) => (+ <DropdownMenuItem+ className={cn(+ action.variant === 'destructive' &&+ 'text-destructive focus:text-destructive focus:bg-destructive/10',+ )}+ disabled={isDisabled}+ key={action.id}+ onSelect={(event) => {+ event.preventDefault();+ handleActionClick(action);+ }}+ >+ {action.icon ? <action.icon className="size-4" /> : null}+ {action.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>)}</div></div>- <ConfirmationDialog- confirmText={confirmText}- description={descriptionText}- handleConfirm={handleConfirm}- handleOpenChange={handleOpenChange}- isOpen={isConfirmOpen}- title={titleText}- />+ {pendingAction?.confirm && (+ <ConfirmationDialog+ confirmText={pendingAction.confirm.confirmText ?? pendingAction.label}+ confirmVariant={pendingAction.variant === 'destructive' ? 'destructive' : 'default'}+ description={pendingAction.confirm.description?.(countLabel)}+ handleConfirm={handleConfirm}+ handleOpenChange={handleConfirmOpenChange}+ isOpen={!!pendingAction}+ title={pendingAction.confirm.title(countLabel)}+ />+ )}</>);};++interface BulkActionButtonProps {+ action: FileManagerBulkAction;+ isDisabled: boolean;+ onClick: (action: FileManagerBulkAction) => void;+}++/**+ * Inline button for a single non-overflow bulk action. Extracted so the icon-only+ * variant (no `label` text on narrow screens) can be added later without bloating+ * the parent's JSX.+ */+const BulkActionButton = ({ action, isDisabled, onClick }: BulkActionButtonProps) => {+ const Icon = action.icon as ComponentType<{ className?: string }> | undefined;+ const button = (+ <Button+ disabled={isDisabled}+ onClick={() => onClick(action)}+ size="sm"+ variant={action.variant === 'destructive' ? 'destructive' : 'outline'}+ >+ {Icon ? <Icon className="size-4" /> : null}+ <span className={cn(action.icon ? 'hidden sm:inline' : undefined)}>{action.label}</span>+ </Button>+ );++ // Tooltip surfaces the label when the inline text is hidden on narrow+ // viewports (icon-only mode). On wider screens the label is already visible,+ // so the tooltip is a harmless duplicate but still helps with keyboard focus.+ if (!action.icon) {+ return button;+ }++ return (+ <Tooltip>+ <TooltipTrigger asChild>{button}</TooltipTrigger>+ <TooltipContent>{action.label}</TooltipContent>+ </Tooltip>+ );+};diff --git a/frontend/src/components/file-manager/file-manager-types.ts b/frontend/src/components/file-manager/file-manager-types.tsindex e51330ae..ae43d05e 100644--- a/frontend/src/components/file-manager/file-manager-types.ts+++ b/frontend/src/components/file-manager/file-manager-types.ts@@ -25,6 +25,56 @@ export interface FileManagerAction {variant?: 'default' | 'destructive';}+/**+ * Single entry in the bulk-actions bar. By analogy with `FileManagerAction` for+ * row dropdowns: the host owns the array, the bar just renders it.+ *+ * The `files` argument always arrives **deduped** — a directory and its descendants+ * never both appear in the list, the parent wins (see `dedupeOverlappingPaths`).+ */+export interface FileManagerBulkAction {+ /**+ * Optional confirm dialog. When set, the bar gates `onSelect` behind it+ * (used for destructive actions like delete).+ */+ confirm?: FileManagerBulkActionConfirm;+ icon?: ComponentType<{ className?: string }>;+ /** Stable identifier — used as React `key`. */+ id: string;+ /**+ * Greys-out the button when `true`. Receives the deduped selection so the+ * action can disable itself contextually (e.g. when only directories are+ * selected and it doesn't apply to them).+ */+ isDisabled?: (files: FileNode[]) => boolean;+ /**+ * Removes the entry entirely when `true`. Same args as `isDisabled` —+ * useful for actions that simply don't make sense for the current selection.+ */+ isHidden?: (files: FileNode[]) => boolean;+ label: string;+ /** Invoked with the deduped selection. */+ onSelect: (files: FileNode[]) => Promise<void> | void;+ /**+ * When `true`, the action is collapsed into the trailing overflow `…` menu+ * instead of being rendered as a standalone button. Use for less-frequent+ * actions to keep the bar uncluttered.+ */+ overflow?: boolean;+ /** Visual treatment of the inline button (no effect when `overflow: true`). */+ variant?: 'default' | 'destructive';+}++/** Optional confirmation dialog config for a bulk action. */+export interface FileManagerBulkActionConfirm {+ /** Submit-button label (default: action's `label`). */+ confirmText?: string;+ /** Body text. Receives the already-pluralized count label (e.g. "3 items"). */+ description?: (countLabel: string) => string;+ /** Title text. Receives the already-pluralized count label (e.g. "3 items"). */+ title: (countLabel: string) => string;+}+/** Optional column toggles. Both columns default to visible. */export interface FileManagerColumnsConfig {isModifiedVisible?: boolean;@@ -45,12 +95,8 @@ export interface FileManagerInternalNode extends FileNode {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;+ /** Trigger label / aria-label for the trailing overflow `…` menu in the bulk bar. */+ bulkMoreActions?: string;columnModified?: string;columnName?: string;columnSize?: string;@@ -60,7 +106,15 @@ export interface FileManagerLabels {* 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. */+ /**+ * Custom formatter for the cumulative size summary shown in the bulk bar.+ * Receives the byte total of every selected file (directories contribute+ * the recursive sum of their descendants); when omitted, the default+ * `formatFileSize` formatter is used. Return an empty string to suppress+ * the size suffix entirely.+ */+ formatSelectionSize?: (totalBytes: number) => string;+ /** Pluralized "N item" / "N items" used for confirmation dialogs. */pluralizeItems?: (count: number) => string;/** aria-label for the header "select all" checkbox. */selectAllAriaLabel?: string;@@ -71,27 +125,34 @@ export interface FileManagerLabels {export interface FileManagerProps {/** Single, ordered list of available row actions (built-in helpers live in `file-manager-actions`). */actions?: readonly FileManagerAction[];+ /**+ * Ordered list of bulk actions rendered in the footer bar when at least one row+ * is selected. When the list is empty / undefined, the bar is not shown at all+ * unless `enableSelection` forces checkboxes (e.g. picker dialogs).+ *+ * Built-in helpers live in `file-manager-actions` (`bulkDeleteAction`,+ * `bulkCopyPathsAction`, `bulkMoveAction`, `bulkCopyAction`).+ *+ * Each callback receives the **deduped** `FileNode[]`: if both a directory and+ * one of its descendants were selected, only the directory is forwarded.+ */+ bulkActions?: readonly FileManagerBulkAction[];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;/**- * Forces row checkboxes to be visible / hidden, independently of `onBulkDelete`.- * - `true` → checkboxes shown even without a bulk-delete handler (e.g. picker dialogs).- * - `false` → checkboxes hidden even when `onBulkDelete` is provided.- * - `undefined` (default) → checkboxes shown whenever `onBulkDelete` is set.+ * Forces row checkboxes to be visible / hidden, independently of `bulkActions`.+ * - `true` → checkboxes shown even without bulk actions (e.g. picker dialogs).+ * - `false` → checkboxes hidden even when bulk actions are provided.+ * - `undefined` (default) → checkboxes shown whenever `bulkActions` is non-empty.*/enableSelection?: boolean;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.- */- onBulkDelete?: (files: FileNode[]) => Promise<void> | void;/*** Enables internal drag-and-drop: rows become draggable and directories accept drops.* Invoked with the dragged item(s) and the destination directory path (`''` for root).diff --git a/frontend/src/components/file-manager/file-manager-utils.test.ts b/frontend/src/components/file-manager/file-manager-utils.test.tsindex c251208b..0e4d100f 100644--- a/frontend/src/components/file-manager/file-manager-utils.test.ts+++ b/frontend/src/components/file-manager/file-manager-utils.test.ts@@ -617,7 +617,7 @@ describe('computeRowClickSelection — toggle modifier', () => {describe('computeRowClickSelection — range modifier', () => {const flatVisible = ['a', 'b', 'c', 'd', 'e'];- it('selects from anchor to target (forward)', () => {+ it('selects from anchor to target (forward) and unions onto prev', () => {const result = computeRowClickSelection({anchor: 'b',flatVisible,@@ -626,11 +626,11 @@ describe('computeRowClickSelection — range modifier', () => {prev: new Set(['a', 'b']),});- expect([...result.next]).toEqual(['b', 'c', 'd']);+ expect([...result.next].sort()).toEqual(['a', 'b', 'c', 'd']);expect(result.nextAnchor).toBe('b');});- it('selects from anchor to target (backward)', () => {+ it('selects from anchor to target (backward) and unions onto prev', () => {const result = computeRowClickSelection({anchor: 'd',flatVisible,@@ -639,24 +639,27 @@ describe('computeRowClickSelection — range modifier', () => {prev: new Set(['d']),});- expect([...result.next]).toEqual(['b', 'c', 'd']);+ expect([...result.next].sort()).toEqual(['b', 'c', 'd']);expect(result.nextAnchor).toBe('d');});- it('replaces previous selection (does not extend it)', () => {+ it('extends — never erases — earlier picks that fall outside the range', () => {+ // Regression: a Cmd-click added `a` to the selection at anchor `c`,+ // then Shift+click on `e` must keep `a` AROUND. Replacing `prev` with+ // just the visible slice would silently drop the user's first pick.const result = computeRowClickSelection({anchor: 'c',flatVisible,modifier: 'range',path: 'e',- prev: new Set(['a']),+ prev: new Set(['a', 'c']),});- expect([...result.next]).toEqual(['c', 'd', 'e']);+ expect([...result.next].sort()).toEqual(['a', 'c', 'd', 'e']);expect(result.nextAnchor).toBe('c');});- it('reduces to a single-row selection when anchor === target', () => {+ it('reduces to "just add the anchor row" when anchor === target', () => {const result = computeRowClickSelection({anchor: 'c',flatVisible,@@ -669,7 +672,23 @@ describe('computeRowClickSelection — range modifier', () => {expect(result.nextAnchor).toBe('c');});- it('falls back to "single" when no anchor is set yet (and moves the anchor)', () => {+ it('does not shrink the selection when the new range is a subset of prev', () => {+ // After a wide Shift+click `a..e` (sel={a,b,c,d,e}), a user who Shift-+ // clicks `c` is asking to "still cover c"; additive semantics keep the+ // wider selection so the gesture never feels destructive.+ const result = computeRowClickSelection({+ anchor: 'a',+ flatVisible,+ modifier: 'range',+ path: 'c',+ prev: new Set(['a', 'b', 'c', 'd', 'e']),+ });++ expect([...result.next].sort()).toEqual(['a', 'b', 'c', 'd', 'e']);+ expect(result.nextAnchor).toBe('a');+ });++ it('falls back to a single-row ADD when no anchor is set yet (and moves the anchor)', () => {const result = computeRowClickSelection({anchor: null,flatVisible,@@ -678,11 +697,11 @@ describe('computeRowClickSelection — range modifier', () => {prev: new Set(['a']),});- expect([...result.next]).toEqual(['c']);+ expect([...result.next].sort()).toEqual(['a', 'c']);expect(result.nextAnchor).toBe('c');});- it('falls back to "single" when the anchor is no longer visible (and PRESERVES the anchor)', () => {+ it('falls back to a single-row ADD when the anchor is no longer visible (and PRESERVES the anchor)', () => {// Scenario: user cmd-clicked `dir/a`, then collapsed `dir`. The anchor// is now off-screen but should not be silently overwritten — a follow-up// shift-click after re-expanding the dir should still extend from there.@@ -694,11 +713,11 @@ describe('computeRowClickSelection — range modifier', () => {prev: new Set(['dir/a']),});- expect([...result.next]).toEqual(['other']);+ expect([...result.next].sort()).toEqual(['dir/a', 'other']);expect(result.nextAnchor).toBe('dir/a');});- it('falls back to "single" when the target is not in flatVisible (defensive)', () => {+ it('falls back to a single-row ADD when the target is not in flatVisible (defensive)', () => {const result = computeRowClickSelection({anchor: 'a',flatVisible,@@ -707,15 +726,19 @@ describe('computeRowClickSelection — range modifier', () => {prev: new Set(['a']),});- expect([...result.next]).toEqual(['ghost']);+ expect([...result.next].sort()).toEqual(['a', 'ghost']);expect(result.nextAnchor).toBe('a');});- it('range click on a directory uses flatVisible (not subtreePaths) when anchor is valid', () => {- // The directory's own subtree is irrelevant for range clicks — only the- // visible-order span matters, mirroring Finder/Explorer.+ it('range click that lands on a directory expands it via dirSubtreePaths', () => {+ // The slice walks `flatVisible`; when one of the items is a directory,+ // `dirSubtreePaths` is consulted so the folder's full branch joins the+ // selection (matching the contract of a plain folder click). Without+ // this, the folder's tri-state checkbox would render unchecked because+ // its descendants stayed out of the selection.const result = computeRowClickSelection({anchor: 'a',+ dirSubtreePaths: new Map<string, readonly string[]>([['dir', ['dir', 'dir/x', 'dir/y']]]),flatVisible: ['a', 'b', 'dir', 'e'],modifier: 'range',path: 'dir',@@ -723,9 +746,52 @@ describe('computeRowClickSelection — range modifier', () => {subtreePaths: ['dir', 'dir/x', 'dir/y'],});- expect([...result.next]).toEqual(['a', 'b', 'dir']);+ expect([...result.next].sort()).toEqual(['a', 'b', 'dir', 'dir/x', 'dir/y']);expect(result.nextAnchor).toBe('a');});++ it('range click after a folder click keeps the folder subtree alive', () => {+ // Regression: clicking a collapsed folder selects {dir, dir/x, dir/y},+ // a follow-up Shift+click on a sibling file must keep the subtree (the+ // pre-additive behaviour wiped it because the descendants weren't in+ // `flatVisible`).+ const result = computeRowClickSelection({+ anchor: 'dir',+ flatVisible: ['dir', 'sib'],+ modifier: 'range',+ path: 'sib',+ prev: new Set(['dir', 'dir/x', 'dir/y']),+ });++ expect([...result.next].sort()).toEqual(['dir', 'dir/x', 'dir/y', 'sib']);+ expect(result.nextAnchor).toBe('dir');+ });++ it('range click across three sibling folders selects every folder + its subtree', () => {+ // User scenario: three collapsed folders side-by-side. Click `f1`,+ // Shift+click `f3` — every folder must end up "fully checked", which+ // requires every descendant to be in the selection. Without+ // `dirSubtreePaths` the slice would only contain the folder paths+ // themselves and the tri-state checkbox would render `false` for f2+ // and f3 because their descendants are missing from `selectedPaths`.+ const dirSubtreePaths = new Map<string, readonly string[]>([+ ['f1', ['f1', 'f1/a', 'f1/b']],+ ['f2', ['f2', 'f2/a', 'f2/b']],+ ['f3', ['f3', 'f3/a', 'f3/b']],+ ]);+ const result = computeRowClickSelection({+ anchor: 'f1',+ dirSubtreePaths,+ flatVisible: ['f1', 'f2', 'f3'],+ modifier: 'range',+ path: 'f3',+ prev: new Set(['f1', 'f1/a', 'f1/b']),+ subtreePaths: ['f3', 'f3/a', 'f3/b'],+ });++ expect([...result.next].sort()).toEqual(['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b', 'f3', 'f3/a', 'f3/b']);+ expect(result.nextAnchor).toBe('f1');+ });});describe('computeRowClickSelection — anchor stability across chained clicks', () => {@@ -768,8 +834,11 @@ describe('computeRowClickSelection — anchor stability across chained clicks',expect(step3.nextAnchor).toBe('b');});- it('toggle click moves the anchor (so subsequent shift-click extends from the new origin)', () => {- // single 'a' → anchor 'a'; toggle 'c' → anchor 'c'; shift 'd' → c..d+ it('toggle click moves the anchor and the next shift-click EXTENDS prev from the new origin', () => {+ // single 'a' → anchor 'a' / sel={a}; toggle 'c' → anchor 'c' / sel={a,c};+ // shift 'd' → range c..d ADDED to {a,c} = {a,c,d}, anchor still 'c'.+ // The cmd-pick `a` survives the shift gesture — that's the whole point+ // of the additive contract for users layering selections.const s1 = computeRowClickSelection({anchor: null,flatVisible,@@ -792,7 +861,7 @@ describe('computeRowClickSelection — anchor stability across chained clicks',prev: s2.next,});- expect([...s3.next]).toEqual(['c', 'd']);+ expect([...s3.next].sort()).toEqual(['a', 'c', 'd']);expect(s3.nextAnchor).toBe('c');});@@ -855,6 +924,384 @@ describe('computeRowClickSelection — purity', () => {expect(result.next).not.toBe(prev);});++ it('never mutates the input prev Set on a range click that expands directories', () => {+ // Defensive: the additive range branch builds `next` via `addAllToSet`+ // on a clone of `prev`. If the clone step ever regressed, every+ // directory expansion would silently corrupt React state. Shaped after+ // the user's three-folder scenario so a regression here always lights+ // up a real-world failure mode.+ const prev = new Set(['f1', 'f1/a', 'f1/b']);+ const snapshot = [...prev];++ computeRowClickSelection({+ anchor: 'f1',+ dirSubtreePaths: new Map<string, readonly string[]>([+ ['f1', ['f1', 'f1/a', 'f1/b']],+ ['f3', ['f3', 'f3/a', 'f3/b']],+ ]),+ flatVisible: ['f1', 'f2', 'f3'],+ modifier: 'range',+ path: 'f3',+ prev,+ });++ expect([...prev]).toEqual(snapshot);+ });+});++describe('computeRowClickSelection — range edge cases (additive + folder expansion)', () => {+ /** Visible order with all three folders collapsed at the same level. */+ const collapsedFlat = ['f1', 'f2', 'f3'];+ /** Same tree, but every folder expanded (so descendants are visible too). */+ const expandedFlat = ['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b', 'f3', 'f3/a', 'f3/b'];+ /** Subtree map kept stable across the cases — three sibling folders, two children each. */+ const dirSubtreePaths = new Map<string, readonly string[]>([+ ['f1', ['f1', 'f1/a', 'f1/b']],+ ['f2', ['f2', 'f2/a', 'f2/b']],+ ['f3', ['f3', 'f3/a', 'f3/b']],+ ]);++ it('range click backward across folders (anchor = last, target = first) still selects every folder + subtree', () => {+ // Symmetric to the forward case the user reported. The bug looked+ // worse forward (because forward clicks land on the visually-collapsed+ // tail), but the same `dirSubtreePaths` expansion has to fire when the+ // range is computed in reverse — otherwise `f1` and `f2` would render+ // unchecked even though their paths are in the selection.+ const result = computeRowClickSelection({+ anchor: 'f3',+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f1',+ prev: new Set(['f3', 'f3/a', 'f3/b']),+ subtreePaths: ['f1', 'f1/a', 'f1/b'],+ });++ expect([...result.next].sort()).toEqual(['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b', 'f3', 'f3/a', 'f3/b']);+ expect(result.nextAnchor).toBe('f3');+ });++ it('range across already-EXPANDED folders does not double-count children (Set dedup)', () => {+ // When folders are open, the slice already contains every descendant+ // AND `expandDir` also returns them via `dirSubtreePaths`. The two+ // sources overlap fully — `Set` semantics must collapse them so the+ // resulting size matches the unique-paths count exactly.+ const result = computeRowClickSelection({+ anchor: 'f1',+ dirSubtreePaths,+ flatVisible: expandedFlat,+ modifier: 'range',+ path: 'f3',+ prev: new Set(),+ subtreePaths: ['f3', 'f3/a', 'f3/b'],+ });++ expect(result.next.size).toBe(expandedFlat.length);+ expect([...result.next].sort()).toEqual([...expandedFlat].sort());+ expect(result.nextAnchor).toBe('f1');+ });++ it('range with anchor = file and target = collapsed folder expands ONLY the target folder', () => {+ // Files in the slice contribute just themselves; folders contribute+ // their whole subtree. Mixed slice — `a` (file) → `f1` (folder) —+ // must include `a` flat plus `f1`'s entire branch.+ const result = computeRowClickSelection({+ anchor: 'a',+ dirSubtreePaths,+ flatVisible: ['a', 'f1', 'f3'],+ modifier: 'range',+ path: 'f1',+ prev: new Set(),+ subtreePaths: ['f1', 'f1/a', 'f1/b'],+ });++ expect([...result.next].sort()).toEqual(['a', 'f1', 'f1/a', 'f1/b']);+ expect(result.nextAnchor).toBe('a');+ });++ it('range with anchor = collapsed folder and target = file expands ONLY the anchor folder', () => {+ // Mirror of the previous case from the other side — the anchor folder+ // expands, the trailing file stays single.+ const result = computeRowClickSelection({+ anchor: 'f1',+ dirSubtreePaths,+ flatVisible: ['f1', 'a', 'b'],+ modifier: 'range',+ path: 'b',+ prev: new Set(['f1', 'f1/a', 'f1/b']),+ });++ expect([...result.next].sort()).toEqual(['a', 'b', 'f1', 'f1/a', 'f1/b']);+ expect(result.nextAnchor).toBe('f1');+ });++ it('range expands an empty folder to just its own path (no descendants to fold in)', () => {+ // Defensive: an empty folder's `dirSubtreePaths` entry is `[folder]`.+ // The expansion has to gracefully no-op — adding the same path twice+ // through a Set is fine, but the result must not silently grow.+ const result = computeRowClickSelection({+ anchor: 'a',+ dirSubtreePaths: new Map<string, readonly string[]>([['empty', ['empty']]]),+ flatVisible: ['a', 'empty', 'b'],+ modifier: 'range',+ path: 'b',+ prev: new Set(),+ });++ expect([...result.next].sort()).toEqual(['a', 'b', 'empty']);+ expect(result.nextAnchor).toBe('a');+ });++ it('range expands NESTED directories — outer folder pulls inner folder + grandchildren', () => {+ // `outer` contains `outer/inner` which contains `outer/inner/leaf`.+ // A range click that picks up `outer` must include every level via+ // the precomputed subtree (we do NOT recurse `expandDir` ourselves —+ // `dirSubtreePaths['outer']` already lists every descendant).+ const dirSubtreeMap = new Map<string, readonly string[]>([+ ['outer', ['outer', 'outer/inner', 'outer/inner/leaf']],+ ['outer/inner', ['outer/inner', 'outer/inner/leaf']],+ ]);+ const result = computeRowClickSelection({+ anchor: 'a',+ dirSubtreePaths: dirSubtreeMap,+ flatVisible: ['a', 'outer', 'b'],+ modifier: 'range',+ path: 'outer',+ prev: new Set(),+ subtreePaths: ['outer', 'outer/inner', 'outer/inner/leaf'],+ });++ expect([...result.next].sort()).toEqual(['a', 'outer', 'outer/inner', 'outer/inner/leaf']);+ expect(result.nextAnchor).toBe('a');+ });++ it('range works with dirSubtreePaths omitted — every slice path stays flat (tree-less callers)', () => {+ // Backwards-compatibility contract: callers that don't have a tree+ // map should still get a sensible additive range. Folders inside the+ // slice degrade to single-path inserts, which is exactly the+ // pre-expansion behaviour and is fine for flat consumers.+ const result = computeRowClickSelection({+ anchor: 'f1',+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f3',+ prev: new Set(['x']),+ });++ expect([...result.next].sort()).toEqual(['f1', 'f2', 'f3', 'x']);+ expect(result.nextAnchor).toBe('f1');+ });++ it('anchor-null fallback adds the target folder + subtree (not just the bare path)', () => {+ // Edge case the caller hits when the user's very first interaction is+ // a Shift+click. The fallback path must still respect folder+ // semantics so the click "feels like a click" — the folder lights up+ // fully, not as an indeterminate row.+ const result = computeRowClickSelection({+ anchor: null,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f2',+ prev: new Set(),+ subtreePaths: ['f2', 'f2/a', 'f2/b'],+ });++ expect([...result.next].sort()).toEqual(['f2', 'f2/a', 'f2/b']);+ expect(result.nextAnchor).toBe('f2');+ });++ it('off-screen anchor fallback adds the target folder + subtree and PRESERVES the original anchor', () => {+ // Scenario: user cmd-clicked `dir/a` (anchor lives inside a folder),+ // collapsed the folder, then Shift+clicked another folder. The anchor+ // is no longer in `flatVisible` so the reducer falls back to a+ // single-shaped add — and that add still has to expand the target.+ const result = computeRowClickSelection({+ anchor: 'dir/a',+ dirSubtreePaths,+ flatVisible: ['f1', 'f2'],+ modifier: 'range',+ path: 'f2',+ prev: new Set(['dir/a']),+ subtreePaths: ['f2', 'f2/a', 'f2/b'],+ });++ expect([...result.next].sort()).toEqual(['dir/a', 'f2', 'f2/a', 'f2/b']);+ expect(result.nextAnchor).toBe('dir/a');+ });++ it('chained shift-clicks accumulate folder subtrees from the same anchor', () => {+ // Step 1: single-click `f1` → sel = whole f1 branch, anchor = f1.+ const step1 = computeRowClickSelection({+ anchor: null,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'single',+ path: 'f1',+ prev: new Set(),+ subtreePaths: ['f1', 'f1/a', 'f1/b'],+ });++ expect([...step1.next].sort()).toEqual(['f1', 'f1/a', 'f1/b']);++ // Step 2: shift-click `f2` → range f1..f2 expands BOTH folders.+ const step2 = computeRowClickSelection({+ anchor: step1.nextAnchor,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f2',+ prev: step1.next,+ subtreePaths: ['f2', 'f2/a', 'f2/b'],+ });++ expect([...step2.next].sort()).toEqual(['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b']);+ expect(step2.nextAnchor).toBe('f1');++ // Step 3: shift-click `f3` → anchor still f1, range now covers all 3.+ const step3 = computeRowClickSelection({+ anchor: step2.nextAnchor,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f3',+ prev: step2.next,+ subtreePaths: ['f3', 'f3/a', 'f3/b'],+ });++ expect([...step3.next].sort()).toEqual(['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b', 'f3', 'f3/a', 'f3/b']);+ expect(step3.nextAnchor).toBe('f1');+ });++ it('toggle a folder, then shift-click another folder → cmd-picked subtree survives + target subtree joins', () => {+ // Real workflow: pick one folder, Cmd-pick a different one, then+ // Shift-click a third to grab everything in between. The toggle moves+ // the anchor to its target, the shift-range expands every folder it+ // touches, and the *original* cmd-pick that lives outside the range+ // stays intact thanks to the additive contract.+ const cmdPick = computeRowClickSelection({+ anchor: null,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'toggle',+ path: 'f1',+ prev: new Set(),+ subtreePaths: ['f1', 'f1/a', 'f1/b'],+ });+ const shiftPick = computeRowClickSelection({+ anchor: cmdPick.nextAnchor,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f3',+ prev: cmdPick.next,+ subtreePaths: ['f3', 'f3/a', 'f3/b'],+ });++ expect([...shiftPick.next].sort()).toEqual(['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b', 'f3', 'f3/a', 'f3/b']);+ // Anchor moved to `f1` on toggle, so the range was f1..f3 — and a+ // follow-up shift-click would still extend from `f1`, not `f3`.+ expect(shiftPick.nextAnchor).toBe('f1');+ });++ it('two cmd-picks on separate folders, then shift-click a third → all three subtrees are present', () => {+ // Anchor moves with each toggle, so the final range is rooted at the+ // most recent cmd-pick. Earlier folders survive via the additive+ // union — the test makes sure the union expands their subtrees too,+ // not just the bare folder paths.+ const cmd1 = computeRowClickSelection({+ anchor: null,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'toggle',+ path: 'f1',+ prev: new Set(),+ subtreePaths: ['f1', 'f1/a', 'f1/b'],+ });+ const cmd2 = computeRowClickSelection({+ anchor: cmd1.nextAnchor,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'toggle',+ path: 'f2',+ prev: cmd1.next,+ subtreePaths: ['f2', 'f2/a', 'f2/b'],+ });+ const shift = computeRowClickSelection({+ anchor: cmd2.nextAnchor,+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f3',+ prev: cmd2.next,+ subtreePaths: ['f3', 'f3/a', 'f3/b'],+ });++ expect([...shift.next].sort()).toEqual(['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b', 'f3', 'f3/a', 'f3/b']);+ expect(shift.nextAnchor).toBe('f2');+ });++ it('shift-click with anchor === target (a folder) adds the folder subtree exactly once', () => {+ // `slice` reduces to `[folder]`; the expansion has to fire just like+ // a normal range so the user sees the row "fully checked" instead of+ // indeterminate. Idempotent — re-clicking shouldn't toggle anything.+ const result = computeRowClickSelection({+ anchor: 'f1',+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f1',+ prev: new Set(['f1', 'f1/a', 'f1/b']),+ subtreePaths: ['f1', 'f1/a', 'f1/b'],+ });++ expect([...result.next].sort()).toEqual(['f1', 'f1/a', 'f1/b']);+ expect(result.nextAnchor).toBe('f1');+ });++ it('shift-click does not shrink a wider selection even when range is fully inside it', () => {+ // Additive contract: a Shift-click that picks a *narrower* range than+ // the previous one keeps the wider selection intact. This is the one+ // place the behaviour openly diverges from Finder/Explorer (those+ // would replace), and the test pins it down so the divergence stays+ // intentional.+ const result = computeRowClickSelection({+ anchor: 'f1',+ dirSubtreePaths,+ flatVisible: collapsedFlat,+ modifier: 'range',+ path: 'f2',+ prev: new Set(['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b', 'f3', 'f3/a', 'f3/b']),+ subtreePaths: ['f2', 'f2/a', 'f2/b'],+ });++ expect([...result.next].sort()).toEqual(['f1', 'f1/a', 'f1/b', 'f2', 'f2/a', 'f2/b', 'f3', 'f3/a', 'f3/b']);+ expect(result.nextAnchor).toBe('f1');+ });++ it('shift-click adds a target folder subtree when the anchor sits inside an unrelated branch', () => {+ // Anchor is the deepest leaf of `dir1`; user shift-clicks `dir2` (a+ // sibling folder). The range slice covers both folder rows and the+ // file rows in between, but the test explicitly verifies that the+ // target folder's full subtree joins the selection — not just `dir2`.+ const dirSubtreeMap = new Map<string, readonly string[]>([+ ['dir1', ['dir1', 'dir1/a']],+ ['dir2', ['dir2', 'dir2/x', 'dir2/y']],+ ]);+ const result = computeRowClickSelection({+ anchor: 'dir1/a',+ dirSubtreePaths: dirSubtreeMap,+ flatVisible: ['dir1', 'dir1/a', 'between', 'dir2'],+ modifier: 'range',+ path: 'dir2',+ prev: new Set(['dir1', 'dir1/a']),+ subtreePaths: ['dir2', 'dir2/x', 'dir2/y'],+ });++ expect([...result.next].sort()).toEqual(['between', 'dir1', 'dir1/a', 'dir2', 'dir2/x', 'dir2/y']);+ expect(result.nextAnchor).toBe('dir1/a');+ });});describe('computeToggleSelection (Space / row checkbox)', () => {@@ -876,27 +1323,23 @@ describe('computeToggleSelection (Space / row checkbox)', () => {).toEqual(['dir', 'dir/a', 'dir/b']);// fully selected → cleared- expect(- [- ...computeToggleSelection({- path: 'dir',- prev: new Set(['dir', 'dir/a', 'dir/b']),- subtreePaths: ['dir', 'dir/a', 'dir/b'],- }),- ],- ).toEqual([]);+ expect([+ ...computeToggleSelection({+ path: 'dir',+ prev: new Set(['dir', 'dir/a', 'dir/b']),+ subtreePaths: ['dir', 'dir/a', 'dir/b'],+ }),+ ]).toEqual([]);});it('preserves unrelated paths on subtree toggle', () => {- expect(- [- ...computeToggleSelection({- path: 'dir',- prev: new Set(['dir', 'dir/a', 'dir/b', 'x']),- subtreePaths: ['dir', 'dir/a', 'dir/b'],- }),- ],- ).toEqual(['x']);+ expect([+ ...computeToggleSelection({+ path: 'dir',+ prev: new Set(['dir', 'dir/a', 'dir/b', 'x']),+ subtreePaths: ['dir', 'dir/a', 'dir/b'],+ }),+ ]).toEqual(['x']);});it('treats empty subtreePaths as "single path" (defensive)', () => {@@ -920,9 +1363,7 @@ describe('computeToggleSelectAll', () => {});it('clears the selection when everything is already selected', () => {- expect([- ...computeToggleSelectAll({ allSelectablePaths: ['a', 'b'], prev: new Set(['a', 'b']) }),- ]).toEqual([]);+ expect([...computeToggleSelectAll({ allSelectablePaths: ['a', 'b'], prev: new Set(['a', 'b']) })]).toEqual([]);});it('returns an empty Set when the universe is empty (no selectable paths)', () => {diff --git a/frontend/src/components/file-manager/file-manager-utils.ts b/frontend/src/components/file-manager/file-manager-utils.tsindex 79f50ec6..a0b53693 100644--- a/frontend/src/components/file-manager/file-manager-utils.ts+++ b/frontend/src/components/file-manager/file-manager-utils.ts@@ -334,7 +334,10 @@ 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: readonly FileManagerInternalNode[],+ path: string,+): FileManagerInternalNode | undefined => {for (const node of nodes) {if (node.path === path) {return node;@@ -418,6 +421,59 @@ export const collectSubtreePaths = (node: FileManagerInternalNode): string[] =>/** Default English pluralization for "N item" / "N items". Override via `labels.pluralizeItems`. */export const pluralizeItemsEnglish = (count: number): string => `${count} ${count === 1 ? 'item' : 'items'}`;+/**+ * Recursively sum every file's `size` inside a node's subtree. Synthetic group+ * roots and directories themselves contribute nothing — only their leaf files+ * carry bytes. Files without a `size` are treated as 0 so a partial backend+ * payload doesn't poison the total.+ */+const sumSubtreeBytes = (node: FileManagerInternalNode): number => {+ if (node.children.length > 0) {+ let total = 0;++ for (const child of node.children) {+ total += sumSubtreeBytes(child);+ }++ return total;+ }++ if (node.isDir || node.isGroupRoot) {+ return 0;+ }++ return node.size ?? 0;+};++/**+ * Cumulative byte total for the bulk-bar size summary. Walks `paths` (which the+ * caller is expected to have already deduped via `dedupeOverlappingPaths`) and+ * adds each entry's contribution: a file pulls its own `size`, a directory pulls+ * the recursive sum of its descendants.+ *+ * Missing nodes are skipped silently — selection paths can transiently lag the+ * tree during async refreshes, and counting "0 bytes" for a vanished entry is+ * less surprising than throwing.+ */+export const computeSelectionTotalBytes = (+ tree: readonly FileManagerInternalNode[],+ paths: Iterable<string>,+): number => {+ let total = 0;++ for (const path of paths) {+ const node = findNodeByPath(tree, path);++ if (!node) {+ continue;+ }++ total += sumSubtreeBytes(node);+ }++ return total;+};+/*** Mutates `set` in place by adding every path from `paths`. Designed for "build a* fresh `next` from `prev`, then add a batch" patterns inside `setState` updaters@@ -477,6 +533,19 @@ export const toggleSubtreeOnSet = (prev: ReadonlySet<string>, paths: readonly stinterface ComputeRowClickSelectionArgs {/** Last-clicked path used as the range anchor. `null` when nothing has been clicked yet. */anchor: null | string;+ /**+ * Subtree map for every directory in the *visible* tree, keyed by the+ * directory's own path. Used to expand directories that appear inside a+ * `range`-modifier slice into their full subtree (folder rows are atomic+ * for the Shift+click gesture too — clicking one selects its branch, so a+ * Shift-range that crosses a folder must do the same; otherwise the+ * folder's checkbox would render unchecked even though its own path is in+ * the selection, because `computeDirSelectionState` derives the state+ * from descendants). Optional — when omitted, range slices stay flat+ * (covers tree-less callers and unit tests that don't care about+ * directory expansion).+ */+ dirSubtreePaths?: ReadonlyMap<string, readonly string[]>;/** Visible nodes in DFS order; range modifier resolves anchor/target indices against this list. */flatVisible: readonly string[];modifier: 'range' | 'single' | 'toggle';@@ -486,9 +555,10 @@ interface ComputeRowClickSelectionArgs {prev: ReadonlySet<string>;/*** For directory rows: the directory's own path plus every descendant. Single- * and toggle modifiers operate on the whole branch; range modifier still- * defers to the visible-order anchor and uses `subtreePaths` only as the- * fallback payload when the range cannot be resolved.+ * and toggle modifiers operate on the whole branch; range modifier uses it+ * for the fallback payload when the range cannot be resolved AND for the+ * target row inside the slice (via `dirSubtreePaths`, which already+ * contains the same data keyed by every directory's path).*/subtreePaths?: readonly string[];}@@ -516,15 +586,25 @@ interface ComputeRowClickSelectionResult {* (files). Anchor moves to `path`.* - **toggle**: all-or-nothing flip of `subtreePaths` (folders) or single* `path` (files). Anchor moves to `path`.- * - **range**: replaces selection with the slice of `flatVisible` between- * `anchor` and `path` (inclusive, direction-agnostic). Anchor is preserved.- * If `anchor` is `null` → behaves like `single` and moves the anchor.- * If either anchor or target is missing from `flatVisible` → falls back to- * a `single`-style replacement but preserves the anchor (the original- * reference point may still be valid once it scrolls back into view).+ * - **range**: ADDITIVELY unions the slice of `flatVisible` between `anchor`+ * and `path` (inclusive, direction-agnostic) onto the previous selection+ * so a Shift-click extends — never erases — what's already selected.+ * Concretely: a Cmd+click‑based selection set, an explicitly clicked+ * folder's full subtree, and any earlier range slice are all preserved+ * when the user reaches for Shift+click to grab "everything from the last+ * click down to here". Anchor is preserved across chained Shift+clicks so+ * each one re-extends from the same origin (matches Finder/Explorer for+ * the anchor; the additive merge is the deliberate divergence the rest of+ * this codebase relies on — folder rows would otherwise drop their+ * subtree on every Shift+click). If `anchor` is `null` → behaves like a+ * `single`-shaped add (no anchor, nothing to extend FROM) and moves the+ * anchor. If either anchor or target is missing from `flatVisible` →+ * falls back to the same single-shaped add but preserves the anchor (the+ * original reference point may still be valid once it scrolls back in).*/export const computeRowClickSelection = ({anchor,+ dirSubtreePaths,flatVisible,modifier,path,@@ -532,8 +612,7 @@ export const computeRowClickSelection = ({subtreePaths,}: ComputeRowClickSelectionArgs): ComputeRowClickSelectionResult => {const hasSubtree = !!subtreePaths && subtreePaths.length > 0;- const buildReplacement = (): Set<string> =>- hasSubtree && subtreePaths ? new Set(subtreePaths) : new Set([path]);+ const buildReplacement = (): Set<string> => (hasSubtree && subtreePaths ? new Set(subtreePaths) : new Set([path]));if (modifier === 'single') {return { next: buildReplacement(), nextAnchor: path };@@ -555,20 +634,48 @@ export const computeRowClickSelection = ({return { next, nextAnchor: path };}+ // Range modifier — additive. The slice computed below is unioned onto+ // `prev`, never replaced, so the user can build up a selection across+ // multiple gestures (single → cmd-click → shift-click → shift-click…)+ // without watching earlier picks vanish. The "fallback to a single-shaped+ // add" branches below honour the same contract: each one extends `prev`+ // by exactly one item (the clicked path or its subtree), never wipes it.+ //+ // Directories inside the slice expand to their full subtree via+ // `dirSubtreePaths` so a Shift-range over collapsed folders behaves like+ // a series of plain folder clicks: every folder picks up its children+ // even when those children aren't in `flatVisible` (folder collapsed).+ // This keeps the tri-state checkbox visibly "fully checked" — without+ // the expansion, `computeDirSelectionState` would render a folder+ // unchecked because its descendants stayed out of the selection.+ const expandDir = (p: string): readonly string[] => dirSubtreePaths?.get(p) ?? [p];++ const addRangeToPrev = (paths: Iterable<string>): Set<string> => {+ const next = new Set(prev);++ for (const p of paths) {+ addAllToSet(next, expandDir(p));+ }++ return next;+ };++ const buildAdditiveFallback = (): Set<string> => addRangeToPrev(hasSubtree && subtreePaths ? subtreePaths : [path]);+if (!anchor) {- return { next: buildReplacement(), nextAnchor: path };+ return { next: buildAdditiveFallback(), nextAnchor: path };}const fromIndex = flatVisible.indexOf(anchor);const toIndex = flatVisible.indexOf(path);if (fromIndex < 0 || toIndex < 0) {- return { next: buildReplacement(), nextAnchor: anchor };+ return { next: buildAdditiveFallback(), nextAnchor: anchor };}const [startIndex, endIndex] = fromIndex <= toIndex ? [fromIndex, toIndex] : [toIndex, fromIndex];- return { next: new Set(flatVisible.slice(startIndex, endIndex + 1)), nextAnchor: anchor };+ return { next: addRangeToPrev(flatVisible.slice(startIndex, endIndex + 1)), nextAnchor: anchor };};interface ComputeToggleSelectionArgs {diff --git a/frontend/src/components/file-manager/file-manager.tsx b/frontend/src/components/file-manager/file-manager.tsxindex 4b0cd0bf..08bbe29c 100644--- a/frontend/src/components/file-manager/file-manager.tsx+++ b/frontend/src/components/file-manager/file-manager.tsx@@ -4,12 +4,19 @@ import { Checkbox } from '@/components/ui/checkbox';import { cn } from '@/lib/utils';import type { FileManagerRowDisplay, FileManagerRowHandlers } from './file-manager-row';-import type { FileManagerAction, FileManagerProps, FileNode } from './file-manager-types';+import type { FileManagerAction, FileManagerBulkAction, FileManagerProps, FileNode } from './file-manager-types';import { FileManagerBulkActionsBar } from './file-manager-bulk-actions-bar';import { FileManagerSkeleton } from './file-manager-skeleton';import { FileManagerTreeNode } from './file-manager-tree-node';-import { collectVisibleFlat, computeDirSelectionState, findNodeByPath, getCheckboxState } from './file-manager-utils';+import {+ collectVisibleFlat,+ computeDirSelectionState,+ computeSelectionTotalBytes,+ dedupeOverlappingPaths,+ findNodeByPath,+ getCheckboxState,+} from './file-manager-utils';import { useFileManagerData } from './use-file-manager-data';import { useFileManagerDnd } from './use-file-manager-dnd';import { useFileManagerExpansion } from './use-file-manager-expansion';@@ -17,9 +24,11 @@ import { useFileManagerKeyboardNavigation } from './use-file-manager-keyboard';import { useFileManagerSelection } from './use-file-manager-selection';const EMPTY_ACTIONS: readonly FileManagerAction[] = Object.freeze([]);+const EMPTY_BULK_ACTIONS: readonly FileManagerBulkAction[] = Object.freeze([]);export const FileManager = ({actions,+ bulkActions,className,columns,emptyState,@@ -27,14 +36,15 @@ export const FileManager = ({files,isLoading,labels,- onBulkDelete,onMoveItems,onOpen,onSelectionChange,rootGroups,search,}: FileManagerProps) => {- const isCheckboxVisible = enableSelection ?? !!onBulkDelete;+ const effectiveBulkActions = bulkActions ?? EMPTY_BULK_ACTIONS;+ const hasBulkActions = effectiveBulkActions.length > 0;+ const isCheckboxVisible = enableSelection ?? hasBulkActions;const hasActions = !!actions?.length;const {@@ -74,9 +84,22 @@ export const FileManager = ({onRowClick,onToggleSelection,selectedPaths,- setSelection,toggleSelectAll,- } = useFileManagerSelection({ allSelectablePaths, flatVisible });+ } = useFileManagerSelection({ allSelectablePaths, dirSubtreePaths, flatVisible });++ // Cumulative byte total of the deduped selection — fed into the bulk bar's+ // size suffix ("3 selected · 14.2 MB"). Recomputed on selection / tree+ // changes; cheap because the dedup keeps the visit list short and each+ // subtree walk uses the same `findNodeByPath` traversal as the bar's other+ // helpers. Skipped entirely when the bar is hidden so a no-checkbox tree+ // never pays the cost.+ const selectionTotalBytes = useMemo(() => {+ if (!hasBulkActions || selectedPaths.size === 0) {+ return 0;+ }++ return computeSelectionTotalBytes(fullTree, dedupeOverlappingPaths(selectedPaths));+ }, [fullTree, hasBulkActions, selectedPaths]);// Tri-state checkbox values per directory: derived from `selectedPaths` so a// single state change updates every parent checkbox in lock-step. The map is@@ -286,7 +309,7 @@ export const FileManager = ({// ring follow the outer container's rounded corners (top corners are// hidden behind the header, so only the bottom is visually affected).dnd.container.isRootDropTarget &&- 'bg-primary/10 ring-primary ring-1 ring-inset [border-radius:inherit]',+ 'bg-primary/10 ring-primary [border-radius:inherit] ring-1 ring-inset',)}onDragEnter={dnd.isEnabled ? dnd.container.onDragEnter : undefined}onDragLeave={dnd.isEnabled ? dnd.container.onDragLeave : undefined}@@ -313,14 +336,14 @@ export const FileManager = ({))}</div>- {onBulkDelete && (+ {hasBulkActions && (<FileManagerBulkActionsBar+ actions={effectiveBulkActions}files={files}labels={effectiveLabels}- onBulkDelete={onBulkDelete}onClearSelection={clearSelection}- onSelectionChange={setSelection}selectedPaths={selectedPaths}+ selectionTotalBytes={selectionTotalBytes}/>)}</div>diff --git a/frontend/src/components/file-manager/index.ts b/frontend/src/components/file-manager/index.tsindex d46c1909..20d9d3c0 100644--- a/frontend/src/components/file-manager/index.ts+++ b/frontend/src/components/file-manager/index.ts@@ -1,9 +1,20 @@export { FileManager } from './file-manager';-export { copyPathAction, deleteAction, downloadAction } from './file-manager-actions';+export {+ bulkCopyAction,+ bulkCopyPathsAction,+ bulkDeleteAction,+ bulkMoveAction,+ bulkPromoteAction,+ copyPathAction,+ deleteAction,+ downloadAction,+} from './file-manager-actions';export { getFileTypeIcon } from './file-manager-icons';export type { FileTypeIcon } from './file-manager-icons';export type {FileManagerAction,+ FileManagerBulkAction,+ FileManagerBulkActionConfirm,FileManagerLabels,FileManagerProps,FileManagerRootGroup,diff --git a/frontend/src/components/file-manager/use-file-manager-selection.ts b/frontend/src/components/file-manager/use-file-manager-selection.tsindex 674ee4ab..ccf94cc0 100644--- a/frontend/src/components/file-manager/use-file-manager-selection.ts+++ b/frontend/src/components/file-manager/use-file-manager-selection.ts@@ -48,6 +48,14 @@ interface UseFileManagerSelection {interface UseFileManagerSelectionArgs {/** Universe of selectable paths (files + real directories) in the *visible* tree. */allSelectablePaths: string[];+ /**+ * Subtree paths per directory in the *visible* tree (the dir itself plus+ * descendants). Forwarded to the range-click reducer so directories caught+ * inside a Shift-range expand to their full branch — keeping their+ * tri-state checkbox fully checked even when they were collapsed at the+ * moment of the gesture (no descendants in `flatVisible` to count).+ */+ dirSubtreePaths: ReadonlyMap<string, readonly string[]>;/** Visible nodes in DFS order — used for shift-range selection. */flatVisible: string[];}@@ -66,6 +74,7 @@ interface UseFileManagerSelectionArgs {*/export const useFileManagerSelection = ({allSelectablePaths,+ dirSubtreePaths,flatVisible,}: UseFileManagerSelectionArgs): UseFileManagerSelection => {const [rawSelectedPaths, setRawSelectedPaths] = useState<Set<string>>(() => new Set());@@ -80,6 +89,7 @@ export const useFileManagerSelection = ({// already used in `use-file-manager-dnd` for `selectionRef`.const flatVisibleRef = useRef(flatVisible);const allSelectablePathsRef = useRef(allSelectablePaths);+ const dirSubtreePathsRef = useRef(dirSubtreePaths);useEffect(() => {flatVisibleRef.current = flatVisible;@@ -89,6 +99,10 @@ export const useFileManagerSelection = ({allSelectablePathsRef.current = allSelectablePaths;}, [allSelectablePaths]);+ useEffect(() => {+ dirSubtreePathsRef.current = dirSubtreePaths;+ }, [dirSubtreePaths]);+const allSelectablePathsSet = useMemo(() => new Set(allSelectablePaths), [allSelectablePaths]);const selectedPaths = useMemo(() => {@@ -116,6 +130,7 @@ export const useFileManagerSelection = ({setRawSelectedPaths((prev) => {const { next, nextAnchor } = computeRowClickSelection({anchor: lastClickedRef.current,+ dirSubtreePaths: dirSubtreePathsRef.current,flatVisible: flatVisibleRef.current,modifier,path,diff --git a/frontend/src/features/flows/files/flow-files-promote-dialog.tsx b/frontend/src/features/flows/files/flow-files-promote-dialog.tsxindex f8a0bed9..66a451ff 100644--- a/frontend/src/features/flows/files/flow-files-promote-dialog.tsx+++ b/frontend/src/features/flows/files/flow-files-promote-dialog.tsx@@ -1,6 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod';import { BookmarkPlus, Loader2 } from 'lucide-react';-import { useEffect } from 'react';+import { useEffect, useMemo } from 'react';import { useForm } from 'react-hook-form';import type { FileNode } from '@/components/file-manager';@@ -18,26 +18,63 @@ import {useFlowFilesPromote,} from './use-flow-files-promote';+/** Guaranteed non-empty by `FlowFilesPromoteDialog` (which gates rendering on `files.length > 0`). */interface FlowFilesPromoteDialogFormProps {- file: FileNode;+ files: readonly [FileNode, ...FileNode[]];flowId: null | string;onClose: () => void;}interface FlowFilesPromoteDialogProps {- file: FileNode | null;+ /**+ * One or more files to promote into the user's resource library. A single-element+ * array renders the "save N to a specific path" UI; multi-element arrays render+ * the "save N items into directory" UI (each file keeps its current name).+ *+ * Use `null` or an empty array to close the dialog.+ */+ files: FileNode[] | null;flowId: null | string;onClose: () => void;}-const buildDefaultDestination = (file: FileNode) => stripFlowRootPrefix(file.path) || file.name;+const buildSingleDefaultDestination = (file: FileNode) => stripFlowRootPrefix(file.path) || file.name;-const FlowFilesPromoteDialogForm = ({ file, flowId, onClose }: FlowFilesPromoteDialogFormProps) => {+/**+ * Default destination directory for a multi-file promote: strip the synthetic+ * root-group prefix (`uploads/`, `container/`, `resources/`) from the file's+ * parent path so the user sees a "library-relative" suggestion. When selections+ * span different parents, fall back to the library root so we don't pick one+ * arbitrarily.+ */+const computeMultiDefaultDestination = (files: readonly [FileNode, ...FileNode[]]): string => {+ const stripParent = (path: string): string => {+ const stripped = stripFlowRootPrefix(path);+ const idx = stripped.lastIndexOf('/');++ return idx === -1 ? '' : stripped.slice(0, idx);+ };++ const first = stripParent(files[0].path);++ return files.every((file) => stripParent(file.path) === first) ? first : '';+};++const FlowFilesPromoteDialogForm = ({ files, flowId, onClose }: FlowFilesPromoteDialogFormProps) => {const { isPromoting, promote } = useFlowFilesPromote({ flowId });+ const isMulti = files.length > 1;++ const defaultDestination = useMemo(() => {+ if (isMulti) {+ return computeMultiDefaultDestination(files);+ }++ return buildSingleDefaultDestination(files[0]);+ }, [files, isMulti]);const form = useForm<FlowFilesPromoteFormValues>({defaultValues: {- destination: buildDefaultDestination(file),+ destination: defaultDestination,shouldOverwrite: false,},mode: 'onChange',@@ -46,13 +83,33 @@ const FlowFilesPromoteDialogForm = ({ file, flowId, onClose }: FlowFilesPromoteDuseEffect(() => {form.reset({- destination: buildDefaultDestination(file),+ destination: defaultDestination,shouldOverwrite: false,});- }, [file, form]);+ }, [defaultDestination, form]);const handleSubmit = form.handleSubmit(async (values) => {- const wasPromoted = await promote(file.path, values);+ if (isMulti) {+ // Multi-file promote: `destination` is the *target directory* inside+ // the resource library, every file keeps its current name. Strip a+ // trailing `/` for consistency with the single-file branch.+ const targetDir = values.destination.trim().replace(/\/+$/, '');+ const results = await Promise.all(+ files.map((file) => {+ const destination = targetDir ? `${targetDir}/${file.name}` : file.name;++ return promote(file.path, { destination, shouldOverwrite: values.shouldOverwrite });+ }),+ );++ if (results.every(Boolean)) {+ onClose();+ }++ return;+ }++ const wasPromoted = await promote(files[0].path, values);if (wasPromoted) {onClose();@@ -60,17 +117,27 @@ const FlowFilesPromoteDialogForm = ({ file, flowId, onClose }: FlowFilesPromoteD});const isSubmitDisabled = !form.formState.isValid || isPromoting;+ const titleText = isMulti ? `Save ${files.length} items as resources` : 'Save as resource';return (<DialogContent><DialogHeader><DialogTitle className="flex items-center gap-2"><BookmarkPlus className="size-4" />- Save as resource+ {titleText}</DialogTitle><DialogDescription>- Promote <code>{file.path}</code> from this flow into your global resource library so you can reuse- it in other flows.+ {isMulti ? (+ <>+ Promote every selected entry from this flow into your global resource library so you can+ reuse them in other flows.+ </>+ ) : (+ <>+ Promote <code>{files[0].path}</code> from this flow into your global resource library so you+ can reuse it in other flows.+ </>+ )}</DialogDescription></DialogHeader>@@ -84,19 +151,30 @@ const FlowFilesPromoteDialogForm = ({ file, flowId, onClose }: FlowFilesPromoteDname="destination"render={({ field }) => (<FormItem>- <FormLabel>Destination path</FormLabel>+ <FormLabel>{isMulti ? 'Destination directory' : 'Destination path'}</FormLabel><FormControl><Input{...field}autoComplete="off"autoFocusdisabled={isPromoting}- placeholder="results/scan.txt"+ placeholder={+ isMulti ? 'Leave empty to save into the library root' : 'results/scan.txt'+ }/></FormControl><FormDescription>- Relative path inside your resource library. Use <code>/</code> to nest into- subdirectories.+ {isMulti ? (+ <>+ Relative directory inside your resource library. Leave empty for the root.+ Each item keeps its current filename.+ </>+ ) : (+ <>+ Relative path inside your resource library. Use <code>/</code> to nest into+ subdirectories.+ </>+ )}</FormDescription><FormMessage /></FormItem>@@ -116,7 +194,9 @@ const FlowFilesPromoteDialogForm = ({ file, flowId, onClose }: FlowFilesPromoteD/></FormControl><FormLabel className="cursor-pointer font-normal">- Overwrite if a resource already exists at this path+ {isMulti+ ? 'Overwrite if a resource already exists at any destination'+ : 'Overwrite if a resource already exists at this path'}</FormLabel><FormDescription className="sr-only">Replace the existing resource entry when one already exists.@@ -148,21 +228,25 @@ const FlowFilesPromoteDialogForm = ({ file, flowId, onClose }: FlowFilesPromoteD);};-export const FlowFilesPromoteDialog = ({ file, flowId, onClose }: FlowFilesPromoteDialogProps) => {+export const FlowFilesPromoteDialog = ({ files, flowId, onClose }: FlowFilesPromoteDialogProps) => {const handleDialogOpenChange = (nextOpen: boolean) => {if (!nextOpen) {onClose();}};+ // Narrow to a non-empty tuple so the inner form can index `files[0]` without+ // optional-chain noise. The Dialog only mounts when this guard passes.+ const nonEmptyFiles = files && files.length > 0 ? (files as [FileNode, ...FileNode[]]) : null;+return (<DialogonOpenChange={handleDialogOpenChange}- open={!!file}+ open={!!nonEmptyFiles}>- {file && (+ {nonEmptyFiles && (<FlowFilesPromoteDialogForm- file={file}+ files={nonEmptyFiles}flowId={flowId}onClose={onClose}/>diff --git a/frontend/src/features/flows/files/flow-files.tsx b/frontend/src/features/flows/files/flow-files.tsxindex 1b5b2310..5feefce0 100644--- a/frontend/src/features/flows/files/flow-files.tsx+++ b/frontend/src/features/flows/files/flow-files.tsx@@ -3,11 +3,15 @@ import { useCallback, useMemo, useState } from 'react';import { toast } from 'sonner';import {+ bulkCopyPathsAction,+ bulkDeleteAction,+ bulkPromoteAction,copyPathAction,deleteAction,downloadAction,FileManager,type FileManagerAction,+ type FileManagerBulkAction,type FileNode,} from '@/components/file-manager';import ConfirmationDialog from '@/components/shared/confirmation-dialog';@@ -25,7 +29,7 @@ import { FlowFilesAttachResourcesDialog } from './flow-files-attach-resources-diimport { ROOT_GROUPS } from './flow-files-constants';import { FlowFilesPromoteDialog } from './flow-files-promote-dialog';import { FlowFilesPullDialog } from './flow-files-pull-dialog';-import { buildDownloadHref } from './flow-files-utils';+import { buildDownloadHref, pluralizeItems } from './flow-files-utils';import { useFlowFilesData } from './use-flow-files-data';import { useFlowFilesDelete } from './use-flow-files-delete';import { useFlowFilesRealtime } from './use-flow-files-realtime';@@ -36,7 +40,9 @@ const FlowFiles = () => {const { flowId, flowStatus } = useFlow();const [isPullDialogOpen, setIsPullDialogOpen] = useState(false);const [isAttachResourcesDialogOpen, setIsAttachResourcesDialogOpen] = useState(false);- const [fileToPromote, setFileToPromote] = useState<FileNode | null>(null);+ // Array now: row-action click pushes a single-element array, the bulk bar+ // pushes the deduped selection. Empty array / null closes the dialog.+ const [filesToPromote, setFilesToPromote] = useState<FileNode[] | null>(null);const { fileNodes, isInitialLoading, isLoading, refetchFiles } = useFlowFilesData({ flowId });@@ -67,13 +73,34 @@ const FlowFiles = () => {toast.error('Failed to copy path');}, []);+ /**+ * Bulk "copy paths" handler: join every selected file's path with `\n` so the+ * user can paste a clean newline-separated list straight into the agent chat,+ * a shell command, or a tool argument. Reports the count for clarity.+ */+ const handleBulkCopyPaths = useCallback(async (paths: string[]) => {+ if (paths.length === 0) {+ return;+ }++ const wasCopied = await copyToClipboard(paths.join('\n'));++ if (wasCopied) {+ toast.success(`${paths.length} ${pluralizeItems(paths.length)} copied to clipboard`);++ return;+ }++ toast.error('Failed to copy paths');+ }, []);+const getDownloadHref = useCallback((file: FileNode): string => buildDownloadHref(flowId, file) ?? '', [flowId]);const handleRequestPromote = useCallback((file: FileNode) => {- setFileToPromote(file);+ setFilesToPromote([file]);}, []);- const handleClosePromoteDialog = useCallback(() => setFileToPromote(null), []);+ const handleClosePromoteDialog = useCallback(() => setFilesToPromote(null), []);const promoteAction = useMemo<FileManagerAction>(() => ({@@ -96,6 +123,18 @@ const FlowFiles = () => {[getDownloadHref, handleCopyPath, promoteAction, deletion.requestDelete],);+ // Bulk-action set: primary "Save as resources" (most common workflow on this+ // page — promote interesting artifacts into the global library), copy-paths+ // in overflow, destructive Delete on the right.+ const fileManagerBulkActions = useMemo<FileManagerBulkAction[]>(+ () => [+ bulkPromoteAction((files) => setFilesToPromote(files)),+ bulkCopyPathsAction(handleBulkCopyPaths),+ bulkDeleteAction(deletion.deleteBulk),+ ],+ [deletion.deleteBulk, handleBulkCopyPaths],+ );+const handleOpenPullDialog = useCallback(() => setIsPullDialogOpen(true), []);const handleClosePullDialog = useCallback(() => setIsPullDialogOpen(false), []);const handleOpenAttachResourcesDialog = useCallback(() => setIsAttachResourcesDialogOpen(true), []);@@ -279,11 +318,11 @@ const FlowFiles = () => {<FileManageractions={fileManagerActions}+ bulkActions={fileManagerBulkActions}className="min-h-0 flex-1"emptyState={noFilesState}files={fileNodes}isLoading={isInitialLoading}- onBulkDelete={deletion.deleteBulk}rootGroups={ROOT_GROUPS}search={{ emptyState: noMatchesState, query: search.debouncedQuery }}/>@@ -303,7 +342,7 @@ const FlowFiles = () => {/><FlowFilesPromoteDialog- file={fileToPromote}+ files={filesToPromote}flowId={flowId}onClose={handleClosePromoteDialog}/>diff --git a/frontend/src/features/resources/resources-copy-dialog.tsx b/frontend/src/features/resources/resources-copy-dialog.tsxindex caa531db..eec0d61f 100644--- a/frontend/src/features/resources/resources-copy-dialog.tsx+++ b/frontend/src/features/resources/resources-copy-dialog.tsx@@ -1,6 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod';import { Copy, Loader2 } from 'lucide-react';-import { useEffect } from 'react';+import { useEffect, useMemo } from 'react';import { useForm } from 'react-hook-form';import type { FileNode } from '@/components/file-manager';@@ -14,17 +14,38 @@ import { Switch } from '@/components/ui/switch';import { ResourcesConflictDialog } from './resources-conflict-dialog';import { resourcesCopyFormSchema, type ResourcesCopyFormValues, useResourcesCopy } from './use-resources-copy';+/** Guaranteed non-empty by `ResourcesCopyDialog` (which gates rendering on `files.length > 0`). */interface ResourcesCopyDialogFormProps {- file: FileNode;+ files: readonly [FileNode, ...FileNode[]];onClose: () => void;}interface ResourcesCopyDialogProps {- file: FileNode | null;+ /**+ * One or more files to copy. Single-element arrays render the "duplicate to a+ * new path" UI (full path edit with a `-copy` suffix), multi-element arrays+ * render the "copy N items into…" UI (destination directory only — every file+ * keeps its current name).+ *+ * Use `null` or an empty array to close the dialog.+ */+ files: FileNode[] | null;onClose: () => void;}-const buildDefaultDestination = (file: FileNode): string => {+/** Parent directory of a virtual path; `''` for root. */+const getParentDir = (path: string): string => {+ const idx = path.lastIndexOf('/');++ return idx === -1 ? '' : path.slice(0, idx);+};++/**+ * Build the single-file copy default destination. Inserts a `-copy` suffix+ * before the extension so the user can submit immediately without manual+ * editing — same convention as Finder's "Duplicate".+ */+const buildSingleDefaultDestination = (file: FileNode): string => {const segments = file.path.split('/');const lastSegment = segments.at(-1) ?? file.name;const parent = segments.slice(0, -1).join('/');@@ -36,12 +57,32 @@ const buildDefaultDestination = (file: FileNode): string => {return parent ? `${parent}/${candidateName}` : candidateName;};-const ResourcesCopyDialogForm = ({ file, onClose }: ResourcesCopyDialogFormProps) => {+/**+ * Default destination directory for a multi-file copy: the common parent if+ * every selection lives under the same one, otherwise the library root.+ * Mirrors `ResourcesMoveDialog`'s logic.+ */+const computeCommonParent = (files: readonly [FileNode, ...FileNode[]]): string => {+ const first = getParentDir(files[0].path);++ return files.every((file) => getParentDir(file.path) === first) ? first : '';+};++const ResourcesCopyDialogForm = ({ files, onClose }: ResourcesCopyDialogFormProps) => {const { cancelConflicts, copy, isCopying, pendingConflicts, resolveConflicts } = useResourcesCopy();+ const isMulti = files.length > 1;++ const defaultDestination = useMemo(() => {+ if (isMulti) {+ return computeCommonParent(files);+ }++ return buildSingleDefaultDestination(files[0]);+ }, [files, isMulti]);const form = useForm<ResourcesCopyFormValues>({defaultValues: {- destination: buildDefaultDestination(file),+ destination: defaultDestination,shouldOverwrite: false,},mode: 'onChange',@@ -50,22 +91,39 @@ const ResourcesCopyDialogForm = ({ file, onClose }: ResourcesCopyDialogFormPropsuseEffect(() => {form.reset({- destination: buildDefaultDestination(file),+ destination: defaultDestination,shouldOverwrite: false,});- }, [file, form]);+ }, [defaultDestination, form]);const handleSubmit = form.handleSubmit(async (values) => {- const wasCopied = await copy(file.path, values);+ if (isMulti) {+ const targetDir = values.destination.trim().replace(/\/+$/, '');+ const results = await Promise.all(+ files.map((file) => {+ const destination = targetDir ? `${targetDir}/${file.name}` : file.name;++ return copy(file.path, { destination, shouldOverwrite: values.shouldOverwrite });+ }),+ );++ if (results.every(Boolean)) {+ onClose();+ }++ return;+ }++ const wasCopied = await copy(files[0].path, values);if (wasCopied) {onClose();}});- // After the user picks "Replace" in the conflict dialog the hook retries the copy- // with `force = true`. Close the form so it doesn't leave a stale modal — the- // resolveConflicts promise resolves once every retry has settled.+ // After the user picks "Replace" in the conflict dialog the hook retries every+ // failed copy with `force = true`. Close the form so it doesn't leave a stale+ // modal — the resolveConflicts promise resolves once every retry has settled.const handleResolveConflicts = async () => {await resolveConflicts();onClose();@@ -73,15 +131,23 @@ const ResourcesCopyDialogForm = ({ file, onClose }: ResourcesCopyDialogFormPropsconst isSubmitDisabled = !form.formState.isValid || isCopying;+ const titleText = isMulti ? `Copy ${files.length} items` : files[0].isDir ? 'Copy directory' : 'Copy resource';+return (<DialogContent><DialogHeader><DialogTitle className="flex items-center gap-2"><Copy className="size-4" />- {file.isDir ? 'Copy directory' : 'Copy resource'}+ {titleText}</DialogTitle><DialogDescription>- Duplicate <code>{file.path}</code> to a new path.+ {isMulti ? (+ <>Duplicate every selected item into the destination directory.</>+ ) : (+ <>+ Duplicate <code>{files[0].path}</code> to a new path.+ </>+ )}</DialogDescription></DialogHeader>@@ -95,16 +161,26 @@ const ResourcesCopyDialogForm = ({ file, onClose }: ResourcesCopyDialogFormPropsname="destination"render={({ field }) => (<FormItem>- <FormLabel>Destination path</FormLabel>+ <FormLabel>{isMulti ? 'Destination directory' : 'Destination path'}</FormLabel><FormControl><Input{...field}autoComplete="off"autoFocusdisabled={isCopying}+ placeholder={isMulti ? 'Leave empty to copy into the library root' : undefined}/></FormControl>- <FormDescription>Relative path inside your library.</FormDescription>+ <FormDescription>+ {isMulti ? (+ <>+ Relative directory inside your library. Leave empty for the root. Each item+ keeps its current filename.+ </>+ ) : (+ <>Relative path inside your library.</>+ )}+ </FormDescription><FormMessage /></FormItem>)}@@ -123,7 +199,9 @@ const ResourcesCopyDialogForm = ({ file, onClose }: ResourcesCopyDialogFormProps/></FormControl><FormLabel className="cursor-pointer font-normal">- Overwrite or merge if the destination already exists+ {isMulti+ ? 'Overwrite or merge if any destination already exists'+ : 'Overwrite or merge if the destination already exists'}</FormLabel></FormItem>)}@@ -158,21 +236,25 @@ const ResourcesCopyDialogForm = ({ file, onClose }: ResourcesCopyDialogFormProps);};-export const ResourcesCopyDialog = ({ file, onClose }: ResourcesCopyDialogProps) => {+export const ResourcesCopyDialog = ({ files, onClose }: ResourcesCopyDialogProps) => {const handleDialogOpenChange = (nextOpen: boolean) => {if (!nextOpen) {onClose();}};+ // Narrow to a non-empty tuple so the inner form can index `files[0]` without+ // optional-chain noise. The Dialog only mounts when this guard passes.+ const nonEmptyFiles = files && files.length > 0 ? (files as [FileNode, ...FileNode[]]) : null;+return (<DialogonOpenChange={handleDialogOpenChange}- open={!!file}+ open={!!nonEmptyFiles}>- {file && (+ {nonEmptyFiles && (<ResourcesCopyDialogForm- file={file}+ files={nonEmptyFiles}onClose={onClose}/>)}diff --git a/frontend/src/features/resources/resources-move-dialog.tsx b/frontend/src/features/resources/resources-move-dialog.tsxindex e94862ce..4ec1c4a4 100644--- a/frontend/src/features/resources/resources-move-dialog.tsx+++ b/frontend/src/features/resources/resources-move-dialog.tsx@@ -1,6 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod';import { FolderInput, Loader2 } from 'lucide-react';-import { useEffect } from 'react';+import { useEffect, useMemo } from 'react';import { useForm } from 'react-hook-form';import type { FileNode } from '@/components/file-manager';@@ -14,22 +14,61 @@ import { Switch } from '@/components/ui/switch';import { ResourcesConflictDialog } from './resources-conflict-dialog';import { resourcesMoveFormSchema, type ResourcesMoveFormValues, useResourcesMove } from './use-resources-move';+/** Guaranteed non-empty by `ResourcesMoveDialog` (which gates rendering on `files.length > 0`). */interface ResourcesMoveDialogFormProps {- file: FileNode;+ files: readonly [FileNode, ...FileNode[]];onClose: () => void;}interface ResourcesMoveDialogProps {- file: FileNode | null;+ /**+ * One or more files to move. Single-element arrays render the "rename or move"+ * UI (full path edit), multi-element arrays render the "move N items into…"+ * UI (destination directory only — every file keeps its current name).+ *+ * Use `null` or an empty array to close the dialog.+ */+ files: FileNode[] | null;onClose: () => void;}-const ResourcesMoveDialogForm = ({ file, onClose }: ResourcesMoveDialogFormProps) => {+/** Parent directory of a virtual path; `''` for root. Mirrors `getParentDir` from the DnD hook. */+const getParentDir = (path: string): string => {+ const idx = path.lastIndexOf('/');++ return idx === -1 ? '' : path.slice(0, idx);+};++/**+ * Default destination directory for a multi-file move. Use the common parent+ * directory when every selected file lives under the same one (so the user+ * sees "where things came from"); otherwise default to the library root so+ * they don't have to first clear an unrelated path.+ */+const computeCommonParent = (files: readonly [FileNode, ...FileNode[]]): string => {+ const first = getParentDir(files[0].path);++ return files.every((file) => getParentDir(file.path) === first) ? first : '';+};++const ResourcesMoveDialogForm = ({ files, onClose }: ResourcesMoveDialogFormProps) => {const { cancelConflicts, isMoving, move, pendingConflicts, resolveConflicts } = useResourcesMove();+ const isMulti = files.length > 1;++ // Default destination differs by mode: single-file rename keeps the existing+ // path so the user can edit only the name part; multi-file move pre-fills+ // the common parent directory so a no-op submission is impossible.+ const defaultDestination = useMemo(() => {+ if (isMulti) {+ return computeCommonParent(files);+ }++ return files[0].path;+ }, [files, isMulti]);const form = useForm<ResourcesMoveFormValues>({defaultValues: {- destination: file.path,+ destination: defaultDestination,shouldOverwrite: false,},mode: 'onChange',@@ -38,22 +77,46 @@ const ResourcesMoveDialogForm = ({ file, onClose }: ResourcesMoveDialogFormPropsuseEffect(() => {form.reset({- destination: file.path,+ destination: defaultDestination,shouldOverwrite: false,});- }, [file, form]);+ }, [defaultDestination, form]);const handleSubmit = form.handleSubmit(async (values) => {- const wasMoved = await move(file.path, values);+ if (isMulti) {+ // Multi-file move: `destination` is the *target directory*, every+ // file keeps its name. Strip a trailing `/` for consistency with the+ // single-file branch (which never has one). Empty string = root.+ const targetDir = values.destination.trim().replace(/\/+$/, '');+ const results = await Promise.all(+ files.map((file) => {+ const destination = targetDir ? `${targetDir}/${file.name}` : file.name;++ return move(file.path, { destination, shouldOverwrite: values.shouldOverwrite });+ }),+ );++ // Close only when nothing is left over (every move either succeeded+ // or surfaced a conflict that the conflict dialog will pick up).+ // If ANY move actually completed, the bulk bar's selection paths+ // are stale anyway — the host clears them after onSelect resolves.+ if (results.every(Boolean)) {+ onClose();+ }++ return;+ }++ const wasMoved = await move(files[0].path, values);if (wasMoved) {onClose();}});- // After the user picks "Replace" in the conflict dialog the hook retries the move- // with `force = true`. Close the form so it doesn't leave a stale modal — the- // resolveConflicts promise resolves once every retry has settled.+ // After the user picks "Replace" in the conflict dialog the hook retries every+ // failed move with `force = true`. Close the form so it doesn't leave a stale+ // modal — the resolveConflicts promise resolves once every retry has settled.const handleResolveConflicts = async () => {await resolveConflicts();onClose();@@ -61,15 +124,27 @@ const ResourcesMoveDialogForm = ({ file, onClose }: ResourcesMoveDialogFormPropsconst isSubmitDisabled = !form.formState.isValid || isMoving;+ const titleText = isMulti+ ? `Move ${files.length} items`+ : files[0].isDir+ ? 'Move directory'+ : 'Rename or move resource';+return (<DialogContent><DialogHeader><DialogTitle className="flex items-center gap-2"><FolderInput className="size-4" />- {file.isDir ? 'Move directory' : 'Rename or move resource'}+ {titleText}</DialogTitle><DialogDescription>- Update the path of <code>{file.path}</code>.+ {isMulti ? (+ <>Move every selected item into the destination directory.</>+ ) : (+ <>+ Update the path of <code>{files[0].path}</code>.+ </>+ )}</DialogDescription></DialogHeader>@@ -83,18 +158,28 @@ const ResourcesMoveDialogForm = ({ file, onClose }: ResourcesMoveDialogFormPropsname="destination"render={({ field }) => (<FormItem>- <FormLabel>New path</FormLabel>+ <FormLabel>{isMulti ? 'Destination directory' : 'New path'}</FormLabel><FormControl><Input{...field}autoComplete="off"autoFocusdisabled={isMoving}+ placeholder={isMulti ? 'Leave empty to move into the library root' : undefined}/></FormControl><FormDescription>- Relative path inside your library. End with <code>/</code> to drop the entry into- that directory.+ {isMulti ? (+ <>+ Relative directory inside your library. Leave empty for the root. Each item+ keeps its current filename.+ </>+ ) : (+ <>+ Relative path inside your library. End with <code>/</code> to drop the entry+ into that directory.+ </>+ )}</FormDescription><FormMessage /></FormItem>@@ -114,7 +199,9 @@ const ResourcesMoveDialogForm = ({ file, onClose }: ResourcesMoveDialogFormProps/></FormControl><FormLabel className="cursor-pointer font-normal">- Overwrite if a resource already exists at the destination+ {isMulti+ ? 'Overwrite if a resource already exists at any destination'+ : 'Overwrite if a resource already exists at the destination'}</FormLabel></FormItem>)}@@ -149,21 +236,25 @@ const ResourcesMoveDialogForm = ({ file, onClose }: ResourcesMoveDialogFormProps);};-export const ResourcesMoveDialog = ({ file, onClose }: ResourcesMoveDialogProps) => {+export const ResourcesMoveDialog = ({ files, onClose }: ResourcesMoveDialogProps) => {const handleDialogOpenChange = (nextOpen: boolean) => {if (!nextOpen) {onClose();}};+ // Narrow to a non-empty tuple so the inner form can index `files[0]` without+ // optional-chain noise. The Dialog only mounts when this guard passes.+ const nonEmptyFiles = files && files.length > 0 ? (files as [FileNode, ...FileNode[]]) : null;+return (<DialogonOpenChange={handleDialogOpenChange}- open={!!file}+ open={!!nonEmptyFiles}>- {file && (+ {nonEmptyFiles && (<ResourcesMoveDialogForm- file={file}+ files={nonEmptyFiles}onClose={onClose}/>)}diff --git a/frontend/src/pages/resources/resources.tsx b/frontend/src/pages/resources/resources.tsxindex a8a751c3..4cf7a05b 100644--- a/frontend/src/pages/resources/resources.tsx+++ b/frontend/src/pages/resources/resources.tsx@@ -3,11 +3,16 @@ import { useCallback, useMemo, useState } from 'react';import { toast } from 'sonner';import {+ bulkCopyAction,+ bulkCopyPathsAction,+ bulkDeleteAction,+ bulkMoveAction,copyPathAction,deleteAction,downloadAction,FileManager,type FileManagerAction,+ type FileManagerBulkAction,type FileNode,} from '@/components/file-manager';import ConfirmationDialog from '@/components/shared/confirmation-dialog';@@ -24,7 +29,7 @@ import { ResourcesConflictDialog } from '@/features/resources/resources-conflictimport { ResourcesCopyDialog } from '@/features/resources/resources-copy-dialog';import { ResourcesMkdirDialog } from '@/features/resources/resources-mkdir-dialog';import { ResourcesMoveDialog } from '@/features/resources/resources-move-dialog';-import { buildResourceDownloadHref, toFileNode } from '@/features/resources/resources-utils';+import { buildResourceDownloadHref, pluralizeItems, toFileNode } from '@/features/resources/resources-utils';import { useResourcesDelete } from '@/features/resources/use-resources-delete';import { useResourcesMove } from '@/features/resources/use-resources-move';import { useResourcesSearch } from '@/features/resources/use-resources-search';@@ -38,8 +43,11 @@ const Resources = () => {const search = useResourcesSearch();const [isMkdirOpen, setIsMkdirOpen] = useState(false);- const [fileToRename, setFileToRename] = useState<FileNode | null>(null);- const [fileToCopy, setFileToCopy] = useState<FileNode | null>(null);+ // Both dialogs accept an array now: a row-action click pushes a single-element+ // array, the bulk bar pushes the full deduped selection. Empty / null array+ // closes the dialog.+ const [filesToMove, setFilesToMove] = useState<FileNode[] | null>(null);+ const [filesToCopy, setFilesToCopy] = useState<FileNode[] | null>(null);const upload = useResourcesUpload();const deletion = useResourcesDelete();@@ -83,6 +91,28 @@ const Resources = () => {toast.error('Failed to copy path');}, []);+ /**+ * Bulk "copy paths" handler: join every selected file's path with `\n` so the+ * user can paste a clean newline-separated list straight into the agent chat,+ * a shell command, or notes. Reports the count for clarity — silent failures+ * confuse users when the clipboard happens to already contain the same text.+ */+ const handleBulkCopyPaths = useCallback(async (paths: string[]) => {+ if (paths.length === 0) {+ return;+ }++ const wasCopied = await copyToClipboard(paths.join('\n'));++ if (wasCopied) {+ toast.success(`${paths.length} ${pluralizeItems(paths.length)} copied to clipboard`);++ return;+ }++ toast.error('Failed to copy paths');+ }, []);+/*** "Open" gesture — fires on double-click or Enter for a file row.* Triggers the same download the dropdown's Download action would, by clicking@@ -110,20 +140,33 @@ const Resources = () => {icon: FileSymlink,id: 'resources-rename',label: 'Rename or move',- onSelect: (file) => setFileToRename(file),+ onSelect: (file) => setFilesToMove([file]),},{appliesToDirs: true,icon: Copy,id: 'resources-copy',label: 'Copy to…',- onSelect: (file) => setFileToCopy(file),+ onSelect: (file) => setFilesToCopy([file]),},deleteAction(deletion.requestDelete),],[deletion.requestDelete, handleCopyPath],);+ // Bulk-action set, rendered in the bulk-actions bar when at least one row+ // is selected. Order matters — primary CTAs first, then less frequent+ // actions in the overflow `…` menu, then destructive Delete on the right.+ const fileManagerBulkActions = useMemo<FileManagerBulkAction[]>(+ () => [+ bulkMoveAction((files) => setFilesToMove(files)),+ bulkCopyAction((files) => setFilesToCopy(files), { overflow: true }),+ bulkCopyPathsAction(handleBulkCopyPaths),+ bulkDeleteAction(deletion.deleteBulk),+ ],+ [deletion.deleteBulk, handleBulkCopyPaths],+ );+const handleDeleteDialogOpenChange = useCallback((nextOpen: boolean) => {if (!nextOpen) {@@ -277,11 +320,11 @@ const Resources = () => {<FileManageractions={fileManagerActions}+ bulkActions={fileManagerBulkActions}className="min-h-0 flex-1"emptyState={noResourcesState}files={fileNodes}isLoading={isInitialLoading}- onBulkDelete={deletion.deleteBulk}onMoveItems={handleMoveItems}onOpen={handleOpenFile}search={{ emptyState: noMatchesState, query: search.debouncedQuery }}@@ -293,13 +336,13 @@ const Resources = () => {/><ResourcesMoveDialog- file={fileToRename}- onClose={() => setFileToRename(null)}+ files={filesToMove}+ onClose={() => setFilesToMove(null)}/><ResourcesCopyDialog- file={fileToCopy}- onClose={() => setFileToCopy(null)}+ files={filesToCopy}+ onClose={() => setFilesToCopy(null)}/><ResourcesConflictDialog