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
ComfyUI provider: resilient polling, one socket per server, blocking first probe, round-3 inputs and outputs
Claudefbbe56408223
diff --git a/src/lib/comfy.ts b/src/lib/comfy.tsindex 5641e5d7..c4e5122e 100644--- a/src/lib/comfy.ts+++ b/src/lib/comfy.ts@@ -51,6 +51,15 @@ export interface ManifestModel {sizeGb?: number;}+export interface ManifestOutput {+ node: string;+ kind: MediaKind;+ /** Audio stems of a voice/background separation. */+ stem?: "voice" | "background";+ /** What a text or image output is: timed caption cues, a plain transcript, the detected language, layers, a grid's sheet or tiles… */+ role?: "cues" | "transcript" | "language" | "layers" | "sheet" | "tiles" | "first-frame" | "turntable";+}+export interface ManifestWorkflow {id: string;title: string;@@ -58,12 +67,19 @@ export interface ManifestWorkflow {file: string;source: string;bindings: Partial<Record<BindingKey, BindingTarget[]>>;- outputs: { node: string; kind: MediaKind }[];+ outputs: ManifestOutput[];defaults: Record<string, number | string>;limits?: Record<string, number>;models: ManifestModel[];customNodes: { name: string; repo: string }[];vramGb?: number | string;+ license?: string;+ /** Node-managed downloads that happen on the first run (not in `models`). */+ autoDownloads?: string[];+ /** "isolated": the node pack has process-wide side effects and runs on a separate ComfyUI. */+ worker?: "isolated";+ /** The provider rewrites the graph before submitting ("captions": one segment per caption cue). */+ expand?: "captions";validated: boolean;notes?: string;}@@ -237,3 +253,240 @@ export function explainComfyError(nodeErrors: unknown, manifest?: ManifestWorkfl}return [...new Set(parts)].join("\n") || "ComfyUI rejected the workflow";}++// ---------------------------------------------------------------------------+// Round-3 helpers: caption cues, caption burn-in graphs, languages, palettes, layer bounding boxes.++export interface CaptionCue {+ start: number;+ end: number;+ text: string;+}++const CUE_LINE = /^\s*(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)\s*:\s?(.*)$/;+const SRT_TIME = /(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})\s*-->\s*(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})/;++const srtSeconds = (h: string | undefined, m: string, s: string, ms: string) => Number(h ?? 0) * 3600 + Number(m) * 60 + Number(s) + Number(ms.padEnd(3, "0")) / 1000;++/**+ * Timed caption cues from text: Qwen3-ASR's "start-end: text" lines (seconds) or SRT / WebVTT blocks.+ * Lines that are neither are ignored; the result is sorted by start time.+ */+export function parseCueLines(input: string | undefined | null): CaptionCue[] {+ if (!input) return [];+ const cues: CaptionCue[] = [];+ const lines = input.replace(/\r/g, "").split("\n");+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const simple = CUE_LINE.exec(line);+ if (simple) {+ cues.push({ start: Number(simple[1]), end: Number(simple[2]), text: simple[3].trim() });+ continue;+ }+ const srt = SRT_TIME.exec(line);+ if (srt) {+ const text: string[] = [];+ while (i + 1 < lines.length && lines[i + 1].trim() && !SRT_TIME.test(lines[i + 1])) text.push(lines[++i].trim());+ cues.push({ start: srtSeconds(srt[1], srt[2], srt[3], srt[4]), end: srtSeconds(srt[5], srt[6], srt[7], srt[8]), text: text.join(" ") });+ }+ }+ return cues.filter((c) => c.text && Number.isFinite(c.start) && c.end > c.start).sort((a, b) => a.start - b.start);+}++const round3 = (n: number) => Math.round(n * 1000) / 1000;++/** Split cues into captions of at most `words` words (TikTok style), timed by their share of the characters. */+export function splitCueWords(cues: CaptionCue[], words: number): CaptionCue[] {+ if (!words || words < 1) return cues;+ return cues.flatMap((c) => {+ const w = c.text.split(/\s+/).filter(Boolean);+ if (w.length <= words) return [c];+ const groups: string[] = [];+ for (let i = 0; i < w.length; i += words) groups.push(w.slice(i, i + words).join(" "));+ const total = groups.reduce((n, g) => n + g.length + 1, 0);+ let t = c.start;+ return groups.map((text, i) => {+ const end = i === groups.length - 1 ? c.end : t + ((c.end - c.start) * (text.length + 1)) / total;+ const cue = { start: round3(t), end: round3(end), text };+ t = end;+ return cue;+ });+ });+}++const isLinkValue = (v: unknown): v is [string, number] => Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "number";++/** BatchImagesNode takes up to 50 images ("images.image0" … "images.image49"); two levels hold 2,500 segments. */+const BATCH_MAX = 50;+export const MAX_CAPTION_SEGMENTS = BATCH_MAX * BATCH_MAX;++/**+ * Rewrite the captions-burnin template for a list of cues: the clip is cut into consecutive Trim Video+ * segments (gaps and cues), each cue segment gets a Draw Text Overlay with the template's style, and the+ * segments are batched back together in order. A segment may not start after the end of the clip, so the+ * last cue runs to the end of the clip.+ */+export function expandCaptionWorkflow(wf: ComfyWorkflow, cues: CaptionCue[]): ComfyWorkflow {+ const out = cloneWorkflow(wf);+ const ids = Object.keys(out);+ const loader = ids.find((id) => out[id].class_type === "LoadVideo");+ const batch = ids.find((id) => out[id].class_type === "BatchImagesNode");+ const template = ids.map((id) => out[id]).find((n) => n.class_type === "TextOverlay");+ if (!loader || !batch || !template) throw new Error("Not a caption burn-in workflow (needs LoadVideo, TextOverlay and BatchImagesNode)");+ const sorted = cues.filter((c) => c.text.trim() && c.end > c.start).sort((a, b) => a.start - b.start);+ if (!sorted.length) throw new Error("No captions to burn in");++ type Segment = { start: number; duration: number; text?: string };+ const segments: Segment[] = [];+ let cursor = 0;+ sorted.forEach((c, i) => {+ let start = round3(Math.max(c.start, cursor, 0));+ if (start - cursor < 0.02) start = round3(cursor); // close gaps shorter than a frame+ const last = i === sorted.length - 1;+ const end = last ? undefined : round3(Math.min(c.end, sorted[i + 1].start));+ if (end !== undefined && end - start < 0.02) return; // swallowed by the next cue+ if (start > cursor) segments.push({ start: round3(cursor), duration: round3(start - cursor) });+ segments.push({ start, duration: end === undefined ? 0 : round3(end - start), text: c.text.trim() });+ if (end !== undefined) cursor = end;+ });+ if (segments.length > MAX_CAPTION_SEGMENTS) throw new Error(`Too many captions (${segments.length} segments, max ${MAX_CAPTION_SEGMENTS})`);++ // Drop the template's segments.+ const sliceIds = new Set(ids.filter((id) => out[id].class_type === "Video Slice"));+ for (const id of ids) {+ const n = out[id];+ const fromSlice = n.class_type === "GetVideoComponents" && isLinkValue(n.inputs.video) && sliceIds.has(n.inputs.video[0]);+ if (sliceIds.has(id) || n.class_type === "TextOverlay" || fromSlice) delete out[id];+ }+ const style = Object.fromEntries(Object.entries(template.inputs).filter(([k]) => k !== "images" && k !== "text"));+ let next = Math.max(1000, ...ids.map((k) => Number(k.split(":").pop()) || 0)) + 1;+ const parts: [string, number][] = segments.map((s, i) => {+ const slice = String(next++);+ const frames = String(next++);+ out[slice] = { class_type: "Video Slice", inputs: { video: [loader, 0], start_time: s.start, duration: s.duration, strict_duration: false }, _meta: { title: `Segment ${i + 1}` } };+ out[frames] = { class_type: "GetVideoComponents", inputs: { video: [slice, 0] }, _meta: { title: `Segment ${i + 1} frames` } };+ if (s.text === undefined) return [frames, 0];+ const overlay = String(next++);+ out[overlay] = { class_type: "TextOverlay", inputs: { ...style, images: [frames, 0], text: s.text }, _meta: { title: `Caption ${i + 1}` } };+ return [overlay, 0];+ });+ const batchNode = (links: [string, number][]): ComfyNode => ({+ class_type: "BatchImagesNode",+ inputs: Object.fromEntries(links.map((l, i) => [`images.image${i}`, l])),+ _meta: { title: "Segments in order" },+ });+ if (parts.length <= BATCH_MAX) out[batch] = batchNode(parts);+ else {+ const groups: [string, number][] = [];+ for (let i = 0; i < parts.length; i += BATCH_MAX) {+ const id = String(next++);+ out[id] = batchNode(parts.slice(i, i + BATCH_MAX));+ groups.push([id, 0]);+ }+ out[batch] = batchNode(groups);+ }+ return out;+}++/** Languages ComfyUI-QwenASR's subtitle node accepts (besides "auto"), by ISO 639 code. */+const ASR_LANGUAGES: Record<string, string> = {+ zh: "Chinese", en: "English", yue: "Cantonese", ar: "Arabic", de: "German", fr: "French", es: "Spanish", pt: "Portuguese",+ id: "Indonesian", it: "Italian", ko: "Korean", ru: "Russian", th: "Thai", vi: "Vietnamese", ja: "Japanese", tr: "Turkish",+ hi: "Hindi", ms: "Malay", nl: "Dutch", sv: "Swedish", da: "Danish", fi: "Finnish", pl: "Polish", cs: "Czech", fil: "Filipino",+ tl: "Filipino", fa: "Persian", el: "Greek", hu: "Hungarian", mk: "Macedonian", ro: "Romanian",+};++const LANGUAGE_NAMES: Record<string, string> = {+ ...ASR_LANGUAGES, he: "Hebrew", no: "Norwegian", nb: "Norwegian", sw: "Swahili", uk: "Ukrainian", bg: "Bulgarian", hr: "Croatian",+ sk: "Slovak", sl: "Slovenian", sr: "Serbian", ca: "Catalan", bn: "Bengali", ta: "Tamil", te: "Telugu", ur: "Urdu",+};++/** The ISO code in "de", "de-DE", "pt_BR" or "German (de)". */+function languageCode(v: string): string | undefined {+ return (/\(([a-z]{2,3})(?:-[A-Za-z]+)?\)\s*$/i.exec(v)?.[1] ?? /^([a-z]{2,3})(?:[-_][A-Za-z]+)?$/i.exec(v)?.[1])?.toLowerCase();+}++/** "de", "German", "German (de)" or "de-DE" → the ASR combo value ("German"); anything unknown → "auto" (detect). */+export function asrLanguage(value: string | undefined | null): string {+ const v = (value ?? "").trim();+ if (!v || v.toLowerCase() === "auto") return "auto";+ const code = languageCode(v);+ if (code && ASR_LANGUAGES[code]) return ASR_LANGUAGES[code];+ const name = v.replace(/\s*\(.*\)\s*$/, "").toLowerCase();+ return Object.values(ASR_LANGUAGES).find((n) => n.toLowerCase() === name) ?? "auto";+}++/** A language as words for an instruction: "German (de)" → "German", "pt-BR" → "Portuguese", "Klingon" stays. */+export function languageName(value: string | undefined | null): string {+ const v = (value ?? "").trim();+ const code = languageCode(v);+ if (code && LANGUAGE_NAMES[code]) return LANGUAGE_NAMES[code];+ return v.replace(/\s*\(.*\)\s*$/, "") || "English";+}++/** "#E4572E" / "e4572e" / "#fff" → [r, g, b], or null. */+export function parseHex(hex: string): [number, number, number] | null {+ const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());+ if (!m) return null;+ const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];+ return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];+}++const toHex = ([r, g, b]: [number, number, number]) => `#${[r, g, b].map((v) => v.toString(16).padStart(2, "0")).join("").toUpperCase()}`;++/** The palette sentence the Soul HEX graph puts after the prompt ("Color palette: #E4572E, #29335C."). */+export function paletteSentence(palette: string[]): string {+ const hexes = palette.map(parseHex).filter((c): c is [number, number, number] => !!c).map(toHex);+ return hexes.length ? `Color palette: ${hexes.join(", ")}.` : "";+}++/**+ * RGBA pixels of a palette swatch: one vertical band per colour, widths proportional to `weights`+ * (equal by default). ColorTransfer matches the colour statistics of this image.+ */+export function swatchPixels(palette: string[], width = 512, height = 512, weights?: number[]): Uint8Array {+ const colors = palette.map(parseHex).filter((c): c is [number, number, number] => !!c);+ if (!colors.length) throw new Error("No valid hex colours in the palette");+ let w = colors.map((_, i) => (weights ? Math.max(0, Number(weights[i]) || 0) : 1));+ if (!w.some((v) => v > 0)) w = colors.map(() => 1);+ const sum = w.reduce((a, b) => a + b, 0);+ const edges: number[] = [];+ let acc = 0;+ for (const v of w) {+ acc += v / sum;+ edges.push(Math.round(acc * width));+ }+ const px = new Uint8Array(width * height * 4);+ for (let x = 0, band = 0; x < width; x++) {+ while (band < colors.length - 1 && x >= edges[band]) band++;+ const [r, g, b] = colors[band];+ for (let y = 0; y < height; y++) {+ const o = (y * width + x) * 4;+ px[o] = r;+ px[o + 1] = g;+ px[o + 2] = b;+ px[o + 3] = 255;+ }+ }+ return px;+}++/** Bounding box [x, y, w, h] of the pixels whose alpha is above `threshold`, or null for an empty layer. */+export function alphaBBox(rgba: Uint8Array, width: number, height: number, threshold = 8): [number, number, number, number] | null {+ let minX = width;+ let minY = height;+ let maxX = -1;+ let maxY = -1;+ for (let y = 0; y < height; y++) {+ const row = y * width * 4;+ for (let x = 0; x < width; x++) {+ if (rgba[row + x * 4 + 3] > threshold) {+ if (x < minX) minX = x;+ if (x > maxX) maxX = x;+ if (y < minY) minY = y;+ if (y > maxY) maxY = y;+ }+ }+ }+ return maxX < 0 ? null : [minX, minY, maxX - minX + 1, maxY - minY + 1];+}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex e75fc41e..e96aedb6 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -1,22 +1,36 @@import "server-only";import fs from "node:fs";import path from "node:path";+import { Worker } from "node:worker_threads";import { tracksFor, type MotionPaths } from "@/lib/motion-paths";import { nanoid } from "nanoid";import {+ alphaBBox,applyBindings,+ asrLanguage,computeDimensions,computeFrames,+ expandCaptionWorkflow,explainComfyError,injectLoras,+ languageName,+ paletteSentence,+ parseCueLines,randomSeed,+ splitCueWords,+ swatchPixels,type BindingKey,+ type CaptionCue,type ComfyWorkflow,type Manifest,+ type ManifestOutput,type ManifestWorkflow,} from "@/lib/comfy";import { guessKind } from "@/lib/catalog/payload";+import type { GenInput, MediaKind, Operation } from "@/lib/catalog/types";import { getSetting } from "../settings";+import { decodePng, encodePng } from "../png";+import { readRef } from "../storage";import { ProviderError, type ProviderAdapter, type RemoteOutput } from "./types";export const WORKFLOW_DIR = path.join(process.cwd(), "workflows", "comfyui");@@ -57,6 +71,17 @@ async function comfyFetch(p: string, init: RequestInit = {}): Promise<Response>}}+/** GET a ComfyUI JSON endpoint. A non-2xx answer or a body that isn't JSON (a proxy's error page) throws, so the runner retries. */+async function comfyJson<T>(p: string): Promise<T> {+ const res = await comfyFetch(p);+ if (!res.ok) throw new ProviderError(`ComfyUI ${p.split("?")[0]} answered HTTP ${res.status}`, res.status);+ try {+ return (await res.json()) as T;+ } catch {+ throw new ProviderError(`ComfyUI ${p.split("?")[0]} sent something that isn't JSON (a proxy error page?)`);+ }+}+// ---------------------------------------------------------------------------// Live progress over the ComfyUI websocket (one connection per server URL).@@ -69,6 +94,8 @@ interface Progress {declare global {var __fuobeComfyWs: { url: string; ws: WebSocket; clientId: string; progress: Map<string, Progress> } | undefined;+ /** Consecutive polls that found a prompt in neither the queue nor the history. */+ var __fuobeComfyMisses: Map<string, number> | undefined;}function ensureSocket(): { clientId: string; progress: Map<string, Progress> } {@@ -76,7 +103,16 @@ function ensureSocket(): { clientId: string; progress: Map<string, Progress> } {const cur = globalThis.__fuobeComfyWs;if (cur && cur.url === url && cur.ws.readyState <= 1) return cur;const clientId = cur?.clientId ?? `fuobe-${nanoid(8)}`;- const progress = cur?.progress ?? new Map<string, Progress>();+ // Same server: keep the progress of prompts in flight. Another server: those prompt ids mean nothing there.+ const progress = cur && cur.url === url ? cur.progress : new Map<string, Progress>();+ if (cur) {+ // A new URL (or a dead socket): close the old connection so it stops writing into the progress map.+ cur.ws.onmessage = null;+ cur.ws.onerror = null;+ try {+ cur.ws.close();+ } catch {}+ }try {const ws = new WebSocket(`${url.replace(/^http/, "ws")}/ws?clientId=${clientId}`);ws.onmessage = (ev) => {@@ -109,46 +145,136 @@ function ensureSocket(): { clientId: string; progress: Map<string, Progress> } {return { clientId, progress };}+/** Forget a finished prompt's progress and missed-poll count. */+function forget(promptId: string) {+ globalThis.__fuobeComfyWs?.progress.delete(promptId);+ globalThis.__fuobeComfyMisses?.delete(promptId);+}+// ---------------------------------------------------------------------------+// Outputstype HistoryFile = { filename: string; subfolder: string; type: string };type HistoryEntry = {+ prompt?: [number, string, ComfyWorkflow, ...unknown[]];status?: { status_str?: string; completed?: boolean; messages?: [string, Record<string, unknown>][] };outputs?: Record<string, Record<string, unknown>>;};-function collectFiles(entry: HistoryEntry, manifest: ManifestWorkflow | undefined): RemoteOutput[] {+/** A provider output that can also carry text (transcripts) and structured extras (cues, layer z/bbox, stems). */+export type ComfyOutput = RemoteOutput & { text?: string; meta?: Record<string, unknown> };++const isFile = (f: unknown): f is HistoryFile =>+ !!f && typeof f === "object" && typeof (f as HistoryFile).filename === "string" && typeof (f as HistoryFile).type === "string";++const MODEL3D_EXT = /\.(glb|gltf|obj|fbx|stl|usdz|ply)$/i;+const TEXT_EXT = /\.(txt|srt|vtt|json|md|csv)$/i;++function kindFor(filename: string, key: string, declared?: MediaKind): MediaKind {+ if (declared) return declared;+ if (MODEL3D_EXT.test(filename) || key === "3d") return "model3d";+ if (TEXT_EXT.test(filename)) return "text";+ return guessKind(filename, undefined, key === "gifs" || key === "videos" ? "video" : key);+}++const CONTENT_TYPES: Record<string, string> = { glb: "model/gltf-binary", gltf: "model/gltf+json", txt: "text/plain", srt: "application/x-subrip", vtt: "text/vtt", json: "application/json" };++function textsOf(ui: Record<string, unknown> | undefined): string[] {+ return Array.isArray(ui?.text) ? (ui.text as unknown[]).filter((t): t is string => typeof t === "string") : [];+}++const dataUrl = (data: Buffer, contentType: string) => `data:${contentType};base64,${data.toString("base64")}`;++/**+ * Every file the prompt saved, declared output nodes first (in manifest order). Text outputs carry their+ * words (`text`) and parsed caption cues (`meta.cues`); a "language" output (PreviewAny) is folded into the+ * text outputs' meta; stems, roles and layer order (`meta.z`, `meta.name`) come from the manifest.+ */+export function collectOutputs(entry: HistoryEntry, manifest: ManifestWorkflow | undefined, base = "", headers: Record<string, string> = {}): ComfyOutput[] {const outputs = entry.outputs ?? {};- const preferred = new Set(manifest?.outputs.map((o) => o.node) ?? []);- const nodeIds = Object.keys(outputs);- const ordered = [...nodeIds.filter((n) => preferred.has(n)), ...nodeIds.filter((n) => !preferred.has(n))];- const files: RemoteOutput[] = [];+ const declared = manifest?.outputs ?? [];+ const declaredIds = declared.map((o) => o.node);+ const order = [...declaredIds.filter((id) => outputs[id]), ...Object.keys(outputs).filter((id) => !declaredIds.includes(id))];+ const language = declared+ .filter((o) => o.role === "language")+ .map((o) => textsOf(outputs[o.node])[0]?.trim())+ .find(Boolean);+ const files: ComfyOutput[] = [];const pick = (type: string) => {- for (const nodeId of ordered) {- const ui = outputs[nodeId];+ for (const nodeId of order) {+ const spec: ManifestOutput | undefined = declared.find((o) => o.node === nodeId);+ if (spec?.role === "language") continue;+ const ui = outputs[nodeId] ?? {};+ const texts = textsOf(ui);+ const found: { key: string; f: HistoryFile }[] = [];for (const [key, val] of Object.entries(ui)) {if (!Array.isArray(val)) continue;- for (const f of val as HistoryFile[]) {- if (!f || typeof f !== "object" || typeof f.filename !== "string" || f.type !== type) continue;- const qs = new URLSearchParams({ filename: f.filename, subfolder: f.subfolder ?? "", type: f.type });- const declared = manifest?.outputs.find((o) => o.node === nodeId)?.kind;- files.push({- url: `${baseUrl()}/view?${qs}`,- kind: declared ?? guessKind(f.filename, undefined, key === "gifs" || key === "videos" ? "video" : key),- headers: authHeaders(),- });- }+ for (const f of val) if (isFile(f) && f.type === type) found.push({ key, f });+ }+ // A text output with no file (PreviewAny): keep the words.+ if (!found.length && type === "output" && spec?.kind === "text" && texts.length) {+ const text = texts.join("\n");+ files.push(textOutput({ url: dataUrl(Buffer.from(text), "text/plain"), kind: "text", contentType: "text/plain" }, text, spec, language));+ continue;}+ found.forEach(({ key, f }, i) => {+ const kind = kindFor(f.filename, key, spec?.kind);+ const qs = new URLSearchParams({ filename: f.filename, subfolder: f.subfolder ?? "", type: f.type });+ const ext = f.filename.split(".").pop()?.toLowerCase() ?? "";+ const o: ComfyOutput = { url: `${base}/view?${qs}`, kind, headers, ...(CONTENT_TYPES[ext] && kind !== "image" ? { contentType: CONTENT_TYPES[ext] } : {}) };+ if (kind === "text") {+ files.push(textOutput(o, texts[i] ?? (found.length === 1 ? texts.join("\n") : undefined), spec, language));+ return;+ }+ const meta: Record<string, unknown> = {};+ if (spec?.stem) meta.stem = spec.stem;+ if (spec?.role) meta.role = spec.role;+ // Qwen-Image-Layered saves its layers back to front.+ if (spec?.role === "layers") Object.assign(meta, { z: i, name: i === 0 ? "Background" : `Layer ${i}` });+ if (Object.keys(meta).length) o.meta = meta;+ files.push(o);+ });}};pick("output");if (!files.length) pick("temp");- // If the manifest declares output nodes, drop intermediate saves from other nodes when we have declared ones.return files;}-// Reachability is probed in the background so routing (which is synchronous) can fall back-// to demo output when no ComfyUI server is up.+function textOutput(o: ComfyOutput, text: string | undefined, spec: ManifestOutput | undefined, language: string | undefined): ComfyOutput {+ const meta: Record<string, unknown> = {};+ if (spec?.role) meta.role = spec.role;+ if (text !== undefined) {+ const cues = parseCueLines(text);+ if (cues.length) meta.cues = cues;+ }+ if (language) meta.language = language;+ return { ...o, kind: "text", ...(text !== undefined ? { text } : {}), ...(Object.keys(meta).length ? { meta } : {}) };+}++/** Layers: download each RGBA layer once, add its bounding box (from alpha) and hand the bytes on as a data URL. */+async function withLayerBoxes(outputs: ComfyOutput[]): Promise<ComfyOutput[]> {+ return Promise.all(+ outputs.map(async (o) => {+ if (o.kind !== "image" || typeof o.meta?.z !== "number" || o.url.startsWith("data:")) return o;+ try {+ const res = await fetch(o.url, { headers: o.headers });+ if (!res.ok) return o;+ const data = Buffer.from(await res.arrayBuffer());+ const png = decodePng(data);+ const bbox = alphaBBox(png.data, png.width, png.height);+ return { ...o, url: dataUrl(data, "image/png"), contentType: "image/png", headers: undefined, meta: { ...o.meta, bbox: bbox ?? [0, 0, 0, 0], width: png.width, height: png.height } };+ } catch {+ return o; // keep the layer without a box rather than failing the job+ }+ }),+ );+}++// ---------------------------------------------------------------------------+// Reachability. Routing (chooseRoute) is synchronous, so the first check for a server URL is a blocking probe+// (a worker thread does the fetch); after that the cached result is refreshed in the background every 10 s.+declare global {var __fuobeComfyReach: { ok: boolean; at: number; url: string } | undefined;}@@ -165,13 +291,283 @@ export async function probeComfy(force = false): Promise<boolean> {return ok;}+const PROBE_WORKER = `const { workerData } = require("node:worker_threads");+const flag = new Int32Array(workerData.sab);+fetch(workerData.url, { headers: workerData.headers, signal: AbortSignal.timeout(workerData.timeout) })+ .then((r) => Atomics.store(flag, 0, r.ok ? 1 : 2), () => Atomics.store(flag, 0, 2))+ .finally(() => Atomics.notify(flag, 0));`;++/** Blocking reachability check (a few ms for a refused port, at most `timeoutMs` for a host that doesn't answer). */+export function probeComfySync(timeoutMs = 1500): boolean {+ const url = baseUrl();+ let ok = false;+ try {+ const sab = new SharedArrayBuffer(4);+ const flag = new Int32Array(sab);+ const worker = new Worker(PROBE_WORKER, { eval: true, workerData: { sab, url: `${url}/system_stats`, headers: authHeaders(), timeout: timeoutMs } });+ Atomics.wait(flag, 0, 0, timeoutMs + 1000);+ ok = Atomics.load(flag, 0) === 1;+ void worker.terminate();+ } catch {}+ globalThis.__fuobeComfyReach = { ok, at: Date.now(), url };+ return ok;+}++// ---------------------------------------------------------------------------+// Building the prompt++/** Loader classes whose input is an uploaded file, and which input holds it. */+const MEDIA_LOADERS: Record<string, string> = { LoadImage: "image", LoadImageMask: "image", LoadVideo: "file", VHS_LoadVideo: "video", LoadAudio: "audio", VHS_LoadAudioUpload: "audio" };++const MEDIA_HINT: Record<string, string> = {+ image: "Add an image",+ image2: "Add a second image",+ image3: "Add a third image",+ image4: "Add a fourth image",+ endImage: "Add an end frame",+ mask: "Paint the area to change",+ video: "Add a video",+ video2: "Add a second clip",+ video3: "Add a third clip",+ video4: "Add a fourth clip",+ audio: "Add an audio track",+ audio2: "Add the second audio track",+ paletteImage: "Pick a palette first",+};++/** Binding keys that point at an upload (LoadImage / LoadVideo / LoadAudio…). */+export function mediaKeys(manifest: ManifestWorkflow, workflow: ComfyWorkflow): string[] {+ return Object.entries(manifest.bindings)+ .filter(([, targets]) => targets?.some((t) => MEDIA_LOADERS[workflow[t.node]?.class_type ?? ""] === t.input))+ .map(([k]) => k);+}++const isMediaRef = (v: unknown): v is string => typeof v === "string" && (v.startsWith("/api/files/") || v.startsWith("data:"));++export interface PrepareContext {+ generationId: string;+ op: Operation;+ /** Upload a file to ComfyUI's input folder; returns the name LoadImage/LoadAudio/LoadVideo take. */+ upload: (data: Buffer, contentType: string, name: string) => Promise<string>;+}++export interface PreparedPrompt {+ manifest: ManifestWorkflow;+ workflow: ComfyWorkflow;+ meta: Record<string, unknown>;+}++/** Caption cues for the burn-in: params.extra.cues, or the prompt's "start-end: text" / SRT lines. */+function captionCues(input: GenInput, extra: Record<string, unknown>): CaptionCue[] {+ const given = Array.isArray(extra.cues)+ ? (extra.cues as Partial<CaptionCue>[]).map((c) => ({ start: Number(c.start), end: Number(c.end), text: String(c.text ?? "") })).filter((c) => Number.isFinite(c.start) && c.end > c.start && c.text.trim())+ : parseCueLines(input.prompt);+ return splitCueWords(given, Number(extra.wordsPerCaption ?? 0));+}++/**+ * Turn a canonical request into the exact ComfyUI prompt: picks the workflow variant, maps Fuobe's inputs+ * onto the workflow's bindings (sizes, frames, trim times, languages, palettes, layers…), uploads files the+ * provider makes itself (palette swatches, media refs in params.extra) and rewrites graphs that depend on the+ * request (caption cues). Pure apart from `ctx.upload` and reading the workflow files.+ */+export async function prepareWorkflow(endpointTemplate: string, input: GenInput, ctx: PrepareContext): Promise<PreparedPrompt> {+ // "video-concat-{n}": one workflow per clip count.+ const clips = input.videos ?? [];+ if (endpointTemplate.includes("{n}") && clips.length > 4) throw new ProviderError("ComfyUI joins up to 4 clips at a time");+ let endpoint = endpointTemplate.replace("{n}", String(Math.max(2, Math.min(4, clips.length))));+ const extra: Record<string, unknown> = { ...(input.extra ?? {}) };++ // Media refs in params.extra (e.g. a background stem for "audio2") are uploaded like regular inputs.+ for (const [k, v] of Object.entries(extra)) {+ if (!isMediaRef(v)) continue;+ const f = await readRef(v);+ extra[k] = await ctx.upload(f.data, f.contentType, f.name);+ }+ // Soundtrack without a background stem: the single-track graph.+ if (ctx.op === "mux" && !extra.audio2 && loadManifest().workflows.some((w) => w.id === `${endpoint}-replace`)) endpoint = `${endpoint}-replace`;++ const { manifest, workflow } = getWorkflow(endpoint);+ const d = manifest.defaults;+ const b = manifest.bindings;+ const images = input.images ?? [];+ const values: Partial<Record<BindingKey, unknown>> = {+ prompt: input.prompt,+ negativePrompt: input.negativePrompt,+ image: images[0],+ image2: images[1],+ image3: images[2],+ image4: images[3],+ endImage: input.endImage,+ mask: input.mask,+ video: input.video ?? clips[0],+ video2: clips[1],+ video3: clips[2],+ video4: clips[3],+ audio: input.audio,+ seed: input.seed !== undefined && input.seed >= 0 ? input.seed : randomSeed(),+ };+ // Voice workflows: "audio" is the voice to speak with (TTS), speaker A (dialogue) or the speech to convert+ // (voice change, whose target voice is "audio2").+ if (ctx.op === "tts") values.audio = input.voiceAudio ?? input.audio;+ if (ctx.op === "dialogue") {+ values.audio = input.voiceAudio;+ values.audio2 = input.voiceAudio2;+ values.prompt = (input.dialogue ?? []).filter((l) => l.text.trim()).map((l) => `SPEAKER ${l.voice === "B" ? "B" : "A"}: ${l.text.trim()}`).join("\n");+ }+ if (ctx.op === "voice-change") values.audio2 = input.voiceAudio;+ // Speech workflows read the soundtrack with LoadAudio, which also takes a video upload.+ if ((ctx.op === "transcribe" || ctx.op === "separate-audio" || ctx.op === "translate") && b.audio && !b.video) values.audio = input.audio ?? input.video ?? clips[0];+ if (b.language && input.targetLanguage) values.language = input.targetLanguage;+ if (b.sourceLanguage && input.sourceLanguage) values.sourceLanguage = asrLanguage(input.sourceLanguage);+ if (b.instruction) {+ const template = String(extra.instruction ?? d.instruction ?? "");+ delete extra.instruction;+ if (template.includes("{language}") && !input.targetLanguage) throw new ProviderError("Pick a language to translate into");+ values.instruction = template.replaceAll("{language}", languageName(input.targetLanguage));+ }++ // Frame rate (params.fps, or a model's fps control), trim window and frame counts.+ const fpsIn = input.fps ?? (typeof extra.fps === "number" && extra.fps > 0 ? extra.fps : undefined);+ if (b.fps && fpsIn) values.fps = fpsIn;+ const fps = Number(values.fps ?? d.fps ?? 16);+ const start = Math.max(0, input.startTime ?? 0);+ const window = input.endTime !== undefined ? Math.max(0, input.endTime - start) : input.duration;+ if (b.startTime && input.startTime !== undefined) values.startTime = start;+ if (b.startFrame && input.startTime !== undefined) values.startFrame = Math.round(start * fps);+ if (b.duration) {+ if (input.endTime !== undefined) values.duration = window;+ else if (input.duration) values.duration = input.duration;+ else if (ctx.op === "trim") values.duration = 0; // from the start time to the end+ }+ if (b.width || b.height) {+ const multiple = Number(manifest.limits?.dimensionMultiple ?? 16);+ // With motion paths the frame keeps the start image's shape, so the paths need no cropping.+ const srcAspect = (extra.motionPaths as MotionPaths | undefined)?.aspect;+ const dims = computeDimensions(+ srcAspect ? `${srcAspect[0]}:${srcAspect[1]}` : input.aspectRatio === "auto" ? undefined : input.aspectRatio,+ input.resolution,+ { width: Number(d.width ?? 1024), height: Number(d.height ?? 1024) },+ multiple,+ );+ // Respect the workflow's size limits while keeping the aspect ratio.+ const maxW = Number(manifest.limits?.maxWidth ?? Infinity);+ const maxH = Number(manifest.limits?.maxHeight ?? Infinity);+ const k = Math.min(1, maxW / dims.width, maxH / dims.height);+ values.width = Math.max(multiple, Math.floor((dims.width * k) / multiple) * multiple);+ values.height = Math.max(multiple, Math.floor((dims.height * k) / multiple) * multiple);+ }+ if (b.frames && window) values.frames = computeFrames(window, fps, Number(d.frameStep ?? 4), manifest.limits?.maxFrames);+ // Drawn motion paths (normalised to the start frame) → one pixel point per output frame (Wan-Move).+ const paths = extra.motionPaths as MotionPaths | undefined;+ delete extra.motionPaths;+ if (b.tracks && paths?.paths.length) {+ const frames = Number(values.frames ?? d.frames ?? 81);+ values.tracks = JSON.stringify(tracksFor(paths, Number(values.width ?? d.width ?? 832), Number(values.height ?? d.height ?? 480), frames));+ }+ if (b.tags && !b.prompt) values.tags = input.prompt;+ if (b.description && !extra.description) values.description = input.prompt;+ if (b.numLayers && input.numLayers) values.numLayers = Math.max(1, Math.min(Number(manifest.limits?.maxLayers ?? 10), Math.round(input.numLayers)));++ // Soul HEX: the hex list as words, plus a swatch the ColorTransfer lock matches.+ const palette = (input.palette ?? []).filter((p) => typeof p === "string" && p.trim());+ if (palette.length) {+ const sentence = paletteSentence(palette);+ if (!sentence) throw new ProviderError("The palette has no valid hex colours (use #RRGGBB)");+ if (b.paletteText) values.paletteText = sentence;+ const swatchSlot = b.paletteImage ? "paletteImage" : ctx.op === "color-match" ? (b.image2 && !values.image2 ? "image2" : b.video && b.image && !values.image ? "image" : undefined) : undefined;+ if (swatchSlot) {+ const weights = Array.isArray(extra.paletteWeights) ? (extra.paletteWeights as number[]) : undefined;+ const px = Buffer.from(swatchPixels(palette, 512, 512, weights));+ values[swatchSlot] = await ctx.upload(encodePng({ width: 512, height: 512, data: px }), "image/png", "palette_swatch.png");+ }+ } else if (b.paletteImage && images[0]) values.paletteImage = images[0]; // a swatch the user made+ delete extra.paletteWeights;++ // Trigger words a LoRA needs at the start of the prompt (try-on: "TRYON").+ const prefix = typeof d.promptPrefix === "string" ? d.promptPrefix.trim() : "";+ if (prefix && typeof values.prompt === "string" && values.prompt.trim() && !values.prompt.trim().startsWith(prefix)) values.prompt = `${prefix} ${values.prompt.trim()}`;+ // Framing text defaults with placeholders ("A {columns}x{rows} grid contact sheet of {count} film stills…").+ const columns = Number(extra.columns ?? d.columns ?? 0);+ const rows = Number(extra.rows ?? d.rows ?? 0);+ for (const key of Object.keys(b)) {+ const def = d[key];+ if (typeof def !== "string" || !def.includes("{") || values[key] !== undefined || extra[key] !== undefined) continue;+ values[key] = def.replaceAll("{columns}", String(columns)).replaceAll("{rows}", String(rows)).replaceAll("{count}", String(columns * rows)).replaceAll("{language}", languageName(input.targetLanguage));+ }++ if (b.filenamePrefix) values.filenamePrefix = `fuobe/${ctx.generationId}`;+ const cues = manifest.expand === "captions" ? captionCues(input, extra) : [];+ delete extra.cues;+ delete extra.wordsPerCaption;+ for (const [k, v] of Object.entries(extra)) values[k as BindingKey] = v;++ // Reference slots the user left empty reuse the previous image (style references want all four; a dress+ // is both the top and the bottom of a try-on).+ for (const [k, prev] of [["image2", "image"], ["image3", "image2"], ["image4", "image3"]] as const) {+ if (b[k] && values[k] === undefined && values[prev] !== undefined) values[k] = values[prev];+ }+ for (const k of mediaKeys(manifest, workflow)) {+ if (values[k] === undefined || values[k] === "") throw new ProviderError(`${MEDIA_HINT[k] ?? `Add the ${k} input`} — ${manifest.title.split(":")[0]} needs it`);+ }++ const bound = applyBindings(workflow, b, values);+ if (bound.missing.length) throw new ProviderError(`Workflow ${manifest.id} bindings point at missing nodes: ${bound.missing.join(", ")}`);+ let wf = bound.workflow;+ if (manifest.expand === "captions") {+ if (!cues.length) throw new ProviderError("No timed captions to burn in. Transcribe the clip first, or write lines like “0.00-2.40: Hello there”");+ wf = expandCaptionWorkflow(wf, cues);+ }+ if (input.loras?.length) wf = injectLoras(wf, input.loras);+ const metaBatch = Object.values(wf).some((n) => n.class_type === "VHS_BatchManager");+ return {+ manifest,+ workflow: wf,+ meta: { workflowId: manifest.id, nodeCount: Object.keys(wf).length, prefix: `fuobe/${ctx.generationId}`, ...(metaBatch ? { metaBatch: true } : {}) },+ };+}++/** Friendlier words for errors that a workflow's nodes report in their own terms. */+function explainExecutionError(err: { exception_message?: string; node_type?: string } | undefined, manifest?: ManifestWorkflow): string {+ if (!err) return "Execution error";+ const msg = (err.exception_message ?? "").trim();+ if (manifest?.expand === "captions" && /division by zero|failed to slice video|no frames exist/i.test(msg)) {+ return "A caption starts after the end of the video — check the cue times";+ }+ if (/no audio stream/i.test(msg)) return "That file has no sound to work with";+ return `${err.node_type}: ${msg}`;+}++const promptHasPrefix = (prompt: unknown, prefix: string) =>+ !!prompt && typeof prompt === "object" && Object.values(prompt as ComfyWorkflow).some((n) => n?.inputs?.filename_prefix === prefix);++/**+ * VHS meta-batching re-queues the prompt (new prompt ids) until every frame is done; only the last pass+ * saves the video. Follow the passes by their shared filename prefix.+ */+async function followMetaBatch(prefix: string, manifest: ManifestWorkflow | undefined): Promise<ComfyOutput[] | "running" | null> {+ const queue = await comfyJson<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue");+ if ([...(queue.queue_running ?? []), ...(queue.queue_pending ?? [])].some((q) => promptHasPrefix(q[2], prefix))) return "running";+ const hist = await comfyJson<Record<string, HistoryEntry>>("/history?max_items=64");+ const passes = Object.values(hist)+ .filter((e) => promptHasPrefix(e.prompt?.[2], prefix))+ .sort((a, c) => Number(c.prompt?.[0] ?? 0) - Number(a.prompt?.[0] ?? 0));+ for (const e of passes) {+ const files = collectOutputs(e, manifest, baseUrl(), authHeaders());+ if (files.length) return files;+ }+ return null;+}+export const comfyProvider: ProviderAdapter = {id: "comfyui",label: "ComfyUI",isConfigured: () => {const cur = globalThis.__fuobeComfyReach;- if (!cur || cur.url !== baseUrl() || Date.now() - cur.at > 10_000) void probeComfy();- return !!cur && cur.url === baseUrl() && cur.ok;+ // First check for this server: wait for the answer, so a request right after start isn't sent to demo.+ if (!cur || cur.url !== baseUrl()) return probeComfySync();+ if (Date.now() - cur.at > 10_000) void probeComfy();+ return cur.ok;},async prepareFile(data, contentType, name) {@@ -187,79 +583,11 @@ export const comfyProvider: ProviderAdapter = {},async submit({ route, input, generationId }) {- // "video-concat-{n}": one workflow per clip count.- const clips = input.videos ?? [];- const endpoint = route.endpoint.replace("{n}", String(Math.max(2, Math.min(4, clips.length))));- if (route.endpoint.includes("{n}") && clips.length > 4) throw new ProviderError("ComfyUI joins up to 4 clips at a time");- const { manifest, workflow } = getWorkflow(endpoint);- const d = manifest.defaults;- const images = input.images ?? [];- const values: Partial<Record<BindingKey, unknown>> = {- prompt: input.prompt,- negativePrompt: input.negativePrompt,- image: images[0],- image2: images[1],- image3: images[2],- image4: images[3],- endImage: input.endImage,- mask: input.mask,- video: input.video ?? clips[0],- video2: clips[1],- video3: clips[2],- video4: clips[3],- audio: input.audio,- seed: input.seed !== undefined && input.seed >= 0 ? input.seed : randomSeed(),- };- // Voice workflows: "audio" is the voice to speak with (TTS), speaker A (dialogue) or the speech to convert- // (voice change, whose target voice is "audio2").- if (route.op === "tts") values.audio = input.voiceAudio ?? input.audio;- if (route.op === "dialogue") {- values.audio = input.voiceAudio;- values.audio2 = input.voiceAudio2;- values.prompt = (input.dialogue ?? []).filter((l) => l.text.trim()).map((l) => `SPEAKER ${l.voice === "B" ? "B" : "A"}: ${l.text.trim()}`).join("\n");- }- if (route.op === "voice-change") values.audio2 = input.voiceAudio;- if (manifest.bindings.language && input.targetLanguage) values.language = input.targetLanguage;- if (manifest.bindings.width || manifest.bindings.height) {- const multiple = Number(manifest.limits?.dimensionMultiple ?? 16);- // With motion paths the frame keeps the start image's shape, so the paths need no cropping.- const srcAspect = (input.extra?.motionPaths as MotionPaths | undefined)?.aspect;- const dims = computeDimensions(- srcAspect ? `${srcAspect[0]}:${srcAspect[1]}` : input.aspectRatio === "auto" ? undefined : input.aspectRatio,- input.resolution,- { width: Number(d.width ?? 1024), height: Number(d.height ?? 1024) },- multiple,- );- // Respect the workflow's size limits while keeping the aspect ratio.- const maxW = Number(manifest.limits?.maxWidth ?? Infinity);- const maxH = Number(manifest.limits?.maxHeight ?? Infinity);- const k = Math.min(1, maxW / dims.width, maxH / dims.height);- values.width = Math.max(multiple, Math.floor((dims.width * k) / multiple) * multiple);- values.height = Math.max(multiple, Math.floor((dims.height * k) / multiple) * multiple);- }- if (manifest.bindings.frames && input.duration) {- const fps = Number(d.fps ?? 16);- values.frames = computeFrames(input.duration, fps, Number(d.frameStep ?? 4), manifest.limits?.maxFrames);- }- // Drawn motion paths (normalised to the start frame) → one pixel point per output frame (Wan-Move).- const extra = { ...(input.extra ?? {}) };- const paths = extra.motionPaths as MotionPaths | undefined;- delete extra.motionPaths;- if (manifest.bindings.tracks && paths?.paths.length) {- const frames = Number(values.frames ?? d.frames ?? 81);- values.tracks = JSON.stringify(tracksFor(paths, Number(values.width ?? d.width ?? 832), Number(values.height ?? d.height ?? 480), frames));- }- if (manifest.bindings.duration && input.duration) values.duration = input.duration;- if (manifest.bindings.tags && !manifest.bindings.prompt) values.tags = input.prompt;- if (manifest.bindings.filenamePrefix) values.filenamePrefix = `fuobe/${generationId}`;- for (const [k, v] of Object.entries(extra)) values[k as BindingKey] = v;-- const bound = applyBindings(workflow, manifest.bindings, values);- const missing = bound.missing;- let wf = bound.workflow;- if (missing.length) throw new ProviderError(`Workflow ${manifest.id} bindings point at missing nodes: ${missing.join(", ")}`);- if (input.loras?.length) wf = injectLoras(wf, input.loras);-+ const { manifest, workflow: wf, meta } = await prepareWorkflow(route.endpoint, input, {+ generationId,+ op: route.op,+ upload: (data, contentType, name) => comfyProvider.prepareFile(data, contentType, name),+ });const { clientId } = ensureSocket();const res = await comfyFetch("/prompt", {method: "POST",@@ -271,39 +599,53 @@ export const comfyProvider: ProviderAdapter = {const detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...(input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: l.url }))] }) : body.error?.message;throw new ProviderError(detail ?? `ComfyUI /prompt failed (${res.status})`, res.status);}- return { externalId: body.prompt_id, meta: { workflowId: manifest.id, nodeCount: Object.keys(wf).length }, payload: wf };+ return { externalId: body.prompt_id, meta, payload: wf };},async poll({ externalId, meta }) {- const histRes = await comfyFetch(`/history/${externalId}`);- if (!histRes.ok) throw new ProviderError(`ComfyUI history ${histRes.status}`);- const hist = (await histRes.json()) as Record<string, HistoryEntry>;- const entry = hist[externalId];- if (entry?.status?.completed || entry?.status?.status_str === "success") {- let manifest: ManifestWorkflow | undefined;- try {- manifest = getWorkflow(String(meta.workflowId)).manifest;- } catch {}- const outputs = collectFiles(entry, manifest);- if (!outputs.length) return { state: "failed", error: "Workflow finished without saving any output" };- return { state: "succeeded", outputs };- }- if (entry?.status?.status_str === "error") {- const err = entry.status.messages?.find(([t]) => t === "execution_error")?.[1] as- | { exception_message?: string; node_type?: string }- | undefined;- return { state: "failed", error: err ? `${err.node_type}: ${err.exception_message}` : "Execution error" };- }- // Still queued or running.+ let manifest: ManifestWorkflow | undefined;+ try {+ manifest = getWorkflow(String(meta.workflowId)).manifest;+ } catch {}+ const finished = async (entry: HistoryEntry) => {+ if (entry.status?.status_str === "error") {+ forget(externalId);+ const err = entry.status.messages?.find(([t]) => t === "execution_error")?.[1] as { exception_message?: string; node_type?: string } | undefined;+ return { state: "failed" as const, error: explainExecutionError(err, manifest) };+ }+ let outputs = collectOutputs(entry, manifest, baseUrl(), authHeaders());+ if (!outputs.length && meta.metaBatch && typeof meta.prefix === "string") {+ const next = await followMetaBatch(meta.prefix, manifest);+ if (next === "running") return { state: "running" as const, message: "Rendering the next batch of frames" };+ outputs = next ?? [];+ }+ forget(externalId);+ if (!outputs.length) return { state: "failed" as const, error: "Workflow finished without saving any output" };+ return { state: "succeeded" as const, outputs: await withLayerBoxes(outputs) };+ };+ const isDone = (e: HistoryEntry | undefined): e is HistoryEntry => !!e && (!!e.status?.completed || e.status?.status_str === "success" || e.status?.status_str === "error");++ const entry = (await comfyJson<Record<string, HistoryEntry>>(`/history/${externalId}`))[externalId];+ if (isDone(entry)) return finished(entry);++ // Still queued or running?const { progress } = ensureSocket();const p = progress.get(externalId);- const queueRes = await comfyFetch("/queue");- const queue = (await queueRes.json().catch(() => ({}))) as { queue_running?: unknown[][]; queue_pending?: unknown[][] };+ const queue = await comfyJson<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue");const running = queue.queue_running?.some((q) => q[1] === externalId);const pendingIdx = queue.queue_pending?.findIndex((q) => q[1] === externalId) ?? -1;if (!running && pendingIdx < 0 && !entry) {+ // It may have finished between the two requests (ComfyUI moves it from the queue to the history at once).+ const again = (await comfyJson<Record<string, HistoryEntry>>(`/history/${externalId}`))[externalId];+ if (isDone(again)) return finished(again);+ const misses = globalThis.__fuobeComfyMisses ?? (globalThis.__fuobeComfyMisses = new Map());+ const n = (misses.get(externalId) ?? 0) + 1;+ misses.set(externalId, n);+ if (n < 3) return { state: "running", message: "Checking on ComfyUI" };+ forget(externalId);return { state: "failed", error: "Prompt disappeared from the ComfyUI queue (server restarted or job was cleared)" };}+ globalThis.__fuobeComfyMisses?.delete(externalId);if (pendingIdx >= 0) return { state: "queued", message: `In ComfyUI queue · position ${pendingIdx + 1}` };const total = Number(meta.nodeCount ?? 0);const stepFrac = p && p.max ? p.value / p.max : 0;@@ -316,6 +658,7 @@ export const comfyProvider: ProviderAdapter = {},async cancel({ externalId }) {+ forget(externalId);await comfyFetch("/queue", {method: "POST",headers: { "Content-Type": "application/json" },diff --git a/tests/comfy-provider.test.ts b/tests/comfy-provider.test.tsnew file mode 100644index 00000000..27a9ad86--- /dev/null+++ b/tests/comfy-provider.test.ts@@ -0,0 +1,450 @@+import fs from "node:fs";+import { Worker } from "node:worker_threads";+import os from "node:os";+import path from "node:path";+import zlib from "node:zlib";+import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";+import type { ManifestWorkflow } from "@/lib/comfy";+import type { ModelDef, ModelRoute } from "@/lib/catalog/types";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-provider-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://comfy.test:8188";++const { setSetting } = await import("@/server/settings");+const { comfyProvider, collectOutputs, getWorkflow, loadManifest, prepareWorkflow } = await import("@/server/providers/comfyui");+const { MODELS } = await import("@/lib/catalog");+const { computeFrames } = await import("@/lib/comfy");++afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++// ---------------------------------------------------------------------------+// fetch + WebSocket stubs++type Handler = (url: string, init?: RequestInit) => Response | Promise<Response>;+const realFetch = globalThis.fetch;+const realWs = globalThis.WebSocket;+let handler: Handler = () => new Response("not stubbed", { status: 599 });+const calls: string[] = [];++class FakeSocket {+ static all: FakeSocket[] = [];+ readyState = 1;+ closed = false;+ onmessage: ((ev: { data: unknown }) => void) | null = null;+ onerror: (() => void) | null = null;+ constructor(public url: string) {+ FakeSocket.all.push(this);+ }+ close() {+ this.closed = true;+ this.readyState = 3;+ }+ emit(msg: unknown) {+ this.onmessage?.({ data: JSON.stringify(msg) });+ }+}++beforeEach(() => {+ calls.length = 0;+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ calls.push(url);+ return handler(url, init);+ }) as typeof fetch;+ globalThis.WebSocket = FakeSocket as unknown as typeof WebSocket;+ setSetting("comfyUrl", "http://comfy.test:8188");+});+afterEach(() => {+ globalThis.fetch = realFetch;+ globalThis.WebSocket = realWs;+});++const json = (v: unknown, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } });+const route: ModelRoute = { op: "edit", provider: "comfyui", endpoint: "selftest-image" };+const model = { id: "m", routes: [route] } as unknown as ModelDef;+const pollCtx = (externalId: string, meta: Record<string, unknown> = { workflowId: "selftest-image", nodeCount: 3 }) => ({ externalId, meta, route, model, createdAt: Date.now() });+const done = (outputs: Record<string, unknown>) => ({ status: { status_str: "success", completed: true }, outputs });++describe("ComfyUI poll (S5)", () => {+ it("retries instead of failing when /queue answers with a proxy error page", async () => {+ handler = (url) => (url.includes("/history/") ? json({}) : new Response("<html>502 Bad Gateway</html>", { status: 502 }));+ await expect(comfyProvider.poll(pollCtx("p-502"))).rejects.toThrow(/HTTP 502/);+ handler = (url) => (url.includes("/history/") ? json({}) : new Response("<html>oops</html>", { status: 200 }));+ await expect(comfyProvider.poll(pollCtx("p-html"))).rejects.toThrow(/isn't JSON/);+ });++ it("collects the outputs of a prompt that finished between the history and queue requests", async () => {+ let historyCalls = 0;+ handler = (url) => {+ if (url.includes("/history/p-race")) {+ historyCalls += 1;+ return json(historyCalls === 1 ? {} : { "p-race": done({ "3": { images: [{ filename: "fuobe_00001_.png", subfolder: "fuobe", type: "output" }] } }) });+ }+ return json({ queue_running: [], queue_pending: [] });+ };+ const res = await comfyProvider.poll(pollCtx("p-race"));+ expect(res.state).toBe("succeeded");+ expect(historyCalls).toBe(2);+ });++ it("fails a prompt only after it is missing from the queue and the history three polls in a row", async () => {+ handler = (url) => (url.includes("/history/") ? json({}) : json({ queue_running: [], queue_pending: [] }));+ expect((await comfyProvider.poll(pollCtx("p-gone"))).state).toBe("running");+ expect((await comfyProvider.poll(pollCtx("p-gone"))).state).toBe("running");+ const third = await comfyProvider.poll(pollCtx("p-gone"));+ expect(third).toMatchObject({ state: "failed", error: expect.stringMatching(/disappeared/) });+ });++ it("reports the queue position while pending", async () => {+ handler = (url) => (url.includes("/history/") ? json({}) : json({ queue_running: [[0, "other"]], queue_pending: [[1, "x"], [2, "p-wait"]] }));+ expect(await comfyProvider.poll(pollCtx("p-wait"))).toMatchObject({ state: "queued", message: "In ComfyUI queue · position 2" });+ });+});++describe("ComfyUI websocket (S15)", () => {+ it("closes the old socket when the server URL changes and forgets finished prompts' progress", async () => {+ handler = (url) => (url.includes("/history/") ? json({}) : json({ queue_running: [[0, "p-run"]], queue_pending: [] }));+ await comfyProvider.poll(pollCtx("p-run"));+ const first = FakeSocket.all.at(-1)!;+ expect(first.url).toBe("ws://comfy.test:8188/ws?clientId=" + globalThis.__fuobeComfyWs!.clientId);+ first.emit({ type: "progress", data: { prompt_id: "p-run", value: 2, max: 8, node: "3" } });+ expect(globalThis.__fuobeComfyWs!.progress.get("p-run")?.value).toBe(2);+ const running = await comfyProvider.poll(pollCtx("p-run"));+ expect(running).toMatchObject({ state: "running", message: "Sampling 2/8" });++ // The prompt finishes: its progress entry goes away.+ handler = (url) => (url.includes("/history/") ? json({ "p-run": done({ "3": { images: [{ filename: "a.png", subfolder: "", type: "output" }] } }) }) : json({}));+ expect((await comfyProvider.poll(pollCtx("p-run"))).state).toBe("succeeded");+ expect(globalThis.__fuobeComfyWs!.progress.has("p-run")).toBe(false);++ // Another server: the first socket is closed and detached, a new one is opened.+ setSetting("comfyUrl", "http://gpu.test:8188");+ handler = (url) => (url.includes("/history/") ? json({}) : json({ queue_running: [[0, "p-gpu"]], queue_pending: [] }));+ await comfyProvider.poll(pollCtx("p-gpu"));+ const second = FakeSocket.all.at(-1)!;+ expect(second).not.toBe(first);+ expect(second.url.startsWith("ws://gpu.test:8188/ws")).toBe(true);+ expect(first.closed).toBe(true);+ expect(first.onmessage).toBeNull();+ });+});++describe("ComfyUI reachability (S16)", () => {+ it("answers the first routing question for a server from a real probe, not a pending one", async () => {+ // A stand-in ComfyUI on its own thread (a real one is another process): the probe blocks this thread.+ const server = new Worker(+ `const http = require("node:http"); const { parentPort } = require("node:worker_threads");+ const s = http.createServer((req, res) => { res.writeHead(req.url === "/system_stats" ? 200 : 404); res.end("{}"); });+ s.listen(0, "127.0.0.1", () => parentPort.postMessage(s.address().port));`,+ { eval: true },+ );+ const port = await new Promise<number>((r) => server.once("message", r));+ try {+ setSetting("comfyUrl", `http://127.0.0.1:${port}`);+ globalThis.__fuobeComfyReach = undefined;+ expect(comfyProvider.isConfigured()).toBe(true); // was false until a background probe finished+ setSetting("comfyUrl", "http://127.0.0.1:9");+ const t0 = Date.now();+ expect(comfyProvider.isConfigured()).toBe(false); // nothing listens: demo mode can take over at once+ expect(Date.now() - t0).toBeLessThan(1500);+ } finally {+ await server.terminate();+ }+ });+});++// ---------------------------------------------------------------------------+// Output mapping++function rgbaPng(w: number, h: number, alpha: (x: number, y: number) => number): Buffer {+ const crcTable = Array.from({ length: 256 }, (_, n) => {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ return c >>> 0;+ });+ const crc = (b: Buffer) => {+ let c = 0xffffffff;+ for (const x of b) c = crcTable[(c ^ x) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+ };+ const chunk = (type: string, data: Buffer) => {+ const len = Buffer.alloc(4);+ len.writeUInt32BE(data.length);+ const td = Buffer.concat([Buffer.from(type), data]);+ const c = Buffer.alloc(4);+ c.writeUInt32BE(crc(td));+ return Buffer.concat([len, td, c]);+ };+ const ihdr = Buffer.alloc(13);+ ihdr.writeUInt32BE(w, 0);+ ihdr.writeUInt32BE(h, 4);+ ihdr.set([8, 6, 0, 0, 0], 8);+ const rows: Buffer[] = [];+ for (let y = 0; y < h; y++) {+ const row = Buffer.alloc(1 + w * 4);+ for (let x = 0; x < w; x++) row.set([200, 100, 50, alpha(x, y)], 1 + x * 4);+ rows.push(row);+ }+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", zlib.deflateSync(Buffer.concat(rows))), chunk("IEND", Buffer.alloc(0))]);+}++const manifestOf = (id: string): ManifestWorkflow => getWorkflow(id).manifest;+const file = (filename: string, subfolder = "fuobe") => ({ filename, subfolder, type: "output" });++describe("ComfyUI output mapping", () => {+ it("turns SaveText into text outputs with parsed cues, and folds the detected language in", () => {+ const outs = collectOutputs(+ done({+ "5": { text: ["English"] },+ "4": { text: ["0.00-1.20: Hello and welcome back.\n1.30-2.80: Today we test the camera."], files: [file("gen_00001.txt")] },+ }),+ manifestOf("captions-qwen3-asr"),+ "http://comfy.test:8188",+ );+ expect(outs).toHaveLength(1);+ expect(outs[0]).toMatchObject({+ kind: "text",+ contentType: "text/plain",+ text: "0.00-1.20: Hello and welcome back.\n1.30-2.80: Today we test the camera.",+ meta: {+ role: "cues",+ language: "English",+ cues: [+ { start: 0, end: 1.2, text: "Hello and welcome back." },+ { start: 1.3, end: 2.8, text: "Today we test the camera." },+ ],+ },+ });+ expect(outs[0].url).toBe("http://comfy.test:8188/view?filename=gen_00001.txt&subfolder=fuobe&type=output");+ });++ it("labels the voice and background stems and keeps the manifest's output order", () => {+ const outs = collectOutputs(+ done({+ "10": { text: ["German"] },+ "9": { text: ["Hallo zusammen."], files: [file("t_00001.txt")] },+ "8": { text: ["0.00-1.50: Hallo zusammen."], files: [file("s_00001.txt")] },+ "6": { audio: [file("background_00001_.mp3")] },+ "5": { audio: [file("vocals_00001_.mp3")] },+ }),+ manifestOf("dub-prepare-separate-transcribe"),+ );+ expect(outs.map((o) => [o.kind, o.meta?.stem ?? o.meta?.role])).toEqual([+ ["audio", "voice"],+ ["audio", "background"],+ ["text", "cues"],+ ["text", "transcript"],+ ]);+ expect(outs[2].meta?.cues).toEqual([{ start: 0, end: 1.5, text: "Hallo zusammen." }]);+ expect(outs[3].meta).toMatchObject({ language: "German" });+ expect(outs[3].meta?.cues).toBeUndefined();+ });++ it("reads Save3D's ui['3d'] as a .glb model and the turntable as video", () => {+ const outs = collectOutputs(+ done({+ "322": { "3d": [file("product_00001_.glb", "fuobe")], camera_info: [{ position: { x: 1 } }], model_3d_info: [] },+ "702": { images: [file("turntable_00001_.mp4")], animated: [true] },+ }),+ manifestOf("image-to-3d-trellis2"),+ );+ expect(outs.map((o) => [o.kind, o.contentType, o.meta?.role])).toEqual([+ ["model3d", "model/gltf-binary", undefined],+ ["video", undefined, "turntable"],+ ]);+ });++ it("returns layers back to front with z, name and a bounding box from alpha (one download each)", async () => {+ const pngs: Record<string, Buffer> = {+ "layer_00001_.png": rgbaPng(16, 12, () => 255),+ "layer_00002_.png": rgbaPng(16, 12, (x, y) => (x >= 4 && x < 10 && y >= 2 && y < 7 ? 255 : 0)),+ };+ handler = (url) => {+ if (url.includes("/history/")) return json({ "p-layers": done({ "60": { images: [file("layer_00001_.png"), file("layer_00002_.png")] } }) });+ const name = new URL(url).searchParams.get("filename")!;+ return new Response(new Uint8Array(pngs[name]), { headers: { "Content-Type": "image/png" } });+ };+ const res = await comfyProvider.poll(pollCtx("p-layers", { workflowId: "layers-qwen-image-layered", nodeCount: 19 }));+ expect(res.state).toBe("succeeded");+ const outs = (res as { outputs: { url: string; kind: string; meta?: Record<string, unknown> }[] }).outputs;+ expect(outs.map((o) => o.meta)).toEqual([+ { role: "layers", z: 0, name: "Background", bbox: [0, 0, 16, 12], width: 16, height: 12 },+ { role: "layers", z: 1, name: "Layer 1", bbox: [4, 2, 6, 5], width: 16, height: 12 },+ ]);+ expect(outs.every((o) => o.url.startsWith("data:image/png;base64,"))).toBe(true);+ expect(calls.filter((c) => c.includes("/view?")).length).toBe(2);+ });++ it("follows VHS meta-batch passes to the one that saved the video", async () => {+ const prefix = "fuobe/gen-mm";+ const pass = (n: number, outputs: Record<string, unknown>) => ({ prompt: [n, `pass-${n}`, { "22": { class_type: "VHS_VideoCombine", inputs: { filename_prefix: prefix } } }], ...done(outputs) });+ let queued = true;+ handler = (url) => {+ if (url.includes("/history/p-mm")) return json({ "p-mm": pass(1, {}) });+ if (url.endsWith("/queue")) return json({ queue_running: queued ? [[2, "pass-2", { "22": { class_type: "VHS_VideoCombine", inputs: { filename_prefix: prefix } } }]] : [], queue_pending: [] });+ if (url.includes("/history?max_items")) return json({ "pass-1": pass(1, {}), "pass-2": pass(2, { "22": { gifs: [file("gen-mm_00001.mp4")] } }) });+ return json({});+ };+ const meta = { workflowId: "mixed-media-zimage-frames", nodeCount: 17, prefix, metaBatch: true };+ expect(await comfyProvider.poll(pollCtx("p-mm", meta))).toMatchObject({ state: "running", message: "Rendering the next batch of frames" });+ queued = false;+ const res = await comfyProvider.poll(pollCtx("p-mm", meta));+ expect(res).toMatchObject({ state: "succeeded", outputs: [{ kind: "video", url: expect.stringContaining("gen-mm_00001.mp4") }] });+ });++ it("explains a caption that starts after the end of the clip", async () => {+ handler = () =>+ json({+ "p-cap": {+ status: { status_str: "error", messages: [["execution_error", { node_type: "GetVideoComponents", exception_message: "division by zero\n" }]] },+ outputs: {},+ },+ });+ expect(await comfyProvider.poll(pollCtx("p-cap", { workflowId: "captions-burnin", nodeCount: 11 }))).toEqual({+ state: "failed",+ error: "A caption starts after the end of the video — check the cue times",+ });+ });+});++// ---------------------------------------------------------------------------+// Every round-3 workflow, bound for real (applyBindings on the library graph through prepareWorkflow)++const ROUND3 = [+ "layers-qwen-image-layered", "layers-qwen-image-layered-control", "style-ref-qwen-edit-2511", "style-ref-flux2-klein-4b", "style-ref-krea2",+ "style-ref-uso-flux1", "palette-zimage-hex", "video-trim", "video-segment-resample", "video-restyle-wan22-fun-vace", "mixed-media-zimage-frames",+ "sfx-stable-audio-3-small", "sfx-stable-audio-open", "sfx-hunyuan-foley", "sfx-mmaudio-t2a", "sfx-thinksound", "dub-prepare-separate-transcribe",+ "captions-qwen3-asr", "captions-burnin", "captions-whisper-burnin", "translate-qwen35-textgen", "speech-translate-gemma4", "lipsync-v2v-infinitetalk",+ "lipsync-latentsync16", "video-mux-audio", "video-mux-audio-replace", "image-to-3d-trellis2", "image-to-3d-hunyuan3d-21", "tryon-flux2-klein-4b",+ "grid-zimage-contact-sheet", "soul-cast-sheet-zimage",+];+const LOADERS: Record<string, string> = { LoadImage: "image", LoadImageMask: "image", LoadVideo: "file", VHS_LoadVideo: "video", LoadAudio: "audio" };+const CUES = "0.00-1.00: Hello there\n1.20-2.00: Second line";+const GIVEN = new Set(["img1.png", "img2.png", "clip.mp4", "voice.wav", "bg.wav", "up_palette_swatch.png"]);+const opFor = (id: string) => MODELS.flatMap((m) => m.routes).find((r) => r.provider === "comfyui" && r.endpoint === id)?.op ?? (id.startsWith("video-mux") ? "mux" : "t2i");++async function prepare(id: string, over: Record<string, unknown> = {}, op = opFor(id)) {+ const input = {+ prompt: CUES,+ negativePrompt: "blurry",+ images: ["img1.png", "img2.png"],+ video: "clip.mp4",+ audio: "voice.wav",+ palette: ["#112233", "#445566"],+ targetLanguage: "German (de)",+ sourceLanguage: "de",+ startTime: 1,+ endTime: 3,+ numLayers: 3,+ aspectRatio: "16:9",+ seed: 7,+ extra: { audio2: "bg.wav" },+ ...over,+ };+ const uploads: string[] = [];+ const res = await prepareWorkflow(id, input, {+ generationId: "gen1",+ op,+ upload: async (_d, _t, name) => {+ uploads.push(name);+ return `up_${name}`;+ },+ });+ return { ...res, uploads };+}+const at = (wf: Record<string, { inputs: Record<string, unknown> }>, m: ManifestWorkflow, key: string) => (m.bindings[key] ?? []).map((t) => wf[t.node].inputs[t.input]);++describe("round-3 workflow bindings", () => {+ it("are all in the manifest, validated, with a licence", () => {+ const byId = new Map(loadManifest().workflows.map((w) => [w.id, w]));+ for (const id of ROUND3) {+ expect(byId.get(id)?.validated, id).toBe(true);+ expect(byId.get(id)?.license, id).toBeTruthy();+ }+ expect(byId.get("lipsync-latentsync16")?.worker).toBe("isolated");+ expect(byId.get("sfx-thinksound")?.worker).toBe("isolated");+ });++ it.each(ROUND3)("%s: every upload slot, the seed and the file prefix are filled", async (id) => {+ const { workflow, manifest } = await prepare(id);+ for (const [nid, n] of Object.entries(workflow)) {+ const inp = LOADERS[n.class_type];+ if (inp) expect(GIVEN.has(String(n.inputs[inp])), `${id} node ${nid} ${n.class_type}.${inp} = ${n.inputs[inp]}`).toBe(true);+ if ("filename_prefix" in n.inputs && manifest.outputs.some((o) => o.node === nid)) expect(n.inputs.filename_prefix, `${id} ${nid}`).toBe("fuobe/gen1");+ }+ for (const v of at(workflow, manifest, "seed")) expect(v).toBe(7);+ if (manifest.bindings.negativePrompt) expect(at(workflow, manifest, "negativePrompt")).toEqual(manifest.bindings.negativePrompt.map(() => "blurry"));+ });++ it("maps trim times, frame rates and frame counts", async () => {+ const trim = await prepare("video-trim");+ expect(trim.workflow["2"].inputs).toMatchObject({ start_time: 1, duration: 2 });+ const open = await prepare("video-trim", { endTime: undefined, startTime: 4 });+ expect(open.workflow["2"].inputs).toMatchObject({ start_time: 4, duration: 0 }); // to the end+ const seg = await prepare("video-segment-resample", { fps: 16 });+ expect(seg.workflow["1"].inputs).toMatchObject({ force_rate: 16, skip_first_frames: 16, frame_load_cap: computeFrames(2, 16, 4, 241) });+ expect(seg.workflow["3"].inputs.fps).toBe(16);+ const { width, height } = seg.workflow["2"].inputs as { width: number; height: number };+ expect(width % 16 + (height % 16)).toBe(0);+ expect(width / height).toBeCloseTo(16 / 9, 1);+ const mm = await prepare("mixed-media-zimage-frames", { extra: { fps: 12 } });+ expect(mm.workflow["1"].inputs).toMatchObject({ force_rate: 12, skip_first_frames: 12, frame_load_cap: computeFrames(2, 12, 1, 240) });+ expect(mm.workflow["22"].inputs.frame_rate).toBe(12);+ expect(mm.meta.metaBatch).toBe(true);+ });++ it("maps layers, languages, palettes and instructions", async () => {+ const layers = await prepare("layers-qwen-image-layered");+ expect(layers.workflow["83:118"].inputs.layers).toBe(3);+ const asr = await prepare("captions-qwen3-asr", { audio: undefined });+ expect(asr.workflow["1"].inputs.audio).toBe("clip.mp4"); // LoadAudio reads the video's soundtrack+ expect(asr.workflow["3"].inputs.language).toBe("German");+ const pal = await prepare("palette-zimage-hex", { prompt: "a rooftop at dusk" });+ expect(pal.workflow["20"].inputs).toMatchObject({ string_a: "a rooftop at dusk", string_b: "Color palette: #112233, #445566." });+ expect(pal.workflow["1"].inputs.image).toBe("up_palette_swatch.png");+ expect(pal.uploads).toEqual(["palette_swatch.png"]);+ const recolor = await prepare("palette-transfer-image", { images: ["img1.png"] }, "color-match");+ expect(recolor.workflow["2"].inputs.image).toBe("up_palette_swatch.png");+ const tr = await prepare("translate-qwen35-textgen");+ expect(tr.workflow["2"].inputs.string_a).toMatch(/into German\./);+ expect(tr.workflow["2"].inputs.string_b).toBe(CUES);+ await expect(prepare("translate-qwen35-textgen", { targetLanguage: undefined })).rejects.toThrow(/Pick a language/);+ const speech = await prepare("speech-translate-gemma4");+ expect(speech.workflow["1"].inputs.prompt).toBe("Transcribe the speech in this audio, then translate it into German. Output only the German translation.");+ const ts = await prepare("sfx-thinksound", { prompt: "door slam" });+ expect(ts.workflow["3"].inputs).toMatchObject({ caption: "door slam", cot_description: "door slam", duration: 2 });+ });++ it("fills reference slots, trigger words and grid framing", async () => {+ const klein = await prepare("style-ref-flux2-klein-4b");+ expect(at(klein.workflow, klein.manifest, "image3")).toEqual(["img2.png"]);+ expect(at(klein.workflow, klein.manifest, "image4")).toEqual(["img2.png"]);+ const tryon = await prepare("tryon-flux2-klein-4b", { prompt: "wear these" });+ expect(tryon.workflow["75:74"].inputs.text).toBe("TRYON wear these");+ expect(tryon.workflow["77"].inputs.image).toBe("img2.png"); // a dress is both top and bottom+ const grid = await prepare("grid-zimage-contact-sheet", { prompt: "a heist", extra: { columns: 2, rows: 2 } });+ expect(grid.workflow["20"].inputs.string_a).toMatch(/^A 2x2 grid contact sheet of 4 film stills/);+ expect(grid.workflow["27"].inputs).toMatchObject({ columns: 2, rows: 2 });+ await expect(prepare("style-ref-qwen-edit-2511", { images: [] })).rejects.toThrow(/Add an image/);+ });++ it("uses the one-track soundtrack graph without a background stem", async () => {+ const mix = await prepare("video-mux-audio");+ expect(mix.manifest.id).toBe("video-mux-audio");+ expect(mix.workflow["4"].inputs.audio).toBe("bg.wav");+ const one = await prepare("video-mux-audio", { extra: {} });+ expect(one.manifest.id).toBe("video-mux-audio-replace");+ expect(one.workflow["3"].inputs.audio).toBe("voice.wav");+ });++ it("writes one segment per caption cue with the chosen style", async () => {+ const { workflow } = await prepare("captions-burnin", { extra: { fontSize: 8, captionPosition: "top", fontColor: "#ffd400" } });+ const slices = Object.values(workflow).filter((n) => n.class_type === "Video Slice").map((n) => [n.inputs.start_time, n.inputs.duration]);+ expect(slices).toEqual([[0, 1], [1, 0.2], [1.2, 0]]);+ const overlays = Object.values(workflow).filter((n) => n.class_type === "TextOverlay");+ expect(overlays.map((n) => n.inputs.text)).toEqual(["Hello there", "Second line"]);+ expect(overlays.every((n) => n.inputs.font_size === 8 && n.inputs.position === "top" && n.inputs.color === "#ffd400")).toBe(true);+ await expect(prepare("captions-burnin", { prompt: "no timings here" })).rejects.toThrow(/No timed captions/);+ });+});diff --git a/tests/comfy.test.ts b/tests/comfy.test.tsindex da9b5b9e..577cbb60 100644--- a/tests/comfy.test.ts+++ b/tests/comfy.test.ts@@ -1,5 +1,24 @@+import fs from "node:fs";+import path from "node:path";import { describe, expect, it } from "vitest";-import { applyBindings, computeDimensions, computeFrames, explainComfyError, injectLoras, referencedModels, type ComfyWorkflow } from "@/lib/comfy";+import {+ alphaBBox,+ applyBindings,+ asrLanguage,+ computeDimensions,+ computeFrames,+ expandCaptionWorkflow,+ explainComfyError,+ injectLoras,+ languageName,+ paletteSentence,+ parseCueLines,+ parseHex,+ referencedModels,+ splitCueWords,+ swatchPixels,+ type ComfyWorkflow,+} from "@/lib/comfy";const wan: ComfyWorkflow = {"1": { class_type: "UNETLoader", inputs: { unet_name: "wan2.2_i2v_high_noise_14B_fp8_scaled.safetensors", weight_dtype: "default" } },@@ -73,3 +92,95 @@ describe("helpers", () => {expect(msg).toContain("https://hf/x");});});++describe("caption cues", () => {+ it("parses Qwen3-ASR cue lines, SRT and WebVTT, sorted, skipping noise", () => {+ expect(parseCueLines("1.30-2.80: Second.\n0.00-1.20: First.\nnot a cue\n2.0-1.0: backwards")).toEqual([+ { start: 0, end: 1.2, text: "First." },+ { start: 1.3, end: 2.8, text: "Second." },+ ]);+ const srt = "1\n00:00:01,500 --> 00:00:03,000\nHello\nthere\n\n2\n00:01:02,000 --> 00:01:04,250\nAgain\n";+ expect(parseCueLines(srt)).toEqual([+ { start: 1.5, end: 3, text: "Hello there" },+ { start: 62, end: 64.25, text: "Again" },+ ]);+ expect(parseCueLines("WEBVTT\n\n00:00.500 --> 00:02.000\nVTT line")).toEqual([{ start: 0.5, end: 2, text: "VTT line" }]);+ expect(parseCueLines(undefined)).toEqual([]);+ });++ it("splits long cues into a few words at a time, timed by length", () => {+ const out = splitCueWords([{ start: 0, end: 4, text: "one two three four five" }], 2);+ expect(out.map((c) => c.text)).toEqual(["one two", "three four", "five"]);+ expect(out[0].start).toBe(0);+ expect(out.at(-1)!.end).toBe(4);+ for (let i = 1; i < out.length; i++) expect(out[i].start).toBe(out[i - 1].end);+ expect(splitCueWords([{ start: 0, end: 1, text: "short" }], 0)).toEqual([{ start: 0, end: 1, text: "short" }]);+ });+});++describe("caption burn-in graph", () => {+ const template = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/captions-burnin.json"), "utf8")) as ComfyWorkflow;+ const kinds = (wf: ComfyWorkflow, t: string) => Object.entries(wf).filter(([, n]) => n.class_type === t);++ it("cuts the clip into gap and cue segments that tile the timeline; the last cue runs to the end", () => {+ const wf = expandCaptionWorkflow(template, [+ { start: 0.5, end: 1.5, text: "Hello" },+ { start: 1.5, end: 2.0, text: "world" },+ { start: 3.0, end: 4.0, text: "again" },+ ]);+ const slices = kinds(wf, "Video Slice").map(([, n]) => [n.inputs.start_time, n.inputs.duration]);+ expect(slices).toEqual([[0, 0.5], [0.5, 1], [1.5, 0.5], [2, 1], [3, 0]]);+ expect(kinds(wf, "TextOverlay").map(([, n]) => n.inputs.text)).toEqual(["Hello", "world", "again"]);+ // style copied from the template's overlay; frames come from each segment+ for (const [, n] of kinds(wf, "TextOverlay")) expect(n.inputs).toMatchObject({ font_size: 6, position: "bottom", align: "center", outline: true });+ // the batch keeps segment order, CreateVideo / SaveVideo are untouched+ const batch = wf["90"];+ expect(Object.keys(batch.inputs)).toEqual(["images.image0", "images.image1", "images.image2", "images.image3", "images.image4"]);+ expect(wf["91"].inputs).toMatchObject({ images: ["90", 0], fps: ["2", 2], audio: ["2", 1] });+ expect(Object.values(wf).every((n) => Object.values(n.inputs).every((v) => !Array.isArray(v) || !!wf[v[0] as string]))).toBe(true);+ });++ it("nests batches past 50 segments and refuses an empty cue list", () => {+ const cues = Array.from({ length: 60 }, (_, i) => ({ start: i, end: i + 1, text: `cue ${i}` }));+ const wf = expandCaptionWorkflow(template, cues);+ const batches = kinds(wf, "BatchImagesNode");+ expect(batches.length).toBe(3); // 60 segments: 50 + 10, then the top level+ expect(Object.keys(wf["90"].inputs)).toEqual(["images.image0", "images.image1"]);+ expect(() => expandCaptionWorkflow(template, [])).toThrow(/No captions/);+ });+});++describe("languages, palettes, layers", () => {+ it("maps languages to the ASR list and to instruction words", () => {+ expect(asrLanguage("de")).toBe("German");+ expect(asrLanguage("German (de)")).toBe("German");+ expect(asrLanguage("pt-BR")).toBe("Portuguese");+ expect(asrLanguage("english")).toBe("English");+ expect(asrLanguage("Klingon")).toBe("auto");+ expect(asrLanguage(undefined)).toBe("auto");+ expect(languageName("Japanese (ja)")).toBe("Japanese");+ expect(languageName("he")).toBe("Hebrew");+ expect(languageName("Klingon")).toBe("Klingon");+ });++ it("writes the palette sentence and a banded swatch", () => {+ expect(parseHex("#fff")).toEqual([255, 255, 255]);+ expect(parseHex("nope")).toBeNull();+ expect(paletteSentence(["#e4572e", "29335c", "teal"])).toBe("Color palette: #E4572E, #29335C.");+ const px = swatchPixels(["#ff0000", "#0000ff"], 4, 2);+ const at = (x: number, y: number) => Array.from(px.slice((y * 4 + x) * 4, (y * 4 + x) * 4 + 4));+ expect([at(0, 0), at(1, 1), at(2, 0), at(3, 1)]).toEqual([[255, 0, 0, 255], [255, 0, 0, 255], [0, 0, 255, 255], [0, 0, 255, 255]]);+ const weighted = swatchPixels(["#ff0000", "#0000ff"], 4, 1, [3, 1]);+ expect(Array.from(weighted.slice(8, 12))).toEqual([255, 0, 0, 255]);+ expect(() => swatchPixels(["x"])).toThrow(/No valid hex/);+ });++ it("finds a layer's bounding box from alpha", () => {+ const w = 5;+ const h = 4;+ const rgba = new Uint8Array(w * h * 4);+ for (const [x, y] of [[1, 1], [3, 2]]) rgba[(y * w + x) * 4 + 3] = 255;+ expect(alphaBBox(rgba, w, h)).toEqual([1, 1, 3, 2]);+ expect(alphaBBox(new Uint8Array(w * h * 4), w, h)).toBeNull();+ });+});