Image Pipeline Playground
feat(backend): implement user script functionality with API and execution support
Mohammad Rajaei472a4d1c2022
diff --git a/backend/app/api/routes.py b/backend/app/api/routes.pyindex 0338794..ef39cd7 100644--- a/backend/app/api/routes.py+++ b/backend/app/api/routes.py@@ -11,17 +11,20 @@ from fastapi import APIRouter, File, HTTPException, UploadFilefrom fastapi.responses import FileResponsefrom pydantic import BaseModel+from app.api.user_scripts import router as user_scripts_routerfrom app.engine.executor import DagExecutorfrom app.engine.registry import registryfrom app.models.assets import RegisterAssetsRequest, RegisterAssetsResponsefrom app.models.graph import ExecuteRequest, Graph, NodeMetadatafrom app.nodes import register_builtin_nodesfrom app.nodes.common import IMAGE_EXTENSIONS+from app.nodes.user_script import register_user_scriptsfrom app.paths import cache_dir, upload_dirfrom app.services import assets as assets_servicefrom app.services.codegen import generate_pythonrouter = APIRouter(prefix="/api")+router.include_router(user_scripts_router)CACHE_DIR = cache_dir()UPLOAD_DIR = upload_dir()@@ -69,6 +72,7 @@ def _sample_lena_path() -> Path | None:@router.get("/nodes", response_model=list[NodeMetadata])def list_nodes() -> list[NodeMetadata]:register_builtin_nodes()+ register_user_scripts()return registry.list_metadata()diff --git a/backend/app/api/user_scripts.py b/backend/app/api/user_scripts.pynew file mode 100644index 0000000..3ffedc4--- /dev/null+++ b/backend/app/api/user_scripts.py@@ -0,0 +1,86 @@+"""REST API for versioned reusable user scripts."""++from __future__ import annotations++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from app.nodes.user_script import refresh_user_script+from app.services import user_scripts as scripts_store++router = APIRouter(prefix="/user-scripts", tags=["user-scripts"])+++class UserScriptMetaResponse(BaseModel):+ id: str+ name: str+ current_version: int+ created_at: str+ updated_at: str+ node_type: str+++class CreateUserScriptBody(BaseModel):+ name: str = Field(min_length=1, max_length=80)+ code: str = Field(min_length=1)+++class NewVersionBody(BaseModel):+ code: str = Field(min_length=1)+++class UserScriptCodeResponse(BaseModel):+ id: str+ version: int+ code: str+++def _meta_response(meta: scripts_store.UserScriptMeta) -> UserScriptMetaResponse:+ return UserScriptMetaResponse(+ id=meta.id,+ name=meta.name,+ current_version=meta.current_version,+ created_at=meta.created_at,+ updated_at=meta.updated_at,+ node_type=meta.node_type(),+ )++[email protected]("", response_model=list[UserScriptMetaResponse])+def list_user_scripts() -> list[UserScriptMetaResponse]:+ return [_meta_response(item) for item in scripts_store.list_scripts()]++[email protected]("", response_model=UserScriptMetaResponse)+def create_user_script(body: CreateUserScriptBody) -> UserScriptMetaResponse:+ try:+ meta = scripts_store.create_script(body.name, body.code)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ refresh_user_script(meta.id)+ return _meta_response(meta)++[email protected]("/{script_id}/versions", response_model=UserScriptMetaResponse)+def create_user_script_version(script_id: str, body: NewVersionBody) -> UserScriptMetaResponse:+ try:+ scripts_store.validate_script_id(script_id)+ meta = scripts_store.add_version(script_id, body.code)+ except FileNotFoundError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ refresh_user_script(meta.id)+ return _meta_response(meta)++[email protected]("/{script_id}/versions/{version}", response_model=UserScriptCodeResponse)+def get_user_script_version(script_id: str, version: int) -> UserScriptCodeResponse:+ try:+ scripts_store.validate_script_id(script_id)+ code = scripts_store.read_code(script_id, version)+ except FileNotFoundError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return UserScriptCodeResponse(id=script_id, version=version, code=code)diff --git a/backend/app/engine/executor.py b/backend/app/engine/executor.pyindex cac02eb..3cf8db3 100644--- a/backend/app/engine/executor.py+++ b/backend/app/engine/executor.py@@ -31,7 +31,7 @@ from app.models.graph import (NodeInstance,PortDirection,)-from app.nodes.custom import graph_has_custom_python+from app.nodes.custom import graph_has_custom_codeclass DagValidationError(ValueError):@@ -354,7 +354,7 @@ class DagExecutor:cancel: CancellationToken | None = None,) -> dict[str, Any]:cancel = cancel or CancellationToken()- if graph_has_custom_python(request.graph.nodes) and not request.allow_custom_code:+ if graph_has_custom_code(request.graph.nodes) and not request.allow_custom_code:raise DagValidationError("This workflow includes Custom Python nodes. ""Trust the custom code before running (allow_custom_code)."diff --git a/backend/app/engine/registry.py b/backend/app/engine/registry.pyindex 4b37137..19d10e1 100644--- a/backend/app/engine/registry.py+++ b/backend/app/engine/registry.py@@ -95,6 +95,15 @@ class NodeRegistry:def has(self, node_type: str) -> bool:return node_type in self._nodes+ def unregister(self, node_type: str) -> None:+ self._nodes.pop(node_type, None)++ def replace(self, node: BaseNode) -> None:+ """Register or overwrite a node implementation (used for user scripts)."""+ if not node.type:+ raise ValueError("Node type must be a non-empty string")+ self._nodes[node.type] = node+def list_metadata(self) -> list[NodeMetadata]:return [node.metadata() for node in self._nodes.values()]diff --git a/backend/app/main.py b/backend/app/main.pyindex afe53e2..b113020 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -5,9 +5,11 @@ from fastapi.middleware.cors import CORSMiddlewarefrom app.api import router as api_routerfrom app.nodes import register_builtin_nodes+from app.nodes.user_script import register_user_scriptsfrom app.websocket import router as ws_routerregister_builtin_nodes()+register_user_scripts()app = FastAPI(title="Image Pipeline Playground",diff --git a/backend/app/nodes/custom.py b/backend/app/nodes/custom.pyindex ed937df..3d1a682 100644--- a/backend/app/nodes/custom.py+++ b/backend/app/nodes/custom.py@@ -4,11 +4,12 @@ from __future__ import annotationsfrom typing import Any-import cv2import numpy as npfrom app.engine.registry import BaseNodefrom app.nodes.common import image_in, image_out, require_image, string_param+from app.nodes.script_runtime import run_process_code+from app.services.user_scripts import is_user_script_typeDEFAULT_CUSTOM_CODE = """\def process(image, seed=0):@@ -20,15 +21,21 @@ def process(image, seed=0):CUSTOM_PYTHON_TYPE = "custom_python"-def graph_has_custom_python(nodes: list[Any]) -> bool:- """True if any node instance is a custom_python node."""+def graph_has_custom_code(nodes: list[Any]) -> bool:+ """True if any node runs user-authored Python (inline or reusable)."""for node in nodes:node_type = node.type if hasattr(node, "type") else node.get("type")- if node_type == CUSTOM_PYTHON_TYPE:+ if node_type == CUSTOM_PYTHON_TYPE or (+ isinstance(node_type, str) and is_user_script_type(node_type)+ ):return Truereturn False+# Back-compat alias used by older imports/tests.+graph_has_custom_python = graph_has_custom_code++class CustomPythonNode(BaseNode):type = CUSTOM_PYTHON_TYPElabel = "Custom Python"@@ -56,41 +63,7 @@ class CustomPythonNode(BaseNode):) -> dict[str, np.ndarray | list[np.ndarray]]:image = require_image(inputs)code = str(params.get("code") or "")- if not code.strip():- raise ValueError("Custom Python node has empty code")-- namespace: dict[str, Any] = {- "__builtins__": __builtins__,- "cv2": cv2,- "np": np,- "numpy": np,- }- try:- compiled = compile(code, "<custom_python>", "exec")- exec(compiled, namespace, namespace) # noqa: S102 — intentional user code- except SyntaxError as exc:- raise ValueError(f"Custom Python syntax error: {exc}") from exc- except Exception as exc: # noqa: BLE001- raise ValueError(f"Custom Python failed while loading: {exc}") from exc-- process = namespace.get("process")- if not callable(process):- raise ValueError("Custom Python code must define a callable process(image, seed=0)")-- try:- result = process(image, seed=seed)- except TypeError:- try:- result = process(image)- except Exception as exc: # noqa: BLE001- raise ValueError(f"Custom Python process() failed: {exc}") from exc- except Exception as exc: # noqa: BLE001- raise ValueError(f"Custom Python process() failed: {exc}") from exc-- if not isinstance(result, np.ndarray):- raise TypeError(- f"Custom Python process() must return a numpy ndarray, got {type(result).__name__}"- )+ result = run_process_code(code, image, seed=seed, source_name="<custom_python>")return {"image": result}def emit_python(diff --git a/backend/app/nodes/script_runtime.py b/backend/app/nodes/script_runtime.pynew file mode 100644index 0000000..c37f8ce--- /dev/null+++ b/backend/app/nodes/script_runtime.py@@ -0,0 +1,53 @@+"""Shared runtime for executing user process(image, seed=0) scripts."""++from __future__ import annotations++from typing import Any++import cv2+import numpy as np+++def run_process_code(+ code: str,+ image: np.ndarray,+ seed: int = 0,+ *,+ source_name: str = "<user_script>",+) -> np.ndarray:+ """Execute user process(image, seed=0) and validate the return value."""+ if not code.strip():+ raise ValueError("Script code is empty")+ namespace: dict[str, Any] = {+ "__builtins__": __builtins__,+ "cv2": cv2,+ "np": np,+ "numpy": np,+ }+ try:+ compiled = compile(code, source_name, "exec")+ exec(compiled, namespace, namespace) # noqa: S102 — intentional user code+ except SyntaxError as exc:+ raise ValueError(f"Script syntax error: {exc}") from exc+ except Exception as exc: # noqa: BLE001+ raise ValueError(f"Script failed while loading: {exc}") from exc++ process = namespace.get("process")+ if not callable(process):+ raise ValueError("Script must define a callable process(image, seed=0)")++ try:+ result = process(image, seed=seed)+ except TypeError:+ try:+ result = process(image)+ except Exception as exc: # noqa: BLE001+ raise ValueError(f"Script process() failed: {exc}") from exc+ except Exception as exc: # noqa: BLE001+ raise ValueError(f"Script process() failed: {exc}") from exc++ if not isinstance(result, np.ndarray):+ raise TypeError(+ f"Script process() must return a numpy ndarray, got {type(result).__name__}"+ )+ return resultdiff --git a/backend/app/nodes/user_script.py b/backend/app/nodes/user_script.pynew file mode 100644index 0000000..d145ca8--- /dev/null+++ b/backend/app/nodes/user_script.py@@ -0,0 +1,101 @@+"""Dynamic BaseNode factory for on-disk user scripts."""++from __future__ import annotations++from typing import Any++from app.engine.registry import BaseNode, registry+from app.nodes.common import image_in, image_out, int_param, require_image+from app.nodes.script_runtime import run_process_code+from app.services.user_scripts import (+ USER_SCRIPT_TYPE_PREFIX,+ UserScriptMeta,+ list_scripts,+ read_code,+ read_meta,+)+++def _make_user_script_node(meta: UserScriptMeta) -> BaseNode:+ script_id = meta.id+ node_type = meta.node_type()+ display_name = meta.name+ default_version = max(1, int(meta.current_version))++ def execute(+ self: BaseNode,+ inputs: dict[str, Any],+ params: dict[str, Any],+ seed: int = 0,+ ) -> dict[str, Any]:+ image = require_image(inputs)+ version = int(params.get("version") or default_version)+ code = read_code(script_id, version)+ result = run_process_code(+ code,+ image,+ seed=seed,+ source_name=f"<{script_id}.v{version}>",+ )+ return {"image": result}++ def emit_python(+ self: BaseNode,+ node_id: str,+ params: dict[str, Any],+ input_vars: dict[str, str],+ output_vars: dict[str, str],+ ) -> list[str]:+ version = int(params.get("version") or default_version)+ code = read_code(script_id, version).rstrip()+ return [+ f"# --- {node_type} v{version}: {node_id} ---",+ *code.splitlines(),+ f"{output_vars['image']} = process({input_vars['image']}, seed=seed)",+ f"# --- end {node_type} ---",+ ]++ attrs: dict[str, Any] = {+ "type": node_type,+ "label": display_name,+ "category": "user_scripts",+ "description": (+ f"Reusable user script '{display_name}' ({script_id}). "+ "Code is loaded from app data; version is pinned on the canvas node."+ ),+ "ports": [image_in(), image_out()],+ "params": [+ int_param(+ "version",+ "Version",+ default_version,+ minimum=1,+ maximum=10_000,+ description="Pinned script version (older versions remain on disk).",+ ),+ ],+ "cacheable": True,+ "execute": execute,+ "emit_python": emit_python,+ }+ class_name = f"UserScript_{script_id}_Node"+ return type(class_name, (BaseNode,), attrs)()+++def unregister_all_user_scripts() -> None:+ for node_type in list(registry._nodes.keys()): # noqa: SLF001+ if node_type.startswith(USER_SCRIPT_TYPE_PREFIX):+ registry.unregister(node_type)+++def register_user_scripts() -> None:+ """Load all on-disk user scripts into the global registry (replace existing)."""+ unregister_all_user_scripts()+ for meta in list_scripts():+ registry.replace(_make_user_script_node(meta))+++def refresh_user_script(script_id: str) -> None:+ """Re-register a single script after create / new version."""+ meta = read_meta(script_id)+ registry.replace(_make_user_script_node(meta))diff --git a/backend/app/paths.py b/backend/app/paths.pyindex 098c6d3..2decc74 100644--- a/backend/app/paths.py+++ b/backend/app/paths.py@@ -34,3 +34,10 @@ def output_dir() -> Path:path = data_root() / "outputs"path.mkdir(parents=True, exist_ok=True)return path+++def user_scripts_dir() -> Path:+ """Reusable versioned user script packages (Electron: under userData/data)."""+ path = data_root() / "user_scripts"+ path.mkdir(parents=True, exist_ok=True)+ return pathdiff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.pyindex a89c0c3..e206c7f 100644--- a/backend/app/services/__init__.py+++ b/backend/app/services/__init__.py@@ -1,5 +1,3 @@-"""Public services exports."""+"""Public services package (submodules imported explicitly)."""-from app.services.codegen import generate_python--__all__ = ["generate_python"]+__all__: list[str] = []diff --git a/backend/app/services/user_scripts.py b/backend/app/services/user_scripts.pynew file mode 100644index 0000000..db95bc2--- /dev/null+++ b/backend/app/services/user_scripts.py@@ -0,0 +1,190 @@+"""On-disk storage for versioned reusable user scripts."""++from __future__ import annotations++import json+import re+from dataclasses import asdict, dataclass+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++from app.paths import user_scripts_dir++SCRIPT_ID_RE = re.compile(r"^script_(\d+)$")+USER_SCRIPT_TYPE_PREFIX = "user_script."+META_FILENAME = "meta.json"+PROCESS_FILENAME = "process.py"+++@dataclass+class UserScriptMeta:+ id: str+ name: str+ current_version: int+ created_at: str+ updated_at: str++ def node_type(self) -> str:+ return f"{USER_SCRIPT_TYPE_PREFIX}{self.id}"+++def is_user_script_type(node_type: str) -> bool:+ return node_type.startswith(USER_SCRIPT_TYPE_PREFIX)+++def script_id_from_type(node_type: str) -> str | None:+ if not is_user_script_type(node_type):+ return None+ script_id = node_type[len(USER_SCRIPT_TYPE_PREFIX) :]+ return script_id if SCRIPT_ID_RE.match(script_id) else None+++def _now_iso() -> str:+ return datetime.now(UTC).replace(microsecond=0).isoformat()+++def _script_dir(script_id: str, root: Path | None = None) -> Path:+ return (root or user_scripts_dir()) / script_id+++def _version_dir(script_id: str, version: int, root: Path | None = None) -> Path:+ return _script_dir(script_id, root) / f"v{version}"+++def _meta_path(script_id: str, root: Path | None = None) -> Path:+ return _script_dir(script_id, root) / META_FILENAME+++def validate_script_id(script_id: str) -> str:+ if not SCRIPT_ID_RE.match(script_id):+ raise ValueError(f"Invalid script id '{script_id}'")+ return script_id+++def validate_display_name(name: str) -> str:+ cleaned = name.strip()+ if not cleaned:+ raise ValueError("Script name is required")+ if len(cleaned) > 80:+ raise ValueError("Script name must be at most 80 characters")+ return cleaned+++def validate_process_code(code: str) -> str:+ """Compile-check that code defines a callable process()."""+ text = code if isinstance(code, str) else str(code)+ if not text.strip():+ raise ValueError("Script code is empty")+ try:+ compiled = compile(text, "<user_script>", "exec")+ except SyntaxError as exc:+ raise ValueError(f"Script syntax error: {exc}") from exc+ namespace: dict[str, Any] = {"__builtins__": __builtins__}+ exec(compiled, namespace, namespace) # noqa: S102 — validation only+ process = namespace.get("process")+ if not callable(process):+ raise ValueError("Script must define a callable process(image, seed=0)")+ return text+++def allocate_script_id(root: Path | None = None) -> str:+ base = root or user_scripts_dir()+ max_n = 0+ if base.is_dir():+ for child in base.iterdir():+ if not child.is_dir():+ continue+ match = SCRIPT_ID_RE.match(child.name)+ if match:+ max_n = max(max_n, int(match.group(1)))+ return f"script_{max_n + 1:03d}"+++def read_meta(script_id: str, root: Path | None = None) -> UserScriptMeta:+ validate_script_id(script_id)+ path = _meta_path(script_id, root)+ if not path.is_file():+ raise FileNotFoundError(f"Unknown user script '{script_id}'")+ data = json.loads(path.read_text(encoding="utf-8"))+ return UserScriptMeta(+ id=str(data["id"]),+ name=str(data["name"]),+ current_version=int(data["current_version"]),+ created_at=str(data["created_at"]),+ updated_at=str(data["updated_at"]),+ )+++def write_meta(meta: UserScriptMeta, root: Path | None = None) -> None:+ path = _meta_path(meta.id, root)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(asdict(meta), indent=2) + "\n", encoding="utf-8")+++def read_code(script_id: str, version: int, root: Path | None = None) -> str:+ validate_script_id(script_id)+ if version < 1:+ raise ValueError("Version must be >= 1")+ path = _version_dir(script_id, version, root) / PROCESS_FILENAME+ if not path.is_file():+ raise FileNotFoundError(+ f"User script '{script_id}' version {version} not found"+ )+ return path.read_text(encoding="utf-8")+++def write_code(script_id: str, version: int, code: str, root: Path | None = None) -> Path:+ validate_script_id(script_id)+ validated = validate_process_code(code)+ version_path = _version_dir(script_id, version, root)+ version_path.mkdir(parents=True, exist_ok=True)+ file_path = version_path / PROCESS_FILENAME+ file_path.write_text(validated, encoding="utf-8")+ return file_path+++def list_scripts(root: Path | None = None) -> list[UserScriptMeta]:+ base = root or user_scripts_dir()+ items: list[UserScriptMeta] = []+ if not base.is_dir():+ return items+ for child in sorted(base.iterdir(), key=lambda p: p.name):+ if not child.is_dir() or not SCRIPT_ID_RE.match(child.name):+ continue+ meta_file = child / META_FILENAME+ if not meta_file.is_file():+ continue+ try:+ items.append(read_meta(child.name, root))+ except (OSError, KeyError, ValueError, json.JSONDecodeError):+ continue+ return items+++def create_script(name: str, code: str, root: Path | None = None) -> UserScriptMeta:+ display = validate_display_name(name)+ validate_process_code(code)+ script_id = allocate_script_id(root)+ now = _now_iso()+ meta = UserScriptMeta(+ id=script_id,+ name=display,+ current_version=1,+ created_at=now,+ updated_at=now,+ )+ write_code(script_id, 1, code, root)+ write_meta(meta, root)+ return meta+++def add_version(script_id: str, code: str, root: Path | None = None) -> UserScriptMeta:+ meta = read_meta(script_id, root)+ validate_process_code(code)+ next_version = meta.current_version + 1+ write_code(script_id, next_version, code, root)+ meta.current_version = next_version+ meta.updated_at = _now_iso()+ write_meta(meta, root)+ return metadiff --git a/backend/tests/test_user_script_nodes.py b/backend/tests/test_user_script_nodes.pynew file mode 100644index 0000000..aaebde5--- /dev/null+++ b/backend/tests/test_user_script_nodes.py@@ -0,0 +1,112 @@+"""Tests for user_script registry nodes."""++from __future__ import annotations++import numpy as np+import pytest++from app.engine.registry import registry+from app.nodes import register_builtin_nodes+from app.nodes.user_script import refresh_user_script, register_user_scripts+from app.services import user_scripts as store+++def test_register_and_execute_pinned_versions(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))+ # Re-bind store root via env for paths.user_scripts_dir+ meta = store.create_script(+ "Invert-ish",+ "def process(image, seed=0):\n return image + 1\n",+ tmp_path / "user_scripts",+ )+ store.add_version(+ meta.id,+ "def process(image, seed=0):\n return image + 5\n",+ tmp_path / "user_scripts",+ )++ register_builtin_nodes()+ register_user_scripts()+ node_type = meta.node_type()+ assert registry.has(node_type)++ image = np.zeros((4, 4, 3), dtype=np.uint8)+ v1 = registry.get(node_type).execute({"image": image}, {"version": 1}, seed=0)["image"]+ v2 = registry.get(node_type).execute({"image": image}, {"version": 2}, seed=0)["image"]+ np.testing.assert_array_equal(v1, image + 1)+ np.testing.assert_array_equal(v2, image + 5)+++def test_refresh_user_script_after_create(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))+ register_builtin_nodes()+ register_user_scripts()+ before = {m.type for m in registry.list_metadata()}++ meta = store.create_script(+ "New",+ "def process(image, seed=0):\n return image\n",+ tmp_path / "user_scripts",+ )+ refresh_user_script(meta.id)+ assert meta.node_type() in {m.type for m in registry.list_metadata()}+ assert meta.node_type() not in before+++def test_missing_version_raises(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))+ meta = store.create_script(+ "X",+ "def process(image, seed=0):\n return image\n",+ tmp_path / "user_scripts",+ )+ register_builtin_nodes()+ register_user_scripts()+ image = np.zeros((2, 2, 3), dtype=np.uint8)+ with pytest.raises(FileNotFoundError):+ registry.get(meta.node_type()).execute({"image": image}, {"version": 9}, seed=0)+++def test_executor_blocks_user_script_without_trust(tmp_path, monkeypatch) -> None:+ from app.engine.executor import DagExecutor+ from app.models.graph import Edge, ExecuteRequest, Graph, NodeInstance+ from app.nodes.custom import graph_has_custom_code++ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))+ meta = store.create_script(+ "Gate",+ "def process(image, seed=0):\n return image\n",+ tmp_path / "user_scripts",+ )+ register_builtin_nodes()+ register_user_scripts()++ graph = Graph(+ nodes=[+ NodeInstance(id="src", type="blank_image", params={"width": 8, "height": 8}),+ NodeInstance(+ id="usr",+ type=meta.node_type(),+ params={"version": 1},+ ),+ ],+ edges=[+ Edge(+ id="e1",+ source="src",+ source_port="image",+ target="usr",+ target_port="image",+ ),+ ],+ )+ assert graph_has_custom_code(graph.nodes)++ from app.engine.executor import DagValidationError++ executor = DagExecutor(tmp_path / "cache")+ with pytest.raises(DagValidationError, match="Trust the custom code"):+ executor.execute(ExecuteRequest(graph=graph, allow_custom_code=False))++ result = executor.execute(ExecuteRequest(graph=graph, allow_custom_code=True))+ assert "order" in resultdiff --git a/backend/tests/test_user_scripts_api.py b/backend/tests/test_user_scripts_api.pynew file mode 100644index 0000000..9394b03--- /dev/null+++ b/backend/tests/test_user_scripts_api.py@@ -0,0 +1,80 @@+"""API tests for versioned user scripts."""++from __future__ import annotations++from fastapi.testclient import TestClient++from app.engine.registry import registry+from app.main import app++GOOD_CODE = "def process(image, seed=0):\n return image\n"+V2_CODE = "def process(image, seed=0):\n return image + 1\n"+++def test_user_scripts_crud_and_nodes_catalog(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))+ client = TestClient(app)++ listed = client.get("/api/user-scripts")+ assert listed.status_code == 200+ assert listed.json() == []++ created = client.post(+ "/api/user-scripts",+ json={"name": "My Sepia", "code": GOOD_CODE},+ )+ assert created.status_code == 200+ body = created.json()+ assert body["id"] == "script_001"+ assert body["name"] == "My Sepia"+ assert body["current_version"] == 1+ assert body["node_type"] == "user_script.script_001"+ assert registry.has("user_script.script_001")++ nodes = client.get("/api/nodes")+ assert nodes.status_code == 200+ types = {item["type"] for item in nodes.json()}+ assert "user_script.script_001" in types++ code_resp = client.get("/api/user-scripts/script_001/versions/1")+ assert code_resp.status_code == 200+ assert code_resp.json()["code"] == GOOD_CODE++ versioned = client.post(+ "/api/user-scripts/script_001/versions",+ json={"code": V2_CODE},+ )+ assert versioned.status_code == 200+ assert versioned.json()["current_version"] == 2++ v1 = client.get("/api/user-scripts/script_001/versions/1")+ v2 = client.get("/api/user-scripts/script_001/versions/2")+ assert v1.json()["code"] == GOOD_CODE+ assert v2.json()["code"] == V2_CODE++ all_scripts = client.get("/api/user-scripts")+ assert len(all_scripts.json()) == 1+ assert all_scripts.json()[0]["current_version"] == 2+++def test_user_scripts_reject_bad_code_and_ids(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))+ client = TestClient(app)++ bad = client.post(+ "/api/user-scripts",+ json={"name": "Bad", "code": "def nope(image):\n return image\n"},+ )+ assert bad.status_code == 400++ empty_name = client.post(+ "/api/user-scripts",+ json={"name": " ", "code": GOOD_CODE},+ )+ assert empty_name.status_code == 422 or empty_name.status_code == 400++ missing = client.get("/api/user-scripts/script_999/versions/1")+ assert missing.status_code in (400, 404)++ bad_id = client.get("/api/user-scripts/not_a_script/versions/1")+ assert bad_id.status_code == 400diff --git a/backend/tests/test_user_scripts_store.py b/backend/tests/test_user_scripts_store.pynew file mode 100644index 0000000..8b40c15--- /dev/null+++ b/backend/tests/test_user_scripts_store.py@@ -0,0 +1,61 @@+"""Tests for versioned user script disk store."""++from __future__ import annotations++import pytest++from app.services import user_scripts as store+++def test_allocate_script_ids(tmp_path) -> None:+ assert store.allocate_script_id(tmp_path) == "script_001"+ store.create_script("First", "def process(image, seed=0):\n return image\n", tmp_path)+ assert store.allocate_script_id(tmp_path) == "script_002"+++def test_create_writes_v1_and_meta(tmp_path) -> None:+ meta = store.create_script(+ " Sepia Tone ",+ "def process(image, seed=0):\n return image\n",+ tmp_path,+ )+ assert meta.id == "script_001"+ assert meta.name == "Sepia Tone"+ assert meta.current_version == 1+ assert (tmp_path / "script_001" / "meta.json").is_file()+ assert (tmp_path / "script_001" / "v1" / "process.py").is_file()+ code = store.read_code("script_001", 1, tmp_path)+ assert "def process" in code+++def test_add_version_preserves_old(tmp_path) -> None:+ store.create_script(+ "Blur",+ "def process(image, seed=0):\n return image\n",+ tmp_path,+ )+ v1 = store.read_code("script_001", 1, tmp_path)+ meta = store.add_version(+ "script_001",+ "def process(image, seed=0):\n return image + 1\n",+ tmp_path,+ )+ assert meta.current_version == 2+ assert store.read_code("script_001", 1, tmp_path) == v1+ assert "image + 1" in store.read_code("script_001", 2, tmp_path)+++def test_rejects_empty_name_and_bad_code(tmp_path) -> None:+ with pytest.raises(ValueError, match="name"):+ store.create_script(" ", "def process(image, seed=0):\n return image\n", tmp_path)+ with pytest.raises(ValueError, match="process"):+ store.create_script("X", "x = 1\n", tmp_path)+ with pytest.raises(ValueError, match="syntax"):+ store.create_script("X", "def process(\n", tmp_path)+++def test_list_scripts(tmp_path) -> None:+ store.create_script("A", "def process(image, seed=0):\n return image\n", tmp_path)+ store.create_script("B", "def process(image, seed=0):\n return image\n", tmp_path)+ items = store.list_scripts(tmp_path)+ assert [item.id for item in items] == ["script_001", "script_002"]