Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Canvas: review fixes for pages, undo, tables and the concatenator

Claude720f2c643208
diff --git a/src/app/api/canvases/[id]/route.ts b/src/app/api/canvases/[id]/route.ts
index 9522daff..fd4346b9 100644
--- a/src/app/api/canvases/[id]/route.ts
+++ b/src/app/api/canvases/[id]/route.ts
@@ -1,6 +1,6 @@
import { connection } from "next/server";
import { z } from "zod";
-import { canvasView, deleteCanvas, graphProblem, pagesProblem, parseGraph, parsePages, updateCanvas } from "@/server/canvas";
+import { CanvasConflict, canvasView, deleteCanvas, graphProblem, pagesProblem, parseGraph, parsePages, updateCanvas } from "@/server/canvas";
const Patch = z.object({
name: z.string().trim().min(1).max(80).optional(),
@@ -28,8 +28,13 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/canvases/[
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, pages, graph, page: parsed.data.page });
- return c ? Response.json(c) : Response.json({ error: "Not found" }, { status: 404 });
+ try {
+ 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 });
+ } catch (e) {
+ if (e instanceof CanvasConflict) return Response.json({ error: e.message }, { status: e.status });
+ throw e;
+ }
}
export async function DELETE(_req: Request, ctx: RouteContext<"/api/canvases/[id]">) {
diff --git a/src/app/api/canvases/[id]/run/route.ts b/src/app/api/canvases/[id]/run/route.ts
index db2af975..8857bb32 100644
--- a/src/app/api/canvases/[id]/run/route.ts
+++ b/src/app/api/canvases/[id]/run/route.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { graphProblem, parseGraph, runCanvas } from "@/server/canvas";
+import { CanvasConflict, graphProblem, pagesProblem, parseGraph, parsePages, runCanvas } from "@/server/canvas";
const Body = z.object({
/** The page to run (the first one when omitted). */
@@ -10,7 +10,9 @@ const Body = z.object({
group: z.string().max(80).optional(),
/** Re-run the targets even when their result is still fresh. */
force: z.boolean().optional(),
- /** The page's board as the editor shows it (saved first). */
+ /** Every page as the editor has them (saved first, like the autosave). */
+ pages: z.unknown().optional(),
+ /** Or only this page's board as the editor shows it (saved first). */
graph: z.unknown().optional(),
});
@@ -22,9 +24,17 @@ export async function POST(request: Request, ctx: RouteContext<"/api/canvases/[i
const { id } = await ctx.params;
const parsed = Body.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) return Response.json({ error: "Invalid run request" }, { status: 400 });
+ const 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 result = runCanvas(id, { page: parsed.data.page, targets: parsed.data.targets, group: parsed.data.group, force: parsed.data.force, graph });
+ let result: ReturnType<typeof runCanvas>;
+ try {
+ result = runCanvas(id, { page: parsed.data.page, pages, targets: parsed.data.targets, group: parsed.data.group, force: parsed.data.force, graph });
+ } catch (e) {
+ if (e instanceof CanvasConflict) return Response.json({ error: e.message }, { status: e.status });
+ throw e;
+ }
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/components/canvas/board.tsx b/src/components/canvas/board.tsx
index c4e65c1b..7face06c 100644
--- a/src/components/canvas/board.tsx
+++ b/src/components/canvas/board.tsx
@@ -379,7 +379,17 @@ const CommentNode = memo(function CommentNode({ id, data, selected }: NodeProps<
};
const count = (text.trim() ? 1 : 0) + replies.length;
return (
- <div className="relative" data-testid={`canvas-comment-${id}`} onKeyDown={(e) => open && e.key === "Escape" && (e.stopPropagation(), close())}>
+ <div
+ className="relative"
+ data-testid={`canvas-comment-${id}`}
+ onKeyDown={(e) => open && e.key === "Escape" && (e.stopPropagation(), close())}
+ // Focus leaving the comment (a click on the board, another comment) closes it, and an empty one goes away. A
+ // click on the card's own padding focuses React Flow's node wrapper: still inside. Switching apps isn't leaving.
+ onBlur={(e) => {
+ const inside = e.currentTarget.closest(".react-flow__node") ?? e.currentTarget;
+ if (open && !inside.contains(e.relatedTarget as Node | null) && document.hasFocus()) close();
+ }}
+ >
<button
onClick={() => (open ? close() : setOpen(true))}
className={cn(
diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsx
index 7e24b937..f0ed9be3 100644
--- a/src/components/canvas/canvas-context.tsx
+++ b/src/components/canvas/canvas-context.tsx
@@ -30,7 +30,7 @@ import {
describeNode,
effectiveOp,
isGenerator,
- rowsFeeding,
+ tablesFeeding,
type CanvasGraph,
type CanvasNode,
type CanvasNodeData,
@@ -210,18 +210,22 @@ export class DescribeCache {
}
const next = new Map<string, { key: unknown[]; info: NodeInfo }>();
const out = new Map<string, NodeInfo>();
- const tables = graph.nodes.some((n) => n.type === "table");
+ // Rows reach a node from a table any number of steps up: the table it runs per row of is an input too
+ // (worked out once for the whole board, not per node).
+ const feeds = graph.nodes.some((n) => n.type === "table") ? tablesFeeding(graph) : null;
+ const tableKey = (n: CanvasNode) => {
+ const rows = feeds!(n);
+ return rows && "table" in rows ? rows.table.data : rows?.error;
+ };
for (const n of graph.nodes) {
if (!isGenerator(n)) continue;
const key: unknown[] = [n.type, n.data];
- // Rows reach a node from a table any number of steps up: the table it runs per row of is an input too.
- if (tables) {
- const rows = rowsFeeding(graph, n);
- key.push(rows && "table" in rows ? rows.table.data : rows?.error);
- }
+ if (feeds) key.push(tableKey(n));
for (const e of into.get(n.id) ?? []) {
const s = byId.get(e.source);
key.push(e.source, e.targetHandle, s?.type, s?.data, s?.position.x, s?.position.y);
+ // A Video concatenator takes a clip per row from a node run per row: that node's table is its input too.
+ if (feeds && n.type === "concat" && s) key.push(tableKey(s));
// A cloned voice passes on what's wired into it: that is an input of this node too.
if (s?.type === "clone-voice") for (const f of into.get(s.id) ?? []) key.push(f.source, byId.get(f.source)?.type, byId.get(f.source)?.data);
}
@@ -319,6 +323,11 @@ export interface EditorActions {
open: (id: string, index?: number) => void;
/** Add an input node holding this node's first output, wired nowhere yet. */
toInput: (id: string) => void;
+ /**
+ * Add an input node holding a file made for this node elsewhere (an open-engine dub), below it; `takeOver` moves
+ * the node's outgoing connections onto it.
+ */
+ addInput: (id: string, file: { url: string; kind: "image" | "video" | "audio"; label?: string }, takeOver?: boolean) => void;
/** Draw an edge (the keyboard's "Connect output to…"). */
connect: (c: Connection) => void;
/** Remove an edge (the keyboard's "Disconnect"). */
diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsx
index a40357af..1c1a3ec0 100644
--- a/src/components/canvas/canvas-editor.tsx
+++ b/src/components/canvas/canvas-editor.tsx
@@ -50,8 +50,10 @@ import {
copyPage,
dragShape,
groupAround,
+ groupMembers,
nextPageName,
penShape,
+ remapNodeData,
shapeHit,
withPageGraph,
type BoardColor,
@@ -73,6 +75,7 @@ import {
isGenerator,
newId,
nodeLabel,
+ OPEN_DUB_HINT,
OUT,
outputType,
paletteItems,
@@ -109,7 +112,7 @@ import { BOARD_COLOR_VAR, boardToFlow, commentNode, flowToBoard, focusOnMount, g
import { NodeList } from "./node-list";
import { NODE_TYPES, type FlowNode } from "./nodes";
import { AddMenu, DRAG_TYPE, Palette, PaletteToggle } from "./palette";
-import { BoardToolbar, PageTabs, TOOL_KEYS, type DragShape, type PageOps, type Tool } from "./toolbar";
+import { BoardToolbar, PAGE_PANEL_ID, PageTabs, pageTabId, TOOL_KEYS, type DragShape, type PageOps, type Tool } from "./toolbar";
import { saveCanvas, useCanvasView, useRunCanvas, type CanvasView } from "./use-canvas";
const GRID: [number, number] = [16, 16];
@@ -159,6 +162,8 @@ const PAN_MIDDLE = [1];
/** Board tools that turn a drag or click on the board into a drawing, a note or a comment. */
const GESTURE_TOOLS = new Set<Tool>(["draw", "erase", "note", "table", "shape", "text", "comment"]);
+/** Tools that place one thing: Enter places it in the middle of the view too. */
+const PLACE_TOOLS = new Set<Tool>(["note", "table", "shape", "text", "comment"]);
/** Edges whose handles still exist after a model / op change. */
function pruneEdges(nodes: FlowNode[], edges: Edge[]): Edge[] {
@@ -171,6 +176,18 @@ const typeOfNode = (n: Pick<FlowNode, "id" | "type" | "data">): PortType | null
const KIND_INPUT: Record<string, CanvasNode["type"]> = { image: "image-input", video: "video-input", audio: "audio-input" };
+/** What a delete took from a board: the nodes, and the edges into or out of them. */
+const goneWith = (before: { nodes: FlowNode[]; edges: Edge[] }, ids: ReadonlySet<string>) => ({
+ nodes: before.nodes.filter((n) => ids.has(n.id)),
+ edges: before.edges.filter((e) => ids.has(e.source) || ids.has(e.target)),
+});
+
+/** What a group frames on the board: everything whose top-left corner sits inside it (it moves and copies with it). */
+function framed(g: FlowNode, nodes: FlowNode[]): FlowNode[] {
+ const box = { x: g.position.x, y: g.position.y, w: g.width ?? g.measured?.width ?? 0, h: g.height ?? g.measured?.height ?? 0 };
+ return nodes.filter((n) => n.id !== g.id && n.position.x >= box.x && n.position.y >= box.y && n.position.x <= box.x + box.w && n.position.y <= box.y + box.h);
+}
+
// ---------------------------------------------------------------------------
export function CanvasEditor({ id }: { id: string }) {
@@ -466,21 +483,60 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
touch();
}, [elements, touch]);
- /** Deleted nodes come back with their edges from the toast's Undo. */
+ /**
+ * Change one page's board, whether it's on screen or not: an Undo clicked after switching pages lands on the page
+ * it belongs to. False when that page is gone.
+ */
+ const editPage = useCallback(
+ (pid: string, f: (nodes: FlowNode[], edges: Edge[]) => { nodes: FlowNode[]; edges: Edge[] }) => {
+ const now = latest.current;
+ if (now.pageId === pid) {
+ const r = f(now.nodes, now.edges);
+ setNodes(r.nodes);
+ setEdges(r.edges);
+ } else {
+ const page = now.pages.find((p) => p.id === pid);
+ if (!page) return false;
+ const r = f(toFlowNodes(page.graph), page.graph.edges.map(toFlowEdge));
+ setPages((ps) => ps.map((p) => (p.id === pid ? { ...p, graph: toGraph(r.nodes, r.edges, p.graph.viewport) } : p)));
+ }
+ touch();
+ return true;
+ },
+ [touch],
+ );
+
+ /** Put back what a delete took (nodes and their edges) on its page; whatever changed since stays as it is. */
+ const restore = useCallback(
+ (pid: string, gone: { nodes: FlowNode[]; edges: Edge[] }) =>
+ editPage(pid, (ns, es) => {
+ const have = new Set(ns.map((n) => n.id));
+ const back = gone.nodes.filter((n) => !have.has(n.id)).map((n) => ({ ...n, selected: false }));
+ const nodes = [...back.filter(isBoardNode), ...ns, ...back.filter((n) => !isBoardNode(n))];
+ const ids = new Set(nodes.map((n) => n.id));
+ const edges = [...es];
+ for (const e of gone.edges) {
+ if (edges.some((x) => x.id === e.id) || !ids.has(e.source) || !ids.has(e.target)) continue;
+ // A single input wired to something else since keeps that connection.
+ const taken = edges.some((x) => x.target === e.target && x.targetHandle === e.targetHandle);
+ if (taken && singleInput(toGraph(nodes, edges), e.target, e.targetHandle)) continue;
+ edges.push({ ...e, selected: false });
+ }
+ return { nodes, edges };
+ }),
+ [editPage],
+ );
+
+ /** Deleted nodes come back with their edges from the toast's Undo (on the page they were deleted from). */
const offerUndo = useCallback(
- (count: number, before: { nodes: FlowNode[]; edges: Edge[] }, what = "node") =>
+ (count: number, gone: { nodes: FlowNode[]; edges: Edge[] }, what = "node") => {
+ const pid = latest.current.pageId;
toast(count === 1 ? `${what[0].toUpperCase()}${what.slice(1)} deleted` : `${count} ${what}s deleted`, {
duration: 5000,
- action: {
- label: "Undo",
- onClick: () => {
- setNodes(before.nodes);
- setEdges(before.edges);
- touch();
- },
- },
- }),
- [touch],
+ action: { label: "Undo", onClick: () => void restore(pid, gone) },
+ });
+ },
+ [restore],
);
const remove = useCallback(
@@ -490,27 +546,29 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
setNodes((ns) => ns.filter((n) => n.id !== nodeId));
setEdges((es) => es.filter((e) => e.source !== nodeId && e.target !== nodeId));
touch();
- // Ungrouping keeps the nodes: no undo needed for a frame. An empty comment closing goes quietly.
- if (type === "group") return void toast("Ungrouped — the nodes stay where they are", { duration: 2500, action: { label: "Undo", onClick: () => (setNodes(before.nodes), touch()) } });
+ const gone = goneWith(before, new Set([nodeId]));
+ // Ungrouping keeps the nodes: the frame alone comes back. An empty comment closing goes quietly.
+ if (type === "group") {
+ const pid = before.pageId;
+ return void toast("Ungrouped — the nodes stay where they are", { duration: 2500, action: { label: "Undo", onClick: () => void restore(pid, gone) } });
+ }
const n = before.nodes.find((x) => x.id === nodeId);
if (type === "comment" && !String(n?.data.text ?? "").trim()) return;
- offerUndo(1, before, type === "comment" ? "comment" : type === "shape" ? "drawing" : "node");
+ offerUndo(1, gone, type === "comment" ? "comment" : type === "shape" ? "drawing" : "node");
},
- [touch, offerUndo],
+ [touch, offerUndo, restore],
);
- /** Copies of the nodes, wired to each other the way the originals are. */
+ /** Copies of the nodes (a group with what's inside it), wired to each other the way the originals are. */
const duplicate = useCallback(
(ids: string | string[]) => {
+ const now = latest.current.nodes;
const list = new Set(Array.isArray(ids) ? ids : [ids]);
- const map = new Map<string, string>();
- const copies = latest.current.nodes
- .filter((n) => list.has(n.id))
- .map((n) => {
- const nid = newId(n.type ?? "node");
- map.set(n.id, nid);
- return { ...n, id: nid, position: { x: n.position.x + 48, y: n.position.y + 48 }, data: { ...n.data, pinned: undefined }, selected: true };
- });
+ for (const g of now) if (list.has(g.id) && g.type === "group") for (const m of framed(g, now)) list.add(m.id);
+ const picked = now.filter((n) => list.has(n.id));
+ const map = new Map(picked.map((n) => [n.id, newId(n.type ?? "node")]));
+ // A Video concatenator copied with its clips keeps each clip's cut, sound and place in the order.
+ const copies = picked.map((n) => ({ ...n, id: map.get(n.id)!, position: { x: n.position.x + 48, y: n.position.y + 48 }, data: { ...remapNodeData(n.data, map), pinned: undefined }, selected: true }));
if (!copies.length) return;
const wires = latest.current.edges
.filter((e) => map.has(e.source) && map.has(e.target))
@@ -556,8 +614,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const moving = new Set(dragged.map((n) => n.id));
for (const g of dragged) {
if (g.type !== "group") continue;
- const box = { x: g.position.x, y: g.position.y, w: g.width ?? g.measured?.width ?? 0, h: g.height ?? g.measured?.height ?? 0 };
- const members = latest.current.nodes.filter((n) => !moving.has(n.id) && n.position.x >= box.x && n.position.y >= box.y && n.position.x <= box.x + box.w && n.position.y <= box.y + box.h);
+ const members = framed(g, latest.current.nodes).filter((n) => !moving.has(n.id));
groupDrag.current.set(g.id, { origin: { ...g.position }, members: new Map(members.map((m) => [m.id, { ...m.position }])) });
}
}, []);
@@ -579,7 +636,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
if (changes.some((c) => c.type === "remove" || c.type === "add" || c.type === "replace" || (c.type === "position" && !c.dragging) || (c.type === "dimensions" && c.resizing === false))) touch();
if (removed.length) {
const kinds = new Set(removed.map((c) => before.nodes.find((n) => n.id === c.id)?.type));
- offerUndo(removed.length, before, kinds.size === 1 && kinds.has("comment") ? "comment" : kinds.size === 1 && kinds.has("shape") ? "drawing" : kinds.size === 1 && kinds.has("group") ? "group" : "node");
+ const gone = goneWith(before, new Set(removed.map((c) => c.id)));
+ offerUndo(removed.length, gone, kinds.size === 1 && kinds.has("comment") ? "comment" : kinds.size === 1 && kinds.has("shape") ? "drawing" : kinds.size === 1 && kinds.has("group") ? "group" : "node");
}
},
[touch, offerUndo],
@@ -658,15 +716,19 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const go = (t?: string[], f?: boolean) => {
const at = latest.current.rev;
runMutate(
- { page: latest.current.pageId, targets: t, group, force: f, graph: toGraph(latest.current.nodes, latest.current.edges, viewport.current) },
+ // Every page goes with the run (saved first, like the autosave): a page renamed, added or deleted, or another
+ // page's edit still in the autosave's debounce, is saved by it too.
+ { page: latest.current.pageId, targets: t, group, force: f, pages: docOf() },
{
onSuccess: (r) => {
- // The run saved the board too.
+ // The run saved the whole canvas as it was at `at`.
savedRev.current = Math.max(savedRev.current, at);
if (latest.current.rev === savedRev.current) setSaveState("saved");
setRunErrors(Object.fromEntries((r.errors ?? []).map((e) => [e.nodeId, e.message])));
if (!r.ok) return void toast.error(r.error ?? "Couldn't run this");
- const issues = r.errors?.length ? `${r.errors.length} node${r.errors.length > 1 ? "s" : ""} need${r.errors.length > 1 ? "" : "s"} attention` : undefined;
+ // A Translate (video) dubbing in Translate & dub isn't something to fix here.
+ const fix = (r.errors ?? []).filter((e) => e.message !== OPEN_DUB_HINT).length;
+ const issues = fix ? `${fix} node${fix > 1 ? "s" : ""} need${fix > 1 ? "" : "s"} attention` : undefined;
if (!r.ran.length) toast("Everything's up to date", { description: issues, action: { label: "Run again", onClick: () => go(t, true) } });
else toast.success(r.ran.length === 1 ? "Running 1 node" : `Running ${r.ran.length} nodes`, { description: issues, duration: 1800 });
},
@@ -676,7 +738,29 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
};
go(targets, force);
},
- [runMutate],
+ [runMutate, docOf],
+ );
+
+ /**
+ * ⌘↵ and Run selected: the selected nodes, and what's inside selected groups (a group alone runs as Run group).
+ * Drawings, comments and notes aren't run: with nothing runnable selected, everything runs.
+ */
+ const runSelection = useCallback(
+ (force?: boolean) => {
+ const sel = latest.current.nodes.filter((n) => n.selected);
+ const groups = sel.filter((n) => n.type === "group");
+ const picked = sel.filter((n) => !isBoardNode(n));
+ if (groups.length === 1 && !picked.length) return run(undefined, force, groups[0].id);
+ const g = toGraph(latest.current.nodes, latest.current.edges);
+ const targets = new Set(picked.map((n) => n.id));
+ for (const fr of groups) {
+ const box = g.groups?.find((x) => x.id === fr.id);
+ if (box) for (const m of groupMembers(g, box)) targets.add(m.id);
+ }
+ if (!targets.size && groups.length) return void toast("Nothing to run in these groups yet — put nodes inside them");
+ run(targets.size ? [...targets] : undefined, force);
+ },
+ [run],
);
const cancel = useCallback(
@@ -691,17 +775,24 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
[runs, gens, qc, id],
);
- const toInput = (nodeId: string) => {
+ /** An input node holding `file`, below the node it came from; `takeOver` moves that node's outgoing connections onto it. */
+ const addInput = (nodeId: string, file: { url: string; kind: string; label?: string }, takeOver = false) => {
const src = latest.current.nodes.find((n) => n.id === nodeId);
- const out = results.get(nodeId)?.outputs.find((x) => KIND_INPUT[x.o.kind]);
- if (!src || !out) return;
+ const type = KIND_INPUT[file.kind];
+ if (!src || !type) return;
const nid = newId("input");
setNodes((ns) => [
...ns.map((n) => ({ ...n, selected: false })),
- { id: nid, type: KIND_INPUT[out.o.kind], position: snap({ x: src.position.x, y: src.position.y + (src.measured?.height ?? 360) + 48 }), data: { url: out.o.url, label: `From ${nodeLabel(toGraph([src], []).nodes[0])}` }, selected: true },
+ { id: nid, type, position: snap({ x: src.position.x, y: src.position.y + (src.measured?.height ?? 360) + 48 }), data: { url: file.url, label: file.label ?? `From ${nodeLabel(toGraph([src], []).nodes[0])}` }, selected: true },
]);
+ const moved = takeOver ? latest.current.edges.filter((e) => e.source === nodeId).length : 0;
+ if (moved) setEdges((es) => es.map((e) => (e.source === nodeId ? { ...e, id: newId("e"), source: nid, sourceHandle: OUT } : e)));
touch();
- toast("Added as an input — connect it anywhere");
+ toast(moved ? `Added as an input, connected where “${nodeLabel(toGraph([src], []).nodes[0])}” was` : "Added as an input — connect it anywhere");
+ };
+ const toInput = (nodeId: string) => {
+ const out = results.get(nodeId)?.outputs.find((x) => KIND_INPUT[x.o.kind]);
+ if (out) addInput(nodeId, { url: out.o.url, kind: out.o.kind });
};
/** One clip of a Video concatenator: merged into what the node holds now (several clips report their lengths at once). */
@@ -735,11 +826,12 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const ungroupSelection = useCallback(() => {
const ids = latest.current.nodes.filter((n) => n.selected && n.type === "group").map((n) => n.id);
if (!ids.length) return;
- const before = latest.current.nodes;
+ const gone = goneWith(latest.current, new Set(ids));
+ const pid = latest.current.pageId;
setNodes((ns) => ns.filter((n) => !ids.includes(n.id)));
touch();
- toast(ids.length === 1 ? "Ungrouped" : `${ids.length} groups ungrouped`, { duration: 2500, action: { label: "Undo", onClick: () => (setNodes(before), touch()) } });
- }, [touch]);
+ toast(ids.length === 1 ? "Ungrouped" : `${ids.length} groups ungrouped`, { duration: 2500, action: { label: "Undo", onClick: () => void restore(pid, gone) } });
+ }, [touch, restore]);
// ---- pages
/** Show another page: the board's page is put back into `pages` first, so nothing on it is lost. */
@@ -789,16 +881,24 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
if (doc.length < 2) return;
const was = latest.current.pageId;
const at = doc.findIndex((p) => p.id === pid);
+ const page = doc[at];
const next = doc.filter((p) => p.id !== pid);
- showPage(next, pid === was ? next[Math.max(0, at - 1)].id : was);
+ if (pid === was) showPage(next, next[Math.max(0, at - 1)].id);
+ else setPages(next);
touch();
- toast(`Deleted “${doc[at].name}”`, {
+ toast(`Deleted “${page.name}”`, {
description: "Its results stay in your library",
duration: 6000,
action: {
label: "Undo",
+ // The page comes back where it was; edits made meanwhile on the other pages stay.
onClick: () => {
- showPage(doc, was);
+ const now = docOf();
+ if (now.some((p) => p.id === pid)) return;
+ if (now.length >= BOARD_LIMITS.pages) return void toast(`A canvas holds up to ${BOARD_LIMITS.pages} pages — delete one to bring “${page.name}” back`);
+ const back = [...now.slice(0, at), page, ...now.slice(at)];
+ if (pid === was) showPage(back, pid);
+ else setPages(back);
touch();
},
},
@@ -829,13 +929,13 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const start = flowAt(e.clientX, e.clientY);
const screen = [{ x: e.clientX - rect.left, y: e.clientY - rect.top }];
const points = [start];
- const before = latest.current;
- let erased = 0;
+ const erased: FlowNode[] = [];
const erase = (p: { x: number; y: number }) => {
const tol = 8 / rf.getZoom();
- const hit = new Set(latest.current.nodes.filter((n) => n.type === "shape").filter((n) => { const sh = asShape(n); return sh && shapeHit(sh, p, tol); }).map((n) => n.id));
+ const hits = latest.current.nodes.filter((n) => n.type === "shape").filter((n) => { const sh = asShape(n); return sh && shapeHit(sh, p, tol); });
+ const hit = new Set(hits.map((n) => n.id));
if (!hit.size) return;
- erased += hit.size;
+ erased.push(...hits);
latest.current = { ...latest.current, nodes: latest.current.nodes.filter((n) => !hit.has(n.id)) };
setNodes((ns) => ns.filter((n) => !hit.has(n.id)));
};
@@ -854,9 +954,9 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const end = flowAt(ev.clientX, ev.clientY);
const dragged = Math.hypot(ev.clientX - rect.left - screen[0].x, ev.clientY - rect.top - screen[0].y) > 6;
if (tool === "erase") {
- if (erased) {
+ if (erased.length) {
touch();
- offerUndo(erased, before, "drawing");
+ offerUndo(erased.length, { nodes: erased, edges: [] }, "drawing");
}
return;
}
@@ -865,25 +965,37 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
if (s) placeShape(s);
return;
}
- if (tool === "shape") {
- const b = dragged ? end : { x: start.x + 160, y: start.y + (shapeKind === "arrow" ? 0 : 100) };
- placeShape(dragShape(newId("shape"), shapeKind, start, b, ink));
- } else if (tool === "text") {
- placeShape({ id: newId("shape"), kind: "text", x: Math.round(start.x), y: Math.round(start.y - 16), width: 260, height: 40, color: ink, text: "" }, true);
- } else if (tool === "note" || tool === "table") {
- addNode(palette.find((p) => p.id === tool)!, start);
- } else if (tool === "comment") {
- const c = commentNode(start);
- focusOnMount.add(c.id);
- setNodes((ns) => [...ns.map((n) => (n.selected ? { ...n, selected: false } : n)), c]);
- touch();
- }
- // Placing is one-off: back to Select (drawing and erasing stay on until switched off).
- setTool("select");
+ place(tool, start, dragged ? end : undefined);
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
};
+ /** A placing tool's one thing at `at` (a shape spans to `to` when dragged); then back to Select. */
+ const place = (t: Tool, at: { x: number; y: number }, to?: { x: number; y: number }) => {
+ if (t === "shape") {
+ const b = to ?? { x: at.x + 160, y: at.y + (shapeKind === "arrow" ? 0 : 100) };
+ placeShape(dragShape(newId("shape"), shapeKind, at, b, ink));
+ } else if (t === "text") {
+ placeShape({ id: newId("shape"), kind: "text", x: Math.round(at.x), y: Math.round(at.y - 16), width: 260, height: 40, color: ink, text: "" }, true);
+ } else if (t === "note" || t === "table") {
+ addNode(palette.find((p) => p.id === t)!, at);
+ } else if (t === "comment") {
+ const c = commentNode(at);
+ focusOnMount.add(c.id);
+ setNodes((ns) => [...ns.map((n) => (n.selected ? { ...n, selected: false } : n)), c]);
+ touch();
+ }
+ // Placing is one-off: back to Select (drawing and erasing stay on until switched off).
+ setTool("select");
+ };
+ /** Enter with a placing tool: in the middle of the view (a shape or note centred there). */
+ const placeAtCentre = (t: Tool) => {
+ const rect = wrapper.current?.getBoundingClientRect();
+ if (!rect) return;
+ const mid = rf.screenToFlowPosition({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 });
+ const half = t === "shape" ? { x: 80, y: shapeKind === "arrow" ? 0 : 50 } : t === "note" || t === "table" ? { x: 140, y: 80 } : t === "text" ? { x: 130, y: 0 } : { x: 0, y: 0 };
+ place(t, { x: mid.x - half.x, y: mid.y - half.y });
+ };
// ---- engine
const boardEngine = graphEngine(graph) ?? engine;
@@ -894,18 +1006,24 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
if (changed) {
const byNode = new Map(next.nodes.map((n) => [n.id, n]));
const after = before.nodes.map((n) => ({ ...n, data: byNode.get(n.id)?.data ?? n.data }));
+ const kept = pruneEdges(after, before.edges);
setNodes(after);
- setEdges((es) => pruneEdges(after, es));
+ setEdges(kept);
touch();
+ const pid = before.pageId;
+ const was = new Map(before.nodes.filter((n) => byNode.get(n.id) && byNode.get(n.id)!.data !== n.data).map((n) => [n.id, n.data]));
+ const dropped = before.edges.filter((x) => !kept.includes(x));
toast.success(`Switched ${changed} node${changed > 1 ? "s" : ""} to ${e === "open" ? "open-source" : "cloud"} models`, {
action: {
label: "Undo",
- onClick: () => {
- // The switch may have dropped edges into inputs the new models don't have: they come back too.
- setNodes(before.nodes);
- setEdges(before.edges);
- touch();
- },
+ // The nodes get their models back on their page, and the edges the switch dropped (inputs the new models
+ // don't have) come back too.
+ onClick: () =>
+ void editPage(pid, (ns, es) => {
+ const nodes = ns.map((n) => (was.has(n.id) ? { ...n, data: was.get(n.id)! } : n));
+ const ids = new Set(nodes.map((n) => n.id));
+ return { nodes, edges: [...es, ...dropped.filter((x) => ids.has(x.source) && ids.has(x.target) && !es.some((y) => y.id === x.id))] };
+ }),
},
});
}
@@ -935,6 +1053,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
cancel: (nid) => void cancel(nid),
open: (nid, index = 0) => setViewer({ nodeId: nid, index }),
toInput,
+ addInput,
connect: (c) => onConnect({ source: c.source, target: c.target, sourceHandle: c.sourceHandle ?? OUT, targetHandle: c.targetHandle ?? null }),
disconnect,
getGraph: () => toGraph(latest.current.nodes, latest.current.edges),
@@ -951,6 +1070,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
cancel: (...a) => handlers.current!.cancel(...a),
open: (...a) => handlers.current!.open(...a),
toInput: (...a) => handlers.current!.toInput(...a),
+ addInput: (...a) => handlers.current!.addInput(...a),
connect: (...a) => handlers.current!.connect(...a),
disconnect: (...a) => handlers.current!.disconnect(...a),
getGraph: () => handlers.current!.getGraph(),
@@ -958,6 +1078,12 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
[],
);
+ // What the keys call, as they are now (the listener below is added once).
+ const keyHandlers = useRef({ runSelection, placeAtCentre });
+ useLayoutEffect(() => {
+ keyHandlers.current = { runSelection, placeAtCentre };
+ });
+
// ---- keyboard: ⌘↵ runs (the selection, else everything), ⌘D duplicates, ⌘G groups (⇧⌘G ungroups),
// and the board tools by letter: V H D E N ⇧T R T C (Escape goes back to Select)
useEffect(() => {
@@ -966,6 +1092,15 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
if (!mod) {
if (e.altKey || isMobile || typing(e.target)) return;
if (e.key === "Escape") return void setTool("select");
+ // Enter with a tool that places something (a comment, a note, text…) places it in the middle of the view:
+ // the keyboard's way to do what a click on the board does. On another button or a link Enter keeps its
+ // meaning; on the chosen tool's own toolbar button, pressed again, it places.
+ const el = e.target as HTMLElement | null;
+ const ownTool = !!el?.closest?.("[role='toolbar'] button[aria-pressed='true']");
+ if (e.key === "Enter" && PLACE_TOOLS.has(toolNow.current) && (ownTool || !el?.closest?.("button, a, [role='tab']"))) {
+ e.preventDefault();
+ return void keyHandlers.current.placeAtCentre(toolNow.current);
+ }
// ⇧T is the table (T alone writes text).
const t = e.shiftKey && e.key.toLowerCase() === "t" ? "table" : TOOL_KEYS[e.key.toLowerCase()];
if (!t || e.repeat) return;
@@ -983,8 +1118,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
}
if (e.key === "Enter") {
e.preventDefault();
- const sel = latest.current.nodes.filter((n) => n.selected).map((n) => n.id);
- actions.run(sel.length ? sel : undefined, e.shiftKey);
+ keyHandlers.current.runSelection(e.shiftKey);
} else if (e.key.toLowerCase() === "d" && !(e.target as HTMLElement)?.closest("input,textarea,[contenteditable]")) {
const sel = latest.current.nodes.filter((n) => n.selected).map((n) => n.id);
if (!sel.length) return;
@@ -994,7 +1128,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [actions, duplicate, isMobile, groupSelection, ungroupSelection]);
+ }, [duplicate, isMobile, groupSelection, ungroupSelection]);
// ---- drop from the palette, or files from the desktop
const onDragOver = (e: React.DragEvent) => {
@@ -1081,7 +1215,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
// A Fuobe Original's step names its engine: a demo is about that engine's providers.
return m && isDemo(s.request.engine ? onEngine(m, s.request.engine) : m);
});
- const attention = new Set(plan.errors.map((e) => e.nodeId)).size;
+ // A Translate (video) on an open-only install dubs in Translate & dub: nothing to fix on the board.
+ const attention = new Set(plan.errors.filter((e) => e.message !== OPEN_DUB_HINT).map((e) => e.nodeId)).size;
const summary = [
plan.steps.length
? `${plan.steps.length} to run · ${planDemo ? "Demo · free" : plan.costUnknown ? "price unknown" : plan.costUsd === 0 ? "Free" : `≈ ${formatCost(plan.costUsd)}`}`
@@ -1094,14 +1229,20 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
.join(" · ");
// ---- what the header and the palette call: stable, so they skip the re-render a keystroke causes
- const uiHandlers = useRef<{ run: typeof run; switchEngine: typeof switchEngine; rename: typeof rename; addAtCenter: typeof addAtCenter } | null>(null);
+ const uiHandlers = useRef<{
+ run: typeof run;
+ runSelection: typeof runSelection;
+ switchEngine: typeof switchEngine;
+ rename: typeof rename;
+ addAtCenter: typeof addAtCenter;
+ } | null>(null);
useLayoutEffect(() => {
- uiHandlers.current = { run, switchEngine, rename, addAtCenter };
+ uiHandlers.current = { run, runSelection, switchEngine, rename, addAtCenter };
});
const ui = useMemo<HeaderUi>(
() => ({
run: (targets, force) => uiHandlers.current!.run(targets, force),
- runSelected: (force) => uiHandlers.current!.run(latest.current.nodes.filter((n) => n.selected).map((n) => n.id), force),
+ runSelected: (force) => uiHandlers.current!.runSelection(force),
switchEngine: (e) => uiHandlers.current!.switchEngine(e),
rename: (v) => void uiHandlers.current!.rename(v),
addAtCenter: (p) => uiHandlers.current!.addAtCenter(p),
@@ -1188,6 +1329,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
<div
ref={wrapper}
className="relative min-h-0 flex-1"
+ // The page tabs' panel (desktop): the board of the open page.
+ {...(!isMobile && { id: PAGE_PANEL_ID, role: "tabpanel", "aria-labelledby": pageTabId(pageId) })}
data-tool={isMobile ? undefined : tool}
onPointerDownCapture={onToolPointerDown}
onDragOver={onDragOver}
@@ -1228,9 +1371,11 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
zoomOnDoubleClick={false}
deleteKeyCode={isMobile ? null : ["Backspace", "Delete"]}
multiSelectionKeyCode={["Meta", "Shift", "Control"]}
- // Select (V): a drag on the board draws a selection box, Space or the middle button pans. Pan (H): a
+ // Select (V): a drag on the board draws a selection box; scrolling, Space-drag or the middle button pans. Pan (H): a
// drag moves the board. The drawing tools take the pointer themselves (onToolPointerDown).
panOnDrag={isMobile || tool === "hand" ? true : tool === "select" ? PAN_MIDDLE : false}
+ // Scrolling (two fingers on a trackpad) pans; pinch or ⌘/Ctrl-scroll zooms.
+ panOnScroll={!isMobile}
selectionOnDrag={!isMobile && tool === "select"}
selectionMode={SelectionMode.Partial}
elementsSelectable={isMobile || tool !== "hand"}
diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsx
index 524364e8..b36d0ea9 100644
--- a/src/components/canvas/nodes.tsx
+++ b/src/components/canvas/nodes.tsx
@@ -68,8 +68,8 @@ import { ModelPicker } from "@/components/studio/model-picker";
import { ResponsivePanel } from "@/components/studio/responsive-panel";
import { VoiceRecorder } from "@/components/studio/voice-recorder";
import { toast } from "sonner";
-import { useQueryClient } from "@tanstack/react-query";
-import { useAssets, useElements } from "@/lib/api";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useAssets, useClipFacts as useFileFacts, useElements } from "@/lib/api";
import { dualEngine, onEngine } from "@/lib/catalog/engines";
import {
CANVAS_TEXT_MAX,
@@ -110,6 +110,7 @@ import {
} from "@/lib/catalog/canvas";
import { OPERATION_LABELS, type Engine, type MediaKind, type ModelDef, type OutputFile } from "@/lib/catalog/types";
import { formatCost } from "@/lib/format";
+import { dubResult, languageStage, type DubSessionView, type DubStage } from "@/lib/av/dub";
import { DUB_LANGUAGES, supportsTarget } from "@/lib/av/languages";
import { matchSpokenLanguage, spokenLanguageName, spokenLanguageOptions } from "@/lib/speech-languages";
import { keyCombo } from "@/lib/keys";
@@ -893,12 +894,43 @@ const selectVideoIn = (s: EditorSnapshot, id: string): string | undefined => {
return src.type === "video-input" ? src.data.url : s.views.get(src.id)?.results.outputs.find((x) => x.o.kind === "video")?.o.url;
};
+/** Whether an input node on the board already holds this file (the dub brought back once). */
+const selectHasFile = (s: EditorSnapshot, url: string) => !!url && s.graph.nodes.some((n) => n.data.url === url);
+
+const DUB_STAGE: Record<DubStage, string> = {
+ preparing: "Transcribing and translating…",
+ review: "Ready for you to check the translation",
+ voicing: "Speaking the translation…",
+ done: "Dubbed",
+ failed: "The dub failed — open it to retry",
+};
+
function OpenDub({ id, data }: { id: string; data: CanvasNodeData }) {
const actions = useEditorActions();
const video = useEditorSelector(selectVideoIn, id);
const lang = data.params?.targetLanguage && OPEN_DUB_LANGUAGES.some((l) => l.code === data.params?.targetLanguage) ? data.params.targetLanguage : undefined;
- const [started, setStarted] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
+ // The dub this node started, while it's still for this clip and language (its result comes back to the board from here).
+ const session = useQuery({
+ queryKey: ["dub", data.dubId],
+ enabled: !!data.dubId,
+ queryFn: async () => {
+ const res = await fetch(`/api/dub/${data.dubId}`);
+ if (!res.ok) throw Object.assign(new Error("gone"), { status: res.status });
+ return (await res.json()) as DubSessionView;
+ },
+ refetchInterval: (q) => {
+ const s = q.state.data;
+ const stage = s && lang ? languageStage(s, lang) : undefined;
+ // Waiting on a step: every 5 s. Waiting on the person (the review, in Translate & dub): now and then.
+ return stage === "preparing" || stage === "voicing" ? 5000 : stage === "review" ? 15_000 : false;
+ },
+ retry: false,
+ }).data;
+ const current = session && lang && session.video === video && session.targets.includes(lang) ? session : undefined;
+ const stage = current && lang ? languageStage(current, lang) : undefined;
+ const result = current && lang ? dubResult(current, lang)?.outputs.find((o) => o.kind === "video") : undefined;
+ const onBoard = useEditorSelector(selectHasFile, result?.url ?? "");
const start = async () => {
if (!video || !lang) return;
setBusy(true);
@@ -906,8 +938,8 @@ function OpenDub({ id, data }: { id: string; data: CanvasNodeData }) {
const res = await fetch("/api/dub", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ engine: "open", mode: "steps", video, targets: [lang], source: "auto", title: data.label || "Canvas dub" }) });
const body = (await res.json().catch(() => ({}))) as { id?: string; error?: string };
if (!res.ok || !body.id) throw new Error(body.error ?? "Couldn't start the dub");
- setStarted(body.id);
- toast.success("Dub started", { description: "Check the translation in Translate & dub, then have it spoken" });
+ actions.update(id, { dubId: body.id });
+ toast.success("Dub started", { description: "Check the translation in Translate & dub, then have it spoken. The dubbed video comes back here." });
} catch (e) {
toast.error((e as Error).message);
} finally {
@@ -915,17 +947,27 @@ function OpenDub({ id, data }: { id: string; data: CanvasNodeData }) {
}
};
return (
- <div className={cn("flex flex-wrap items-center gap-1.5", NO_DRAG)}>
- <OptionSelect label="Dub into" value={lang} options={OPEN_DUB_LANGUAGES.map((l) => l.code)} onChange={(v) => actions.update(id, { params: { ...data.params, targetLanguage: v } })} format={(v) => OPEN_DUB_LANGUAGES.find((l) => l.code === v)?.name ?? v} />
- {started ? (
- <Link href={`/audio/translate?dub=${started}`} className={chip}>
- Review the dub
- </Link>
- ) : (
- <button className={chip} onClick={() => void start()} disabled={!video || !lang || busy} title={!video ? "Connect a video (an upload, or a finished clip)" : !lang ? "Pick the language to dub into" : "Free on your GPU"}>
- {busy ? <Loader2 className="size-3 animate-spin" /> : <Play className="size-3" />} Start in Translate &amp; dub
- </button>
- )}
+ <div className={cn("space-y-1.5", NO_DRAG)}>
+ <div className="flex flex-wrap items-center gap-1.5">
+ <OptionSelect label="Dub into" value={lang} options={OPEN_DUB_LANGUAGES.map((l) => l.code)} onChange={(v) => actions.update(id, { params: { ...data.params, targetLanguage: v } })} format={(v) => OPEN_DUB_LANGUAGES.find((l) => l.code === v)?.name ?? v} />
+ {current ? (
+ <Link href={`/audio/translate?dub=${current.id}`} className={chip}>
+ {stage === "review" ? "Check the translation" : "Open the dub"}
+ </Link>
+ ) : (
+ <button className={chip} onClick={() => void start()} disabled={!video || !lang || busy} title={!video ? "Connect a video (an upload, or a finished clip)" : !lang ? "Pick the language to dub into" : "Free on your GPU"}>
+ {busy ? <Loader2 className="size-3 animate-spin" /> : <Play className="size-3" />} Start in Translate &amp; dub
+ </button>
+ )}
+ {result && !onBoard && (
+ <button className={chip} onClick={() => actions.addInput(id, { url: result.url, kind: "video", label: `${data.label || "Translate"} · dubbed` }, true)} title="A Video input with the dubbed clip, connected where this node was">
+ <Plus className="size-3" /> Use the dubbed video
+ </button>
+ )}
+ </div>
+ <p className="text-[12px] leading-snug text-muted-foreground" aria-live="polite">
+ {stage === "done" && onBoard ? "Dubbed — it's on the board as a Video input" : stage ? DUB_STAGE[stage] : "When it's dubbed, bring it back here as a Video input."}
+ </p>
</div>
);
}
@@ -1021,6 +1063,16 @@ function ClipItem({ id, row, index, count, settings, readOnly, onMove }: { id: s
useClipFacts(row.url, (f) => {
if (f.length !== settings.length || f.width !== settings.width || f.height !== settings.height) set(f);
});
+ // Whether it has sound, from its header on the server (a browser can't tell): a silent clip gets a silent track on
+ // the cloud. Its length too, when this browser couldn't read the file.
+ const header = useFileFacts(row.url).data;
+ useEffect(() => {
+ if (!header) return;
+ const patch: Partial<ClipSettings> = {};
+ if (typeof header.hasAudio === "boolean" && header.hasAudio !== settings.audio) patch.audio = header.hasAudio;
+ if (settings.length === undefined && header.duration) patch.length = Math.round(header.duration * 1000) / 1000;
+ if (Object.keys(patch).length) actions.patchClip(id, row.nodeId, patch);
+ }, [header, settings.audio, settings.length, actions, id, row.nodeId]);
const muted = !!settings.mute;
return (
<li className="rounded-lg bg-muted/60 p-2">
diff --git a/src/components/canvas/toolbar.tsx b/src/components/canvas/toolbar.tsx
index f6fe9fb7..ea8fc545 100644
--- a/src/components/canvas/toolbar.tsx
+++ b/src/components/canvas/toolbar.tsx
@@ -18,15 +18,15 @@ export type DragShape = "rect" | "ellipse" | "arrow";
export const TOOL_KEYS: Record<string, Tool> = { v: "select", h: "hand", d: "draw", e: "erase", n: "note", r: "shape", t: "text", c: "comment" };
const TOOLS: { tool: Tool; label: string; key: string; icon: LucideIcon; hint: string }[] = [
- { tool: "select", label: "Select", key: "V", icon: MousePointer2, hint: "Drag to select · hold Space to pan" },
+ { tool: "select", label: "Select", key: "V", icon: MousePointer2, hint: "Drag to select · scroll or hold Space to pan · pinch or ⌘-scroll to zoom" },
{ tool: "hand", label: "Pan", key: "H", icon: Hand, hint: "Drag to move around the board" },
{ tool: "draw", label: "Draw", key: "D", icon: Pencil, hint: "Draw freehand on the board" },
{ tool: "erase", label: "Eraser", key: "E", icon: Eraser, hint: "Drag over drawings and shapes to erase them" },
- { tool: "note", label: "Sticky note", key: "N", icon: StickyNote, hint: "Click to place a note" },
+ { tool: "note", label: "Sticky note", key: "N", icon: StickyNote, hint: "Click to place a note (Enter: in the middle)" },
{ tool: "table", label: "Table", key: "⇧T", icon: Table, hint: "Click to place a table: what it feeds runs once per row" },
- { tool: "shape", label: "Shapes", key: "R", icon: Square, hint: "Drag to draw a shape" },
- { tool: "text", label: "Text", key: "T", icon: Type, hint: "Click to write on the board" },
- { tool: "comment", label: "Comment", key: "C", icon: MessageCircle, hint: "Click to pin a comment" },
+ { tool: "shape", label: "Shapes", key: "R", icon: Square, hint: "Drag to draw a shape (Enter: in the middle)" },
+ { tool: "text", label: "Text", key: "T", icon: Type, hint: "Click to write on the board (Enter: in the middle)" },
+ { tool: "comment", label: "Comment", key: "C", icon: MessageCircle, hint: "Click to pin a comment (Enter: in the middle)" },
];
const SHAPE_ICON: Record<DragShape, LucideIcon> = { rect: Square, ellipse: Circle, arrow: ArrowUpRight };
@@ -150,13 +150,29 @@ export interface PageOps {
remove: (id: string) => void;
}
-/** The canvas's pages as tabs: each its own board. Double-click a tab to rename it. */
+/** The id of a page's tab (the board is the tabpanel it labels). */
+export const pageTabId = (id: string) => `canvas-page-tab-${id}`;
+export const PAGE_PANEL_ID = "canvas-page-panel";
+
+/**
+ * The canvas's pages as tabs: each its own board. Double-click a tab to rename it. One tab is in the Tab order
+ * (the open page); the arrow keys, Home and End move between tabs and open them.
+ */
export const PageTabs = memo(function PageTabs({ pages, active, ops, readOnly }: { pages: { id: string; name: string }[]; active: string; ops: PageOps; readOnly: boolean }) {
const [editing, setEditing] = useState<string | null>(null);
const full = pages.length >= BOARD_LIMITS.pages;
+ const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
+ const at = pages.findIndex((p) => p.id === active);
+ const to = e.key === "ArrowRight" ? at + 1 : e.key === "ArrowLeft" ? at - 1 : e.key === "Home" ? 0 : e.key === "End" ? pages.length - 1 : null;
+ if (to === null || at < 0 || !(e.target as HTMLElement).matches("[role='tab']")) return;
+ e.preventDefault();
+ const next = pages[(to + pages.length) % pages.length];
+ ops.switchTo(next.id);
+ requestAnimationFrame(() => document.getElementById(pageTabId(next.id))?.focus());
+ };
return (
<div className="flex max-w-full items-center gap-0.5 rounded-full border bg-popover p-1 shadow-normal" data-board-ui>
- <div className="flex min-w-0 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]" role="tablist" aria-label="Pages">
+ <div className="flex min-w-0 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]" role="tablist" aria-label="Pages" onKeyDown={onKeyDown}>
{pages.map((p) =>
editing === p.id ? (
<input
@@ -181,8 +197,11 @@ export const PageTabs = memo(function PageTabs({ pages, active, ops, readOnly }:
) : (
<button
key={p.id}
+ id={pageTabId(p.id)}
role="tab"
aria-selected={p.id === active}
+ aria-controls={PAGE_PANEL_ID}
+ tabIndex={p.id === active ? 0 : -1}
onClick={() => ops.switchTo(p.id)}
onDoubleClick={() => !readOnly && setEditing(p.id)}
title={readOnly ? p.name : `${p.name} · double-click to rename`}
diff --git a/src/components/canvas/use-canvas.ts b/src/components/canvas/use-canvas.ts
index ff2cbc63..1bbbf942 100644
--- a/src/components/canvas/use-canvas.ts
+++ b/src/components/canvas/use-canvas.ts
@@ -93,7 +93,7 @@ export interface RunResponse {
export function useRunCanvas(id: string) {
const qc = useQueryClient();
return useMutation({
- mutationFn: async (body: { page: string; targets?: string[]; group?: string; force?: boolean; graph: CanvasGraph }) => {
+ mutationFn: async (body: { page: string; targets?: string[]; group?: string; force?: boolean; pages: CanvasPage[] }) => {
const res = await send(`/api/canvases/${id}/run`, "POST", body);
const data = (await res.json().catch(() => ({}))) as Partial<RunResponse> & { error?: string };
if (!res.ok && !data.errors) throw new Error(data.error ?? `Request failed (${res.status})`);
diff --git a/src/lib/catalog/canvas-board.ts b/src/lib/catalog/canvas-board.ts
index 8708134b..ebfe9da7 100644
--- a/src/lib/catalog/canvas-board.ts
+++ b/src/lib/catalog/canvas-board.ts
@@ -9,7 +9,7 @@
* 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";
+import type { CanvasGraph, CanvasNode, CanvasNodeData } from "./canvas";
// ---------------------------------------------------------------------------
// Annotations
@@ -94,7 +94,9 @@ export function penShape(id: string, raw: { x: number; y: number }[], color: Boa
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);
+ // Every n-th point plus the last one: n leaves room for that last point within the limit.
+ const max = BOARD_LIMITS.penPoints;
+ const every = pts.length > max ? Math.ceil(pts.length / (max - 1)) : 1;
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);
@@ -281,6 +283,20 @@ export function nextPageName(pages: readonly CanvasPage[]): string {
for (let i = pages.length; ; i++) if (!names.has(pageName(i).toLowerCase())) return pageName(i);
}
+/**
+ * A node's data with the node ids it refers to renamed by `map` (a Video concatenator keys each clip's cut and
+ * sound, and the clips' order, by the clip's node id). Ids not in the map stay as they are.
+ */
+export function remapNodeData(data: CanvasNodeData, map: ReadonlyMap<string, string>): CanvasNodeData {
+ if (!data.clips && !data.order) return data;
+ const to = (id: string) => map.get(id) ?? id;
+ return {
+ ...data,
+ ...(data.clips && { clips: Object.fromEntries(Object.entries(data.clips).map(([k, v]) => [to(k), v])) }),
+ ...(data.order && { order: data.order.map(to) }),
+ };
+}
+
/**
* 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.
@@ -293,7 +309,7 @@ export function copyPage(page: CanvasPage, id: string, name: string, newId: (pre
name,
graph: {
...g,
- nodes: g.nodes.map((n) => ({ ...n, id: map.get(n.id)!, data: { ...n.data, pinned: undefined } })),
+ nodes: g.nodes.map((n) => ({ ...n, id: map.get(n.id)!, data: { ...remapNodeData(n.data, map), 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") })) }),
diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.ts
index 019ca5fd..564deb27 100644
--- a/src/lib/catalog/canvas.ts
+++ b/src/lib/catalog/canvas.ts
@@ -65,7 +65,7 @@ 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). */
+ /** The clip's own length, size and whether it has sound (read from its file; undefined = not known yet). */
length?: number;
width?: number;
height?: number;
@@ -104,6 +104,8 @@ export interface CanvasNodeData {
/** Table: its column names, and its rows of cells (one per column). */
columns?: string[];
rows?: string[][];
+ /** Translate (video) on the open engine: the Translate & dub session it started (its result comes back from there). */
+ dubId?: string;
}
export interface CanvasNode {
@@ -143,6 +145,8 @@ export interface NodeRun {
out?: string;
/** A node run once per row of a table: each row's generation, in row order (what a row of the next node takes). */
rows?: string[];
+ /** Each row's own signature (rowSignature): a row whose inputs didn't change and whose result is live is kept. */
+ rowSigs?: string[];
}
/** The generation a node's result (and what it passes on) is in. */
@@ -1014,26 +1018,60 @@ export function tableRows(t: Pick<CanvasNode, "data">): string[][] {
const rowText = (cells: string[]) => cells.filter(Boolean).join(", ");
+/** The table a node runs per row of (with its filled rows), why it can't, or null when no table is upstream. */
+export type RowsFeed = { table: CanvasNode; rows: string[][] } | { error: string } | null;
+
/**
- * The table a node runs per row of: one wired into it, or one feeding a node it builds on (a Video concatenator
- * collects the rows instead, so nothing after it runs per row). Null when no table is upstream.
+ * The table every node of a graph runs per row of, worked out once per node however many nodes ask (the
+ * editor asks for each generator on every keystroke). See rowsFeeding.
*/
-export function rowsFeeding(graph: CanvasGraph, n: CanvasNode, seen = new Set<string>()): { table: CanvasNode; rows: string[][] } | { error: string } | null {
- if (n.type === "table") return { table: n, rows: tableRows(n) };
- if (!isGenerator(n) || n.type === "concat" || seen.has(n.id)) return null;
- seen.add(n.id);
+export function tablesFeeding(graph: CanvasGraph): (n: Pick<CanvasNode, "id" | "type" | "data">) => RowsFeed {
const nodes = nodeMap(graph);
- let found: { table: CanvasNode; rows: string[][] } | null = null;
- for (const e of incoming(graph, n.id)) {
- const s = nodes.get(e.source);
- if (!s || (s.type !== "table" && !isGenerator(s))) continue;
- const r = rowsFeeding(graph, s, seen);
- if (!r) continue;
- if ("error" in r) return r;
- if (found && found.table.id !== r.table.id) return { error: `“${nodeLabel(found.table)}” and “${nodeLabel(r.table)}” both reach “${nodeLabel(n)}” — rows run from one table at a time` };
- found = r;
+ const into = new Map<string, string[]>();
+ for (const e of graph.edges) {
+ const list = into.get(e.target);
+ if (list) list.push(e.source);
+ else into.set(e.target, [e.source]);
}
- return found;
+ const memo = new Map<string, RowsFeed>();
+ const visiting = new Set<string>();
+ const feed = (n: Pick<CanvasNode, "id" | "type" | "data">): RowsFeed => {
+ if (n.type === "table") return { table: n as CanvasNode, rows: tableRows(n) };
+ if (!isGenerator(n) || n.type === "concat" || visiting.has(n.id)) return null;
+ const known = memo.get(n.id);
+ if (known !== undefined) return known;
+ visiting.add(n.id);
+ let found: { table: CanvasNode; rows: string[][] } | null = null;
+ let out: RowsFeed | undefined;
+ for (const sid of into.get(n.id) ?? []) {
+ const s = nodes.get(sid);
+ if (!s || (s.type !== "table" && !isGenerator(s))) continue;
+ const r = feed(s);
+ if (!r) continue;
+ if ("error" in r) {
+ out = r;
+ break;
+ }
+ if (found && found.table.id !== r.table.id) {
+ out = { error: `“${nodeLabel(found.table)}” and “${nodeLabel(r.table)}” both reach “${nodeLabel(n)}” — rows run from one table at a time` };
+ break;
+ }
+ found = r;
+ }
+ visiting.delete(n.id);
+ const result = out ?? found;
+ memo.set(n.id, result);
+ return result;
+ };
+ return feed;
+}
+
+/**
+ * The table a node runs per row of: one wired into it, or one feeding a node it builds on (a Video concatenator
+ * collects the rows instead, so nothing after it runs per row). Null when no table is upstream.
+ */
+export function rowsFeeding(graph: CanvasGraph, n: CanvasNode): RowsFeed {
+ return tablesFeeding(graph)(n);
}
/** One job per row: the table read as that row (its cells in "{Column}", or as connected text), upstream rows matched by number. */
@@ -1045,8 +1083,9 @@ function rowRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef, b: { tab
const own = n.data.prompt ?? "";
const direct = graph.edges.some((e) => e.source === b.table.id && e.target === n.id);
const named = direct && columns.some((c) => c && own.includes(`{${c}}`));
+ const feeds = tablesFeeding(graph);
const perRow = (id: string) => {
- const r = rowsFeeding(graph, nodes.get(id)!);
+ const r = feeds(nodes.get(id)!);
return !!r && !("error" in r);
};
const steps: NodeStep[] = [];
@@ -1089,6 +1128,19 @@ export const concatRatio = (r: string | undefined): ConcatRatio => ((CONCAT_RATI
/** 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;
+/**
+ * A silent sound track `seconds` long, as a concatenator step names it: the server writes the WAV when the run
+ * starts (silenceSeconds reads the length back). A clip muted, or with no sound of its own, gets one, so every clip
+ * reaches merge-videos with sound (whether it keeps the others' sound when one clip has no audio stream is unknown).
+ */
+export const SILENCE_REF = "silence:";
+export const silenceRef = (seconds: number) => `${SILENCE_REF}${Math.round(seconds * 1000) / 1000}`;
+export function silenceSeconds(ref: string | undefined): number | null {
+ if (!ref?.startsWith(SILENCE_REF)) return null;
+ const s = Number(ref.slice(SILENCE_REF.length));
+ return Number.isFinite(s) && s > 0 && s <= 36_000 ? s : null;
+}
+
/** 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);
@@ -1099,17 +1151,19 @@ function clipCut(c: ClipSettings, i: number): { start: number; end?: number } |
}
/**
- * 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
+ * The Video Concatenator's jobs. Cloud, per clip: trim-video (when cut), scale-video (into the film's frame), and
+ * for a muted clip or one with no sound of its own, silence as long as it plays muxed in (merge-audio-video with a
+ * WAV the server writes); a muted clip whose length isn't known yet gets its own soundtrack lowered −70 dB instead.
+ * 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 nodes = nodeMap(graph);
// A node run once per row of a table gives a clip per row, in row order (each with that node's cut and sound).
+ const feeds = tablesFeeding(graph);
const clips = concatClips(graph, n).flatMap((c): { nodeId: string; settings: ClipSettings; row?: number }[] => {
- const rows = rowsFeeding(graph, nodes.get(c.nodeId)!);
+ const rows = feeds(nodes.get(c.nodeId)!);
return rows && !("error" in rows) ? rows.rows.map((_, row) => ({ ...c, row })) : [c];
});
if (!clips.length) return { error: `Connect the clips to join (up to ${CONCAT_LIMITS.clips})` };
@@ -1139,11 +1193,13 @@ function concatRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): Node
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);
+ // A clip per table row: the facts measured from one row's file (length, sound) don't hold for the others.
+ const facts: ClipSettings = c.row === undefined ? c.settings : { start: c.settings.start, end: c.settings.end, mute: c.settings.mute };
+ const cut = clipCut(facts, 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, ...(c.row !== undefined && { row: c.row }) };
- const mute = !!c.settings.mute && c.settings.audio !== false;
+ const mute = !!facts.mute;
if (engine === "open") {
at = add(`fit:${i}`, at, {
modelId: CONCAT_TOOLS.open.fit,
@@ -1154,12 +1210,18 @@ function concatRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): Node
} 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;
+ const end = cut.end ?? facts.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) {
+ // How long the clip plays: its cut, else its measured length from the start of the cut.
+ const plays = cut.end !== undefined ? cut.end - cut.start : facts.length !== undefined ? facts.length - cut.start : undefined;
+ if ((mute || facts.audio === false) && plays !== undefined && plays > 0) {
+ // Muted, or silent to begin with: its sound becomes silence exactly as long as the clip.
+ at = add(`quiet:${i}`, at, { modelId: CONCAT_TOOLS.cloud.mux, op: "mux", inputs: { audio: silenceRef(plays) }, step: label("Mute") });
+ } else if (mute) {
+ // Its length isn't known yet (a clip made upstream in this run): its own sound, lowered to −70 dB.
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}` } }]);
@@ -1311,6 +1373,29 @@ export function nodeSignature(req: GenerationRequest, depIds: string[], steps?:
return hash(stable({ ...unlabeled(req), deps: depIds }));
}
+/**
+ * What a node builds on, for its signature: the generation of the node it takes, or for a node run per table row
+ * every row's (a row run again on its own leaves the first one as it was, and what joins the rows is stale all the same).
+ */
+export const depIdentity = (run: Pick<NodeRun, "rows"> | undefined, generationId: string): string => run?.rows?.join(",") ?? generationId;
+
+/** One row of a node run per table row: its request (minus labels) and the generations its slots take. */
+export function rowSignature(req: GenerationRequest, sources: (string | undefined)[]): string {
+ return hash(stable({ ...unlabeled(req), from: sources }));
+}
+
+const LIVE = new Set<GenerationStatus | undefined>(["queued", "running", "succeeded"]);
+
+/**
+ * The generation a row of a node run per table row keeps from its last run: the row's result when it's still live
+ * and the row's inputs are unchanged (its own signature; for a run saved before rows had one, the node's).
+ */
+export function keptRow(prev: NodeRun | undefined, row: number, rowSig: string, sig: string, status: (generationId: string) => GenerationStatus | undefined): string | undefined {
+ const old = prev?.rows?.[row];
+ if (!old || !LIVE.has(status(old))) return undefined;
+ return (prev!.rowSigs ? prev!.rowSigs[row] === rowSig : prev!.sig === sig) ? old : undefined;
+}
+
// ---------------------------------------------------------------------------
// Planning a run
@@ -1320,7 +1405,10 @@ export interface PlannedStep extends NodeRequest {
nodeId: string;
label: string;
reason: RunReason;
+ /** What this run costs (a node run per row: the rows it runs again, when the planner can tell). */
costUsd: number | null;
+ /** A node run per row: one row's price. */
+ rowCostUsd?: number | null;
}
export interface CanvasPlan {
@@ -1349,8 +1437,6 @@ export interface PlanOptions extends DescribeContext {
describe?: (n: CanvasNode) => NodeDescription;
}
-const LIVE = new Set<GenerationStatus | undefined>(["queued", "running", "succeeded"]);
-
export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPlan {
const nodes = nodeMap(graph);
const runs = opts.runs ?? {};
@@ -1388,7 +1474,7 @@ export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPl
continue;
}
const prev = runs[id];
- // A node run per row is as fresh as its weakest row: a failed or trashed row makes it run again.
+ // A node run per row is as fresh as its weakest row: a failed or trashed row makes it run again (that row only).
const rowStatus = prev?.rows?.map(status);
const weakest = rowStatus?.findIndex((x) => !LIVE.has(x)) ?? -1;
const prevStatus = rowStatus ? rowStatus[Math.max(0, weakest)] : prev ? status(runOutput(prev)) : undefined;
@@ -1416,11 +1502,18 @@ export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPl
continue;
}
let reason: RunReason | null;
+ let cost = d.costUsd;
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), d.steps);
+ const sig = nodeSignature(d.request, upstream.map((u) => depIdentity(runs[u.dep], (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";
+ // Rows that are live and unchanged are kept (the server does the same): only the others are paid for.
+ if (reason && reason !== "forced" && d.rows && d.steps && prev?.rows && cost !== null) {
+ const from = (f: StepSource) => ("node" in f ? (f.row === undefined ? (state.get(f.node) as { id: string }).id : runs[f.node]?.rows?.[f.row]) : undefined);
+ const redo = d.steps.filter((st, r) => !keptRow(prev, r, rowSignature(st.request, st.from.map(from)), sig, status)).length;
+ cost = Math.round(((cost * redo) / d.steps.length) * 10000) / 10000;
+ }
}
if (!reason) {
state.set(id, { kind: "reuse", id: runOutput(prev!) });
@@ -1428,9 +1521,18 @@ export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPl
continue;
}
state.set(id, { kind: "run" });
- steps.push({ nodeId: id, label, request: d.request, deps: d.deps, ...(d.steps && { steps: d.steps }), ...(d.rows && { rows: d.rows }), reason, costUsd: d.costUsd });
- if (d.costUsd === null) costUnknown = true;
- else costUsd += d.costUsd;
+ steps.push({
+ nodeId: id,
+ label,
+ request: d.request,
+ deps: d.deps,
+ ...(d.steps && { steps: d.steps }),
+ ...(d.rows && { rows: d.rows, rowCostUsd: d.costUsd === null ? null : d.costUsd / d.rows }),
+ reason,
+ costUsd: cost,
+ });
+ if (cost === null) costUnknown = true;
+ else costUsd += cost;
}
return { order: inScope, steps, reused, errors, costUsd: Math.round(costUsd * 1000) / 1000, costUnknown };
}
diff --git a/src/server/canvas.ts b/src/server/canvas.ts
index 9f78d6f5..c30e401b 100644
--- a/src/server/canvas.ts
+++ b/src/server/canvas.ts
@@ -21,14 +21,18 @@ import {
TABLE_LIMITS,
cleanGraph,
concatClips,
+ depIdentity,
EMPTY_GRAPH,
getTemplate,
+ keptRow,
NODE_SPECS,
nodeLabel,
nodeMap,
nodeSignature,
outline,
planCanvas,
+ rowSignature,
+ silenceSeconds,
withCurrentElements,
type Canvas,
type CanvasGraph,
@@ -36,14 +40,16 @@ import {
type CanvasPlan,
type CanvasRuns,
type CanvasSummary,
+ type StepSource,
} from "@/lib/catalog/canvas";
-import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
+import type { Engine, Generation, GenerationRequest, MediaKind } from "@/lib/catalog/types";
import { createPipeline } from "./chains";
import { db } from "./db";
import { listElements } from "./elements";
import { createGenerations, getGeneration } from "./generations";
+import { silentWav } from "./marketing";
import { engineMode } from "./settings";
-import { absolutePath } from "./storage";
+import { absolutePath, saveFile } from "./storage";
/**
* Canvas boards (Higgsfield Canvas): the pages the user edits (each a graph, with its groups, comments and
@@ -159,6 +165,8 @@ const NodeData = z.object({
// Table: column names and rows of cells (a few empty rows past the limit are fine; only filled rows run).
columns: z.array(z.string().max(TABLE_LIMITS.column)).min(1).max(TABLE_LIMITS.columns).optional(),
rows: z.array(z.array(z.string().max(TABLE_LIMITS.cell)).max(TABLE_LIMITS.columns)).max(TABLE_LIMITS.rows * 2).optional(),
+ // Translate (video) on the open engine: the dub it started in Translate & dub.
+ dubId: z.string().max(40).optional(),
});
const Num = z.number().finite();
@@ -249,6 +257,13 @@ 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)";
+ // One drawing, group or comment that doesn't fit (not too many of them): say which kind, and what to do.
+ if (list === "shapes" && typeof index === "number") {
+ const kind = (input as { shapes?: { kind?: string }[] }).shapes?.[index]?.kind;
+ return rest[0] === "points" ? "A drawing has too many points to save — erase it and draw it again in shorter strokes" : `A ${kind === "text" ? "text" : "drawing"} on this board couldn't be saved — erase it and make it again`;
+ }
+ if (list === "groups" && typeof index === "number") return "A group on this board couldn't be saved — ungroup it and group the nodes again";
+ if (list === "comments" && typeof index === "number") return "A comment on this board couldn't be saved — delete it and pin it again";
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`;
@@ -388,7 +403,16 @@ export interface CanvasPatch {
page?: string;
}
-/** Save a new name, pages and/or one page's graph. Moving a viewport alone doesn't count as an edit. */
+/** A change the canvas can't take as it is now (a 409: the editor shows the message). */
+export class CanvasConflict extends Error {
+ readonly status = 409;
+}
+
+/**
+ * Save a new name, pages and/or one page's graph. Moving a viewport alone doesn't count as an edit. A graph for a
+ * page the canvas doesn't have yet (one the editor added, run before its autosave) adds that page; with no room for
+ * it, the save is refused (CanvasConflict) rather than written over another page.
+ */
export function updateCanvas(id: string, patch: CanvasPatch): Canvas | null {
const current = getCanvas(id);
if (!current) return null;
@@ -397,10 +421,13 @@ export function updateCanvas(id: string, patch: CanvasPatch): Canvas | null {
let pages = current.pages;
if (patch.pages?.length) pages = patch.pages.map((p) => ({ ...p, graph: cleanGraph(p.graph) }));
if (patch.graph) {
- const graph = cleanGraph(patch.graph);
- // A page the editor added and hasn't saved yet (a run sent before the autosave): added, never written over page 1.
- if (patch.page && !pages.some((p) => p.id === patch.page) && pages.length < BOARD_LIMITS.pages) pages = [...pages, { id: patch.page, name: nextPageName(pages), graph }];
- else pages = withPageGraph(pages, patch.page, graph);
+ const known = !patch.page || pages.some((p) => p.id === patch.page);
+ if (!known && pages.length >= BOARD_LIMITS.pages) throw new CanvasConflict(`This canvas already holds ${BOARD_LIMITS.pages} pages, so the new one couldn't be saved — reload the canvas`);
+ const target = patch.page ?? pages[0].id;
+ // Results are kept by node id, so two pages can't share one: a node another page holds stays there (as parsePages does).
+ const elsewhere = new Set(pages.filter((p) => p.id !== target).flatMap((p) => p.graph.nodes.map((n) => n.id)));
+ const graph = cleanGraph({ ...patch.graph, nodes: patch.graph.nodes.filter((n) => !elsewhere.has(n.id)) });
+ pages = known ? withPageGraph(pages, target, graph) : [...pages, { id: target, name: nextPageName(pages), 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);
@@ -452,6 +479,8 @@ export function canvasView(id: string): { canvas: Canvas; generations: Generatio
export interface RunOptions {
/** The page to run (the first one when omitted). */
page?: string;
+ /** Every page as the editor has them (saved first, like an autosave): the run saves the whole canvas. */
+ pages?: CanvasPage[];
/** Nodes to run with their upstream; omit for Run all (of the page). */
targets?: string[];
/** Run a group: its nodes and what they need. */
@@ -495,10 +524,31 @@ function oversizedClip(graph: CanvasGraph, nodeId: string): string | null {
return null;
}
+/**
+ * The silent tracks a run's steps name (silenceRef: a muted or soundless clip of the cloud concatenator), written
+ * as WAV files when the run starts; one file per length.
+ */
+function silenceWriter(): (req: GenerationRequest) => GenerationRequest {
+ const files = new Map<number, string>();
+ return (req) => {
+ const seconds = silenceSeconds(req.inputs?.audio);
+ if (seconds === null) return req;
+ let url = files.get(seconds);
+ if (!url) {
+ url = saveFile({ data: silentWav(seconds), contentType: "audio/wav", source: "generation", name: "canvas-silence.wav" }).url;
+ files.set(seconds, url);
+ }
+ return { ...req, inputs: { ...req.inputs, audio: url } };
+ };
+}
+
export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
let canvas = getCanvas(id);
if (!canvas) return null;
+ if (opts.pages?.length) canvas = updateCanvas(id, { pages: opts.pages })!;
if (opts.graph) canvas = updateCanvas(id, { graph: opts.graph, page: opts.page })!;
+ // A page named is run, never another one in its place.
+ if (opts.page && !canvas.pages.some((p) => p.id === opts.page)) throw new CanvasConflict("That page isn't on this canvas any more — reload it");
// An element renamed since the board was saved: its node mentions the new @handle.
const graph = withCurrentElements(pageOf(canvas.pages, opts.page).graph, listElements());
const targets = opts.group ? groupTargets(graph, opts.group) : opts.targets;
@@ -510,9 +560,12 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
// Nodes run per row of a table: each row's generation (a row of the next node waits for the same row).
const madeRows = new Map<string, string[]>(plan.reused.flatMap((r) => (canvas.runs[r.nodeId]?.rows ? [[r.nodeId, canvas.runs[r.nodeId].rows!] as [string, string[]]] : [])));
const errors = [...plan.errors];
+ const withSilence = silenceWriter();
const items: Generation[] = [];
const ran: string[] = [];
const runs: CanvasRuns = {};
+ /** What each started node costs (a node run per row: only the rows that run again). */
+ const spent = new Map<string, number>();
const n = plan.steps.length;
plan.steps.forEach((step, i) => {
const depIds = step.deps.map((d) => made.get(d));
@@ -522,13 +575,13 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
return;
}
try {
- const sig = nodeSignature(step.request, depIds as string[], step.steps);
+ const sig = nodeSignature(step.request, step.deps.map((d, k) => depIdentity({ rows: madeRows.get(d) }, depIds[k] 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: Record<string, string> = Object.fromEntries(step.deps.map((d, k) => [`node:${d}`, depIds[k] as string]));
- const at = (f: NonNullable<typeof step.steps>[number]["from"][number]) => {
+ const at = (f: StepSource) => {
if (!("node" in f)) return f.step;
if (f.row === undefined) return `node:${f.node}`;
const id = madeRows.get(f.node)?.[f.row];
@@ -536,25 +589,38 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
existing[`node:${f.node}#${f.row}`] = id;
return `node:${f.node}#${f.row}`;
};
- 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(at),
- })),
- { batchId, existing },
- );
+ // A node run per row keeps the rows whose result is live and whose inputs didn't change: one failed row
+ // (or a row added to the table) runs, and is paid for, on its own.
+ const source = (f: StepSource) => ("node" in f ? (f.row === undefined ? made.get(f.node) : madeRows.get(f.node)?.[f.row]) : undefined);
+ const rowSigs = step.rows ? step.steps.map((st) => rowSignature(st.request, st.from.map(source))) : undefined;
+ const prev = canvas.runs[step.nodeId];
+ const kept = step.steps.map((_, r) => (rowSigs && step.reason !== "forced" ? keptRow(prev, r, rowSigs[r], sig, statusOf) : undefined));
+ const todo = step.steps.filter((_, r) => !kept[r]);
+ const pipe = todo.length
+ ? createPipeline(
+ todo.map((st) => ({
+ key: st.key,
+ request: withSilence({ ...st.request, step: { label: st.request.step?.label ?? step.label, index: i, of: n } }),
+ after: st.from.map(at),
+ })),
+ { batchId, existing },
+ )
+ : null;
if (step.rows) {
// Every row is a result; the next node takes the first one, or its own row.
- const rows = step.steps.map((st) => pipe.byKey[st.key].id);
+ const rows = step.steps.map((st, r) => kept[r] ?? pipe!.byKey[st.key].id);
made.set(step.nodeId, rows[0]);
madeRows.set(step.nodeId, rows);
- runs[step.nodeId] = { sig, ids: pipe.items.map((g) => g.id), rows, at: Date.now() };
+ const ids = [...rows, ...(pipe?.items.map((g) => g.id).filter((g) => !rows.includes(g)) ?? [])];
+ runs[step.nodeId] = { sig, ids, rows, rowSigs, at: Date.now() };
+ spent.set(step.nodeId, (step.rowCostUsd ?? 0) * todo.length);
} else {
- const out = pipe.byKey[step.steps[step.steps.length - 1].key];
+ 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() };
+ runs[step.nodeId] = { sig, ids: pipe!.items.map((g) => g.id), out: out.id, at: Date.now() };
+ spent.set(step.nodeId, step.costUsd ?? 0);
}
+ if (!pipe) return;
items.push(...pipe.items);
} else {
const created = createGenerations(
@@ -563,6 +629,7 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
);
made.set(step.nodeId, created[0].id);
runs[step.nodeId] = { sig, ids: created.map((g) => g.id), at: Date.now() };
+ spent.set(step.nodeId, step.costUsd ?? 0);
items.push(...created);
}
ran.push(step.nodeId);
@@ -570,7 +637,7 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
errors.push({ nodeId: step.nodeId, message: (e as Error).message });
}
});
- if (ran.length) {
+ if (Object.keys(runs).length) {
// Merge into the latest runs (another run may have finished writing meanwhile).
db().transaction(() => {
const row = db().prepare("SELECT runs_json FROM canvases WHERE id = ?").get(id) as { runs_json: string } | undefined;
@@ -584,6 +651,6 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {
ran,
reused: plan.reused,
errors,
- costUsd: plan.steps.filter((s) => ran.includes(s.nodeId)).reduce((sum, s) => sum + (s.costUsd ?? 0), 0),
+ costUsd: Math.round([...spent.values()].reduce((sum, c) => sum + c, 0) * 10000) / 10000,
};
}
diff --git a/tests/canvas-plus.test.ts b/tests/canvas-plus.test.ts
index 846f604e..484d696f 100644
--- a/tests/canvas-plus.test.ts
+++ b/tests/canvas-plus.test.ts
@@ -16,6 +16,9 @@ const {
CONCAT_SIZE,
MUTE_LEVEL,
OPEN_DUB_HINT,
+ silenceRef,
+ silenceSeconds,
+ rowSignature,
cleanGraph,
concatClips,
connectionError,
@@ -202,26 +205,42 @@ describe("plans for the new nodes", () => {
const d = describeNode(g, g.nodes[2], { engineMode: "cloud" });
expect(d.error).toBeUndefined();
expect(d.deps).toEqual(["gen"]);
+ // The muted clip plays 3 s: its sound becomes 3 s of silence (whether it had sound or not).
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" }]],
+ ["quiet:0", "merge-audio-video", "mux", [{ step: "fit:0" }]],
["fit:1", "scale-video", "reframe", [{ node: "gen" }]],
- ["join", "join-clips", "concat", [{ step: "mute:0" }, { step: "fit:1" }]],
+ ["join", "join-clips", "concat", [{ step: "quiet: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("quiet:0")).toMatchObject({ inputs: { audio: silenceRef(3) }, chain: [{ slot: "video" }] });
+ expect(silenceSeconds(step("quiet:0").inputs!.audio)).toBe(3);
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 muted clip whose length isn't known yet (made upstream in this run): its own sound, lowered to −70 dB.
+ g.nodes[2].data.clips = { gen: { mute: true } };
+ const quiet = describeNode(g, g.nodes[2]).steps!;
+ expect(quiet.filter((s) => s.key.endsWith(":1")).map((s) => [s.key, s.request.modelId, s.from])).toEqual([
+ ["fit:1", "scale-video", [{ node: "gen" }]],
+ ["sound:1", "extract-soundtrack", [{ step: "fit:1" }]],
+ ["quiet:1", "ffmpeg-loudnorm", [{ step: "sound:1" }]],
+ ["mute:1", "merge-audio-video", [{ step: "fit:1" }, { step: "quiet:1" }]],
+ ]);
+ expect(quiet.find((s) => s.key === "quiet:1")!.request.params!.extra).toEqual(MUTE_LEVEL);
+ // A clip with no sound of its own (read from its file) gets silence as long as it plays, so every clip reaches
+ // merge-videos with a sound track; one with sound is left as it is.
+ g.nodes[2].data.clips = { a: { audio: false, length: 6.5, start: 2 }, gen: { audio: true, length: 5 } };
+ const silent = describeNode(g, g.nodes[2]).steps!;
+ expect(silent.find((s) => s.key === "quiet:0")!.request.inputs!.audio).toBe(silenceRef(4.5));
+ expect(silent.some((s) => s.key === "quiet:1" || s.key === "sound:1")).toBe(false);
+
// 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/);
@@ -542,7 +561,8 @@ describe("pages", () => {
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);
+ // The cut clip: trim, frame, its silence (muted); the shot: frame; then the join.
+ expect(film.ids).toHaveLength(5);
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);
@@ -564,3 +584,204 @@ describe("pages", () => {
expect(((await res.json()) as { error: string }).error).toBe("This group has no nodes in it yet");
}, 90_000);
});
+
+describe("review fixes", () => {
+ it("a long stroke is thinned within the saved limit whatever its length, and a refused drawing is named", async () => {
+ for (let n = 2; n <= 2400; n++) {
+ const s = board.penShape("s", Array.from({ length: n }, (_, i) => ({ x: i * 3, y: (i % 7) * 3 })), "ink")!;
+ expect(s.points!.length, `${n} points`).toBeLessThanOrEqual(board.BOARD_LIMITS.penPoints);
+ // The stroke still ends where it was drawn to.
+ expect(s.points!.at(-1)![0]).toBe(1);
+ }
+ const { graphProblem } = await import("@/server/canvas");
+ const pen = (points: number) => ({ id: "s", kind: "pen", x: 0, y: 0, width: 10, height: 10, color: "ink", points: Array.from({ length: points }, () => [0, 0]) });
+ expect(graphProblem({ nodes: [], edges: [], shapes: [pen(401)] })).toMatch(/^A drawing has too many points to save/);
+ expect(graphProblem({ nodes: [], edges: [], shapes: Array.from({ length: 501 }, () => pen(2)) })).toMatch(/too many drawings to save \(500 at most\)/);
+ });
+
+ it("a page copy keeps the concatenator's cuts, sound and order on the new clip ids", () => {
+ const g: CanvasGraph = {
+ nodes: [node("a", "video-input", { url: "/api/files/u/a.mp4" }), node("b", "video-input", { url: "/api/files/u/b.mp4" }, 0, 300), node("film", "concat", { modelId: "join-clips", order: ["b", "a"], clips: { a: { start: 1, end: 3, mute: true }, b: { start: 2, end: 4 } } }, 400)],
+ edges: [edge("a", "film", "videos"), edge("b", "film", "videos")],
+ };
+ const before = concatClips(g, g.nodes[2]).map((c) => c.settings);
+ let k = 0;
+ const copy = board.copyPage({ id: "page-1", name: "Page 1", graph: g }, "page-2", "Copy", (p) => `${p}-${++k}`);
+ const film = copy.graph.nodes.find((n) => n.type === "concat")!;
+ const clips = concatClips(copy.graph, film);
+ expect(clips.map((c) => c.settings)).toEqual(before);
+ expect(clips.map((c) => c.nodeId)).toEqual(film.data.order);
+ expect(clips.map((c) => c.nodeId)).not.toContain("a");
+ // Ids the map doesn't know stay as they are.
+ expect(board.remapNodeData({ order: ["x"], clips: { x: { mute: true } } }, new Map())).toEqual({ order: ["x"], clips: { x: { mute: true } } });
+ });
+
+ it("a graph for a page the canvas doesn't have is added, or refused when the canvas is full — never written over page 1", async () => {
+ const pages = Array.from({ length: board.BOARD_LIMITS.pages }, (_, i) => ({ id: `p${i}`, name: `Page ${i + 1}`, graph: { nodes: [node(`n${i}`, "prompt", { text: `text ${i}` })], edges: [] } }));
+ let res = await list.POST(req("POST", { name: "Full", pages }));
+ const c = (await res.json()) as Canvas;
+ expect(c.pages).toHaveLength(20);
+ const fresh = { nodes: [node("fresh", "prompt", { text: "new" })], edges: [] };
+ res = await one.PATCH(req("PATCH", { page: "page-new", graph: fresh }), ctx(c.id));
+ expect(res.status).toBe(409);
+ expect(((await res.json()) as { error: string }).error).toMatch(/already holds 20 pages/);
+ res = await run.POST(req("POST", { page: "page-new", graph: fresh }), ctx(c.id));
+ expect(res.status).toBe(409);
+ // A page that isn't there isn't run in another page's place either.
+ expect((await run.POST(req("POST", { page: "nope" }), ctx(c.id))).status).toBe(409);
+ const view = (await (await one.GET(req("GET"), ctx(c.id))).json()) as { canvas: Canvas };
+ expect(view.canvas.pages[0].graph.nodes.map((n) => n.id)).toEqual(["n0"]);
+ expect(view.canvas.pages).toHaveLength(20);
+ // A graph saved for one page can't take a node id another page holds (results are kept by node id).
+ res = await one.PATCH(req("PATCH", { page: "p1", graph: { nodes: [node("n0", "prompt", { text: "stolen" }), node("mine", "prompt", { text: "ok" })], edges: [] } }), ctx(c.id));
+ const saved = (await res.json()) as Canvas;
+ expect(saved.pages[1].graph.nodes.map((n) => n.id)).toEqual(["mine"]);
+ expect(saved.pages[0].graph.nodes[0].data.text).toBe("text 0");
+ });
+
+ it("a run sends every page: a rename, a new page and another page's edit are saved with it", async () => {
+ let res = await list.POST(req("POST", { name: "Run saves all", graph: { nodes: [node("p", "prompt", { text: "A heron" }), node("img", "model", { modelId: "nano-banana-pro" }, 400)], edges: [edge("p", "img", "prompt")] } }));
+ const c = (await res.json()) as Canvas;
+ const pages = [
+ { ...c.pages[0], name: "Birds" },
+ { id: "page-x", name: "Later", graph: { nodes: [node("q", "prompt", { text: "A crane" })], edges: [] } },
+ ];
+ res = await run.POST(req("POST", { page: "page-1", pages }), ctx(c.id));
+ expect(res.status).toBe(201);
+ const body = (await res.json()) as { ran: string[]; canvas: Canvas };
+ expect(body.ran).toEqual(["img"]);
+ expect(body.canvas.pages.map((p) => [p.id, p.name])).toEqual([
+ ["page-1", "Birds"],
+ ["page-x", "Later"],
+ ]);
+ // Bad pages are refused like the autosave refuses them.
+ res = await run.POST(req("POST", { page: "page-1", pages: [] }), ctx(c.id));
+ expect(res.status).toBe(400);
+ }, 30_000);
+
+ it("the board's cached plan of a concatenator follows the table its clips are made from", async () => {
+ const { DescribeCache } = await import("@/components/canvas/canvas-context");
+ const { getTemplate } = await import("@/lib/catalog/canvas");
+ for (const mode of ["cloud", "open"] as const) {
+ const cache = new DescribeCache();
+ const three = getTemplate("table-film")!.build(mode);
+ const at = (g: CanvasGraph) => g.nodes.findIndex((n) => n.type === "concat");
+ const film = (g: CanvasGraph) => describeNode(g, g.nodes[at(g)], { engineMode: mode });
+ expect(film(three).error).toBeUndefined();
+ expect(cache.run(three, mode).get("film")!.d.steps).toEqual(film(three).steps);
+ // Two rows more: the table changed, not the concatenator or the node wired into it.
+ const t = three.nodes.findIndex((n) => n.type === "table");
+ const five = { ...three, nodes: three.nodes.map((n, i) => (i === t ? { ...n, data: { ...n.data, rows: [...n.data.rows!, ["wolf", "a ridge"], ["hare", "a meadow"]] } } : n)) };
+ expect(film(five).steps!.length).toBeGreaterThan(film(three).steps!.length);
+ const cached = cache.run(five, mode).get("film")!.d;
+ expect(cached.steps).toEqual(film(five).steps);
+ expect(cached.costUsd).toBe(film(five).costUsd);
+ }
+ });
+
+ it("a failed row runs again on its own, with the same row after it; the others are kept and not paid for again", async () => {
+ const g: CanvasGraph = {
+ nodes: [
+ node("t", "table", { label: "Cast", columns: ["Animal"], rows: [["fox"], ["owl"], ["bear"]] }),
+ node("img", "model", { modelId: "nano-banana-pro", mediaKind: "image", prompt: "A {Animal}" }, 400),
+ node("vid", "model", { modelId: "kling-2-5-turbo", mediaKind: "video", op: "i2v", prompt: "slow push-in" }, 800),
+ ],
+ edges: [edge("t", "img", "prompt"), edge("img", "vid", "images")],
+ };
+ let res = await list.POST(req("POST", { name: "Rows", graph: g }));
+ const c = (await res.json()) as Canvas;
+ res = await run.POST(req("POST", {}), ctx(c.id));
+ const first = (await res.json()) as { canvas: Canvas; costUsd: number };
+ const img = first.canvas.runs.img;
+ const vid = first.canvas.runs.vid;
+ expect(img.rowSigs).toHaveLength(3);
+ for (const id of [...img.rows!, ...vid.rows!]) await settle(id);
+
+ // Row 2's image fails: only that image runs again, and only row 2's video after it.
+ db().prepare("UPDATE generations SET status = 'failed' WHERE id = ?").run(img.rows![1]);
+ const plan = planCanvas(g, { runs: first.canvas.runs, status: (id) => gens.getGeneration(id)?.status });
+ const imgStep = plan.steps.find((s) => s.nodeId === "img")!;
+ expect(imgStep.reason).toBe("failed");
+ expect(imgStep.costUsd).toBeCloseTo(imgStep.rowCostUsd!, 6);
+ res = await run.POST(req("POST", {}), ctx(c.id));
+ const again = (await res.json()) as { ran: string[]; items: Generation[]; canvas: Canvas; costUsd: number };
+ expect(again.ran).toEqual(["img", "vid"]);
+ expect(again.items).toHaveLength(2);
+ const img2 = again.canvas.runs.img;
+ const vid2 = again.canvas.runs.vid;
+ expect([img2.rows![0], img2.rows![2]]).toEqual([img.rows![0], img.rows![2]]);
+ expect(img2.rows![1]).not.toBe(img.rows![1]);
+ expect([vid2.rows![0], vid2.rows![2]]).toEqual([vid.rows![0], vid.rows![2]]);
+ expect(vid2.rows![1]).not.toBe(vid.rows![1]);
+ expect(again.items.find((x) => x.id === vid2.rows![1])!.prompt).toBe("slow push-in");
+ const deps = (id: string) => (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;
+ expect(deps(vid2.rows![1])).toBe(img2.rows![1]);
+ // The node shows every row's result, in row order.
+ expect(img2.ids.slice(0, 3)).toEqual(img2.rows);
+ for (const id of [img2.rows![1], vid2.rows![1]]) await settle(id);
+
+ // A row added to the table runs on its own too.
+ const view = (await (await one.GET(req("GET"), ctx(c.id))).json()) as { canvas: Canvas };
+ const page = view.canvas.pages[0].graph;
+ page.nodes[0].data.rows = [["fox"], ["owl"], ["bear"], ["hare"]];
+ res = await run.POST(req("POST", { page: "page-1", graph: page }), ctx(c.id));
+ const more = (await res.json()) as { ran: string[]; items: Generation[]; canvas: Canvas };
+ expect(more.ran).toEqual(["img", "vid"]);
+ expect(more.items.map((x) => x.prompt)).toEqual(["A hare", "slow push-in"]);
+ expect(more.canvas.runs.img.rows!.slice(0, 3)).toEqual(img2.rows);
+ // A row's own signature names its inputs: the same request on another image is another row.
+ expect(rowSignature({ feature: "canvas", modelId: "m" }, ["g1"])).not.toBe(rowSignature({ feature: "canvas", modelId: "m" }, ["g2"]));
+ }, 90_000);
+
+ it("a film joined from a node's rows is stale once any of its rows is made again", async () => {
+ const g: CanvasGraph = {
+ nodes: [
+ node("t", "table", { label: "Cast", columns: ["Animal"], rows: [["fox"], ["owl"]] }),
+ node("img", "model", { modelId: "nano-banana-pro", mediaKind: "image", prompt: "A {Animal}" }, 400),
+ node("vid", "model", { modelId: "kling-2-5-turbo", mediaKind: "video", op: "i2v", prompt: "slow push-in" }, 800),
+ node("film", "concat", { modelId: "join-clips" }, 1200),
+ ],
+ edges: [edge("t", "img", "prompt"), edge("img", "vid", "images"), edge("vid", "film", "videos")],
+ };
+ let res = await list.POST(req("POST", { name: "Rows film", graph: g }));
+ const c = (await res.json()) as Canvas;
+ res = await run.POST(req("POST", {}), ctx(c.id));
+ const first = (await res.json()) as { ran: string[]; canvas: Canvas };
+ expect(first.ran).toEqual(["img", "vid", "film"]);
+ expect((await settle(first.canvas.runs.film.out!)).status).toBe("succeeded");
+ const status = (id: string) => gens.getGeneration(id)?.status;
+ expect(planCanvas(g, { runs: first.canvas.runs, status }).steps).toEqual([]);
+ // Row 2's clip fails and is made again on its own (the film isn't run): the first row is the same as before…
+ db().prepare("UPDATE generations SET status = 'failed' WHERE id = ?").run(first.canvas.runs.vid.rows![1]);
+ res = await run.POST(req("POST", { targets: ["vid"] }), ctx(c.id));
+ const redo = (await res.json()) as { ran: string[]; items: Generation[]; canvas: Canvas };
+ expect(redo.ran).toEqual(["vid"]);
+ expect(redo.items).toHaveLength(1);
+ expect(redo.canvas.runs.vid.rows![0]).toBe(first.canvas.runs.vid.rows![0]);
+ // …but the film was joined from the old second clip: it runs again.
+ const plan = planCanvas(g, { runs: redo.canvas.runs, status });
+ expect(plan.steps.map((s) => [s.nodeId, s.reason])).toEqual([["film", "changed"]]);
+ }, 90_000);
+
+ it("a muted cloud clip's silence is written when the run starts", async () => {
+ const graph: CanvasGraph = {
+ nodes: [node("a", "video-input", { url: "/api/files/u/quiet.mp4" }), node("b", "video-input", { url: "/api/files/u/quiet.mp4" }, 0, 300), node("film", "concat", { modelId: "join-clips", clips: { a: { end: 1.5, mute: true } } }, 400)],
+ edges: [edge("a", "film", "videos"), edge("b", "film", "videos")],
+ };
+ fs.mkdirSync(path.join(dir, "files", "u"), { recursive: true });
+ fs.writeFileSync(path.join(dir, "files", "u", "quiet.mp4"), Buffer.alloc(256));
+ let res = await list.POST(req("POST", { name: "Silence", graph }));
+ const c = (await res.json()) as Canvas;
+ res = await run.POST(req("POST", {}), ctx(c.id));
+ expect(res.status).toBe(201);
+ const body = (await res.json()) as { items: Generation[] };
+ const mux = body.items.find((x) => x.modelId === "merge-audio-video")!;
+ const audio = mux.request.inputs!.audio!;
+ expect(audio).toMatch(/^\/api\/files\//);
+ const { absolutePath } = await import("@/server/storage");
+ const wav = fs.readFileSync(absolutePath(decodeURIComponent(audio.slice("/api/files/".length))));
+ expect(wav.toString("ascii", 0, 4)).toBe("RIFF");
+ // 1.5 s of 16-bit stereo at 44.1 kHz.
+ expect(wav.length).toBe(44 + Math.round(1.5 * 44100) * 4);
+ }, 30_000);
+});