Skip to content

Image Pipeline Playground

feat(backend/api): serve bundled sample image for examples

Mohammad Rajaei2f2b6158035f
diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py
index 8bc926d..b0e94ea 100644
--- a/backend/app/api/routes.py
+++ b/backend/app/api/routes.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import sys
import uuid
from pathlib import Path
@@ -50,12 +51,38 @@ def _allowed_extension(filename: str) -> bool:
return suffix in {ext.lower() for ext in IMAGE_EXTENSIONS}
+def _sample_lena_path() -> Path | None:
+ """Locate bundled Lena used by example templates."""
+ candidates = [
+ Path(__file__).resolve().parents[2] / "examples" / "lena.png",
+ Path.cwd() / "examples" / "lena.png",
+ ]
+ if getattr(sys, "frozen", False):
+ candidates.append(Path(sys.executable).resolve().parent / "examples" / "lena.png")
+ meipass = getattr(sys, "_MEIPASS", None)
+ if meipass:
+ candidates.append(Path(meipass) / "examples" / "lena.png")
+ for path in candidates:
+ if path.is_file():
+ return path
+ return None
+
+
@router.get("/nodes", response_model=list[NodeMetadata])
def list_nodes() -> list[NodeMetadata]:
register_builtin_nodes()
return registry.list_metadata()
[email protected]("/sample-image")
+def sample_image() -> FileResponse:
+ """Return the bundled sample image for example workflows."""
+ path = _sample_lena_path()
+ if path is None:
+ raise HTTPException(status_code=404, detail="Sample image not found")
+ return FileResponse(path, media_type="image/png", filename="lena.png")
+
+
@router.post("/uploads", response_model=UploadResponse)
async def upload_images(
files: list[UploadFile] = File(...),
diff --git a/backend/app/nodes/io.py b/backend/app/nodes/io.py
index d258042..7b97541 100644
--- a/backend/app/nodes/io.py
+++ b/backend/app/nodes/io.py
@@ -26,7 +26,6 @@ from app.nodes.common import (
select_param,
string_param,
)
-from app.paths import resolve_load_path
def _normalized_extensions(extensions: list[str] | None = None) -> set[str]:
@@ -81,7 +80,7 @@ class LoadImageNode(BaseNode):
current_source_stems.set([])
return
try:
- files = list_image_files(resolve_load_path(path_value))
+ files = list_image_files(Path(path_value))
current_source_stems.set([file_path.stem for file_path in files])
except (OSError, ValueError, FileNotFoundError):
current_source_stems.set([])
@@ -95,7 +94,7 @@ class LoadImageNode(BaseNode):
path_value = str(params["path"])
if not path_value:
raise ValueError("Load Images requires a file or folder selection")
- path = resolve_load_path(path_value)
+ path = Path(path_value)
files = list_image_files(path)
current_source_stems.set([file_path.stem for file_path in files])
images = [read_image(file_path) for file_path in files]
@@ -108,7 +107,7 @@ class LoadImageNode(BaseNode):
input_vars: dict[str, str],
output_vars: dict[str, str],
) -> list[str]:
- path = str(resolve_load_path(str(params["path"])))
+ path = params["path"]
dst = output_vars["image"]
return [
f"_path = Path({path!r})",
diff --git a/backend/app/paths.py b/backend/app/paths.py
index 3c633f3..64955c7 100644
--- a/backend/app/paths.py
+++ b/backend/app/paths.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import os
-import sys
from pathlib import Path
@@ -18,50 +17,6 @@ def data_root() -> Path:
return root
-def examples_dir() -> Path:
- """Directory containing bundled example assets (e.g. lena.png)."""
- override = os.environ.get("IMAGE_PIPES_EXAMPLES_DIR")
- if override:
- return Path(override)
- # Source / normal install: backend/examples (this file is backend/app/paths.py)
- candidate = Path(__file__).resolve().parents[1] / "examples"
- if candidate.exists():
- return candidate
- if getattr(sys, "frozen", False):
- beside = Path(sys.executable).resolve().parent / "examples"
- if beside.exists():
- return beside
- meipass = getattr(sys, "_MEIPASS", None)
- if meipass:
- bundled = Path(meipass) / "examples"
- if bundled.exists():
- return bundled
- return candidate
-
-
-def resolve_load_path(path_value: str) -> Path:
- """Resolve a load_image path, including portable example-relative paths.
-
- Template workflows store paths like ``examples/lena.png``. Those only exist
- when the process cwd is the backend root; resolve against ``examples_dir()``
- so loads work regardless of how the server was started.
- """
- path = Path(path_value)
- if path.exists():
- return path
- if path.is_absolute():
- return path
- # ``examples/lena.png`` → ``<backend>/examples/lena.png``
- relative_to_backend = examples_dir().parent / path
- if relative_to_backend.exists():
- return relative_to_backend
- # Bare filename → look under examples/
- under_examples = examples_dir() / path
- if under_examples.exists():
- return under_examples
- return path
-
-
def cache_dir() -> Path:
path = data_root() / "cache"
path.mkdir(parents=True, exist_ok=True)
diff --git a/backend/tests/test_load_image.py b/backend/tests/test_load_image.py
index c64c9e1..89a86c1 100644
--- a/backend/tests/test_load_image.py
+++ b/backend/tests/test_load_image.py
@@ -10,7 +10,6 @@ import numpy as np
from app.engine.registry import registry
from app.nodes import register_builtin_nodes
from app.nodes.io import list_image_files
-from app.paths import examples_dir, resolve_load_path
def _write(path: Path, value: int) -> None:
@@ -46,25 +45,6 @@ def test_load_image_single_file_still_returns_list(tmp_path: Path) -> None:
assert len(loaded) == 1
-def test_resolve_load_path_finds_bundled_example(tmp_path: Path, monkeypatch) -> None:
- lena = examples_dir() / "lena.png"
- assert lena.is_file(), f"expected bundled example at {lena}"
- monkeypatch.chdir(tmp_path)
- resolved = resolve_load_path("examples/lena.png")
- assert resolved.resolve() == lena.resolve()
-
-
-def test_load_image_accepts_relative_example_path(tmp_path: Path, monkeypatch) -> None:
- register_builtin_nodes()
- monkeypatch.chdir(tmp_path)
- loaded = registry.get("load_image").execute(
- {}, {"path": "examples/lena.png"}, seed=0
- )["image"]
- assert isinstance(loaded, list)
- assert len(loaded) == 1
- assert loaded[0].ndim >= 2
-
-
def test_load_image_metadata_exposes_file_accept() -> None:
register_builtin_nodes()
meta = next(item for item in registry.list_metadata() if item.type == "load_image")
diff --git a/backend/tests/test_uploads.py b/backend/tests/test_uploads.py
index 3997dbc..720be19 100644
--- a/backend/tests/test_uploads.py
+++ b/backend/tests/test_uploads.py
@@ -9,6 +9,14 @@ from fastapi.testclient import TestClient
from app.main import app
+def test_sample_image_returns_lena() -> None:
+ client = TestClient(app)
+ response = client.get("/api/sample-image")
+ assert response.status_code == 200
+ assert response.headers.get("content-type", "").startswith("image/")
+ assert len(response.content) > 100
+
+
def test_delete_uploaded_file(tmp_path, monkeypatch) -> None:
uploads = tmp_path / "uploads"
uploads.mkdir()
diff --git a/desktop/README.md b/desktop/README.md
index 52b4cbf..06a21a3 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -25,16 +25,18 @@ cd backend && uv sync && uv run python run_server.py
cd frontend && npm run build # once, so FastAPI can serve the UI
```
-Or run everything from Electron (spawns `uv run python run_server.py` for you):
+Or run everything from Electron (spawns backend + Vite for you):
```bash
-cd frontend && npm run build
-cd ../backend && uv sync
+cd backend && uv sync
+cd ../frontend && npm install
cd ../desktop && npm install
cd .. && npm run desktop
```
-`npm run desktop` launches Electron with `--dev` (opens DevTools).
+`npm run desktop` launches Electron with `--dev`: it starts the FastAPI backend, starts the **Vite** frontend (hot reload), and loads that URL. Edit React code and the window updates without rebuilding.
+
+`npm run desktop:start` (no `--dev`) serves the built `frontend/dist` instead — run `npm run build:frontend` first for that path.
## What gets packaged
diff --git a/desktop/src/main.cjs b/desktop/src/main.cjs
index 962c17f..1856ae1 100644
--- a/desktop/src/main.cjs
+++ b/desktop/src/main.cjs
@@ -5,14 +5,20 @@ const net = require('node:net')
const path = require('node:path')
const fs = require('node:fs')
-const DEFAULT_PORT = 8765
-const isDev = process.argv.includes('--dev') || !app.isPackaged
+const DEFAULT_BACKEND_PORT = 8000
+const DEFAULT_VITE_PORT = 5173
+/** Vite HMR UI — only when launched with `electron . --dev` (npm run desktop). */
+const useViteDev = process.argv.includes('--dev') && !app.isPackaged
+const isDev = useViteDev || !app.isPackaged
/** @type {import('node:child_process').ChildProcess | null} */
let backendProcess = null
+/** @type {import('node:child_process').ChildProcess | null} */
+let viteProcess = null
/** @type {BrowserWindow | null} */
let mainWindow = null
-let backendPort = DEFAULT_PORT
+let backendPort = DEFAULT_BACKEND_PORT
+let vitePort = DEFAULT_VITE_PORT
function repoRoot() {
// desktop/src -> desktop -> repo
@@ -47,15 +53,15 @@ function findFreePort(startPort) {
})
}
-function waitForHealth(port, timeoutMs = 90000) {
+function waitForHttpOk(port, pathName, label, timeoutMs = 90000) {
const started = Date.now()
return new Promise((resolve, reject) => {
const tick = () => {
const req = http.get(
- { host: '127.0.0.1', port, path: '/api/health', timeout: 1500 },
+ { host: '127.0.0.1', port, path: pathName, timeout: 1500 },
(res) => {
res.resume()
- if (res.statusCode === 200) {
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 500) {
resolve()
return
}
@@ -70,7 +76,7 @@ function waitForHealth(port, timeoutMs = 90000) {
}
const retry = () => {
if (Date.now() - started > timeoutMs) {
- reject(new Error('Backend did not become healthy in time'))
+ reject(new Error(`${label} did not become ready in time`))
return
}
setTimeout(tick, 400)
@@ -91,9 +97,12 @@ function buildBackendEnv(port) {
PYTHONUNBUFFERED: '1',
}
- const frontendDist = path.join(repoRoot(), 'frontend', 'dist')
- if (fs.existsSync(frontendDist)) {
- env.IMAGE_PIPES_FRONTEND_DIST = frontendDist
+ // Production / non-Vite desktop: FastAPI serves the built SPA.
+ if (!useViteDev) {
+ const frontendDist = path.join(repoRoot(), 'frontend', 'dist')
+ if (fs.existsSync(frontendDist)) {
+ env.IMAGE_PIPES_FRONTEND_DIST = frontendDist
+ }
}
if (app.isPackaged) {
@@ -106,6 +115,15 @@ function buildBackendEnv(port) {
return env
}
+function attachProcessLogs(child, label) {
+ const log = (chunk) => {
+ const text = chunk.toString()
+ if (text.trim()) console.log(`[${label}] ${text.trimEnd()}`)
+ }
+ child.stdout?.on('data', log)
+ child.stderr?.on('data', log)
+}
+
function spawnBackend(port) {
const env = buildBackendEnv(port)
const cwdBackend = path.join(repoRoot(), 'backend')
@@ -124,10 +142,8 @@ function spawnBackend(port) {
windowsHide: true,
})
} else {
- // Dev / unpackaged: prefer `uv run`, fall back to python.
const runServer = path.join(cwdBackend, 'run_server.py')
- const uvArgs = ['run', 'python', runServer]
- backendProcess = spawn('uv', uvArgs, {
+ backendProcess = spawn('uv', ['run', 'python', runServer], {
cwd: cwdBackend,
env,
stdio: ['ignore', 'pipe', 'pipe'],
@@ -136,35 +152,62 @@ function spawnBackend(port) {
})
}
- const log = (chunk) => {
- const text = chunk.toString()
- if (text.trim()) console.log(`[backend] ${text.trimEnd()}`)
- }
- backendProcess.stdout?.on('data', log)
- backendProcess.stderr?.on('data', log)
+ attachProcessLogs(backendProcess, 'backend')
backendProcess.on('exit', (code, signal) => {
console.log(`[backend] exited code=${code} signal=${signal}`)
backendProcess = null
})
}
-function stopBackend() {
- if (!backendProcess || backendProcess.killed) return
+function spawnVite(port, apiPort) {
+ const frontendDir = path.join(repoRoot(), 'frontend')
+ viteProcess = spawn('npm', ['run', 'dev', '--', '--host', '127.0.0.1', '--port', String(port)], {
+ cwd: frontendDir,
+ env: {
+ ...process.env,
+ IMAGE_PIPES_API_PROXY: `http://127.0.0.1:${apiPort}`,
+ IMAGE_PIPES_VITE_PORT: String(port),
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ shell: process.platform === 'win32',
+ windowsHide: true,
+ })
+
+ attachProcessLogs(viteProcess, 'vite')
+ viteProcess.on('exit', (code, signal) => {
+ console.log(`[vite] exited code=${code} signal=${signal}`)
+ viteProcess = null
+ })
+}
+
+function stopProcess(child) {
+ if (!child || child.killed || child.pid == null) return
try {
if (process.platform === 'win32') {
- spawn('taskkill', ['/pid', String(backendProcess.pid), '/f', '/t'], {
+ spawn('taskkill', ['/pid', String(child.pid), '/f', '/t'], {
stdio: 'ignore',
windowsHide: true,
})
} else {
- backendProcess.kill('SIGTERM')
+ child.kill('SIGTERM')
}
} catch (error) {
- console.error('Failed to stop backend', error)
+ console.error('Failed to stop process', error)
}
+}
+
+function stopChildren() {
+ stopProcess(viteProcess)
+ viteProcess = null
+ stopProcess(backendProcess)
backendProcess = null
}
+function uiUrl() {
+ if (useViteDev) return `http://127.0.0.1:${vitePort}`
+ return `http://127.0.0.1:${backendPort}`
+}
+
async function createWindow() {
mainWindow = new BrowserWindow({
width: 1440,
@@ -188,10 +231,9 @@ async function createWindow() {
return { action: 'deny' }
})
- const url = `http://127.0.0.1:${backendPort}`
- await mainWindow.loadURL(url)
+ await mainWindow.loadURL(uiUrl())
- if (isDev) {
+ if (useViteDev) {
mainWindow.webContents.openDevTools({ mode: 'detach' })
}
@@ -201,9 +243,16 @@ async function createWindow() {
}
async function bootstrap() {
- backendPort = await findFreePort(DEFAULT_PORT)
+ backendPort = await findFreePort(DEFAULT_BACKEND_PORT)
spawnBackend(backendPort)
- await waitForHealth(backendPort)
+ await waitForHttpOk(backendPort, '/api/health', 'Backend')
+
+ if (useViteDev) {
+ vitePort = await findFreePort(DEFAULT_VITE_PORT)
+ spawnVite(vitePort, backendPort)
+ await waitForHttpOk(vitePort, '/', 'Vite')
+ }
+
await createWindow()
}
@@ -211,22 +260,24 @@ app.whenReady().then(() => {
Menu.setApplicationMenu(null)
void bootstrap().catch(async (error) => {
console.error(error)
- stopBackend()
+ stopChildren()
await dialog.showErrorBox(
'Image Pipes failed to start',
`${error instanceof Error ? error.message : String(error)}\n\n` +
- 'Dev tip: run `uv sync` in backend/ and `npm run build` in frontend/.',
+ (useViteDev
+ ? 'Dev tip: run `uv sync` in backend/ and `npm install` in frontend/.'
+ : 'Dev tip: run `uv sync` in backend/ and `npm run build` in frontend/.'),
)
app.quit()
})
})
app.on('before-quit', () => {
- stopBackend()
+ stopChildren()
})
app.on('window-all-closed', () => {
- stopBackend()
+ stopChildren()
if (process.platform !== 'darwin') app.quit()
})
diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx
index 8248cd5..0e77352 100644
--- a/frontend/src/app/App.tsx
+++ b/frontend/src/app/App.tsx
@@ -16,6 +16,7 @@ import {
import { useWorkflowPersistence } from '../hooks/useWorkflowPersistence'
import { notifyError, notifyInfo, notifySuccess } from '../notify'
import { downloadWorkflowJson, parseWorkflowJson } from '../workflow/io'
+import { materializeSampleImages } from '../workflow/materializeSampleImages'
import type { WorkflowTemplate } from '../workflow/templates'
import { AppHeader } from './AppHeader'
@@ -53,9 +54,10 @@ export default function App() {
}
}
- const applyLoadedWorkflow = (text: string, successMessage: string) => {
+ const applyLoadedWorkflow = async (text: string, successMessage: string) => {
const doc = parseWorkflowJson(text)
const { skippedTypes } = loadWorkflow(doc)
+ await materializeSampleImages()
if (skippedTypes.length > 0) {
notifyInfo(`${successMessage} (skipped unknown nodes: ${skippedTypes.join(', ')})`)
} else {
@@ -76,7 +78,7 @@ export default function App() {
if (!file) return
try {
const text = await file.text()
- applyLoadedWorkflow(text, 'Workflow loaded')
+ await applyLoadedWorkflow(text, 'Workflow loaded')
} catch (error) {
notifyError(error instanceof Error ? error.message : 'Load failed')
} finally {
@@ -99,7 +101,7 @@ export default function App() {
throw new Error(`Could not fetch template (${response.status})`)
}
const text = await response.text()
- applyLoadedWorkflow(text, `Loaded “${template.name}”`)
+ await applyLoadedWorkflow(text, `Loaded “${template.name}”`)
setTemplatesOpen(false)
} catch (error) {
notifyError(error instanceof Error ? error.message : 'Template load failed')
diff --git a/frontend/src/app/AppHeader.tsx b/frontend/src/app/AppHeader.tsx
index 083db40..89ff8d8 100644
--- a/frontend/src/app/AppHeader.tsx
+++ b/frontend/src/app/AppHeader.tsx
@@ -2,6 +2,8 @@ import {
Box,
Button,
IconButton,
+ Menu,
+ MenuItem,
Stack,
TextField,
Typography,
@@ -168,6 +170,10 @@ export function AppHeader({
const nodeCount = useGraphStore((s) => s.nodes.length)
const edgeCount = useGraphStore((s) => s.edges.length)
const [infoOpen, setInfoOpen] = useState(false)
+ const [exportAnchor, setExportAnchor] = useState<null | HTMLElement>(null)
+ const exportMenuOpen = Boolean(exportAnchor)
+
+ const closeExportMenu = () => setExportAnchor(null)
return (
<Box
@@ -303,7 +309,18 @@ export function AppHeader({
/>
</Stack>
- <Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
+ <Stack
+ direction="row"
+ spacing={1}
+ sx={{
+ alignItems: 'center',
+ px: 0.75,
+ py: 0.5,
+ borderRadius: 1.5,
+ bgcolor: 'rgba(0,0,0,0.28)',
+ border: '1px solid rgba(255,255,255,0.06)',
+ }}
+ >
{isExecuting ? (
<Button
variant="outlined"
@@ -339,7 +356,9 @@ export function AppHeader({
fontSize: 13,
bgcolor: isExecuting ? '#5a4a3a' : '#e67e22',
color: '#0f0f0f',
- boxShadow: isExecuting ? 'none' : '0 0 0 1px rgba(230,126,34,0.35), 0 8px 20px rgba(230,126,34,0.22)',
+ boxShadow: isExecuting
+ ? 'none'
+ : '0 0 0 1px rgba(230,126,34,0.35), 0 8px 20px rgba(230,126,34,0.22)',
'&:hover': { bgcolor: '#f39c12' },
'&.Mui-disabled': {
bgcolor: 'rgba(230,126,34,0.35)',
@@ -379,7 +398,20 @@ export function AppHeader({
>
Run to selected
</Button>
+ </Stack>
+ <Stack
+ direction="row"
+ spacing={1}
+ sx={{
+ alignItems: 'center',
+ px: 0.75,
+ py: 0.5,
+ borderRadius: 1.5,
+ bgcolor: 'rgba(0,0,0,0.28)',
+ border: '1px solid rgba(255,255,255,0.06)',
+ }}
+ >
<Button
variant="outlined"
disabled={isExecuting}
@@ -401,20 +433,75 @@ export function AppHeader({
<Button
variant="outlined"
disabled={isExecuting}
- onClick={onExportWorkflow}
+ aria-haspopup="menu"
+ aria-expanded={exportMenuOpen ? 'true' : undefined}
+ aria-controls={exportMenuOpen ? 'export-menu' : undefined}
+ onClick={(event) => setExportAnchor(event.currentTarget)}
sx={outlineBtnSx}
>
Export
+ <Box component="span" sx={{ ml: 0.75, fontSize: 10, opacity: 0.7, lineHeight: 1 }}>
+ ▾
+ </Box>
</Button>
- <Button
- variant="outlined"
- disabled={isExecuting}
- onClick={onExportPython}
- sx={outlineBtnSx}
+ <Menu
+ id="export-menu"
+ anchorEl={exportAnchor}
+ open={exportMenuOpen}
+ onClose={closeExportMenu}
+ anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
+ transformOrigin={{ vertical: 'top', horizontal: 'right' }}
+ slotProps={{
+ paper: {
+ elevation: 0,
+ sx: {
+ mt: 0.75,
+ minWidth: 180,
+ bgcolor: '#161616',
+ color: '#f4f1ea',
+ border: '1px solid rgba(255,255,255,0.1)',
+ borderRadius: 1.5,
+ overflow: 'hidden',
+ boxShadow: '0 18px 40px rgba(0,0,0,0.55)',
+ backgroundImage: 'none',
+ },
+ },
+ list: {
+ dense: true,
+ sx: { py: 0.5 },
+ },
+ }}
>
- Export Python
- </Button>
+ <MenuItem
+ onClick={() => {
+ closeExportMenu()
+ onExportWorkflow()
+ }}
+ sx={{
+ fontSize: 13,
+ fontWeight: 600,
+ py: 1,
+ '&:hover': { bgcolor: 'rgba(125,206,160,0.1)' },
+ }}
+ >
+ Workflow JSON
+ </MenuItem>
+ <MenuItem
+ onClick={() => {
+ closeExportMenu()
+ onExportPython()
+ }}
+ sx={{
+ fontSize: 13,
+ fontWeight: 600,
+ py: 1,
+ '&:hover': { bgcolor: 'rgba(125,206,160,0.1)' },
+ }}
+ >
+ Python script
+ </MenuItem>
+ </Menu>
</Stack>
</Box>
)
diff --git a/frontend/src/hooks/useWorkflowPersistence.ts b/frontend/src/hooks/useWorkflowPersistence.ts
index f9e4338..4fdc5e0 100644
--- a/frontend/src/hooks/useWorkflowPersistence.ts
+++ b/frontend/src/hooks/useWorkflowPersistence.ts
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import { useGraphStore } from '../store/graphStore'
+import { materializeSampleImages } from '../workflow/materializeSampleImages'
import { loadWorkflowSession, saveWorkflowSession } from '../workflow/persist'
const SAVE_DEBOUNCE_MS = 400
@@ -25,6 +26,9 @@ export function useWorkflowPersistence() {
const saved = loadWorkflowSession()
if (saved && saved.graph.nodes.length > 0) {
loadWorkflow(saved)
+ void materializeSampleImages().catch(() => {
+ // Session may already have real upload paths; ignore sample staging failures.
+ })
}
setSessionReady(true)
}, [nodeCatalog, loadWorkflow])
diff --git a/frontend/src/workflow/materializeSampleImages.ts b/frontend/src/workflow/materializeSampleImages.ts
new file mode 100644
index 0000000..0615890
--- /dev/null
+++ b/frontend/src/workflow/materializeSampleImages.ts
@@ -0,0 +1,55 @@
+/** Turn template placeholder paths like examples/lena.png into real uploads. */
+
+import { useGraphStore } from '../store/graphStore'
+
+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.
+ */
+export async function materializeSampleImages(): Promise<void> {
+ const { nodes, updateNodeParams, setLocalPreviews, setSampleCount } =
+ useGraphStore.getState()
+ const targets = nodes.filter(
+ (node) =>
+ node.data.type === 'load_image' &&
+ isExamplePlaceholder(String(node.data.params.path ?? '')),
+ )
+ if (targets.length === 0) return
+
+ const response = await fetch('/api/sample-image')
+ if (!response.ok) {
+ throw new Error('Could not load sample image')
+ }
+ const blob = await response.blob()
+ const file = new File([blob], 'lena.png', { type: 'image/png' })
+ const dataUrl = await blobToDataUrl(blob)
+
+ 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,
+ })
+ 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)
+ }
+ setSampleCount(1)
+}
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 88eb390..8999ee0 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -1,17 +1,21 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
+const apiTarget = process.env.IMAGE_PIPES_API_PROXY || 'http://127.0.0.1:8000'
+const vitePort = Number(process.env.IMAGE_PIPES_VITE_PORT || 5173)
+
export default defineConfig({
plugins: [react()],
server: {
- port: 5173,
+ port: vitePort,
+ strictPort: true,
proxy: {
'/api': {
- target: 'http://127.0.0.1:8000',
+ target: apiTarget,
changeOrigin: true,
},
'/ws': {
- target: 'ws://127.0.0.1:8000',
+ target: apiTarget.replace(/^http/, 'ws'),
ws: true,
},
},