Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
refactor(frontend): unify overwrite flow and atomic multi-path file APIs
Sergey Kozyrenko76cb4c12836d
diff --git a/frontend/src/components/file-manager/file-manager-actions.tsx b/frontend/src/components/shared/file-manager/file-manager-actions.tsxsimilarity index 72%rename from frontend/src/components/file-manager/file-manager-actions.tsxrename to frontend/src/components/shared/file-manager/file-manager-actions.tsxindex 7e853a10..a2712fc0 100644--- a/frontend/src/components/file-manager/file-manager-actions.tsx+++ b/frontend/src/components/shared/file-manager/file-manager-actions.tsx@@ -154,3 +154,66 @@ export const bulkPromoteAction = (onSelect: onPromote,overflow: options.overflow,});++interface BulkDownloadOptions {+ /** Override the suggested filename hint passed to the browser. */+ getDownloadName?: (files: FileNode[]) => string;+ label?: string;+ overflow?: boolean;+}++/**+ * Default browser-side filename hint for bulk download. Mirrors what the+ * backend will set via `Content-Disposition` so the browser shows a sensible+ * name even when the response header is missing or stripped:+ *+ * - 1 file → original filename+ * - 1 directory → `${name}.zip`+ * - many entries → `download.zip`+ */+const defaultBulkDownloadName = (files: FileNode[]): string => {+ const [single, ...rest] = files;++ if (single && rest.length === 0) {+ return single.isDir ? `${single.name}.zip` : single.name;+ }++ return 'download.zip';+};++/**+ * Built-in "download" bulk action. The host supplies a function that builds the+ * download URL from the selection (typically with `?paths[]=…&paths[]=…`); the+ * helper takes care of triggering the actual browser download via a transient+ * `<a download>` element. Backend decides the response shape: a single file is+ * served as-is, anything else is packaged into a ZIP archive.+ */+export const bulkDownloadAction = (+ getDownloadHref: (files: FileNode[]) => string,+ options: BulkDownloadOptions = {},+): FileManagerBulkAction => ({+ icon: Download,+ id: '__builtin_bulk_download',+ label: options.label ?? 'Download',+ onSelect: (files) => {+ if (files.length === 0) {+ return;+ }++ const href = getDownloadHref(files);++ // Trigger the download via a transient anchor so the browser respects+ // the `download` attribute and the backend's `Content-Disposition`.+ // `window.open` would do, but it can be blocked as a popup and doesn't+ // honour the filename hint the same way.+ const anchor = document.createElement('a');++ anchor.href = href;+ anchor.download = (options.getDownloadName ?? defaultBulkDownloadName)(files);+ anchor.rel = 'noopener';+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ },+ overflow: options.overflow,+});diff --git a/frontend/src/components/file-manager/file-manager-bulk-actions-bar.tsx b/frontend/src/components/shared/file-manager/file-manager-bulk-actions-bar.tsxsimilarity index 100%rename from frontend/src/components/file-manager/file-manager-bulk-actions-bar.tsxrename to frontend/src/components/shared/file-manager/file-manager-bulk-actions-bar.tsxdiff --git a/frontend/src/components/file-manager/file-manager-highlighted-name.tsx b/frontend/src/components/shared/file-manager/file-manager-highlighted-name.tsxsimilarity index 100%rename from frontend/src/components/file-manager/file-manager-highlighted-name.tsxrename to frontend/src/components/shared/file-manager/file-manager-highlighted-name.tsxdiff --git a/frontend/src/components/file-manager/file-manager-icons.tsx b/frontend/src/components/shared/file-manager/file-manager-icons.tsxsimilarity index 100%rename from frontend/src/components/file-manager/file-manager-icons.tsxrename to frontend/src/components/shared/file-manager/file-manager-icons.tsxdiff --git a/frontend/src/components/file-manager/file-manager-row.tsx b/frontend/src/components/shared/file-manager/file-manager-row.tsxsimilarity index 92%rename from frontend/src/components/file-manager/file-manager-row.tsxrename to frontend/src/components/shared/file-manager/file-manager-row.tsxindex 2a08ebb5..68230f44 100644--- a/frontend/src/components/file-manager/file-manager-row.tsx+++ b/frontend/src/components/shared/file-manager/file-manager-row.tsx@@ -59,6 +59,12 @@ export interface FileManagerRowHandlers {onClick: (event: ReactMouseEvent, path: string, subtreePaths?: readonly string[]) => void;onFocusRow: (path: string) => void;onOpen?: (file: FileNode) => void;+ /**+ * Optional override for the directory "open" gesture (double-click / Enter).+ * When set, replaces the default expand/collapse — used by navigation-style+ * file browsers (e.g. drilling into a remote folder by replacing the listing).+ */+ onOpenDirectory?: (dir: FileNode) => void;onToggleExpand: (path: string, wasExpanded: boolean) => void;/*** Polymorphic selection toggle: file rows pass just `path`, directory rows@@ -137,7 +143,7 @@ const FileManagerRowImpl = ({isSizeVisible,searchQuery,} = display;- const { onClick, onFocusRow, onOpen, onToggleExpand, onToggleSelection } = handlers;+ const { onClick, onFocusRow, onOpen, onOpenDirectory, onToggleExpand, onToggleSelection } = handlers;const { icon: Icon, tone } = useMemo(() =>@@ -161,11 +167,15 @@ const FileManagerRowImpl = ({onClick(event, file.path, file.isDir ? dirSubtreePaths : undefined);};- // Double-click is the row's "open" gesture. For directories it expands or- // collapses (decoupling expansion from the single click keeps `Shift`/`Cmd`+click- // pure selection gestures and matches Finder/Explorer). For files it forwards+ // Double-click is the row's "open" gesture. Directories default to expand /+ // collapse (decoupling expansion from the single click keeps `Shift`/`Cmd`+click+ // pure selection gestures and matches Finder/Explorer); navigation-style+ // browsers can override this by passing `onOpenDirectory`, which gets called+ // instead — typical for drilling into a remote container directory by+ // replacing the listing rather than expanding inline. Files always forward// to `onOpen` — typically wired to download / preview / open-in-tab. The- // chevron icon and arrow keys remain alternative ways to expand without selecting.+ // chevron icon on the row's left edge always toggles expand/collapse for+ // directories, regardless of `onOpenDirectory`.const handleRowDoubleClick = (event: ReactMouseEvent) => {if (isClickInsideSkipZone(event.target)) {return;@@ -173,7 +183,12 @@ const FileManagerRowImpl = ({if (file.isDir) {event.preventDefault();- onToggleExpand(file.path, isExpanded);++ if (onOpenDirectory) {+ onOpenDirectory(file);+ } else {+ onToggleExpand(file.path, isExpanded);+ }return;}diff --git a/frontend/src/components/file-manager/file-manager-skeleton.tsx b/frontend/src/components/shared/file-manager/file-manager-skeleton.tsxsimilarity index 96%rename from frontend/src/components/file-manager/file-manager-skeleton.tsxrename to frontend/src/components/shared/file-manager/file-manager-skeleton.tsxindex 219373d9..8ae2e5e0 100644--- a/frontend/src/components/file-manager/file-manager-skeleton.tsx+++ b/frontend/src/components/shared/file-manager/file-manager-skeleton.tsx@@ -100,9 +100,7 @@ export const FileManagerSkeleton = ({</div>{isSizeVisible && (- <Skeleton- className={cn('h-3 shrink-0', row.isDir ? 'w-0 opacity-0' : row.sizeWidth)}- />+ <Skeleton className={cn('h-3 shrink-0', row.isDir ? 'w-0 opacity-0' : row.sizeWidth)} />)}{isModifiedVisible && <Skeleton className="h-3 w-16 shrink-0" />}{hasActions && (diff --git a/frontend/src/components/file-manager/file-manager-tree-node.tsx b/frontend/src/components/shared/file-manager/file-manager-tree-node.tsxsimilarity index 100%rename from frontend/src/components/file-manager/file-manager-tree-node.tsxrename to frontend/src/components/shared/file-manager/file-manager-tree-node.tsxdiff --git a/frontend/src/components/file-manager/file-manager-types.ts b/frontend/src/components/shared/file-manager/file-manager-types.tssimilarity index 91%rename from frontend/src/components/file-manager/file-manager-types.tsrename to frontend/src/components/shared/file-manager/file-manager-types.tsindex ae43d05e..f5237d1c 100644--- a/frontend/src/components/file-manager/file-manager-types.ts+++ b/frontend/src/components/shared/file-manager/file-manager-types.ts@@ -162,13 +162,25 @@ export interface FileManagerProps {*/onMoveItems?: (sources: FileNode[], destinationDir: string) => Promise<void> | void;/**- * Fired when the user "opens" a *file* row via double-click or `Enter`. Directories- * are not passed through this callback; they always toggle expand/collapse on- * activation, mirroring Finder/Explorer semantics.+ * Fired when the user "opens" a *file* row via double-click or `Enter`.+ * Directories go through `onOpenDirectory` instead; when that is omitted,+ * they fall back to the default Finder/Explorer-style expand/collapse.** Use it to wire downloads, in-app previews, or open-in-tab behavior.*/onOpen?: (file: FileNode) => void;+ /**+ * Fired when the user "opens" a *directory* row via double-click or `Enter`.+ * When provided, **replaces** the default expand/collapse gesture — useful+ * for navigation-style file browsers (e.g. drilling into a remote directory+ * by replacing the listing instead of expanding inline). When omitted,+ * directories keep the default expand/collapse behaviour.+ *+ * The chevron icon on the row's left edge always toggles expand/collapse+ * regardless of this prop, so the user still has access to inline+ * exploration when it makes sense.+ */+ onOpenDirectory?: (dir: FileNode) => void;/*** Fires whenever the multi-selection changes. Use it from selection-only* flows (e.g. resource pickers) where the parent owns its own confirm buttondiff --git a/frontend/src/components/file-manager/file-manager-utils.test.ts b/frontend/src/components/shared/file-manager/file-manager-utils.test.tssimilarity index 100%rename from frontend/src/components/file-manager/file-manager-utils.test.tsrename to frontend/src/components/shared/file-manager/file-manager-utils.test.tsdiff --git a/frontend/src/components/file-manager/file-manager-utils.ts b/frontend/src/components/shared/file-manager/file-manager-utils.tssimilarity index 100%rename from frontend/src/components/file-manager/file-manager-utils.tsrename to frontend/src/components/shared/file-manager/file-manager-utils.tsdiff --git a/frontend/src/components/file-manager/file-manager.tsx b/frontend/src/components/shared/file-manager/file-manager.tsxsimilarity index 91%rename from frontend/src/components/file-manager/file-manager.tsxrename to frontend/src/components/shared/file-manager/file-manager.tsxindex 08bbe29c..788f90be 100644--- a/frontend/src/components/file-manager/file-manager.tsx+++ b/frontend/src/components/shared/file-manager/file-manager.tsx@@ -38,6 +38,7 @@ export const FileManager = ({labels,onMoveItems,onOpen,+ onOpenDirectory,onSelectionChange,rootGroups,search,@@ -132,19 +133,36 @@ export const FileManager = ({onSelectionChangeRef.current?.(selectedPaths);}, [selectedPaths]);- // Same latest-ref pattern for `onOpen`: it bleeds into the keyboard handler's- // deps and through `TreeNode` → `Row`, so a non-memoized parent callback would- // otherwise invalidate the memo on every row whenever the parent re-renders.+ // Same latest-ref pattern for `onOpen` / `onOpenDirectory`: both bleed into+ // the keyboard handler's deps and through `TreeNode` → `Row`, so a+ // non-memoized parent callback would otherwise invalidate the memo on every+ // row whenever the parent re-renders.const onOpenRef = useRef(onOpen);+ const onOpenDirectoryRef = useRef(onOpenDirectory);useEffect(() => {onOpenRef.current = onOpen;}, [onOpen]);+ useEffect(() => {+ onOpenDirectoryRef.current = onOpenDirectory;+ }, [onOpenDirectory]);+const handleOpen = useCallback((file: FileNode) => {onOpenRef.current?.(file);}, []);+ // We need the row + keyboard handler to know whether the consumer registered+ // a custom directory-open callback so the default expand/collapse is bypassed+ // only when an override actually exists. Wrapping in a stable callback keeps+ // the row memo intact across parent re-renders, but we conditionally pass it+ // (vs. an always-defined wrapper) by gating on the prop reference itself.+ const handleOpenDirectory = useCallback((dir: FileNode) => {+ onOpenDirectoryRef.current?.(dir);+ }, []);++ const stableHandleOpenDirectory = onOpenDirectory ? handleOpenDirectory : undefined;+// ── roving tabindex / keyboard navigation ────────────────────────────────const [activeRowPath, setActiveRowPath] = useState<null | string>(null);const containerRef = useRef<HTMLDivElement | null>(null);@@ -180,6 +198,7 @@ export const FileManager = ({isCheckboxVisible,onClearSelection: clearSelection,onOpen: handleOpen,+ onOpenDirectory: stableHandleOpenDirectory,onSelectAll: toggleSelectAll,onSetActiveRow: setActiveRowPath,onToggleExpand: toggleExpand,@@ -238,10 +257,11 @@ export const FileManager = ({onClick: onRowClick,onFocusRow: handleRowFocus,onOpen: handleOpen,+ onOpenDirectory: stableHandleOpenDirectory,onToggleExpand: toggleExpand,onToggleSelection,}),- [handleOpen, handleRowFocus, onRowClick, onToggleSelection, toggleExpand],+ [handleOpen, handleRowFocus, onRowClick, onToggleSelection, stableHandleOpenDirectory, toggleExpand],);if (isLoading) {diff --git a/frontend/src/components/file-manager/index.ts b/frontend/src/components/shared/file-manager/index.tssimilarity index 96%rename from frontend/src/components/file-manager/index.tsrename to frontend/src/components/shared/file-manager/index.tsindex 20d9d3c0..7e6be0a1 100644--- a/frontend/src/components/file-manager/index.ts+++ b/frontend/src/components/shared/file-manager/index.ts@@ -3,6 +3,7 @@ export {bulkCopyAction,bulkCopyPathsAction,bulkDeleteAction,+ bulkDownloadAction,bulkMoveAction,bulkPromoteAction,copyPathAction,diff --git a/frontend/src/components/file-manager/use-file-manager-data.ts b/frontend/src/components/shared/file-manager/use-file-manager-data.tssimilarity index 100%rename from frontend/src/components/file-manager/use-file-manager-data.tsrename to frontend/src/components/shared/file-manager/use-file-manager-data.tsdiff --git a/frontend/src/components/file-manager/use-file-manager-dnd.ts b/frontend/src/components/shared/file-manager/use-file-manager-dnd.tssimilarity index 100%rename from frontend/src/components/file-manager/use-file-manager-dnd.tsrename to frontend/src/components/shared/file-manager/use-file-manager-dnd.tsdiff --git a/frontend/src/components/file-manager/use-file-manager-expansion.ts b/frontend/src/components/shared/file-manager/use-file-manager-expansion.tssimilarity index 100%rename from frontend/src/components/file-manager/use-file-manager-expansion.tsrename to frontend/src/components/shared/file-manager/use-file-manager-expansion.tsdiff --git a/frontend/src/components/file-manager/use-file-manager-keyboard.ts b/frontend/src/components/shared/file-manager/use-file-manager-keyboard.tssimilarity index 84%rename from frontend/src/components/file-manager/use-file-manager-keyboard.tsrename to frontend/src/components/shared/file-manager/use-file-manager-keyboard.tsindex 7d23f2ea..48eff556 100644--- a/frontend/src/components/file-manager/use-file-manager-keyboard.ts+++ b/frontend/src/components/shared/file-manager/use-file-manager-keyboard.ts@@ -11,8 +11,14 @@ interface UseFileManagerKeyboardNavigationArgs {focusRow: (path: null | string) => void;isCheckboxVisible: boolean;onClearSelection: () => void;- /** Open handler for file rows (Enter). Directories always toggle expand. */+ /** Open handler for file rows (Enter). */onOpen?: (file: FileNode) => void;+ /**+ * Open handler for directory rows (Enter). When set, replaces the default+ * expand/collapse gesture for the focused folder — used by navigation-style+ * browsers that drill into a remote directory instead of expanding inline.+ */+ onOpenDirectory?: (dir: FileNode) => void;onSelectAll: () => void;onSetActiveRow: (path: null | string) => void;onToggleExpand: (path: string, wasExpanded: boolean) => void;@@ -26,8 +32,8 @@ interface UseFileManagerKeyboardNavigationArgs {/*** Keyboard handler implementing the WAI-ARIA Tree pattern:* Arrow Up/Down → move focus, Home/End → jump to ends, Arrow Left/Right → collapse/expand- * directories, Enter → expand/collapse a directory or fire `onOpen` for a file,- * Space → toggle the row's checkbox (only when checkboxes are shown),+ * directories, Enter → fire `onOpenDirectory`/`onOpen` (file), defaulting to expand/collapse+ * for directories, Space → toggle the row's checkbox (only when checkboxes are shown),* Ctrl/Cmd+A → select all, Escape → clear selection.*/export const useFileManagerKeyboardNavigation = ({@@ -37,6 +43,7 @@ export const useFileManagerKeyboardNavigation = ({isCheckboxVisible,onClearSelection,onOpen,+ onOpenDirectory,onSelectAll,onSetActiveRow,onToggleExpand,@@ -141,7 +148,13 @@ export const useFileManagerKeyboardNavigation = ({event.preventDefault();if (node.isDir) {- onToggleExpand(node.path, expandedPaths.has(node.path));+ // Navigation-style consumers (e.g. remote container browser)+ // override expand/collapse with a "drill in" handler.+ if (onOpenDirectory) {+ onOpenDirectory(node);+ } else {+ onToggleExpand(node.path, expandedPaths.has(node.path));+ }return;}@@ -167,6 +180,7 @@ export const useFileManagerKeyboardNavigation = ({isCheckboxVisible,onClearSelection,onOpen,+ onOpenDirectory,onSelectAll,onSetActiveRow,onToggleExpand,diff --git a/frontend/src/components/file-manager/use-file-manager-selection.ts b/frontend/src/components/shared/file-manager/use-file-manager-selection.tssimilarity index 100%rename from frontend/src/components/file-manager/use-file-manager-selection.tsrename to frontend/src/components/shared/file-manager/use-file-manager-selection.tsdiff --git a/frontend/src/components/shared/overwrite-confirm-dialog.tsx b/frontend/src/components/shared/overwrite-confirm-dialog.tsxnew file mode 100644index 00000000..c492216d--- /dev/null+++ b/frontend/src/components/shared/overwrite-confirm-dialog.tsx@@ -0,0 +1,85 @@+import { Replace } from 'lucide-react';++import ConfirmationDialog from '@/components/shared/confirmation-dialog';++export interface OverwriteConflict {+ destination: string;+ /** Display name extracted from `destination` for the confirm dialog. */+ destinationName: string;+}++interface OverwriteConfirmDialogProps {+ /**+ * Overrides the auto-generated confirm button label. Defaults to+ * `"Replace"` for a single conflict and `"Replace all"` for a batch.+ */+ confirmText?: string;+ /**+ * Conflicts collected from a batch operation. Empty array keeps the dialog hidden.+ * For a single conflict the message names the conflicting item; for many it falls+ * back to a count-based summary (Finder-style "Apply to all").+ */+ conflicts: OverwriteConflict[];+ /**+ * Optional override for the description body. When omitted, the component+ * renders the canonical Finder-style copy that names the single conflicting+ * item or the count for a batch.+ */+ description?: string;+ onCancel: () => void;+ onReplaceAll: () => Promise<unknown> | unknown;+ /** Optional override for the dialog title. Defaults to `"Replace existing item?"`. */+ title?: string;+}++const buildDefaultDescription = (conflicts: OverwriteConflict[]): string | undefined => {+ const single = conflicts.length === 1 ? conflicts[0] : undefined;++ if (single) {+ return `An item named "${single.destinationName}" already exists at /${single.destination}. Do you want to replace it?`;+ }++ if (conflicts.length > 1) {+ return `${conflicts.length} items already exist at the destination. Do you want to replace all of them?`;+ }++ return undefined;+};++const buildDefaultConfirmText = (count: number): string => (count > 1 ? 'Replace all' : 'Replace');++/**+ * Shared "Replace or cancel" confirmation for destructive overwrite flows+ * (move / copy / pull / attach / promote, …). The hook owns the conflict+ * state; this component only renders the prompt and forwards the user's+ * decision back through the callbacks. A batch decision (Replace all) is+ * applied to every pending conflict in one shot — this matches the OS+ * file-manager UX and keeps the user from being prompted N times for the+ * same destination directory.+ */+export const OverwriteConfirmDialog = ({+ confirmText,+ conflicts,+ description,+ onCancel,+ onReplaceAll,+ title = 'Replace existing item?',+}: OverwriteConfirmDialogProps) => (+ <ConfirmationDialog+ cancelText="Cancel"+ confirmIcon={<Replace />}+ confirmText={confirmText ?? buildDefaultConfirmText(conflicts.length)}+ confirmVariant="destructive"+ description={description ?? buildDefaultDescription(conflicts)}+ handleConfirm={async () => {+ await onReplaceAll();+ }}+ handleOpenChange={(nextOpen) => {+ if (!nextOpen) {+ onCancel();+ }+ }}+ isOpen={conflicts.length > 0}+ title={title}+ />+);diff --git a/frontend/src/components/shared/overwrite-cta-buttons.tsx b/frontend/src/components/shared/overwrite-cta-buttons.tsxnew file mode 100644index 00000000..a8b93c13--- /dev/null+++ b/frontend/src/components/shared/overwrite-cta-buttons.tsx@@ -0,0 +1,83 @@+import type { ComponentType } from 'react';++import { Loader2, Replace } from 'lucide-react';++import { Button } from '@/components/ui/button';++interface OverwriteCtaButtonsProps {+ /**+ * When `true` both buttons are greyed-out and clicks are ignored. Use to+ * disable the CTAs based on form validity, selection emptiness, or any+ * other guard that doesn't carry a "request in flight" semantic.+ */+ isDisabled?: boolean;+ /**+ * When `true` both buttons are still disabled, but the primary one+ * additionally swaps its icon for a loading spinner. Wire this to the+ * `is{Verb}ing` flag from the corresponding action hook.+ */+ isProcessing?: boolean;+ onOverwrite: () => void;+ /** Optional primary action. When `primaryType="submit"` this is ignored and form submission is used instead. */+ onPrimary?: () => void;+ overwriteLabel: string;+ primaryIcon: ComponentType<{ className?: string }>;+ primaryLabel: string;+ /**+ * Render type for the primary button. Defaults to `"button"`. Pass `"submit"`+ * when the dialog uses `react-hook-form` and the primary CTA should submit+ * the form so validation runs first. The overwrite CTA is always a plain+ * button — explicit `with overwrite` is intentional and never gated by form+ * validation.+ */+ primaryType?: 'button' | 'submit';+}++/**+ * Two-CTA footer pattern shared by every overwrite-aware dialog (Pull, Attach,+ * Promote, Move, Copy):+ *+ * [ Primary action ] [ Action with overwrite ]+ *+ * The primary action runs the dialog's regular flow (preflight → execute with+ * `force=false`); the overwrite variant sends `force=true` straight away.+ * Visually the latter uses the destructive variant so users can spot it from+ * across the screen — overwriting is always destructive in our model.+ *+ * The component owns the spinner / icon swap, so callers don't repeat that+ * boilerplate in five different dialogs.+ */+export const OverwriteCtaButtons = ({+ isDisabled,+ isProcessing,+ onOverwrite,+ onPrimary,+ overwriteLabel,+ primaryIcon: PrimaryIcon,+ primaryLabel,+ primaryType = 'button',+}: OverwriteCtaButtonsProps) => {+ const disabled = isDisabled || isProcessing;++ return (+ <>+ <Button+ disabled={disabled}+ onClick={primaryType === 'submit' ? undefined : onPrimary}+ type={primaryType}+ >+ {isProcessing ? <Loader2 className="animate-spin" /> : <PrimaryIcon />}+ {primaryLabel}+ </Button>+ <Button+ disabled={disabled}+ onClick={onOverwrite}+ type="button"+ variant="destructive"+ >+ <Replace />+ {overwriteLabel}+ </Button>+ </>+ );+};diff --git a/frontend/src/components/shared/use-overwrite-action.ts b/frontend/src/components/shared/use-overwrite-action.tsnew file mode 100644index 00000000..a6c1abc4--- /dev/null+++ b/frontend/src/components/shared/use-overwrite-action.ts@@ -0,0 +1,194 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import type { OverwriteConflict } from '@/components/shared/overwrite-confirm-dialog';++/**+ * Discriminated outcome of a server action that supports an overwrite flag.+ * Hooks wrapping REST calls return this so the orchestrator can branch+ * between success, a 409 that warrants a user prompt, and any other error+ * (which the hook is expected to surface as a toast on its own).+ *+ * `conflict` carries an optional `conflicts` array — callers that fan out+ * a batch into N parallel requests (e.g. multi-promote) can attach precise+ * per-item descriptors here. When omitted, the hook falls back to+ * `synthesizeFallbackConflicts` and finally to an anonymous descriptor so+ * the dialog still opens with the count-based copy.+ */+export type OverwriteOutcome =+ | { conflicts?: OverwriteConflict[]; kind: 'conflict' }+ | { kind: 'error' }+ | { kind: 'ok' };++/**+ * Anonymous fallback descriptor used when a 409 sneaks through after a clean+ * preflight and the caller didn't provide `synthesizeFallbackConflicts`. Falls+ * back to the count-based copy ("N items already exist...") in+ * `OverwriteConfirmDialog`.+ */+const ANONYMOUS_FALLBACK_CONFLICT: OverwriteConflict = {+ destination: '',+ destinationName: 'an item',+};++interface UseOverwriteActionOptions<TPlan> {+ /**+ * Execute the REST call. Receives the plan + a boolean `force` flag.+ * Should return a discriminated outcome — see `OverwriteOutcome`.+ */+ execute: (plan: TPlan, force: boolean) => Promise<OverwriteOutcome>;+ /**+ * Pure function: inspect the local snapshot and return any destinations+ * that would conflict. Empty array → primary execute proceeds with+ * `force=false`; non-empty → the OverwriteConfirmDialog is opened+ * pre-populated with these descriptors.+ */+ findConflicts: (plan: TPlan) => OverwriteConflict[];+ /** Fired only when `execute` resolves with `kind: 'ok'`. */+ onSuccess?: () => void;+ /**+ * Optional. Synthesizes conflict descriptors for the race-fallback case:+ * preflight returned [] but the server still answered 409. Defaults to a+ * single anonymous descriptor, which makes the dialog show the count-based+ * copy ("Some items already exist…") instead of a per-item name.+ */+ synthesizeFallbackConflicts?: (plan: TPlan) => OverwriteConflict[];+}++interface UseOverwriteActionResult<TPlan> {+ /** Live conflict descriptors. Wire to `<OverwriteConfirmDialog conflicts={…} />`. */+ conflicts: OverwriteConflict[];+ /**+ * Execute the action with `force=true` immediately, bypassing the+ * preflight and the conflict prompt. Wire to the secondary CTA.+ */+ forceExecute: (plan: TPlan) => Promise<void>;+ /** Wire to the `onReplaceAll` handler of `<OverwriteConfirmDialog />`. */+ handleReplaceAll: () => Promise<void>;+ /**+ * Execute the action with the preflight + race-fallback workflow. Wire+ * to the primary CTA.+ */+ primaryExecute: (plan: TPlan) => Promise<void>;+ /** Wire to the `onCancel` handler of `<OverwriteConfirmDialog />`. */+ resetConflicts: () => void;+}++/**+ * Orchestrates the canonical "primary CTA / `… with overwrite` CTA / Replace+ * all" workflow shared by the Pull, Attach, Promote, Move and Copy dialogs.+ *+ * Workflow:+ * 1. The user clicks the **primary CTA** → `primaryExecute(plan)` runs.+ * `findConflicts` is consulted on the local snapshot first; if anything+ * collides, the OverwriteConfirmDialog opens with those descriptors.+ * Otherwise `execute(plan, false)` is dispatched. A 409 from the server+ * (race) auto-opens the dialog with `synthesizeFallbackConflicts` (or an+ * anonymous fallback).+ * 2. The user clicks the **`… with overwrite` CTA** → `forceExecute(plan)`+ * runs `execute(plan, true)` straight away — no preflight, no prompt.+ * 3. Inside the conflict dialog, **Replace all** → `handleReplaceAll()`+ * retries the cached plan with `force=true`. **Cancel** →+ * `resetConflicts()` only closes the prompt; the parent dialog stays+ * open so the user can change the destination and re-submit.+ *+ * Callbacks passed in `options` are read through a ref, so callers don't need+ * to wrap them in `useCallback`. This keeps the hook ergonomic at the call+ * site without sacrificing reference stability for the returned actions.+ */+export const useOverwriteAction = <TPlan,>(+ options: UseOverwriteActionOptions<TPlan>,+): UseOverwriteActionResult<TPlan> => {+ const [conflicts, setConflicts] = useState<OverwriteConflict[]>([]);+ const [pendingPlan, setPendingPlan] = useState<null | TPlan>(null);++ // Read the latest options through a ref so callers can pass inline+ // arrow functions without re-creating the action callbacks every render.+ const optionsRef = useRef(options);++ useEffect(() => {+ optionsRef.current = options;+ }, [options]);++ const settle = useCallback(async (plan: TPlan, force: boolean): Promise<OverwriteOutcome> => {+ const outcome = await optionsRef.current.execute(plan, force);++ if (outcome.kind === 'ok') {+ setConflicts([]);+ setPendingPlan(null);+ optionsRef.current.onSuccess?.();+ }++ return outcome;+ }, []);++ const primaryExecute = useCallback(+ async (plan: TPlan): Promise<void> => {+ const detected = optionsRef.current.findConflicts(plan);++ if (detected.length > 0) {+ setConflicts(detected);+ setPendingPlan(plan);++ return;+ }++ const outcome = await settle(plan, false);++ if (outcome.kind !== 'conflict') {+ return;+ }++ // Resolution chain (most → least specific):+ // 1. precise descriptors returned by `execute` itself (e.g.+ // multi-promote that fanned the batch into N parallel calls+ // and knows exactly which ones came back as 409),+ // 2. caller-supplied synthesizer derived from the plan,+ // 3. an anonymous descriptor that triggers the dialog's+ // count-based copy.+ const fromOutcome = outcome.conflicts ?? [];+ const synthesized = optionsRef.current.synthesizeFallbackConflicts?.(plan) ?? [];++ let final: OverwriteConflict[];++ if (fromOutcome.length > 0) {+ final = fromOutcome;+ } else if (synthesized.length > 0) {+ final = synthesized;+ } else {+ final = [ANONYMOUS_FALLBACK_CONFLICT];+ }++ setConflicts(final);+ setPendingPlan(plan);+ },+ [settle],+ );++ const forceExecute = useCallback(+ async (plan: TPlan): Promise<void> => {+ await settle(plan, true);+ },+ [settle],+ );++ const handleReplaceAll = useCallback(async (): Promise<void> => {+ if (pendingPlan === null) {+ return;+ }++ await settle(pendingPlan, true);+ }, [pendingPlan, settle]);++ const resetConflicts = useCallback(() => {+ setConflicts([]);+ setPendingPlan(null);+ }, []);++ return {+ conflicts,+ forceExecute,+ handleReplaceAll,+ primaryExecute,+ resetConflicts,+ };+};diff --git a/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx b/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsxindex 6b786404..8809885a 100644--- a/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx+++ b/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx@@ -1,19 +1,33 @@-import { FolderInput, Loader2, Search, X } from 'lucide-react';+import { FolderInput, Search, X } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';-import { FileManager, type FileNode } from '@/components/file-manager';+import { FileManager, type FileNode } from '@/components/shared/file-manager';+import { OverwriteConfirmDialog } from '@/components/shared/overwrite-confirm-dialog';+import { OverwriteCtaButtons } from '@/components/shared/overwrite-cta-buttons';+import { useOverwriteAction } from '@/components/shared/use-overwrite-action';import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';-import { Label } from '@/components/ui/label';-import { Switch } from '@/components/ui/switch';import { toFileNode } from '@/features/resources/resources-utils';import { useResources } from '@/providers/resources-provider';+import { findAttachConflicts } from './flow-files-conflicts';import { useFlowFilesAttachResources } from './use-flow-files-attach-resources';+interface AttachPlan {+ /** GraphQL `UserResource.id` values. Sent to the backend (after numeric coercion). */+ ids: readonly string[];+ /** Library paths used for both client-side preflight and the race-fallback synthesizer. */+ resourcePaths: readonly string[];+}+interface FlowFilesAttachResourcesDialogProps {+ /**+ * Snapshot of the flow's cache used for client-side conflict preflight.+ * Provided by the parent so we don't refetch a list the page already owns.+ */+ cachedFiles: readonly FileNode[];flowId: null | string;isOpen: boolean;onClose: () => void;@@ -23,30 +37,23 @@ interface FlowFilesAttachResourcesDialogProps {const EMPTY_SELECTION: ReadonlySet<string> = new Set();const FlowFilesAttachResourcesDialogBody = ({+ cachedFiles,flowId,onClose,onSuccess,}: Omit<FlowFilesAttachResourcesDialogProps, 'isOpen'>) => {const { error: resourcesError, isInitialLoading: isResourcesLoading, resources } = useResources();- const { attach, isAttaching } = useFlowFilesAttachResources({- flowId,- onSuccess: () => {- onSuccess();- onClose();- },- });+ const { attach, isAttaching } = useFlowFilesAttachResources({ flowId });const [selectedPaths, setSelectedPaths] = useState<ReadonlySet<string>>(EMPTY_SELECTION);- const [shouldOverwrite, setShouldOverwrite] = useState(false);const [searchQuery, setSearchQuery] = useState('');const files = useMemo<FileNode[]>(() => resources.map(toFileNode), [resources]);- // Map selected paths back to resource ids on submit. Built lazily — the lookup- // is only walked once per attach, so a per-render `Map` allocation is wasteful.- // `resource.id` is canonically numeric in the cache (see `resources-rest.ts`)- // even though codegen types it as `string`; coerce here so downstream callers- // that rely on the `string` contract (`useFlowFilesAttachResources`) stay safe.+ // Map selected paths back to resource ids on submit. `resource.id` is+ // canonically numeric in the cache (see `resources-rest.ts`) even though+ // codegen types it as `string`; coerce here so downstream callers that+ // rely on the `string` contract stay safe.const pathToIdRef = useMemo(() => {const map = new Map<string, string>();@@ -61,38 +68,78 @@ const FlowFilesAttachResourcesDialogBody = ({setSelectedPaths(next);}, []);- const handleAttach = useCallback(async () => {+ /**+ * Drive the canonical "Attach / Attach with overwrite / Replace all"+ * workflow from the shared hook. The plan carries both the IDs (sent to+ * the backend) and the resource paths (used by preflight against the+ * flow's existing cache mirror).+ */+ const overwriteAction = useOverwriteAction<AttachPlan>({+ execute: async ({ ids }, force) => attach({ ids: [...ids], shouldOverwrite: force }),+ findConflicts: ({ resourcePaths }) => findAttachConflicts(resourcePaths, cachedFiles),+ onSuccess: () => {+ onSuccess();+ onClose();+ },+ synthesizeFallbackConflicts: ({ resourcePaths }) =>+ resourcePaths.map((path) => ({+ destination: `resources/${path}`,+ destinationName: path.split('/').pop() ?? path,+ })),+ });++ /**+ * Build the plan for the current selection. Earlier versions deduped+ * descendants of any picked directory on the assumption that the backend+ * would copy directory trees recursively — it does not. Until that+ * becomes recursive on the backend, the user must multi-select a folder+ * together with its children to attach the contents.+ */+ const buildPlan = useCallback((): AttachPlan | null => {if (selectedPaths.size === 0) {- return;+ return null;}- // Forward every explicitly selected path's ID to the backend. Earlier- // versions deduped descendants of any picked directory on the assumption- // that the backend would copy directory trees recursively — it does not- // (`flowfiles.CopyResourcesToFlow` only `MkdirAll`s a directory ref and- // file refs are copied individually). Until that becomes recursive on- // the backend, the user must multi-select a folder together with its- // children to attach the contents.const ids: string[] = [];+ const resourcePaths: string[] = [];for (const path of selectedPaths) {const id = pathToIdRef.get(path);if (id) {ids.push(id);+ resourcePaths.push(path);}}if (ids.length === 0) {- return;+ return null;+ }++ return { ids, resourcePaths };+ }, [pathToIdRef, selectedPaths]);++ const handlePrimary = useCallback(() => {+ const plan = buildPlan();++ if (plan) {+ void overwriteAction.primaryExecute(plan);}+ }, [buildPlan, overwriteAction]);++ const handleOverwrite = useCallback(() => {+ const plan = buildPlan();- await attach({ ids, shouldOverwrite });- }, [attach, pathToIdRef, selectedPaths, shouldOverwrite]);+ if (plan) {+ void overwriteAction.forceExecute(plan);+ }+ }, [buildPlan, overwriteAction]);const selectedCount = selectedPaths.size;const hasResources = resources.length > 0;- const isAttachDisabled = isAttaching || selectedCount === 0;+ const isAttachDisabled = selectedCount === 0;+ const primaryLabel = selectedCount > 0 ? `Attach ${selectedCount}` : 'Attach';+ const overwriteLabel = selectedCount > 0 ? `Attach ${selectedCount} with overwrite` : 'Attach with overwrite';const emptyState = (<Empty className="border-0">@@ -121,104 +168,103 @@ const FlowFilesAttachResourcesDialogBody = ({);return (- <DialogContent className="flex max-h-[85vh] max-w-3xl flex-col gap-4">- <DialogHeader>- <DialogTitle className="flex items-center gap-2">- <FolderInput className="size-4" />- Attach resources from library- </DialogTitle>- <DialogDescription>- Pick files and/or folders from your global library — they will be copied into{' '}- <code>resources/</code> of this flow and made available at <code>/work/resources</code> inside the- container.- </DialogDescription>- </DialogHeader>-- <div className="flex min-h-0 flex-1 flex-col gap-3">- <InputGroup>- <InputGroupAddon>- <Search />- </InputGroupAddon>- <InputGroupInput- autoComplete="off"- disabled={isAttaching || isResourcesLoading}- onChange={(event) => setSearchQuery(event.target.value)}- placeholder="Search resources..."- type="text"- value={searchQuery}- />- {searchQuery && (- <InputGroupAddon align="inline-end">- <InputGroupButton- onClick={() => setSearchQuery('')}- type="button"- >- <X />- </InputGroupButton>+ <>+ <DialogContent className="flex max-h-[85vh] max-w-3xl flex-col gap-4">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <FolderInput className="size-4" />+ Attach resources from library+ </DialogTitle>+ <DialogDescription>+ Pick files and/or folders from your global library — they will be copied into{' '}+ <code>resources/</code> of this flow and made available at <code>/work/resources</code> inside+ the container.+ </DialogDescription>+ </DialogHeader>++ <div className="flex min-h-0 flex-1 flex-col gap-3">+ <InputGroup>+ <InputGroupAddon>+ <Search /></InputGroupAddon>+ <InputGroupInput+ autoComplete="off"+ disabled={isAttaching || isResourcesLoading}+ onChange={(event) => setSearchQuery(event.target.value)}+ placeholder="Search resources..."+ type="text"+ value={searchQuery}+ />+ {searchQuery && (+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ onClick={() => setSearchQuery('')}+ type="button"+ >+ <X />+ </InputGroupButton>+ </InputGroupAddon>+ )}+ </InputGroup>++ {!isResourcesLoading && resourcesError ? (+ <div className="text-destructive flex flex-1 items-center justify-center rounded-md border p-6 text-center text-sm">+ {resourcesError.message}+ </div>+ ) : (+ <FileManager+ className="min-h-[280px] flex-1"+ emptyState={emptyState}+ enableSelection+ files={files}+ isLoading={isResourcesLoading}+ onSelectionChange={handleSelectionChange}+ search={{ emptyState: noMatchesState, query: searchQuery }}+ />)}- </InputGroup>+ </div>- {!isResourcesLoading && resourcesError ? (- <div className="text-destructive flex flex-1 items-center justify-center rounded-md border p-6 text-center text-sm">- {resourcesError.message}+ <div className="flex items-center justify-between gap-2">+ <span className="text-muted-foreground text-xs">+ {selectedCount > 0+ ? `${selectedCount} selected`+ : hasResources+ ? 'Select one or more items'+ : ''}+ </span>+ <div className="flex flex-wrap justify-end gap-2">+ <Button+ disabled={isAttaching}+ onClick={onClose}+ type="button"+ variant="outline"+ >+ Cancel+ </Button>+ <OverwriteCtaButtons+ isDisabled={isAttachDisabled}+ isProcessing={isAttaching}+ onOverwrite={handleOverwrite}+ onPrimary={handlePrimary}+ overwriteLabel={overwriteLabel}+ primaryIcon={FolderInput}+ primaryLabel={primaryLabel}+ /></div>- ) : (- <FileManager- className="min-h-[280px] flex-1"- emptyState={emptyState}- enableSelection- files={files}- isLoading={isResourcesLoading}- onSelectionChange={handleSelectionChange}- search={{ emptyState: noMatchesState, query: searchQuery }}- />- )}-- <div className="flex items-center gap-2">- <Switch- checked={shouldOverwrite}- disabled={isAttaching}- id="attach-resources-force"- onCheckedChange={setShouldOverwrite}- />- <Label- className="cursor-pointer font-normal"- htmlFor="attach-resources-force"- >- Overwrite existing files in flow- </Label>- </div>- </div>-- <div className="flex items-center justify-between gap-2">- <span className="text-muted-foreground text-xs">- {selectedCount > 0 ? `${selectedCount} selected` : hasResources ? 'Select one or more items' : ''}- </span>- <div className="flex gap-2">- <Button- disabled={isAttaching}- onClick={onClose}- type="button"- variant="outline"- >- Cancel- </Button>- <Button- disabled={isAttachDisabled}- onClick={handleAttach}- type="button"- >- {isAttaching ? <Loader2 className="animate-spin" /> : <FolderInput />}- {selectedCount > 0 ? `Attach ${selectedCount}` : 'Attach'}- </Button></div>- </div>- </DialogContent>+ </DialogContent>++ <OverwriteConfirmDialog+ conflicts={overwriteAction.conflicts}+ onCancel={overwriteAction.resetConflicts}+ onReplaceAll={overwriteAction.handleReplaceAll}+ />+ </>);};export const FlowFilesAttachResourcesDialog = ({+ cachedFiles,flowId,isOpen,onClose,@@ -237,6 +283,7 @@ export const FlowFilesAttachResourcesDialog = ({>{isOpen && (<FlowFilesAttachResourcesDialogBody+ cachedFiles={cachedFiles}flowId={flowId}onClose={onClose}onSuccess={onSuccess}diff --git a/frontend/src/features/flows/files/flow-files-conflicts.ts b/frontend/src/features/flows/files/flow-files-conflicts.tsnew file mode 100644index 00000000..eb1ea58e--- /dev/null+++ b/frontend/src/features/flows/files/flow-files-conflicts.ts@@ -0,0 +1,102 @@+import type { FileNode } from '@/components/shared/file-manager';+import type { OverwriteConflict } from '@/components/shared/overwrite-confirm-dialog';++import { CONTAINER_PATH_PREFIX, RESOURCES_PATH_PREFIX } from './flow-files-constants';++const splitName = (path: string): string => path.split('/').pop() ?? path;++/**+ * Convert an absolute container path (`/work/foo.txt`) into the cache-relative+ * path under which the Pull endpoint stores it (`container/work/foo.txt`).+ *+ * Mirrors the server-side `SanitizeContainerCachePath` normalisation:+ * leading slashes are stripped, the rest is appended verbatim under the+ * synthetic `container/` group prefix used in flow file paths. An empty+ * result is impossible: pulling the literal `/` is rejected by the backend.+ */+const containerPathToCachePath = (containerPath: string): string => {+ const rel = containerPath.replace(/^\/+/, '');++ return `${CONTAINER_PATH_PREFIX}/${rel}`;+};++/**+ * Local preflight for the Pull dialog: cross-check the absolute container+ * paths the user is about to pull against the flow's existing cache mirror.+ *+ * Only **exact** root-path collisions are reported — covers the common case+ * (re-pulling a file the user already has) without an extra REST round-trip.+ * Nested conflicts (the user pulls `/etc/` while only `/etc/nginx.conf` is+ * cached) still surface server-side as a 409 and are auto-redialed by the+ * caller through the same `OverwriteConfirmDialog` flow.+ */+export const findPullConflicts = (+ pullTargets: readonly string[],+ cachedFiles: readonly FileNode[],+): OverwriteConflict[] => {+ if (pullTargets.length === 0 || cachedFiles.length === 0) {+ return [];+ }++ const cachedPaths = new Set(cachedFiles.map((file) => file.path));+ const conflicts: OverwriteConflict[] = [];++ for (const containerPath of pullTargets) {+ const cachePath = containerPathToCachePath(containerPath);++ if (cachedPaths.has(cachePath)) {+ conflicts.push({+ destination: cachePath,+ destinationName: splitName(cachePath),+ });+ }+ }++ return conflicts;+};++/**+ * Local preflight for the Attach Resources dialog. Each picked resource is+ * copied into `resources/<resource_path>` inside the flow cache, so we+ * cross-check the destination paths against the existing flow files.+ *+ * The caller passes the resource virtual paths (`foo/bar.txt`) — exactly the+ * shape stored in the resource library — and the deduped list of flow files.+ * Directory resources never collide on their own (the backend always+ * `MkdirAll`s parents), so we keep the check focused on file paths.+ */+export const findAttachConflicts = (+ selectedResourcePaths: readonly string[],+ cachedFiles: readonly FileNode[],+): OverwriteConflict[] => {+ if (selectedResourcePaths.length === 0 || cachedFiles.length === 0) {+ return [];+ }++ const flowResourcePaths = new Set<string>();++ for (const file of cachedFiles) {+ if (!file.isDir && file.path.startsWith(`${RESOURCES_PATH_PREFIX}/`)) {+ flowResourcePaths.add(file.path);+ }+ }++ if (flowResourcePaths.size === 0) {+ return [];+ }++ const conflicts: OverwriteConflict[] = [];++ for (const resourcePath of selectedResourcePaths) {+ const destination = `${RESOURCES_PATH_PREFIX}/${resourcePath}`;++ if (flowResourcePaths.has(destination)) {+ conflicts.push({+ destination,+ destinationName: splitName(resourcePath),+ });+ }+ }++ return conflicts;+};diff --git a/frontend/src/features/flows/files/flow-files-constants.ts b/frontend/src/features/flows/files/flow-files-constants.tsindex 03da26b0..62c77f0b 100644--- a/frontend/src/features/flows/files/flow-files-constants.ts+++ b/frontend/src/features/flows/files/flow-files-constants.ts@@ -1,6 +1,6 @@import { Folder, FolderUp, HardDrive } from 'lucide-react';-import type { FileManagerRootGroup } from '@/components/file-manager';+import type { FileManagerRootGroup } from '@/components/shared/file-manager';export const SEARCH_DEBOUNCE_MS = 300;@@ -16,6 +16,7 @@ export const ROOT_GROUPS: FileManagerRootGroup[] = [export const FLOW_FILES_API_PATH = (flowId: string) => `/flows/${flowId}/files/`;export const FLOW_FILES_PULL_API_PATH = (flowId: string) => `/flows/${flowId}/files/pull`;+export const FLOW_FILES_CONTAINER_API_PATH = (flowId: string) => `/flows/${flowId}/files/container`;export const FLOW_FILES_ATTACH_RESOURCES_API_PATH = (flowId: string) => `/flows/${flowId}/files/resources`;export const FLOW_FILES_PROMOTE_API_PATH = (flowId: string) => `/flows/${flowId}/files/to-resources`;export const RESOURCES_LIST_API_PATH = '/resources/';@@ -23,3 +24,6 @@ export const RESOURCES_LIST_API_PATH = '/resources/';export const UPLOADS_TARGET_DIRECTORY = '/work/uploads';export const CONTAINER_TARGET_DIRECTORY = 'container/';export const RESOURCES_TARGET_DIRECTORY = '/work/resources';++/** Default container path browsed when the Pull dialog opens. */+export const CONTAINER_DEFAULT_PATH = '/work';diff --git a/frontend/src/features/flows/files/flow-files-promote-dialog.tsx b/frontend/src/features/flows/files/flow-files-promote-dialog.tsxindex 66a451ff..8df00671 100644--- a/frontend/src/features/flows/files/flow-files-promote-dialog.tsx+++ b/frontend/src/features/flows/files/flow-files-promote-dialog.tsx@@ -1,15 +1,20 @@import { zodResolver } from '@hookform/resolvers/zod';-import { BookmarkPlus, Loader2 } from 'lucide-react';+import { BookmarkPlus } from 'lucide-react';import { useEffect, useMemo } from 'react';import { useForm } from 'react-hook-form';-import type { FileNode } from '@/components/file-manager';+import type { FileNode } from '@/components/shared/file-manager';+import type { OverwriteConflict } from '@/components/shared/overwrite-confirm-dialog';+import type { OverwriteOutcome } from '@/components/shared/use-overwrite-action';+import { OverwriteConfirmDialog } from '@/components/shared/overwrite-confirm-dialog';+import { OverwriteCtaButtons } from '@/components/shared/overwrite-cta-buttons';+import { useOverwriteAction } from '@/components/shared/use-overwrite-action';import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';import { Input } from '@/components/ui/input';-import { Switch } from '@/components/ui/switch';+import { useResources } from '@/providers/resources-provider';import { stripFlowRootPrefix } from './flow-files-utils';import {@@ -38,14 +43,22 @@ interface FlowFilesPromoteDialogProps {onClose: () => void;}-const buildSingleDefaultDestination = (file: FileNode) => stripFlowRootPrefix(file.path) || file.name;+interface PromotePlan {+ /** Final virtual path inside the user's library. */+ destination: string;+ /** Display name extracted from the destination for the conflict dialog. */+ destinationName: string;+ /** Source path inside the flow cache (e.g. `uploads/result.md`). */+ source: string;+}++const buildSingleDefaultDestination = (file: FileNode): string => stripFlowRootPrefix(file.path) || file.name;/*** 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.+ * parent path. 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 => {@@ -60,8 +73,45 @@ const computeMultiDefaultDestination = (files: readonly [FileNode, ...FileNode[]return files.every((file) => stripParent(file.path) === first) ? first : '';};+/**+ * Build the final set of `(source, destination)` promotion plans from the form+ * value and the picked files. For a single file the user types the full path;+ * for a batch the input is a directory and every entry keeps its name.+ */+const buildPromotePlans = (+ files: readonly [FileNode, ...FileNode[]],+ values: FlowFilesPromoteFormValues,+): PromotePlan[] => {+ if (files.length > 1) {+ const targetDir = values.destination.trim().replace(/\/+$/, '');++ return files.map((file) => ({+ destination: targetDir ? `${targetDir}/${file.name}` : file.name,+ destinationName: file.name,+ source: file.path,+ }));+ }++ const [single] = files;+ const destination = values.destination.trim();++ return [+ {+ destination,+ destinationName: destination.split('/').pop() ?? destination,+ source: single.path,+ },+ ];+};++const planToConflict = ({ destination, destinationName }: PromotePlan): OverwriteConflict => ({+ destination,+ destinationName,+});+const FlowFilesPromoteDialogForm = ({ files, flowId, onClose }: FlowFilesPromoteDialogFormProps) => {const { isPromoting, promote } = useFlowFilesPromote({ flowId });+ const { resources } = useResources();const isMulti = files.length > 1;const defaultDestination = useMemo(() => {@@ -73,158 +123,167 @@ const FlowFilesPromoteDialogForm = ({ files, flowId, onClose }: FlowFilesPromote}, [files, isMulti]);const form = useForm<FlowFilesPromoteFormValues>({- defaultValues: {- destination: defaultDestination,- shouldOverwrite: false,- },+ defaultValues: { destination: defaultDestination },mode: 'onChange',resolver: zodResolver(flowFilesPromoteFormSchema),});useEffect(() => {- form.reset({- destination: defaultDestination,- shouldOverwrite: false,- });+ form.reset({ destination: defaultDestination });}, [defaultDestination, form]);- const handleSubmit = form.handleSubmit(async (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 });- }),+ const resourcePaths = useMemo(() => new Set(resources.map((resource) => resource.path)), [resources]);++ /**+ * Drive the canonical "Save / Save with overwrite / Replace all" workflow+ * from the shared hook. The plan is the array of promote operations+ * derived from the form on submit; per-file outcomes are aggregated into+ * a single `OverwriteOutcome` so the hook can branch uniformly.+ */+ const overwriteAction = useOverwriteAction<readonly PromotePlan[]>({+ execute: async (plans, force): Promise<OverwriteOutcome> => {+ const outcomes = await Promise.all(+ plans.map((plan) => promote(plan.source, { destination: plan.destination }, force)),);- if (results.every(Boolean)) {- onClose();+ // Surface per-file conflict descriptors so the dialog names exactly+ // which destinations are taken — far more useful for multi-promote+ // than a count-based fallback.+ const conflicts: OverwriteConflict[] = [];++ outcomes.forEach((outcome, index) => {+ if (outcome.kind === 'conflict') {+ const plan = plans[index];++ if (plan) {+ conflicts.push(planToConflict(plan));+ }+ }+ });++ if (conflicts.length > 0) {+ return { conflicts, kind: 'conflict' };}- return;- }+ if (outcomes.some((outcome) => outcome.kind === 'error')) {+ return { kind: 'error' };+ }- const wasPromoted = await promote(files[0].path, values);+ return { kind: 'ok' };+ },+ findConflicts: (plans) =>+ plans.filter((plan) => resourcePaths.has(plan.destination)).map(planToConflict),+ onSuccess: onClose,+ });- if (wasPromoted) {- onClose();- }+ const handleSave = form.handleSubmit(async (values) => {+ await overwriteAction.primaryExecute(buildPromotePlans(files, values));+ });++ const handleSaveWithOverwrite = form.handleSubmit(async (values) => {+ await overwriteAction.forceExecute(buildPromotePlans(files, values));});- const isSubmitDisabled = !form.formState.isValid || isPromoting;+ const isSubmitDisabled = !form.formState.isValid;const titleText = isMulti ? `Save ${files.length} items as resources` : 'Save as resource';+ const overwriteCtaLabel = isMulti ? `Save ${files.length} with overwrite` : 'Save with overwrite';return (- <DialogContent>- <DialogHeader>- <DialogTitle className="flex items-center gap-2">- <BookmarkPlus className="size-4" />- {titleText}- </DialogTitle>- <DialogDescription>- {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>-- <Form {...form}>- <form- className="flex flex-col gap-4"- onSubmit={handleSubmit}- >- <FormField- control={form.control}- name="destination"- render={({ field }) => (- <FormItem>- <FormLabel>{isMulti ? 'Destination directory' : 'Destination path'}</FormLabel>- <FormControl>- <Input- {...field}- autoComplete="off"- autoFocus- disabled={isPromoting}- placeholder={- isMulti ? 'Leave empty to save into the library root' : 'results/scan.txt'- }- />- </FormControl>- <FormDescription>- {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>- )}- />-- <FormField- control={form.control}- name="shouldOverwrite"- render={({ field }) => (- <FormItem className="flex flex-row items-center gap-2">- <FormControl>- <Switch- checked={field.value}- disabled={isPromoting}- onCheckedChange={field.onChange}- />- </FormControl>- <FormLabel className="cursor-pointer font-normal">- {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.- </FormDescription>- </FormItem>+ <>+ <DialogContent>+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <BookmarkPlus className="size-4" />+ {titleText}+ </DialogTitle>+ <DialogDescription>+ {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.+ </>)}- />-- <div className="flex justify-end gap-2">- <Button- disabled={isPromoting}- onClick={onClose}- type="button"- variant="outline"- >- Cancel- </Button>- <Button- disabled={isSubmitDisabled}- type="submit"- >- {isPromoting ? <Loader2 className="animate-spin" /> : <BookmarkPlus />}- Save- </Button>- </div>- </form>- </Form>- </DialogContent>+ </DialogDescription>+ </DialogHeader>++ <Form {...form}>+ <form+ className="flex flex-col gap-4"+ onSubmit={handleSave}+ >+ <FormField+ control={form.control}+ name="destination"+ render={({ field }) => (+ <FormItem>+ <FormLabel>{isMulti ? 'Destination directory' : 'Destination path'}</FormLabel>+ <FormControl>+ <Input+ {...field}+ autoComplete="off"+ autoFocus+ disabled={isPromoting}+ placeholder={+ isMulti+ ? 'Leave empty to save into the library root'+ : 'results/scan.txt'+ }+ />+ </FormControl>+ <FormDescription>+ {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>+ )}+ />++ <div className="flex flex-wrap justify-end gap-2">+ <Button+ disabled={isPromoting}+ onClick={onClose}+ type="button"+ variant="outline"+ >+ Cancel+ </Button>+ <OverwriteCtaButtons+ isDisabled={isSubmitDisabled}+ isProcessing={isPromoting}+ onOverwrite={() => {+ void handleSaveWithOverwrite();+ }}+ overwriteLabel={overwriteCtaLabel}+ primaryIcon={BookmarkPlus}+ primaryLabel="Save"+ primaryType="submit"+ />+ </div>+ </form>+ </Form>+ </DialogContent>++ <OverwriteConfirmDialog+ conflicts={overwriteAction.conflicts}+ onCancel={overwriteAction.resetConflicts}+ onReplaceAll={overwriteAction.handleReplaceAll}+ />+ </>);};diff --git a/frontend/src/features/flows/files/flow-files-pull-dialog.tsx b/frontend/src/features/flows/files/flow-files-pull-dialog.tsxindex a23e3fb1..96f99c7c 100644--- a/frontend/src/features/flows/files/flow-files-pull-dialog.tsx+++ b/frontend/src/features/flows/files/flow-files-pull-dialog.tsx@@ -1,140 +1,349 @@-import { zodResolver } from '@hookform/resolvers/zod';-import { ArrowDownToLine, Loader2 } from 'lucide-react';-import { useForm } from 'react-hook-form';+import { ArrowDownToLine, ArrowUp, FolderOpen, Loader2, RefreshCw } from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import {+ dedupeOverlappingPaths,+ FileManager,+ type FileManagerBulkAction,+ type FileNode,+} from '@/components/shared/file-manager';+import { OverwriteConfirmDialog } from '@/components/shared/overwrite-confirm-dialog';+import { OverwriteCtaButtons } from '@/components/shared/overwrite-cta-buttons';+import { useOverwriteAction } from '@/components/shared/use-overwrite-action';import { Button } from '@/components/ui/button';-import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';-import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';import { Input } from '@/components/ui/input';-import { Switch } from '@/components/ui/switch';+import { Label } from '@/components/ui/label';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';-import { flowFilesPullFormSchema, type FlowFilesPullFormValues, useFlowFilesPull } from './use-flow-files-pull';+import { findPullConflicts } from './flow-files-conflicts';+import { CONTAINER_DEFAULT_PATH } from './flow-files-constants';+import { pluralizeItems } from './flow-files-utils';+import { useFlowContainerFiles } from './use-flow-container-files';+import { useFlowFilesPull } from './use-flow-files-pull';interface FlowFilesPullDialogFormProps {+ cachedFiles: readonly FileNode[];flowId: null | string;onClose: () => void;onSuccess: () => void;}interface FlowFilesPullDialogProps {+ cachedFiles: readonly FileNode[];flowId: null | string;isOpen: boolean;onClose: () => void;onSuccess: () => void;}-const DEFAULT_PULL_FORM_VALUES: FlowFilesPullFormValues = {- containerPath: '',- shouldOverwrite: false,+/**+ * Normalise a user-entered container path:+ * - trim whitespace,+ * - convert empty / "" to root "/",+ * - guarantee a leading slash so the backend treats it as absolute,+ * - strip a trailing slash for everything except root "/" itself.+ */+const normalizeContainerPath = (raw: string): string => {+ const trimmed = raw.trim();++ if (trimmed === '' || trimmed === '/') {+ return '/';+ }++ const withSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;++ return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') : withSlash;+};++/** Parent of an absolute container path; root collapses onto itself. */+const getParentContainerPath = (path: string): string => {+ if (path === '/' || path === '') {+ return '/';+ }++ const idx = path.lastIndexOf('/');++ if (idx <= 0) {+ return '/';+ }++ return path.slice(0, idx);};/**- * Inner component holding the form state. Mounted only while the dialog is open- * so closing the dialog discards every transient field without an imperative reset.+ * Inner component holding the live browser state. Mounted only while the dialog+ * is open so closing it discards every transient field without an imperative reset.+ *+ * The actual overwrite orchestration (preflight → execute → ConflictDialog+ * fallback) is delegated to {@link useOverwriteAction}; this component only+ * owns the listing browser UI and the per-action plan derivation.*/-const FlowFilesPullDialogForm = ({ flowId, onClose, onSuccess }: FlowFilesPullDialogFormProps) => {- const { isPulling, pull } = useFlowFilesPull({ flowId, onSuccess });+const FlowFilesPullDialogForm = ({ cachedFiles, flowId, onClose, onSuccess }: FlowFilesPullDialogFormProps) => {+ const [currentPath, setCurrentPath] = useState<string>(CONTAINER_DEFAULT_PATH);+ const [pathInputValue, setPathInputValue] = useState<string>(CONTAINER_DEFAULT_PATH);+ const [selectedPaths, setSelectedPaths] = useState<ReadonlySet<string>>(() => new Set<string>());- const form = useForm<FlowFilesPullFormValues>({- defaultValues: DEFAULT_PULL_FORM_VALUES,- mode: 'onChange',- resolver: zodResolver(flowFilesPullFormSchema),+ // Stable single-element array so the listing hook's effect doesn't re-fire+ // on every parent re-render.+ const listingPaths = useMemo(() => [currentPath], [currentPath]);++ const {+ error: listingError,+ files,+ isLoading: isListingLoading,+ refetch: refetchListing,+ } = useFlowContainerFiles({ flowId, paths: listingPaths });++ const { isPulling, pull } = useFlowFilesPull({+ flowId,+ // Refresh the listing after a successful pull so newly available entries+ // (or, with `force=true`, replaced ones) reflect their fresh state.+ onSuccess: () => {+ void refetchListing();+ onSuccess();+ },});- const handleSubmit = form.handleSubmit(async (values) => {- const wasPulled = await pull(values);+ /**+ * Drive the canonical "Pull / Pull with overwrite / Replace all" workflow+ * from the shared hook. The hook owns conflict-state, race-fallback and+ * close-on-success — this dialog just provides the plan (paths) and the+ * three pure helpers (find / execute / synthesize).+ */+ const overwriteAction = useOverwriteAction<readonly string[]>({+ execute: (paths, force) => pull(paths, force),+ findConflicts: (paths) => findPullConflicts(paths, cachedFiles),+ onSuccess: onClose,+ synthesizeFallbackConflicts: (paths) =>+ paths.map((path) => ({+ destination: path,+ destinationName: path.split('/').pop() ?? path,+ })),+ });- if (wasPulled) {- onClose();+ const navigateTo = useCallback((nextPath: string) => {+ const normalized = normalizeContainerPath(nextPath);++ setCurrentPath(normalized);+ setPathInputValue(normalized);+ setSelectedPaths(new Set<string>());+ }, []);++ const handleOpenDirectory = useCallback(+ (dir: FileNode) => {+ navigateTo(dir.path);+ },+ [navigateTo],+ );++ const handleNavigateUp = useCallback(() => {+ navigateTo(getParentContainerPath(currentPath));+ }, [currentPath, navigateTo]);++ const handlePathInputKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key === 'Enter') {+ event.preventDefault();+ navigateTo(pathInputValue);+ }+ },+ [navigateTo, pathInputValue],+ );++ const handleRefresh = useCallback(() => {+ void refetchListing();+ }, [refetchListing]);++ // Final list of paths to pull. Empty selection → fall back to the directory+ // the user is currently browsing. Non-empty selection wins and is deduped+ // so a folder + one of its descendants don't double-process.+ const pullTargets = useMemo<readonly string[]>(() => {+ if (selectedPaths.size > 0) {+ return dedupeOverlappingPaths(selectedPaths);+ }++ return [currentPath];+ }, [currentPath, selectedPaths]);++ const isUpDisabled = currentPath === '/' || isListingLoading || isPulling;+ const isPullDisabled = isListingLoading || pullTargets.length === 0 || !flowId;++ const primaryLabel = useMemo(() => {+ if (selectedPaths.size === 0) {+ return `Pull ${currentPath}`;+ }++ return `Pull ${selectedPaths.size} ${pluralizeItems(selectedPaths.size)}`;+ }, [currentPath, selectedPaths.size]);++ const overwriteLabel = useMemo(() => {+ if (selectedPaths.size === 0) {+ return 'Pull with overwrite';}- });- const isSubmitDisabled = !form.formState.isValid || isPulling;+ return `Pull ${selectedPaths.size} with overwrite`;+ }, [selectedPaths.size]);++ // The FileManager doesn't ship a "selection only" mode — passing an empty+ // bulk-actions array is the cheapest way to surface the checkboxes.+ const bulkActions = useMemo<FileManagerBulkAction[]>(() => [], []);++ const emptyState = listingError ? (+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <FolderOpen />+ </EmptyMedia>+ <EmptyTitle>Failed to list container</EmptyTitle>+ <EmptyDescription>{listingError.message}</EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <FolderOpen />+ </EmptyMedia>+ <EmptyTitle>Directory is empty</EmptyTitle>+ <EmptyDescription>+ Nothing to pull from <code>{currentPath}</code>.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ );return (- <DialogContent>- <DialogHeader>- <DialogTitle className="flex items-center gap-2">- <ArrowDownToLine className="size-4" />- Pull from container- </DialogTitle>- <DialogDescription>- Enter a path inside the running container. The file or directory will be synced to the local cache- under <code>container/</code>.- </DialogDescription>- </DialogHeader>-- <Form {...form}>- <form- className="flex flex-col gap-4"- onSubmit={handleSubmit}- >- <FormField- control={form.control}- name="containerPath"- render={({ field }) => (- <FormItem>- <FormLabel>Container path</FormLabel>- <FormControl>- <Input- {...field}- autoComplete="off"- autoFocus- disabled={isPulling}- placeholder="/etc/nginx/conf"- />- </FormControl>- <FormMessage />- </FormItem>- )}+ <>+ <DialogContent className="sm:max-w-2xl">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <ArrowDownToLine className="size-4" />+ Pull from container+ </DialogTitle>+ <DialogDescription>+ Browse the running container and select files or directories to sync into the local cache under{' '}+ <code>container/</code>. Double-click a folder to drill in.+ </DialogDescription>+ </DialogHeader>++ <div className="flex flex-col gap-3">+ <div className="flex items-end gap-2">+ <div className="flex-1">+ <Label+ className="mb-1.5 block text-sm font-normal"+ htmlFor="flow-files-pull-path"+ >+ Container path+ </Label>+ <Input+ autoComplete="off"+ autoFocus+ disabled={isPulling}+ id="flow-files-pull-path"+ onChange={(event) => setPathInputValue(event.target.value)}+ onKeyDown={handlePathInputKeyDown}+ placeholder="/work"+ value={pathInputValue}+ />+ </div>++ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Button+ disabled={isUpDisabled}+ onClick={handleNavigateUp}+ size="icon-sm"+ type="button"+ variant="outline"+ >+ <ArrowUp />+ </Button>+ </span>+ </TooltipTrigger>+ <TooltipContent>Parent directory</TooltipContent>+ </Tooltip>++ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Button+ disabled={isListingLoading || isPulling}+ onClick={handleRefresh}+ size="icon-sm"+ type="button"+ variant="outline"+ >+ {isListingLoading ? <Loader2 className="animate-spin" /> : <RefreshCw />}+ </Button>+ </span>+ </TooltipTrigger>+ <TooltipContent>Refresh listing</TooltipContent>+ </Tooltip>+ </div>++ <FileManager+ bulkActions={bulkActions}+ className="h-[360px]"+ emptyState={emptyState}+ enableSelection+ files={files}+ isLoading={isListingLoading && files.length === 0}+ onOpenDirectory={handleOpenDirectory}+ onSelectionChange={setSelectedPaths}/>+ </div>- <FormField- control={form.control}- name="shouldOverwrite"- render={({ field }) => (- <FormItem className="flex flex-row items-center gap-2">- <FormControl>- <Switch- checked={field.value}- disabled={isPulling}- onCheckedChange={field.onChange}- />- </FormControl>- <FormLabel className="cursor-pointer font-normal">- Overwrite if already cached- </FormLabel>- <FormDescription className="sr-only">- Replace the cached entry when it already exists.- </FormDescription>- </FormItem>- )}+ <DialogFooter>+ <Button+ disabled={isPulling}+ onClick={onClose}+ type="button"+ variant="outline"+ >+ Cancel+ </Button>+ <OverwriteCtaButtons+ isDisabled={isPullDisabled}+ isProcessing={isPulling}+ onOverwrite={() => {+ void overwriteAction.forceExecute(pullTargets);+ }}+ onPrimary={() => {+ void overwriteAction.primaryExecute(pullTargets);+ }}+ overwriteLabel={overwriteLabel}+ primaryIcon={ArrowDownToLine}+ primaryLabel={primaryLabel}/>+ </DialogFooter>+ </DialogContent>- <div className="flex justify-end gap-2">- <Button- disabled={isPulling}- onClick={onClose}- type="button"- variant="outline"- >- Cancel- </Button>- <Button- disabled={isSubmitDisabled}- type="submit"- >- {isPulling ? <Loader2 className="animate-spin" /> : <ArrowDownToLine />}- Pull- </Button>- </div>- </form>- </Form>- </DialogContent>+ <OverwriteConfirmDialog+ conflicts={overwriteAction.conflicts}+ onCancel={overwriteAction.resetConflicts}+ onReplaceAll={overwriteAction.handleReplaceAll}+ />+ </>);};-export const FlowFilesPullDialog = ({ flowId, isOpen, onClose, onSuccess }: FlowFilesPullDialogProps) => {+export const FlowFilesPullDialog = ({+ cachedFiles,+ flowId,+ isOpen,+ onClose,+ onSuccess,+}: FlowFilesPullDialogProps) => {const handleDialogOpenChange = (nextOpen: boolean) => {if (!nextOpen) {onClose();@@ -148,6 +357,7 @@ export const FlowFilesPullDialog = ({ flowId, isOpen, onClose, onSuccess }: Flow>{isOpen && (<FlowFilesPullDialogForm+ cachedFiles={cachedFiles}flowId={flowId}onClose={onClose}onSuccess={onSuccess}diff --git a/frontend/src/features/flows/files/flow-files-utils.ts b/frontend/src/features/flows/files/flow-files-utils.tsindex 09d90afa..17258de6 100644--- a/frontend/src/features/flows/files/flow-files-utils.ts+++ b/frontend/src/features/flows/files/flow-files-utils.ts@@ -1,10 +1,21 @@-import type { FileNode } from '@/components/file-manager';+import type { FileNode } from '@/components/shared/file-manager';import type { FlowFileFragmentFragment } from '@/graphql/types';+import { buildPathsQuery } from '@/features/resources/resources-utils';import { baseUrl } from '@/models/api';import { CONTAINER_PATH_PREFIX, RESOURCES_PATH_PREFIX, UPLOADS_PATH_PREFIX } from './flow-files-constants';+/**+ * Wire shape of `models.ContainerFiles`. `path` echoes back the queried path+ * when exactly one was requested — empty string for multi-path queries.+ */+export interface ContainerFilesResponse {+ files: RestContainerFile[];+ path: string;+ total: number;+}+export type FlowFile = FlowFileFragmentFragment;/**@@ -18,6 +29,16 @@ export interface FlowFilesResponse {total: number;}+/** Wire shape of `models.ContainerFile` — matches `RestFlowFile` exactly today. */+export interface RestContainerFile {+ id: string;+ is_dir: boolean;+ modified_at: string;+ name: string;+ path: string;+ size: number;+}+export interface RestFlowFile {id: string;is_dir: boolean;@@ -45,16 +66,20 @@ export const stripFlowRootPrefix = (path: string): string => {};/**- * Builds the absolute URL the browser hits to download a single file or directory archive- * for the given flow. Returns `null` when no flow is selected so callers can disable- * the download UI without checking `flowId` themselves.+ * Build the absolute download URL for one or more flow files. Returns `null`+ * when no flow is selected so callers can disable the download UI without+ * checking `flowId` themselves. The backend decides the response shape on its+ * own (single file → attachment, single directory → `<dirname>.zip`, multiple+ * paths → `download.zip`); callers just pass the file list.*/-export const buildDownloadHref = (flowId: null | string, file: FileNode): null | string => {+export const buildFlowFilesDownloadHref = (flowId: null | string, files: readonly FileNode[]): null | string => {if (!flowId) {return null;}- return `${baseUrl}/flows/${flowId}/files/download?path=${encodeURIComponent(file.path)}`;+ const query = buildPathsQuery(files.map((file) => file.path));++ return `${baseUrl}/flows/${flowId}/files/download?${query}`;};export const toFileNode = (file: FlowFile): FileNode => ({@@ -66,4 +91,19 @@ export const toFileNode = (file: FlowFile): FileNode => ({size: file.size,});+/**+ * Convert a `RestContainerFile` (snake_case wire shape) into a `FileNode` the+ * FileManager can render. Container paths are absolute (`/work/foo.txt`); the+ * Pull dialog sends them straight back to `POST /files/pull?paths=…` so no+ * normalisation is needed here — we pass the path through verbatim.+ */+export const containerFileToFileNode = (file: RestContainerFile): FileNode => ({+ id: file.id,+ isDir: file.is_dir,+ modifiedAt: file.modified_at,+ name: file.name,+ path: file.path,+ size: file.size,+});+export const pluralizeItems = (count: number): string => (count === 1 ? 'item' : 'items');diff --git a/frontend/src/features/flows/files/flow-files.tsx b/frontend/src/features/flows/files/flow-files.tsxindex 5feefce0..bd32ba96 100644--- a/frontend/src/features/flows/files/flow-files.tsx+++ b/frontend/src/features/flows/files/flow-files.tsx@@ -2,9 +2,11 @@ import { ArrowDownToLine, FolderInput, FolderOutput, FolderUp, Info, Loader2, Seimport { useCallback, useMemo, useState } from 'react';import { toast } from 'sonner';+import ConfirmationDialog from '@/components/shared/confirmation-dialog';import {bulkCopyPathsAction,bulkDeleteAction,+ bulkDownloadAction,bulkPromoteAction,copyPathAction,deleteAction,@@ -13,8 +15,7 @@ import {type FileManagerAction,type FileManagerBulkAction,type FileNode,-} from '@/components/file-manager';-import ConfirmationDialog from '@/components/shared/confirmation-dialog';+} from '@/components/shared/file-manager';import { Button } from '@/components/ui/button';import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';import { Form, FormControl, FormField, FormItem } from '@/components/ui/form';@@ -29,7 +30,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, pluralizeItems } from './flow-files-utils';+import { buildFlowFilesDownloadHref, 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';@@ -94,7 +95,18 @@ const FlowFiles = () => {toast.error('Failed to copy paths');}, []);- const getDownloadHref = useCallback((file: FileNode): string => buildDownloadHref(flowId, file) ?? '', [flowId]);+ // Single-file row download specialises the bulk URL builder via a 1-element+ // array. `flowId` may be missing (no flow selected yet) — return '' so+ // FileManager renders a noop link instead of crashing on `null`.+ const getRowDownloadHref = useCallback(+ (file: FileNode): string => buildFlowFilesDownloadHref(flowId, [file]) ?? '',+ [flowId],+ );++ const getBulkDownloadHref = useCallback(+ (files: FileNode[]): string => buildFlowFilesDownloadHref(flowId, files) ?? '',+ [flowId],+ );const handleRequestPromote = useCallback((file: FileNode) => {setFilesToPromote([file]);@@ -115,12 +127,12 @@ const FlowFiles = () => {const fileManagerActions = useMemo<FileManagerAction[]>(() => [- downloadAction(getDownloadHref),+ downloadAction(getRowDownloadHref),copyPathAction(handleCopyPath),promoteAction,deleteAction(deletion.requestDelete),],- [getDownloadHref, handleCopyPath, promoteAction, deletion.requestDelete],+ [getRowDownloadHref, handleCopyPath, promoteAction, deletion.requestDelete],);// Bulk-action set: primary "Save as resources" (most common workflow on this@@ -128,11 +140,12 @@ const FlowFiles = () => {// in overflow, destructive Delete on the right.const fileManagerBulkActions = useMemo<FileManagerBulkAction[]>(() => [+ bulkDownloadAction(getBulkDownloadHref),bulkPromoteAction((files) => setFilesToPromote(files)),bulkCopyPathsAction(handleBulkCopyPaths),- bulkDeleteAction(deletion.deleteBulk),+ bulkDeleteAction(deletion.deleteFiles),],- [deletion.deleteBulk, handleBulkCopyPaths],+ [deletion.deleteFiles, getBulkDownloadHref, handleBulkCopyPaths],);const handleOpenPullDialog = useCallback(() => setIsPullDialogOpen(true), []);@@ -328,6 +341,7 @@ const FlowFiles = () => {/><FlowFilesPullDialog+ cachedFiles={fileNodes}flowId={flowId}isOpen={isPullDialogOpen}onClose={handleClosePullDialog}@@ -335,6 +349,7 @@ const FlowFiles = () => {/><FlowFilesAttachResourcesDialog+ cachedFiles={fileNodes}flowId={flowId}isOpen={isAttachResourcesDialogOpen}onClose={handleCloseAttachResourcesDialog}diff --git a/frontend/src/features/flows/files/use-flow-container-files.ts b/frontend/src/features/flows/files/use-flow-container-files.tsnew file mode 100644index 00000000..b9d4fef1--- /dev/null+++ b/frontend/src/features/flows/files/use-flow-container-files.ts@@ -0,0 +1,120 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';++import type { FileNode } from '@/components/shared/file-manager';++import { buildPathsQuery } from '@/features/resources/resources-utils';+import { api, getApiErrorMessage, unwrapApiResponse } from '@/lib/axios';++import { FLOW_FILES_CONTAINER_API_PATH } from './flow-files-constants';+import { type ContainerFilesResponse, containerFileToFileNode } from './flow-files-utils';++interface UseFlowContainerFilesParams {+ flowId: null | string;+ /**+ * Absolute container paths to list (e.g. `['/work']`, `['/etc', '/var/log']`).+ * Backend accepts multiple via `?paths[]=…&paths[]=…` and returns a deduped,+ * sort-stable union. Empty array disables the request entirely — handy for+ * "skip until ready" patterns when the dialog is closed.+ */+ paths: readonly string[];+}++interface UseFlowContainerFilesResult {+ error: Error | null;+ files: FileNode[];+ isLoading: boolean;+ /**+ * Re-fetches the listing using the current `paths`. Use after a Pull+ * succeeds so the user sees the updated container state without closing+ * the dialog.+ */+ refetch: () => Promise<void>;+}++/**+ * Live listing of files inside the running container, returned as `FileNode[]`+ * so the FileManager component can render them directly.+ *+ * The Pull dialog uses this to let the user browse `/work` (or any other+ * absolute path inside the container) and pick which entries to copy into the+ * local cache. The listing is shallow — backend returns a single directory's+ * contents — and the dialog handles drill-in by replacing `paths` with the+ * folder the user just opened.+ *+ * When `flowId` is `null` or `paths` is empty, the hook idles: no request+ * is issued, `files` stays an empty array, `isLoading` stays `false`.+ */+export const useFlowContainerFiles = ({ flowId, paths }: UseFlowContainerFilesParams): UseFlowContainerFilesResult => {+ const [files, setFiles] = useState<FileNode[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ // Stringify the paths array so that effect / refetch deps stay stable across+ // renders (a fresh array reference would re-fire the effect on every parent+ // re-render even when the contents are identical). The `\u0000` separator+ // can't appear in any container path so it's a safe delimiter.+ const pathsKey = useMemo(() => paths.join('\u0000'), [paths]);++ // Each in-flight fetch increments this counter; the response-handling code+ // bails when its captured token no longer matches `currentTokenRef.current`,+ // which guarantees the latest request always wins (no race-induced flicker+ // when the user drills in / out faster than the server can respond).+ const currentTokenRef = useRef(0);++ const fetchListing = useCallback(async () => {+ if (!flowId || paths.length === 0) {+ currentTokenRef.current += 1;+ setFiles([]);+ setIsLoading(false);+ setError(null);++ return;+ }++ const token = (currentTokenRef.current += 1);++ setIsLoading(true);+ setError(null);++ try {+ const url = `${FLOW_FILES_CONTAINER_API_PATH(flowId)}?${buildPathsQuery(paths)}`;+ // Listing the container can take several seconds for huge directory+ // trees; opt out of the default 30s axios timeout so the dialog+ // doesn't fail spuriously while the kernel walks /proc, /sys, etc.+ const response = await api.get<ContainerFilesResponse>(url, { timeout: 0 });+ const data = unwrapApiResponse(response);++ if (token !== currentTokenRef.current) {+ return;+ }++ setFiles(data.files.map(containerFileToFileNode));+ } catch (caught) {+ if (token !== currentTokenRef.current) {+ return;+ }++ setError(new Error(getApiErrorMessage(caught, 'Failed to load container files')));+ setFiles([]);+ } finally {+ if (token === currentTokenRef.current) {+ setIsLoading(false);+ }+ }+ }, [flowId, paths]);++ useEffect(() => {+ void fetchListing();+ // We deliberately depend on the stable `pathsKey` instead of the array+ // reference so identical contents don't re-fire the request on every+ // render. `flowId` triggers a fresh fetch when the user switches flows.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [flowId, pathsKey]);++ return {+ error,+ files,+ isLoading,+ refetch: fetchListing,+ };+};diff --git a/frontend/src/features/flows/files/use-flow-files-attach-resources.ts b/frontend/src/features/flows/files/use-flow-files-attach-resources.tsindex 1509306c..c1adaee8 100644--- a/frontend/src/features/flows/files/use-flow-files-attach-resources.ts+++ b/frontend/src/features/flows/files/use-flow-files-attach-resources.ts@@ -1,8 +1,10 @@import { useCallback, useState } from 'react';import { toast } from 'sonner';+import type { OverwriteOutcome } from '@/components/shared/use-overwrite-action';+import { resourceIdsToWire } from '@/features/resources/resources-rest';-import { api, getApiErrorMessage } from '@/lib/axios';+import { api, getApiErrorMessage, getApiErrorStatusCode } from '@/lib/axios';import type { FlowFilesResponse } from './flow-files-utils';@@ -14,32 +16,21 @@ interface AttachOptions {shouldOverwrite: boolean;}-/**- * Wire shape of `models.AddResourcesRequest`. Backend expects `ids` as- * uint64 (JSON numbers); see {@link resourceIdsToWire} for the bridge from- * the GraphQL `string` ID convention used internally.- */-interface AttachResourcesRequestBody {- force: boolean;- ids: number[];-}-interface UseFlowFilesAttachResourcesParams {flowId: null | string;onSuccess?: () => void;}interface UseFlowFilesAttachResourcesResult {- attach: (options: AttachOptions) => Promise<boolean>;+ attach: (options: AttachOptions) => Promise<OverwriteOutcome>;isAttaching: boolean;}-const ATTACH_OVERWRITE_HINT = 'Some files already exist — enable "Overwrite" to replace them';-/*** Wraps the "attach user resources to flow" REST call (`POST /files/resources`)- * with toast notifications and a loading flag. Resolves to `true` on success so- * the caller dialog can close itself on a successful attach.+ * with toast notifications and a loading flag. Returns a discriminated outcome+ * so callers can branch between success, a 409 conflict that warrants a user+ * prompt, and any other failure (already toasted).*/export const useFlowFilesAttachResources = ({flowId,@@ -48,9 +39,9 @@ export const useFlowFilesAttachResources = ({const [isAttaching, setIsAttaching] = useState(false);const attach = useCallback(- async ({ ids, shouldOverwrite }: AttachOptions): Promise<boolean> => {+ async ({ ids, shouldOverwrite }: AttachOptions): Promise<OverwriteOutcome> => {if (!flowId || ids.length === 0) {- return false;+ return { kind: 'error' };}let numericIds: number[];@@ -64,13 +55,13 @@ export const useFlowFilesAttachResources = ({toast.error('Attach failed', { description });- return false;+ return { kind: 'error' };}setIsAttaching(true);try {- await api.post<FlowFilesResponse, AttachResourcesRequestBody>(+ await api.post<FlowFilesResponse, { force: boolean; ids: number[] }>(FLOW_FILES_ATTACH_RESOURCES_API_PATH(flowId),{force: shouldOverwrite,@@ -84,15 +75,17 @@ export const useFlowFilesAttachResources = ({});onSuccess?.();- return true;+ return { kind: 'ok' };} catch (error) {- const description = getApiErrorMessage(error, 'Failed to attach resources', {- 409: ATTACH_OVERWRITE_HINT,- });+ if (!shouldOverwrite && getApiErrorStatusCode(error) === 409) {+ return { kind: 'conflict' };+ }++ const description = getApiErrorMessage(error, 'Failed to attach resources');toast.error('Attach failed', { description });- return false;+ return { kind: 'error' };} finally {setIsAttaching(false);}diff --git a/frontend/src/features/flows/files/use-flow-files-data.ts b/frontend/src/features/flows/files/use-flow-files-data.tsindex 5aa6ef87..86fbdc2e 100644--- a/frontend/src/features/flows/files/use-flow-files-data.ts+++ b/frontend/src/features/flows/files/use-flow-files-data.ts@@ -1,7 +1,7 @@import { useEffect, useMemo } from 'react';import { toast } from 'sonner';-import type { FileNode } from '@/components/file-manager';+import type { FileNode } from '@/components/shared/file-manager';import { useFlowFilesQuery } from '@/graphql/types';diff --git a/frontend/src/features/flows/files/use-flow-files-delete.ts b/frontend/src/features/flows/files/use-flow-files-delete.tsindex ef0e0b5b..b5d45cbf 100644--- a/frontend/src/features/flows/files/use-flow-files-delete.ts+++ b/frontend/src/features/flows/files/use-flow-files-delete.ts@@ -1,8 +1,9 @@import { useCallback, useState } from 'react';import { toast } from 'sonner';-import type { FileNode } from '@/components/file-manager';+import type { FileNode } from '@/components/shared/file-manager';+import { buildPathsQuery } from '@/features/resources/resources-utils';import { api, getApiErrorMessage } from '@/lib/axios';import { FLOW_FILES_API_PATH } from './flow-files-constants';@@ -16,31 +17,27 @@ interface UseFlowFilesDeleteParams {interface UseFlowFilesDeleteResult {clearFileToDelete: () => void;confirmDelete: () => Promise<void>;- deleteBulk: (filesToDelete: FileNode[]) => Promise<void>;+ /**+ * Delete one or more flow files in a single atomic backend call. Both the+ * row-level "Delete" action and the bulk-bar entry funnel through this+ * method — the row flow shows a one-name confirm dialog first via+ * `requestDelete` / `confirmDelete`.+ */+ deleteFiles: (filesToDelete: readonly FileNode[]) => Promise<void>;fileToDelete: FileNode | null;requestDelete: (file: FileNode) => void;}-const deleteFileRequest = (flowId: string, path: string) =>- api.delete<FlowFilesResponse>(FLOW_FILES_API_PATH(flowId), { params: { path } });--const reportBulkDeleteOutcome = (succeededCount: number, failedCount: number): void => {- if (failedCount === 0) {- toast.success(`${succeededCount} ${pluralizeItems(succeededCount)} deleted`);-- return;- }-- if (succeededCount === 0) {- toast.error('Bulk delete failed', {- description: `Failed to delete ${failedCount} ${pluralizeItems(failedCount)}`,- });-- return;- }-- toast.warning(`${succeededCount} succeeded · ${failedCount} failed`);-};+/**+ * Issues one `DELETE /flows/{id}/files?paths[]=…` regardless of how many files+ * are passed in. The backend deduplicates and validates atomically: either every+ * path is removed or nothing is. The response enumerates every entry that was+ * actually deleted (including nested files for directory removals) — we still+ * trigger an explicit refetch because flow files don't have a deletion+ * subscription wired into Apollo yet.+ */+const deleteFlowFilesRequest = (flowId: string, paths: readonly string[]) =>+ api.delete<FlowFilesResponse>(`${FLOW_FILES_API_PATH(flowId)}?${buildPathsQuery(paths)}`);/*** Owns both the single-file and bulk-delete flows. The component drives the@@ -59,45 +56,53 @@ export const useFlowFilesDelete = ({ flowId, refetchFiles }: UseFlowFilesDeletePsetFileToDelete(null);}, []);+ const deleteFiles = useCallback(+ async (filesToDelete: readonly FileNode[]) => {+ if (!flowId || filesToDelete.length === 0) {+ return;+ }++ try {+ await deleteFlowFilesRequest(+ flowId,+ filesToDelete.map((file) => file.path),+ );++ if (filesToDelete.length === 1) {+ const single = filesToDelete[0];+ toast.success(single.isDir ? 'Directory deleted' : 'File deleted');+ } else {+ toast.success(`${filesToDelete.length} ${pluralizeItems(filesToDelete.length)} deleted`);+ }+ } catch (error) {+ const description = getApiErrorMessage(error, 'Failed to delete file');++ toast.error('Delete failed', { description });+ } finally {+ // Always refetch — succeeded paths now leave the cache, failed+ // paths may have been partially recreated by other clients.+ await refetchFiles();+ }+ },+ [flowId, refetchFiles],+ );+const confirmDelete = useCallback(async () => {- if (!flowId || !fileToDelete) {+ if (!fileToDelete) {return;}try {- await deleteFileRequest(flowId, fileToDelete.path);- toast.success(fileToDelete.isDir ? 'Directory deleted' : 'File deleted');- await refetchFiles();- } catch (error) {- const description = getApiErrorMessage(error, 'Failed to delete file');-- toast.error('Delete failed', { description });+ await deleteFiles([fileToDelete]);} finally {setFileToDelete(null);}- }, [flowId, fileToDelete, refetchFiles]);-- const deleteBulk = useCallback(- async (filesToDelete: FileNode[]) => {- if (!flowId || filesToDelete.length === 0) {- return;- }-- const results = await Promise.allSettled(filesToDelete.map((file) => deleteFileRequest(flowId, file.path)));- const succeededCount = results.filter((result) => result.status === 'fulfilled').length;- const failedCount = results.length - succeededCount;-- reportBulkDeleteOutcome(succeededCount, failedCount);-- await refetchFiles();- },- [flowId, refetchFiles],- );+ }, [deleteFiles, fileToDelete]);return {clearFileToDelete,confirmDelete,- deleteBulk,+ deleteFiles,fileToDelete,requestDelete,};diff --git a/frontend/src/features/flows/files/use-flow-files-promote.ts b/frontend/src/features/flows/files/use-flow-files-promote.tsindex bc695900..b40f2e07 100644--- a/frontend/src/features/flows/files/use-flow-files-promote.ts+++ b/frontend/src/features/flows/files/use-flow-files-promote.ts@@ -2,9 +2,10 @@ import { useCallback, useState } from 'react';import { toast } from 'sonner';import { z } from 'zod';+import type { OverwriteOutcome } from '@/components/shared/use-overwrite-action';import type { RestResourceList } from '@/features/resources/resources-rest';-import { api, getApiErrorMessage } from '@/lib/axios';+import { api, getApiErrorMessage, getApiErrorStatusCode } from '@/lib/axios';import { FLOW_FILES_PROMOTE_API_PATH } from './flow-files-constants';@@ -15,7 +16,6 @@ export const flowFilesPromoteFormSchema = z.object({.min(1, { message: 'Destination cannot be empty' }).refine((value) => !value.startsWith('/'), { message: 'Destination must be a relative path' }).refine((value) => !value.split('/').includes('..'), { message: 'Destination must not contain ".."' }),- shouldOverwrite: z.boolean(),});export type FlowFilesPromoteFormValues = z.infer<typeof flowFilesPromoteFormSchema>;@@ -32,15 +32,18 @@ interface UseFlowFilesPromoteParams {interface UseFlowFilesPromoteResult {isPromoting: boolean;- promote: (source: string, values: FlowFilesPromoteFormValues) => Promise<boolean>;+ promote: (+ source: string,+ values: FlowFilesPromoteFormValues,+ force: boolean,+ ) => Promise<OverwriteOutcome>;}-const PROMOTE_OVERWRITE_HINT = 'Resource already exists — enable "Overwrite" to replace it';-/*** Wraps the "promote flow file → user resource" REST call (`POST /files/to-resources`)- * with toast notifications and a loading flag. Returns a `promote(source, values)`- * callback that resolves to `true` on success so the dialog can decide whether to close.+ * with toast notifications and a loading flag. Returns a discriminated outcome+ * so callers can branch between success, a 409 conflict that warrants a user+ * prompt, and any other failure (already toasted).** The endpoint accepts both single files and directories — the backend always returns* a `ResourceList` covering every entry it created or updated. The response payload@@ -51,9 +54,13 @@ export const useFlowFilesPromote = ({ flowId }: UseFlowFilesPromoteParams): UseFconst [isPromoting, setIsPromoting] = useState(false);const promote = useCallback(- async (source: string, { destination, shouldOverwrite }: FlowFilesPromoteFormValues): Promise<boolean> => {+ async (+ source: string,+ { destination }: FlowFilesPromoteFormValues,+ force: boolean,+ ): Promise<OverwriteOutcome> => {if (!flowId) {- return false;+ return { kind: 'error' };}setIsPromoting(true);@@ -63,7 +70,7 @@ export const useFlowFilesPromote = ({ flowId }: UseFlowFilesPromoteParams): UseFFLOW_FILES_PROMOTE_API_PATH(flowId),{destination: destination.trim(),- force: shouldOverwrite,+ force,source,},{ timeout: 0 },@@ -73,15 +80,17 @@ export const useFlowFilesPromote = ({ flowId }: UseFlowFilesPromoteParams): UseFdescription: `Stored at ${destination.trim()} in your resource library`,});- return true;+ return { kind: 'ok' };} catch (error) {- const description = getApiErrorMessage(error, 'Failed to save resource', {- 409: PROMOTE_OVERWRITE_HINT,- });+ if (!force && getApiErrorStatusCode(error) === 409) {+ return { kind: 'conflict' };+ }++ const description = getApiErrorMessage(error, 'Failed to save resource');toast.error('Save as resource failed', { description });- return false;+ return { kind: 'error' };} finally {setIsPromoting(false);}diff --git a/frontend/src/features/flows/files/use-flow-files-pull.ts b/frontend/src/features/flows/files/use-flow-files-pull.tsindex 06a19d5d..96773a9d 100644--- a/frontend/src/features/flows/files/use-flow-files-pull.ts+++ b/frontend/src/features/flows/files/use-flow-files-pull.ts@@ -1,18 +1,12 @@import { useCallback, useState } from 'react';import { toast } from 'sonner';-import { z } from 'zod';-import { api, getApiErrorMessage } from '@/lib/axios';+import type { OverwriteOutcome } from '@/components/shared/use-overwrite-action';-import { CONTAINER_TARGET_DIRECTORY, FLOW_FILES_PULL_API_PATH } from './flow-files-constants';-import { type FlowFilesResponse } from './flow-files-utils';--export const flowFilesPullFormSchema = z.object({- containerPath: z.string().trim().min(1, { message: 'Container path cannot be empty' }),- shouldOverwrite: z.boolean(),-});+import { api, getApiErrorMessage, getApiErrorStatusCode } from '@/lib/axios';-export type FlowFilesPullFormValues = z.infer<typeof flowFilesPullFormSchema>;+import { CONTAINER_TARGET_DIRECTORY, FLOW_FILES_PULL_API_PATH } from './flow-files-constants';+import { type FlowFilesResponse, pluralizeItems } from './flow-files-utils';interface UseFlowFilesPullParams {flowId: null | string;@@ -21,23 +15,28 @@ interface UseFlowFilesPullParams {interface UseFlowFilesPullResult {isPulling: boolean;- pull: (values: FlowFilesPullFormValues) => Promise<boolean>;+ /**+ * Pulls one or more absolute container paths into the local cache. Returns+ * a discriminated outcome so callers can branch between success, a 409+ * conflict that warrants a user prompt, and any other failure (toasted).+ * The backend deduplicates and validates atomically (fail-fast on cache+ * conflicts unless `force=true`).+ */+ pull: (paths: readonly string[], force: boolean) => Promise<OverwriteOutcome>;}-const PULL_OVERWRITE_HINT = 'Entry already exists — enable "Overwrite" to replace it';-/**- * Wraps the "pull from container" REST call with toast notifications and a loading flag.- * Returns a `pull(values)` callback that resolves to `true` on success, so the dialog- * can decide whether to close itself.+ * Wraps the "pull from container" REST call. The hook is path-agnostic — it+ * always sends the array as `paths` in the body (single-path callers just pass+ * a 1-element array), matching the wire shape the rest of our file APIs use.*/export const useFlowFilesPull = ({ flowId, onSuccess }: UseFlowFilesPullParams): UseFlowFilesPullResult => {const [isPulling, setIsPulling] = useState(false);const pull = useCallback(- async ({ containerPath, shouldOverwrite }: FlowFilesPullFormValues): Promise<boolean> => {- if (!flowId) {- return false;+ async (paths: readonly string[], force: boolean): Promise<OverwriteOutcome> => {+ if (!flowId || paths.length === 0) {+ return { kind: 'error' };}setIsPulling(true);@@ -46,28 +45,35 @@ export const useFlowFilesPull = ({ flowId, onSuccess }: UseFlowFilesPullParams):await api.post<FlowFilesResponse>(FLOW_FILES_PULL_API_PATH(flowId),{- force: shouldOverwrite,- path: containerPath,+ force,+ paths,},// Copying a directory out of the container can take longer than the default 30s// (large logs, deep trees) — disable the per-call timeout entirely.{ timeout: 0 },);- toast.success('Pulled from container', {- description: `Saved to local cache under ${CONTAINER_TARGET_DIRECTORY}`,- });+ const description =+ paths.length === 1+ ? `Saved to local cache under ${CONTAINER_TARGET_DIRECTORY}`+ : `Saved ${paths.length} ${pluralizeItems(paths.length)} to local cache under ${CONTAINER_TARGET_DIRECTORY}`;++ toast.success('Pulled from container', { description });onSuccess();- return true;+ return { kind: 'ok' };} catch (error) {- const description = getApiErrorMessage(error, 'Failed to pull from container', {- 409: PULL_OVERWRITE_HINT,- });+ if (!force && getApiErrorStatusCode(error) === 409) {+ // The caller resolves conflicts through a richer dialog, so we+ // intentionally skip the toast here to avoid double-surfacing.+ return { kind: 'conflict' };+ }++ const description = getApiErrorMessage(error, 'Failed to pull from container');toast.error('Pull failed', { description });- return false;+ return { kind: 'error' };} finally {setIsPulling(false);}diff --git a/frontend/src/features/resources/resources-conflict-dialog.tsx b/frontend/src/features/resources/resources-conflict-dialog.tsxindex fe4b347a..3f3b7205 100644--- a/frontend/src/features/resources/resources-conflict-dialog.tsx+++ b/frontend/src/features/resources/resources-conflict-dialog.tsx@@ -1,11 +1,7 @@-import { Replace } from 'lucide-react';--import ConfirmationDialog from '@/components/shared/confirmation-dialog';--interface ConflictItem {- destination: string;- destinationName: string;-}+import {+ OverwriteConfirmDialog,+ type OverwriteConflict,+} from '@/components/shared/overwrite-confirm-dialog';interface ResourcesConflictDialogProps {/**@@ -13,50 +9,24 @@ interface ResourcesConflictDialogProps {* For a single conflict the message names the conflicting item; for many it falls* back to a count-based summary (Finder-style "Apply to all").*/- conflicts: ConflictItem[];+ conflicts: OverwriteConflict[];onCancel: () => void;onReplaceAll: () => Promise<unknown> | unknown;}-const buildDescription = (conflicts: ConflictItem[]): string | undefined => {- const single = conflicts.length === 1 ? conflicts[0] : undefined;-- if (single) {- return `An item named "${single.destinationName}" already exists at /${single.destination}. Do you want to replace it?`;- }-- if (conflicts.length > 1) {- return `${conflicts.length} items already exist at the destination. Do you want to replace all of them?`;- }-- return undefined;-};--const buildConfirmText = (count: number): string => (count > 1 ? 'Replace all' : 'Replace');-/**- * Shared "Replace or cancel" dialog for `409` conflicts coming from move / copy hooks.- * The hook owns the conflict state; this component only renders the prompt and forwards- * the user's decision back through the callbacks. A batch decision (Replace all) is- * applied to every pending conflict in one shot — this matches the OS file-manager UX- * and keeps the user from being prompted N times for the same destination directory.+ * Backwards-compatible thin wrapper over the shared {@link OverwriteConfirmDialog}.+ * Move / copy hooks already consume `ConflictItem` shaped values that mirror+ * `OverwriteConflict` 1:1, so this is a pure rename / re-export today.+ *+ * New call sites should depend on `OverwriteConfirmDialog` directly — this file+ * only exists to keep the existing imports in `resources-move-dialog.tsx` and+ * `resources-copy-dialog.tsx` working without churn.*/export const ResourcesConflictDialog = ({ conflicts, onCancel, onReplaceAll }: ResourcesConflictDialogProps) => (- <ConfirmationDialog- cancelText="Cancel"- confirmIcon={<Replace />}- confirmText={buildConfirmText(conflicts.length)}- confirmVariant="destructive"- description={buildDescription(conflicts)}- handleConfirm={async () => {- await onReplaceAll();- }}- handleOpenChange={(nextOpen) => {- if (!nextOpen) {- onCancel();- }- }}- isOpen={conflicts.length > 0}- title="Replace existing item?"+ <OverwriteConfirmDialog+ conflicts={conflicts}+ onCancel={onCancel}+ onReplaceAll={onReplaceAll}/>);diff --git a/frontend/src/features/resources/resources-copy-dialog.tsx b/frontend/src/features/resources/resources-copy-dialog.tsxindex eec0d61f..1d018873 100644--- a/frontend/src/features/resources/resources-copy-dialog.tsx+++ b/frontend/src/features/resources/resources-copy-dialog.tsx@@ -1,15 +1,15 @@import { zodResolver } from '@hookform/resolvers/zod';-import { Copy, Loader2 } from 'lucide-react';+import { Copy } from 'lucide-react';import { useEffect, useMemo } from 'react';import { useForm } from 'react-hook-form';-import type { FileNode } from '@/components/file-manager';+import type { FileNode } from '@/components/shared/file-manager';+import { OverwriteCtaButtons } from '@/components/shared/overwrite-cta-buttons';import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';import { Input } from '@/components/ui/input';-import { Switch } from '@/components/ui/switch';import { ResourcesConflictDialog } from './resources-conflict-dialog';import { resourcesCopyFormSchema, type ResourcesCopyFormValues, useResourcesCopy } from './use-resources-copy';@@ -68,6 +68,25 @@ const computeCommonParent = (files: readonly [FileNode, ...FileNode[]]): stringreturn files.every((file) => getParentDir(file.path) === first) ? first : '';};+/**+ * Resolve the per-file destination from the form value:+ * - single copy → use the typed path verbatim,+ * - multi-file batch → derive `<targetDir>/<file.name>`, root when empty.+ */+const resolveDestination = (+ file: FileNode,+ values: ResourcesCopyFormValues,+ isMulti: boolean,+): string => {+ if (!isMulti) {+ return values.destination;+ }++ const targetDir = values.destination.trim().replace(/\/+$/, '');++ return targetDir ? `${targetDir}/${file.name}` : file.name;+};+const ResourcesCopyDialogForm = ({ files, onClose }: ResourcesCopyDialogFormProps) => {const { cancelConflicts, copy, isCopying, pendingConflicts, resolveConflicts } = useResourcesCopy();const isMulti = files.length > 1;@@ -81,42 +100,42 @@ const ResourcesCopyDialogForm = ({ files, onClose }: ResourcesCopyDialogFormProp}, [files, isMulti]);const form = useForm<ResourcesCopyFormValues>({- defaultValues: {- destination: defaultDestination,- shouldOverwrite: false,- },+ defaultValues: { destination: defaultDestination },mode: 'onChange',resolver: zodResolver(resourcesCopyFormSchema),});useEffect(() => {- form.reset({- destination: defaultDestination,- shouldOverwrite: false,- });+ form.reset({ destination: defaultDestination });}, [defaultDestination, form]);- const handleSubmit = form.handleSubmit(async (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;+ /**+ * Run every copy in parallel with the given `force` flag. Returns `true`+ * when every operation either succeeded or surfaced as a 409 conflict+ * (the latter feeds into `pendingConflicts` for the aggregated dialog).+ * `false` means at least one entry hit a non-conflict error and the form+ * should stay open so the user can read the toast and retry.+ */+ const submitAll = async (values: ResourcesCopyFormValues, force: boolean): Promise<boolean> => {+ const results = await Promise.all(+ files.map((file) => copy(file.path, { destination: resolveDestination(file, values, isMulti) }, force)),+ );- return copy(file.path, { destination, shouldOverwrite: values.shouldOverwrite });- }),- );+ return results.every(Boolean);+ };- if (results.every(Boolean)) {- onClose();- }+ const handleSave = form.handleSubmit(async (values) => {+ const ok = await submitAll(values, false);- return;+ if (ok) {+ onClose();}+ });- const wasCopied = await copy(files[0].path, values);+ const handleSaveWithOverwrite = form.handleSubmit(async (values) => {+ const ok = await submitAll(values, true);- if (wasCopied) {+ if (ok) {onClose();}});@@ -129,9 +148,9 @@ const ResourcesCopyDialogForm = ({ files, onClose }: ResourcesCopyDialogFormProponClose();};- const isSubmitDisabled = !form.formState.isValid || isCopying;-+ const isSubmitDisabled = !form.formState.isValid;const titleText = isMulti ? `Copy ${files.length} items` : files[0].isDir ? 'Copy directory' : 'Copy resource';+ const overwriteCtaLabel = isMulti ? `Copy ${files.length} with overwrite` : 'Copy with overwrite';return (<DialogContent>@@ -154,7 +173,7 @@ const ResourcesCopyDialogForm = ({ files, onClose }: ResourcesCopyDialogFormProp<Form {...form}><formclassName="flex flex-col gap-4"- onSubmit={handleSubmit}+ onSubmit={handleSave}><FormFieldcontrol={form.control}@@ -186,28 +205,7 @@ const ResourcesCopyDialogForm = ({ files, onClose }: ResourcesCopyDialogFormProp)}/>- <FormField- control={form.control}- name="shouldOverwrite"- render={({ field }) => (- <FormItem className="flex flex-row items-center gap-2">- <FormControl>- <Switch- checked={field.value}- disabled={isCopying}- onCheckedChange={field.onChange}- />- </FormControl>- <FormLabel className="cursor-pointer font-normal">- {isMulti- ? 'Overwrite or merge if any destination already exists'- : 'Overwrite or merge if the destination already exists'}- </FormLabel>- </FormItem>- )}- />-- <div className="flex justify-end gap-2">+ <div className="flex flex-wrap justify-end gap-2"><Buttondisabled={isCopying}onClick={onClose}@@ -216,13 +214,17 @@ const ResourcesCopyDialogForm = ({ files, onClose }: ResourcesCopyDialogFormProp>Cancel</Button>- <Button- disabled={isSubmitDisabled}- type="submit"- >- {isCopying ? <Loader2 className="animate-spin" /> : <Copy />}- Copy- </Button>+ <OverwriteCtaButtons+ isDisabled={isSubmitDisabled}+ isProcessing={isCopying}+ onOverwrite={() => {+ void handleSaveWithOverwrite();+ }}+ overwriteLabel={overwriteCtaLabel}+ primaryIcon={Copy}+ primaryLabel="Copy"+ primaryType="submit"+ /></div></form></Form>diff --git a/frontend/src/features/resources/resources-move-dialog.tsx b/frontend/src/features/resources/resources-move-dialog.tsxindex 4ec1c4a4..3f9eda88 100644--- a/frontend/src/features/resources/resources-move-dialog.tsx+++ b/frontend/src/features/resources/resources-move-dialog.tsx@@ -1,15 +1,15 @@import { zodResolver } from '@hookform/resolvers/zod';-import { FolderInput, Loader2 } from 'lucide-react';+import { FolderInput } from 'lucide-react';import { useEffect, useMemo } from 'react';import { useForm } from 'react-hook-form';-import type { FileNode } from '@/components/file-manager';+import type { FileNode } from '@/components/shared/file-manager';+import { OverwriteCtaButtons } from '@/components/shared/overwrite-cta-buttons';import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';import { Input } from '@/components/ui/input';-import { Switch } from '@/components/ui/switch';import { ResourcesConflictDialog } from './resources-conflict-dialog';import { resourcesMoveFormSchema, type ResourcesMoveFormValues, useResourcesMove } from './use-resources-move';@@ -51,6 +51,25 @@ const computeCommonParent = (files: readonly [FileNode, ...FileNode[]]): stringreturn files.every((file) => getParentDir(file.path) === first) ? first : '';};+/**+ * Resolve the per-file destination from the form value:+ * - single rename / move → use the typed path verbatim,+ * - multi-file batch → derive `<targetDir>/<file.name>`, root when empty.+ */+const resolveDestination = (+ file: FileNode,+ values: ResourcesMoveFormValues,+ isMulti: boolean,+): string => {+ if (!isMulti) {+ return values.destination;+ }++ const targetDir = values.destination.trim().replace(/\/+$/, '');++ return targetDir ? `${targetDir}/${file.name}` : file.name;+};+const ResourcesMoveDialogForm = ({ files, onClose }: ResourcesMoveDialogFormProps) => {const { cancelConflicts, isMoving, move, pendingConflicts, resolveConflicts } = useResourcesMove();const isMulti = files.length > 1;@@ -67,49 +86,42 @@ const ResourcesMoveDialogForm = ({ files, onClose }: ResourcesMoveDialogFormProp}, [files, isMulti]);const form = useForm<ResourcesMoveFormValues>({- defaultValues: {- destination: defaultDestination,- shouldOverwrite: false,- },+ defaultValues: { destination: defaultDestination },mode: 'onChange',resolver: zodResolver(resourcesMoveFormSchema),});useEffect(() => {- form.reset({- destination: defaultDestination,- shouldOverwrite: false,- });+ form.reset({ destination: defaultDestination });}, [defaultDestination, form]);- const handleSubmit = form.handleSubmit(async (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;+ /**+ * Run every move in parallel with the given `force` flag. Returns `true`+ * when every operation either succeeded or surfaced as a 409 conflict+ * (the latter feeds into `pendingConflicts` for the aggregated dialog).+ * `false` means at least one entry hit a non-conflict error and the form+ * should stay open so the user can read the toast and retry.+ */+ const submitAll = async (values: ResourcesMoveFormValues, force: boolean): Promise<boolean> => {+ const results = await Promise.all(+ files.map((file) => move(file.path, { destination: resolveDestination(file, values, isMulti) }, force)),+ );++ return results.every(Boolean);+ };++ const handleSave = form.handleSubmit(async (values) => {+ const ok = await submitAll(values, false);++ if (ok) {+ onClose();}+ });- const wasMoved = await move(files[0].path, values);+ const handleSaveWithOverwrite = form.handleSubmit(async (values) => {+ const ok = await submitAll(values, true);- if (wasMoved) {+ if (ok) {onClose();}});@@ -122,13 +134,13 @@ const ResourcesMoveDialogForm = ({ files, onClose }: ResourcesMoveDialogFormProponClose();};- const isSubmitDisabled = !form.formState.isValid || isMoving;-+ const isSubmitDisabled = !form.formState.isValid;const titleText = isMulti? `Move ${files.length} items`: files[0].isDir? 'Move directory': 'Rename or move resource';+ const overwriteCtaLabel = isMulti ? `Move ${files.length} with overwrite` : 'Move with overwrite';return (<DialogContent>@@ -151,7 +163,7 @@ const ResourcesMoveDialogForm = ({ files, onClose }: ResourcesMoveDialogFormProp<Form {...form}><formclassName="flex flex-col gap-4"- onSubmit={handleSubmit}+ onSubmit={handleSave}><FormFieldcontrol={form.control}@@ -186,28 +198,7 @@ const ResourcesMoveDialogForm = ({ files, onClose }: ResourcesMoveDialogFormProp)}/>- <FormField- control={form.control}- name="shouldOverwrite"- render={({ field }) => (- <FormItem className="flex flex-row items-center gap-2">- <FormControl>- <Switch- checked={field.value}- disabled={isMoving}- onCheckedChange={field.onChange}- />- </FormControl>- <FormLabel className="cursor-pointer font-normal">- {isMulti- ? 'Overwrite if a resource already exists at any destination'- : 'Overwrite if a resource already exists at the destination'}- </FormLabel>- </FormItem>- )}- />-- <div className="flex justify-end gap-2">+ <div className="flex flex-wrap justify-end gap-2"><Buttondisabled={isMoving}onClick={onClose}@@ -216,13 +207,17 @@ const ResourcesMoveDialogForm = ({ files, onClose }: ResourcesMoveDialogFormProp>Cancel</Button>- <Button- disabled={isSubmitDisabled}- type="submit"- >- {isMoving ? <Loader2 className="animate-spin" /> : <FolderInput />}- Move- </Button>+ <OverwriteCtaButtons+ isDisabled={isSubmitDisabled}+ isProcessing={isMoving}+ onOverwrite={() => {+ void handleSaveWithOverwrite();+ }}+ overwriteLabel={overwriteCtaLabel}+ primaryIcon={FolderInput}+ primaryLabel="Move"+ primaryType="submit"+ /></div></form></Form>diff --git a/frontend/src/features/resources/resources-utils.ts b/frontend/src/features/resources/resources-utils.tsindex 8f02d058..7e0da780 100644--- a/frontend/src/features/resources/resources-utils.ts+++ b/frontend/src/features/resources/resources-utils.ts@@ -1,4 +1,4 @@-import type { FileNode } from '@/components/file-manager';+import type { FileNode } from '@/components/shared/file-manager';import type { UserResourceFragmentFragment } from '@/graphql/types';import { baseUrl } from '@/models/api';@@ -15,8 +15,37 @@ export const toFileNode = (resource: UserResourceFragmentFragment): FileNode =>size: resource.size,});-/** Absolute URL used by the FileManager download action. */-export const buildResourceDownloadHref = (file: FileNode): string =>- `${baseUrl}${RESOURCES_DOWNLOAD_API_PATH}?path=${encodeURIComponent(file.path)}`;+/**+ * Serialise a list of paths into the `paths[]=…&paths[]=…` query string the+ * backend expects across every multi-path file API. Single-path callers pass+ * a 1-element array — there is no separate `?path=` form, the backend treats+ * `paths[]` as the sole canonical input.+ */+export const buildPathsQuery = (paths: readonly string[]): string => {+ const params = new URLSearchParams();++ for (const p of paths) {+ params.append('paths[]', p);+ }++ return params.toString();+};++/**+ * Build the absolute download URL for one or more resources. The backend decides+ * the response shape on its own:+ * - 1 regular file → `application/octet-stream` with `Content-Disposition`+ * setting the original filename;+ * - 1 directory → `application/zip` named `<dirname>.zip`;+ * - multiple paths → `application/zip` named `download.zip`, entry names use+ * the full virtual path so the user keeps directory context.+ *+ * Callers don't need to special-case any of the above — just pass the file list.+ */+export const buildResourcesDownloadHref = (files: readonly FileNode[]): string => {+ const query = buildPathsQuery(files.map((file) => file.path));++ return `${baseUrl}${RESOURCES_DOWNLOAD_API_PATH}?${query}`;+};export const pluralizeItems = (count: number): string => (count === 1 ? 'item' : 'items');diff --git a/frontend/src/features/resources/use-resources-copy.ts b/frontend/src/features/resources/use-resources-copy.tsindex 5396f469..b4a7053d 100644--- a/frontend/src/features/resources/use-resources-copy.ts+++ b/frontend/src/features/resources/use-resources-copy.ts@@ -2,7 +2,7 @@ import { useCallback, useState } from 'react';import { toast } from 'sonner';import { z } from 'zod';-import { api, type ApiHttpError, getApiErrorMessage } from '@/lib/axios';+import { api, getApiErrorMessage, getApiErrorStatusCode } from '@/lib/axios';import { RESOURCES_COPY_API_PATH } from './resources-constants';@@ -13,7 +13,6 @@ export const resourcesCopyFormSchema = z.object({.min(1, { message: 'Destination cannot be empty' }).refine((value) => !value.startsWith('/'), { message: 'Destination must be a relative path' }).refine((value) => !value.split('/').includes('..'), { message: 'Destination must not contain ".."' }),- shouldOverwrite: z.boolean(),});export interface ResourcesCopyConflict {@@ -34,7 +33,12 @@ interface CopyRequestBody {interface UseResourcesCopyResult {/** Drop the pending conflicts without retrying. */cancelConflicts: () => void;- copy: (sourcePath: string, values: ResourcesCopyFormValues) => Promise<boolean>;+ /**+ * Issue a single copy. `force=false` collects 409s into `pendingConflicts`+ * for an aggregated dialog; `force=true` skips that branch and toasts on+ * any failure (used by the "Copy with overwrite" CTA path).+ */+ copy: (sourcePath: string, values: ResourcesCopyFormValues, force: boolean) => Promise<boolean>;isCopying: boolean;/*** 409 conflicts collected across one or more parallel `copy()` calls. The consumer@@ -46,12 +50,6 @@ interface UseResourcesCopyResult {resolveConflicts: () => Promise<void>;}-const getStatusCode = (error: unknown): number | undefined => {- const httpError = error as ApiHttpError | null | undefined;-- return httpError?.statusCode ?? httpError?.response?.status;-};-const extractName = (path: string): string => path.split('/').pop() ?? path;/** Wraps `POST /resources/copy`. */@@ -74,7 +72,7 @@ export const useResourcesCopy = (): UseResourcesCopyResult => {return true;} catch (error) {- if (getStatusCode(error) === 409 && !force) {+ if (getApiErrorStatusCode(error) === 409 && !force) {setPendingConflicts((prev) => [...prev,{@@ -100,8 +98,8 @@ export const useResourcesCopy = (): UseResourcesCopyResult => {);const copy = useCallback(- (sourcePath: string, { destination, shouldOverwrite }: ResourcesCopyFormValues): Promise<boolean> =>- performCopy(sourcePath, destination.trim(), shouldOverwrite),+ (sourcePath: string, { destination }: ResourcesCopyFormValues, force: boolean): Promise<boolean> =>+ performCopy(sourcePath, destination.trim(), force),[performCopy],);diff --git a/frontend/src/features/resources/use-resources-delete.ts b/frontend/src/features/resources/use-resources-delete.tsindex 06929aa9..c713f60a 100644--- a/frontend/src/features/resources/use-resources-delete.ts+++ b/frontend/src/features/resources/use-resources-delete.ts@@ -1,12 +1,12 @@import { useCallback, useState } from 'react';import { toast } from 'sonner';-import type { FileNode } from '@/components/file-manager';+import type { FileNode } from '@/components/shared/file-manager';import { api, getApiErrorMessage } from '@/lib/axios';import { RESOURCES_API_PATH } from './resources-constants';-import { pluralizeItems } from './resources-utils';+import { buildPathsQuery, pluralizeItems } from './resources-utils';interface UseResourcesDeleteParams {onAfterDelete?: () => void;@@ -15,33 +15,30 @@ interface UseResourcesDeleteParams {interface UseResourcesDeleteResult {clearFileToDelete: () => void;confirmDelete: () => Promise<void>;- deleteBulk: (filesToDelete: FileNode[]) => Promise<void>;+ /**+ * Delete one or more resources in a single atomic backend call. Both the+ * row-level "Delete" action and the bulk-bar entry funnel through this+ * method — the only difference is that the row flow shows a one-name+ * confirm dialog first via `requestDelete` / `confirmDelete`.+ */+ deleteFiles: (filesToDelete: readonly FileNode[]) => Promise<void>;fileToDelete: FileNode | null;requestDelete: (file: FileNode) => void;}-const deleteResourceRequest = (path: string) => api.delete<void>(RESOURCES_API_PATH, { params: { path } });--const reportBulkDeleteOutcome = (succeededCount: number, failedCount: number): void => {- if (failedCount === 0) {- toast.success(`${succeededCount} ${pluralizeItems(succeededCount)} deleted`);-- return;- }-- if (succeededCount === 0) {- toast.error('Bulk delete failed', {- description: `Failed to delete ${failedCount} ${pluralizeItems(failedCount)}`,- });-- return;- }-- toast.warning(`${succeededCount} succeeded · ${failedCount} failed`);-};+/**+ * Issues one `DELETE /resources/?paths[]=…` regardless of how many files are+ * passed in. The backend deduplicates and validates atomically: either every+ * path is removed or nothing is, so callers don't have to reconcile partial+ * failures. The response payload enumerates every entry that was actually+ * removed — but we ignore it here because the GraphQL `resourceDeleted`+ * subscription already drives the Apollo cache update.+ */+const deleteResourcesRequest = (paths: readonly string[]) =>+ api.delete<void>(`${RESOURCES_API_PATH}?${buildPathsQuery(paths)}`);/**- * Owns both the single-resource and bulk-delete flows. Component drives the+ * Owns both the single-resource and bulk-delete flows. The component drives the* confirmation dialog state through the returned `fileToDelete`/`requestDelete`/* `clearFileToDelete` triple, while the hook hides every API call and toast.*@@ -59,44 +56,48 @@ export const useResourcesDelete = ({ onAfterDelete }: UseResourcesDeleteParams =setFileToDelete(null);}, []);+ const deleteFiles = useCallback(+ async (filesToDelete: readonly FileNode[]) => {+ if (filesToDelete.length === 0) {+ return;+ }++ try {+ await deleteResourcesRequest(filesToDelete.map((file) => file.path));++ if (filesToDelete.length === 1) {+ const single = filesToDelete[0];+ toast.success(single.isDir ? 'Directory deleted' : 'Resource deleted');+ } else {+ toast.success(`${filesToDelete.length} ${pluralizeItems(filesToDelete.length)} deleted`);+ }++ onAfterDelete?.();+ } catch (error) {+ const description = getApiErrorMessage(error, 'Failed to delete resource');++ toast.error('Delete failed', { description });+ }+ },+ [onAfterDelete],+ );+const confirmDelete = useCallback(async () => {if (!fileToDelete) {return;}try {- await deleteResourceRequest(fileToDelete.path);- toast.success(fileToDelete.isDir ? 'Directory deleted' : 'Resource deleted');- onAfterDelete?.();- } catch (error) {- const description = getApiErrorMessage(error, 'Failed to delete resource');-- toast.error('Delete failed', { description });+ await deleteFiles([fileToDelete]);} finally {setFileToDelete(null);}- }, [fileToDelete, onAfterDelete]);-- const deleteBulk = useCallback(- async (filesToDelete: FileNode[]) => {- if (filesToDelete.length === 0) {- return;- }-- const results = await Promise.allSettled(filesToDelete.map((file) => deleteResourceRequest(file.path)));- const succeededCount = results.filter((result) => result.status === 'fulfilled').length;- const failedCount = results.length - succeededCount;-- reportBulkDeleteOutcome(succeededCount, failedCount);- onAfterDelete?.();- },- [onAfterDelete],- );+ }, [deleteFiles, fileToDelete]);return {clearFileToDelete,confirmDelete,- deleteBulk,+ deleteFiles,fileToDelete,requestDelete,};diff --git a/frontend/src/features/resources/use-resources-move.ts b/frontend/src/features/resources/use-resources-move.tsindex 34cbbc03..ff80b528 100644--- a/frontend/src/features/resources/use-resources-move.ts+++ b/frontend/src/features/resources/use-resources-move.ts@@ -2,7 +2,7 @@ import { useCallback, useState } from 'react';import { toast } from 'sonner';import { z } from 'zod';-import { api, type ApiHttpError, getApiErrorMessage } from '@/lib/axios';+import { api, getApiErrorMessage, getApiErrorStatusCode } from '@/lib/axios';import { RESOURCES_MOVE_API_PATH } from './resources-constants';@@ -13,7 +13,6 @@ export const resourcesMoveFormSchema = z.object({.min(1, { message: 'Destination cannot be empty' }).refine((value) => !value.startsWith('/'), { message: 'Destination must be a relative path' }).refine((value) => !value.split('/').includes('..'), { message: 'Destination must not contain ".."' }),- shouldOverwrite: z.boolean(),});export interface ResourcesMoveConflict {@@ -35,7 +34,12 @@ interface UseResourcesMoveResult {/** Drop the pending conflicts without retrying. */cancelConflicts: () => void;isMoving: boolean;- move: (sourcePath: string, values: ResourcesMoveFormValues) => Promise<boolean>;+ /**+ * Issue a single move. `force=false` collects 409s into `pendingConflicts`+ * for an aggregated dialog; `force=true` skips that branch and toasts on+ * any failure (used by the "Move with overwrite" CTA path).+ */+ move: (sourcePath: string, values: ResourcesMoveFormValues, force: boolean) => Promise<boolean>;/*** 409 conflicts collected across one or more parallel `move()` calls. The consumer* shows a single "Replace?" dialog summarising the count; clicking Replace retries@@ -46,12 +50,6 @@ interface UseResourcesMoveResult {resolveConflicts: () => Promise<void>;}-const getStatusCode = (error: unknown): number | undefined => {- const httpError = error as ApiHttpError | null | undefined;-- return httpError?.statusCode ?? httpError?.response?.status;-};-const extractName = (path: string): string => path.split('/').pop() ?? path;/** Wraps `PUT /resources/move` for rename / move operations. */@@ -79,7 +77,7 @@ export const useResourcesMove = (): UseResourcesMoveResult => {// every parallel `move()` call. `force = true` skips this branch (the// overwrite was already pre-confirmed), so retries land in the toast// path on any unexpected re-conflict.- if (getStatusCode(error) === 409 && !force) {+ if (getApiErrorStatusCode(error) === 409 && !force) {setPendingConflicts((prev) => [...prev,{@@ -105,8 +103,8 @@ export const useResourcesMove = (): UseResourcesMoveResult => {);const move = useCallback(- (sourcePath: string, { destination, shouldOverwrite }: ResourcesMoveFormValues): Promise<boolean> =>- performMove(sourcePath, destination.trim(), shouldOverwrite),+ (sourcePath: string, { destination }: ResourcesMoveFormValues, force: boolean): Promise<boolean> =>+ performMove(sourcePath, destination.trim(), force),[performMove],);diff --git a/frontend/src/lib/axios.ts b/frontend/src/lib/axios.tsindex 7f784d7c..a25b9f2b 100644--- a/frontend/src/lib/axios.ts+++ b/frontend/src/lib/axios.ts@@ -224,5 +224,23 @@ export const getApiErrorMessage = (return err.message || fallback;};+/**+ * Extract the HTTP status code from an unknown error thrown by axios. Returns+ * `undefined` for non-axios errors or when the request never reached a server.+ *+ * Used across hooks that need to branch on a specific status (most commonly+ * 409 conflict) without re-implementing the same `error.statusCode ??+ * error.response?.status` shape every time.+ */+export const getApiErrorStatusCode = (error: unknown): number | undefined => {+ if (!error || typeof error !== 'object') {+ return undefined;+ }++ const httpError = error as ApiHttpError;++ return httpError.statusCode ?? httpError.response?.status;+};+export default axios;export { axios };diff --git a/frontend/src/pages/resources/resources.tsx b/frontend/src/pages/resources/resources.tsxindex 4cf7a05b..7d5577f2 100644--- a/frontend/src/pages/resources/resources.tsx+++ b/frontend/src/pages/resources/resources.tsx@@ -2,10 +2,12 @@ import { Copy, FileSymlink, Folder, FolderPlus, FolderUp, Loader2, Search, X } fimport { useCallback, useMemo, useState } from 'react';import { toast } from 'sonner';+import ConfirmationDialog from '@/components/shared/confirmation-dialog';import {bulkCopyAction,bulkCopyPathsAction,bulkDeleteAction,+ bulkDownloadAction,bulkMoveAction,copyPathAction,deleteAction,@@ -14,8 +16,7 @@ import {type FileManagerAction,type FileManagerBulkAction,type FileNode,-} from '@/components/file-manager';-import ConfirmationDialog from '@/components/shared/confirmation-dialog';+} from '@/components/shared/file-manager';import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';import { Button } from '@/components/ui/button';import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';@@ -29,7 +30,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, pluralizeItems, toFileNode } from '@/features/resources/resources-utils';+import { buildResourcesDownloadHref, 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';@@ -64,7 +65,9 @@ const Resources = () => {/*** Drag-and-drop entry point: move every dragged item into `destinationDir` by issuing* one `PUT /resources/move` per source. We don't pre-check or batch — each request- * goes out independently so a partial failure still moves the rest.+ * goes out independently so a partial failure still moves the rest. Conflicts feed+ * into `pendingConflicts` and surface through the shared overwrite confirm dialog;+ * `force=false` is therefore safe even for repeated drags onto the same target.*/const handleMoveItems = useCallback(async (sources: FileNode[], destinationDir: string) => {@@ -72,7 +75,7 @@ const Resources = () => {sources.map((source) => {const destination = destinationDir ? `${destinationDir}/${source.name}` : source.name;- return moveAction.move(source.path, { destination, shouldOverwrite: false });+ return moveAction.move(source.path, { destination }, false);}),);},@@ -123,7 +126,7 @@ const Resources = () => {const handleOpenFile = useCallback((file: FileNode) => {const anchor = document.createElement('a');- anchor.href = buildResourceDownloadHref(file);+ anchor.href = buildResourcesDownloadHref([file]);anchor.download = file.name;anchor.rel = 'noopener';document.body.appendChild(anchor);@@ -133,7 +136,10 @@ const Resources = () => {const fileManagerActions = useMemo<FileManagerAction[]>(() => [- downloadAction(buildResourceDownloadHref),+ // Row download is the single-file specialisation of the bulk download:+ // we hand the URL builder a 1-element array so the same backend+ // contract (`?paths[]=`) is used everywhere.+ downloadAction((file) => buildResourcesDownloadHref([file])),copyPathAction(handleCopyPath),{appliesToDirs: true,@@ -159,12 +165,13 @@ const Resources = () => {// actions in the overflow `…` menu, then destructive Delete on the right.const fileManagerBulkActions = useMemo<FileManagerBulkAction[]>(() => [+ bulkDownloadAction(buildResourcesDownloadHref),bulkMoveAction((files) => setFilesToMove(files)),bulkCopyAction((files) => setFilesToCopy(files), { overflow: true }),bulkCopyPathsAction(handleBulkCopyPaths),- bulkDeleteAction(deletion.deleteBulk),+ bulkDeleteAction(deletion.deleteFiles),],- [deletion.deleteBulk, handleBulkCopyPaths],+ [deletion.deleteFiles, handleBulkCopyPaths],);const handleDeleteDialogOpenChange = useCallback(