The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Canvas: list page, React Flow editor, node palette and phone view
Claude69980790d59b
diff --git a/src/app/(studio)/canvas/[id]/page.tsx b/src/app/(studio)/canvas/[id]/page.tsxnew file mode 100644index 00000000..926462ca--- /dev/null+++ b/src/app/(studio)/canvas/[id]/page.tsx@@ -0,0 +1,18 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { CanvasEditor } from "@/components/canvas/canvas-editor";++export const metadata: Metadata = { title: "Canvas" };++async function Editor({ params }: { params: PageProps<"/canvas/[id]">["params"] }) {+ const { id } = await params;+ return <CanvasEditor id={id} />;+}++export default function Page({ params }: PageProps<"/canvas/[id]">) {+ return (+ <Suspense fallback={null}>+ <Editor params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/canvas/page.tsx b/src/app/(studio)/canvas/page.tsxnew file mode 100644index 00000000..fa1b58fd--- /dev/null+++ b/src/app/(studio)/canvas/page.tsx@@ -0,0 +1,8 @@+import type { Metadata } from "next";+import { CanvasList } from "@/components/canvas/canvas-list";++export const metadata: Metadata = { title: "Canvas" };++export default function Page() {+ return <CanvasList />;+}diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex cc5364b1..f48a7156 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -23,6 +23,7 @@ import {ListChecks,Mic2,Moon,+ Network,Plus,Settings,SlidersHorizontal,@@ -68,6 +69,7 @@ const NAV = [{ href: "/motions", label: "Camera motions", icon: Film },{ href: "/effects", label: "Effects", icon: Sparkles },{ href: "/storyboard", label: "Storyboard", icon: GalleryHorizontal },+ { href: "/canvas", label: "Canvas", icon: Network },{ href: "/apps", label: "Apps", icon: LayoutGrid },],},diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsxnew file mode 100644index 00000000..bf5c0caf--- /dev/null+++ b/src/components/canvas/canvas-context.tsx@@ -0,0 +1,128 @@+"use client";++import {+ AtSign,+ AudioLines,+ Clapperboard,+ Columns3,+ Combine,+ Eraser,+ Film,+ Frame,+ GalleryHorizontal,+ ImageIcon,+ MessageSquareText,+ Mic2,+ MonitorPlay,+ Package,+ Sparkles,+ StickyNote,+ Type,+ 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 type { EngineMode } from "@/lib/api";++export const ICONS: Record<string, LucideIcon> = {+ Type,+ ImageIcon,+ Film,+ AudioLines,+ AtSign,+ Sparkles,+ Combine,+ Frame,+ ZoomIn,+ Eraser,+ Mic2,+ MonitorPlay,+ StickyNote,+ Clapperboard,+ MessageSquareText,+ Package,+ GalleryHorizontal,+ Columns3,+};++/** A node type's or template's icon, by lucide name. */+export function NodeIcon({ name, className }: { name: string; className?: string }) {+ const Icon: LucideIcon = ICONS[name] ?? Sparkles;+ return <Icon className={className} />;+}++/** Edge and handle colours per port type (the app's chart tokens, so both themes work). */+export const PORT_COLOR: Record<PortType, string> = {+ text: "var(--chart-2)",+ image: "var(--chart-5)",+ video: "var(--chart-4)",+ audio: "var(--chart-3)",+ element: "var(--chart-1)",+};++export type NodeState = GenerationStatus | "idle";++/** What a generator node has made: its latest run's generations, folded into one status. */+export interface NodeResults {+ gens: Generation[];+ state: NodeState;+ /** 0–1 while running. */+ progress: number | null;+ message: string | null;+ error: string | null;+ /** Every output of the latest run, in order. */+ outputs: { g: Generation; o: OutputFile; i: number }[];+}++export const EMPTY_RESULTS: NodeResults = { gens: [], state: "idle", progress: null, message: null, error: null, outputs: [] };++export function foldResults(gens: Generation[]): NodeResults {+ if (!gens.length) return EMPTY_RESULTS;+ const has = (s: GenerationStatus) => gens.some((g) => g.status === s);+ const state: NodeState = has("running") ? "running" : has("queued") ? "queued" : has("failed") ? "failed" : has("canceled") ? "canceled" : "succeeded";+ const live = gens.filter((g) => g.status === "running" || g.status === "queued");+ const progress = live.length ? live.reduce((n, g) => n + (g.progress ?? 0), 0) / live.length : null;+ return {+ gens,+ state,+ progress: progress && progress > 0 ? progress : null,+ message: live[0]?.message ?? null,+ error: gens.find((g) => g.status === "failed")?.error ?? null,+ outputs: gens.flatMap((g) => (g.status === "succeeded" ? g.outputs.map((o, i) => ({ g, o, i })) : [])),+ };+}++export interface EditorApi {+ 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;+ running: boolean;+ /** True when this model would run on the demo provider (no key / no ComfyUI). */+ isDemo: (m: ModelDef) => boolean;+ update: (id: string, patch: Partial<CanvasNodeData>) => void;+ remove: (id: string) => void;+ duplicate: (id: string) => void;+ run: (targets?: string[], force?: boolean) => void;+ cancel: (id: string) => void;+ open: (id: string, index?: number) => void;+ /** Add an input node holding this node's first output, wired nowhere yet. */+ toInput: (id: string) => void;+}++export const EditorContext = createContext<EditorApi | null>(null);++export function useEditor(): EditorApi {+ const v = useContext(EditorContext);+ if (!v) throw new Error("useEditor outside the canvas editor");+ return v;+}diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxnew file mode 100644index 00000000..d7b98240--- /dev/null+++ b/src/components/canvas/canvas-editor.tsx@@ -0,0 +1,864 @@+"use client";++import "@xyflow/react/dist/style.css";+import "./canvas.css";++import { useQueryClient } from "@tanstack/react-query";+import {+ applyEdgeChanges,+ applyNodeChanges,+ Background,+ BackgroundVariant,+ Controls,+ MiniMap,+ Panel,+ ReactFlow,+ ReactFlowProvider,+ useNodesInitialized,+ useReactFlow,+ type Connection,+ type Edge,+ type EdgeChange,+ type FitViewOptions,+ type NodeChange,+ type OnConnectEnd,+ type Viewport,+} from "@xyflow/react";+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 { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";+import { Kbd } from "@/components/ui/kbd";+import { SidebarTrigger } from "@/components/ui/sidebar";+import { Skeleton } from "@/components/ui/skeleton";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+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 { getModel } from "@/lib/catalog";+import {+ acceptsType,+ cleanGraph,+ connectionError,+ convertEngine,+ defaultModelForNode,+ describeNode,+ graphEngine,+ inputPorts,+ isGenerator,+ newId,+ nodeLabel,+ OUT,+ outputType,+ paletteItems,+ planCanvas,+ PREVIEW_IN,+ singleInput,+ type Canvas,+ type CanvasEdge,+ type CanvasGraph,+ type CanvasNode,+ type CanvasNodeData,+ type NodeDescription,+ type PaletteItem,+ type PortType,+} from "@/lib/catalog/canvas";+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 { 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";++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] });++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 });++function toGraph(nodes: FlowNode[], edges: Edge[], viewport?: Viewport): CanvasGraph {+ return {+ nodes: nodes.map((n) => ({+ id: n.id,+ type: n.type as CanvasNode["type"],+ position: { x: Math.round(n.position.x), y: Math.round(n.position.y) },+ data: n.data,+ ...(n.type === "output" && n.width ? { width: n.width } : {}),+ })),+ edges: edges.map((e) => ({ id: e.id, source: e.source, target: e.target, sourceHandle: e.sourceHandle ?? OUT, targetHandle: e.targetHandle ?? null })),+ ...(viewport && { viewport: { x: Math.round(viewport.x), y: Math.round(viewport.y), zoom: Math.round(viewport.zoom * 1000) / 1000 } }),+ };+}++/** Edges whose handles still exist after a model / op change. */+function pruneEdges(nodes: FlowNode[], edges: Edge[]): Edge[] {+ const keep = new Set(cleanGraph(toGraph(nodes, edges)).edges.map((e) => e.id));+ return edges.filter((e) => keep.has(e.id));+}++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);+ if (view.isLoading) return <EditorSkeleton />;+ if (!view.data) {+ return (+ <div className="flex min-h-svh flex-col">+ <div className="flex h-14 items-center px-3 md:hidden">+ <SidebarTrigger />+ </div>+ <Empty className="flex-1">+ <EmptyHeader>+ <EmptyTitle className="text-[22px]">This canvas isn't here</EmptyTitle>+ <EmptyDescription>It may have been deleted. Your results are still in the library.</EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button asChild variant="secondary">+ <Link href="/canvas">All canvases</Link>+ </Button>+ </EmptyContent>+ </Empty>+ </div>+ );+ }+ return (+ <ReactFlowProvider>+ <Editor id={id} initial={view.data.canvas} view={view.data} />+ </ReactFlowProvider>+ );+}++function EditorSkeleton() {+ return (+ <div className="flex h-svh flex-col md:h-[calc(100svh-0.5rem)]">+ <div className="flex h-14 items-center gap-3 border-b px-3 sm:px-4">+ <Skeleton className="h-6 w-48" />+ <Skeleton className="ml-auto h-8 w-24 rounded-full" />+ </div>+ <div className="relative flex-1">+ <Skeleton className="absolute top-[20%] left-[15%] h-40 w-64 rounded-xl" />+ <Skeleton className="absolute top-[30%] left-[45%] h-56 w-72 rounded-xl" />+ </div>+ </div>+ );+}++type SaveState = "saved" | "saving" | "error";++interface MenuState {+ x: number;+ y: number;+ flow: { x: number; y: number };+ connect?: { nodeId: string; handleId: string | null; from: "source" | "target"; type: PortType };+}++function Editor({ id, initial, view }: { id: string; initial: Canvas; view: CanvasView }) {+ const qc = useQueryClient();+ const rf = useReactFlow<FlowNode, Edge>();+ const { resolvedTheme } = useTheme();+ const isMobile = useIsMobile();+ const [engine, setEngine, mode] = useEngine();+ const status = useStatus().data;+ const runM = useRunCanvas(id);++ const [nodes, setNodes] = useState<FlowNode[]>(() => initial.graph.nodes.map(toFlowNode));+ const [edges, setEdges] = useState<Edge[]>(() => initial.graph.edges.map(toFlowEdge));+ const [name, setName] = useState(initial.name);+ const [tab, setTab] = useState<"board" | "list">("board");+ const [paletteOpen, setPaletteOpen] = useState(true);+ const [menu, setMenu] = useState<MenuState | null>(null);+ const [viewer, setViewer] = useState<{ nodeId: string; index: number } | null>(null);+ const [runErrors, setRunErrors] = useState<Record<string, string>>({});+ const [saveState, setSaveState] = useState<SaveState>("saved");+ const [rev, setRev] = useState(0);+ const wrapper = useRef<HTMLDivElement>(null);+ const viewport = useRef<Viewport | undefined>(initial.graph.viewport);+ const savedRev = useRef(0);++ // Latest state for event handlers (synced right after each commit).+ const latest = useRef({ nodes, edges });+ useLayoutEffect(() => {+ latest.current = { nodes, edges };+ }, [nodes, edges]);++ const touch = useCallback(() => setRev((r) => r + 1), []);++ // ---- derived: graph, plan, results+ const graph = useMemo(() => toGraph(nodes, edges), [nodes, edges]);+ const planned = useDeferredValue(graph);+ const runs = view.canvas.runs;+ const gens = useMemo(() => new Map(view.generations.map((g) => [g.id, g])), [view.generations]);+ const statusOf = useCallback((gid: string) => gens.get(gid)?.status, [gens]);+ const plan = useMemo(() => planCanvas(planned, { runs, status: statusOf, engineMode: mode }), [planned, runs, statusOf, mode]);+ const descriptions = useMemo(() => {+ const m = new Map<string, NodeDescription>();+ for (const n of planned.nodes) if (isGenerator(n)) m.set(n.id, describeNode(planned, n, { engineMode: mode }));+ return m;+ }, [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)));+ return m;+ }, [runs, gens]);+ 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;+ if (status.demoMode === "on") return true;+ if (status.demoMode === "off") return false;+ return !m.routes.some((r) => status.providers[r.provider]?.configured);+ },+ [status],+ );++ // ---- autosave+ const save = useCallback(+ async (keepalive = false) => {+ const at = 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");+ void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });+ } catch {+ setSaveState("error");+ }+ },+ [id, rev, 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.+ useEffect(() => {+ if (saveState !== "error") return;+ const t = setTimeout(() => void save(), 4000);+ return () => clearTimeout(t);+ }, [saveState, 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);+ };+ document.addEventListener("visibilitychange", flush);+ window.addEventListener("beforeunload", leave);+ return () => {+ document.removeEventListener("visibilitychange", flush);+ window.removeEventListener("beforeunload", leave);+ };+ }, [save, rev]);++ const rename = async (next: string) => {+ const v = next.trim();+ if (!v || v === initial.name) return setName(v || initial.name);+ try {+ await saveCanvas(id, { name: v });+ void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });+ } catch (e) {+ toast.error((e as Error).message);+ }+ };++ // ---- editing+ const update = useCallback(+ (nodeId: string, patch: Partial<CanvasNodeData>) => {+ const apply = (ns: FlowNode[]) => ns.map((n) => (n.id === nodeId ? { ...n, data: { ...n.data, ...patch } } : n));+ setNodes(apply);+ if ("modelId" in patch || "op" in patch || "mediaKind" in patch) setEdges((es) => pruneEdges(apply(latest.current.nodes), es));+ setRunErrors((r) => {+ if (!(nodeId in r)) return r;+ const next = { ...r };+ delete next[nodeId];+ return next;+ });+ touch();+ },+ [touch],+ );++ const remove = useCallback(+ (nodeId: string) => {+ setNodes((ns) => ns.filter((n) => n.id !== nodeId));+ setEdges((es) => es.filter((e) => e.source !== nodeId && e.target !== nodeId));+ touch();+ },+ [touch],+ );++ const duplicate = useCallback(+ (ids: string | string[]) => {+ const list = new Set(Array.isArray(ids) ? ids : [ids]);+ 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 }));+ if (!copies.length) return;+ setNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })), ...copies]);+ touch();+ },+ [touch],+ );++ const addNode = useCallback(+ (item: PaletteItem, at: { x: number; y: number }, connect?: MenuState["connect"]) => {+ 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");+ if (m) data.modelId = m.id;+ }+ const node: FlowNode = { id: newId(item.type), type: item.type, position: snap(at), data, selected: true };+ setNodes((ns) => [...ns.map((n) => (n.selected ? { ...n, selected: false } : n)), node]);+ if (connect) {+ const g = toGraph([...latest.current.nodes, node], latest.current.edges);+ const c: Connection =+ connect.from === "source"+ ? { source: connect.nodeId, sourceHandle: OUT, target: node.id, targetHandle: item.type === "output" ? PREVIEW_IN : (inputPorts(toGraph([node], []).nodes[0]).find((p) => acceptsType(p, connect.type))?.id ?? null) }+ : { source: node.id, sourceHandle: OUT, target: connect.nodeId, targetHandle: connect.handleId };+ if (c.targetHandle && !connectionError(g, c)) {+ setEdges((es) => [...(singleInput(g, c.target, c.targetHandle) ? es.filter((e) => !(e.target === c.target && e.targetHandle === c.targetHandle)) : es), { id: newId("e"), ...c }]);+ }+ }+ touch();+ return node.id;+ },+ [engine, touch],+ );++ const onNodesChange = useCallback(+ (changes: NodeChange<FlowNode>[]) => {+ setNodes((ns) => applyNodeChanges(changes, ns));+ if (changes.some((c) => c.type === "remove" || c.type === "add" || c.type === "replace" || (c.type === "position" && !c.dragging))) touch();+ },+ [touch],+ );+ const onEdgesChange = useCallback(+ (changes: EdgeChange<Edge>[]) => {+ setEdges((es) => applyEdgeChanges(changes, es));+ if (changes.some((c) => c.type !== "select")) touch();+ },+ [touch],+ );+ const isValidConnection = useCallback((c: Connection | Edge) => !connectionError(toGraph(latest.current.nodes, latest.current.edges), c), []);+ const onConnect = useCallback(+ (c: Connection) => {+ const g = toGraph(latest.current.nodes, latest.current.edges);+ const err = connectionError(g, c);+ if (err) return void toast.error(err);+ // A single input (start frame, video, audio…) takes the new edge instead of the old one.+ setEdges((es) => [...(singleInput(g, c.target, c.targetHandle) ? es.filter((e) => !(e.target === c.target && e.targetHandle === c.targetHandle)) : es), { id: newId("e"), ...c }]);+ touch();+ },+ [touch],+ );++ const openMenuAt = useCallback(+ (clientX: number, clientY: number, connect?: MenuState["connect"]) => {+ const rect = wrapper.current?.getBoundingClientRect();+ if (!rect) return;+ const x = Math.min(Math.max(8, clientX - rect.left), rect.width - 264);+ const y = Math.min(Math.max(8, clientY - rect.top), rect.height - 340);+ setMenu({ x, y, flow: rf.screenToFlowPosition({ x: clientX, y: clientY }), connect });+ },+ [rf],+ );++ // A connection dropped on empty board: offer the nodes that fit, and wire the new one up.+ const onConnectEnd: OnConnectEnd = useCallback(+ (event, state) => {+ if (state.isValid || !state.fromNode || state.toNode) return;+ const pt = "changedTouches" in event ? event.changedTouches[0] : event;+ const g = toGraph(latest.current.nodes, latest.current.edges);+ const from = g.nodes.find((n) => n.id === state.fromNode!.id);+ if (!from) return;+ const fromSource = state.fromHandle?.type === "source";+ const type = fromSource ? outputType(g, from) : inputPorts(from).find((p) => p.id === state.fromHandle?.id)?.type;+ if (!type) return;+ openMenuAt(pt.clientX, pt.clientY, { nodeId: from.id, handleId: state.fromHandle?.id ?? null, from: fromSource ? "source" : "target", type });+ },+ [openMenuAt],+ );++ const menuItems = useMemo(() => {+ const all = paletteItems();+ const c = menu?.connect;+ if (!c) return all;+ return all.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;+ const n: CanvasNode = { id: "probe", type: p.type, position: { x: 0, y: 0 }, data };+ 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]);++ // ---- running+ const run = useCallback(+ (targets?: string[], force?: boolean) => {+ const go = (t?: string[], f?: boolean) =>+ runM.mutate(+ { 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");+ 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;+ if (!r.ran.length) toast("Everything's up to date", { description: issues, action: { label: "Run again", onClick: () => go(t, true) } });+ else toast.success(r.ran.length === 1 ? "Running 1 node" : `Running ${r.ran.length} nodes`, { description: issues, duration: 1800 });+ },+ onError: (e) => toast.error((e as Error).message),+ },+ );+ go(targets, force);+ },+ [runM, rev],+ );++ const cancel = useCallback(+ async (nodeId: string) => {+ const ids = (runs[nodeId]?.ids ?? []).filter((g) => {+ const s = gens.get(g)?.status;+ return s === "queued" || s === "running";+ });+ await Promise.all(ids.map((g) => fetch(`/api/generations/${g}/cancel`, { method: "POST" })));+ void qc.invalidateQueries({ queryKey: ["canvases", id] });+ },+ [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],+ );++ // ---- 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);+ 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 }));+ setNodes(after);+ setEdges((es) => pruneEdges(after, es));+ touch();+ toast.success(`Switched ${changed} node${changed > 1 ? "s" : ""} to ${e === "open" ? "open-source" : "cloud"} models`, {+ action: {+ label: "Undo",+ onClick: () => {+ setNodes(before);+ touch();+ },+ },+ });+ }+ 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;+ });++ // ---- keyboard: ⌘↵ runs (the selection, else everything), ⌘D duplicates+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ const mod = e.metaKey || e.ctrlKey;+ if (!mod) return;+ 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);+ } 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;+ e.preventDefault();+ duplicate(sel);+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [run, duplicate]);++ // ---- drop from the palette, or files from the desktop+ const onDragOver = (e: React.DragEvent) => {+ if (isMobile) return;+ if (e.dataTransfer.types.includes(DRAG_TYPE) || e.dataTransfer.types.includes("Files")) {+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ }+ };+ const onDrop = (e: React.DragEvent) => {+ const itemId = e.dataTransfer.getData(DRAG_TYPE);+ const at = rf.screenToFlowPosition({ x: e.clientX, y: e.clientY });+ if (itemId) {+ e.preventDefault();+ const item = paletteItems().find((p) => p.id === itemId);+ if (item) addNode(item, at);+ return;+ }+ const files = [...(e.dataTransfer.files ?? [])];+ if (!files.length) return;+ e.preventDefault();+ 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 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);+ });+ };++ const addAtCenter = (item: PaletteItem) => {+ const rect = wrapper.current?.getBoundingClientRect();+ const at = rf.screenToFlowPosition({ x: (rect?.left ?? 0) + (rect?.width ?? 800) / 2 - 140, y: (rect?.top ?? 0) + (rect?.height ?? 600) / 2 - 100 });+ addNode(item, at);+ };++ 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 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 });+ 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) => {+ 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,+ };++ const viewerEntries = viewer ? (results.get(viewer.nodeId)?.outputs ?? []) : [];+ const entry = viewer ? viewerEntries[viewer.index] : undefined;+ const planDemo = plan.steps.some((s) => {+ const m = getModel(s.request.modelId);+ return m && isDemo(m);+ });+ const summary = plan.steps.length+ ? `${plan.steps.length} to run · ${planDemo ? "Demo · free" : plan.costUnknown ? "price unknown" : plan.costUsd === 0 ? "Free" : `≈ ${formatCost(plan.costUsd)}`}`+ : generators.length+ ? "Up to date"+ : "";++ 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)]"+ />+ <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>+ ))}+ </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>+ )}++ {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();+ }}+ 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 && (+ <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>+ </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>+ )}+ </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>+ );+}diff --git a/src/components/canvas/canvas-list.tsx b/src/components/canvas/canvas-list.tsxnew file mode 100644index 00000000..f6f27319--- /dev/null+++ b/src/components/canvas/canvas-list.tsx@@ -0,0 +1,338 @@+"use client";++import { Cloud, Copy, Cpu, Loader2, MoreHorizontal, Pencil, Plus, Search, Trash2, Workflow } from "lucide-react";+import Link from "next/link";+import { useRouter, useSearchParams } from "next/navigation";+import { Suspense, useMemo, useState } from "react";+import { toast } from "sonner";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";+import { Input } from "@/components/ui/input";+import { Skeleton } from "@/components/ui/skeleton";+import { EngineSwitch } from "@/components/studio/engine-switch";+import { PageShell } from "@/components/page-shell";+import { useEngine } from "@/lib/api";+import { getModel } from "@/lib/catalog";+import { CANVAS_TEMPLATES, isGenerator, outline, type CanvasNodeType, type CanvasSummary, type CanvasTemplate, type Outline } from "@/lib/catalog/canvas";+import type { Engine } from "@/lib/catalog/types";+import { timeAgo } from "@/lib/format";+import { cn } from "@/lib/utils";+import { NodeIcon } from "./canvas-context";+import { useCanvasActions, useCanvases } from "./use-canvas";++const BOX = { w: 280, h: 150 };++const BOX_COLOR: Partial<Record<CanvasNodeType, string>> = {+ prompt: "var(--chart-2)",+ "image-input": "var(--chart-5)",+ "video-input": "var(--chart-4)",+ "audio-input": "var(--chart-3)",+ element: "var(--chart-1)",+ output: "var(--muted-foreground)",+};++/** The board in miniature, for cards without a result to show. */+function Schematic({ outline: o, className }: { outline: Outline; className?: string }) {+ if (!o.boxes.length) {+ return (+ <div className={cn("grid size-full place-items-center text-subtle-foreground", className)}>+ <Workflow className="size-8" />+ </div>+ );+ }+ const xs = o.boxes.map((b) => b.x);+ const ys = o.boxes.map((b) => b.y);+ const pad = 80;+ const minX = Math.min(...xs) - pad;+ const minY = Math.min(...ys) - pad;+ const w = Math.max(...xs) + BOX.w + pad - minX;+ const h = Math.max(...ys) + BOX.h + pad - minY;+ return (+ <svg viewBox={`${minX} ${minY} ${w} ${h}`} preserveAspectRatio="xMidYMid meet" className={cn("size-full", className)} aria-hidden>+ {o.links.map(([a, b], i) => {+ const s = o.boxes[a];+ const t = o.boxes[b];+ const x1 = s.x + BOX.w;+ const y1 = s.y + BOX.h / 2;+ const x2 = t.x;+ const y2 = t.y + BOX.h / 2;+ const mx = (x1 + x2) / 2;+ return <path key={i} d={`M${x1},${y1} C${mx},${y1} ${mx},${y2} ${x2},${y2}`} fill="none" stroke="var(--border-strong)" strokeWidth={8} />;+ })}+ {o.boxes.map((b, i) => (+ <g key={i}>+ <rect x={b.x} y={b.y} width={BOX.w} height={BOX.h} rx={22} fill="var(--card)" stroke="var(--border-strong)" strokeWidth={4} />+ <rect x={b.x + 24} y={b.y + 28} width={44} height={44} rx={10} fill={BOX_COLOR[b.type] ?? "var(--primary)"} opacity={0.85} />+ <rect x={b.x + 84} y={b.y + 36} width={150} height={14} rx={7} fill="var(--muted-foreground)" opacity={0.35} />+ <rect x={b.x + 24} y={b.y + 94} width={220} height={12} rx={6} fill="var(--muted-foreground)" opacity={0.18} />+ </g>+ ))}+ </svg>+ );+}++function CanvasCard({ c, onRename, onDelete }: { c: CanvasSummary; onRename: () => void; onDelete: () => void }) {+ const router = useRouter();+ const { duplicate } = useCanvasActions();+ return (+ <article className="group/card relative min-w-0">+ <Link href={`/canvas/${c.id}`} className="block rounded-xl outline-none focus-visible:ring-4 focus-visible:ring-brand-faint">+ <div className="aspect-[16/10] overflow-hidden rounded-xl border bg-muted/50 transition-shadow group-hover/card:shadow-normal">+ {c.preview ? (+ c.preview.kind === "video" ? (+ <video src={`${c.preview.url}#t=0.1`} muted playsInline preload="metadata" className="size-full object-cover" />+ ) : (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={c.preview.url} alt="" loading="lazy" className="size-full object-cover" />+ )+ ) : (+ <Schematic outline={c.outline} className="p-3" />+ )}+ </div>+ <h3 className="mt-2 truncate pr-9 text-[14px] font-medium">{c.name}</h3>+ <p className="text-[12px] text-muted-foreground">+ {c.editedAt ? `Edited ${timeAgo(c.editedAt)}` : "Never edited"} · {c.nodeCount} node{c.nodeCount === 1 ? "" : "s"}+ </p>+ </Link>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="absolute right-0 bottom-5 grid size-8 place-items-center rounded-md text-muted-foreground opacity-100 hover:bg-accent hover:text-foreground focus-visible:opacity-100 sm:opacity-0 sm:group-hover/card:opacity-100 data-[state=open]:opacity-100"+ aria-label={`Actions for ${c.name}`}+ >+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-44">+ <DropdownMenuItem onSelect={onRename}>+ <Pencil /> Rename+ </DropdownMenuItem>+ <DropdownMenuItem+ onSelect={() =>+ void duplicate(c.id).then(+ (copy) => toast.success("Duplicated", { action: { label: "Open", onClick: () => router.push(`/canvas/${copy.id}`) } }),+ (e) => toast.error((e as Error).message),+ )+ }+ >+ <Copy /> Duplicate+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onSelect={onDelete}>+ <Trash2 /> Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </article>+ );+}++function TemplateCard({ t, engine, onUse, busy }: { t: CanvasTemplate; engine: Engine; onUse: () => void; busy: boolean }) {+ const graph = useMemo(() => t.build(engine), [t, engine]);+ const models = [...new Set(graph.nodes.filter(isGenerator).map((n) => getModel(n.data.modelId ?? "")?.name).filter(Boolean))];+ return (+ <article className="flex min-w-0 flex-col overflow-hidden rounded-xl border bg-card">+ <div className="relative aspect-[16/9] bg-muted/50" style={{ background: `linear-gradient(135deg, oklch(0.62 0.12 ${t.hue} / 0.14), transparent 70%)` }}>+ <Schematic outline={outline(graph)} className="p-4" />+ <span className="absolute top-3 left-3 grid size-8 place-items-center rounded-lg bg-background/90 text-foreground shadow-soft">+ <NodeIcon name={t.icon} className="size-4" />+ </span>+ </div>+ <div className="flex flex-1 flex-col gap-2 p-3.5">+ <div>+ <h3 className="text-[14px] font-medium">{t.name}</h3>+ <p className="text-[13px] text-muted-foreground">{t.description}</p>+ </div>+ <p className="flex items-start gap-1.5 text-[12px] text-subtle-foreground">+ {engine === "open" ? <Cpu className="mt-px size-3.5 shrink-0" /> : <Cloud className="mt-px size-3.5 shrink-0" />}+ <span className="line-clamp-2">{models.join(" · ")}</span>+ </p>+ <Button size="sm" className="mt-auto w-fit rounded-full" onClick={onUse} disabled={busy}>+ {busy ? <Loader2 className="animate-spin" /> : <Plus />} Use template+ </Button>+ </div>+ </article>+ );+}++function ListInner() {+ const router = useRouter();+ const params = useSearchParams();+ const tab = params.get("tab") === "templates" ? "templates" : "mine";+ const canvases = useCanvases();+ const { create, rename, remove } = useCanvasActions();+ const [engine, setEngine] = useEngine();+ const [q, setQ] = useState("");+ const [creating, setCreating] = useState<string | null>(null);+ const [renaming, setRenaming] = useState<CanvasSummary | null>(null);+ const [draft, setDraft] = useState("");+ const [deleting, setDeleting] = useState<CanvasSummary | null>(null);++ const items = (canvases.data ?? []).filter((c) => !q || c.name.toLowerCase().includes(q.toLowerCase()));+ const setTab = (t: "mine" | "templates") => router.replace(t === "templates" ? "/canvas?tab=templates" : "/canvas", { scroll: false });++ const start = async (key: string, body: Parameters<typeof create>[0]) => {+ setCreating(key);+ try {+ const c = await create(body);+ router.push(`/canvas/${c.id}`);+ } catch (e) {+ toast.error((e as Error).message);+ setCreating(null);+ }+ };++ return (+ <PageShell wide>+ <div className="flex flex-col gap-4 sm:flex-row sm:items-end">+ <div className="min-w-0 flex-1">+ <h1 className="font-heading text-[34px] leading-tight">Canvas</h1>+ <p className="mt-1 max-w-xl text-[15px] text-muted-foreground">Make images, videos and ideas in one place: wire prompts, files and models together, then run them in order or side by side.</p>+ </div>+ <Button className="w-fit rounded-full" onClick={() => void start("new", {})} disabled={!!creating}>+ {creating === "new" ? <Loader2 className="animate-spin" /> : <Plus />} New canvas+ </Button>+ </div>++ <div className="mt-6 flex flex-wrap items-center gap-3">+ <div className="inline-grid h-9 grid-cols-2 rounded-full bg-muted p-0.5 text-[13px] font-medium" role="tablist" aria-label="Canvases or templates">+ {(+ [+ ["mine", "Your canvases"],+ ["templates", "Templates"],+ ] as const+ ).map(([k, label]) => (+ <button key={k} role="tab" aria-selected={tab === k} onClick={() => setTab(k)} className={cn("rounded-full px-3.5 transition-colors", tab === k ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}>+ {label}+ </button>+ ))}+ </div>+ {tab === "mine" ? (+ <div className="relative ml-auto w-full sm:w-64">+ <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search canvases" aria-label="Search canvases" className="h-9 rounded-full pl-9" />+ </div>+ ) : (+ <div className="ml-auto flex items-center gap-2 text-[13px] text-muted-foreground">+ <span className="hidden sm:inline">Variant</span>+ <EngineSwitch value={engine} onChange={setEngine} size="sm" />+ </div>+ )}+ </div>++ {tab === "mine" ? (+ canvases.isLoading ? (+ <div className="mt-6 grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {Array.from({ length: 4 }, (_, i) => (+ <div key={i}>+ <Skeleton className="aspect-[16/10] rounded-xl" />+ <Skeleton className="mt-2 h-4 w-2/3" />+ </div>+ ))}+ </div>+ ) : items.length ? (+ <div className="mt-6 grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {items.map((c) => (+ <CanvasCard+ key={c.id}+ c={c}+ onRename={() => {+ setDraft(c.name);+ setRenaming(c);+ }}+ onDelete={() => setDeleting(c)}+ />+ ))}+ </div>+ ) : q ? (+ <p className="py-16 text-center text-[15px] text-muted-foreground">No canvas called “{q}”.</p>+ ) : (+ <Empty className="mt-6 border">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <Workflow />+ </EmptyMedia>+ <EmptyTitle className="text-[22px]">No canvases yet</EmptyTitle>+ <EmptyDescription>Build a workflow once — prompt → image → video, three models side by side — and run it again whenever you like.</EmptyDescription>+ </EmptyHeader>+ <EmptyContent className="flex-row justify-center">+ <Button className="rounded-full" onClick={() => void start("new", {})} disabled={!!creating}>+ <Plus /> New canvas+ </Button>+ <Button variant="secondary" className="rounded-full" onClick={() => setTab("templates")}>+ Browse templates+ </Button>+ </EmptyContent>+ </Empty>+ )+ ) : (+ <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {CANVAS_TEMPLATES.map((t) => (+ <TemplateCard key={t.id} t={t} engine={engine} busy={creating === t.id} onUse={() => void start(t.id, { templateId: t.id, engine })} />+ ))}+ </div>+ )}++ <Dialog open={!!renaming} onOpenChange={(o) => !o && setRenaming(null)}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>Rename canvas</DialogTitle>+ <DialogDescription className="sr-only">Give this canvas a new name</DialogDescription>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ const c = renaming!;+ const name = draft.trim();+ setRenaming(null);+ if (name && name !== c.name) void rename(c.id, name).then(() => toast.success("Renamed", { duration: 1500 }), (err) => toast.error((err as Error).message));+ }}+ >+ <Input autoFocus value={draft} maxLength={80} onChange={(e) => setDraft(e.target.value)} aria-label="Name" />+ <DialogFooter className="mt-4">+ <Button type="button" variant="ghost" onClick={() => setRenaming(null)}>+ Cancel+ </Button>+ <Button type="submit" disabled={!draft.trim()}>+ Save+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete “{deleting?.name}”?</AlertDialogTitle>+ <AlertDialogDescription>The board is removed for good. Everything it made stays in your library.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ const c = deleting!;+ setDeleting(null);+ void remove(c.id).then(() => toast("Deleted", { duration: 1500 }), (e) => toast.error((e as Error).message));+ }}+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </PageShell>+ );+}++export function CanvasList() {+ return (+ <Suspense fallback={null}>+ <ListInner />+ </Suspense>+ );+}diff --git a/src/components/canvas/canvas.css b/src/components/canvas/canvas.cssnew file mode 100644index 00000000..499795f2--- /dev/null+++ b/src/components/canvas/canvas.css@@ -0,0 +1,123 @@+/*+ * React Flow themed with Fuobe's tokens (src/app/globals.css), so the board follows light and+ * dark mode like the rest of the app. Scoped to the canvas editor.+ */+.fuobe-canvas .react-flow {+ --xy-background-color: var(--background);+ --xy-background-pattern-dots-color: var(--border-strong);+ --xy-edge-stroke: var(--border-strong);+ --xy-edge-stroke-width: 2;+ --xy-edge-stroke-selected: var(--primary);+ --xy-connectionline-stroke: var(--primary);+ --xy-connectionline-stroke-width: 2;+ --xy-minimap-background-color: var(--popover);+ --xy-minimap-mask-background-color: color-mix(in oklab, var(--muted) 70%, transparent);+ --xy-minimap-mask-stroke-color: var(--border-strong);+ --xy-minimap-node-background-color: var(--muted);+ --xy-controls-button-background-color: var(--popover);+ --xy-controls-button-background-color-hover: var(--secondary);+ --xy-controls-button-color: var(--foreground);+ --xy-controls-button-color-hover: var(--foreground);+ --xy-controls-button-border-color: var(--border);+ --xy-controls-box-shadow: var(--elevation-normal);+ --xy-selection-background-color: var(--brand-faint);+ --xy-selection-border: 1px solid var(--primary);+ --xy-node-boxshadow-selected: none;+ --xy-node-border-radius: 14px;+ --xy-edge-label-background-color: var(--popover);+ --xy-edge-label-color: var(--foreground);+ font-family: var(--font-sans);+}++/* Our "output" node type shares React Flow's built-in class name: drop the built-in look. */+.fuobe-canvas .react-flow__node-output {+ padding: 0;+ width: auto;+ border: 0;+ border-radius: 0;+ background: transparent;+ color: inherit;+ font-size: inherit;+ text-align: start;+}+.fuobe-canvas .react-flow__node-output.selectable:hover,+.fuobe-canvas .react-flow__node-output.selectable.selected,+.fuobe-canvas .react-flow__node-output.selectable:focus,+.fuobe-canvas .react-flow__node-output.selectable:focus-visible {+ box-shadow: none;+}++/* Typed handles: a dot in the colour of what they carry. */+.fuobe-canvas .react-flow__handle.canvas-handle {+ width: 12px;+ height: 12px;+ min-width: 12px;+ min-height: 12px;+ border: 2px solid var(--card);+ background: var(--port, var(--muted-foreground));+ box-shadow: 0 0 0 1px var(--border-strong);+ transition: transform 100ms, box-shadow 100ms;+}+.fuobe-canvas .react-flow__handle.canvas-handle:hover,+.fuobe-canvas .react-flow__handle.canvas-handle.connectingto,+.fuobe-canvas .react-flow__handle.canvas-handle.valid {+ box-shadow: 0 0 0 4px color-mix(in oklab, var(--port, var(--primary)) 35%, transparent);+}+.fuobe-canvas .react-flow__handle.canvas-handle-any {+ background: conic-gradient(var(--chart-2), var(--chart-5), var(--chart-4), var(--chart-3), var(--chart-2));+}+/* Bigger touch targets for connecting by hand. */+.fuobe-canvas .react-flow__handle.canvas-handle::after {+ content: "";+ position: absolute;+ inset: -8px;+}++.fuobe-canvas .react-flow__edge.selected .react-flow__edge-path,+.fuobe-canvas .react-flow__edge:hover .react-flow__edge-path {+ filter: drop-shadow(0 0 3px color-mix(in oklab, var(--primary) 45%, transparent));+}++.fuobe-canvas .react-flow__controls {+ border-radius: 10px;+ overflow: hidden;+ border: 1px solid var(--border);+}+.fuobe-canvas .react-flow__controls-button {+ width: 30px;+ height: 30px;+}+.fuobe-canvas .react-flow__controls-button svg {+ fill: currentColor;+}++.fuobe-canvas .react-flow__attribution {+ background: transparent;+ font-size: 10px;+ opacity: 0.55;+}+.fuobe-canvas .react-flow__attribution a {+ color: var(--muted-foreground);+}++.fuobe-canvas .react-flow__minimap {+ border-radius: 12px;+ overflow: hidden;+ border: 1px solid var(--border);+ box-shadow: var(--elevation-normal);+}++.fuobe-canvas .react-flow__node.selectable:focus-visible {+ outline: none;+}+.fuobe-canvas .react-flow__node:focus-visible > [data-testid^="canvas-node-"] {+ box-shadow: 0 0 0 4px var(--brand-faint);+ border-color: var(--primary);+}++.fuobe-canvas .react-flow__pane.draggable {+ cursor: default;+}+.fuobe-canvas .react-flow__pane.dragging {+ cursor: grabbing;+}diff --git a/src/components/canvas/node-list.tsx b/src/components/canvas/node-list.tsxnew file mode 100644index 00000000..cdbb0b63--- /dev/null+++ b/src/components/canvas/node-list.tsx@@ -0,0 +1,122 @@+"use client";++import { AlertCircle, Play, RotateCcw, Square, Upload } from "lucide-react";+import { useRef } from "react";+import { getModel } from "@/lib/catalog";+import { isGenerator, NODE_SPECS, nodeLabel, 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";++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";++/**+ * 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).+ */+export function NodeList() {+ const ed = useEditor();+ const byId = new Map(ed.graph.nodes.map((n) => [n.id, n]));+ const { order, cyclic } = topoOrder(ed.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 (+ <ol className="space-y-3 px-4 pt-3 pb-24" aria-label="Nodes in run order">+ {nodes.map((n, i) => (+ <li key={n.id}>+ <NodeCard node={n} index={i + 1} />+ </li>+ ))}+ </ol>+ );+}++function NodeCard({ node, index }: { node: CanvasNode; index: number }) {+ const ed = useEditor();+ 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 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) : [];+ 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">+ <span className="font-mono text-[11px] text-subtle-foreground">{index}</span>+ <NodeIcon name={NODE_SPECS[node.type].icon} className="size-4 shrink-0 text-muted-foreground" />+ <h3 className="min-w-0 flex-1 truncate text-[15px] font-semibold">{nodeLabel(node)}</h3>+ <EngineBadge model={model} />+ {gen && (+ <button+ onClick={() => (running ? ed.cancel(node.id) : ed.run([node.id], !step))}+ className={cn("grid size-9 shrink-0 place-items-center rounded-full", running ? "bg-muted" : "bg-primary text-primary-foreground")}+ aria-label={running ? "Cancel" : step ? "Run node" : "Run it again"}+ >+ {running ? <Square className="size-3.5" /> : 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" />}+ {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>+ <input+ ref={file}+ type="file"+ hidden+ 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);+ 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>}+ {gen && (+ <>+ <p className="text-[12px] text-muted-foreground">+ {model?.name ?? "No model"} · {costLabel(ed, model, desc?.costUsd ?? null)}+ </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)" />+ ) : null}+ <Results id={node.id} r={r} />+ </>+ )}+ {node.type === "output" &&+ (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)} />] : [];+ })}+ </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")}>+ <AlertCircle className="mt-0.5 size-3.5 shrink-0" />+ {error}+ </p>+ )}+ </div>+ </article>+ );+}diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxnew file mode 100644index 00000000..19aecb4e--- /dev/null+++ b/src/components/canvas/nodes.tsx@@ -0,0 +1,892 @@+"use client";++import { Handle, Position, useUpdateNodeInternals, type Node, type NodeProps } from "@xyflow/react";+import {+ AlertCircle,+ AudioLines,+ Check,+ Cloud,+ Copy,+ Cpu,+ ImagePlus,+ Library,+ Loader2,+ MoreHorizontal,+ Pin,+ PinOff,+ Play,+ Plus,+ RotateCcw,+ Square,+ Trash2,+ 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 { 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";+import { LanguageChip, SlidersChip } from "@/components/studio/audio-controls";+import { fileToSlot, type SlotValue } from "@/components/studio/media-slot";+import { ControlsChip } from "@/components/studio/model-controls";+import { ModelPicker } from "@/components/studio/model-picker";+import { useAssets, useElements } from "@/lib/api";+import { getModel } from "@/lib/catalog";+import {+ defaultModelFor,+ effectiveOp,+ inputPorts,+ isGenerator,+ modelChoices,+ NODE_SPECS,+ nodeLabel,+ nodeOps,+ OUT,+ outputType,+ PORT_TYPE_LABEL,+ PREVIEW_IN,+ sanitizeParams,+ type CanvasNode,+ type CanvasNodeData,+ type CanvasNodeType,+ 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";++export type FlowNode = Node<CanvasNodeData, CanvasNodeType>;++/** Interactive controls inside a node must not drag the node or zoom the board. */+const NO_DRAG = "nodrag nopan nowheel";+const chip = cn("inline-flex h-7 shrink-0 items-center gap-1 rounded-full bg-secondary px-2.5 text-[12px] font-medium text-secondary-foreground transition-colors hover:bg-accent", NO_DRAG);++function asNode(id: string, type: CanvasNodeType, data: CanvasNodeData): CanvasNode {+ return { id, type, data, position: { x: 0, y: 0 } };+}++// ---------------------------------------------------------------------------+// Handles++function InPort({ port, count }: { port: PortDef; count: number }) {+ return (+ <div className="relative flex h-6 items-center gap-1.5 pr-3 pl-3.5 text-[11px] text-muted-foreground">+ <Handle+ type="target"+ position={Position.Left}+ id={port.id}+ className="canvas-handle"+ style={{ "--port": PORT_COLOR[port.type] } as React.CSSProperties}+ aria-label={`${port.label} input (${PORT_TYPE_LABEL[port.type]})`}+ />+ <span className={cn("font-medium", count > 0 && "text-foreground")}>{port.label}</span>+ {count > 0 && port.multiple && <span className="font-mono text-subtle-foreground">{count}</span>}+ </div>+ );+}++function OutPort({ type }: { type: PortType }) {+ return (+ <Handle+ type="source"+ position={Position.Right}+ id={OUT}+ className="canvas-handle canvas-handle-out"+ style={{ "--port": PORT_COLOR[type] } as React.CSSProperties}+ aria-label={`${PORT_TYPE_LABEL[type]} output`}+ title={`${PORT_TYPE_LABEL[type]} out — drag to connect`}+ />+ );+}++// ---------------------------------------------------------------------------+// Shell: header (icon, title, badges, menu), body, footer++interface MenuItem {+ label: string;+ icon: React.ComponentType<{ className?: string }>;+ onSelect: () => void;+ shortcut?: string;+ destructive?: boolean;+ separatorBefore?: boolean;+}++function EditableTitle({ value, placeholder, onChange, readOnly }: { value?: string; placeholder: string; onChange: (v: string | undefined) => void; readOnly: boolean }) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState("");+ if (editing) {+ return (+ <input+ autoFocus+ value={draft}+ maxLength={80}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={() => {+ setEditing(false);+ onChange(draft.trim() || undefined);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ if (e.key === "Escape") setEditing(false);+ e.stopPropagation();+ }}+ aria-label="Node name"+ className={cn("h-7 min-w-0 flex-1 rounded-md border bg-background px-1.5 text-[13px] font-semibold outline-none focus:border-primary", NO_DRAG)}+ />+ );+ }+ return (+ <span+ className="min-w-0 flex-1 truncate text-[13px] font-semibold"+ onDoubleClick={(e) => {+ if (readOnly) return;+ e.stopPropagation();+ setDraft(value ?? placeholder);+ setEditing(true);+ }}+ title={readOnly ? undefined : "Double-click to rename"}+ >+ {value || placeholder}+ </span>+ );+}++function NodeShell({+ id,+ type,+ data,+ selected,+ out,+ badge,+ menu,+ footer,+ children,+ width = 300,+ tone,+}: {+ id: string;+ type: CanvasNodeType;+ data: CanvasNodeData;+ selected: boolean;+ out?: PortType | null;+ badge?: React.ReactNode;+ 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>+ ));+ return (+ <ContextMenu>+ <ContextMenuTrigger asChild disabled={ed.readOnly}>+ <div+ className={cn(+ "group/node rounded-xl border bg-card text-card-foreground shadow-soft transition-[box-shadow,border-color]",+ selected && "border-primary ring-4 ring-brand-faint",+ tone === "running" && !selected && "border-primary/50",+ tone === "failed" && !selected && "border-destructive/50",+ tone === "note" && "border-highlight/70 bg-highlight/15",+ )}+ style={{ width }}+ data-testid={`canvas-node-${id}`}+ >+ <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} />+ {badge}+ {!ed.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">+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-56">+ {items(DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut)}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ {out && <OutPort type={out} />}+ </div>+ {children}+ {footer}+ </div>+ </ContextMenuTrigger>+ <ContextMenuContent className="w-56">{items(ContextMenuItem, ContextMenuSeparator as typeof DropdownMenuSeparator, ContextMenuShortcut as typeof DropdownMenuShortcut)}</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++function OutputThumb({ o, onOpen, className, large }: { o: OutputFile; onOpen: () => void; className?: string; large?: boolean }) {+ const media = cn("w-full object-cover", large ? "max-h-80" : "max-h-44");+ if (o.kind === "text") {+ return (+ <button onClick={onOpen} className={cn("block w-full rounded-lg bg-muted p-2.5 text-left text-[12px] leading-snug whitespace-pre-line", NO_DRAG, className)}>+ <span className="line-clamp-6">{o.text ?? "Text result"}</span>+ </button>+ );+ }+ if (o.kind === "audio") {+ return (+ <div className={cn("flex items-center gap-2 rounded-lg bg-brand-faint p-2 text-brand-text", NO_DRAG, className)}>+ <AudioLines className="size-4 shrink-0" />+ <audio src={o.url} controls preload="none" className="h-8 min-w-0 flex-1" />+ </div>+ );+ }+ return (+ <button onClick={onOpen} className={cn("block w-full overflow-hidden rounded-lg bg-muted", NO_DRAG, className)} aria-label="Open result">+ {o.kind === "video" ? (+ <video+ src={`${o.url}#t=0.1`}+ muted+ loop+ playsInline+ preload="metadata"+ onMouseEnter={(e) => void e.currentTarget.play().catch(() => {})}+ onMouseLeave={(e) => e.currentTarget.pause()}+ className={media}+ />+ ) : (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={o.url} alt="" loading="lazy" className={media} />+ )}+ </button>+ );+}++function Results({ id, r, compact }: { id: string; r: NodeResults; compact?: boolean }) {+ const ed = useEditor();+ if (r.state === "queued" || r.state === "running") {+ const pct = r.progress != null ? Math.round(r.progress * 100) : null;+ return (+ <div className="relative overflow-hidden rounded-lg bg-muted" style={{ height: compact ? 56 : 96 }}>+ <div className="skeleton-sweep absolute inset-0 animate-skeleton" />+ <div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-2.5">+ <p className="shimmer-text animate-shimmer-text truncate text-[12px] font-medium">{r.message ?? (r.state === "queued" ? "Queued" : "Generating…")}</p>+ {pct != null && <span className="font-mono text-[11px] text-muted-foreground">{pct}%</span>}+ </div>+ {pct != null && <div className="absolute inset-x-0 top-0 h-0.5 bg-primary transition-[width] duration-500" style={{ width: `${pct}%` }} />}+ </div>+ );+ }+ if (r.state === "failed" || r.state === "canceled") {+ return (+ <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")}>+ <RotateCcw className="size-3" /> Retry+ </button>+ )}+ </div>+ );+ }+ if (!r.outputs.length) return null;+ const shown = r.outputs.slice(0, 4);+ return (+ <div className={cn("grid gap-1.5", shown.length > 1 && "grid-cols-2")}>+ {shown.map((x, k) => (+ <OutputThumb key={`${x.g.id}-${x.i}`} o={x.o} onOpen={() => ed.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>+ );+}++// ---------------------------------------------------------------------------+// Generator nodes (any model, and the utilities)++function OptionSelect<T extends string | number>({ value, options, onChange, label, format }: { value: T | undefined; options: T[]; onChange: (v: T) => void; label: string; format?: (v: T) => string }) {+ return (+ <Select value={value === undefined ? undefined : String(value)} onValueChange={(v) => onChange((typeof options[0] === "number" ? Number(v) : v) as T)}>+ <SelectTrigger size="sm" aria-label={label} className={cn("h-7 gap-1 rounded-full border-0 bg-secondary px-2.5 text-[12px] font-medium shadow-none hover:bg-accent dark:bg-secondary", NO_DRAG)}>+ <SelectValue placeholder={label} />+ </SelectTrigger>+ <SelectContent className="max-h-72">+ {options.map((o) => (+ <SelectItem key={String(o)} value={String(o)} className="text-[13px]">+ {format ? format(o) : String(o)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++function ModelOptions({ id, model, data }: { id: string; model: ModelDef; data: CanvasNodeData }) {+ const ed = useEditor();+ 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 extra = (p.extra ?? {}) as Record<string, unknown>;+ const setExtra = (param: string, v?: string | number) => {+ const next = { ...extra };+ if (v === undefined) delete next[param];+ else next[param] = v;+ set({ extra: Object.keys(next).length ? (next as Record<string, string | number>) : undefined });+ };+ 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" />);+ 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)}>+ <AudioLines className="size-3" /> Sound+ </button>,+ );+ 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>;+}++function EngineBadge({ model }: { model?: ModelDef }) {+ if (!model) return null;+ const open = model.engine === "open";+ return (+ <span className={cn("inline-flex h-5 shrink-0 items-center gap-1 rounded-full px-1.5 text-[10px] font-semibold", open ? "bg-success/15 text-success" : "bg-brand-faint text-brand-text")}>+ {open ? <Cpu className="size-3" /> : <Cloud className="size-3" />}+ {open ? "Open" : "Cloud"}+ </span>+ );+}++function costLabel(ed: ReturnType<typeof useEditor>, model: ModelDef | undefined, cost: number | null): string {+ if (!model) return "";+ if (ed.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 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 auto = type === "model" && ops.length > 1;+ const inferred = auto ? effectiveOp(ed.graph, ed.graph.nodes.find((n) => n.id === id) ?? node) : undefined;+ const [pickerEngine, setPickerEngine] = useState<Engine>(model?.engine ?? ed.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;++ // Handles change with the model and op: tell React Flow to re-measure them.+ 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 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) });+ };++ // Upscale / Remove background: image or video.+ 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 running = r.state === "running" || r.state === "queued";+ const menu: MenuItem[] = [+ { label: "Run node", icon: Play, onSelect: () => ed.run([id]) },+ { label: "Re-run", icon: RotateCcw, onSelect: () => ed.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: true },+ ...(r.outputs.some((x) => ["image", "video", "audio"].includes(x.o.kind)) ? [{ label: "Use result as an input", icon: ImagePlus, onSelect: () => ed.toInput(id) }] : []),+ ...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" : "";++ return (+ <NodeShell+ id={id}+ type={type}+ data={data}+ selected={!!selected}+ out={out}+ menu={menu}+ tone={running ? "running" : r.state === "failed" ? "failed" : undefined}+ badge={+ <>+ {data.pinned && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Pin className="size-3.5 shrink-0 text-brand-text" aria-label="Pinned" />+ </TooltipTrigger>+ <TooltipContent>Pinned: runs reuse this result</TooltipContent>+ </Tooltip>+ )}+ <EngineBadge model={model} />+ </>+ }+ 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(" · ")}+ </span>+ {!ed.readOnly && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ onClick={() => (running ? ed.cancel(id) : ed.run([id], !step && !!reused))}+ disabled={ed.running && !running}+ className={cn(+ "grid size-7 shrink-0 place-items-center rounded-full transition-colors disabled:opacity-50",+ running ? "bg-muted text-foreground hover:bg-accent" : "bg-primary text-primary-foreground hover:bg-primary/90",+ NO_DRAG,+ )}+ aria-label={running ? "Cancel" : step ? "Run node" : "Run node again"}+ >+ {running ? <Square className="size-3" /> : step ? <Play className="size-3.5" /> : <RotateCcw className="size-3.5" />}+ </button>+ </TooltipTrigger>+ <TooltipContent>{running ? "Cancel" : step ? "Run this node (and what it needs)" : "Run it again"}</TooltipContent>+ </Tooltip>+ )}+ </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>}+ <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")}>+ {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")}>+ {choices.length ? (+ <div className={NO_DRAG}>+ <ModelPicker models={choices} value={model} onChange={pickModel} engine={pickerEngine} onEngineChange={setPickerEngine} />+ </div>+ ) : (+ <p className="text-[12px] text-muted-foreground">No model for this yet.</p>+ )}+ {auto && model && (+ <OptionSelect+ 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])}+ />+ )}+ </div>+ {promptPort && !showPrompt && !ed.readOnly && (+ <button className={chip} onClick={() => setAddWords(true)}>+ <Plus className="size-3" /> Add your own words+ </button>+ )}+ {showPrompt && (+ <textarea+ value={data.prompt ?? ""}+ onChange={(e) => ed.update(id, { prompt: e.target.value })}+ onBlur={() => !data.prompt && setAddWords(false)}+ autoFocus={addWords && !data.prompt}+ readOnly={ed.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}+ 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} />}+ <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")}>+ <AlertCircle className="mt-px size-3.5 shrink-0" />+ {error}+ </p>+ )}+ </div>+ </NodeShell>+ );+});++// ---------------------------------------------------------------------------+// Inputs++const PromptNode = memo(function PromptNode({ id, type, data, selected }: NodeProps<FlowNode>) {+ const ed = useEditor();+ return (+ <NodeShell id={id} type={type} data={data} selected={!!selected} out="text" menu={baseMenu(ed, id)} width={280}>+ <div className="p-3">+ <textarea+ value={data.text ?? ""}+ onChange={(e) => ed.update(id, { text: e.target.value })}+ readOnly={ed.readOnly}+ rows={3}+ placeholder="e.g. “a lighthouse on a cliff at golden hour, cinematic”"+ aria-label="Text"+ 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>+ );+});++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);+ const assets = useAssets(undefined, kind);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button 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>+ );+}++function MediaPreview({ kind, url }: { kind: MediaKind; url: string }) {+ if (kind === "video") return <video src={url} muted playsInline loop controls preload="metadata" className={cn("max-h-52 w-full rounded-lg bg-media object-contain", NO_DRAG)} />;+ if (kind === "audio")+ return (+ <div className={cn("flex items-center gap-2 rounded-lg bg-brand-faint p-2 text-brand-text", NO_DRAG)}>+ <AudioLines className="size-4 shrink-0" />+ <audio src={url} controls preload="metadata" className="h-8 min-w-0 flex-1" />+ </div>+ );+ // eslint-disable-next-line @next/next/no-img-element+ return <img src={url} alt="" className="max-h-52 w-full rounded-lg bg-muted object-contain" />;+}++const MediaInputNode = memo(function MediaInputNode({ id, type, data, selected }: NodeProps<FlowNode>) {+ const ed = useEditor();+ const kind = KIND_OF[type]!;+ const input = useRef<HTMLInputElement>(null);+ const [pending, setPending] = useState<SlotValue | null>(null);+ const [over, setOver] = useState(false);+ const take = (f: File) =>+ void fileToSlot(+ f,+ (v) => {+ if (!v) return setPending(null);+ if (v.uploading) return setPending(v);+ setPending(null);+ ed.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}>+ <div+ className="space-y-2 p-3"+ onDragOver={(e) => {+ if (ed.readOnly || !e.dataTransfer.types.includes("Files")) return;+ e.preventDefault();+ e.stopPropagation();+ setOver(true);+ }}+ onDragLeave={() => setOver(false)}+ onDrop={(e) => {+ const f = e.dataTransfer.files?.[0];+ if (!f || ed.readOnly) return;+ e.preventDefault();+ e.stopPropagation();+ setOver(false);+ take(f);+ }}+ >+ {pending ? (+ <div className="relative">+ <MediaPreview kind={kind} url={pending.preview} />+ <div className="absolute inset-0 grid place-items-center rounded-lg bg-background/60">+ <Loader2 className="size-5 animate-spin" />+ </div>+ </div>+ ) : data.url ? (+ <MediaPreview kind={kind} url={data.url} />+ ) : (+ <button+ onClick={() => input.current?.click()}+ disabled={ed.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",+ NO_DRAG,+ )}+ >+ <Upload className="size-4" />+ <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 && (+ <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 })} />+ {data.url && (+ <button className={chip} onClick={() => ed.update(id, { url: undefined, name: undefined })} aria-label="Remove file">+ <X className="size-3" /> Remove+ </button>+ )}+ </div>+ )}+ <input+ ref={input}+ type="file"+ accept={accept}+ hidden+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) take(f);+ e.target.value = "";+ }}+ />+ </div>+ </NodeShell>+ );+});++const ElementNode = memo(function ElementNode({ id, type, data, selected }: NodeProps<FlowNode>) {+ const ed = useEditor();+ const elements = useElements();+ const [open, setOpen] = useState(false);+ 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;+ return (+ <NodeShell id={id} type={type} data={data} selected={!!selected} out="element" menu={baseMenu(ed, id)} 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" />}+ </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 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>+ )}+ </div>+ </NodeShell>+ );+});++// ---------------------------------------------------------------------------+// 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+ .filter((e) => e.target === id)+ .map((e) => nodes.get(e.source))+ .filter((n): n is CanvasNode => !!n)+ .sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x);+ 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)];+ return (+ <NodeShell id={id} type={type} data={data} selected={!!selected} menu={menu} width={w}>+ <div className="relative p-3">+ <Handle type="target" position={Position.Left} id={PREVIEW_IN} className="canvas-handle canvas-handle-any" aria-label="Preview input (any type)" />+ {sources.length === 0 ? (+ <p className="py-6 text-center text-[12px] text-muted-foreground">Connect results here to preview them side by side.</p>+ ) : (+ <div className={cn("grid gap-2", sources.length > 1 && "grid-cols-2", sources.length > 2 && w >= 540 && "grid-cols-3")}>+ {sources.map((s) => (+ <figure key={s.id} className="min-w-0 space-y-1">+ <SourcePreview node={s} />+ <figcaption className="truncate text-[11px] text-muted-foreground">{nodeLabel(s)}</figcaption>+ </figure>+ ))}+ </div>+ )}+ </div>+ </NodeShell>+ );+});++function SourcePreview({ node }: { node: CanvasNode }) {+ const ed = useEditor();+ 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.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>;+ }+ const kind = KIND_OF[node.type];+ if (kind && node.data.url) return <MediaPreview kind={kind} url={node.data.url} />;+ if (node.type === "prompt") return <p className="line-clamp-6 rounded-lg bg-muted p-2.5 text-[12px] leading-snug">{node.data.text || "Empty text"}</p>;+ return <div className="grid h-20 place-items-center rounded-lg bg-muted text-[11px] text-subtle-foreground">Nothing yet</div>;+}++const NoteNode = memo(function NoteNode({ id, type, data, selected }: NodeProps<FlowNode>) {+ const ed = useEditor();+ return (+ <NodeShell id={id} type={type} data={data} selected={!!selected} menu={baseMenu(ed, id)} width={240} tone="note">+ <div className="p-3">+ <textarea+ value={data.text ?? ""}+ onChange={(e) => ed.update(id, { text: e.target.value })}+ readOnly={ed.readOnly}+ rows={3}+ 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)}+ />+ </div>+ </NodeShell>+ );+});++export const NODE_TYPES = {+ prompt: PromptNode,+ "image-input": MediaInputNode,+ "video-input": MediaInputNode,+ "audio-input": MediaInputNode,+ element: ElementNode,+ model: GeneratorNode,+ join: GeneratorNode,+ frame: GeneratorNode,+ upscale: GeneratorNode,+ "bg-remove": GeneratorNode,+ tts: GeneratorNode,+ output: OutputNode,+ note: NoteNode,+} satisfies Record<CanvasNodeType, React.ComponentType<NodeProps<FlowNode>>>;++export { MediaPreview, OutputThumb, Results, EngineBadge, costLabel };diff --git a/src/components/canvas/palette.tsx b/src/components/canvas/palette.tsxnew file mode 100644index 00000000..33449260--- /dev/null+++ b/src/components/canvas/palette.tsx@@ -0,0 +1,139 @@+"use client";++import { PanelLeftClose, Plus, Search } from "lucide-react";+import { 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";+import { NodeIcon } from "./canvas-context";++export const DRAG_TYPE = "application/x-fuobe-canvas-node";++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 }) {+ const [q, setQ] = useState("");+ const shown = useMemo(() => items.filter((p) => matches(p, q)), [items, q]);+ return (+ <aside className="flex max-h-full w-60 flex-col overflow-hidden rounded-xl border bg-popover/95 shadow-normal backdrop-blur" aria-label="Add nodes">+ <div className="flex items-center gap-1 border-b p-2">+ <div className="relative min-w-0 flex-1">+ <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <input+ value={q}+ onChange={(e) => setQ(e.target.value)}+ placeholder="Search nodes"+ aria-label="Search nodes"+ className="h-8 w-full rounded-md bg-muted pr-2 pl-8 text-[13px] outline-none placeholder:text-subtle-foreground focus:ring-2 focus:ring-brand-faint"+ />+ </div>+ <Tooltip>+ <TooltipTrigger asChild>+ <button onClick={onClose} className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Hide the node palette">+ <PanelLeftClose className="size-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Hide palette</TooltipContent>+ </Tooltip>+ </div>+ <div className="min-h-0 flex-1 space-y-3 overflow-y-auto p-2">+ {GROUPS.map((group) => {+ const list = shown.filter((p) => p.group === group);+ if (!list.length) return null;+ return (+ <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) => {+ return (+ <button+ key={p.id}+ draggable+ onDragStart={(e) => {+ e.dataTransfer.setData(DRAG_TYPE, p.id);+ e.dataTransfer.effectAllowed = "copy";+ }}+ onClick={() => onAdd(p)}+ className="flex w-full cursor-grab items-start gap-2.5 rounded-lg px-1.5 py-1.5 text-left transition-colors hover:bg-accent active:cursor-grabbing"+ title={`${p.description}. Drag onto the board, or click to add.`}+ >+ <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-1 text-[11px] leading-snug text-muted-foreground">{p.description}</span>+ </span>+ </button>+ );+ })}+ </div>+ );+ })}+ {!shown.length && <p className="px-2 py-6 text-center text-[12px] text-muted-foreground">No node called “{q}”.</p>}+ </div>+ </aside>+ );+}++export function PaletteToggle({ onOpen }: { onOpen: () => void }) {+ return (+ <button onClick={onOpen} className="inline-flex h-9 items-center gap-1.5 rounded-full border bg-popover px-3.5 text-[13px] font-medium shadow-normal hover:bg-accent" aria-label="Add a node">+ <Plus className="size-4" /> Add node+ </button>+ );+}++/**+ * The floating Add-node menu (right-click or double-click on the board, or a connection dropped on+ * empty space). Positioned in the board's own coordinates; Escape or a click outside closes it.+ */+export function AddMenu({ x, y, items, title, onPick, onClose }: { x: number; y: number; items: PaletteItem[]; title?: string; onPick: (p: PaletteItem) => void; onClose: () => void }) {+ const ref = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const down = (e: PointerEvent) => {+ if (ref.current && !ref.current.contains(e.target as Node)) onClose();+ };+ window.addEventListener("pointerdown", down, true);+ return () => window.removeEventListener("pointerdown", down, true);+ }, [onClose]);+ return (+ <div+ ref={ref}+ className="absolute z-30 w-64 animate-pop-in overflow-hidden rounded-xl border bg-popover shadow-strong"+ style={{ left: x, top: y }}+ onKeyDown={(e) => {+ if (e.key === "Escape") onClose();+ e.stopPropagation();+ }}+ onContextMenu={(e) => e.preventDefault()}+ >+ {/* Plain substring matching: fuzzy matching finds "Audio" for "upsc". */}+ <Command className="rounded-none!" filter={(value, search) => (value.toLowerCase().includes(search.trim().toLowerCase()) ? 1 : 0)}>+ {title && <p className="px-2.5 pt-2 text-[11px] font-medium text-muted-foreground">{title}</p>}+ <CommandInput autoFocus placeholder="Add a node…" />+ <CommandList className="max-h-80">+ <CommandEmpty>Nothing matches.</CommandEmpty>+ {GROUPS.map((group) => {+ const list = items.filter((p) => p.group === group);+ if (!list.length) return null;+ return (+ <CommandGroup key={group} heading={group}>+ {list.map((p) => {+ return (+ <CommandItem key={p.id} value={`${p.label} ${p.keywords ?? ""}`} onSelect={() => onPick(p)} className="gap-2">+ <NodeIcon name={p.icon} className="size-4 text-muted-foreground" />+ <span className="truncate text-[13px]">{p.label}</span>+ </CommandItem>+ );+ })}+ </CommandGroup>+ );+ })}+ </CommandList>+ </Command>+ </div>+ );+}diff --git a/src/components/canvas/use-canvas.ts b/src/components/canvas/use-canvas.tsnew file mode 100644index 00000000..b738a953--- /dev/null+++ b/src/components/canvas/use-canvas.ts@@ -0,0 +1,151 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useEffect, useRef, useState } from "react";+import type { Canvas, CanvasGraph, CanvasPlan, CanvasSummary } from "@/lib/catalog/canvas";+import type { Engine, Generation } from "@/lib/catalog/types";++/** Client hooks for /api/canvases (kept next to the canvas UI; the shapes live in src/lib/catalog/canvas.ts). */++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 });+ return body;+}++const send = (url: string, method: string, body?: unknown, init?: RequestInit) =>+ fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), ...init });++export interface CanvasView {+ canvas: Canvas;+ generations: Generation[];+}++const active = (g: Generation) => g.status === "queued" || g.status === "running";++export function useCanvases() {+ return useQuery({+ queryKey: ["canvases"],+ queryFn: async () => (await json<{ items: CanvasSummary[] }>(await fetch("/api/canvases"))).items,+ });+}++/**+ * One canvas with its nodes' generations. Polls while something renders (slower when the live+ * stream delivers updates).+ */+export function useCanvasView(id: string, live: boolean) {+ return useQuery({+ queryKey: ["canvases", id],+ queryFn: async () => json<CanvasView>(await fetch(`/api/canvases/${id}`)),+ refetchInterval: (q) => (q.state.data?.generations.some(active) ? (live ? 6000 : 1500) : false),+ // The editor owns the graph once loaded; refetches only bring runs and generations.+ refetchOnWindowFocus: false,+ });+}++export function useCanvasActions() {+ const qc = useQueryClient();+ const refresh = () => void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });+ return {+ create: async (body: { name?: string; templateId?: string; engine?: Engine; graph?: CanvasGraph }) => {+ const c = await json<Canvas>(await send("/api/canvases", "POST", body));+ refresh();+ return c;+ },+ rename: async (id: string, name: string) => {+ qc.setQueryData<CanvasSummary[]>(["canvases"], (old) => old?.map((c) => (c.id === id ? { ...c, name } : c)));+ await json<Canvas>(await send(`/api/canvases/${id}`, "PATCH", { name }));+ refresh();+ },+ duplicate: async (id: string) => {+ const c = await json<Canvas>(await send(`/api/canvases/${id}/duplicate`, "POST"));+ refresh();+ return c;+ },+ remove: async (id: string) => {+ qc.setQueryData<CanvasSummary[]>(["canvases"], (old) => old?.filter((c) => c.id !== id));+ const res = await fetch(`/api/canvases/${id}`, { method: "DELETE" });+ if (!res.ok && res.status !== 404) throw new Error("Couldn't delete it. Please try again.");+ qc.removeQueries({ queryKey: ["canvases", id] });+ refresh();+ },+ };+}++/** Save the board (autosave). `keepalive` lets a save started while leaving the page finish. */+export async function saveCanvas(id: string, patch: { name?: string; graph?: CanvasGraph }, keepalive = false): Promise<Canvas> {+ return json<Canvas>(await send(`/api/canvases/${id}`, "PATCH", patch, { keepalive }));+}++export interface RunResponse {+ canvas: Canvas;+ items: Generation[];+ ran: string[];+ reused: CanvasPlan["reused"];+ errors: CanvasPlan["errors"];+ costUsd: number;+}++export function useRunCanvas(id: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: async (body: { targets?: string[]; force?: boolean; graph: CanvasGraph }) => {+ const res = await send(`/api/canvases/${id}/run`, "POST", body);+ const data = (await res.json().catch(() => ({}))) as Partial<RunResponse> & { error?: string };+ if (!res.ok && !data.errors) throw new Error(data.error ?? `Request failed (${res.status})`);+ return { ...data, ok: res.ok } as RunResponse & { ok: boolean; error?: string };+ },+ onSuccess: (r) => {+ if (!r.canvas) return;+ qc.setQueryData<CanvasView>(["canvases", id], (old) => {+ const known = new Map((old?.generations ?? []).map((g) => [g.id, g]));+ for (const g of r.items ?? []) known.set(g.id, g);+ return { canvas: { ...(old?.canvas ?? r.canvas), runs: r.canvas.runs, updatedAt: r.canvas.updatedAt }, generations: [...known.values()] };+ });+ // New results appear in the library and feeds too.+ void qc.invalidateQueries({ queryKey: ["generations"] });+ void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });+ },+ });+}++/**+ * 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/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex 7019cf80..377bdbb2 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -128,6 +128,12 @@ export interface OutlineBox {type: CanvasNodeType;}+/** The board in miniature: node boxes and the edges between them (as indexes into `boxes`). */+export interface Outline {+ boxes: OutlineBox[];+ links: [number, number][];+}+export interface CanvasSummary {id: string;name: string;@@ -135,7 +141,7 @@ export interface CanvasSummary {templateId: string | null;/** The newest finished image or video made on this canvas. */preview: { url: string; kind: MediaKind } | null;- outline: OutlineBox[];+ outline: Outline;createdAt: number;updatedAt: number;editedAt: number | null;@@ -808,7 +814,10 @@ function hash(s: string): string {/** The node's identity for "is this result still fresh": its request (minus labels) and the generations it builds on. */export function nodeSignature(req: GenerationRequest, depIds: string[]): string {- const { step: _step, frame: _frame, feature: _feature, ...rest } = req;+ const rest: Partial<GenerationRequest> = { ...req };+ delete rest.step;+ delete rest.frame;+ delete rest.feature;return hash(stable({ ...rest, deps: depIds }));}@@ -1013,8 +1022,13 @@ export function cleanGraph(graph: CanvasGraph): CanvasGraph {return g;}-export function outline(graph: CanvasGraph): OutlineBox[] {- return graph.nodes.filter((n) => n.type !== "note").slice(0, 40).map((n) => ({ x: Math.round(n.position.x), y: Math.round(n.position.y), type: n.type }));+export function outline(graph: CanvasGraph): Outline {+ const nodes = graph.nodes.filter((n) => n.type !== "note").slice(0, 40);+ const index = new Map(nodes.map((n, i) => [n.id, i]));+ return {+ boxes: nodes.map((n) => ({ x: Math.round(n.position.x), y: Math.round(n.position.y), type: n.type })),+ links: graph.edges.flatMap((e) => (index.has(e.source) && index.has(e.target) ? [[index.get(e.source)!, index.get(e.target)!] as [number, number]] : [])),+ };}let seq = 0;@@ -1072,7 +1086,9 @@ function tpl(nodes: TplNode[], edges: [string, string, string?][]): (engine: Eng};}-const COL = 360;+/** Column and row spacing: a generator node with a result is about 300 × 460 px. */+const COL = 380;+const ROW = 500;export const CANVAS_TEMPLATES: CanvasTemplate[] = [{@@ -1103,12 +1119,12 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [hue: 30,build: tpl([- { id: "product", type: "image-input", x: 0, y: 200, data: { label: "Product photo" } },+ { id: "product", type: "image-input", x: 0, y: ROW, data: { label: "Product photo" } },{ id: "front", type: "model", x: COL, y: 0, data: { mediaKind: "image", label: "Front ¾ angle", op: "edit", prompt: "The same product from a three-quarter front angle on a seamless studio background, soft key light, sharp details" }, models: { cloud: "nano-banana-pro", open: "oss-qwen-edit" } },- { id: "side", type: "model", x: COL, y: 230, data: { mediaKind: "image", label: "Side profile", op: "edit", prompt: "The same product in a clean side profile on a seamless studio background, rim light, sharp details" }, models: { cloud: "nano-banana-pro", open: "oss-qwen-edit" } },- { id: "top", type: "model", x: COL, y: 460, data: { mediaKind: "image", label: "Top-down", op: "edit", prompt: "The same product shot top-down as a flat lay on a seamless studio background, even light" }, models: { cloud: "nano-banana-pro", open: "oss-qwen-edit" } },- { id: "video", type: "model", x: COL * 2, y: 200, data: { mediaKind: "video", label: "Ad clip", op: "ref2v", prompt: "A premium product commercial: the camera orbits the product from the reference angles, studio lighting, slow and smooth", params: { aspectRatio: "16:9", duration: 5 } }, models: { cloud: "seedance-2-5", open: "oss-wan-vace" } },- { id: "out", type: "output", x: COL * 3, y: 220, data: { label: "Ad" } },+ { id: "side", type: "model", x: COL, y: ROW, data: { mediaKind: "image", label: "Side profile", op: "edit", prompt: "The same product in a clean side profile on a seamless studio background, rim light, sharp details" }, models: { cloud: "nano-banana-pro", open: "oss-qwen-edit" } },+ { id: "top", type: "model", x: COL, y: ROW * 2, data: { mediaKind: "image", label: "Top-down", op: "edit", prompt: "The same product shot top-down as a flat lay on a seamless studio background, even light" }, models: { cloud: "nano-banana-pro", open: "oss-qwen-edit" } },+ { id: "video", type: "model", x: COL * 2, y: ROW - 40, data: { mediaKind: "video", label: "Ad clip", op: "ref2v", prompt: "A premium product commercial: the camera orbits the product from the reference angles, studio lighting, slow and smooth", params: { aspectRatio: "16:9", duration: 5 } }, models: { cloud: "seedance-2-5", open: "oss-wan-vace" } },+ { id: "out", type: "output", x: COL * 3, y: ROW, data: { label: "Ad" } },],[["product", "front", "images"],@@ -1129,12 +1145,12 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [hue: 200,build: tpl([- { id: "script", type: "prompt", x: 0, y: 230, 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: 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." } },...[0, 1, 2].map((i) => ({id: `frame${i + 1}`,type: "model" as const,x: COL,- y: i * 230,+ y: i * ROW,data: {mediaKind: "image" as const,label: `Frame ${i + 1}`,@@ -1151,7 +1167,7 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [id: `shot${i + 1}`,type: "model" as const,x: COL * 2,- y: i * 230,+ y: i * ROW,data: {mediaKind: "video" as const,label: `Shot ${i + 1}`,@@ -1161,8 +1177,8 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [},models: { cloud: "kling-2-5-turbo", open: "oss-wan22-14b-fast" },})),- { id: "film", type: "join", x: COL * 3, y: 230, data: { label: "Film" }, models: { cloud: "join-clips", open: "oss-join-clips" } },- { id: "out", type: "output", x: COL * 4, y: 250, data: { label: "Film" } },+ { id: "film", type: "join", x: COL * 3, y: ROW, data: { label: "Film" }, models: { cloud: "join-clips", open: "oss-join-clips" } },+ { id: "out", type: "output", x: COL * 4, y: ROW, data: { label: "Film" } },],[["script", "frame1", "prompt"],@@ -1188,9 +1204,9 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [const models = engine === "open" ? ["oss-z-image-turbo", "oss-qwen-image", "oss-flux1-krea"] : ["nano-banana-pro", "seedream-5-pro", "flux-2-pro"];return tpl([- { id: "prompt", type: "prompt", x: 0, y: 230, data: { label: "Prompt", text: "Portrait of an elderly fisherman mending a net at dawn, soft window light, film grain" } },- ...models.map((m, i) => ({ id: `m${i + 1}`, type: "model" as const, x: COL, y: i * 230, data: { mediaKind: "image" as const, modelId: m, params: { aspectRatio: "3:4" } } })),- { id: "out", type: "output", x: COL * 2, y: 200, data: { label: "Compare" }, width: 560 },+ { id: "prompt", type: "prompt", x: 0, y: ROW - 60, data: { label: "Prompt", text: "Portrait of an elderly fisherman mending a net at dawn, soft window light, film grain" } },+ ...models.map((m, i) => ({ id: `m${i + 1}`, type: "model" as const, x: COL, y: i * (ROW - 60), data: { mediaKind: "image" as const, modelId: m, params: { aspectRatio: "3:4" } } })),+ { id: "out", type: "output", x: COL * 2, y: ROW - 120, data: { label: "Compare" }, width: 560 },],[["prompt", "m1", "prompt"], ["prompt", "m2", "prompt"], ["prompt", "m3", "prompt"], ["m1", "out"], ["m2", "out"], ["m3", "out"]],)(engine);@@ -1205,9 +1221,9 @@ export const CANVAS_TEMPLATES: CanvasTemplate[] = [build: tpl([{ id: "portrait", type: "image-input", x: 0, y: 0, data: { label: "Portrait" } },- { id: "sample", type: "audio-input", x: 0, y: 220, data: { label: "Voice sample (10–30 s)" } },- { id: "script", type: "prompt", x: 0, y: 420, data: { label: "Script", text: "Hi! This whole clip was made on a Fuobe canvas from one photo and a few seconds of my voice." } },- { id: "voice", type: "tts", x: COL, y: 280, data: { label: "Cloned voice" }, models: { cloud: "chatterbox-cloud", open: "oss-chatterbox" } },+ { id: "sample", type: "audio-input", x: 0, y: 340, data: { label: "Voice sample (10–30 s)" } },+ { id: "script", type: "prompt", x: 0, y: 540, data: { label: "Script", text: "Hi! This whole clip was made on a Fuobe canvas from one photo and a few seconds of my voice." } },+ { id: "voice", type: "tts", x: COL, y: 400, data: { label: "Cloned voice" }, models: { cloud: "chatterbox-cloud", open: "oss-chatterbox" } },{ id: "avatar", type: "model", x: COL * 2, y: 80, data: { mediaKind: "video", label: "Talking avatar", op: "avatar", prompt: "A friendly presenter talking to the camera, natural head movement" }, models: { cloud: "kling-avatar-2", open: "oss-infinitetalk" } },{ id: "out", type: "output", x: COL * 3, y: 100, data: { label: "Clip" } },],diff --git a/src/server/canvas.ts b/src/server/canvas.tsindex 1c20853f..ebbf29c3 100644--- a/src/server/canvas.ts+++ b/src/server/canvas.ts@@ -134,7 +134,7 @@ export function getCanvas(id: string): Canvas | null {return r ? toCanvas(r) : null;}-/** The newest finished image or video among the canvas's results. */+/** The newest finished image among the canvas's results (a video when it made no image). */function previewOf(runs: CanvasRuns): CanvasSummary["preview"] {const ids = Object.values(runs).sort((a, b) => b.at - a.at)@@ -142,7 +142,9 @@ function previewOf(runs: CanvasRuns): CanvasSummary["preview"] {.slice(0, 60);if (!ids.length) return null;const rows = db()- .prepare(`SELECT outputs_json FROM generations WHERE id IN (${ids.map(() => "?").join(",")}) AND status = 'succeeded' AND kind IN ('image','video') ORDER BY completed_at DESC LIMIT 1`)+ .prepare(+ `SELECT outputs_json FROM generations WHERE id IN (${ids.map(() => "?").join(",")}) AND status = 'succeeded' AND kind IN ('image','video') ORDER BY kind = 'image' DESC, completed_at DESC LIMIT 1`,+ ).all(...ids) as { outputs_json: string }[];const o = rows[0] ? (JSON.parse(rows[0].outputs_json) as { url: string; kind: MediaKind }[]).find((x) => x.kind === "image" || x.kind === "video") : undefined;return o ? { url: o.url, kind: o.kind } : null;diff --git a/tests/canvas-api.test.ts b/tests/canvas-api.test.tsindex aadd73cf..a8417b97 100644--- a/tests/canvas-api.test.ts+++ b/tests/canvas-api.test.ts@@ -83,7 +83,12 @@ describe("canvas API", () => {res = await list.GET();const items = ((await res.json()) as { items: CanvasSummary[] }).items;expect(items[0]).toMatchObject({ id, name: "Fox film", nodeCount: 4, preview: null });- expect(items[0].outline).toHaveLength(4);+ expect(items[0].outline.boxes).toHaveLength(4);+ expect(items[0].outline.links).toEqual([+ [0, 1],+ [1, 2],+ [2, 3],+ ]);});it("runs the graph as chained generations, then reuses fresh results", async () => {@@ -110,7 +115,8 @@ describe("canvas API", () => {const view = (await res.json()) as { canvas: Canvas; generations: Generation[] };expect(view.generations.map((g) => g.status).sort()).toEqual(["succeeded", "succeeded"]);const listed = ((await (await list.GET()).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;- expect(listed.preview?.kind).toBe("video");+ // Cards prefer a still over a clip.+ expect(listed.preview).toEqual({ url: gens.getGeneration(img.id)!.outputs[0].url, kind: "image" });// Nothing changed: Run all starts nothing.res = await run.POST(req("POST", {}), ctx(id));