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
Workers: every input that names a file, a download or code keeps to a rule
Adarshc7dff1919f47
diff --git a/bin/lib/worker/checks.mjs b/bin/lib/worker/checks.mjsindex 4b01745b..e6b0600d 100644--- a/bin/lib/worker/checks.mjs+++ b/bin/lib/worker/checks.mjs@@ -2,12 +2,14 @@//// 1. Every node type is on the allowlist built into this worker (dist/allowed-nodes.json), plus a file the PC's owner// passes with --allow-nodes. The studio can never add to it: a studio taken over can't run new code on this PC.-// 2. Every file the graph reads was sent with the job (the shared runner's graphProblem does this one).-// 3. No string input names a path: an absolute path, a drive letter, a network share, or a ".." step.-// 4. Every model file the graph names is one this worker verified (its inventory).+// 2. Every file the graph reads was sent with the job (the shared runner's graphProblem, and the input-file rule).+// 3. Every input keeps to its rule (dist/input-rules.json, see rules.mjs), and no link from another node reaches an+// input that has one. Inputs with no rule that don't take free text hold no path (the second layer).+// 4. Every model file the graph names is one this worker verified (its inventory), by its exact name.import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";+import { inputProblem, verifiedIndex } from "./rules.mjs";const here = path.dirname(fileURLToPath(import.meta.url));@@ -17,28 +19,38 @@ export function allowedNodes(extraFile) {return new Set([...built, ...(Array.isArray(extra) ? extra : (extra.nodes ?? []))]);}-const PATHLIKE = [/^[A-Za-z]:[\\/]/, /^\\\\/, /^\/(?!\/)[^\s]*\//, /(^|[\\/])\.\.([\\/]|$)/, /^~[\\/]/];-const MODEL = /\.(safetensors|gguf|ckpt|pt|pth|bin|sft)$/i;+/** The input rules built into this worker. Throws when they aren't built: the worker never runs without them. */+export function inputRules(file = path.join(here, "dist", "input-rules.json")) {+ const r = JSON.parse(fs.readFileSync(file, "utf8"));+ if (!r || typeof r.inputs !== "object") throw new Error("The worker's input rules are unreadable. Run: node scripts/build-worker.mjs");+ return r;+}-/** The first problem with a job's graph for this worker, or null. */-export function vetGraph(graph, allowed, verified) {- for (const node of Object.values(graph ?? {})) {- if (!node || typeof node.class_type !== "string" || !allowed.has(node.class_type)) return "unknown-node";- }- for (const node of Object.values(graph)) {- for (const v of Object.values(node.inputs ?? {})) {- if (typeof v !== "string") continue;- if (PATHLIKE.some((r) => r.test(v))) return "unsafe-path";- }+/**+ * The first problem with a job's graph for this worker, or null: { reason, node, cls, input }. The reason is+ * "unknown-node", "unsafe-path" (an input outside its rule, a link into a ruled input, or a path) or "model-unverified".+ * `o`: { rules, staged } (the built rules, and the names of the files this job sent).+ */+export function graphCheck(graph, allowed, verified, o = {}) {+ for (const [id, node] of Object.entries(graph ?? {})) {+ if (!node || typeof node.class_type !== "string" || !allowed.has(node.class_type)) return { reason: "unknown-node", node: id, cls: typeof node?.class_type === "string" ? node.class_type : null, input: null };}- for (const node of Object.values(graph)) {- for (const v of Object.values(node.inputs ?? {})) {- if (typeof v !== "string" || !MODEL.test(v)) continue;- const name = v.replace(/\\/g, "/");- if (!verified.has(name) && !verified.has(name.split("/").pop())) return "model-unverified";+ const ctx = { rules: o.rules ?? null, staged: o.staged ?? [], byName: verifiedIndex(verified) };+ let unverified = null;+ for (const [id, node] of Object.entries(graph)) {+ const inputs = node.inputs && typeof node.inputs === "object" ? node.inputs : {};+ for (const [input, v] of Object.entries(inputs)) {+ const reason = inputProblem(node.class_type, input, v, ctx);+ if (reason === "unsafe-path") return { reason, node: id, cls: node.class_type, input };+ if (reason && !unverified) unverified = { reason, node: id, cls: node.class_type, input };}}- return null;+ return unverified;+}++/** The first problem with a job's graph for this worker (its reason), or null. */+export function vetGraph(graph, allowed, verified, o = {}) {+ return graphCheck(graph, allowed, verified, o)?.reason ?? null;}/** Delete everything in the worker's own input, output and temp folders (at start: whatever a crash left). */diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjsindex e570b986..40868f1b 100644--- a/bin/lib/worker/index.mjs+++ b/bin/lib/worker/index.mjs@@ -30,7 +30,7 @@ export async function worker(args, io) {io.stderr.write("This worker isn't set up yet. Run: fuobe worker setup\n");return 2;}- if (!fs.existsSync(path.join(here, "dist", "computer-runner.mjs"))) {+ if (!["computer-runner.mjs", "allowed-nodes.json", "input-rules.json"].every((f) => fs.existsSync(path.join(here, "dist", f)))) {io.stderr.write("The worker's shared parts aren't built. Run: node scripts/build-worker.mjs\n");return 2;}diff --git a/bin/lib/worker/rules.mjs b/bin/lib/worker/rules.mjsnew file mode 100644index 00000000..f1a4ad3a--- /dev/null+++ b/bin/lib/worker/rules.mjs@@ -0,0 +1,169 @@+// The worker's input rules (docs/gpu-workers.md): what each node input may hold. scripts/build-worker.mjs derives a+// rule for every input that could name a file, a folder, a download or code from the studio's catalog, and writes them+// to dist/input-rules.json. The studio can't change them: a studio taken over can't make this worker read or write+// files, fetch anything, or run new code through a node it allows.+//+// A rule is one of:+// { kind: "literal", value } the catalog's one value+// { kind: "enum", values } one of the catalog's values+// { kind: "range", min, max, integer } a number from min to max+// { kind: "input-file" } a file this job sent, under the name the studio gave it+// { kind: "output-name" } a save name the studio makes: plain name parts, no path+// { kind: "model-file", folders } a model file this worker verified (in one of those model folders)+// Every ruled input takes a value written in the graph, never a link from another node.++/** Input names that name a file, a folder or an address. */+export const PATH_WORDS = new Set(["path", "paths", "file", "files", "filename", "filenames", "filepath", "pathname", "fname", "dir", "dirs", "directory", "folder", "folders", "subfolder", "url", "urls", "uri", "location"]);++/** The words of an input name: output_path → output, path; videoPath → video, path. */+export const nameWords = (name) =>+ String(name)+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter(Boolean);++/** Is this input named for a file, a folder or an address? */+export const pathNamed = (name) => nameWords(name).some((w) => PATH_WORDS.has(w));++/** Loader classes whose input names a file in the input folder (as the shared runner's graphProblem sees them). */+export const loaderInput = (cls, input) => (cls === "AUSBOSS_NODES_ImageCropRotatePad" && input === "image") || (/^(Load|VHS_Load)/.test(cls) && /image|video|audio|file|path|directory/i.test(input));++/** Inputs that take free text (prompts, lyrics, captions, expressions): the path check doesn't read them. */+export const TEXT_NAME = /^(text|texts|prompt|prompts|positive|negative|caption|captions|lyrics|tags|style|instruct|instruction|hints|string|string_[a-z]|value|expression)$|^(.+_)?(prompt|text|description|caption|instruction)$|^values\.[a-z0-9_]+$/i;++/** File names that hold weights (or pickled code). */+export const MODEL_EXT = /\.(safetensors|gguf|ckpt|pt|pth|bin|sft|onnx|pkl|pickle)$/i;++/** A save name the studio makes: name parts of letters, digits, "_", "-" and ".", joined by "/"; no "..". */+const OUTPUT_NAME = /^(?!.*\.\.)[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}(\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}){0,7}$/;++const DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)(\..*)?$/i;++/** A link from another node's output: ["node id", output index]. */+export const isLink = (v) => Array.isArray(v);++/**+ * The second layer: a value written into an input that has no rule and doesn't take free text. "unsafe-path", or null.+ *+ * A name (no spaces) is refused with a ":" (a drive, a scheme, a stream), "%" or "~" (some nodes expand them), or "..".+ * Any value is refused that starts like a path (a leading "/", "\" or "~", or a drive such as "C:"), holds an address+ * ("://"), a drive path ("C:\" after a space), an encoded or variable part ("%2e", "%TEMP%"), a ".." step, a NUL, or a+ * Windows device name (CON, NUL, COM1…) as any part of a path. Words with spaces (a plan's roles, say) are read only+ * for those path shapes, so "Scene 2: 50% faster" stays as it is.+ */+export function pathProblem(v) {+ if (typeof v !== "string" || v === "") return null;+ if (/\0/.test(v) || /^[\\/~]/.test(v) || /^[A-Za-z]:/.test(v) || v.includes("://")) return "unsafe-path";+ if (/(^|\s)[A-Za-z]:[\\/]/.test(v) || /%[0-9A-Fa-f]{2}|%[A-Za-z_][A-Za-z0-9_]*%/.test(v) || /(^|[\\/])\.\.([\\/]|$)/.test(v)) return "unsafe-path";+ if (!/\s/.test(v) && (/[:%~]/.test(v) || v.includes(".."))) return "unsafe-path";+ if (v.split(/[\\/]/).some((part) => DEVICE.test(part.replace(/[. ]+$/, "")))) return "unsafe-path";+ return null;+}++/** The second layer on a value: a JSON object or list written as text (a node's settings) is read part by part. */+export function valueProblem(v) {+ if (typeof v === "string" && /^\s*[[{]/.test(v)) {+ try {+ const parsed = JSON.parse(v);+ if (parsed && typeof parsed === "object") {+ for (const s of strings(parsed)) if (pathProblem(s)) return "unsafe-path";+ return null;+ }+ } catch {}+ }+ return pathProblem(v);+}++const same = (a, b) => a === b || (typeof a === "object" && a !== null && typeof b === "object" && b !== null && JSON.stringify(a) === JSON.stringify(b));++/** Every string inside a value (a list or an object of settings), for the second layer. */+function* strings(v) {+ if (typeof v === "string") yield v;+ else if (Array.isArray(v)) for (const x of v) yield* strings(x);+ else if (v && typeof v === "object") for (const x of Object.values(v)) yield* strings(x);+}++/** The verified model files by name: name → the folders it was verified in. Takes {folder, name} or "folder/name". */+export function verifiedIndex(verified) {+ const byName = new Map();+ const add = (folder, name) => {+ const key = String(name).replace(/\\/g, "/");+ if (!byName.has(key)) byName.set(key, new Set());+ byName.get(key).add(folder);+ };+ for (const v of verified ?? []) {+ if (v && typeof v === "object") add(v.folder, v.name);+ else if (typeof v === "string") {+ const i = v.indexOf("/");+ if (i > 0) add(v.slice(0, i), v.slice(i + 1));+ else add("*", v);+ }+ }+ return byName;+}++/** Is this model name verified (in one of these folders, or in any when none are known)? The exact name, never its base name. */+function modelVerified(v, folders, byName) {+ const there = byName.get(v.replace(/\\/g, "/"));+ if (!there) return false;+ return !folders?.length || there.has("*") || folders.some((f) => there.has(f));+}++/** Does a value keep to its rule? "unsafe-path", "model-unverified", or null. */+export function ruleProblem(rule, v, ctx) {+ if (isLink(v)) return "unsafe-path";+ switch (rule.kind) {+ case "literal":+ return same(v, rule.value) ? null : "unsafe-path";+ case "enum":+ return rule.values.some((x) => same(v, x)) ? null : "unsafe-path";+ case "range":+ return typeof v === "number" && Number.isFinite(v) && v >= rule.min && v <= rule.max && (!rule.integer || Number.isInteger(v)) ? null : "unsafe-path";+ case "input-file": {+ const sent = (x) => typeof x === "string" && ctx.staged.includes(x.replace(/ \[input\]$/, ""));+ // Any Angle's saved 3D view: each picture a file this job sent, or empty; the camera only numbers.+ if (v && typeof v === "object") {+ return Object.entries(v).every(([k, x]) => (k === "camera_info" ? [...strings(x)].length === 0 : x === "" || x === null || sent(x))) ? null : "unsafe-path";+ }+ return sent(v) ? null : "unsafe-path";+ }+ case "output-name":+ return typeof v === "string" && OUTPUT_NAME.test(v) ? null : "unsafe-path";+ case "model-file":+ if (typeof v !== "string" || pathProblem(v)) return "unsafe-path";+ return !MODEL_EXT.test(v) || modelVerified(v, rule.folders, ctx.byName) ? null : "model-unverified";+ default:+ return "unsafe-path";+ }+}++/** The rule for an input: the built one, or the ones every worker knows (loaders' files, save names). */+export function ruleFor(rules, cls, input) {+ const built = rules?.inputs?.[cls]?.[input];+ if (built) return built;+ if (loaderInput(cls, input)) return { kind: "input-file" };+ if (input === "filename_prefix") return { kind: "output-name" };+ return null;+}++/**+ * The first problem with one input, or null. `ctx`: { rules, staged, byName }.+ * In order: its rule; a closed class's unknown input; free text; an unknown input named for a file; the second layer+ * and the model check on everything else.+ */+export function inputProblem(cls, input, v, ctx) {+ const rule = ruleFor(ctx.rules, cls, input);+ if (rule) return ruleProblem(rule, v, ctx);+ const closed = ctx.rules?.closed?.[cls];+ if (closed && !closed.includes(input)) return "unsafe-path";+ if (TEXT_NAME.test(input) || ctx.rules?.text?.[cls]?.includes(input)) return null;+ if (pathNamed(input) && (isLink(v) || (v !== "" && [...strings(v)].some((s) => s !== "")))) return "unsafe-path";+ if (isLink(v) && v.length === 2 && typeof v[0] === "string") return null;+ let worst = null;+ for (const s of strings(v)) {+ if (valueProblem(s)) return "unsafe-path";+ if (MODEL_EXT.test(s) && !modelVerified(s, null, ctx.byName)) worst = "model-unverified";+ }+ return worst;+}diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 45d33b4f..8df3b199 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -5,7 +5,7 @@ import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";-import { cleanJob, emptyFolders, allowedNodes, vetGraph } from "./checks.mjs";+import { allowedNodes, cleanJob, emptyFolders, graphCheck, inputRules } from "./checks.mjs";import { folders, OwnComfy, PortBusy } from "./comfy.mjs";import { PROTOCOL, readControl, writeControl, writeStatus } from "./config.mjs";import { GpuWatch, othersOf, readGpu } from "./gpu.mjs";@@ -40,7 +40,8 @@ export function localPause(control, gpu, comfyTrouble, now) {}/**- * Run until `signal` aborts. `deps`: { fetch, now, sleep, readGpu, log, home, requirements, ComputerRunner }.+ * Run until `signal` aborts. `deps`: { fetch, now, sleep, readGpu, log, home, requirements, ComputerRunner, rules }+ * (rules: the built input rules, read from dist/ when not given).*/export async function runWorker(cfg, deps) {const now = deps.now ?? Date.now;@@ -54,6 +55,7 @@ export async function runWorker(cfg, deps) {fs.mkdirSync(cfg.workDir, { recursive: true });emptyFolders(f);const allowed = allowedNodes(cfg.allowNodesFile);+ const rules = deps.rules ?? inputRules();const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [] });const gpu = new GpuWatch({ autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000, resumeBelowC: cfg.resumeBelowC ?? 75 });let comfyTrouble = null;@@ -76,7 +78,6 @@ export async function runWorker(cfg, deps) {invHash = inventoryHash(inv);}await scan();- const verified = () => new Set(inv.files.flatMap((x) => [x.name, `${x.folder}/${x.name}`]));const runner = new ComputerRunner({@@ -88,7 +89,12 @@ export async function runWorker(cfg, deps) {socket: typeof WebSocket === "function" ? (url) => new WebSocket(url) : undefined,now,sleep,- vet: (t) => vetGraph(t.graph, allowed, verified()),+ vet: (t) => {+ const problem = graphCheck(t.graph, allowed, inv.files, { rules, staged: (t.inputs ?? []).map((i) => i.name) });+ // Which node and input, for the PC's owner (never a value: those are someone's prompt or file).+ if (problem) log(`Refused job ${t.id}: ${problem.reason} at node ${problem.node}${problem.cls ? ` (${problem.cls}${problem.input ? `.${problem.input}` : ""})` : ""}.`);+ return problem?.reason ?? null;+ },ended: (t, phase) => {log(`Job ${t.id} ${phase}.`);return cleanJob(t, f, comfy.base, fetchFn);diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 1dcd64a5..ad8bbcb2 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -145,9 +145,24 @@ Before its ComfyUI gets a graph, the worker checks all of these. The studio cann1. Every node type is on the allowlist that is built into the worker (`bin/lib/worker/dist/allowed-nodes.json`, madeby `scripts/build-worker.mjs` from the catalog's workflows and the graph builders). For your own workflows, passa file with `allowNodesFile` in `worker.json`. The studio can never send a file like that.-2. Every file that the graph reads was sent with the job.-3. No string input names a path (an absolute path, a drive letter, a network share or a `..` step).-4. Every model file that the graph names is one that the worker verified.+2. Every file that the graph reads was sent with the job, under the name the studio gave it.+3. Every input keeps to its rule (`bin/lib/worker/dist/input-rules.json`). The build gives a rule to each input that+ could name a file, a folder, a download or code, from the values in the catalog's own workflows:+ - a fixed value, or one of a list (a subtitle node writes no file; a timeline node reads no clip by path; a format+ string, a download name and a save folder stay the catalog's);+ - a number range;+ - a file that this job sent;+ - a save name that the studio makes (plain name parts, no path);+ - a model file that the worker verified, in the model folder that its loader reads.++ No link from another node may reach an input that has a rule, so a value cannot be built from pieces. A node that+ has such an input takes only the inputs that the catalog gives it.+4. Inputs with no rule that do not take free text hold no path. A name is refused if it has a `:`, `%`, `~` or `..`.+ Any value is refused if it starts with `/`, `\`, `~` or a drive (`C:`), or if it holds an address (`://`), an+ encoded or variable part (`%2e`, `%TEMP%`), a `..` step or a Windows device name (`CON`, `NUL`, `COM1`…).+ Prompts, lyrics and captions keep any text.+5. Every model file that the graph names is one that the worker verified, by its exact name. A file with the same+ name in another folder does not count.After each job, the worker deletes the job's inputs and results from its folders and deletes the prompt from itsComfyUI's history. At start, it empties its folders.@@ -170,8 +185,9 @@ token on every call, so a revoked token stops at once.models }`.- `POST /api/gpu/computer/bench`: bench jobs for this worker only (none are defined yet). The times of every finishedjob also count: the last 20 jobs in each lane give the median and the 90th percentile.-- Reports, inputs and results work as they do for the browser. `failed` can also give `unknown-node`, `unsafe-path`- or `model-unverified` as the reason.+- Reports, inputs and results work as they do for the browser. `failed` can also give `unknown-node`, `unsafe-path` (a+ path, or an input outside its rule) or `model-unverified` as the reason. The worker's own log names the node and the+ input, never the value.Each worker counts against its own rate limits, so three workers that beat every 5 seconds never hold each other up.@@ -192,7 +208,10 @@ routes.## Tests-- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`)+- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`,+ `tests/worker-input-rules.test.ts`, `tests/worker-environment.test.ts`). The input-rule tests send graphs that try to+ write or read files outside the worker's folders, and check that the worker refuses them. They also prepare every+ catalog workflow the way the studio does, and check that the worker accepts each one.- `node tests/e2e/worker.mjs` and `node tests/e2e/fuobe-connect.mjs` (after `pnpm build`, or with `E2E_DEV=1`). Theseuse a stand-in ComfyUI and a stand-in `nvidia-smi` on ports 3361 and 3362. They never touch a real GPU or ComfyUI.- `python -m unittest discover -s tests` in `integrations/fuobe-connect`diff --git a/scripts/build-worker.mjs b/scripts/build-worker.mjsindex 436b9b64..d91de2c9 100644--- a/scripts/build-worker.mjs+++ b/scripts/build-worker.mjs@@ -3,12 +3,16 @@// - the job runner the browser uses (src/lib/computer-runner.ts and its helpers), transpiled to plain .mjs with the// typescript dev dependency, relative imports rewritten to .mjs;// - allowed-nodes.json: every node type the studio's workflows and graph builders use, frozen into the worker. The-// studio can't add to it; a worker refuses a graph with any other node.+// studio can't add to it; a worker refuses a graph with any other node;+// - input-rules.json: a rule for each node input that could name a file, a folder, a download or code, from the+// catalog's own values (scripts/lib/worker-catalog.mjs). A worker refuses a value outside its rule, and a link+// into it.// `pnpm build` runs it first. No new dependency.import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import ts from "typescript";+import { allowedNodeList, 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");@@ -26,26 +30,13 @@ for (const name of SOURCES) {fs.writeFileSync(path.join(out, `${name}.mjs`), `// Built from src/lib/${name}.ts by scripts/build-worker.mjs. Don't edit.\n${js}`);}-// The node allowlist.-const index = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/requirements.json"), "utf8"));-const nodes = new Set();-for (const wf of Object.values(index.workflows)) {- for (const c of wf.core) nodes.add(c);- for (const cs of Object.values(wf.packs)) for (const c of cs) nodes.add(c);-}-for (const f of fs.readdirSync(path.join(root, "workflows/comfyui"))) {- if (!f.endsWith(".json") || f === "requirements.json" || f === "manifest.json") continue;- try {- const g = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui", f), "utf8"));- for (const n of Object.values(g)) if (n && typeof n === "object" && typeof n.class_type === "string") nodes.add(n.class_type);- } catch {}-}-// What the graph builders add on their own (LoRA loaders, video joins, overlays…).-const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : /\.tsx?$/.test(e.name) ? [path.join(dir, e.name)] : []));-for (const file of [...walk(path.join(root, "src/lib")), ...walk(path.join(root, "src/server"))]) {- for (const m of fs.readFileSync(file, "utf8").matchAll(/class_type: "([^"]+)"/g)) nodes.add(m[1]);-}-for (const extra of ["LoraLoader", "LoraLoaderModelOnly"]) nodes.add(extra);-const list = [...nodes].sort();-fs.writeFileSync(path.join(out, "allowed-nodes.json"), `${JSON.stringify({ built: "scripts/build-worker.mjs", nodes: list }, null, 1)}\n`);-console.log(`worker: ${SOURCES.length} modules, ${list.length} allowed node types -> ${path.relative(root, out)}`);+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 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 -> ${path.relative(root, out)}`);diff --git a/scripts/lib/worker-catalog.mjs b/scripts/lib/worker-catalog.mjsnew file mode 100644index 00000000..757d433d--- /dev/null+++ b/scripts/lib/worker-catalog.mjs@@ -0,0 +1,187 @@+// What the worker program learns from the studio's catalog at build time (scripts/build-worker.mjs writes it into+// bin/lib/worker/dist/). Pure apart from reading the catalog's files, so the tests derive the same rules in memory.+//+// - allowedNodes: every node type the catalog's workflows and the graph builders use.+// - inputRules: a rule for each node input that could name a file, a folder, a download or code, taken from the+// catalog's own values. The worker refuses a value outside its rule, and a link from another node into it.+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"]);++/** The catalog: its workflow graphs by file name, its manifest and its requirement index. */+export function readCatalog(root) {+ const 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()) {+ if (!f.endsWith(".json") || SKIP.has(f)) continue;+ try {+ graphs[f] = read(f);+ } catch {}+ }+ return { graphs, manifest: read("manifest.json"), requirements: read("requirements.json") };+}++const nodesOf = (graph) => Object.entries(graph ?? {}).filter(([, n]) => n && typeof n === "object" && typeof n.class_type === "string");++/** Every source file of the graph builders (they add nodes of their own: LoRA loaders, joins, overlays…). */+function builderSources(root) {+ const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : /\.tsx?$/.test(e.name) ? [path.join(dir, e.name)] : []));+ return [...walk(path.join(root, "src/lib")), ...walk(path.join(root, "src/server"))];+}++/** The node allowlist: the catalog's node types, the ones the graph builders add, and the LoRA loaders. */+export function allowedNodeList(root, catalog = readCatalog(root)) {+ const nodes = new Set();+ for (const wf of Object.values(catalog.requirements.workflows ?? {})) {+ for (const c of wf.core ?? []) nodes.add(c);+ for (const cs of Object.values(wf.packs ?? {})) for (const c of cs) nodes.add(c);+ }+ for (const g of Object.values(catalog.graphs)) for (const [, n] of nodesOf(g)) nodes.add(n.class_type);+ for (const file of builderSources(root)) for (const m of fs.readFileSync(file, "utf8").matchAll(/class_type: "([^"]+)"/g)) nodes.add(m[1]);+ for (const extra of ["LoraLoader", "LoraLoaderModelOnly"]) nodes.add(extra);+ return [...nodes].sort();+}++// ---------------------------------------------------------------------------+// Input rules (their kinds, and how the worker reads them: bin/lib/worker/rules.mjs)++/** Manifest bindings that name a file the job sends, and the ones that name a model file. */+const MEDIA_BINDING = /^(image\d*|endImage|mask|prevMask|paletteImage|video\d*|historyVideo|audio\d*|splatFile|fadeCurve)$/;+const MODEL_BINDING = /^(checkpoint|unet|vae|lora|loraHigh|loraLow|upscaleModel)$/;++/** Inputs held to the catalog's values whatever their name: a format string, and whether a node writes a file. */+const ALWAYS_PINNED = { StringFormat: ["f_string"], AILab_Qwen3ASRSubtitle: ["output_format"] };++const isLink = (v) => Array.isArray(v);+/** A path or a download id ("org/name"): no spaces, and a slash. */+const looksLikePath = (v) => typeof v === "string" && !/\s/.test(v) && /[\\/]/.test(v);++/** Sort key for values of mixed types (so the built file is stable). */+const valueKey = (v) => `${typeof v}:${JSON.stringify(v)}`;++/**+ * The rules, from the catalog alone: { inputs: { class: { input: rule } }, text: { class: [input] }, closed: { class:+ * [input] } }. "text": inputs that take free text or a value the studio fills per run (the second layer skips them).+ * "closed": classes with an input pinned for naming a file or holding code; each takes only the inputs listed.+ */+export function inputRules(catalog) {+ const pairs = new Map();+ const pair = (cls, input) => {+ const key = `${cls}\u0000${input}`;+ let p = pairs.get(key);+ if (!p) pairs.set(key, (p = { cls, input, literals: new Map(), links: 0, bindings: new Set(), defaults: new Map(), folders: new Set() }));+ return p;+ };+ // Every value the catalog's graphs write, and every link.+ for (const g of Object.values(catalog.graphs)) {+ for (const [, n] of nodesOf(g)) {+ for (const [input, v] of Object.entries(n.inputs ?? {})) {+ const p = pair(n.class_type, input);+ if (isLink(v)) p.links++;+ else p.literals.set(valueKey(v), v);+ }+ }+ }+ // What the manifest binds: which inputs the studio fills per run, and with what (and their defaults).+ for (const w of catalog.manifest.workflows ?? []) {+ const g = catalog.graphs[w.file];+ if (!g) continue;+ for (const [b, targets] of Object.entries(w.bindings ?? {})) {+ for (const t of targets) {+ const n = g[t.node];+ if (!n || typeof n.class_type !== "string") continue;+ const p = pair(n.class_type, t.input);+ p.bindings.add(b);+ const d = w.defaults?.[b];+ if (d !== undefined && d !== null && typeof d !== "object") p.defaults.set(valueKey(d), d);+ }+ }+ }+ // Which model folders each loader input reads.+ for (const f of Object.values(catalog.requirements.files ?? {})) {+ for (const [cls, input] of f.loaders ?? []) pair(cls, input).folders.add(f.folder);+ }++ const inputs = {};+ const text = {};+ const closed = new Set();+ const set = (p, rule) => ((inputs[p.cls] ??= {})[p.input] = rule);+ const pinned = (p, extra = []) => {+ const values = [...new Map([...p.literals, ...extra.map((v) => [valueKey(v), v])]).values()].sort((a, b) => valueKey(a).localeCompare(valueKey(b)));+ return values.length === 1 ? { kind: "literal", value: values[0] } : { kind: "enum", values };+ };+ const addText = (p) => (text[p.cls] ??= []).push(p.input);+ const pin = (p, close) => {+ if (p.links) throw new Error(`${p.cls}.${p.input} names a file, a download or code, and the catalog links into it: give it a literal value`);+ set(p, pinned(p, [...p.defaults.values()]));+ if (close) closed.add(p.cls);+ };++ for (const p of pairs.values()) {+ const b = [...p.bindings];+ const lits = [...p.literals.values()];+ const strings = lits.filter((v) => typeof v === "string");+ // Named for a file or folder (a number or a switch never names one: path_precision is a precision).+ const named = pathNamed(p.input) && !(lits.length && !strings.length);+ // A file this job sent.+ if (loaderInput(p.cls, p.input) || b.some((x) => MEDIA_BINDING.test(x))) set(p, { kind: "input-file" });+ // A save name the studio makes.+ else if (p.input === "filename_prefix" || b.includes("filenamePrefix")) set(p, { kind: "output-name" });+ // A model file, by its name in a model folder.+ else if (!named && !strings.some(looksLikePath) && (p.folders.size || b.some((x) => MODEL_BINDING.test(x)) || strings.some((v) => MODEL_EXT.test(v) && !/\s/.test(v)))) {+ set(p, { kind: "model-file", folders: [...p.folders].sort() });+ }+ // Code, or an input named for a file or folder: the catalog's values only, and the class takes only the catalog's inputs.+ else if (ALWAYS_PINNED[p.cls]?.includes(p.input) || named) pin(p, true);+ // Prompts, captions, lyrics, expressions.+ else if (TEXT_NAME.test(p.input)) addText(p);+ // A value that is a path, a download (an org/name id) or anything else the second layer refuses: pinned. (A value+ // the studio fills per run is pinned only when it looks like a path or an id.)+ else if (b.length ? strings.some(looksLikePath) : strings.some((v) => looksLikePath(v) || (!/\s/.test(v) && valueProblem(v)))) pin(p, false);+ // Filled per run (a size, a seed, a language, a setting), or written as prose in the catalog.+ else if (b.length || strings.some((v) => /\s/.test(v))) addText(p);+ }++ // A closed class takes only the inputs the catalog gives it. Every other input the catalog writes as a literal is+ // held to the catalog's values too (they set what such a node reads, writes or keeps), unless the studio fills it+ // per run; a number to the catalog's range.+ const known = {};+ for (const p of pairs.values()) {+ if (!closed.has(p.cls)) continue;+ (known[p.cls] ??= []).push(p.input);+ if (inputs[p.cls]?.[p.input] || p.links || p.bindings.size) continue;+ const lits = [...p.literals.values()];+ if (!lits.length) continue;+ if (lits.every((v) => typeof v === "number")) {+ set(p, { kind: "range", min: Math.min(...lits), max: Math.max(...lits), integer: lits.every(Number.isInteger) });+ } else set(p, pinned(p));+ if (text[p.cls]) text[p.cls] = text[p.cls].filter((i) => i !== p.input);+ }++ const sortObj = (o) => Object.fromEntries(Object.keys(o).sort().map((k) => [k, o[k]]));+ const lists = (o) => sortObj(Object.fromEntries(Object.entries(o).map(([c, l]) => [c, [...new Set(l)].sort()])));+ return {+ inputs: sortObj(Object.fromEntries(Object.entries(inputs).map(([c, r]) => [c, sortObj(r)]))),+ text: lists(text),+ closed: lists(known),+ };+}++/** Inputs that must have a rule whenever their node is allowed: each writes or reads a file, or formats with code. */+export const REQUIRED_RULES = [+ ["AILab_Qwen3ASRSubtitle", "output_path"],+ ["AILab_Qwen3ASRSubtitle", "output_format"],+ ["MiniMaxH3SourceTimeline", "video_path"],+ ["MiniMaxH3SourceTimeline", "audio_path"],+ ["WanVideoImageToVideoMultiTalk", "output_path"],+ ["StringFormat", "f_string"],+];++/** The required inputs of allowed nodes that have no rule ("Class.input"); the build stops on any. */+export function missingRules(rules, allowed) {+ return REQUIRED_RULES.filter(([cls, input]) => allowed.includes(cls) && !rules.inputs[cls]?.[input]).map(([cls, input]) => `${cls}.${input}`);+}+diff --git a/tests/worker-environment.test.ts b/tests/worker-environment.test.tsindex 11cf1b16..871b7cee 100644--- a/tests/worker-environment.test.ts+++ b/tests/worker-environment.test.ts@@ -2,6 +2,7 @@ import fs from "node:fs";import net from "node:net";import path from "node:path";import { describe, expect, it } from "vitest";+import { inputRules } from "../bin/lib/worker/checks.mjs";import { comfyArgs, comfyEnv, OFFLINE_ENV, OwnComfy } from "../bin/lib/worker/comfy.mjs";import { nodePacks, packFolders } from "../bin/lib/worker/inventory.mjs";import { minVramBytesFor, needsOf, VRAM_TOLERANCE } from "@/lib/lanes";@@ -95,6 +96,12 @@ describe("its own ComfyUI's environment", () => {});});+describe("the worker's built rules", () => {+ it("must be there: a worker never runs without them", () => {+ expect(() => inputRules(path.join(tempDir("fuobe-worker-norules-"), "input-rules.json"))).toThrow();+ });+});+describe("VRAM: a card takes the lanes made for its size", () => {const index = {files: {},diff --git a/tests/worker-input-rules.test.ts b/tests/worker-input-rules.test.tsnew file mode 100644index 00000000..5d534bd4--- /dev/null+++ b/tests/worker-input-rules.test.ts@@ -0,0 +1,272 @@+import path from "node:path";+import { describe, expect, it } from "vitest";+import { graphCheck, vetGraph } from "../bin/lib/worker/checks.mjs";+import { loaderInput, pathProblem } from "../bin/lib/worker/rules.mjs";+import { allowedNodeList, inputRules, missingRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";+import { tempDir } from "./helpers/temp-dir";++process.env.FUOBE_DATA_DIR = tempDir("fuobe-worker-rules-");++type Node = { class_type: string; inputs: Record<string, unknown> };+type Graph = Record<string, Node>;++const root = path.resolve(__dirname, "..");+/** The catalog as the build reads it (its JSON, typed for the test). */+const catalog = readCatalog(root) as unknown as {+ graphs: Record<string, Graph>;+ manifest: { workflows: { id: string; file: string }[] };+ requirements: { files: Record<string, { folder: string; file: string }> };+};+const rules = inputRules(catalog);+const allowed = new Set(allowedNodeList(root, catalog));+const verified = Object.values(catalog.requirements.files as Record<string, { folder: string; file: string }>).map((f) => ({ folder: f.folder, name: f.file }));+const SENT = ["fuobe_abcdefgh01.png", "fuobe_abcdefgh02.wav", "fuobe_abcdefgh03.mp4"];+const check = (g: Graph, staged: string[] = SENT) => vetGraph(g, allowed, verified, { rules, staged });++/** The catalog's workflows (the manifest's graphs). */+const workflows = (catalog.manifest.workflows as { id: string; file: string }[]).filter((w) => catalog.graphs[w.file]);++/** The file names a graph's loaders read (in a test, the files "sent" with it). */+function loaderNames(g: Graph): string[] {+ const out: string[] = [];+ for (const n of Object.values(g)) {+ for (const [k, v] of Object.entries(n?.inputs ?? {})) {+ if (!loaderInput(n.class_type, k)) continue;+ if (typeof v === "string") out.push(v);+ else if (v && typeof v === "object" && !Array.isArray(v)) for (const x of Object.values(v)) if (typeof x === "string") out.push(x);+ }+ }+ return out;+}++// Graphs a studio taken over could send. Every node in them is on the allowlist.+const speech = { class_type: "LoadAudio", inputs: { audio: "fuobe_abcdefgh02.wav" } };+const concat = (a: string, b: string) => ({ class_type: "StringConcatenate", inputs: { string_a: a, string_b: b, delimiter: "" } });+const asr = (over: Record<string, unknown>) => ({+ class_type: "AILab_Qwen3ASRSubtitle",+ inputs: { audio: ["1", 0], model: "Qwen/Qwen3-ASR-0.6B-hf", precision: "bf16", attention: "auto", forced_aligner: "Qwen/Qwen3-ForcedAligner-0.6B-hf", language: "auto", hints: "", output_format: "none", output_path: "fuobe/captions", split_mode: "split_by_punctuation_or_pause_or_length", max_gap_sec: 0.6, max_chars: 32, max_inference_batch_size: 32, max_new_tokens: 256, normalize_text: true, unload_models: true, ...over },+});+const timeline = (over: Record<string, unknown>) => ({ class_type: "MiniMaxH3SourceTimeline", inputs: { video_path: "", audio_path: "", embedded_audio: "auto", skip_first_frames: 0, source_audio: ["1", 0], ...over } });++describe("the worker's input rules", () => {+ it("are built for the inputs that name files, downloads or code", () => {+ expect(rules.inputs.AILab_Qwen3ASRSubtitle.output_format).toEqual({ kind: "literal", value: "none" });+ expect(rules.inputs.AILab_Qwen3ASRSubtitle.output_path).toEqual({ kind: "enum", values: ["", "fuobe/captions"] });+ expect(rules.inputs.MiniMaxH3SourceTimeline.video_path).toEqual({ kind: "literal", value: "" });+ expect(rules.inputs.MiniMaxH3SourceTimeline.audio_path).toEqual({ kind: "literal", value: "" });+ expect(rules.inputs.WanVideoImageToVideoMultiTalk.output_path).toEqual({ kind: "literal", value: "" });+ expect(rules.inputs.StringFormat.f_string.kind).toBe("enum");+ expect(rules.inputs.LoadImage.image).toEqual({ kind: "input-file" });+ expect(rules.inputs.SaveVideo.filename_prefix).toEqual({ kind: "output-name" });+ expect(rules.inputs.UNETLoader.unet_name.kind).toBe("model-file");+ expect(rules.inputs.AILab_Qwen3ASRSubtitle.max_new_tokens).toEqual({ kind: "range", min: 256, max: 256, integer: true });+ // Prompts take free text: no rule.+ expect(rules.inputs.CLIPTextEncode?.text).toBeUndefined();+ expect(rules.text.CLIPTextEncode).toContain("text");+ // Each input that writes or reads a file, or formats with code, has its rule; the build stops without one.+ expect(missingRules(rules, [...allowed])).toEqual([]);+ expect(missingRules({ inputs: {} }, ["StringFormat", "KSampler"])).toEqual(["StringFormat.f_string"]);+ });++ it("every catalog workflow passes as the catalog has it", () => {+ const refused: string[] = [];+ for (const w of workflows) {+ const g = catalog.graphs[w.file] as Graph;+ const p = graphCheck(g, allowed, verified, { rules, staged: loaderNames(g) });+ if (p) refused.push(`${w.id}: ${p.reason} ${p.cls}.${p.input}`);+ }+ // A few name a file their node downloads, or a LoRA the run picks: no verified file is known for them (as before).+ expect(refused.every((r) => / model-unverified /.test(r)), refused.join("\n")).toBe(true);+ expect(refused.length).toBeLessThanOrEqual(4);+ });++ it("an allowed subtitle node can't write a file anywhere", () => {+ // A path built from text pieces, linked into the output path.+ const built: Graph = { "1": speech, "2": concat("C", ":\\Users\\x\\Start Menu\\Programs\\Startup\\x.bat"), "3": asr({ output_format: "srt", output_path: ["2", 0] }) };+ expect(check(built)).toBe("unsafe-path");+ // Written straight in, in each form the old check missed.+ for (const p of ["C:Users\\x\\x.bat", "\\Users\\x\\x.bat", "/x.bat", "//host/share/x", "output/x.srt", "x.bat"]) {+ expect(check({ "1": speech, "3": asr({ output_format: "srt", output_path: p }) }), p).toBe("unsafe-path");+ }+ // A file format other than none.+ expect(check({ "1": speech, "3": asr({ output_format: "srt" }) })).toBe("unsafe-path");+ // An input the catalog never gives it.+ expect(check({ "1": speech, "3": asr({ save_path: "x" }) })).toBe("unsafe-path");+ // As the catalog has it: passes.+ expect(check({ "1": speech, "3": asr({}) })).toBeNull();+ });++ it("an allowed timeline node can't read a clip from anywhere", () => {+ for (const p of ["C:Users\\x\\Videos\\private.mp4", "\\Users\\x\\v.mp4", "output/render.mp4", "//host/share/v.mp4", "~/v.mp4", "v.mp4"]) {+ expect(check({ "1": speech, "2": timeline({ video_path: p }) }), p).toBe("unsafe-path");+ expect(check({ "1": speech, "2": timeline({ audio_path: p }) }), p).toBe("unsafe-path");+ }+ expect(check({ "1": speech, "3": concat("out", "put/v.mp4"), "2": timeline({ video_path: ["3", 0] }) })).toBe("unsafe-path");+ expect(check({ "1": speech, "2": timeline({}) })).toBeNull();+ });++ it("refuses every other form of a path, and links into inputs that have a rule", () => {+ const missed = ["C:Users\\x", "\\Users\\x", "/Program Files/x", "/x.bat", "//host/share/x", "file:///C:/x", "http://h/x", "%2e%2e/x", "a.png:ads", "CON", "NUL.txt", "x/aux.txt", "~user/x", "\\/host/share", "/\\host\\share", "..\\x"];+ for (const p of missed) expect(pathProblem(p), p).toBe("unsafe-path");+ // An input with no rule that takes no free text: the second layer.+ for (const p of missed) expect(check({ "1": { class_type: "ImageScale", inputs: { upscale_method: p } } }), p).toBe("unsafe-path");+ // A loader: only a file this job sent, never a link.+ for (const p of [...missed, "output/x.mp4", "input.mp4"]) expect(check({ "1": { class_type: "LoadVideo", inputs: { file: p } } }), p).toBe("unsafe-path");+ expect(check({ "1": concat("fuobe_abcdefgh03", ".mp4"), "2": { class_type: "LoadVideo", inputs: { file: ["1", 0] } } })).toBe("unsafe-path");+ expect(check({ "1": { class_type: "LoadVideo", inputs: { file: "fuobe_abcdefgh03.mp4" } } })).toBeNull();+ expect(check({ "1": { class_type: "LoadVideo", inputs: { file: "fuobe_abcdefgh03.mp4 [input]" } } })).toBeNull();+ // The multi-talk node's output path, and a save name.+ const talk = { class_type: "WanVideoImageToVideoMultiTalk", inputs: { width: 832, height: 480, frame_window_size: 81, motion_frame: 9, force_offload: false, colormatch: "disabled", tiled_vae: false, mode: "infinitetalk", output_path: "C:x" } };+ expect(check({ "1": talk })).toBe("unsafe-path");+ for (const p of ["../x", "/x", "C:/x", "x/../../y", "fuobe/%date%"]) expect(check({ "1": { class_type: "SaveImage", inputs: { images: ["2", 0], filename_prefix: p } } }), p).toBe("unsafe-path");+ expect(check({ "1": { class_type: "SaveImage", inputs: { images: ["2", 0], filename_prefix: "fuobe/gen-1_a" } } })).toBeNull();+ });++ it("a format string stays the catalog's (no walk into the environment)", () => {+ const walk = { class_type: "StringFormat", inputs: { "values.a": ["9", 0], f_string: "{a.__init__.__globals__[os].environ}" } };+ expect(check({ "9": { class_type: "VAELoader", inputs: { vae_name: "ae.safetensors" } }, "1": walk })).toBe("unsafe-path");+ expect(check({ "1": { class_type: "StringFormat", inputs: { "values.a": "a fox: running", f_string: "{a} Keep everything else exactly the same." } } })).toBeNull();+ });++ it("a model by its exact name only, in its own folder; never a link", () => {+ expect(check({ "1": { class_type: "UNETLoader", inputs: { unet_name: "flux1-dev.safetensors", weight_dtype: "default" } } })).toBeNull();+ // The base name of a verified file under another folder no longer passes.+ expect(check({ "1": { class_type: "UNETLoader", inputs: { unet_name: "anyfolder/flux1-dev.safetensors", weight_dtype: "default" } } })).toBe("model-unverified");+ // A verified name, but in a folder that loader doesn't read.+ expect(check({ "1": { class_type: "UNETLoader", inputs: { unet_name: "ae.safetensors", weight_dtype: "default" } } })).toBe("model-unverified");+ expect(check({ "2": concat("flux1-dev", ".safetensors"), "1": { class_type: "UNETLoader", inputs: { unet_name: ["2", 0], weight_dtype: "default" } } })).toBe("unsafe-path");+ expect(check({ "1": { class_type: "UNETLoader", inputs: { unet_name: "C:x.safetensors", weight_dtype: "default" } } })).toBe("unsafe-path");+ });++ it("downloads stay the catalog's: no other repository id", () => {+ expect(check({ "1": speech, "3": asr({ model: "someone/other-model" }) })).toBe("unsafe-path");+ expect(check({ "1": speech, "3": asr({ model: "Qwen/Qwen3-ASR-1.7B-hf" }) })).toBeNull();+ });++ it("numbers stay in their range", () => {+ expect(check({ "1": speech, "3": asr({ max_new_tokens: 1e9 }) })).toBe("unsafe-path");+ expect(check({ "1": speech, "3": asr({ max_new_tokens: "256" }) })).toBe("unsafe-path");+ });++ it("prompts keep any text", () => {+ const text = "Scene 2: 50% off, wait.. C:/ isn't a path here ~ http://x";+ expect(check({ "1": { class_type: "CLIPTextEncode", inputs: { text, clip: ["2", 0] } } })).toBeNull();+ expect(check({ "1": { class_type: "StringConcatenate", inputs: { string_a: text, string_b: text, delimiter: "" } } })).toBeNull();+ });+});++describe("graphs as the studio builds them", () => {+ // The clips' headers, as the studio reads them from an upload.+ const media = (name: string) =>+ /\.mp4$/.test(name)+ ? { container: "mp4", hasVideo: true, hasAudio: true, duration: 6, videoDuration: 6, width: 640, height: 360, fps: 30, frames: 180 }+ : /\.wav$/.test(name)+ ? { container: "wav", hasVideo: false, hasAudio: true, duration: 10 }+ : undefined;++ it("every catalog workflow, prepared for a run, passes the worker's rules", async () => {+ const { prepareWorkflow } = await import("@/server/providers/comfyui");+ const { MODELS } = await import("@/lib/catalog");+ const opFor = (id: string) => MODELS.flatMap((m) => m.routes).find((r) => r.provider === "comfyui" && r.endpoint === id)?.op ?? "t2i";+ const given = ["fuobe_given00001.png", "fuobe_given00002.png", "fuobe_given00003.mp4", "fuobe_given00004.wav", "fuobe_given00005.wav", "fuobe_given00006.png", "fuobe_given00007.mp4"];+ let prepared = 0;+ const refused: string[] = [];+ for (const w of workflows) {+ const uploads: string[] = [];+ const input = {+ prompt: "Scene 2: a fox at 50% speed, wait.. then ~ calm",+ negativePrompt: "blurry",+ images: [given[0], given[1]],+ endImage: given[1],+ mask: given[5],+ video: given[2],+ videos: [given[2], given[6]],+ audio: given[3],+ audios: [given[3], given[4]],+ palette: ["#112233", "#445566"],+ targetLanguage: "German (de)",+ sourceLanguage: "de",+ startTime: 1,+ endTime: 3,+ numLayers: 3,+ aspectRatio: "16:9",+ seed: 7,+ extra: { audio2: given[4] },+ };+ let graph: Graph;+ try {+ const res = await prepareWorkflow(w.id, input as never, {+ generationId: "gen1",+ op: opFor(w.id) as never,+ upload: async (_d, _t, name) => {+ const n = `fuobe_up${String(uploads.length).padStart(6, "0")}.${name.split(".").pop() ?? "bin"}`;+ uploads.push(n);+ return n;+ },+ media: media as never,+ });+ graph = res.workflow as Graph;+ } catch {+ continue; // a workflow this input doesn't fit (another op, a missing setting): the server refuses it before any worker+ }+ prepared++;+ const p = graphCheck(graph, allowed, verified, { rules, staged: [...given, ...uploads, ...loaderNames(catalog.graphs[w.file] as Graph)] });+ if (p && p.reason !== "model-unverified") refused.push(`${w.id}: ${p.reason} ${p.cls}.${p.input} = ${JSON.stringify(graph[p.node]?.inputs?.[p.input ?? ""])?.slice(0, 80)}`);+ }+ expect(refused, refused.join("\n")).toEqual([]);+ expect(prepared).toBeGreaterThan(workflows.length * 0.9);+ }, 120_000);++ it("the graph builders' own nodes pass too (swaps, scene edits, joins, keyframes, finishes)", async () => {+ const { prepareWorkflow } = await import("@/server/providers/comfyui");+ const { OPENJUTSU_WORKFLOWS: W } = await import("@/lib/openjutsu-graphs");+ const a = "fuobe_given00001.png";+ const b = "fuobe_given00002.png";+ const clip = "fuobe_given00003.mp4";+ const runs: [string, Record<string, unknown>, string][] = [+ [W.group, { video: clip, images: [a, b], seed: 11, extra: { openjutsu: { pictures: 2, roles: ["the person on the left", "the person on the right"], quality: "720p", edge: "tight" } } }, "group-swap"],+ [W.group, { video: clip, images: [a, b], extra: { openjutsu: { pictures: 2, onePerPerson: true } } }, "group-swap"],+ [W.scene, { video: clip, extra: { openjutsu: { action: "remove", target: "the handbag" } } }, "scene-edit"],+ [W.scene, { video: clip, images: [a], extra: { openjutsu: { action: "background", target: "the people", becomes: "an Amalfi terrace", picture: true } } }, "scene-edit"],+ [W.prepare, { video: clip, images: [a], startTime: 2, extra: { openjutsu: { light: "Light it: warm, 50% softer." } } }, "picture-frame"],+ [W.h3, { video: clip, images: [a], extra: { openjutsu: {} } }, "from-picture"],+ [W.motionH3, { video: clip, images: [a], extra: { openjutsu: {} } }, "motion-transfer"],+ [W.faces, { video: clip, images: [a], extra: { openjutsu: {} } }, "fix-faces"],+ [W.colours, { video: clip, extra: { openjutsu: { finish: "filmic", strength: 0.4, soften: 0.3 } } }, "fix-colours"],+ ["audio-join-crossfade", { audios: ["fuobe_given00004.wav", "fuobe_given00005.wav", "fuobe_given00006.wav"], crossfade: 1 }, "audio-join"],+ ["video-concat-encoded", { videos: ["fuobe_given00007.mp4", "fuobe_given00008.mp4", "fuobe_given00009.mp4"] }, "concat"],+ ["wan22-flf2v-14b", { images: [a], endImage: b, duration: 3 }, "flf2v"],+ ["kenburns-still", { images: [a], aspectRatio: "9:16", resolution: "480p", duration: 7, easing: "linear" }, "still-motion"],+ ];+ let prepared = 0;+ const refused: string[] = [];+ const failed: string[] = [];+ for (const [id, input, op] of runs) {+ const uploads: string[] = [];+ let graph: Graph;+ try {+ const res = await prepareWorkflow(id, input as never, {+ generationId: "gen1",+ op: op as never,+ upload: async (_d, _t, name) => {+ const n = `fuobe_up${String(uploads.length).padStart(6, "0")}.${name.split(".").pop() ?? "bin"}`;+ uploads.push(n);+ return n;+ },+ media: media as never,+ });+ graph = res.workflow as Graph;+ } catch (e) {+ failed.push(`${id}: ${(e as Error).message}`);+ continue;+ }+ prepared++;+ const sent = [...JSON.stringify(input).matchAll(/fuobe_given\d+\.\w+/g)].map((m) => m[0]);+ const p = graphCheck(graph, allowed, verified, { rules, staged: [...sent, ...uploads] });+ if (p && p.reason !== "model-unverified") refused.push(`${id}: ${p.reason} ${p.cls}.${p.input} = ${JSON.stringify(graph[p.node]?.inputs?.[p.input ?? ""])?.slice(0, 80)}`);+ }+ expect(refused, refused.join("\n")).toEqual([]);+ expect(failed, failed.join("\n")).toEqual([]);+ expect(prepared).toBe(runs.length);+ }, 120_000);+});