Skip to content

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

feat: integrate user resources into flows and polish file manager

Sergey Kozyrenko3da56244dd4b
diff --git a/frontend/.gitignore b/frontend/.gitignore
index d661acaa..aaa05ede 100644
--- a/frontend/.gitignore
+++ b/frontend/.gitignore
@@ -13,6 +13,7 @@ dist
dist-ssr
ssl
*.local
+*.tsbuildinfo
# Editor directories and files
.DS_Store
diff --git a/frontend/src/components/file-manager/file-manager-actions.tsx b/frontend/src/components/file-manager/file-manager-actions.tsx
index aec21885..b555d704 100644
--- a/frontend/src/components/file-manager/file-manager-actions.tsx
+++ b/frontend/src/components/file-manager/file-manager-actions.tsx
@@ -46,5 +46,4 @@ export const deleteAction = (onDelete: (file: FileNode) => void): FileManagerAct
label: 'Delete',
onSelect: onDelete,
separatorBefore: true,
- variant: 'destructive',
});
diff --git a/frontend/src/components/file-manager/file-manager-row.tsx b/frontend/src/components/file-manager/file-manager-row.tsx
index 926a1cc9..d6fda748 100644
--- a/frontend/src/components/file-manager/file-manager-row.tsx
+++ b/frontend/src/components/file-manager/file-manager-row.tsx
@@ -20,6 +20,7 @@ import {
import { cn } from '@/lib/utils';
import type { FileManagerAction, FileManagerInternalNode } from './file-manager-types';
+import type { FileManagerNodeDndHandlers } from './use-file-manager-dnd';
import { FileManagerHighlightedName } from './file-manager-highlighted-name';
import { getFileTypeIcon } from './file-manager-icons';
@@ -36,6 +37,8 @@ const skipRowClickProps = { [SKIP_ROW_CLICK_ATTR]: '' };
interface FileManagerRowProps {
actions: readonly FileManagerAction[];
activeRowPath: null | string;
+ /** Drag/drop handlers for this row. `null` when intra-tree DnD is disabled. */
+ dnd: FileManagerNodeDndHandlers | null;
file: FileManagerInternalNode;
formatModified?: (modifiedAt: Date | string | undefined) => string;
gridTemplate: string;
@@ -68,6 +71,7 @@ const buildVisibleActions = (
const FileManagerRowImpl = ({
actions,
activeRowPath,
+ dnd,
file,
formatModified = defaultFormatModified,
gridTemplate,
@@ -171,6 +175,10 @@ const FileManagerRowImpl = ({
gridTemplateColumns: gridTemplate,
} as CSSProperties & Record<'--fm-depth', number>;
+ const isDraggable = !!dnd && !file.isGroupRoot;
+ const isDropTarget = dnd?.isDropTarget ?? false;
+ const isBeingDragged = dnd?.isBeingDragged ?? false;
+
const row = (
<div
aria-expanded={file.isDir ? isExpanded : undefined}
@@ -179,12 +187,30 @@ const FileManagerRowImpl = ({
aria-selected={isSelected}
aria-setsize={setSize}
className={cn(
- 'group hover:bg-muted/50 grid cursor-pointer items-center gap-3 px-3 py-1.5 transition-colors outline-none',
+ 'group hover:bg-accent grid cursor-pointer items-center gap-3 px-3 py-1.5 transition-colors outline-none',
'focus-visible:bg-muted/70 focus-visible:ring-ring focus-visible:ring-1',
isSelected && 'bg-muted',
+ isDropTarget && 'bg-primary/10 ring-primary/40 ring-1 ring-inset',
+ // Ghost every row that's part of the in-flight drag (the grabbed row
+ // plus any other selected rows being moved together) so the user sees
+ // the entire batch on the move, not just the row whose drag image the
+ // browser is rendering. Combine reduced opacity + dashed outline so
+ // the effect is unmistakable even when the row is already selected
+ // (`bg-muted` would otherwise mute the opacity contrast).
+ isBeingDragged && 'border-muted-foreground/40 border border-dashed opacity-40',
+ // Counter-act the 1px border above to keep the row from shifting layout
+ // when the dashed border kicks in.
+ !isBeingDragged && 'border border-transparent',
)}
data-path={file.path}
+ draggable={isDraggable}
onClick={handleRowClick}
+ onDragEnd={dnd?.onDragEnd}
+ onDragEnter={dnd?.onDragEnter}
+ onDragLeave={dnd?.onDragLeave}
+ onDragOver={dnd?.onDragOver}
+ onDragStart={dnd?.onDragStart}
+ onDrop={dnd?.onDrop}
onFocus={() => onFocusRow(file.path)}
role="treeitem"
style={rowStyle}
@@ -208,7 +234,15 @@ const FileManagerRowImpl = ({
/>
)}
- <div className="flex min-w-0 items-center gap-1.5 pl-[calc(var(--fm-depth)*16px)]">
+ <div className="relative flex min-w-0 items-center gap-1.5 self-stretch pl-[calc(var(--fm-depth)*16px)]">
+ {Array.from({ length: file.depth }, (_, i) => (
+ <span
+ aria-hidden="true"
+ className="bg-border pointer-events-none absolute -inset-y-1.5 w-px"
+ key={i}
+ style={{ left: `${i * 16 + 6}px` }}
+ />
+ ))}
{file.isDir ? (
<span
aria-hidden="true"
@@ -221,7 +255,7 @@ const FileManagerRowImpl = ({
) : (
<span
aria-hidden="true"
- className="size-4 shrink-0"
+ className="-mx-0.5 size-4 shrink-0"
/>
)}
<Icon className={cn('size-4 shrink-0', tone)} />
diff --git a/frontend/src/components/file-manager/file-manager-skeleton.tsx b/frontend/src/components/file-manager/file-manager-skeleton.tsx
index 718f6f7d..219373d9 100644
--- a/frontend/src/components/file-manager/file-manager-skeleton.tsx
+++ b/frontend/src/components/file-manager/file-manager-skeleton.tsx
@@ -1,52 +1,120 @@
+import { type CSSProperties } from 'react';
+
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
-const ROOT_NAME_WIDTHS = ['w-28', 'w-36', 'w-24', 'w-32'];
-const NESTED_NAME_WIDTHS = ['w-44', 'w-36', 'w-28'];
-
-export const FileManagerSkeleton = () => (
- <div className="bg-card overflow-hidden rounded-lg border">
- <div className="bg-muted/30 flex items-center gap-3 border-b px-3 py-2">
- <Skeleton className="size-4 shrink-0 rounded-sm" />
- <Skeleton className="h-3 w-12" />
- <div className="ml-auto flex items-center gap-3">
- <Skeleton className="h-3 w-10" />
- <Skeleton className="h-3 w-16" />
- <div className="size-7" />
+import type { FileManagerColumnsConfig } from './file-manager-types';
+
+import { buildFileManagerGridTemplate } from './file-manager-utils';
+
+interface FileManagerSkeletonRow {
+ depth: number;
+ isDir: boolean;
+ nameWidth: string;
+ sizeWidth: string;
+}
+
+const SKELETON_ROWS: readonly FileManagerSkeletonRow[] = [
+ { depth: 0, isDir: true, nameWidth: 'w-28', sizeWidth: 'w-10' },
+ { depth: 1, isDir: false, nameWidth: 'w-44', sizeWidth: 'w-12' },
+ { depth: 1, isDir: false, nameWidth: 'w-36', sizeWidth: 'w-10' },
+ { depth: 1, isDir: false, nameWidth: 'w-28', sizeWidth: 'w-14' },
+ { depth: 0, isDir: true, nameWidth: 'w-36', sizeWidth: 'w-10' },
+ { depth: 0, isDir: false, nameWidth: 'w-24', sizeWidth: 'w-14' },
+ { depth: 0, isDir: false, nameWidth: 'w-32', sizeWidth: 'w-12' },
+];
+
+interface FileManagerSkeletonProps {
+ columns?: FileManagerColumnsConfig;
+ hasActions?: boolean;
+ isCheckboxVisible?: boolean;
+}
+
+export const FileManagerSkeleton = ({
+ columns,
+ hasActions = false,
+ isCheckboxVisible = false,
+}: FileManagerSkeletonProps) => {
+ const isSizeVisible = columns?.isSizeVisible ?? true;
+ const isModifiedVisible = columns?.isModifiedVisible ?? true;
+ const gridTemplate = buildFileManagerGridTemplate(isSizeVisible, isModifiedVisible, hasActions);
+
+ return (
+ <div className="bg-card flex flex-col overflow-hidden rounded-lg border">
+ <div
+ className="bg-muted/30 grid items-center gap-3 border-b px-3 py-2"
+ style={{ gridTemplateColumns: gridTemplate }}
+ >
+ {isCheckboxVisible ? (
+ <Skeleton className="size-4 shrink-0 rounded-sm" />
+ ) : (
+ <span
+ aria-hidden="true"
+ className="size-4"
+ />
+ )}
+ <Skeleton className="h-3 w-12" />
+ {isSizeVisible && <Skeleton className="h-3 w-10" />}
+ {isModifiedVisible && <Skeleton className="h-3 w-16" />}
+ {hasActions && (
+ <span
+ aria-hidden="true"
+ className="size-7"
+ />
+ )}
</div>
- </div>
- <div className="flex flex-col gap-px py-1">
- <div className="flex items-center gap-3 px-3 py-1.5">
- <Skeleton className="size-4 shrink-0 rounded-sm" />
- <Skeleton className="size-3.5 shrink-0" />
- <Skeleton className="size-4 shrink-0" />
- <Skeleton className="h-4 w-20" />
+
+ <div className="flex flex-col py-1">
+ {SKELETON_ROWS.map((row, index) => {
+ const rowStyle = {
+ '--fm-depth': row.depth,
+ gridTemplateColumns: gridTemplate,
+ } as CSSProperties & Record<'--fm-depth', number>;
+
+ return (
+ <div
+ className="grid items-center gap-3 border border-transparent px-3 py-1.5"
+ key={index}
+ style={rowStyle}
+ >
+ {isCheckboxVisible ? (
+ <Skeleton className="size-4 shrink-0 rounded-sm" />
+ ) : (
+ <span
+ aria-hidden="true"
+ className="size-4"
+ />
+ )}
+
+ <div className="flex min-w-0 items-center gap-1.5 pl-[calc(var(--fm-depth)*16px)]">
+ {row.isDir ? (
+ <Skeleton className="-mx-0.5 size-4 shrink-0 rounded-sm" />
+ ) : (
+ <span
+ aria-hidden="true"
+ className="-mx-0.5 size-4 shrink-0"
+ />
+ )}
+ <Skeleton className="size-4 shrink-0 rounded-sm" />
+ <Skeleton className={cn('h-4', row.nameWidth)} />
+ </div>
+
+ {isSizeVisible && (
+ <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 && (
+ <span
+ aria-hidden="true"
+ className="size-7"
+ />
+ )}
+ </div>
+ );
+ })}
</div>
- {NESTED_NAME_WIDTHS.map((width, index) => (
- <div
- className="flex items-center gap-3 px-3 py-1.5 pl-9"
- key={`nested-${index}`}
- >
- <Skeleton className="size-4 shrink-0 rounded-sm" />
- <Skeleton className="size-4 shrink-0" />
- <Skeleton className={cn('h-4', width)} />
- <Skeleton className="ml-auto h-3 w-10" />
- <Skeleton className="h-3 w-16" />
- </div>
- ))}
- {ROOT_NAME_WIDTHS.map((width, index) => (
- <div
- className="flex items-center gap-3 px-3 py-1.5"
- key={`root-${index}`}
- >
- <Skeleton className="size-4 shrink-0 rounded-sm" />
- <Skeleton className="size-3.5 shrink-0" />
- <Skeleton className="size-4 shrink-0" />
- <Skeleton className={cn('h-4', width)} />
- <Skeleton className="ml-auto h-3 w-10" />
- <Skeleton className="h-3 w-16" />
- </div>
- ))}
</div>
- </div>
-);
+ );
+};
diff --git a/frontend/src/components/file-manager/file-manager-tree-node.tsx b/frontend/src/components/file-manager/file-manager-tree-node.tsx
index 34de3fde..bb745521 100644
--- a/frontend/src/components/file-manager/file-manager-tree-node.tsx
+++ b/frontend/src/components/file-manager/file-manager-tree-node.tsx
@@ -1,12 +1,15 @@
import { Fragment, type MouseEvent as ReactMouseEvent } from 'react';
import type { FileManagerAction, FileManagerInternalNode } from './file-manager-types';
+import type { FileManagerNodeDndHandlers } from './use-file-manager-dnd';
import { FileManagerRow } from './file-manager-row';
interface FileManagerTreeNodeProps {
actions: readonly FileManagerAction[];
activeRowPath: null | string;
+ /** Returns drag/drop handlers for a node, or `null` when DnD is disabled. */
+ bindNodeDnd: (node: FileManagerInternalNode) => FileManagerNodeDndHandlers | null;
expandedPaths: Set<string>;
formatModified?: (modifiedAt: Date | string | undefined) => string;
gridTemplate: string;
@@ -36,6 +39,7 @@ interface FileManagerTreeNodeProps {
export const FileManagerTreeNode = ({
actions,
activeRowPath,
+ bindNodeDnd,
expandedPaths,
formatModified,
gridTemplate,
@@ -56,12 +60,14 @@ export const FileManagerTreeNode = ({
const isExpanded = expandedPaths.has(node.path);
const isSelected = selectedPaths.has(node.path);
const renderChildren = node.isDir && isExpanded && node.children.length > 0;
+ const dnd = bindNodeDnd(node);
return (
<Fragment>
<FileManagerRow
actions={actions}
activeRowPath={activeRowPath}
+ dnd={dnd}
file={node}
formatModified={formatModified}
gridTemplate={gridTemplate}
@@ -84,6 +90,7 @@ export const FileManagerTreeNode = ({
<FileManagerTreeNode
actions={actions}
activeRowPath={activeRowPath}
+ bindNodeDnd={bindNodeDnd}
expandedPaths={expandedPaths}
formatModified={formatModified}
gridTemplate={gridTemplate}
diff --git a/frontend/src/components/file-manager/file-manager-types.ts b/frontend/src/components/file-manager/file-manager-types.ts
index ef30a772..0bc884ba 100644
--- a/frontend/src/components/file-manager/file-manager-types.ts
+++ b/frontend/src/components/file-manager/file-manager-types.ts
@@ -76,6 +76,13 @@ export interface FileManagerProps {
columns?: FileManagerColumnsConfig;
/** Empty state node (rendered when files.length === 0 and not loading). */
emptyState?: ReactNode;
+ /**
+ * Forces row checkboxes to be visible / hidden, independently of `onBulkDelete`.
+ * - `true` → checkboxes shown even without a bulk-delete handler (e.g. picker dialogs).
+ * - `false` → checkboxes hidden even when `onBulkDelete` is provided.
+ * - `undefined` (default) → checkboxes shown whenever `onBulkDelete` is set.
+ */
+ enableSelection?: boolean;
files: FileNode[];
isLoading?: boolean;
/** Localizable user-facing strings. */
@@ -85,6 +92,23 @@ export interface FileManagerProps {
* if both a directory and one of its descendants were selected, only the directory is included.
*/
onBulkDelete?: (files: FileNode[]) => Promise<void> | void;
+ /**
+ * Enables internal drag-and-drop: rows become draggable and directories accept drops.
+ * Invoked with the dragged item(s) and the destination directory path (`''` for root).
+ *
+ * `FileManager` does **not** mutate its own list — the caller is expected to refresh
+ * the data (or rely on subscriptions) so the new positions become visible.
+ */
+ onMoveItems?: (sources: FileNode[], destinationDir: string) => Promise<void> | void;
+ /**
+ * Fires whenever the multi-selection changes. Use it from selection-only
+ * flows (e.g. resource pickers) where the parent owns its own confirm button
+ * and needs to know which items are currently checked.
+ *
+ * The supplied callback is read through a ref, so it does not need to be
+ * memoized — only meaningful selection changes will trigger it.
+ */
+ onSelectionChange?: (selectedPaths: Set<string>) => void;
/** Synthetic top-level groups (e.g. Uploads / Container). When omitted, root is flat. */
rootGroups?: FileManagerRootGroup[];
/** Search query and matching empty state. Provide `query` to enable filtering. */
diff --git a/frontend/src/components/file-manager/file-manager-utils.ts b/frontend/src/components/file-manager/file-manager-utils.ts
index 2849a412..df225fec 100644
--- a/frontend/src/components/file-manager/file-manager-utils.ts
+++ b/frontend/src/components/file-manager/file-manager-utils.ts
@@ -232,14 +232,14 @@ export const walkTree = (
return result;
};
-/**
- * Collect paths of *file* nodes only (no synthetic group roots, no directories).
- * Used as the universe for "select all".
- */
+/** Collect paths of *file* nodes only (no synthetic group roots, no directories). */
export const collectAllFilePaths = (nodes: FileManagerInternalNode[]): string[] =>
walkTree(nodes, { include: (node) => !node.isGroupRoot && !node.isDir });
-/** Collect paths of every selectable node (files + real directories), used for bulk-delete validation. */
+/**
+ * Collect paths of every selectable node (files + real directories), excluding
+ * synthetic group roots. Used as the universe for "select all" / bulk operations.
+ */
export const collectAllNodePaths = (nodes: FileManagerInternalNode[]): string[] =>
walkTree(nodes, { include: (node) => !node.isGroupRoot });
diff --git a/frontend/src/components/file-manager/file-manager.tsx b/frontend/src/components/file-manager/file-manager.tsx
index eb528768..63be3e10 100644
--- a/frontend/src/components/file-manager/file-manager.tsx
+++ b/frontend/src/components/file-manager/file-manager.tsx
@@ -1,4 +1,4 @@
-import { type MouseEvent as ReactMouseEvent, useCallback, useMemo, useRef, useState } from 'react';
+import { type MouseEvent as ReactMouseEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { cn } from '@/lib/utils';
@@ -11,12 +11,14 @@ import { FileManagerTreeNode } from './file-manager-tree-node';
import {
buildFileManagerGridTemplate,
buildFileManagerTree,
- collectAllFilePaths,
+ collectAllNodePaths,
collectVisibleFlat,
filterFileManagerTree,
+ findNodeByPath,
getCheckboxState,
normalizeRootGroups,
} from './file-manager-utils';
+import { useFileManagerDnd } from './use-file-manager-dnd';
import { useFileManagerExpansion } from './use-file-manager-expansion';
import { useFileManagerKeyboardNavigation } from './use-file-manager-keyboard';
import { useFileManagerSelection } from './use-file-manager-selection';
@@ -28,10 +30,13 @@ export const FileManager = ({
className,
columns,
emptyState,
+ enableSelection,
files,
isLoading,
labels,
onBulkDelete,
+ onMoveItems,
+ onSelectionChange,
rootGroups,
search,
}: FileManagerProps) => {
@@ -50,7 +55,7 @@ export const FileManager = ({
[fullTree, isFiltering, trimmedSearch],
);
- const allFilePaths = useMemo(() => collectAllFilePaths(visibleTree), [visibleTree]);
+ const allSelectablePaths = useMemo(() => collectAllNodePaths(visibleTree), [visibleTree]);
const { expandedPaths, toggleExpand } = useFileManagerExpansion({
isFiltering,
@@ -69,10 +74,23 @@ export const FileManager = ({
selectedPaths,
setSelection,
toggleSelectAll,
- } = useFileManagerSelection({ allFilePaths, flatVisible });
+ } = useFileManagerSelection({ allSelectablePaths, flatVisible });
- const isCheckboxVisible = !!onBulkDelete;
+ const isCheckboxVisible = enableSelection ?? !!onBulkDelete;
const hasActions = !!actions?.length;
+
+ // Report selection changes upstream without forcing parents to memoize the
+ // callback — stash it in a ref so the effect only re-fires when the actual
+ // selection changes (not when a fresh function instance is passed in).
+ const onSelectionChangeRef = useRef(onSelectionChange);
+
+ useEffect(() => {
+ onSelectionChangeRef.current = onSelectionChange;
+ }, [onSelectionChange]);
+
+ useEffect(() => {
+ onSelectionChangeRef.current?.(selectedPaths);
+ }, [selectedPaths]);
const gridTemplate = useMemo(
() => buildFileManagerGridTemplate(isSizeVisible, isModifiedVisible, hasActions),
[hasActions, isModifiedVisible, isSizeVisible],
@@ -120,6 +138,13 @@ export const FileManager = ({
visibleTree,
});
+ const dnd = useFileManagerDnd({
+ findNode: useCallback((path: string) => findNodeByPath(fullTree, path), [fullTree]),
+ onClearSelection: clearSelection,
+ onMoveItems,
+ selectedPaths,
+ });
+
const handleContainerClick = useCallback(
(event: ReactMouseEvent<HTMLDivElement>) => {
if (event.target === event.currentTarget) {
@@ -132,7 +157,11 @@ export const FileManager = ({
if (isLoading) {
return (
<div className={className}>
- <FileManagerSkeleton />
+ <FileManagerSkeleton
+ columns={columns}
+ hasActions={hasActions}
+ isCheckboxVisible={isCheckboxVisible}
+ />
</div>
);
}
@@ -186,13 +215,27 @@ export const FileManager = ({
<div
aria-label="File tree"
aria-multiselectable={isCheckboxVisible || undefined}
- className="flex flex-1 flex-col overflow-y-auto py-1"
+ className={cn(
+ 'flex flex-1 flex-col overflow-y-auto py-1 transition-colors',
+ // Highlight the whole tree only when the cursor is actually hovering
+ // the empty area outside any row — that's the only place a "drop to
+ // root" will be accepted. `border-radius: inherit` makes the inset
+ // ring follow the outer container's rounded corners (top corners are
+ // hidden behind the header, so only the bottom is visually affected).
+ dnd.container.isRootDropTarget &&
+ 'bg-primary/10 ring-primary ring-1 ring-inset [border-radius:inherit]',
+ )}
+ onDragEnter={dnd.isEnabled ? dnd.container.onDragEnter : undefined}
+ onDragLeave={dnd.isEnabled ? dnd.container.onDragLeave : undefined}
+ onDragOver={dnd.isEnabled ? dnd.container.onDragOver : undefined}
+ onDrop={dnd.isEnabled ? dnd.container.onDrop : undefined}
role="tree"
>
{visibleTree.map((node, index) => (
<FileManagerTreeNode
actions={effectiveActions}
activeRowPath={resolvedActiveRow}
+ bindNodeDnd={dnd.bindNodeDnd}
expandedPaths={expandedPaths}
formatModified={formatModified}
gridTemplate={gridTemplate}
@@ -214,14 +257,16 @@ export const FileManager = ({
))}
</div>
- <FileManagerBulkActionsBar
- files={files}
- labels={effectiveLabels}
- onBulkDelete={onBulkDelete}
- onClearSelection={clearSelection}
- onSelectionChange={setSelection}
- selectedPaths={selectedPaths}
- />
+ {onBulkDelete && (
+ <FileManagerBulkActionsBar
+ files={files}
+ labels={effectiveLabels}
+ onBulkDelete={onBulkDelete}
+ onClearSelection={clearSelection}
+ onSelectionChange={setSelection}
+ selectedPaths={selectedPaths}
+ />
+ )}
</div>
);
};
diff --git a/frontend/src/components/file-manager/index.ts b/frontend/src/components/file-manager/index.ts
index 100b7721..d46c1909 100644
--- a/frontend/src/components/file-manager/index.ts
+++ b/frontend/src/components/file-manager/index.ts
@@ -9,3 +9,4 @@ export type {
FileManagerRootGroup,
FileNode,
} from './file-manager-types';
+export { dedupeOverlappingPaths } from './file-manager-utils';
diff --git a/frontend/src/components/file-manager/use-file-manager-dnd.ts b/frontend/src/components/file-manager/use-file-manager-dnd.ts
new file mode 100644
index 00000000..b5b9b684
--- /dev/null
+++ b/frontend/src/components/file-manager/use-file-manager-dnd.ts
@@ -0,0 +1,522 @@
+import { type DragEvent as ReactDragEvent, useCallback, useEffect, useRef, useState } from 'react';
+
+import type { FileManagerInternalNode, FileNode } from './file-manager-types';
+
+import { dedupeOverlappingPaths } from './file-manager-utils';
+
+const FM_DND_MIME = 'application/x-fm-paths';
+
+/** Sentinel destination — represents the root area outside any directory. */
+export const FM_ROOT_DROP_SENTINEL = '__fm_root__';
+
+export interface FileManagerContainerDndHandlers {
+ isRootDropTarget: boolean;
+ onDragEnter: (event: ReactDragEvent<HTMLDivElement>) => void;
+ onDragLeave: (event: ReactDragEvent<HTMLDivElement>) => void;
+ onDragOver: (event: ReactDragEvent<HTMLDivElement>) => void;
+ onDrop: (event: ReactDragEvent<HTMLDivElement>) => void;
+}
+
+export interface FileManagerNodeDndHandlers {
+ /**
+ * `true` when this row is part of the in-flight drag operation. Drives the
+ * "ghosted" appearance for every selected row when the user drags one of them,
+ * so it's obvious that the whole batch is being moved (not just the row whose
+ * native drag image the browser is showing).
+ */
+ isBeingDragged: boolean;
+ isDropTarget: boolean;
+ onDragEnd: () => void;
+ onDragEnter: (event: ReactDragEvent<HTMLDivElement>) => void;
+ onDragLeave: (event: ReactDragEvent<HTMLDivElement>) => void;
+ onDragOver: (event: ReactDragEvent<HTMLDivElement>) => void;
+ onDragStart: (event: ReactDragEvent<HTMLDivElement>) => void;
+ onDrop: (event: ReactDragEvent<HTMLDivElement>) => void;
+}
+
+interface UseFileManagerDndParams {
+ /** Stable "real" `FileNode` reference for a path — used to build the source list. */
+ findNode: (path: string) => FileManagerInternalNode | undefined;
+ /**
+ * Invoked when the user starts dragging a row that's NOT part of the current
+ * selection (Finder-style: "you're acting on something else, the selection is
+ * dropped") and after a successful drop (selection paths are now stale because
+ * the items live elsewhere). Optional — when omitted, selection isn't touched.
+ */
+ onClearSelection?: () => void;
+ /** When undefined, DnD is fully disabled. */
+ onMoveItems?: (sources: FileNode[], destinationDir: string) => Promise<void> | void;
+ /**
+ * Currently-selected paths. When the user grabs a row that's part of this set,
+ * every selected item is dragged together; otherwise only the grabbed row.
+ * Synthetic group roots and overlapping descendants are filtered automatically.
+ */
+ selectedPaths?: Set<string>;
+}
+
+interface UseFileManagerDndResult {
+ /** Returns drag/drop handlers bound to a specific tree node, or `null` when DnD is off. */
+ bindNodeDnd: (node: FileManagerInternalNode) => FileManagerNodeDndHandlers | null;
+ /**
+ * Drag/drop handlers for the outer tree container. Drops here are interpreted as
+ * "move to library root" and only fire when the cursor is over the empty area
+ * outside any row (rows always stop event propagation).
+ */
+ container: FileManagerContainerDndHandlers;
+ /** When true, rows have to set `draggable={true}` themselves. */
+ isEnabled: boolean;
+}
+
+/** Returns the parent directory of a virtual path, or `''` for root. */
+const getParentDir = (path: string): string => {
+ const idx = path.lastIndexOf('/');
+
+ return idx === -1 ? '' : path.slice(0, idx);
+};
+
+/**
+ * Validates that every source can be moved into `destDir`:
+ * - never into itself,
+ * - never into its current parent (no-op),
+ * - never into one of its own descendants.
+ */
+const isValidMove = (sources: FileManagerInternalNode[], destDir: string): boolean => {
+ if (sources.length === 0) {
+ return false;
+ }
+
+ for (const src of sources) {
+ if (src.path === destDir) {
+ return false;
+ }
+
+ if (getParentDir(src.path) === destDir) {
+ return false;
+ }
+
+ if (src.isDir && (destDir === src.path || destDir.startsWith(`${src.path}/`))) {
+ return false;
+ }
+ }
+
+ return true;
+};
+
+const isFmDragEvent = (event: ReactDragEvent<HTMLDivElement>): boolean =>
+ event.dataTransfer.types?.includes(FM_DND_MIME) ?? false;
+
+/**
+ * Top-level files (no parent directory) act as a pass-through to the container's
+ * root-drop logic: instead of treating the row as its own drop target, we let the
+ * drag event bubble so the container accepts it as a "move to library root".
+ *
+ * The user mental model: anything outside any folder is "the root" — that includes
+ * the empty padding *and* loose files sitting at the top level.
+ */
+const isRootPassthrough = (node: FileManagerInternalNode): boolean =>
+ !node.isDir && !node.isGroupRoot && getParentDir(node.path) === '';
+
+/**
+ * Encapsulates the drag-counter pattern + path-set tracking used by `FileManager` for
+ * intra-tree move-via-drag. Scoped to a single `FileManager` instance — all intra-instance
+ * drags share one set of refs, but two separate instances do not interfere.
+ *
+ * Row handlers stop event propagation so the container only sees drags over the empty
+ * (root) area. Counters live on `enter`/`leave` (per the W3C drag-counter pattern); drop
+ * targets are resolved on `over` only via `preventDefault`.
+ */
+export const useFileManagerDnd = ({
+ findNode,
+ onClearSelection,
+ onMoveItems,
+ selectedPaths,
+}: UseFileManagerDndParams): UseFileManagerDndResult => {
+ const isEnabled = !!onMoveItems;
+
+ // Stash via ref so the dragstart handler doesn't re-create on every selection
+ // change (which would invalidate `bindNodeDnd` and re-render every row through
+ // the tree). Synced via effect to keep ESLint happy about render-time mutations.
+ const selectionRef = useRef(selectedPaths);
+
+ useEffect(() => {
+ selectionRef.current = selectedPaths;
+ }, [selectedPaths]);
+
+ const dragSourcesRef = useRef<FileManagerInternalNode[]>([]);
+ const containerCounterRef = useRef(0);
+ const nodeCounterRef = useRef(new Map<string, number>());
+
+ // Drop-target highlighting. `null` = no active drag, otherwise the path of the directory
+ // currently hovered, or `FM_ROOT_DROP_SENTINEL` when the user is over the empty root area.
+ const [dropTargetPath, setDropTargetPath] = useState<null | string>(null);
+ // Paths of every row currently being dragged. Used to ghost rows in the UI so the
+ // user sees that the whole selection is on the move, not just the grabbed row
+ // (whose drag image the browser already shows).
+ const [draggingPaths, setDraggingPaths] = useState<ReadonlySet<string>>(() => new Set());
+
+ const resetDragState = useCallback(() => {
+ dragSourcesRef.current = [];
+ containerCounterRef.current = 0;
+ nodeCounterRef.current.clear();
+ setDropTargetPath(null);
+ setDraggingPaths(new Set());
+ }, []);
+
+ // ── per-node handlers ───────────────────────────────────────────────────────
+
+ const handleNodeDragStart = useCallback(
+ (node: FileManagerInternalNode, event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || node.isGroupRoot) {
+ return;
+ }
+
+ const selection = selectionRef.current;
+ const isPartOfSelection = !!selection && selection.has(node.path);
+
+ // Build the source path list:
+ // - If the dragged row IS part of the selection → drag everything selected
+ // (deduped so a parent dir doesn't ship together with its descendants).
+ // - Otherwise → drag just this row, and clear the previous selection so
+ // the user isn't left with a stale highlight pointing at unrelated items.
+ const sourcePaths = isPartOfSelection && selection ? dedupeOverlappingPaths(selection) : [node.path];
+
+ if (!isPartOfSelection && selection && selection.size > 0) {
+ onClearSelection?.();
+ }
+
+ // Re-resolve through `findNode` so we drag the freshest data — the row's
+ // `node` prop may be stale if the tree was re-rendered mid-drag.
+ const sources: FileManagerInternalNode[] = [];
+
+ for (const path of sourcePaths) {
+ const fresh = findNode(path);
+
+ // Group roots are synthetic headers, never valid sources.
+ if (fresh && !fresh.isGroupRoot) {
+ sources.push(fresh);
+ }
+ }
+
+ if (sources.length === 0) {
+ return;
+ }
+
+ dragSourcesRef.current = sources;
+ event.dataTransfer.effectAllowed = 'move';
+ // Browsers require *some* payload for drag to start; the actual list lives
+ // in the ref. Newline-separate so external listeners can still parse it.
+ event.dataTransfer.setData(FM_DND_MIME, sources.map((source) => source.path).join('\n'));
+
+ // For multi-source drags swap the browser's default drag image (= the
+ // grabbed row only) with a compact "N items" badge — without it the
+ // user can't tell at a glance that the whole selection is on the move.
+ if (sources.length > 1) {
+ const badge = document.createElement('div');
+
+ badge.textContent = `${sources.length} items`;
+ badge.style.cssText = [
+ 'position: fixed',
+ // Render off-screen so we never flash it to the user — `setDragImage`
+ // captures the visual immediately, the element itself is throwaway.
+ 'top: -1000px',
+ 'left: -1000px',
+ 'padding: 6px 12px',
+ 'background: hsl(var(--primary))',
+ 'color: hsl(var(--primary-foreground))',
+ 'border-radius: 6px',
+ 'font: 500 13px system-ui, -apple-system, "Segoe UI", sans-serif',
+ 'white-space: nowrap',
+ 'pointer-events: none',
+ 'box-shadow: 0 4px 12px rgba(0, 0, 0, 0.18)',
+ ].join(';');
+
+ document.body.appendChild(badge);
+ event.dataTransfer.setDragImage(badge, 12, 12);
+ // The browser snapshots the element synchronously into a bitmap, so
+ // it's safe to remove on the next frame.
+ requestAnimationFrame(() => badge.remove());
+ }
+
+ // Mark every dragged source so the rows can ghost themselves. setState
+ // here is safe — React commits the update *after* this handler returns,
+ // so the browser captures the drag image with the original (un-ghosted)
+ // styles before the dim style is applied.
+ setDraggingPaths(new Set(sources.map((source) => source.path)));
+ },
+ [findNode, isEnabled, onClearSelection],
+ );
+
+ const handleNodeDragEnter = useCallback(
+ (node: FileManagerInternalNode, event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || !isFmDragEvent(event)) {
+ return;
+ }
+
+ // Top-level files behave as part of the root drop area — let the event
+ // bubble so the container handler shows the root highlight.
+ if (isRootPassthrough(node)) {
+ return;
+ }
+
+ // Otherwise stop propagation so a drag over a row never bubbles into the
+ // container handler — otherwise the container would treat the row position
+ // as a drop into the empty (root) area and call the move API on release.
+ event.stopPropagation();
+
+ const isValidDirTarget =
+ node.isDir && !node.isGroupRoot && isValidMove(dragSourcesRef.current, node.path);
+
+ if (!isValidDirTarget) {
+ // Cursor is now over a non-droppable row — make sure the previously
+ // shown root highlight (if any) gets cleared. Container `dragleave`
+ // gates clearing on `relatedTarget` to avoid flicker, so the row
+ // handler is responsible for this case.
+ setDropTargetPath((current) => (current === FM_ROOT_DROP_SENTINEL ? null : current));
+
+ return;
+ }
+
+ const counters = nodeCounterRef.current;
+ const next = (counters.get(node.path) ?? 0) + 1;
+ counters.set(node.path, next);
+
+ if (next === 1) {
+ setDropTargetPath(node.path);
+ }
+ },
+ [isEnabled],
+ );
+
+ const handleNodeDragLeave = useCallback(
+ (node: FileManagerInternalNode, event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || !isFmDragEvent(event)) {
+ return;
+ }
+
+ // Mirrors `handleNodeDragEnter`: pass-through rows must let `dragleave`
+ // bubble too, so the container's enter/leave counter stays balanced.
+ if (isRootPassthrough(node)) {
+ return;
+ }
+
+ event.stopPropagation();
+
+ const counters = nodeCounterRef.current;
+ const current = counters.get(node.path) ?? 0;
+
+ if (current <= 1) {
+ counters.delete(node.path);
+ setDropTargetPath((value) => (value === node.path ? null : value));
+ } else {
+ counters.set(node.path, current - 1);
+ }
+ },
+ [isEnabled],
+ );
+
+ const handleNodeDragOver = useCallback(
+ (node: FileManagerInternalNode, event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || !isFmDragEvent(event)) {
+ return;
+ }
+
+ // Pass-through rows defer drop-acceptance to the container (= root drop).
+ if (isRootPassthrough(node)) {
+ return;
+ }
+
+ // Otherwise stop propagation; only `preventDefault` (= "drop allowed") for
+ // valid directory targets. Without the stop, the container would
+ // `preventDefault` on top of us and accept any row position as a root drop.
+ event.stopPropagation();
+
+ if (!node.isDir || node.isGroupRoot) {
+ return;
+ }
+
+ if (!isValidMove(dragSourcesRef.current, node.path)) {
+ return;
+ }
+
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'move';
+ },
+ [isEnabled],
+ );
+
+ const handleNodeDrop = useCallback(
+ (node: FileManagerInternalNode, event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || !isFmDragEvent(event)) {
+ return;
+ }
+
+ // Pass-through rows let the container handle the actual drop (= root move).
+ if (isRootPassthrough(node)) {
+ return;
+ }
+
+ // Otherwise stop propagation so a drop on a row never bubbles to the
+ // container, which would otherwise treat the drop as a root move (the source
+ // bug behind "drag a file, return it back" → unintended API call).
+ event.stopPropagation();
+
+ if (!node.isDir || node.isGroupRoot) {
+ resetDragState();
+
+ return;
+ }
+
+ const sources = dragSourcesRef.current;
+
+ if (!isValidMove(sources, node.path)) {
+ resetDragState();
+
+ return;
+ }
+
+ event.preventDefault();
+ resetDragState();
+ // Selection paths reference the OLD locations, which the move call is
+ // about to invalidate. Clear them so the bulk-actions bar / "select-all"
+ // checkbox don't show stale state.
+ onClearSelection?.();
+ void onMoveItems?.(sources, node.path);
+ },
+ [isEnabled, onClearSelection, onMoveItems, resetDragState],
+ );
+
+ const bindNodeDnd = useCallback(
+ (node: FileManagerInternalNode): FileManagerNodeDndHandlers | null => {
+ if (!isEnabled) {
+ return null;
+ }
+
+ return {
+ isBeingDragged: draggingPaths.has(node.path),
+ isDropTarget: dropTargetPath === node.path,
+ onDragEnd: resetDragState,
+ onDragEnter: (event) => handleNodeDragEnter(node, event),
+ onDragLeave: (event) => handleNodeDragLeave(node, event),
+ onDragOver: (event) => handleNodeDragOver(node, event),
+ onDragStart: (event) => handleNodeDragStart(node, event),
+ onDrop: (event) => handleNodeDrop(node, event),
+ };
+ },
+ [
+ draggingPaths,
+ dropTargetPath,
+ handleNodeDragEnter,
+ handleNodeDragLeave,
+ handleNodeDragOver,
+ handleNodeDragStart,
+ handleNodeDrop,
+ isEnabled,
+ resetDragState,
+ ],
+ );
+
+ // ── container-level handlers (root drop area) ───────────────────────────────
+
+ const handleContainerDragEnter = useCallback(
+ (event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || !isFmDragEvent(event)) {
+ return;
+ }
+
+ containerCounterRef.current += 1;
+
+ if (!isValidMove(dragSourcesRef.current, '')) {
+ return;
+ }
+
+ // Highlight only when the user is *outside* every directory row — otherwise the
+ // node-level handler already owns the highlight and propagation was stopped there.
+ if (containerCounterRef.current === 1) {
+ setDropTargetPath((current) => current ?? FM_ROOT_DROP_SENTINEL);
+ }
+ },
+ [isEnabled],
+ );
+
+ const handleContainerDragLeave = useCallback(
+ (event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || !isFmDragEvent(event)) {
+ return;
+ }
+
+ containerCounterRef.current = Math.max(containerCounterRef.current - 1, 0);
+
+ // Only clear the root highlight when the cursor truly left the container.
+ // `dragleave` also fires when the cursor enters a child element — clearing
+ // there would cause a flicker for pass-through rows (which immediately
+ // re-set the highlight via bubbled `dragenter`/`dragover`).
+ const relatedTarget = event.relatedTarget;
+ const cursorLeftContainer =
+ !(relatedTarget instanceof Node) || !event.currentTarget.contains(relatedTarget);
+
+ if (cursorLeftContainer) {
+ setDropTargetPath((current) => (current === FM_ROOT_DROP_SENTINEL ? null : current));
+ }
+ },
+ [isEnabled],
+ );
+
+ const handleContainerDragOver = useCallback(
+ (event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || !isFmDragEvent(event)) {
+ return;
+ }
+
+ if (!isValidMove(dragSourcesRef.current, '')) {
+ return;
+ }
+
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'move';
+ // `dragover` fires continuously while the cursor is over the container's
+ // direct area (or a pass-through child). It is the moment-of-truth for the
+ // root highlight: relying on the counter pattern alone misses the case
+ // where the cursor is implicitly inside the container at `dragstart`
+ // (no `dragenter` ever fires on the container, so the counter stays at 0
+ // and the highlight never appears until the user leaves and re-enters).
+ setDropTargetPath((current) => current ?? FM_ROOT_DROP_SENTINEL);
+ },
+ [isEnabled],
+ );
+
+ const handleContainerDrop = useCallback(
+ (event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!isEnabled || !isFmDragEvent(event)) {
+ return;
+ }
+
+ const sources = dragSourcesRef.current;
+
+ if (!isValidMove(sources, '')) {
+ resetDragState();
+
+ return;
+ }
+
+ event.preventDefault();
+ resetDragState();
+ // Selection paths are about to be invalidated by the move — clear them so
+ // the bulk bar doesn't display stale "N selected".
+ onClearSelection?.();
+ void onMoveItems?.(sources, '');
+ },
+ [isEnabled, onClearSelection, onMoveItems, resetDragState],
+ );
+
+ return {
+ bindNodeDnd,
+ container: {
+ isRootDropTarget: dropTargetPath === FM_ROOT_DROP_SENTINEL,
+ onDragEnter: handleContainerDragEnter,
+ onDragLeave: handleContainerDragLeave,
+ onDragOver: handleContainerDragOver,
+ onDrop: handleContainerDrop,
+ },
+ isEnabled,
+ };
+};
diff --git a/frontend/src/components/file-manager/use-file-manager-selection.ts b/frontend/src/components/file-manager/use-file-manager-selection.ts
index 5fec7757..9133f64f 100644
--- a/frontend/src/components/file-manager/use-file-manager-selection.ts
+++ b/frontend/src/components/file-manager/use-file-manager-selection.ts
@@ -23,8 +23,8 @@ interface UseFileManagerSelection {
}
interface UseFileManagerSelectionArgs {
- /** Universe of selectable file paths in the *visible* tree. */
- allFilePaths: string[];
+ /** Universe of selectable paths (files + real directories) in the *visible* tree. */
+ allSelectablePaths: string[];
/** Visible nodes in DFS order — used for shift-range selection. */
flatVisible: string[];
}
@@ -36,13 +36,13 @@ interface UseFileManagerSelectionArgs {
* downstream don't re-render needlessly.
*/
export const useFileManagerSelection = ({
- allFilePaths,
+ allSelectablePaths,
flatVisible,
}: UseFileManagerSelectionArgs): UseFileManagerSelection => {
const [rawSelectedPaths, setRawSelectedPaths] = useState<Set<string>>(() => new Set());
const lastClickedRef = useRef<null | string>(null);
- const allFilePathsSet = useMemo(() => new Set(allFilePaths), [allFilePaths]);
+ const allSelectablePathsSet = useMemo(() => new Set(allSelectablePaths), [allSelectablePaths]);
const selectedPaths = useMemo(() => {
if (rawSelectedPaths.size === 0) {
@@ -53,7 +53,7 @@ export const useFileManagerSelection = ({
const valid = new Set<string>();
for (const path of rawSelectedPaths) {
- if (allFilePathsSet.has(path)) {
+ if (allSelectablePathsSet.has(path)) {
valid.add(path);
} else {
allValid = false;
@@ -61,7 +61,7 @@ export const useFileManagerSelection = ({
}
return allValid ? rawSelectedPaths : valid;
- }, [allFilePathsSet, rawSelectedPaths]);
+ }, [allSelectablePathsSet, rawSelectedPaths]);
const onRowClick = useCallback(
(event: ReactMouseEvent, path: string) => {
@@ -131,12 +131,12 @@ export const useFileManagerSelection = ({
});
}, []);
- const isAllSelected = allFilePaths.length > 0 && selectedPaths.size === allFilePaths.length;
+ const isAllSelected = allSelectablePaths.length > 0 && selectedPaths.size === allSelectablePaths.length;
const isSomeSelected = selectedPaths.size > 0 && !isAllSelected;
const toggleSelectAll = useCallback(() => {
- setRawSelectedPaths(() => (isAllSelected ? new Set() : new Set(allFilePaths)));
- }, [allFilePaths, isAllSelected]);
+ setRawSelectedPaths(() => (isAllSelected ? new Set() : new Set(allSelectablePaths)));
+ }, [allSelectablePaths, isAllSelected]);
const clearSelection = useCallback(() => {
setRawSelectedPaths((prev) => (prev.size === 0 ? prev : new Set()));
diff --git a/frontend/src/components/layouts/main-sidebar.tsx b/frontend/src/components/layouts/main-sidebar.tsx
index 4aca03a8..6a764dfe 100644
--- a/frontend/src/components/layouts/main-sidebar.tsx
+++ b/frontend/src/components/layouts/main-sidebar.tsx
@@ -17,7 +17,7 @@ import {
Sun,
UserIcon,
} from 'lucide-react';
-import { type ChangeEvent, useMemo, useRef, useState } from 'react';
+import { useMemo, useState } from 'react';
import { Link, useMatch, useParams } from 'react-router-dom';
import type { Flow } from '@/providers/sidebar-flows-provider';
@@ -49,9 +49,7 @@ import {
} from '@/components/ui/sidebar';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { PasswordChangeForm } from '@/features/authentication/password-change-form';
-import { ACCEPTED_FILE_TYPES } from '@/features/resources/constants';
-import { ResourcesUploadOptionsDialog } from '@/features/resources/resources-upload-options-dialog';
-import { useFileUpload } from '@/features/resources/use-file-upload';
+import { useResourcesUpload } from '@/features/resources/use-resources-upload';
import { useTheme } from '@/hooks/use-theme';
import { useFavorites } from '@/providers/favorites-provider';
import { useSidebarFlows } from '@/providers/sidebar-flows-provider';
@@ -94,7 +92,6 @@ const FlowMenuItem = ({ activeFlowId, flow, isFavorite, onToggleFavorite }: Flow
export const MainSidebar = () => {
const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);
- const resourcesFileInputRef = useRef<HTMLInputElement>(null);
const isDashboardActive = useMatch('/dashboard');
const isFlowsActive = useMatch('/flows/*');
const isTemplatesActive = useMatch('/templates/*');
@@ -108,20 +105,7 @@ export const MainSidebar = () => {
const { addFavoriteFlow, favoriteFlowIds, removeFavoriteFlow } = useFavorites();
const { flows } = useSidebarFlows();
- const {
- handleFileChange: handleResourcesFileChange,
- handleUploadOptionsCancel,
- handleUploadOptionsConfirm,
- isUploadOptionsDialogOpen,
- } = useFileUpload();
-
- const handleResourcesUploadClick = () => {
- resourcesFileInputRef.current?.click();
- };
-
- const handleResourcesFileInputChange = async (event: ChangeEvent<HTMLInputElement>) => {
- await handleResourcesFileChange(event.target.files, resourcesFileInputRef);
- };
+ const resourcesUpload = useResourcesUpload();
const flowId = useMemo(() => (flowIdParam ? Number(flowIdParam) : null), [flowIdParam]);
@@ -231,7 +215,7 @@ export const MainSidebar = () => {
</SidebarMenuButton>
<SidebarMenuAction
className="data-[state=open]:bg-accent rounded-sm"
- onClick={handleResourcesUploadClick}
+ onClick={resourcesUpload.openFilePicker}
showOnHover
title="Upload file"
type="button"
@@ -397,17 +381,11 @@ export const MainSidebar = () => {
<SidebarRail />
<input
- accept={ACCEPTED_FILE_TYPES}
className="hidden"
+ key={resourcesUpload.fileInputKey}
multiple
- onChange={handleResourcesFileInputChange}
- ref={resourcesFileInputRef}
type="file"
- />
- <ResourcesUploadOptionsDialog
- isOpen={isUploadOptionsDialogOpen}
- onCancel={handleUploadOptionsCancel}
- onConfirm={handleUploadOptionsConfirm}
+ {...resourcesUpload.fileInputProps}
/>
<Dialog
diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsx
index 120e2cb8..1cb15689 100644
--- a/frontend/src/components/ui/dropdown-menu.tsx
+++ b/frontend/src/components/ui/dropdown-menu.tsx
@@ -153,7 +153,7 @@ const DropdownMenuSeparator = React.forwardRef<
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
- className={cn('bg-muted -mx-1 my-1 h-px', className)}
+ className={cn('bg-border -mx-1 my-1 h-px', className)}
ref={ref}
{...props}
/>
diff --git a/frontend/src/components/ui/file-drop-zone.tsx b/frontend/src/components/ui/file-drop-zone.tsx
new file mode 100644
index 00000000..bbd3b41c
--- /dev/null
+++ b/frontend/src/components/ui/file-drop-zone.tsx
@@ -0,0 +1,70 @@
+import { UploadCloudIcon } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+
+export interface FileDropZoneProps {
+ /** Label of the call-to-action button. */
+ actionLabel?: string;
+ className?: string;
+ /** Sub-text shown under the title. */
+ description?: string;
+ /** Tiny extra hint rendered at the bottom (e.g. limits). */
+ hint?: string;
+ /** Highlight state — pass the `isDragging` flag from `useFilesDragAndDrop`. */
+ isDragging?: boolean;
+ /** Disables the action while an upload is already in flight. */
+ isUploading?: boolean;
+ /** Called when the user clicks the action button. */
+ onBrowse: () => void;
+ /** Heading of the drop zone. */
+ title?: string;
+}
+
+/**
+ * Stateless drop zone surface. The component itself doesn't bind any drag/drop
+ * handlers — the parent attaches them on the actual drop container via
+ * `useFilesDragAndDrop` and forwards the `isDragging` flag here for visual feedback.
+ *
+ * The button uses `onBrowse` to open the file picker (typically wired to
+ * `useResourcesUpload().openFilePicker`).
+ */
+export const FileDropZone = ({
+ actionLabel = 'Browse files',
+ className,
+ description = 'or click the button to choose files from your computer',
+ hint,
+ isDragging = false,
+ isUploading = false,
+ onBrowse,
+ title = 'Drag and drop your files',
+}: FileDropZoneProps) => (
+ <div
+ className={cn(
+ 'bg-card flex flex-col items-center justify-center rounded-md border-2 border-dashed px-6 py-12 text-center transition-all duration-200',
+ isDragging
+ ? 'border-foreground bg-muted/50'
+ : 'border-muted-foreground/25 hover:border-muted-foreground/40',
+ className,
+ )}
+ >
+ <UploadCloudIcon
+ className={cn(
+ 'text-muted-foreground mb-3 size-10 transition-transform duration-200',
+ isDragging && 'text-foreground scale-110',
+ )}
+ />
+ <span className="text-sm font-medium">{isDragging ? 'Drop files here' : title}</span>
+ <span className="text-muted-foreground mt-1 max-w-md text-xs">{description}</span>
+ <Button
+ className="mt-4 h-7 text-xs"
+ disabled={isUploading}
+ onClick={onBrowse}
+ size="sm"
+ variant="outline"
+ >
+ {actionLabel}
+ </Button>
+ {hint && <span className="text-muted-foreground mt-3 text-xs">{hint}</span>}
+ </div>
+);
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.tsx
new file mode 100644
index 00000000..66bb4482
--- /dev/null
+++ b/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
@@ -0,0 +1,241 @@
+import { FolderInput, Loader2, Search, X } from 'lucide-react';
+import { useCallback, useMemo, useState } from 'react';
+
+import { dedupeOverlappingPaths, FileManager, type FileNode } from '@/components/file-manager';
+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 { useFlowFilesAttachResources } from './use-flow-files-attach-resources';
+
+interface FlowFilesAttachResourcesDialogProps {
+ flowId: null | string;
+ isOpen: boolean;
+ onClose: () => void;
+ onSuccess: () => void;
+}
+
+const EMPTY_SELECTION: ReadonlySet<string> = new Set();
+
+const FlowFilesAttachResourcesDialogBody = ({
+ flowId,
+ onClose,
+ onSuccess,
+}: Omit<FlowFilesAttachResourcesDialogProps, 'isOpen'>) => {
+ const { error: resourcesError, isInitialLoading: isResourcesLoading, resources } = useResources();
+ const { attach, isAttaching } = useFlowFilesAttachResources({
+ flowId,
+ onSuccess: () => {
+ onSuccess();
+ onClose();
+ },
+ });
+
+ 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.
+ const pathToIdRef = useMemo(() => {
+ const map = new Map<string, string>();
+
+ for (const resource of resources) {
+ map.set(resource.path, resource.id);
+ }
+
+ return map;
+ }, [resources]);
+
+ const handleSelectionChange = useCallback((next: Set<string>) => {
+ setSelectedPaths(next);
+ }, []);
+
+ const handleAttach = useCallback(async () => {
+ if (selectedPaths.size === 0) {
+ return;
+ }
+
+ // Drop descendants of any picked directory so the backend doesn't
+ // re-process them — a recursive copy of the parent already covers them.
+ const ids: string[] = [];
+
+ for (const path of dedupeOverlappingPaths(selectedPaths)) {
+ const id = pathToIdRef.get(path);
+
+ if (id) {
+ ids.push(id);
+ }
+ }
+
+ if (ids.length === 0) {
+ return;
+ }
+
+ await attach({ ids, shouldOverwrite });
+ }, [attach, pathToIdRef, selectedPaths, shouldOverwrite]);
+
+ const selectedCount = selectedPaths.size;
+ const hasResources = resources.length > 0;
+ const isAttachDisabled = isAttaching || selectedCount === 0;
+
+ const emptyState = (
+ <Empty className="border-0">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <FolderInput />
+ </EmptyMedia>
+ <EmptyTitle>Resource library is empty</EmptyTitle>
+ <EmptyDescription>Upload resources first to attach them to a flow.</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+
+ const noMatchesState = (
+ <Empty className="border-0">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Search />
+ </EmptyMedia>
+ <EmptyTitle>No matches</EmptyTitle>
+ <EmptyDescription>
+ No resources match <code>{searchQuery.trim()}</code>.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+
+ 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>
+ </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 }}
+ />
+ )}
+
+ <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>
+ );
+};
+
+export const FlowFilesAttachResourcesDialog = ({
+ flowId,
+ isOpen,
+ onClose,
+ onSuccess,
+}: FlowFilesAttachResourcesDialogProps) => {
+ const handleDialogOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ onClose();
+ }
+ };
+
+ return (
+ <Dialog
+ onOpenChange={handleDialogOpenChange}
+ open={isOpen}
+ >
+ {isOpen && (
+ <FlowFilesAttachResourcesDialogBody
+ flowId={flowId}
+ onClose={onClose}
+ onSuccess={onSuccess}
+ />
+ )}
+ </Dialog>
+ );
+};
+
+export type { FlowFilesAttachResourcesDialogProps };
diff --git a/frontend/src/features/flows/files/flow-files-constants.ts b/frontend/src/features/flows/files/flow-files-constants.ts
index 25e693e1..03da26b0 100644
--- a/frontend/src/features/flows/files/flow-files-constants.ts
+++ b/frontend/src/features/flows/files/flow-files-constants.ts
@@ -16,6 +16,10 @@ 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_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/';
export const UPLOADS_TARGET_DIRECTORY = '/work/uploads';
export const CONTAINER_TARGET_DIRECTORY = 'container/';
+export const RESOURCES_TARGET_DIRECTORY = '/work/resources';
diff --git a/frontend/src/features/flows/files/flow-files-promote-dialog.tsx b/frontend/src/features/flows/files/flow-files-promote-dialog.tsx
new file mode 100644
index 00000000..f8a0bed9
--- /dev/null
+++ b/frontend/src/features/flows/files/flow-files-promote-dialog.tsx
@@ -0,0 +1,172 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { BookmarkPlus, Loader2 } from 'lucide-react';
+import { useEffect } from 'react';
+import { useForm } from 'react-hook-form';
+
+import type { FileNode } from '@/components/file-manager';
+
+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 { stripFlowRootPrefix } from './flow-files-utils';
+import {
+ flowFilesPromoteFormSchema,
+ type FlowFilesPromoteFormValues,
+ useFlowFilesPromote,
+} from './use-flow-files-promote';
+
+interface FlowFilesPromoteDialogFormProps {
+ file: FileNode;
+ flowId: null | string;
+ onClose: () => void;
+}
+
+interface FlowFilesPromoteDialogProps {
+ file: FileNode | null;
+ flowId: null | string;
+ onClose: () => void;
+}
+
+const buildDefaultDestination = (file: FileNode) => stripFlowRootPrefix(file.path) || file.name;
+
+const FlowFilesPromoteDialogForm = ({ file, flowId, onClose }: FlowFilesPromoteDialogFormProps) => {
+ const { isPromoting, promote } = useFlowFilesPromote({ flowId });
+
+ const form = useForm<FlowFilesPromoteFormValues>({
+ defaultValues: {
+ destination: buildDefaultDestination(file),
+ shouldOverwrite: false,
+ },
+ mode: 'onChange',
+ resolver: zodResolver(flowFilesPromoteFormSchema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ destination: buildDefaultDestination(file),
+ shouldOverwrite: false,
+ });
+ }, [file, form]);
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const wasPromoted = await promote(file.path, values);
+
+ if (wasPromoted) {
+ onClose();
+ }
+ });
+
+ const isSubmitDisabled = !form.formState.isValid || isPromoting;
+
+ return (
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <BookmarkPlus className="size-4" />
+ Save as resource
+ </DialogTitle>
+ <DialogDescription>
+ Promote <code>{file.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>Destination path</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ autoComplete="off"
+ autoFocus
+ disabled={isPromoting}
+ placeholder="results/scan.txt"
+ />
+ </FormControl>
+ <FormDescription>
+ 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">
+ 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>
+ )}
+ />
+
+ <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>
+ );
+};
+
+export const FlowFilesPromoteDialog = ({ file, flowId, onClose }: FlowFilesPromoteDialogProps) => {
+ const handleDialogOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ onClose();
+ }
+ };
+
+ return (
+ <Dialog
+ onOpenChange={handleDialogOpenChange}
+ open={!!file}
+ >
+ {file && (
+ <FlowFilesPromoteDialogForm
+ file={file}
+ flowId={flowId}
+ onClose={onClose}
+ />
+ )}
+ </Dialog>
+ );
+};
diff --git a/frontend/src/features/flows/files/flow-files-utils.ts b/frontend/src/features/flows/files/flow-files-utils.ts
index 0681e70b..d493976d 100644
--- a/frontend/src/features/flows/files/flow-files-utils.ts
+++ b/frontend/src/features/flows/files/flow-files-utils.ts
@@ -3,6 +3,8 @@ import type { FlowFileFragmentFragment } from '@/graphql/types';
import { baseUrl } from '@/models/api';
+import { CONTAINER_PATH_PREFIX, RESOURCES_PATH_PREFIX, UPLOADS_PATH_PREFIX } from './flow-files-constants';
+
export type FlowFile = FlowFileFragmentFragment;
export interface FlowFilesResponse {
@@ -10,6 +12,35 @@ export interface FlowFilesResponse {
total: number;
}
+/** Mirrors `models.ResourceEntry` from the backend (REST shape, not GraphQL). */
+export interface ResourceEntry {
+ createdAt: string;
+ id: number;
+ isDir: boolean;
+ name: string;
+ path: string;
+ size: number;
+ updatedAt: string;
+ userId: number;
+}
+
+const ROOT_PREFIXES = [`${UPLOADS_PATH_PREFIX}/`, `${CONTAINER_PATH_PREFIX}/`, `${RESOURCES_PATH_PREFIX}/`];
+
+/**
+ * Strips the synthetic root group prefix (`uploads/`, `container/`, `resources/`)
+ * from a flow-file path so callers can suggest a sensible default `destination`
+ * when promoting the file into the user's global resource library.
+ */
+export const stripFlowRootPrefix = (path: string): string => {
+ for (const prefix of ROOT_PREFIXES) {
+ if (path.startsWith(prefix)) {
+ return path.slice(prefix.length);
+ }
+ }
+
+ return path;
+};
+
/**
* 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
diff --git a/frontend/src/features/flows/files/flow-files.tsx b/frontend/src/features/flows/files/flow-files.tsx
index 29eb7cd9..1b5b2310 100644
--- a/frontend/src/features/flows/files/flow-files.tsx
+++ b/frontend/src/features/flows/files/flow-files.tsx
@@ -1,4 +1,4 @@
-import { ArrowDownToLine, FolderUp, Info, Loader2, Search, X } from 'lucide-react';
+import { ArrowDownToLine, FolderInput, FolderOutput, FolderUp, Info, Loader2, Search, X } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { toast } from 'sonner';
@@ -17,31 +17,26 @@ import { Form, FormControl, FormField, FormItem } from '@/components/ui/form';
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { StatusType } from '@/graphql/types';
+import { useFilesDragAndDrop } from '@/hooks/use-files-drag-and-drop';
import { copyToClipboard } from '@/lib/report';
import { useFlow } from '@/providers/flow-provider';
+import { FlowFilesAttachResourcesDialog } from './flow-files-attach-resources-dialog';
import { ROOT_GROUPS } from './flow-files-constants';
+import { FlowFilesPromoteDialog } from './flow-files-promote-dialog';
import { FlowFilesPullDialog } from './flow-files-pull-dialog';
import { buildDownloadHref } from './flow-files-utils';
-import { useFilesDragAndDrop } from './use-files-drag-and-drop';
import { useFlowFilesData } from './use-flow-files-data';
import { useFlowFilesDelete } from './use-flow-files-delete';
import { useFlowFilesRealtime } from './use-flow-files-realtime';
import { useFlowFilesSearch } from './use-flow-files-search';
import { useFlowFilesUpload } from './use-flow-files-upload';
-interface FlowFilesContentProps {
- flowId: null | string;
- flowStatus: StatusType | undefined;
-}
-
-/**
- * Holds every piece of local state for a single flow. The outer `<FlowFiles />`
- * remounts this component via `key={flowId}` so switching flows is a fresh mount
- * with no leftover form values, drag overlays or pending toasts.
- */
-const FlowFilesContent = ({ flowId, flowStatus }: FlowFilesContentProps) => {
+const FlowFiles = () => {
+ const { flowId, flowStatus } = useFlow();
const [isPullDialogOpen, setIsPullDialogOpen] = useState(false);
+ const [isAttachResourcesDialogOpen, setIsAttachResourcesDialogOpen] = useState(false);
+ const [fileToPromote, setFileToPromote] = useState<FileNode | null>(null);
const { fileNodes, isInitialLoading, isLoading, refetchFiles } = useFlowFilesData({ flowId });
@@ -72,18 +67,39 @@ const FlowFilesContent = ({ flowId, flowStatus }: FlowFilesContentProps) => {
toast.error('Failed to copy path');
}, []);
- const getDownloadHref = useCallback(
- (file: FileNode): string => buildDownloadHref(flowId, file) ?? '',
- [flowId],
+ const getDownloadHref = useCallback((file: FileNode): string => buildDownloadHref(flowId, file) ?? '', [flowId]);
+
+ const handleRequestPromote = useCallback((file: FileNode) => {
+ setFileToPromote(file);
+ }, []);
+
+ const handleClosePromoteDialog = useCallback(() => setFileToPromote(null), []);
+
+ const promoteAction = useMemo<FileManagerAction>(
+ () => ({
+ appliesToDirs: true,
+ icon: FolderOutput,
+ id: 'flow-files-save-as-resource',
+ label: 'Save as resource',
+ onSelect: handleRequestPromote,
+ }),
+ [handleRequestPromote],
);
const fileManagerActions = useMemo<FileManagerAction[]>(
- () => [downloadAction(getDownloadHref), copyPathAction(handleCopyPath), deleteAction(deletion.requestDelete)],
- [getDownloadHref, handleCopyPath, deletion.requestDelete],
+ () => [
+ downloadAction(getDownloadHref),
+ copyPathAction(handleCopyPath),
+ promoteAction,
+ deleteAction(deletion.requestDelete),
+ ],
+ [getDownloadHref, handleCopyPath, promoteAction, deletion.requestDelete],
);
const handleOpenPullDialog = useCallback(() => setIsPullDialogOpen(true), []);
const handleClosePullDialog = useCallback(() => setIsPullDialogOpen(false), []);
+ const handleOpenAttachResourcesDialog = useCallback(() => setIsAttachResourcesDialogOpen(true), []);
+ const handleCloseAttachResourcesDialog = useCallback(() => setIsAttachResourcesDialogOpen(false), []);
const handleDeleteDialogOpenChange = useCallback(
(nextOpen: boolean) => {
if (!nextOpen) {
@@ -93,6 +109,8 @@ const FlowFilesContent = ({ flowId, flowStatus }: FlowFilesContentProps) => {
[deletion],
);
+ const isAttachResourcesDisabled = !flowId || isLoading || upload.isUploading;
+
const noFilesState = (
<Empty>
<EmptyHeader>
@@ -218,6 +236,23 @@ const FlowFilesContent = ({ flowId, flowStatus }: FlowFilesContentProps) => {
<TooltipContent>Upload files</TooltipContent>
</Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ disabled={isAttachResourcesDisabled}
+ onClick={handleOpenAttachResourcesDialog}
+ size="icon-sm"
+ type="button"
+ variant="outline"
+ >
+ <FolderInput />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Attach resources from library</TooltipContent>
+ </Tooltip>
+
<Tooltip>
<TooltipTrigger asChild>
<span>
@@ -260,6 +295,19 @@ const FlowFilesContent = ({ flowId, flowStatus }: FlowFilesContentProps) => {
onSuccess={refetchFiles}
/>
+ <FlowFilesAttachResourcesDialog
+ flowId={flowId}
+ isOpen={isAttachResourcesDialogOpen}
+ onClose={handleCloseAttachResourcesDialog}
+ onSuccess={refetchFiles}
+ />
+
+ <FlowFilesPromoteDialog
+ file={fileToPromote}
+ flowId={flowId}
+ onClose={handleClosePromoteDialog}
+ />
+
<ConfirmationDialog
confirmText="Delete"
handleConfirm={deletion.confirmDelete}
@@ -273,16 +321,4 @@ const FlowFilesContent = ({ flowId, flowStatus }: FlowFilesContentProps) => {
);
};
-const FlowFiles = () => {
- const { flowId, flowStatus } = useFlow();
-
- return (
- <FlowFilesContent
- flowId={flowId}
- flowStatus={flowStatus}
- key={flowId ?? 'no-flow'}
- />
- );
-};
-
export default FlowFiles;
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.ts
new file mode 100644
index 00000000..fa2993eb
--- /dev/null
+++ b/frontend/src/features/flows/files/use-flow-files-attach-resources.ts
@@ -0,0 +1,86 @@
+import { useCallback, useState } from 'react';
+import { toast } from 'sonner';
+
+import { api, getApiErrorMessage } from '@/lib/axios';
+
+import type { FlowFilesResponse } from './flow-files-utils';
+
+import { FLOW_FILES_ATTACH_RESOURCES_API_PATH, RESOURCES_TARGET_DIRECTORY } from './flow-files-constants';
+
+interface AttachOptions {
+ ids: string[];
+ shouldOverwrite: boolean;
+}
+
+interface AttachResourcesRequestBody {
+ force: boolean;
+ ids: string[];
+}
+
+interface UseFlowFilesAttachResourcesParams {
+ flowId: null | string;
+ onSuccess?: () => void;
+}
+
+interface UseFlowFilesAttachResourcesResult {
+ attach: (options: AttachOptions) => Promise<boolean>;
+ 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.
+ */
+export const useFlowFilesAttachResources = ({
+ flowId,
+ onSuccess,
+}: UseFlowFilesAttachResourcesParams): UseFlowFilesAttachResourcesResult => {
+ const [isAttaching, setIsAttaching] = useState(false);
+
+ const attach = useCallback(
+ async ({ ids, shouldOverwrite }: AttachOptions): Promise<boolean> => {
+ if (!flowId || ids.length === 0) {
+ return false;
+ }
+
+ setIsAttaching(true);
+
+ try {
+ await api.post<FlowFilesResponse, AttachResourcesRequestBody>(
+ FLOW_FILES_ATTACH_RESOURCES_API_PATH(flowId),
+ {
+ force: shouldOverwrite,
+ ids,
+ },
+ { timeout: 0 },
+ );
+
+ toast.success('Resources attached', {
+ description: `Copied ${ids.length} ${ids.length === 1 ? 'item' : 'items'} to ${RESOURCES_TARGET_DIRECTORY}`,
+ });
+ onSuccess?.();
+
+ return true;
+ } catch (error) {
+ const description = getApiErrorMessage(error, 'Failed to attach resources', {
+ 409: ATTACH_OVERWRITE_HINT,
+ });
+
+ toast.error('Attach failed', { description });
+
+ return false;
+ } finally {
+ setIsAttaching(false);
+ }
+ },
+ [flowId, onSuccess],
+ );
+
+ return {
+ attach,
+ isAttaching,
+ };
+};
diff --git a/frontend/src/features/flows/files/use-flow-files-delete.ts b/frontend/src/features/flows/files/use-flow-files-delete.ts
index 862a4473..ef0e0b5b 100644
--- a/frontend/src/features/flows/files/use-flow-files-delete.ts
+++ b/frontend/src/features/flows/files/use-flow-files-delete.ts
@@ -83,9 +83,7 @@ export const useFlowFilesDelete = ({ flowId, refetchFiles }: UseFlowFilesDeleteP
return;
}
- const results = await Promise.allSettled(
- filesToDelete.map((file) => deleteFileRequest(flowId, file.path)),
- );
+ 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;
diff --git a/frontend/src/features/flows/files/use-flow-files-promote.ts b/frontend/src/features/flows/files/use-flow-files-promote.ts
new file mode 100644
index 00000000..6c7b7d0f
--- /dev/null
+++ b/frontend/src/features/flows/files/use-flow-files-promote.ts
@@ -0,0 +1,96 @@
+import { useCallback, useState } from 'react';
+import { toast } from 'sonner';
+import { z } from 'zod';
+
+import { api, getApiErrorMessage } from '@/lib/axios';
+
+import type { ResourceEntry } from './flow-files-utils';
+
+import { FLOW_FILES_PROMOTE_API_PATH } from './flow-files-constants';
+
+export const flowFilesPromoteFormSchema = z.object({
+ destination: z
+ .string()
+ .trim()
+ .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>;
+
+interface PromoteRequestBody {
+ destination: string;
+ force: boolean;
+ sourcePath: string;
+}
+
+interface UseFlowFilesPromoteParams {
+ flowId: null | string;
+ onSuccess?: (entry: ResourceEntry) => void;
+}
+
+interface UseFlowFilesPromoteResult {
+ isPromoting: boolean;
+ promote: (sourcePath: string, values: FlowFilesPromoteFormValues) => Promise<boolean>;
+}
+
+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(sourcePath, values)`
+ * callback that resolves to `true` on success so the dialog can decide whether to close.
+ */
+export const useFlowFilesPromote = ({ flowId, onSuccess }: UseFlowFilesPromoteParams): UseFlowFilesPromoteResult => {
+ const [isPromoting, setIsPromoting] = useState(false);
+
+ const promote = useCallback(
+ async (sourcePath: string, { destination, shouldOverwrite }: FlowFilesPromoteFormValues): Promise<boolean> => {
+ if (!flowId) {
+ return false;
+ }
+
+ setIsPromoting(true);
+
+ try {
+ const response = await api.post<ResourceEntry, PromoteRequestBody>(
+ FLOW_FILES_PROMOTE_API_PATH(flowId),
+ {
+ destination: destination.trim(),
+ force: shouldOverwrite,
+ sourcePath,
+ },
+ { timeout: 0 },
+ );
+
+ toast.success('Saved to resources', {
+ description: `Stored at ${destination.trim()} in your resource library`,
+ });
+
+ if (response.status === 'success' && response.data) {
+ onSuccess?.(response.data);
+ }
+
+ return true;
+ } catch (error) {
+ const description = getApiErrorMessage(error, 'Failed to save resource', {
+ 409: PROMOTE_OVERWRITE_HINT,
+ });
+
+ toast.error('Save as resource failed', { description });
+
+ return false;
+ } finally {
+ setIsPromoting(false);
+ }
+ },
+ [flowId, onSuccess],
+ );
+
+ return {
+ isPromoting,
+ promote,
+ };
+};
diff --git a/frontend/src/features/flows/flow-form.tsx b/frontend/src/features/flows/flow-form.tsx
index ad5b6777..11559e31 100644
--- a/frontend/src/features/flows/flow-form.tsx
+++ b/frontend/src/features/flows/flow-form.tsx
@@ -1,11 +1,23 @@
import { zodResolver } from '@hookform/resolvers/zod';
-import { ArrowUp, Check, ChevronDown, FileSymlink, FileText, Loader2, Paperclip, Plus, Square, X } from 'lucide-react';
+import {
+ ArrowUp,
+ Check,
+ ChevronDown,
+ FileSymlink,
+ FileText,
+ Folder,
+ Loader2,
+ Paperclip,
+ Plus,
+ Square,
+ X,
+} from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRef } from 'react';
-import { useForm } from 'react-hook-form';
+import { useForm, useWatch } from 'react-hook-form';
import { z } from 'zod';
-import type { ResourceItem } from '@/features/resources/types';
+import type { UserResourceFragmentFragment } from '@/graphql/types';
import { ProviderIcon } from '@/components/icons/provider-icon';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
@@ -28,9 +40,7 @@ import {
import { Spinner } from '@/components/ui/spinner';
import { Switch } from '@/components/ui/switch';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
-import { ACCEPTED_FILE_TYPES } from '@/features/resources/constants';
-import { ResourcesUploadOptionsDialog } from '@/features/resources/resources-upload-options-dialog';
-import { useFileUpload } from '@/features/resources/use-file-upload';
+import { useResourcesUpload } from '@/features/resources/use-resources-upload';
import { getProviderDisplayName } from '@/models/provider';
import { useProviders } from '@/providers/providers-provider';
import { useResources } from '@/providers/resources-provider';
@@ -39,6 +49,7 @@ import { type Template, useTemplates } from '@/providers/templates-provider';
const formSchema = z.object({
message: z.string().trim().min(1, { message: 'Message cannot be empty' }),
providerName: z.string().trim().min(1, { message: 'Provider must be selected' }),
+ resourceIds: z.array(z.string()),
useAgents: z.boolean(),
});
@@ -77,42 +88,25 @@ export const FlowForm = ({
const [providerSearch, setProviderSearch] = useState('');
const [templateSearch, setTemplateSearch] = useState('');
const [resourceSearch, setResourceSearch] = useState('');
- const [attachedFileIds, setAttachedFileIds] = useState<string[]>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
- const handleResourceAttach = useCallback((resource: ResourceItem) => {
- setAttachedFileIds((current) => (current.includes(resource.id) ? current : [...current, resource.id]));
- }, []);
-
- const { handleFileChange, handleUploadOptionsCancel, handleUploadOptionsConfirm, isUploadOptionsDialogOpen } =
- useFileUpload({ onResourceAttach: handleResourceAttach });
-
- const attachedFiles = useMemo<ResourceItem[]>(() => {
- const byId = new Map(resources.map((item) => [item.id, item]));
-
- return attachedFileIds.map((id) => byId.get(id)).filter((item): item is ResourceItem => Boolean(item));
- }, [attachedFileIds, resources]);
-
- const isAnyAttachmentUploading = attachedFiles.some((file) => !file.isUploaded);
-
const sortedResources = useMemo(
- () => [...resources].sort((a, b) => new Date(b.uploadedAt).getTime() - new Date(a.uploadedAt).getTime()),
+ () => [...resources].sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()),
[resources],
);
const filteredResources = useMemo(() => {
- const search = resourceSearch.trim().toLowerCase();
+ const queryValue = resourceSearch.trim().toLowerCase();
- if (!search) {
+ if (!queryValue) {
return sortedResources;
}
- return sortedResources.filter((resource) => {
- const fullName = resource.format ? `${resource.name}.${resource.format}` : resource.name;
-
- return fullName.toLowerCase().includes(search);
- });
+ return sortedResources.filter(
+ (resource) =>
+ resource.name.toLowerCase().includes(queryValue) || resource.path.toLowerCase().includes(queryValue),
+ );
}, [sortedResources, resourceSearch]);
const filteredTemplates = useMemo(() => {
@@ -146,6 +140,7 @@ export const FlowForm = ({
defaultValues: {
message: defaultValues?.message ?? '',
providerName: defaultValues?.providerName ?? '',
+ resourceIds: defaultValues?.resourceIds ?? [],
useAgents: defaultValues?.useAgents ?? false,
},
mode: 'onChange',
@@ -161,6 +156,47 @@ export const FlowForm = ({
setValue,
} = form;
+ const resourceIds = useWatch({ control, name: 'resourceIds' });
+
+ const updateResourceIds = useCallback(
+ (updater: ((current: string[]) => string[]) | string[]) => {
+ const current = getValues('resourceIds') ?? [];
+ const raw = typeof updater === 'function' ? updater(current) : updater;
+ // TODO(backend): drop the `String(id)` coercion once the REST `/resources/`
+ // endpoints return `id` as a string (matching the GraphQL `ID` scalar). Until
+ // then this is a safety net for stray numeric ids that would fail zod's
+ // `z.array(z.string())` and silently block submission.
+ const next = raw.map((id) => String(id));
+ setValue('resourceIds', next, { shouldDirty: true, shouldValidate: true });
+ },
+ [getValues, setValue],
+ );
+
+ const flowResources = useMemo<UserResourceFragmentFragment[]>(() => {
+ const byId = new Map(resources.map((item) => [item.id, item]));
+
+ return resourceIds
+ .map((id) => byId.get(id))
+ .filter((item): item is UserResourceFragmentFragment => Boolean(item));
+ }, [resourceIds, resources]);
+
+ const upload = useResourcesUpload({
+ onSuccess: (uploaded) => {
+ const ids = uploaded.items.map((item) => item.id);
+
+ if (ids.length === 0) {
+ return;
+ }
+
+ updateResourceIds((current) => {
+ const merged = new Set(current);
+ ids.forEach((id) => merged.add(id));
+
+ return Array.from(merged);
+ });
+ },
+ });
+
// Update form values from defaultValues if user hasn't manually changed them
useEffect(() => {
if (!defaultValues) {
@@ -169,16 +205,27 @@ export const FlowForm = ({
const currentValues = getValues();
- // Update only fields that user hasn't manually changed and that differ from current values
+ // Update only fields that user hasn't manually changed and that differ from current values.
+ // Arrays are compared shallowly so a new-but-identical `resourceIds` reference doesn't
+ // trigger an unnecessary setValue (and the re-render it causes).
Object.entries(defaultValues)
.filter(([fieldName, defaultValue]) => {
const typedFieldName = fieldName as keyof FlowFormValues;
- return (
- defaultValue !== undefined &&
- !dirtyFields[typedFieldName] &&
- currentValues[typedFieldName] !== defaultValue
- );
+ if (defaultValue === undefined || dirtyFields[typedFieldName]) {
+ return false;
+ }
+
+ const currentValue = currentValues[typedFieldName];
+
+ if (Array.isArray(defaultValue) && Array.isArray(currentValue)) {
+ return (
+ currentValue.length !== defaultValue.length ||
+ currentValue.some((item, index) => item !== defaultValue[index])
+ );
+ }
+
+ return currentValue !== defaultValue;
})
.forEach(([fieldName, defaultValue]) => {
const typedFieldName = fieldName as keyof FlowFormValues;
@@ -192,10 +239,10 @@ export const FlowForm = ({
const previousFormDisabledRef = useRef(isFormDisabled);
useEffect(() => {
- const isDisabled = previousFormDisabledRef.current;
+ const wasDisabled = previousFormDisabledRef.current;
previousFormDisabledRef.current = isFormDisabled;
- if (isDisabled && !isFormDisabled) {
+ if (wasDisabled && !isFormDisabled) {
textareaRef.current?.focus();
}
}, [isFormDisabled]);
@@ -203,23 +250,35 @@ export const FlowForm = ({
const handleSubmit = async (values: FlowFormValues) => {
await onSubmit(values);
resetField('message');
- setAttachedFileIds([]);
+ resetField('resourceIds');
};
const handleAttachClick = () => {
fileInputRef.current?.click();
};
- const handleFileInputChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
- await handleFileChange(event.target.files, fileInputRef);
- };
+ const handleFileInputChange = useCallback(
+ async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const selectedFiles = Array.from(event.target.files ?? []);
+
+ // Reset native input so re-uploading the same file fires `change` again.
+ event.target.value = '';
+
+ if (selectedFiles.length === 0) {
+ return;
+ }
+
+ await upload.uploadFiles(selectedFiles);
+ },
+ [upload],
+ );
const handleRemoveAttachment = (id: string) => {
- setAttachedFileIds((current) => current.filter((fileId) => fileId !== id));
+ updateResourceIds((current) => current.filter((fileId) => fileId !== id));
};
const handleToggleAttachment = (id: string) => {
- setAttachedFileIds((current) =>
+ updateResourceIds((current) =>
current.includes(id) ? current.filter((fileId) => fileId !== id) : [...current, id],
);
};
@@ -267,38 +326,29 @@ export const FlowForm = ({
render={({ field }) => (
<FormControl>
<InputGroup className="block">
- {attachedFiles.length > 0 && (
+ {flowResources.length > 0 && (
<InputGroupAddon
align="block-start"
className="flex-wrap gap-1.5"
>
- {attachedFiles.map((file) => {
- const fullName = file.format ? `${file.name}.${file.format}` : file.name;
+ {flowResources.map((resource) => {
+ const Icon = resource.isDir ? Folder : FileText;
return (
<div
className="bg-muted/50 flex max-w-full items-center gap-1.5 rounded-md border px-2 py-1 text-xs"
- key={file.id}
- title={fullName}
+ key={resource.id}
+ title={resource.path}
>
- {file.isUploaded ? (
- <FileText className="text-muted-foreground size-3.5 shrink-0" />
- ) : (
- <Loader2 className="text-muted-foreground size-3.5 shrink-0 animate-spin" />
- )}
+ <Icon className="text-muted-foreground size-3.5 shrink-0" />
<span className="text-foreground max-w-40 truncate">
- {fullName}
+ {resource.name}
</span>
- {!file.isUploaded && (
- <span className="text-muted-foreground tabular-nums">
- {file.progress}%
- </span>
- )}
<button
- aria-label={`Remove ${fullName}`}
+ aria-label={`Remove ${resource.name}`}
className="text-muted-foreground hover:text-destructive ml-0.5 flex shrink-0 items-center justify-center"
disabled={isFormDisabled}
- onClick={() => handleRemoveAttachment(file.id)}
+ onClick={() => handleRemoveAttachment(resource.id)}
type="button"
>
<X className="size-3.5" />
@@ -544,9 +594,9 @@ export const FlowForm = ({
variant="ghost"
>
<Paperclip className="shrink-0" />
- {attachedFiles.length > 0 && (
+ {flowResources.length > 0 && (
<span className="bg-muted text-muted-foreground -mx-0.5 flex h-4 min-w-4 items-center justify-center rounded px-1 text-xs font-medium tabular-nums">
- {attachedFiles.length}
+ {flowResources.length}
</span>
)}
<ChevronDown />
@@ -590,10 +640,8 @@ export const FlowForm = ({
</DropdownMenuItem>
) : (
filteredResources.map((resource) => {
- const isSelected = attachedFileIds.includes(resource.id);
- const fullName = resource.format
- ? `${resource.name}.${resource.format}`
- : resource.name;
+ const isSelected = resourceIds.includes(resource.id);
+ const Icon = resource.isDir ? Folder : FileText;
return (
<DropdownMenuItem
@@ -609,19 +657,17 @@ export const FlowForm = ({
}}
>
<div className="flex w-full min-w-0 items-center gap-2">
- {resource.isUploaded ? (
- <FileText className="text-muted-foreground size-4 shrink-0" />
- ) : (
- <Loader2 className="text-muted-foreground size-4 shrink-0 animate-spin" />
- )}
- <span className="max-w-80 flex-1 truncate">
- {fullName}
- </span>
- {!resource.isUploaded && (
- <span className="text-muted-foreground text-xs tabular-nums">
- {resource.progress}%
+ <Icon className="text-muted-foreground size-4 shrink-0" />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate">
+ {resource.name}
</span>
- )}
+ {resource.path !== resource.name && (
+ <span className="text-muted-foreground truncate text-xs">
+ {resource.path}
+ </span>
+ )}
+ </div>
{isSelected && (
<Check className="ml-auto size-4 shrink-0" />
)}
@@ -633,6 +679,7 @@ export const FlowForm = ({
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem
+ disabled={upload.isUploading}
onSelect={(event) => {
event.preventDefault();
@@ -643,8 +690,8 @@ export const FlowForm = ({
handleAttachClick();
}}
>
- <Plus />
- Upload file
+ {upload.isUploading ? <Loader2 className="animate-spin" /> : <Plus />}
+ {upload.isUploading ? 'Uploading…' : 'Upload file'}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -652,7 +699,7 @@ export const FlowForm = ({
{!isLoading || isSubmitting ? (
<InputGroupButton
className="ml-auto"
- disabled={isSubmitting || !isValid || isAnyAttachmentUploading}
+ disabled={isSubmitting || !isValid || upload.isUploading}
size="icon-xs"
type="submit"
variant="default"
@@ -678,7 +725,6 @@ export const FlowForm = ({
/>
</form>
<input
- accept={ACCEPTED_FILE_TYPES}
className="hidden"
multiple
onChange={handleFileInputChange}
@@ -701,11 +747,6 @@ export const FlowForm = ({
isOpen={isReplaceConfirmOpen}
title="Replace content?"
/>
- <ResourcesUploadOptionsDialog
- isOpen={isUploadOptionsDialogOpen}
- onCancel={handleUploadOptionsCancel}
- onConfirm={handleUploadOptionsConfirm}
- />
</Form>
);
};
diff --git a/frontend/src/features/resources/api.ts b/frontend/src/features/resources/api.ts
deleted file mode 100644
index c1a8be12..00000000
--- a/frontend/src/features/resources/api.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import type { ResourcePreviewModel, UploadUrlResponse } from './types';
-
-import { getFileBaseName, getFileExtension } from './constants';
-import { mockStore } from './mock-store';
-
-const NETWORK_LATENCY_MIN_MS = 200;
-const NETWORK_LATENCY_MAX_MS = 500;
-const UPLOAD_TICK_INTERVAL_MS = 120;
-const UPLOAD_TICK_PROGRESS_STEP = 10;
-
-const randomDelay = () =>
- new Promise<void>((resolve) => {
- const delay = NETWORK_LATENCY_MIN_MS + Math.random() * (NETWORK_LATENCY_MAX_MS - NETWORK_LATENCY_MIN_MS);
- setTimeout(resolve, delay);
- });
-
-const generateId = () => {
- if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
- return `res_${crypto.randomUUID()}`;
- }
-
- return `res_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
-};
-
-export async function deleteResource(id: string): Promise<void> {
- await randomDelay();
- mockStore.removeById(id);
-}
-
-export async function getResources(): Promise<ResourcePreviewModel[]> {
- await randomDelay();
-
- return mockStore.list();
-}
-
-export async function getUploadUrl({
- fileName,
- knowledgeId,
-}: {
- fileName: string;
- knowledgeId?: string;
-}): Promise<UploadUrlResponse> {
- await randomDelay();
-
- const id = knowledgeId ?? generateId();
- const item: ResourcePreviewModel = {
- format: getFileExtension(fileName),
- id,
- name: getFileBaseName(fileName),
- uploadedAt: new Date().toISOString(),
- };
-
- if (knowledgeId) {
- const updated = mockStore.update(knowledgeId, item);
-
- if (!updated) {
- mockStore.insert(item);
- }
- } else {
- mockStore.insert(item);
- }
-
- return {
- id,
- item,
- uploadUrl: `mock://upload/${id}`,
- };
-}
-
-export async function uploadResource({
- file,
- onProgress,
-}: {
- file: File;
- onProgress?: (progress: number) => void;
- uploadUrl: string;
-}): Promise<void> {
- if (!file.size) {
- throw new Error('Cannot upload an empty file');
- }
-
- return new Promise<void>((resolve) => {
- let progress = 0;
-
- const tick = () => {
- progress = Math.min(100, progress + UPLOAD_TICK_PROGRESS_STEP);
- onProgress?.(progress);
-
- if (progress >= 100) {
- resolve();
-
- return;
- }
-
- setTimeout(tick, UPLOAD_TICK_INTERVAL_MS);
- };
-
- setTimeout(tick, UPLOAD_TICK_INTERVAL_MS);
- });
-}
diff --git a/frontend/src/features/resources/constants.ts b/frontend/src/features/resources/constants.ts
deleted file mode 100644
index 9e68d8d7..00000000
--- a/frontend/src/features/resources/constants.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-export const UPLOAD_COMPLETE_ANIMATION_DELAY = 200;
-
-export const MAX_FILE_SIZE_MB = 5;
-
-export const MAX_FILE_SIZE_MB_BY_EXTENSION: Record<string, number> = {
- ppt: 20,
- pptx: 20,
-};
-
-export const ACCEPTED_FILE_EXTENSIONS = [
- 'txt',
- 'md',
- 'html',
- 'doc',
- 'docx',
- 'csv',
- 'tsv',
- 'xls',
- 'xlsx',
- 'pdf',
- 'ppt',
- 'pptx',
-];
-
-export const ACCEPTED_FILE_TYPES = ACCEPTED_FILE_EXTENSIONS.map((extension) => `.${extension}`).join(',');
-
-export function getFileBaseName(fileName: string): string {
- const lastDotIndex = fileName.lastIndexOf('.');
-
- return lastDotIndex === -1 ? fileName : fileName.slice(0, lastDotIndex);
-}
-
-export function getFileExtension(fileName: string): string {
- return fileName.split('.').pop()?.toLowerCase() ?? '';
-}
-
-export function isFileTypeAccepted(fileName: string): boolean {
- const extension = fileName.split('.').pop()?.toLowerCase();
-
- if (!extension) {
- return false;
- }
-
- return ACCEPTED_FILE_EXTENSIONS.includes(extension);
-}
diff --git a/frontend/src/features/resources/mock-store.ts b/frontend/src/features/resources/mock-store.ts
deleted file mode 100644
index e8c536d4..00000000
--- a/frontend/src/features/resources/mock-store.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { Log } from '@/lib/log';
-
-import type { ResourcePreviewModel } from './types';
-
-const STORAGE_KEY = 'pentagi:resources';
-
-const SEED_RESOURCES: ResourcePreviewModel[] = [
- {
- format: 'pdf',
- id: 'res_seed_1',
- name: 'web-app-pentest-checklist',
- uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString(),
- },
- {
- format: 'md',
- id: 'res_seed_2',
- name: 'recon-tools-cheatsheet',
- uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3).toISOString(),
- },
- {
- format: 'docx',
- id: 'res_seed_3',
- name: 'incident-response-playbook',
- uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 10).toISOString(),
- },
- {
- format: 'csv',
- id: 'res_seed_4',
- name: 'cve-export-2025-q4',
- uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 32).toISOString(),
- },
- {
- format: 'txt',
- id: 'res_seed_5',
- name: 'wordlist-rockyou-top-1000',
- uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 60).toISOString(),
- },
-];
-
-const isBrowser = typeof window !== 'undefined';
-
-const readFromStorage = (): null | ResourcePreviewModel[] => {
- if (!isBrowser) {
- return null;
- }
-
- try {
- const raw = window.localStorage.getItem(STORAGE_KEY);
-
- if (!raw) {
- return null;
- }
-
- const parsed = JSON.parse(raw) as unknown;
-
- if (!Array.isArray(parsed)) {
- return null;
- }
-
- return parsed as ResourcePreviewModel[];
- } catch (error) {
- Log.warn('Failed to parse resources from localStorage');
- Log.error('mock-store readFromStorage error:', error);
-
- return null;
- }
-};
-
-const writeToStorage = (items: ResourcePreviewModel[]): void => {
- if (!isBrowser) {
- return;
- }
-
- try {
- window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
- } catch (error) {
- Log.warn('Failed to persist resources to localStorage');
- Log.error('mock-store writeToStorage error:', error);
- }
-};
-
-const ensureSeed = (): ResourcePreviewModel[] => {
- const existing = readFromStorage();
-
- if (existing) {
- return existing;
- }
-
- writeToStorage(SEED_RESOURCES);
-
- return [...SEED_RESOURCES];
-};
-
-export const mockStore = {
- insert(item: ResourcePreviewModel): ResourcePreviewModel {
- const items = ensureSeed();
- const next = [item, ...items.filter((existing) => existing.id !== item.id)];
- writeToStorage(next);
-
- return item;
- },
- list(): ResourcePreviewModel[] {
- return ensureSeed();
- },
- removeById(id: string): boolean {
- const items = ensureSeed();
- const next = items.filter((item) => item.id !== id);
-
- if (next.length === items.length) {
- return false;
- }
-
- writeToStorage(next);
-
- return true;
- },
- update(id: string, patch: Partial<ResourcePreviewModel>): null | ResourcePreviewModel {
- const items = ensureSeed();
- const index = items.findIndex((item) => item.id === id);
-
- if (index === -1) {
- return null;
- }
-
- const updated: ResourcePreviewModel = { ...items[index]!, ...patch, id };
- const next = [...items];
- next[index] = updated;
- writeToStorage(next);
-
- return updated;
- },
-};
diff --git a/frontend/src/features/resources/resources-conflict-dialog.tsx b/frontend/src/features/resources/resources-conflict-dialog.tsx
new file mode 100644
index 00000000..fe4b347a
--- /dev/null
+++ b/frontend/src/features/resources/resources-conflict-dialog.tsx
@@ -0,0 +1,62 @@
+import { Replace } from 'lucide-react';
+
+import ConfirmationDialog from '@/components/shared/confirmation-dialog';
+
+interface ConflictItem {
+ destination: string;
+ destinationName: string;
+}
+
+interface ResourcesConflictDialogProps {
+ /**
+ * 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: ConflictItem[];
+ 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.
+ */
+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?"
+ />
+);
diff --git a/frontend/src/features/resources/resources-constants.ts b/frontend/src/features/resources/resources-constants.ts
new file mode 100644
index 00000000..6f3de6df
--- /dev/null
+++ b/frontend/src/features/resources/resources-constants.ts
@@ -0,0 +1,27 @@
+// ── REST API paths ──────────────────────────────────────────────────────────
+
+export const RESOURCES_API_PATH = '/resources/';
+export const RESOURCES_MKDIR_API_PATH = '/resources/mkdir';
+export const RESOURCES_MOVE_API_PATH = '/resources/move';
+export const RESOURCES_COPY_API_PATH = '/resources/copy';
+export const RESOURCES_DOWNLOAD_API_PATH = '/resources/download';
+
+// ── UI constants ────────────────────────────────────────────────────────────
+
+export const SEARCH_DEBOUNCE_MS = 300;
+
+// ── Upload limits (mirror backend's `pkg/resources/resources.go`) ───────────
+//
+// The backend does not whitelist file extensions — any file is accepted as
+// long as the file name passes `validatePathComponent` (no `/ \ : * ? " < > |`,
+// no control characters, ≤ 255 bytes). We re-state the size limits here so the
+// client can fail fast instead of waiting for a 4xx response on huge uploads.
+
+/** Mirrors `resources.MaxUploadFileSize` (300 MB). */
+export const MAX_FILE_SIZE_MB = 300;
+
+/** Mirrors `resources.MaxUploadTotalSize` (2 GB) — combined size of one request. */
+export const MAX_UPLOAD_TOTAL_SIZE_MB = 2 * 1024;
+
+/** Mirrors `resources.MaxUploadFiles`. */
+export const MAX_UPLOAD_FILES_PER_REQUEST = 1000;
diff --git a/frontend/src/features/resources/resources-copy-dialog.tsx b/frontend/src/features/resources/resources-copy-dialog.tsx
new file mode 100644
index 00000000..caa531db
--- /dev/null
+++ b/frontend/src/features/resources/resources-copy-dialog.tsx
@@ -0,0 +1,181 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { Copy, Loader2 } from 'lucide-react';
+import { useEffect } from 'react';
+import { useForm } from 'react-hook-form';
+
+import type { FileNode } from '@/components/file-manager';
+
+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';
+
+interface ResourcesCopyDialogFormProps {
+ file: FileNode;
+ onClose: () => void;
+}
+
+interface ResourcesCopyDialogProps {
+ file: FileNode | null;
+ onClose: () => void;
+}
+
+const buildDefaultDestination = (file: FileNode): string => {
+ const segments = file.path.split('/');
+ const lastSegment = segments.at(-1) ?? file.name;
+ const parent = segments.slice(0, -1).join('/');
+ const dotIndex = lastSegment.lastIndexOf('.');
+ const baseName = file.isDir || dotIndex === -1 ? lastSegment : lastSegment.slice(0, dotIndex);
+ const extension = file.isDir || dotIndex === -1 ? '' : lastSegment.slice(dotIndex);
+ const candidateName = `${baseName}-copy${extension}`;
+
+ return parent ? `${parent}/${candidateName}` : candidateName;
+};
+
+const ResourcesCopyDialogForm = ({ file, onClose }: ResourcesCopyDialogFormProps) => {
+ const { cancelConflicts, copy, isCopying, pendingConflicts, resolveConflicts } = useResourcesCopy();
+
+ const form = useForm<ResourcesCopyFormValues>({
+ defaultValues: {
+ destination: buildDefaultDestination(file),
+ shouldOverwrite: false,
+ },
+ mode: 'onChange',
+ resolver: zodResolver(resourcesCopyFormSchema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ destination: buildDefaultDestination(file),
+ shouldOverwrite: false,
+ });
+ }, [file, form]);
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const wasCopied = await copy(file.path, values);
+
+ if (wasCopied) {
+ onClose();
+ }
+ });
+
+ // After the user picks "Replace" in the conflict dialog the hook retries the copy
+ // with `force = true`. Close the form so it doesn't leave a stale modal — the
+ // resolveConflicts promise resolves once every retry has settled.
+ const handleResolveConflicts = async () => {
+ await resolveConflicts();
+ onClose();
+ };
+
+ const isSubmitDisabled = !form.formState.isValid || isCopying;
+
+ return (
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Copy className="size-4" />
+ {file.isDir ? 'Copy directory' : 'Copy resource'}
+ </DialogTitle>
+ <DialogDescription>
+ Duplicate <code>{file.path}</code> to a new path.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Form {...form}>
+ <form
+ className="flex flex-col gap-4"
+ onSubmit={handleSubmit}
+ >
+ <FormField
+ control={form.control}
+ name="destination"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Destination path</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ autoComplete="off"
+ autoFocus
+ disabled={isCopying}
+ />
+ </FormControl>
+ <FormDescription>Relative path inside your library.</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={isCopying}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ <FormLabel className="cursor-pointer font-normal">
+ Overwrite or merge if the destination already exists
+ </FormLabel>
+ </FormItem>
+ )}
+ />
+
+ <div className="flex justify-end gap-2">
+ <Button
+ disabled={isCopying}
+ onClick={onClose}
+ type="button"
+ variant="outline"
+ >
+ Cancel
+ </Button>
+ <Button
+ disabled={isSubmitDisabled}
+ type="submit"
+ >
+ {isCopying ? <Loader2 className="animate-spin" /> : <Copy />}
+ Copy
+ </Button>
+ </div>
+ </form>
+ </Form>
+
+ <ResourcesConflictDialog
+ conflicts={pendingConflicts}
+ onCancel={cancelConflicts}
+ onReplaceAll={handleResolveConflicts}
+ />
+ </DialogContent>
+ );
+};
+
+export const ResourcesCopyDialog = ({ file, onClose }: ResourcesCopyDialogProps) => {
+ const handleDialogOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ onClose();
+ }
+ };
+
+ return (
+ <Dialog
+ onOpenChange={handleDialogOpenChange}
+ open={!!file}
+ >
+ {file && (
+ <ResourcesCopyDialogForm
+ file={file}
+ onClose={onClose}
+ />
+ )}
+ </Dialog>
+ );
+};
diff --git a/frontend/src/features/resources/resources-mkdir-dialog.tsx b/frontend/src/features/resources/resources-mkdir-dialog.tsx
new file mode 100644
index 00000000..88c04ca9
--- /dev/null
+++ b/frontend/src/features/resources/resources-mkdir-dialog.tsx
@@ -0,0 +1,135 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { FolderPlus, Loader2 } from 'lucide-react';
+import { useEffect } from 'react';
+import { useForm } from 'react-hook-form';
+
+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 { resourcesMkdirFormSchema, type ResourcesMkdirFormValues, useResourcesMkdir } from './use-resources-mkdir';
+
+interface ResourcesMkdirDialogFormProps {
+ defaultParentPath: string;
+ onClose: () => void;
+}
+
+interface ResourcesMkdirDialogProps {
+ /** Pre-filled parent path (without leading "/"). Empty string targets the root. */
+ defaultParentPath?: string;
+ isOpen: boolean;
+ onClose: () => void;
+}
+
+const buildDefaultPath = (defaultParentPath: string): string =>
+ defaultParentPath ? `${defaultParentPath.replace(/\/+$/u, '')}/new-folder` : 'new-folder';
+
+const ResourcesMkdirDialogForm = ({ defaultParentPath, onClose }: ResourcesMkdirDialogFormProps) => {
+ const { isCreating, mkdir } = useResourcesMkdir();
+
+ const form = useForm<ResourcesMkdirFormValues>({
+ defaultValues: { path: buildDefaultPath(defaultParentPath) },
+ mode: 'onChange',
+ resolver: zodResolver(resourcesMkdirFormSchema),
+ });
+
+ useEffect(() => {
+ form.reset({ path: buildDefaultPath(defaultParentPath) });
+ }, [defaultParentPath, form]);
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const wasCreated = await mkdir(values);
+
+ if (wasCreated) {
+ onClose();
+ }
+ });
+
+ const isSubmitDisabled = !form.formState.isValid || isCreating;
+
+ return (
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <FolderPlus className="size-4" />
+ Create directory
+ </DialogTitle>
+ <DialogDescription>
+ Create a virtual directory inside your resource library. Existing parent directories are reused
+ automatically.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Form {...form}>
+ <form
+ className="flex flex-col gap-4"
+ onSubmit={handleSubmit}
+ >
+ <FormField
+ control={form.control}
+ name="path"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Path</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ autoComplete="off"
+ autoFocus
+ disabled={isCreating}
+ placeholder="reports/2025"
+ />
+ </FormControl>
+ <FormDescription>
+ Relative path. Use <code>/</code> to nest into subdirectories.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="flex justify-end gap-2">
+ <Button
+ disabled={isCreating}
+ onClick={onClose}
+ type="button"
+ variant="outline"
+ >
+ Cancel
+ </Button>
+ <Button
+ disabled={isSubmitDisabled}
+ type="submit"
+ >
+ {isCreating ? <Loader2 className="animate-spin" /> : <FolderPlus />}
+ Create
+ </Button>
+ </div>
+ </form>
+ </Form>
+ </DialogContent>
+ );
+};
+
+export const ResourcesMkdirDialog = ({ defaultParentPath = '', isOpen, onClose }: ResourcesMkdirDialogProps) => {
+ const handleDialogOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ onClose();
+ }
+ };
+
+ return (
+ <Dialog
+ onOpenChange={handleDialogOpenChange}
+ open={isOpen}
+ >
+ {isOpen && (
+ <ResourcesMkdirDialogForm
+ defaultParentPath={defaultParentPath}
+ onClose={onClose}
+ />
+ )}
+ </Dialog>
+ );
+};
diff --git a/frontend/src/features/resources/resources-move-dialog.tsx b/frontend/src/features/resources/resources-move-dialog.tsx
new file mode 100644
index 00000000..e94862ce
--- /dev/null
+++ b/frontend/src/features/resources/resources-move-dialog.tsx
@@ -0,0 +1,172 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { FolderInput, Loader2 } from 'lucide-react';
+import { useEffect } from 'react';
+import { useForm } from 'react-hook-form';
+
+import type { FileNode } from '@/components/file-manager';
+
+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';
+
+interface ResourcesMoveDialogFormProps {
+ file: FileNode;
+ onClose: () => void;
+}
+
+interface ResourcesMoveDialogProps {
+ file: FileNode | null;
+ onClose: () => void;
+}
+
+const ResourcesMoveDialogForm = ({ file, onClose }: ResourcesMoveDialogFormProps) => {
+ const { cancelConflicts, isMoving, move, pendingConflicts, resolveConflicts } = useResourcesMove();
+
+ const form = useForm<ResourcesMoveFormValues>({
+ defaultValues: {
+ destination: file.path,
+ shouldOverwrite: false,
+ },
+ mode: 'onChange',
+ resolver: zodResolver(resourcesMoveFormSchema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ destination: file.path,
+ shouldOverwrite: false,
+ });
+ }, [file, form]);
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const wasMoved = await move(file.path, values);
+
+ if (wasMoved) {
+ onClose();
+ }
+ });
+
+ // After the user picks "Replace" in the conflict dialog the hook retries the move
+ // with `force = true`. Close the form so it doesn't leave a stale modal — the
+ // resolveConflicts promise resolves once every retry has settled.
+ const handleResolveConflicts = async () => {
+ await resolveConflicts();
+ onClose();
+ };
+
+ const isSubmitDisabled = !form.formState.isValid || isMoving;
+
+ return (
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <FolderInput className="size-4" />
+ {file.isDir ? 'Move directory' : 'Rename or move resource'}
+ </DialogTitle>
+ <DialogDescription>
+ Update the path of <code>{file.path}</code>.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Form {...form}>
+ <form
+ className="flex flex-col gap-4"
+ onSubmit={handleSubmit}
+ >
+ <FormField
+ control={form.control}
+ name="destination"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>New path</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ autoComplete="off"
+ autoFocus
+ disabled={isMoving}
+ />
+ </FormControl>
+ <FormDescription>
+ Relative path inside your library. End with <code>/</code> to drop the entry into
+ that directory.
+ </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={isMoving}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ <FormLabel className="cursor-pointer font-normal">
+ Overwrite if a resource already exists at the destination
+ </FormLabel>
+ </FormItem>
+ )}
+ />
+
+ <div className="flex justify-end gap-2">
+ <Button
+ disabled={isMoving}
+ onClick={onClose}
+ type="button"
+ variant="outline"
+ >
+ Cancel
+ </Button>
+ <Button
+ disabled={isSubmitDisabled}
+ type="submit"
+ >
+ {isMoving ? <Loader2 className="animate-spin" /> : <FolderInput />}
+ Move
+ </Button>
+ </div>
+ </form>
+ </Form>
+
+ <ResourcesConflictDialog
+ conflicts={pendingConflicts}
+ onCancel={cancelConflicts}
+ onReplaceAll={handleResolveConflicts}
+ />
+ </DialogContent>
+ );
+};
+
+export const ResourcesMoveDialog = ({ file, onClose }: ResourcesMoveDialogProps) => {
+ const handleDialogOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ onClose();
+ }
+ };
+
+ return (
+ <Dialog
+ onOpenChange={handleDialogOpenChange}
+ open={!!file}
+ >
+ {file && (
+ <ResourcesMoveDialogForm
+ file={file}
+ onClose={onClose}
+ />
+ )}
+ </Dialog>
+ );
+};
diff --git a/frontend/src/features/resources/resources-upload-options-dialog.tsx b/frontend/src/features/resources/resources-upload-options-dialog.tsx
deleted file mode 100644
index 72c8e1f5..00000000
--- a/frontend/src/features/resources/resources-upload-options-dialog.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-import { useState } from 'react';
-
-import { Button } from '@/components/ui/button';
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/components/ui/dialog';
-import { cn } from '@/lib/utils';
-
-import type { UploadOption } from './use-file-upload';
-
-interface OptionDescriptor {
- description: string;
- label: string;
- value: UploadOption;
-}
-
-interface ResourcesUploadOptionsDialogProps {
- isOpen: boolean;
- onCancel: () => void;
- onConfirm: (option: UploadOption) => void;
-}
-
-const OPTIONS: OptionDescriptor[] = [
- {
- description: 'Uploads will overwrite files with the same names.',
- label: 'Replace existing files',
- value: 'replace',
- },
- {
- description: 'Saves both copies. New files get renamed automatically.',
- label: 'Keep both versions',
- value: 'keep-both',
- },
-];
-
-export function ResourcesUploadOptionsDialog({ isOpen, onCancel, onConfirm }: ResourcesUploadOptionsDialogProps) {
- const [selectedOption, setSelectedOption] = useState<UploadOption>('replace');
-
- const handleCancel = () => {
- setSelectedOption('replace');
- onCancel();
- };
-
- const handleConfirm = () => {
- const option = selectedOption;
- setSelectedOption('replace');
- onConfirm(option);
- };
-
- return (
- <Dialog
- onOpenChange={(open) => {
- if (!open) {
- handleCancel();
- }
- }}
- open={isOpen}
- >
- <DialogContent
- className="max-w-md"
- onEscapeKeyDown={(event) => {
- event.stopPropagation();
- event.preventDefault();
- }}
- onInteractOutside={(event) => event.preventDefault()}
- >
- <DialogHeader>
- <DialogTitle>Upload options</DialogTitle>
- <DialogDescription>One or more files already exist in Resources.</DialogDescription>
- </DialogHeader>
-
- <div className="flex flex-col gap-2">
- {OPTIONS.map((option) => {
- const isSelected = selectedOption === option.value;
-
- return (
- <button
- aria-pressed={isSelected}
- className={cn(
- 'flex items-start gap-3 rounded-lg border p-3 text-left transition-colors',
- 'hover:bg-muted/40 focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-hidden',
- isSelected ? 'border-primary bg-muted/30' : 'border-border',
- )}
- key={option.value}
- onClick={() => setSelectedOption(option.value)}
- type="button"
- >
- <span
- aria-hidden
- className={cn(
- 'mt-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-full border',
- isSelected ? 'border-primary' : 'border-input',
- )}
- >
- <span
- className={cn(
- 'size-2 rounded-full transition-opacity',
- isSelected ? 'bg-primary opacity-100' : 'opacity-0',
- )}
- />
- </span>
- <span className="flex flex-col gap-0.5">
- <span className="text-sm font-medium">{option.label}</span>
- <span className="text-muted-foreground text-xs">{option.description}</span>
- </span>
- </button>
- );
- })}
- </div>
-
- <DialogFooter className="gap-2">
- <Button
- onClick={handleCancel}
- variant="outline"
- >
- Cancel
- </Button>
- <Button onClick={handleConfirm}>Upload</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/frontend/src/features/resources/resources-utils.ts b/frontend/src/features/resources/resources-utils.ts
new file mode 100644
index 00000000..8f02d058
--- /dev/null
+++ b/frontend/src/features/resources/resources-utils.ts
@@ -0,0 +1,22 @@
+import type { FileNode } from '@/components/file-manager';
+import type { UserResourceFragmentFragment } from '@/graphql/types';
+
+import { baseUrl } from '@/models/api';
+
+import { RESOURCES_DOWNLOAD_API_PATH } from './resources-constants';
+
+/** Convert a GraphQL `UserResource` into a `FileNode` consumed by the FileManager. */
+export const toFileNode = (resource: UserResourceFragmentFragment): FileNode => ({
+ id: resource.id,
+ isDir: resource.isDir,
+ modifiedAt: resource.updatedAt,
+ name: resource.name,
+ path: resource.path,
+ 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)}`;
+
+export const pluralizeItems = (count: number): string => (count === 1 ? 'item' : 'items');
diff --git a/frontend/src/features/resources/types.ts b/frontend/src/features/resources/types.ts
deleted file mode 100644
index 3d8b0a96..00000000
--- a/frontend/src/features/resources/types.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export interface ResourceItem extends ResourcePreviewModel {
- isUploaded: boolean;
- progress: number;
-}
-
-export interface ResourcePreviewModel {
- format: string;
- id: string;
- name: string;
- uploadedAt: string;
-}
-
-export interface UploadUrlResponse {
- id: string;
- item: ResourcePreviewModel;
- uploadUrl: string;
-}
diff --git a/frontend/src/features/resources/use-file-upload.ts b/frontend/src/features/resources/use-file-upload.ts
deleted file mode 100644
index 39e4305a..00000000
--- a/frontend/src/features/resources/use-file-upload.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import { useCallback, useState } from 'react';
-import { toast } from 'sonner';
-
-import { useResources } from '@/providers/resources-provider';
-
-import type { ResourceItem } from './types';
-
-import {
- getFileBaseName,
- getFileExtension,
- isFileTypeAccepted,
- MAX_FILE_SIZE_MB,
- MAX_FILE_SIZE_MB_BY_EXTENSION,
-} from './constants';
-
-export type UploadOption = 'keep-both' | 'replace';
-
-interface PendingFile {
- existingResource: null | ResourceItem;
- file: File;
-}
-
-interface UseFileUploadOptions {
- onResourceAttach?: (resource: ResourceItem) => void;
-}
-
-const getNextAvailableFileName = (originalFileName: string, usedNames: Set<string>): string => {
- const lastDotIndex = originalFileName.lastIndexOf('.');
- const hasExtension = lastDotIndex !== -1;
-
- const baseName = hasExtension ? originalFileName.slice(0, lastDotIndex) : originalFileName;
- const extension = hasExtension ? originalFileName.slice(lastDotIndex) : '';
-
- let counter = 1;
- let nextName = `${baseName} (${counter})${extension}`;
-
- while (usedNames.has(nextName)) {
- counter += 1;
- nextName = `${baseName} (${counter})${extension}`;
- }
-
- return nextName;
-};
-
-const buildFullName = (item: { format: string; name: string }) => {
- if (!item.format) {
- return item.name;
- }
-
- return `${item.name}.${item.format}`;
-};
-
-export function useFileUpload(options?: UseFileUploadOptions) {
- const { resources, uploadResource } = useResources();
- const onResourceAttach = options?.onResourceAttach;
-
- const [pendingFiles, setPendingFiles] = useState<PendingFile[]>([]);
- const [isUploadOptionsDialogOpen, setIsUploadOptionsDialogOpen] = useState(false);
-
- const processFiles = useCallback(
- async (files: PendingFile[], option: UploadOption) => {
- const usedFileNames = new Set<string>(resources.map(buildFullName));
-
- const filesToUpload = files.map(({ existingResource, file }) => {
- let fileName: string;
- let knowledgeId: string | undefined;
-
- if (option === 'replace' && existingResource) {
- knowledgeId = existingResource.id;
- fileName = file.name;
- } else if (option === 'keep-both' && usedFileNames.has(file.name)) {
- fileName = getNextAvailableFileName(file.name, usedFileNames);
- usedFileNames.add(fileName);
- } else {
- fileName = file.name;
- usedFileNames.add(fileName);
- }
-
- return { file, fileName, knowledgeId };
- });
-
- await Promise.allSettled(
- filesToUpload.map(({ file, fileName, knowledgeId }) =>
- uploadResource(file, { fileName, knowledgeId, onStart: onResourceAttach }),
- ),
- );
- },
- [resources, uploadResource, onResourceAttach],
- );
-
- const handleFileChange = useCallback(
- async (selectedFiles: FileList | null, fileInputRef?: React.RefObject<HTMLInputElement | null>) => {
- const resetInput = () => {
- if (!fileInputRef?.current) {
- return;
- }
-
- requestAnimationFrame(() => {
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- });
- };
-
- if (!selectedFiles?.length) {
- return;
- }
-
- const filesToProcess: PendingFile[] = [];
-
- for (const file of Array.from(selectedFiles)) {
- if (!file.size) {
- toast.error(`File "${file.name}" is empty`, {
- description: 'Please upload a file with content.',
- });
-
- continue;
- }
-
- if (!isFileTypeAccepted(file.name)) {
- toast.error(`File "${file.name}" has unsupported format`, {
- description: 'Please upload a supported file type.',
- });
-
- continue;
- }
-
- const extension = getFileExtension(file.name);
- const maxFileSize = MAX_FILE_SIZE_MB_BY_EXTENSION[extension] ?? MAX_FILE_SIZE_MB;
-
- if (file.size > maxFileSize * 1024 * 1024) {
- toast.error(`File "${file.name}" is too large`, {
- description: `Maximum file size is ${maxFileSize}MB.`,
- });
-
- continue;
- }
-
- const baseName = getFileBaseName(file.name);
- const existingResource =
- resources.find((item) => item.name === baseName && item.format === extension) ?? null;
-
- filesToProcess.push({ existingResource, file });
- }
-
- if (!filesToProcess.length) {
- resetInput();
-
- return;
- }
-
- const hasDuplicates = filesToProcess.some((entry) => entry.existingResource !== null);
-
- if (hasDuplicates) {
- setPendingFiles(filesToProcess);
- setIsUploadOptionsDialogOpen(true);
- } else {
- await processFiles(filesToProcess, 'keep-both');
- }
-
- resetInput();
- },
- [processFiles, resources],
- );
-
- const handleUploadOptionsConfirm = useCallback(
- async (option: UploadOption) => {
- setIsUploadOptionsDialogOpen(false);
- const files = pendingFiles;
- setPendingFiles([]);
- await processFiles(files, option);
- },
- [pendingFiles, processFiles],
- );
-
- const handleUploadOptionsCancel = useCallback(() => {
- setIsUploadOptionsDialogOpen(false);
- setPendingFiles([]);
- }, []);
-
- return {
- handleFileChange,
- handleUploadOptionsCancel,
- handleUploadOptionsConfirm,
- isUploadOptionsDialogOpen,
- pendingFiles,
- };
-}
diff --git a/frontend/src/features/resources/use-resources-copy.ts b/frontend/src/features/resources/use-resources-copy.ts
new file mode 100644
index 00000000..5396f469
--- /dev/null
+++ b/frontend/src/features/resources/use-resources-copy.ts
@@ -0,0 +1,133 @@
+import { useCallback, useState } from 'react';
+import { toast } from 'sonner';
+import { z } from 'zod';
+
+import { api, type ApiHttpError, getApiErrorMessage } from '@/lib/axios';
+
+import { RESOURCES_COPY_API_PATH } from './resources-constants';
+
+export const resourcesCopyFormSchema = z.object({
+ destination: z
+ .string()
+ .trim()
+ .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 {
+ destination: string;
+ /** Display name extracted from `destination` for the confirm dialog. */
+ destinationName: string;
+ sourcePath: string;
+}
+
+export type ResourcesCopyFormValues = z.infer<typeof resourcesCopyFormSchema>;
+
+interface CopyRequestBody {
+ destination: string;
+ force: boolean;
+ source: string;
+}
+
+interface UseResourcesCopyResult {
+ /** Drop the pending conflicts without retrying. */
+ cancelConflicts: () => void;
+ copy: (sourcePath: string, values: ResourcesCopyFormValues) => Promise<boolean>;
+ isCopying: boolean;
+ /**
+ * 409 conflicts collected across one or more parallel `copy()` calls. The consumer
+ * shows a single "Replace?" dialog summarising the count; clicking Replace retries
+ * every entry with `force = true`.
+ */
+ pendingConflicts: ResourcesCopyConflict[];
+ /** Retry every pending conflict with `force = true`. Promise resolves when all settle. */
+ 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`. */
+export const useResourcesCopy = (): UseResourcesCopyResult => {
+ const [isCopying, setIsCopying] = useState(false);
+ const [pendingConflicts, setPendingConflicts] = useState<ResourcesCopyConflict[]>([]);
+
+ const performCopy = useCallback(
+ async (sourcePath: string, destination: string, force: boolean): Promise<boolean> => {
+ setIsCopying(true);
+
+ try {
+ await api.post<void, CopyRequestBody>(RESOURCES_COPY_API_PATH, {
+ destination,
+ force,
+ source: sourcePath,
+ });
+
+ toast.success('Resource copied', { description: `Copied to /${destination}` });
+
+ return true;
+ } catch (error) {
+ if (getStatusCode(error) === 409 && !force) {
+ setPendingConflicts((prev) => [
+ ...prev,
+ {
+ destination,
+ destinationName: extractName(destination),
+ sourcePath,
+ },
+ ]);
+
+ return false;
+ }
+
+ const description = getApiErrorMessage(error, 'Failed to copy resource');
+
+ toast.error('Copy failed', { description });
+
+ return false;
+ } finally {
+ setIsCopying(false);
+ }
+ },
+ [],
+ );
+
+ const copy = useCallback(
+ (sourcePath: string, { destination, shouldOverwrite }: ResourcesCopyFormValues): Promise<boolean> =>
+ performCopy(sourcePath, destination.trim(), shouldOverwrite),
+ [performCopy],
+ );
+
+ const resolveConflicts = useCallback(async (): Promise<void> => {
+ if (pendingConflicts.length === 0) {
+ return;
+ }
+
+ const conflicts = pendingConflicts;
+
+ setPendingConflicts([]);
+
+ await Promise.allSettled(
+ conflicts.map((conflict) => performCopy(conflict.sourcePath, conflict.destination, true)),
+ );
+ }, [pendingConflicts, performCopy]);
+
+ const cancelConflicts = useCallback(() => {
+ setPendingConflicts([]);
+ }, []);
+
+ return {
+ cancelConflicts,
+ copy,
+ isCopying,
+ pendingConflicts,
+ resolveConflicts,
+ };
+};
diff --git a/frontend/src/features/resources/use-resources-delete.ts b/frontend/src/features/resources/use-resources-delete.ts
new file mode 100644
index 00000000..06929aa9
--- /dev/null
+++ b/frontend/src/features/resources/use-resources-delete.ts
@@ -0,0 +1,103 @@
+import { useCallback, useState } from 'react';
+import { toast } from 'sonner';
+
+import type { FileNode } from '@/components/file-manager';
+
+import { api, getApiErrorMessage } from '@/lib/axios';
+
+import { RESOURCES_API_PATH } from './resources-constants';
+import { pluralizeItems } from './resources-utils';
+
+interface UseResourcesDeleteParams {
+ onAfterDelete?: () => void;
+}
+
+interface UseResourcesDeleteResult {
+ clearFileToDelete: () => void;
+ confirmDelete: () => Promise<void>;
+ deleteBulk: (filesToDelete: 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`);
+};
+
+/**
+ * Owns both the single-resource and bulk-delete flows. Component drives the
+ * confirmation dialog state through the returned `fileToDelete`/`requestDelete`/
+ * `clearFileToDelete` triple, while the hook hides every API call and toast.
+ *
+ * No imperative refetch is performed: the GraphQL `resourceDeleted` subscription
+ * is wired into the Apollo cache and removes the deleted entries automatically.
+ */
+export const useResourcesDelete = ({ onAfterDelete }: UseResourcesDeleteParams = {}): UseResourcesDeleteResult => {
+ const [fileToDelete, setFileToDelete] = useState<FileNode | null>(null);
+
+ const requestDelete = useCallback((file: FileNode) => {
+ setFileToDelete(file);
+ }, []);
+
+ const clearFileToDelete = useCallback(() => {
+ setFileToDelete(null);
+ }, []);
+
+ 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 });
+ } 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],
+ );
+
+ return {
+ clearFileToDelete,
+ confirmDelete,
+ deleteBulk,
+ fileToDelete,
+ requestDelete,
+ };
+};
diff --git a/frontend/src/features/resources/use-resources-mkdir.ts b/frontend/src/features/resources/use-resources-mkdir.ts
new file mode 100644
index 00000000..7cd36d11
--- /dev/null
+++ b/frontend/src/features/resources/use-resources-mkdir.ts
@@ -0,0 +1,57 @@
+import { useCallback, useState } from 'react';
+import { toast } from 'sonner';
+import { z } from 'zod';
+
+import { api, getApiErrorMessage } from '@/lib/axios';
+
+import { RESOURCES_MKDIR_API_PATH } from './resources-constants';
+
+export const resourcesMkdirFormSchema = z.object({
+ path: z
+ .string()
+ .trim()
+ .min(1, { message: 'Path cannot be empty' })
+ .refine((value) => !value.startsWith('/'), { message: 'Path must be relative (no leading "/")' })
+ .refine((value) => !value.split('/').includes('..'), { message: 'Path must not contain ".."' }),
+});
+
+export type ResourcesMkdirFormValues = z.infer<typeof resourcesMkdirFormSchema>;
+
+interface MkdirRequestBody {
+ path: string;
+}
+
+interface UseResourcesMkdirResult {
+ isCreating: boolean;
+ mkdir: (values: ResourcesMkdirFormValues) => Promise<boolean>;
+}
+
+/** Wraps `POST /resources/mkdir` (idempotent — returns existing dir on hit). */
+export const useResourcesMkdir = (): UseResourcesMkdirResult => {
+ const [isCreating, setIsCreating] = useState(false);
+
+ const mkdir = useCallback(async ({ path }: ResourcesMkdirFormValues): Promise<boolean> => {
+ setIsCreating(true);
+
+ try {
+ await api.post<void, MkdirRequestBody>(RESOURCES_MKDIR_API_PATH, { path: path.trim() });
+
+ toast.success('Directory created', { description: `Created at /${path.trim()}` });
+
+ return true;
+ } catch (error) {
+ const description = getApiErrorMessage(error, 'Failed to create directory');
+
+ toast.error('Create directory failed', { description });
+
+ return false;
+ } finally {
+ setIsCreating(false);
+ }
+ }, []);
+
+ return {
+ isCreating,
+ mkdir,
+ };
+};
diff --git a/frontend/src/features/resources/use-resources-move.ts b/frontend/src/features/resources/use-resources-move.ts
new file mode 100644
index 00000000..34cbbc03
--- /dev/null
+++ b/frontend/src/features/resources/use-resources-move.ts
@@ -0,0 +1,138 @@
+import { useCallback, useState } from 'react';
+import { toast } from 'sonner';
+import { z } from 'zod';
+
+import { api, type ApiHttpError, getApiErrorMessage } from '@/lib/axios';
+
+import { RESOURCES_MOVE_API_PATH } from './resources-constants';
+
+export const resourcesMoveFormSchema = z.object({
+ destination: z
+ .string()
+ .trim()
+ .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 {
+ destination: string;
+ /** Display name extracted from `destination` for the confirm dialog. */
+ destinationName: string;
+ sourcePath: string;
+}
+
+export type ResourcesMoveFormValues = z.infer<typeof resourcesMoveFormSchema>;
+
+interface MoveRequestBody {
+ destination: string;
+ force: boolean;
+ source: string;
+}
+
+interface UseResourcesMoveResult {
+ /** Drop the pending conflicts without retrying. */
+ cancelConflicts: () => void;
+ isMoving: boolean;
+ move: (sourcePath: string, values: ResourcesMoveFormValues) => 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
+ * every entry with `force = true`.
+ */
+ pendingConflicts: ResourcesMoveConflict[];
+ /** Retry every pending conflict with `force = true`. Promise resolves when all settle. */
+ 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. */
+export const useResourcesMove = (): UseResourcesMoveResult => {
+ const [isMoving, setIsMoving] = useState(false);
+ const [pendingConflicts, setPendingConflicts] = useState<ResourcesMoveConflict[]>([]);
+
+ const performMove = useCallback(
+ async (sourcePath: string, destination: string, force: boolean): Promise<boolean> => {
+ setIsMoving(true);
+
+ try {
+ await api.put<void, MoveRequestBody>(RESOURCES_MOVE_API_PATH, {
+ destination,
+ force,
+ source: sourcePath,
+ });
+
+ toast.success('Resource moved', { description: `Moved to /${destination}` });
+
+ return true;
+ } catch (error) {
+ // 409 = destination already exists. Push to the conflict array so the
+ // consumer can render a single aggregated "Replace?" dialog covering
+ // 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) {
+ setPendingConflicts((prev) => [
+ ...prev,
+ {
+ destination,
+ destinationName: extractName(destination),
+ sourcePath,
+ },
+ ]);
+
+ return false;
+ }
+
+ const description = getApiErrorMessage(error, 'Failed to move resource');
+
+ toast.error('Move failed', { description });
+
+ return false;
+ } finally {
+ setIsMoving(false);
+ }
+ },
+ [],
+ );
+
+ const move = useCallback(
+ (sourcePath: string, { destination, shouldOverwrite }: ResourcesMoveFormValues): Promise<boolean> =>
+ performMove(sourcePath, destination.trim(), shouldOverwrite),
+ [performMove],
+ );
+
+ const resolveConflicts = useCallback(async (): Promise<void> => {
+ if (pendingConflicts.length === 0) {
+ return;
+ }
+
+ const conflicts = pendingConflicts;
+
+ setPendingConflicts([]);
+
+ await Promise.allSettled(
+ conflicts.map((conflict) => performMove(conflict.sourcePath, conflict.destination, true)),
+ );
+ }, [pendingConflicts, performMove]);
+
+ const cancelConflicts = useCallback(() => {
+ setPendingConflicts([]);
+ }, []);
+
+ return {
+ cancelConflicts,
+ isMoving,
+ move,
+ pendingConflicts,
+ resolveConflicts,
+ };
+};
diff --git a/frontend/src/features/resources/use-resources-realtime.ts b/frontend/src/features/resources/use-resources-realtime.ts
new file mode 100644
index 00000000..9bb164eb
--- /dev/null
+++ b/frontend/src/features/resources/use-resources-realtime.ts
@@ -0,0 +1,25 @@
+import {
+ useResourceAddedSubscription,
+ useResourceDeletedSubscription,
+ useResourceUpdatedSubscription,
+} from '@/graphql/types';
+
+interface UseResourcesRealtimeParams {
+ /**
+ * When `true`, every subscription is skipped. The flag is needed to delay
+ * subscription delivery until the initial query has populated the Apollo cache
+ * so that the cache field exists before the subscription updates arrive.
+ */
+ isPaused: boolean;
+}
+
+/**
+ * Wires up the three user-resource subscriptions (added / updated / deleted).
+ * The Apollo subscription-cache link in `lib/apollo.ts` writes incoming entries
+ * straight into the `resources` query cache, so callers don't need extra refetch.
+ */
+export const useResourcesRealtime = ({ isPaused }: UseResourcesRealtimeParams): void => {
+ useResourceAddedSubscription({ skip: isPaused });
+ useResourceUpdatedSubscription({ skip: isPaused });
+ useResourceDeletedSubscription({ skip: isPaused });
+};
diff --git a/frontend/src/features/resources/use-resources-search.ts b/frontend/src/features/resources/use-resources-search.ts
new file mode 100644
index 00000000..9f9faffb
--- /dev/null
+++ b/frontend/src/features/resources/use-resources-search.ts
@@ -0,0 +1,43 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { useCallback } from 'react';
+import { useForm, type UseFormReturn } from 'react-hook-form';
+import { z } from 'zod';
+
+import { useDebouncedValue } from '@/hooks/use-debounced-value';
+
+import { SEARCH_DEBOUNCE_MS } from './resources-constants';
+
+const resourcesSearchFormSchema = z.object({
+ search: z.string(),
+});
+
+export type ResourcesSearchFormValues = z.infer<typeof resourcesSearchFormSchema>;
+
+interface UseResourcesSearchResult {
+ debouncedQuery: string;
+ form: UseFormReturn<ResourcesSearchFormValues>;
+ rawQuery: string;
+ resetSearch: () => void;
+}
+
+/** Owns the search form and exposes a debounced version of the typed query. */
+export const useResourcesSearch = (): UseResourcesSearchResult => {
+ const form = useForm<ResourcesSearchFormValues>({
+ defaultValues: { search: '' },
+ resolver: zodResolver(resourcesSearchFormSchema),
+ });
+
+ const rawQuery = form.watch('search');
+ const debouncedQuery = useDebouncedValue(rawQuery, SEARCH_DEBOUNCE_MS);
+
+ const resetSearch = useCallback(() => {
+ form.reset({ search: '' });
+ }, [form]);
+
+ return {
+ debouncedQuery,
+ form,
+ rawQuery,
+ resetSearch,
+ };
+};
diff --git a/frontend/src/features/resources/use-resources-upload.ts b/frontend/src/features/resources/use-resources-upload.ts
new file mode 100644
index 00000000..e3a7ec24
--- /dev/null
+++ b/frontend/src/features/resources/use-resources-upload.ts
@@ -0,0 +1,189 @@
+import { useCallback, useRef, useState } from 'react';
+import { toast } from 'sonner';
+
+import type { UserResourceFragmentFragment } from '@/graphql/types';
+
+import { api, getApiErrorMessage, unwrapApiResponse } from '@/lib/axios';
+
+import {
+ MAX_FILE_SIZE_MB,
+ MAX_UPLOAD_FILES_PER_REQUEST,
+ MAX_UPLOAD_TOTAL_SIZE_MB,
+ RESOURCES_API_PATH,
+} from './resources-constants';
+import { pluralizeItems } from './resources-utils';
+
+interface UploadOptions {
+ /** Virtual directory path inside the user's library. Empty/undefined uploads to root. */
+ dir?: string;
+}
+
+interface UploadResponse {
+ items: UserResourceFragmentFragment[];
+ total: number;
+}
+
+interface UseResourcesUploadParams {
+ onSuccess?: (uploaded: UploadResponse) => void;
+}
+
+interface UseResourcesUploadResult {
+ fileInputKey: number;
+ fileInputProps: {
+ onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
+ ref: React.RefObject<HTMLInputElement | null>;
+ };
+ isUploading: boolean;
+ openFilePicker: () => void;
+ uploadFiles: (selectedFiles: File[], options?: UploadOptions) => Promise<null | UploadResponse>;
+}
+
+const UPLOAD_OVERWRITE_HINT = 'Resource already exists — please rename or remove the existing entry';
+
+/**
+ * Mirrors the per-file / per-batch limits enforced by the backend
+ * (`pkg/resources/resources.go`). The backend itself does not whitelist file
+ * extensions, so neither does the client.
+ */
+const validateUploadBatch = (files: File[]): null | string => {
+ if (files.length > MAX_UPLOAD_FILES_PER_REQUEST) {
+ return `Too many files: max ${MAX_UPLOAD_FILES_PER_REQUEST} per upload`;
+ }
+
+ const maxBytesPerFile = MAX_FILE_SIZE_MB * 1024 * 1024;
+ const maxTotalBytes = MAX_UPLOAD_TOTAL_SIZE_MB * 1024 * 1024;
+ let totalBytes = 0;
+
+ for (const file of files) {
+ if (file.size === 0) {
+ return `File "${file.name}" is empty`;
+ }
+
+ if (file.size > maxBytesPerFile) {
+ return `File "${file.name}" is larger than ${MAX_FILE_SIZE_MB} MB`;
+ }
+
+ totalBytes += file.size;
+ }
+
+ if (totalBytes > maxTotalBytes) {
+ return `Total upload size exceeds the ${MAX_UPLOAD_TOTAL_SIZE_MB} MB limit`;
+ }
+
+ return null;
+};
+
+const buildUploadSuccessMessage = (uploadedCount: number, dir?: string) => {
+ const target = dir ? `to /${dir}` : 'to your library';
+
+ if (uploadedCount === 1) {
+ return { description: `Uploaded ${target}`, title: 'File uploaded' };
+ }
+
+ return {
+ description: `${uploadedCount} files uploaded ${target}`,
+ title: `${uploadedCount} ${pluralizeItems(uploadedCount)} uploaded`,
+ };
+};
+
+/**
+ * Wraps the multipart `POST /resources/` REST call. Bumps `fileInputKey` after
+ * each upload so the consumer can remount the hidden `<input>` and clear it
+ * declaratively.
+ */
+export const useResourcesUpload = ({ onSuccess }: UseResourcesUploadParams = {}): UseResourcesUploadResult => {
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const [isUploading, setIsUploading] = useState(false);
+ const [fileInputKey, setFileInputKey] = useState(0);
+
+ const openFilePicker = useCallback(() => {
+ inputRef.current?.click();
+ }, []);
+
+ const uploadFiles = useCallback(
+ async (selectedFiles: File[], options?: UploadOptions): Promise<null | UploadResponse> => {
+ if (selectedFiles.length === 0) {
+ return null;
+ }
+
+ const validationError = validateUploadBatch(selectedFiles);
+
+ if (validationError) {
+ toast.error('Upload failed', { description: validationError });
+
+ return null;
+ }
+
+ const formData = new FormData();
+
+ selectedFiles.forEach((file) => formData.append('files', file));
+
+ setIsUploading(true);
+
+ try {
+ const response = await api.post<UploadResponse, FormData>(RESOURCES_API_PATH, formData, {
+ headers: { 'Content-Type': undefined },
+ params: options?.dir ? { dir: options.dir } : undefined,
+ timeout: 0,
+ });
+ const raw = unwrapApiResponse(response);
+ // TODO(backend): drop the `String(item.id)` / `String(item.userId)`
+ // coercion once `POST /resources/` returns `id`/`userId` as strings.
+ // The GraphQL `ID` scalar is typed as `string` everywhere; REST sends
+ // numbers, so we normalize here to keep downstream consumers (forms,
+ // Apollo cache, etc.) type-consistent.
+ const data: UploadResponse = {
+ ...raw,
+ items: (raw.items ?? []).map((item) => ({
+ ...item,
+ id: String(item.id),
+ userId: String(item.userId),
+ })),
+ };
+ const uploadedCount = data.items.length;
+ const message = buildUploadSuccessMessage(uploadedCount, options?.dir);
+
+ toast.success(message.title, { description: message.description });
+
+ onSuccess?.(data);
+
+ return data;
+ } catch (error) {
+ const description = getApiErrorMessage(error, 'Failed to upload files', {
+ 409: UPLOAD_OVERWRITE_HINT,
+ });
+
+ toast.error('Upload failed', { description });
+
+ return null;
+ } finally {
+ setIsUploading(false);
+ }
+ },
+ [onSuccess],
+ );
+
+ const handleFileSelection = useCallback(
+ async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const selectedFiles = Array.from(event.target.files ?? []);
+
+ try {
+ await uploadFiles(selectedFiles);
+ } finally {
+ setFileInputKey((previousKey) => previousKey + 1);
+ }
+ },
+ [uploadFiles],
+ );
+
+ return {
+ fileInputKey,
+ fileInputProps: {
+ onChange: handleFileSelection,
+ ref: inputRef,
+ },
+ isUploading,
+ openFilePicker,
+ uploadFiles,
+ };
+};
diff --git a/frontend/src/features/flows/files/use-files-drag-and-drop.ts b/frontend/src/hooks/use-files-drag-and-drop.ts
similarity index 95%
rename from frontend/src/features/flows/files/use-files-drag-and-drop.ts
rename to frontend/src/hooks/use-files-drag-and-drop.ts
index 28475d86..f52e4a05 100644
--- a/frontend/src/features/flows/files/use-files-drag-and-drop.ts
+++ b/frontend/src/hooks/use-files-drag-and-drop.ts
@@ -27,8 +27,8 @@ const isFileDragEvent = (event: React.DragEvent<HTMLDivElement>): boolean =>
* sees only an immutable `isDragging` flag and four event handlers.
*
* The hook does not auto-reset on external identity changes: the consumer is expected
- * to remount the subtree (via `key={flowId}` or similar) which discards both the
- * counter and the `isDragging` state.
+ * to remount the subtree (via `key={...}` on the surrounding component) which discards
+ * both the counter and the `isDragging` state.
*/
export const useFilesDragAndDrop = ({
canAcceptDrop,
diff --git a/frontend/src/pages/resources/resources.tsx b/frontend/src/pages/resources/resources.tsx
index e8a3bdc7..9d021367 100644
--- a/frontend/src/pages/resources/resources.tsx
+++ b/frontend/src/pages/resources/resources.tsx
@@ -1,253 +1,122 @@
-import type { ColumnDef } from '@tanstack/react-table';
-
-import { format, formatDistanceToNow } from 'date-fns';
-import { ArrowDown, ArrowUp, Folder, Loader2, MoreHorizontal, Plus, Trash } from 'lucide-react';
-import { useMemo, useRef, useState } from 'react';
-
-import type { ResourceItem } from '@/features/resources/types';
+import { Copy, FileSymlink, Folder, FolderPlus, FolderUp, Loader2, Search, X } from 'lucide-react';
+import { useCallback, useMemo, useState } from 'react';
+import { toast } from 'sonner';
+import {
+ copyPathAction,
+ deleteAction,
+ downloadAction,
+ FileManager,
+ type FileManagerAction,
+ type FileNode,
+} from '@/components/file-manager';
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from '@/components/ui/breadcrumb';
import { Button } from '@/components/ui/button';
-import { ContextMenuItem } from '@/components/ui/context-menu';
-import { DataTable } from '@/components/ui/data-table';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from '@/components/ui/dropdown-menu';
+import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';
+import { FileDropZone } from '@/components/ui/file-drop-zone';
+import { Form, FormControl, FormField, FormItem } from '@/components/ui/form';
+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger } from '@/components/ui/sidebar';
-import { StatusCard } from '@/components/ui/status-card';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { ACCEPTED_FILE_TYPES } from '@/features/resources/constants';
-import { ResourcesUploadOptionsDialog } from '@/features/resources/resources-upload-options-dialog';
-import { useFileUpload } from '@/features/resources/use-file-upload';
+import { ResourcesConflictDialog } from '@/features/resources/resources-conflict-dialog';
+import { ResourcesCopyDialog } from '@/features/resources/resources-copy-dialog';
+import { ResourcesMkdirDialog } from '@/features/resources/resources-mkdir-dialog';
+import { ResourcesMoveDialog } from '@/features/resources/resources-move-dialog';
+import { buildResourceDownloadHref, toFileNode } from '@/features/resources/resources-utils';
+import { useResourcesDelete } from '@/features/resources/use-resources-delete';
+import { useResourcesMove } from '@/features/resources/use-resources-move';
+import { useResourcesSearch } from '@/features/resources/use-resources-search';
+import { useResourcesUpload } from '@/features/resources/use-resources-upload';
+import { useFilesDragAndDrop } from '@/hooks/use-files-drag-and-drop';
+import { copyToClipboard } from '@/lib/report';
import { useResources } from '@/providers/resources-provider';
const Resources = () => {
- const { deleteResource, resources } = useResources();
- const fileInputRef = useRef<HTMLInputElement>(null);
+ const { isInitialLoading, resources } = useResources();
+ const search = useResourcesSearch();
- const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
- const [deletingResource, setDeletingResource] = useState<null | ResourceItem>(null);
- const [deletingIds, setDeletingIds] = useState<Set<string>>(new Set());
+ const [isMkdirOpen, setIsMkdirOpen] = useState(false);
+ const [fileToRename, setFileToRename] = useState<FileNode | null>(null);
+ const [fileToCopy, setFileToCopy] = useState<FileNode | null>(null);
- const { handleFileChange, handleUploadOptionsCancel, handleUploadOptionsConfirm, isUploadOptionsDialogOpen } =
- useFileUpload();
+ const upload = useResourcesUpload();
+ const deletion = useResourcesDelete();
+ const moveAction = useResourcesMove();
- const handleUploadFile = () => {
- fileInputRef.current?.click();
- };
+ const canAcceptDrop = !upload.isUploading;
+ const { dragHandlers, isDragging } = useFilesDragAndDrop({
+ canAcceptDrop,
+ onDrop: upload.uploadFiles,
+ });
- const handleFileInputChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
- await handleFileChange(event.target.files, fileInputRef);
- };
+ const fileNodes = useMemo<FileNode[]>(() => resources.map(toFileNode), [resources]);
- const handleDeleteDialogOpen = (resource: ResourceItem) => {
- setDeletingResource(resource);
- setIsDeleteDialogOpen(true);
- };
+ /**
+ * 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.
+ */
+ const handleMoveItems = useCallback(
+ async (sources: FileNode[], destinationDir: string) => {
+ await Promise.allSettled(
+ sources.map((source) => {
+ const destination = destinationDir ? `${destinationDir}/${source.name}` : source.name;
- const handleDelete = async () => {
- if (!deletingResource) {
- return;
- }
+ return moveAction.move(source.path, { destination, shouldOverwrite: false });
+ }),
+ );
+ },
+ [moveAction],
+ );
- setDeletingIds((prev) => new Set(prev).add(deletingResource.id));
+ const handleCopyPath = useCallback(async (file: FileNode) => {
+ const wasCopied = await copyToClipboard(file.path);
- try {
- await deleteResource(deletingResource.id);
- setDeletingResource(null);
- } catch {
- // Error already handled in provider with toast
- } finally {
- setDeletingIds((prev) => {
- const next = new Set(prev);
- next.delete(deletingResource.id);
+ if (wasCopied) {
+ toast.success('Path copied to clipboard');
- return next;
- });
+ return;
}
- };
- const columns: ColumnDef<ResourceItem>[] = useMemo(
- () => [
- {
- accessorKey: 'name',
- cell: ({ row }) => {
- const resource = row.original;
+ toast.error('Failed to copy path');
+ }, []);
- return (
- <div className="flex min-w-0 flex-col gap-0.5">
- <span className="truncate font-medium">{resource.name}</span>
- {!resource.isUploaded && (
- <span className="text-muted-foreground flex items-center gap-1.5 text-xs">
- <Loader2 className="size-3 animate-spin" />
- Uploading… {resource.progress}%
- </span>
- )}
- </div>
- );
- },
- enableHiding: false,
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
- variant="link"
- >
- Name
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
- },
- {
- accessorKey: 'format',
- cell: ({ row }) => {
- const value = (row.getValue('format') as string) ?? '';
-
- return <span className="text-muted-foreground uppercase">{value || '—'}</span>;
- },
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
- variant="link"
- >
- Format
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
- size: 120,
- },
+ const fileManagerActions = useMemo<FileManagerAction[]>(
+ () => [
+ downloadAction(buildResourceDownloadHref),
+ copyPathAction(handleCopyPath),
{
- accessorKey: 'uploadedAt',
- cell: ({ row }) => {
- const value = row.getValue('uploadedAt') as string;
- const date = new Date(value);
- const relative = formatDistanceToNow(date, { addSuffix: true });
- const absolute = format(date, 'd MMM yyyy, HH:mm');
-
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="text-muted-foreground cursor-default text-sm">{relative}</span>
- </TooltipTrigger>
- <TooltipContent>
- <span className="text-xs">{absolute}</span>
- </TooltipContent>
- </Tooltip>
- );
- },
- header: ({ column }) => {
- const sorted = column.getIsSorted();
-
- return (
- <Button
- className="text-muted-foreground hover:text-primary flex items-center gap-2 p-0 no-underline hover:no-underline"
- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
- variant="link"
- >
- Date
- {sorted === 'asc' ? (
- <ArrowDown className="size-4" />
- ) : sorted === 'desc' ? (
- <ArrowUp className="size-4" />
- ) : null}
- </Button>
- );
- },
- size: 160,
- sortingFn: (rowA, rowB) =>
- new Date(rowA.original.uploadedAt).getTime() - new Date(rowB.original.uploadedAt).getTime(),
+ appliesToDirs: true,
+ icon: FileSymlink,
+ id: 'resources-rename',
+ label: 'Rename or move',
+ onSelect: (file) => setFileToRename(file),
},
{
- cell: ({ row }) => {
- const resource = row.original;
- const isDeleting = deletingIds.has(resource.id);
- const disabled = isDeleting || !resource.isUploaded;
-
- return (
- <div className="flex items-center justify-end gap-1 opacity-0 transition-opacity group-hover:opacity-100">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- className="size-8 p-0"
- variant="ghost"
- >
- <MoreHorizontal />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="min-w-24"
- >
- <DropdownMenuItem
- disabled={disabled}
- onClick={() => handleDeleteDialogOpen(resource)}
- >
- {isDeleting ? (
- <>
- <Loader2 className="size-4 animate-spin" />
- Deleting...
- </>
- ) : (
- <>
- <Trash className="size-4" />
- Delete
- </>
- )}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- );
- },
- enableHiding: false,
- header: () => null,
- id: 'actions',
- meta: { preventRowClick: true },
- size: 48,
+ appliesToDirs: true,
+ icon: Copy,
+ id: 'resources-copy',
+ label: 'Copy to…',
+ onSelect: (file) => setFileToCopy(file),
},
+ deleteAction(deletion.requestDelete),
],
- [deletingIds],
+ [deletion.requestDelete, handleCopyPath],
);
- const renderRowContextMenu = (resource: ResourceItem) => {
- const isDeleting = deletingIds.has(resource.id);
- const disabled = isDeleting || !resource.isUploaded;
-
- return (
- <ContextMenuItem
- disabled={disabled}
- onClick={() => handleDeleteDialogOpen(resource)}
- >
- <Trash />
- {isDeleting ? 'Deleting...' : 'Delete'}
- </ContextMenuItem>
- );
- };
+ const handleDeleteDialogOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ if (!nextOpen) {
+ deletion.clearFileToDelete();
+ }
+ },
+ [deletion],
+ );
const pageHeader = (
- <header className="bg-background sticky top-0 z-10 flex h-12 w-full shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12">
+ <header className="bg-background sticky top-0 z-10 flex h-12 w-full shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear">
<div className="flex items-center gap-2 px-4">
<SidebarTrigger className="-ml-1" />
<Separator
@@ -263,87 +132,171 @@ const Resources = () => {
</BreadcrumbList>
</Breadcrumb>
</div>
- <div className="ml-auto flex items-center gap-2 px-4">
- <Button
- onClick={handleUploadFile}
- size="sm"
- variant="secondary"
- >
- <Plus />
- Add file
- </Button>
- </div>
</header>
);
- const fileInput = (
- <input
- accept={ACCEPTED_FILE_TYPES}
- className="hidden"
- multiple
- onChange={handleFileInputChange}
- ref={fileInputRef}
- type="file"
+ const hasResources = resources.length > 0;
+
+ const noResourcesState = (
+ <FileDropZone
+ actionLabel="Upload files"
+ description="Upload documents so PentAGI agents can reference them during your flows. You can also drag & drop files anywhere in this panel."
+ hint="Up to 300 MB per file · 2 GB per upload"
+ isDragging={isDragging}
+ isUploading={upload.isUploading}
+ onBrowse={upload.openFilePicker}
+ title="No resources yet"
/>
);
- if (!resources.length) {
- return (
- <>
- {pageHeader}
- {fileInput}
- <div className="flex flex-col gap-4 p-4">
- <StatusCard
- action={
- <Button
- onClick={handleUploadFile}
- variant="secondary"
- >
- <Plus className="size-4" />
- Upload file
- </Button>
- }
- description="Upload documents so PentAGI agents can reference them during your flows"
- icon={<Folder className="text-muted-foreground size-8" />}
- title="No resources yet"
- />
- </div>
- <ResourcesUploadOptionsDialog
- isOpen={isUploadOptionsDialogOpen}
- onCancel={handleUploadOptionsCancel}
- onConfirm={handleUploadOptionsConfirm}
- />
- </>
- );
- }
+ const noMatchesState = (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Search />
+ </EmptyMedia>
+ <EmptyTitle>No matches</EmptyTitle>
+ <EmptyDescription>
+ No resources match <code>{search.debouncedQuery.trim()}</code>. Try a different query.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
return (
<>
{pageHeader}
- {fileInput}
- <div className="flex flex-col gap-4 p-4 pt-0">
- <DataTable
- columns={columns}
- data={resources}
- filterColumn="name"
- filterPlaceholder="Filter resources..."
- renderRowContextMenu={renderRowContextMenu}
+ <div
+ className="relative flex flex-1 flex-col gap-4 p-4"
+ {...dragHandlers}
+ >
+ <input
+ className="hidden"
+ key={upload.fileInputKey}
+ multiple
+ type="file"
+ {...upload.fileInputProps}
/>
- <ConfirmationDialog
- cancelText="Cancel"
- confirmText="Delete"
- handleConfirm={handleDelete}
- handleOpenChange={setIsDeleteDialogOpen}
- isOpen={isDeleteDialogOpen}
- itemName={deletingResource?.name}
- itemType="resource"
+ {isDragging && hasResources && (
+ <div className="bg-primary/10 border-primary pointer-events-none absolute inset-2 z-30 flex items-center justify-center rounded-lg border-2 border-dashed">
+ <div className="text-primary flex flex-col items-center gap-2">
+ <FolderUp className="size-8" />
+ <span className="text-sm font-medium">Drop files to upload</span>
+ </div>
+ </div>
+ )}
+
+ <Form {...search.form}>
+ <div className="flex gap-2 p-px">
+ <FormField
+ control={search.form.control}
+ name="search"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormControl>
+ <InputGroup>
+ <InputGroupAddon>
+ <Search />
+ </InputGroupAddon>
+ <InputGroupInput
+ {...field}
+ autoComplete="off"
+ placeholder="Search resources..."
+ type="text"
+ />
+ {field.value && (
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ onClick={search.resetSearch}
+ type="button"
+ >
+ <X />
+ </InputGroupButton>
+ </InputGroupAddon>
+ )}
+ </InputGroup>
+ </FormControl>
+ </FormItem>
+ )}
+ />
+
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ disabled={upload.isUploading}
+ onClick={() => setIsMkdirOpen(true)}
+ size="icon-sm"
+ type="button"
+ variant="outline"
+ >
+ <FolderPlus />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Create directory</TooltipContent>
+ </Tooltip>
+
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ disabled={upload.isUploading}
+ onClick={upload.openFilePicker}
+ size="icon-sm"
+ type="button"
+ variant="outline"
+ >
+ {upload.isUploading ? <Loader2 className="animate-spin" /> : <FolderUp />}
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Upload files</TooltipContent>
+ </Tooltip>
+ </div>
+ </Form>
+
+ <FileManager
+ actions={fileManagerActions}
+ className="min-h-0 flex-1"
+ emptyState={noResourcesState}
+ files={fileNodes}
+ isLoading={isInitialLoading}
+ onBulkDelete={deletion.deleteBulk}
+ onMoveItems={handleMoveItems}
+ search={{ emptyState: noMatchesState, query: search.debouncedQuery }}
+ />
+
+ <ResourcesMkdirDialog
+ isOpen={isMkdirOpen}
+ onClose={() => setIsMkdirOpen(false)}
+ />
+
+ <ResourcesMoveDialog
+ file={fileToRename}
+ onClose={() => setFileToRename(null)}
+ />
+
+ <ResourcesCopyDialog
+ file={fileToCopy}
+ onClose={() => setFileToCopy(null)}
/>
- <ResourcesUploadOptionsDialog
- isOpen={isUploadOptionsDialogOpen}
- onCancel={handleUploadOptionsCancel}
- onConfirm={handleUploadOptionsConfirm}
+ <ResourcesConflictDialog
+ conflicts={moveAction.pendingConflicts}
+ onCancel={moveAction.cancelConflicts}
+ onReplaceAll={moveAction.resolveConflicts}
+ />
+
+ <ConfirmationDialog
+ confirmText="Delete"
+ handleConfirm={deletion.confirmDelete}
+ handleOpenChange={handleDeleteDialogOpenChange}
+ isOpen={!!deletion.fileToDelete}
+ itemName={deletion.fileToDelete?.name}
+ itemType={deletion.fileToDelete?.isDir ? 'directory' : 'resource'}
+ title={deletion.fileToDelete?.isDir ? 'Delete Directory' : 'Delete Resource'}
/>
</div>
</>
diff --git a/frontend/src/providers/flow-provider.tsx b/frontend/src/providers/flow-provider.tsx
index efbdb08e..0957e63b 100644
--- a/frontend/src/providers/flow-provider.tsx
+++ b/frontend/src/providers/flow-provider.tsx
@@ -194,7 +194,7 @@ export const FlowProvider = ({ children }: FlowProviderProps) => {
return;
}
- const { message: input, providerName } = values;
+ const { message: input, providerName, resourceIds } = values;
try {
await putUserInput({
@@ -202,6 +202,7 @@ export const FlowProvider = ({ children }: FlowProviderProps) => {
flowId,
input,
modelProvider: providerName || undefined,
+ resourceIds: resourceIds?.length ? resourceIds : undefined,
},
});
} catch (error) {
@@ -238,7 +239,7 @@ export const FlowProvider = ({ children }: FlowProviderProps) => {
const createAssistant = useCallback(
async (values: FlowFormValues) => {
- const { message, providerName, useAgents } = values;
+ const { message, providerName, resourceIds, useAgents } = values;
const input = message.trim();
const modelProvider = providerName.trim();
@@ -253,6 +254,7 @@ export const FlowProvider = ({ children }: FlowProviderProps) => {
flowId,
input,
modelProvider,
+ resourceIds: resourceIds?.length ? resourceIds : undefined,
useAgents,
},
});
@@ -278,7 +280,7 @@ export const FlowProvider = ({ children }: FlowProviderProps) => {
const submitAssistantMessage = useCallback(
async (assistantId: string, values: FlowFormValues) => {
- const { message, useAgents } = values;
+ const { message, resourceIds, useAgents } = values;
const input = message.trim();
@@ -292,6 +294,7 @@ export const FlowProvider = ({ children }: FlowProviderProps) => {
assistantId,
flowId,
input,
+ resourceIds: resourceIds?.length ? resourceIds : undefined,
useAgents,
},
});
diff --git a/frontend/src/providers/flows-provider.tsx b/frontend/src/providers/flows-provider.tsx
index e6f162c9..fe790883 100644
--- a/frontend/src/providers/flows-provider.tsx
+++ b/frontend/src/providers/flows-provider.tsx
@@ -72,7 +72,7 @@ export const FlowsProvider = ({ children }: FlowsProviderProps) => {
const createFlow = useCallback(
async (values: FlowFormValues) => {
- const { message, providerName } = values;
+ const { message, providerName, resourceIds } = values;
const input = message.trim();
const modelProvider = providerName.trim();
@@ -86,6 +86,7 @@ export const FlowsProvider = ({ children }: FlowsProviderProps) => {
variables: {
input,
modelProvider,
+ resourceIds: resourceIds?.length ? resourceIds : undefined,
},
});
@@ -109,7 +110,7 @@ export const FlowsProvider = ({ children }: FlowsProviderProps) => {
const createFlowWithAssistant = useCallback(
async (values: FlowFormValues) => {
- const { message, providerName, useAgents } = values;
+ const { message, providerName, resourceIds, useAgents } = values;
const input = message.trim();
const modelProvider = providerName.trim();
@@ -124,6 +125,7 @@ export const FlowsProvider = ({ children }: FlowsProviderProps) => {
flowId: '0',
input,
modelProvider,
+ resourceIds: resourceIds?.length ? resourceIds : undefined,
useAgents,
},
});
diff --git a/frontend/src/providers/resources-provider.tsx b/frontend/src/providers/resources-provider.tsx
index 3c3709db..1a42b7a3 100644
--- a/frontend/src/providers/resources-provider.tsx
+++ b/frontend/src/providers/resources-provider.tsx
@@ -1,197 +1,174 @@
-import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react';
+import { useApolloClient } from '@apollo/client';
+import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
-import type { ResourceItem, ResourcePreviewModel } from '@/features/resources/types';
+import type { UserResourceFragmentFragment } from '@/graphql/types';
-import {
- deleteResource as deleteResourceApi,
- getResources,
- getUploadUrl,
- uploadResource as uploadResourceApi,
-} from '@/features/resources/api';
-import { UPLOAD_COMPLETE_ANIMATION_DELAY } from '@/features/resources/constants';
-import { Log } from '@/lib/log';
+import { RESOURCES_API_PATH } from '@/features/resources/resources-constants';
+import { useResourcesRealtime } from '@/features/resources/use-resources-realtime';
+import { ResourcesDocument, useResourcesQuery } from '@/graphql/types';
+import { api, getApiErrorMessage, unwrapApiResponse } from '@/lib/axios';
import { useUser } from '@/providers/user-provider';
interface ResourcesContextValue {
- deleteResource: (id: string) => Promise<void>;
- getResource: (id: string) => ResourceItem | undefined;
+ /** Recursive list of every entry in the user's library (files + directories). */
+ error: Error | null | undefined;
+ /** Lookup helper: returns `undefined` when the resource is unknown. */
+ getResource: (id: string) => undefined | UserResourceFragmentFragment;
+ isInitialLoading: boolean;
isLoading: boolean;
- resources: ResourceItem[];
- uploadResource: (file: File, options?: UploadResourceOptions) => Promise<ResourceItem>;
+ /** Force a network re-read of the resources list. */
+ refetch: () => Promise<unknown>;
+ resources: UserResourceFragmentFragment[];
}
-interface ResourcesProviderProps {
- children: ReactNode;
+/**
+ * Shape of the REST `GET /resources/` response wrapper.
+ * The element type is intentionally aliased to the GraphQL fragment — the backend's
+ * `models.ResourceEntry` is meant to be structurally identical, and we treat them as
+ * the same type so REST-loaded entries can sit in the same Apollo cache as GraphQL ones.
+ */
+interface ResourcesListResponse {
+ items?: null | UserResourceFragmentFragment[];
+ total?: number;
}
-interface UploadResourceOptions {
- fileName?: string;
- knowledgeId?: string;
- onStart?: (resource: ResourceItem) => void;
+interface ResourcesProviderProps {
+ children: ReactNode;
}
const ResourcesContext = createContext<ResourcesContextValue | undefined>(undefined);
-const toResourceItem = (item: ResourcePreviewModel): ResourceItem => ({
- ...item,
- isUploaded: true,
- progress: 100,
-});
-
+const RESOURCES_ERROR_TOAST_ID = 'resources-error';
+
+/**
+ * Loads the user's full resource library and keeps it in sync via three GraphQL
+ * subscriptions (added / updated / deleted).
+ *
+ * **Temporary detail**: the initial library is fetched via REST
+ * `GET /resources/?recursive=true` rather than the GraphQL `resources` query.
+ * The GraphQL resolver currently has a bug for `path == "" && recursive == true`
+ * that returns only top-level entries — we side-step it by hydrating the same
+ * Apollo cache slot from REST and reading it back through `useResourcesQuery`
+ * with a `cache-only` fetch policy. Subscriptions continue to update the cache
+ * as before, so consumers see no behavioural change.
+ *
+ * Once the backend resolver is fixed this hook should switch back to a plain
+ * `useResourcesQuery({ variables: { recursive: true } })`.
+ */
export const ResourcesProvider = ({ children }: ResourcesProviderProps) => {
const { authInfo, isAuthenticated } = useUser();
const shouldFetchResources = Boolean(authInfo && authInfo.type !== 'guest' && isAuthenticated());
- const [resources, setResources] = useState<ResourceItem[]>([]);
- const [isLoading, setIsLoading] = useState(false);
- const [hasLoaded, setHasLoaded] = useState(false);
+ const apolloClient = useApolloClient();
+ const [restLoading, setRestLoading] = useState(false);
+ const [restError, setRestError] = useState<Error | null>(null);
+ const [refreshTick, setRefreshTick] = useState(0);
+
+ // Hydrate the Apollo cache from REST. We write to the same `resources(recursive: true)`
+ // cache slot that `useResourcesQuery` reads, so subscription delta updates plumbed
+ // through `lib/apollo.ts` keep working without any extra wiring.
useEffect(() => {
- if (!shouldFetchResources || hasLoaded) {
+ if (!shouldFetchResources) {
return;
}
let isCancelled = false;
- setIsLoading(true);
- getResources()
- .then((items) => {
+ setRestLoading(true);
+ setRestError(null);
+
+ (async () => {
+ try {
+ const response = await api.get<ResourcesListResponse>(RESOURCES_API_PATH, {
+ params: { recursive: true },
+ });
+ const data = unwrapApiResponse(response);
+
if (isCancelled) {
return;
}
- setResources(items.map(toResourceItem));
- setHasLoaded(true);
- })
- .catch((error: unknown) => {
+ // `__typename` is required so Apollo normalizes each entry under
+ // `UserResource:<id>` in the cache. Without it the read-back through
+ // `useResourcesQuery` returns objects whose scalar fields are `undefined`
+ // (the cache treats every entry as an unidentifiable structural blob).
+ //
+ // TODO(backend): remove `String(item.id)` / `String(item.userId)` coercion
+ // once the REST `/resources/` endpoint returns `id`/`userId` as strings.
+ // Currently it returns them as numbers, which breaks consumers that rely
+ // on the GraphQL `ID` scalar (typed as `string` everywhere) — e.g. zod
+ // validation `z.array(z.string())` in `FlowForm.resourceIds`.
+ apolloClient.writeQuery({
+ data: {
+ resources: (data.items ?? []).map((item) => ({
+ ...item,
+ __typename: 'UserResource' as const,
+ id: String(item.id),
+ userId: String(item.userId),
+ })),
+ },
+ query: ResourcesDocument,
+ variables: { recursive: true },
+ });
+ } catch (caught) {
if (isCancelled) {
return;
}
- const description = error instanceof Error ? error.message : 'Failed to load resources';
- toast.error('Failed to load resources', {
- description,
- });
- Log.error('Error loading resources:', error);
- })
- .finally(() => {
+ const message = getApiErrorMessage(caught, 'Failed to load resources');
+
+ setRestError(new Error(message));
+ } finally {
if (!isCancelled) {
- setIsLoading(false);
+ setRestLoading(false);
}
- });
+ }
+ })();
return () => {
isCancelled = true;
};
- }, [shouldFetchResources, hasLoaded]);
-
- const getResource = useCallback(
- (id: string): ResourceItem | undefined => resources.find((item) => item.id === id),
- [resources],
- );
+ }, [apolloClient, refreshTick, shouldFetchResources]);
- const upsertResource = useCallback((next: ResourceItem) => {
- setResources((current) => {
- const exists = current.some((item) => item.id === next.id);
+ const { data, error: graphqlError } = useResourcesQuery({
+ fetchPolicy: 'cache-only',
+ skip: !shouldFetchResources,
+ variables: { recursive: true },
+ });
- if (exists) {
- return current.map((item) => (item.id === next.id ? next : item));
- }
+ const error = restError ?? graphqlError ?? null;
+ const isInitialLoading = restLoading && data === undefined;
- return [next, ...current];
- });
- }, []);
+ useResourcesRealtime({ isPaused: !shouldFetchResources || isInitialLoading });
- const updateResource = useCallback((id: string, patch: Partial<ResourceItem>) => {
- setResources((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item)));
- }, []);
-
- const removeResourceFromState = useCallback((id: string) => {
- setResources((current) => current.filter((item) => item.id !== id));
- }, []);
-
- const uploadResource = useCallback(
- async (file: File, options?: UploadResourceOptions): Promise<ResourceItem> => {
- try {
- const fileName = options?.fileName ?? file.name;
- const { id, item, uploadUrl } = await getUploadUrl({
- fileName,
- knowledgeId: options?.knowledgeId,
- });
-
- const optimisticItem: ResourceItem = {
- ...item,
- isUploaded: false,
- progress: 0,
- };
- upsertResource(optimisticItem);
- options?.onStart?.(optimisticItem);
-
- try {
- await uploadResourceApi({
- file,
- onProgress: (progress) => {
- updateResource(id, { progress });
- },
- uploadUrl,
- });
- } catch (uploadError) {
- removeResourceFromState(id);
- throw uploadError;
- }
-
- const finalItem: ResourceItem = {
- ...item,
- isUploaded: false,
- progress: 100,
- };
- updateResource(id, finalItem);
-
- setTimeout(() => {
- updateResource(id, { isUploaded: true, progress: 100 });
- }, UPLOAD_COMPLETE_ANIMATION_DELAY);
-
- return { ...finalItem, isUploaded: true };
- } catch (error) {
- const description = error instanceof Error ? error.message : 'Failed to upload file';
- toast.error('Failed to upload file', {
- description,
- });
- Log.error('Error uploading resource:', error);
- throw error;
- }
- },
- [removeResourceFromState, updateResource, upsertResource],
- );
+ useEffect(() => {
+ if (error) {
+ toast.error('Failed to load resources', {
+ description: error.message,
+ id: RESOURCES_ERROR_TOAST_ID,
+ });
+ }
+ }, [error]);
- const deleteResource = useCallback(
- async (id: string) => {
- try {
- await deleteResourceApi(id);
- removeResourceFromState(id);
- } catch (error) {
- const description = error instanceof Error ? error.message : 'Failed to delete resource';
- toast.error('Failed to delete resource', {
- description,
- });
- Log.error('Error deleting resource:', error);
- throw error;
- }
- },
- [removeResourceFromState],
- );
+ const resources = useMemo<UserResourceFragmentFragment[]>(() => data?.resources ?? [], [data?.resources]);
const value = useMemo<ResourcesContextValue>(
() => ({
- deleteResource,
- getResource,
- isLoading,
+ error,
+ getResource: (id: string) => resources.find((item) => item.id === id),
+ isInitialLoading,
+ isLoading: restLoading,
+ refetch: () => {
+ setRefreshTick((tick) => tick + 1);
+
+ return Promise.resolve();
+ },
resources,
- uploadResource,
}),
- [deleteResource, getResource, isLoading, resources, uploadResource],
+ [error, isInitialLoading, resources, restLoading],
);
return <ResourcesContext.Provider value={value}>{children}</ResourcesContext.Provider>;