Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Model checks: every file pinned, first-run files, a rule for every path input, one build from the catalog

Adarsh3d3895f27e88
diff --git a/scripts/build-worker.mjs b/scripts/build-worker.mjs
index 12af82aa..635740a0 100644
--- a/scripts/build-worker.mjs
+++ b/scripts/build-worker.mjs
@@ -9,38 +9,77 @@
// into it;
// - file-pins.json: the SHA-256 of every model file the catalog names. A worker reports a file only when its own
// hash matches.
-// `pnpm build` runs it first. No new dependency.
+// `pnpm build` runs it first. No new dependency. The build stops, and writes nothing, when an input that must have a
+// rule has none (docs/adding-a-model.md).
+//
+// node scripts/build-worker.mjs # into bin/lib/worker/dist/
+// node scripts/build-worker.mjs --out <dir> # into another folder (the tests compare two builds)
+// node scripts/build-worker.mjs --catalog <dir> # from another copy of workflows/comfyui
import fs from "node:fs";
import path from "node:path";
-import { fileURLToPath } from "node:url";
+import { fileURLToPath, pathToFileURL } from "node:url";
import ts from "typescript";
+import { unruledPathInputs } from "./lib/catalog-checks.mjs";
import { allowedNodeList, filePins, inputRules, missingRules, readCatalog } from "./lib/worker-catalog.mjs";
-const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
-const out = path.join(root, "bin/lib/worker/dist");
-const SOURCES = ["computer-runner", "comfy-guard", "comfy-ws", "fetch-within", "local-comfy", "relay", "lanes", "worker-hours"];
+export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+export const SOURCES = ["computer-runner", "comfy-guard", "comfy-ws", "fetch-within", "local-comfy", "relay", "lanes", "worker-hours"];
-fs.mkdirSync(out, { recursive: true });
-for (const name of SOURCES) {
- const src = fs.readFileSync(path.join(root, "src/lib", `${name}.ts`), "utf8");
- const { outputText } = ts.transpileModule(src, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, verbatimModuleSyntax: false, isolatedModules: true }, fileName: `${name}.ts` });
- const js = outputText.replace(/from "\.\/([\w-]+)"/g, (m, dep) => {
- if (!SOURCES.includes(dep)) throw new Error(`${name}.ts imports ./${dep}, which the worker build doesn't include`);
- return `from "./${dep}.mjs"`;
- });
- if (/from "(@\/|\.\.\/)/.test(js)) throw new Error(`${name}.ts imports something outside src/lib's worker files`);
- fs.writeFileSync(path.join(out, `${name}.mjs`), `// Built from src/lib/${name}.ts by scripts/build-worker.mjs. Don't edit.\n${js}`);
+/**
+ * What the worker learns from the catalog: its node allowlist, its input rules and its file pins. Throws when an input
+ * that must have a rule has none: one of the inputs that write or read a file or format with code (missingRules), or
+ * any input whose catalog value names a path, a download or code (unruledPathInputs).
+ */
+export function workerParts(catalog, root = ROOT) {
+ const nodes = allowedNodeList(root, catalog);
+ const rules = inputRules(catalog);
+ const missing = [...missingRules(rules, nodes), ...unruledPathInputs(catalog, rules)];
+ if (missing.length) throw new Error(`These allowed inputs have no rule: ${missing.join(", ")}. Give each a literal value in the catalog.`);
+ return { nodes, rules, pins: filePins(catalog) };
}
-const catalog = readCatalog(root);
-const write = (name, data) => fs.writeFileSync(path.join(out, name), `${JSON.stringify({ built: "scripts/build-worker.mjs", ...data }, null, 1)}\n`);
-const nodes = allowedNodeList(root, catalog);
-write("allowed-nodes.json", { nodes });
-const rules = inputRules(catalog);
-const missing = missingRules(rules, nodes);
-if (missing.length) throw new Error(`These allowed inputs have no rule: ${missing.join(", ")}. Give each a literal value in the catalog.`);
-write("input-rules.json", rules);
-const pins = filePins(catalog);
-write("file-pins.json", { files: pins });
-const ruled = Object.values(rules.inputs).reduce((n, r) => n + Object.keys(r).length, 0);
-console.log(`worker: ${SOURCES.length} modules, ${nodes.length} allowed node types, ${ruled} input rules, ${Object.keys(pins).length} file hashes -> ${path.relative(root, out)}`);
+/** Each built file's text: the transpiled modules and the three catalog files. Nothing is written. */
+export function workerFiles({ root = ROOT, catalogDir } = {}) {
+ const catalog = readCatalog(root, catalogDir);
+ const { nodes, rules, pins } = workerParts(catalog, root);
+ const files = {};
+ for (const name of SOURCES) {
+ const src = fs.readFileSync(path.join(root, "src/lib", `${name}.ts`), "utf8");
+ const { outputText } = ts.transpileModule(src, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, verbatimModuleSyntax: false, isolatedModules: true }, fileName: `${name}.ts` });
+ const js = outputText.replace(/from "\.\/([\w-]+)"/g, (m, dep) => {
+ if (!SOURCES.includes(dep)) throw new Error(`${name}.ts imports ./${dep}, which the worker build doesn't include`);
+ return `from "./${dep}.mjs"`;
+ });
+ if (/from "(@\/|\.\.\/)/.test(js)) throw new Error(`${name}.ts imports something outside src/lib's worker files`);
+ files[`${name}.mjs`] = `// Built from src/lib/${name}.ts by scripts/build-worker.mjs. Don't edit.\n${js}`;
+ }
+ const json = (data) => `${JSON.stringify({ built: "scripts/build-worker.mjs", ...data }, null, 1)}\n`;
+ files["allowed-nodes.json"] = json({ nodes });
+ files["input-rules.json"] = json(rules);
+ files["file-pins.json"] = json({ files: pins });
+ const ruled = Object.values(rules.inputs).reduce((n, r) => n + Object.keys(r).length, 0);
+ return { files, summary: `worker: ${SOURCES.length} modules, ${nodes.length} allowed node types, ${ruled} input rules, ${Object.keys(pins).length} file hashes` };
+}
+
+function main(argv) {
+ const arg = (name) => {
+ const i = argv.indexOf(name);
+ if (i < 0) return undefined;
+ if (!argv[i + 1]) throw new Error(`${name} needs a folder`);
+ return path.resolve(argv[i + 1]);
+ };
+ const out = arg("--out") ?? path.join(ROOT, "bin/lib/worker/dist");
+ const { files, summary } = workerFiles({ catalogDir: arg("--catalog") });
+ fs.mkdirSync(out, { recursive: true });
+ for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(out, name), text);
+ console.log(`${summary} -> ${path.relative(ROOT, out) || out}`);
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
+ try {
+ main(process.argv.slice(2));
+ } catch (e) {
+ console.error(e.message ?? e);
+ process.exit(1);
+ }
+}
diff --git a/scripts/lib/catalog-checks.mjs b/scripts/lib/catalog-checks.mjs
new file mode 100644
index 00000000..fa7878fa
--- /dev/null
+++ b/scripts/lib/catalog-checks.mjs
@@ -0,0 +1,161 @@
+// Checks on the catalog that the worker build and the tests share (docs/adding-a-model.md). Pure: they read a catalog
+// object (scripts/lib/worker-catalog.mjs readCatalog) and the built rules, never the disk.
+import { loaderInput, MODEL_EXT, pathNamed, TEXT_NAME, valueProblem } from "../../bin/lib/worker/rules.mjs";
+import { filePins, REQUIRED_RULES } from "./worker-catalog.mjs";
+
+const nodesOf = (graph) => Object.values(graph ?? {}).filter((n) => n && typeof n === "object" && typeof n.class_type === "string");
+
+/**
+ * Every node input in the catalog's graphs whose written value names a path, a download or code, read on its own and
+ * not through the rules builder: a loader's input file, a text value of an input named for a file or a folder, a value
+ * with a slash and no spaces (a path, or an "org/name" download id), a model file's name, a value the worker's second
+ * layer refuses, and the inputs that must always have a rule (REQUIRED_RULES). Inputs that take free text (prompts,
+ * captions, expressions) are left out: they keep any text.
+ * @returns {{ cls: string, input: string, why: string[] }[]} sorted by class and input
+ */
+export function pathInputs(catalog) {
+ const out = new Map();
+ const add = (cls, input, why) => {
+ const key = `${cls}\u0000${input}`;
+ const p = out.get(key) ?? { cls, input, why: [] };
+ if (!p.why.includes(why)) p.why.push(why);
+ out.set(key, p);
+ };
+ const required = new Set(REQUIRED_RULES.map(([cls, input]) => `${cls}\u0000${input}`));
+ for (const g of Object.values(catalog.graphs ?? {})) {
+ for (const n of nodesOf(g)) {
+ for (const [input, v] of Object.entries(n.inputs ?? {})) {
+ if (Array.isArray(v)) continue; // a link: the rules builder refuses links into these inputs itself
+ const cls = n.class_type;
+ if (required.has(`${cls}\u0000${input}`)) add(cls, input, "required");
+ if (loaderInput(cls, input)) add(cls, input, "input file");
+ if (typeof v !== "string" || TEXT_NAME.test(input)) continue;
+ if (pathNamed(input)) add(cls, input, "named for a path");
+ if (!/\s/.test(v) && /[\\/]/.test(v)) add(cls, input, "a path or a download");
+ if (!/\s/.test(v) && MODEL_EXT.test(v)) add(cls, input, "a model file");
+ if (!/\s/.test(v) && valueProblem(v)) add(cls, input, "refused as a path");
+ }
+ }
+ }
+ return [...out.values()].sort((a, b) => a.cls.localeCompare(b.cls) || a.input.localeCompare(b.input));
+}
+
+/** The path, download and code inputs of the catalog that `rules` gives no rule ("Class.input (why)"). */
+export function unruledPathInputs(catalog, rules) {
+ return pathInputs(catalog)
+ .filter((p) => !rules.inputs?.[p.cls]?.[p.input])
+ .map((p) => `${p.cls}.${p.input} (${p.why.join(", ")})`);
+}
+
+/** Manifest bindings whose model file the run picks (a LoRA, an upscaler): no file of the catalog, so no pin. */
+const RUN_PICKED = /^(lora|loraHigh|loraLow|upscaleModel)$/;
+
+/**
+ * The model files the catalog names that have no SHA-256 pin: every file of the requirement index (required and
+ * optional), and every model file a graph names that the index doesn't hold, unless the run picks it (a LoRA or an
+ * upscaler the manifest binds) or a node fetches it on its first run (named in the workflow's autoDownloads, pinned in
+ * first-run-files.json instead).
+ * @returns {Record<string, string[]>} "folder/file" (the bare name for a file the index doesn't know) → workflow ids
+ */
+export function unpinnedModelFiles(catalog, rules) {
+ const pins = filePins(catalog);
+ const out = new Map();
+ const add = (key, id) => out.set(key, new Set([...(out.get(key) ?? []), id]));
+ for (const [id, wf] of Object.entries(catalog.requirements.workflows ?? {})) {
+ for (const key of [...(wf.files ?? []), ...(wf.optional ?? [])]) if (!pins[key]) add(key, id);
+ }
+ const known = Object.values(catalog.requirements.files ?? {});
+ for (const w of catalog.manifest.workflows ?? []) {
+ const g = catalog.graphs[w.file];
+ if (!g) continue;
+ const picked = new Set(Object.entries(w.bindings ?? {}).filter(([b]) => RUN_PICKED.test(b)).flatMap(([, targets]) => targets.map((t) => `${t.node}\u0000${t.input}`)));
+ const firstRun = (w.autoDownloads ?? []).join("\n");
+ for (const [nodeId, n] of Object.entries(g)) {
+ if (!n || typeof n.class_type !== "string") continue;
+ for (const [input, v] of Object.entries(n.inputs ?? {})) {
+ const rule = rules.inputs?.[n.class_type]?.[input];
+ if (rule?.kind !== "model-file" || typeof v !== "string" || !v) continue;
+ if (picked.has(`${nodeId}\u0000${input}`) || firstRun.includes(v)) continue;
+ const f = known.find((x) => x.file === v && (!rule.folders?.length || rule.folders.includes(x.folder)));
+ if (!f) add(v, w.id);
+ else if (!pins[`${f.folder}/${f.file}`]) add(`${f.folder}/${f.file}`, w.id);
+ }
+ }
+ }
+ return Object.fromEntries([...out].sort(([a], [b]) => a.localeCompare(b)).map(([k, ids]) => [k, [...ids].sort()]));
+}
+
+/** A path under the ComfyUI folder: plain name parts joined by "/", no "..", no drive, no leading slash. */
+const PLAIN_PATH = /^[\w@+-][\w.@+-]*(\/[\w@+-][\w.@+-]*)*$/;
+
+/** What is wrong with one pinned first-run file ({ path, url, sizeBytes, sha256 }), or null. */
+export function firstRunFileProblem(f) {
+ if (!f || typeof f !== "object" || Array.isArray(f)) return "each file is an object: { path, url, sizeBytes, sha256 }";
+ const name = typeof f.path === "string" ? f.path : JSON.stringify(f.path);
+ if (typeof f.path !== "string" || !PLAIN_PATH.test(f.path)) return `${name}: the path must be a plain relative path under the ComfyUI folder`;
+ if (typeof f.url !== "string" || !/^https:\/\/[^\s/]+\/\S+$/.test(f.url)) return `${name}: the url must be an https link`;
+ if (/^https:\/\/huggingface\.co\//.test(f.url) && !/\/resolve\/[0-9a-f]{40}\//.test(f.url)) return `${name}: a Hugging Face url must name a commit (resolve/<40 hex>/)`;
+ if (!Number.isInteger(f.sizeBytes) || f.sizeBytes <= 0) return `${name}: sizeBytes must be the file's exact size`;
+ if (typeof f.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(f.sha256)) return `${name}: sha256 must be 64 lower-case hex digits`;
+ return null;
+}
+
+/**
+ * Every workflow whose nodes fetch files on their first run (autoDownloads) lists those files with their pins in
+ * first-run-files.json, unless it is on `gaps` (the workflows not pinned yet, a list that may only shrink).
+ * @returns {string[]} the problems, or none
+ */
+export function firstRunProblems(manifest, firstRunFiles, gaps = []) {
+ const problems = [];
+ const byId = new Map((manifest.workflows ?? []).map((w) => [w.id, w]));
+ const downloads = (id) => (byId.get(id)?.autoDownloads ?? []).length > 0;
+ const listed = firstRunFiles?.workflows ?? {};
+ for (const w of manifest.workflows ?? []) {
+ if (!downloads(w.id)) continue;
+ const has = Array.isArray(listed[w.id]) && listed[w.id].length > 0;
+ if (gaps.includes(w.id)) {
+ if (has) problems.push(`${w.id}: its first-run files are pinned now; take it off the list of gaps`);
+ } else if (!has) problems.push(`${w.id}: a node fetches files on its first run (autoDownloads) and first-run-files.json pins none`);
+ }
+ for (const id of gaps) if (!downloads(id)) problems.push(`${id}: on the list of gaps, but it fetches nothing on its first run`);
+ for (const [id, files] of Object.entries(listed)) {
+ if (!downloads(id)) problems.push(`${id}: first-run-files.json lists it, but the manifest names no first-run download for it`);
+ if (!Array.isArray(files)) {
+ problems.push(`${id}: a list of files`);
+ continue;
+ }
+ for (const f of files) {
+ const p = firstRunFileProblem(f);
+ if (p) problems.push(`${id}: ${p}`);
+ }
+ }
+ return problems;
+}
+
+/**
+ * VideoHelperSuite's save node formats that write metadata into a clip, from the node's definition in
+ * object_info.subset.json: the formats whose options include save_metadata (its default is on). Null: not known.
+ */
+export function metadataFormats(subset) {
+ const formats = subset?.VHS_VideoCombine?.input?.required?.format?.[1]?.formats;
+ if (!formats || typeof formats !== "object") return null;
+ return new Set(Object.entries(formats).filter(([, options]) => JSON.stringify(options).includes('"save_metadata"')).map(([f]) => f));
+}
+
+/**
+ * The catalog workflows whose graphs save a clip with its metadata (the prompt, the machine's local time): a save node
+ * whose save_metadata isn't false, in a format that writes it (`formats`, from metadataFormats; every format when not
+ * known). An input left out takes the node's default, which keeps the metadata.
+ * @param {{ graphs: Record<string, object>, manifest: { workflows?: { id: string, file: string }[] } }} catalog
+ * @param {Set<string> | null} [formats]
+ * @returns {string[]} workflow ids
+ */
+export function metadataKept(catalog, formats = null) {
+ const keeps = (n) => {
+ if (n.class_type !== "VHS_VideoCombine" && !("save_metadata" in (n.inputs ?? {}))) return false;
+ if (n.inputs?.save_metadata === false) return false;
+ const format = n.inputs?.format;
+ return !formats || typeof format !== "string" || formats.has(format);
+ };
+ return (catalog.manifest.workflows ?? []).filter((w) => nodesOf(catalog.graphs[w.file]).some(keeps)).map((w) => w.id).sort();
+}
diff --git a/scripts/lib/worker-catalog.mjs b/scripts/lib/worker-catalog.mjs
index 26b12c66..d03e4962 100644
--- a/scripts/lib/worker-catalog.mjs
+++ b/scripts/lib/worker-catalog.mjs
@@ -9,11 +9,13 @@ import fs from "node:fs";
import path from "node:path";
import { loaderInput, MODEL_EXT, pathNamed, TEXT_NAME, valueProblem } from "../../bin/lib/worker/rules.mjs";
-const SKIP = new Set(["requirements.json", "manifest.json", "model-pins.json"]);
+const SKIP = new Set(["requirements.json", "manifest.json", "model-pins.json", "first-run-files.json"]);
-/** The catalog: its workflow graphs by file name, its manifest, its requirement index and its model pins. */
-export function readCatalog(root) {
- const dir = path.join(root, "workflows/comfyui");
+/**
+ * The catalog: its workflow graphs by file name, its manifest, its requirement index and its model pins. `dir` is the
+ * library folder (workflows/comfyui under the root unless given).
+ */
+export function readCatalog(root, dir = path.join(root, "workflows/comfyui")) {
const read = (f) => JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
const graphs = {};
for (const f of fs.readdirSync(dir).sort()) {
diff --git a/tests/adding-a-model.test.ts b/tests/adding-a-model.test.ts
index 0db3e55e..c0571c72 100644
--- a/tests/adding-a-model.test.ts
+++ b/tests/adding-a-model.test.ts
@@ -1,19 +1,261 @@
-// The automatic checks of adding a model, a workflow or a node pack: CPU work is marked in the requirement index.
+// The automatic checks of docs/adding-a-model.md: every model file pinned, every first-run download pinned, a rule for
+// every input that names a path, a download or code, a worker build that matches the catalog, CPU work marked, and clips
+// saved without their metadata. Each known gap is listed here, and each list may only shrink.
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
import path from "node:path";
-import { describe, expect, it } from "vitest";
+import { beforeAll, describe, expect, it } from "vitest";
+import { workerParts } from "../scripts/build-worker.mjs";
import { LOADER_FOLDERS } from "../scripts/comfy/build-library.mjs";
-import { cpuWork } from "../scripts/comfy/build-requirements.mjs";
-import { inputRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";
+import { buildIndex, cpuWork, formatIndex, loadInputs } from "../scripts/comfy/build-requirements.mjs";
+import { firstRunFileProblem, firstRunProblems, metadataFormats, metadataKept, pathInputs, unpinnedModelFiles, unruledPathInputs } from "../scripts/lib/catalog-checks.mjs";
+import { filePins, inputRules, readCatalog, REQUIRED_RULES } from "../scripts/lib/worker-catalog.mjs";
+import { tempDir } from "./helpers/temp-dir";
type Node = { class_type: string; inputs: Record<string, unknown> };
type Graph = Record<string, Node>;
-type ManifestWorkflow = { id: string; file: string; vramGb?: number; models: { file: string; folder: string }[]; autoDownloads?: string[] };
-type Rules = { inputs: Record<string, Record<string, { kind: string }>> };
-type Catalog = { graphs: Record<string, Graph>; manifest: { workflows: ManifestWorkflow[] }; requirements: { workflows: Record<string, { cpu?: true }> } };
+type ManifestWorkflow = { id: string; file: string; vramGb?: number; models: { file: string; folder: string }[]; autoDownloads?: string[]; bindings?: Record<string, { node: string; input: string }[]> };
+type Rule = { kind: string; folders?: string[] };
+type Rules = { inputs: Record<string, Record<string, Rule>>; text: Record<string, string[]>; closed: Record<string, string[]> };
+type Catalog = {
+ graphs: Record<string, Graph>;
+ manifest: { workflows: ManifestWorkflow[] };
+ requirements: { files: Record<string, { folder: string; file: string; url: string }>; workflows: Record<string, { files: string[]; optional: string[]; vramGb: number; firstRun: string[]; cpu?: true }> };
+ pins: Record<string, { sha256?: string }>;
+};
const root = path.resolve(__dirname, "..");
+const LIBRARY = path.join(root, "workflows/comfyui");
+const BUILD = path.join(root, "scripts/build-worker.mjs");
+const read = (f: string) => JSON.parse(fs.readFileSync(path.join(LIBRARY, f), "utf8"));
const catalog = readCatalog(root) as unknown as Catalog;
const rules = inputRules(catalog) as Rules;
+const build = (...args: string[]) => spawnSync(process.execPath, [BUILD, ...args], { cwd: root, encoding: "utf8" });
+
+/**
+ * Model files the catalog names that have no SHA-256 pin yet. A worker never reports such a file, so no worker runs a
+ * workflow that needs one. Their pins need the exact files, or a signed-in account for the repositories that ask for
+ * one (`node scripts/comfy/build-requirements.mjs --refresh-pins` with HF_TOKEN). The list may only shrink: a new file
+ * with no pin fails, and so does a file here that has a pin now.
+ */
+const UNPINNED_FILES = [
+ "dbs/DBS-BSRNN-DnR/config.json",
+ "dbs/DBS-TIGER-DnR/config.json",
+ "diffusion_models/flux3-image-klein-base-bf16.safetensors",
+ "diffusion_models/flux3-image-klein-base-int8-convrot.safetensors",
+ "diffusion_models/flux3-image-klein-base-nvfp4.safetensors",
+ "diffusion_models/flux3-image-klein-bf16.safetensors",
+ "diffusion_models/flux3-image-klein-int8-convrot.safetensors",
+ "diffusion_models/flux3-image-klein-nvfp4.safetensors",
+ "diffusion_models/ltx-2.5-22b-distilled-transformer-comfy-int8-convrot.safetensors",
+ "latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors",
+ "loras/ltx-2.5-22b-ic-lora-refine-details-1.0.safetensors",
+ "loras/ltx-2.5-22b-ic-lora-restore-1.0.safetensors",
+ "text_encoders/gemma4-12b-with-proj-ltx-2.5-comfy-int8-convrot.safetensors",
+ "text_encoders/qwen3.5_9b_flux3_prompt_upsampler_int8_convrot.safetensors",
+ "text_encoders/qwen3.5_9b_flux3_prompt_upsampler_w4a8.safetensors",
+ "vae/ltx-2.5-audio-vae-bf16.safetensors",
+ "vae/ltx-2.5-video-vae-bf16.safetensors",
+];
+
+/**
+ * Workflows whose nodes fetch files on their first run (autoDownloads) and whose files first-run-files.json doesn't pin
+ * yet. The list may only shrink: a new workflow must pin its first-run files, and a workflow here that pins them now
+ * must come off.
+ */
+const FIRST_RUN_GAPS = [
+ "bg-remove-rmbg",
+ "captions-qwen3-asr",
+ "captions-whisper-burnin",
+ "dub-prepare-dbs-transcribe",
+ "dub-prepare-separate-transcribe",
+ "face-swap-reactor",
+ "infinitetalk-wanwrapper",
+ "interpolate-rife-vfi",
+ "lipsync-latentsync16",
+ "lipsync-v2v-infinitetalk",
+ "qwen-image-21-edit-small",
+ "qwen-image-21-t2i-small",
+ "sfx-hunyuan-foley",
+ "sfx-thinksound",
+ "tryon-flux2-klein-4b",
+ "tts-chatterbox-multilingual",
+ "tts-dialogue-chatterbox",
+ "tts-indextts2",
+ "tts-qwen3-clone",
+ "tts-qwen3-design",
+ "tts-voxcpm2",
+ "tts-voxcpm2-clone",
+ "v2a-hunyuan-foley",
+ "video-depth-vda-large",
+ "video-depth-vda-small",
+ "video-fix-faces-h3",
+ "video-from-picture-h3",
+ "video-from-picture-solar",
+ "video-motion-transfer-h3",
+ "voice-change-chatterbox",
+];
+
+/** Workflows whose graphs still save clips with their metadata (the prompt, the local time). The list may only shrink. */
+const KEEPS_METADATA = [
+ "captions-whisper-burnin",
+ "infinitetalk-wanwrapper",
+ "interpolate-rife-vfi",
+ "lipsync-latentsync16",
+ "lipsync-v2v-infinitetalk",
+ "mixed-media-zimage-frames",
+ "selftest-meta-batch",
+ "upscale-video-esrgan-chunked",
+ "upscale-video-seedvr2-chunked",
+ "v2a-mmaudio",
+];
+
+const SHA = "0123456789abcdef".repeat(4);
+const COMMIT = "0123456789abcdef0123456789abcdef01234567";
+
+describe("every model file has a SHA-256 pin", () => {
+ it("every file a catalog workflow names, but for a list of gaps that may only shrink", () => {
+ const gaps = unpinnedModelFiles(catalog, rules);
+ const fresh = Object.keys(gaps).filter((f) => !UNPINNED_FILES.includes(f));
+ expect(fresh, `Pin these in workflows/comfyui/model-pins.json:\n${fresh.map((f) => `${f} (${gaps[f].join(", ")})`).join("\n")}`).toEqual([]);
+ const pinned = UNPINNED_FILES.filter((f) => !gaps[f]);
+ expect(pinned, `These have a pin now: take them off UNPINNED_FILES\n${pinned.join("\n")}`).toEqual([]);
+ const pins = filePins(catalog) as Record<string, string>;
+ for (const sha of Object.values(pins)) expect(sha).toMatch(/^[0-9a-f]{64}$/);
+ expect(Object.keys(pins).length + UNPINNED_FILES.length).toBe(Object.keys(catalog.requirements.files).length);
+ });
+
+ it("a file with no pin is found, in the index or only in a graph", () => {
+ const loader = (name: string) => ({ "1": { class_type: "UNETLoader", inputs: { unet_name: name, weight_dtype: "default" } } });
+ const fake = (graph: Graph, over: Partial<ManifestWorkflow> = {}, pins: Catalog["pins"] = {}) => ({
+ graphs: { "a.json": graph },
+ manifest: { workflows: [{ id: "a", file: "a.json", models: [], bindings: {}, ...over }] },
+ requirements: { files: { "diffusion_models/x.safetensors": { folder: "diffusion_models", file: "x.safetensors", url: "https://h/x" } }, workflows: { a: { files: ["diffusion_models/x.safetensors"], optional: [] } } },
+ pins,
+ });
+ const r = { inputs: { UNETLoader: { unet_name: { kind: "model-file", folders: ["diffusion_models"] } } } };
+ expect(unpinnedModelFiles(fake(loader("x.safetensors")), r)).toEqual({ "diffusion_models/x.safetensors": ["a"] });
+ expect(unpinnedModelFiles(fake(loader("x.safetensors"), {}, { "https://h/x": { sha256: SHA } }), r)).toEqual({});
+ // A file the index doesn't know can't have a pin.
+ expect(unpinnedModelFiles(fake(loader("y.safetensors"), {}, { "https://h/x": { sha256: SHA } }), r)).toEqual({ "y.safetensors": ["a"] });
+ // Unless the run picks it (a LoRA the manifest binds), or a node fetches it on its first run (pinned there).
+ expect(unpinnedModelFiles(fake(loader("y.safetensors"), { bindings: { lora: [{ node: "1", input: "unet_name" }] } }, { "https://h/x": { sha256: SHA } }), r)).toEqual({});
+ expect(unpinnedModelFiles(fake(loader("y.safetensors"), { autoDownloads: ["the node downloads y.safetensors on first run"] }, { "https://h/x": { sha256: SHA } }), r)).toEqual({});
+ });
+});
+
+describe("first-run downloads have pinned files", () => {
+ it("every workflow whose nodes fetch files on their first run, but for a list of gaps that may only shrink", () => {
+ expect(firstRunProblems(catalog.manifest, read("first-run-files.json"), FIRST_RUN_GAPS)).toEqual([]);
+ });
+
+ it("a pinned file names its place, a fixed link, its exact size and its SHA-256", () => {
+ const good = { path: "models/RMBG/BEN2/BEN2_Base.pth", url: `https://huggingface.co/org/repo/resolve/${COMMIT}/BEN2_Base.pth`, sizeBytes: 1024, sha256: SHA };
+ expect(firstRunFileProblem(good)).toBeNull();
+ expect(firstRunFileProblem({ ...good, url: "https://github.com/org/repo/releases/download/v1/BEN2_Base.pth" })).toBeNull();
+ for (const p of ["../x.pth", "/x.pth", "C:/x.pth", "models/../x.pth", "models\\x.pth", "~/x.pth", "models//x.pth", ".hidden/x", ""]) {
+ expect(firstRunFileProblem({ ...good, path: p }), p).toMatch(/plain relative path/);
+ }
+ expect(firstRunFileProblem({ ...good, url: "http://huggingface.co/org/repo/resolve/main/x" })).toMatch(/https/);
+ expect(firstRunFileProblem({ ...good, url: "https://huggingface.co/org/repo/resolve/main/x" })).toMatch(/commit/);
+ expect(firstRunFileProblem({ ...good, sizeBytes: 0 })).toMatch(/size/);
+ expect(firstRunFileProblem({ ...good, sha256: SHA.toUpperCase() })).toMatch(/sha256/);
+ expect(firstRunFileProblem({ ...good, sha256: undefined })).toMatch(/sha256/);
+
+ const manifest = { workflows: [{ id: "a", autoDownloads: ["a node fetches x on first run"] }, { id: "b" }] };
+ expect(firstRunProblems(manifest, { workflows: {} })).toEqual(["a: a node fetches files on its first run (autoDownloads) and first-run-files.json pins none"]);
+ expect(firstRunProblems(manifest, { workflows: { a: [good] } })).toEqual([]);
+ expect(firstRunProblems(manifest, { workflows: {} }, ["a"])).toEqual([]);
+ expect(firstRunProblems(manifest, { workflows: { a: [good] } }, ["a"])).toEqual(["a: its first-run files are pinned now; take it off the list of gaps"]);
+ expect(firstRunProblems(manifest, { workflows: {} }, ["a", "b"])).toEqual(["b: on the list of gaps, but it fetches nothing on its first run"]);
+ expect(firstRunProblems(manifest, { workflows: { a: [good], b: [good] } })).toEqual(["b: first-run-files.json lists it, but the manifest names no first-run download for it"]);
+ expect(firstRunProblems(manifest, { workflows: { a: [{ ...good, sha256: "x" }] } })).toEqual([`a: ${good.path}: sha256 must be 64 lower-case hex digits`]);
+ });
+});
+
+describe("the worker build", () => {
+ let first = "";
+ let second = "";
+ beforeAll(() => {
+ first = tempDir("fuobe-worker-build-a-");
+ second = tempDir("fuobe-worker-build-b-");
+ for (const out of [first, second]) {
+ const r = build("--out", out);
+ expect(r.status, r.stderr).toBe(0);
+ }
+ }, 120_000);
+ const built = (dir: string, f: string) => JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
+
+ it("gives a rule to every input whose catalog value names a path, a download or code", () => {
+ const found = pathInputs(catalog).map((p: { cls: string; input: string }) => `${p.cls}.${p.input}`);
+ expect(found).toEqual(
+ expect.arrayContaining(["AILab_Qwen3ASRSubtitle.output_path", "AILab_Qwen3ASRSubtitle.model", "MiniMaxH3SourceTimeline.video_path", "StringFormat.f_string", "LoadImage.image", "UNETLoader.unet_name", "SaveVideo.filename_prefix"]),
+ );
+ expect(unruledPathInputs(catalog, rules)).toEqual([]);
+ // In the file the build wrote, too: each of them, and each input that must always have one.
+ const written = built(first, "input-rules.json") as Rules;
+ const allowed = built(first, "allowed-nodes.json").nodes as string[];
+ const missing = pathInputs(catalog).filter((p: { cls: string; input: string }) => !written.inputs[p.cls]?.[p.input]);
+ expect(missing).toEqual([]);
+ for (const [cls, input] of REQUIRED_RULES as [string, string][]) if (allowed.includes(cls)) expect(written.inputs[cls]?.[input], `${cls}.${input}`).toBeTruthy();
+ // A prompt keeps free text: no rule.
+ expect(written.inputs.CLIPTextEncode?.text).toBeUndefined();
+ });
+
+ it("names an input that has no rule", () => {
+ const less = structuredClone(rules);
+ delete less.inputs.AILab_Qwen3ASRSubtitle.output_path;
+ delete less.inputs.UNETLoader.unet_name;
+ expect(unruledPathInputs(catalog, less)).toEqual(["AILab_Qwen3ASRSubtitle.output_path (required, named for a path, a path or a download)", "UNETLoader.unet_name (a model file)"]);
+ });
+
+ it("stops when an input that must have a rule has none, or the catalog links into one", () => {
+ const without = structuredClone(catalog);
+ for (const g of Object.values(without.graphs)) for (const n of Object.values(g ?? {})) if (n?.class_type === "AILab_Qwen3ASRSubtitle") delete n.inputs.output_path;
+ expect(() => workerParts(without, root)).toThrow(/no rule: .*AILab_Qwen3ASRSubtitle\.output_path/);
+ const linked = structuredClone(catalog);
+ for (const g of Object.values(linked.graphs)) for (const n of Object.values(g ?? {})) if (n?.class_type === "MiniMaxH3SourceTimeline") n.inputs.video_path = ["1", 0];
+ expect(() => workerParts(linked, root)).toThrow(/MiniMaxH3SourceTimeline\.video_path .*links into it/);
+ });
+
+ it("from the command line: a missing rule fails the build, which writes nothing", () => {
+ const copy = tempDir("fuobe-worker-catalog-");
+ let changed = 0;
+ for (const f of fs.readdirSync(LIBRARY).filter((x) => x.endsWith(".json"))) {
+ let text = fs.readFileSync(path.join(LIBRARY, f), "utf8");
+ if (text.includes("AILab_Qwen3ASRSubtitle") && f !== "requirements.json" && f !== "manifest.json" && f !== "object_info.subset.json") {
+ const g = JSON.parse(text) as Graph;
+ for (const n of Object.values(g)) {
+ if (n?.class_type !== "AILab_Qwen3ASRSubtitle") continue;
+ delete n.inputs.output_path;
+ changed++;
+ }
+ text = JSON.stringify(g);
+ }
+ fs.writeFileSync(path.join(copy, f), text);
+ }
+ expect(changed).toBeGreaterThan(0);
+ const out = path.join(tempDir("fuobe-worker-out-"), "dist");
+ const r = build("--catalog", copy, "--out", out);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toMatch(/These allowed inputs have no rule: .*AILab_Qwen3ASRSubtitle\.output_path/);
+ expect(fs.existsSync(out)).toBe(false);
+ }, 60_000);
+
+ it("rebuilding gives no diff: two builds write the same files, and they match the catalog", () => {
+ const files = fs.readdirSync(first).sort();
+ expect(fs.readdirSync(second).sort()).toEqual(files);
+ for (const f of files) expect(fs.readFileSync(path.join(second, f), "utf8"), f).toBe(fs.readFileSync(path.join(first, f), "utf8"));
+ expect(files).toEqual(expect.arrayContaining(["allowed-nodes.json", "input-rules.json", "file-pins.json", "computer-runner.mjs"]));
+ const parts = workerParts(catalog, root) as { nodes: string[]; rules: Rules; pins: Record<string, string> };
+ expect(built(first, "allowed-nodes.json")).toEqual({ built: "scripts/build-worker.mjs", nodes: parts.nodes });
+ expect(built(first, "input-rules.json")).toEqual({ built: "scripts/build-worker.mjs", ...parts.rules });
+ expect(built(first, "file-pins.json")).toEqual({ built: "scripts/build-worker.mjs", files: filePins(catalog) });
+ // The pins come from the requirement index, which is the one its inputs build, byte for byte (a Windows checkout
+ // may turn its line ends into CRLF).
+ expect(fs.readFileSync(path.join(LIBRARY, "requirements.json"), "utf8").replace(/\r\n/g, "\n")).toBe(formatIndex(buildIndex(loadInputs(LIBRARY))));
+ });
+});
describe("CPU work is marked, so it is never counted as GPU work", () => {
const index = catalog.requirements.workflows;
@@ -41,3 +283,22 @@ describe("CPU work is marked, so it is never counted as GPU work", () => {
expect(cpuWork({ models: [], vramGb: 2 })).toBe(false);
});
});
+
+describe("saved clips carry no metadata", () => {
+ const formats = metadataFormats(read("object_info.subset.json"));
+
+ it("new graphs save clips without their metadata, but for a list that may only shrink", () => {
+ expect(metadataKept(catalog, formats)).toEqual(KEEPS_METADATA);
+ });
+
+ it("a save node keeps metadata unless told not to, in the formats that write it", () => {
+ expect(formats?.has("video/h264-mp4")).toBe(true);
+ expect(formats?.has("video/ProRes")).toBe(false);
+ const one = (inputs: Record<string, unknown>) => ({ graphs: { "a.json": { "1": { class_type: "VHS_VideoCombine", inputs } } }, manifest: { workflows: [{ id: "a", file: "a.json" }] } });
+ expect(metadataKept(one({ format: "video/h264-mp4", save_metadata: true }), formats)).toEqual(["a"]);
+ expect(metadataKept(one({ format: "video/h264-mp4" }), formats)).toEqual(["a"]);
+ expect(metadataKept(one({ format: "video/h264-mp4", save_metadata: false }), formats)).toEqual([]);
+ expect(metadataKept(one({ format: "video/ProRes" }), formats)).toEqual([]);
+ expect(metadataKept(one({ format: "video/ProRes" }))).toEqual(["a"]);
+ });
+});
diff --git a/workflows/comfyui/first-run-files.json b/workflows/comfyui/first-run-files.json
new file mode 100644
index 00000000..6357a41a
--- /dev/null
+++ b/workflows/comfyui/first-run-files.json
@@ -0,0 +1,4 @@
+{
+ "about": "Files a node fetches by itself the first time it runs: the workflows with autoDownloads in scripts/comfy/library.spec.mjs. Each file is listed with its pin, so it can be put in place on a machine before the workflow runs there: path (under the ComfyUI folder), url (at a fixed revision), sizeBytes and sha256. Kept by hand (docs/adding-a-model.md); tests/adding-a-model.test.ts checks it.",
+ "workflows": {}
+}