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
Model checks: one list of unpinned files, text inputs read for paths, and worker parts stamped with their checkout
Adarshd72b3f4789bc
diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjsindex 8ff5490d..caa0db40 100644--- a/bin/lib/worker/index.mjs+++ b/bin/lib/worker/index.mjs@@ -39,10 +39,17 @@ export async function worker(args, io) {io.stderr.write("This worker isn't set up yet. Run: fuobe worker setup\n");return 2;}- if (!["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json"].every((f) => fs.existsSync(path.join(here, "dist", f)))) {+ const dist = io.distDir ?? path.join(here, "dist");+ if (!["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json"].every((f) => fs.existsSync(path.join(dist, f)))) {io.stderr.write("The worker's shared parts aren't built. Run: node scripts/build-worker.mjs\n");return 2;}+ // Parts built from other files than this checkout (an update whose build didn't run) are never used.+ const { distProblem } = await import("./stamp.mjs");+ if (distProblem(io.rootDir ?? path.resolve(here, "../../.."), dist)) {+ io.stderr.write("The worker's shared parts were built from other files than this checkout. Run: node scripts/build-worker.mjs\n");+ return 2;+ }const { runWorker, siteProblem, withoutOldPort } = await import("./run.mjs");const problem = siteProblem(cfg.site, cfg);if (problem) {diff --git a/bin/lib/worker/rules.mjs b/bin/lib/worker/rules.mjsindex f1a4ad3a..f7d97ace 100644--- a/bin/lib/worker/rules.mjs+++ b/bin/lib/worker/rules.mjs@@ -9,7 +9,8 @@// { 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)+// { kind: "model-file", folders, plain? } a model file this worker verified (in one of those model folders), or+// one of the catalog's own values that name no file ("plain")// 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. */@@ -29,11 +30,14 @@ 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;+/**+ * Inputs that take free text (prompts, lyrics, captions, expressions, and the prompts that a text encoder takes for+ * each of its encoders: clip_l, clip_g, t5xxl): 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|clip_l|clip_g|t5xxl)$|^(.+_)?(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;+export const MODEL_EXT = /\.(safetensors|gguf|ckpt|pt|pt2|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}$/;@@ -75,6 +79,63 @@ export function valueProblem(v) {return pathProblem(v);}+/** A ".." step in a path. */+const DOT_DOT = /(^|[\\/])\.\.([\\/]|$)/;+/** A variable some nodes expand ("%TEMP%", "$HOME", "${HOME}"). */+const VARIABLE = /%[A-Za-z_][A-Za-z0-9_]*%|\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/;+/**+ * Path shapes that words with spaces never take: a drive path, a share, a rooted path with two parts, a home path, a+ * ".." step (at the start of a word too).+ */+const PATH_IN_WORDS = [/^[A-Za-z]:[\\/]/, /^[\\/]{2}[^\\/\s]/, /^\/[^\s/]+\//, /^~[\\/]/, DOT_DOT, /(^|\s)\.\.[\\/]/];++/** One string of free text, read for path shapes: true when it names a path. */+function pathShape(s) {+ if (/\0/.test(s)) return true;+ const t = s.trim();+ if (!/\s/.test(t)) return /^[\\/~]/.test(t) || /^[A-Za-z]:/.test(t) || t.includes("://") || DOT_DOT.test(t) || VARIABLE.test(t);+ return PATH_IN_WORDS.some((r) => r.test(t));+}++/** A JSON object or list written as text: its keys and its strings, every one. None for anything else. */+export function jsonStrings(v) {+ if (typeof v !== "string" || !/^\s*[[{]/.test(v)) return [];+ try {+ const parsed = JSON.parse(v);+ if (!parsed || typeof parsed !== "object") return [];+ const out = [];+ const walk = (x) => {+ if (typeof x === "string") out.push(x);+ else if (Array.isArray(x)) x.forEach(walk);+ else if (x && typeof x === "object") {+ for (const [k, y] of Object.entries(x)) {+ out.push(k);+ walk(y);+ }+ }+ };+ walk(parsed);+ return out;+ } catch {+ return [];+ }+}++/**+ * Free text that isn't a prompt (a node's settings written as text, or a value the studio fills per run: a size, a+ * language, a plan written as JSON): "unsafe-path" when it, or any key or string of a JSON value it holds, names a path.+ * A value with no spaces is refused when it starts with "/", "\" or "~", starts with a drive ("C:"), holds an address+ * ("://"), takes a ".." step, or holds a variable ("%TEMP%", "$HOME"). Words with spaces are refused only for a drive+ * path ("C:\"), a share ("\\host"), a rooted path with two parts ("/etc/x"), a home path ("~/x") and a ".." step, so+ * "16:9", "50% faster" and "auto (1088 -> 1080)" stay as they are.+ */+export function textPathProblem(v) {+ for (const s of strings(v)) {+ if (pathShape(s) || jsonStrings(s).some(pathShape)) return "unsafe-path";+ }+ return null;+}+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. */@@ -131,8 +192,11 @@ export function ruleProblem(rule, v, ctx) {case "output-name":return typeof v === "string" && OUTPUT_NAME.test(v) ? null : "unsafe-path";case "model-file":+ // A file this worker verified, whatever its name ends with (a loader may take any extension). Only the catalog's+ // own values that name no file ("plain": "None", say) need no file.if (typeof v !== "string" || pathProblem(v)) return "unsafe-path";- return !MODEL_EXT.test(v) || modelVerified(v, rule.folders, ctx.byName) ? null : "model-unverified";+ if (Array.isArray(rule.plain) && rule.plain.includes(v)) return null;+ return modelVerified(v, rule.folders, ctx.byName) ? null : "model-unverified";default:return "unsafe-path";}@@ -149,15 +213,16 @@ export function ruleFor(rules, cls, input) {/*** 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.+ * In order: its rule; a closed class's unknown input; a prompt (any text); other free text (path shapes only); 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 (TEXT_NAME.test(input)) return null;+ if (ctx.rules?.text?.[cls]?.includes(input)) return textPathProblem(v);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;diff --git a/bin/lib/worker/stamp.mjs b/bin/lib/worker/stamp.mjsnew file mode 100644index 00000000..330a2e3b--- /dev/null+++ b/bin/lib/worker/stamp.mjs@@ -0,0 +1,55 @@+// The build stamp of the worker's shared parts (docs/gpu-workers.md, "Install and update"). scripts/build-worker.mjs+// writes it into dist/build-stamp.json: one SHA-256 over every file the parts are built from. The worker starts only when+// its checkout gives the same stamp, so parts built from another checkout (an update whose build didn't run, or a build+// that wrote somewhere else) are never used with this code: not an older node allowlist, input rules or file pins.+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";++/** The file the build writes the stamp into, in dist/. */+export const STAMP_FILE = "build-stamp.json";++/** The code that turns the catalog into the worker's parts. */+const BUILD_CODE = ["scripts/build-worker.mjs", "scripts/lib/worker-build.mjs", "scripts/lib/worker-catalog.mjs", "scripts/lib/catalog-checks.mjs", "bin/lib/worker/rules.mjs", "bin/lib/worker/stamp.mjs"];++/** Every source file of the studio's graph builders and job runner (src/lib and src/server, .ts and .tsx). */+export 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"))];+}++/**+ * Every file the parts are built from, as [its name in the stamp, its path]: the studio's sources (the job runner, and+ * the graph builders the node allowlist reads), the build's own code, and every .json of the catalog's folder.+ */+export function stampFiles(root, catalogDir = path.join(root, "workflows/comfyui")) {+ const rel = (f) => path.relative(root, f).split(path.sep).join("/");+ const files = [...builderSources(root).map((f) => [rel(f), f]), ...BUILD_CODE.map((f) => [f, path.join(root, f)])];+ for (const f of fs.readdirSync(catalogDir).filter((x) => x.endsWith(".json"))) files.push([`workflows/comfyui/${f}`, path.join(catalogDir, f)]);+ return files.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+}++/** The stamp: a SHA-256 over each file's name and SHA-256 (a missing file counts as missing), as they are on disk. */+export function buildStamp(root, catalogDir) {+ const all = crypto.createHash("sha256");+ for (const [name, file] of stampFiles(root, catalogDir)) {+ let sum = "missing";+ if (fs.existsSync(file)) sum = crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");+ all.update(`${name}\u0000${sum}\n`);+ }+ return all.digest("hex");+}++/** Why the parts in `dist` can't be used with the checkout at `root`: "unbuilt" (no stamp), "stale", or null. */+export function distProblem(root, dist) {+ let built = null;+ try {+ built = JSON.parse(fs.readFileSync(path.join(dist, STAMP_FILE), "utf8"))?.stamp ?? null;+ } catch {}+ if (typeof built !== "string") return "unbuilt";+ try {+ return built === buildStamp(root) ? null : "stale";+ } catch {+ return "stale";+ }+}diff --git a/docs/adding-a-model.md b/docs/adding-a-model.mdindex fbca93d9..4e0c5558 100644--- a/docs/adding-a-model.md+++ b/docs/adding-a-model.md@@ -63,23 +63,35 @@ required rule is missing.}```- `path` is where the node looks, under the ComfyUI folder. A Hugging Face link names a commit, never `main`. Put the- files in place on a worker before the workflow runs there.+ `path` is where the node looks, under the ComfyUI folder: a model folder (`models/…`) or a folder inside the node pack+ (`custom_nodes/<pack>/<folder>/…`), never the pack's own top level or anywhere else. A first-run file is data: the+ test refuses code (`.py`, `.dll`, `.exe`, `.js` and the like) and Windows device names (`CON`, `NUL`…). A Hugging+ Face link (`huggingface.co`, `hf.co` or a host under them) names a commit, never `main`. Put the files in place on a+ worker before the workflow runs there.+- A model file that a graph names and that a node fetches on its first run needs no entry in `model-pins.json` when+ `first-run-files.json` lists it for that workflow, under the same file name. Naming it in `autoDownloads` is not+ enough: the test counts it as a file with no pin.## 4. The node allowlist and the input rules- Run `node scripts/build-worker.mjs` (`pnpm build` runs it first). It rebuilds `bin/lib/worker/dist/allowed-nodes.json`,- `input-rules.json` and `file-pins.json` from the catalog. Two builds of the same commit write the same files.+ `input-rules.json` and `file-pins.json` from the catalog. Two builds of the same commit write the same files. It also+ writes `build-stamp.json`, a hash of every file that it read. A worker starts only when the stamp matches its+ checkout.- Every node input that could name a file, a folder, a download or code gets a rule, from the catalog's own values:a fixed value, one of a list, a number range, a file that the job sent, a save name that the studio makes, or amodel file that the worker verified in its loader's folder.- A worker refuses a graph that links another node into an input with a rule, or that holds a value outside its- rule. An input with no rule that takes no free text may hold no path.+ rule. An input with no rule that takes no free text may hold no path. Other text that isn't a prompt (settings+ written as text or JSON, values the studio fills per run) may hold no path either.+- A model input takes only a file that the worker verified, whatever its extension, or one of the catalog's own values+ for that input that names no file.- The build stops, and writes nothing, when:- an input that writes or reads a file, or formats with code, has no rule (`REQUIRED_RULES` in`scripts/lib/worker-catalog.mjs`);- any catalog value that names a path, a download or code has no rule (`scripts/lib/catalog-checks.mjs`);- - the catalog links another node into such an input.+ - the catalog links another node into any input that has a rule: a model file, a file that the job sends, a save+ name or a fixed value. A worker would refuse every such graph.- Write a path, a download id or a format string in the graph as a fixed value. Never build one from other nodes.- A node that reads or writes a path it is given: add the input to `REQUIRED_RULES`, and give it a fixed value in thecatalog (empty when the node allows "no file"). If the build reports a missing rule, add the rule. Never widen the@@ -87,6 +99,10 @@ required rule is missing.- Bind a person's text only to inputs that take free text (prompts, captions, lyrics: `TEXT_NAME` in`bin/lib/worker/rules.mjs`). An input named for a file or a folder keeps the catalog's values, so a run that sendsother text there is refused.+- An input that the run fills with text that isn't a prompt (typed `STRING` in `object_info.subset.json`, or text in+ the catalog when that file doesn't name the input) gets no rule. The test lists every such input, and the list must+ match `FREE_TEXT_INPUTS` (`scripts/lib/worker-catalog.mjs`). Add an input there only after you read its node's code+ and see that it never uses the value as a path. Otherwise give the input a fixed value, or bind it to nothing.## 5. Inputs and outputs@@ -96,9 +112,14 @@ required rule is missing.with ffmpeg on the worker before its ComfyUI reads them ([Clips and sound](gpu-workers.md#clips-and-sound)). Theworker knows a clip or a sound by its type, its name or the loader that reads it.- Save results under the save name that the studio makes: bind `filename_prefix` to `filenamePrefix`.-- VideoHelperSuite's save node (`VHS_VideoCombine`) writes the prompt and the local time into a clip unless- `save_metadata` is `false`. Set `"save_metadata": false` in every new graph. The worker's ComfyUI also starts with- `--disable-metadata`.+- The worker's ComfyUI starts with `--disable-metadata`. That flag covers only ComfyUI's own save nodes.+- VideoHelperSuite's save node (`VHS_VideoCombine`) writes the run's graph and the local time into a clip unless+ `save_metadata` is `false`, whatever `--disable-metadata` says. Set `"save_metadata": false` in every new graph. A+ worker sets `save_metadata` to `false` on every such node of each graph before its ComfyUI gets it, so this matters+ for runs on a person's own GPU.+- ComfyUI's SVG save node (`SaveSVGNode`) writes the run's graph into every SVG, whatever `--disable-metadata` says. A+ worker takes that `<metadata>` element out of each SVG result. Prefer a save node that writes none. The test counts+ every graph with such a node as one that keeps metadata.## 6. VRAM, lanes and CPU work@@ -109,9 +130,10 @@ required rule is missing.size.- NVFP4 files need a Blackwell card. The queue doesn't read a card's generation, so leave lanes with NVFP4 files off anolder card's allowed lanes. Give smaller and older cards an fp8 or GGUF workflow where one exists.-- A workflow that loads no model file, fetches none on its first run and has `vramGb: 0` is CPU work: joins, trims,- adding sound, Ken Burns, still to clip. The index marks it `"cpu": true`, so it is never counted as GPU work. Set- `vramGb` above 0 when any node of the workflow uses the GPU.+- A workflow that loads no model file, fetches none on its first run and has `vramGb: 0` (the number 0, written in the+ entry) is CPU work: joins, trims, adding sound, Ken Burns, still to clip. The index marks it `"cpu": true`. Nothing+ in the studio reads the marker yet. The index build stops when an entry has no `vramGb` number, so a workflow never+ becomes CPU work by mistake. Set `vramGb` above 0 when any node of the workflow uses the GPU.## 7. The rest of the studio@@ -134,11 +156,15 @@ required rule is missing.## Known gaps-`tests/adding-a-model.test.ts` lists what isn't done yet. Each list may only shrink: the test fails when something new-joins it, and when something on it is fixed but still listed.+These lists hold what isn't done yet. Each list may only shrink: `tests/adding-a-model.test.ts` fails when something+new joins it, and when something on it is fixed but still listed.-- `UNPINNED_FILES`: model files with no SHA-256 pin yet. No worker runs the workflows that need them.-- `FIRST_RUN_GAPS`: workflows whose first-run files aren't in `first-run-files.json` yet.-- `KEEPS_METADATA`: workflows whose save node still writes metadata into a clip.+- `UNPINNED_FILES` (`scripts/lib/worker-catalog.mjs`, the one list of them): model files with no SHA-256 pin yet. A+ file of the index is listed as `folder/file`. A file that only a graph names (a node fetches it on its first run) is+ listed by its name, until `first-run-files.json` pins it. No worker runs the workflows that need them.+- `FIRST_RUN_GAPS` (`tests/adding-a-model.test.ts`): workflows whose first-run files aren't in+ `first-run-files.json` yet.+- `KEEPS_METADATA` (`tests/adding-a-model.test.ts`): workflows whose save node still writes metadata into a result.+ A worker takes it out of its own results (section 5), so the list matters for runs on a person's own GPU.Never add to these lists. Pin the file, list the first-run files, or set `save_metadata` to `false` instead.diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 83a0e227..86f1da7a 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -79,7 +79,9 @@ offer the worker as a download. Use a git checkout at a signed release tag:4. Check it out: `git checkout <tag>`.5. Install the build's tools: `pnpm install --frozen-lockfile`. The build needs TypeScript, which is a developmentdependency.-6. Build the worker's parts: `node scripts/build-worker.mjs`.+6. Build the worker's parts: `node scripts/build-worker.mjs`. The build stamps the parts with the files that it read.+ The worker starts only when that stamp matches its checkout. After an update, it asks for this step until you run+ it.**Release tags.** A maintainer makes each release tag with `git tag -s <version>` (a signed, annotated tag) and pushesit. Get the maintainer's public key from a source that you trust, and import it before step 3. Until the repository@@ -103,7 +105,11 @@ The worker always starts and stops its own ComfyUI process. It never uses a Comf- uses its own `user`, `input`, `output` and `temp` folders in the worker folder;- gets the model folders through `extra_model_paths.yaml`;- starts with `--disable-metadata` and `--disable-auto-launch`, and with `--disable-partner-nodes` when that ComfyUI- has the flag (the worker reads ComfyUI's `comfy/cli_args.py` to find out);+ has the flag (the worker reads ComfyUI's `comfy/cli_args.py` to find out). That flag covers only ComfyUI's own save+ nodes. Two save nodes write the run's graph all the same, so the worker takes care of them: it sets `save_metadata`+ to `false` on every VideoHelperSuite save node (`VHS_VideoCombine`) of each graph before its ComfyUI gets it (else+ the node writes the graph and the PC's local time into each clip), and it takes the `<metadata>` element out of each+ SVG result from ComfyUI's SVG save node before it keeps or sends the result;- loads only the custom node packs that the worker found (`--disable-all-custom-nodes --whitelist-custom-nodes …`).The worker finds a pack whatever the case of its folder name, and gives ComfyUI the folder name as it is on disk;- gets only the environment variables that it needs: the system's own, `PATH`, the temp folder, the user folders@@ -294,7 +300,8 @@ does not count as an attempt.### What the worker checks itself-Before its ComfyUI gets a graph, the worker checks all of these. The studio cannot change these checks:+Before its ComfyUI gets a graph, the worker checks all of these. The studio cannot change these checks. To add a model,+a workflow or a node pack that workers run, follow [Adding a model, a workflow or a node pack](adding-a-model.md).1. 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, pass@@ -314,15 +321,18 @@ Before its ComfyUI gets a graph, the worker checks all of these. The studio cann4. 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 (`://`), anencoded 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.+ Prompts, lyrics and captions keep any text. Other text (a size, a colour, settings written as text or as JSON) is+ read only for the shape of a path, in each key and string of its JSON too. A drive path, a share, a rooted or home+ path, a `..` step, an address or a variable is refused. `16:9` and `Scene 2: 50% faster` stay as they are.+5. Every model file that the graph names is one that the worker verified, by its exact name, whatever the name ends+ with. A file with the same name in another folder does not count. A model input takes no other value, except the+ catalog's own values for that input that name no file.The worker reports a model file only when its SHA-256 matches the hash that the catalog pins for it(`bin/lib/worker/dist/file-pins.json`, from `requirements.json` and `model-pins.json`). A file that has no pinned hashis not reported, so no job that needs it comes to the worker. The worker keeps the hashes it computed, so a restartdoes not read the files again. The catalog's files that still have no pin are listed in `UNPINNED_FILES`-(`scripts/lib/worker-catalog.mjs`). A test fails when a workflow for workers needs a file that has no pin and is not on+(`scripts/lib/worker-catalog.mjs`), the one list of them. A test fails when a catalog file has no pin and is not onthat list, and when a file on the list gets a pin, so the list only gets shorter.The worker checks the copy that its ComfyUI loads:@@ -364,7 +374,7 @@ list or any other format that would make ffmpeg open other files or addresses isWhat ffmpeg writes has limits too: at most one hour, at most 4096 pixels on the long side (a bigger picture is madesmaller, in the same shape), and at most 8 times the input's size (at least 256 MB, at most 2 GB). A result thatreaches the size cap is refused before the worker reads it. If ffmpeg cannot read a file, or its result is too big,-the job fails with plain words ("A clip or a sound in this run couldn't be read").+the job fails with plain words ("A clip or sound in this run couldn't be read.").Without `ffmpeg`, the worker takes pictures only. Its inventory says so (`media: ["image"]`), and the studio sends it noworkflow that reads a clip or a sound. If such a job comes anyway, the worker gives it back to the line.@@ -386,10 +396,12 @@ The worker keeps its jobs going by itself:seconds. The worker waits up to 2 minutes for a call, and up to an hour for a part of a result. It sends a callagain only when that is safe. A proxy's page in place of the studio's answer (a 403 that is not JSON) never stopsthe worker.-- **A job that stalls goes back to the line.** If a job makes no progress for `stallMin` minutes (10), or runs past the- run limit that the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps- its place in the line. If its ComfyUI does not let go of the prompt within 15 seconds, the worker stops ComfyUI and+- **A job that stalls goes back to the line.** If a job makes no progress for its stall limit, or runs past the run+ limit that the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps its+ place in the line. If its ComfyUI does not let go of the prompt within 15 seconds, the worker stops ComfyUI andstarts it again. A job that is given back counts as an attempt; the third time, it fails.+- **The stall limit** comes with each claim (`stallMs`). The studio gives 10 minutes for every lane now. `stallMin`+ in `worker.json` has no default; when you set it, its minutes win over the claim's limit on that PC.- **The run limit** counts from when its ComfyUI starts running the job (the model load included), not while the jobwaits. The studio gives 3 times the lane's 90th-percentile time on that worker plus the lane's model load, at least10 minutes and at most the run ceiling (45 minutes). For a lane with no times on that worker yet, it gives the run@@ -440,8 +452,10 @@ token on every call, so a revoked token stops at once.→ `{ lanes, workflows, missing }`. `media` lists the kinds of input that the worker takes (`image`, `video`,`audio`). With no `media` (a worker from before it was added, which doesn't make clips and sound again), the studiocounts pictures only.-- `POST /api/gpu/computer/claim`: the browser's claimed task plus `{ lane, estMs, runLimitMs, notAfter, attempt,- models }`. See "The run limit" above for `runLimitMs`.+- `POST /api/gpu/computer/claim`: the browser's claimed task plus+ `{ lane, estMs, runLimitMs, stallMs, notAfter, attempt, models }`. See "The run limit" above for `runLimitMs`.+ `stallMs` is how long the job may go with no progress before the worker gives it back (see "The stall limit"). A+ worker ignores a `stallMs` under one minute, and uses its own 10 minutes then.- `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, with these additions:diff --git a/scripts/build-worker.mjs b/scripts/build-worker.mjsindex 635740a0..c5251b0a 100644--- a/scripts/build-worker.mjs+++ b/scripts/build-worker.mjs@@ -1,65 +1,19 @@#!/usr/bin/env node-// Builds the worker program's shared parts (docs/gpu-workers.md) into bin/lib/worker/dist/:-// - 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;-// - 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;-// - file-pins.json: the SHA-256 of every model file the catalog names. A worker reports a file only when its own-// hash matches.+// Builds the worker program's shared parts (docs/gpu-workers.md) into bin/lib/worker/dist/: the job runner the browser+// uses, the node allowlist, the input rules and the file pins (scripts/lib/worker-build.mjs says what each holds).// `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+//+// It always builds when run, however it is reached (a linked folder included): the tests import the parts from+// scripts/lib/worker-build.mjs, never this file.import fs from "node:fs";import path from "node:path";-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";--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"];--/**- * 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) };-}--/** 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` };-}+import { STAMP_FILE } from "../bin/lib/worker/stamp.mjs";+import { ROOT, workerFiles } from "./lib/worker-build.mjs";function main(argv) {const arg = (name) => {@@ -71,15 +25,16 @@ function main(argv) {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);+ // The stamp goes first and comes back last, so parts left half written never pass for a whole build.+ fs.rmSync(path.join(out, STAMP_FILE), { force: true });+ for (const [name, text] of Object.entries(files)) if (name !== STAMP_FILE) fs.writeFileSync(path.join(out, name), text);+ fs.writeFileSync(path.join(out, STAMP_FILE), files[STAMP_FILE]);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);- }+try {+ main(process.argv.slice(2));+} catch (e) {+ console.error(e.message ?? e);+ process.exit(1);}diff --git a/scripts/comfy/build-requirements.mjs b/scripts/comfy/build-requirements.mjsindex 09a13ef3..727990df 100644--- a/scripts/comfy/build-requirements.mjs+++ b/scripts/comfy/build-requirements.mjs@@ -86,11 +86,11 @@ export function canonical(v) {export const indexHash = (index) => crypto.createHash('sha256').update(canonical({ ...index, hash: undefined })).digest('hex');/**- * CPU work: a manifest workflow that loads no model file, fetches none on its first run and needs no graphics memory- * (joins, trims, adding sound, Ken Burns, still to clip). The index marks it `cpu: true`, so it is never counted as GPU- * work.+ * CPU work: a manifest workflow that loads no model file, fetches none on its first run and says it needs no graphics+ * memory (`vramGb: 0`, written as a number): joins, trims, adding sound, Ken Burns, still to clip. The index marks it+ * `cpu: true`. A missing or misspelt vramGb never makes a workflow CPU work (buildIndex refuses it).*/-export const cpuWork = (wf) => !(wf.models ?? []).length && !(wf.autoDownloads ?? []).length && !(Number(wf.vramGb) > 0);+export const cpuWork = (wf) => typeof wf.vramGb === 'number' && wf.vramGb === 0 && !(wf.models ?? []).length && !(wf.autoDownloads ?? []).length;/*** Build the index from the library's inputs. Pure: no file or network access.@@ -176,6 +176,7 @@ export function buildIndex({ manifest, graphs, subset, packs, pins, packClassesproblems.push(`${wf.id}: no workflow graph`);continue;}+ if (typeof wf.vramGb !== 'number' || !Number.isFinite(wf.vramGb) || wf.vramGb < 0) problems.push(`${wf.id}: vramGb must be a number of GB (0 when no node uses graphics memory)`);const core = new Set();const byPack = {};for (const n of wf.customNodes) byPack[n.name] ??= new Set();diff --git a/scripts/lib/catalog-checks.mjs b/scripts/lib/catalog-checks.mjsindex fa7878fa..cacf4d66 100644--- a/scripts/lib/catalog-checks.mjs+++ b/scripts/lib/catalog-checks.mjs@@ -1,16 +1,50 @@// 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 { loaderInput, MODEL_EXT, pathNamed, pathProblem, 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");+/** A path or a download id: no spaces, and a slash. */+const slashPath = (s) => !/\s/.test(s) && /[\\/]/.test(s);+/** A model file's name: no spaces, and a model file's extension. */+const modelName = (s) => !/\s/.test(s) && MODEL_EXT.test(s);+/** Path shapes inside words: a drive path, a share, a rooted path with two parts, a home path, a ".." step. */+const PATH_IN_WORDS = [/^\s*[A-Za-z]:[\\/]/, /^\s*[\\/]{2}[^\\/\s]/, /^\s*\/[^\s/]+\//, /^\s*~[\\/]/, /(^|[\\/])\.\.([\\/]|$)/, /(^|\s)\.\.[\\/]/];++/** The keys and strings inside a value written as JSON (a node's settings), read on their own. Null for other text. */+function jsonParts(v) {+ if (!/^\s*[[{]/.test(v)) return null;+ let parsed;+ try {+ parsed = JSON.parse(v);+ } catch {+ return null;+ }+ const out = [];+ const walk = (x) => {+ if (typeof x === "string") out.push(x);+ else if (Array.isArray(x)) x.forEach(walk);+ else if (x && typeof x === "object") {+ for (const [k, y] of Object.entries(x)) {+ out.push(k);+ walk(y);+ }+ }+ };+ walk(parsed);+ return out;+}+/*** 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.+ * layer refuses, words that take a path's shape ("C:\…", "\\host", "/etc/…", "~/…", ".."), and in a value written as+ * JSON, a key or a string that is a slash path, a model file or one of those shapes; 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. An input the studio fills per run (the manifest binds it) is read only for a slash path, a model file and a+ * name that says path: its catalog value is a default, and any other value ("16:9", "00:00:05") is the run's own.* @returns {{ cls: string, input: string, why: string[] }[]} sorted by class and input*/export function pathInputs(catalog) {@@ -22,24 +56,46 @@ export function pathInputs(catalog) {out.set(key, p);};const required = new Set(REQUIRED_RULES.map(([cls, input]) => `${cls}\u0000${input}`));+ const bound = boundInputs(catalog);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+ if (Array.isArray(v)) continue; // a link: the rules builder stops on a link into an input that has a ruleconst 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 (slashPath(v)) add(cls, input, "a path or a download");+ if (modelName(v)) add(cls, input, "a model file");+ if (bound.has(`${cls}\u0000${input}`)) continue;if (!/\s/.test(v) && valueProblem(v)) add(cls, input, "refused as a path");+ const parts = jsonParts(v);+ if (parts) {+ if (parts.some((s) => slashPath(s) || modelName(s) || PATH_IN_WORDS.some((r) => r.test(s)))) add(cls, input, "a path in its JSON");+ } else if (/\s/.test(v) && PATH_IN_WORDS.some((r) => r.test(v))) add(cls, input, "a path in its words");}}}return [...out.values()].sort((a, b) => a.cls.localeCompare(b.cls) || a.input.localeCompare(b.input));}+/** The inputs the manifest binds ("Class\0input"): the studio fills them per run. */+function boundInputs(catalog) {+ const out = new Set();+ for (const w of catalog.manifest?.workflows ?? []) {+ const g = catalog.graphs?.[w.file];+ if (!g) continue;+ for (const targets of Object.values(w.bindings ?? {})) {+ for (const t of targets ?? []) {+ const n = g[t.node];+ if (n && typeof n.class_type === "string") out.add(`${n.class_type}\u0000${t.input}`);+ }+ }+ }+ return out;+}+/** 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)@@ -47,14 +103,50 @@ export function unruledPathInputs(catalog, rules) {.map((p) => `${p.cls}.${p.input} (${p.why.join(", ")})`);}+/** An input's type in the nodes' definitions (object_info.subset.json): "STRING", "INT", "COMBO"…, or null. */+function inputType(subset, cls, input) {+ const def = subset?.[cls]?.input;+ const spec = def?.required?.[input] ?? def?.optional?.[input];+ if (!Array.isArray(spec)) return null;+ return Array.isArray(spec[0]) ? "COMBO" : typeof spec[0] === "string" ? spec[0] : null;+}++/**+ * Inputs the studio fills per run (the manifest binds them) with text that isn't a prompt, and that `rules` gives no+ * rule: typed STRING in the nodes' definitions (`subset`, object_info.subset.json), or holding text in the catalog when+ * the definitions don't name the input. A person's text reaches each one, so each must be a setting that its node never+ * reads as a file (FREE_TEXT_INPUTS in scripts/lib/worker-catalog.mjs), or get a rule. Prompts (TEXT_NAME) keep any+ * text and aren't listed.+ * @returns {string[]} "Class.input", sorted+ */+export function perRunTextInputs(catalog, subset, rules) {+ const out = new Set();+ for (const w of catalog.manifest?.workflows ?? []) {+ const g = catalog.graphs?.[w.file];+ if (!g) continue;+ for (const targets of Object.values(w.bindings ?? {})) {+ for (const t of targets ?? []) {+ const n = g[t.node];+ if (!n || typeof n.class_type !== "string" || TEXT_NAME.test(t.input) || rules.inputs?.[n.class_type]?.[t.input]) continue;+ const type = inputType(subset, n.class_type, t.input);+ if (type === "STRING" || (type === null && typeof n.inputs?.[t.input] === "string")) out.add(`${n.class_type}.${t.input}`);+ }+ }+ }+ return [...out].sort();+}+/** 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)$/;+/** A path's last part ("a/b/c.pth" → "c.pth"). */+const baseName = (p) => p.split(/[\\/]/).pop();+/*** 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).+ * upscaler the manifest binds) or first-run-files.json pins it for that workflow (a file a node fetches on its first+ * run, matched by its exact file name). A name that only appears in the workflow's autoDownloads text still counts.* @returns {Record<string, string[]>} "folder/file" (the bare name for a file the index doesn't know) → workflow ids*/export function unpinnedModelFiles(catalog, rules) {@@ -69,13 +161,14 @@ export function unpinnedModelFiles(catalog, rules) {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");+ const listed = catalog.firstRun?.workflows?.[w.id];+ const firstRun = new Set((Array.isArray(listed) ? listed : []).filter((f) => typeof f?.path === "string").map((f) => baseName(f.path)));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;+ if (picked.has(`${nodeId}\u0000${input}`) || firstRun.has(baseName(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);@@ -88,13 +181,34 @@ export function unpinnedModelFiles(catalog, rules) {/** A path under the ComfyUI folder: plain name parts joined by "/", no "..", no drive, no leading slash. */const PLAIN_PATH = /^[\w@+-][\w.@+-]*(\/[\w@+-][\w.@+-]*)*$/;+/** File names that hold code a program runs or loads (a node pack's own files, a script, a library). */+const CODE_EXT = /\.(py|pyc|pyo|pyd|pyw|pyz|so|dylib|dll|exe|com|scr|msi|bat|cmd|ps1|psm1|vbs|sh|js|mjs|cjs|jar|whl|egg)$/i;++/**+ * A data folder for a first-run file: a model folder (models/<…>/<file>), or a folder inside a node pack+ * (custom_nodes/<pack>/<folder>/<…>/<file>). Never the pack's own top level, and never anywhere else in ComfyUI.+ */+const dataPlace = (parts) => (parts[0] === "models" && parts.length >= 2) || (parts[0] === "custom_nodes" && parts.length >= 4);++/** Hugging Face's hosts: huggingface.co, hf.co and every host under them. */+const hfHost = (host) => ["huggingface.co", "hf.co"].some((h) => host === h || host.endsWith(`.${h}`));+/** 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 (typeof f.path !== "string" || !PLAIN_PATH.test(f.path) || f.path.includes("..")) return `${name}: the path must be a plain relative path under the ComfyUI folder`;+ const parts = f.path.split("/");+ // Windows reads "x." as "x", and a device name (CON, NUL, COM1…) as the device, in any folder.+ if (parts.some((p) => p.endsWith(".")) || pathProblem(f.path)) return `${name}: the path names a Windows device or ends a name with "."`;+ if (!dataPlace(parts)) return `${name}: the path must be in a model folder (models/…) or in a folder inside a node pack (custom_nodes/<pack>/<folder>/…)`;+ if (CODE_EXT.test(f.path)) return `${name}: a first-run file is data, never code (.py, .dll, .exe, .js…)`;+ let url = null;+ try {+ url = typeof f.url === "string" && !/\s/.test(f.url) ? new URL(f.url) : null;+ } catch {}+ if (!url || url.protocol !== "https:" || !url.hostname || url.username || url.password || url.pathname.length < 2) return `${name}: the url must be an https link`;+ if (hfHost(url.hostname) && !/\/resolve\/[0-9a-f]{40}\//.test(url.pathname)) 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;@@ -143,15 +257,23 @@ export function metadataFormats(subset) {}/**- * 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.+ * Save nodes that write the run's graph into every file they save, whatever ComfyUI's --disable-metadata says: core+ * ComfyUI's SVG save node puts it in a <metadata> element.+ */+export const ALWAYS_WRITE_METADATA = new Set(["SaveSVGNode"]);++/**+ * The catalog workflows whose graphs save a result with its metadata (the prompt, the machine's local time): a save+ * node that always writes it (ALWAYS_WRITE_METADATA), or one 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 (ALWAYS_WRITE_METADATA.has(n.class_type)) return true;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;diff --git a/scripts/lib/worker-build.mjs b/scripts/lib/worker-build.mjsnew file mode 100644index 00000000..d4bdca3e--- /dev/null+++ b/scripts/lib/worker-build.mjs@@ -0,0 +1,61 @@+// The worker program's shared parts, as scripts/build-worker.mjs writes them into bin/lib/worker/dist/ (that script is+// only the command line; the tests import the parts from here):+// - 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;+// - 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;+// - file-pins.json: the SHA-256 of every model file the catalog names. A worker reports a file only when its own+// hash matches;+// - build-stamp.json: one SHA-256 over every file the parts are built from (bin/lib/worker/stamp.mjs). A worker+// starts only when its checkout gives the same stamp.+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import ts from "typescript";+import { buildStamp, STAMP_FILE } from "../../bin/lib/worker/stamp.mjs";+import { unruledPathInputs } from "./catalog-checks.mjs";+import { allowedNodeList, filePins, inputRules, missingRules, readCatalog } from "./worker-catalog.mjs";++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"];++/**+ * 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). inputRules itself throws when+ * the catalog links another node into an input that has a rule.+ */+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) };+}++/** Each built file's text: the transpiled modules, the three catalog files and the stamp. 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 });+ files[STAMP_FILE] = json({ stamp: buildStamp(root, catalogDir) });+ 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` };+}diff --git a/scripts/lib/worker-catalog.mjs b/scripts/lib/worker-catalog.mjsindex d03e4962..66244bc9 100644--- a/scripts/lib/worker-catalog.mjs+++ b/scripts/lib/worker-catalog.mjs@@ -3,17 +3,19 @@//// - 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.+// catalog's own values. The worker refuses a value outside its rule, and a link from another node into it, so the+// build stops when the catalog links into an input that has a rule.// - filePins: the SHA-256 of every model file the catalog names, from requirements.json and model-pins.json.import fs from "node:fs";import path from "node:path";-import { loaderInput, MODEL_EXT, pathNamed, TEXT_NAME, valueProblem } from "../../bin/lib/worker/rules.mjs";+import { jsonStrings, loaderInput, MODEL_EXT, pathNamed, TEXT_NAME, textPathProblem, valueProblem } from "../../bin/lib/worker/rules.mjs";+import { builderSources } from "../../bin/lib/worker/stamp.mjs";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. `dir` is the- * library folder (workflows/comfyui under the root unless given).+ * The catalog: its workflow graphs by file name, its manifest, its requirement index, its model pins and its pinned+ * first-run files. `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"));@@ -25,18 +27,22 @@ export function readCatalog(root, dir = path.join(root, "workflows/comfyui")) {} catch {}}const pinsFile = path.join(dir, "model-pins.json");- return { graphs, manifest: read("manifest.json"), requirements: read("requirements.json"), pins: fs.existsSync(pinsFile) ? read("model-pins.json") : {} };+ const firstRunFile = path.join(dir, "first-run-files.json");+ return {+ graphs,+ manifest: read("manifest.json"),+ requirements: read("requirements.json"),+ pins: fs.existsSync(pinsFile) ? read("model-pins.json") : {},+ firstRun: fs.existsSync(firstRunFile) ? read("first-run-files.json") : { workflows: {} },+ };}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. */+/**+ * The node allowlist: the catalog's node types, the ones the graph builders add (builderSources: they add nodes of+ * their own, such as LoRA loaders, joins and overlays), and the LoRA loaders.+ */export function allowedNodeList(root, catalog = readCatalog(root)) {const nodes = new Set();for (const wf of Object.values(catalog.requirements.workflows ?? {})) {@@ -63,6 +69,12 @@ 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);+/** A name with a file's extension (".json", ".engine", ".safetensors"…). */+const FILE_EXT = /\.[A-Za-z0-9_]{1,12}$/;++/** A path, a download id or a model file's name: no spaces, and a slash or a model file's extension. */+const namesFile = (v) => looksLikePath(v) || (typeof v === "string" && !/\s/.test(v) && MODEL_EXT.test(v));+/** Sort key for values of mixed types (so the built file is stable). */const valueKey = (v) => `${typeof v}:${JSON.stringify(v)}`;@@ -112,14 +124,18 @@ export function inputRules(catalog) {const inputs = {};const text = {};const closed = new Set();- const set = (p, rule) => ((inputs[p.cls] ??= {})[p.input] = rule);+ // A worker refuses a link into any input that has a rule, so a catalog graph that links into one could never run on+ // a worker: the build stops instead.+ const set = (p, rule) => {+ 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`);+ (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);};@@ -136,15 +152,18 @@ export function inputRules(catalog) {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() });+ // The worker takes only a file it verified, or one of these catalog values that name no file ("None", say).+ const plain = [...new Set(strings.filter((v) => v !== "" && !FILE_EXT.test(v)))].sort();+ set(p, { kind: "model-file", folders: [...p.folders].sort(), ...(plain.length && { plain }) });}// 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+ // A value that is a path, a download (an org/name id) or anything else the second layer refuses, or text (JSON+ // settings, say) that the worker's check of free text refuses or that holds a path or a model file: 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);+ else if (b.length ? strings.some(looksLikePath) : strings.some((v) => looksLikePath(v) || (!/\s/.test(v) && valueProblem(v)) || textPathProblem(v) || jsonStrings(v).some(namesFile))) 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);}@@ -190,23 +209,59 @@ export function missingRules(rules, allowed) {}/**- * Model files that workflows for workers need and that have no SHA-256 pin yet ("folder/file"). A worker never reports- * such a file, so no worker runs a workflow that needs one. Their repositories need a signed-in account to read the- * hashes (`node scripts/comfy/build-requirements.mjs --refresh-pins` with HF_TOKEN); the LTX-2.5 entries also need- * their exact sizes and a pinned revision. The list may only shrink: a test fails when a new file has no pin, and when- * a file here gets one.+ * Inputs the studio fills per run with text that isn't a prompt, and that have no rule ("Class.input"). Each is a+ * setting that its node reads as text or as a choice, never as a file: touches, boxes and points written as JSON,+ * numbers written as text, a colour, a size, a profile. A person's text reaches them, and the worker refuses any value+ * that takes a path's shape (rules.mjs textPathProblem). tests/adding-a-model.test.ts (perRunTextInputs) fails when the+ * catalog fills another such input per run: add it here only when its node never reads it as a path, or give it a+ * rule. It also fails when an input here is no longer filled per run.+ */+export const FREE_TEXT_INPUTS = [+ "AUSBOSS_NODES_MaskByTouch.touches",+ "Add Subtitles To Frames.font_color",+ "H3CharacterSwapPrepareVideo.resolution",+ "H3CharacterSwapSelectSubject.selection",+ "H3CharacterSwapWindowPlan.history_frames",+ "H3CharacterSwapWindowPlan.window_frames",+ "H3RelayReviewWindows.window_controls",+ "ManualSigmas.sigmas",+ "OpenH3RegenPrepareDraft.size",+ "OpenH3RegenUpscale.resolution",+ "QWMDetect.boxes_json",+ "SAM3_Detect.negative_coords",+ "SAM3_Detect.positive_coords",+ "VHS_VideoCombine.profile",+];++/**+ * Model files the catalog names that have no SHA-256 pin yet: the one list of them. A file of the requirement index is+ * "folder/file". A file that only a graph names is its bare name: a node fetches it on its first run, and+ * first-run-files.json doesn't pin it yet. A worker never reports such a file, so no worker runs a workflow that needs+ * one. The index files' repositories need a signed-in account to read the hashes+ * (`node scripts/comfy/build-requirements.mjs --refresh-pins` with HF_TOKEN); the LTX-2.5 entries also need their exact+ * sizes and a pinned revision. The list may only shrink: tests/adding-a-model.test.ts fails when a file has no pin and+ * isn't here, and when a file here gets one; tests/worker-input-rules.test.ts fails when a file that a workflow for+ * workers needs has no pin and isn't here.*/export const UNPINNED_FILES = [+ "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",+ "rife49.pth",+ "video_depth_anything_vitl.pth",+ "video_depth_anything_vits.pth",];/** The files that workflows for workers (not isolated) need and that have no pin: "folder/file" → the workflows. */diff --git a/src/lib/gpu/types.ts b/src/lib/gpu/types.tsindex 04a69d12..15108c1e 100644--- a/src/lib/gpu/types.ts+++ b/src/lib/gpu/types.ts@@ -90,8 +90,9 @@ export interface IndexWorkflow {/** On a graph a real ComfyUI accepted. */validated?: true;/**- * CPU work: no model file, no first-run download and no VRAM (joins, trims, adding sound, Ken Burns). It is never- * counted as GPU work. Derived by scripts/comfy/build-requirements.mjs (cpuWork).+ * CPU work: no model file, no first-run download and `vramGb: 0` written in the manifest (joins, trims, adding sound,+ * Ken Burns). A marker only: nothing in the studio reads it yet. Derived by scripts/comfy/build-requirements.mjs+ * (cpuWork).*/cpu?: true;}diff --git a/tests/adding-a-model.test.ts b/tests/adding-a-model.test.tsindex c0571c72..c811d876 100644--- a/tests/adding-a-model.test.ts+++ b/tests/adding-a-model.test.ts@@ -1,15 +1,17 @@// 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.+// every input that names a path, a download or code, a worker build that matches the catalog, CPU work marked, and+// results saved without their metadata. Each known gap is listed (the unpinned files in scripts/lib/worker-catalog.mjs,+// the others here), and each list may only shrink.import { spawnSync } from "node:child_process";import fs from "node:fs";import path from "node:path";import { beforeAll, describe, expect, it } from "vitest";-import { workerParts } from "../scripts/build-worker.mjs";+import { buildStamp, distProblem } from "../bin/lib/worker/stamp.mjs";import { LOADER_FOLDERS } from "../scripts/comfy/build-library.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 { firstRunFileProblem, firstRunProblems, metadataFormats, metadataKept, pathInputs, perRunTextInputs, unpinnedModelFiles, unruledPathInputs } from "../scripts/lib/catalog-checks.mjs";+import { workerParts } from "../scripts/lib/worker-build.mjs";+import { FREE_TEXT_INPUTS, filePins, inputRules, readCatalog, REQUIRED_RULES, UNPINNED_FILES } from "../scripts/lib/worker-catalog.mjs";import { tempDir } from "./helpers/temp-dir";type Node = { class_type: string; inputs: Record<string, unknown> };@@ -32,32 +34,6 @@ 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@@ -96,9 +72,15 @@ const FIRST_RUN_GAPS = ["voice-change-chatterbox",];-/** Workflows whose graphs still save clips with their metadata (the prompt, the local time). The list may only shrink. */+/**+ * Workflows whose graphs still save results with their metadata (the prompt, the local time). The list may only shrink.+ * image-vectorize-vtracer's SVG save node writes the run's graph into each SVG whatever ComfyUI is told. A worker takes+ * it out of the SVG before the studio gets it, and tells every clip save node to write none (bin/lib/worker/results.mjs),+ * so the list matters for runs on a person's own GPU.+ */const KEEPS_METADATA = ["captions-whisper-burnin",+ "image-vectorize-vtracer","infinitetalk-wanwrapper","interpolate-rife-vfi","lipsync-latentsync16",@@ -119,28 +101,40 @@ describe("every model file has a SHA-256 pin", () => {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([]);+ expect(pinned, `These have a pin now: take them off UNPINNED_FILES (scripts/lib/worker-catalog.mjs)\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);+ // Every file of the index is pinned or on the list; the list's other entries are files only a graph names.+ const indexFiles = Object.keys(catalog.requirements.files);+ const onList = UNPINNED_FILES.filter((f) => indexFiles.includes(f));+ expect(Object.keys(pins).length + onList.length).toBe(indexFiles.length);+ for (const f of UNPINNED_FILES.filter((x) => !indexFiles.includes(x))) expect(f, f).not.toMatch(/[\\/]/);});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"] = {}) => ({+ const fake = (graph: Graph, over: Partial<ManifestWorkflow> = {}, pins: Catalog["pins"] = {}, firstRun: Record<string, { path: string }[]> = {}) => ({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,+ firstRun: { workflows: firstRun },});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({});+ // Unless the run picks it (a LoRA the manifest binds), or first-run-files.json pins it for that workflow.+ const pinned = { "https://h/x": { sha256: SHA } };+ expect(unpinnedModelFiles(fake(loader("y.safetensors"), { bindings: { lora: [{ node: "1", input: "unet_name" }] } }, pinned), r)).toEqual({});+ const fetched = { autoDownloads: ["the node downloads y.safetensors on first run"] };+ expect(unpinnedModelFiles(fake(loader("y.safetensors"), fetched, pinned, { a: [{ path: "models/diffusion_models/y.safetensors" }] }), r)).toEqual({});+ // Named in the autoDownloads text only, or pinned for another workflow, or under a name that only starts the+ // same: it still has no pin.+ expect(unpinnedModelFiles(fake(loader("y.safetensors"), fetched, pinned), r)).toEqual({ "y.safetensors": ["a"] });+ expect(unpinnedModelFiles(fake(loader("y.safetensors"), fetched, pinned, { b: [{ path: "models/diffusion_models/y.safetensors" }] }), r)).toEqual({ "y.safetensors": ["a"] });+ expect(unpinnedModelFiles(fake(loader("y.pt"), { autoDownloads: ["the node downloads y.pth"] }, pinned, { a: [{ path: "models/x/y.pth" }] }), r)).toEqual({ "y.pt": ["a"] });});});@@ -153,11 +147,30 @@ describe("first-run downloads have pinned files", () => {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", ""]) {+ for (const p of ["../x.pth", "/x.pth", "C:/x.pth", "models/../x.pth", "models\\x.pth", "~/x.pth", "models//x.pth", ".hidden/x", "models/x..pth", ""]) {expect(firstRunFileProblem({ ...good, path: p }), p).toMatch(/plain relative path/);}+ // Data folders only: a model folder, or a folder inside a node pack. Never ComfyUI's or a pack's own code.+ for (const p of ["custom_nodes/ComfyUI-Frame-Interpolation/ckpts/rife/rife49.pth", "custom_nodes/ComfyUI-IndexTTS2/checkpoints/config.yaml", "models/insightface/models/buffalo_l/det_10g.onnx", "models/x.pth"]) {+ expect(firstRunFileProblem({ ...good, path: p }), p).toBeNull();+ }+ for (const p of ["main.py", "comfy/sd.py", "custom_nodes/ComfyUI-RMBG/__init__.py", "custom_nodes/ComfyUI-RMBG/x.pth", "custom_nodes/x.pth", "user/default/x.json", "models"]) {+ expect(firstRunFileProblem({ ...good, path: p }), p).toMatch(/model folder .* node pack/);+ }+ for (const p of ["custom_nodes/ComfyUI-RMBG/nodes/x.py", "custom_nodes/pack/lib/x.pyd", "models/x/run.bat", "models/x/lib.dll", "models/x/a.so", "models/x/tool.EXE", "models/x/web.js", "models/x/x.ps1"]) {+ expect(firstRunFileProblem({ ...good, path: p }), p).toMatch(/never code/);+ }+ for (const p of ["models/CON", "models/nul.pth", "models/x/COM1.bin", "models/aux/x.pth", "models/x/y."]) {+ expect(firstRunFileProblem({ ...good, path: p }), p).toMatch(/Windows device/);+ }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, url: "https://[email protected]/org/repo/x" })).toMatch(/https/);+ expect(firstRunFileProblem({ ...good, url: "https://github.com" })).toMatch(/https/);+ // Every Hugging Face host names a commit: huggingface.co, hf.co and the hosts under them, in any case.+ for (const url of ["https://huggingface.co/org/repo/resolve/main/x", "https://hf.co/org/repo/resolve/main/x", "https://HuggingFace.co/org/repo/resolve/main/x", "https://cdn-lfs.huggingface.co/repos/x", "https://cas-bridge.xethub.hf.co/x"]) {+ expect(firstRunFileProblem({ ...good, url }), url).toMatch(/commit/);+ }+ expect(firstRunFileProblem({ ...good, url: `https://hf.co/org/repo/resolve/${COMMIT}/BEN2_Base.pth` })).toBeNull();expect(firstRunFileProblem({ ...good, sizeBytes: 0 })).toMatch(/size/);expect(firstRunFileProblem({ ...good, sha256: SHA.toUpperCase() })).toMatch(/sha256/);expect(firstRunFileProblem({ ...good, sha256: undefined })).toMatch(/sha256/);@@ -209,6 +222,120 @@ describe("the worker build", () => {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 the catalog links another node into any input that has a rule (a model file, a sent file, a save name)", () => {+ const relink = (cls: string, input: string) => {+ const c = structuredClone(catalog);+ let n = 0;+ for (const g of Object.values(c.graphs)) {+ for (const node of Object.values(g ?? {})) {+ if (node?.class_type !== cls || !(input in (node.inputs ?? {})) || n) continue;+ node.inputs[input] = ["999", 0];+ n++;+ }+ }+ expect(n, `${cls}.${input}`).toBe(1);+ return c;+ };+ for (const [cls, input] of [+ ["UNETLoader", "unet_name"],+ ["LoadImage", "image"],+ ["SaveImage", "filename_prefix"],+ ["SaveVideo", "filename_prefix"],+ ]) {+ expect(() => workerParts(relink(cls, input), root), `${cls}.${input}`).toThrow(new RegExp(`${cls}\\.${input} .*links into it`));+ }+ });++ it("reads a value the studio fills per run only for a slash path, a model file or a name that says path", () => {+ const fake = (inputs: Record<string, unknown>, bound: string[] = []) => ({+ graphs: { "a.json": { "1": { class_type: "SomeApiNode", inputs } } },+ manifest: { workflows: [{ id: "a", file: "a.json", models: [], bindings: Object.fromEntries(bound.map((i) => [i, [{ node: "1", input: i }]])) }] },+ requirements: { files: {}, workflows: { a: { core: ["SomeApiNode"], packs: {}, files: [], optional: [], vramGb: 0, firstRun: [] } } },+ pins: {},+ });+ const flagged = (c: ReturnType<typeof fake>) => pathInputs(c).map((p: { input: string; why: string[] }) => `${p.input} (${p.why.join(", ")})`);+ const ruleOf = (c: ReturnType<typeof fake>, input: string) => (inputRules(c) as Rules).inputs.SomeApiNode?.[input];+ // An aspect ratio and a time the run fills: free text, which the worker takes ("16:9", "21:9").+ const perRun = fake({ aspect_ratio: "16:9", start: "00:00:05" }, ["aspect_ratio", "start"]);+ expect(flagged(perRun)).toEqual([]);+ expect(() => workerParts(perRun, root)).not.toThrow();+ expect(ruleOf(perRun, "aspect_ratio")).toBeUndefined();+ expect((inputRules(perRun) as Rules).text.SomeApiNode).toEqual(["aspect_ratio", "start"]);+ // The same values written in the catalog only: held to them.+ const fixed = fake({ aspect_ratio: "16:9", start: "00:00:05" });+ expect(flagged(fixed)).toEqual(["aspect_ratio (refused as a path)", "start (refused as a path)"]);+ expect(unruledPathInputs(fixed, inputRules(fixed))).toEqual([]);+ expect(ruleOf(fixed, "aspect_ratio")).toEqual({ kind: "literal", value: "16:9" });+ // A slash path is held to the catalog's value even when the run fills the input.+ const slash = fake({ source: "C:/media/x.mp4" }, ["source"]);+ expect(flagged(slash)).toEqual(["source (a path or a download)"]);+ expect(unruledPathInputs(slash, inputRules(slash))).toEqual([]);+ });++ it("finds a path in words and inside settings written as JSON, and the build holds them to the catalog's values", () => {+ const fake = (inputs: Record<string, unknown>) => ({+ graphs: { "a.json": { "1": { class_type: "SomeNode", inputs } } },+ manifest: { workflows: [{ id: "a", file: "a.json", models: [], bindings: {} }] },+ requirements: { files: {}, workflows: { a: { core: ["SomeNode"], packs: {}, files: [], optional: [], vramGb: 0, firstRun: [] } } },+ pins: {},+ });+ const cases: [unknown, string][] = [+ [JSON.stringify({ shots: [{ id: "a", prompt: "A calm shot." }], source: "../../../Users/x/v.mp4" }, null, 2), "a path in its JSON"],+ [JSON.stringify({ weights: "model.safetensors", note: "the base" }, null, 2), "a path in its JSON"],+ [JSON.stringify({ base: "C:\\Users\\x" }, null, 2), "a path in its JSON"],+ ["C:\\Users\\x\\a secret file.mp4", "a path in its words"],+ ["/etc/x and more words", "a path in its words"],+ ];+ for (const [v, why] of cases) {+ const c = fake({ plan: v });+ expect(pathInputs(c).map((p: { why: string[] }) => p.why.join(", ")), String(v)).toEqual([why]);+ expect(unruledPathInputs(c, inputRules(c)), String(v)).toEqual([]);+ expect((inputRules(c) as Rules).inputs.SomeNode?.plan, String(v)).toEqual({ kind: "literal", value: v });+ }+ // Settings and words with no path keep free text.+ for (const v of [JSON.stringify({ coordinate_space: "pixels", boxes: [] }, null, 2), "auto (1088 -> 1080, 2176 -> 2160)", "Scene 2: 50% faster"]) {+ const c = fake({ plan: v });+ expect(pathInputs(c), v).toEqual([]);+ expect((inputRules(c) as Rules).text.SomeNode, v).toEqual(["plan"]);+ }+ });++ it("every input filled per run with text that isn't a prompt has a rule or is a known setting", () => {+ const subset = read("object_info.subset.json");+ expect(perRunTextInputs(catalog, subset, rules), "Give each a rule, or add it to FREE_TEXT_INPUTS (scripts/lib/worker-catalog.mjs) when its node never reads it as a path").toEqual([...FREE_TEXT_INPUTS].sort());+ // Read on its own: a text input the run fills, with a default that names no path, is found all the same.+ const fake = (inputs: Record<string, unknown>, bound: string[], cls = "SomeNode") => ({+ graphs: { "a.json": { "1": { class_type: cls, inputs } } },+ manifest: { workflows: [{ id: "a", file: "a.json", models: [], bindings: Object.fromEntries(bound.map((i) => [i, [{ node: "1", input: i }]])) }] },+ requirements: { files: {}, workflows: {} },+ pins: {},+ });+ const defs = { SomeNode: { input: { required: { voice: ["STRING", {}], prompt: ["STRING", {}], mode: [["fast", "slow"]], steps: ["INT", {}], picked: ["COMBO", { options: ["a"] }] }, optional: { extra: ["STRING", {}] } } } };+ const c = fake({ voice: "narrator", prompt: "a calm shot", mode: "fast", steps: 4, picked: "a", extra: "" }, ["voice", "prompt", "mode", "steps", "picked", "extra"]);+ expect(perRunTextInputs(c, defs, inputRules(c))).toEqual(["SomeNode.extra", "SomeNode.voice"]);+ // Not filled per run: the catalog's own value, which the path checks read.+ expect(perRunTextInputs(fake({ voice: "narrator" }, []), defs, { inputs: {} })).toEqual([]);+ // With a rule: held to it.+ expect(perRunTextInputs(c, defs, { inputs: { SomeNode: { voice: { kind: "literal", value: "narrator" }, extra: { kind: "literal", value: "" } } } })).toEqual([]);+ // A node the definitions don't name: text in the catalog counts, a number doesn't.+ expect(perRunTextInputs(fake({ voice: "narrator", steps: 4 }, ["voice", "steps"], "OtherNode"), defs, { inputs: {} })).toEqual(["OtherNode.voice"]);+ });++ it("from the command line it builds however the script is reached, a linked folder included", () => {+ const link = path.join(tempDir("fuobe-worker-link-"), "repo");+ fs.symlinkSync(root, link, process.platform === "win32" ? "junction" : "dir");+ try {+ const out = path.join(tempDir("fuobe-worker-linked-out-"), "dist");+ const r = spawnSync(process.execPath, [path.join(link, "scripts/build-worker.mjs"), "--out", out], { cwd: link, encoding: "utf8" });+ expect(r.status, r.stderr).toBe(0);+ expect(r.stdout).toMatch(/^worker: /);+ expect(fs.readdirSync(out).sort()).toEqual(fs.readdirSync(first).sort());+ for (const f of fs.readdirSync(out)) expect(fs.readFileSync(path.join(out, f), "utf8"), f).toBe(fs.readFileSync(path.join(first, f), "utf8"));+ } finally {+ fs.unlinkSync(link);+ }+ }, 60_000);+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;@@ -246,7 +373,10 @@ describe("the worker build", () => {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"]));+ expect(files).toEqual(expect.arrayContaining(["allowed-nodes.json", "input-rules.json", "file-pins.json", "computer-runner.mjs", "build-stamp.json"]));+ // Stamped with this checkout, so a worker starts on these parts (and on no older ones).+ expect(built(first, "build-stamp.json")).toEqual({ built: "scripts/build-worker.mjs", stamp: buildStamp(root) });+ expect(distProblem(root, first)).toBeNull();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 });@@ -254,17 +384,29 @@ describe("the worker build", () => {// 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))));- });+ }, 60_000);});-describe("CPU work is marked, so it is never counted as GPU work", () => {+describe("CPU work is marked in the requirement index", () => {const index = catalog.requirements.workflows;const loaders = new Set(Object.keys(LOADER_FOLDERS));- /** Read on its own: a node that loads or runs a model, a model file, a first-run download, or VRAM. */- const usesGpu = (w: ManifestWorkflow) => {- const nodes = Object.values(catalog.graphs[w.file] ?? {}).filter((n) => typeof n?.class_type === "string");+ /**+ * Read on its own: a node that loads or runs a model, a model file, an input whose value names a download or a model+ * file (a node that fetches weights by an "org/name" id), a first-run download, or VRAM.+ */+ const usesGpu = (w: ManifestWorkflow, graphs: Record<string, Graph> = catalog.graphs) => {+ const graph = graphs[w.file] ?? {};+ const nodes = Object.values(graph).filter((n) => typeof n?.class_type === "string");const gpuNode = nodes.some((n) => loaders.has(n.class_type) || Object.keys(n.inputs ?? {}).some((i) => rules.inputs[n.class_type]?.[i]?.kind === "model-file"));- return gpuNode || w.models.length > 0 || (w.autoDownloads ?? []).length > 0 || (Number(w.vramGb) || 0) > 0;+ // A save name or a file the job sends names no weights, whatever its value, and neither does a media type+ // ("video/h264-mp4", a save node's format).+ const flagged = pathInputs({ graphs: { [w.file]: graph }, manifest: { workflows: [w] } }).filter(+ (p: { cls: string; input: string; why: string[] }) =>+ !["input-file", "output-name"].includes(rules.inputs[p.cls]?.[p.input]?.kind ?? "") && p.why.some((why) => why === "a path or a download" || why === "a model file"),+ );+ const mediaType = (v: unknown) => typeof v === "string" && /^(image|video|audio)\/[\w.+-]+$/.test(v);+ const weights = flagged.some((p: { cls: string; input: string }) => nodes.some((n) => n.class_type === p.cls && p.input in (n.inputs ?? {}) && !mediaType(n.inputs[p.input]) && !Array.isArray(n.inputs[p.input])));+ return gpuNode || weights || w.models.length > 0 || (w.autoDownloads ?? []).length > 0 || typeof w.vramGb !== "number" || w.vramGb > 0;};it("every catalog workflow that uses no GPU node is marked, and only those", () => {@@ -275,22 +417,53 @@ describe("CPU work is marked, so it is never counted as GPU work", () => {for (const id of ["wan22-t2v-14b", "bg-remove-rmbg", "separate-soundtrack-dbs", "video-fix-colours", "upscale-image-esrgan"]) expect(index[id]?.cpu, id).toBeUndefined();});+ it("the cross-check finds a node that fetches weights by a download id or a file name, with no loader and no model listed", () => {+ const w: ManifestWorkflow = { id: "x", file: "x.json", models: [], vramGb: 0, bindings: {} };+ const one = (inputs: Record<string, unknown>) => ({ "x.json": { "1": { class_type: "SomeNewNode", inputs }, "2": { class_type: "SaveVideo", inputs: { video: ["1", 0], filename_prefix: "fuobe/x", format: "video/h264-mp4" } } } });+ // What the index would say (CPU work) against what the graph shows: the test above fails on such a workflow.+ expect(cpuWork(w)).toBe(true);+ expect(usesGpu(w, one({ repo_id: "someone/weights-model" }))).toBe(true);+ expect(usesGpu(w, one({ weights: "net.pth" }))).toBe(true);+ expect(usesGpu(w, one({ mode: "fast", fps: 24 }))).toBe(false);+ });+it("a model file, a first-run download or any VRAM makes a workflow GPU work", () => {expect(cpuWork({ models: [], vramGb: 0 })).toBe(true);- expect(cpuWork({ models: [] })).toBe(true);expect(cpuWork({ models: [{ file: "x.safetensors", folder: "vae" }], vramGb: 0 })).toBe(false);expect(cpuWork({ models: [], autoDownloads: ["a node fetches x"], vramGb: 0 })).toBe(false);expect(cpuWork({ models: [], vramGb: 2 })).toBe(false);+ // Only an explicit 0: a missing, misspelt or written-as-text vramGb is never CPU work.+ expect(cpuWork({ models: [] })).toBe(false);+ expect(cpuWork({ models: [], vramGB: 0 })).toBe(false);+ expect(cpuWork({ models: [], vramGb: "0" })).toBe(false);+ expect(cpuWork({ models: [], vramGb: null })).toBe(false);+ });++ it("the index can't be built while a workflow's vramGb is missing or isn't a number", () => {+ const inputs = loadInputs(LIBRARY);+ const id = "video-trim";+ for (const vramGb of [undefined, "0", null, -1, Number.NaN]) {+ const manifest = { ...inputs.manifest, workflows: inputs.manifest.workflows.map((w: ManifestWorkflow) => (w.id === id ? { ...w, vramGb } : w)) };+ expect(() => buildIndex({ ...inputs, manifest }), String(vramGb)).toThrow(new RegExp(`${id}: vramGb must be a number`));+ }+ expect(() => buildIndex(inputs)).not.toThrow();});});-describe("saved clips carry no metadata", () => {+describe("saved results 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", () => {+ it("new graphs save results without their metadata, but for a list that may only shrink", () => {expect(metadataKept(catalog, formats)).toEqual(KEEPS_METADATA);});+ it("an SVG save node always keeps it, whatever its inputs say", () => {+ const svg = (inputs: Record<string, unknown>) => ({ graphs: { "a.json": { "1": { class_type: "SaveSVGNode", inputs } } }, manifest: { workflows: [{ id: "a", file: "a.json" }] } });+ expect(metadataKept(svg({ svg: ["2", 0], filename_prefix: "fuobe/x" }), formats)).toEqual(["a"]);+ expect(metadataKept(svg({ svg: ["2", 0], filename_prefix: "fuobe/x", save_metadata: false }), formats)).toEqual(["a"]);+ expect(metadataKept({ graphs: { "a.json": { "1": { class_type: "SaveImage", inputs: { images: ["2", 0] } } } }, manifest: { workflows: [{ id: "a", file: "a.json" }] } }, formats)).toEqual([]);+ });+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);diff --git a/tests/worker-input-rules.test.ts b/tests/worker-input-rules.test.tsindex 0c3f8759..d4cd0b71 100644--- a/tests/worker-input-rules.test.ts+++ b/tests/worker-input-rules.test.ts@@ -1,7 +1,7 @@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 { inputProblem, loaderInput, pathProblem, ruleProblem, textPathProblem, verifiedIndex } from "../bin/lib/worker/rules.mjs";import { allowedNodeList, filePins, inputRules, missingRules, readCatalog, UNPINNED_FILES, unpinnedFiles } from "../scripts/lib/worker-catalog.mjs";import { tempDir } from "./helpers/temp-dir";@@ -17,6 +17,7 @@ const catalog = readCatalog(root) as unknown as {manifest: { workflows: { id: string; file: string }[] };requirements: { files: Record<string, { folder: string; file: string }> };pins: Record<string, unknown>;+ firstRun: unknown;};const rules = inputRules(catalog);const allowed = new Set(allowedNodeList(root, catalog));@@ -139,6 +140,31 @@ describe("the worker's input rules", () => {expect(check({ "1": { class_type: "UNETLoader", inputs: { unet_name: "C:x.safetensors", weight_dtype: "default" } } })).toBe("unsafe-path");});+ it("a model input takes only a verified file, whatever its name ends with, or the catalog's own values that name no file", () => {+ const none = { byName: verifiedIndex([]), staged: [] };+ const loras = { kind: "model-file", folders: ["loras"] };+ for (const v of ["x.pt2", "x.engine", "x.json", "DBS-BSRNN-DnR/config.json", "x", "None"]) expect(ruleProblem(loras, v, none), v).toBe("model-unverified");+ const some = { byName: verifiedIndex([{ folder: "loras", name: "x.pt2" }, { folder: "loras", name: "sub/x.engine" }]), staged: [] };+ expect(ruleProblem(loras, "x.pt2", some)).toBeNull();+ expect(ruleProblem(loras, "sub/x.engine", some)).toBeNull();+ expect(ruleProblem({ kind: "model-file", folders: ["vae"] }, "x.pt2", some)).toBe("model-unverified");+ // The catalog's own values that name no file pass as they are; nothing else does.+ const withNone = { kind: "model-file", folders: ["loras"], plain: ["None"] };+ expect(ruleProblem(withNone, "None", none)).toBeNull();+ for (const v of ["none", "None.pt2", "default", "../None"]) expect(ruleProblem(withNone, v, none), v).not.toBeNull();+ // The rules builder lists those values, and only for a model input whose catalog has them.+ const fake = (values: string[]) => ({+ graphs: Object.fromEntries(values.map((v, i) => [`${i}.json`, { "1": { class_type: "LoraLoaderModelOnly", inputs: { model: ["2", 0], lora_name: v, strength_model: 1 } } }])),+ manifest: { workflows: [] },+ requirements: { files: {}, workflows: {} },+ pins: {},+ });+ expect(inputRules(fake(["a.safetensors", "None"])).inputs.LoraLoaderModelOnly.lora_name).toEqual({ kind: "model-file", folders: [], plain: ["None"] });+ expect(inputRules(fake(["a.safetensors", "b.pt2"])).inputs.LoraLoaderModelOnly.lora_name).toEqual({ kind: "model-file", folders: [] });+ // An input with no rule: a .pt2 file needs verifying too.+ expect(inputProblem("SomeNode", "weights", "x.pt2", { rules, staged: [], byName: verifiedIndex([]) })).toBe("model-unverified");+ });+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();@@ -153,6 +179,68 @@ describe("the worker's input rules", () => {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();+ // A text encoder's prompt for each of its encoders is a prompt too, whatever it starts with.+ const one = (cls: string, input: string, v: unknown) => inputProblem(cls, input, v, { rules, staged: SENT, byName: new Map() });+ for (const input of ["clip_l", "t5xxl"]) expect(one("CLIPTextEncodeFlux", input, "../x and C:/y, a calm shot"), input).toBeNull();+ // Text the run fills that isn't a prompt keeps the path checks.+ expect(one("ManualSigmas", "sigmas", "../x and C:/y")).toBe("unsafe-path");+ });++ it("other free text (settings written as text or JSON, values filled per run) holds no path", () => {+ // Inputs that take text the studio writes, or a value it fills per run: no rule, but no path either.+ const free = [+ ["MiniMaxH3ChainPlanModern", "plan_json"],+ ["H3RelayReviewWindows", "window_controls"],+ ["QWMDetect", "boxes_json"],+ ["JsonExtractString", "json_string"],+ ["ImageResizeKJv2", "pad_color"],+ ] as const;+ for (const [cls, input] of free) {+ expect(rules.inputs[cls]?.[input], `${cls}.${input}`).toBeUndefined();+ expect(rules.text[cls], `${cls}.${input}`).toContain(input);+ }+ const one = (cls: string, input: string, v: unknown) => inputProblem(cls, input, v, { rules, staged: SENT, byName: new Map() });+ const paths = [+ "C:/Users/x/secret.mp4",+ "C:secret.mp4",+ "//host/share/x",+ "\\\\host\\share\\x",+ "/etc/passwd",+ "/x",+ "~/x",+ "../../../Users/x",+ "file:///etc/passwd",+ "%USERPROFILE%\\x",+ "$HOME/x",+ "x\u0000y",+ "C:\\Users\\x\\a secret file.mp4",+ "/etc/x and more words",+ "see ../../x for it",+ "see ../x for it",+ JSON.stringify({ shots: [{ id: "a", prompt: "A calm shot.", video: "../../../Users/x/v.mp4" }] }),+ JSON.stringify({ boxes: [], path: "C:/Users/x" }),+ JSON.stringify({ "/etc/passwd": 1 }),+ JSON.stringify(["~/x"]),+ ];+ for (const [cls, input] of free) for (const v of paths) expect(one(cls, input, v), `${cls}.${input}: ${v}`).toBe("unsafe-path");+ // Settings and per-run values as the studio writes them stay as they are.+ const fine = [+ "16:9",+ "00:00:05",+ "50% faster",+ "0, 0, 0",+ "auto (1088 -> 1080, 2176 -> 2160)",+ "dpm++_sde",+ "#ffffff",+ "",+ JSON.stringify({ coordinate_space: "pixels", boxes: [] }),+ JSON.stringify({ shots: [{ id: "intro", prompt: "Describe the opening: a wide shot, then a slow push in. Scene 2: 50% faster." }] }, null, 2),+ ];+ for (const [cls, input] of free) for (const v of fine) expect(one(cls, input, v), `${cls}.${input}: ${v}`).toBeNull();+ // Numbers, and a link from another node (text built by another node), as before.+ expect(one("ImageScale", "width", 512)).toBeNull();+ expect(one("QWMDetect", "boxes_json", ["2", 0])).toBeNull();+ expect(textPathProblem(["C:/x", "fine"])).toBe("unsafe-path");});it("pins a SHA-256 for nearly every model file the catalog names", () => {@@ -162,14 +250,12 @@ describe("the worker's input rules", () => {for (const sha of Object.values(pins)) expect(sha).toMatch(/^[0-9a-f]{64}$/);});- it("pins every model file a workflow for workers needs, but for a known list of gaps that may only shrink", () => {+ it("pins every model file a workflow for workers needs, but for the known list of gaps", () => {const gaps = unpinnedFiles(catalog);// A new workflow file with no pin would quietly keep that workflow off every worker: pin it (model-pins.json).+ // (tests/adding-a-model.test.ts checks that the list, which holds every unpinned file of the catalog, only shrinks.)const fresh = Object.keys(gaps).filter((f) => !UNPINNED_FILES.includes(f));expect(fresh, fresh.map((f) => `${f} (${gaps[f].join(", ")})`).join("\n")).toEqual([]);- // A gap that has a pin now: take it off the list.- const pinned = UNPINNED_FILES.filter((f) => !gaps[f]);- expect(pinned, pinned.join("\n")).toEqual([]);});});diff --git a/tests/worker-stamp.test.ts b/tests/worker-stamp.test.tsnew file mode 100644index 00000000..56d18fc3--- /dev/null+++ b/tests/worker-stamp.test.ts@@ -0,0 +1,103 @@+/**+ * The build stamp of the worker's shared parts (bin/lib/worker/stamp.mjs): the worker starts only on parts built from+ * its own checkout. Parts from an older build (an update whose build didn't run) are refused, never used.+ */+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { worker } from "../bin/lib/worker/index.mjs";+import { buildStamp, distProblem, STAMP_FILE, stampFiles } from "../bin/lib/worker/stamp.mjs";+import { tempDir } from "./helpers/temp-dir";++/** A small checkout: a source of each folder, the build's code and a catalog. */+function checkout() {+ const root = tempDir("fuobe-worker-stamp-");+ const put = (f: string, text: string) => {+ fs.mkdirSync(path.dirname(path.join(root, f)), { recursive: true });+ fs.writeFileSync(path.join(root, f), text);+ };+ put("src/lib/relay.ts", "export const a = 1;\n");+ put("src/lib/catalog/x.tsx", "export const b = 2;\n");+ put("src/server/pool.ts", 'export const g = { class_type: "SaveImage" };\n');+ put("scripts/lib/worker-catalog.mjs", "export const r = 1;\n");+ put("bin/lib/worker/rules.mjs", "export const r = 2;\n");+ put("workflows/comfyui/manifest.json", '{"workflows":[]}\n');+ put("workflows/comfyui/wf.json", '{"1":{"class_type":"SaveImage","inputs":{}}}\n');+ put("workflows/comfyui/README.md", "not part of it\n");+ return { root, put };+}++/** A worker folder whose dist has every part, stamped with `stamp`. */+function dist(stamp: string | null) {+ const dir = tempDir("fuobe-worker-dist-");+ for (const f of ["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json"]) fs.writeFileSync(path.join(dir, f), "{}");+ if (stamp !== null) fs.writeFileSync(path.join(dir, STAMP_FILE), JSON.stringify({ built: "scripts/build-worker.mjs", stamp }));+ return dir;+}++describe("the worker's build stamp", () => {+ it("covers the sources, the build's code and the catalog's .json files, by name", () => {+ const { root } = checkout();+ const names = (stampFiles(root) as [string, string][]).map(([n]) => n);+ expect(names).toEqual(expect.arrayContaining(["src/lib/relay.ts", "src/lib/catalog/x.tsx", "src/server/pool.ts", "scripts/build-worker.mjs", "scripts/lib/worker-build.mjs", "scripts/lib/worker-catalog.mjs", "bin/lib/worker/rules.mjs", "workflows/comfyui/manifest.json", "workflows/comfyui/wf.json"]));+ expect(names).not.toContain("workflows/comfyui/README.md");+ expect(names).toEqual([...names].sort());+ });++ it("changes with any of them, and only with them", () => {+ const { root, put } = checkout();+ const first = buildStamp(root);+ expect(buildStamp(root)).toBe(first);+ put("workflows/comfyui/README.md", "changed\n");+ put("docs/x.md", "not part of it\n");+ expect(buildStamp(root)).toBe(first);+ for (const [f, text] of [+ ["workflows/comfyui/wf.json", '{"1":{"class_type":"SaveVideo","inputs":{}}}\n'],+ ["src/server/pool.ts", 'export const g = { class_type: "SaveVideo" };\n'],+ ["bin/lib/worker/rules.mjs", "export const r = 3;\n"],+ ["scripts/lib/catalog-checks.mjs", "export const c = 1;\n"],+ ["src/lib/new.ts", "export const n = 1;\n"],+ ["workflows/comfyui/new.json", "{}\n"],+ ]) {+ const before = buildStamp(root);+ put(f, text);+ expect(buildStamp(root), f).not.toBe(before);+ }+ });++ it("a copy of the catalog in another folder gives the same stamp", () => {+ const { root } = checkout();+ const copy = tempDir("fuobe-worker-stamp-catalog-");+ for (const f of fs.readdirSync(path.join(root, "workflows/comfyui"))) fs.copyFileSync(path.join(root, "workflows/comfyui", f), path.join(copy, f));+ expect(buildStamp(root, copy)).toBe(buildStamp(root));+ });++ it("parts with no stamp, or another checkout's, can't be used", () => {+ const { root, put } = checkout();+ expect(distProblem(root, dist(null))).toBe("unbuilt");+ const d = dist(buildStamp(root));+ expect(distProblem(root, d)).toBeNull();+ put("workflows/comfyui/wf.json", '{"1":{"class_type":"SaveVideo","inputs":{}}}\n');+ expect(distProblem(root, d)).toBe("stale");+ fs.writeFileSync(path.join(d, STAMP_FILE), "not json");+ expect(distProblem(root, d)).toBe("unbuilt");+ expect(distProblem(path.join(root, "gone"), dist("x"))).toBe("stale");+ });++ it("`fuobe worker run` stops, and says how to build, on parts built from other files", async () => {+ const { root, put } = checkout();+ const home = tempDir("fuobe-worker-stamp-home-");+ fs.writeFileSync(path.join(home, "worker.json"), JSON.stringify({ site: "https://studio.example", token: "t", workDir: tempDir("fuobe-worker-stamp-work-") }));+ const old = dist(buildStamp(root));+ put("src/lib/relay.ts", "export const a = 2;\n");+ let err = "";+ let out = "";+ const io = { env: { FUOBE_WORKER_HOME: home }, home, stdout: { write: (s: string) => void (out += s) }, stderr: { write: (s: string) => void (err += s) }, distDir: old, rootDir: root };+ expect(await worker(["run"], io)).toBe(2);+ expect(err).toBe("The worker's shared parts were built from other files than this checkout. Run: node scripts/build-worker.mjs\n");+ expect(out).toBe("");+ err = "";+ expect(await worker(["run"], { ...io, distDir: dist(null) })).toBe(2);+ expect(err).toMatch(/built from other files than this checkout/);+ });+});