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 server: trashed results count as gone, long text is clamped, refusals name the node

Claude6098d9eb2f4b
diff --git a/src/app/api/canvases/[id]/route.ts b/src/app/api/canvases/[id]/route.ts
index 6f29d775..0e67b6ab 100644
--- a/src/app/api/canvases/[id]/route.ts
+++ b/src/app/api/canvases/[id]/route.ts
@@ -1,6 +1,6 @@
import { connection } from "next/server";
import { z } from "zod";
-import { canvasView, deleteCanvas, parseGraph, updateCanvas } from "@/server/canvas";
+import { canvasView, deleteCanvas, graphProblem, parseGraph, updateCanvas } from "@/server/canvas";
const Patch = z.object({
name: z.string().trim().min(1).max(80).optional(),
@@ -21,7 +21,7 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/canvases/[
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 });
+ if (graph === null) return Response.json({ error: graphProblem(parsed.data.graph) }, { status: 400 });
const c = updateCanvas(id, { name: parsed.data.name, graph });
return c ? Response.json(c) : 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
index 49b57091..303a826d 100644
--- a/src/app/api/canvases/[id]/run/route.ts
+++ b/src/app/api/canvases/[id]/run/route.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { parseGraph, runCanvas } from "@/server/canvas";
+import { graphProblem, parseGraph, runCanvas } from "@/server/canvas";
const Body = z.object({
/** Node ids to run with everything upstream (Run node, Run selected); omit for Run all. */
@@ -19,7 +19,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/canvases/[i
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 });
+ if (graph === null) return Response.json({ error: graphProblem(parsed.data.graph) }, { 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) {
diff --git a/src/server/canvas.ts b/src/server/canvas.ts
index ebbf29c3..67f1a13f 100644
--- a/src/server/canvas.ts
+++ b/src/server/canvas.ts
@@ -2,9 +2,11 @@ import "server-only";
import { nanoid } from "nanoid";
import { z } from "zod";
import {
+ CANVAS_TEXT_MAX as TEXT_MAX,
cleanGraph,
EMPTY_GRAPH,
getTemplate,
+ NODE_SPECS,
nodeLabel,
nodeMap,
nodeSignature,
@@ -70,18 +72,27 @@ const Params = z.object({
extra: z.record(z.string(), z.union([z.string().max(2000), z.number(), z.boolean()])).optional(),
});
+/** Free text is clamped, not refused: one over-long paste must never stop the whole board from saving. */
+const clamped = (max: number) => z.string().transform((s) => s.slice(0, max));
+
+/** Element handles are letters, digits, `_` and `-` (handleFor); anything else is dropped. */
+const Handle = z
+ .string()
+ .max(200)
+ .transform((h) => h.replace(/[^\p{L}\p{N}_-]/gu, "").slice(0, 60) || undefined);
+
const NodeData = z.object({
- label: z.string().max(80).optional(),
- text: z.string().max(10_000).optional(),
+ label: clamped(80).optional(),
+ text: clamped(TEXT_MAX).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(),
+ name: clamped(200).optional(),
elementId: z.string().max(40).optional(),
- handle: z.string().max(60).optional(),
+ handle: Handle.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(),
+ prompt: clamped(TEXT_MAX).optional(),
params: Params.optional(),
pinned: z.boolean().optional(),
mediaKind: z.enum(KINDS).optional(),
@@ -116,6 +127,24 @@ export const GraphSchema = z.object({
viewport: z.object({ x: Num, y: Num, zoom: Num.positive().max(10) }).optional(),
});
+/** Why a graph from the browser was refused, naming the node (the editor shows it in a toast). */
+export function graphProblem(input: unknown): string {
+ const parsed = GraphSchema.safeParse(input);
+ const fallback = "That board couldn't be saved — reload the page";
+ if (parsed.success) return fallback;
+ const [list, index, ...rest] = parsed.error.issues[0]?.path ?? [];
+ if (list === "nodes" && typeof index === "number") {
+ const n = (input as { nodes?: { type?: string; data?: { label?: unknown } }[] }).nodes?.[index];
+ const custom = typeof n?.data?.label === "string" && n.data.label.trim() ? n.data.label.trim().slice(0, 80) : undefined;
+ const label = custom ?? NODE_SPECS[n?.type as CanvasNodeType]?.label ?? "A node";
+ const field = rest.filter((p): p is string => typeof p === "string" && p !== "data").join(" ");
+ return `“${label}” couldn't be saved${field ? ` (its ${field})` : ""}: change it or remove the node`;
+ }
+ if (list === "nodes") return "This board has too many nodes to save (300 at most)";
+ if (list === "edges") return "This board has too many connections to save (1,200 at most)";
+ return fallback;
+}
+
/** 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);
@@ -134,6 +163,9 @@ export function getCanvas(id: string): Canvas | null {
return r ? toCanvas(r) : null;
}
+/** Generations in the Trash count as gone: never a card preview, never a fresh result to reuse. */
+const NOT_TRASHED = "NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = g.id)";
+
/** The newest finished image among the canvas's results (a video when it made no image). */
function previewOf(runs: CanvasRuns): CanvasSummary["preview"] {
const ids = Object.values(runs)
@@ -143,7 +175,7 @@ function previewOf(runs: CanvasRuns): CanvasSummary["preview"] {
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 kind = 'image' DESC, completed_at DESC LIMIT 1`,
+ `SELECT g.outputs_json FROM generations g WHERE g.id IN (${ids.map(() => "?").join(",")}) AND g.status = 'succeeded' AND g.kind IN ('image','video') AND ${NOT_TRASHED} ORDER BY g.kind = 'image' DESC, g.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;
@@ -277,8 +309,9 @@ export interface RunResult {
costUsd: number;
}
+/** A result's status; undefined once it's gone (deleted, or in the Trash), so its node runs again. */
function statusOf(id: string): Generation["status"] | undefined {
- return (db().prepare("SELECT status FROM generations WHERE id = ?").get(id) as { status: Generation["status"] } | undefined)?.status;
+ return (db().prepare(`SELECT g.status FROM generations g WHERE g.id = ? AND ${NOT_TRASHED}`).get(id) as { status: Generation["status"] } | undefined)?.status;
}
export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
diff --git a/tests/canvas-api.test.ts b/tests/canvas-api.test.ts
index a8417b97..e71a4011 100644
--- a/tests/canvas-api.test.ts
+++ b/tests/canvas-api.test.ts
@@ -14,6 +14,7 @@ process.env.COMFYUI_URL = "http://127.0.0.1:9";
const { setSetting } = await import("@/server/settings");
const gens = await import("@/server/generations");
+const lib = await import("@/server/library");
const { db } = await import("@/server/db");
const list = await import("@/app/api/canvases/route");
const one = await import("@/app/api/canvases/[id]/route");
@@ -140,6 +141,63 @@ describe("canvas API", () => {
await settle(body.items[0].id);
}, 60_000);
+ it("treats a result moved to the Trash as gone: Run all makes it again", async () => {
+ // Bring the whole board up to date (the last test re-ran only the image).
+ let res = await run.POST(req("POST", {}), ctx(id));
+ for (const g of ((await res.json()) as { items: Generation[] }).items) await settle(g.id);
+ expect((await run.POST(req("POST", {}), ctx(id))).status).toBe(200);
+ let view = (await (await one.GET(req("GET"), ctx(id))).json()) as { canvas: Canvas; generations: Generation[] };
+ const imgId = view.canvas.runs.img.ids[0];
+ expect(gens.getGeneration(imgId)?.status).toBe("succeeded");
+
+ lib.trashGenerations([imgId]);
+ view = (await (await one.GET(req("GET"), ctx(id))).json()) as typeof view;
+ expect(view.generations.map((g) => g.id)).not.toContain(imgId);
+ // The card's preview no longer shows the trashed image.
+ const card = ((await (await list.GET()).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;
+ expect(card.preview?.url).not.toBe(gens.getGeneration(imgId, { includeDeleted: true })!.outputs[0].url);
+
+ res = await run.POST(req("POST", {}), ctx(id));
+ expect(res.status).toBe(201);
+ const body = (await res.json()) as { ran: string[]; reused: { nodeId: string }[]; items: Generation[] };
+ expect(body.ran).toEqual(["img", "vid"]);
+ expect(body.reused).toEqual([]);
+ await settle(body.items[1].id);
+ }, 60_000);
+
+ it("clamps over-long text instead of refusing the board, and names the node it can't save", async () => {
+ const long = structuredClone(board);
+ long.nodes[0].data.text = "x".repeat(10_001);
+ long.nodes[2].data.prompt = "y".repeat(12_000);
+ long.nodes[1].data.label = "L".repeat(200);
+ let res = await one.PATCH(req("PATCH", { graph: long }), ctx(id));
+ expect(res.status).toBe(200);
+ const saved = (await res.json()) as Canvas;
+ expect(saved.graph.nodes[0].data.text).toHaveLength(10_000);
+ expect(saved.graph.nodes[2].data.prompt).toHaveLength(10_000);
+ expect(saved.graph.nodes[1].data.label).toHaveLength(80);
+
+ // Element handles keep letters, digits, _ and - only (they end up in prompts as @handle).
+ const odd = structuredClone(board);
+ odd.nodes.push({ id: "el", type: "element", position: { x: 0, y: 300 }, data: { handle: "a(b", elementId: "x" } });
+ odd.edges.push({ id: "e4", source: "el", sourceHandle: "out", target: "img", targetHandle: "elements" });
+ res = await one.PATCH(req("PATCH", { graph: odd }), ctx(id));
+ expect(((await res.json()) as Canvas).graph.nodes.find((n) => n.id === "el")!.data.handle).toBe("ab");
+ // Planning a board with an odd handle never throws (it used to build a RegExp from it).
+ res = await run.POST(req("POST", { graph: odd, targets: ["out"] }), ctx(id));
+ expect(res.status).toBeLessThan(500);
+ for (const g of ((await res.json()) as { items?: Generation[] }).items ?? []) await gens.cancelGeneration(g.id);
+
+ // What can't be clamped is refused with the node's name.
+ const bad = structuredClone(board);
+ bad.nodes[1].data.label = "Hero shot";
+ bad.nodes[1].data.preview = "http://evil.example/a.png";
+ res = await one.PATCH(req("PATCH", { graph: bad }), ctx(id));
+ expect(res.status).toBe(400);
+ expect(((await res.json()) as { error: string }).error).toBe("“Hero shot” couldn't be saved (its preview): change it or remove the node");
+ await one.PATCH(req("PATCH", { graph: board }), ctx(id));
+ }, 60_000);
+
it("says what to fix when nothing can start", async () => {
const broken = structuredClone(board);
broken.nodes[1].data.modelId = undefined;