Image Pipeline Playground
feat(frontend): wire desktop assets and folder save UX
Mohammad Rajaeid564667b46f4
diff --git a/frontend/src/api/assets.ts b/frontend/src/api/assets.tsnew file mode 100644index 0000000..3894c20--- /dev/null+++ b/frontend/src/api/assets.ts@@ -0,0 +1,90 @@+/** Desktop bridge + asset/upload HTTP helpers. */++import type {+ AssetBatch,+ RegisterAssetsResponse,+ UploadResponse,+} from '../types'++export function isDesktopApp(): boolean {+ return Boolean(window.imagePipesDesktop?.isDesktop)+}++export function getDesktop() {+ return window.imagePipesDesktop+}++export function assetPreviewUrl(batchId: string, name: string): string {+ return `/api/assets/${batchId}/files/${encodeURIComponent(name)}`+}++export async function registerLocalPaths(+ paths: string[],+ options?: { asFolder?: boolean; appendTo?: string },+): Promise<RegisterAssetsResponse> {+ const response = await fetch('/api/assets/register', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ paths,+ as_folder: Boolean(options?.asFolder),+ append_to: options?.appendTo ?? null,+ }),+ })+ if (!response.ok) {+ const detail = await response.text()+ throw new Error(detail || 'Could not register images')+ }+ return response.json() as Promise<RegisterAssetsResponse>+}++export async function uploadImageFiles(+ files: File[],+ options?: { asFolder?: boolean; appendTo?: string },+): Promise<UploadResponse> {+ const body = new FormData()+ for (const file of files) {+ body.append('files', file, file.name)+ }+ const params = new URLSearchParams({+ as_folder: options?.asFolder ? 'true' : 'false',+ })+ if (options?.appendTo) params.set('append_to', options.appendTo)+ const response = await fetch(`/api/uploads?${params.toString()}`, {+ method: 'POST',+ body,+ })+ if (!response.ok) {+ const detail = await response.text()+ throw new Error(detail || 'Upload failed')+ }+ return response.json() as Promise<UploadResponse>+}++export async function deleteUploadedPath(path: string): Promise<void> {+ await fetch(`/api/uploads?path=${encodeURIComponent(path)}`, { method: 'DELETE' })+}++export async function deleteAssetFile(batchId: string, name: string): Promise<void> {+ await fetch(`/api/assets/${batchId}/files/${encodeURIComponent(name)}`, {+ method: 'DELETE',+ })+}++export function batchDisplayPath(batch: AssetBatch): string {+ if (batch.root) return batch.root+ if (batch.files.length === 1) return batch.files[0].path+ if (batch.files.length > 1) {+ const parent = batch.files[0].path.replace(/[\\/][^\\/]+$/, '')+ return parent || batch.id+ }+ return ''+}++export function batchPreviewUrls(batch: AssetBatch): string[] {+ return batch.files.map((file) => assetPreviewUrl(batch.id, file.name))+}++export function batchFilePaths(batch: AssetBatch): string[] {+ return batch.files.map((file) => file.path)+}diff --git a/frontend/src/features/inspector/FileParamInput.tsx b/frontend/src/features/inspector/FileParamInput.tsxindex 7c858b1..9636826 100644--- a/frontend/src/features/inspector/FileParamInput.tsx+++ b/frontend/src/features/inspector/FileParamInput.tsx@@ -1,25 +1,29 @@import { useEffect, useRef, useState } from 'react'import { Box, Button, IconButton, TextField, Typography } from '@mui/material'+import {+ batchDisplayPath,+ batchFilePaths,+ batchPreviewUrls,+ isDesktopApp,+ getDesktop,+ registerLocalPaths,+ uploadImageFiles,+} from '../../api/assets'import type { ParamField } from '../../types'import { notifyError, notifySuccess } from '../../notify'interface FileParamInputProps {field: ParamFieldvalue: string+ assetBatchId?: stringpreviewUrls?: string[]uploadedFiles?: string[]onChange: (path: string) => void+ onAssetBatchId?: (batchId: string) => voidonPreviews?: (dataUrls: string[], uploadedFiles: string[]) => voidonRemovePreview?: (index: number) => void}-interface UploadResponse {- path: string- kind: string- files: string[]- count: number-}-function acceptAttr(field: ParamField): string {const extensions = field.accept?.length? field.accept@@ -45,28 +49,6 @@ function parentDir(filePath: string): string {return filePath.replace(/[\\/][^\\/]+$/, '')}-async function uploadFiles(- files: File[],- asFolder: boolean,- appendTo?: string,-): Promise<UploadResponse> {- const body = new FormData()- for (const file of files) {- body.append('files', file, file.name)- }- const params = new URLSearchParams({ as_folder: asFolder ? 'true' : 'false' })- if (appendTo) params.set('append_to', appendTo)- const response = await fetch(`/api/uploads?${params.toString()}`, {- method: 'POST',- body,- })- if (!response.ok) {- const detail = await response.text()- throw new Error(detail || 'Upload failed')- }- return response.json() as Promise<UploadResponse>-}-function readFileAsDataUrl(file: File): Promise<string> {return new Promise((resolve, reject) => {const reader = new FileReader()@@ -79,9 +61,11 @@ function readFileAsDataUrl(file: File): Promise<string> {export function FileParamInput({field,value,+ assetBatchId = '',previewUrls = [],uploadedFiles = [],onChange,+ onAssetBatchId,onPreviews,onRemovePreview,}: FileParamInputProps) {@@ -90,6 +74,7 @@ export function FileParamInput({const folderRef = useRef<HTMLInputElement>(null)const [busy, setBusy] = useState(false)const [error, setError] = useState<string | null>(null)+ const desktop = isDesktopApp()const summary =previewUrls.length > 1? `${previewUrls.length} images selected`@@ -104,6 +89,67 @@ export function FileParamInput({input.setAttribute('directory', '')}, [])+ const applyBatch = (+ batchId: string,+ path: string,+ urls: string[],+ files: string[],+ message: string,+ ) => {+ onAssetBatchId?.(batchId)+ onChange(path)+ onPreviews?.(urls, files)+ notifySuccess(message)+ }++ const handleDesktopPick = async (mode: 'replace' | 'append' | 'folder') => {+ const bridge = getDesktop()+ if (!bridge) return+ setBusy(true)+ setError(null)+ try {+ if (mode === 'folder') {+ const picked = await bridge.openFolder()+ if (picked.canceled || !picked.path) return+ const result = await registerLocalPaths([picked.path], { asFolder: true })+ applyBatch(+ result.batch.id,+ batchDisplayPath(result.batch),+ batchPreviewUrls(result.batch),+ batchFilePaths(result.batch),+ result.count > 1 ? `${result.count} images loaded` : 'Image loaded',+ )+ return+ }++ const picked = await bridge.openImages()+ if (picked.canceled || picked.paths.length === 0) return+ const appending = mode === 'append' && Boolean(assetBatchId)+ const result = await registerLocalPaths(picked.paths, {+ asFolder: picked.paths.length > 1,+ appendTo: appending ? assetBatchId : undefined,+ })+ applyBatch(+ result.batch.id,+ batchDisplayPath(result.batch),+ batchPreviewUrls(result.batch),+ batchFilePaths(result.batch),+ appending+ ? `Images updated (${result.batch.files.length} total)`+ : result.count > 1+ ? `${result.count} images loaded`+ : 'Image loaded',+ )+ } catch (err) {+ if (mode === 'replace' || mode === 'folder') onPreviews?.([], [])+ const message = err instanceof Error ? err.message : 'Could not open images'+ setError(message)+ notifyError(message)+ } finally {+ setBusy(false)+ }+ }+const handleFiles = async (fileList: FileList | null,asFolder: boolean,@@ -125,10 +171,11 @@ export function FileParamInput({const appending = mode === 'append' && uploadedFiles.length > 0const appendTo = appending ? parentDir(uploadedFiles[0]) : undefinedconst batch = asFolder || files.length > 1 || appending- const result = await uploadFiles(files, batch, appendTo)+ const result = await uploadImageFiles(files, { asFolder: batch, appendTo })if (appending) {const nextUrls = [...previewUrls, ...urls]const nextFiles = [...uploadedFiles, ...result.files]+ onAssetBatchId?.(result.asset_batch_id)onPreviews?.(nextUrls, nextFiles)onChange(result.path)notifySuccess(@@ -137,6 +184,7 @@ export function FileParamInput({: `Added image (${nextUrls.length} total)`,)} else {+ onAssetBatchId?.(result.asset_batch_id)onPreviews?.(urls, result.files)onChange(result.path)notifySuccess(@@ -160,7 +208,11 @@ export function FileParamInput({label={field.label}value={value}onChange={(event) => onChange(event.target.value)}- helperText={field.description ?? `Allowed: ${acceptAttr(field)}`}+ helperText={+ desktop+ ? 'Native file dialogs register local paths (no copy).'+ : (field.description ?? `Allowed: ${acceptAttr(field)}`)+ }/><Boxsx={{@@ -174,7 +226,10 @@ export function FileParamInput({size="small"variant="outlined"disabled={busy}- onClick={() => fileRef.current?.click()}+ onClick={() => {+ if (desktop) void handleDesktopPick('replace')+ else fileRef.current?.click()+ }}sx={{ textTransform: 'none' }}>Choose images@@ -183,7 +238,10 @@ export function FileParamInput({size="small"variant="outlined"disabled={busy}- onClick={() => addRef.current?.click()}+ onClick={() => {+ if (desktop) void handleDesktopPick('append')+ else addRef.current?.click()+ }}sx={{ textTransform: 'none' }}>Add image@@ -192,44 +250,51 @@ export function FileParamInput({size="small"variant="outlined"disabled={busy}- onClick={() => folderRef.current?.click()}+ onClick={() => {+ if (desktop) void handleDesktopPick('folder')+ else folderRef.current?.click()+ }}sx={{ textTransform: 'none' }}>Choose folder</Button></Box>- <input- ref={fileRef}- type="file"- hidden- multiple- accept={acceptAttr(field)}- onChange={(event) => {- void handleFiles(event.target.files, false, 'replace')- event.target.value = ''- }}- />- <input- ref={addRef}- type="file"- hidden- multiple- accept={acceptAttr(field)}- onChange={(event) => {- void handleFiles(event.target.files, false, 'append')- event.target.value = ''- }}- />- <input- ref={folderRef}- type="file"- hidden- multiple- onChange={(event) => {- void handleFiles(event.target.files, true, 'replace')- event.target.value = ''- }}- />+ {!desktop && (+ <>+ <input+ ref={fileRef}+ type="file"+ hidden+ multiple+ accept={acceptAttr(field)}+ onChange={(event) => {+ void handleFiles(event.target.files, false, 'replace')+ event.target.value = ''+ }}+ />+ <input+ ref={addRef}+ type="file"+ hidden+ multiple+ accept={acceptAttr(field)}+ onChange={(event) => {+ void handleFiles(event.target.files, false, 'append')+ event.target.value = ''+ }}+ />+ <input+ ref={folderRef}+ type="file"+ hidden+ multiple+ onChange={(event) => {+ void handleFiles(event.target.files, true, 'replace')+ event.target.value = ''+ }}+ />+ </>+ )}{previewUrls.length > 0 && (<Boxsx={{diff --git a/frontend/src/features/inspector/NodeInspector.tsx b/frontend/src/features/inspector/NodeInspector.tsxindex b1361cb..06eb3a5 100644--- a/frontend/src/features/inspector/NodeInspector.tsx+++ b/frontend/src/features/inspector/NodeInspector.tsx@@ -108,10 +108,15 @@ export function NodeInspector() {filename={String(selected.data.params.filename ?? '{filename}_{index}.png',)}+ outputDir={String(selected.data.params.output_dir ?? '')}onFilenameChange={(filename) => {setValue('filename', filename, { shouldDirty: true, shouldValidate: true })updateNodeParams(selected.id, { filename })}}+ onOutputDirChange={(outputDir) => {+ setValue('output_dir', outputDir, { shouldDirty: true, shouldValidate: true })+ updateNodeParams(selected.id, { output_dir: outputDir })+ }}/>) : isAnnotations ? (<AnnotationsParams@@ -142,30 +147,58 @@ export function NodeInspector() {</Typography>)}{fields.map((field) => {+ if (field.name === 'asset_batch_id' || field.name === 'output_dir') {+ return null+ }if (field.type === 'file') {return (<FileParamInputkey={field.name}field={field}value={String(selected.data.params[field.name] ?? '')}+ assetBatchId={String(selected.data.params.asset_batch_id ?? '')}previewUrls={selected.data.localPreviewUrls ?? []}uploadedFiles={selected.data.uploadedFiles ?? []}onChange={(path) => {setValue(field.name, path, { shouldDirty: true, shouldValidate: true })updateNodeParams(selected.id, { [field.name]: path })}}+ onAssetBatchId={(batchId) => {+ setValue('asset_batch_id', batchId, {+ shouldDirty: true,+ shouldValidate: true,+ })+ updateNodeParams(selected.id, { asset_batch_id: batchId })+ }}onPreviews={(urls, files) => setLocalPreviews(selected.id, urls, files)}onRemovePreview={(index) => {+ const prevBatchId = String(+ selected.data.params.asset_batch_id ?? '',+ )const result = removeLocalPreview(selected.id, index)if (!result) returnsetValue(field.name, result.path, {shouldDirty: true,shouldValidate: true,})+ if (result.assetBatchId !== undefined) {+ setValue('asset_batch_id', result.assetBatchId, {+ shouldDirty: true,+ shouldValidate: true,+ })+ }if (!result.file) return- void fetch(`/api/uploads?path=${encodeURIComponent(result.file)}`, {- method: 'DELETE',- })+ if (prevBatchId) {+ const name = result.file.replace(/^.*[\\/]/, '')+ void fetch(+ `/api/assets/${prevBatchId}/files/${encodeURIComponent(name)}`,+ { method: 'DELETE' },+ )+ } else {+ void fetch(`/api/uploads?path=${encodeURIComponent(result.file)}`, {+ method: 'DELETE',+ })+ }}}/>)diff --git a/frontend/src/features/inspector/SaveImageParams.tsx b/frontend/src/features/inspector/SaveImageParams.tsxindex 0e167fd..d8c0e38 100644--- a/frontend/src/features/inspector/SaveImageParams.tsx+++ b/frontend/src/features/inspector/SaveImageParams.tsx@@ -1,4 +1,6 @@import { Box, Button, TextField, Typography } from '@mui/material'+import { getDesktop, isDesktopApp } from '../../api/assets'+import { notifyError } from '../../notify'const SAVE_PATH_TEMPLATES = [{ token: '{filename}', hint: 'source stem' },@@ -8,21 +10,63 @@ const SAVE_PATH_TEMPLATES = [type SaveImageParamsProps = {filename: string+ outputDir: stringonFilenameChange: (filename: string) => void+ onOutputDirChange: (outputDir: string) => void}-export function SaveImageParams({ filename, onFilenameChange }: SaveImageParamsProps) {+export function SaveImageParams({+ filename,+ outputDir,+ onFilenameChange,+ onOutputDirChange,+}: SaveImageParamsProps) {+ const desktop = isDesktopApp()+const insertTemplate = (token: string) => {onFilenameChange(`${filename}${token}`)}+ const pickFolder = async () => {+ const bridge = getDesktop()+ if (!bridge) return+ try {+ const result = await bridge.pickFolder()+ if (result.canceled || !result.path) return+ onOutputDirChange(result.path)+ } catch (err) {+ notifyError(err instanceof Error ? err.message : 'Could not pick folder')+ }+ }+return (<Box sx={{ display: 'grid', gap: 1.5 }}><Typography sx={{ fontSize: 13, color: 'rgba(244,241,234,0.55)', lineHeight: 1.45 }}>- After Run, images are packed into a ZIP and your browser downloads it. No local folder- access is required.+ {desktop+ ? 'Pick an output folder to write images after Run. Leave empty to fall back to a ZIP download.'+ : 'After Run, images are packed into a ZIP and downloaded. Set an output folder when running on desktop.'}</Typography>+ <Box sx={{ display: 'grid', gap: 1 }}>+ <TextField+ size="small"+ label="Output folder"+ value={outputDir}+ onChange={(event) => onOutputDirChange(event.target.value)}+ helperText={desktop ? 'Required for direct disk writes' : 'Optional on desktop builds'}+ />+ {desktop && (+ <Button+ size="small"+ variant="outlined"+ onClick={() => void pickFolder()}+ sx={{ textTransform: 'none', justifySelf: 'start' }}+ >+ Choose folder+ </Button>+ )}+ </Box>+<TextFieldsize="small"label="Filename"diff --git a/frontend/src/hooks/useExecutionSocket.ts b/frontend/src/hooks/useExecutionSocket.tsindex 9e9c0ae..9cba9ac 100644--- a/frontend/src/hooks/useExecutionSocket.ts+++ b/frontend/src/hooks/useExecutionSocket.ts@@ -111,9 +111,25 @@ export function useExecutionSocket() {setIsExecuting(false)setActiveNodeId(null)}+ if (event.type === 'saved' && event.saved_dir) {+ appendLog(event.message ?? `Saved to ${event.saved_dir}`)+ notifySuccess(event.message ?? `Saved to ${event.saved_dir}`)+ const reveal = window.imagePipesDesktop?.revealInFolder+ if (reveal) {+ const files = event.data?.files+ const firstFile =+ Array.isArray(files) && typeof files[0] === 'string'+ ? files[0]+ : event.saved_dir+ void reveal(firstFile).catch(() => {+ /* ignore reveal failures */+ })+ }+ }if (event.type === 'download' && event.download_url) {const filename = event.download_filename ?? 'results.zip'appendLog(event.message ?? `Download ready: ${filename}`)+ // Desktop with folder saves already revealed the output; ZIP is fallback only.const anchor = document.createElement('a')anchor.href = event.download_urlanchor.download = filenamediff --git a/frontend/src/store/graphStore.ts b/frontend/src/store/graphStore.tsindex 3196f2f..b32140c 100644--- a/frontend/src/store/graphStore.ts+++ b/frontend/src/store/graphStore.ts@@ -85,6 +85,7 @@ interface GraphState {removeLocalPreview: (nodeId: string, index: number) => {file: string | nullpath: string+ assetBatchId?: string} | nullsetActiveNodeId: (nodeId: string | null) => voidaddPreview: (preview: ExecutionPreview) => void@@ -400,8 +401,10 @@ export const useGraphStore = create<GraphState>((set, get) => ({if (index < files.length) files.splice(index, 1)let nextPath = String(node.data.params.path ?? '')+ let nextBatchId = String(node.data.params.asset_batch_id ?? '')if (previews.length === 0) {nextPath = ''+ nextBatchId = ''} else if (files.length === 1) {nextPath = files[0]} else if (files.length > 1) {@@ -419,14 +422,18 @@ export const useGraphStore = create<GraphState>((set, get) => ({...item.data,localPreviewUrls: previews,uploadedFiles: files,- params: { ...item.data.params, path: nextPath },+ params: {+ ...item.data.params,+ path: nextPath,+ asset_batch_id: nextBatchId,+ },},}: item,),workflowDirty: true,})- return { file: removedFile, path: nextPath }+ return { file: removedFile, path: nextPath, assetBatchId: nextBatchId }},setActiveNodeId: (nodeId) =>diff --git a/frontend/src/workflow/materializeSampleImages.ts b/frontend/src/workflow/materializeSampleImages.tsindex 8047e92..ac9b4c7 100644--- a/frontend/src/workflow/materializeSampleImages.ts+++ b/frontend/src/workflow/materializeSampleImages.ts@@ -1,23 +1,20 @@-/** Turn template placeholder paths like examples/lena.png into real uploads. */+/** Turn template placeholder paths like examples/lena.png into real asset refs. */+import {+ batchDisplayPath,+ batchFilePaths,+ batchPreviewUrls,+} from '../api/assets'import { useGraphStore } from '../store/graphStore'+import type { RegisterAssetsResponse } from '../types'function isExamplePlaceholder(path: string): boolean {return path.replace(/\\/g, '/').replace(/^\.\//, '').startsWith('examples/')}-function blobToDataUrl(blob: Blob): Promise<string> {- return new Promise((resolve, reject) => {- const reader = new FileReader()- reader.onload = () => resolve(String(reader.result))- reader.onerror = () => reject(new Error('Could not read sample image'))- reader.readAsDataURL(blob)- })-}-/**- * For Load Image nodes that still point at examples/..., download the bundled- * sample via /api/sample-image and attach it like a normal file pick.+ * For Load Image nodes that still point at examples/..., register the bundled+ * sample via /api/assets/sample (no FormData copy).*/export async function materializeSampleImages(): Promise<void> {const { nodes, updateNodeParams, setLocalPreviews } = useGraphStore.getState()@@ -28,26 +25,21 @@ export async function materializeSampleImages(): Promise<void> {)if (targets.length === 0) return- const response = await fetch('/api/sample-image')+ const response = await fetch('/api/assets/sample', { method: 'POST' })if (!response.ok) {- throw new Error('Could not load sample image')+ throw new Error('Could not stage sample image')}- const blob = await response.blob()- const file = new File([blob], 'lena.png', { type: 'image/png' })- const dataUrl = await blobToDataUrl(blob)+ const result = (await response.json()) as RegisterAssetsResponse+ const path = batchDisplayPath(result.batch)+ const urls = batchPreviewUrls(result.batch)+ const files = batchFilePaths(result.batch)for (const node of targets) {- const body = new FormData()- body.append('files', file)- const upload = await fetch('/api/uploads?as_folder=false', {- method: 'POST',- body,+ // Share one registered batch across all example Load Image nodes.+ updateNodeParams(node.id, {+ path,+ asset_batch_id: result.batch.id,})- if (!upload.ok) {- throw new Error('Could not stage sample image')- }- const result = (await upload.json()) as { path: string; files: string[] }- updateNodeParams(node.id, { path: result.path })- setLocalPreviews(node.id, [dataUrl], result.files)+ setLocalPreviews(node.id, urls, files)}}