Skip to content

Self-improving AI Employees for everyone

feat(gallery): add "Choose from workspace" — the only working assign path

trohitg9341663d9921
diff --git a/CLAUDE.md b/CLAUDE.md
index b5dfb804..ca1518b7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -450,6 +450,7 @@ locked by `server/tests/test_output_contract.py`.
6. **No theme-locked names in non-decorative code.** Avoid `bg-dracula-purple`, `text-dracula-cyan`, etc. unless the constant accent is intentional (action-button palette). Prefer the role token (`bg-node-agent`) so future themes redefine without code edits.
7. **No `useAppTheme()` in new files.** It is grandfathered for the canvas node components and `EdgeConditionEditor` only because they interpolate per-definition `nodeColor`. Every other surface uses Tailwind + the tokens above.
8. **Icons → `lucide-react`.** Inline SVGs are reserved for non-iconographic graphics (charts, decorative shapes). Replace any `<svg>...</svg>` icon you encounter while editing.
+9. **Any `draggable` element that performs a function must ship a pointer-operable, non-drag control reaching the same end state through the same write path.** WCAG 2.2 SC 2.5.7 (Level AA); the sufficient technique is [G219](https://www.w3.org/WAI/WCAG22/Techniques/general/G219), the failure is [F108](https://www.w3.org/WAI/WCAG22/Techniques/failures/F108). Two traps worth stating: **keyboard support does not discharge it** — the Understanding doc is explicit that an equivalent counts only "*unless that equivalent keyboard operation also provides controls that can be clicked or tapped with a pointer*", because touchscreen users may have no keyboard. And the alternative must operate *the same function*, so extract the write into a shared helper rather than reimplementing it — see [`lib/workspaceFileAssign.ts`](./client/src/lib/workspaceFileAssign.ts), which both `ParameterRenderer.handleDrop` and `WorkspaceFilePickerDialog` call, with a test asserting the two paths produce deep-equal results.
When in doubt, read [docs-internal/frontend_architecture.md](./docs-internal/frontend_architecture.md) before introducing new patterns.
diff --git a/client/src/components/ParameterRenderer.tsx b/client/src/components/ParameterRenderer.tsx
index be617b45..ea96229b 100644
--- a/client/src/components/ParameterRenderer.tsx
+++ b/client/src/components/ParameterRenderer.tsx
@@ -35,6 +35,8 @@ 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';
+import { assignWorkspaceFile, buildWorkspaceFilePayload } from '../lib/workspaceFileAssign';
+import WorkspaceFilePickerDialog from './parameterPanel/gallery/WorkspaceFilePickerDialog';
/**
* Radix reserves the empty string to clear a Select, so raw node option
@@ -809,10 +811,18 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
// This prevents showing template code briefly before saved code appears
const currentValue = isLoadingParameters ? (value ?? '') : (value !== undefined ? value : parameter.default);
const [isDragOver, setIsDragOver] = useState(false);
+ // The pointer-operable alternative to dragging a file out of the gallery
+ // (WCAG 2.2 SC 2.5.7) — and, since the gallery panel and this input can
+ // never be on screen together, the only in-app assignment path there is.
+ const [pickerOpen, setPickerOpen] = useState(false);
const [dynamicOptions, setDynamicOptions] = useState<INodePropertyOption[]>([]);
const [nodeParameters, setNodeParameters] = useState<Record<string, any>>({});
const selectedNode = useAppStore((s) => s.selectedNode);
+ // Slice selector, not a whole-store destructure (see the perf rules in
+ // CLAUDE.md). Needed at render time to decide whether the workspace picker
+ // can be offered at all; the file-upload callback reads it via getState().
+ const workflowId = useAppStore((s) => s.currentWorkflow?.id);
const { getNodeParameters, sendRequest } = useWebSocket();
const { getStoredApiKey, hasStoredKey, getStoredModels, getProviderDefaults } = useApiKeys();
const activeNodeIdRef = React.useRef<string | null>(selectedNode?.id ?? null);
@@ -1231,18 +1241,14 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
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);
+ // Same function the "Choose from workspace" picker calls. WCAG 2.2
+ // SC 2.5.7 requires the non-drag alternative to operate *the same*
+ // function, so append-vs-replace has exactly one definition.
+ assignWorkspaceFile(parsedData, {
+ parameterType: parameter.type,
+ currentValue,
+ onChange,
+ });
return;
}
} catch (err) {
@@ -1749,6 +1755,15 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
style={{ display: 'none' }}
accept={getFileAcceptType()}
/>
+ {workflowId && (
+ <ActionButton
+ intent="config"
+ onClick={() => setPickerOpen(true)}
+ title="Pick a file already in this workflow's workspace"
+ >
+ Choose from workspace
+ </ActionButton>
+ )}
<ActionButton
intent="config"
onClick={() => fileInputRef.current?.click()}
@@ -1772,6 +1787,7 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
)}
</div>
<div
+ aria-live="polite"
className={`mt-1 text-[11px] italic ${uploadError ? 'text-destructive' : 'text-muted-foreground'}`}
>
{uploadError
@@ -1782,6 +1798,21 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
? `Size: ${(currentValue.data.length * 0.75 / 1024).toFixed(1)} KB | Type: ${currentValue.mimeType}`
: 'Enter server path or click Upload to select a file'}
</div>
+ <WorkspaceFilePickerDialog
+ open={pickerOpen}
+ onOpenChange={setPickerOpen}
+ workflowId={workflowId}
+ onChoose={(entry) => {
+ const payload = buildWorkspaceFilePayload(entry);
+ if (payload) {
+ assignWorkspaceFile(payload, {
+ parameterType: parameter.type,
+ currentValue,
+ onChange,
+ });
+ }
+ }}
+ />
</div>
);
diff --git a/client/src/components/__tests__/ParameterRendererWorkspacePicker.test.tsx b/client/src/components/__tests__/ParameterRendererWorkspacePicker.test.tsx
new file mode 100644
index 00000000..76169ca9
--- /dev/null
+++ b/client/src/components/__tests__/ParameterRendererWorkspacePicker.test.tsx
@@ -0,0 +1,156 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders as render } from '../../test/providers';
+import { useAppStore } from '../../store/useAppStore';
+import type { WorkspaceEntry } from '../../types/workspaceFiles';
+
+const { wsMock, apiKeysMock } = vi.hoisted(() => ({
+ wsMock: {
+ getNodeParameters: vi.fn().mockResolvedValue({}),
+ sendRequest: vi.fn(),
+ 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 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 file: 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: ref.url,
+ preview: 'audio',
+ ref,
+};
+
+const listing = (entries: WorkspaceEntry[]) => ({
+ success: true, workflow_id: 'wf-1', path: '', parent: null, crumbs: [],
+ entries, count: entries.length, truncated: false,
+ workspace_exists: true, path_exists: true,
+});
+
+const fileParam = { displayName: 'Audio', name: 'audio_file', type: 'file' } as any;
+
+/**
+ * The whole assignment, using only discrete clicks.
+ *
+ * This is the SC 2.5.7 / F108 test procedure: the same function the drag
+ * performs must be operable by single pointer activations with no dragging.
+ * Nothing in here may fire a drag event or a key.
+ */
+const pickFileByClickingOnly = async () => {
+ fireEvent.click(await screen.findByRole('button', { name: /choose from workspace/i }));
+ fireEvent.click(await screen.findByText('greeting.wav'));
+ fireEvent.click(await screen.findByRole('button', { name: /use this file/i }));
+};
+
+describe('ParameterRenderer — workspace picker (WCAG 2.2 SC 2.5.7)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ wsMock.sendRequest.mockResolvedValue(listing([file]));
+ useAppStore.setState({ currentWorkflow: { id: 'wf-1', name: 'W', nodes: [], edges: [] } as any });
+ });
+
+ it('assigns a file using single pointer activations only — no dragging', async () => {
+ const onChange = vi.fn();
+ render(<ParameterRenderer parameter={fileParam} value="" onChange={onChange} />);
+
+ await pickFileByClickingOnly();
+
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith(ref));
+ });
+
+ it('reaches the same end state as the drag, through the same function', async () => {
+ // Run A: the drag path.
+ const onChangeDrag = vi.fn();
+ const { unmount } = render(
+ <ParameterRenderer parameter={fileParam} value="" onChange={onChangeDrag} />,
+ );
+ fireEvent.drop(screen.getByPlaceholderText('Enter file path or upload'), {
+ dataTransfer: {
+ getData: (type: string) =>
+ type === 'application/json'
+ ? JSON.stringify({ type: 'workspaceFile', path: file.path, ref })
+ : '',
+ setData: vi.fn(),
+ types: ['application/json'],
+ },
+ });
+ unmount();
+
+ // Run B: the pointer path.
+ const onChangePick = vi.fn();
+ render(<ParameterRenderer parameter={fileParam} value="" onChange={onChangePick} />);
+ await pickFileByClickingOnly();
+ await waitFor(() => expect(onChangePick).toHaveBeenCalled());
+
+ // G219 asks that the alternative operate *the same function*. This is
+ // what turns that from a claim into an assertion.
+ expect(onChangePick.mock.calls[0][0]).toEqual(onChangeDrag.mock.calls[0][0]);
+ });
+
+ it('is available with no gallery node in the workflow and no gallery pane open', async () => {
+ useAppStore.setState({
+ currentWorkflow: { id: 'wf-1', name: 'W', nodes: [], edges: [] } as any,
+ });
+ render(<ParameterRenderer parameter={fileParam} value="" onChange={vi.fn()} />);
+
+ // The alternative must not depend on the user having placed a gallery
+ // node, nor on a panel that can never be co-rendered with this input.
+ expect(
+ await screen.findByRole('button', { name: /choose from workspace/i }),
+ ).toBeEnabled();
+ });
+
+ it('is hidden when there is no workflow, since there is no workspace to browse', () => {
+ useAppStore.setState({ currentWorkflow: null as any });
+ render(<ParameterRenderer parameter={fileParam} value="" onChange={vi.fn()} />);
+
+ expect(screen.queryByRole('button', { name: /choose from workspace/i })).toBeNull();
+ // Upload's own unsaved-workflow behaviour is untouched.
+ expect(screen.getByRole('button', { name: /upload/i })).toBeInTheDocument();
+ });
+
+ it('offers no drag surface inside the picker', async () => {
+ const { container } = render(
+ <ParameterRenderer parameter={fileParam} value="" onChange={vi.fn()} />,
+ );
+ fireEvent.click(await screen.findByRole('button', { name: /choose from workspace/i }));
+ await screen.findByText('greeting.wav');
+
+ // An alternative that reintroduced the barrier would defeat its purpose.
+ expect(container.querySelectorAll('[draggable="true"]')).toHaveLength(0);
+ });
+
+ it('keeps the confirm button inert until a file is chosen', async () => {
+ render(<ParameterRenderer parameter={fileParam} value="" onChange={vi.fn()} />);
+ fireEvent.click(await screen.findByRole('button', { name: /choose from workspace/i }));
+
+ expect(await screen.findByRole('button', { name: /use this file/i })).toBeDisabled();
+ });
+});
diff --git a/client/src/components/parameterPanel/GalleryPanel.tsx b/client/src/components/parameterPanel/GalleryPanel.tsx
index 456054bb..d71fcfa0 100644
--- a/client/src/components/parameterPanel/GalleryPanel.tsx
+++ b/client/src/components/parameterPanel/GalleryPanel.tsx
@@ -1,31 +1,15 @@
-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import {
- AlertTriangle,
- ChevronRight,
- FolderOpen,
- Home,
- LayoutGrid,
- List,
- Pin,
- RefreshCw,
- Search,
- Upload,
-} from 'lucide-react';
+import React, { useCallback, useMemo, useRef, useState } from 'react';
+import { Pin, 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 type { WorkspaceEntry } from '@/types/workspaceFiles';
import FilePreviewDialog from './gallery/FilePreviewDialog';
-import FileGlyph from './gallery/FileGlyph';
-import { formatBytes, formatModified, glyphToneFor } from './gallery/fileIcons';
+import WorkspaceBrowser from './gallery/WorkspaceBrowser';
interface Props {
workflowId?: string;
@@ -33,16 +17,11 @@ interface Props {
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.
@@ -55,81 +34,22 @@ const GalleryPanel: React.FC<Props> = ({ workflowId, parameters, onParameterChan
);
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 [refreshToken, setRefreshToken] = useState(0);
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 openEntry = useCallback((entry: WorkspaceEntry) => {
+ if (entry.is_dir) navigate(entry.path);
+ else setPreview(entry);
+ }, [navigate]);
+
const togglePin = useCallback((entry: WorkspaceEntry) => {
const next = selectionSet.has(entry.path)
? selection.filter((item) => item !== entry.path)
@@ -150,48 +70,28 @@ const GalleryPanel: React.FC<Props> = ({ workflowId, parameters, onParameterChan
// 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);
+ else setRefreshToken((token) => token + 1);
} 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.';
+ }, [navigate, path, workflowId]);
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>
+ {/* Deliberately does NOT promise drag-to-parameter: this panel and a
+ parameter input are the two branches of one ternary inside a
+ single-node modal, so they are never on screen together. The
+ working path is the picker on the destination field. */}
<p className="text-sm text-fg-muted">
- Everything this workflow has produced. Drag a file onto another node&apos;s parameter to use it.
+ Everything this workflow has produced. Any node can read these files — open a node and
+ use <strong className="font-medium text-fg-default">Choose from workspace</strong> on a
+ file parameter.
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
@@ -211,273 +111,38 @@ const GalleryPanel: React.FC<Props> = ({ workflowId, parameters, onParameterChan
<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">
+ <WorkspaceBrowser
+ workflowId={workflowId}
+ path={path}
+ onPathChange={navigate}
+ onActivate={openEntry}
+ draggable
+ onDragStart={handleFileDragStart}
+ selectionSet={selectionSet}
+ onTogglePin={togglePin}
+ refreshToken={refreshToken}
+ />
+
+ {selection.length > 0 && (
+ <div className="mt-2 flex shrink-0 items-center gap-1 text-xs text-fg-default">
+ <Pin className="h-3 w-3" /> {selection.length} pinned for this node&apos;s output
<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'}
+ className="h-auto px-1 py-0 text-xs"
+ onClick={() => onParameterChange('selection', [])}
>
- <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" />
+ clear
</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/gallery/WorkspaceBrowser.tsx b/client/src/components/parameterPanel/gallery/WorkspaceBrowser.tsx
new file mode 100644
index 00000000..8c09a146
--- /dev/null
+++ b/client/src/components/parameterPanel/gallery/WorkspaceBrowser.tsx
@@ -0,0 +1,429 @@
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import {
+ AlertTriangle,
+ ChevronRight,
+ FolderOpen,
+ Home,
+ LayoutGrid,
+ List,
+ RefreshCw,
+ Search,
+} from 'lucide-react';
+import { toast } from 'sonner';
+
+import { useWebSocket } from '@/contexts/WebSocketContext';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Checkbox } from '@/components/ui/checkbox';
+import { buildApiUrl } from '@/config/api';
+import type { ListWorkspaceFilesResponse, WorkspaceEntry } from '@/types/workspaceFiles';
+
+import FileGlyph from './FileGlyph';
+import { formatBytes, formatModified, glyphToneFor } from './fileIcons';
+
+/**
+ * The workspace browsing engine — listing, breadcrumbs, search, grid/list.
+ *
+ * Extracted so the gallery panel and the "Choose from workspace" picker are
+ * one implementation rather than two. They differ only in what wraps it: the
+ * panel stores `path` on its node and allows dragging; the picker keeps `path`
+ * in local state and offers no drag surface at all (a non-drag alternative
+ * that reintroduced a drag would defeat its purpose).
+ *
+ * `path` is controlled by the parent for exactly that reason.
+ */
+interface Props {
+ workflowId?: string;
+ path: string;
+ onPathChange: (next: string) => void;
+ /** Directory → navigate, file → whatever the host wants (preview or select). */
+ onActivate: (entry: WorkspaceEntry) => void;
+ /** Rows carry an HTML5 drag payload. Off inside the picker. */
+ draggable?: boolean;
+ onDragStart?: (event: React.DragEvent, entry: WorkspaceEntry) => void;
+ /** Optional per-row checkbox (the panel's "pin to node output"). */
+ selectionSet?: ReadonlySet<string>;
+ onTogglePin?: (entry: WorkspaceEntry) => void;
+ /** Highlighted row, for the picker's single-select. */
+ activePath?: string | null;
+ /** Bumping this forces a refetch — the panel uses it after an upload. */
+ refreshToken?: number;
+}
+
+const POLL_INTERVAL_MS = 5000;
+const SEARCH_DEBOUNCE_MS = 250;
+
+const WorkspaceBrowser: React.FC<Props> = ({
+ workflowId,
+ path,
+ onPathChange,
+ onActivate,
+ draggable = false,
+ onDragStart,
+ selectionSet,
+ onTogglePin,
+ activePath = null,
+ refreshToken = 0,
+}) => {
+ const { sendRequest } = useWebSocket();
+
+ 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 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, refreshToken]);
+
+ useEffect(() => {
+ const poll = window.setInterval(() => {
+ // A background tab has nothing to show.
+ if (document.visibilityState !== 'visible') return;
+ void refresh(true);
+ }, POLL_INTERVAL_MS);
+ return () => window.clearInterval(poll);
+ }, [refresh]);
+
+ const navigate = useCallback((next: string) => {
+ setSearch('');
+ setQuery('');
+ onPathChange(next);
+ }, [onPathChange]);
+
+ 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 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.';
+
+ const rowProps = (entry: WorkspaceEntry) => ({
+ entry,
+ pinned: selectionSet?.has(entry.path) ?? false,
+ showPin: !!onTogglePin,
+ active: activePath === entry.path,
+ showFullPath: searching,
+ draggable: draggable && !entry.is_dir && !!entry.ref,
+ onOpen: onActivate,
+ onTogglePin,
+ onDragStart,
+ });
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
+ <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>
+
+ <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'} />
+ </Button>
+ </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} {...rowProps(entry)} />)}
+ </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} {...rowProps(entry)} />)}
+ </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>
+ {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>
+ </div>
+ );
+};
+
+interface RowProps {
+ entry: WorkspaceEntry;
+ pinned: boolean;
+ showPin: boolean;
+ active: boolean;
+ showFullPath: boolean;
+ draggable: boolean;
+ onOpen: (entry: WorkspaceEntry) => void;
+ onTogglePin?: (entry: WorkspaceEntry) => void;
+ onDragStart?: (event: React.DragEvent, entry: WorkspaceEntry) => void;
+}
+
+/** Enter and Space activate, matching what a `role="button"` promises. */
+const activationKeys = (onOpen: () => void) => (event: React.KeyboardEvent) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ onOpen();
+ }
+};
+
+const GridTile: React.FC<RowProps> = ({
+ entry, pinned, showPin, active, showFullPath, draggable, onOpen, onTogglePin, onDragStart,
+}) => {
+ const [thumbFailed, setThumbFailed] = useState(false);
+ const showThumb = entry.preview === 'image' && !!entry.url && !thumbFailed;
+
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ aria-pressed={active}
+ draggable={draggable}
+ onDragStart={onDragStart ? (event) => onDragStart(event, entry) : undefined}
+ onClick={() => onOpen(entry)}
+ onKeyDown={activationKeys(() => onOpen(entry))}
+ title={entry.path}
+ className={`group relative flex cursor-pointer flex-col gap-2 rounded border bg-bg-panel p-2 text-left transition-colors hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus ${
+ active ? 'border-border-focus' : 'border-border-default hover:border-border-strong'
+ }`}
+ >
+ <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>
+
+ {showPin && !entry.is_dir && onTogglePin && (
+ <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, showPin, active, showFullPath, draggable, onOpen, onTogglePin, onDragStart,
+}) => (
+ // role/tabIndex/keydown so list view is operable without a pointer — the
+ // grid tiles always were, and a view toggle must not change what is reachable.
+ <tr
+ role="button"
+ tabIndex={0}
+ aria-pressed={active}
+ draggable={draggable}
+ onDragStart={onDragStart ? (event) => onDragStart(event, entry) : undefined}
+ onClick={() => onOpen(entry)}
+ onKeyDown={activationKeys(() => onOpen(entry))}
+ title={entry.path}
+ className={`cursor-pointer border-b border-border-default hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus ${
+ active ? 'bg-bg-active' : ''
+ }`}
+ >
+ <td className="px-3 py-2" onClick={(event) => event.stopPropagation()}>
+ {showPin && !entry.is_dir && onTogglePin && (
+ <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 WorkspaceBrowser;
diff --git a/client/src/components/parameterPanel/gallery/WorkspaceFilePickerDialog.tsx b/client/src/components/parameterPanel/gallery/WorkspaceFilePickerDialog.tsx
new file mode 100644
index 00000000..9b72ce60
--- /dev/null
+++ b/client/src/components/parameterPanel/gallery/WorkspaceFilePickerDialog.tsx
@@ -0,0 +1,139 @@
+import React, { useCallback, useRef, useState } from 'react';
+import { Upload } from 'lucide-react';
+import { toast } from 'sonner';
+
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import { ActionButton } from '@/components/ui/action-button';
+import { Button } from '@/components/ui/button';
+import { uploadToWorkspace } from '@/lib/workspaceUpload';
+import type { WorkspaceEntry } from '@/types/workspaceFiles';
+
+import WorkspaceBrowser from './WorkspaceBrowser';
+
+/**
+ * Pick a workspace file for a parameter, using only discrete clicks.
+ *
+ * This is the WCAG 2.2 SC 2.5.7 alternative to dragging a file out of the
+ * gallery — and, because the gallery panel and a parameter input can never be
+ * on screen together (they are the two branches of one ternary inside a
+ * single-node modal), it is also the only assignment path that works in-app.
+ *
+ * It deliberately renders **no drag surface**: an alternative that reintroduced
+ * the barrier it exists to remove would be pointless. `draggable` is off, so no
+ * row carries a drag payload.
+ */
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ workflowId?: string;
+ /** Called with the chosen row. The dialog never writes a parameter itself. */
+ onChoose: (entry: WorkspaceEntry) => void;
+}
+
+const parentOf = (path: string): string =>
+ path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
+
+const WorkspaceFilePickerDialog: React.FC<Props> = ({
+ open, onOpenChange, workflowId, onChoose,
+}) => {
+ const [path, setPath] = useState('');
+ const [selected, setSelected] = useState<WorkspaceEntry | null>(null);
+ const [uploading, setUploading] = useState(false);
+ const [refreshToken, setRefreshToken] = useState(0);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const handleActivate = useCallback((entry: WorkspaceEntry) => {
+ if (entry.is_dir) {
+ setSelected(null);
+ setPath(entry.path);
+ return;
+ }
+ // Single click selects. Confirming is a separate, explicit click — so the
+ // whole operation is two discrete activations with no pointer travel.
+ setSelected(entry);
+ }, []);
+
+ const handlePathChange = useCallback((next: string) => {
+ setSelected(null);
+ setPath(next);
+ }, []);
+
+ 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`);
+ // An empty workspace must not be a dead end, so go to where it landed.
+ if (landedIn !== null && landedIn !== path) handlePathChange(landedIn);
+ else setRefreshToken((token) => token + 1);
+ } catch (caught) {
+ toast.error(caught instanceof Error ? caught.message : 'Upload failed');
+ } finally {
+ setUploading(false);
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ }
+ }, [handlePathChange, path, workflowId]);
+
+ const confirm = () => {
+ if (!selected) return;
+ onChoose(selected);
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex h-[70vh] max-w-4xl flex-col">
+ <DialogHeader>
+ <DialogTitle>Choose a workspace file</DialogTitle>
+ </DialogHeader>
+
+ <WorkspaceBrowser
+ workflowId={workflowId}
+ path={path}
+ onPathChange={handlePathChange}
+ onActivate={handleActivate}
+ activePath={selected?.path ?? null}
+ refreshToken={refreshToken}
+ />
+
+ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border-default pt-3">
+ <div className="min-w-0 text-xs text-fg-muted">
+ {selected
+ ? <span className="truncate font-mono text-fg-default">{selected.path}</span>
+ : 'Select a file to continue.'}
+ </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)}
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!workflowId || uploading}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <Upload className="h-4 w-4" /> {uploading ? 'Uploading…' : 'Upload'}
+ </Button>
+ <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <ActionButton intent="save" disabled={!selected} onClick={confirm}>
+ Use this file
+ </ActionButton>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export default WorkspaceFilePickerDialog;
diff --git a/client/src/hooks/useDragWorkspaceFile.ts b/client/src/hooks/useDragWorkspaceFile.ts
index 1a5864f4..12ede216 100644
--- a/client/src/hooks/useDragWorkspaceFile.ts
+++ b/client/src/hooks/useDragWorkspaceFile.ts
@@ -1,10 +1,7 @@
import { useCallback } from 'react';
-import {
- WORKSPACE_FILE_DRAG_TYPE,
- type WorkspaceEntry,
- type WorkspaceFileDragPayload,
-} from '@/types/workspaceFiles';
+import { buildWorkspaceFilePayload } from '@/lib/workspaceFileAssign';
+import type { WorkspaceEntry } from '@/types/workspaceFiles';
interface DragWorkspaceFileHookReturn {
handleFileDragStart: (event: React.DragEvent, entry: WorkspaceEntry) => void;
@@ -25,17 +22,12 @@ interface DragWorkspaceFileHookReturn {
*/
export function useDragWorkspaceFile(): DragWorkspaceFileHookReturn {
const handleFileDragStart = useCallback((event: React.DragEvent, entry: WorkspaceEntry) => {
- if (entry.is_dir || !entry.ref) {
+ const payload = buildWorkspaceFilePayload(entry);
+ if (!payload) {
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';
diff --git a/client/src/lib/__tests__/workspaceFileAssign.test.ts b/client/src/lib/__tests__/workspaceFileAssign.test.ts
new file mode 100644
index 00000000..192387b4
--- /dev/null
+++ b/client/src/lib/__tests__/workspaceFileAssign.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { assignWorkspaceFile, buildWorkspaceFilePayload } from '../workspaceFileAssign';
+import type { WorkspaceEntry, WorkspaceFileRef } from '../../types/workspaceFiles';
+
+const ref: WorkspaceFileRef = {
+ 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',
+};
+
+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: ref.url as string,
+ preview: 'audio',
+ ref,
+};
+
+const payload = buildWorkspaceFilePayload(entry)!;
+
+describe('buildWorkspaceFilePayload', () => {
+ it('forwards the server-built ref rather than reconstructing one', () => {
+ expect(payload).toEqual({ type: 'workspaceFile', path: 'audio/greeting.wav', ref });
+ });
+
+ it('refuses a directory', () => {
+ expect(buildWorkspaceFilePayload({ ...entry, is_dir: true, ref: null })).toBeNull();
+ });
+
+ it('refuses a row the server gave no ref for', () => {
+ expect(buildWorkspaceFilePayload({ ...entry, ref: null })).toBeNull();
+ });
+});
+
+describe('assignWorkspaceFile', () => {
+ it('replaces a file parameter with the whole reference', () => {
+ const onChange = vi.fn();
+ assignWorkspaceFile(payload, { parameterType: 'file', currentValue: '', onChange });
+ // Deep equality, not just .path — a file param stores the ref object.
+ expect(onChange).toHaveBeenCalledWith(ref);
+ });
+
+ it('appends to a text parameter instead of replacing it', () => {
+ const onChange = vi.fn();
+ assignWorkspaceFile(payload, { parameterType: 'string', currentValue: 'Transcribe', onChange });
+ expect(onChange).toHaveBeenCalledWith('Transcribe audio/greeting.wav');
+ });
+
+ it('does not double-space when the text already ends in one', () => {
+ const onChange = vi.fn();
+ assignWorkspaceFile(payload, { parameterType: 'string', currentValue: 'Transcribe ', onChange });
+ expect(onChange).toHaveBeenCalledWith('Transcribe audio/greeting.wav');
+ });
+
+ it('starts an empty text parameter with no leading space', () => {
+ const onChange = vi.fn();
+ assignWorkspaceFile(payload, { parameterType: 'string', currentValue: '', onChange });
+ expect(onChange).toHaveBeenCalledWith('audio/greeting.wav');
+ });
+
+ it('survives a non-string current value on a text parameter', () => {
+ const onChange = vi.fn();
+ // A `file` param's value is an object; `.endsWith` on one would throw.
+ assignWorkspaceFile(payload, { parameterType: 'json', currentValue: ref, onChange });
+ expect(onChange).toHaveBeenCalledWith('audio/greeting.wav');
+ });
+});
diff --git a/client/src/lib/workspaceFileAssign.ts b/client/src/lib/workspaceFileAssign.ts
new file mode 100644
index 00000000..0605d836
--- /dev/null
+++ b/client/src/lib/workspaceFileAssign.ts
@@ -0,0 +1,68 @@
+/**
+ * The single write path for assigning a workspace file to a parameter.
+ *
+ * Two entry points reach this: the drag drop handler in `ParameterRenderer`,
+ * and the "Choose from workspace" picker. They must not diverge — WCAG 2.2
+ * SC 2.5.7 requires the non-drag alternative to operate *the same function*,
+ * not merely a similar one, so the append-vs-replace rule lives here once and
+ * both callers invoke it.
+ *
+ * Pure and React-free, so the parity between the two paths is unit-testable
+ * rather than a claim.
+ */
+
+import {
+ WORKSPACE_FILE_DRAG_TYPE,
+ type WorkspaceEntry,
+ type WorkspaceFileDragPayload,
+} from '@/types/workspaceFiles';
+
+/**
+ * Lift a listing row into the payload both paths carry.
+ *
+ * Returns `null` for anything that cannot be assigned — a directory, or a row
+ * the server declined to give a `ref`. Callers treat null as "not assignable"
+ * (the drag hook cancels the drag; the picker disables its confirm button).
+ */
+export const buildWorkspaceFilePayload = (
+ entry: WorkspaceEntry,
+): WorkspaceFileDragPayload | null => {
+ if (entry.is_dir || !entry.ref) return null;
+ return {
+ type: WORKSPACE_FILE_DRAG_TYPE,
+ path: entry.path,
+ ref: entry.ref,
+ };
+};
+
+interface AssignTarget {
+ /** The `INodeProperties`/`NodeParameter` type of the destination field. */
+ parameterType?: string;
+ /** Whatever the field currently holds — may be an object for `file` params. */
+ currentValue: unknown;
+ onChange: (value: unknown) => void;
+}
+
+/**
+ * Write a chosen file into a parameter.
+ *
+ * A `file` parameter holds exactly one reference, so it is REPLACED. Every
+ * other parameter is text and is APPENDED to: dropping — or picking — a file
+ * while a prompt is half-written must leave the prompt intact. That asymmetry
+ * is the reason this app does not reuse the pre-existing `nodeOutput` drag
+ * discriminator, whose handler replaces unconditionally.
+ */
+export const assignWorkspaceFile = (
+ payload: WorkspaceFileDragPayload,
+ { parameterType, currentValue, onChange }: AssignTarget,
+): void => {
+ if (parameterType === 'file' && payload.ref) {
+ onChange(payload.ref);
+ return;
+ }
+
+ // Guarded: a `file` param's value is an object, and `.endsWith` on one throws.
+ const existing = typeof currentValue === 'string' ? currentValue : '';
+ const needsSpace = existing.length > 0 && !existing.endsWith(' ');
+ onChange(existing + (needsSpace ? ' ' : '') + payload.path);
+};