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 editor: per-node store, shared live stream, save on leave, keyboard menus

Claude2e7cdfbec5fd
diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsx
index bf5c0caf..4a0439cc 100644
--- a/src/components/canvas/canvas-context.tsx
+++ b/src/components/canvas/canvas-context.tsx
@@ -21,9 +21,9 @@ import {
ZoomIn,
type LucideIcon,
} from "lucide-react";
-import { createContext, useContext } from "react";
-import type { CanvasGraph, CanvasNodeData, CanvasPlan, NodeDescription, PortType } from "@/lib/catalog/canvas";
-import type { Engine, Generation, GenerationStatus, ModelDef, OutputFile } from "@/lib/catalog/types";
+import { createContext, useContext, useMemo, useSyncExternalStore } from "react";
+import { effectiveOp, isGenerator, type CanvasGraph, type CanvasNode, type CanvasNodeData, type CanvasPlan, type Connection, type NodeDescription, type PortType, type RunReason } from "@/lib/catalog/canvas";
+import type { Engine, Generation, GenerationStatus, ModelDef, Operation, OutputFile } from "@/lib/catalog/types";
import type { EngineMode } from "@/lib/api";
export const ICONS: Record<string, LucideIcon> = {
@@ -94,21 +94,138 @@ export function foldResults(gens: Generation[]): NodeResults {
};
}
-export interface EditorApi {
+/** The same results object when the node's generations are the very same objects (memoized nodes skip a render). */
+export function foldResultsKeep(prev: NodeResults | undefined, gens: Generation[]): NodeResults {
+ if (prev && prev.gens.length === gens.length && prev.gens.every((g, i) => g === gens[i])) return prev;
+ return foldResults(gens);
+}
+
+// ---------------------------------------------------------------------------
+// The editor's state, as nodes read it.
+//
+// Every node subscribes to the slice it shows (its own NodeView, a few globals) instead of one
+// context object that changes on every keystroke: editing node A re-renders A, not the board.
+
+/** Everything a generator node shows that depends on the rest of the board. */
+export interface NodeView {
+ /** The op it runs (an Auto model node's inferred op, a utility's fixed op). */
+ op?: Operation;
+ /** Edges into each input handle, e.g. { prompt: 1, images: 2 }. */
+ 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). */
+ costUsd: number | null;
+ /** Why Run all would run it; null when its result is reused (or it can't run). */
+ step: RunReason | null;
+ reused: boolean;
+ /** The server's error for this node from the last run. */
+ runError?: string;
+ results: NodeResults;
+}
+
+export const EMPTY_VIEW: NodeView = { counts: {}, costUsd: null, step: null, reused: false, results: EMPTY_RESULTS };
+
+/** Board-wide settings the nodes read (they change rarely). */
+export interface EditorGlobals {
canvasId: string;
- graph: CanvasGraph;
- plan: CanvasPlan;
- describe: (id: string) => NodeDescription | undefined;
- results: (id: string) => NodeResults;
- /** Errors the server gave the last run, per node. */
- runErrors: Record<string, string>;
engine: Engine;
mode: EngineMode;
/** Phone: pan, zoom and tap only. */
readOnly: boolean;
+ /** A run request is in flight. */
running: boolean;
/** True when this model would run on the demo provider (no key / no ComfyUI). */
isDemo: (m: ModelDef) => boolean;
+}
+
+export interface EditorSnapshot {
+ /** The board as it is now. */
+ graph: CanvasGraph;
+ byId: ReadonlyMap<string, CanvasNode>;
+ plan: CanvasPlan;
+ views: ReadonlyMap<string, NodeView>;
+ globals: EditorGlobals;
+}
+
+const sameCounts = (a: Readonly<Record<string, number>>, b: Readonly<Record<string, number>>) => {
+ const ka = Object.keys(a);
+ return ka.length === Object.keys(b).length && ka.every((k) => a[k] === b[k]);
+};
+
+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);
+
+/**
+ * One NodeView per generator node, keeping the previous object whenever nothing it shows changed
+ * (so its memoized node doesn't re-render).
+ */
+export function buildViews(
+ prev: ReadonlyMap<string, NodeView> | null,
+ graph: CanvasGraph,
+ plan: CanvasPlan,
+ describe: (id: string) => NodeDescription | undefined,
+ results: ReadonlyMap<string, NodeResults>,
+ runErrors: Record<string, string>,
+): Map<string, NodeView> {
+ const counts = new Map<string, Record<string, number>>();
+ for (const e of graph.edges) {
+ if (!e.targetHandle) continue;
+ const c = counts.get(e.target) ?? {};
+ c[e.targetHandle] = (c[e.targetHandle] ?? 0) + 1;
+ counts.set(e.target, c);
+ }
+ const steps = new Map(plan.steps.map((s) => [s.nodeId, s.reason]));
+ const reused = new Set(plan.reused.map((r) => r.nodeId));
+ const out = new Map<string, NodeView>();
+ for (const n of graph.nodes) {
+ if (!isGenerator(n)) continue;
+ const d = describe(n.id);
+ const next: NodeView = {
+ op: effectiveOp(graph, n),
+ counts: counts.get(n.id) ?? EMPTY_VIEW.counts,
+ error: d?.error,
+ costUsd: d?.costUsd ?? null,
+ step: steps.get(n.id) ?? null,
+ reused: reused.has(n.id),
+ runError: runErrors[n.id],
+ results: results.get(n.id) ?? EMPTY_RESULTS,
+ };
+ const old = prev?.get(n.id);
+ out.set(n.id, old && sameView(old, next) ? old : next);
+ }
+ return out;
+}
+
+/**
+ * A tiny external store: the editor publishes a snapshot after each commit, nodes select from it.
+ * The editor also peeks at the last snapshot to keep unchanged NodeViews (and results) identical.
+ */
+export class EditorStore {
+ private snap: EditorSnapshot | null = null;
+ private listeners = new Set<() => void>();
+ get = (): EditorSnapshot => this.snap!;
+ /** The last published snapshot (null before the first render). */
+ peek(): EditorSnapshot | null {
+ return this.snap;
+ }
+ /** The first render's snapshot, so the nodes' first render reads real values (nobody listens yet). */
+ prime(first: EditorSnapshot) {
+ if (!this.snap) this.snap = first;
+ }
+ set(next: EditorSnapshot) {
+ if (next === this.snap) return;
+ this.snap = next;
+ this.listeners.forEach((l) => l());
+ }
+ subscribe = (l: () => void) => {
+ this.listeners.add(l);
+ return () => void this.listeners.delete(l);
+ };
+}
+
+/** What nodes can do to the board. The object never changes, so it never re-renders a node. */
+export interface EditorActions {
update: (id: string, patch: Partial<CanvasNodeData>) => void;
remove: (id: string) => void;
duplicate: (id: string) => void;
@@ -117,12 +234,71 @@ export interface EditorApi {
open: (id: string, index?: number) => void;
/** Add an input node holding this node's first output, wired nowhere yet. */
toInput: (id: string) => void;
+ /** Draw an edge (the keyboard's "Connect output to…"). */
+ connect: (c: Connection) => void;
+ /** Remove an edge (the keyboard's "Disconnect"). */
+ disconnect: (edgeId: string) => void;
+ /** The board right now, read in event handlers and menus (not a subscription). */
+ getGraph: () => CanvasGraph;
+}
+
+export const EditorStoreContext = createContext<EditorStore | null>(null);
+export const EditorActionsContext = createContext<EditorActions | null>(null);
+
+function useStore(): EditorStore {
+ const s = useContext(EditorStoreContext);
+ if (!s) throw new Error("Canvas node outside the editor");
+ return s;
+}
+
+export function useEditorActions(): EditorActions {
+ const a = useContext(EditorActionsContext);
+ if (!a) throw new Error("Canvas node outside the editor");
+ return a;
+}
+
+/**
+ * Select a slice of the editor's state. The component re-renders only when the slice changes
+ * (by `isEqual`). `key` is the selector's only input besides the snapshot (a node id).
+ */
+export function useEditorSelector<T>(selector: (s: EditorSnapshot, key: string) => T, key: string, isEqual: (a: T, b: T) => boolean = Object.is): T {
+ const store = useStore();
+ // The selector and isEqual are module-level functions in practice; what changes is the key.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const getSnapshot = useMemo(() => cachedSelector(store, selector, key, isEqual), [store, key]);
+ return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
}
-export const EditorContext = createContext<EditorApi | null>(null);
+/** getSnapshot for useSyncExternalStore: the same value until the slice really changes. */
+function cachedSelector<T>(store: EditorStore, selector: (s: EditorSnapshot, key: string) => T, key: string, isEqual: (a: T, b: T) => boolean): () => T {
+ let last: { snap: EditorSnapshot; value: T } | null = null;
+ return () => {
+ const snap = store.get();
+ if (last && last.snap === snap) return last.value;
+ const value = selector(snap, key);
+ last = { snap, value: last && isEqual(last.value, value) ? last.value : value };
+ return last.value;
+ };
+}
+
+const selectView = (s: EditorSnapshot, id: string) => s.views.get(id) ?? EMPTY_VIEW;
+const selectResults = (s: EditorSnapshot, id: string) => s.views.get(id)?.results ?? EMPTY_RESULTS;
+const selectGlobals = (s: EditorSnapshot) => s.globals;
+const selectAll = (s: EditorSnapshot) => s;
+
+export function useNodeView(id: string): NodeView {
+ return useEditorSelector(selectView, id);
+}
+
+export function useNodeResults(id: string): NodeResults {
+ return useEditorSelector(selectResults, id);
+}
+
+export function useEditorGlobals(): EditorGlobals {
+ return useEditorSelector(selectGlobals, "");
+}
-export function useEditor(): EditorApi {
- const v = useContext(EditorContext);
- if (!v) throw new Error("useEditor outside the canvas editor");
- return v;
+/** The whole snapshot (the phone's node list, which shows everything anyway). */
+export function useEditorSnapshot(): EditorSnapshot {
+ return useEditorSelector(selectAll, "");
}
diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsx
index 48fd15ec..c2af8958 100644
--- a/src/components/canvas/canvas-editor.tsx
+++ b/src/components/canvas/canvas-editor.tsx
@@ -27,7 +27,7 @@ import {
import { ChevronDown, ChevronLeft, Check, Cloud, Cpu, LayoutGrid, List, Loader2, Play, RotateCcw, Sparkles, TriangleAlert } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
-import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { memo, useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
@@ -40,15 +40,17 @@ import { EngineSwitch } from "@/components/studio/engine-switch";
import { fileToSlot } from "@/components/studio/media-slot";
import { Viewer } from "@/components/studio/viewer";
import { useIsMobile } from "@/hooks/use-mobile";
-import { useEngine, useStatus } from "@/lib/api";
+import { useEngine, useStatus, type EngineMode } from "@/lib/api";
import { getModel } from "@/lib/catalog";
import {
acceptsType,
cleanGraph,
connectionError,
convertEngine,
+ counterpart,
defaultModelForNode,
describeNode,
+ EMPTY_GRAPH,
graphEngine,
inputPorts,
isGenerator,
@@ -72,15 +74,31 @@ import {
import type { Engine, MediaKind, ModelDef } from "@/lib/catalog/types";
import { formatCost } from "@/lib/format";
import { cn } from "@/lib/utils";
-import { EditorContext, EMPTY_RESULTS, foldResults, PORT_COLOR, type EditorApi, type NodeResults } from "./canvas-context";
+import {
+ buildViews,
+ EditorActionsContext,
+ EditorStore,
+ EditorStoreContext,
+ foldResultsKeep,
+ PORT_COLOR,
+ type EditorActions,
+ type EditorGlobals,
+ type EditorSnapshot,
+ type NodeResults,
+} from "./canvas-context";
import { NodeList } from "./node-list";
import { NODE_TYPES, type FlowNode } from "./nodes";
import { AddMenu, DRAG_TYPE, Palette, PaletteToggle } from "./palette";
-import { saveCanvas, useCanvasView, useLiveGenerations, useRunCanvas, type CanvasView } from "./use-canvas";
+import { saveCanvas, useCanvasView, useRunCanvas, type CanvasView } from "./use-canvas";
const GRID: [number, number] = [16, 16];
const snap = (p: { x: number; y: number }) => ({ x: Math.round(p.x / GRID[0]) * GRID[0], y: Math.round(p.y / GRID[1]) * GRID[1] });
+/** Palette width plus its margin: the board's fit leaves this side free while the palette is open. */
+const PALETTE_SPACE = 292;
+/** Below this zoom a board's text is too small to read with the palette open: the first fit hides the palette instead. */
+const READABLE_ZOOM = 0.5;
+
const toFlowNode = (n: CanvasNode): FlowNode => ({ id: n.id, type: n.type, position: n.position, data: n.data, ...(n.type === "output" && n.width ? { width: n.width } : {}) });
const toFlowEdge = (e: CanvasEdge): Edge => ({ id: e.id, source: e.source, target: e.target, sourceHandle: e.sourceHandle ?? OUT, targetHandle: e.targetHandle ?? null });
@@ -104,13 +122,15 @@ function pruneEdges(nodes: FlowNode[], edges: Edge[]): Edge[] {
return edges.filter((e) => keep.has(e.id));
}
+/** What a node's output handle carries (no graph walk: the node alone decides). */
+const typeOfNode = (n: Pick<FlowNode, "id" | "type" | "data">): PortType | null => outputType(EMPTY_GRAPH, { id: n.id, type: n.type as CanvasNode["type"], data: n.data, position: { x: 0, y: 0 } });
+
const KIND_INPUT: Record<string, CanvasNode["type"]> = { image: "image-input", video: "video-input", audio: "audio-input" };
// ---------------------------------------------------------------------------
export function CanvasEditor({ id }: { id: string }) {
- const live = useLiveGenerations(id);
- const view = useCanvasView(id, live);
+ const view = useCanvasView(id);
if (view.isLoading) return <EditorSkeleton />;
if (!view.data) {
return (
@@ -171,6 +191,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const [engine, setEngine, mode] = useEngine();
const status = useStatus().data;
const runM = useRunCanvas(id);
+ const runMutate = runM.mutate;
const [nodes, setNodes] = useState<FlowNode[]>(() => initial.graph.nodes.map(toFlowNode));
const [edges, setEdges] = useState<Edge[]>(() => initial.graph.edges.map(toFlowEdge));
@@ -181,21 +202,27 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const [viewer, setViewer] = useState<{ nodeId: string; index: number } | null>(null);
const [runErrors, setRunErrors] = useState<Record<string, string>>({});
const [saveState, setSaveState] = useState<SaveState>("saved");
+ /** A save the server refused (a 4xx): retrying won't help, the next edit tries again. */
+ const [saveRefused, setSaveRefused] = useState(false);
const [rev, setRev] = useState(0);
const wrapper = useRef<HTMLDivElement>(null);
const viewport = useRef<Viewport | undefined>(initial.graph.viewport);
const savedRev = useRef(0);
+ const savedName = useRef(initial.name);
- // Latest state for event handlers (synced right after each commit).
- const latest = useRef({ nodes, edges });
+ // Latest state for event handlers and the save on leave (synced right after each commit).
+ const latest = useRef({ nodes, edges, rev });
useLayoutEffect(() => {
- latest.current = { nodes, edges };
- }, [nodes, edges]);
+ latest.current = { nodes, edges, rev };
+ }, [nodes, edges, rev]);
const touch = useCallback(() => setRev((r) => r + 1), []);
- // ---- derived: graph, plan, results
+ // ---- derived: graph, plan, results, and the per-node views the nodes subscribe to
+ const [store] = useState(() => new EditorStore());
+ const prev = store.peek();
const graph = useMemo(() => toGraph(nodes, edges), [nodes, edges]);
+ const byId = useMemo(() => new Map(graph.nodes.map((n) => [n.id, n])), [graph]);
const planned = useDeferredValue(graph);
const runs = view.canvas.runs;
const gens = useMemo(() => new Map(view.generations.map((g) => [g.id, g])), [view.generations]);
@@ -208,29 +235,23 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
}, [planned, mode]);
const results = useMemo(() => {
const m = new Map<string, NodeResults>();
- for (const [nodeId, r] of Object.entries(runs)) m.set(nodeId, foldResults(r.ids.map((g) => gens.get(g)).filter((g): g is NonNullable<typeof g> => !!g)));
+ for (const [nodeId, r] of Object.entries(runs)) {
+ const list = r.ids.map((g) => gens.get(g)).filter((g): g is NonNullable<typeof g> => !!g);
+ m.set(nodeId, foldResultsKeep(prev?.views.get(nodeId)?.results, list));
+ }
return m;
+ // `prev` only lends unchanged objects (identity), it isn't an input.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [runs, gens]);
+ const views = useMemo(
+ () => buildViews(prev?.views ?? null, planned, plan, (nid) => descriptions.get(nid), results, runErrors),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [planned, plan, descriptions, results, runErrors],
+ );
const selected = useMemo(() => nodes.filter((n) => n.selected).map((n) => n.id), [nodes]);
const busy = [...results.values()].filter((r) => r.state === "running" || r.state === "queued").length;
const generators = graph.nodes.filter(isGenerator);
- // Fit around the nodes, leaving the palette's side free.
- const fitOptions = useMemo<FitViewOptions<FlowNode>>(
- () => ({ padding: { top: "56px", right: "56px", bottom: "56px", left: paletteOpen && !isMobile ? "292px" : isMobile ? "16px" : "56px" }, maxZoom: 1, minZoom: isMobile ? 0.3 : 0.5 }),
- [paletteOpen, isMobile],
- );
- // Phones always start fitted (a viewport saved on a big screen would show an empty board).
- const savedViewport = isMobile ? undefined : initial.graph.viewport;
- // Fit once every node has its size (React Flow's own fitView can run after the first few only).
- const initialized = useNodesInitialized();
- const fitted = useRef(false);
- useEffect(() => {
- if (!initialized || fitted.current) return;
- fitted.current = true;
- if (!savedViewport && latest.current.nodes.length) void rf.fitView(fitOptions);
- }, [initialized, savedViewport, rf, fitOptions]);
-
const isDemo = useCallback(
(m: ModelDef) => {
if (!status) return false;
@@ -240,56 +261,116 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
},
[status],
);
+ const globals = useMemo<EditorGlobals>(() => ({ canvasId: id, engine, mode, readOnly: isMobile, running: runM.isPending, isDemo }), [id, engine, mode, isMobile, runM.isPending, isDemo]);
+ const snapshot = useMemo<EditorSnapshot>(() => ({ graph, byId, plan, views, globals }), [graph, byId, plan, views, globals]);
+ store.prime(snapshot);
+ useLayoutEffect(() => store.set(snapshot), [store, snapshot]);
+
+ // Fit around the nodes, leaving the palette's side free.
+ const fitFor = useCallback(
+ (withPalette: boolean): FitViewOptions<FlowNode> => ({
+ padding: { top: "56px", right: "56px", bottom: "56px", left: withPalette && !isMobile ? `${PALETTE_SPACE}px` : isMobile ? "16px" : "56px" },
+ maxZoom: 1,
+ minZoom: isMobile ? 0.3 : 0.5,
+ }),
+ [isMobile],
+ );
+ const fitOptions = useMemo(() => fitFor(paletteOpen), [fitFor, paletteOpen]);
+ // Phones always start fitted (a viewport saved on a big screen would show an empty board).
+ const savedViewport = isMobile ? undefined : initial.graph.viewport;
+ // The first fit, once every node has its size: a big board may zoom further out than later fits,
+ // and when it would be too small to read beside the palette, the palette folds away instead.
+ const initialized = useNodesInitialized();
+ const fitted = useRef(false);
+ useEffect(() => {
+ if (!initialized || fitted.current) return;
+ fitted.current = true;
+ if (savedViewport || !latest.current.nodes.length) return;
+ const frame = requestAnimationFrame(() => {
+ const rect = wrapper.current?.getBoundingClientRect();
+ let withPalette = paletteOpen && !isMobile;
+ if (withPalette && rect) {
+ const b = rf.getNodesBounds(latest.current.nodes);
+ const zoom = Math.min((rect.width - PALETTE_SPACE - 56) / Math.max(1, b.width), (rect.height - 112) / Math.max(1, b.height));
+ if (zoom < READABLE_ZOOM) {
+ withPalette = false;
+ setPaletteOpen(false);
+ }
+ }
+ void rf.fitView({ ...fitFor(withPalette), minZoom: isMobile ? 0.15 : 0.3 });
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [initialized, savedViewport, rf, fitFor, paletteOpen, isMobile]);
// ---- autosave
const save = useCallback(
async (keepalive = false) => {
- const at = rev;
+ const at = latest.current.rev;
if (at === savedRev.current) return;
setSaveState("saving");
try {
await saveCanvas(id, { graph: toGraph(latest.current.nodes, latest.current.edges, viewport.current) }, keepalive);
savedRev.current = Math.max(savedRev.current, at);
setSaveState("saved");
+ setSaveRefused(false);
void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });
- } catch {
+ } catch (e) {
setSaveState("error");
+ const code = (e as { status?: number }).status;
+ if (code && code >= 400 && code < 500) {
+ // Retrying the same board won't help: say what's wrong (the server names the node).
+ setSaveRefused(true);
+ toast.error((e as Error).message, { id: `canvas-save-${id}` });
+ }
}
},
- [id, rev, qc],
+ [id, qc],
);
useEffect(() => {
if (rev === 0) return;
const t = setTimeout(() => void save(), 700);
return () => clearTimeout(t);
}, [rev, save]);
- // Retry a failed save, and flush when the tab is hidden or closed.
+ // Retry a failed save (a network blip, a restart), and flush when the tab is hidden or closed.
useEffect(() => {
- if (saveState !== "error") return;
+ if (saveState !== "error" || saveRefused) return;
const t = setTimeout(() => void save(), 4000);
return () => clearTimeout(t);
- }, [saveState, save]);
+ }, [saveState, saveRefused, save]);
useEffect(() => {
const flush = () => {
if (document.visibilityState === "hidden") void save(true);
};
// Leaving with unsaved edits: send them with keepalive (no "leave site?" prompt).
- const leave = () => {
- if (rev !== savedRev.current) void save(true);
- };
+ const leave = () => void save(true);
document.addEventListener("visibilitychange", flush);
window.addEventListener("beforeunload", leave);
return () => {
document.removeEventListener("visibilitychange", flush);
window.removeEventListener("beforeunload", leave);
};
- }, [save, rev]);
+ }, [save]);
+ // Leaving through an in-app link (the page unmounts, or Next hides it): send what the debounce still holds.
+ const flushOnLeave = useCallback(() => {
+ const at = latest.current.rev;
+ if (at === savedRev.current) return;
+ savedRev.current = at;
+ void saveCanvas(id, { graph: toGraph(latest.current.nodes, latest.current.edges, viewport.current) }, true)
+ .then(() => qc.invalidateQueries({ queryKey: ["canvases"], exact: true }))
+ .catch(() => {
+ // Not saved after all: the next edit (or the next visit) saves again.
+ savedRev.current = -1;
+ });
+ }, [id, qc]);
+ useEffect(() => flushOnLeave, [flushOnLeave]);
const rename = async (next: string) => {
const v = next.trim();
- if (!v || v === initial.name) return setName(v || initial.name);
+ if (!v) return setName(savedName.current);
+ if (v === savedName.current) return;
try {
await saveCanvas(id, { name: v });
+ savedName.current = v;
void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });
} catch (e) {
toast.error((e as Error).message);
@@ -341,14 +422,24 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
[touch, offerUndo],
);
+ /** Copies of the nodes, wired to each other the way the originals are. */
const duplicate = useCallback(
(ids: string | string[]) => {
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) => ({ ...n, id: newId(n.type ?? "node"), position: { x: n.position.x + 48, y: n.position.y + 48 }, data: { ...n.data, pinned: undefined }, selected: true }));
+ .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 };
+ });
if (!copies.length) return;
+ const wires = latest.current.edges
+ .filter((e) => map.has(e.source) && map.has(e.target))
+ .map((e) => ({ ...e, id: newId("e"), source: map.get(e.source)!, target: map.get(e.target)!, selected: false }));
setNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })), ...copies]);
+ if (wires.length) setEdges((es) => [...es, ...wires]);
touch();
},
[touch],
@@ -356,9 +447,11 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const addNode = useCallback(
(item: PaletteItem, at: { x: number; y: number }, connect?: MenuState["connect"]) => {
+ if (item.disabled) return void toast(item.disabled);
const data: CanvasNodeData = { ...item.data };
if (isGenerator({ type: item.type })) {
- const m = defaultModelForNode({ type: item.type, data }, engine) ?? defaultModelForNode({ type: item.type, data }, engine === "open" ? "cloud" : "open");
+ // An install locked to one engine never gets a node on the other.
+ const m = defaultModelForNode({ type: item.type, data }, engine) ?? (mode === "both" ? defaultModelForNode({ type: item.type, data }, engine === "open" ? "cloud" : "open") : undefined);
if (m) data.modelId = m.id;
}
const node: FlowNode = { id: newId(item.type), type: item.type, position: snap(at), data, selected: true };
@@ -376,7 +469,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
touch();
return node.id;
},
- [engine, touch],
+ [engine, mode, touch],
);
const onNodesChange = useCallback(
@@ -408,6 +501,13 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
},
[touch],
);
+ const disconnect = useCallback(
+ (edgeId: string) => {
+ setEdges((es) => es.filter((e) => e.id !== edgeId));
+ touch();
+ },
+ [touch],
+ );
const openMenuAt = useCallback(
(clientX: number, clientY: number, connect?: MenuState["connect"]) => {
@@ -436,11 +536,11 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
[openMenuAt],
);
+ const palette = useMemo(() => paletteItems(mode), [mode]);
const menuItems = useMemo(() => {
- const all = paletteItems();
const c = menu?.connect;
- if (!c) return all;
- return all.filter((p) => {
+ if (!c) return palette;
+ return palette.filter((p) => {
const data: CanvasNodeData = { ...p.data };
const m = isGenerator({ type: p.type }) ? defaultModelForNode({ type: p.type, data }, engine) : undefined;
if (m) data.modelId = m.id;
@@ -448,19 +548,20 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
if (c.from === "source") return p.type === "output" ? c.type !== "element" : inputPorts(n).some((port) => acceptsType(port, c.type));
return outputType({ nodes: [n], edges: [] }, n) === c.type;
});
- }, [menu, engine]);
+ }, [menu, engine, palette]);
// ---- running
const run = useCallback(
(targets?: string[], force?: boolean) => {
- const go = (t?: string[], f?: boolean) =>
- runM.mutate(
+ const go = (t?: string[], f?: boolean) => {
+ const at = latest.current.rev;
+ runMutate(
{ targets: t, force: f, graph: toGraph(latest.current.nodes, latest.current.edges, viewport.current) },
{
onSuccess: (r) => {
// The run saved the board too.
- savedRev.current = rev;
- setSaveState("saved");
+ 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;
@@ -470,9 +571,10 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
onError: (e) => toast.error((e as Error).message),
},
);
+ };
go(targets, force);
},
- [runM, rev],
+ [runMutate],
);
const cancel = useCallback(
@@ -487,31 +589,28 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
[runs, gens, qc, id],
);
- const toInput = useCallback(
- (nodeId: string) => {
- 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 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 },
- ]);
- touch();
- toast("Added as an input — connect it anywhere");
- },
- [results, touch],
- );
+ const toInput = (nodeId: string) => {
+ 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 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 },
+ ]);
+ touch();
+ toast("Added as an input — connect it anywhere");
+ };
// ---- engine
const boardEngine = graphEngine(graph) ?? engine;
const switchEngine = (e: Engine) => {
setEngine(e);
- const before = latest.current.nodes;
- const { graph: next, changed, missing } = convertEngine(toGraph(before, latest.current.edges), e);
+ const before = latest.current;
+ const { graph: next, changed, missing } = convertEngine(toGraph(before.nodes, before.edges), e);
if (changed) {
- const byId = new Map(next.nodes.map((n) => [n.id, n]));
- const after = before.map((n) => ({ ...n, data: byId.get(n.id)?.data ?? n.data }));
+ 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 }));
setNodes(after);
setEdges((es) => pruneEdges(after, es));
touch();
@@ -519,7 +618,9 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
action: {
label: "Undo",
onClick: () => {
- setNodes(before);
+ // 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();
},
},
@@ -527,10 +628,47 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
}
if (missing.length) toast(`${missing.length} node${missing.length > 1 ? "s have" : " has"} no ${e === "open" ? "open-source" : "cloud"} version yet`);
};
- const offEngine = mode === "both" ? [] : generators.filter((n) => {
- const m = n.data.modelId ? getModel(n.data.modelId) : undefined;
- return m && m.engine !== mode;
+ const offEngine =
+ mode === "both"
+ ? []
+ : generators.filter((n) => {
+ const m = n.data.modelId ? getModel(n.data.modelId) : undefined;
+ return m && m.engine !== mode;
+ });
+ const stuck = offEngine.filter((n) => !counterpart(graph, n, mode as Engine));
+ const switchable = offEngine.length - stuck.length;
+
+ // ---- the actions nodes call: one object for the editor's lifetime, always reaching the latest handlers
+ const handlers = useRef<EditorActions | null>(null);
+ useLayoutEffect(() => {
+ handlers.current = {
+ update,
+ remove,
+ duplicate,
+ run,
+ cancel: (nid) => void cancel(nid),
+ open: (nid, index = 0) => setViewer({ nodeId: nid, index }),
+ toInput,
+ 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),
+ };
});
+ const actions = useMemo<EditorActions>(
+ () => ({
+ update: (...a) => handlers.current!.update(...a),
+ remove: (...a) => handlers.current!.remove(...a),
+ duplicate: (...a) => handlers.current!.duplicate(...a),
+ run: (...a) => handlers.current!.run(...a),
+ cancel: (...a) => handlers.current!.cancel(...a),
+ open: (...a) => handlers.current!.open(...a),
+ toInput: (...a) => handlers.current!.toInput(...a),
+ connect: (...a) => handlers.current!.connect(...a),
+ disconnect: (...a) => handlers.current!.disconnect(...a),
+ getGraph: () => handlers.current!.getGraph(),
+ }),
+ [],
+ );
// ---- keyboard: ⌘↵ runs (the selection, else everything), ⌘D duplicates
useEffect(() => {
@@ -540,7 +678,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);
- run(sel.length ? sel : undefined, e.shiftKey);
+ actions.run(sel.length ? sel : undefined, 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;
@@ -550,7 +688,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [run, duplicate]);
+ }, [actions, duplicate]);
// ---- drop from the palette, or files from the desktop
const onDragOver = (e: React.DragEvent) => {
@@ -565,7 +703,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
const at = rf.screenToFlowPosition({ x: e.clientX, y: e.clientY });
if (itemId) {
e.preventDefault();
- const item = paletteItems().find((p) => p.id === itemId);
+ const item = palette.find((p) => p.id === itemId);
if (item) addNode(item, at);
return;
}
@@ -575,9 +713,9 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
files.slice(0, 8).forEach((f, i) => {
const kind: MediaKind | null = f.type.startsWith("image/") ? "image" : f.type.startsWith("video/") ? "video" : f.type.startsWith("audio/") ? "audio" : null;
if (!kind) return void toast.error(`${f.name} isn't an image, video or audio file`);
- const item = paletteItems().find((p) => p.type === KIND_INPUT[kind])!;
+ const item = palette.find((p) => p.type === KIND_INPUT[kind])!;
const nid = addNode(item, { x: at.x + i * 32, y: at.y + i * 32 });
- void fileToSlot(f, (v) => v && !v.uploading && update(nid, { url: v.ref, name: v.name }), kind);
+ if (nid) void fileToSlot(f, (v) => v && !v.uploading && update(nid, { url: v.ref, name: v.name }), kind);
});
};
@@ -587,50 +725,46 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
addNode(item, at);
};
+ /** Text prompt → image model → Output, wired (no dragging needed, so phones get it too). */
const quickStart = () => {
const rect = wrapper.current?.getBoundingClientRect();
// Right of the palette, a little below the top.
- const at = rf.screenToFlowPosition({ x: (rect?.left ?? 0) + (paletteOpen ? 300 : 80), y: (rect?.top ?? 0) + 160 });
+ const at = rf.screenToFlowPosition({ x: (rect?.left ?? 0) + (isMobile ? 16 : paletteOpen ? 300 : 80), y: (rect?.top ?? 0) + 160 });
const items = paletteItems();
const p = addNode(items.find((i) => i.id === "prompt")!, at);
const m = addNode(items.find((i) => i.id === "model-image")!, { x: at.x + 360, y: at.y - 40 });
const o = addNode(items.find((i) => i.id === "output")!, { x: at.x + 720, y: at.y });
+ if (!p || !m || !o) return;
setEdges((es) => [...es, { id: newId("e"), source: p, sourceHandle: OUT, target: m, targetHandle: "prompt" }, { id: newId("e"), source: m, sourceHandle: OUT, target: o, targetHandle: PREVIEW_IN }]);
setTimeout(() => void rf.fitView({ ...fitOptions, duration: 300 }), 60);
};
- // ---- edges: coloured by what they carry, animated into running nodes
- const flowEdges = useMemo(() => {
- const byId = new Map(graph.nodes.map((n) => [n.id, n]));
- return edges.map((e) => {
+ // ---- edges: coloured by what they carry, animated into running nodes. Rebuilt only when that
+ // look changes (not on every keystroke), so React Flow doesn't re-render every edge.
+ const edgeLook = edges
+ .map((e) => {
const src = byId.get(e.source);
- const t = src ? outputType(graph, src) : null;
const r = results.get(e.target);
- const live = r?.state === "running" || r?.state === "queued";
- return { ...e, animated: live, style: { stroke: t ? PORT_COLOR[t] : undefined, strokeWidth: e.selected ? 3 : 2 } };
- });
- }, [edges, graph, results]);
-
- const api: EditorApi = {
- canvasId: id,
- graph,
- plan,
- describe: (nid) => descriptions.get(nid),
- results: (nid) => results.get(nid) ?? EMPTY_RESULTS,
- runErrors,
- engine,
- mode,
- readOnly: isMobile,
- running: runM.isPending,
- isDemo,
- update,
- remove,
- duplicate,
- run,
- cancel: (nid) => void cancel(nid),
- open: (nid, index = 0) => setViewer({ nodeId: nid, index }),
- toInput,
- };
+ return `${e.id}:${src ? typeOfNode(src) : ""}:${r?.state === "running" || r?.state === "queued" ? 1 : 0}`;
+ })
+ .join("|");
+ const flowEdges = useMemo(
+ () =>
+ edges.map((e) => {
+ const src = byId.get(e.source);
+ const t = src ? typeOfNode(src) : null;
+ const r = results.get(e.target);
+ const live = r?.state === "running" || r?.state === "queued";
+ return { ...e, animated: live, style: { stroke: t ? PORT_COLOR[t] : undefined, strokeWidth: e.selected ? 3 : 2 } };
+ }),
+ // byId and results are read through edgeLook (what the edges show of them).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [edges, edgeLook],
+ );
+ const miniColor = useCallback((n: FlowNode) => {
+ const t = typeOfNode(n);
+ return t ? PORT_COLOR[t] : "var(--muted-foreground)";
+ }, []);
const viewerEntries = viewer ? (results.get(viewer.nodeId)?.outputs ?? []) : [];
const entry = viewer ? viewerEntries[viewer.index] : undefined;
@@ -650,243 +784,324 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
.filter(Boolean)
.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);
+ useLayoutEffect(() => {
+ uiHandlers.current = { run, 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),
+ switchEngine: (e) => uiHandlers.current!.switchEngine(e),
+ rename: (v) => void uiHandlers.current!.rename(v),
+ addAtCenter: (p) => uiHandlers.current!.addAtCenter(p),
+ }),
+ [],
+ );
+ const closePalette = useCallback(() => setPaletteOpen(false), []);
+
+ const otherEngineName = mode === "open" ? "cloud" : "open-source";
+ const stuckNames = stuck.map((n) => `“${nodeLabel(n)}”`);
+
return (
- <EditorContext.Provider value={api}>
- <div className="fuobe-canvas flex h-svh min-w-0 flex-col md:h-[calc(100svh-0.5rem)]">
- <header className="z-20 flex h-14 shrink-0 items-center gap-2 border-b bg-background px-2 sm:px-4">
- <SidebarTrigger className="md:hidden" />
- <Tooltip>
- <TooltipTrigger asChild>
- <Link href="/canvas" className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="All canvases">
- <ChevronLeft className="size-4" />
- </Link>
- </TooltipTrigger>
- <TooltipContent>All canvases</TooltipContent>
- </Tooltip>
- <input
- value={name}
- onChange={(e) => setName(e.target.value)}
- onBlur={(e) => void rename(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
- maxLength={80}
- aria-label="Canvas name"
- className="h-9 w-0 min-w-0 flex-1 truncate rounded-md bg-transparent px-1.5 font-heading text-[20px] leading-none outline-none hover:bg-accent focus:bg-muted sm:max-w-[320px] sm:flex-none sm:w-[min(320px,30vw)]"
+ <EditorStoreContext.Provider value={store}>
+ <EditorActionsContext.Provider value={actions}>
+ <div className="fuobe-canvas flex h-svh min-w-0 flex-col md:h-[calc(100svh-0.5rem)]">
+ <EditorHeader
+ name={name}
+ setName={setName}
+ saveState={saveState}
+ saveRefused={saveRefused}
+ busy={busy}
+ summary={summary}
+ boardEngine={boardEngine}
+ selectedCount={isMobile ? 0 : selected.length}
+ running={runM.isPending}
+ canRun={generators.length > 0}
+ mode={mode}
+ ui={ui}
/>
- <span className="hidden shrink-0 items-center gap-1 text-[12px] text-muted-foreground sm:inline-flex" aria-live="polite">
- {saveState === "saving" ? <Loader2 className="size-3 animate-spin" /> : saveState === "error" ? <TriangleAlert className="size-3 text-warning" /> : <Check className="size-3" />}
- {saveState === "saving" ? "Saving…" : saveState === "error" ? "Not saved — retrying" : "Saved"}
- </span>
- <div className="ml-auto flex shrink-0 items-center gap-2">
- {busy > 0 && (
- <span className="hidden items-center gap-1.5 text-[12px] font-medium text-brand-text lg:inline-flex">
- <Loader2 className="size-3.5 animate-spin" /> {busy} running
- </span>
- )}
- {summary && <span className="hidden font-mono text-[12px] text-muted-foreground lg:inline">{summary}</span>}
- <div className="hidden md:block">
- <EngineSwitch value={boardEngine} onChange={switchEngine} size="sm" />
- </div>
- {selected.length > 0 && !isMobile && (
- <Button variant="secondary" size="sm" className="h-8 rounded-full px-3" onClick={() => run(selected)} disabled={runM.isPending}>
- <Play /> Run selected <span className="font-mono text-muted-foreground">{selected.length}</span>
- </Button>
- )}
- <div className="flex items-center">
- <Tooltip>
- <TooltipTrigger asChild>
- <Button size="sm" className="h-8 rounded-l-full rounded-r-none pr-2.5 pl-3.5" onClick={() => run()} disabled={runM.isPending || !generators.length}>
- {runM.isPending ? <Loader2 className="animate-spin" /> : <Play />} Run all
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- Run every node that changed <Kbd>⌘</Kbd>
- <Kbd>↵</Kbd>
- </TooltipContent>
- </Tooltip>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button size="sm" className="h-8 rounded-l-none rounded-r-full border-l border-primary-foreground/20 px-2" aria-label="More run options" disabled={!generators.length}>
- <ChevronDown />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-60">
- <DropdownMenuItem onSelect={() => run()}>
- <Play /> Run all <span className="ml-auto text-[11px] text-muted-foreground">changed nodes</span>
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => run(undefined, true)}>
- <RotateCcw /> Re-run everything
- </DropdownMenuItem>
- {selected.length > 0 && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onSelect={() => run(selected)}>
- <Play /> Run selected ({selected.length})
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => run(selected, true)}>
- <RotateCcw /> Re-run selected
- </DropdownMenuItem>
- </>
- )}
- <DropdownMenuSeparator />
- <DropdownMenuItem disabled={mode === "cloud"} onSelect={() => switchEngine("open")}>
- <Cpu /> Switch all to open source
- </DropdownMenuItem>
- <DropdownMenuItem disabled={mode === "open"} onSelect={() => switchEngine("cloud")}>
- <Cloud /> Switch all to cloud
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- </header>
-
- {isMobile && (
- <div className="flex shrink-0 items-center gap-2 border-b px-4 py-2">
- <div className="inline-grid h-9 grid-cols-2 rounded-full bg-muted p-0.5 text-[13px] font-medium" role="tablist" aria-label="View">
- {(["board", "list"] as const).map((t) => (
- <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={cn("inline-flex items-center gap-1.5 rounded-full px-3.5", tab === t ? "bg-background shadow-soft" : "text-muted-foreground")}>
- {t === "board" ? <LayoutGrid className="size-3.5" /> : <List className="size-3.5" />}
- {t === "board" ? "Board" : "Nodes"}
- </button>
- ))}
+
+ {isMobile && (
+ <div className="flex shrink-0 items-center gap-2 border-b px-4 py-2">
+ <div className="inline-grid h-9 grid-cols-2 rounded-full bg-muted p-0.5 text-[13px] font-medium" role="tablist" aria-label="View">
+ {(["board", "list"] as const).map((t) => (
+ <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={cn("inline-flex items-center gap-1.5 rounded-full px-3.5", tab === t ? "bg-background shadow-soft" : "text-muted-foreground")}>
+ {t === "board" ? <LayoutGrid className="size-3.5" /> : <List className="size-3.5" />}
+ {t === "board" ? "Board" : "Nodes"}
+ </button>
+ ))}
+ </div>
+ <span className="ml-auto truncate font-mono text-[11px] text-muted-foreground">{busy ? `${busy} running` : summary}</span>
</div>
- <span className="ml-auto truncate font-mono text-[11px] text-muted-foreground">{busy ? `${busy} running` : summary}</span>
- </div>
- )}
+ )}
- {offEngine.length > 0 && (
- <div className="flex shrink-0 flex-wrap items-center gap-2 border-b bg-highlight/20 px-4 py-2 text-[13px]">
- <TriangleAlert className="size-4 shrink-0 text-warning" />
- <span className="min-w-0 flex-1">
- {offEngine.length} node{offEngine.length > 1 ? "s use" : " uses"} {mode === "open" ? "cloud" : "open-source"} models, but this install is set to {mode === "open" ? "open source only" : "cloud only"}.
- </span>
- <Button size="sm" variant="secondary" className="h-7 rounded-full" onClick={() => switchEngine(mode as Engine)}>
- Switch {offEngine.length > 1 ? "them" : "it"}
- </Button>
- </div>
- )}
+ {offEngine.length > 0 && (
+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b bg-highlight/20 px-4 py-2 text-[13px]">
+ <TriangleAlert className="size-4 shrink-0 text-warning" />
+ <span className="min-w-0 flex-1">
+ {offEngine.length} node{offEngine.length > 1 ? "s use" : " uses"} {otherEngineName} models, but this install is set to {mode === "open" ? "open source only" : "cloud only"}.
+ {stuck.length > 0 && (
+ <>
+ {" "}
+ {stuckNames.join(", ")} {stuck.length > 1 ? "have" : "has"} no {mode === "open" ? "open-source" : "cloud"} version yet: remove {stuck.length > 1 ? "them" : "it"}, or change Settings → Engine mode.
+ </>
+ )}
+ </span>
+ {switchable > 0 && (
+ <Button size="sm" variant="secondary" className="h-7 rounded-full" onClick={() => switchEngine(mode as Engine)}>
+ Switch {switchable > 1 ? `${switchable} nodes` : stuck.length ? "the other" : "it"}
+ </Button>
+ )}
+ </div>
+ )}
- {isMobile && tab === "list" ? (
- <div className="min-h-0 flex-1 overflow-y-auto">
- <NodeList />
- </div>
- ) : (
- <div
- ref={wrapper}
- className="relative min-h-0 flex-1"
- onDragOver={onDragOver}
- onDrop={onDrop}
- onDoubleClick={(e) => {
- if (isMobile || !(e.target as HTMLElement).classList.contains("react-flow__pane")) return;
- openMenuAt(e.clientX, e.clientY);
- }}
- >
- <ReactFlow<FlowNode, Edge>
- nodes={nodes}
- edges={flowEdges}
- nodeTypes={NODE_TYPES}
- onNodesChange={onNodesChange}
- onEdgesChange={onEdgesChange}
- onConnect={onConnect}
- onConnectEnd={onConnectEnd}
- isValidConnection={isValidConnection}
- onPaneContextMenu={(e) => {
- e.preventDefault();
- if (!isMobile) openMenuAt(e.clientX, e.clientY);
- }}
- onPaneClick={() => setMenu(null)}
- onMoveEnd={(_, vp) => {
- // The phone's fitted view isn't saved over the desktop one.
- if (isMobile) return;
- viewport.current = vp;
- touch();
+ {isMobile && tab === "list" ? (
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <NodeList
+ onQuickStart={() => {
+ setTab("board");
+ setTimeout(quickStart, 0);
+ }}
+ />
+ </div>
+ ) : (
+ <div
+ ref={wrapper}
+ className="relative min-h-0 flex-1"
+ onDragOver={onDragOver}
+ onDrop={onDrop}
+ onDoubleClick={(e) => {
+ if (isMobile || !(e.target as HTMLElement).classList.contains("react-flow__pane")) return;
+ openMenuAt(e.clientX, e.clientY);
}}
- defaultViewport={savedViewport}
- fitViewOptions={fitOptions}
- minZoom={0.15}
- maxZoom={2}
- snapToGrid
- snapGrid={GRID}
- zoomOnDoubleClick={false}
- deleteKeyCode={isMobile ? null : ["Backspace", "Delete"]}
- multiSelectionKeyCode={["Meta", "Shift", "Control"]}
- nodesDraggable={!isMobile}
- nodesConnectable={!isMobile}
- connectionRadius={28}
- colorMode={resolvedTheme === "dark" ? "dark" : "light"}
- attributionPosition="top-right"
- aria-label="Canvas board"
>
- <Background variant={BackgroundVariant.Dots} gap={GRID[0] * 1.5} size={1.4} />
- <Controls position="bottom-left" showInteractive={false} className="canvas-controls" />
- {!isMobile && (
- <MiniMap
- position="bottom-right"
- pannable
- zoomable
- ariaLabel="Mini map"
- nodeBorderRadius={6}
- nodeColor={(n) => {
- const g = graph.nodes.find((x) => x.id === n.id);
- const t = g ? outputType(graph, g) : null;
- return t ? PORT_COLOR[t] : "var(--muted-foreground)";
- }}
- />
- )}
- {!isMobile && (
- <Panel position="top-left" className="m-3! flex max-h-[calc(100%-7rem)] flex-col">
- {paletteOpen ? <Palette items={paletteItems()} onAdd={addAtCenter} onClose={() => setPaletteOpen(false)} /> : <PaletteToggle onOpen={() => setPaletteOpen(true)} />}
- </Panel>
- )}
- </ReactFlow>
-
- {nodes.length === 0 && (
- <div className="pointer-events-none absolute inset-0 grid place-items-center p-6">
- <div className="pointer-events-auto max-w-md text-center">
- <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">Build freely. Automate visually.</p>
- <h2 className="mt-2 font-heading text-[28px] leading-tight text-balance">Wire models together, run them in order</h2>
- <p className="mt-2 text-[14px] text-muted-foreground">
- {isMobile ? "Open this canvas on a larger screen to add nodes, or start from a template." : "Double-click or right-click anywhere to add a node, or drag one in from the palette."}
- </p>
- <div className="mt-5 flex flex-wrap justify-center gap-2">
- {!isMobile && (
+ <ReactFlow<FlowNode, Edge>
+ nodes={nodes}
+ edges={flowEdges}
+ nodeTypes={NODE_TYPES}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ onConnect={onConnect}
+ onConnectEnd={onConnectEnd}
+ isValidConnection={isValidConnection}
+ onPaneContextMenu={(e) => {
+ e.preventDefault();
+ if (!isMobile) openMenuAt(e.clientX, e.clientY);
+ }}
+ onPaneClick={() => setMenu(null)}
+ onMoveEnd={(_, vp) => {
+ // The phone's fitted view isn't saved over the desktop one.
+ if (isMobile) return;
+ viewport.current = vp;
+ touch();
+ }}
+ defaultViewport={savedViewport}
+ fitViewOptions={fitOptions}
+ minZoom={0.15}
+ maxZoom={2}
+ snapToGrid
+ snapGrid={GRID}
+ zoomOnDoubleClick={false}
+ deleteKeyCode={isMobile ? null : ["Backspace", "Delete"]}
+ multiSelectionKeyCode={["Meta", "Shift", "Control"]}
+ nodesDraggable={!isMobile}
+ nodesConnectable={!isMobile}
+ // Tab goes node to node (each node's menu connects and disconnects from the keyboard).
+ edgesFocusable={false}
+ connectionRadius={28}
+ colorMode={resolvedTheme === "dark" ? "dark" : "light"}
+ attributionPosition="top-right"
+ aria-label="Canvas board"
+ >
+ <Background variant={BackgroundVariant.Dots} gap={GRID[0] * 1.5} size={1.4} />
+ <Controls position="bottom-left" showInteractive={false} className="canvas-controls" fitViewOptions={fitOptions} />
+ {!isMobile && <MiniMap position="bottom-right" pannable zoomable ariaLabel="Mini map" nodeBorderRadius={6} nodeColor={miniColor} />}
+ {!isMobile && (
+ <Panel position="top-left" className="m-3! flex max-h-[calc(100%-7rem)] flex-col">
+ {paletteOpen ? <Palette items={palette} onAdd={ui.addAtCenter} onClose={closePalette} /> : <PaletteToggle onOpen={() => setPaletteOpen(true)} />}
+ </Panel>
+ )}
+ </ReactFlow>
+
+ {nodes.length === 0 && (
+ <div className="pointer-events-none absolute inset-0 grid place-items-center p-6">
+ <div className="pointer-events-auto max-w-md text-center">
+ <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">Build freely. Automate visually.</p>
+ <h2 className="mt-2 font-heading text-[28px] leading-tight text-balance">Wire models together, run them in order</h2>
+ <p className="mt-2 text-[14px] text-muted-foreground">
+ {isMobile
+ ? "Start with a ready-made chain or a template, then edit each node from the Nodes tab. Wiring new nodes takes a larger screen."
+ : "Double-click or right-click anywhere to add a node, or drag one in from the palette."}
+ </p>
+ <div className="mt-5 flex flex-wrap justify-center gap-2">
<Button className="rounded-full" onClick={quickStart}>
<Sparkles /> Start with Text → Image
</Button>
- )}
- <Button variant="secondary" className="rounded-full" asChild>
- <Link href="/canvas?tab=templates">Browse templates</Link>
- </Button>
+ <Button variant="secondary" className="rounded-full" asChild>
+ <Link href="/canvas?tab=templates">Browse templates</Link>
+ </Button>
+ </div>
</div>
</div>
- </div>
- )}
-
- {menu && (
- <AddMenu
- x={menu.x}
- y={menu.y}
- items={menuItems}
- title={menu.connect ? (menu.connect.from === "source" ? `Send this ${menu.connect.type} to…` : `Make the ${menu.connect.type} with…`) : undefined}
- onPick={(p) => {
- addNode(p, menu.flow, menu.connect);
- setMenu(null);
- }}
- onClose={() => setMenu(null)}
- />
- )}
- </div>
+ )}
+
+ {menu && (
+ <AddMenu
+ x={menu.x}
+ y={menu.y}
+ items={menuItems}
+ title={menu.connect ? (menu.connect.from === "source" ? `Send this ${menu.connect.type} to…` : `Make the ${menu.connect.type} with…`) : undefined}
+ onPick={(p) => {
+ addNode(p, menu.flow, menu.connect);
+ setMenu(null);
+ }}
+ onClose={() => setMenu(null)}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ {entry && (
+ <Viewer
+ generation={entry.g}
+ index={entry.i}
+ onClose={() => setViewer(null)}
+ onPrev={viewer!.index > 0 ? () => setViewer({ ...viewer!, index: viewer!.index - 1 }) : undefined}
+ onNext={viewer!.index < viewerEntries.length - 1 ? () => setViewer({ ...viewer!, index: viewer!.index + 1 }) : undefined}
+ />
)}
- </div>
- {entry && (
- <Viewer
- generation={entry.g}
- index={entry.i}
- onClose={() => setViewer(null)}
- onPrev={viewer!.index > 0 ? () => setViewer({ ...viewer!, index: viewer!.index - 1 }) : undefined}
- onNext={viewer!.index < viewerEntries.length - 1 ? () => setViewer({ ...viewer!, index: viewer!.index + 1 }) : undefined}
- />
- )}
- </EditorContext.Provider>
+ </EditorActionsContext.Provider>
+ </EditorStoreContext.Provider>
);
}
+
+// ---------------------------------------------------------------------------
+// Header: name, save state, plan summary, engine, Run. Memoized with stable handlers, so typing on
+// the board doesn't re-render its menus and tooltips.
+
+interface HeaderUi {
+ run: (targets?: string[], force?: boolean) => void;
+ runSelected: (force?: boolean) => void;
+ switchEngine: (e: Engine) => void;
+ rename: (name: string) => void;
+ addAtCenter: (p: PaletteItem) => void;
+}
+
+const EditorHeader = memo(function EditorHeader({
+ name,
+ setName,
+ saveState,
+ saveRefused,
+ busy,
+ summary,
+ boardEngine,
+ selectedCount,
+ running,
+ canRun,
+ mode,
+ ui,
+}: {
+ name: string;
+ setName: (v: string) => void;
+ saveState: SaveState;
+ saveRefused: boolean;
+ busy: number;
+ summary: string;
+ boardEngine: Engine;
+ selectedCount: number;
+ running: boolean;
+ canRun: boolean;
+ mode: EngineMode;
+ ui: HeaderUi;
+}) {
+ return (
+ <header className="z-20 flex h-14 shrink-0 items-center gap-2 border-b bg-background px-2 sm:px-4">
+ <SidebarTrigger className="md:hidden" />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Link href="/canvas" className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="All canvases">
+ <ChevronLeft className="size-4" />
+ </Link>
+ </TooltipTrigger>
+ <TooltipContent>All canvases</TooltipContent>
+ </Tooltip>
+ <input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onBlur={(e) => ui.rename(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
+ maxLength={80}
+ aria-label="Canvas name"
+ className="h-9 w-0 min-w-0 flex-1 truncate rounded-md bg-transparent px-1.5 font-heading text-[20px] leading-none outline-none hover:bg-accent focus:bg-muted sm:max-w-[320px] sm:flex-none sm:w-[min(320px,30vw)]"
+ />
+ <span className={cn("shrink-0 items-center gap-1 text-[12px] text-muted-foreground", saveState === "error" ? "inline-flex" : "hidden sm:inline-flex")} aria-live="polite">
+ {saveState === "saving" ? <Loader2 className="size-3 animate-spin" /> : saveState === "error" ? <TriangleAlert className="size-3 text-warning" /> : <Check className="size-3" />}
+ <span className={cn(saveState === "error" && "max-sm:sr-only")}>{saveState === "saving" ? "Saving…" : saveState === "error" ? (saveRefused ? "Not saved" : "Not saved — retrying") : "Saved"}</span>
+ </span>
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ {busy > 0 && (
+ <span className="hidden items-center gap-1.5 text-[12px] font-medium text-brand-text lg:inline-flex">
+ <Loader2 className="size-3.5 animate-spin" /> {busy} running
+ </span>
+ )}
+ {summary && <span className="hidden font-mono text-[12px] text-muted-foreground lg:inline">{summary}</span>}
+ <div className="hidden md:block">
+ <EngineSwitch value={boardEngine} onChange={ui.switchEngine} size="sm" />
+ </div>
+ {selectedCount > 0 && (
+ <Button variant="secondary" size="sm" className="h-8 rounded-full px-3" onClick={() => ui.runSelected()} disabled={running}>
+ <Play /> Run selected <span className="font-mono text-muted-foreground">{selectedCount}</span>
+ </Button>
+ )}
+ <div className="flex items-center">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button size="sm" className="h-8 rounded-l-full rounded-r-none pr-2.5 pl-3.5" onClick={() => ui.run()} disabled={running || !canRun}>
+ {running ? <Loader2 className="animate-spin" /> : <Play />} Run all
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ Run every node that changed <Kbd>⌘</Kbd>
+ <Kbd>↵</Kbd>
+ </TooltipContent>
+ </Tooltip>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button size="sm" className="h-8 rounded-l-none rounded-r-full border-l border-primary-foreground/20 px-2" aria-label="More run options" disabled={!canRun}>
+ <ChevronDown />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-60">
+ <DropdownMenuItem onSelect={() => ui.run()}>
+ <Play /> Run all <span className="ml-auto text-[11px] text-muted-foreground">changed nodes</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => ui.run(undefined, true)}>
+ <RotateCcw /> Re-run everything
+ </DropdownMenuItem>
+ {selectedCount > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => ui.runSelected()}>
+ <Play /> Run selected ({selectedCount})
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => ui.runSelected(true)}>
+ <RotateCcw /> Re-run selected
+ </DropdownMenuItem>
+ </>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem disabled={mode === "cloud"} onSelect={() => ui.switchEngine("open")}>
+ <Cpu /> Switch all to open source
+ </DropdownMenuItem>
+ <DropdownMenuItem disabled={mode === "open"} onSelect={() => ui.switchEngine("cloud")}>
+ <Cloud /> Switch all to cloud
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ </header>
+ );
+});
diff --git a/src/components/canvas/node-list.tsx b/src/components/canvas/node-list.tsx
index 87fd0797..2944f438 100644
--- a/src/components/canvas/node-list.tsx
+++ b/src/components/canvas/node-list.tsx
@@ -1,30 +1,45 @@
"use client";
-import { AlertCircle, PinOff, Play, RotateCcw, Square, Upload } from "lucide-react";
+import { AlertCircle, PinOff, Play, RotateCcw, Sparkles, Square, Upload } from "lucide-react";
+import Link from "next/link";
import { useRef } from "react";
+import { Button } from "@/components/ui/button";
import { getModel } from "@/lib/catalog";
-import { isGenerator, NODE_SPECS, nodeLabel, topoOrder, type CanvasNode } from "@/lib/catalog/canvas";
+import { CANVAS_TEXT_MAX, isGenerator, NODE_SPECS, nodeLabel, promptPlaceholder, 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";
-import { NodeIcon, useEditor } from "./canvas-context";
-import { costLabel, EngineBadge, MediaPreview, OutputThumb, Results } from "./nodes";
+import { EMPTY_VIEW, NodeIcon, useEditorActions, useEditorSnapshot } from "./canvas-context";
+import { costLabel, ElementPicker, EngineBadge, LibraryButton, MediaPreview, OutputThumb, Results } from "./nodes";
const KIND: Partial<Record<CanvasNode["type"], MediaKind>> = { "image-input": "image", "video-input": "video", "audio-input": "audio" };
const field = "field-sizing-content max-h-40 min-h-12 w-full resize-none rounded-lg bg-muted px-3 py-2 text-[15px] leading-snug outline-none placeholder:text-subtle-foreground focus:ring-2 focus:ring-brand-faint";
+const pill = "inline-flex h-9 items-center gap-1.5 rounded-full bg-secondary px-3.5 text-[13px] font-medium";
/**
- * The phone view of a canvas: every node in run order as a card, with its text, files, results
- * and a Run button. Wiring stays on the board (pan and zoom it on the Board tab).
+ * The phone view of a canvas: every node in run order as a card, with its text, files (upload or
+ * library), elements, results and a Run button. Wiring stays on the board (pan and zoom it on the Board tab).
*/
-export function NodeList() {
- const ed = useEditor();
- const byId = new Map(ed.graph.nodes.map((n) => [n.id, n]));
- const { order, cyclic } = topoOrder(ed.graph);
+export function NodeList({ onQuickStart }: { onQuickStart: () => void }) {
+ const { graph } = useEditorSnapshot();
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
+ const { order, cyclic } = topoOrder(graph);
const nodes = [...order, ...cyclic].map((id) => byId.get(id)!).filter((n) => n && n.type !== "note");
if (!nodes.length) {
- return <p className="px-6 py-16 text-center text-[15px] text-muted-foreground">This canvas is empty. Add nodes on a larger screen, or start from a template.</p>;
+ return (
+ <div className="px-6 py-16 text-center">
+ <p className="text-[15px] text-muted-foreground">This canvas is empty. Start with a ready-made chain, or pick a template.</p>
+ <div className="mt-5 flex flex-wrap justify-center gap-2">
+ <Button className="rounded-full" onClick={onQuickStart}>
+ <Sparkles /> Start with Text → Image
+ </Button>
+ <Button variant="secondary" className="rounded-full" asChild>
+ <Link href="/canvas?tab=templates">Browse templates</Link>
+ </Button>
+ </div>
+ </div>
+ );
}
return (
<ol className="space-y-3 px-4 pt-3 pb-24" aria-label="Nodes in run order">
@@ -38,17 +53,18 @@ export function NodeList() {
}
function NodeCard({ node, index }: { node: CanvasNode; index: number }) {
- const ed = useEditor();
+ const actions = useEditorActions();
+ const { graph, views, globals } = useEditorSnapshot();
const model = node.data.modelId ? getModel(node.data.modelId) : undefined;
const kind = KIND[node.type];
const file = useRef<HTMLInputElement>(null);
const gen = isGenerator(node);
- const r = ed.results(node.id);
- const desc = gen ? ed.describe(node.id) : undefined;
- const step = ed.plan.steps.find((s) => s.nodeId === node.id);
+ const v = views.get(node.id) ?? EMPTY_VIEW;
+ const r = v.results;
+ const step = v.step;
const running = r.state === "running" || r.state === "queued";
- const error = ed.runErrors[node.id] ?? desc?.error;
- const sources = node.type === "output" ? ed.graph.edges.filter((e) => e.target === node.id).map((e) => ed.graph.nodes.find((x) => x.id === e.source)).filter((x): x is CanvasNode => !!x) : [];
+ const error = v.runError ?? v.error;
+ const sources = node.type === "output" ? graph.edges.filter((e) => e.target === node.id).map((e) => graph.nodes.find((x) => x.id === e.source)).filter((x): x is CanvasNode => !!x) : [];
return (
<article className="rounded-xl border bg-card p-3 shadow-soft" data-testid={`canvas-card-${node.id}`}>
<header className="flex items-center gap-2">
@@ -58,22 +74,27 @@ function NodeCard({ node, index }: { node: CanvasNode; index: number }) {
<EngineBadge model={model} />
{gen && (
<button
- onClick={() => (running ? ed.cancel(node.id) : node.data.pinned ? ed.update(node.id, { pinned: false }) : ed.run([node.id], !step))}
+ onClick={() => (running ? actions.cancel(node.id) : node.data.pinned ? actions.update(node.id, { pinned: false }) : actions.run([node.id], !step))}
className={cn("grid size-9 shrink-0 place-items-center rounded-full", running || node.data.pinned ? "bg-muted" : "bg-primary text-primary-foreground")}
- aria-label={running ? "Cancel" : node.data.pinned ? "Unpin result" : step ? "Run node" : "Run it again"}
+ aria-label={running ? `Cancel ${nodeLabel(node)}` : node.data.pinned ? `Unpin ${nodeLabel(node)}` : step ? `Run ${nodeLabel(node)}` : `Run ${nodeLabel(node)} again`}
>
{running ? <Square className="size-3.5" /> : node.data.pinned ? <PinOff className="size-4" /> : step ? <Play className="size-4" /> : <RotateCcw className="size-4" />}
</button>
)}
</header>
<div className="mt-2.5 space-y-2.5">
- {node.type === "prompt" && <textarea value={node.data.text ?? ""} onChange={(e) => ed.update(node.id, { text: e.target.value })} className={field} aria-label="Text" placeholder="Write the text" />}
+ {node.type === "prompt" && (
+ <textarea value={node.data.text ?? ""} onChange={(e) => actions.update(node.id, { text: e.target.value })} maxLength={CANVAS_TEXT_MAX} className={field} aria-label={`Text of ${nodeLabel(node)}`} placeholder="Write the text" />
+ )}
{kind && (
<>
{node.data.url ? <MediaPreview kind={kind} url={node.data.url} /> : <p className="text-[13px] text-muted-foreground">No file yet.</p>}
- <button onClick={() => file.current?.click()} className="inline-flex h-9 items-center gap-1.5 rounded-full bg-secondary px-3.5 text-[13px] font-medium">
- <Upload className="size-4" /> {node.data.url ? "Replace" : "Upload"}
- </button>
+ <div className="flex flex-wrap gap-1.5">
+ <button onClick={() => file.current?.click()} className={pill}>
+ <Upload className="size-4" /> {node.data.url ? "Replace" : "Upload"}
+ </button>
+ <LibraryButton kind={kind} className={pill} onPick={(url, name) => actions.update(node.id, { url, name })} />
+ </div>
<input
ref={file}
type="file"
@@ -81,20 +102,32 @@ function NodeCard({ node, index }: { node: CanvasNode; index: number }) {
accept={`${kind}/*`}
onChange={(e) => {
const f = e.target.files?.[0];
- if (f) void fileToSlot(f, (v) => v && !v.uploading && ed.update(node.id, { url: v.ref, name: v.name }), kind);
+ if (f) void fileToSlot(f, (s) => s && !s.uploading && actions.update(node.id, { url: s.ref, name: s.name }), kind);
e.target.value = "";
}}
/>
</>
)}
- {node.type === "element" && <p className="font-mono text-[13px] text-brand-text">{node.data.handle ? `@${node.data.handle}` : "No element picked"}</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>
+ <ElementPicker data={node.data} className={pill} onPick={(patch) => actions.update(node.id, patch)} />
+ </div>
+ )}
{gen && (
<>
<p className="text-[12px] text-muted-foreground">
- {model?.name ?? "No model"} · {costLabel(ed, model, desc?.costUsd ?? null)}
+ {model?.name ?? "No model"} · {costLabel(globals.isDemo, model, v.costUsd)}
</p>
{node.data.prompt !== undefined || node.type === "model" ? (
- <textarea value={node.data.prompt ?? ""} onChange={(e) => ed.update(node.id, { prompt: e.target.value })} className={field} aria-label="Prompt" placeholder="Prompt (connected text joins in)" />
+ <textarea
+ value={node.data.prompt ?? ""}
+ onChange={(e) => actions.update(node.id, { prompt: e.target.value })}
+ maxLength={CANVAS_TEXT_MAX}
+ className={field}
+ aria-label={`Prompt for ${nodeLabel(node)}`}
+ placeholder={promptPlaceholder(v.op)}
+ />
) : null}
<Results id={node.id} r={r} />
</>
@@ -103,15 +136,15 @@ function NodeCard({ node, index }: { node: CanvasNode; index: number }) {
(sources.length ? (
<div className="grid grid-cols-2 gap-2">
{sources.flatMap((s) => {
- const out = ed.results(s.id).outputs[0];
- return out ? [<OutputThumb key={s.id} o={out.o} onOpen={() => ed.open(s.id, 0)} />] : [];
+ const out = views.get(s.id)?.results.outputs[0];
+ return out ? [<OutputThumb key={s.id} o={out.o} onOpen={() => actions.open(s.id, 0)} />] : [];
})}
</div>
) : (
<p className="text-[13px] text-muted-foreground">Nothing connected.</p>
))}
{error && r.state !== "failed" && (
- <p className={cn("flex items-start gap-1.5 text-[13px] leading-snug", ed.runErrors[node.id] ? "text-destructive" : "text-warning")}>
+ <p className={cn("flex items-start gap-1.5 text-[13px] leading-snug", v.runError ? "text-destructive" : "text-warning")}>
<AlertCircle className="mt-0.5 size-3.5 shrink-0" />
{error}
</p>
diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsx
index 1ee49c3d..50fe3a6f 100644
--- a/src/components/canvas/nodes.tsx
+++ b/src/components/canvas/nodes.tsx
@@ -5,6 +5,7 @@ import {
AlertCircle,
AudioLines,
Box,
+ Cable,
Check,
Cloud,
Copy,
@@ -14,6 +15,7 @@ import {
Library,
Loader2,
MoreHorizontal,
+ Pencil,
Pin,
PinOff,
Play,
@@ -22,13 +24,34 @@ import {
SlidersHorizontal,
Square,
Trash2,
+ Unplug,
Upload,
X,
} from "lucide-react";
import Link from "next/link";
import { memo, useEffect, useMemo, useRef, useState } from "react";
-import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuTrigger } from "@/components/ui/context-menu";
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuSeparator,
+ ContextMenuShortcut,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+ ContextMenuTrigger,
+} from "@/components/ui/context-menu";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
@@ -37,11 +60,14 @@ import { downloadName } from "@/components/studio/feed";
import { fileToSlot, type SlotValue } from "@/components/studio/media-slot";
import { ControlsChip } from "@/components/studio/model-controls";
import { ModelPicker } from "@/components/studio/model-picker";
+import { ResponsivePanel } from "@/components/studio/responsive-panel";
import { useAssets, useElements } from "@/lib/api";
import { getModel } from "@/lib/catalog";
import {
+ CANVAS_TEXT_MAX,
+ connectionError,
defaultModelFor,
- effectiveOp,
+ EMPTY_GRAPH,
inputPorts,
isGenerator,
modelChoices,
@@ -52,17 +78,21 @@ import {
outputType,
PORT_TYPE_LABEL,
PREVIEW_IN,
+ promptPlaceholder,
sanitizeParams,
+ type CanvasEdge,
+ type CanvasGraph,
type CanvasNode,
type CanvasNodeData,
type CanvasNodeType,
+ type Connection,
type PortDef,
type PortType,
} 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 { cn } from "@/lib/utils";
-import { NodeIcon, PORT_COLOR, useEditor, type NodeResults } from "./canvas-context";
+import { NodeIcon, PORT_COLOR, useEditorActions, useEditorGlobals, useEditorSelector, useNodeResults, useNodeView, type EditorSnapshot, type NodeResults } from "./canvas-context";
export type FlowNode = Node<CanvasNodeData, CanvasNodeType>;
@@ -74,6 +104,12 @@ function asNode(id: string, type: CanvasNodeType, data: CanvasNodeData): CanvasN
return { id, type, data, position: { x: 0, y: 0 } };
}
+/**
+ * Nodes re-render when their own data or selection changes, not on every drag frame or size
+ * measurement (what they show from the rest of the board comes from the editor store).
+ */
+const sameNodeProps = (a: NodeProps<FlowNode>, b: NodeProps<FlowNode>) => a.id === b.id && a.type === b.type && a.data === b.data && a.selected === b.selected;
+
// ---------------------------------------------------------------------------
// Handles
@@ -109,7 +145,7 @@ function OutPort({ type }: { type: PortType }) {
}
// ---------------------------------------------------------------------------
-// Shell: header (icon, title, badges, menu), body, footer
+// Menus: the ⋯ button and right-click show the same items (keyboard users get Rename, Connect and Disconnect)
interface MenuItem {
label: string;
@@ -120,15 +156,161 @@ interface MenuItem {
separatorBefore?: boolean;
}
-function EditableTitle({ value, placeholder, onChange, readOnly }: { value?: string; placeholder: string; onChange: (v: string | undefined) => void; readOnly: boolean }) {
- const [editing, setEditing] = useState(false);
+interface MenuKit {
+ Item: typeof DropdownMenuItem;
+ Separator: typeof DropdownMenuSeparator;
+ Shortcut: typeof DropdownMenuShortcut;
+ Sub: typeof DropdownMenuSub;
+ SubTrigger: typeof DropdownMenuSubTrigger;
+ SubContent: typeof DropdownMenuSubContent;
+}
+
+const DROPDOWN: MenuKit = { Item: DropdownMenuItem, Separator: DropdownMenuSeparator, Shortcut: DropdownMenuShortcut, Sub: DropdownMenuSub, SubTrigger: DropdownMenuSubTrigger, SubContent: DropdownMenuSubContent };
+const CONTEXT = {
+ Item: ContextMenuItem,
+ Separator: ContextMenuSeparator,
+ Shortcut: ContextMenuShortcut,
+ Sub: ContextMenuSub,
+ SubTrigger: ContextMenuSubTrigger,
+ SubContent: ContextMenuSubContent,
+} as unknown as MenuKit;
+
+const byBoardPosition = (a: CanvasNode, b: CanvasNode) => a.position.x - b.position.x || a.position.y - b.position.y;
+
+function portLabel(n: CanvasNode | undefined, handle: string | null | undefined): string {
+ if (!n) return "";
+ if (n.type === "output") return "Preview";
+ return inputPorts(n).find((p) => p.id === handle)?.label ?? handle ?? "";
+}
+
+/** "Connect output to…": every input on the board this node's output may go into. */
+function ConnectItems({ id, kit }: { id: string; kit: MenuKit }) {
+ const actions = useEditorActions();
+ const graph = actions.getGraph();
+ const options: { key: string; label: string; c: Connection }[] = [];
+ for (const t of [...graph.nodes].sort(byBoardPosition)) {
+ if (t.id === id || t.type === "note") continue;
+ const handles = t.type === "output" ? [PREVIEW_IN] : inputPorts(t).map((p) => p.id);
+ for (const h of handles) {
+ const c: Connection = { source: id, sourceHandle: OUT, target: t.id, targetHandle: h };
+ if (graph.edges.some((e) => e.source === id && e.target === t.id && e.targetHandle === h) || connectionError(graph, c)) continue;
+ options.push({ key: `${t.id}:${h}`, label: `${nodeLabel(t)} · ${portLabel(t, h)}`, c });
+ }
+ }
+ if (!options.length) return <kit.Item disabled>Nothing on the board takes this output</kit.Item>;
+ return (
+ <>
+ {options.map((o) => (
+ <kit.Item key={o.key} onSelect={() => actions.connect(o.c)}>
+ {o.label}
+ </kit.Item>
+ ))}
+ </>
+ );
+}
+
+/** "Disconnect": this node's connections, in and out. */
+function DisconnectItems({ id, kit }: { id: string; kit: MenuKit }) {
+ const actions = useEditorActions();
+ const graph: CanvasGraph = actions.getGraph();
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
+ const self = byId.get(id);
+ const edges: CanvasEdge[] = graph.edges.filter((e) => e.source === id || e.target === id);
+ if (!edges.length) return <kit.Item disabled>No connections yet</kit.Item>;
+ return (
+ <>
+ {edges.map((e) => {
+ const incoming = e.target === id;
+ const other = byId.get(incoming ? e.source : e.target);
+ const label = incoming ? `${portLabel(self, e.targetHandle)} ← ${other ? nodeLabel(other) : "?"}` : `→ ${other ? nodeLabel(other) : "?"} · ${portLabel(other, e.targetHandle)}`;
+ return (
+ <kit.Item key={e.id} onSelect={() => actions.disconnect(e.id)}>
+ {label}
+ </kit.Item>
+ );
+ })}
+ </>
+ );
+}
+
+function MenuItems({ id, kit, items, canConnect, onRename }: { id: string; kit: MenuKit; items: MenuItem[]; canConnect: boolean; onRename: () => void }) {
+ const actions = useEditorActions();
+ const entry = (m: MenuItem) => (
+ <div key={m.label}>
+ {m.separatorBefore && <kit.Separator />}
+ <kit.Item onSelect={m.onSelect} variant={m.destructive ? "destructive" : "default"}>
+ <m.icon className="size-4" />
+ {m.label}
+ {m.shortcut && <kit.Shortcut>{m.shortcut}</kit.Shortcut>}
+ </kit.Item>
+ </div>
+ );
+ return (
+ <>
+ {items.map(entry)}
+ {items.length > 0 && <kit.Separator />}
+ <kit.Item onSelect={onRename}>
+ <Pencil className="size-4" />
+ Rename
+ </kit.Item>
+ {canConnect && (
+ <kit.Sub>
+ <kit.SubTrigger>
+ <Cable className="size-4" />
+ Connect output to…
+ </kit.SubTrigger>
+ <kit.SubContent className="max-h-80 w-64 overflow-y-auto">
+ <ConnectItems id={id} kit={kit} />
+ </kit.SubContent>
+ </kit.Sub>
+ )}
+ <kit.Sub>
+ <kit.SubTrigger>
+ <Unplug className="size-4" />
+ Disconnect
+ </kit.SubTrigger>
+ <kit.SubContent className="max-h-80 w-64 overflow-y-auto">
+ <DisconnectItems id={id} kit={kit} />
+ </kit.SubContent>
+ </kit.Sub>
+ {entry({ label: "Duplicate", icon: Copy, onSelect: () => actions.duplicate(id), shortcut: "⌘D", separatorBefore: true })}
+ {entry({ label: "Delete", icon: Trash2, onSelect: () => actions.remove(id), shortcut: "⌫", destructive: true })}
+ </>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Shell: header (icon, title, badges, menu), body, footer
+
+function EditableTitle({
+ value,
+ placeholder,
+ onChange,
+ readOnly,
+ editing,
+ setEditing,
+}: {
+ value?: string;
+ placeholder: string;
+ onChange: (v: string | undefined) => void;
+ readOnly: boolean;
+ editing: boolean;
+ setEditing: (v: boolean) => void;
+}) {
const [draft, setDraft] = useState("");
+ const [wasEditing, setWasEditing] = useState(false);
+ // Opening the editor (double-click or the menu's Rename) starts from the current name.
+ if (editing !== wasEditing) {
+ setWasEditing(editing);
+ if (editing) setDraft(value ?? placeholder);
+ }
if (editing) {
return (
<input
autoFocus
value={draft}
maxLength={80}
+ onFocus={(e) => e.currentTarget.select()}
onChange={(e) => setDraft(e.target.value)}
onBlur={() => {
setEditing(false);
@@ -150,7 +332,6 @@ function EditableTitle({ value, placeholder, onChange, readOnly }: { value?: str
onDoubleClick={(e) => {
if (readOnly) return;
e.stopPropagation();
- setDraft(value ?? placeholder);
setEditing(true);
}}
title={readOnly ? undefined : "Double-click to rename"}
@@ -167,7 +348,7 @@ function NodeShell({
selected,
out,
badge,
- menu,
+ menu = [],
footer,
children,
width = 300,
@@ -179,27 +360,32 @@ function NodeShell({
selected: boolean;
out?: PortType | null;
badge?: React.ReactNode;
- menu: MenuItem[];
+ menu?: MenuItem[];
footer?: React.ReactNode;
children?: React.ReactNode;
width?: number;
tone?: "running" | "failed" | "note";
}) {
- const ed = useEditor();
- const items =(Item: typeof DropdownMenuItem | typeof ContextMenuItem, Sep: typeof DropdownMenuSeparator, Short: typeof DropdownMenuShortcut) =>
- menu.map((m) => (
- <div key={m.label}>
- {m.separatorBefore && <Sep />}
- <Item onSelect={m.onSelect} variant={m.destructive ? "destructive" : "default"}>
- <m.icon className="size-4" />
- {m.label}
- {m.shortcut && <Short>{m.shortcut}</Short>}
- </Item>
- </div>
- ));
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
+ const [renaming, setRenaming] = useState(false);
+ // Rename opens the title field once the menu has closed (an open menu keeps the focus), and the
+ // menu doesn't hand the focus back to its trigger then.
+ const wantRename = useRef(false);
+ const rename = () => {
+ wantRename.current = true;
+ };
+ const keepFocus = (e: Event) => {
+ if (!wantRename.current) return;
+ wantRename.current = false;
+ e.preventDefault();
+ setRenaming(true);
+ };
+ const placeholder = nodeLabel({ type, data: { ...data, label: undefined } });
+ const label = data.label || placeholder;
return (
<ContextMenu>
- <ContextMenuTrigger asChild disabled={ed.readOnly}>
+ <ContextMenuTrigger asChild disabled={readOnly}>
<div
className={cn(
"group/node rounded-xl border bg-card text-card-foreground shadow-soft transition-[box-shadow,border-color]",
@@ -213,17 +399,17 @@ function NodeShell({
>
<div className="relative flex h-10 items-center gap-2 border-b px-3">
<NodeIcon name={NODE_SPECS[type].icon} className="size-4 shrink-0 text-muted-foreground" />
- <EditableTitle value={data.label} placeholder={nodeLabel({ type, data: { ...data, label: undefined } })} onChange={(label) => ed.update(id, { label })} readOnly={ed.readOnly} />
+ <EditableTitle value={data.label} placeholder={placeholder} onChange={(l) => actions.update(id, { label: l })} readOnly={readOnly} editing={renaming} setEditing={setRenaming} />
{badge}
- {!ed.readOnly && (
+ {!readOnly && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <button className={cn("-mr-1 grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground", NO_DRAG)} aria-label="Node actions">
+ <button className={cn("-mr-1 grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground", NO_DRAG)} aria-label={`Actions for ${label}`}>
<MoreHorizontal className="size-4" />
</button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-56">
- {items(DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut)}
+ <DropdownMenuContent align="end" className="w-56" onCloseAutoFocus={keepFocus}>
+ <MenuItems id={id} kit={DROPDOWN} items={menu} canConnect={!!out} onRename={rename} />
</DropdownMenuContent>
</DropdownMenu>
)}
@@ -233,18 +419,15 @@ function NodeShell({
{footer}
</div>
</ContextMenuTrigger>
- <ContextMenuContent className="w-56">{items(ContextMenuItem, ContextMenuSeparator as typeof DropdownMenuSeparator, ContextMenuShortcut as typeof DropdownMenuShortcut)}</ContextMenuContent>
+ {!readOnly && (
+ <ContextMenuContent className="w-56" onCloseAutoFocus={keepFocus}>
+ <MenuItems id={id} kit={CONTEXT} items={menu} canConnect={!!out} onRename={rename} />
+ </ContextMenuContent>
+ )}
</ContextMenu>
);
}
-function baseMenu(ed: ReturnType<typeof useEditor>, id: string): MenuItem[] {
- return [
- { label: "Duplicate", icon: Copy, onSelect: () => ed.duplicate(id), shortcut: "⌘D", separatorBefore: true },
- { label: "Delete", icon: Trash2, onSelect: () => ed.remove(id), shortcut: "⌫", destructive: true },
- ];
-}
-
// ---------------------------------------------------------------------------
// Results
@@ -294,7 +477,8 @@ function OutputThumb({ o, onOpen, className, large }: { o: OutputFile; onOpen: (
}
function Results({ id, r, compact }: { id: string; r: NodeResults; compact?: boolean }) {
- const ed = useEditor();
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
if (r.state === "queued" || r.state === "running") {
const pct = r.progress != null ? Math.round(r.progress * 100) : null;
return (
@@ -313,8 +497,8 @@ function Results({ id, r, compact }: { id: string; r: NodeResults; compact?: boo
<div className="rounded-lg border border-dashed p-2.5">
<p className="text-[12px] font-medium">{r.state === "canceled" ? "Canceled" : "Couldn't generate this"}</p>
{r.error && <p className="mt-0.5 line-clamp-4 text-[12px] leading-snug break-words text-muted-foreground">{r.error}</p>}
- {!ed.readOnly && (
- <button onClick={() => ed.run([id], true)} className={cn(chip, "mt-2")}>
+ {!readOnly && (
+ <button onClick={() => actions.run([id], true)} className={cn(chip, "mt-2")}>
<RotateCcw className="size-3" /> Retry
</button>
)}
@@ -326,7 +510,7 @@ function Results({ id, r, compact }: { id: string; r: NodeResults; compact?: boo
return (
<div className={cn("grid gap-1.5", shown.length > 1 ? "grid-cols-[repeat(2,minmax(0,1fr))]" : "grid-cols-[minmax(0,1fr)]")}>
{shown.map((x, k) => (
- <OutputThumb key={`${x.g.id}-${x.i}`} o={x.o} onOpen={() => ed.open(id, k)} />
+ <OutputThumb key={`${x.g.id}-${x.i}`} o={x.o} onOpen={() => actions.open(id, k)} />
))}
{r.outputs.length > 4 && <p className="col-span-2 text-[11px] text-muted-foreground">+{r.outputs.length - 4} more — open to see them all</p>}
</div>
@@ -354,11 +538,11 @@ function OptionSelect<T extends string | number>({ value, options, onChange, lab
}
function ModelOptions({ id, model, data }: { id: string; model: ModelDef; data: CanvasNodeData }) {
- const ed = useEditor();
+ const actions = useEditorActions();
const p = data.params ?? {};
const o = model.options;
const d = model.defaults ?? {};
- const set = (patch: Partial<NonNullable<CanvasNodeData["params"]>>) => ed.update(id, { params: { ...p, ...patch } });
+ const set = (patch: Partial<NonNullable<CanvasNodeData["params"]>>) => actions.update(id, { params: { ...p, ...patch } });
const extra = (p.extra ?? {}) as Record<string, unknown>;
const setExtra = (param: string, v?: string | number) => {
const next = { ...extra };
@@ -366,13 +550,23 @@ function ModelOptions({ id, model, data }: { id: string; model: ModelDef; data:
else next[param] = v;
set({ extra: Object.keys(next).length ? (next as Record<string, string | number>) : undefined });
};
+ const text = model.kind === "text";
const items: React.ReactNode[] = [];
if (o.aspectRatios?.length) items.push(<OptionSelect key="ar" label="Aspect ratio" value={p.aspectRatio ?? d.aspectRatio} options={o.aspectRatios} onChange={(v) => set({ aspectRatio: v })} />);
if (o.durations?.length && o.durations.length > 1) items.push(<OptionSelect key="dur" label="Duration" value={p.duration ?? d.duration} options={o.durations} onChange={(v) => set({ duration: v })} format={(v) => `${v}s`} />);
if (o.resolutions?.length && o.resolutions.length > 1) items.push(<OptionSelect key="res" label="Quality" value={p.resolution ?? d.resolution} options={o.resolutions} onChange={(v) => set({ resolution: v })} />);
if ((o.maxOutputs ?? 1) > 1) items.push(<OptionSelect key="n" label="Count" value={p.numOutputs ?? 1} options={Array.from({ length: Math.min(4, o.maxOutputs!) }, (_, i) => i + 1)} onChange={(v) => set({ numOutputs: v })} format={(v) => `×${v}`} />);
if (o.voices?.length) items.push(<OptionSelect key="voice" label="Voice" value={p.voice ?? d.voice ?? o.voices[0].id} options={o.voices.map((v) => v.id)} onChange={(v) => set({ voice: v })} format={(v) => o.voices!.find((x) => x.id === v)?.name ?? v} />);
- if (o.languages?.length) items.push(<LanguageChip key="lang" languages={o.languages} value={p.targetLanguage} onChange={(v) => set({ targetLanguage: v })} label="Language" />);
+ // A text model writes; picking a language makes it translate (Auto), and "Don't translate" goes back to writing.
+ if (o.languages?.length && !(text && data.op === "write")) {
+ items.push(<LanguageChip key="lang" languages={o.languages} value={p.targetLanguage} onChange={(v) => set({ targetLanguage: v })} label={text ? "Translate to…" : "Language"} />);
+ if (text && p.targetLanguage && data.op !== "translate")
+ items.push(
+ <button key="lang-x" className={chip} onClick={() => set({ targetLanguage: undefined })}>
+ <X className="size-3" /> Don&apos;t translate
+ </button>,
+ );
+ }
if (o.audio === true)
items.push(
<button key="audio" onClick={() => set({ generateAudio: !(p.generateAudio ?? d.generateAudio ?? false) })} className={cn(chip, (p.generateAudio ?? d.generateAudio) && "bg-brand-faint text-brand-text hover:bg-brand-faint-hover")} aria-pressed={!!(p.generateAudio ?? d.generateAudio)}>
@@ -382,7 +576,7 @@ function ModelOptions({ id, model, data }: { id: string; model: ModelDef; data:
if (o.sliders?.length) items.push(<div key="sliders" className={NO_DRAG}><SlidersChip model={model} values={extra} onChange={setExtra} /></div>);
if (o.controls?.length) items.push(<div key="controls" className={NO_DRAG}><ControlsChip controls={o.controls} values={extra} onChange={setExtra} /></div>);
if (!items.length) return null;
- return <div className="flex flex-wrap gap-1 [&_button]:h-7 [&_button]:text-[12px]">{items}</div>;
+ return <div className={cn("flex flex-wrap gap-1 [&_button]:h-7 [&_button]:text-[12px]", NO_DRAG)}>{items}</div>;
}
/** A model's numeric settings behind one chip (the studio composer shows them in its settings panel). */
@@ -413,46 +607,43 @@ function EngineBadge({ model }: { model?: ModelDef }) {
);
}
-function costLabel(ed: ReturnType<typeof useEditor>, model: ModelDef | undefined, cost: number | null): string {
+function costLabel(isDemo: (m: ModelDef) => boolean, model: ModelDef | undefined, cost: number | null): string {
if (!model) return "";
- if (ed.isDemo(model)) return "Demo · free";
+ if (isDemo(model)) return "Demo · free";
if (model.engine === "open") return "Free · your GPU";
return cost == null ? "Price unknown" : cost === 0 ? "Free" : `≈ ${formatCost(cost)}`;
}
const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }: NodeProps<FlowNode>) {
- const ed = useEditor();
+ const actions = useEditorActions();
+ const g = useEditorGlobals();
+ const v = useNodeView(id);
const node = useMemo(() => asNode(id, type, data), [id, type, data]);
const model = data.modelId ? getModel(data.modelId) : undefined;
- const ports = inputPorts(node);
- const out = outputType(ed.graph, node);
- const desc = ed.describe(id);
- const r = ed.results(id);
- const ops = nodeOps(node, model);
+ const ports = useMemo(() => inputPorts(node), [node]);
+ const out = outputType(EMPTY_GRAPH, node);
+ const r = v.results;
+ const ops = useMemo(() => nodeOps(node, model), [node, model]);
const auto = type === "model" && ops.length > 1;
- const inferred = auto ? effectiveOp(ed.graph, ed.graph.nodes.find((n) => n.id === id) ?? node) : undefined;
// The picker opens on the node's own engine (or the install's only one); its switch browses the other.
const [browseEngine, setBrowseEngine] = useState<Engine | null>(null);
- const pickerEngine: Engine = ed.mode !== "both" ? ed.mode : (browseEngine ?? model?.engine ?? ed.engine);
+ const pickerEngine: Engine = g.mode !== "both" ? g.mode : (browseEngine ?? model?.engine ?? g.engine);
const choices = useMemo(() => modelChoices(node), [node]);
- const step = ed.plan.steps.find((s) => s.nodeId === id);
- const reused = ed.plan.reused.find((s) => s.nodeId === id);
- const error = ed.runErrors[id] ?? desc?.error;
+ const error = v.runError ?? v.error;
- // Handles change with the model and op: tell React Flow to re-measure them.
+ // Handles change with the model and op: tell React Flow to re-measure them (React Flow measures new nodes itself).
const updateInternals = useUpdateNodeInternals();
const portKey = `${ports.map((p) => p.id).join(",")}|${out}`;
- useEffect(() => updateInternals(id), [id, portKey, updateInternals]);
-
- const counts = useMemo(() => {
- const m = new Map<string, number>();
- for (const e of ed.graph.edges) if (e.target === id && e.targetHandle) m.set(e.targetHandle, (m.get(e.targetHandle) ?? 0) + 1);
- return m;
- }, [ed.graph.edges, id]);
+ const measuredKey = useRef(portKey);
+ useEffect(() => {
+ if (measuredKey.current === portKey) return;
+ measuredKey.current = portKey;
+ updateInternals(id);
+ }, [id, portKey, updateInternals]);
const pickModel = (m: ModelDef) => {
const keepOp = data.op && m.routes.some((x) => x.op === data.op) ? data.op : undefined;
- ed.update(id, { modelId: m.id, op: keepOp, params: sanitizeParams(m, data.params) });
+ actions.update(id, { modelId: m.id, op: keepOp, params: sanitizeParams(m, data.params) });
setBrowseEngine(null);
};
@@ -460,8 +651,9 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
const variants = NODE_SPECS[type].ops && NODE_SPECS[type].ops!.length === 2 ? NODE_SPECS[type].ops! : null;
const setVariant = (kind: MediaKind) => {
const op = variants![kind === "video" ? 1 : 0];
- const m = defaultModelFor(op, model?.engine ?? ed.engine, { hidden: true }) ?? defaultModelFor(op, model?.engine === "open" ? "cloud" : "open", { hidden: true });
- ed.update(id, { mediaKind: kind, modelId: m?.id, op: undefined, params: undefined });
+ const engine = model?.engine ?? g.engine;
+ const m = defaultModelFor(op, engine, { hidden: true }) ?? (g.mode === "both" ? defaultModelFor(op, engine === "open" ? "cloud" : "open", { hidden: true }) : undefined);
+ actions.update(id, { mediaKind: kind, modelId: m?.id, op: undefined, params: undefined });
};
const running = r.state === "running" || r.state === "queued";
@@ -470,33 +662,49 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
...(data.pinned
? []
: [
- { label: "Run node", icon: Play, onSelect: () => ed.run([id]) },
- { label: "Re-run", icon: RotateCcw, onSelect: () => ed.run([id], true) },
+ { label: "Run node", icon: Play, onSelect: () => actions.run([id]) },
+ { label: "Re-run", icon: RotateCcw, onSelect: () => actions.run([id], true) },
]),
- ...(running ? [{ label: "Cancel", icon: Square, onSelect: () => ed.cancel(id) }] : []),
- { label: data.pinned ? "Unpin result" : "Pin result", icon: data.pinned ? PinOff : Pin, onSelect: () => ed.update(id, { pinned: !data.pinned }), separatorBefore: !data.pinned },
- ...(r.outputs.some((x) => ["image", "video", "audio"].includes(x.o.kind)) ? [{ label: "Use result as an input", icon: ImagePlus, onSelect: () => ed.toInput(id) }] : []),
+ ...(running ? [{ label: "Cancel", icon: Square, onSelect: () => actions.cancel(id) }] : []),
+ { label: data.pinned ? "Unpin result" : "Pin result", icon: data.pinned ? PinOff : Pin, onSelect: () => actions.update(id, { pinned: !data.pinned }), separatorBefore: !data.pinned },
+ ...(r.outputs.some((x) => ["image", "video", "audio"].includes(x.o.kind)) ? [{ label: "Use result as an input", icon: ImagePlus, onSelect: () => actions.toInput(id) }] : []),
...(r.outputs.length
? [
{
label: r.outputs.length > 1 ? "Download first result" : "Download result",
icon: Download,
onSelect: () => {
- const { g, o, i } = r.outputs[0];
+ const { g: gen, o, i } = r.outputs[0];
const a = document.createElement("a");
- a.href = `${o.url}?download=${encodeURIComponent(downloadName(g, o, i))}`;
+ a.href = `${o.url}?download=${encodeURIComponent(downloadName(gen, o, i))}`;
a.click();
},
},
]
: []),
- ...baseMenu(ed, id),
];
const promptPort = ports.find((p) => p.id === "prompt");
// With text wired in, the node's own words are optional: keep the box folded until wanted.
const [addWords, setAddWords] = useState(false);
- const showPrompt = !!promptPort && (!counts.get("prompt") || !!data.prompt || addWords);
- const stateHint = data.pinned ? "Pinned" : running ? "Running" : step ? (r.state === "idle" ? "Not run yet" : "Changed") : reused ? "Up to date" : "";
+ const showPrompt = !!promptPort && (!v.counts.prompt || !!data.prompt || addWords);
+ const step = v.step;
+ const stateHint = data.pinned
+ ? "Pinned"
+ : running
+ ? "Running"
+ : step === "changed"
+ ? "Changed"
+ : r.state === "failed"
+ ? "Failed"
+ : r.state === "canceled"
+ ? "Canceled"
+ : step === "upstream"
+ ? "Inputs changed"
+ : step
+ ? "Not run yet"
+ : v.reused
+ ? "Up to date"
+ : "";
return (
<NodeShell
@@ -523,14 +731,14 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
footer={
<div className="flex h-10 items-center gap-2 border-t px-3">
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground">
- {[stateHint, step || r.state === "idle" ? costLabel(ed, model, desc?.costUsd ?? null) : ""].filter(Boolean).join(" · ")}
+ {[stateHint, step || r.state === "idle" ? costLabel(g.isDemo, model, v.costUsd) : ""].filter(Boolean).join(" · ")}
</span>
- {!ed.readOnly && (
+ {!g.readOnly && (
<Tooltip>
<TooltipTrigger asChild>
<button
- onClick={() => (running ? ed.cancel(id) : data.pinned ? ed.update(id, { pinned: false }) : ed.run([id], !step && !!reused))}
- disabled={ed.running && !running}
+ onClick={() => (running ? actions.cancel(id) : data.pinned ? actions.update(id, { pinned: false }) : actions.run([id], !step && v.reused))}
+ disabled={g.running && !running}
className={cn(
"grid size-7 shrink-0 place-items-center rounded-full transition-colors disabled:opacity-50",
running || data.pinned ? "bg-muted text-foreground hover:bg-accent" : "bg-primary text-primary-foreground hover:bg-primary/90",
@@ -547,18 +755,18 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
</div>
}
>
- {ports.length > 0 && <div className="border-b py-1">{ports.map((p) => <InPort key={p.id} port={p} count={counts.get(p.id) ?? 0} />)}</div>}
+ {ports.length > 0 && <div className="border-b py-1">{ports.map((p) => <InPort key={p.id} port={p} count={v.counts[p.id] ?? 0} />)}</div>}
<div className="space-y-2 p-3">
{variants && (
<div className={cn("inline-grid h-7 grid-cols-2 rounded-full bg-muted p-0.5 text-[12px] font-medium", NO_DRAG)} role="radiogroup" aria-label="Image or video">
{(["image", "video"] as const).map((k) => (
- <button key={k} role="radio" aria-checked={(data.mediaKind ?? "image") === k} disabled={ed.readOnly} onClick={() => setVariant(k)} className={cn("rounded-full px-2.5 capitalize", (data.mediaKind ?? "image") === k ? "bg-background shadow-soft" : "text-muted-foreground")}>
+ <button key={k} role="radio" aria-checked={(data.mediaKind ?? "image") === k} disabled={g.readOnly} onClick={() => setVariant(k)} className={cn("rounded-full px-2.5 capitalize", (data.mediaKind ?? "image") === k ? "bg-background shadow-soft" : "text-muted-foreground")}>
{k}
</button>
))}
</div>
)}
- <div className={cn("flex flex-wrap items-center gap-1.5 [&>button]:h-7 [&>button]:text-[12px]", ed.readOnly && "pointer-events-none")}>
+ <div className={cn("flex flex-wrap items-center gap-1.5 [&>button]:h-7 [&>button]:text-[12px]", g.readOnly && "pointer-events-none")}>
{choices.length ? (
<div className={NO_DRAG}>
<ModelPicker models={choices} value={model} onChange={pickModel} engine={pickerEngine} onEngineChange={setBrowseEngine} />
@@ -571,12 +779,12 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
label="Operation"
value={data.op ?? "__auto"}
options={["__auto", ...ops]}
- onChange={(v) => ed.update(id, { op: v === "__auto" ? undefined : (v as typeof ops[number]) })}
- format={(v) => (v === "__auto" ? `Auto${inferred ? ` · ${OPERATION_LABELS[inferred]}` : ""}` : OPERATION_LABELS[v as keyof typeof OPERATION_LABELS])}
+ onChange={(o) => actions.update(id, { op: o === "__auto" ? undefined : (o as (typeof ops)[number]) })}
+ format={(o) => (o === "__auto" ? `Auto${v.op ? ` · ${OPERATION_LABELS[v.op]}` : ""}` : OPERATION_LABELS[o as keyof typeof OPERATION_LABELS])}
/>
)}
</div>
- {promptPort && !showPrompt && !ed.readOnly && (
+ {promptPort && !showPrompt && !g.readOnly && (
<button className={chip} onClick={() => setAddWords(true)}>
<Plus className="size-3" /> Add your own words
</button>
@@ -584,20 +792,21 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
{showPrompt && (
<textarea
value={data.prompt ?? ""}
- onChange={(e) => ed.update(id, { prompt: e.target.value })}
+ onChange={(e) => actions.update(id, { prompt: e.target.value })}
onBlur={() => !data.prompt && setAddWords(false)}
autoFocus={addWords && !data.prompt}
- readOnly={ed.readOnly}
+ readOnly={g.readOnly}
rows={2}
- placeholder={promptPort.label === "Text" ? "Text to speak, or connect a text" : "Describe it — connected text joins in, or use {text}"}
- aria-label={promptPort.label}
+ maxLength={CANVAS_TEXT_MAX}
+ placeholder={promptPlaceholder(v.op ?? ops[0])}
+ aria-label={`${promptPort.label} for ${data.label || nodeLabel(node)}`}
className={cn("field-sizing-content max-h-36 min-h-14 w-full resize-none rounded-lg bg-muted px-2.5 py-2 text-[13px] leading-snug outline-none placeholder:text-subtle-foreground focus:ring-2 focus:ring-brand-faint", NO_DRAG)}
/>
)}
- {model && !ed.readOnly && <ModelOptions id={id} model={model} data={data} />}
+ {model && !g.readOnly && <ModelOptions id={id} model={model} data={data} />}
<Results id={id} r={r} />
{error && r.state !== "failed" && (
- <p className={cn("flex items-start gap-1.5 text-[12px] leading-snug", ed.runErrors[id] ? "text-destructive" : "text-warning")}>
+ <p className={cn("flex items-start gap-1.5 text-[12px] leading-snug", v.runError ? "text-destructive" : "text-warning")}>
<AlertCircle className="mt-px size-3.5 shrink-0" />
{error}
</p>
@@ -605,76 +814,88 @@ const GeneratorNode = memo(function GeneratorNode({ id, type, data, selected }:
</div>
</NodeShell>
);
-});
+}, sameNodeProps);
// ---------------------------------------------------------------------------
// Inputs
const PromptNode = memo(function PromptNode({ id, type, data, selected }: NodeProps<FlowNode>) {
- const ed = useEditor();
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} out="text" menu={baseMenu(ed, id)} width={280}>
+ <NodeShell id={id} type={type} data={data} selected={!!selected} out="text" width={280}>
<div className="p-3">
<textarea
value={data.text ?? ""}
- onChange={(e) => ed.update(id, { text: e.target.value })}
- readOnly={ed.readOnly}
+ onChange={(e) => actions.update(id, { text: e.target.value })}
+ readOnly={readOnly}
rows={3}
+ maxLength={CANVAS_TEXT_MAX}
placeholder="e.g. “a lighthouse on a cliff at golden hour, cinematic”"
- aria-label="Text"
+ aria-label={`Text of ${data.label || "Text prompt"}`}
className={cn("field-sizing-content max-h-60 min-h-20 w-full resize-none rounded-lg bg-muted px-2.5 py-2 text-[13px] leading-snug outline-none placeholder:text-subtle-foreground focus:ring-2 focus:ring-brand-faint", NO_DRAG)}
/>
</div>
</NodeShell>
);
-});
+}, sameNodeProps);
const KIND_OF: Partial<Record<CanvasNodeType, "image" | "video" | "audio">> = { "image-input": "image", "video-input": "video", "audio-input": "audio" };
-function LibraryButton({ kind, onPick }: { kind: MediaKind; onPick: (url: string, name?: string) => void }) {
- const [open, setOpen] = useState(false);
+function LibraryGrid({ kind, onPick }: { kind: MediaKind; onPick: (url: string, name?: string) => void }) {
const assets = useAssets(undefined, kind);
return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <button className={chip}>
+ <>
+ <p className="px-1 pb-2 text-[13px] font-medium max-md:hidden">From your library</p>
+ {assets.isLoading ? (
+ <p className="py-6 text-center text-sm text-muted-foreground">Loading…</p>
+ ) : assets.data?.length ? (
+ <div className="grid max-h-72 grid-cols-4 gap-1.5 overflow-y-auto max-md:max-h-none">
+ {assets.data.map((a) => (
+ <button key={a.id} className="aspect-square overflow-hidden rounded-md bg-muted ring-primary transition hover:ring-2" onClick={() => onPick(a.url, a.name ?? undefined)} aria-label={a.name ?? "Library item"}>
+ {a.kind === "video" ? (
+ <video src={`${a.url}#t=0.1`} muted preload="metadata" className="size-full object-cover" />
+ ) : a.kind === "audio" ? (
+ <span className="grid size-full place-items-center bg-brand-faint text-brand-text">
+ <AudioLines className="size-4" />
+ </span>
+ ) : (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={a.url} alt="" loading="lazy" className="size-full object-cover" />
+ )}
+ </button>
+ ))}
+ </div>
+ ) : (
+ <p className="px-1 py-6 text-center text-sm text-muted-foreground">Nothing here yet.</p>
+ )}
+ </>
+ );
+}
+
+/** Pick an image, video or audio file from the library: a popover on the board, a sheet on phones. */
+export function LibraryButton({ kind, onPick, className }: { kind: MediaKind; onPick: (url: string, name?: string) => void; className?: string }) {
+ const [open, setOpen] = useState(false);
+ return (
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title="From your library"
+ className="w-80 p-2"
+ trigger={
+ <button className={className ?? chip}>
<Library className="size-3" /> Library
</button>
- </PopoverTrigger>
- <PopoverContent className="w-80 p-2" align="start" collisionPadding={12}>
- <p className="px-1 pb-2 text-[13px] font-medium">From your library</p>
- {assets.isLoading ? (
- <p className="py-6 text-center text-sm text-muted-foreground">Loading…</p>
- ) : assets.data?.length ? (
- <div className="grid max-h-72 grid-cols-4 gap-1.5 overflow-y-auto">
- {assets.data.map((a) => (
- <button
- key={a.id}
- className="aspect-square overflow-hidden rounded-md bg-muted ring-primary transition hover:ring-2"
- onClick={() => {
- onPick(a.url, a.name ?? undefined);
- setOpen(false);
- }}
- aria-label={a.name ?? "Library item"}
- >
- {a.kind === "video" ? (
- <video src={`${a.url}#t=0.1`} muted preload="metadata" className="size-full object-cover" />
- ) : a.kind === "audio" ? (
- <span className="grid size-full place-items-center bg-brand-faint text-brand-text">
- <AudioLines className="size-4" />
- </span>
- ) : (
- // eslint-disable-next-line @next/next/no-img-element
- <img src={a.url} alt="" loading="lazy" className="size-full object-cover" />
- )}
- </button>
- ))}
- </div>
- ) : (
- <p className="px-1 py-6 text-center text-sm text-muted-foreground">Nothing here yet.</p>
- )}
- </PopoverContent>
- </Popover>
+ }
+ >
+ <LibraryGrid
+ kind={kind}
+ onPick={(url, name) => {
+ onPick(url, name);
+ setOpen(false);
+ }}
+ />
+ </ResponsivePanel>
);
}
@@ -692,7 +913,8 @@ function MediaPreview({ kind, url }: { kind: MediaKind; url: string }) {
}
const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }: NodeProps<FlowNode>) {
- const ed = useEditor();
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
const kind = KIND_OF[type]!;
const input = useRef<HTMLInputElement>(null);
const [pending, setPending] = useState<SlotValue | null>(null);
@@ -704,17 +926,17 @@ const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }
if (!v) return setPending(null);
if (v.uploading) return setPending(v);
setPending(null);
- ed.update(id, { url: v.ref, name: v.name });
+ actions.update(id, { url: v.ref, name: v.name });
},
kind,
);
const accept = kind === "image" ? "image/png,image/jpeg,image/webp,image/gif" : kind === "video" ? "video/mp4,video/webm,video/quicktime" : "audio/*";
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} out={kind} menu={baseMenu(ed, id)} width={260}>
+ <NodeShell id={id} type={type} data={data} selected={!!selected} out={kind} width={260}>
<div
className="space-y-2 p-3"
onDragOver={(e) => {
- if (ed.readOnly || !e.dataTransfer.types.includes("Files")) return;
+ if (readOnly || !e.dataTransfer.types.includes("Files")) return;
e.preventDefault();
e.stopPropagation();
setOver(true);
@@ -722,7 +944,7 @@ const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }
onDragLeave={() => setOver(false)}
onDrop={(e) => {
const f = e.dataTransfer.files?.[0];
- if (!f || ed.readOnly) return;
+ if (!f || readOnly) return;
e.preventDefault();
e.stopPropagation();
setOver(false);
@@ -741,7 +963,7 @@ const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }
) : (
<button
onClick={() => input.current?.click()}
- disabled={ed.readOnly}
+ disabled={readOnly}
className={cn(
"flex h-28 w-full flex-col items-center justify-center gap-1 rounded-lg border border-dashed border-border-strong text-muted-foreground transition-colors hover:border-primary hover:bg-brand-faint hover:text-brand-text",
over && "border-primary bg-brand-faint text-brand-text",
@@ -752,16 +974,16 @@ const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }
<span className="text-[12px] font-medium">Drop {kind === "audio" ? "an audio file" : `a${kind === "image" ? "n" : ""} ${kind}`} or click to upload</span>
</button>
)}
- {!ed.readOnly && (
+ {!readOnly && (
<div className="flex flex-wrap gap-1">
{data.url && (
<button className={chip} onClick={() => input.current?.click()}>
<Upload className="size-3" /> Replace
</button>
)}
- <LibraryButton kind={kind} onPick={(url, name) => ed.update(id, { url, name })} />
+ <LibraryButton kind={kind} onPick={(url, name) => actions.update(id, { url, name })} />
{data.url && (
- <button className={chip} onClick={() => ed.update(id, { url: undefined, name: undefined })} aria-label="Remove file">
+ <button className={chip} onClick={() => actions.update(id, { url: undefined, name: undefined })} aria-label="Remove file">
<X className="size-3" /> Remove
</button>
)}
@@ -781,94 +1003,115 @@ const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }
</div>
</NodeShell>
);
-});
+}, sameNodeProps);
-const ElementNode = memo(function ElementNode({ id, type, data, selected }: NodeProps<FlowNode>) {
- const ed = useEditor();
- const elements = useElements();
+/** Pick an @character, location, prop or style from Elements (a popover on the board, a sheet on phones). */
+export function ElementPicker({ data, onPick, className }: { data: CanvasNodeData; onPick: (patch: Partial<CanvasNodeData>) => void; className?: string }) {
const [open, setOpen] = useState(false);
+ return (
+ <ResponsivePanel open={open} onOpenChange={setOpen} title="Pick an element" className="w-72 p-1.5" trigger={<button className={className ?? chip}>{data.handle ? "Change" : "Pick an element"}</button>}>
+ <ElementList
+ current={data.elementId}
+ onPick={(patch) => {
+ onPick(patch);
+ setOpen(false);
+ }}
+ />
+ </ResponsivePanel>
+ );
+}
+
+function ElementList({ current, onPick }: { current?: string; onPick: (patch: Partial<CanvasNodeData>) => void }) {
+ const elements = useElements();
const visual = (elements.data ?? []).filter((e) => e.kind !== "voice");
- const el = visual.find((e) => e.id === data.elementId);
- const preview = el?.references[0] ?? data.preview;
+ if (elements.isLoading) return <p className="p-3 text-[13px] text-muted-foreground">Loading…</p>;
+ if (!visual.length) {
+ return (
+ <p className="p-3 text-[13px] text-muted-foreground">
+ No elements yet.{" "}
+ <Link href="/elements" className="text-brand-text underline-offset-4 hover:underline">
+ Create one
+ </Link>
+ </p>
+ );
+ }
+ return (
+ <div className="max-h-72 overflow-y-auto max-md:max-h-none">
+ {visual.map((e) => (
+ <button
+ key={e.id}
+ onClick={() => onPick({ elementId: e.id, handle: e.handle, name: e.name, preview: e.references[0] })}
+ className={cn("flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left hover:bg-accent", e.id === current && "bg-brand-faint")}
+ >
+ <span className="size-8 shrink-0 overflow-hidden rounded-md bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {e.references[0] && <img src={e.references[0]} alt="" className="size-full object-cover" />}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium">{e.name}</span>
+ <span className="block truncate text-[11px] text-muted-foreground">
+ @{e.handle} · {e.kind}
+ </span>
+ </span>
+ {e.id === current && <Check className="size-3.5 text-brand-text" />}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+const ElementNode = memo(function ElementNode({ id, type, data, selected }: NodeProps<FlowNode>) {
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} out="element" menu={baseMenu(ed, id)} width={240}>
+ <NodeShell id={id} type={type} data={data} selected={!!selected} out="element" width={240}>
<div className="space-y-2 p-3">
{data.handle ? (
<div className="flex items-center gap-2.5">
<span className="size-12 shrink-0 overflow-hidden rounded-lg bg-muted">
{/* eslint-disable-next-line @next/next/no-img-element */}
- {preview && <img src={preview} alt="" className="size-full object-cover" />}
+ {data.preview && <img src={data.preview} alt="" className="size-full object-cover" />}
</span>
<span className="min-w-0">
- <span className="block truncate text-[13px] font-medium">{el?.name ?? data.name ?? data.handle}</span>
+ <span className="block truncate text-[13px] font-medium">{data.name ?? data.handle}</span>
<span className="block truncate font-mono text-[12px] text-brand-text">@{data.handle}</span>
</span>
</div>
) : (
<p className="text-[12px] text-muted-foreground">Adds an @character, location, prop or style to the models it connects to.</p>
)}
- {!ed.readOnly && (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <button className={chip}>{data.handle ? "Change" : "Pick an element"}</button>
- </PopoverTrigger>
- <PopoverContent className="w-72 p-1.5" align="start" collisionPadding={12}>
- {visual.length ? (
- <div className="max-h-72 overflow-y-auto">
- {visual.map((e) => (
- <button
- key={e.id}
- onClick={() => {
- ed.update(id, { elementId: e.id, handle: e.handle, name: e.name, preview: e.references[0], label: data.label });
- setOpen(false);
- }}
- className={cn("flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left hover:bg-accent", e.id === data.elementId && "bg-brand-faint")}
- >
- <span className="size-8 shrink-0 overflow-hidden rounded-md bg-muted">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- {e.references[0] && <img src={e.references[0]} alt="" className="size-full object-cover" />}
- </span>
- <span className="min-w-0 flex-1">
- <span className="block truncate text-[13px] font-medium">{e.name}</span>
- <span className="block truncate text-[11px] text-muted-foreground">
- @{e.handle} · {e.kind}
- </span>
- </span>
- {e.id === data.elementId && <Check className="size-3.5 text-brand-text" />}
- </button>
- ))}
- </div>
- ) : (
- <p className="p-3 text-[13px] text-muted-foreground">
- No elements yet.{" "}
- <Link href="/elements" className="text-brand-text underline-offset-4 hover:underline">
- Create one
- </Link>
- </p>
- )}
- </PopoverContent>
- </Popover>
- )}
+ {!readOnly && <ElementPicker data={data} onPick={(patch) => actions.update(id, patch)} />}
</div>
</NodeShell>
);
-});
+}, sameNodeProps);
// ---------------------------------------------------------------------------
// Output preview and notes
-const OutputNode = memo(function OutputNode({ id, type, data, selected }: NodeProps<FlowNode>) {
- const ed = useEditor();
- const nodes = useMemo(() => new Map(ed.graph.nodes.map((n) => [n.id, n])), [ed.graph.nodes]);
- // The saved width (templates set one), not React Flow's measured width (that would feed back).
- const width = nodes.get(id)?.width;
- const sources = ed.graph.edges
+type Source = Pick<CanvasNode, "id" | "type" | "data">;
+
+const sameSources = (a: Source[], b: Source[]) => a.length === b.length && a.every((s, i) => s.id === b[i].id && s.type === b[i].type && s.data === b[i].data);
+
+/** What feeds an Output node, top to bottom. */
+const selectSources = (s: EditorSnapshot, id: string): Source[] =>
+ s.graph.edges
.filter((e) => e.target === id)
- .map((e) => nodes.get(e.source))
+ .map((e) => s.byId.get(e.source))
.filter((n): n is CanvasNode => !!n)
- .sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x);
+ .sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x)
+ .map((n) => ({ id: n.id, type: n.type, data: n.data }));
+
+/** The saved width (templates set one), not React Flow's measured width (that would feed back). */
+const selectWidth = (s: EditorSnapshot, id: string) => s.byId.get(id)?.width;
+
+const OutputNode = memo(function OutputNode({ id, type, data, selected }: NodeProps<FlowNode>) {
+ const actions = useEditorActions();
+ // Re-renders only when that list or one of those nodes changes.
+ const sources = useEditorSelector(selectSources, id, sameSources);
+ const width = useEditorSelector(selectWidth, id);
const w = width ?? (sources.length > 1 ? 560 : 320);
- const menu: MenuItem[] = [{ label: "Run what feeds this", icon: Play, onSelect: () => ed.run([id]) }, ...baseMenu(ed, id)];
+ const menu: MenuItem[] = [{ label: "Run what feeds this", icon: Play, onSelect: () => actions.run([id]) }];
return (
<NodeShell id={id} type={type} data={data} selected={!!selected} menu={menu} width={w}>
<div className="relative p-3">
@@ -888,13 +1131,13 @@ const OutputNode = memo(function OutputNode({ id, type, data, selected }: NodePr
</div>
</NodeShell>
);
-});
+}, sameNodeProps);
-function SourcePreview({ node }: { node: CanvasNode }) {
- const ed = useEditor();
+function SourcePreview({ node }: { node: Source }) {
+ const actions = useEditorActions();
+ const r = useNodeResults(node.id);
if (isGenerator(node)) {
- const r = ed.results(node.id);
- if (r.outputs.length) return <OutputThumb o={r.outputs[0].o} onOpen={() => ed.open(node.id, 0)} large />;
+ if (r.outputs.length) return <OutputThumb o={r.outputs[0].o} onOpen={() => actions.open(node.id, 0)} large />;
if (r.state !== "idle") return <Results id={node.id} r={r} compact />;
return <div className="grid h-20 place-items-center rounded-lg bg-muted text-[11px] text-subtle-foreground">Not run yet</div>;
}
@@ -905,15 +1148,17 @@ function SourcePreview({ node }: { node: CanvasNode }) {
}
const NoteNode = memo(function NoteNode({ id, type, data, selected }: NodeProps<FlowNode>) {
- const ed = useEditor();
+ const actions = useEditorActions();
+ const { readOnly } = useEditorGlobals();
return (
- <NodeShell id={id} type={type} data={data} selected={!!selected} menu={baseMenu(ed, id)} width={240} tone="note">
+ <NodeShell id={id} type={type} data={data} selected={!!selected} width={240} tone="note">
<div className="p-3">
<textarea
value={data.text ?? ""}
- onChange={(e) => ed.update(id, { text: e.target.value })}
- readOnly={ed.readOnly}
+ onChange={(e) => actions.update(id, { text: e.target.value })}
+ readOnly={readOnly}
rows={3}
+ maxLength={CANVAS_TEXT_MAX}
placeholder="A note for this board"
aria-label="Note"
className={cn("field-sizing-content max-h-72 min-h-16 w-full resize-none bg-transparent text-[13px] leading-snug outline-none placeholder:text-muted-foreground", NO_DRAG)}
@@ -921,7 +1166,7 @@ const NoteNode = memo(function NoteNode({ id, type, data, selected }: NodeProps<
</div>
</NodeShell>
);
-});
+}, sameNodeProps);
export const NODE_TYPES = {
prompt: PromptNode,
diff --git a/src/components/canvas/palette.tsx b/src/components/canvas/palette.tsx
index 33449260..4d1ed562 100644
--- a/src/components/canvas/palette.tsx
+++ b/src/components/canvas/palette.tsx
@@ -1,7 +1,7 @@
"use client";
import { PanelLeftClose, Plus, Search } from "lucide-react";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { memo, useEffect, useMemo, useRef, useState } from "react";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { NodeGroup, PaletteItem } from "@/lib/catalog/canvas";
@@ -14,7 +14,7 @@ const GROUPS: NodeGroup[] = ["Inputs", "Generate", "Utilities", "Output"];
const matches = (p: PaletteItem, q: string) => !q || `${p.label} ${p.description} ${p.keywords ?? ""}`.toLowerCase().includes(q.toLowerCase());
/** The left-hand node palette (desktop): search, drag onto the board or click to add in the middle. */
-export function Palette({ items, onAdd, onClose }: { items: PaletteItem[]; onAdd: (p: PaletteItem) => void; onClose: () => void }) {
+export const Palette = memo(function Palette({ items, onAdd, onClose }: { items: PaletteItem[]; onAdd: (p: PaletteItem) => void; onClose: () => void }) {
const [q, setQ] = useState("");
const shown = useMemo(() => items.filter((p) => matches(p, q)), [items, q]);
return (
@@ -47,6 +47,20 @@ export function Palette({ items, onAdd, onClose }: { items: PaletteItem[]; onAdd
<div key={group}>
<p className="px-1.5 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{group}</p>
{list.map((p) => {
+ // An entry with no model on the only engine this install allows: shown, with why, but not addable.
+ if (p.disabled) {
+ return (
+ <div key={p.id} className="flex w-full cursor-not-allowed items-start gap-2.5 rounded-lg px-1.5 py-1.5 text-left opacity-60" title={p.disabled} aria-disabled="true">
+ <span className="grid size-7 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground">
+ <NodeIcon name={p.icon} className="size-3.5" />
+ </span>
+ <span className="min-w-0">
+ <span className="block truncate text-[13px] font-medium">{p.label}</span>
+ <span className="line-clamp-2 text-[11px] leading-snug text-muted-foreground">{p.disabled}</span>
+ </span>
+ </div>
+ );
+ }
return (
<button
key={p.id}
@@ -76,7 +90,7 @@ export function Palette({ items, onAdd, onClose }: { items: PaletteItem[]; onAdd
</div>
</aside>
);
-}
+});
export function PaletteToggle({ onOpen }: { onOpen: () => void }) {
return (
@@ -123,9 +137,10 @@ export function AddMenu({ x, y, items, title, onPick, onClose }: { x: number; y:
<CommandGroup key={group} heading={group}>
{list.map((p) => {
return (
- <CommandItem key={p.id} value={`${p.label} ${p.keywords ?? ""}`} onSelect={() => onPick(p)} className="gap-2">
+ <CommandItem key={p.id} value={`${p.label} ${p.keywords ?? ""}`} onSelect={() => onPick(p)} disabled={!!p.disabled} title={p.disabled} className="gap-2">
<NodeIcon name={p.icon} className="size-4 text-muted-foreground" />
<span className="truncate text-[13px]">{p.label}</span>
+ {p.disabled && <span className="ml-auto shrink-0 text-[11px] text-muted-foreground">not on this engine</span>}
</CommandItem>
);
})}
diff --git a/src/components/canvas/use-canvas.ts b/src/components/canvas/use-canvas.ts
index b738a953..9806f839 100644
--- a/src/components/canvas/use-canvas.ts
+++ b/src/components/canvas/use-canvas.ts
@@ -1,7 +1,7 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useEffect, useRef, useState } from "react";
+import { useGenerationStream } from "@/lib/api";
import type { Canvas, CanvasGraph, CanvasPlan, CanvasSummary } from "@/lib/catalog/canvas";
import type { Engine, Generation } from "@/lib/catalog/types";
@@ -9,7 +9,7 @@ import type { Engine, Generation } from "@/lib/catalog/types";
async function json<T>(res: Response): Promise<T> {
const body = (await res.json().catch(() => ({}))) as T & { error?: string };
- if (!res.ok) throw Object.assign(new Error(body.error ?? `Request failed (${res.status})`), { body });
+ if (!res.ok) throw Object.assign(new Error(body.error ?? `Request failed (${res.status})`), { body, status: res.status });
return body;
}
@@ -31,10 +31,12 @@ export function useCanvases() {
}
/**
- * One canvas with its nodes' generations. Polls while something renders (slower when the live
- * stream delivers updates).
+ * One canvas with its nodes' generations. The app's shared live stream (src/lib/api.ts) patches
+ * the generations as jobs move, are trashed or restored; polling is the fallback while something
+ * renders (a slow safety net when the stream is connected).
*/
-export function useCanvasView(id: string, live: boolean) {
+export function useCanvasView(id: string) {
+ const live = useGenerationStream();
return useQuery({
queryKey: ["canvases", id],
queryFn: async () => json<CanvasView>(await fetch(`/api/canvases/${id}`)),
@@ -109,43 +111,3 @@ export function useRunCanvas(id: string) {
},
});
}
-
-/**
- * Live generation updates from GET /api/generations/stream (when this install has it): patches the
- * canvas view as soon as a node's job moves. Returns whether the stream is connected; without it
- * the view falls back to polling.
- */
-export function useLiveGenerations(id: string): boolean {
- const qc = useQueryClient();
- const [live, setLive] = useState(false);
- const failed = useRef(false);
- useEffect(() => {
- if (failed.current || typeof EventSource === "undefined") return;
- const es = new EventSource("/api/generations/stream");
- es.onopen = () => setLive(true);
- es.onerror = () => {
- // A missing endpoint (404) or a dropped connection: poll instead; don't hammer the server.
- if (es.readyState === EventSource.CLOSED) {
- failed.current = true;
- setLive(false);
- }
- };
- es.addEventListener("generation", (e) => {
- let g: Generation;
- try {
- g = JSON.parse((e as MessageEvent<string>).data) as Generation;
- } catch {
- return;
- }
- qc.setQueryData<CanvasView>(["canvases", id], (old) => {
- if (!old || !old.generations.some((x) => x.id === g.id)) return old;
- return { ...old, generations: old.generations.map((x) => (x.id === g.id ? g : x)) };
- });
- });
- return () => {
- es.close();
- setLive(false);
- };
- }, [id, qc]);
- return live;
-}
diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsx
index d9d9031a..99d60106 100644
--- a/src/components/studio/model-picker.tsx
+++ b/src/components/studio/model-picker.tsx
@@ -111,27 +111,46 @@ function ModelRow({
);
}
-/**
- * Model picker on cmdk: Recent, Starred and "Best for this studio" above the full list for the
- * current engine; typing searches both engines at once (each row says which). A popover on
- * desktop, a bottom sheet on phones.
- */
-export function ModelPicker({
- models,
- value,
- onChange,
- engine,
- onEngineChange,
- defaultModels,
-}: {
+interface PickerProps {
models: ModelDef[];
value: ModelDef | undefined;
onChange: (m: ModelDef) => void;
engine: Engine;
onEngineChange: (e: Engine) => void;
defaultModels?: { cloud: string; open: string };
-}) {
+}
+
+/**
+ * Model picker on cmdk: Recent, Starred and "Best for this studio" above the full list for the
+ * current engine; typing searches both engines at once (each row says which). A popover on
+ * desktop, a bottom sheet on phones. The list is built only while the panel is open (a canvas
+ * board shows dozens of closed pickers).
+ */
+export function ModelPicker(props: PickerProps) {
const [open, setOpen] = useState(false);
+ const { value } = props;
+ return (
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title="Choose a model"
+ className="w-[min(92vw,440px)] p-0 shadow-strong"
+ sheetClassName="h-[80svh]"
+ trigger={
+ <Button variant="secondary" size="sm" className="h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label={`Model: ${value?.name ?? "none"}. Change model`}>
+ {value?.engine === "open" ? <Cpu className="size-3.5" /> : <Cloud className="size-3.5" />}
+ <span className="max-w-32 truncate sm:max-w-44">{value?.name ?? "Choose model"}</span>
+ <ChevronDown className="size-3.5 opacity-60" />
+ </Button>
+ }
+ >
+ <PickerList {...props} onPicked={() => setOpen(false)} />
+ </ResponsivePanel>
+ );
+}
+
+/** The searchable list (mounted by the popover / sheet only while it shows). */
+function PickerList({ models, value, onChange, engine, onEngineChange, defaultModels, onPicked }: PickerProps & { onPicked: () => void }) {
const [q, setQ] = useState("");
const status = useStatus().data;
const mode = useEngineMode();
@@ -149,89 +168,70 @@ export function ModelPicker({
const pick = (m: ModelDef) => {
onChange(m);
- setOpen(false);
- setQ("");
+ onPicked();
};
return (
- <ResponsivePanel
- open={open}
- onOpenChange={(o) => {
- setOpen(o);
- if (!o) setQ("");
- }}
- title="Choose a model"
- className="w-[min(92vw,440px)] p-0 shadow-strong"
- sheetClassName="h-[80svh]"
- trigger={
- <Button variant="secondary" size="sm" className="h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label={`Model: ${value?.name ?? "none"}. Change model`}>
- {value?.engine === "open" ? <Cpu className="size-3.5" /> : <Cloud className="size-3.5" />}
- <span className="max-w-32 truncate sm:max-w-44">{value?.name ?? "Choose model"}</span>
- <ChevronDown className="size-3.5 opacity-60" />
- </Button>
- }
- >
- <Command shouldFilter={false} loop label="Models" className="rounded-none! bg-transparent p-0">
- <div className="flex items-center gap-2 p-1 sm:p-2 sm:pb-1">
- <div className="min-w-0 flex-1 [&_[data-slot=command-input-wrapper]]:p-0">
- <CommandInput value={q} onValueChange={setQ} placeholder={mode === "both" ? "Search all models" : "Search models"} aria-label="Search models" autoFocus={!mobile} />
- </div>
- <EngineSwitch value={engine} onChange={onEngineChange} size="sm" />
- </div>
- <div className="flex items-baseline gap-x-2 px-3 pb-1.5 leading-snug text-[11px] text-muted-foreground sm:px-3.5">
- <span className="shrink-0 whitespace-nowrap tabular-nums">{q ? `${count} result${count === 1 ? "" : "s"}` : `${count} ${engine === "open" ? "open-source" : "cloud"} model${count === 1 ? "" : "s"}`}</span>
- {demo && (
- <>
- <span aria-hidden>·</span>
- <span className="min-w-0">
- Demo — no key connected, outputs are placeholders.{" "}
- <Link href="/settings" className="text-brand-text hover:underline">
- Connect
- </Link>
- </span>
- </>
- )}
+ <Command shouldFilter={false} loop label="Models" className="rounded-none! bg-transparent p-0">
+ <div className="flex items-center gap-2 p-1 sm:p-2 sm:pb-1">
+ <div className="min-w-0 flex-1 [&_[data-slot=command-input-wrapper]]:p-0">
+ <CommandInput value={q} onValueChange={setQ} placeholder={mode === "both" ? "Search all models" : "Search models"} aria-label="Search models" autoFocus={!mobile} />
</div>
- <CommandList className="max-h-[min(52vh,420px)] border-t sm:max-h-[min(56vh,440px)]">
- {groups.map((g) => (
- <CommandGroup key={g.id} heading={g.label}>
- {g.models.map((m) => (
- <CommandItem
- key={`${g.id}:${m.id}`}
- value={`${g.id}:${m.id}`}
- onSelect={() => pick(m)}
- data-checked={value?.id === m.id}
- className={cn("gap-2.5 rounded-lg px-2 py-1.5 [&>svg:last-child]:hidden", value?.id === m.id && "bg-brand-faint data-selected:bg-brand-faint-hover")}
- >
- <ModelRow m={m} selected={value?.id === m.id} starred={starred.includes(m.id)} showEngine={!!q || m.engine !== engine} onStar={() => setStarred((s) => toggleIn(s, m.id))} />
- </CommandItem>
- ))}
- </CommandGroup>
- ))}
- {!groups.length && (
- <div className="flex flex-col items-center gap-2 px-4 py-10 text-center">
- <SearchX className="size-5 text-subtle-foreground" />
- {noneForEngine ? (
- <>
- <p className="text-[13px] text-muted-foreground">No {engine === "open" ? "open-source" : "cloud"} models for this yet.</p>
- {engines.includes(otherEngine) && (
- <Button variant="secondary" size="sm" onClick={() => onEngineChange(otherEngine)}>
- Show {otherEngine === "open" ? "open-source" : "cloud"} models
- </Button>
- )}
- </>
- ) : (
- <>
- <p className="text-[13px] text-muted-foreground">No models match “{q}”</p>
- <Button variant="secondary" size="sm" onClick={() => setQ("")}>
- Clear search
+ <EngineSwitch value={engine} onChange={onEngineChange} size="sm" />
+ </div>
+ <div className="flex items-baseline gap-x-2 px-3 pb-1.5 leading-snug text-[11px] text-muted-foreground sm:px-3.5">
+ <span className="shrink-0 whitespace-nowrap tabular-nums">{q ? `${count} result${count === 1 ? "" : "s"}` : `${count} ${engine === "open" ? "open-source" : "cloud"} model${count === 1 ? "" : "s"}`}</span>
+ {demo && (
+ <>
+ <span aria-hidden>·</span>
+ <span className="min-w-0">
+ Demo — no key connected, outputs are placeholders.{" "}
+ <Link href="/settings" className="text-brand-text hover:underline">
+ Connect
+ </Link>
+ </span>
+ </>
+ )}
+ </div>
+ <CommandList className="max-h-[min(52vh,420px)] border-t sm:max-h-[min(56vh,440px)]">
+ {groups.map((g) => (
+ <CommandGroup key={g.id} heading={g.label}>
+ {g.models.map((m) => (
+ <CommandItem
+ key={`${g.id}:${m.id}`}
+ value={`${g.id}:${m.id}`}
+ onSelect={() => pick(m)}
+ data-checked={value?.id === m.id}
+ className={cn("gap-2.5 rounded-lg px-2 py-1.5 [&>svg:last-child]:hidden", value?.id === m.id && "bg-brand-faint data-selected:bg-brand-faint-hover")}
+ >
+ <ModelRow m={m} selected={value?.id === m.id} starred={starred.includes(m.id)} showEngine={!!q || m.engine !== engine} onStar={() => setStarred((s) => toggleIn(s, m.id))} />
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ ))}
+ {!groups.length && (
+ <div className="flex flex-col items-center gap-2 px-4 py-10 text-center">
+ <SearchX className="size-5 text-subtle-foreground" />
+ {noneForEngine ? (
+ <>
+ <p className="text-[13px] text-muted-foreground">No {engine === "open" ? "open-source" : "cloud"} models for this yet.</p>
+ {engines.includes(otherEngine) && (
+ <Button variant="secondary" size="sm" onClick={() => onEngineChange(otherEngine)}>
+ Show {otherEngine === "open" ? "open-source" : "cloud"} models
</Button>
- </>
- )}
- </div>
- )}
- </CommandList>
- </Command>
- </ResponsivePanel>
+ )}
+ </>
+ ) : (
+ <>
+ <p className="text-[13px] text-muted-foreground">No models match “{q}”</p>
+ <Button variant="secondary" size="sm" onClick={() => setQ("")}>
+ Clear search
+ </Button>
+ </>
+ )}
+ </div>
+ )}
+ </CommandList>
+ </Command>
);
}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 0296bfdf..7f3e840d 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -6,7 +6,20 @@ import { toast } from "sonner";
import type { AssistThread, AssistThreadSummary, AssistThreadView } from "./assist";
import type { ElementKind, StudioElement } from "./catalog/elements";
import type { Engine, Generation, GenerationRequest, MediaKind } from "./catalog/types";
-import { applyToList, applyToPages, applyToThread, backoff, parseSse, shareById, sharePagesById, toStreamEvent, type Pages, type StreamEvent } from "./generation-stream";
+import {
+ applyToCanvasView,
+ applyToList,
+ applyToPages,
+ applyToThread,
+ backoff,
+ parseSse,
+ shareById,
+ sharePagesById,
+ toStreamEvent,
+ type CanvasViewLike,
+ type Pages,
+ type StreamEvent,
+} from "./generation-stream";
import { filterToSearch, type FeedFilter, type Folder } from "./library";
export interface Asset {
@@ -58,6 +71,13 @@ function applyEvent(qc: QueryClient, ev: StreamEvent): void {
const next = applyToThread(data, ev);
if (next !== data) qc.setQueryData(q.queryKey, next);
}
+ // Canvas boards (["canvases", id]): a result trashed in the Viewer or the Library leaves its node.
+ for (const q of qc.getQueryCache().findAll({ queryKey: ["canvases"] })) {
+ if (q.queryKey.length !== 2 || typeof q.queryKey[1] !== "string") continue;
+ const data = q.state.data as CanvasViewLike | undefined;
+ const next = applyToCanvasView(data, ev);
+ if (next !== data) qc.setQueryData(q.queryKey, next);
+ }
}
/** The freshest copy of a generation in any cache (a viewer may hold an older object). */
@@ -69,6 +89,7 @@ function cached(qc: QueryClient, id: string): Generation | undefined {
for (const q of qc.getQueryCache().findAll({ queryKey: ["generations"] })) (q.state.data as Generation[] | undefined)?.forEach(consider);
for (const q of qc.getQueryCache().findAll({ queryKey: ["library"] })) (q.state.data as Pages | undefined)?.pages?.forEach((p) => p.forEach(consider));
for (const q of qc.getQueryCache().findAll({ queryKey: ["assist"] })) (q.state.data as AssistThreadView | undefined)?.generations?.forEach(consider);
+ for (const q of qc.getQueryCache().findAll({ queryKey: ["canvases"] })) if (q.queryKey.length === 2) (q.state.data as CanvasViewLike | undefined)?.generations?.forEach(consider);
return best;
}
@@ -117,6 +138,7 @@ async function connect() {
if (live.everConnected) {
void live.client.invalidateQueries({ queryKey: ["generations"] });
void live.client.invalidateQueries({ queryKey: ["library"] });
+ void live.client.invalidateQueries({ queryKey: ["canvases"] });
}
live.everConnected = true;
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
@@ -137,8 +159,8 @@ async function connect() {
if (live.abort === ctrl) scheduleReconnect(false);
}
-/** Share one stream between every list on the page; returns whether it's connected. */
-function useGenerationStream(): boolean {
+/** Share one stream between every list on the page (and canvas boards); returns whether it's connected. */
+export function useGenerationStream(): boolean {
const qc = useQueryClient();
useEffect(() => {
live.client = qc;
diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.ts
index 628f97fe..8f82f38b 100644
--- a/src/lib/catalog/canvas.ts
+++ b/src/lib/catalog/canvas.ts
@@ -1148,6 +1148,8 @@ function tpl(nodes: TplNode[], edges: [string, string, string?][]): (engine: Eng
/** Column and row spacing: a generator node with a result is about 300 × 460 px. */
const COL = 380;
const ROW = 500;
+/** A video node with its clip is taller (four inputs, prompt, settings, result). */
+const FILM_ROW = 620;
export const CANVAS_TEMPLATES: CanvasTemplate[] = [
{
@@ -1204,13 +1206,13 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [
hue: 200,
build: tpl(
[
- { id: "script", type: "prompt", x: 0, y: ROW, data: { label: "Script", text: "A paper boat sails down a rain-soaked city gutter, rides a little waterfall into a storm drain and comes out on a sunny canal." } },
+ { id: "script", type: "prompt", x: 0, y: FILM_ROW, data: { label: "Script", text: "A paper boat sails down a rain-soaked city gutter, rides a little waterfall into a storm drain and comes out on a sunny canal." } },
// The script reaches every shot through a text model: edit the script and all three shots follow.
...[0, 1, 2].map((i) => ({
id: `beat${i + 1}`,
type: "model" as const,
x: COL,
- y: i * ROW,
+ y: i * FILM_ROW,
data: {
mediaKind: "text" as const,
label: `Shot ${i + 1} text`,
@@ -1223,7 +1225,7 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [
id: `frame${i + 1}`,
type: "model" as const,
x: COL * 2,
- y: i * ROW,
+ y: i * FILM_ROW,
data: { mediaKind: "image" as const, label: `Frame ${i + 1}`, prompt: "Cinematic storyboard still, one consistent look across the film: {text}", params: { aspectRatio: "16:9" } },
models: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" },
})),
@@ -1231,12 +1233,12 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [
id: `shot${i + 1}`,
type: "model" as const,
x: COL * 3,
- y: i * ROW,
+ y: i * FILM_ROW,
data: { mediaKind: "video" as const, label: `Shot ${i + 1}`, op: "i2v" as const, prompt: "Animate this moment, smooth cinematic camera move: {text}", params: { aspectRatio: "16:9", duration: 5 } },
models: { cloud: "kling-2-5-turbo", open: "oss-wan22-14b-fast" },
})),
- { id: "film", type: "join", x: COL * 4, y: ROW / 2, data: { label: "Film" }, models: { cloud: "join-clips", open: "oss-join-clips" } },
- { id: "out", type: "output", x: COL * 4, y: ROW * 1.5, data: { label: "Film" } },
+ { id: "film", type: "join", x: COL * 4, y: FILM_ROW / 2, data: { label: "Film" }, models: { cloud: "join-clips", open: "oss-join-clips" } },
+ { id: "out", type: "output", x: COL * 4, y: FILM_ROW * 1.5, data: { label: "Film" } },
],
[
["script", "beat1", "prompt"],
diff --git a/src/lib/generation-stream.ts b/src/lib/generation-stream.ts
index 1d93e66c..014ff9fb 100644
--- a/src/lib/generation-stream.ts
+++ b/src/lib/generation-stream.ts
@@ -124,6 +124,31 @@ export function applyToThread<T extends { generations: Generation[] }>(view: T |
return { ...view, generations };
}
+/** The shape of a canvas board's cache (["canvases", id]): the board's runs and the generations they made. */
+export interface CanvasViewLike {
+ canvas: { runs: Record<string, { ids: string[] }> };
+ generations: Generation[];
+}
+
+/**
+ * A canvas board holds the generations its nodes made: patch them by id, drop trashed or deleted
+ * ones (the node then reads as not run), and bring back a restored one that a node's run still names.
+ */
+export function applyToCanvasView<T extends CanvasViewLike>(view: T | undefined, ev: StreamEvent): T | undefined {
+ if (!view) return view;
+ const id = ev.type === "deleted" ? ev.id : ev.generation.id;
+ const at = view.generations.findIndex((g) => g.id === id);
+ if (ev.type === "deleted" || ev.generation.deletedAt) return at < 0 ? view : { ...view, generations: view.generations.filter((g) => g.id !== id) };
+ if (at >= 0) {
+ if (view.generations[at].updatedAt > ev.generation.updatedAt) return view;
+ const generations = view.generations.slice();
+ generations[at] = ev.generation;
+ return { ...view, generations };
+ }
+ const ours = Object.values(view.canvas.runs).some((r) => r.ids.includes(id));
+ return ours ? { ...view, generations: [...view.generations, ev.generation] } : view;
+}
+
/**
* Structural sharing by id for generation lists. React Query's default compares arrays index by
* index, so one new result at the top (everything shifts by one) would hand every row a new
diff --git a/tests/canvas-editor-state.test.ts b/tests/canvas-editor-state.test.ts
new file mode 100644
index 00000000..2aa921c8
--- /dev/null
+++ b/tests/canvas-editor-state.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from "vitest";
+import { buildViews, EMPTY_RESULTS, foldResultsKeep, type NodeResults } from "@/components/canvas/canvas-context";
+import { describeNode, planCanvas, type CanvasGraph, type CanvasNode } from "@/lib/catalog/canvas";
+import type { Generation } from "@/lib/catalog/types";
+import { applyToCanvasView, type CanvasViewLike } from "@/lib/generation-stream";
+
+let n = 0;
+function gen(p: Partial<Generation> = {}): Generation {
+ n++;
+ return {
+ id: p.id ?? `g${n}`,
+ batchId: null,
+ feature: "canvas",
+ presetId: null,
+ modelId: "nano-banana-pro",
+ engine: "cloud",
+ provider: "mock",
+ op: "t2i",
+ kind: "image",
+ status: "succeeded",
+ progress: 1,
+ message: null,
+ prompt: "a fox",
+ request: { feature: "canvas", modelId: "nano-banana-pro", prompt: "a fox" },
+ outputs: [{ url: `/api/files/outputs/d/${n}.png`, kind: "image" }],
+ error: null,
+ costUsd: 0,
+ favorite: false,
+ createdAt: 1000 + n,
+ updatedAt: 1000 + n,
+ completedAt: null,
+ deletedAt: null,
+ folderId: null,
+ ...p,
+ };
+}
+
+describe("canvas board cache ← live stream", () => {
+ const view = (gens: Generation[], ids = gens.map((g) => g.id)): CanvasViewLike => ({ canvas: { runs: { img: { ids } } }, generations: gens });
+
+ it("replaces a result by id, ignoring late events and other boards' generations", () => {
+ const a = gen({ status: "running", updatedAt: 10 });
+ const v = view([a]);
+ const done = { ...a, status: "succeeded" as const, updatedAt: 20 };
+ expect(applyToCanvasView(v, { type: "generation", generation: done })!.generations).toEqual([done]);
+ // An older copy (a late event) changes nothing.
+ expect(applyToCanvasView(v, { type: "generation", generation: { ...a, updatedAt: 5 } })).toBe(v);
+ // Someone else's generation: same object back.
+ expect(applyToCanvasView(v, { type: "generation", generation: gen() })).toBe(v);
+ });
+
+ it("drops a result moved to the Trash (Viewer → Delete) and brings it back on Restore", () => {
+ const a = gen();
+ const v = view([a]);
+ const trashed = applyToCanvasView(v, { type: "generation", generation: { ...a, deletedAt: 99, updatedAt: a.updatedAt + 1 } })!;
+ expect(trashed.generations).toEqual([]);
+ expect(applyToCanvasView(v, { type: "deleted", id: a.id })!.generations).toEqual([]);
+ // Restored: the node's run still names it, so it comes back.
+ const restored = { ...a, deletedAt: null, updatedAt: a.updatedAt + 2 };
+ expect(applyToCanvasView(trashed, { type: "generation", generation: restored })!.generations).toEqual([restored]);
+ expect(applyToCanvasView(undefined, { type: "deleted", id: a.id })).toBeUndefined();
+ });
+});
+
+describe("canvas node views", () => {
+ const graph: CanvasGraph = {
+ nodes: [
+ { id: "p", type: "prompt", position: { x: 0, y: 0 }, data: { text: "A red fox" } },
+ { id: "img", type: "model", position: { x: 300, y: 0 }, data: { modelId: "nano-banana-pro" } },
+ { id: "vid", type: "model", position: { x: 600, y: 0 }, data: { modelId: "kling-2-5-turbo", op: "i2v", prompt: "It runs" } },
+ ],
+ edges: [
+ { id: "e1", source: "p", sourceHandle: "out", target: "img", targetHandle: "prompt" },
+ { id: "e2", source: "img", sourceHandle: "out", target: "vid", targetHandle: "images" },
+ ],
+ };
+ const describe_ = (g: CanvasGraph) => (id: string) => describeNode(g, g.nodes.find((x) => x.id === id)!);
+
+ it("keeps every unchanged node's view object, so only the edited node re-renders", () => {
+ const plan = planCanvas(graph);
+ const results = new Map<string, NodeResults>();
+ const first = buildViews(null, graph, plan, describe_(graph), results, {});
+ expect(first.get("img")).toMatchObject({ op: "t2i", counts: { prompt: 1 }, step: "new", reused: false, results: EMPTY_RESULTS });
+ expect(first.get("vid")).toMatchObject({ op: "i2v", counts: { images: 1 } });
+ expect(first.has("p")).toBe(false);
+
+ // Nothing changed: identical objects.
+ const same = buildViews(first, graph, planCanvas(graph), describe_(graph), results, {});
+ expect(same.get("img")).toBe(first.get("img"));
+ expect(same.get("vid")).toBe(first.get("vid"));
+
+ // The video's own prompt changes: the image's view is untouched.
+ const edited: CanvasGraph = { ...graph, nodes: graph.nodes.map((x): CanvasNode => (x.id === "vid" ? { ...x, data: { ...x.data, prompt: "" } } : x)) };
+ const next = buildViews(first, edited, planCanvas(edited), describe_(edited), results, { vid: "Nope" });
+ expect(next.get("img")).toBe(first.get("img"));
+ expect(next.get("vid")).not.toBe(first.get("vid"));
+ expect(next.get("vid")).toMatchObject({ error: "Write a prompt first", runError: "Nope" });
+ });
+
+ it("folds a node's results once per change of its generations", () => {
+ const a = gen();
+ const r = foldResultsKeep(undefined, [a]);
+ expect(r).toMatchObject({ state: "succeeded", outputs: [{ g: a, i: 0 }] });
+ expect(foldResultsKeep(r, [a])).toBe(r);
+ const b = { ...a, status: "running" as const, progress: 0.5 };
+ expect(foldResultsKeep(r, [b])).toMatchObject({ state: "running", progress: 0.5 });
+ expect(foldResultsKeep(r, [])).toBe(EMPTY_RESULTS);
+ });
+});
diff --git a/tests/e2e/canvas-smoke.mjs b/tests/e2e/canvas-smoke.mjs
new file mode 100644
index 00000000..47f42b29
--- /dev/null
+++ b/tests/e2e/canvas-smoke.mjs
@@ -0,0 +1,149 @@
+// Canvas editor smoke test: the save and run state machine, in a real browser.
+// Usage: node tests/e2e/canvas-smoke.mjs [appUrl] [--perf=60]
+// (app must be running in demo mode: no keys, COMFYUI_URL pointing nowhere). Exits 1 on any failure.
+//
+// Checks:
+// 1. An edit followed at once by an in-app link (the debounce hasn't fired) reaches the server.
+// 2. Renaming a canvas and then back to its first name is saved.
+// 3. A result moved to the Trash from the Viewer leaves its node, and Run all makes it again.
+// 4. --perf=N: a board of N nodes (prompt → image → video chains) loads, and typing in one prompt
+// repaints within budget (prints keystroke → paint times; fails above 50 ms on average).
+//
+// Playwright: the `playwright` (or `playwright-core`) package if it resolves, else the global install
+// at /opt/node22/lib/node_modules. Chromium: $CHROMIUM_PATH, else the newest /opt/pw-browsers/chromium-*.
+import fs from "node:fs";
+import path from "node:path";
+import { createRequire } from "node:module";
+import { fileURLToPath } from "node:url";
+
+const args = process.argv.slice(2);
+const app = (args.find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
+const perf = Number(args.find((a) => a.startsWith("--perf="))?.slice(7) ?? 0);
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
+
+function loadPlaywright() {
+ for (const from of [path.join(root, "package.json"), "/opt/node22/lib/node_modules/"]) {
+ const req = createRequire(from);
+ for (const name of ["playwright", "playwright-core"]) {
+ try {
+ return req(name);
+ } catch {}
+ }
+ }
+ throw new Error("Playwright not found: install playwright-core or run where the global install exists");
+}
+
+function chromiumPath() {
+ if (process.env.CHROMIUM_PATH) return process.env.CHROMIUM_PATH;
+ const dir = "/opt/pw-browsers";
+ if (!fs.existsSync(dir)) return undefined;
+ const newest = fs
+ .readdirSync(dir)
+ .filter((d) => /^chromium-\d+$/.test(d))
+ .sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]))[0];
+ const exe = newest && path.join(dir, newest, "chrome-linux/chrome");
+ return exe && fs.existsSync(exe) ? exe : undefined;
+}
+
+const api = async (p, init) => (await fetch(app + p, { headers: { "Content-Type": "application/json" }, ...init })).json();
+const failures = [];
+const check = (label, ok, detail = "") => {
+ console.log(`${ok ? "ok " : "FAIL"} ${label}${detail ? ` (${detail})` : ""}`);
+ if (!ok) failures.push(label);
+};
+
+const { chromium } = loadPlaywright();
+const browser = await chromium.launch({ executablePath: chromiumPath() });
+const page = await (await browser.newContext({ viewport: { width: 1440, height: 900 } })).newPage();
+page.on("pageerror", (e) => failures.push(`page error: ${e.message}`));
+
+try {
+ // 1. Edit, then leave through the back link before the autosave debounce fires.
+ const c = await api("/api/canvases", { method: "POST", body: JSON.stringify({ name: "Smoke test" }) });
+ await page.goto(`${app}/canvas/${c.id}`, { waitUntil: "load" });
+ await page.getByRole("button", { name: /Start with Text → Image/ }).click();
+ const prompt = page.locator('[data-testid^="canvas-node-prompt-"] textarea');
+ await prompt.waitFor();
+ await prompt.fill("A paper boat on a canal");
+ await page.getByRole("link", { name: "All canvases" }).click();
+ await page.waitForURL(/\/canvas$/);
+ await page.waitForTimeout(800);
+ const saved = await api(`/api/canvases/${c.id}`);
+ check("an edit made just before leaving is saved", saved.canvas.graph.nodes.find((n) => n.type === "prompt")?.data.text === "A paper boat on a canal");
+
+ // 2. Rename, then back.
+ await page.goto(`${app}/canvas/${c.id}`, { waitUntil: "load" });
+ const name = page.getByRole("textbox", { name: "Canvas name" });
+ await name.fill("Renamed once");
+ await name.press("Enter");
+ await page.waitForTimeout(500);
+ await name.fill("Smoke test");
+ await name.press("Enter");
+ await page.waitForTimeout(600);
+ check("renaming back to the first name is saved", (await api(`/api/canvases/${c.id}`)).canvas.name === "Smoke test");
+
+ // 3. Run, trash the result from the Viewer, run again.
+ const image = page.locator('[data-testid^="canvas-node-model-"]').first();
+ await page.getByRole("button", { name: "Run all", exact: true }).click();
+ const thumb = image.locator('button[aria-label="Open result"]').first();
+ await thumb.waitFor({ timeout: 60_000 });
+ await thumb.click();
+ const viewer = page.getByRole("dialog");
+ await viewer.waitFor();
+ await viewer.getByRole("button", { name: /delete|trash/i }).first().click();
+ await page.waitForTimeout(600);
+ if (await viewer.count()) await page.keyboard.press("Escape");
+ await page.waitForTimeout(400);
+ check("a trashed result leaves its node", (await thumb.count()) === 0 && /Not run yet/.test(await image.innerText()));
+ await page.getByRole("button", { name: "Run all", exact: true }).click();
+ await page.getByText(/Running 1 node/).first().waitFor({ timeout: 10_000 }).then(
+ () => check("Run all makes the trashed result again", true),
+ () => check("Run all makes the trashed result again", false),
+ );
+ await thumb.waitFor({ timeout: 60_000 });
+
+ // 4. A big board stays responsive.
+ if (perf > 0) {
+ const chains = Math.ceil(perf / 3);
+ const nodes = [];
+ const edges = [];
+ for (let i = 0; i < chains; i++) {
+ const y = i * 520;
+ nodes.push({ id: `p${i}`, type: "prompt", position: { x: 0, y }, data: { text: `Prompt ${i}: a fox in snow` } });
+ nodes.push({ id: `i${i}`, type: "model", position: { x: 380, y }, data: { modelId: "nano-banana-pro", mediaKind: "image" } });
+ nodes.push({ id: `v${i}`, type: "model", position: { x: 760, y }, data: { modelId: "kling-2-5-turbo", mediaKind: "video", op: "i2v", prompt: "it moves" } });
+ edges.push({ id: `a${i}`, source: `p${i}`, sourceHandle: "out", target: `i${i}`, targetHandle: "prompt" });
+ edges.push({ id: `b${i}`, source: `i${i}`, sourceHandle: "out", target: `v${i}`, targetHandle: "images" });
+ }
+ const big = await api("/api/canvases", { method: "POST", body: JSON.stringify({ name: `Perf ${chains * 3}`, graph: { nodes, edges } }) });
+ const t0 = Date.now();
+ await page.goto(`${app}/canvas/${big.id}`, { waitUntil: "load" });
+ await page.locator(".react-flow__node").first().waitFor({ timeout: 120_000 });
+ console.log(` ${chains * 3} nodes: first node after ${Date.now() - t0} ms`);
+ await page.waitForTimeout(1500);
+ const times = await page.evaluate(async () => {
+ const ta = document.querySelector('[data-testid="canvas-node-p0"] textarea');
+ ta.focus();
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value").set;
+ const out = [];
+ for (let k = 0; k < 20; k++) {
+ const t = performance.now();
+ setter.call(ta, `${ta.value}x`);
+ ta.dispatchEvent(new Event("input", { bubbles: true }));
+ await new Promise((r) => requestAnimationFrame(() => setTimeout(r, 0)));
+ out.push(performance.now() - t);
+ }
+ return out;
+ });
+ const avg = times.reduce((a, b) => a + b, 0) / times.length;
+ console.log(` keystroke → paint ms: ${times.map((x) => Math.round(x)).join(", ")} (avg ${avg.toFixed(1)})`);
+ check(`typing on a ${chains * 3}-node board repaints in under 50 ms on average`, avg < 50, `${avg.toFixed(1)} ms`);
+ }
+} catch (e) {
+ failures.push(`script: ${e.message.split("\n")[0]}`);
+ console.log(`FAIL ${e.message.split("\n")[0]}`);
+} finally {
+ await browser.close();
+}
+console.log(failures.length ? `\n${failures.length} canvas check(s) failed` : "\nAll canvas checks passed.");
+process.exit(failures.length ? 1 : 0);