Skip to content

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

refactor(flow-files): share upload validator and rely on subscriptions for cache sync

Sergey Kozyrenkod743bf510537
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
index 8809885a..0bba43d0 100644
--- a/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
+++ b/frontend/src/features/flows/files/flow-files-attach-resources-dialog.tsx
@@ -31,7 +31,12 @@ interface FlowFilesAttachResourcesDialogProps {
flowId: null | string;
isOpen: boolean;
onClose: () => void;
- onSuccess: () => void;
+ /**
+ * Optional UI hook fired after a successful attach. The flow-files Apollo
+ * cache itself is updated via the `flowFileAdded` subscription, so callers
+ * should NOT use this to drive an imperative refetch.
+ */
+ onSuccess?: () => void;
}
const EMPTY_SELECTION: ReadonlySet<string> = new Set();
@@ -78,7 +83,7 @@ const FlowFilesAttachResourcesDialogBody = ({
execute: async ({ ids }, force) => attach({ ids: [...ids], shouldOverwrite: force }),
findConflicts: ({ resourcePaths }) => findAttachConflicts(resourcePaths, cachedFiles),
onSuccess: () => {
- onSuccess();
+ onSuccess?.();
onClose();
},
synthesizeFallbackConflicts: ({ resourcePaths }) =>
diff --git a/frontend/src/features/flows/files/flow-files-constants.ts b/frontend/src/features/flows/files/flow-files-constants.ts
index 62c77f0b..5a6ac2dc 100644
--- a/frontend/src/features/flows/files/flow-files-constants.ts
+++ b/frontend/src/features/flows/files/flow-files-constants.ts
@@ -27,3 +27,18 @@ export const RESOURCES_TARGET_DIRECTORY = '/work/resources';
/** Default container path browsed when the Pull dialog opens. */
export const CONTAINER_DEFAULT_PATH = '/work';
+
+// ── Upload limits (mirror backend's `pkg/flowfiles/files.go`) ──────────────
+//
+// Symmetric with the resources library limits (`features/resources/resources-constants.ts`)
+// today, but kept as a separate set so they can diverge from resources without
+// touching the resources call sites.
+
+/** Mirrors `flowfiles.MaxUploadFileSize` (300 MB). */
+export const FLOW_FILES_MAX_FILE_SIZE_MB = 300;
+
+/** Mirrors `flowfiles.MaxUploadTotalSize` (2 GB) — combined size of one request. */
+export const FLOW_FILES_MAX_UPLOAD_TOTAL_SIZE_MB = 2 * 1024;
+
+/** Mirrors `flowfiles.MaxUploadFiles`. */
+export const FLOW_FILES_MAX_UPLOAD_FILES_PER_REQUEST = 1000;
diff --git a/frontend/src/features/flows/files/flow-files-pull-dialog.tsx b/frontend/src/features/flows/files/flow-files-pull-dialog.tsx
index 96f99c7c..e9202d20 100644
--- a/frontend/src/features/flows/files/flow-files-pull-dialog.tsx
+++ b/frontend/src/features/flows/files/flow-files-pull-dialog.tsx
@@ -34,7 +34,12 @@ interface FlowFilesPullDialogFormProps {
cachedFiles: readonly FileNode[];
flowId: null | string;
onClose: () => void;
- onSuccess: () => void;
+ /**
+ * Optional UI hook fired after a successful pull. The flow-files Apollo
+ * cache itself is updated via the `flowFileAdded` subscription, so callers
+ * should NOT use this to drive an imperative refetch.
+ */
+ onSuccess?: () => void;
}
interface FlowFilesPullDialogProps {
@@ -42,7 +47,8 @@ interface FlowFilesPullDialogProps {
flowId: null | string;
isOpen: boolean;
onClose: () => void;
- onSuccess: () => void;
+ /** See {@link FlowFilesPullDialogFormProps.onSuccess}. */
+ onSuccess?: () => void;
}
/**
@@ -109,7 +115,7 @@ const FlowFilesPullDialogForm = ({ cachedFiles, flowId, onClose, onSuccess }: Fl
// (or, with `force=true`, replaced ones) reflect their fresh state.
onSuccess: () => {
void refetchListing();
- onSuccess();
+ onSuccess?.();
},
});
diff --git a/frontend/src/features/flows/files/flow-files.tsx b/frontend/src/features/flows/files/flow-files.tsx
index bd32ba96..19906f6c 100644
--- a/frontend/src/features/flows/files/flow-files.tsx
+++ b/frontend/src/features/flows/files/flow-files.tsx
@@ -45,13 +45,13 @@ const FlowFiles = () => {
// pushes the deduped selection. Empty array / null closes the dialog.
const [filesToPromote, setFilesToPromote] = useState<FileNode[] | null>(null);
- const { fileNodes, isInitialLoading, isLoading, refetchFiles } = useFlowFilesData({ flowId });
+ const { fileNodes, isInitialLoading, isLoading } = useFlowFilesData({ flowId });
useFlowFilesRealtime({ flowId, isPaused: isLoading });
const search = useFlowFilesSearch();
- const upload = useFlowFilesUpload({ flowId, refetchFiles });
- const deletion = useFlowFilesDelete({ flowId, refetchFiles });
+ const upload = useFlowFilesUpload({ flowId });
+ const deletion = useFlowFilesDelete({ flowId });
const canAcceptDrop = !!flowId && !upload.isUploading;
const { dragHandlers, isDragging } = useFilesDragAndDrop({
@@ -345,7 +345,6 @@ const FlowFiles = () => {
flowId={flowId}
isOpen={isPullDialogOpen}
onClose={handleClosePullDialog}
- onSuccess={refetchFiles}
/>
<FlowFilesAttachResourcesDialog
@@ -353,7 +352,6 @@ const FlowFiles = () => {
flowId={flowId}
isOpen={isAttachResourcesDialogOpen}
onClose={handleCloseAttachResourcesDialog}
- onSuccess={refetchFiles}
/>
<FlowFilesPromoteDialog
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 b5d45cbf..12a578f0 100644
--- a/frontend/src/features/flows/files/use-flow-files-delete.ts
+++ b/frontend/src/features/flows/files/use-flow-files-delete.ts
@@ -11,7 +11,14 @@ import { type FlowFilesResponse, pluralizeItems } from './flow-files-utils';
interface UseFlowFilesDeleteParams {
flowId: null | string;
- refetchFiles: () => Promise<unknown>;
+ /**
+ * Optional UI-side hook fired after a successful delete. Useful for the
+ * caller to clear local state (selection, dialogs, …) — the Apollo cache
+ * itself is updated automatically by the `flowFileDeleted` subscription
+ * (see `lib/apollo.ts`), so callers should NOT use this to drive an
+ * imperative refetch.
+ */
+ onAfterDelete?: () => void;
}
interface UseFlowFilesDeleteResult {
@@ -32,9 +39,9 @@ interface UseFlowFilesDeleteResult {
* Issues one `DELETE /flows/{id}/files?paths[]=…` regardless of how many files
* are passed in. The backend deduplicates and validates atomically: either every
* path is removed or nothing is. The response enumerates every entry that was
- * actually deleted (including nested files for directory removals) — we still
- * trigger an explicit refetch because flow files don't have a deletion
- * subscription wired into Apollo yet.
+ * actually deleted (including nested files for directory removals) — we ignore
+ * it here because the GraphQL `flowFileDeleted` subscription is wired into the
+ * Apollo cache (see `lib/apollo.ts`) and removes those entries automatically.
*/
const deleteFlowFilesRequest = (flowId: string, paths: readonly string[]) =>
api.delete<FlowFilesResponse>(`${FLOW_FILES_API_PATH(flowId)}?${buildPathsQuery(paths)}`);
@@ -42,10 +49,15 @@ const deleteFlowFilesRequest = (flowId: string, paths: readonly string[]) =>
/**
* Owns both the single-file and bulk-delete flows. The component drives the
* confirmation dialog state through the returned `fileToDelete`/`requestDelete`/
- * `clearFileToDelete` triple, while the hook hides every API call, toast and
- * post-delete refetch.
+ * `clearFileToDelete` triple, while the hook hides every API call and toast.
+ *
+ * No imperative refetch is performed: the GraphQL `flowFileDeleted` subscription
+ * is wired into the Apollo cache and removes the deleted entries automatically.
*/
-export const useFlowFilesDelete = ({ flowId, refetchFiles }: UseFlowFilesDeleteParams): UseFlowFilesDeleteResult => {
+export const useFlowFilesDelete = ({
+ flowId,
+ onAfterDelete,
+}: UseFlowFilesDeleteParams): UseFlowFilesDeleteResult => {
const [fileToDelete, setFileToDelete] = useState<FileNode | null>(null);
const requestDelete = useCallback((file: FileNode) => {
@@ -74,17 +86,15 @@ export const useFlowFilesDelete = ({ flowId, refetchFiles }: UseFlowFilesDeleteP
} else {
toast.success(`${filesToDelete.length} ${pluralizeItems(filesToDelete.length)} deleted`);
}
+
+ onAfterDelete?.();
} catch (error) {
const description = getApiErrorMessage(error, 'Failed to delete file');
toast.error('Delete failed', { description });
- } finally {
- // Always refetch — succeeded paths now leave the cache, failed
- // paths may have been partially recreated by other clients.
- await refetchFiles();
}
},
- [flowId, refetchFiles],
+ [flowId, onAfterDelete],
);
const confirmDelete = useCallback(async () => {
diff --git a/frontend/src/features/flows/files/use-flow-files-upload.ts b/frontend/src/features/flows/files/use-flow-files-upload.ts
index cbe70da5..dec6a79a 100644
--- a/frontend/src/features/flows/files/use-flow-files-upload.ts
+++ b/frontend/src/features/flows/files/use-flow-files-upload.ts
@@ -2,13 +2,19 @@ import { useCallback, useRef, useState } from 'react';
import { toast } from 'sonner';
import { api, getApiErrorMessage, unwrapApiResponse } from '@/lib/axios';
-
-import { FLOW_FILES_API_PATH, UPLOADS_TARGET_DIRECTORY } from './flow-files-constants';
+import { validateUploadBatch } from '@/lib/upload-validation';
+
+import {
+ FLOW_FILES_API_PATH,
+ FLOW_FILES_MAX_FILE_SIZE_MB,
+ FLOW_FILES_MAX_UPLOAD_FILES_PER_REQUEST,
+ FLOW_FILES_MAX_UPLOAD_TOTAL_SIZE_MB,
+ UPLOADS_TARGET_DIRECTORY,
+} from './flow-files-constants';
import { type FlowFilesResponse } from './flow-files-utils';
interface UseFlowFilesUploadParams {
flowId: null | string;
- refetchFiles: () => Promise<unknown>;
}
interface UseFlowFilesUploadResult {
@@ -44,8 +50,12 @@ const buildUploadSuccessMessage = (uploadedCount: number, firstFileName?: string
*
* The `key` value is bumped after every upload so React remounts the `<input>` —
* this clears its native value declaratively without mutating the DOM directly.
+ *
+ * No imperative refetch is performed: the GraphQL `flowFileAdded` subscription
+ * is wired into the Apollo cache (see `lib/apollo.ts`) and appends the newly
+ * uploaded entries automatically.
*/
-export const useFlowFilesUpload = ({ flowId, refetchFiles }: UseFlowFilesUploadParams): UseFlowFilesUploadResult => {
+export const useFlowFilesUpload = ({ flowId }: UseFlowFilesUploadParams): UseFlowFilesUploadResult => {
const inputRef = useRef<HTMLInputElement | null>(null);
const [isUploading, setIsUploading] = useState(false);
const [fileInputKey, setFileInputKey] = useState(0);
@@ -60,6 +70,18 @@ export const useFlowFilesUpload = ({ flowId, refetchFiles }: UseFlowFilesUploadP
return;
}
+ const validationError = validateUploadBatch(selectedFiles, {
+ maxFiles: FLOW_FILES_MAX_UPLOAD_FILES_PER_REQUEST,
+ maxFileSizeMb: FLOW_FILES_MAX_FILE_SIZE_MB,
+ maxTotalSizeMb: FLOW_FILES_MAX_UPLOAD_TOTAL_SIZE_MB,
+ });
+
+ if (validationError) {
+ toast.error('Upload failed', { description: validationError });
+
+ return;
+ }
+
const formData = new FormData();
selectedFiles.forEach((file) => formData.append('files', file));
@@ -78,8 +100,6 @@ export const useFlowFilesUpload = ({ flowId, refetchFiles }: UseFlowFilesUploadP
const successMessage = buildUploadSuccessMessage(uploadedCount, data.files?.[0]?.name);
toast.success(successMessage.title, { description: successMessage.description });
-
- await refetchFiles();
} catch (error) {
const description = getApiErrorMessage(error, 'Failed to upload files');
@@ -88,7 +108,7 @@ export const useFlowFilesUpload = ({ flowId, refetchFiles }: UseFlowFilesUploadP
setIsUploading(false);
}
},
- [flowId, refetchFiles],
+ [flowId],
);
const handleFileSelection = useCallback(
diff --git a/frontend/src/features/resources/use-resources-upload.ts b/frontend/src/features/resources/use-resources-upload.ts
index 14ac4812..7b13da7f 100644
--- a/frontend/src/features/resources/use-resources-upload.ts
+++ b/frontend/src/features/resources/use-resources-upload.ts
@@ -4,6 +4,7 @@ import { toast } from 'sonner';
import type { UserResourceFragmentFragment } from '@/graphql/types';
import { api, getApiErrorMessage, unwrapApiResponse } from '@/lib/axios';
+import { validateUploadBatch } from '@/lib/upload-validation';
import {
MAX_FILE_SIZE_MB,
@@ -63,39 +64,6 @@ interface UseResourcesUploadResult {
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';
@@ -156,7 +124,11 @@ export const useResourcesUpload = ({
return null;
}
- const validationError = validateUploadBatch(selectedFiles);
+ const validationError = validateUploadBatch(selectedFiles, {
+ maxFiles: MAX_UPLOAD_FILES_PER_REQUEST,
+ maxFileSizeMb: MAX_FILE_SIZE_MB,
+ maxTotalSizeMb: MAX_UPLOAD_TOTAL_SIZE_MB,
+ });
if (validationError) {
toast.error('Upload failed', { description: validationError });
diff --git a/frontend/src/lib/upload-validation.test.ts b/frontend/src/lib/upload-validation.test.ts
new file mode 100644
index 00000000..74c18f1e
--- /dev/null
+++ b/frontend/src/lib/upload-validation.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+
+import { type UploadValidationLimits, validateUploadBatch } from './upload-validation';
+
+const MB = 1024 * 1024;
+
+const DEFAULT_LIMITS: UploadValidationLimits = {
+ maxFiles: 1000,
+ maxFileSizeMb: 300,
+ maxTotalSizeMb: 2 * 1024,
+};
+
+/**
+ * Build a File whose `.size` is forced to `bytes` without actually allocating
+ * a buffer of that size. Lets us exercise the multi-GB total-size branch in a
+ * unit test without OOMing the worker.
+ */
+const makeFile = (name: string, bytes: number): File => {
+ const file = new File([], name);
+
+ Object.defineProperty(file, 'size', { configurable: true, value: bytes });
+
+ return file;
+};
+
+describe('validateUploadBatch', () => {
+ it('returns null for an empty batch', () => {
+ expect(validateUploadBatch([], DEFAULT_LIMITS)).toBeNull();
+ });
+
+ it('returns null when every file is within limits', () => {
+ const files = [makeFile('a.txt', 100 * MB), makeFile('b.zip', 250 * MB)];
+
+ expect(validateUploadBatch(files, DEFAULT_LIMITS)).toBeNull();
+ });
+
+ it('rejects batches exceeding the file count cap', () => {
+ const files = Array.from({ length: 5 }, (_, i) => makeFile(`f-${i}.txt`, 1));
+
+ expect(validateUploadBatch(files, { ...DEFAULT_LIMITS, maxFiles: 4 })).toBe(
+ 'Too many files: max 4 per upload',
+ );
+ });
+
+ it('rejects a single file that is larger than the per-file cap', () => {
+ const files = [makeFile('ok.txt', 1 * MB), makeFile('huge.bin', 350 * MB)];
+
+ expect(validateUploadBatch(files, DEFAULT_LIMITS)).toBe(
+ 'File "huge.bin" is larger than 300 MB',
+ );
+ });
+
+ it('rejects batches whose combined size exceeds the total cap', () => {
+ // Each file fits under maxFileSizeMb, but the sum is over the batch limit.
+ const files = [
+ makeFile('a.bin', 250 * MB),
+ makeFile('b.bin', 250 * MB),
+ makeFile('c.bin', 250 * MB),
+ ];
+
+ expect(validateUploadBatch(files, { ...DEFAULT_LIMITS, maxTotalSizeMb: 600 })).toBe(
+ 'Total upload size exceeds the 600 MB limit',
+ );
+ });
+
+ it('rejects 0-byte files by default', () => {
+ const files = [makeFile('ok.txt', 1 * MB), makeFile('empty.txt', 0)];
+
+ expect(validateUploadBatch(files, DEFAULT_LIMITS)).toBe('File "empty.txt" is empty');
+ });
+
+ it('lets 0-byte files through when rejectEmpty is disabled', () => {
+ const files = [makeFile('ok.txt', 1 * MB), makeFile('empty.txt', 0)];
+
+ expect(validateUploadBatch(files, { ...DEFAULT_LIMITS, rejectEmpty: false })).toBeNull();
+ });
+
+ it('reports the first violation when multiple rules would fail', () => {
+ // Both "too many files" AND a too-big file are present — the count
+ // check runs first by contract.
+ const files = Array.from({ length: 6 }, (_, i) => makeFile(`f-${i}.bin`, 400 * MB));
+
+ expect(validateUploadBatch(files, { ...DEFAULT_LIMITS, maxFiles: 5 })).toBe(
+ 'Too many files: max 5 per upload',
+ );
+ });
+});
diff --git a/frontend/src/lib/upload-validation.ts b/frontend/src/lib/upload-validation.ts
new file mode 100644
index 00000000..c76c3608
--- /dev/null
+++ b/frontend/src/lib/upload-validation.ts
@@ -0,0 +1,69 @@
+/**
+ * Shared client-side preflight for multipart uploads. Run before constructing
+ * the FormData so the user gets an instant toast instead of waiting for the
+ * network round-trip and a generic 4xx error.
+ *
+ * Mirrors the per-file / per-batch limits enforced by the backend
+ * (`pkg/resources/resources.go` for the resources library and
+ * `pkg/flowfiles/files.go` for the flow files cache). Both backends do not
+ * whitelist file extensions, so neither does this validator — it only checks
+ * size, count and emptiness.
+ */
+
+export interface UploadValidationLimits {
+ /** Maximum number of files allowed per request. */
+ maxFiles: number;
+ /** Maximum size of a single file in megabytes. */
+ maxFileSizeMb: number;
+ /** Maximum combined size of the batch in megabytes. */
+ maxTotalSizeMb: number;
+ /**
+ * Reject 0-byte files. Defaults to `true` because both servers stream the
+ * upload body and surface a confusing `EOF on read` error mid-request when
+ * an empty file lands in the multipart payload.
+ */
+ rejectEmpty?: boolean;
+}
+
+const MEGABYTE = 1024 * 1024;
+
+/**
+ * Validate a batch of `File` objects against the supplied limits. Returns
+ * `null` when the batch is acceptable or the user-facing error message for
+ * the **first** violation otherwise — callers typically forward this string
+ * directly into a `toast.error('Upload failed', { description })`.
+ *
+ * Empty batches are treated as a no-op (`null`); callers usually short-circuit
+ * before reaching the validator anyway.
+ */
+export const validateUploadBatch = (
+ files: readonly File[],
+ limits: UploadValidationLimits,
+): null | string => {
+ if (files.length > limits.maxFiles) {
+ return `Too many files: max ${limits.maxFiles} per upload`;
+ }
+
+ const maxBytesPerFile = limits.maxFileSizeMb * MEGABYTE;
+ const maxTotalBytes = limits.maxTotalSizeMb * MEGABYTE;
+ const rejectEmpty = limits.rejectEmpty ?? true;
+ let totalBytes = 0;
+
+ for (const file of files) {
+ if (rejectEmpty && file.size === 0) {
+ return `File "${file.name}" is empty`;
+ }
+
+ if (file.size > maxBytesPerFile) {
+ return `File "${file.name}" is larger than ${limits.maxFileSizeMb} MB`;
+ }
+
+ totalBytes += file.size;
+ }
+
+ if (totalBytes > maxTotalBytes) {
+ return `Total upload size exceeds the ${limits.maxTotalSizeMb} MB limit`;
+ }
+
+ return null;
+};