Image Pipeline Playground
feat(frontend): auto-download Save Image ZIP after pipeline run
Mohammad Rajaei832e1cc64382
diff --git a/.gitignore b/.gitignoreindex 9b709ec..53ce920 100644--- a/.gitignore+++ b/.gitignore@@ -21,6 +21,8 @@ backend/uploads/*!backend/uploads/.gitkeepbackend/outputs/*!backend/outputs/.gitkeep+backend/outputs/downloads/*+!backend/outputs/downloads/.gitkeep# Node / frontendnode_modules/diff --git a/backend/app/api/routes.py b/backend/app/api/routes.pyindex 7ec1de6..1d831d4 100644--- a/backend/app/api/routes.py+++ b/backend/app/api/routes.py@@ -6,6 +6,7 @@ import uuidfrom pathlib import Pathfrom fastapi import APIRouter, File, HTTPException, UploadFile+from fastapi.responses import FileResponsefrom pydantic import BaseModelfrom app.engine.executor import DagExecutor@@ -154,7 +155,7 @@ def delete_uploaded_file(path: str) -> dict[str, str]:@router.post("/outputs", response_model=OutputDirResponse)def create_output_directory() -> OutputDirResponse:- """Create a new root folder under outputs/ for Save Image nodes."""+ """Create a new root folder under outputs/ (legacy helper)."""OUTPUT_DIR.mkdir(parents=True, exist_ok=True)name = uuid.uuid4().hex[:12]folder = OUTPUT_DIR / name@@ -162,6 +163,27 @@ def create_output_directory() -> OutputDirResponse:return OutputDirResponse(path=str(folder.resolve()), name=name)[email protected]("/downloads/{filename}")+def download_result_archive(filename: str) -> FileResponse:+ """Serve a ZIP produced by Save Image nodes during a pipeline run."""+ from app.engine.save_bundle import DOWNLOAD_DIR++ safe_name = Path(filename).name+ if safe_name != filename or not safe_name.endswith(".zip"):+ raise HTTPException(status_code=400, detail="Invalid download name")+ target = (DOWNLOAD_DIR / safe_name).resolve()+ downloads_root = DOWNLOAD_DIR.resolve()+ if downloads_root not in target.parents and target != downloads_root:+ raise HTTPException(status_code=400, detail="Path is outside downloads directory")+ if not target.is_file():+ raise HTTPException(status_code=404, detail="Download not found")+ return FileResponse(+ path=target,+ media_type="application/zip",+ filename=safe_name,+ )++@router.post("/execute")def execute_graph(request: ExecuteRequest) -> dict:register_builtin_nodes()diff --git a/backend/app/engine/executor.py b/backend/app/engine/executor.pyindex faf8827..1a394d8 100644--- a/backend/app/engine/executor.py+++ b/backend/app/engine/executor.py@@ -16,6 +16,7 @@ import numpy as npfrom app.engine.cache import CacheManagerfrom app.engine.registry import NodeRegistry, registryfrom app.engine.run_context import current_sample_index+from app.engine.save_bundle import SaveBundle, current_save_bundlefrom app.models.graph import (Edge,ExecuteRequest,@@ -267,101 +268,121 @@ class DagExecutor:order = [node_id for node_id in order if node_id in keep]sample_count = max(1, request.sample_count)results: dict[str, Any] = {"order": order, "samples": []}+ save_bundle = SaveBundle()+ bundle_token = current_save_bundle.set(save_bundle)def emit(event: ExecutionEvent) -> None:if on_event is not None:on_event(event)- for sample_index in range(sample_count):- cancel.check()- sample_seed = request.seed + sample_index- sample_token = current_sample_index.set(sample_index)- outputs: dict[str, dict[str, np.ndarray | list[np.ndarray]]] = {}- sample_previews: dict[str, Any] = {}-- try:- for index, node_id in enumerate(order):- cancel.check()- instance = nodes[node_id]- node_impl = self.registry.get(instance.type)- params = node_impl.validate_params(instance.params)- node_impl.prepare_run(params)- inputs = _collect_inputs(- node_id,- request.graph.edges,- outputs,- sample_index=sample_index,- )- input_hash_map = _input_hashes(inputs, self.cache)- cache_key = self.cache.make_key(- instance.type, params, input_hash_map, sample_seed- )-- emit(- ExecutionEvent(- type=ExecutionEventType.PROGRESS,- node_id=node_id,- progress=(index + 1) / len(order),+ try:+ for sample_index in range(sample_count):+ cancel.check()+ sample_seed = request.seed + sample_index+ sample_token = current_sample_index.set(sample_index)+ outputs: dict[str, dict[str, np.ndarray | list[np.ndarray]]] = {}+ sample_previews: dict[str, Any] = {}++ try:+ for index, node_id in enumerate(order):+ cancel.check()+ instance = nodes[node_id]+ node_impl = self.registry.get(instance.type)+ params = node_impl.validate_params(instance.params)+ node_impl.prepare_run(params)+ inputs = _collect_inputs(+ node_id,+ request.graph.edges,+ outputs,sample_index=sample_index,- message=f"Executing {instance.type}",)- )+ input_hash_map = _input_hashes(inputs, self.cache)+ cache_key = self.cache.make_key(+ instance.type, params, input_hash_map, sample_seed+ )++ emit(+ ExecutionEvent(+ type=ExecutionEventType.PROGRESS,+ node_id=node_id,+ progress=(index + 1) / len(order),+ sample_index=sample_index,+ message=f"Executing {instance.type}",+ )+ )- cache_hit = False- produced: dict[str, np.ndarray | list[np.ndarray]]- started = time.perf_counter()- use_cache = request.cache and node_impl.cacheable- if use_cache and self.cache.has_outputs(cache_key):- cached = self.cache.get_outputs(cache_key)- if cached is not None:- produced = cached+ cache_hit = False+ produced: dict[str, np.ndarray | list[np.ndarray]]+ started = time.perf_counter()+ use_cache = request.cache and node_impl.cacheable+ if use_cache and self.cache.has_outputs(cache_key):+ cached = self.cache.get_outputs(cache_key)+ if cached is not None:+ produced = cached+ outputs[node_id] = produced+ cache_hit = True++ if not cache_hit:+ produced = node_impl.execute(inputs, params, seed=sample_seed)outputs[node_id] = produced- cache_hit = True-- if not cache_hit:- produced = node_impl.execute(inputs, params, seed=sample_seed)- outputs[node_id] = produced- if use_cache:- self.cache.put_outputs(- cache_key,- produced,- meta={"node_id": node_id, "type": instance.type},+ if use_cache:+ self.cache.put_outputs(+ cache_key,+ produced,+ meta={"node_id": node_id, "type": instance.type},+ )++ duration_ms = (time.perf_counter() - started) * 1000.0+ emit(+ ExecutionEvent(+ type=ExecutionEventType.PROGRESS,+ node_id=node_id,+ progress=(index + 1) / len(order),+ sample_index=sample_index,+ cache_hit=cache_hit,+ duration_ms=duration_ms,+ message=(+ f"Finished {instance.type} in {duration_ms:.1f}ms"+ + (" (cache)" if cache_hit else "")+ ),)+ )- duration_ms = (time.perf_counter() - started) * 1000.0- emit(- ExecutionEvent(- type=ExecutionEventType.PROGRESS,+ _emit_port_previews(+ emit=emit,node_id=node_id,- progress=(index + 1) / len(order),+ produced=produced,sample_index=sample_index,cache_hit=cache_hit,- duration_ms=duration_ms,- message=(- f"Finished {instance.type} in {duration_ms:.1f}ms"- + (" (cache)" if cache_hit else "")- ),+ sample_previews=sample_previews,)- )- _emit_port_previews(- emit=emit,- node_id=node_id,- produced=produced,- sample_index=sample_index,- cache_hit=cache_hit,- sample_previews=sample_previews,+ results["samples"].append(+ {+ "sample_index": sample_index,+ "seed": sample_seed,+ "previews": sample_previews,+ })+ finally:+ current_sample_index.reset(sample_token)- results["samples"].append(- {- "sample_index": sample_index,- "seed": sample_seed,- "previews": sample_previews,- }+ if save_bundle.files:+ zip_path = save_bundle.write_zip()+ download_name = zip_path.name+ emit(+ ExecutionEvent(+ type=ExecutionEventType.DOWNLOAD,+ message=f"Ready to download {len(save_bundle.files)} image(s)",+ download_url=f"/api/downloads/{download_name}",+ download_filename=download_name,+ data={"count": len(save_bundle.files)},+ ))- finally:- current_sample_index.reset(sample_token)+ results["download_url"] = f"/api/downloads/{download_name}"+ results["download_filename"] = download_name- emit(ExecutionEvent(type=ExecutionEventType.DONE, message="Execution complete"))- return results+ emit(ExecutionEvent(type=ExecutionEventType.DONE, message="Execution complete"))+ return results+ finally:+ current_save_bundle.reset(bundle_token)diff --git a/backend/app/engine/save_bundle.py b/backend/app/engine/save_bundle.pynew file mode 100644index 0000000..8cf6576--- /dev/null+++ b/backend/app/engine/save_bundle.py@@ -0,0 +1,80 @@+"""Collect Save Image outputs into a downloadable ZIP for the browser."""++from __future__ import annotations++import io+import uuid+import zipfile+from contextvars import ContextVar+from dataclasses import dataclass, field+from datetime import datetime+from pathlib import Path++import cv2+import numpy as np++DOWNLOAD_DIR = Path(__file__).resolve().parents[2] / "outputs" / "downloads"+++@dataclass+class SaveBundle:+ """In-memory image files that will be zipped at the end of a run."""++ files: dict[str, bytes] = field(default_factory=dict)++ def add_image(self, name: str, image: np.ndarray) -> str:+ safe = Path(name).name or "image.png"+ suffix = Path(safe).suffix.lower()+ if suffix not in {".png", ".jpg", ".jpeg", ".bmp", ".webp"}:+ safe = f"{Path(safe).stem}.png"+ suffix = ".png"+ final_name = safe+ stem = Path(safe).stem+ file_suffix = Path(safe).suffix+ index = 2+ while final_name in self.files:+ final_name = f"{stem}_{index}{file_suffix}"+ index += 1+ encode_ext = ".jpg" if suffix in {".jpg", ".jpeg"} else suffix+ success, buffer = cv2.imencode(encode_ext, image)+ if not success:+ success, buffer = cv2.imencode(".png", image)+ final_name = f"{Path(final_name).stem}.png"+ if not success:+ raise RuntimeError(f"Failed to encode image for '{final_name}'")+ self.files[final_name] = buffer.tobytes()+ return final_name++ def write_zip(self, destination: Path | None = None) -> Path:+ if not self.files:+ raise ValueError("No images were saved")+ DOWNLOAD_DIR.mkdir(parents=True, exist_ok=True)+ stamp = datetime.now().strftime("%Y%m%d_%H%M%S")+ out = destination or (DOWNLOAD_DIR / f"results_{stamp}_{uuid.uuid4().hex[:8]}.zip")+ out.parent.mkdir(parents=True, exist_ok=True)+ with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED) as archive:+ for name, payload in self.files.items():+ archive.writestr(name, payload)+ return out.resolve()+++current_save_bundle: ContextVar[SaveBundle | None] = ContextVar(+ "current_save_bundle",+ default=None,+)+++def get_save_bundle() -> SaveBundle:+ bundle = current_save_bundle.get()+ if bundle is None:+ raise RuntimeError("Save bundle is not available for this run")+ return bundle+++def zip_bytes(bundle: SaveBundle) -> bytes:+ """Return ZIP contents without writing to disk (tests / helpers)."""+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:+ for name, payload in bundle.files.items():+ archive.writestr(name, payload)+ return buffer.getvalue()diff --git a/backend/app/models/graph.py b/backend/app/models/graph.pyindex e12e5b0..2b3d78d 100644--- a/backend/app/models/graph.py+++ b/backend/app/models/graph.py@@ -59,6 +59,7 @@ class ExecutionEventType(StrEnum):ERROR = "error"DONE = "done"CANCELLED = "cancelled"+ DOWNLOAD = "download"class ExecutionEvent(BaseModel):@@ -72,6 +73,8 @@ class ExecutionEvent(BaseModel):cache_hit: bool | None = Noneduration_ms: float | None = Nonedata: dict[str, Any] | None = None+ download_url: str | None = None+ download_filename: str | None = Noneclass ParamField(BaseModel):diff --git a/backend/app/nodes/io.py b/backend/app/nodes/io.pyindex 6f42c45..7b97541 100644--- a/backend/app/nodes/io.py+++ b/backend/app/nodes/io.py@@ -15,6 +15,7 @@ from app.engine.run_context import (current_source_stems,source_stem_for_sample,)+from app.engine.save_bundle import get_save_bundlefrom app.nodes.common import (IMAGE_EXTENSIONS,file_param,@@ -131,18 +132,12 @@ class SaveImageNode(BaseNode):label = "Save Image"category = "io"description = (- "Write image(s) into a selected output folder. "+ "Collect image(s) into a ZIP download after the run. ""Filename supports templates: {filename}, {time}, {index}.")cacheable = Falseports = [image_in(), image_out()]params = [- string_param(- "directory",- "Output folder",- "",- description="Required. Choose a root folder to save into.",- ),string_param("filename","Filename",@@ -157,21 +152,15 @@ class SaveImageNode(BaseNode):params: dict[str, Any],seed: int = 0,) -> dict[str, np.ndarray | list[np.ndarray]]:- directory = str(params.get("directory", "")).strip()- if not directory:- raise ValueError("Save Image requires an output folder — choose one in the inspector")image = require_image(inputs)sample_index = current_sample_index.get()- path = resolve_save_path(- directory,+ name = resolve_save_filename(str(params.get("filename") or "{filename}_{index}.png"),index=sample_index,filename=source_stem_for_sample(sample_index),when=datetime.now(),)- path.parent.mkdir(parents=True, exist_ok=True)- if not cv2.imwrite(str(path), image):- raise RuntimeError(f"Failed to write image to '{path}'")+ get_save_bundle().add_image(name, image)return {"image": image}def emit_python(@@ -181,13 +170,14 @@ class SaveImageNode(BaseNode):input_vars: dict[str, str],output_vars: dict[str, str],) -> list[str]:- directory = str(params.get("directory", "")).strip()name_template = str(params.get("filename") or "{filename}_{index}.png")src = input_vars["image"]dst = output_vars["image"]return ["from datetime import datetime",- f"_dir = Path({directory!r})",+ "from pathlib import Path",+ "_out_dir = Path('output')",+ "_out_dir.mkdir(parents=True, exist_ok=True)",f"_name_template = {name_template!r}","_index = 0 # set per sample when batching","_filename = 'image'",@@ -202,27 +192,21 @@ class SaveImageNode(BaseNode):"and '{time}' not in _name_template and '{filename}' not in _name_template:")," _stem = Path(_name).stem",- " _suffix = Path(_name).suffix",+ " _suffix = Path(_name).suffix or '.png'"," _name = f'{_stem}_{_index}{_suffix}'",- "_path = _dir / _name",- "_path.parent.mkdir(parents=True, exist_ok=True)",- f"cv2.imwrite(str(_path), {src})",+ "cv2.imwrite(str(_out_dir / _name), " + src + ")",f"{dst} = {src}",]-def resolve_save_path(- directory: str,+def resolve_save_filename(name_template: str,*,index: int,filename: str,when: datetime,-) -> Path:- """Join a root folder with an expanded filename template."""- root = str(directory).strip()- if not root:- raise ValueError("Output folder is required")+) -> str:+ """Expand {filename}, {time}, {index} into a ZIP entry filename."""safe_name = Path(filename).stem or "image"safe_name = safe_name.replace("/", "_").replace("\\", "_")time_token = when.strftime("%Y%m%d_%H%M%S")@@ -231,15 +215,16 @@ def resolve_save_path(.replace("{time}", time_token).replace("{index}", str(index)))- # Filename only — ignore any directory components in the template.name = Path(expanded).name or f"image_{index}.png"+ if not Path(name).suffix:+ name = f"{name}.png"has_unique_token = any(token in name_template for token in ("{index}", "{time}", "{filename}"))if index > 0 and not has_unique_token:path_name = Path(name)name = f"{path_name.stem}_{index}{path_name.suffix}"- return Path(root) / name+ return nameclass PreviewNode(BaseNode):diff --git a/backend/tests/test_io_save_image.py b/backend/tests/test_io_save_image.pyindex cea57f9..16a4c49 100644--- a/backend/tests/test_io_save_image.py+++ b/backend/tests/test_io_save_image.py@@ -1,104 +1,80 @@-"""Tests for Save Image path templates and multi-sample writes."""+"""Tests for Save Image ZIP download flow."""from __future__ import annotationsfrom datetime import datetime-from pathlib import Pathimport cv2import numpy as np-import pytestfrom fastapi.testclient import TestClientfrom app.engine.executor import DagExecutorfrom app.engine.registry import registryfrom app.engine.run_context import current_sample_index, current_source_stems+from app.engine.save_bundle import SaveBundle, current_save_bundlefrom app.main import appfrom app.models.graph import Edge, ExecuteRequest, Graph, NodeInstancefrom app.nodes import register_builtin_nodes-from app.nodes.io import resolve_save_path+from app.nodes.io import resolve_save_filename-def test_resolve_save_path_templates(tmp_path) -> None:+def test_resolve_save_filename_templates() -> None:when = datetime(2026, 7, 30, 22, 55, 1)- path = resolve_save_path(- str(tmp_path),+ name = resolve_save_filename("{filename}_{index}_{time}.png",index=2,filename="lena",when=when,)- assert path == tmp_path / "lena_2_20260730_225501.png"+ assert name == "lena_2_20260730_225501.png"-def test_resolve_save_path_auto_index_when_missing(tmp_path) -> None:- path = resolve_save_path(- str(tmp_path),+def test_resolve_save_filename_auto_index_when_missing() -> None:+ name = resolve_save_filename("output.png",index=3,filename="x",when=datetime(2026, 1, 1, 0, 0, 0),)- assert path.name == "output_3.png"+ assert name == "output_3.png"-def test_resolve_save_path_requires_directory() -> None:- with pytest.raises(ValueError, match="Output folder is required"):- resolve_save_path(- " ",- "{index}.png",- index=0,- filename="a",- when=datetime(2026, 1, 1, 0, 0, 0),- )---def test_save_image_requires_directory() -> None:- register_builtin_nodes()- image = np.zeros((2, 2, 3), dtype=np.uint8)- with pytest.raises(ValueError, match="output folder"):- registry.get("save_image").execute(- {"image": image},- {"directory": "", "filename": "{index}.png"},- seed=0,- )---def test_save_image_uses_templates(tmp_path) -> None:+def test_save_image_adds_to_bundle(tmp_path, monkeypatch) -> None:register_builtin_nodes()+ monkeypatch.setattr("app.engine.save_bundle.DOWNLOAD_DIR", tmp_path / "downloads")image = np.zeros((4, 4, 3), dtype=np.uint8)image[:, :] = (10, 20, 30)+ bundle = SaveBundle()+ token_b = current_save_bundle.set(bundle)token_i = current_sample_index.set(1)token_s = current_source_stems.set(["photo"])try:out = registry.get("save_image").execute({"image": image},- {"directory": str(tmp_path), "filename": "{filename}_{index}.png"},+ {"filename": "{filename}_{index}.png"},seed=0,)["image"]finally:+ current_save_bundle.reset(token_b)current_sample_index.reset(token_i)current_source_stems.reset(token_s)assert out.shape == image.shape- saved = tmp_path / "photo_1.png"- assert saved.is_file()- loaded = cv2.imread(str(saved))- assert loaded is not None- assert tuple(loaded[0, 0]) == (10, 20, 30)+ assert "photo_1.png" in bundle.files+ assert len(bundle.files["photo_1.png"]) > 0-def test_save_image_batch_writes_unique_files(tmp_path) -> None:+def test_executor_emits_download_zip(tmp_path, monkeypatch) -> None:register_builtin_nodes()+ monkeypatch.setattr("app.engine.save_bundle.DOWNLOAD_DIR", tmp_path / "downloads")a = np.full((2, 2, 3), 1, dtype=np.uint8)b = np.full((2, 2, 3), 2, dtype=np.uint8)path_a = tmp_path / "a.png"path_b = tmp_path / "b.png"cv2.imwrite(str(path_a), a)cv2.imwrite(str(path_b), b)- out_dir = tmp_path / "out"- out_dir.mkdir()+ events: list[str] = []request = ExecuteRequest(graph=Graph(nodes=[@@ -110,10 +86,7 @@ def test_save_image_batch_writes_unique_files(tmp_path) -> None:NodeInstance(id="save",type="save_image",- params={- "directory": str(out_dir),- "filename": "{filename}_{index}.png",- },+ params={"filename": "{filename}_{index}.png"},),],edges=[@@ -128,21 +101,23 @@ def test_save_image_batch_writes_unique_files(tmp_path) -> None:),seed=0,sample_count=2,- cache=True,+ cache=False,)executor = DagExecutor(tmp_path / "cache", node_registry=registry)- executor.execute(request)-- assert (out_dir / "a_0.png").is_file()- assert (out_dir / "b_1.png").is_file()+ result = executor.execute(+ request,+ on_event=lambda event: events.append(event.type.value),+ )+ assert "download" in events+ assert result["download_url"].startswith("/api/downloads/")+ zip_name = result["download_filename"]+ zip_path = tmp_path / "downloads" / zip_name+ assert zip_path.is_file()-def test_create_output_directory(tmp_path, monkeypatch) -> None:- outputs = tmp_path / "outputs"- monkeypatch.setattr("app.api.routes.OUTPUT_DIR", outputs)client = TestClient(app)- response = client.post("/api/outputs")+ # Point API download dir to the same temp folder used by the executor.+ monkeypatch.setattr("app.engine.save_bundle.DOWNLOAD_DIR", tmp_path / "downloads")+ response = client.get(f"/api/downloads/{zip_name}")assert response.status_code == 200- body = response.json()- assert Path(body["path"]).is_dir()- assert Path(body["path"]).parent == outputs.resolve()+ assert response.headers["content-type"].startswith("application/zip")diff --git a/frontend/src/features/inspector/NodeInspector.tsx b/frontend/src/features/inspector/NodeInspector.tsxindex 28307e1..09d971f 100644--- a/frontend/src/features/inspector/NodeInspector.tsx+++ b/frontend/src/features/inspector/NodeInspector.tsx@@ -104,14 +104,9 @@ export function NodeInspector() {>{isSaveImage ? (<SaveImageParams- directory={String(selected.data.params.directory ?? '')}filename={String(selected.data.params.filename ?? '{filename}_{index}.png',)}- onDirectoryChange={(directory) => {- setValue('directory', directory, { shouldDirty: true, shouldValidate: true })- updateNodeParams(selected.id, { directory })- }}onFilenameChange={(filename) => {setValue('filename', filename, { shouldDirty: true, shouldValidate: true })updateNodeParams(selected.id, { filename })diff --git a/frontend/src/features/inspector/SaveImageParams.tsx b/frontend/src/features/inspector/SaveImageParams.tsxindex 650049f..0e167fd 100644--- a/frontend/src/features/inspector/SaveImageParams.tsx+++ b/frontend/src/features/inspector/SaveImageParams.tsx@@ -1,6 +1,4 @@-import { useState } from 'react'import { Box, Button, TextField, Typography } from '@mui/material'-import { notifyError, notifySuccess } from '../../notify'const SAVE_PATH_TEMPLATES = [{ token: '{filename}', hint: 'source stem' },@@ -9,93 +7,21 @@ const SAVE_PATH_TEMPLATES = [] as consttype SaveImageParamsProps = {- directory: stringfilename: string- onDirectoryChange: (directory: string) => voidonFilenameChange: (filename: string) => void}-export function SaveImageParams({- directory,- filename,- onDirectoryChange,- onFilenameChange,-}: SaveImageParamsProps) {- const [busy, setBusy] = useState(false)- const folderLabel = directory- ? directory.replace(/\\/g, '/').split('/').filter(Boolean).at(-1) ?? directory- : null-- const chooseFolder = async () => {- setBusy(true)- try {- const response = await fetch('/api/outputs', { method: 'POST' })- if (!response.ok) {- throw new Error((await response.text()) || 'Could not create output folder')- }- const body = (await response.json()) as { path: string; name: string }- onDirectoryChange(body.path)- notifySuccess(`Output folder ready: ${body.name}`)- } catch (error) {- notifyError(error instanceof Error ? error.message : 'Folder selection failed')- } finally {- setBusy(false)- }- }-+export function SaveImageParams({ filename, onFilenameChange }: SaveImageParamsProps) {const insertTemplate = (token: string) => {onFilenameChange(`${filename}${token}`)}return (<Box sx={{ display: 'grid', gap: 1.5 }}>- <Box sx={{ display: 'grid', gap: 0.75 }}>- <Typography- sx={{- fontSize: 10,- fontWeight: 700,- letterSpacing: '0.06em',- textTransform: 'uppercase',- color: 'rgba(244,241,234,0.4)',- }}- >- Output folder (required)- </Typography>- <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, alignItems: 'center' }}>- <Button- size="small"- variant="outlined"- disabled={busy}- onClick={() => void chooseFolder()}- sx={{ textTransform: 'none' }}- >- {directory ? 'Change folder' : 'Choose folder'}- </Button>- <Typography- sx={{- fontSize: 12,- color: directory ? 'rgba(244,241,234,0.75)' : '#ff8a80',- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',- wordBreak: 'break-all',- }}- >- {directory ? folderLabel : 'No folder selected'}- </Typography>- </Box>- {directory && (- <Typography- sx={{- fontSize: 11,- color: 'rgba(244,241,234,0.4)',- wordBreak: 'break-all',- lineHeight: 1.4,- }}- title={directory}- >- {directory}- </Typography>- )}- </Box>+ <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.+ </Typography><TextFieldsize="small"diff --git a/frontend/src/hooks/useExecutionSocket.ts b/frontend/src/hooks/useExecutionSocket.tsindex e534338..ae8aa6a 100644--- a/frontend/src/hooks/useExecutionSocket.ts+++ b/frontend/src/hooks/useExecutionSocket.ts@@ -106,6 +106,18 @@ export function useExecutionSocket() {setIsExecuting(false)setActiveNodeId(null)}+ if (event.type === 'download' && event.download_url) {+ const filename = event.download_filename ?? 'results.zip'+ appendLog(event.message ?? `Download ready: ${filename}`)+ const anchor = document.createElement('a')+ anchor.href = event.download_url+ anchor.download = filename+ anchor.rel = 'noopener'+ document.body.appendChild(anchor)+ anchor.click()+ anchor.remove()+ notifySuccess(event.message ?? `Downloading ${filename}`)+ }if (event.type === 'done') {appendLog(event.message ?? 'done')const target = targetLabelRef.currentdiff --git a/frontend/src/types/graph.ts b/frontend/src/types/graph.tsindex ccbd99b..3e4d970 100644--- a/frontend/src/types/graph.ts+++ b/frontend/src/types/graph.ts@@ -61,6 +61,7 @@ export type ExecutionEventType =| 'error'| 'done'| 'cancelled'+ | 'download'export interface ExecutionEvent {type: ExecutionEventType@@ -72,4 +73,7 @@ export interface ExecutionEvent {sample_index?: number | nullcache_hit?: boolean | nullduration_ms?: number | null+ data?: Record<string, unknown> | null+ download_url?: string | null+ download_filename?: string | null}