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
Worker: send nested model names as its ComfyUI lists them; block two pack routes
Adarsh201e0bbff77d
diff --git a/bin/lib/worker/comfy_guard.py b/bin/lib/worker/comfy_guard.pyindex ba6cfbc2..37f316a0 100644--- a/bin/lib/worker/comfy_guard.py+++ b/bin/lib/worker/comfy_guard.py@@ -43,9 +43,10 @@ CHALLENGE = re.compile(r"^[0-9a-f]{16,128}$")# recordings and can send UDP) is left out of the pack the worker installs; this refuses it again if a full copy loads.# The same for ComfyUI-H3-FaceRefine's face picker (/h3_facerefine/*: it reads and serves a video from any path) and# ComfyUI-Impact-Pack's routes (/sam/*: SAM on an image read by a path the request gives; /impact/*: wildcards,-# preview-bridge images by path, earlier jobs' crops; /view/validate: whether a file exists). ComfyUI's own /view-# stays open.-BLOCKED_ROUTES = ("/instanthmr", "/h3_facerefine", "/sam", "/impact", "/view/validate")+# preview-bridge images by path, earlier jobs' crops; /view/validate: whether a file exists), kandinsky6's model+# downloader (/kandinsky6/*: it fetches and writes model files) and h3-relay's staged runs and previews (/h3_relay/*).+# ComfyUI's own /view stays open.+BLOCKED_ROUTES = ("/instanthmr", "/h3_facerefine", "/sam", "/impact", "/view/validate", "/kandinsky6", "/h3_relay")def blocked(path: str) -> bool:diff --git a/bin/lib/worker/inventory.mjs b/bin/lib/worker/inventory.mjsindex 982628dc..4cfa82a3 100644--- a/bin/lib/worker/inventory.mjs+++ b/bin/lib/worker/inventory.mjs@@ -101,6 +101,54 @@ export function packsAsSeen(packs, loaded = {}) {});}+/**+ * The names a ComfyUI lists with "\" (a model file in a subfolder, on Windows), from its GET /object_info: for each+ * node class and list input that has one, those names keyed by the same name with "/". A catalog graph names such a file+ * with "/", and ComfyUI refuses a list value it doesn't list. Empty where no list has one.+ * @returns {Map<string, Map<string, string>>} `${class}\u0000${input}` → (name with "/" → name as listed)+ */+export function listedNames(objectInfo) {+ const out = new Map();+ for (const [cls, def] of Object.entries(objectInfo && typeof objectInfo === "object" ? objectInfo : {})) {+ const groups = def?.input;+ if (!groups || typeof groups !== "object") continue;+ for (const group of [groups.required, groups.optional]) {+ if (!group || typeof group !== "object") continue;+ for (const [input, spec] of Object.entries(group)) {+ // ComfyUI's two forms of a list input: [[names…], {…}] and ["COMBO", { options: [names…] }].+ const options = Array.isArray(spec?.[0]) ? spec[0] : spec?.[0] === "COMBO" && Array.isArray(spec?.[1]?.options) ? spec[1].options : null;+ if (!options) continue;+ let names = null;+ for (const o of options) if (typeof o === "string" && o.includes("\\")) (names ??= new Map()).set(o.replaceAll("\\", "/"), o);+ if (names) out.set(`${cls}\u0000${input}`, names);+ }+ }+ }+ return out;+}++/**+ * A job's graph with each list value that names a file with "/" written as its ComfyUI lists it (listedNames). Any+ * other value stays as it is, and the graph passed in isn't changed.+ */+export function asListed(graph, listed) {+ if (!listed?.size || !graph || typeof graph !== "object") return graph;+ let out = graph;+ for (const [id, node] of Object.entries(graph)) {+ const inputs = node?.inputs;+ if (!inputs || typeof inputs !== "object" || typeof node.class_type !== "string") continue;+ for (const [input, v] of Object.entries(inputs)) {+ if (typeof v !== "string" || !v.includes("/")) continue;+ const name = listed.get(`${node.class_type}\u0000${input}`)?.get(v);+ if (!name) continue;+ if (out === graph) out = { ...graph };+ if (out[id] === node) out[id] = { ...node, inputs: { ...inputs } };+ out[id].inputs[input] = name;+ }+ }+ return out;+}+/** Its last reading of what its ComfyUI loaded (loadedPacks), kept in its working folder across restarts. */export function readLoaded(file) {try {diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex d1565b27..610c48fe 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -30,7 +30,7 @@ import { folders, GuardMissing, OwnComfy, PortBusy, yamlFolders } from "./comfy.import { ffmpegOf, PROTOCOL, protocolOf, readControl, saveConfig, savedConfig, writeControl, writeStatus } from "./config.mjs";import { BRIEF_COOL_DOWN_MS, BRIEF_EVERY_MS, BRIEF_PAUSE_MS, GpuWatch, MID_JOB_GRACE_MS, othersOf, readGpu, readGpuGen, readGpuTotal } from "./gpu.mjs";import { Hold } from "./hold.mjs";-import { inventoryHash, loadedPacks, missingModelDirs, modelFiles, packFolders, packsAsSeen, readLoaded, runtimeFileList, writeLoaded } from "./inventory.mjs";+import { asListed, inventoryHash, listedNames, loadedPacks, missingModelDirs, modelFiles, packFolders, packsAsSeen, readLoaded, runtimeFileList, writeLoaded } from "./inventory.mjs";import { freeLocal, localIdle, readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";import { takeLock, workerLives } from "./lock.mjs";import { finishers } from "./finish.mjs";@@ -505,6 +505,8 @@ async function work(saved, deps, owner) {// failed there doesn't count for the workflows that need its nodes, whatever its folder says.const loadedFile = path.join(cfg.workDir, "loaded-packs.json");let loaded = readLoaded(loadedFile);+ // The model names its ComfyUI lists with "\" (Windows), read with its nodes: a job's "/" names are sent as listed.+ let listed = new Map();async function scan() {packs = packFolders(cfg.comfyDir, index);inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json"), deps.pins, { comfyDir: cfg.comfyDir, fileCheck: cfg.fileCheck, runtime }), nodePacks: packsAsSeen(packs, loaded), media: inv.media };@@ -524,6 +526,7 @@ async function work(saved, deps, owner) {return;}if (!info || typeof info !== "object" || !Object.keys(info).length) return;+ listed = listedNames(info);faceNodes = deps.faceNodes ?? (!!info.H3FaceTrackCrop && !!info.PreviewAny);const fresh = loadedPacks(packs, index, info);for (const [name, l] of Object.entries(fresh)) {@@ -752,6 +755,7 @@ async function work(saved, deps, owner) {log(`Refused job ${t.id}: ${problem.reason} at node ${problem.node}${problem.cls ? ` (${problem.cls}${problem.input ? `.${problem.input}` : ""})` : ""}.`);return problem.reason;}+ t.graph = asListed(t.graph, listed);if (o.faces && detectsFaces(t.graph) && !(await checkFaces("before a face job", { job: true }))) return { giveBack: "self-check" };if (o.faces) jobVetted = true;return null;diff --git a/tests/worker-guard.test.ts b/tests/worker-guard.test.tsindex 52a1feaf..394c323f 100644--- a/tests/worker-guard.test.ts+++ b/tests/worker-guard.test.ts@@ -104,7 +104,7 @@ if __name__ == "__main__":app.router.add_get(base + "/instanthmr/ws", ws)app.router.add_get(base + "/instanthmr", files)app.router.add_get(base + "/instanthmr_other", files)- for route in ("/h3_facerefine/preview", "/sam/prepare", "/impact/wildcards/list", "/view/validate"):+ for route in ("/h3_facerefine/preview", "/sam/prepare", "/impact/wildcards/list", "/view/validate", "/kandinsky6/download-models", "/h3_relay/staged"):app.router.add_get(base + route, files)app.router.add_get(base + "/view", files)app.add_subapp("/internal", internal)@@ -205,8 +205,8 @@ describe.skipIf(!python)("the guard in front of a stand-in ComfyUI (Python)", ()expect(await wsOpens(`ws://${host}/api/instanthmr/ws`, key)).toBe(false);// Only that route and what is under it: a route that merely starts with the same letters, and the rest, answer.expect((await c.fetch(`${c.base}/instanthmr_other`)).status).toBe(200);- // H3-FaceRefine's face picker and Impact Pack's routes are refused too; ComfyUI's own /view still answers.- for (const p of ["/h3_facerefine/preview?path=C:/x.mp4", "/api/h3_facerefine/preview", "/H3_FaceRefine/preview", "/sam/prepare", "/api/sam/prepare", "/impact/wildcards/list", "/api/Impact/wildcards/list", "/view/validate", "/api/view/validate"]) {+ // H3-FaceRefine's face picker, Impact Pack's, kandinsky6's and h3-relay's routes are refused too; ComfyUI's own /view still answers.+ for (const p of ["/h3_facerefine/preview?path=C:/x.mp4", "/api/h3_facerefine/preview", "/H3_FaceRefine/preview", "/sam/prepare", "/api/sam/prepare", "/impact/wildcards/list", "/api/Impact/wildcards/list", "/view/validate", "/api/view/validate", "/kandinsky6/download-models", "/api/kandinsky6/download-models", "/h3_relay/staged", "/api/H3_Relay/staged"]) {expect((await raw(port, p, { Host: host, ...key })).status, p).toBe(403);}expect((await c.fetch(`${c.base}/view`)).status).toBe(200);diff --git a/tests/worker-listed-names.test.ts b/tests/worker-listed-names.test.tsnew file mode 100644index 00000000..1b43748e--- /dev/null+++ b/tests/worker-listed-names.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import { asListed, listedNames } from "../bin/lib/worker/inventory.mjs";++/**+ * ComfyUI on Windows lists a model file in a subfolder with "\", and a catalog graph names it with "/": ComfyUI then+ * refuses the job ("value not in list"). The worker reads its ComfyUI's lists with its nodes and sends such a name as+ * its ComfyUI lists it.+ */++const BS = String.fromCharCode(92);+const nested = ["Kandinsky-6.0-Lite-distill-5s-Diffusers", "transformer", "diffusion_pytorch_model.safetensors"];+const slash = nested.join("/");+const back = nested.join(BS);++const info = {+ UNETLoader: { input: { required: { unet_name: [["flux.safetensors", back], {}], weight_dtype: [["default", "fp8_e4m3fn"], {}] } } },+ VAELoader: { input: { required: { vae_name: ["COMBO", { options: ["ae.safetensors", ["vae", "wan.safetensors"].join(BS)] }] } } },+ CLIPTextEncode: { input: { required: { text: ["STRING", { multiline: true }] } } },+ Broken: { input: null },+};++describe("listedNames", () => {+ it("keeps only the list inputs that name something with a backslash, in both list forms", () => {+ const listed = listedNames(info);+ expect([...listed.keys()].sort()).toEqual(["UNETLoader\u0000unet_name", "VAELoader\u0000vae_name"]);+ expect(listed.get("UNETLoader\u0000unet_name")?.get(slash)).toBe(back);+ expect(listed.get("VAELoader\u0000vae_name")?.get("vae/wan.safetensors")).toBe(["vae", "wan.safetensors"].join(BS));+ });++ it("is empty where no list has one (Linux, macOS) or for nothing read", () => {+ expect(listedNames({ UNETLoader: { input: { required: { unet_name: [["a/b.safetensors"], {}] } } } }).size).toBe(0);+ expect(listedNames(null).size).toBe(0);+ expect(listedNames({}).size).toBe(0);+ });+});++describe("asListed", () => {+ const listed = listedNames(info);++ it("writes a nested model name as its ComfyUI lists it, and leaves the graph passed in as it was", () => {+ const graph = {+ "1": { class_type: "UNETLoader", inputs: { unet_name: slash, weight_dtype: "default" } },+ "2": { class_type: "CLIPTextEncode", inputs: { text: "a/b and c/d", clip: ["3", 0] } },+ };+ const before = JSON.stringify(graph);+ const out = asListed(graph, listed) as typeof graph;+ expect(out["1"].inputs.unet_name).toBe(back);+ expect(out["1"].inputs.weight_dtype).toBe("default");+ expect(out["2"]).toBe(graph["2"]);+ expect(JSON.stringify(graph)).toBe(before);+ });++ it("changes nothing that its ComfyUI doesn't list that way: another input, another class, an unknown name, a link", () => {+ const graph = {+ "1": { class_type: "UNETLoader", inputs: { unet_name: "other/x.safetensors" } },+ "2": { class_type: "CheckpointLoaderSimple", inputs: { ckpt_name: slash } },+ "3": { class_type: "CLIPTextEncode", inputs: { text: slash } },+ "4": { class_type: "UNETLoader", inputs: { unet_name: ["5", 0] } },+ };+ expect(asListed(graph, listed)).toBe(graph);+ });++ it("returns the graph as it is with nothing listed", () => {+ const graph = { "1": { class_type: "UNETLoader", inputs: { unet_name: slash } } };+ expect(asListed(graph, new Map())).toBe(graph);+ expect(asListed(graph, undefined as never)).toBe(graph);+ });+});