The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Canvas: Table node — the node it feeds runs once per filled row, and rows carry down to the concatenator
Claude0f58b41fd6ce
diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsxindex 05ca8080..7e24b937 100644--- a/src/components/canvas/canvas-context.tsx+++ b/src/components/canvas/canvas-context.tsx@@ -19,6 +19,7 @@ import {Package,Sparkles,StickyNote,+ Table,Type,UserRound,ZoomIn,@@ -29,6 +30,7 @@ import {describeNode,effectiveOp,isGenerator,+ rowsFeeding,type CanvasGraph,type CanvasNode,type CanvasNodeData,@@ -64,6 +66,7 @@ export const ICONS: Record<string, LucideIcon> = {AudioWaveform,UserRound,Languages,+ Table,};/** A node type's or template's icon, by lucide name. */@@ -135,8 +138,10 @@ export interface NodeView {counts: Readonly<Record<string, number>>;/** What to fix before it can run (pick a model, add an image…). */error?: string;- /** One run's estimate (null = unknown). */+ /** One run's estimate (null = unknown); every row's, for a node run per row of a table. */costUsd: number | null;+ /** Runs once per row of a table: how many rows. */+ rows?: number;/** Why Run all would run it; null when its result is reused (or it can't run). */step: RunReason | null;reused: boolean;@@ -175,7 +180,7 @@ const sameCounts = (a: Readonly<Record<string, number>>, b: Readonly<Record<stri};const sameView = (a: NodeView, b: NodeView) =>- a.op === b.op && a.error === b.error && a.costUsd === b.costUsd && a.step === b.step && a.reused === b.reused && a.runError === b.runError && a.results === b.results && sameCounts(a.counts, b.counts);+ a.op === b.op && a.error === b.error && a.costUsd === b.costUsd && a.rows === b.rows && a.step === b.step && a.reused === b.reused && a.runError === b.runError && a.results === b.results && sameCounts(a.counts, b.counts);/** What the planner knows about one generator node: its description and the op it runs. */export interface NodeInfo {@@ -205,9 +210,15 @@ 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");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);+ }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);@@ -255,6 +266,7 @@ export function buildViews(counts: counts.get(n.id) ?? EMPTY_VIEW.counts,error: d?.error,costUsd: d?.costUsd ?? null,+ ...(d?.rows && { rows: d.rows }),step: steps.get(n.id) ?? null,reused: reused.has(n.id),runError: runErrors[n.id],diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex 5a28ca1f..a40357af 100644--- a/src/components/canvas/canvas-editor.tsx+++ b/src/components/canvas/canvas-editor.tsx@@ -158,7 +158,7 @@ const typing = (t: EventTarget | null) => !!(t as HTMLElement | null)?.closest?.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", "shape", "text", "comment"]);+const GESTURE_TOOLS = new Set<Tool>(["draw", "erase", "note", "table", "shape", "text", "comment"]);/** Edges whose handles still exist after a model / op change. */function pruneEdges(nodes: FlowNode[], edges: Edge[]): Edge[] {@@ -870,8 +870,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: CanvplaceShape(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") {- addNode(palette.find((p) => p.id === "note")!, start);+ } 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);@@ -959,14 +959,15 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv);// ---- keyboard: ⌘↵ runs (the selection, else everything), ⌘D duplicates, ⌘G groups (⇧⌘G ungroups),- // and the board tools by letter: V H D E N R T C (Escape goes back to Select)+ // and the board tools by letter: V H D E N ⇧T R T C (Escape goes back to Select)useEffect(() => {const onKey = (e: KeyboardEvent) => {const mod = e.metaKey || e.ctrlKey;if (!mod) {if (e.altKey || isMobile || typing(e.target)) return;if (e.key === "Escape") return void setTool("select");- const t = TOOL_KEYS[e.key.toLowerCase()];+ // ⇧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;e.preventDefault();// R again cycles rectangle → ellipse → arrow.diff --git a/src/components/canvas/canvas-list.tsx b/src/components/canvas/canvas-list.tsxindex 265ef5e7..9944d34b 100644--- a/src/components/canvas/canvas-list.tsx+++ b/src/components/canvas/canvas-list.tsx@@ -27,6 +27,7 @@ const BOX = { w: 280, h: 150 };const BOX_COLOR: Partial<Record<CanvasNodeType, string>> = {prompt: "var(--chart-2)",+ table: "var(--chart-2)","image-input": "var(--chart-5)","video-input": "var(--chart-4)","audio-input": "var(--chart-3)",diff --git a/src/components/canvas/node-list.tsx b/src/components/canvas/node-list.tsxindex 7388e4cb..f572b1b5 100644--- a/src/components/canvas/node-list.tsx+++ b/src/components/canvas/node-list.tsx@@ -4,7 +4,7 @@ import { AlertCircle, PinOff, Play, RotateCcw, Sparkles, Square, Upload } from "import Link from "next/link";import { useRef } from "react";import { Button } from "@/components/ui/button";-import { CANVAS_TEXT_MAX, isGenerator, NODE_SPECS, nodeLabel, nodeModel, promptPlaceholder, topoOrder, type CanvasNode } from "@/lib/catalog/canvas";+import { CANVAS_TEXT_MAX, isGenerator, NODE_SPECS, nodeLabel, nodeModel, promptPlaceholder, tableRows, topoOrder, type CanvasNode } from "@/lib/catalog/canvas";import type { MediaKind } from "@/lib/catalog/types";import { fileToSlot } from "@/components/studio/media-slot";import { cn } from "@/lib/utils";@@ -107,6 +107,14 @@ function NodeCard({ node, index }: { node: CanvasNode; index: number }) {/></>)}+ {node.type === "table" && (+ <p className="text-[13px] text-muted-foreground">+ {(() => {+ const rows = tableRows(node);+ return rows.length ? `${rows.length === 1 ? "1 row" : `${rows.length} rows`}: ${rows.map((r) => r.filter(Boolean).join(", ")).join(" · ")}` : "No rows yet: fill the table on the board.";+ })()}+ </p>+ )}{node.type === "element" && (<div className="flex items-center gap-2"><p className="min-w-0 flex-1 truncate font-mono text-[13px] text-brand-text">{node.data.handle ? `@${node.data.handle}` : "No element picked"}</p>diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex 8e4da306..524364e8 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -30,6 +30,7 @@ import {Upload,Volume2,VolumeX,+ Table,X,} from "lucide-react";import Link from "next/link";@@ -90,6 +91,8 @@ import {nodeOps,OPEN_DUB_HINT,OUT,+ TABLE_LIMITS,+ tableRows,outputType,PORT_TYPE_LABEL,PREVIEW_IN,@@ -859,6 +862,11 @@ const GeneratorNode = memo(function GeneratorNode({ id, type: flowType, data, se/>)}{model && !g.readOnly && type !== "concat" && <ModelOptions id={id} model={model} data={data} />}+ {v.rows && (+ <p className="flex items-center gap-1.5 text-[12px] text-muted-foreground">+ <Table className="size-3.5 shrink-0" /> Runs once per table row: {v.rows === 1 ? "1 run" : `${v.rows} runs`}+ </p>+ )}<Results id={id} r={r} />{error && r.state !== "failed" && (<p className={cn("flex items-start gap-1.5 text-[12px] leading-snug", v.runError ? "text-destructive" : "text-warning")}>@@ -930,9 +938,11 @@ interface ClipRow {label: string;/** The clip's file when it's known now: an uploaded clip, or a finished result upstream. */url?: string;+ /** A node run once per table row gives a clip per row (each with this cut and sound). */+ rows?: number;}-const sameRows = (a: ClipRow[], b: ClipRow[]) => a.length === b.length && a.every((x, i) => x.nodeId === b[i].nodeId && x.label === b[i].label && x.url === b[i].url);+const sameRows = (a: ClipRow[], b: ClipRow[]) => a.length === b.length && a.every((x, i) => x.nodeId === b[i].nodeId && x.label === b[i].label && x.url === b[i].url && x.rows === b[i].rows);const selectClipRows = (s: EditorSnapshot, id: string): ClipRow[] => {const n = s.byId.get(id);@@ -940,7 +950,8 @@ const selectClipRows = (s: EditorSnapshot, id: string): ClipRow[] => {return concatClips(s.graph, n).map(({ nodeId }) => {const src = s.byId.get(nodeId);const url = src?.type === "video-input" ? src.data.url : s.views.get(nodeId)?.results.outputs.find((x) => x.o.kind === "video")?.o.url;- return { nodeId, label: src ? nodeLabel(src) : "Clip", ...(url && { url }) };+ const rows = s.views.get(nodeId)?.rows;+ return { nodeId, label: src ? nodeLabel(src) : "Clip", ...(url && !rows && { url }), ...(rows && { rows }) };});};@@ -1016,6 +1027,7 @@ function ClipItem({ id, row, index, count, settings, readOnly, onMove }: { id: s<div className="flex items-center gap-1.5"><span className="grid size-5 shrink-0 place-items-center rounded-full bg-background font-mono text-[10px]">{index + 1}</span><span className="min-w-0 flex-1 truncate text-[12px] font-medium">{row.label}</span>+ {row.rows && <span className="shrink-0 font-mono text-[11px] text-muted-foreground" title="A clip per table row, in row order">× {row.rows} rows</span>}<span className="shrink-0 font-mono text-[11px] text-muted-foreground">{seconds(settings.length)}</span>{!readOnly && (<>@@ -1574,6 +1586,112 @@ const NoteNode = memo(function NoteNode({ id, type, data, selected }: NodeProps<);}, sameNodeProps);+// ---------------------------------------------------------------------------+// Table: rows of words, each row one run of the node it feeds++const TableNode = memo(function TableNode({ id, data, selected }: NodeProps<FlowNode>) {+ const actions = useEditorActions();+ const { readOnly } = useEditorGlobals();+ const columns = data.columns?.length ? data.columns : ["Subject"];+ const rows = data.rows?.length ? data.rows : [[""]];+ const filled = tableRows({ data: { columns, rows } }).length;+ const grid = useRef<HTMLTableSectionElement>(null);+ const setRows = (next: string[][]) => actions.update(id, { columns, rows: next });+ const setCell = (i: number, j: number, v: string) => setRows(rows.map((r, k) => (k === i ? Array.from({ length: columns.length }, (_, c) => (c === j ? v : (r[c] ?? ""))) : r)));+ const addRow = (focus = false) => {+ if (rows.length >= TABLE_LIMITS.rows * 2) return;+ setRows([...rows, columns.map(() => "")]);+ if (focus) requestAnimationFrame(() => grid.current?.querySelector<HTMLInputElement>(`tr:last-child input`)?.focus());+ };+ const addColumn = () => {+ if (columns.length >= TABLE_LIMITS.columns) return;+ actions.update(id, { columns: [...columns, `Column ${columns.length + 1}`], rows: rows.map((r) => [...r, ""]) });+ };+ const removeColumn = (j: number) => actions.update(id, { columns: columns.filter((_, c) => c !== j), rows: rows.map((r) => r.filter((_, c) => c !== j)) });+ const cell = cn("h-7 w-full min-w-0 rounded-md bg-muted px-2 text-[12px] outline-none placeholder:text-subtle-foreground focus:ring-2 focus:ring-brand-faint", NO_DRAG);+ return (+ <NodeShell id={id} type="table" data={data} selected={!!selected} out="text" width={Math.min(560, 120 + columns.length * 150)}>+ <div className="space-y-2 p-3">+ <table className="w-full border-separate border-spacing-1 text-left">+ <thead>+ <tr>+ <th className="w-5" aria-hidden />+ {columns.map((c, j) => (+ <th key={j} scope="col" className="font-normal">+ <div className="flex items-center gap-0.5">+ <input+ value={c}+ readOnly={readOnly}+ maxLength={TABLE_LIMITS.column}+ onChange={(e) => actions.update(id, { columns: columns.map((x, k) => (k === j ? e.target.value : x)), rows })}+ onKeyDown={(e) => e.stopPropagation()}+ aria-label={`Column ${j + 1} name`}+ className={cn(cell, "bg-transparent font-mono text-[11px] font-semibold text-muted-foreground")}+ />+ {!readOnly && columns.length > 1 && (+ <button onClick={() => removeColumn(j)} className={cn("grid size-5 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground", NO_DRAG)} aria-label={`Remove column ${c || j + 1}`}>+ <X className="size-3" />+ </button>+ )}+ </div>+ </th>+ ))}+ <th className="w-5" aria-hidden />+ </tr>+ </thead>+ <tbody ref={grid}>+ {rows.map((r, i) => (+ <tr key={i}>+ <td className="text-center font-mono text-[10px] text-muted-foreground">{i + 1}</td>+ {columns.map((c, j) => (+ <td key={j}>+ <input+ value={r[j] ?? ""}+ readOnly={readOnly}+ maxLength={TABLE_LIMITS.cell}+ onChange={(e) => setCell(i, j, e.target.value)}+ onKeyDown={(e) => {+ // Enter on the last row starts a new one.+ if (e.key === "Enter" && i === rows.length - 1 && !readOnly) addRow(true);+ e.stopPropagation();+ }}+ placeholder={i === 0 ? (c ? `${c}…` : "…") : undefined}+ aria-label={`Row ${i + 1}, ${c || `column ${j + 1}`}`}+ className={cell}+ />+ </td>+ ))}+ <td>+ {!readOnly && rows.length > 1 && (+ <button onClick={() => setRows(rows.filter((_, k) => k !== i))} className={cn("grid size-5 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground", NO_DRAG)} aria-label={`Remove row ${i + 1}`}>+ <X className="size-3" />+ </button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ {!readOnly && (+ <div className="flex flex-wrap gap-1">+ <button className={chip} onClick={() => addRow(true)} disabled={rows.length >= TABLE_LIMITS.rows * 2}>+ <Plus className="size-3" /> Row+ </button>+ <button className={chip} onClick={addColumn} disabled={columns.length >= TABLE_LIMITS.columns}>+ <Plus className="size-3" /> Column+ </button>+ </div>+ )}+ <p className={cn("text-[11px] leading-snug", filled > TABLE_LIMITS.rows ? "text-warning" : "text-muted-foreground")}>+ {filled > TABLE_LIMITS.rows+ ? `${filled} rows: up to ${TABLE_LIMITS.rows} run at once`+ : `${filled === 1 ? "1 filled row" : `${filled} filled rows`}: what this feeds runs once per row. Write {${columns.find((c) => c.trim())?.trim() || "Subject"}} in its prompt to place a cell.`}+ </p>+ </div>+ </NodeShell>+ );+}, sameNodeProps);+export const NODE_TYPES = {prompt: PromptNode,"image-input": MediaInputNode,@@ -1590,6 +1708,7 @@ export const NODE_TYPES = {"clone-voice": CloneVoiceNode,translate: GeneratorNode,concat: GeneratorNode,+ table: TableNode,output: OutputNode,note: NoteNode,...BOARD_NODE_TYPES,diff --git a/src/components/canvas/toolbar.tsx b/src/components/canvas/toolbar.tsxindex d3b791dd..f6fe9fb7 100644--- a/src/components/canvas/toolbar.tsx+++ b/src/components/canvas/toolbar.tsx@@ -1,6 +1,6 @@"use client";-import { ArrowUpRight, Circle, Copy, Eraser, Group, Hand, MessageCircle, MousePointer2, MoreHorizontal, Pencil, Plus, Square, StickyNote, Trash2, Type, type LucideIcon } from "lucide-react";+import { ArrowUpRight, Circle, Copy, Eraser, Group, Hand, MessageCircle, MousePointer2, MoreHorizontal, Pencil, Plus, Square, StickyNote, Table, Trash2, Type, type LucideIcon } from "lucide-react";import { memo, useState } from "react";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Kbd } from "@/components/ui/kbd";@@ -11,8 +11,8 @@ import { useModKey } from "@/lib/keys";import { cn } from "@/lib/utils";import { BOARD_COLOR_VAR, Swatches } from "./board";-/** What a drag or click on the board does (Higgsfield's toolbar: V, H, D, E, N, R, T, C). */-export type Tool = "select" | "hand" | "draw" | "erase" | "note" | "shape" | "text" | "comment";+/** What a drag or click on the board does (Higgsfield's toolbar: V, H, D, E, N, ⇧T, R, T, C). */+export type Tool = "select" | "hand" | "draw" | "erase" | "note" | "table" | "shape" | "text" | "comment";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" };@@ -23,6 +23,7 @@ const TOOLS: { tool: Tool; label: string; key: string; icon: LucideIcon; hint: s{ 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: "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" },@@ -61,7 +62,7 @@ export const BoardToolbar = memo(function BoardToolbar({const active = tool === t.tool;return (<div key={t.tool} className="flex items-center">- {(i === 2 || i === 4 || i === 7) && <span className="mx-0.5 h-5 w-px bg-border" aria-hidden />}+ {(i === 2 || i === 4 || i === 8) && <span className="mx-0.5 h-5 w-px bg-border" aria-hidden />}<Tooltip><TooltipTrigger asChild><buttondiff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex a91a5f1d..019ca5fd 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -56,6 +56,7 @@ export type CanvasNodeType =| "clone-voice"| "translate"| "concat"+ | "table"| "output"| "note";@@ -100,6 +101,9 @@ export interface CanvasNodeData {clips?: Record<string, ClipSettings>;/** Video Concatenator: the clips' order (node ids); clips not listed follow in board order. */order?: string[];+ /** Table: its column names, and its rows of cells (one per column). */+ columns?: string[];+ rows?: string[][];}export interface CanvasNode {@@ -137,6 +141,8 @@ export interface NodeRun {at: number;/** A node made in several steps (Video Concatenator): the generation holding its result. Default: the first id. */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[];}/** The generation a node's result (and what it passes on) is in. */@@ -223,6 +229,7 @@ export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {"clone-voice": { type: "clone-voice", label: "Clone voice", group: "Inputs", icon: "UserRound", description: "A voice sample (or one of your saved voices) to speak with" },translate: { type: "translate", label: "Translate", group: "Utilities", icon: "Languages", ops: ["translate", "dub"], variants: ["text", "video"], description: "Translate a text, or dub a video into another language" },concat: { type: "concat", label: "Video concatenator", group: "Utilities", icon: "Film", ops: ["concat"], description: "Up to 50 clips in one film: trim and mute each, pick the frame" },+ table: { type: "table", label: "Table", group: "Inputs", icon: "Table", description: "Rows of words: what it feeds runs once per row" },output: { type: "output", label: "Output", group: "Output", icon: "MonitorPlay", description: "Preview what's connected, side by side" },note: { type: "note", label: "Sticky note", group: "Output", icon: "StickyNote", description: "A note on the board (not run)" },};@@ -264,6 +271,7 @@ export const PALETTE: PaletteItem[] = [{ ...pick("clone-voice"), id: "clone-voice", keywords: "voice sample clone my voice speaker" },{ ...pick("translate"), id: "translate", data: { mediaKind: "text" }, keywords: "language translate dub localize subtitles" },{ ...pick("concat"), id: "concat", keywords: "concatenate join merge stitch edit trim mute film assemble" },+ { ...pick("table"), id: "table", data: { columns: ["Subject"], rows: [[""], [""], [""]] }, keywords: "rows batch spreadsheet list variations csv grid" },{ ...pick("output"), id: "output", keywords: "preview compare result" },{ ...pick("note"), id: "note", keywords: "comment annotation" },];@@ -555,7 +563,7 @@ const toPortType = (k: MediaKind | undefined): PortType | null => (k === "image"/** The type of a node's output handle (null = no output handle). */export function outputType(_graph: CanvasGraph, n: CanvasNode): PortType | null {- if (n.type === "prompt") return "text";+ if (n.type === "prompt" || n.type === "table") return "text";if (n.type === "clone-voice") return "voice";if (n.type === "element") return "element";if (MEDIA_INPUT_TYPE[n.type]) return MEDIA_INPUT_TYPE[n.type]!;@@ -679,11 +687,19 @@ export function connectionError(graph: CanvasGraph, c: Connection): string | nulif (t.type === "output") {if (c.targetHandle && c.targetHandle !== PREVIEW_IN) return "Unknown input";if (!acceptsType("preview", type)) return "Elements go into a model's Elements input";+ if (s.type === "table") return "A table goes into a node's Text input: that node runs once per row";} else {const port = inputPorts(t).find((p) => p.id === c.targetHandle);if (!port) return `${nodeLabel(t)} has no ${c.targetHandle ?? ""} input`;if (!acceptsType(port, type)) return type === "voice" ? `A voice goes into a Voice input (Text to speech, Change voice)` : `${PORT_TYPE_LABEL[type]} can't go into ${port.label}`;if (t.type === "concat" && graph.edges.filter((e) => e.target === t.id && e.source !== s.id).length >= CONCAT_LIMITS.clips) return `The video concatenator takes up to ${CONCAT_LIMITS.clips} clips`;+ // Rows from a table: one table per node, and Join clips can't take a clip per row (the concatenator can).+ if (graph.nodes.some((n) => n.type === "table")) {+ const withEdge: CanvasGraph = { ...graph, edges: [...graph.edges, { id: "", source: s.id, target: t.id, sourceHandle: OUT, targetHandle: c.targetHandle ?? null }] };+ const rows = rowsFeeding(withEdge, t);+ if (rows && "error" in rows) return rows.error;+ if (rows && t.type === "join") return "Join clips takes one clip per input — the Video concatenator joins a clip per row";+ }}if (ancestors(graph, [s.id]).has(t.id)) return "That would make a loop";return null;@@ -767,10 +783,12 @@ export interface NodeRequest {deps: string[];/** A node made in several steps (Video Concatenator): its jobs in order; the last one holds the result. */steps?: NodeStep[];+ /** A node run once per row of a table: how many rows (its steps are the rows, and every one is a result). */+ rows?: number;}-/** What fills a step's chain slot: an upstream node's result, or an earlier step of the same node. */-export type StepSource = { node: string } | { step: string };+/** What fills a step's chain slot: an upstream node's result (one row of it, for a node run per row), or an earlier step of the same node. */+export type StepSource = { node: string; row?: number } | { step: string };export interface NodeStep {key: string;@@ -790,6 +808,11 @@ export interface NodeDescription extends Partial<NodeRequest> {function sourceOf(graph: CanvasGraph, s: CanvasNode): Source | { error: string } {if (s.type === "prompt") return { kind: "text", text: (s.data.text ?? "").trim() };+ // A table is read row by row (rowRequest); read whole, it is its first row.+ if (s.type === "table") {+ const first = tableRows(s)[0];+ return first ? { kind: "text", text: rowText(first) } : { error: `Fill in a row of “${nodeLabel(s)}”` };+ }if (s.type === "clone-voice") {// A sample wired in wins over the node's own file (a recording, a generated voice).const e = graph.edges.find((x) => x.target === s.id && x.targetHandle === "audio");@@ -866,7 +889,7 @@ function mentionedIn(text: string): Set<string> {return new Set([...text.matchAll(/@([\p{L}\p{N}_-]+)/gu)].map((m) => m[1].toLowerCase()));}-function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeRequest | { error: string } {+function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef, single = false): NodeRequest | { error: string } {const nodes = nodeMap(graph);const ports = inputPorts(n);const ops = nodeOps(n, model);@@ -874,6 +897,12 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeRif (n.type !== "model" && op && !supportsOp(model, op)) return { error: `${model.name} can't do ${OPERATION_LABELS[op].toLowerCase()} — pick another model` };if ((op === "translate" || op === "dub") && !n.data.params?.targetLanguage) return { error: op === "dub" ? "Pick a language to dub into" : "Pick a language to translate into" };if (n.type === "concat") return concatRequest(graph, n, model);+ if (!single) {+ const rows = rowsFeeding(graph, n);+ if (rows && "error" in rows) return rows;+ if (rows && n.type === "join") return { error: `Join clips takes one clip per input — use the Video concatenator to join every row of “${nodeLabel(rows.table)}”` };+ if (rows) return rowRequest(graph, n, model, rows);+ }const inputs: NonNullable<GenerationRequest["inputs"]> = {};const chain: ChainSlot[] = [];@@ -970,6 +999,76 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeRreturn { request, deps };}+// ---------------------------------------------------------------------------+// Tables: the node a table feeds runs once per filled row (and so does every node after it, until a Video+// concatenator joins the rows into one film). "{Column}" in that node's prompt takes the row's cell; otherwise the+// row's cells, joined, are its connected text.++export const TABLE_LIMITS = { rows: 50, columns: 8, cell: 2000, column: 40 } as const;++/** A table's filled rows (a row with at least one cell written), each with one cell per column. */+export function tableRows(t: Pick<CanvasNode, "data">): string[][] {+ const width = Math.max(1, t.data.columns?.length ?? 1);+ return (t.data.rows ?? []).filter((r) => r.some((c) => c?.trim())).map((r) => Array.from({ length: width }, (_, j) => (r[j] ?? "").trim()));+}++const rowText = (cells: string[]) => cells.filter(Boolean).join(", ");++/**+ * 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, 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);+ 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;+ }+ return found;+}++/** One job per row: the table read as that row (its cells in "{Column}", or as connected text), upstream rows matched by number. */+function rowRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef, b: { table: CanvasNode; rows: string[][] }): NodeRequest | { error: string } {+ if (!b.rows.length) return { error: `Fill in a row of “${nodeLabel(b.table)}”` };+ if (b.rows.length > TABLE_LIMITS.rows) return { error: `“${nodeLabel(b.table)}” has ${b.rows.length} rows — up to ${TABLE_LIMITS.rows} run at once` };+ const nodes = nodeMap(graph);+ const columns = (b.table.data.columns ?? []).map((c) => c.trim());+ 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 perRow = (id: string) => {+ const r = rowsFeeding(graph, nodes.get(id)!);+ return !!r && !("error" in r);+ };+ const steps: NodeStep[] = [];+ const deps: string[] = [];+ for (const [i, cells] of b.rows.entries()) {+ const prompt = named ? columns.reduce((p, c, j) => (c ? p.replaceAll(`{${c}}`, cells[j]) : p), own) : own;+ const rowGraph: CanvasGraph = {+ ...graph,+ nodes: graph.nodes.map((x) => (x.id === b.table.id ? { ...x, type: "prompt" as const, data: { text: named ? "" : rowText(cells) } } : x.id === n.id ? { ...x, data: { ...x.data, prompt } } : x)),+ };+ const r = buildRequest(rowGraph, rowGraph.nodes.find((x) => x.id === n.id)!, model, true);+ if ("error" in r) return { error: `Row ${i + 1}: ${r.error}` };+ for (const d of r.deps) if (!deps.includes(d)) deps.push(d);+ steps.push({+ key: `row:${i}`,+ request: { ...r.request, step: { label: `${nodeLabel(n)} · row ${i + 1}`, index: i, of: b.rows.length } },+ from: r.deps.map((d) => (perRow(d) ? { node: d, row: i } : { node: d })),+ });+ }+ return { request: steps[0].request, deps, steps, rows: steps.length };+}+// ---------------------------------------------------------------------------// Video Concatenator: one job per clip step, then the join@@ -1007,10 +1106,14 @@ function clipCut(c: ClipSettings, i: number): { start: number; end?: number } |*/function concatRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): NodeRequest | { error: string } {const engine = model.engine;- const clips = concatClips(graph, n);+ 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 clips = concatClips(graph, n).flatMap((c): { nodeId: string; settings: ClipSettings; row?: number }[] => {+ const rows = rowsFeeding(graph, 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})` };if (clips.length > CONCAT_LIMITS.clips) return { error: `The video concatenator takes up to ${CONCAT_LIMITS.clips} clips — remove ${clips.length - CONCAT_LIMITS.clips}` };- const nodes = nodeMap(graph);const ratio = concatRatio(n.data.params?.aspectRatio);const size = CONCAT_SIZE[ratio];const title = nodeLabel(n);@@ -1039,7 +1142,7 @@ function concatRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef): Nodeconst cut = clipCut(c.settings, i);if ("error" in cut) return cut;const label = (what: string) => ({ label: `${title} · ${what} clip ${i + 1}`, index: i, of: clips.length });- let at: StepSource | { url: string } = src.kind === "media" ? { url: src.url } : { node: src.nodeId };+ 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;if (engine === "open") {at = add(`fit:${i}`, at, {@@ -1285,7 +1388,10 @@ export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPlcontinue;}const prev = runs[id];- const prevStatus = prev ? status(runOutput(prev)) : undefined;+ // A node run per row is as fresh as its weakest row: a failed or trashed row makes it run again.+ 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;if (n.data.pinned) {if (prev && LIVE.has(prevStatus)) {state.set(id, { kind: "reuse", id: runOutput(prev) });@@ -1322,7 +1428,7 @@ export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPlcontinue;}state.set(id, { kind: "run" });- steps.push({ nodeId: id, label, request: d.request, deps: d.deps, ...(d.steps && { steps: d.steps }), reason, costUsd: d.costUsd });+ 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;}@@ -1671,6 +1777,26 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [],),},+ {+ id: "table-film",+ name: "Table → shots → film",+ description: "One row per shot: each row makes a still and animates it, then the concatenator joins every row into one film",+ icon: "Table",+ hue: 160,+ build: tpl(+ [+ { id: "cast", type: "table", x: 0, y: 40, data: { label: "Shots", columns: ["Animal", "Place"], rows: [["red fox", "a snowy pine forest"], ["barn owl", "an old wooden barn at dusk"], ["sea otter", "a kelp forest at sunrise"]] } },+ { id: "still", type: "model", x: COL + 140, y: 0, data: { mediaKind: "image", label: "Still", prompt: "A {Animal} in {Place}, wildlife photography, soft natural light", params: { aspectRatio: "16:9" } }, models: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" } },+ { id: "animate", type: "model", x: COL * 2 + 140, y: 0, data: { mediaKind: "video", label: "Animate", op: "i2v", prompt: "Slow push-in, the animal turns its head", params: { aspectRatio: "16:9", duration: 5 } }, models: { cloud: "kling-2-5-turbo", open: "oss-wan22-14b-fast" } },+ { id: "film", type: "concat", x: COL * 3 + 140, y: 0, data: { label: "Film", params: { aspectRatio: "16:9" } }, models: { cloud: CONCAT_MODELS.cloud, open: CONCAT_MODELS.open } },+ ],+ [+ ["cast", "still", "prompt"],+ ["still", "animate", "images"],+ ["animate", "film", "videos"],+ ],+ ),+ },{id: "clips-film",name: "Clips → one film",diff --git a/src/server/canvas.ts b/src/server/canvas.tsindex 91b1e77e..9f78d6f5 100644--- a/src/server/canvas.ts+++ b/src/server/canvas.ts@@ -18,6 +18,7 @@ import {import {CANVAS_TEXT_MAX as TEXT_MAX,CONCAT_LIMITS,+ TABLE_LIMITS,cleanGraph,concatClips,EMPTY_GRAPH,@@ -93,6 +94,7 @@ const NODE_TYPES = ["clone-voice","translate","concat",+ "table","output","note",] as const satisfies readonly CanvasNodeType[];@@ -154,6 +156,9 @@ const NodeData = z.object({).optional(),order: z.array(z.string().max(80)).max(CONCAT_LIMITS.clips * 2).optional(),+ // 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(),});const Num = z.number().finite();@@ -502,6 +507,8 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {const nodes = nodeMap(graph);const batchId = nanoid(10);const made = new Map<string, string>(plan.reused.map((r) => [r.nodeId, r.generationId]));+ // 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 items: Generation[] = [];const ran: string[] = [];@@ -520,18 +527,34 @@ export function runCanvas(id: string, opts: RunOptions = {}): RunResult | null {const big = oversizedClip(graph, step.nodeId);if (big) throw new Error(big);// A node made in several steps: one pipeline, waiting on the upstream nodes' results like on its own steps.- const existing = Object.fromEntries(step.deps.map((d, k) => [`node:${d}`, depIds[k] as string]));+ const 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]) => {+ if (!("node" in f)) return f.step;+ if (f.row === undefined) return `node:${f.node}`;+ const id = madeRows.get(f.node)?.[f.row];+ if (!id) throw new Error(`Row ${f.row + 1} of “${nodeLabel(nodes.get(f.node)!)}” has no result yet — run it again`);+ 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((f) => ("node" in f ? `node:${f.node}` : f.step)),+ after: st.from.map(at),})),{ batchId, existing },);- const out = pipe.byKey[step.steps[step.steps.length - 1].key];- made.set(step.nodeId, out.id);- runs[step.nodeId] = { sig, ids: pipe.items.map((g) => g.id), out: out.id, at: Date.now() };+ 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);+ 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() };+ } else {+ const out = pipe.byKey[step.steps[step.steps.length - 1].key];+ made.set(step.nodeId, out.id);+ runs[step.nodeId] = { sig, ids: pipe.items.map((g) => g.id), out: out.id, at: Date.now() };+ }items.push(...pipe.items);} else {const created = createGenerations(diff --git a/tests/canvas-plus.test.ts b/tests/canvas-plus.test.tsindex 9f3b6078..846f604e 100644--- a/tests/canvas-plus.test.ts+++ b/tests/canvas-plus.test.ts@@ -335,6 +335,94 @@ describe("board annotations", () => {});});+describe("tables", () => {+ const table = (rows: string[][], columns = ["Animal", "Place"]) => node("t", "table", { label: "Cast", columns, rows });+ const board = (rows: string[][], prompt = "A {Animal} in {Place}, golden hour"): CanvasGraph => ({+ nodes: [+ table(rows),+ node("img", "model", { modelId: "nano-banana-pro", mediaKind: "image", prompt }, 400, 0),+ node("vid", "model", { modelId: "kling-2-5-turbo", mediaKind: "video", op: "i2v", prompt: "slow push-in" }, 800, 0),+ node("film", "concat", { modelId: "join-clips" }, 1200, 0),+ node("solo", "model", { modelId: "nano-banana-pro", mediaKind: "image", prompt: "A lighthouse" }, 400, 600),+ ],+ edges: [edge("t", "img", "prompt"), edge("img", "vid", "images"), edge("vid", "film", "videos")],+ });++ it("a table is text that goes into Text inputs, one table per node, and Join clips can't take its rows", () => {+ const g = board([["fox", "snow"]]);+ expect(outputType(g, g.nodes[0])).toBe("text");+ expect(connectionError(g, { source: "t", target: "solo", targetHandle: "prompt" })).toBeNull();+ expect(connectionError(g, { source: "t", target: "vid", targetHandle: "images" })).toMatch(/Text can't go into/);+ g.nodes.push(node("out", "output", {}, 1600, 0), node("t2", "table", { label: "Other", columns: ["X"], rows: [["a"]] }, 0, 300), node("join", "join", { modelId: "join-clips" }, 1200, 400));+ expect(connectionError(g, { source: "t", target: "out", targetHandle: "in" })).toMatch(/Text input/);+ expect(connectionError(g, { source: "t2", target: "vid", targetHandle: "prompt" })).toMatch(/“Other” and “Cast” both reach “vid”|“Cast” and “Other” both reach/);+ expect(connectionError(g, { source: "vid", target: "join", targetHandle: "videos" })).toMatch(/Video concatenator joins a clip per row/);+ expect(paletteItems("open").find((p) => p.id === "table")!.disabled).toBeUndefined();+ });++ it("the node it feeds runs once per filled row, cells in {Column}; rows carry down the chain into the concatenator", () => {+ const g = board([["fox", "snow"], ["", ""], ["owl", "a barn"]]);+ const img = describeNode(g, g.nodes[1]);+ expect(img.error).toBeUndefined();+ expect(img.rows).toBe(2);+ expect(img.steps!.map((s) => [s.key, s.request.prompt, s.from])).toEqual([+ ["row:0", "A fox in snow, golden hour", []],+ ["row:1", "A owl in a barn, golden hour", []],+ ]);+ const one = describeNode({ ...g, nodes: [table([["fox", "snow"]]), ...g.nodes.slice(1)] }, g.nodes[1]);+ expect(img.costUsd).toBeCloseTo(one.costUsd! * 2, 6);+ // Without a {Column} the row's cells are the connected text.+ const plain = board([["fox", "snow"]], "Studio photo");+ expect(describeNode(plain, plain.nodes[1]).steps![0].request.prompt).toBe("Studio photo\n\nfox, snow");+ // The video after it runs per row too, each row on the image of the same row.+ const vid = describeNode(g, g.nodes[2]);+ expect(vid.rows).toBe(2);+ expect(vid.steps!.map((s) => s.from)).toEqual([[{ node: "img", row: 0 }], [{ node: "img", row: 1 }]]);+ // The concatenator joins a clip per row (and doesn't run per row itself).+ const film = describeNode(g, g.nodes[3]);+ expect(film.rows).toBeUndefined();+ expect(film.steps!.find((s) => s.key === "join")!.from).toHaveLength(2);+ expect(film.steps!.filter((s) => s.key.startsWith("fit:")).map((s) => s.from)).toEqual([[{ node: "vid", row: 0 }], [{ node: "vid", row: 1 }]]);+ // An empty table, and too many rows, say so.+ const empty = board([["", ""]]);+ expect(describeNode(empty, empty.nodes[1]).error).toBe("Fill in a row of “Cast”");+ const big = board(Array.from({ length: 51 }, (_, i) => [`fox ${i}`, "snow"]));+ expect(describeNode(big, big.nodes[1]).error).toMatch(/51 rows — up to 50/);+ // Planned as rows; a run's freshness is its weakest row.+ const plan = planCanvas(g, { targets: ["vid"] });+ expect(plan.steps.map((s) => [s.nodeId, s.rows])).toEqual([+ ["img", 2],+ ["vid", 2],+ ]);+ const runs = { img: { sig: "x", ids: ["a", "b"], rows: ["a", "b"], at: 1 } };+ const fresh = planCanvas(g, { targets: ["img"], runs: { img: { ...runs.img, sig: nodeSignature(img.request!, [], img.steps) } }, status: (id) => (id === "b" ? "failed" : "succeeded") });+ expect(fresh.steps.map((s) => [s.nodeId, s.reason])).toEqual([["img", "failed"]]);+ });++ it("runs every row, and the next node's rows wait for the same rows", async () => {+ const g = board([["fox", "snow"], ["owl", "a barn"]]);+ let res = await list.POST(req("POST", { name: "Table run", graph: { ...g, nodes: g.nodes.filter((n) => n.id !== "film" && n.id !== "solo") } }));+ const c = (await res.json()) as Canvas;+ expect(c.pages[0].graph.nodes.find((n) => n.id === "t")!.data.rows).toEqual([["fox", "snow"], ["owl", "a barn"]]);+ res = await run.POST(req("POST", {}), ctx(c.id));+ expect(res.status).toBe(201);+ const body = (await res.json()) as { ran: string[]; items: Generation[]; canvas: Canvas };+ expect(body.ran).toEqual(["img", "vid"]);+ const img = body.canvas.runs.img;+ const vid = body.canvas.runs.vid;+ expect(img.rows).toHaveLength(2);+ expect(vid.rows).toHaveLength(2);+ expect(img.out).toBeUndefined();+ expect(body.items.filter((x) => img.rows!.includes(x.id)).map((x) => x.prompt)).toEqual(["A fox in snow, golden hour", "A owl in a barn, golden hour"]);+ const deps = (id: string) => (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;+ expect(vid.rows!.map(deps)).toEqual(img.rows);+ for (const id of vid.rows!) expect((await settle(id)).status).toBe("succeeded");+ // Fresh now: nothing runs again.+ res = await run.POST(req("POST", {}), ctx(c.id));+ expect(((await res.json()) as { ran: string[] }).ran).toEqual([]);+ }, 60_000);+});+describe("pages", () => {it("an older row's board reads as page 1; a page copy gets new ids everywhere", () => {const legacy = { nodes: [node("p", "prompt", { text: "x" })], edges: [], viewport: { x: 1, y: 2, zoom: 1 } };