Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Canvas: canvases table, CRUD and POST /api/canvases/:id/run

Claude7ddd493db701
diff --git a/src/app/api/canvases/[id]/duplicate/route.ts b/src/app/api/canvases/[id]/duplicate/route.ts
new file mode 100644
index 00000000..b9700fdc
--- /dev/null
+++ b/src/app/api/canvases/[id]/duplicate/route.ts
@@ -0,0 +1,8 @@
+import { duplicateCanvas } from "@/server/canvas";
+
+/** "Copy of {name}", with the same nodes and results. */
+export async function POST(_req: Request, ctx: RouteContext<"/api/canvases/[id]/duplicate">) {
+ const { id } = await ctx.params;
+ const c = duplicateCanvas(id);
+ return c ? Response.json(c, { status: 201 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/canvases/[id]/route.ts b/src/app/api/canvases/[id]/route.ts
new file mode 100644
index 00000000..6f29d775
--- /dev/null
+++ b/src/app/api/canvases/[id]/route.ts
@@ -0,0 +1,32 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { canvasView, deleteCanvas, parseGraph, updateCanvas } from "@/server/canvas";
+
+const Patch = z.object({
+ name: z.string().trim().min(1).max(80).optional(),
+ graph: z.unknown().optional(),
+});
+
+/** The board, its nodes' last runs and the generations they made. */
+export async function GET(_req: Request, ctx: RouteContext<"/api/canvases/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const view = canvasView(id);
+ return view ? Response.json(view) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+/** Rename and/or autosave the graph. */
+export async function PATCH(request: Request, ctx: RouteContext<"/api/canvases/[id]">) {
+ const { id } = await ctx.params;
+ const parsed = Patch.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Give the canvas a name" }, { status: 400 });
+ const graph = parsed.data.graph === undefined ? undefined : parseGraph(parsed.data.graph);
+ if (graph === null) return Response.json({ error: "That board couldn't be saved — reload the page" }, { status: 400 });
+ const c = updateCanvas(id, { name: parsed.data.name, graph });
+ return c ? Response.json(c) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/canvases/[id]">) {
+ const { id } = await ctx.params;
+ return deleteCanvas(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/canvases/[id]/run/route.ts b/src/app/api/canvases/[id]/run/route.ts
new file mode 100644
index 00000000..49b57091
--- /dev/null
+++ b/src/app/api/canvases/[id]/run/route.ts
@@ -0,0 +1,30 @@
+import { z } from "zod";
+import { parseGraph, runCanvas } from "@/server/canvas";
+
+const Body = z.object({
+ /** Node ids to run with everything upstream (Run node, Run selected); omit for Run all. */
+ targets: z.array(z.string().max(80)).max(300).optional(),
+ /** Re-run the targets even when their result is still fresh. */
+ force: z.boolean().optional(),
+ /** The board as the editor shows it (saved first). */
+ graph: z.unknown().optional(),
+});
+
+/**
+ * Turn the graph into generations: one per generator node that needs to run, chained with
+ * dependsOn along the edges. Fresh and pinned nodes are reused. 422 when nothing could start.
+ */
+export async function POST(request: Request, ctx: RouteContext<"/api/canvases/[id]/run">) {
+ const { id } = await ctx.params;
+ const parsed = Body.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return Response.json({ error: "Invalid run request" }, { status: 400 });
+ const graph = parsed.data.graph === undefined ? undefined : parseGraph(parsed.data.graph);
+ if (graph === null) return Response.json({ error: "That board couldn't be read — reload the page" }, { status: 400 });
+ const result = runCanvas(id, { targets: parsed.data.targets, force: parsed.data.force, graph });
+ if (!result) return Response.json({ error: "Not found" }, { status: 404 });
+ if (!result.ran.length && result.errors.length) {
+ const first = result.errors[0].message;
+ return Response.json({ ...result, error: result.errors.length > 1 ? `${first} (and ${result.errors.length - 1} more)` : first }, { status: 422 });
+ }
+ return Response.json(result, { status: result.ran.length ? 201 : 200 });
+}
diff --git a/src/app/api/canvases/route.ts b/src/app/api/canvases/route.ts
new file mode 100644
index 00000000..2b3011a5
--- /dev/null
+++ b/src/app/api/canvases/route.ts
@@ -0,0 +1,28 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { createCanvas, listCanvases, parseGraph } from "@/server/canvas";
+
+const Body = z.object({
+ name: z.string().max(80).optional(),
+ templateId: z.string().max(60).optional(),
+ engine: z.enum(["cloud", "open"]).optional(),
+ graph: z.unknown().optional(),
+});
+
+export async function GET() {
+ await connection();
+ return Response.json({ items: listCanvases() });
+}
+
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => ({})));
+ if (!parsed.success) return Response.json({ error: "Invalid canvas" }, { status: 400 });
+ const { graph: rawGraph, ...rest } = parsed.data;
+ const graph = rawGraph === undefined ? undefined : parseGraph(rawGraph);
+ if (graph === null) return Response.json({ error: "That board couldn't be read" }, { status: 400 });
+ try {
+ return Response.json(createCanvas({ ...rest, graph }), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/server/canvas.ts b/src/server/canvas.ts
new file mode 100644
index 00000000..1c20853f
--- /dev/null
+++ b/src/server/canvas.ts
@@ -0,0 +1,332 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import {
+ cleanGraph,
+ EMPTY_GRAPH,
+ getTemplate,
+ nodeLabel,
+ nodeMap,
+ nodeSignature,
+ outline,
+ planCanvas,
+ type Canvas,
+ type CanvasGraph,
+ type CanvasNodeType,
+ type CanvasPlan,
+ type CanvasRuns,
+ type CanvasSummary,
+} from "@/lib/catalog/canvas";
+import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
+import { db } from "./db";
+import { createGenerations, getGeneration } from "./generations";
+import { engineMode } from "./settings";
+
+/**
+ * Canvas boards (Higgsfield Canvas): the graph the user edits, plus the last run of each
+ * generator node. Running turns the graph into chained generations (src/lib/catalog/canvas.ts
+ * plans it; createGenerations + dependsOn runs it), so results survive restarts like any other job.
+ */
+
+interface Row {
+ id: string;
+ name: string;
+ graph_json: string;
+ runs_json: string;
+ template_id: string | null;
+ created_at: number;
+ updated_at: number;
+ edited_at: number | null;
+}
+
+const toCanvas = (r: Row): Canvas => ({
+ id: r.id,
+ name: r.name,
+ graph: JSON.parse(r.graph_json) as CanvasGraph,
+ runs: JSON.parse(r.runs_json) as CanvasRuns,
+ templateId: r.template_id,
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ editedAt: r.edited_at,
+});
+
+// ---------------------------------------------------------------------------
+// Validation of graphs coming from the browser
+
+const NODE_TYPES = ["prompt", "image-input", "video-input", "audio-input", "element", "model", "join", "frame", "upscale", "bg-remove", "tts", "output", "note"] as const satisfies readonly CanvasNodeType[];
+const KINDS = ["image", "video", "audio", "text", "model3d"] as const satisfies readonly MediaKind[];
+
+/** The settings a node may send (the same limits as POST /api/generations). */
+const Params = z.object({
+ aspectRatio: z.string().max(20).optional(),
+ resolution: z.string().max(20).optional(),
+ duration: z.number().positive().max(600).optional(),
+ numOutputs: z.number().int().min(1).max(8).optional(),
+ seed: z.number().int().optional(),
+ generateAudio: z.boolean().optional(),
+ voice: z.string().max(200).optional(),
+ targetLanguage: z.string().max(80).optional(),
+ sourceLanguage: z.string().max(80).optional(),
+ extra: z.record(z.string(), z.union([z.string().max(2000), z.number(), z.boolean()])).optional(),
+});
+
+const NodeData = z.object({
+ label: z.string().max(80).optional(),
+ text: z.string().max(10_000).optional(),
+ // Media comes from Fuobe's own storage (uploads, the library, generated outputs).
+ url: z.string().startsWith("/api/files/").max(2000).optional(),
+ name: z.string().max(200).optional(),
+ elementId: z.string().max(40).optional(),
+ handle: z.string().max(60).optional(),
+ preview: z.string().startsWith("/api/files/").max(2000).optional(),
+ modelId: z.string().max(120).optional(),
+ op: z.string().max(40).optional(),
+ prompt: z.string().max(10_000).optional(),
+ params: Params.optional(),
+ pinned: z.boolean().optional(),
+ mediaKind: z.enum(KINDS).optional(),
+});
+
+const Num = z.number().finite();
+
+export const GraphSchema = z.object({
+ nodes: z
+ .array(
+ z.object({
+ id: z.string().min(1).max(80),
+ type: z.enum(NODE_TYPES),
+ position: z.object({ x: Num, y: Num }),
+ data: NodeData,
+ width: Num.positive().max(4000).optional(),
+ height: Num.positive().max(4000).optional(),
+ }),
+ )
+ .max(300),
+ edges: z
+ .array(
+ z.object({
+ id: z.string().min(1).max(200),
+ source: z.string().min(1).max(80),
+ target: z.string().min(1).max(80),
+ sourceHandle: z.string().max(40).nullish(),
+ targetHandle: z.string().max(40).nullish(),
+ }),
+ )
+ .max(1200),
+ viewport: z.object({ x: Num, y: Num, zoom: Num.positive().max(10) }).optional(),
+});
+
+/** A parsed graph, with duplicate node ids, dangling edges and edges into missing handles removed. */
+export function parseGraph(input: unknown): CanvasGraph | null {
+ const parsed = GraphSchema.safeParse(input);
+ if (!parsed.success) return null;
+ const g = parsed.data as CanvasGraph;
+ const seen = new Set<string>();
+ const nodes = g.nodes.filter((n) => !seen.has(n.id) && seen.add(n.id));
+ return cleanGraph({ ...g, nodes });
+}
+
+// ---------------------------------------------------------------------------
+// CRUD
+
+export function getCanvas(id: string): Canvas | null {
+ const r = db().prepare("SELECT * FROM canvases WHERE id = ?").get(id) as Row | undefined;
+ return r ? toCanvas(r) : null;
+}
+
+/** The newest finished image or video among the canvas's results. */
+function previewOf(runs: CanvasRuns): CanvasSummary["preview"] {
+ const ids = Object.values(runs)
+ .sort((a, b) => b.at - a.at)
+ .flatMap((r) => r.ids)
+ .slice(0, 60);
+ if (!ids.length) return null;
+ const rows = db()
+ .prepare(`SELECT outputs_json FROM generations WHERE id IN (${ids.map(() => "?").join(",")}) AND status = 'succeeded' AND kind IN ('image','video') ORDER BY completed_at DESC LIMIT 1`)
+ .all(...ids) as { outputs_json: string }[];
+ const o = rows[0] ? (JSON.parse(rows[0].outputs_json) as { url: string; kind: MediaKind }[]).find((x) => x.kind === "image" || x.kind === "video") : undefined;
+ return o ? { url: o.url, kind: o.kind } : null;
+}
+
+export function listCanvases(): CanvasSummary[] {
+ const rows = db().prepare("SELECT * FROM canvases ORDER BY updated_at DESC LIMIT 200").all() as Row[];
+ return rows.map((r) => {
+ const c = toCanvas(r);
+ return {
+ id: c.id,
+ name: c.name,
+ nodeCount: c.graph.nodes.length,
+ templateId: c.templateId,
+ preview: previewOf(c.runs),
+ outline: outline(c.graph),
+ createdAt: c.createdAt,
+ updatedAt: c.updatedAt,
+ editedAt: c.editedAt,
+ };
+ });
+}
+
+export interface CreateCanvasInput {
+ name?: string;
+ graph?: CanvasGraph;
+ /** Start from a template, in the cloud or the all-open-source variant. */
+ templateId?: string;
+ engine?: Engine;
+}
+
+export function createCanvas(input: CreateCanvasInput = {}): Canvas {
+ const template = input.templateId ? getTemplate(input.templateId) : undefined;
+ if (input.templateId && !template) throw new Error("That template doesn't exist");
+ // A locked install only ever gets the variant it can run.
+ const mode = engineMode();
+ const engine: Engine = mode === "both" ? (input.engine ?? "cloud") : mode;
+ const graph = template ? template.build(engine) : (input.graph ?? EMPTY_GRAPH);
+ const now = Date.now();
+ const row: Row = {
+ id: nanoid(10),
+ name: (input.name?.trim() || template?.name || "Untitled canvas").slice(0, 80),
+ graph_json: JSON.stringify(cleanGraph(graph)),
+ runs_json: "{}",
+ template_id: template?.id ?? null,
+ created_at: now,
+ updated_at: now,
+ edited_at: null,
+ };
+ db()
+ .prepare(`INSERT INTO canvases (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ return toCanvas(row);
+}
+
+/** Save a new name and/or graph. Moving the viewport alone doesn't count as an edit. */
+export function updateCanvas(id: string, patch: { name?: string; graph?: CanvasGraph }): Canvas | null {
+ const current = getCanvas(id);
+ if (!current) return null;
+ const now = Date.now();
+ const name = patch.name?.trim() ? patch.name.trim().slice(0, 80) : current.name;
+ let graphJson = JSON.stringify(current.graph);
+ let edited = current.editedAt;
+ if (patch.graph) {
+ const next = cleanGraph(patch.graph);
+ const strip = (g: CanvasGraph) => JSON.stringify({ nodes: g.nodes, edges: g.edges });
+ if (strip(next) !== strip(current.graph)) edited = now;
+ graphJson = JSON.stringify(next);
+ }
+ db().prepare("UPDATE canvases SET name = ?, graph_json = ?, updated_at = ?, edited_at = ? WHERE id = ?").run(name, graphJson, now, edited, id);
+ return getCanvas(id);
+}
+
+export function duplicateCanvas(id: string): Canvas | null {
+ const c = getCanvas(id);
+ if (!c) return null;
+ const now = Date.now();
+ const row: Row = {
+ id: nanoid(10),
+ name: `Copy of ${c.name}`.slice(0, 80),
+ graph_json: JSON.stringify(c.graph),
+ // The copy shows the same results until it's run again.
+ runs_json: JSON.stringify(c.runs),
+ template_id: c.templateId,
+ created_at: now,
+ updated_at: now,
+ edited_at: c.editedAt,
+ };
+ db()
+ .prepare(`INSERT INTO canvases (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ return toCanvas(row);
+}
+
+/** Deletes the board; what it made stays in the library. */
+export function deleteCanvas(id: string): boolean {
+ return db().prepare("DELETE FROM canvases WHERE id = ?").run(id).changes > 0;
+}
+
+/** The canvas with the generations its nodes made (for status, progress and outputs). */
+export function canvasView(id: string): { canvas: Canvas; generations: Generation[] } | null {
+ const canvas = getCanvas(id);
+ if (!canvas) return null;
+ const ids = [...new Set(Object.values(canvas.runs).flatMap((r) => r.ids))];
+ // getGeneration also makes sure the runner is polling after a restart.
+ const generations = ids.map((g) => getGeneration(g)).filter((g): g is Generation => !!g);
+ return { canvas, generations };
+}
+
+// ---------------------------------------------------------------------------
+// Run
+
+export interface RunOptions {
+ /** Nodes to run with their upstream; omit for Run all. */
+ targets?: string[];
+ /** Re-run the targets even when their result is fresh. */
+ force?: boolean;
+ /** The board as the editor has it now (saved first, so an autosave in flight can't race the run). */
+ graph?: CanvasGraph;
+}
+
+export interface RunResult {
+ canvas: Canvas;
+ /** Generations created, in run order. */
+ items: Generation[];
+ /** Node ids that started, in order. */
+ ran: string[];
+ reused: CanvasPlan["reused"];
+ errors: CanvasPlan["errors"];
+ costUsd: number;
+}
+
+function statusOf(id: string): Generation["status"] | undefined {
+ return (db().prepare("SELECT status FROM generations WHERE id = ?").get(id) as { status: Generation["status"] } | undefined)?.status;
+}
+
+export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
+ let canvas = getCanvas(id);
+ if (!canvas) return null;
+ if (opts.graph) canvas = updateCanvas(id, { graph: opts.graph })!;
+ const graph = canvas.graph;
+ const plan = planCanvas(graph, { targets: opts.targets, force: opts.force, runs: canvas.runs, status: statusOf, engineMode: engineMode() });
+ const nodes = nodeMap(graph);
+ const batchId = nanoid(10);
+ const made = new Map<string, string>(plan.reused.map((r) => [r.nodeId, r.generationId]));
+ const errors = [...plan.errors];
+ const items: Generation[] = [];
+ const ran: string[] = [];
+ const runs: CanvasRuns = {};
+ const n = plan.steps.length;
+ plan.steps.forEach((step, i) => {
+ const depIds = step.deps.map((d) => made.get(d));
+ const missing = step.deps.find((d, k) => !depIds[k]);
+ if (missing) {
+ errors.push({ nodeId: step.nodeId, message: `Waiting on “${nodeLabel(nodes.get(missing)!)}”, which couldn't start` });
+ return;
+ }
+ try {
+ const created = createGenerations(
+ { ...step.request, step: { label: step.label, index: i, of: n } },
+ { batchId, ...(depIds.length && { dependsOn: depIds as string[] }) },
+ );
+ made.set(step.nodeId, created[0].id);
+ runs[step.nodeId] = { sig: nodeSignature(step.request, depIds as string[]), ids: created.map((g) => g.id), at: Date.now() };
+ items.push(...created);
+ ran.push(step.nodeId);
+ } catch (e) {
+ errors.push({ nodeId: step.nodeId, message: (e as Error).message });
+ }
+ });
+ if (ran.length) {
+ // Merge into the latest runs (another run may have finished writing meanwhile).
+ db().transaction(() => {
+ const row = db().prepare("SELECT runs_json FROM canvases WHERE id = ?").get(id) as { runs_json: string } | undefined;
+ const merged = { ...(row ? (JSON.parse(row.runs_json) as CanvasRuns) : {}), ...runs };
+ db().prepare("UPDATE canvases SET runs_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(merged), Date.now(), id);
+ })();
+ }
+ return {
+ canvas: getCanvas(id)!,
+ items,
+ ran,
+ reused: plan.reused,
+ errors,
+ costUsd: plan.steps.filter((s) => ran.includes(s.nodeId)).reduce((sum, s) => sum + (s.costUsd ?? 0), 0),
+ };
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 994f90a9..7a8e183b 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -101,6 +101,18 @@ const MIGRATIONS: string[] = [
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS assist_threads_updated ON assist_threads(updated_at DESC);`,
+ // Canvas boards: the node graph (edited by the user) and each generator node's last run (written by the server).
+ `CREATE TABLE IF NOT EXISTS canvases (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ graph_json TEXT NOT NULL DEFAULT '{"nodes":[],"edges":[]}',
+ runs_json TEXT NOT NULL DEFAULT '{}',
+ template_id TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ edited_at INTEGER
+ );
+ CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,
];
declare global {
diff --git a/tests/canvas-api.test.ts b/tests/canvas-api.test.ts
new file mode 100644
index 00000000..aadd73cf
--- /dev/null
+++ b/tests/canvas-api.test.ts
@@ -0,0 +1,188 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { Canvas, CanvasGraph, CanvasSummary } from "@/lib/catalog/canvas";
+import type { Generation } from "@/lib/catalog/types";
+
+// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-canvas-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const list = await import("@/app/api/canvases/route");
+const one = await import("@/app/api/canvases/[id]/route");
+const dup = await import("@/app/api/canvases/[id]/duplicate/route");
+const run = await import("@/app/api/canvases/[id]/run/route");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as any;
+const req = (method: string, body?: unknown) =>
+ new Request("http://localhost/api/canvases", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+
+async function settle(id: string, ms = 40_000) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+const dependsOn = (id: string) => (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;
+
+/** Text prompt → image → video → output: the three-node graph the editor is verified with. */
+const board: CanvasGraph = {
+ nodes: [
+ { id: "p", type: "prompt", position: { x: 0, y: 0 }, data: { text: "A red fox in fresh snow" } },
+ { id: "img", type: "model", position: { x: 320, y: 0 }, data: { modelId: "nano-banana-pro", label: "Still", params: { aspectRatio: "16:9" } } },
+ { id: "vid", type: "model", position: { x: 640, y: 0 }, data: { modelId: "kling-2-5-turbo", op: "i2v", prompt: "It looks up", params: { duration: 5 } } },
+ { id: "out", type: "output", position: { x: 960, y: 0 }, data: {} },
+ ],
+ edges: [
+ { id: "e1", source: "p", sourceHandle: "out", target: "img", targetHandle: "prompt" },
+ { id: "e2", source: "img", sourceHandle: "out", target: "vid", targetHandle: "images" },
+ { id: "e3", source: "vid", sourceHandle: "out", target: "out", targetHandle: "in" },
+ ],
+};
+
+describe("canvas API", () => {
+ let id = "";
+
+ it("creates, lists, renames and autosaves", async () => {
+ let res = await list.POST(req("POST", {}));
+ expect(res.status).toBe(201);
+ const blank = (await res.json()) as Canvas;
+ expect(blank).toMatchObject({ name: "Untitled canvas", graph: { nodes: [], edges: [] }, runs: {}, editedAt: null });
+ id = blank.id;
+
+ res = await one.PATCH(req("PATCH", { name: "Fox film", graph: board }), ctx(id));
+ expect(res.status).toBe(200);
+ const saved = (await res.json()) as Canvas;
+ expect(saved.name).toBe("Fox film");
+ expect(saved.graph.nodes).toHaveLength(4);
+ expect(saved.graph.edges).toHaveLength(3);
+ expect(saved.editedAt).not.toBeNull();
+
+ // Media must come from Fuobe's own storage; bad graphs are refused.
+ res = await one.PATCH(req("PATCH", { graph: { nodes: [{ id: "x", type: "image-input", position: { x: 0, y: 0 }, data: { url: "http://evil.example/a.png" } }], edges: [] } }), ctx(id));
+ expect(res.status).toBe(400);
+ // Edges into inputs a node doesn't have are dropped on save.
+ res = await one.PATCH(req("PATCH", { graph: { ...board, edges: [...board.edges, { id: "bad", source: "p", target: "vid", targetHandle: "audio" }] } }), ctx(id));
+ expect(((await res.json()) as Canvas).graph.edges.map((e) => e.id)).toEqual(["e1", "e2", "e3"]);
+
+ res = await list.GET();
+ const items = ((await res.json()) as { items: CanvasSummary[] }).items;
+ expect(items[0]).toMatchObject({ id, name: "Fox film", nodeCount: 4, preview: null });
+ expect(items[0].outline).toHaveLength(4);
+ });
+
+ it("runs the graph as chained generations, then reuses fresh results", async () => {
+ let res = await run.POST(req("POST", {}), ctx(id));
+ expect(res.status).toBe(201);
+ let body = (await res.json()) as { ran: string[]; items: Generation[]; canvas: Canvas; errors: unknown[] };
+ expect(body.errors).toEqual([]);
+ expect(body.ran).toEqual(["img", "vid"]);
+ const [img, vid] = body.items;
+ expect(img).toMatchObject({ feature: "canvas", modelId: "nano-banana-pro", op: "t2i", prompt: "A red fox in fresh snow" });
+ expect(img.request.step).toEqual({ label: "Still", index: 0, of: 2 });
+ expect(vid).toMatchObject({ modelId: "kling-2-5-turbo", op: "i2v", status: "queued" });
+ expect(vid.request.chain).toEqual([{ slot: "images", position: "first" }]);
+ expect(dependsOn(vid.id)).toBe(img.id);
+ expect(body.canvas.runs.img.ids).toEqual([img.id]);
+ expect(body.canvas.runs.vid.ids).toEqual([vid.id]);
+
+ // Demo mode: the image lands, then the video is made from it.
+ const done = await settle(vid.id);
+ expect(done.status).toBe("succeeded");
+ expect(done.request.inputs?.images?.[0]).toBe(gens.getGeneration(img.id)!.outputs[0].url);
+
+ res = await one.GET(req("GET"), ctx(id));
+ const view = (await res.json()) as { canvas: Canvas; generations: Generation[] };
+ expect(view.generations.map((g) => g.status).sort()).toEqual(["succeeded", "succeeded"]);
+ const listed = ((await (await list.GET()).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;
+ expect(listed.preview?.kind).toBe("video");
+
+ // Nothing changed: Run all starts nothing.
+ res = await run.POST(req("POST", {}), ctx(id));
+ expect(res.status).toBe(200);
+ body = (await res.json()) as typeof body;
+ expect(body.ran).toEqual([]);
+
+ // Re-run the video only: it builds on the image that's already there.
+ res = await run.POST(req("POST", { targets: ["vid"], force: true }), ctx(id));
+ body = (await res.json()) as typeof body;
+ expect(body.ran).toEqual(["vid"]);
+ expect(dependsOn(body.items[0].id)).toBe(img.id);
+
+ // Editing the prompt (sent with the run) re-runs the image and what's downstream.
+ const edited = structuredClone(board);
+ edited.nodes[0].data.text = "A grey wolf in fresh snow";
+ res = await run.POST(req("POST", { graph: edited, targets: ["img"] }), ctx(id));
+ body = (await res.json()) as typeof body;
+ expect(body.ran).toEqual(["img"]);
+ expect(body.canvas.graph.nodes[0].data.text).toBe("A grey wolf in fresh snow");
+ await settle(body.items[0].id);
+ }, 60_000);
+
+ it("says what to fix when nothing can start", async () => {
+ const broken = structuredClone(board);
+ broken.nodes[1].data.modelId = undefined;
+ const res = await run.POST(req("POST", { graph: broken }), ctx(id));
+ expect(res.status).toBe(422);
+ const body = (await res.json()) as { error: string; errors: { nodeId: string; message: string }[] };
+ expect(body.error).toBe("Pick a model (and 1 more)");
+ expect(body.errors.map((e) => e.nodeId)).toEqual(["img", "vid"]);
+ });
+
+ it("respects the engine mode", async () => {
+ setSetting("engineMode", "open");
+ try {
+ // A template asked for in its cloud variant comes out open-source on an open-only install.
+ let res = await list.POST(req("POST", { templateId: "image-animate", engine: "cloud" }));
+ const c = (await res.json()) as Canvas;
+ expect(c.name).toBe("Image → Animate");
+ expect(c.graph.nodes.filter((n) => n.data.modelId).map((n) => n.data.modelId)).toEqual(["oss-z-image-turbo", "oss-wan22-14b-fast"]);
+ // Cloud nodes are refused with a reason.
+ res = await run.POST(req("POST", { graph: board }), ctx(id));
+ expect(res.status).toBe(422);
+ expect(((await res.json()) as { error: string }).error).toMatch(/^Nano Banana Pro is a paid cloud model, but this install is open source only/);
+ // The open variant runs.
+ res = await run.POST(req("POST", {}), ctx(c.id));
+ expect(res.status).toBe(201);
+ const body = (await res.json()) as { items: Generation[] };
+ expect(body.items.map((g) => g.engine)).toEqual(["open", "open"]);
+ for (const g of body.items) await gens.cancelGeneration(g.id);
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ const res = await list.POST(req("POST", { templateId: "nope" }));
+ expect(res.status).toBe(422);
+ });
+
+ it("duplicates and deletes", async () => {
+ let res = await dup.POST(req("POST"), ctx(id));
+ expect(res.status).toBe(201);
+ const copy = (await res.json()) as Canvas;
+ expect(copy.name).toBe("Copy of Fox film");
+ expect(copy.graph.nodes).toHaveLength(4);
+ expect(Object.keys(copy.runs).sort()).toEqual(["img", "vid"]);
+
+ res = await one.DELETE(req("DELETE"), ctx(copy.id));
+ expect(res.status).toBe(204);
+ res = await one.GET(req("GET"), ctx(copy.id));
+ expect(res.status).toBe(404);
+ // The original and its results are untouched.
+ res = await one.GET(req("GET"), ctx(id));
+ expect(((await res.json()) as { generations: Generation[] }).generations.length).toBeGreaterThan(0);
+ });
+});