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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Canvas: pages, groups, comments and drawings in the board; Change voice, Clone voice, Translate and Video concatenator nodes
Claude67ae7ee13c60
diff --git a/src/app/api/canvases/[id]/route.ts b/src/app/api/canvases/[id]/route.tsindex 0e67b6ab..9522daff 100644--- a/src/app/api/canvases/[id]/route.ts+++ b/src/app/api/canvases/[id]/route.ts@@ -1,10 +1,14 @@import { connection } from "next/server";import { z } from "zod";-import { canvasView, deleteCanvas, graphProblem, parseGraph, updateCanvas } from "@/server/canvas";+import { canvasView, deleteCanvas, graphProblem, pagesProblem, parseGraph, parsePages, updateCanvas } from "@/server/canvas";const Patch = z.object({name: z.string().trim().min(1).max(80).optional(),+ /** Every page (the editor's autosave). */+ pages: z.unknown().optional(),+ /** One page's board (`page`, else the first page). */graph: z.unknown().optional(),+ page: z.string().max(40).optional(),});/** The board, its nodes' last runs and the generations they made. */@@ -15,14 +19,16 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/canvases/[id]">return view ? Response.json(view) : Response.json({ error: "Not found" }, { status: 404 });}-/** Rename and/or autosave the graph. */+/** Rename and/or autosave the pages (or one page's 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 pages = parsed.data.pages === undefined ? undefined : parsePages(parsed.data.pages);+ if (pages === null) return Response.json({ error: pagesProblem(parsed.data.pages) }, { status: 400 });const graph = parsed.data.graph === undefined ? undefined : parseGraph(parsed.data.graph);if (graph === null) return Response.json({ error: graphProblem(parsed.data.graph) }, { status: 400 });- const c = updateCanvas(id, { name: parsed.data.name, graph });+ const c = updateCanvas(id, { name: parsed.data.name, pages, graph, page: parsed.data.page });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.tsindex 303a826d..db2af975 100644--- a/src/app/api/canvases/[id]/run/route.ts+++ b/src/app/api/canvases/[id]/run/route.ts@@ -2,11 +2,15 @@ import { z } from "zod";import { graphProblem, parseGraph, runCanvas } from "@/server/canvas";const Body = z.object({+ /** The page to run (the first one when omitted). */+ page: z.string().max(40).optional(),/** 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(),+ /** Run a group's nodes (and what they need). */+ group: z.string().max(80).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). */+ /** The page's board as the editor shows it (saved first). */graph: z.unknown().optional(),});@@ -20,7 +24,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/canvases/[iif (!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: graphProblem(parsed.data.graph) }, { status: 400 });- const result = runCanvas(id, { targets: parsed.data.targets, force: parsed.data.force, graph });+ const result = runCanvas(id, { page: parsed.data.page, targets: parsed.data.targets, group: parsed.data.group, 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;diff --git a/src/app/api/canvases/route.ts b/src/app/api/canvases/route.tsindex 2b3011a5..a6c37953 100644--- a/src/app/api/canvases/route.ts+++ b/src/app/api/canvases/route.ts@@ -1,12 +1,13 @@import { connection } from "next/server";import { z } from "zod";-import { createCanvas, listCanvases, parseGraph } from "@/server/canvas";+import { createCanvas, listCanvases, parseGraph, parsePages } 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(),+ pages: z.unknown().optional(),});export async function GET() {@@ -17,11 +18,12 @@ export async function GET() {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, pages: rawPages, ...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 });+ const pages = rawPages === undefined ? undefined : parsePages(rawPages);+ if (graph === null || pages === null) return Response.json({ error: "That board couldn't be read" }, { status: 400 });try {- return Response.json(createCanvas({ ...rest, graph }), { status: 201 });+ return Response.json(createCanvas({ ...rest, graph, pages }), { status: 201 });} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsxindex 30818236..a2bfcf4f 100644--- a/src/components/canvas/canvas-context.tsx+++ b/src/components/canvas/canvas-context.tsx@@ -72,6 +72,7 @@ export const PORT_COLOR: Record<PortType, string> = {video: "var(--chart-4)",audio: "var(--chart-3)",element: "var(--chart-1)",+ voice: "var(--chart-3)",};export type NodeState = GenerationStatus | "idle";diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex c8cbeaee..2c25eea8 100644--- a/src/components/canvas/canvas-editor.tsx+++ b/src/components/canvas/canvas-editor.tsx@@ -181,8 +181,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvconst runM = useRunCanvas(id);const runMutate = runM.mutate;- const [nodes, setNodes] = useState<FlowNode[]>(() => initial.graph.nodes.map(toFlowNode));- const [edges, setEdges] = useState<Edge[]>(() => initial.graph.edges.map(toFlowEdge));+ const [nodes, setNodes] = useState<FlowNode[]>(() => initial.pages[0].graph.nodes.map(toFlowNode));+ const [edges, setEdges] = useState<Edge[]>(() => initial.pages[0].graph.edges.map(toFlowEdge));const [name, setName] = useState(initial.name);const [tab, setTab] = useState<"board" | "list">("board");const [paletteOpen, setPaletteOpen] = useState(true);@@ -194,7 +194,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvconst [saveRefused, setSaveRefused] = useState(false);const [rev, setRev] = useState(0);const wrapper = useRef<HTMLDivElement>(null);- const viewport = useRef<Viewport | undefined>(initial.graph.viewport);+ const viewport = useRef<Viewport | undefined>(initial.pages[0].graph.viewport);const savedRev = useRef(0);const savedName = useRef(initial.name);@@ -275,7 +275,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv);const fitOptions = useMemo(() => fitFor(paletteOpen), [fitFor, paletteOpen]);// Phones always start fitted (a viewport saved on a big screen would show an empty board).- const savedViewport = isMobile ? undefined : initial.graph.viewport;+ const savedViewport = isMobile ? undefined : initial.pages[0].graph.viewport;// The first fit, once every node has its size: a big board may zoom further out than later fits,// and when it would be too small to read beside the palette, the palette folds away instead.const initialized = useNodesInitialized();diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex 1f756326..163f6625 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -1211,6 +1211,10 @@ export const NODE_TYPES = {upscale: GeneratorNode,"bg-remove": GeneratorNode,tts: GeneratorNode,+ "voice-change": GeneratorNode,+ "clone-voice": MediaInputNode,+ translate: GeneratorNode,+ concat: GeneratorNode,output: OutputNode,note: NoteNode,} satisfies Record<CanvasNodeType, React.ComponentType<NodeProps<FlowNode>>>;diff --git a/src/lib/catalog/canvas-board.ts b/src/lib/catalog/canvas-board.tsnew file mode 100644index 00000000..20f85b46--- /dev/null+++ b/src/lib/catalog/canvas-board.ts@@ -0,0 +1,307 @@+/**+ * Canvas boards beyond the node graph (Higgsfield Canvas parity): pages, groups (frames), comment pins and+ * annotation shapes. Everything here is pure, shared by the editor and the server.+ *+ * A canvas row stores a document of pages; each page is its own board (nodes, edges, viewport, and the+ * groups, comments and shapes drawn on it). Rows saved before pages existed hold one board: they read as+ * a single page. Results stay keyed by node id across pages (node ids are unique within a canvas).+ *+ * Groups don't own their nodes: a node belongs to the group its top-left corner sits in, so the planner+ * and the server agree on membership without parent links (positions stay absolute).+ */+import type { CanvasGraph, CanvasNode } from "./canvas";++// ---------------------------------------------------------------------------+// Annotations++/** Annotation and group colours: the app's chart tokens (both themes), and "ink" (the text colour). */+export const BOARD_COLORS = ["ink", "chart-1", "chart-2", "chart-3", "chart-4", "chart-5"] as const;+export type BoardColor = (typeof BOARD_COLORS)[number];++export const BOARD_COLOR_LABEL: Record<BoardColor, string> = {+ ink: "Ink",+ "chart-1": "Lime",+ "chart-2": "Blue",+ "chart-3": "Violet",+ "chart-4": "Orange",+ "chart-5": "Pink",+};++/** A frame around nodes: moves them with it, and runs them together. */+export interface CanvasGroup {+ id: string;+ title: string;+ color: BoardColor;+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface CommentReply {+ id: string;+ author: string;+ text: string;+ at: number;+}++/** A comment pinned to the board. */+export interface CanvasComment {+ id: string;+ x: number;+ y: number;+ author: string;+ text: string;+ at: number;+ resolved?: boolean;+ replies?: CommentReply[];+}++export type ShapeKind = "rect" | "ellipse" | "arrow" | "text" | "pen";++export const SHAPE_LABEL: Record<ShapeKind, string> = { rect: "Rectangle", ellipse: "Ellipse", arrow: "Arrow", text: "Text", pen: "Drawing" };++/** A drawing on the board (not run). Arrow and pen points are fractions (0–1) of the shape's box, so resizing scales them. */+export interface CanvasShape {+ id: string;+ kind: ShapeKind;+ x: number;+ y: number;+ width: number;+ height: number;+ color: BoardColor;+ text?: string;+ points?: [number, number][];+}++/** Who wrote a comment: Fuobe is single-user, so it's always you. */+export const COMMENT_AUTHOR = "You";++export const BOARD_LIMITS = { pages: 20, groups: 100, comments: 200, shapes: 500, penPoints: 400, commentText: 2000, replies: 50, groupTitle: 80, shapeText: 2000 } as const;++/** Freehand points closer than this (board px) to the last kept one are dropped. */+const PEN_STEP = 2;++/**+ * A freehand stroke as a shape: its bounding box and its points as fractions of it. Points closer than+ * PEN_STEP are dropped and long strokes are thinned to BOARD_LIMITS.penPoints. Null for a dot.+ */+export function penShape(id: string, raw: { x: number; y: number }[], color: BoardColor): CanvasShape | null {+ const pts: { x: number; y: number }[] = [];+ for (const p of raw) {+ const last = pts[pts.length - 1];+ if (!last || Math.hypot(p.x - last.x, p.y - last.y) >= PEN_STEP) pts.push(p);+ }+ if (pts.length < 2) return null;+ const every = Math.ceil(pts.length / BOARD_LIMITS.penPoints);+ const kept = every > 1 ? pts.filter((_, i) => i % every === 0 || i === pts.length - 1) : pts;+ const box = boundsOf(kept);+ const w = Math.max(1, box.width);+ const h = Math.max(1, box.height);+ return {+ id,+ kind: "pen",+ x: Math.round(box.x),+ y: Math.round(box.y),+ width: Math.round(w),+ height: Math.round(h),+ color,+ points: kept.map((p) => [round3((p.x - box.x) / w), round3((p.y - box.y) / h)]),+ };+}++/** A rectangle, ellipse or arrow dragged from `a` to `b` (an arrow keeps its direction in its points). */+export function dragShape(id: string, kind: Exclude<ShapeKind, "pen" | "text">, a: { x: number; y: number }, b: { x: number; y: number }, color: BoardColor): CanvasShape {+ const x = Math.min(a.x, b.x);+ const y = Math.min(a.y, b.y);+ const width = Math.max(8, Math.abs(b.x - a.x));+ const height = Math.max(8, Math.abs(b.y - a.y));+ const shape: CanvasShape = { id, kind, x: Math.round(x), y: Math.round(y), width: Math.round(width), height: Math.round(height), color };+ if (kind === "arrow") shape.points = [[a.x <= b.x ? 0 : 1, a.y <= b.y ? 0 : 1], [a.x <= b.x ? 1 : 0, a.y <= b.y ? 1 : 0]];+ return shape;+}++const round3 = (n: number) => Math.round(n * 1000) / 1000;++function boundsOf(pts: { x: number; y: number }[]): { x: number; y: number; width: number; height: number } {+ let x0 = Infinity;+ let y0 = Infinity;+ let x1 = -Infinity;+ let y1 = -Infinity;+ for (const p of pts) {+ x0 = Math.min(x0, p.x);+ y0 = Math.min(y0, p.y);+ x1 = Math.max(x1, p.x);+ y1 = Math.max(y1, p.y);+ }+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };+}++/** Distance from p to the segment ab. */+function toSegment(p: { x: number; y: number }, a: { x: number; y: number }, b: { x: number; y: number }): number {+ const dx = b.x - a.x;+ const dy = b.y - a.y;+ const len = dx * dx + dy * dy;+ const t = len ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len)) : 0;+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));+}++/** Whether a point on the board touches a shape (the eraser): its outline for strokes and arrows, its box otherwise. */+export function shapeHit(s: CanvasShape, p: { x: number; y: number }, tolerance = 6): boolean {+ if (p.x < s.x - tolerance || p.y < s.y - tolerance || p.x > s.x + s.width + tolerance || p.y > s.y + s.height + tolerance) return false;+ if ((s.kind === "pen" || s.kind === "arrow") && s.points && s.points.length > 1) {+ const at = (q: [number, number]) => ({ x: s.x + q[0] * s.width, y: s.y + q[1] * s.height });+ for (let i = 1; i < s.points.length; i++) if (toSegment(p, at(s.points[i - 1]), at(s.points[i])) <= tolerance) return true;+ return false;+ }+ if (s.kind === "ellipse") {+ const rx = s.width / 2 + tolerance;+ const ry = s.height / 2 + tolerance;+ const dx = p.x - (s.x + s.width / 2);+ const dy = p.y - (s.y + s.height / 2);+ return (dx * dx) / (rx * rx) + (dy * dy) / (ry * ry) <= 1;+ }+ return true;+}++/** An SVG path through a stroke's points, in a box of w × h. */+export function strokePath(points: [number, number][], w: number, h: number): string {+ if (!points.length) return "";+ const xy = points.map(([x, y]) => [round3(x * w), round3(y * h)] as const);+ if (xy.length < 3) return `M${xy.map((p) => p.join(" ")).join(" L")}`;+ // Midpoint quadratic smoothing: a hand-drawn line without the corners of a polyline.+ let d = `M${xy[0][0]} ${xy[0][1]}`;+ for (let i = 1; i < xy.length - 1; i++) {+ const mx = round3((xy[i][0] + xy[i + 1][0]) / 2);+ const my = round3((xy[i][1] + xy[i + 1][1]) / 2);+ d += ` Q${xy[i][0]} ${xy[i][1]} ${mx} ${my}`;+ }+ const last = xy[xy.length - 1];+ return `${d} L${last[0]} ${last[1]}`;+}++// ---------------------------------------------------------------------------+// Groups++/** Room around the nodes when a group is made from a selection, and the title bar above them. */+export const GROUP_PAD = 32;+export const GROUP_BAR = 44;++/** A group framing these boxes (the selected nodes' measured bounds). */+export function groupAround(id: string, boxes: { x: number; y: number; width: number; height: number }[], title = "Group", color: BoardColor = "chart-2"): CanvasGroup | null {+ if (!boxes.length) return null;+ const corners = boxes.flatMap((b) => [+ { x: b.x, y: b.y },+ { x: b.x + b.width, y: b.y + b.height },+ ]);+ const b = boundsOf(corners);+ return {+ id,+ title,+ color,+ x: Math.round(b.x - GROUP_PAD),+ y: Math.round(b.y - GROUP_PAD - GROUP_BAR),+ width: Math.round(b.width + GROUP_PAD * 2),+ height: Math.round(b.height + GROUP_PAD * 2 + GROUP_BAR),+ };+}++const inside = (g: Pick<CanvasGroup, "x" | "y" | "width" | "height">, p: { x: number; y: number }) => p.x >= g.x && p.y >= g.y && p.x <= g.x + g.width && p.y <= g.y + g.height;++/**+ * The nodes in a group: those whose top-left corner sits inside it. A node inside two nested groups+ * belongs to both (running the outer one runs the inner one's nodes too).+ */+export function groupMembers(graph: Pick<CanvasGraph, "nodes">, group: Pick<CanvasGroup, "x" | "y" | "width" | "height">): CanvasNode[] {+ return graph.nodes.filter((n) => inside(group, n.position));+}++/** The groups inside this one (moved with it). */+export function innerGroups(groups: readonly CanvasGroup[], group: CanvasGroup): CanvasGroup[] {+ return groups.filter((g) => g.id !== group.id && inside(group, g) && inside(group, { x: g.x + g.width, y: g.y + g.height }));+}++/** Node ids to run for "Run group": its members (the planner adds what they need upstream). */+export function groupTargets(graph: CanvasGraph, groupId: string): string[] {+ const g = graph.groups?.find((x) => x.id === groupId);+ return g ? groupMembers(graph, g).map((n) => n.id) : [];+}++// ---------------------------------------------------------------------------+// Pages++export interface CanvasPage {+ id: string;+ name: string;+ graph: CanvasGraph;+}++/** What a canvas row's graph_json holds. */+export interface CanvasDoc {+ pages: CanvasPage[];+}++export const FIRST_PAGE_ID = "page-1";++export const pageName = (i: number) => `Page ${i + 1}`;++/**+ * The pages stored in a canvas row: the document as saved, or an older row's single board as page 1+ * (nothing is rewritten until the board is saved again).+ */+export function readPages(json: unknown): CanvasPage[] {+ const doc = json as Partial<CanvasDoc> & Partial<CanvasGraph>;+ if (doc && Array.isArray(doc.pages) && doc.pages.length) return doc.pages;+ const graph: CanvasGraph = { nodes: Array.isArray(doc?.nodes) ? doc.nodes : [], edges: Array.isArray(doc?.edges) ? doc.edges : [] };+ if (doc?.viewport) graph.viewport = doc.viewport;+ for (const k of ["groups", "comments", "shapes"] as const) if (Array.isArray(doc?.[k])) (graph as unknown as Record<string, unknown>)[k] = doc[k];+ return [{ id: FIRST_PAGE_ID, name: pageName(0), graph }];+}++/** A page by id, else the first one. */+export function pageOf(pages: readonly CanvasPage[], id?: string | null): CanvasPage {+ return (id && pages.find((p) => p.id === id)) || pages[0];+}++/** The pages with one page's board replaced (the first page when the id isn't there). */+export function withPageGraph(pages: readonly CanvasPage[], id: string | null | undefined, graph: CanvasGraph): CanvasPage[] {+ const target = pageOf(pages, id).id;+ return pages.map((p) => (p.id === target ? { ...p, graph } : p));+}++/** Every node on every page. */+export function allNodes(pages: readonly CanvasPage[]): CanvasNode[] {+ return pages.flatMap((p) => p.graph.nodes);+}++/** A name for a new page that no page has yet: "Page 3". */+export function nextPageName(pages: readonly CanvasPage[]): string {+ const names = new Set(pages.map((p) => p.name.toLowerCase()));+ for (let i = pages.length; ; i++) if (!names.has(pageName(i).toLowerCase())) return pageName(i);+}++/**+ * A copy of a page with new ids for its nodes, edges, groups, comments and shapes (node ids are unique+ * across a canvas, since results are kept by node id). `newId` makes the ids.+ */+export function copyPage(page: CanvasPage, id: string, name: string, newId: (prefix: string) => string): CanvasPage {+ const map = new Map(page.graph.nodes.map((n) => [n.id, newId(n.type)]));+ const g = page.graph;+ return {+ id,+ name,+ graph: {+ ...g,+ nodes: g.nodes.map((n) => ({ ...n, id: map.get(n.id)!, data: { ...n.data, pinned: undefined } })),+ edges: g.edges.flatMap((e) => (map.has(e.source) && map.has(e.target) ? [{ ...e, id: newId("e"), source: map.get(e.source)!, target: map.get(e.target)! }] : [])),+ ...(g.groups && { groups: g.groups.map((x) => ({ ...x, id: newId("group") })) }),+ ...(g.comments && { comments: g.comments.map((x) => ({ ...x, id: newId("comment") })) }),+ ...(g.shapes && { shapes: g.shapes.map((x) => ({ ...x, id: newId("shape") })) }),+ },+ };+}++/** What counts as an edit of a page (its viewport doesn't): compared to set "edited". */+export function pageContent(pages: readonly CanvasPage[]): string {+ return JSON.stringify(pages.map((p) => ({ id: p.id, name: p.name, nodes: p.graph.nodes, edges: p.graph.edges, groups: p.graph.groups, comments: p.graph.comments, shapes: p.graph.shapes })));+}diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex 9bc34aba..11298c36 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -7,6 +7,7 @@* Everything here is pure (no server, no DOM) so the editor (live validation, ports, cost) and* the server (POST /api/canvases/:id/run) plan a graph exactly the same way.*/+import type { CanvasComment, CanvasGroup, CanvasPage, CanvasShape } from "./canvas-board";import { getModel, getPreset, MODELS, supportsOp } from "./index";import { dualEngine, onEngine, runsOn } from "./engines";import { chainedWaitMessage, keyframeChain } from "./keyframes";@@ -27,8 +28,8 @@ import {// ---------------------------------------------------------------------------// Graph types (stored as JSON in the canvases table)-/** What travels along an edge. */-export type PortType = "text" | "image" | "video" | "audio" | "element";+/** What travels along an edge. A voice is an audio sample to speak with (Clone Voice). */+export type PortType = "text" | "image" | "video" | "audio" | "element" | "voice";export const PORT_TYPE_LABEL: Record<PortType, string> = {text: "Text",@@ -36,6 +37,7 @@ export const PORT_TYPE_LABEL: Record<PortType, string> = {video: "Video",audio: "Audio",element: "Element",+ voice: "Voice",};export type CanvasNodeType =@@ -50,9 +52,25 @@ export type CanvasNodeType =| "upscale"| "bg-remove"| "tts"+ | "voice-change"+ | "clone-voice"+ | "translate"+ | "concat"| "output"| "note";+/** Video Concatenator: one clip's cut and sound. Start and end are seconds of the clip; length and size are what the editor measured. */+export interface ClipSettings {+ start?: number;+ end?: number;+ mute?: boolean;+ /** The clip's own length, size and whether it has sound (measured in the browser; undefined = not known yet). */+ length?: number;+ width?: number;+ height?: number;+ audio?: boolean;+}+/** One flat shape for every node type (React Flow wants `data` to be a plain record). */export interface CanvasNodeData {[key: string]: unknown;@@ -76,8 +94,12 @@ export interface CanvasNodeData {params?: GenParams;/** Keep the current result: never re-run this node, downstream nodes use its output as is. */pinned?: boolean;- /** Model node: the kind it was added as (filters the model list). Upscale / Remove background: image or video. */+ /** Model node: the kind it was added as (filters the model list). Upscale / Remove background: image or video. Translate: text or video. */mediaKind?: MediaKind;+ /** Video Concatenator: each clip's cut and sound, by the node it comes from. */+ clips?: Record<string, ClipSettings>;+ /** Video Concatenator: the clips' order (node ids); clips not listed follow in board order. */+ order?: string[];}export interface CanvasNode {@@ -102,6 +124,10 @@ export interface CanvasGraph {nodes: CanvasNode[];edges: CanvasEdge[];viewport?: { x: number; y: number; zoom: number };+ /** Frames around nodes, comment pins and drawings (src/lib/catalog/canvas-board.ts): not run. */+ groups?: CanvasGroup[];+ comments?: CanvasComment[];+ shapes?: CanvasShape[];}/** What a generator node last ran as: its signature (inputs + settings) and its generations. */@@ -109,14 +135,20 @@ export interface NodeRun {sig: string;ids: string[];at: number;+ /** A node made in several steps (Video Concatenator): the generation holding its result. Default: the first id. */+ out?: string;}+/** The generation a node's result (and what it passes on) is in. */+export const runOutput = (r: NodeRun): string => r.out ?? r.ids[0];+export type CanvasRuns = Record<string, NodeRun>;export interface Canvas {id: string;name: string;- graph: CanvasGraph;+ /** Its pages, each a board of its own (one for a canvas saved before pages). */+ pages: CanvasPage[];runs: CanvasRuns;templateId: string | null;createdAt: number;@@ -142,6 +174,7 @@ export interface CanvasSummary {id: string;name: string;nodeCount: number;+ pageCount: number;templateId: string | null;/** The newest finished image or video made on this canvas. */preview: { url: string; kind: MediaKind } | null;@@ -170,6 +203,8 @@ export interface NodeSpec {icon: string;/** Generator nodes: the operations they run (empty = any operation of the chosen model). */ops?: Operation[];+ /** Two ops picked by what goes in: the first runs on the first kind (the default), the second on the second. */+ variants?: [MediaKind, MediaKind];}export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {@@ -181,14 +216,18 @@ export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {model: { type: "model", label: "Model", group: "Generate", icon: "Sparkles", ops: [], description: "Any model in the catalog — image, video, audio or text" },join: { type: "join", label: "Join clips", group: "Utilities", icon: "Combine", ops: ["concat"], description: "Stitch clips into one video, in order (top to bottom)" },frame: { type: "frame", label: "Extract frame", group: "Utilities", icon: "Frame", ops: ["frame"], description: "The last frame of a video, as an image" },- upscale: { type: "upscale", label: "Upscale", group: "Utilities", icon: "ZoomIn", ops: ["upscale-image", "upscale-video"], description: "Sharper, larger images or videos" },- "bg-remove": { type: "bg-remove", label: "Remove background", group: "Utilities", icon: "Eraser", ops: ["bg-remove", "bg-remove-video"], description: "Cut out the subject of an image or video" },+ upscale: { type: "upscale", label: "Upscale", group: "Utilities", icon: "ZoomIn", ops: ["upscale-image", "upscale-video"], variants: ["image", "video"], description: "Sharper, larger images or videos" },+ "bg-remove": { type: "bg-remove", label: "Remove background", group: "Utilities", icon: "Eraser", ops: ["bg-remove", "bg-remove-video"], variants: ["image", "video"], description: "Cut out the subject of an image or video" },tts: { type: "tts", label: "Text to speech", group: "Utilities", icon: "Mic2", ops: ["tts"], description: "Speak a text, in a preset voice or a cloned one" },+ "voice-change": { type: "voice-change", label: "Change voice", group: "Utilities", icon: "AudioWaveform", ops: ["voice-change"], description: "Say a recording again in another voice, keeping its timing" },+ "clone-voice": { type: "clone-voice", label: "Clone voice", group: "Inputs", icon: "UserRound", description: "A voice sample (or one of your saved voices) to speak with" },+ translate: { type: "translate", label: "Translate", group: "Utilities", icon: "Languages", ops: ["translate", "dub"], variants: ["text", "video"], description: "Translate a text, or dub a video into another language" },+ concat: { type: "concat", label: "Video concatenator", group: "Utilities", icon: "Film", ops: ["concat"], description: "Up to 50 clips in one film: trim and mute each, pick the frame" },output: { type: "output", label: "Output", group: "Output", icon: "MonitorPlay", description: "Preview what's connected, side by side" },note: { type: "note", label: "Sticky note", group: "Output", icon: "StickyNote", description: "A note on the board (not run)" },};-export const GENERATOR_TYPES = new Set<CanvasNodeType>(["model", "join", "frame", "upscale", "bg-remove", "tts"]);+export const GENERATOR_TYPES = new Set<CanvasNodeType>(["model", "join", "frame", "upscale", "bg-remove", "tts", "voice-change", "translate", "concat"]);export const isGenerator = (n: Pick<CanvasNode, "type">) => GENERATOR_TYPES.has(n.type);/** Entries of the Add-node palette (several entries can make the same node type). */@@ -221,6 +260,10 @@ export const PALETTE: PaletteItem[] = [{ ...pick("upscale"), id: "upscale", data: { mediaKind: "image" }, keywords: "enhance resolution 4k sharpen" },{ ...pick("bg-remove"), id: "bg-remove", data: { mediaKind: "image" }, keywords: "cutout matte transparent" },{ ...pick("tts"), id: "tts", keywords: "voice speech narration clone" },+ { ...pick("voice-change"), id: "voice-change", keywords: "voice changer speech to speech revoice convert" },+ { ...pick("clone-voice"), id: "clone-voice", keywords: "voice sample clone my voice speaker" },+ { ...pick("translate"), id: "translate", data: { mediaKind: "text" }, keywords: "language translate dub localize subtitles" },+ { ...pick("concat"), id: "concat", keywords: "concatenate join merge stitch edit trim mute film assemble" },{ ...pick("output"), id: "output", keywords: "preview compare result" },{ ...pick("note"), id: "note", keywords: "comment annotation" },];@@ -282,6 +325,8 @@ const PREFERRED: Partial<Record<Operation, Partial<Record<Engine, string>>>> = {avatar: { cloud: "kling-avatar-2", open: "oss-infinitetalk" },lipsync: { cloud: "sync-lipsync-2-pro" },tts: { cloud: "elevenlabs-v4", open: "oss-chatterbox" },+ "voice-change": { cloud: "elevenlabs-voice-changer", open: "oss-chatterbox-vc" },+ dub: { cloud: "elevenlabs-dubbing" },music: { cloud: "elevenlabs-music", open: "oss-ace-step" },sfx: { cloud: "elevenlabs-sfx" },concat: { cloud: "join-clips", open: "oss-join-clips" },@@ -299,15 +344,42 @@ export function nodeOps(n: Pick<CanvasNode, "type" | "data">, model?: ModelDef):const spec = NODE_SPECS[n.type];if (!spec?.ops) return [];if (spec.ops.length) {- if (spec.ops.length === 1) return spec.ops;- // Upscale / Remove background: the image or the video variant.- const video = n.data.mediaKind === "video";- return [spec.ops[video ? 1 : 0]];+ if (spec.ops.length === 1 || !spec.variants) return spec.ops.slice(0, 1);+ // Upscale / Remove background (image or video), Translate (text or video).+ return [spec.ops[n.data.mediaKind === spec.variants[1] ? 1 : 0]];}if (!model) return [];return [...new Set(model.routes.map((r) => r.op))].filter((op) => !UNSUPPORTED_OPS.has(op));}+/**+ * Video Concatenator (Higgsfield's video_assemble): up to 50 clips, each trimmed and muted on its own, framed+ * to one of 8 aspect ratios at 30 fps. Clips over 512 MB are refused. The node's model names its engine: the+ * cloud cuts with trim-video, frames with scale-video, mutes with a −70 dB level and joins with merge-videos;+ * the open engine cuts, frames, retimes and mutes each clip in one CPU step (video-fit-clip) and joins them+ * packet by packet (video-concat-encoded).+ */+export const CONCAT_LIMITS = { clips: 50, fps: 30, maxBytes: 512 * 1024 * 1024, cloudJoin: 24 } as const;+export const CONCAT_RATIOS = ["16:9", "9:16", "1:1", "4:3", "3:4", "3:2", "2:3", "21:9"] as const;+export type ConcatRatio = (typeof CONCAT_RATIOS)[number];+/** The film's size per ratio (720 on the short side, 1280×720 by default; even, within merge-videos' 512–2048). */+export const CONCAT_SIZE: Record<ConcatRatio, { width: number; height: number }> = {+ "16:9": { width: 1280, height: 720 },+ "9:16": { width: 720, height: 1280 },+ "1:1": { width: 960, height: 960 },+ "4:3": { width: 960, height: 720 },+ "3:4": { width: 720, height: 960 },+ "3:2": { width: 1080, height: 720 },+ "2:3": { width: 720, height: 1080 },+ "21:9": { width: 1680, height: 720 },+};+export const CONCAT_MODELS: Record<Engine, string> = { cloud: "join-clips", open: "oss-join-encoded" };+/** The steps of a concatenation, per engine. */+export const CONCAT_TOOLS = {+ cloud: { trim: "trim-video", fit: "scale-video", sound: "extract-soundtrack", level: "ffmpeg-loudnorm", mux: "merge-audio-video", join: "join-clips" },+ open: { fit: "oss-fit-clip", join: "oss-join-encoded" },+} as const;+/** The default model for an op on an engine (utilities may use hidden models, e.g. Extract frame). */export function defaultModelFor(op: Operation, engine: Engine, opts: { hidden?: boolean } = {}): ModelDef | undefined {const preferred = PREFERRED[op]?.[engine];@@ -320,6 +392,7 @@ const KIND_OP: Record<MediaKind, Operation> = { image: "t2i", video: "t2v", audi/** The model a new generator node starts with. */export function defaultModelForNode(n: Pick<CanvasNode, "type" | "data">, engine: Engine): ModelDef | undefined {+ if (n.type === "concat") return getModel(CONCAT_MODELS[engine]);if (n.type === "model") {const kind = n.data.mediaKind ?? "image";return defaultModelFor(n.data.op ?? KIND_OP[kind], engine) ?? MODELS.find((m) => m.engine === engine && !m.hidden && m.kind === kind);@@ -350,6 +423,7 @@ export function modelChoices(n: Pick<CanvasNode, "type" | "data">): ModelDef[] {const kind = n.data.mediaKind;return MODELS.filter((m) => !m.hidden && (!kind || m.kind === kind) && !needsMarks(m) && m.routes.some((r) => !UNSUPPORTED_OPS.has(r.op)));}+ if (n.type === "concat") return Object.values(CONCAT_MODELS).flatMap((id) => getModel(id) ?? []);const ops = nodeOps(n);return MODELS.filter((m) => ops.some((op) => supportsOp(m, op)) && (!m.hidden || ops.includes("frame")) && !needsMarks(m));}@@ -440,6 +514,8 @@ const TEXT_LABEL_OPS = new Set<Operation>(["tts", "translate", "write", "sfx", "/** The input handles a generator node shows (the union over its ops when the op is automatic). */export function inputPorts(n: Pick<CanvasNode, "type" | "data">): PortDef[] {+ // Clone voice: the sample can come from another node (a recording, a generated voice) instead of a file.+ if (n.type === "clone-voice") return [{ id: "audio", label: "Sample", type: "audio", multiple: false }];if (n.type === "output") return [];if (!isGenerator(n)) return [];const model = n.data.modelId ? getModel(n.data.modelId) : undefined;@@ -452,8 +528,9 @@ export function inputPorts(n: Pick<CanvasNode, "type" | "data">): PortDef[] {const ids = new Set(ops.flatMap((op) => OP_PORTS[op] ?? []));// Start & end frames: shown on image-to-video models that can take an end frame.if (ops.includes("i2v") && (model?.options.endFrame || (model && supportsOp(model, "flf2v")))) ids.add("endImage");- // A cloned voice only where the model clones voices.- if (ids.has("voice") && model && !model.options.voiceClone) ids.delete("voice");+ // A cloned voice only where the model clones voices (Text to speech and Change voice always show it, and say+ // which models clone when a voice is connected to one that doesn't).+ if (ids.has("voice") && model && !model.options.voiceClone && n.type !== "tts" && n.type !== "voice-change") ids.delete("voice");// Visual elements only on image and video models.if (ids.has("elements") && model && model.kind !== "image" && model.kind !== "video") ids.delete("elements");const maxImages = model?.options.maxImages ?? (ops.some((op) => MULTI_IMAGE_OPS.has(op)) ? 4 : 1);@@ -467,7 +544,7 @@ export function inputPorts(n: Pick<CanvasNode, "type" | "data">): PortDef[] {video: { id: "video", label: "Video", type: "video", multiple: false },videos: { id: "videos", label: "Clips", type: "video", multiple: true },audio: { id: "audio", label: "Audio", type: "audio", multiple: false },- voice: { id: "voice", label: "Voice to clone", type: "audio", multiple: false },+ voice: { id: "voice", label: "Voice", type: "voice", multiple: false },};return INPUT_ORDER.filter((id) => ids.has(id)).map((id) => defs[id]);}@@ -479,6 +556,7 @@ const toPortType = (k: MediaKind | undefined): PortType | null => (k === "image"/** The type of a node's output handle (null = no output handle). */export function outputType(_graph: CanvasGraph, n: CanvasNode): PortType | null {if (n.type === "prompt") return "text";+ if (n.type === "clone-voice") return "voice";if (n.type === "element") return "element";if (MEDIA_INPUT_TYPE[n.type]) return MEDIA_INPUT_TYPE[n.type]!;if (!isGenerator(n)) return null;@@ -489,15 +567,16 @@ export function outputType(_graph: CanvasGraph, n: CanvasNode): PortType | nullif (op) return toPortType(OPERATION_OUTPUT[op]);if (model) return toPortType(model.kind);if (n.type === "upscale" || n.type === "bg-remove") return n.data.mediaKind === "video" ? "video" : "image";- if (n.type === "join") return "video";+ if (n.type === "join" || n.type === "concat") return "video";if (n.type === "frame") return "image";if (n.type === "tts") return "audio";return toPortType(n.data.mediaKind ?? "image");}-/** Which ports accept which types. */+/** Which ports accept which types: a voice input also takes plain audio (a sample straight from a file or a model). */export function acceptsType(port: PortDef | "preview", type: PortType): boolean {- return port === "preview" ? type !== "element" : port.type === type;+ if (port === "preview") return type !== "element";+ return port.type === type || (port.type === "voice" && type === "audio");}// ---------------------------------------------------------------------------@@ -603,7 +682,8 @@ export function connectionError(graph: CanvasGraph, c: Connection): string | nul} else {const port = inputPorts(t).find((p) => p.id === c.targetHandle);if (!port) return `${nodeLabel(t)} has no ${c.targetHandle ?? ""} input`;- if (!acceptsType(port, type)) return `${PORT_TYPE_LABEL[type]} can't go into ${port.label}`;+ if (!acceptsType(port, type)) return type === "voice" ? `A voice goes into a Voice input (Text to speech, Change voice)` : `${PORT_TYPE_LABEL[type]} can't go into ${port.label}`;+ if (t.type === "concat" && graph.edges.filter((e) => e.target === t.id && e.source !== s.id).length >= CONCAT_LIMITS.clips) return `The video concatenator takes up to ${CONCAT_LIMITS.clips} clips`;}if (ancestors(graph, [s.id]).has(t.id)) return "That would make a loop";return null;@@ -681,9 +761,22 @@ export function withPlaceholders(req: GenerationRequest): GenerationRequest {}export interface NodeRequest {+ /** The request (the last step's, for a node made in several steps). */request: GenerationRequest;- /** Upstream generator nodes, in the order of `request.chain`. */+ /** Upstream generator nodes, in the order of `request.chain` (for steps: each one once, in order of use). */deps: string[];+ /** A node made in several steps (Video Concatenator): its jobs in order; the last one holds the result. */+ steps?: NodeStep[];+}++/** What fills a step's chain slot: an upstream node's result, or an earlier step of the same node. */+export type StepSource = { node: string } | { step: string };++export interface NodeStep {+ key: string;+ /** Its chain slots (request.chain) are filled from `from`, in order. */+ request: GenerationRequest;+ from: StepSource[];}export interface NodeDescription extends Partial<NodeRequest> {@@ -695,8 +788,15 @@ export interface NodeDescription extends Partial<NodeRequest> {error?: string;}-function sourceOf(s: CanvasNode): Source | { error: string } {+function sourceOf(graph: CanvasGraph, s: CanvasNode): Source | { error: string } {if (s.type === "prompt") return { kind: "text", text: (s.data.text ?? "").trim() };+ if (s.type === "clone-voice") {+ // A sample wired in wins over the node's own file (a recording, a generated voice).+ const e = graph.edges.find((x) => x.target === s.id && x.targetHandle === "audio");+ const from = e && graph.nodes.find((n) => n.id === e.source);+ if (from && from.type !== "clone-voice") return sourceOf(graph, from);+ return s.data.url ? { kind: "media", url: s.data.url } : { error: `Add a voice sample to “${nodeLabel(s)}”: record, upload or pick a saved voice` };+ }if (MEDIA_INPUT_TYPE[s.type]) {const what = s.type === "image-input" ? "an image" : s.type === "video-input" ? "a video" : "an audio clip";return s.data.url ? { kind: "media", url: s.data.url } : { error: `Add ${what} to “${nodeLabel(s)}”` };@@ -772,7 +872,8 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeRconst ops = nodeOps(n, model);const op = n.data.op && ops.includes(n.data.op) ? n.data.op : n.type !== "model" ? ops[0] : textOp(model, n.data.params);if (n.type !== "model" && op && !supportsOp(model, op)) return { error: `${model.name} can't do ${OPERATION_LABELS[op].toLowerCase()} — pick another model` };- if (op === "translate" && !n.data.params?.targetLanguage) return { error: "Pick a language to translate into" };+ if ((op === "translate" || op === "dub") && !n.data.params?.targetLanguage) return { error: op === "dub" ? "Pick a language to dub into" : "Pick a language to translate into" };+ if (n.type === "concat") return concatRequest(graph, n, model);const inputs: NonNullable<GenerationRequest["inputs"]> = {};const chain: ChainSlot[] = [];@@ -791,7 +892,7 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeRconst s = nodes.get(e.source)!;const type = outputType(graph, s);if (!type || !acceptsType(port, type)) return { error: `${nodeLabel(s)} can't go into ${port.label}` };- const src = sourceOf(s);+ const src = sourceOf(graph, s);if ("error" in src) return src;list.push(src);}@@ -836,6 +937,11 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeR}}if (generatedText > 1) return { error: "Connect one generated text at a time — join the others into one text model" };+ // A voice wired into a model that only speaks preset voices: say which ones clone.+ if (!model.options.voiceClone && graph.edges.some((e) => e.target === n.id && e.targetHandle === "voice")) {+ const cloners = MODELS.filter((m) => !m.hidden && m.options.voiceClone && op && supportsOp(m, op) && m.engine === model.engine).map((m) => m.name);+ return { error: `${model.name} speaks in preset voices — pick ${cloners.length ? cloners.slice(0, 2).join(" or ") : "a model that clones voices"} to use the connected voice, or disconnect it` };+ }// Prompt: the node's own words, then connected texts, then the elements, then generated text.// "{text}" in the node's prompt marks where connected text goes (a generated text fills it on the server).@@ -864,6 +970,139 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeRreturn { request, deps };}+// ---------------------------------------------------------------------------+// Video Concatenator: one job per clip step, then the join++/** A Video Concatenator's clips in their order: the order picked in the node, then the others top to bottom. */+export function concatClips(graph: CanvasGraph, n: Pick<CanvasNode, "id" | "data">): { nodeId: string; settings: ClipSettings }[] {+ const nodes = nodeMap(graph);+ const ids = [...new Set(incoming(graph, n.id).filter((e) => e.targetHandle === "videos" && nodes.has(e.source)).map((e) => e.source))];+ ids.sort((a, b) => byPosition(nodes.get(a)!, nodes.get(b)!));+ const picked = (n.data.order ?? []).filter((id) => ids.includes(id));+ return [...picked, ...ids.filter((id) => !picked.includes(id))].map((nodeId) => ({ nodeId, settings: n.data.clips?.[nodeId] ?? {} }));+}++/** The feature of a node's in-between jobs (a "-step" feature: the Library lists them under Show steps). */+export const CANVAS_STEP_FEATURE = "canvas-step";++export const concatRatio = (r: string | undefined): ConcatRatio => ((CONCAT_RATIOS as readonly string[]).includes(r ?? "") ? (r as ConcatRatio) : "16:9");++/** loudnorm in linear mode at its lowest target: the clip's sound −70 dB (silent), with no measuring (see linearGain in av/dub.ts). */+export const MUTE_LEVEL = { linear: true, integrated_loudness: -70, measured_i: 0, measured_tp: -12, measured_lra: 1, measured_thresh: -80, loudness_range: 7 } as const;++/** One clip's cut, in seconds, checked against its length when known. */+function clipCut(c: ClipSettings, i: number): { start: number; end?: number } | { error: string } {+ const start = Math.max(0, c.start ?? 0);+ const end = c.end;+ if (end !== undefined && end <= start + 0.05) return { error: `Clip ${i + 1}: the end has to come after the start` };+ if (c.length !== undefined && start >= c.length) return { error: `Clip ${i + 1} starts past its end (it is ${Math.round(c.length * 10) / 10} s long)` };+ return { start: Math.round(start * 1000) / 1000, ...(end !== undefined && { end: Math.round(Math.min(end, c.length ?? end) * 1000) / 1000 }) };+}++/**+ * The Video Concatenator's jobs. Cloud, per clip: trim-video (when cut), scale-video (into the film's frame),+ * and for a muted clip with sound its soundtrack, lowered −70 dB, muxed back; then merge-videos at 30 fps,+ * folded in joins of 24. Open, per clip: video-fit-clip (cut, frame, 30 fps and the sound or silence in one+ * CPU pass), then video-concat-encoded (packet copy: the clips now share one size, rate and sound layout).+ */+function concatRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeRequest | { error: string } {+ const engine = model.engine;+ const clips = concatClips(graph, n);+ if (!clips.length) return { error: `Connect the clips to join (up to ${CONCAT_LIMITS.clips})` };+ if (clips.length > CONCAT_LIMITS.clips) return { error: `The video concatenator takes up to ${CONCAT_LIMITS.clips} clips — remove ${clips.length - CONCAT_LIMITS.clips}` };+ const nodes = nodeMap(graph);+ const ratio = concatRatio(n.data.params?.aspectRatio);+ const size = CONCAT_SIZE[ratio];+ const title = nodeLabel(n);+ const base = { feature: "canvas" } as const;+ const steps: NodeStep[] = [];+ const deps: string[] = [];+ const lasts: string[] = [];+ /** A step reading one video: a file (inputs.video) or an upstream node / earlier step (a chain slot). */+ const add = (key: string, from: StepSource | { url: string }, req: Omit<GenerationRequest, "feature">, more: { slot: ChainSlot; from: StepSource }[] = []) => {+ const url = "url" in from ? from.url : undefined;+ const slots: ChainSlot[] = [...(url ? [] : [{ slot: "video" as const }]), ...more.map((m) => m.slot)];+ steps.push({+ key,+ request: { ...base, ...req, ...(url && { inputs: { ...req.inputs, video: url } }), ...(slots.length && { chain: slots }) },+ from: [...(url ? [] : [from as StepSource]), ...more.map((m) => m.from)],+ });+ return { step: key } as StepSource;+ };+ for (const [i, c] of clips.entries()) {+ const s = nodes.get(c.nodeId)!;+ if (outputType(graph, s) !== "video") return { error: `${nodeLabel(s)} can't go into Clips` };+ const src = sourceOf(graph, s);+ if ("error" in src) return src;+ if (src.kind !== "media" && src.kind !== "node") return { error: `${nodeLabel(s)} can't go into Clips` };+ if (src.kind === "node" && !deps.includes(src.nodeId)) deps.push(src.nodeId);+ const cut = clipCut(c.settings, i);+ if ("error" in cut) return cut;+ const label = (what: string) => ({ label: `${title} · ${what} clip ${i + 1}`, index: i, of: clips.length });+ let at: StepSource | { url: string } = src.kind === "media" ? { url: src.url } : { node: src.nodeId };+ const mute = !!c.settings.mute && c.settings.audio !== false;+ if (engine === "open") {+ at = add(`fit:${i}`, at, {+ modelId: CONCAT_TOOLS.open.fit,+ op: "trim",+ params: { startTime: cut.start, ...(cut.end !== undefined && { endTime: cut.end }), fps: CONCAT_LIMITS.fps, extra: { ...size, ...(mute && { mute: true }) } },+ step: label("Fit"),+ });+ } else {+ if (cut.start > 0 || cut.end !== undefined) {+ // fal's trim-video defaults to 1 s → 3 s when an end is missing: always send both.+ const end = cut.end ?? c.settings.length;+ if (end === undefined) return { error: `Clip ${i + 1}: set where it ends too — the cloud cut needs both ends (or run the clip first, so its length is known)` };+ at = add(`trim:${i}`, at, { modelId: CONCAT_TOOLS.cloud.trim, op: "trim", params: { startTime: cut.start, endTime: end }, step: label("Trim") });+ }+ at = add(`fit:${i}`, at, { modelId: CONCAT_TOOLS.cloud.fit, op: "reframe", params: { aspectRatio: ratio, extra: { ...size } }, step: label("Frame") });+ if (mute) {+ const sound = add(`sound:${i}`, at, { modelId: CONCAT_TOOLS.cloud.sound, op: "separate-audio", step: label("Sound of") });+ steps.push({ key: `quiet:${i}`, request: { ...base, modelId: CONCAT_TOOLS.cloud.level, op: "level", params: { extra: { ...MUTE_LEVEL } }, chain: [{ slot: "audio" }], step: label("Mute") }, from: [sound] });+ at = add(`mute:${i}`, at, { modelId: CONCAT_TOOLS.cloud.mux, op: "mux", step: label("Mute") }, [{ slot: { slot: "audio" }, from: { step: `quiet:${i}` } }]);+ }+ }+ lasts.push((at as { step: string }).step);+ }+ // The join: one on the open engine (up to 100 clips), folded by 24 on the cloud.+ let level = lasts;+ const max = engine === "open" ? CONCAT_LIMITS.clips : CONCAT_LIMITS.cloudJoin;+ for (let depth = 0; level.length > 1; depth++) {+ const groups = Math.ceil(level.length / max);+ const last = groups === 1;+ const next: string[] = [];+ for (let g = 0; g < groups; g++) {+ const part = level.slice(Math.floor((g * level.length) / groups), Math.floor(((g + 1) * level.length) / groups));+ if (part.length === 1) {+ next.push(part[0]);+ continue;+ }+ const key = last ? "join" : `join:${depth}:${g}`;+ steps.push({+ key,+ request: {+ ...base,+ modelId: engine === "open" ? CONCAT_TOOLS.open.join : CONCAT_TOOLS.cloud.join,+ op: "concat",+ ...(engine === "cloud" && { params: { extra: { target_fps: CONCAT_LIMITS.fps } } }),+ chain: part.map(() => ({ slot: "videos" as const })),+ step: { label: last ? title : `${title} · join part ${g + 1}`, index: clips.length, of: clips.length + 1 },+ },+ from: part.map((k) => ({ step: k })),+ });+ next.push(key);+ }+ level = next;+ }+ // The cuts, frames and parts are helper steps (the Library hides them): only the film is a result.+ for (const st of steps) if (st.key !== level[0]) st.request = { ...st.request, feature: CANVAS_STEP_FEATURE };+ const final = steps.find((x) => x.key === level[0])!;+ return { request: final.request, deps, steps };+}++/** A Translate node set to video with no cloud model allowed: where the open engine dubs. */+export const OPEN_DUB_HINT = "Dubbing a video here runs on the cloud (ElevenLabs Dubbing, HeyGen). On the open engine, dub it in Dub, where you check the translation before it's spoken";+export interface DescribeContext {engineMode?: "both" | "open" | "cloud";}@@ -874,7 +1113,7 @@ export function describeNode(graph: CanvasGraph, n: CanvasNode, ctx: DescribeConconst mode = ctx.engineMode ?? "both";// A Fuobe Original as it runs on the node's engine (its routes, its price).const model = nodeModel(n, mode);- if (!model) return { costUsd: null, error: n.data.modelId ? "That model is no longer in the catalog — pick another" : "Pick a model" };+ if (!model) return { costUsd: null, error: n.data.modelId ? "That model is no longer in the catalog — pick another" : n.type === "translate" && n.data.mediaKind === "video" ? OPEN_DUB_HINT : "Pick a model" };if (mode !== "both" && !runsOn(model, mode)) {return {model,@@ -887,6 +1126,7 @@ export function describeNode(graph: CanvasGraph, n: CanvasNode, ctx: DescribeCon}const built = buildRequest(graph, n, model);if ("error" in built) return { model, costUsd: null, error: built.error };+ if (built.steps) return describeSteps(built, model);try {const plan = planGeneration(withPlaceholders(built.request), (id) => (id === model.id ? model : getModel(id)), getPreset);// A film built clip by clip, or the open text-to-3D still and model, is planned from its inputs when it starts:@@ -899,6 +1139,24 @@ export function describeNode(graph: CanvasGraph, n: CanvasNode, ctx: DescribeCon}}+/** A node made in several steps: every step planned with placeholders, the price their sum, the plan the last step's. */+function describeSteps(built: NodeRequest, model: ModelDef): NodeDescription {+ let cost = 0;+ let unknown = false;+ let plan: Plan | undefined;+ for (const st of built.steps!) {+ try {+ plan = planGeneration(withPlaceholders(st.request), getModel, getPreset);+ } catch (e) {+ return { ...built, model, costUsd: null, error: `${st.request.step?.label ?? st.key}: ${(e as Error).message}` };+ }+ const c = estimateCost(plan.model, plan.params, plan.jobs, plan.op);+ if (c === null) unknown = true;+ else cost += c;+ }+ return { ...built, model, plan, costUsd: unknown ? null : Math.round(cost * 10000) / 10000 };+}+// ---------------------------------------------------------------------------// Signatures: a node is fresh when it last ran with exactly these inputs and settings.@@ -928,13 +1186,21 @@ function hash(s: string): string {return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);}-/** The node's identity for "is this result still fresh": its request (minus labels) and the generations it builds on. */-export function nodeSignature(req: GenerationRequest, depIds: string[]): string {+const unlabeled = (req: GenerationRequest): Partial<GenerationRequest> => {const rest: Partial<GenerationRequest> = { ...req };delete rest.step;delete rest.frame;delete rest.feature;- return hash(stable({ ...rest, deps: depIds }));+ return rest;+};++/**+ * The node's identity for "is this result still fresh": its request (minus labels) and the generations it+ * builds on. A node made in several steps: every step and what feeds it.+ */+export function nodeSignature(req: GenerationRequest, depIds: string[], steps?: NodeStep[]): string {+ if (steps) return hash(stable({ steps: steps.map((st) => ({ key: st.key, request: unlabeled(st.request), from: st.from })), deps: depIds }));+ return hash(stable({ ...unlabeled(req), deps: depIds }));}// ---------------------------------------------------------------------------@@ -1014,11 +1280,11 @@ export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPlcontinue;}const prev = runs[id];- const prevStatus = prev ? status(prev.ids[0]) : undefined;+ const prevStatus = prev ? status(runOutput(prev)) : undefined;if (n.data.pinned) {if (prev && LIVE.has(prevStatus)) {- state.set(id, { kind: "reuse", id: prev.ids[0] });- reused.push({ nodeId: id, reason: "pinned", generationId: prev.ids[0] });+ state.set(id, { kind: "reuse", id: runOutput(prev) });+ reused.push({ nodeId: id, reason: "pinned", generationId: runOutput(prev) });} else {state.set(id, { kind: "blocked" });errors.push({ nodeId: id, message: "Pinned, but there's no result to use yet — unpin it to run it" });@@ -1041,17 +1307,17 @@ export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPllet reason: RunReason | null;if (upstream.some((u) => u.s!.kind === "run")) reason = prev ? "upstream" : "new";else {- const sig = nodeSignature(d.request, upstream.map((u) => (u.s as { id: string }).id));+ const sig = nodeSignature(d.request, upstream.map((u) => (u.s as { id: string }).id), d.steps);const fresh = !!prev && prev.sig === sig && LIVE.has(prevStatus);reason = opts.force && targets.has(id) ? "forced" : fresh ? null : !prev || prevStatus === undefined ? "new" : prev.sig !== sig ? "changed" : "failed";}if (!reason) {- state.set(id, { kind: "reuse", id: prev!.ids[0] });- reused.push({ nodeId: id, reason: "fresh", generationId: prev!.ids[0] });+ state.set(id, { kind: "reuse", id: runOutput(prev!) });+ reused.push({ nodeId: id, reason: "fresh", generationId: runOutput(prev!) });continue;}state.set(id, { kind: "run" });- steps.push({ nodeId: id, label, request: d.request, deps: d.deps, reason, costUsd: d.costUsd });+ steps.push({ nodeId: id, label, request: d.request, deps: d.deps, ...(d.steps && { steps: d.steps }), reason, costUsd: d.costUsd });if (d.costUsd === null) costUnknown = true;else costUsd += d.costUsd;}@@ -1091,6 +1357,8 @@ export function convertEngine(graph: CanvasGraph, engine: Engine): { graph: Canvreturn n;}changed++;+ // The concatenator's settings are its own (the frame, the cuts): only the engine's tools change.+ if (n.type === "concat") return { ...n, data: { ...n.data, modelId: m.id } };const keepOp = n.data.op && supportsOp(m, n.data.op) ? n.data.op : undefined;return { ...n, data: { ...n.data, modelId: m.id, op: keepOp, params: sanitizeParams(m, n.data.params), engine: dualEngine(m) ? engine : undefined } };});@@ -1383,7 +1651,7 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [build: tpl([{ id: "portrait", type: "image-input", x: 0, y: 0, data: { label: "Portrait" } },- { id: "sample", type: "audio-input", x: 0, y: 340, data: { label: "Voice sample (10–30 s)" } },+ { id: "sample", type: "clone-voice", x: 0, y: 340, data: { label: "Your voice (10–30 s sample)" } },{ id: "script", type: "prompt", x: 0, y: 540, data: { label: "Script", text: "Hi! This whole clip was made on a Fuobe canvas from one photo and a few seconds of my voice." } },{ id: "voice", type: "tts", x: COL, y: 400, data: { label: "Cloned voice" }, models: { cloud: "chatterbox-cloud", open: "oss-chatterbox" } },{ id: "avatar", type: "model", x: COL * 2, y: 80, data: { mediaKind: "video", label: "Talking avatar", op: "avatar", prompt: "A friendly presenter talking to the camera, natural head movement" }, models: { cloud: "kling-avatar-2", open: "oss-infinitetalk" } },@@ -1400,6 +1668,27 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [},];+CANVAS_TEMPLATES.push({+ id: "clips-film",+ name: "Clips → one film",+ description: "Trim, mute and join clips in one frame, 30 fps, with the Video concatenator",+ icon: "Film",+ hue: 250,+ build: tpl(+ [+ ...[0, 1, 2].map((i) => ({ id: `clip${i + 1}`, type: "video-input" as const, x: 0, y: i * 320, data: { label: `Clip ${i + 1}` } })),+ { id: "film", type: "concat", x: COL, y: 200, data: { label: "Film", params: { aspectRatio: "16:9" } }, models: { cloud: CONCAT_MODELS.cloud, open: CONCAT_MODELS.open } },+ { id: "out", type: "output", x: COL * 2 + 40, y: 240, data: { label: "Film" } },+ ],+ [+ ["clip1", "film", "videos"],+ ["clip2", "film", "videos"],+ ["clip3", "film", "videos"],+ ["film", "out"],+ ],+ ),+});+export function getTemplate(id: string): CanvasTemplate | undefined {return CANVAS_TEMPLATES.find((t) => t.id === id);}diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex 6ac83ef4..d7cd644f 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -926,6 +926,19 @@ const open: ModelDef[] = [routes: [comfy("trim", "video-trim")],options: {},}),+ // Canvas Video Concatenator: each clip cut, framed, retimed to 30 fps and given its sound (or silence) in one+ // streamed pass, so video-concat-encoded can join the clips packet by packet.+ o({+ id: "oss-fit-clip",+ name: "Fit clip",+ vendor: "ComfyUI",+ family: "utility",+ kind: "video",+ tagline: "Cuts a clip and fits it to one size and frame rate, with its sound or silence · CPU",+ routes: [comfy("trim", "video-fit-clip", "VHS loader in passes: start, length, frame rate; centre crop; sound, or silence when muted")],+ options: {},+ hidden: true,+ }),o({id: "oss-segment",name: "Cut segment (resampled)",diff --git a/src/server/canvas.ts b/src/server/canvas.tsindex 2058e397..9a92c93c 100644--- a/src/server/canvas.ts+++ b/src/server/canvas.ts@@ -1,9 +1,24 @@import "server-only";+import fs from "node:fs";import { nanoid } from "nanoid";import { z } from "zod";+import {+ BOARD_COLORS,+ BOARD_LIMITS,+ FIRST_PAGE_ID,+ groupTargets,+ pageContent,+ pageName,+ pageOf,+ readPages,+ withPageGraph,+ type CanvasPage,+} from "@/lib/catalog/canvas-board";import {CANVAS_TEXT_MAX as TEXT_MAX,+ CONCAT_LIMITS,cleanGraph,+ concatClips,EMPTY_GRAPH,getTemplate,NODE_SPECS,@@ -21,15 +36,19 @@ import {type CanvasSummary,} from "@/lib/catalog/canvas";import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";+import { createPipeline } from "./chains";import { db } from "./db";import { listElements } from "./elements";import { createGenerations, getGeneration } from "./generations";import { engineMode } from "./settings";+import { absolutePath } from "./storage";/**- * 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.+ * Canvas boards (Higgsfield Canvas): the pages the user edits (each a graph, with its groups, comments and+ * drawings), plus the last run of each generator node. Running turns a page's graph into chained generations+ * (src/lib/catalog/canvas.ts plans it; createGenerations + dependsOn runs it, createPipeline for a node made in+ * several steps), so results survive restarts like any other job. graph_json holds {pages}; a row saved before+ * pages holds one graph, read as page 1 (readPages).*/interface Row {@@ -46,7 +65,7 @@ interface Row {const toCanvas = (r: Row): Canvas => ({id: r.id,name: r.name,- graph: JSON.parse(r.graph_json) as CanvasGraph,+ pages: readPages(JSON.parse(r.graph_json)),runs: JSON.parse(r.runs_json) as CanvasRuns,templateId: r.template_id,createdAt: r.created_at,@@ -57,7 +76,25 @@ const toCanvas = (r: Row): Canvas => ({// ---------------------------------------------------------------------------// 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 NODE_TYPES = [+ "prompt",+ "image-input",+ "video-input",+ "audio-input",+ "element",+ "model",+ "join",+ "frame",+ "upscale",+ "bg-remove",+ "tts",+ "voice-change",+ "clone-voice",+ "translate",+ "concat",+ "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). */@@ -100,9 +137,61 @@ const NodeData = z.object({params: Params.optional(),pinned: z.boolean().optional(),mediaKind: z.enum(KINDS).optional(),+ // Video Concatenator: each clip's cut and sound (by source node id) and the clips' order.+ clips: z+ .record(+ z.string().max(80),+ z.object({+ start: z.number().min(0).max(36_000).optional(),+ end: z.number().min(0).max(36_000).optional(),+ mute: z.boolean().optional(),+ length: z.number().min(0).max(36_000).optional(),+ width: z.number().int().min(1).max(16_384).optional(),+ height: z.number().int().min(1).max(16_384).optional(),+ audio: z.boolean().optional(),+ }),+ )+ .optional(),+ order: z.array(z.string().max(80)).max(CONCAT_LIMITS.clips * 2).optional(),});const Num = z.number().finite();+const Color = z.enum(BOARD_COLORS);++const Group = z.object({+ id: z.string().min(1).max(80),+ title: clamped(BOARD_LIMITS.groupTitle),+ color: Color,+ x: Num,+ y: Num,+ width: Num.positive().max(40_000),+ height: Num.positive().max(40_000),+});++const Reply = z.object({ id: z.string().min(1).max(80), author: clamped(60), text: clamped(BOARD_LIMITS.commentText), at: Num });++const Comment = z.object({+ id: z.string().min(1).max(80),+ x: Num,+ y: Num,+ author: clamped(60),+ text: clamped(BOARD_LIMITS.commentText),+ at: Num,+ resolved: z.boolean().optional(),+ replies: z.array(Reply).max(BOARD_LIMITS.replies).optional(),+});++const Shape = z.object({+ id: z.string().min(1).max(80),+ kind: z.enum(["rect", "ellipse", "arrow", "text", "pen"]),+ x: Num,+ y: Num,+ width: Num.positive().max(40_000),+ height: Num.positive().max(40_000),+ color: Color,+ text: clamped(BOARD_LIMITS.shapeText).optional(),+ points: z.array(z.tuple([z.number().min(-1).max(2), z.number().min(-1).max(2)])).max(BOARD_LIMITS.penPoints).optional(),+});export const GraphSchema = z.object({nodes: z@@ -129,8 +218,16 @@ export const GraphSchema = z.object({).max(1200),viewport: z.object({ x: Num, y: Num, zoom: Num.positive().max(10) }).optional(),+ groups: z.array(Group).max(BOARD_LIMITS.groups).optional(),+ comments: z.array(Comment).max(BOARD_LIMITS.comments).optional(),+ shapes: z.array(Shape).max(BOARD_LIMITS.shapes).optional(),});+export const PagesSchema = z+ .array(z.object({ id: z.string().min(1).max(40), name: clamped(60), graph: GraphSchema }))+ .min(1)+ .max(BOARD_LIMITS.pages);+/** 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);@@ -146,9 +243,26 @@ export function graphProblem(input: unknown): string {}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)";+ if (list === "groups") return `This board has too many groups to save (${BOARD_LIMITS.groups} at most)`;+ if (list === "comments") return `This board has too many comments to save (${BOARD_LIMITS.comments} at most)`;+ if (list === "shapes") return `This board has too many drawings to save (${BOARD_LIMITS.shapes} at most) — erase a few`;return fallback;}+/** Why pages from the browser were refused (the page and the node, when one is to blame). */+export function pagesProblem(input: unknown): string {+ if (!Array.isArray(input) || !input.length) return "A canvas needs at least one page";+ if (input.length > BOARD_LIMITS.pages) return `A canvas holds up to ${BOARD_LIMITS.pages} pages`;+ for (const [i, p] of input.entries()) {+ const g = (p as { graph?: unknown } | null)?.graph;+ if (!GraphSchema.safeParse(g).success) {+ const name = typeof (p as { name?: unknown })?.name === "string" ? (p as { name: string }).name : pageName(i);+ return `${name}: ${graphProblem(g)}`;+ }+ }+ return "Those pages couldn't be saved — reload the page";+}+/** 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);@@ -159,6 +273,25 @@ export function parseGraph(input: unknown): CanvasGraph | null {return cleanGraph({ ...g, nodes });}+/**+ * Parsed pages: page ids made unique, and a node id used on an earlier page dropped from later ones+ * (results are kept by node id, so two pages can't share one).+ */+export function parsePages(input: unknown): CanvasPage[] | null {+ const parsed = PagesSchema.safeParse(input);+ if (!parsed.success) return null;+ const ids = new Set<string>();+ const nodeIds = new Set<string>();+ return parsed.data.map((p, i) => {+ let id = p.id;+ for (let k = 2; ids.has(id); k++) id = `${p.id}-${k}`;+ ids.add(id);+ const g = p.graph as CanvasGraph;+ const nodes = g.nodes.filter((n) => !nodeIds.has(n.id) && nodeIds.add(n.id));+ return { id, name: p.name.trim() || pageName(i), graph: cleanGraph({ ...g, nodes }) };+ });+}+// ---------------------------------------------------------------------------// CRUD@@ -193,10 +326,11 @@ export function listCanvases(): CanvasSummary[] {return {id: c.id,name: c.name,- nodeCount: c.graph.nodes.length,+ nodeCount: c.pages.reduce((n, p) => n + p.graph.nodes.length, 0),+ pageCount: c.pages.length,templateId: c.templateId,preview: previewOf(c.runs),- outline: outline(c.graph),+ outline: outline(c.pages[0].graph),createdAt: c.createdAt,updatedAt: c.updatedAt,editedAt: c.editedAt,@@ -207,6 +341,7 @@ export function listCanvases(): CanvasSummary[] {export interface CreateCanvasInput {name?: string;graph?: CanvasGraph;+ pages?: CanvasPage[];/** Start from a template, in the cloud or the all-open-source variant. */templateId?: string;engine?: Engine;@@ -219,11 +354,12 @@ export function createCanvas(input: CreateCanvasInput = {}): Canvas {const mode = engineMode();const engine: Engine = mode === "both" ? (input.engine ?? "cloud") : mode;const graph = template ? template.build(engine) : (input.graph ?? EMPTY_GRAPH);+ const pages = !template && input.pages?.length ? input.pages : [{ id: FIRST_PAGE_ID, name: pageName(0), graph: cleanGraph(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)),+ graph_json: JSON.stringify({ pages }),runs_json: "{}",template_id: template?.id ?? null,created_at: now,@@ -236,21 +372,26 @@ export function createCanvas(input: CreateCanvasInput = {}): Canvas {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 {+export interface CanvasPatch {+ name?: string;+ /** Every page, as the editor has them (page tabs added, renamed, reordered or removed). */+ pages?: CanvasPage[];+ /** One page's board: `page` (the first page when omitted, as before pages). */+ graph?: CanvasGraph;+ page?: string;+}++/** Save a new name, pages and/or one page's graph. Moving a viewport alone doesn't count as an edit. */+export function updateCanvas(id: string, patch: CanvasPatch): 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);+ let pages = current.pages;+ if (patch.pages?.length) pages = patch.pages.map((p) => ({ ...p, graph: cleanGraph(p.graph) }));+ if (patch.graph) pages = withPageGraph(pages, patch.page, cleanGraph(patch.graph));+ const edited = pageContent(pages) !== pageContent(current.pages) ? now : current.editedAt;+ db().prepare("UPDATE canvases SET name = ?, graph_json = ?, updated_at = ?, edited_at = ? WHERE id = ?").run(name, JSON.stringify({ pages }), now, edited, id);return getCanvas(id);}@@ -261,7 +402,7 @@ export function duplicateCanvas(id: string): Canvas | null {const row: Row = {id: nanoid(10),name: `Copy of ${c.name}`.slice(0, 80),- graph_json: JSON.stringify(c.graph),+ graph_json: JSON.stringify({ pages: c.pages }),// The copy shows the same results until it's run again.runs_json: JSON.stringify(c.runs),template_id: c.templateId,@@ -285,7 +426,8 @@ export function canvasView(id: string): { canvas: Canvas; generations: Generatioconst stored = getCanvas(id);if (!stored) return null;// Element nodes show (and mention) their element as it's called now, after a rename.- const canvas = { ...stored, graph: withCurrentElements(stored.graph, listElements()) };+ const elements = listElements();+ const canvas = { ...stored, pages: stored.pages.map((p) => ({ ...p, graph: withCurrentElements(p.graph, elements) })) };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);@@ -296,11 +438,15 @@ export function canvasView(id: string): { canvas: Canvas; generations: Generatio// Runexport interface RunOptions {- /** Nodes to run with their upstream; omit for Run all. */+ /** The page to run (the first one when omitted). */+ page?: string;+ /** Nodes to run with their upstream; omit for Run all (of the page). */targets?: string[];+ /** Run a group: its nodes and what they need. */+ group?: 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). */+ /** The page's board as the editor has it now (saved first, so an autosave in flight can't race the run). */graph?: CanvasGraph;}@@ -320,13 +466,32 @@ function statusOf(id: string): Generation["status"] | undefined {return (db().prepare(`SELECT g.status FROM generations g WHERE g.id = ? AND ${NOT_TRASHED}`).get(id) as { status: Generation["status"] } | undefined)?.status;}+/** A clip on the board that the concatenator refuses: a stored file over 512 MB. */+function oversizedClip(graph: CanvasGraph, nodeId: string): string | null {+ const nodes = nodeMap(graph);+ const n = nodes.get(nodeId);+ if (n?.type !== "concat") return null;+ for (const [i, c] of concatClips(graph, n).entries()) {+ const url = nodes.get(c.nodeId)?.data.url;+ if (!url?.startsWith("/api/files/")) continue;+ try {+ if (fs.statSync(absolutePath(decodeURIComponent(url.slice("/api/files/".length)))).size > CONCAT_LIMITS.maxBytes) return `Clip ${i + 1} is over 512 MB — trim or compress it first`;+ } catch {+ // Gone: the job says so.+ }+ }+ return null;+}+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 })!;+ if (opts.graph) canvas = updateCanvas(id, { graph: opts.graph, page: opts.page })!;// An element renamed since the board was saved: its node mentions the new @handle.- const graph = withCurrentElements(canvas.graph, listElements());- const plan = planCanvas(graph, { targets: opts.targets, force: opts.force, runs: canvas.runs, status: statusOf, engineMode: engineMode() });+ const graph = withCurrentElements(pageOf(canvas.pages, opts.page).graph, listElements());+ const targets = opts.group ? groupTargets(graph, opts.group) : opts.targets;+ if (opts.group && !targets?.length) return { canvas, items: [], ran: [], reused: [], errors: [{ nodeId: opts.group, message: "This group has no nodes in it yet" }], costUsd: 0 };+ const plan = planCanvas(graph, { 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]));@@ -343,13 +508,33 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {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);+ const sig = nodeSignature(step.request, depIds as string[], step.steps);+ if (step.steps) {+ const big = oversizedClip(graph, step.nodeId);+ if (big) throw new Error(big);+ // A node made in several steps: one pipeline, waiting on the upstream nodes' results like on its own steps.+ const existing = Object.fromEntries(step.deps.map((d, k) => [`node:${d}`, depIds[k] as string]));+ const pipe = createPipeline(+ step.steps.map((st) => ({+ key: st.key,+ request: { ...st.request, step: { label: st.request.step?.label ?? step.label, index: i, of: n } },+ after: st.from.map((f) => ("node" in f ? `node:${f.node}` : f.step)),+ })),+ { batchId, existing },+ );+ const out = pipe.byKey[step.steps[step.steps.length - 1].key];+ made.set(step.nodeId, out.id);+ runs[step.nodeId] = { sig, ids: pipe.items.map((g) => g.id), out: out.id, at: Date.now() };+ items.push(...pipe.items);+ } else {+ 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, 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 });diff --git a/tests/canvas-api.test.ts b/tests/canvas-api.test.tsindex 4ec24c02..629830a5 100644--- a/tests/canvas-api.test.ts+++ b/tests/canvas-api.test.ts@@ -63,15 +63,15 @@ describe("canvas API", () => {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 });+ expect(blank).toMatchObject({ name: "Untitled canvas", pages: [{ id: "page-1", name: "Page 1", 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.pages[0].graph.nodes).toHaveLength(4);+ expect(saved.pages[0].graph.edges).toHaveLength(3);expect(saved.editedAt).not.toBeNull();// Media must come from Fuobe's own storage; bad graphs are refused.@@ -79,7 +79,7 @@ describe("canvas API", () => {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"]);+ expect(((await res.json()) as Canvas).pages[0].graph.edges.map((e) => e.id)).toEqual(["e1", "e2", "e3"]);res = await list.GET();const items = ((await res.json()) as { items: CanvasSummary[] }).items;@@ -137,7 +137,7 @@ describe("canvas API", () => {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");+ expect(body.canvas.pages[0].graph.nodes[0].data.text).toBe("A grey wolf in fresh snow");await settle(body.items[0].id);}, 60_000);@@ -173,16 +173,16 @@ describe("canvas API", () => {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);+ expect(saved.pages[0].graph.nodes[0].data.text).toHaveLength(10_000);+ expect(saved.pages[0].graph.nodes[2].data.prompt).toHaveLength(10_000);+ expect(saved.pages[0].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");+ expect(((await res.json()) as Canvas).pages[0].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);@@ -215,7 +215,7 @@ describe("canvas API", () => {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"]);+ expect(c.pages[0].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);@@ -238,7 +238,7 @@ describe("canvas API", () => {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(copy.pages[0].graph.nodes).toHaveLength(4);expect(Object.keys(copy.runs).sort()).toEqual(["img", "vid"]);res = await one.DELETE(req("DELETE"), ctx(copy.id));@@ -265,7 +265,7 @@ describe("canvas API", () => {expect(renamed.handle).not.toBe(el.handle);// The board shows the element's name now, and a run mentions its new @handle.const view = (await (await one.GET(req("GET"), ctx(created.id))).json()) as { canvas: Canvas };- expect(view.canvas.graph.nodes[0].data).toMatchObject({ handle: renamed.handle, name: "Maya Lee" });+ expect(view.canvas.pages[0].graph.nodes[0].data).toMatchObject({ handle: renamed.handle, name: "Maya Lee" });const body = (await (await run.POST(req("POST", { graph }), ctx(created.id))).json()) as { items: Generation[] };expect(body.items[0].request.prompt).toContain(`@${renamed.handle}`);// …which the server resolves to the element (it has no photos: its name goes into the prompt).diff --git a/tests/canvas-plus.test.ts b/tests/canvas-plus.test.tsnew file mode 100644index 00000000..8b5a0088--- /dev/null+++ b/tests/canvas-plus.test.ts@@ -0,0 +1,464 @@+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, CanvasNode } 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-plus-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";++const {+ CONCAT_SIZE,+ MUTE_LEVEL,+ OPEN_DUB_HINT,+ cleanGraph,+ concatClips,+ connectionError,+ convertEngine,+ describeNode,+ inputPorts,+ nodeSignature,+ outputType,+ paletteItems,+ planCanvas,+ runOutput,+} = await import("@/lib/catalog/canvas");+const board = await import("@/lib/catalog/canvas-board");+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 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) });++const node = (id: string, type: CanvasNode["type"], data: CanvasNode["data"] = {}, x = 0, y = 0): CanvasNode => ({ id, type, position: { x, y }, data });+const edge = (source: string, target: string, targetHandle: string) => ({ id: `${source}-${target}-${targetHandle}`, source, sourceHandle: "out", target, targetHandle });++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));+ }+}++// ---------------------------------------------------------------------------++describe("typed ports of the new nodes", () => {+ const g: CanvasGraph = {+ nodes: [+ node("voice", "clone-voice", { url: "/api/files/u/me.wav" }),+ node("rec", "audio-input", { url: "/api/files/u/line.wav" }),+ node("text", "prompt", { text: "Hello there" }),+ node("clip", "video-input", { url: "/api/files/u/a.mp4" }),+ node("tts", "tts", { modelId: "oss-chatterbox" }),+ node("change", "voice-change", { modelId: "oss-chatterbox-vc" }),+ node("lips", "model", { modelId: "sync-lipsync-2-pro", op: "lipsync" }),+ node("tr", "translate", { modelId: "text-llm", mediaKind: "text" }),+ node("dub", "translate", { modelId: "elevenlabs-dubbing", mediaKind: "video" }),+ node("film", "concat", { modelId: "join-clips" }),+ ],+ edges: [],+ };++ it("a cloned voice goes only into Voice inputs; plain audio goes there too", () => {+ expect(outputType(g, g.nodes[0])).toBe("voice");+ expect(connectionError(g, { source: "voice", target: "tts", targetHandle: "voice" })).toBeNull();+ expect(connectionError(g, { source: "voice", target: "change", targetHandle: "voice" })).toBeNull();+ expect(connectionError(g, { source: "rec", target: "change", targetHandle: "voice" })).toBeNull();+ expect(connectionError(g, { source: "rec", target: "change", targetHandle: "audio" })).toBeNull();+ expect(connectionError(g, { source: "voice", target: "lips", targetHandle: "audio" })).toMatch(/Voice input/);+ expect(connectionError(g, { source: "voice", target: "change", targetHandle: "audio" })).toMatch(/Voice input/);+ // A recording (or a generated voice) can be the clone's sample.+ expect(connectionError(g, { source: "rec", target: "voice", targetHandle: "audio" })).toBeNull();+ expect(connectionError(g, { source: "text", target: "voice", targetHandle: "audio" })).toMatch(/Text can't go into Sample/);+ });++ it("Translate takes text or a video, by its mode; the concatenator takes clips only", () => {+ expect(inputPorts(g.nodes[7]).map((p) => [p.id, p.type])).toEqual([["prompt", "text"]]);+ expect(outputType(g, g.nodes[7])).toBe("text");+ expect(inputPorts(g.nodes[8]).map((p) => [p.id, p.type])).toEqual([["video", "video"]]);+ expect(outputType(g, g.nodes[8])).toBe("video");+ expect(connectionError(g, { source: "text", target: "tr", targetHandle: "prompt" })).toBeNull();+ expect(connectionError(g, { source: "clip", target: "tr", targetHandle: "prompt" })).toMatch(/Video can't go into Text/);+ expect(connectionError(g, { source: "clip", target: "dub", targetHandle: "video" })).toBeNull();+ expect(connectionError(g, { source: "clip", target: "film", targetHandle: "videos" })).toBeNull();+ expect(connectionError(g, { source: "rec", target: "film", targetHandle: "videos" })).toMatch(/Audio can't go into Clips/);+ expect(outputType(g, g.nodes[9])).toBe("video");+ });++ it("the concatenator refuses a 51st clip", () => {+ const many: CanvasGraph = { nodes: [node("film", "concat", { modelId: "join-clips" })], edges: [] };+ for (let i = 0; i < 51; i++) many.nodes.push(node(`c${i}`, "video-input", { url: `/api/files/u/${i}.mp4` }, 0, i * 10));+ for (let i = 0; i < 50; i++) many.edges.push(edge(`c${i}`, "film", "videos"));+ expect(connectionError(many, { source: "c50", target: "film", targetHandle: "videos" })).toMatch(/up to 50 clips/);+ // Re-drawing an edge that's already there is no 51st clip.+ expect(connectionError(many, { source: "c3", target: "film", targetHandle: "videos" })).toBeNull();+ });++ it("the palette offers the new nodes, and an open-only install keeps Translate (text) and the concatenator", () => {+ const ids = paletteItems("both").map((p) => p.id);+ expect(ids).toEqual(expect.arrayContaining(["voice-change", "clone-voice", "translate", "concat"]));+ const open = paletteItems("open");+ for (const id of ["voice-change", "clone-voice", "translate", "concat"]) expect(open.find((p) => p.id === id)!.disabled, id).toBeUndefined();+ });+});++describe("plans for the new nodes", () => {+ it("Change voice: ElevenLabs re-voices in a preset voice; Chatterbox in the connected one, on both engines", () => {+ const cloud: CanvasGraph = {+ nodes: [node("rec", "audio-input", { url: "/api/files/u/line.wav" }), node("change", "voice-change", { modelId: "elevenlabs-voice-changer", params: { voice: "JBFqnCBsd6RMkjVDRZzb" } })],+ edges: [edge("rec", "change", "audio")],+ };+ const d = describeNode(cloud, cloud.nodes[1], { engineMode: "cloud" });+ expect(d.error).toBeUndefined();+ expect(d.request).toMatchObject({ modelId: "elevenlabs-voice-changer", op: "voice-change", inputs: { audio: "/api/files/u/line.wav" }, params: { voice: "JBFqnCBsd6RMkjVDRZzb" } });+ expect(d.costUsd).toBeGreaterThan(0);++ // A clone connected to a model with preset voices only: say which models clone.+ cloud.nodes.push(node("me", "clone-voice", { url: "/api/files/u/me.wav" }));+ cloud.edges.push(edge("me", "change", "voice"));+ expect(describeNode(cloud, cloud.nodes[1], { engineMode: "cloud" }).error).toMatch(/preset voices — pick Chatterbox Voice Conversion \(hosted\)/);+ cloud.nodes[1].data.modelId = "chatterbox-vc-cloud";+ expect(describeNode(cloud, cloud.nodes[1], { engineMode: "cloud" }).request).toMatchObject({ modelId: "chatterbox-vc-cloud", inputs: { audio: "/api/files/u/line.wav", voiceAudio: "/api/files/u/me.wav" } });++ const open = convertEngine(cloud, "open").graph;+ const o = describeNode(open, open.nodes[1], { engineMode: "open" });+ expect(o.request).toMatchObject({ modelId: "oss-chatterbox-vc", op: "voice-change", inputs: { audio: "/api/files/u/line.wav", voiceAudio: "/api/files/u/me.wav" } });+ expect(o.costUsd).toBe(0);+ });++ it("Clone voice passes a generated sample on: the speech waits for it", () => {+ const g: CanvasGraph = {+ nodes: [+ node("line", "prompt", { text: "Say this in my voice" }, 0, 0),+ node("first", "tts", { modelId: "elevenlabs-v4", prompt: "A sample" }, 0, 300),+ node("me", "clone-voice", {}, 300, 300),+ node("speak", "tts", { modelId: "chatterbox-cloud" }, 600, 0),+ ],+ edges: [edge("first", "me", "audio"), edge("me", "speak", "voice"), edge("line", "speak", "prompt")],+ };+ const plan = planCanvas(g, { engineMode: "cloud" });+ expect(plan.errors).toEqual([]);+ expect(plan.steps.map((s) => [s.nodeId, s.deps])).toEqual([+ ["first", []],+ ["speak", ["first"]],+ ]);+ expect(plan.steps[1].request.chain).toEqual([{ slot: "voiceAudio" }]);+ // Nothing wired in and no file: the clone asks for a sample.+ g.edges = g.edges.filter((e) => e.source !== "first");+ expect(planCanvas(g, { engineMode: "cloud" }).errors[0].message).toMatch(/^Add a voice sample to “Clone voice”/);+ });++ it("Translate: text through the LLM on both engines, a video through a cloud dub", () => {+ const g: CanvasGraph = {+ nodes: [node("t", "prompt", { text: "Good morning" }), node("tr", "translate", { modelId: "text-llm", mediaKind: "text" })],+ edges: [edge("t", "tr", "prompt")],+ };+ expect(describeNode(g, g.nodes[1]).error).toBe("Pick a language to translate into");+ g.nodes[1].data.params = { targetLanguage: "Spanish" };+ expect(describeNode(g, g.nodes[1]).request).toMatchObject({ modelId: "text-llm", op: "translate", prompt: "Good morning", params: { targetLanguage: "Spanish" } });+ const open = convertEngine(g, "open").graph;+ expect(describeNode(open, open.nodes[1], { engineMode: "open" }).request).toMatchObject({ modelId: "oss-text-llm", op: "translate" });++ const v: CanvasGraph = {+ nodes: [node("clip", "video-input", { url: "/api/files/u/talk.mp4" }), node("dub", "translate", { modelId: "elevenlabs-dubbing", mediaKind: "video", params: { targetLanguage: "es" } })],+ edges: [edge("clip", "dub", "video")],+ };+ expect(describeNode(v, v.nodes[1], { engineMode: "cloud" }).request).toMatchObject({ modelId: "elevenlabs-dubbing", op: "dub", inputs: { video: "/api/files/u/talk.mp4" }, params: { targetLanguage: "es" } });+ // No open dub model: the node says where the open engine dubs.+ const { graph: openV, missing } = convertEngine(v, "open");+ expect(missing).toEqual(["dub"]);+ expect(describeNode({ ...openV, nodes: [openV.nodes[0], { ...openV.nodes[1], data: { ...openV.nodes[1].data, modelId: undefined } }] }, { ...openV.nodes[1], data: { mediaKind: "video" } }, { engineMode: "open" }).error).toBe(OPEN_DUB_HINT);+ });++ const clips = (engine: "cloud" | "open"): CanvasGraph => ({+ nodes: [+ node("a", "video-input", { url: "/api/files/u/a.mp4" }, 0, 0),+ node("gen", "model", { modelId: engine === "cloud" ? "kling-2-5-turbo" : "oss-wan22-14b-fast", mediaKind: "video", prompt: "Waves" }, 0, 400),+ node("film", "concat", { modelId: engine === "cloud" ? "join-clips" : "oss-join-encoded", params: { aspectRatio: "9:16" }, clips: { a: { start: 1, end: 4, mute: true, audio: true } } }, 400, 200),+ ],+ edges: [edge("a", "film", "videos"), edge("gen", "film", "videos")],+ });++ it("Video concatenator, cloud: cut, frame and mute each clip, then join at 30 fps", () => {+ const g = clips("cloud");+ const d = describeNode(g, g.nodes[2], { engineMode: "cloud" });+ expect(d.error).toBeUndefined();+ expect(d.deps).toEqual(["gen"]);+ expect(d.steps!.map((s) => [s.key, s.request.modelId, s.request.op, s.from])).toEqual([+ ["trim:0", "trim-video", "trim", []],+ ["fit:0", "scale-video", "reframe", [{ step: "trim:0" }]],+ ["sound:0", "extract-soundtrack", "separate-audio", [{ step: "fit:0" }]],+ ["quiet:0", "ffmpeg-loudnorm", "level", [{ step: "sound:0" }]],+ ["mute:0", "merge-audio-video", "mux", [{ step: "fit:0" }, { step: "quiet:0" }]],+ ["fit:1", "scale-video", "reframe", [{ node: "gen" }]],+ ["join", "join-clips", "concat", [{ step: "mute:0" }, { step: "fit:1" }]],+ ]);+ const step = (k: string) => d.steps!.find((s) => s.key === k)!.request;+ expect(step("trim:0")).toMatchObject({ inputs: { video: "/api/files/u/a.mp4" }, params: { startTime: 1, endTime: 4 } });+ expect(step("fit:0")).toMatchObject({ params: { aspectRatio: "9:16", extra: CONCAT_SIZE["9:16"] }, chain: [{ slot: "video" }] });+ expect(step("quiet:0").params!.extra).toEqual(MUTE_LEVEL);+ expect(step("mute:0").chain).toEqual([{ slot: "video" }, { slot: "audio" }]);+ expect(step("join")).toMatchObject({ feature: "canvas", params: { extra: { target_fps: 30 } }, chain: [{ slot: "videos" }, { slot: "videos" }] });+ // The in-between jobs are helper steps (the Library hides them); the film is the node's request.+ expect(d.steps!.filter((s) => s.key !== "join").every((s) => s.request.feature === "canvas-step")).toBe(true);+ expect(d.request).toBe(step("join"));+ expect(d.costUsd).toBeGreaterThan(0);++ // A clip cut at its start with no end: the cloud cut needs both, so it asks (or uses the measured length).+ g.nodes[2].data.clips = { a: { start: 2 } };+ expect(describeNode(g, g.nodes[2]).error).toMatch(/Clip 1: set where it ends too/);+ g.nodes[2].data.clips = { a: { start: 2, length: 9 } };+ expect(describeNode(g, g.nodes[2]).steps![0].request.params).toMatchObject({ startTime: 2, endTime: 9 });+ g.nodes[2].data.clips = { a: { start: 5, end: 4 } };+ expect(describeNode(g, g.nodes[2]).error).toBe("Clip 1: the end has to come after the start");+ });++ it("Video concatenator, open: one fit pass per clip (cut, frame, 30 fps, sound or silence), one packet-copy join", () => {+ const g = clips("open");+ const d = describeNode(g, g.nodes[2], { engineMode: "open" });+ expect(d.error).toBeUndefined();+ expect(d.steps!.map((s) => [s.key, s.request.modelId, s.from])).toEqual([+ ["fit:0", "oss-fit-clip", []],+ ["fit:1", "oss-fit-clip", [{ node: "gen" }]],+ ["join", "oss-join-encoded", [{ step: "fit:0" }, { step: "fit:1" }]],+ ]);+ expect(d.steps![0].request).toMatchObject({ op: "trim", inputs: { video: "/api/files/u/a.mp4" }, params: { startTime: 1, endTime: 4, fps: 30, extra: { width: 720, height: 1280, mute: true } } });+ expect(d.steps![1].request.params).toEqual({ startTime: 0, fps: 30, extra: { width: 720, height: 1280 } });+ expect(d.costUsd).toBe(0);+ // The clips' order: picked in the node first, the rest top to bottom.+ expect(concatClips(g, { ...g.nodes[2], data: { ...g.nodes[2].data, order: ["gen"] } }).map((c) => c.nodeId)).toEqual(["gen", "a"]);+ // Switching engines keeps the frame and the cuts.+ const cloud = convertEngine(g, "cloud").graph.nodes[2].data;+ expect(cloud).toMatchObject({ modelId: "join-clips", params: { aspectRatio: "9:16" }, clips: { a: { start: 1, end: 4, mute: true } } });+ });++ it("Video concatenator, cloud: 30 clips fold into joins of at most 24", () => {+ const g: CanvasGraph = { nodes: [node("film", "concat", { modelId: "join-clips" }, 500, 0)], edges: [] };+ for (let i = 0; i < 30; i++) {+ g.nodes.push(node(`c${i}`, "video-input", { url: `/api/files/u/${i}.mp4` }, 0, i * 10));+ g.edges.push(edge(`c${i}`, "film", "videos"));+ }+ const d = describeNode(g, g.nodes[0]);+ const joins = d.steps!.filter((s) => s.request.op === "concat");+ expect(joins.map((s) => [s.key, s.from.length])).toEqual([+ ["join:0:0", 15],+ ["join:0:1", 15],+ ["join", 2],+ ]);+ expect(d.request!.modelId).toBe("join-clips");+ });++ it("a node made in steps is fresh by all its steps, and reused by its last generation", () => {+ const g = clips("open");+ const d = describeNode(g, g.nodes[2], { engineMode: "open" });+ const sig = nodeSignature(d.request!, ["g-1"], d.steps);+ expect(nodeSignature(d.request!, ["g-1"], d.steps)).toBe(sig);+ g.nodes[2].data.clips = { a: { start: 1, end: 4 } };+ const d2 = describeNode(g, g.nodes[2], { engineMode: "open" });+ // Unmuting changes the first clip's pass, not the last step's request.+ expect(d2.request).toEqual(d.request);+ expect(nodeSignature(d2.request!, ["g-1"], d2.steps)).not.toBe(sig);++ const gen = describeNode(g, g.nodes[1], { engineMode: "open" });+ const runs = { gen: { sig: nodeSignature(gen.request!, []), ids: ["g-1"], at: 1 }, film: { sig: nodeSignature(d2.request!, ["g-1"], d2.steps), ids: ["s1", "s2", "s3"], out: "s3", at: 2 } };+ expect(runOutput(runs.film)).toBe("s3");+ const plan = planCanvas(g, { engineMode: "open", runs, status: (id) => (id === "g-1" || id === "s3" ? "succeeded" : undefined) });+ expect(plan.steps).toEqual([]);+ expect(plan.reused.find((r) => r.nodeId === "film")).toEqual({ nodeId: "film", reason: "fresh", generationId: "s3" });+ });+});++describe("board annotations", () => {+ it("strokes keep their shape as fractions of their box, thinned, and the eraser finds them", () => {+ const pts = Array.from({ length: 1000 }, (_, i) => ({ x: 100 + i * 0.5, y: 50 + Math.sin(i / 50) * 40 }));+ const s = board.penShape("s1", pts, "chart-2")!;+ expect(s.kind).toBe("pen");+ expect(s.points!.length).toBeLessThanOrEqual(board.BOARD_LIMITS.penPoints);+ expect(s.points![0]).toEqual([0, expect.closeTo(0.5, 1)]);+ expect(Math.max(...s.points!.map((p) => p[0]))).toBe(1);+ expect(board.shapeHit(s, { x: 100, y: 50 })).toBe(true);+ expect(board.shapeHit(s, { x: 300, y: 200 })).toBe(false);+ expect(board.penShape("dot", [{ x: 1, y: 1 }], "ink")).toBeNull();+ expect(board.strokePath([[0, 0], [0.5, 1], [1, 0]], 100, 50)).toBe("M0 0 Q50 50 75 25 L100 0");+ });++ it("an arrow keeps the way it was drawn; an ellipse is hit inside its curve only", () => {+ const a = board.dragShape("a", "arrow", { x: 200, y: 10 }, { x: 100, y: 110 }, "ink");+ expect(a).toMatchObject({ x: 100, y: 10, width: 100, height: 100, points: [[1, 0], [0, 1]] });+ expect(board.shapeHit(a, { x: 150, y: 60 })).toBe(true);+ expect(board.shapeHit(a, { x: 110, y: 20 })).toBe(false);+ const e = board.dragShape("e", "ellipse", { x: 0, y: 0 }, { x: 100, y: 100 }, "ink");+ expect(board.shapeHit(e, { x: 50, y: 50 })).toBe(true);+ expect(board.shapeHit(e, { x: 2, y: 2 }, 0)).toBe(false);+ });++ it("a group frames the selection and runs the nodes inside it, with what they need upstream", () => {+ const g: CanvasGraph = {+ nodes: [+ node("p", "prompt", { text: "A lighthouse" }, 0, 0),+ node("img", "model", { modelId: "nano-banana-pro", mediaKind: "image" }, 400, 0),+ node("vid", "model", { modelId: "kling-2-5-turbo", mediaKind: "video", op: "i2v", prompt: "Waves roll in" }, 800, 0),+ node("other", "model", { modelId: "nano-banana-pro", mediaKind: "image", prompt: "A boat" }, 400, 600),+ ],+ edges: [edge("p", "img", "prompt"), edge("img", "vid", "images")],+ };+ const grp = board.groupAround("g1", [{ x: 800, y: 0, width: 300, height: 400 }], "Animate", "chart-3")!;+ expect(grp).toMatchObject({ x: 800 - board.GROUP_PAD, y: -board.GROUP_PAD - board.GROUP_BAR, width: 300 + 2 * board.GROUP_PAD });+ g.groups = [grp];+ expect(board.groupMembers(g, grp).map((n) => n.id)).toEqual(["vid"]);+ const plan = planCanvas(g, { targets: board.groupTargets(g, "g1") });+ expect(plan.steps.map((s) => s.nodeId)).toEqual(["img", "vid"]);+ expect(board.groupTargets(g, "nope")).toEqual([]);+ const outer = { ...board.groupAround("g0", [{ x: 0, y: 0, width: 1200, height: 1200 }])!, id: "g0" };+ expect(board.innerGroups([outer, grp], outer).map((x) => x.id)).toEqual(["g1"]);+ });+});++describe("pages", () => {+ it("an older row's board reads as page 1; a page copy gets new ids everywhere", () => {+ const legacy = { nodes: [node("p", "prompt", { text: "x" })], edges: [], viewport: { x: 1, y: 2, zoom: 1 } };+ expect(board.readPages(legacy)).toEqual([{ id: "page-1", name: "Page 1", graph: legacy }]);+ expect(board.readPages({ pages: [{ id: "a", name: "A", graph: { nodes: [], edges: [] } }] })[0].id).toBe("a");++ const g: CanvasGraph = {+ nodes: [node("p", "prompt", { text: "x" }), node("m", "model", { modelId: "nano-banana-pro", pinned: true })],+ edges: [edge("p", "m", "prompt")],+ groups: [{ id: "g", title: "G", color: "ink", x: 0, y: 0, width: 10, height: 10 }],+ comments: [{ id: "c", x: 0, y: 0, author: "You", text: "hi", at: 1 }],+ shapes: [{ id: "s", kind: "rect", x: 0, y: 0, width: 10, height: 10, color: "ink" }],+ };+ let n = 0;+ const copy = board.copyPage({ id: "page-1", name: "Page 1", graph: g }, "page-2", "Page 2", (p) => `${p}-${++n}`);+ expect(copy.graph.nodes.map((x) => x.id)).not.toContain("p");+ expect(copy.graph.edges[0]).toMatchObject({ source: copy.graph.nodes[0].id, target: copy.graph.nodes[1].id });+ expect(copy.graph.nodes[1].data.pinned).toBeUndefined();+ expect([copy.graph.groups![0].id, copy.graph.comments![0].id, copy.graph.shapes![0].id]).not.toContain("g");+ expect(board.nextPageName([{ id: "1", name: "Page 1", graph: g }, copy])).toBe("Page 3");+ expect(cleanGraph(copy.graph).edges).toHaveLength(1);+ });++ it("store, reload and run each page of a canvas", async () => {+ let res = await list.POST(req("POST", { name: "Pages", graph: { nodes: [node("p", "prompt", { text: "A red fox" }), node("img", "model", { modelId: "nano-banana-pro" }, 400)], edges: [edge("p", "img", "prompt")] } }));+ const c = (await res.json()) as Canvas;+ expect(c.pages.map((p) => [p.id, p.name, p.graph.nodes.length])).toEqual([["page-1", "Page 1", 2]]);++ const second: CanvasGraph = {+ nodes: [node("p2", "prompt", { text: "A grey wolf" }), node("img2", "model", { modelId: "nano-banana-pro" }, 400), node("img", "note", { text: "same id as on page 1" })],+ edges: [edge("p2", "img2", "prompt")],+ groups: [{ id: "g", title: "Wolves", color: "chart-4", x: 300, y: -100, width: 500, height: 600 }],+ comments: [{ id: "c1", x: 10, y: 10, author: "You", text: "Try a husky too", at: Date.now(), replies: [{ id: "r1", author: "You", text: "Or a fox", at: Date.now() }] }],+ shapes: [{ id: "s1", kind: "pen", x: 0, y: 0, width: 50, height: 20, color: "chart-2", points: [[0, 0], [1, 1]] }],+ viewport: { x: 5, y: 6, zoom: 0.8 },+ };+ const pages = [c.pages[0], { id: "page-2", name: "Wolves", graph: second }];+ res = await one.PATCH(req("PATCH", { pages }), ctx(c.id));+ expect(res.status).toBe(200);+ const saved = (await res.json()) as Canvas;+ expect(saved.editedAt).not.toBeNull();+ expect(saved.pages.map((p) => p.name)).toEqual(["Page 1", "Wolves"]);+ // A node id already used on page 1 can't be reused on page 2 (results are kept by node id).+ expect(saved.pages[1].graph.nodes.map((x) => x.id)).toEqual(["p2", "img2"]);+ expect(saved.pages[1].graph).toMatchObject({ groups: second.groups, comments: second.comments, shapes: second.shapes, viewport: second.viewport });+ // Reloaded as stored.+ const view = (await (await one.GET(req("GET"), ctx(c.id))).json()) as { canvas: Canvas };+ expect(view.canvas.pages[1].graph.comments![0].replies![0].text).toBe("Or a fox");+ const card = ((await (await list.GET()).json()) as { items: { id: string; pageCount: number; nodeCount: number }[] }).items.find((x) => x.id === c.id)!;+ expect(card).toMatchObject({ pageCount: 2, nodeCount: 4 });++ // Bad pages are refused, naming the page.+ res = await one.PATCH(req("PATCH", { pages: [{ id: "x", name: "Broken", graph: { nodes: [{ id: "n", type: "nope", position: { x: 0, y: 0 }, data: {} }], edges: [] } }] }), ctx(c.id));+ expect(res.status).toBe(400);+ expect(((await res.json()) as { error: string }).error).toMatch(/^Broken: /);+ expect((await one.PATCH(req("PATCH", { pages: [] }), ctx(c.id))).status).toBe(400);++ // Run page 2: only its nodes run; page 1 is left alone.+ res = await run.POST(req("POST", { page: "page-2" }), ctx(c.id));+ expect(res.status).toBe(201);+ const ran = (await res.json()) as { ran: string[]; items: Generation[]; canvas: Canvas };+ expect(ran.ran).toEqual(["img2"]);+ expect(ran.items[0].prompt).toBe("A grey wolf");+ expect(Object.keys(ran.canvas.runs)).toEqual(["img2"]);+ await settle(ran.items[0].id);++ // A graph sent with a run updates that page only.+ const edited = structuredClone(second);+ edited.nodes[0].data.text = "A white wolf";+ res = await run.POST(req("POST", { page: "page-2", graph: edited }), ctx(c.id));+ const again = (await res.json()) as { ran: string[]; canvas: Canvas };+ expect(again.ran).toEqual(["img2"]);+ expect(again.canvas.pages[0].graph.nodes[0].data.text).toBe("A red fox");+ expect(again.canvas.pages[1].graph.nodes[0].data.text).toBe("A white wolf");++ // A row stored before pages (one bare graph) still opens, as page 1.+ db().prepare("UPDATE canvases SET graph_json = ? WHERE id = ?").run(JSON.stringify({ nodes: [node("old", "prompt", { text: "old" })], edges: [] }), c.id);+ const old = (await (await one.GET(req("GET"), ctx(c.id))).json()) as { canvas: Canvas };+ expect(old.canvas.pages).toEqual([{ id: "page-1", name: "Page 1", graph: { nodes: [node("old", "prompt", { text: "old" })], edges: [] } }]);+ // …and a save of its first page by graph alone keeps working.+ res = await one.PATCH(req("PATCH", { graph: { nodes: [node("new", "prompt", { text: "new" })], edges: [] } }), ctx(c.id));+ expect(((await res.json()) as Canvas).pages[0].graph.nodes[0].id).toBe("new");+ }, 60_000);++ it("runs a group, and a concatenator as one pipeline whose film the node keeps", async () => {+ const graph: CanvasGraph = {+ nodes: [+ node("p", "prompt", { text: "Waves on rocks" }, 0, 0),+ node("shot", "model", { modelId: "kling-2-5-turbo", mediaKind: "video" }, 400, 0),+ node("clip", "video-input", { url: "/api/files/u/demo.mp4" }, 400, 500),+ node("film", "concat", { modelId: "join-clips", clips: { clip: { start: 0.5, end: 2, mute: true } } }, 800, 200),+ node("lonely", "model", { modelId: "nano-banana-pro", prompt: "A cat" }, 0, 1200),+ ],+ edges: [edge("p", "shot", "prompt"), edge("shot", "film", "videos"), edge("clip", "film", "videos")],+ groups: [{ id: "edit", title: "Edit", color: "chart-2", x: 760, y: 100, width: 400, height: 500 }],+ };+ // The demo provider reads the clip like a real one would.+ fs.mkdirSync(path.join(dir, "files", "u"), { recursive: true });+ fs.writeFileSync(path.join(dir, "files", "u", "demo.mp4"), Buffer.alloc(256));+ let res = await list.POST(req("POST", { name: "Group run", graph }));+ const c = (await res.json()) as Canvas;+ res = await run.POST(req("POST", { group: "edit" }), ctx(c.id));+ expect(res.status).toBe(201);+ const body = (await res.json()) as { ran: string[]; items: Generation[]; canvas: Canvas; errors: unknown[] };+ expect(body.errors).toEqual([]);+ // The group's node and what it needs; never the node outside it.+ expect(body.ran).toEqual(["shot", "film"]);+ const film = body.canvas.runs.film;+ const shotId = body.canvas.runs.shot.ids[0];+ expect(film.ids).toHaveLength(7);+ const out = gens.getGeneration(film.out!)!;+ expect(out).toMatchObject({ modelId: "join-clips", op: "concat", feature: "canvas" });+ expect(body.items.filter((g) => film.ids.includes(g.id) && g.id !== film.out).every((g) => g.feature === "canvas-step")).toBe(true);+ // The generated shot is framed after it's made: its fit step waits for it.+ const deps = (id: string) => (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;+ expect(body.items.filter((g) => g.modelId === "scale-video").map((g) => deps(g.id))).toContain(shotId);++ const done = await settle(film.out!);+ expect(done.status, film.ids.map((i) => `${gens.getGeneration(i)!.modelId}: ${gens.getGeneration(i)!.status} ${gens.getGeneration(i)!.error ?? ""}`).join("\n")).toBe("succeeded");+ // Fresh now: running the group again starts nothing and reuses the film.+ res = await run.POST(req("POST", { group: "edit" }), ctx(c.id));+ const again = (await res.json()) as { ran: string[]; reused: { nodeId: string; generationId: string }[] };+ expect(again.ran).toEqual([]);+ expect(again.reused.find((r) => r.nodeId === "film")!.generationId).toBe(film.out);++ // An empty group says so.+ res = await run.POST(req("POST", { group: "nope" }), ctx(c.id));+ expect(res.status).toBe(422);+ expect(((await res.json()) as { error: string }).error).toBe("This group has no nodes in it yet");+ }, 90_000);+});diff --git a/tests/canvas.test.ts b/tests/canvas.test.tsindex 0fbcf547..fdb7a258 100644--- a/tests/canvas.test.ts+++ b/tests/canvas.test.ts@@ -352,7 +352,7 @@ describe("canvas templates", () => {expect(graphEngine(g)).toBe(engine);const plan = planCanvas(g, { engineMode: engine });// Only the empty upload nodes need the user.- for (const e of plan.errors) expect(e.message).toMatch(/^(Add (an image|an audio clip) to|Waiting on)/);+ for (const e of plan.errors) expect(e.message).toMatch(/^(Add (an image|an audio clip|a video|a voice sample) to|Waiting on)/);if (!plan.errors.length) expect(plan.steps.length).toBe(g.nodes.filter(isGenerator).length);if (engine === "open") expect(plan.costUsd).toBe(0);});