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 editor: re-describe only what changed, lazy option lists
Claudeecd44effda86
diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsxindex 4a0439cc..30818236 100644--- a/src/components/canvas/canvas-context.tsx+++ b/src/components/canvas/canvas-context.tsx@@ -22,7 +22,19 @@ import {type LucideIcon,} from "lucide-react";import { createContext, useContext, useMemo, useSyncExternalStore } from "react";-import { effectiveOp, isGenerator, type CanvasGraph, type CanvasNode, type CanvasNodeData, type CanvasPlan, type Connection, type NodeDescription, type PortType, type RunReason } from "@/lib/catalog/canvas";+import {+ describeNode,+ effectiveOp,+ isGenerator,+ type CanvasGraph,+ type CanvasNode,+ type CanvasNodeData,+ type CanvasPlan,+ type Connection,+ type NodeDescription,+ type PortType,+ type RunReason,+} from "@/lib/catalog/canvas";import type { Engine, Generation, GenerationStatus, ModelDef, Operation, OutputFile } from "@/lib/catalog/types";import type { EngineMode } from "@/lib/api";@@ -156,6 +168,51 @@ const sameCounts = (a: Readonly<Record<string, number>>, b: Readonly<Record<striconst sameView = (a: NodeView, b: NodeView) =>a.op === b.op && a.error === b.error && a.costUsd === b.costUsd && a.step === b.step && a.reused === b.reused && a.runError === b.runError && a.results === b.results && sameCounts(a.counts, b.counts);+/** What the planner knows about one generator node: its description and the op it runs. */+export interface NodeInfo {+ d: NodeDescription;+ op?: Operation;+}++/**+ * describeNode and effectiveOp per generator node, worked out again only for nodes whose own data+ * or whose inputs (the nodes wired into them, their order on the board) changed. Typing in one+ * prompt re-describes that prompt's consumers, not the whole board.+ */+export class DescribeCache {+ private entries = new Map<string, { key: unknown[]; info: NodeInfo }>();+ private mode: string | null = null;+ run(graph: CanvasGraph, mode: EngineMode): Map<string, NodeInfo> {+ if (mode !== this.mode) {+ this.entries.clear();+ this.mode = mode;+ }+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));+ const into = new Map<string, CanvasGraph["edges"]>();+ for (const e of graph.edges) {+ const list = into.get(e.target);+ if (list) list.push(e);+ else into.set(e.target, [e]);+ }+ const next = new Map<string, { key: unknown[]; info: NodeInfo }>();+ const out = new Map<string, NodeInfo>();+ for (const n of graph.nodes) {+ if (!isGenerator(n)) continue;+ const key: unknown[] = [n.type, n.data];+ for (const e of into.get(n.id) ?? []) {+ const s = byId.get(e.source);+ key.push(e.source, e.targetHandle, s?.type, s?.data, s?.position.x, s?.position.y);+ }+ const old = this.entries.get(n.id);+ const entry = old && old.key.length === key.length && old.key.every((k, i) => k === key[i]) ? old : { key, info: { d: describeNode(graph, n, { engineMode: mode }), op: effectiveOp(graph, n) } };+ next.set(n.id, entry);+ out.set(n.id, entry.info);+ }+ this.entries = next;+ return out;+ }+}+/*** One NodeView per generator node, keeping the previous object whenever nothing it shows changed* (so its memoized node doesn't re-render).@@ -167,6 +224,7 @@ export function buildViews(describe: (id: string) => NodeDescription | undefined,results: ReadonlyMap<string, NodeResults>,runErrors: Record<string, string>,+ opOf: (n: CanvasNode) => Operation | undefined = (n) => effectiveOp(graph, n),): Map<string, NodeView> {const counts = new Map<string, Record<string, number>>();for (const e of graph.edges) {@@ -182,7 +240,7 @@ export function buildViews(if (!isGenerator(n)) continue;const d = describe(n.id);const next: NodeView = {- op: effectiveOp(graph, n),+ op: opOf(n),counts: counts.get(n.id) ?? EMPTY_VIEW.counts,error: d?.error,costUsd: d?.costUsd ?? null,diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex c2af8958..6dba60c5 100644--- a/src/components/canvas/canvas-editor.tsx+++ b/src/components/canvas/canvas-editor.tsx@@ -67,7 +67,6 @@ import {type CanvasGraph,type CanvasNode,type CanvasNodeData,- type NodeDescription,type PaletteItem,type PortType,} from "@/lib/catalog/canvas";@@ -76,6 +75,7 @@ import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";import {buildViews,+ DescribeCache,EditorActionsContext,EditorStore,EditorStoreContext,@@ -154,7 +154,7 @@ export function CanvasEditor({ id }: { id: string }) {}return (<ReactFlowProvider>- <Editor id={id} initial={view.data.canvas} view={view.data} />+ <Editor key={id} id={id} initial={view.data.canvas} view={view.data} /></ReactFlowProvider>);}@@ -227,12 +227,13 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvconst 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]);+ // Described again only where a node or its inputs changed (one keystroke touches one prompt's consumers).+ const [describer] = useState(() => new DescribeCache());+ const described = useMemo(() => describer.run(planned, mode), [describer, planned, mode]);+ const plan = useMemo(+ () => planCanvas(planned, { runs, status: statusOf, engineMode: mode, describe: (n) => described.get(n.id)?.d ?? describeNode(planned, n, { engineMode: mode }) }),+ [planned, runs, statusOf, mode, described],+ );const results = useMemo(() => {const m = new Map<string, NodeResults>();for (const [nodeId, r] of Object.entries(runs)) {@@ -244,9 +245,18 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv// eslint-disable-next-line react-hooks/exhaustive-deps}, [runs, gens]);const views = useMemo(- () => buildViews(prev?.views ?? null, planned, plan, (nid) => descriptions.get(nid), results, runErrors),+ () =>+ buildViews(+ prev?.views ?? null,+ planned,+ plan,+ (nid) => described.get(nid)?.d,+ results,+ runErrors,+ (n) => described.get(n.id)?.op,+ ),// eslint-disable-next-line react-hooks/exhaustive-deps- [planned, plan, descriptions, results, runErrors],+ [planned, plan, described, results, runErrors],);const selected = useMemo(() => nodes.filter((n) => n.selected).map((n) => n.id), [nodes]);const busy = [...results.values()].filter((r) => r.state === "running" || r.state === "queued").length;diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex 50fe3a6f..9fd62410 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -520,19 +520,27 @@ function Results({ id, r, compact }: { id: string; r: NodeResults; compact?: boo// ---------------------------------------------------------------------------// Generator nodes (any model, and the utilities)+/**+ * A compact select. Its options mount only while it's open (a closed Radix Select still renders+ * every item, which adds up to thousands on a big board); the trigger shows the value itself.+ */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 }) {+ const [open, setOpen] = useState(false);+ const text = (v: T) => (format ? format(v) : String(v));return (- <Select value={value === undefined ? undefined : String(value)} onValueChange={(v) => onChange((typeof options[0] === "number" ? Number(v) : v) as T)}>+ <Select open={open} onOpenChange={setOpen} 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} />+ <SelectValue placeholder={label}>{value === undefined ? undefined : text(value)}</SelectValue></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>+ {open && (+ <SelectContent className="max-h-72">+ {options.map((o) => (+ <SelectItem key={String(o)} value={String(o)} className="text-[13px]">+ {text(o)}+ </SelectItem>+ ))}+ </SelectContent>+ )}</Select>);}diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex 8f82f38b..ba0e539a 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -914,6 +914,8 @@ export interface PlanOptions extends DescribeContext {runs?: CanvasRuns;/** Status of a generation this canvas made (undefined = gone). */status?: (generationId: string) => GenerationStatus | undefined;+ /** describeNode, when the caller keeps its own cache of it (the editor re-plans on every keystroke). */+ describe?: (n: CanvasNode) => NodeDescription;}const LIVE = new Set<GenerationStatus | undefined>(["queued", "running", "succeeded"]);@@ -966,7 +968,7 @@ export function planCanvas(graph: CanvasGraph, opts: PlanOptions = {}): CanvasPl}continue;}- const d = describeNode(graph, n, opts);+ const d = opts.describe?.(n) ?? describeNode(graph, n, opts);if (d.error || !d.request || !d.deps) {state.set(id, { kind: "blocked" });errors.push({ nodeId: id, message: d.error ?? "Can't run this node" });diff --git a/tests/canvas-editor-state.test.ts b/tests/canvas-editor-state.test.tsindex 2aa921c8..92140a43 100644--- a/tests/canvas-editor-state.test.ts+++ b/tests/canvas-editor-state.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { buildViews, EMPTY_RESULTS, foldResultsKeep, type NodeResults } from "@/components/canvas/canvas-context";+import { buildViews, DescribeCache, EMPTY_RESULTS, foldResultsKeep, type NodeResults } from "@/components/canvas/canvas-context";import { describeNode, planCanvas, type CanvasGraph, type CanvasNode } from "@/lib/catalog/canvas";import type { Generation } from "@/lib/catalog/types";import { applyToCanvasView, type CanvasViewLike } from "@/lib/generation-stream";@@ -97,6 +97,24 @@ describe("canvas node views", () => {expect(next.get("vid")).toMatchObject({ error: "Write a prompt first", runError: "Nope" });});+ it("describes again only the nodes whose own data or inputs changed", () => {+ const cache = new DescribeCache();+ const first = cache.run(graph, "both");+ expect(first.get("img")).toMatchObject({ op: "t2i", d: { request: { prompt: "A red fox" } } });+ expect(first.get("vid")?.op).toBe("i2v");+ // Same graph: same objects.+ const again = cache.run(graph, "both");+ expect(again.get("img")).toBe(first.get("img"));+ // Typing in the prompt touches the image (its input) and nothing downstream of it.+ const typed: CanvasGraph = { ...graph, nodes: graph.nodes.map((x): CanvasNode => (x.id === "p" ? { ...x, data: { text: "A red fox in snow" } } : x)) };+ const next = cache.run(typed, "both");+ expect(next.get("img")).not.toBe(first.get("img"));+ expect(next.get("img")?.d.request?.prompt).toBe("A red fox in snow");+ expect(next.get("vid")).toBe(first.get("vid"));+ // The engine mode changes every description.+ expect(cache.run(typed, "open").get("vid")?.d.error).toMatch(/paid cloud model/);+ });+it("folds a node's results once per change of its generations", () => {const a = gen();const r = foldResultsKeep(undefined, [a]);