Skip to content

Self-improving AI Employees for everyone

feat(gallery): workspace file explorer with drag-to-parameter

trohitg449665138863
diff --git a/client/src/components/ParameterRenderer.tsx b/client/src/components/ParameterRenderer.tsx
index 86faa1f0..be617b45 100644
--- a/client/src/components/ParameterRenderer.tsx
+++ b/client/src/components/ParameterRenderer.tsx
@@ -34,6 +34,7 @@ import { AI_MODEL_PROVIDER_MAP } from '../lib/aiModelProviders';
import { resolveNodeDescription } from '../lib/nodeSpec';
import { uploadToWorkspace } from '../lib/workspaceUpload';
+import { WORKSPACE_FILE_DRAG_TYPE, isWorkspaceFileRef } from '../types/workspaceFiles';
/**
* Radix reserves the empty string to clear a Select, so raw node option
@@ -1229,6 +1230,21 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
onChange(parsedData.value);
return;
}
+ if (parsedData.type === WORKSPACE_FILE_DRAG_TYPE) {
+ // A `file` parameter holds exactly one reference, so it replaces.
+ // Everything else is text and must APPEND: dropping a file into a
+ // half-written prompt has to leave the prompt intact.
+ if (parameter.type === 'file' && parsedData.ref) {
+ onChange(parsedData.ref);
+ return;
+ }
+ // Guard the type — a `file` param's currentValue is an object, and
+ // the branches above would throw on `.endsWith` if one lands here.
+ const existingValue = typeof currentValue === 'string' ? currentValue : '';
+ const needsSpace = existingValue.length > 0 && !existingValue.endsWith(' ');
+ onChange(existingValue + (needsSpace ? ' ' : '') + parsedData.path);
+ return;
+ }
} catch (err) {
console.warn('Failed to parse JSON drag data:', err);
}
@@ -1676,7 +1692,11 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
};
const isUploadedFile = currentValue && typeof currentValue === 'object' && currentValue.type === 'upload';
- const isFileRef = currentValue && typeof currentValue === 'object' && currentValue.kind === 'audio';
+ // Every FileKind, not just 'audio': the gallery emits kind:"file"
+ // even for a .wav, because kind:"audio" asserts the container was
+ // probed. Narrowing this here would render a dragged file as a raw
+ // object instead of a chip.
+ const isFileRef = isWorkspaceFileRef(currentValue);
// Determine file accept type based on context (e.g., message_type for WhatsApp)
const getFileAcceptType = () => {
diff --git a/client/src/components/__tests__/ParameterRendererWorkspaceFileDrop.test.tsx b/client/src/components/__tests__/ParameterRendererWorkspaceFileDrop.test.tsx
new file mode 100644
index 00000000..e6a1264a
--- /dev/null
+++ b/client/src/components/__tests__/ParameterRendererWorkspaceFileDrop.test.tsx
@@ -0,0 +1,151 @@
+import { fireEvent, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders as render } from '../../test/providers';
+import type { WorkspaceFileDragPayload } from '../../types/workspaceFiles';
+
+const { wsMock, apiKeysMock } = vi.hoisted(() => ({
+ wsMock: {
+ getNodeParameters: vi.fn().mockResolvedValue({}),
+ sendRequest: vi.fn().mockResolvedValue({ success: true }),
+ getWhatsAppGroups: vi.fn().mockResolvedValue([]),
+ getWhatsAppGroupInfo: vi.fn().mockResolvedValue(null),
+ getWhatsAppChannels: vi.fn().mockResolvedValue([]),
+ },
+ apiKeysMock: {
+ getStoredApiKey: vi.fn().mockResolvedValue(null),
+ hasStoredKey: vi.fn().mockReturnValue(false),
+ getStoredModels: vi.fn().mockResolvedValue([]),
+ getProviderDefaults: vi.fn().mockResolvedValue(null),
+ },
+}));
+vi.mock('../../contexts/WebSocketContext', () => ({ useWebSocket: () => wsMock }));
+vi.mock('../../hooks/useApiKeys', () => ({ useApiKeys: () => apiKeysMock }));
+
+import ParameterRenderer from '../ParameterRenderer';
+
+const payload: WorkspaceFileDragPayload = {
+ type: 'workspaceFile',
+ path: 'audio/greeting.wav',
+ ref: {
+ kind: 'file',
+ path: 'audio/greeting.wav',
+ workflow_id: 'wf-1',
+ filename: 'greeting.wav',
+ mime_type: 'audio/wav',
+ size_bytes: 20844,
+ modified_at: '2026-07-25T22:47:10',
+ url: '/api/workspace/wf-1/files/audio/greeting.wav',
+ },
+};
+
+/** A dataTransfer that answers only the MIME types actually provided. */
+const transfer = (data: Record<string, string>) => ({
+ getData: (type: string) => data[type] ?? '',
+ setData: vi.fn(),
+ dropEffect: 'copy',
+ effectAllowed: 'copy',
+ types: Object.keys(data),
+});
+
+const dropOn = (element: Element, data: Record<string, string>) =>
+ fireEvent.drop(element, { dataTransfer: transfer(data) });
+
+const jsonPayload = { 'application/json': JSON.stringify(payload), 'text/plain': payload.path };
+
+describe('ParameterRenderer — workspace file drop', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('assigns the whole reference to a file parameter', () => {
+ const onChange = vi.fn();
+ render(
+ <ParameterRenderer
+ parameter={{ displayName: 'Audio', name: 'audio_file', type: 'file' } as any}
+ value=""
+ onChange={onChange}
+ />,
+ );
+
+ dropOn(screen.getByPlaceholderText('Enter file path or upload'), jsonPayload);
+
+ expect(onChange).toHaveBeenCalledWith(payload.ref);
+ });
+
+ it('appends the path to a text parameter instead of replacing it', () => {
+ const onChange = vi.fn();
+ render(
+ <ParameterRenderer
+ parameter={{ displayName: 'Prompt', name: 'prompt', type: 'string' } as any}
+ value="Transcribe"
+ onChange={onChange}
+ />,
+ );
+
+ dropOn(screen.getByRole('textbox'), jsonPayload);
+
+ // The headline guarantee: a half-written prompt survives the drop.
+ expect(onChange).toHaveBeenCalledWith('Transcribe audio/greeting.wav');
+ });
+
+ it('does not double-space when the text already ends in one', () => {
+ const onChange = vi.fn();
+ render(
+ <ParameterRenderer
+ parameter={{ displayName: 'Prompt', name: 'prompt', type: 'string' } as any}
+ value="Transcribe "
+ onChange={onChange}
+ />,
+ );
+
+ dropOn(screen.getByRole('textbox'), jsonPayload);
+
+ expect(onChange).toHaveBeenCalledWith('Transcribe audio/greeting.wav');
+ });
+
+ it('starts a bare text parameter with no leading space', () => {
+ const onChange = vi.fn();
+ render(
+ <ParameterRenderer
+ parameter={{ displayName: 'Prompt', name: 'prompt', type: 'string' } as any}
+ value=""
+ onChange={onChange}
+ />,
+ );
+
+ dropOn(screen.getByRole('textbox'), jsonPayload);
+
+ expect(onChange).toHaveBeenCalledWith('audio/greeting.wav');
+ });
+
+ it('ignores a bare path with no structured payload', () => {
+ const onChange = vi.fn();
+ render(
+ <ParameterRenderer
+ parameter={{ displayName: 'Prompt', name: 'prompt', type: 'string' } as any}
+ value=""
+ onChange={onChange}
+ />,
+ );
+
+ // Only `{{...}}` templates are accepted off text/plain; a naked path
+ // from an unrelated drag source must not silently rewrite a parameter.
+ dropOn(screen.getByRole('textbox'), { 'text/plain': 'audio/greeting.wav' });
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('renders a dropped reference as a named chip, not raw JSON', () => {
+ render(
+ <ParameterRenderer
+ parameter={{ displayName: 'Audio', name: 'audio_file', type: 'file' } as any}
+ value={payload.ref}
+ onChange={vi.fn()}
+ />,
+ );
+
+ // kind is "file", not "audio" — the pre-gallery check looked only for
+ // "audio" and would have fallen through to an empty input here.
+ expect(screen.getByDisplayValue('greeting.wav')).toBeInTheDocument();
+ expect(screen.getByText(/audio\/greeting\.wav/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/parameterPanel/GalleryPanel.tsx b/client/src/components/parameterPanel/GalleryPanel.tsx
new file mode 100644
index 00000000..456054bb
--- /dev/null
+++ b/client/src/components/parameterPanel/GalleryPanel.tsx
@@ -0,0 +1,483 @@
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ AlertTriangle,
+ ChevronRight,
+ FolderOpen,
+ Home,
+ LayoutGrid,
+ List,
+ Pin,
+ RefreshCw,
+ Search,
+ Upload,
+} from 'lucide-react';
+import { toast } from 'sonner';
+
+import { useWebSocket } from '@/contexts/WebSocketContext';
+import { ActionButton } from '@/components/ui/action-button';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Checkbox } from '@/components/ui/checkbox';
+import { buildApiUrl } from '@/config/api';
+import { uploadToWorkspace } from '@/lib/workspaceUpload';
+import { useDragWorkspaceFile } from '@/hooks/useDragWorkspaceFile';
+import type { ListWorkspaceFilesResponse, WorkspaceEntry } from '@/types/workspaceFiles';
+
+import FilePreviewDialog from './gallery/FilePreviewDialog';
+import FileGlyph from './gallery/FileGlyph';
+import { formatBytes, formatModified, glyphToneFor } from './gallery/fileIcons';
+
+interface Props {
+ workflowId?: string;
+ parameters: Record<string, any>;
+ onParameterChange: (name: string, value: any) => void;
+}
+
+const POLL_INTERVAL_MS = 5000;
+const SEARCH_DEBOUNCE_MS = 250;
+
+/** Directory of an uploaded file, so the panel can go to where it landed. */
+const parentOf = (path: string): string =>
+ path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
+
+const GalleryPanel: React.FC<Props> = ({ workflowId, parameters, onParameterChange }) => {
+ const { sendRequest } = useWebSocket();
+
+ // `path` and `selection` live on the node, not in local state: what you
+ // browse to is what the node lists when it runs, and what you pin is what
+ // it emits. One source of truth, so the panel can't drift from the node.
+ const path = typeof parameters.path === 'string' ? parameters.path : '';
+ // Memoised because the `[]` fallback is a fresh array every render, which
+ // would churn every dependency list that reads it.
+ const selection = useMemo<string[]>(
+ () => (Array.isArray(parameters.selection) ? parameters.selection : []),
+ [parameters.selection],
+ );
+ const selectionSet = useMemo(() => new Set(selection), [selection]);
+
+ const [entries, setEntries] = useState<WorkspaceEntry[]>([]);
+ const [crumbs, setCrumbs] = useState<Array<{ name: string; path: string }>>([]);
+ const [parent, setParent] = useState<string | null>(null);
+ const [truncated, setTruncated] = useState(false);
+ const [workspaceExists, setWorkspaceExists] = useState(true);
+ const [pathExists, setPathExists] = useState(true);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [view, setView] = useState<'grid' | 'list'>('grid');
+ const [search, setSearch] = useState('');
+ const [query, setQuery] = useState('');
+ const [preview, setPreview] = useState<WorkspaceEntry | null>(null);
+ const [uploading, setUploading] = useState(false);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const { handleFileDragStart } = useDragWorkspaceFile();
+ const searching = query.trim().length > 0;
+
+ useEffect(() => {
+ const timer = window.setTimeout(() => setQuery(search), SEARCH_DEBOUNCE_MS);
+ return () => window.clearTimeout(timer);
+ }, [search]);
+
+ const refresh = useCallback(async (quiet = false) => {
+ if (!workflowId) return;
+ if (!quiet) setLoading(true);
+ try {
+ const term = query.trim();
+ // The raw term goes over the wire; the server decides what searching
+ // for it means and which directories that spans.
+ const response = await sendRequest<ListWorkspaceFilesResponse>('list_workspace_files', {
+ workflow_id: workflowId,
+ path,
+ ...(term ? { search: term } : {}),
+ limit: 500,
+ });
+
+ if (!response.success) throw new Error(response.error || 'Could not read this workspace');
+
+ setEntries(response.entries ?? []);
+ setCrumbs(response.crumbs ?? []);
+ setParent(response.parent ?? null);
+ setTruncated(response.truncated ?? false);
+ // Absent on the glob branch, which never reports them — treat a search
+ // as always "inside" a workspace so it can't flash the empty-state.
+ setWorkspaceExists(response.workspace_exists ?? true);
+ setPathExists(response.path_exists ?? true);
+ setError(null);
+ } catch (caught) {
+ const message = caught instanceof Error ? caught.message : 'Could not read this workspace';
+ setError(message);
+ if (!quiet) toast.error(message);
+ } finally {
+ if (!quiet) setLoading(false);
+ }
+ }, [path, query, sendRequest, workflowId]);
+
+ useEffect(() => { void refresh(); }, [refresh]);
+
+ useEffect(() => {
+ const poll = window.setInterval(() => {
+ // A background tab has nothing to show, and a dialog or an in-flight
+ // upload would have the listing swapped out from under it.
+ if (document.visibilityState !== 'visible' || preview || uploading) return;
+ void refresh(true);
+ }, POLL_INTERVAL_MS);
+ return () => window.clearInterval(poll);
+ }, [preview, refresh, uploading]);
+
+ const navigate = useCallback((next: string) => {
+ setSearch('');
+ setQuery('');
+ onParameterChange('path', next);
+ }, [onParameterChange]);
+
+ const togglePin = useCallback((entry: WorkspaceEntry) => {
+ const next = selectionSet.has(entry.path)
+ ? selection.filter((item) => item !== entry.path)
+ : [...selection, entry.path];
+ onParameterChange('selection', next);
+ }, [onParameterChange, selection, selectionSet]);
+
+ const handleUpload = useCallback(async (files: FileList | null) => {
+ if (!files?.length || !workflowId) return;
+ setUploading(true);
+ try {
+ let landedIn: string | null = null;
+ for (const file of Array.from(files)) {
+ const ref = await uploadToWorkspace(file, workflowId);
+ landedIn = parentOf(ref.path);
+ }
+ toast.success(files.length === 1 ? `Uploaded ${files[0].name}` : `Uploaded ${files.length} files`);
+ // Uploads always land in the workspace's uploads/ directory, not the
+ // folder being browsed — so go there, or the file appears to vanish.
+ if (landedIn !== null && landedIn !== path) navigate(landedIn);
+ else await refresh(true);
+ } catch (caught) {
+ toast.error(caught instanceof Error ? caught.message : 'Upload failed');
+ } finally {
+ setUploading(false);
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ }
+ }, [navigate, path, refresh, workflowId]);
+
+ const visible = useMemo(() => {
+ // The backend already filtered a search; this only narrows a plain listing.
+ if (searching) return entries;
+ const term = search.trim().toLowerCase();
+ return term ? entries.filter((entry) => entry.name.toLowerCase().includes(term)) : entries;
+ }, [entries, search, searching]);
+
+ const fileCount = visible.filter((entry) => !entry.is_dir).length;
+
+ const openEntry = useCallback((entry: WorkspaceEntry) => {
+ if (entry.is_dir) navigate(entry.path);
+ else setPreview(entry);
+ }, [navigate]);
+
+ const emptyMessage = !workflowId
+ ? 'Save this workflow to give it a workspace.'
+ : !workspaceExists
+ ? 'No workspace yet. Run a node that writes a file — a download, a recording, a report — and it will appear here.'
+ : !pathExists
+ ? 'This folder no longer exists.'
+ : searching
+ ? 'Nothing in this workspace matches that search.'
+ : search.trim()
+ ? 'Nothing here matches that filter.'
+ : 'This folder is empty.';
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden p-4">
+ <header className="mb-3 flex shrink-0 items-start justify-between gap-3">
+ <div>
+ <h2 className="text-lg font-semibold text-fg-default">Workspace Files</h2>
+ <p className="text-sm text-fg-muted">
+ Everything this workflow has produced. Drag a file onto another node&apos;s parameter to use it.
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ className="hidden"
+ onChange={(event) => void handleUpload(event.target.files)}
+ />
+ <ActionButton
+ intent="save"
+ disabled={!workflowId || uploading}
+ onClick={() => fileInputRef.current?.click()}
+ title={workflowId ? 'Upload files into this workspace' : 'Save the workflow first'}
+ >
+ <Upload className="h-4 w-4" />
+ {uploading ? 'Uploading…' : 'Upload'}
+ </ActionButton>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={loading || !workflowId}
+ onClick={() => void refresh()}
+ aria-label="Refresh workspace files"
+ >
+ <RefreshCw className={loading ? 'h-4 w-4 animate-spin' : 'h-4 w-4'} /> Refresh
+ </Button>
+ </div>
+ </header>
+
+ <div className="mb-3 flex shrink-0 flex-wrap items-center gap-2">
+ <nav aria-label="Workspace path" className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="shrink-0 px-2"
+ onClick={() => navigate('')}
+ aria-label="Workspace root"
+ >
+ <Home className="h-4 w-4" />
+ </Button>
+ {crumbs.map((crumb, index) => (
+ <React.Fragment key={crumb.path}>
+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-fg-faint" />
+ <Button
+ variant="ghost"
+ size="sm"
+ className={`shrink-0 px-2 ${index === crumbs.length - 1 ? 'text-fg-default' : 'text-fg-muted'}`}
+ onClick={() => navigate(crumb.path)}
+ >
+ {crumb.name}
+ </Button>
+ </React.Fragment>
+ ))}
+ {searching && (
+ <>
+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-fg-faint" />
+ <span className="shrink-0 px-2 text-sm text-fg-default">Search results</span>
+ </>
+ )}
+ </nav>
+
+ <div className="relative w-56 shrink-0">
+ <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-fg-muted" />
+ <Input
+ className="pl-9"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ placeholder="Search this workspace"
+ aria-label="Search this workspace"
+ />
+ </div>
+
+ <div className="flex shrink-0 items-center rounded border border-border-default">
+ <Button
+ variant={view === 'grid' ? 'secondary' : 'ghost'}
+ size="sm"
+ className="rounded-r-none"
+ onClick={() => setView('grid')}
+ aria-label="Grid view"
+ aria-pressed={view === 'grid'}
+ >
+ <LayoutGrid className="h-4 w-4" />
+ </Button>
+ <Button
+ variant={view === 'list' ? 'secondary' : 'ghost'}
+ size="sm"
+ className="rounded-l-none"
+ onClick={() => setView('list')}
+ aria-label="List view"
+ aria-pressed={view === 'list'}
+ >
+ <List className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+
+ {error && (
+ <div className="mb-3 flex shrink-0 items-center gap-2 rounded border border-destructive bg-bg-elevated px-3 py-2 text-xs text-destructive">
+ <AlertTriangle className="h-4 w-4 shrink-0" /> {error}
+ </div>
+ )}
+
+ <div className="min-h-0 flex-1 overflow-auto rounded border border-border-default bg-bg-elevated p-3">
+ {visible.length === 0 ? (
+ <div className="flex h-full flex-col items-center justify-center gap-3 py-12 text-center">
+ <FolderOpen className="h-10 w-10 text-fg-faint" />
+ <p className="max-w-sm text-sm text-fg-muted">{emptyMessage}</p>
+ {!pathExists && workspaceExists && parent !== null && (
+ <Button variant="outline" size="sm" onClick={() => navigate(parent)}>
+ Go up
+ </Button>
+ )}
+ </div>
+ ) : view === 'grid' ? (
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(8.5rem,1fr))] gap-3">
+ {visible.map((entry) => (
+ <GridTile
+ key={entry.path}
+ entry={entry}
+ pinned={selectionSet.has(entry.path)}
+ showFullPath={searching}
+ onOpen={openEntry}
+ onTogglePin={togglePin}
+ onDragStart={handleFileDragStart}
+ />
+ ))}
+ </div>
+ ) : (
+ <table className="w-full border-collapse text-sm">
+ <thead className="text-left text-xs text-fg-muted">
+ <tr>
+ {['', 'Name', 'Size', 'Modified', 'Type'].map((label, index) => (
+ <th key={label || index} className="border-b border-border-default px-3 py-2 font-medium">
+ {label}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {visible.map((entry) => (
+ <ListRow
+ key={entry.path}
+ entry={entry}
+ pinned={selectionSet.has(entry.path)}
+ showFullPath={searching}
+ onOpen={openEntry}
+ onTogglePin={togglePin}
+ onDragStart={handleFileDragStart}
+ />
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+
+ <footer className="mt-2 flex shrink-0 flex-wrap items-center gap-x-4 gap-y-1 text-xs text-fg-muted">
+ <span>{fileCount} {fileCount === 1 ? 'file' : 'files'}{visible.length !== fileCount ? ` · ${visible.length - fileCount} folders` : ''}</span>
+ {selection.length > 0 && (
+ <span className="flex items-center gap-1 text-fg-default">
+ <Pin className="h-3 w-3" /> {selection.length} pinned for this node&apos;s output
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-auto px-1 py-0 text-xs"
+ onClick={() => onParameterChange('selection', [])}
+ >
+ clear
+ </Button>
+ </span>
+ )}
+ {truncated && (
+ <span className="flex items-center gap-1 text-warning">
+ <AlertTriangle className="h-3 w-3" /> Showing the first {visible.length} — narrow with search.
+ </span>
+ )}
+ </footer>
+
+ <FilePreviewDialog entry={preview} onOpenChange={(open) => { if (!open) setPreview(null); }} />
+ </div>
+ );
+};
+
+interface RowProps {
+ entry: WorkspaceEntry;
+ pinned: boolean;
+ showFullPath: boolean;
+ onOpen: (entry: WorkspaceEntry) => void;
+ onTogglePin: (entry: WorkspaceEntry) => void;
+ onDragStart: (event: React.DragEvent, entry: WorkspaceEntry) => void;
+}
+
+const GridTile: React.FC<RowProps> = ({ entry, pinned, showFullPath, onOpen, onTogglePin, onDragStart }) => {
+ const [thumbFailed, setThumbFailed] = useState(false);
+ const showThumb = entry.preview === 'image' && !!entry.url && !thumbFailed;
+
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ draggable={!entry.is_dir}
+ onDragStart={(event) => onDragStart(event, entry)}
+ onClick={() => onOpen(entry)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ onOpen(entry);
+ }
+ }}
+ title={entry.path}
+ className="group relative flex cursor-pointer flex-col gap-2 rounded border border-border-default bg-bg-panel p-2 text-left transition-colors hover:border-border-strong hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus"
+ >
+ <div className="flex aspect-square items-center justify-center overflow-hidden rounded bg-bg-app">
+ {showThumb ? (
+ <img
+ src={buildApiUrl(entry.url as string)}
+ alt={entry.name}
+ loading="lazy"
+ draggable={false}
+ onError={() => setThumbFailed(true)}
+ className="h-full w-full object-cover"
+ />
+ ) : (
+ <FileGlyph entry={entry} className={`h-8 w-8 ${glyphToneFor(entry)}`} />
+ )}
+ </div>
+
+ <div className="min-w-0">
+ <div className="truncate text-xs font-medium text-fg-default">{entry.name}</div>
+ <div className="truncate text-[11px] text-fg-muted">
+ {showFullPath ? entry.path : entry.is_dir ? 'Folder' : formatBytes(entry.size_bytes)}
+ </div>
+ </div>
+
+ {!entry.is_dir && (
+ <div
+ className={pinned ? 'absolute right-2 top-2' : 'absolute right-2 top-2 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100'}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <Checkbox
+ checked={pinned}
+ onCheckedChange={() => onTogglePin(entry)}
+ aria-label={`Pin ${entry.name} to this node's output`}
+ />
+ </div>
+ )}
+ </div>
+ );
+};
+
+const ListRow: React.FC<RowProps> = ({ entry, pinned, showFullPath, onOpen, onTogglePin, onDragStart }) => {
+ return (
+ <tr
+ draggable={!entry.is_dir}
+ onDragStart={(event) => onDragStart(event, entry)}
+ onClick={() => onOpen(entry)}
+ title={entry.path}
+ className="cursor-pointer border-b border-border-default hover:bg-bg-hover"
+ >
+ <td className="px-3 py-2" onClick={(event) => event.stopPropagation()}>
+ {!entry.is_dir && (
+ <Checkbox
+ checked={pinned}
+ onCheckedChange={() => onTogglePin(entry)}
+ aria-label={`Pin ${entry.name} to this node's output`}
+ />
+ )}
+ </td>
+ <td className="max-w-0 px-3 py-2">
+ <div className="flex items-center gap-2">
+ <FileGlyph entry={entry} className={`h-4 w-4 shrink-0 ${glyphToneFor(entry)}`} />
+ <span className="truncate text-fg-default">{showFullPath ? entry.path : entry.name}</span>
+ </div>
+ </td>
+ <td className="whitespace-nowrap px-3 py-2 tabular-nums text-fg-muted">
+ {formatBytes(entry.size_bytes, entry.is_dir)}
+ </td>
+ <td className="whitespace-nowrap px-3 py-2 text-xs text-fg-muted">
+ {formatModified(entry.modified_at)}
+ </td>
+ <td className="max-w-[14rem] truncate px-3 py-2 text-xs text-fg-muted">
+ {entry.is_dir ? 'Folder' : entry.mime_type || 'unknown'}
+ </td>
+ </tr>
+ );
+};
+
+export default GalleryPanel;
diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsx
index 0de4caca..6959caa2 100644
--- a/client/src/components/parameterPanel/MiddleSection.tsx
+++ b/client/src/components/parameterPanel/MiddleSection.tsx
@@ -32,6 +32,7 @@ import TodoEditor from './TodoEditor';
import TaskManagerPanel from './TaskManagerPanel';
import TeamMonitorPanel from './TeamMonitorPanel';
import ProcessManagerPanel from './ProcessManagerPanel';
+import GalleryPanel from './GalleryPanel';
import { useAppStore } from '../../store/useAppStore';
import { useNodeStatus, useWebSocket, CompactionStats } from '../../contexts/WebSocketContext';
import { useUserSettingsQuery } from '../../hooks/useUserSettingsQuery';
@@ -199,6 +200,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
const isTaskManagerNode = hints.isTaskManagerPanel === true;
const isMonitorNode = hints.isMonitorPanel === true;
const isProcessManagerNode = hints.isProcessManagerPanel === true;
+ const isGalleryNode = hints.isGalleryPanel === true;
const isAgentWithSkills = hints.hasSkills === true;
const { data: userSettings } = useUserSettingsQuery();
@@ -538,7 +540,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
<div className="relative flex h-full flex-1 flex-col overflow-hidden">
{/* Description - hide for code editor nodes (Python, Skill), masterSkill,
and the todo editor (each renders its own full-panel header). */}
- {!needsCodeEditorLayout && !isMasterSkillNode && !isTodoEditorNode && !isTaskManagerNode && !isMonitorNode && !isProcessManagerNode && (
+ {!needsCodeEditorLayout && !isMasterSkillNode && !isTodoEditorNode && !isTaskManagerNode && !isMonitorNode && !isProcessManagerNode && !isGalleryNode && (
<div className="shrink-0 border-b border-border-default bg-bg-panel px-6 pt-4 pb-2">
<p className="m-0 text-base leading-[1.5] text-fg-muted">
{nodeDefinition.description}
@@ -577,6 +579,15 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
/>
) : isProcessManagerNode ? (
<ProcessManagerPanel workflowId={currentWorkflow?.id} />
+ ) : isGalleryNode ? (
+ // The panel edits the node's own params: browsing sets `path`,
+ // pinning sets `selection`. So it replaces the generic list
+ // rather than sitting alongside a second, drifting copy of it.
+ <GalleryPanel
+ workflowId={currentWorkflow?.id}
+ parameters={parameters}
+ onParameterChange={onParameterChange}
+ />
) : (
<>
{/* Parameters */}
diff --git a/client/src/components/parameterPanel/__tests__/GalleryPanel.test.tsx b/client/src/components/parameterPanel/__tests__/GalleryPanel.test.tsx
new file mode 100644
index 00000000..de83b0c2
--- /dev/null
+++ b/client/src/components/parameterPanel/__tests__/GalleryPanel.test.tsx
@@ -0,0 +1,162 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders as render } from '../../../test/providers';
+import type { WorkspaceEntry } from '../../../types/workspaceFiles';
+
+const { wsMock } = vi.hoisted(() => ({ wsMock: { sendRequest: vi.fn() } }));
+vi.mock('../../../contexts/WebSocketContext', () => ({ useWebSocket: () => wsMock }));
+
+import GalleryPanel from '../GalleryPanel';
+
+const dir = (name: string): WorkspaceEntry => ({
+ name, path: name, is_dir: true, size_bytes: 0,
+ modified_at: '2026-07-20T10:00:00', mime_type: null, url: null,
+ preview: 'none', ref: null,
+});
+
+// Mirrors what the server sends: the ref and the preview verdict arrive
+// with the row, so the panel never derives either.
+const file = (path: string, mime = 'audio/wav'): WorkspaceEntry => {
+ const name = path.split('/').pop() as string;
+ const url = `/api/workspace/wf-1/files/${path}`;
+ return {
+ name,
+ path,
+ is_dir: false,
+ size_bytes: 20844,
+ modified_at: '2026-07-25T22:47:10',
+ mime_type: mime,
+ url,
+ preview: 'audio',
+ ref: {
+ kind: 'file', path, workflow_id: 'wf-1', filename: name,
+ mime_type: mime, size_bytes: 20844,
+ modified_at: '2026-07-25T22:47:10', url,
+ },
+ };
+};
+
+const listing = (entries: WorkspaceEntry[], extra: Record<string, unknown> = {}) => ({
+ success: true, workflow_id: 'wf-1', path: '', parent: null, crumbs: [],
+ entries, count: entries.length, truncated: false,
+ workspace_exists: true, path_exists: true, ...extra,
+});
+
+const noop = () => {};
+
+describe('GalleryPanel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ wsMock.sendRequest.mockResolvedValue(listing([dir('audio'), file('greeting.wav')]));
+ });
+
+ it('lists the workspace and shows a size for files but not folders', async () => {
+ render(<GalleryPanel workflowId="wf-1" parameters={{}} onParameterChange={noop} />);
+
+ expect(await screen.findByText('greeting.wav')).toBeInTheDocument();
+ expect(screen.getByText('audio')).toBeInTheDocument();
+ expect(screen.getByText('20 KB')).toBeInTheDocument();
+ expect(screen.getByText('Folder')).toBeInTheDocument();
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('list_workspace_files', {
+ workflow_id: 'wf-1', path: '', limit: 500,
+ });
+ });
+
+ it('writes the node path when a folder is opened, so the node lists what you browse', async () => {
+ const onParameterChange = vi.fn();
+ render(<GalleryPanel workflowId="wf-1" parameters={{}} onParameterChange={onParameterChange} />);
+
+ fireEvent.click(await screen.findByText('audio'));
+
+ expect(onParameterChange).toHaveBeenCalledWith('path', 'audio');
+ });
+
+ it('renders the breadcrumb trail the server computed', async () => {
+ wsMock.sendRequest.mockResolvedValue(listing([file('audio/clips/one.wav')], {
+ path: 'audio/clips',
+ parent: 'audio',
+ crumbs: [{ name: 'audio', path: 'audio' }, { name: 'clips', path: 'audio/clips' }],
+ }));
+ render(<GalleryPanel workflowId="wf-1" parameters={{ path: 'audio/clips' }} onParameterChange={noop} />);
+
+ await waitFor(() => expect(wsMock.sendRequest).toHaveBeenCalledWith('list_workspace_files', {
+ workflow_id: 'wf-1', path: 'audio/clips', limit: 500,
+ }));
+ // Not re-split from `path` here — the trail arrives ready to render.
+ expect(await screen.findByRole('button', { name: 'audio' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'clips' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Workspace root' })).toBeInTheDocument();
+ });
+
+ it('pins a file into `selection` and unpins it again', async () => {
+ const onParameterChange = vi.fn();
+ const { rerender } = render(
+ <GalleryPanel workflowId="wf-1" parameters={{}} onParameterChange={onParameterChange} />,
+ );
+
+ fireEvent.click(await screen.findByRole('checkbox', { name: /Pin greeting\.wav/ }));
+ expect(onParameterChange).toHaveBeenCalledWith('selection', ['greeting.wav']);
+
+ rerender(
+ <GalleryPanel
+ workflowId="wf-1"
+ parameters={{ selection: ['greeting.wav'] }}
+ onParameterChange={onParameterChange}
+ />,
+ );
+ fireEvent.click(await screen.findByRole('checkbox', { name: /Pin greeting\.wav/ }));
+ expect(onParameterChange).toHaveBeenLastCalledWith('selection', []);
+ });
+
+ it('never calls the backend without a workflow, and says why', async () => {
+ render(<GalleryPanel parameters={{}} onParameterChange={noop} />);
+
+ expect(await screen.findByText(/Save this workflow to give it a workspace/)).toBeInTheDocument();
+ expect(wsMock.sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('distinguishes "no workspace yet" from "empty folder"', async () => {
+ wsMock.sendRequest.mockResolvedValue(listing([], { workspace_exists: false }));
+ const { unmount } = render(
+ <GalleryPanel workflowId="wf-1" parameters={{}} onParameterChange={noop} />,
+ );
+ expect(await screen.findByText(/No workspace yet/)).toBeInTheDocument();
+ unmount();
+
+ wsMock.sendRequest.mockResolvedValue(listing([]));
+ render(<GalleryPanel workflowId="wf-1" parameters={{}} onParameterChange={noop} />);
+ expect(await screen.findByText('This folder is empty.')).toBeInTheDocument();
+ });
+
+ it('surfaces a failed listing instead of showing an empty workspace', async () => {
+ wsMock.sendRequest.mockResolvedValue({ success: false, error: 'outside this workflow' });
+ render(<GalleryPanel workflowId="wf-1" parameters={{}} onParameterChange={noop} />);
+
+ expect(await screen.findByText('outside this workflow')).toBeInTheDocument();
+ });
+
+ it('sends the raw search term and lets the server decide what it means', async () => {
+ render(<GalleryPanel workflowId="wf-1" parameters={{ path: 'audio' }} onParameterChange={noop} />);
+ await screen.findByText('greeting.wav');
+
+ fireEvent.change(screen.getByLabelText('Search this workspace'), { target: { value: 'greet' } });
+
+ // No glob is assembled here: term-to-pattern is `search_to_pattern` on
+ // the server, so the node and the panel cannot disagree about it.
+ await waitFor(() => expect(wsMock.sendRequest).toHaveBeenCalledWith('list_workspace_files', {
+ workflow_id: 'wf-1', path: 'audio', search: 'greet', limit: 500,
+ }));
+ });
+
+ it('makes files draggable and folders not', async () => {
+ render(<GalleryPanel workflowId="wf-1" parameters={{}} onParameterChange={noop} />);
+ await screen.findByText('greeting.wav');
+
+ const tileOf = (label: string) =>
+ screen.getByText(label).closest('[role="button"]') as HTMLElement;
+
+ expect(tileOf('greeting.wav')).toHaveAttribute('draggable', 'true');
+ expect(tileOf('audio')).toHaveAttribute('draggable', 'false');
+ });
+});
diff --git a/client/src/components/parameterPanel/gallery/FileGlyph.tsx b/client/src/components/parameterPanel/gallery/FileGlyph.tsx
new file mode 100644
index 00000000..ced95f15
--- /dev/null
+++ b/client/src/components/parameterPanel/gallery/FileGlyph.tsx
@@ -0,0 +1,27 @@
+import { createElement } from 'react';
+
+import type { WorkspaceEntry } from '@/types/workspaceFiles';
+
+import { glyphFor } from './fileIcons';
+
+/**
+ * Renders the icon for a workspace entry.
+ *
+ * A component rather than `const Glyph = glyphFor(entry)` at each call
+ * site: binding a component to a capitalized local during render trips
+ * `react-hooks/static-components`, because in the general case such an
+ * identity churns and resets state. Resolving inside a module-scope
+ * component keeps every call site clean and lint-honest.
+ *
+ * It lives in its own file so `fileIcons` stays a pure helper module —
+ * a file that exports both components and helpers breaks Fast Refresh.
+ */
+export const FileGlyph = ({
+ entry,
+ className,
+}: {
+ entry: WorkspaceEntry;
+ className?: string;
+}) => createElement(glyphFor(entry), { className });
+
+export default FileGlyph;
diff --git a/client/src/components/parameterPanel/gallery/FilePreviewDialog.tsx b/client/src/components/parameterPanel/gallery/FilePreviewDialog.tsx
new file mode 100644
index 00000000..19e62420
--- /dev/null
+++ b/client/src/components/parameterPanel/gallery/FilePreviewDialog.tsx
@@ -0,0 +1,106 @@
+import React, { useEffect, useState } from 'react';
+import { AlertCircle, Download } from 'lucide-react';
+
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import { Button } from '@/components/ui/button';
+import { buildApiUrl } from '@/config/api';
+import type { WorkspaceEntry } from '@/types/workspaceFiles';
+
+import FileGlyph from './FileGlyph';
+import { formatBytes, formatModified, glyphToneFor } from './fileIcons';
+
+interface Props {
+ entry: WorkspaceEntry | null;
+ onOpenChange: (open: boolean) => void;
+}
+
+const FilePreviewDialog: React.FC<Props> = ({ entry, onOpenChange }) => {
+ const [failed, setFailed] = useState(false);
+
+ // A new file gets a fresh chance to load; without this a single failure
+ // would poison every subsequent preview in the same dialog instance.
+ useEffect(() => { setFailed(false); }, [entry?.path]);
+
+ if (!entry) return null;
+
+ const kind = entry.preview;
+ const src = entry.url ? buildApiUrl(entry.url) : null;
+
+ return (
+ <Dialog open onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-3xl">
+ <DialogHeader>
+ <DialogTitle className="truncate font-mono text-sm">{entry.name}</DialogTitle>
+ </DialogHeader>
+
+ <div className="flex min-h-0 flex-col gap-3">
+ <div className="flex items-center justify-center rounded border border-border-default bg-bg-panel p-3">
+ {!src || failed || kind === 'none' ? (
+ // Three different reasons converge on one honest panel: no URL
+ // (unsaved workflow), a load failure (cleaned up, or an expired
+ // session surfacing as a silent `error` event), or a type the
+ // server refuses to serve inline.
+ <div className="flex flex-col items-center gap-2 py-10 text-center">
+ <FileGlyph entry={entry} className={`h-10 w-10 ${glyphToneFor(entry)}`} />
+ <p className="flex items-center gap-2 text-xs text-fg-muted">
+ {failed && <AlertCircle className="h-3.5 w-3.5 shrink-0 text-destructive" />}
+ {failed
+ ? 'Could not load this file. It may have been removed, or the session expired.'
+ : !src
+ ? 'Save and run this workflow to give its files a stable address.'
+ : 'No inline preview for this file type.'}
+ </p>
+ </div>
+ ) : kind === 'image' ? (
+ <img
+ src={src}
+ alt={entry.name}
+ onError={() => setFailed(true)}
+ className="max-h-[55vh] w-auto max-w-full rounded object-contain"
+ />
+ ) : kind === 'audio' ? (
+ <audio
+ controls
+ preload="metadata"
+ src={src}
+ onError={() => setFailed(true)}
+ className="w-full"
+ />
+ ) : (
+ <video
+ controls
+ preload="metadata"
+ src={src}
+ onError={() => setFailed(true)}
+ className="max-h-[55vh] w-full rounded"
+ />
+ )}
+ </div>
+
+ <div className="flex items-end justify-between gap-4">
+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs">
+ <dt className="text-fg-muted">Path</dt>
+ <dd className="break-all font-mono text-fg-default">{entry.path}</dd>
+ <dt className="text-fg-muted">Type</dt>
+ <dd className="text-fg-default">{entry.mime_type || 'unknown'}</dd>
+ <dt className="text-fg-muted">Size</dt>
+ <dd className="text-fg-default">{formatBytes(entry.size_bytes, entry.is_dir)}</dd>
+ <dt className="text-fg-muted">Modified</dt>
+ <dd className="text-fg-default">{formatModified(entry.modified_at)}</dd>
+ </dl>
+
+ {src && (
+ <Button asChild variant="outline" size="sm">
+ <a href={src} download={entry.name} target="_blank" rel="noreferrer">
+ <Download className="h-4 w-4" /> Download
+ </a>
+ </Button>
+ )}
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export default FilePreviewDialog;
diff --git a/client/src/components/parameterPanel/gallery/fileIcons.tsx b/client/src/components/parameterPanel/gallery/fileIcons.tsx
new file mode 100644
index 00000000..ab474d6d
--- /dev/null
+++ b/client/src/components/parameterPanel/gallery/fileIcons.tsx
@@ -0,0 +1,104 @@
+import type { LucideIcon } from 'lucide-react';
+import {
+ File as FileGlyphIcon,
+ FileArchive,
+ FileAudio,
+ FileCode,
+ FileImage,
+ FileJson,
+ FileSpreadsheet,
+ FileText,
+ FileVideo,
+ Folder,
+} from 'lucide-react';
+
+import type { WorkspaceEntry } from '@/types/workspaceFiles';
+
+/**
+ * Presentation only.
+ *
+ * Which glyph and which tint — nothing here decides what a file *is*. The
+ * row already carries `preview` (the server's inline-rendering verdict) and
+ * `mime_type`; this module just picks pixels for them. Anything that would
+ * amount to re-classifying a file belongs in
+ * `server/nodes/filesystem/gallery/_service.py`.
+ */
+
+const extensionOf = (name: string): string => {
+ const dot = name.lastIndexOf('.');
+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
+};
+
+const EXTENSION_GLYPH: Record<string, LucideIcon> = {
+ json: FileJson, jsonl: FileJson,
+ csv: FileSpreadsheet, tsv: FileSpreadsheet, xlsx: FileSpreadsheet, xls: FileSpreadsheet,
+ zip: FileArchive, gz: FileArchive, tar: FileArchive, tgz: FileArchive,
+ rar: FileArchive, '7z': FileArchive,
+ py: FileCode, js: FileCode, jsx: FileCode, ts: FileCode, tsx: FileCode,
+ sh: FileCode, ps1: FileCode, rb: FileCode, go: FileCode, rs: FileCode,
+ java: FileCode, c: FileCode, cpp: FileCode, h: FileCode, sql: FileCode,
+ html: FileCode, css: FileCode, xml: FileCode, yaml: FileCode, yml: FileCode,
+ toml: FileCode,
+ md: FileText, txt: FileText, log: FileText, pdf: FileText, rtf: FileText,
+};
+
+/** The glyph for a row. Directories always win over any extension match. */
+export const glyphFor = (entry: WorkspaceEntry): LucideIcon => {
+ if (entry.is_dir) return Folder;
+
+ switch (entry.preview) {
+ case 'image': return FileImage;
+ case 'audio': return FileAudio;
+ case 'video': return FileVideo;
+ default: break;
+ }
+
+ // preview === 'none' still covers media the route refuses to serve
+ // inline — an SVG is a picture even though it will never render here.
+ const mime = entry.mime_type || '';
+ if (mime.startsWith('image/')) return FileImage;
+ if (mime.startsWith('audio/')) return FileAudio;
+ if (mime.startsWith('video/')) return FileVideo;
+ if (mime.startsWith('text/')) return FileText;
+
+ return EXTENSION_GLYPH[extensionOf(entry.name)] ?? FileGlyphIcon;
+};
+
+/**
+ * Tints the glyph by role using node-role tokens, so every theme restyles
+ * the explorer without touching this file. No palette names, no opacity
+ * arithmetic — see CLAUDE.md "Frontend Design + Theme System (strict)".
+ */
+export const glyphToneFor = (entry: WorkspaceEntry): string => {
+ if (entry.is_dir) return 'text-node-workflow';
+ switch (entry.preview) {
+ case 'image': return 'text-node-agent';
+ case 'audio': return 'text-node-model';
+ case 'video': return 'text-node-trigger';
+ default: return 'text-fg-muted';
+ }
+};
+
+/** Human byte size. Directories report nothing rather than a misleading 0 B. */
+export const formatBytes = (bytes: number, isDir = false): string => {
+ if (isDir) return '—';
+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
+ const exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
+ const value = bytes / 1024 ** exponent;
+ return `${exponent === 0 ? value : value.toFixed(value < 10 ? 1 : 0)} ${units[exponent]}`;
+};
+
+/**
+ * Locale-aware timestamp. `Intl` with an undefined locale follows the host,
+ * so this reads correctly on every platform without a format string.
+ */
+export const formatModified = (value: string | null): string => {
+ if (!value) return '—';
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) return '—';
+ return new Intl.DateTimeFormat(undefined, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ }).format(parsed);
+};
diff --git a/client/src/hooks/__tests__/useDragWorkspaceFile.test.ts b/client/src/hooks/__tests__/useDragWorkspaceFile.test.ts
new file mode 100644
index 00000000..5673c3e1
--- /dev/null
+++ b/client/src/hooks/__tests__/useDragWorkspaceFile.test.ts
@@ -0,0 +1,92 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useDragWorkspaceFile } from '../useDragWorkspaceFile';
+import type { WorkspaceEntry } from '../../types/workspaceFiles';
+
+function makeDragEvent() {
+ const setData = vi.fn();
+ const preventDefault = vi.fn();
+ const event = {
+ preventDefault,
+ dataTransfer: { setData, effectAllowed: '', getData: vi.fn() },
+ } as unknown as React.DragEvent;
+ return { event, setData, preventDefault };
+}
+
+const ref = {
+ kind: 'file' as const,
+ path: 'audio/greeting.wav',
+ workflow_id: 'wf-1',
+ filename: 'greeting.wav',
+ mime_type: 'audio/wav',
+ size_bytes: 20844,
+ modified_at: '2026-07-25T22:47:10',
+ url: '/api/workspace/wf-1/files/audio/greeting.wav',
+};
+
+const entry: WorkspaceEntry = {
+ name: 'greeting.wav',
+ path: 'audio/greeting.wav',
+ is_dir: false,
+ size_bytes: 20844,
+ modified_at: '2026-07-25T22:47:10',
+ mime_type: 'audio/wav',
+ url: '/api/workspace/wf-1/files/audio/greeting.wav',
+ preview: 'audio',
+ ref,
+};
+
+describe('useDragWorkspaceFile', () => {
+ it('carries a payload the drop handler can consume verbatim', () => {
+ const { result } = renderHook(() => useDragWorkspaceFile());
+ const { event, setData } = makeDragEvent();
+
+ result.current.handleFileDragStart(event, entry);
+
+ // Deep equality, not a shape check: a renamed key here silently breaks
+ // ParameterRenderer's drop branch with no type error on either side.
+ expect(JSON.parse(setData.mock.calls.find(([type]) => type === 'application/json')![1])).toEqual({
+ type: 'workspaceFile',
+ path: 'audio/greeting.wav',
+ // Forwarded exactly as the server sent it. Rebuilding the ref here
+ // would be a second, untyped copy of a Pydantic model that forbids
+ // unknown fields.
+ ref,
+ });
+ });
+
+ it('sets a plain-text fallback and a copy effect', () => {
+ const { result } = renderHook(() => useDragWorkspaceFile());
+ const { event, setData } = makeDragEvent();
+
+ result.current.handleFileDragStart(event, entry);
+
+ expect(setData).toHaveBeenCalledWith('text/plain', 'audio/greeting.wav');
+ expect(event.dataTransfer.effectAllowed).toBe('copy');
+ });
+
+ it('refuses to drag a directory', () => {
+ const { result } = renderHook(() => useDragWorkspaceFile());
+ const { event, setData, preventDefault } = makeDragEvent();
+
+ result.current.handleFileDragStart(event, {
+ ...entry, is_dir: true, path: 'audio', name: 'audio', ref: null, preview: 'none',
+ });
+
+ expect(setData).not.toHaveBeenCalled();
+ expect(preventDefault).toHaveBeenCalled();
+ });
+
+ it('refuses a row the server gave no reference for', () => {
+ const { result } = renderHook(() => useDragWorkspaceFile());
+ const { event, setData, preventDefault } = makeDragEvent();
+
+ // Rather than inventing one locally — exactly the coupling that moving
+ // ref construction to the server removed.
+ result.current.handleFileDragStart(event, { ...entry, ref: null });
+
+ expect(setData).not.toHaveBeenCalled();
+ expect(preventDefault).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/hooks/useDragWorkspaceFile.ts b/client/src/hooks/useDragWorkspaceFile.ts
new file mode 100644
index 00000000..1a5864f4
--- /dev/null
+++ b/client/src/hooks/useDragWorkspaceFile.ts
@@ -0,0 +1,47 @@
+import { useCallback } from 'react';
+
+import {
+ WORKSPACE_FILE_DRAG_TYPE,
+ type WorkspaceEntry,
+ type WorkspaceFileDragPayload,
+} from '@/types/workspaceFiles';
+
+interface DragWorkspaceFileHookReturn {
+ handleFileDragStart: (event: React.DragEvent, entry: WorkspaceEntry) => void;
+}
+
+/**
+ * Produces the drag payload for a workspace file.
+ *
+ * Mirrors `useDragVariable`: both MIME types are set — `application/json`
+ * carries the structured payload, `text/plain` carries a human-readable
+ * fallback so the path still lands when dropped on a plain <textarea> or an
+ * editor outside this app.
+ *
+ * The reference is not assembled here — the row arrives with a finished one
+ * from the server, which owns the `FileRef` model. Directories have none, so
+ * a directory is simply not draggable (and appending a bare folder path into
+ * a prompt was never what was meant anyway).
+ */
+export function useDragWorkspaceFile(): DragWorkspaceFileHookReturn {
+ const handleFileDragStart = useCallback((event: React.DragEvent, entry: WorkspaceEntry) => {
+ if (entry.is_dir || !entry.ref) {
+ event.preventDefault();
+ return;
+ }
+
+ const payload: WorkspaceFileDragPayload = {
+ type: WORKSPACE_FILE_DRAG_TYPE,
+ path: entry.path,
+ ref: entry.ref,
+ };
+
+ event.dataTransfer.setData('application/json', JSON.stringify(payload));
+ event.dataTransfer.setData('text/plain', entry.path);
+ event.dataTransfer.effectAllowed = 'copy';
+ }, []);
+
+ return { handleFileDragStart };
+}
+
+export default useDragWorkspaceFile;
diff --git a/client/src/types/workspaceFiles.ts b/client/src/types/workspaceFiles.ts
new file mode 100644
index 00000000..d8428d92
--- /dev/null
+++ b/client/src/types/workspaceFiles.ts
@@ -0,0 +1,116 @@
+/**
+ * Wire types for the workspace file explorer (the `gallery` node).
+ *
+ * Declarations only. Every decision these describe is made server-side:
+ * - `WorkspaceEntry` <- `server/nodes/filesystem/gallery/_service.py::_to_row`
+ * - `WorkspaceFileRef` <- `server/services/media/refs.py::FileRef`
+ *
+ * In particular the client does not build a `FileRef` (the row arrives with
+ * a finished one in `ref`), does not decide what is previewable (`preview`
+ * comes from the same function that sets the route's Content-Disposition),
+ * and does not translate a search term into a glob. Each of those would be
+ * a second copy of a server rule, and copies drift.
+ */
+
+/** What the workspace route will let a browser render in place. */
+export type PreviewKind = 'image' | 'audio' | 'video' | 'none';
+
+/** One entry in a directory listing. `path` is always workspace-relative. */
+export interface WorkspaceEntry {
+ name: string;
+ /**
+ * POSIX, workspace-relative, no leading slash ('audio/greeting.wav').
+ * Never OS-native: a leading slash reads as absolute on POSIX but not on
+ * Windows, so a native path would resolve on a Windows dev box and fail
+ * in production.
+ */
+ path: string;
+ is_dir: boolean;
+ /** 0 for directories, and for files whose stat() failed. */
+ size_bytes: number;
+ /** ISO 8601, or null when stat() failed. Advisory — not a cache key. */
+ modified_at: string | null;
+ /** null for directories. */
+ mime_type: string | null;
+ /** Path-only (no scheme/host); null for directories. Prefix via buildApiUrl. */
+ url: string | null;
+ /** Server's verdict on inline rendering. 'none' for directories. */
+ preview: PreviewKind;
+ /** Finished `FileRef`, ready to drop into a parameter. null for directories. */
+ ref: WorkspaceFileRef | null;
+}
+
+/** Every `kind` the backend's `FileKind` literal allows. */
+export const FILE_REF_KINDS = ['file', 'audio', 'image', 'video', 'document'] as const;
+export type FileRefKind = (typeof FILE_REF_KINDS)[number];
+
+/** A serialized `FileRef`. `AudioRef` is this plus probed audio fields. */
+export interface WorkspaceFileRef {
+ kind: FileRefKind;
+ path: string;
+ workflow_id?: string | null;
+ filename: string;
+ mime_type?: string;
+ size_bytes?: number;
+ modified_at?: string | null;
+ sha256?: string | null;
+ url?: string | null;
+}
+
+const KIND_SET: ReadonlySet<string> = new Set(FILE_REF_KINDS);
+
+/**
+ * Structural check for "this parameter value is a file reference".
+ *
+ * Deliberately accepts every `FileKind`, not just 'audio': the gallery emits
+ * `kind: "file"` even for a .wav, because `kind: "audio"` asserts the
+ * container was probed by `inspect_audio` and a fabricated duration would
+ * mis-bill a per-second provider downstream.
+ */
+export const isWorkspaceFileRef = (value: unknown): value is WorkspaceFileRef =>
+ !!value &&
+ typeof value === 'object' &&
+ KIND_SET.has((value as WorkspaceFileRef).kind) &&
+ typeof (value as WorkspaceFileRef).path === 'string' &&
+ typeof (value as WorkspaceFileRef).filename === 'string';
+
+/**
+ * Drag discriminator.
+ *
+ * Deliberately NOT the existing 'nodeOutput' — that handler replaces the
+ * target value unconditionally, so reusing it would mean dropping a file
+ * into a half-written prompt destroys the prompt.
+ */
+export const WORKSPACE_FILE_DRAG_TYPE = 'workspaceFile';
+
+export interface WorkspaceFileDragPayload {
+ type: typeof WORKSPACE_FILE_DRAG_TYPE;
+ /** For text params — appended as plain text. */
+ path: string;
+ /** For `file` params — assigned whole. */
+ ref: WorkspaceFileRef;
+}
+
+/**
+ * Response to `list_workspace_files`.
+ *
+ * The directory and glob branches return *different* key sets: only the
+ * directory branch carries `parent` / `workspace_exists` / `path_exists`,
+ * and only the glob branch carries `pattern`. Hence the wide optionality.
+ */
+export interface ListWorkspaceFilesResponse {
+ success: boolean;
+ error?: string;
+ workflow_id?: string;
+ path?: string;
+ parent?: string | null;
+ /** Breadcrumb trail for `path`, root excluded. Directory branch only. */
+ crumbs?: Array<{ name: string; path: string }>;
+ pattern?: string;
+ entries?: WorkspaceEntry[];
+ /** Equals `entries.length` — the *capped* count, never the untruncated total. */
+ count?: number;
+ truncated?: boolean;
+ workspace_exists?: boolean;
+ path_exists?: boolean;
+}
diff --git a/server/nodes/filesystem/gallery/__init__.py b/server/nodes/filesystem/gallery/__init__.py
index 7fc00870..45b882ec 100644
--- a/server/nodes/filesystem/gallery/__init__.py
+++ b/server/nodes/filesystem/gallery/__init__.py
@@ -109,7 +109,9 @@ class GalleryNode(ActionNode):
)
rows = result["entries"]
- files = [to_file_ref(r, ctx.workflow_id) for r in rows if not r["is_dir"]]
+ # The listing already carries a finished ref per row — building a
+ # second one here would be two places to keep in step.
+ files = [r["ref"] for r in rows if not r["is_dir"]]
directories = [r["path"] for r in rows if r["is_dir"]]
return GalleryOutput(
diff --git a/server/nodes/filesystem/gallery/_handlers.py b/server/nodes/filesystem/gallery/_handlers.py
index cc7a66b9..acf3f92b 100644
--- a/server/nodes/filesystem/gallery/_handlers.py
+++ b/server/nodes/filesystem/gallery/_handlers.py
@@ -20,7 +20,12 @@ from fastapi import WebSocket
from core.logging import get_logger
from services.plugin.ws import ws_response
-from ._service import WORKSPACE_LIST_DEFAULT, list_directory, list_matching
+from ._service import (
+ WORKSPACE_LIST_DEFAULT,
+ list_directory,
+ list_matching,
+ search_to_pattern,
+)
logger = get_logger(__name__)
@@ -44,14 +49,27 @@ async def _root_for(workflow_id: str, *, mutating: bool = False):
async def handle_list_workspace_files(
data: Dict[str, Any], websocket: WebSocket
) -> Dict[str, Any]:
- """List one directory of a workflow's workspace, or glob across it."""
+ """List one directory of a workflow's workspace, or search across it.
+
+ ``pattern`` is a literal glob. ``search`` is what a person typed into a
+ find box; translating that into a glob is this side's job, so the panel
+ stays a text field and the meaning of "search" is defined once.
+
+ A search covers the whole workspace, not the folder in view — a find
+ box that only finds what is already on screen is not one.
+ """
workflow_id = str(data.get("workflow_id") or "")
root = await _root_for(workflow_id)
- pattern = str(data.get("pattern") or "").strip()
limit = int(data.get("limit") or WORKSPACE_LIST_DEFAULT)
path = str(data.get("path") or "")
+ pattern = str(data.get("pattern") or "").strip()
+ search = str(data.get("search") or "")
+ if not pattern and search:
+ pattern = search_to_pattern(search)
+ path = ""
+
if pattern:
result = await list_matching(
str(root),
diff --git a/server/nodes/filesystem/gallery/_service.py b/server/nodes/filesystem/gallery/_service.py
index 8495753d..208ee9d3 100644
--- a/server/nodes/filesystem/gallery/_service.py
+++ b/server/nodes/filesystem/gallery/_service.py
@@ -45,17 +45,28 @@ def _entry_url(workflow_id: Optional[str], rel_path: str, is_dir: bool) -> Optio
def _to_row(info: Dict[str, Any], workflow_id: Optional[str]) -> Dict[str, Any]:
- """One ``_file_info`` dict -> the wire row, a strict subset of FileRef.
-
- Keeping the field names a subset means the client can lift a row into a
- ``FileRef`` without a round trip: no ambiguity about which name wins.
+ """One ``_file_info`` dict -> the wire row.
+
+ The row is self-sufficient on purpose. It carries the finished
+ ``FileRef`` and the preview verdict rather than the raw material for
+ them, so a client renders and drags without re-deriving anything:
+
+ - ``ref`` is built by :func:`to_file_ref` here, where ``FileRef`` and
+ its ``extra="forbid"`` config live. A client assembling that object
+ itself would be a second, untyped copy of a server model.
+ - ``preview`` comes from :func:`services.media.preview.preview_kind`,
+ the same function that decides the route's ``Content-Disposition``,
+ so what the panel offers to display and what the server will serve
+ inline cannot disagree.
"""
+ from services.media.preview import preview_kind
+
is_dir = bool(info.get("is_dir"))
rel = _relative(str(info.get("path", "")))
name = rel.rsplit("/", 1)[-1]
mime = None if is_dir else (mimetypes.guess_type(name)[0] or "application/octet-stream")
- return {
+ row: Dict[str, Any] = {
"name": name,
"path": rel,
"is_dir": is_dir,
@@ -63,7 +74,45 @@ def _to_row(info: Dict[str, Any], workflow_id: Optional[str]) -> Dict[str, Any]:
"modified_at": info.get("modified_at"),
"mime_type": mime,
"url": _entry_url(workflow_id, rel, is_dir),
+ "preview": "none" if is_dir else preview_kind(mime),
}
+ # A directory has no reference: there is no such thing as a FileRef to
+ # one, and a null is what stops a client offering to drag it anywhere.
+ row["ref"] = None if is_dir else to_file_ref(row, workflow_id)
+ return row
+
+
+def _crumbs(rel: str) -> List[Dict[str, str]]:
+ """Breadcrumb trail for a workspace-relative path.
+
+ The root is omitted — it has no name of its own, and how to label it is
+ the panel's business. Every other segment gets the path that navigating
+ to it requires, so a client never has to reassemble one by splitting.
+ """
+ parts = [part for part in rel.split("/") if part]
+ return [
+ {"name": part, "path": "/".join(parts[: index + 1])}
+ for index, part in enumerate(parts)
+ ]
+
+
+_GLOB_METACHARACTERS = frozenset("*?[]")
+
+
+def search_to_pattern(term: str) -> str:
+ """A human search term -> a glob the matcher will actually match.
+
+ A bare word is not a glob, so ``greeting`` alone finds nothing and a
+ search box would appear broken. Wrapping it makes the box behave the
+ way people expect; a term already carrying glob metacharacters passes
+ through untouched, so exact control stays available to anyone who
+ wants it. Deciding this server-side keeps one definition of what
+ "search" means for both the panel and the node.
+ """
+ term = term.strip()
+ if not term:
+ return ""
+ return term if any(char in _GLOB_METACHARACTERS for char in term) else f"*{term}*"
def _sort_key(row: Dict[str, Any]):
@@ -114,6 +163,7 @@ async def list_directory(
return {
"path": rel,
"parent": None if not rel else rel.rsplit("/", 1)[0] if "/" in rel else "",
+ "crumbs": _crumbs(rel),
"entries": rows[:capped],
"count": min(len(rows), capped),
"truncated": truncated,
@@ -181,5 +231,6 @@ __all__ = [
"WORKSPACE_LIST_LIMIT",
"list_directory",
"list_matching",
+ "search_to_pattern",
"to_file_ref",
]
diff --git a/server/nodes/filesystem/gallery/icon.svg b/server/nodes/filesystem/gallery/icon.svg
new file mode 100644
index 00000000..03193ca1
--- /dev/null
+++ b/server/nodes/filesystem/gallery/icon.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#8be9fd"><path fill-rule="evenodd" clip-rule="evenodd" d="M3 5a2 2 0 0 1 2-2h4.6a2 2 0 0 1 1.42.59L12.41 5H19a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5Zm2 4v10h14V9H5Z"/><path d="M6.5 17.5 9.5 13.9 11.7 16.5 14.3 13.1 17.5 17.5Z"/><circle cx="8.4" cy="11.4" r="1.3"/></svg>
diff --git a/server/routers/workspace.py b/server/routers/workspace.py
index 67df5798..0f527877 100644
--- a/server/routers/workspace.py
+++ b/server/routers/workspace.py
@@ -34,22 +34,13 @@ from core.container import container
from core.database import Database
from core.logging import get_logger
from services.media import MEDIA_MAX_UPLOAD_BYTES, AudioRef, write_audio
+from services.media.preview import serves_inline
from services.media.workspace import UPLOAD_SUBDIR
logger = get_logger(__name__)
router = APIRouter(prefix="/api/workspace", tags=["workspace"])
-# Types a browser may render in place. Everything else downloads.
-#
-# `text/html` and `image/svg+xml` are excluded deliberately and must stay
-# excluded: `shell`, `fileDownloader` and `fileModify` can all write
-# arbitrary files into a workspace, so serving attacker-authored markup
-# inline from the app origin would be stored XSS with access to the session
-# cookie. Both types are script-bearing.
-_INLINE_PREFIXES = ("audio/", "image/", "video/")
-_NEVER_INLINE = {"image/svg+xml", "text/html", "text/xml", "application/xhtml+xml"}
-
# Bounded so a hostile Content-Length cannot make us allocate; the running
# total is what enforces the cap, not the declared length.
_UPLOAD_CHUNK_BYTES = 1024 * 1024
@@ -106,8 +97,7 @@ async def serve_workspace_file(
target = _resolve(root, file_path)
media_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
- inline = media_type.startswith(_INLINE_PREFIXES) and media_type not in _NEVER_INLINE
- disposition = "inline" if inline else "attachment"
+ disposition = "inline" if serves_inline(media_type) else "attachment"
return FileResponse(
target,
diff --git a/server/services/media/preview.py b/server/services/media/preview.py
new file mode 100644
index 00000000..336e9542
--- /dev/null
+++ b/server/services/media/preview.py
@@ -0,0 +1,63 @@
+"""What a browser may render in place, and what must download.
+
+One rule with two consumers: :mod:`routers.workspace` uses it to choose a
+``Content-Disposition``, and the gallery listing uses it to tell the panel
+which entries are previewable. That is the whole reason it lives here
+rather than in either caller — if the two ever disagreed, the panel would
+open a player for a file the route forces to download, and the user would
+see a dead frame with no explanation.
+
+The client is deliberately not trusted to re-derive this from a mime type.
+It would be a second copy of a security decision, and copies drift.
+"""
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+PreviewKind = Literal["image", "audio", "video", "none"]
+
+# Types a browser may render in place. Everything else downloads.
+#
+# `text/html` and `image/svg+xml` are excluded deliberately and must stay
+# excluded: `shell`, `fileDownloader` and `fileModify` can all write
+# arbitrary files into a workspace, so serving attacker-authored markup
+# inline from the app origin would be stored XSS with access to the session
+# cookie. Both types are script-bearing.
+INLINE_PREFIXES = ("audio/", "image/", "video/")
+NEVER_INLINE = frozenset(
+ {"image/svg+xml", "text/html", "text/xml", "application/xhtml+xml"}
+)
+
+
+def serves_inline(mime_type: Optional[str]) -> bool:
+ """Whether the workspace route will serve this with ``inline`` disposition."""
+ if not mime_type:
+ return False
+ return mime_type.startswith(INLINE_PREFIXES) and mime_type not in NEVER_INLINE
+
+
+def preview_kind(mime_type: Optional[str]) -> PreviewKind:
+ """Which element can display this file, or ``"none"``.
+
+ Gated on :func:`serves_inline` first, so a type the route refuses to
+ send inline can never be reported as previewable.
+ """
+ if not serves_inline(mime_type) or not mime_type:
+ return "none"
+ if mime_type.startswith("image/"):
+ return "image"
+ if mime_type.startswith("audio/"):
+ return "audio"
+ if mime_type.startswith("video/"):
+ return "video"
+ return "none"
+
+
+__all__ = [
+ "INLINE_PREFIXES",
+ "NEVER_INLINE",
+ "PreviewKind",
+ "preview_kind",
+ "serves_inline",
+]
diff --git a/server/tests/nodes/test_gallery.py b/server/tests/nodes/test_gallery.py
index a7d18e65..1464a73a 100644
--- a/server/tests/nodes/test_gallery.py
+++ b/server/tests/nodes/test_gallery.py
@@ -310,3 +310,118 @@ class TestWorkspaceContainmentOfSymlinks:
result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)
assert "escape.txt" not in [entry["name"] for entry in result["entries"]]
+
+
+class TestRowsAreSelfSufficient:
+ """The panel renders; it must not have to re-derive anything.
+
+ Both fields here exist to delete a copy of a server rule that had been
+ living in TypeScript: one hand-assembling a Pydantic model that forbids
+ unknown fields, the other second-guessing the route's disposition.
+ """
+
+ async def test_every_file_row_carries_a_finished_reference(self, workspace):
+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)
+
+ for entry in result["entries"]:
+ if entry["is_dir"]:
+ # There is no FileRef to a directory; null is what stops a
+ # client offering to drag one somewhere.
+ assert entry["ref"] is None
+ else:
+ assert entry["ref"] == to_file_ref(entry, WORKFLOW_ID)
+
+ async def test_the_carried_reference_validates_as_a_FileRef(self, workspace):
+ from services.media.refs import FileRef
+
+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)
+ rows = [entry for entry in result["entries"] if not entry["is_dir"]]
+ assert rows
+
+ for entry in rows:
+ # extra="forbid", so this fails loudly if the row ever grows a
+ # field the model does not know about.
+ assert FileRef.model_validate(entry["ref"]).path == entry["path"]
+
+ async def test_preview_matches_what_the_route_will_serve_inline(self, workspace):
+ from services.media.preview import serves_inline
+
+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)
+
+ for entry in result["entries"]:
+ previewable = entry["preview"] != "none"
+ assert previewable is (
+ not entry["is_dir"] and serves_inline(entry["mime_type"])
+ )
+
+ async def test_media_is_previewable_and_text_is_not(self, workspace):
+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)
+ by_name = {entry["name"]: entry for entry in result["entries"]}
+
+ assert by_name["chart.png"]["preview"] == "image"
+ assert by_name["notes.txt"]["preview"] == "none"
+ assert by_name["audio"]["preview"] == "none"
+
+ async def test_an_svg_is_never_previewable(self, workspace):
+ # Script-bearing, so the route forces `attachment`. A panel that
+ # opened an <img> for it would show a dead frame after a download.
+ (workspace / "diagram.svg").write_text("<svg/>")
+
+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)
+ by_name = {entry["name"]: entry for entry in result["entries"]}
+
+ assert by_name["diagram.svg"]["mime_type"] == "image/svg+xml"
+ assert by_name["diagram.svg"]["preview"] == "none"
+
+
+class TestBreadcrumbs:
+ async def test_root_has_no_trail(self, workspace):
+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)
+
+ assert result["crumbs"] == []
+
+ async def test_each_segment_carries_the_path_to_navigate_to(self, workspace):
+ (workspace / "audio" / "clips").mkdir()
+
+ result = await list_directory(
+ str(workspace), path="audio/clips", workflow_id=WORKFLOW_ID
+ )
+
+ assert result["crumbs"] == [
+ {"name": "audio", "path": "audio"},
+ {"name": "clips", "path": "audio/clips"},
+ ]
+
+
+class TestSearchTermTranslation:
+ """One definition of what "search" means, shared by panel and node."""
+
+ def test_a_bare_word_becomes_a_containment_glob(self):
+ from nodes.filesystem.gallery._service import search_to_pattern
+
+ # Unwrapped, `greeting` matches nothing and the box looks broken.
+ assert search_to_pattern("greeting") == "*greeting*"
+
+ def test_an_explicit_glob_passes_through(self):
+ from nodes.filesystem.gallery._service import search_to_pattern
+
+ assert search_to_pattern("*.wav") == "*.wav"
+ assert search_to_pattern("clip?.mp3") == "clip?.mp3"
+ assert search_to_pattern("[abc]*.txt") == "[abc]*.txt"
+
+ def test_whitespace_only_is_not_a_search(self):
+ from nodes.filesystem.gallery._service import search_to_pattern
+
+ assert search_to_pattern(" ") == ""
+ assert search_to_pattern("") == ""
+
+ async def test_a_search_finds_a_file_in_a_subdirectory(self, workspace):
+ from nodes.filesystem.gallery._service import search_to_pattern
+
+ result = await list_matching(
+ str(workspace),
+ pattern=search_to_pattern("greet"),
+ workflow_id=WORKFLOW_ID,
+ )
+
+ assert [entry["path"] for entry in result["entries"]] == ["audio/greeting.wav"]
diff --git a/server/tests/routers/test_workspace.py b/server/tests/routers/test_workspace.py
index 006c7a59..66e4a738 100644
--- a/server/tests/routers/test_workspace.py
+++ b/server/tests/routers/test_workspace.py
@@ -229,3 +229,53 @@ class TestUpload:
stored = Path(response.json()["path"])
assert stored.parts[0] == "uploads"
assert ".." not in stored.parts
+
+
+class TestInlineDispositionHasOneDefinition:
+ """The route and the gallery listing must agree on what renders inline.
+
+ They are two consumers of one security decision. If they ever drifted,
+ the panel would open a player for a file the route forces to download,
+ and the user would get a dead frame with no explanation -- or worse, the
+ listing would advertise as previewable something excluded for being
+ script-bearing.
+ """
+
+ def test_the_route_delegates_rather_than_re_deriving(self):
+ import inspect
+
+ from routers import workspace
+
+ source = inspect.getsource(workspace.serve_workspace_file)
+
+ assert "serves_inline(" in source, (
+ "The disposition choice must come from services.media.preview, "
+ "not from a local copy of the prefix/deny lists."
+ )
+ assert "_INLINE_PREFIXES" not in source
+ assert "_NEVER_INLINE" not in source
+
+ def test_script_bearing_types_are_never_inline(self):
+ from services.media.preview import preview_kind, serves_inline
+
+ for mime in ("image/svg+xml", "text/html", "text/xml", "application/xhtml+xml"):
+ assert serves_inline(mime) is False, mime
+ assert preview_kind(mime) == "none", mime
+
+ def test_media_is_inline_and_names_its_element(self):
+ from services.media.preview import preview_kind, serves_inline
+
+ for mime, kind in (
+ ("image/png", "image"),
+ ("audio/wav", "audio"),
+ ("video/mp4", "video"),
+ ):
+ assert serves_inline(mime) is True, mime
+ assert preview_kind(mime) == kind, mime
+
+ def test_everything_else_downloads(self):
+ from services.media.preview import preview_kind, serves_inline
+
+ for mime in ("application/pdf", "text/plain", "application/octet-stream", None):
+ assert serves_inline(mime) is False, mime
+ assert preview_kind(mime) == "none", mime