The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: offer a workflow only where its nodes loaded
Adarsh31d3b38f33a8
diff --git a/bin/lib/worker/inventory.mjs b/bin/lib/worker/inventory.mjsindex 9d4975b7..982628dc 100644--- a/bin/lib/worker/inventory.mjs+++ b/bin/lib/worker/inventory.mjs@@ -72,6 +72,51 @@ export function packFolders(comfyDir, index) {/** The node packs as the studio sees them: the catalog's name and the commit. */export const nodePacks = (comfyDir, index) => packFolders(comfyDir, index).map(({ name, commit }) => ({ name, commit }));+/**+ * What its ComfyUI loaded of each pack it has (GET /object_info's node classes): for every pack folder, the catalog's+ * classes of that pack (requirements.json packs → classes) that ComfyUI doesn't list, sorted. A pack whose import+ * failed (a missing Python module) lists none of its classes: a folder alone doesn't run its workflows.+ * { [pack name]: { commit, missing: [class, …] } }.+ * @returns {Record<string, { commit: string | null; missing: string[] }>}+ */+export function loadedPacks(packs, index, objectInfo) {+ /** @type {Record<string, { commit: string | null; missing: string[] }>} */+ const out = {};+ for (const p of packs) {+ const classes = Array.isArray(index.packs?.[p.name]?.classes) ? index.packs[p.name].classes : [];+ out[p.name] = { commit: p.commit ?? null, missing: classes.filter((c) => typeof c === "string" && !Object.hasOwn(objectInfo, c)).sort() };+ }+ return out;+}++/**+ * The node packs as the studio sees them, with what its ComfyUI loaded of each (`missingClasses`: the catalog classes it+ * didn't list) where it was read at the same commit (`loaded`: loadedPacks, kept from its last start). A pack not read+ * yet has no `missingClasses`: the studio then counts its folder, as from a worker that doesn't say.+ */+export function packsAsSeen(packs, loaded = {}) {+ return packs.map(({ name, commit }) => {+ const l = loaded[name];+ return l && Array.isArray(l.missing) && (l.commit ?? null) === (commit ?? null) ? { name, commit, missingClasses: l.missing } : { name, commit };+ });+}++/** Its last reading of what its ComfyUI loaded (loadedPacks), kept in its working folder across restarts. */+export function readLoaded(file) {+ try {+ const v = JSON.parse(fs.readFileSync(file, "utf8"));+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};+ } catch {+ return {};+ }+}++export function writeLoaded(file, loaded) {+ try {+ fs.writeFileSync(file, JSON.stringify(loaded), { mode: 0o600 });+ } catch {}+}+function gitCommit(dir) {try {const head = fs.readFileSync(path.join(dir, ".git", "HEAD"), "utf8").trim();@@ -287,9 +332,12 @@ export async function modelFiles(modelDirs, index, cacheFile, pins = filePins(),return out;}+/** A pack in the hash: name@commit, and the classes its ComfyUI didn't load after a "!" (none: as before). */+const packKey = (p) => `${p.name}@${p.commit ?? ""}${p.missingClasses?.length ? `!${[...p.missingClasses].sort().join(",")}` : ""}`;+/** The same hash the studio computes (src/server/computer/pool.ts inventoryHash), with the kinds of input it takes. */export function inventoryHash(inv) {const files = inv.files.map((f) => `${f.folder}/${f.name}:${f.size}:${f.sha256 ?? ""}`).sort();- const packs = inv.nodePacks.map((p) => `${p.name}@${p.commit ?? ""}`).sort();+ const packs = inv.nodePacks.map(packKey).sort();return crypto.createHash("sha256").update(JSON.stringify({ files, packs, ...(inv.media && { media: [...inv.media].sort() }) })).digest("hex");}diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex cffedcdb..d9d332f9 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -30,7 +30,7 @@ import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";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, missingModelDirs, modelFiles, packFolders, runtimeFileList } from "./inventory.mjs";+import { inventoryHash, 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";@@ -396,9 +396,40 @@ async function work(saved, deps, owner) {// The run-time files it verifies beside the catalog's own (a look's or a motion's LoRAs), as its build lists them.const runtime = deps.runtime ?? runtimeFileList();+ // What its ComfyUI loaded of each pack (GET /object_info after each start), kept across restarts: a pack whose import+ // 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);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: packs.map(({ name, commit }) => ({ name, commit })), media: inv.media };+ 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 };+ invHash = inventoryHash(inv);+ }+ /**+ * After its ComfyUI started: which of the catalog's node classes it lists, pack by pack. A change goes in the next+ * beat's hash, and the studio asks for the list again. Not read (an older ComfyUI, no answer): the last reading stays.+ */+ async function readLoadedNodes() {+ let info;+ try {+ const r = await comfy.fetch(`${comfy.base}/object_info`, {}, 120_000);+ if (!r.ok) return;+ info = await r.json();+ } catch {+ return;+ }+ if (!info || typeof info !== "object" || !Object.keys(info).length) return;+ const fresh = loadedPacks(packs, index, info);+ for (const [name, l] of Object.entries(fresh)) {+ if (!l.missing.length || JSON.stringify(loaded[name]) === JSON.stringify(l)) continue;+ const all = (index.packs?.[name]?.classes ?? []).length === l.missing.length;+ log(`${all ? `The node pack ${name} didn't load in its ComfyUI` : `Some nodes of ${name} didn't load in its ComfyUI`} (${l.missing.join(", ")}; see comfyui.log): the studio sends it no workflow that needs ${all ? "them" : "those"}.`);+ }+ for (const [name, l] of Object.entries(fresh)) if (!l.missing.length && loaded[name]?.missing?.length) log(`The node pack ${name} loads in its ComfyUI now.`);+ if (JSON.stringify(fresh) === JSON.stringify(loaded)) return;+ loaded = fresh;+ writeLoaded(loadedFile, loaded);+ inv = { ...inv, nodePacks: packsAsSeen(packs, loaded) };invHash = inventoryHash(inv);}// One look at a time; the next beat carries a changed hash, and the studio then asks for the list.@@ -1003,6 +1034,7 @@ async function work(saved, deps, owner) {packs.map((p) => p.folder),{ signal: stopStarts.signal },)+ .then(() => readLoadedNodes()).catch((e) => {if (stopStarts.signal.aborted) return;if (e instanceof PortBusy) {diff --git a/src/components/workers-admin.tsx b/src/components/workers-admin.tsxindex a5899be9..6e7eb976 100644--- a/src/components/workers-admin.tsx+++ b/src/components/workers-admin.tsx@@ -40,6 +40,8 @@ interface WorkerView {lanes: string[];/** The lanes it can run only some workflows of (a server from before sends none). */partLanes?: Record<string, { runnable: number; of: number }>;+ /** Node packs it has whose nodes its ComfyUI didn't load (a server or worker from before sends none). */+ unloaded?: { pack: string; classes: string[]; workflows: string[] }[];warmLane: string | null;facts: { device?: string; vramBytes?: number; version?: string };seenAt: number | null;@@ -243,6 +245,15 @@ export function LanesEditor({ w, lanes, onSave }: { w: WorkerView; lanes: Lane[]);}+/** A pack whose nodes didn't load on the worker's PC, in words: what is missing and which workflows it isn't sent. */+export function unloadedLine(u: { pack: string; classes: string[]; workflows: string[] }): string {+ const n = u.workflows.length;+ return (+ `${u.pack} didn't load in this PC's ComfyUI (missing ${u.classes.join(", ")}; its comfyui.log says why). ` ++ (n ? `${n === 1 ? "The workflow that needs it isn't" : `The ${n} workflows that need it aren't`} sent here: ${u.workflows.join(", ")}.` : "No workflow here needs those nodes.")+ );+}+function WorkerCard({ w, lanes, onToken }: { w: WorkerView; lanes: Lane[]; onToken: (t: string) => void }) {const qc = useQueryClient();const now = useNow(10_000);@@ -287,6 +298,11 @@ function WorkerCard({ w, lanes, onToken }: { w: WorkerView; lanes: Lane[]; onTok</div></div><p className="text-[12px] text-muted-foreground">{hoursWords(w.hours)}</p>+ {w.unloaded?.map((u) => (+ <p key={u.pack} className="text-[12px] text-destructive">+ {unloadedLine(u)}+ </p>+ ))}<label className="flex items-start gap-2 text-[13px]"><inputtype="checkbox"diff --git a/src/lib/lanes.ts b/src/lib/lanes.tsindex cf8cfb49..970db743 100644--- a/src/lib/lanes.ts+++ b/src/lib/lanes.ts@@ -114,14 +114,36 @@ export function mediaOf(wf: Pick<IndexWorkflow, "core" | "packs">): ("video" | "/*** A worker's verified files and node packs (PUT /api/gpu/computer/inventory), and the kinds of input it takes (`media`:* a worker without a way to make clips and sound again takes pictures only). No `media` (a worker from before workers- * made clips and sound again): pictures only.+ * made clips and sound again): pictures only. A pack's `missingClasses`: the catalog's node classes of that pack its+ * ComfyUI didn't list after it started (a pack whose import failed lists none); a workflow that needs one of them isn't+ * the worker's to run. No `missingClasses` (a worker that doesn't say, or hasn't read them yet): its folder counts.*/export interface Inventory {files: FileNeed[];- nodePacks: { name: string; commit: string | null }[];+ nodePacks: NodePack[];media?: MediaKind[];}+export interface NodePack {+ name: string;+ commit: string | null;+ missingClasses?: string[];+}++/** A pack in an inventory's hash: name@commit, then the classes its ComfyUI didn't load after a "!" (none: as before). */+export const packKey = (p: NodePack) => `${p.name}@${p.commit ?? ""}${p.missingClasses?.length ? `!${[...p.missingClasses].sort().join(",")}` : ""}`;++/**+ * The node classes a workflow needs that its worker's ComfyUI didn't load, by pack ("pack/Class"): its packs are there+ * (by folder), but a class the worker said is missing would stop the run.+ */+export function unloadedNodes(wf: Pick<IndexWorkflow, "packs">, packs: ReadonlyMap<string, NodePack>): string[] {+ return Object.entries(wf.packs).flatMap(([name, classes]) => {+ const missing = new Set(packs.get(name)?.missingClasses ?? []);+ return classes.filter((c) => missing.has(c)).map((c) => `${name}/${c}`);+ });+}+const fileKey = (f: Pick<FileNeed, "folder" | "name">) => `${f.folder}/${f.name}`;/** Has the worker this file: folder, name and exact size always; the SHA-256 too when the index pins one. */@@ -133,15 +155,15 @@ export function hasFile(inv: Inventory, need: FileNeed): boolean {export const hasFiles = (inv: Inventory, needs: readonly FileNeed[] | undefined): boolean => !needs?.length || needs.every((n) => hasFile(inv, n));/**- * What a worker can run with what it has: the workflows whose files and packs are all there, the lanes whose every- * workflow runs, and, for the other lanes, what it lacks. A task goes only to a worker that can run its workflow.+ * What a worker can run with what it has: the workflows whose files and packs are all there (and whose packs' node+ * classes its ComfyUI loaded, where it said), the lanes whose every workflow runs, and, for the other lanes, what it lacks. A task goes only to a worker that can run its workflow.*/export function lanesFor(index: RequirementIndex,inv: Inventory,sha: Sha,): { lanes: string[]; workflows: string[]; missing: { lane: string; label: string; files: string[]; bytes: number }[] } {- const packs = new Set(inv.nodePacks.map((p) => p.name));+ const packs = new Map(inv.nodePacks.map((p) => [p.name, p]));const takes = new Set<string>(inv.media ?? ["image"]);const ok = new Map<string, boolean>();const workflows: string[] = [];@@ -153,7 +175,8 @@ export function lanesFor(const missingFiles = n.files.filter((f) => !hasFile(inv, f));const missingPacks = n.packs.filter((p) => !packs.has(p));const missingMedia = mediaOf(index.workflows[id]).filter((k) => !takes.has(k));- const fine = !missingFiles.length && !missingPacks.length && !missingMedia.length;+ const notLoaded = unloadedNodes(index.workflows[id], packs);+ const fine = !missingFiles.length && !missingPacks.length && !missingMedia.length && !notLoaded.length;if (fine) workflows.push(id);ok.set(lane, (ok.get(lane) ?? true) && fine);if (!fine) {@@ -161,6 +184,7 @@ export function lanesFor(for (const f of missingFiles) m.set(fileKey(f), f.size);for (const p of missingPacks) m.set(`pack:${p}`, 0);for (const k of missingMedia) m.set(`input:${k}`, 0);+ for (const c of notLoaded) m.set(`node:${c}`, 0);lacking.set(lane, m);}}diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex cd8ed17d..84d6626a 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -2,7 +2,7 @@ import "server-only";import crypto from "node:crypto";import { FINISH_KINDS, type FinishTicket } from "@/lib/finish-ticket";import { ceilingProblem, cleanCeiling, insideCeiling, lanesInside, type Ceiling } from "@/lib/job-ticket";-import { allLanes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, needsOf, partLanes, type FileNeed, type Inventory, type Needs } from "@/lib/lanes";+import { allLanes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, needsOf, packKey, partLanes, unloadedNodes, type FileNeed, type Inventory, type NodePack, type Needs } from "@/lib/lanes";import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat } from "@/lib/relay";import { runtimeFileKeys } from "@/lib/runtime-files";import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";@@ -418,10 +418,13 @@ export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; wo});const known = knownFiles();const files = sent.filter((f) => !/[\\/]|\.\./.test(f.folder) && fileNameOk(f.name) && known.has(`${f.folder}/${f.name}`));- const nodePacks = (Array.isArray(o.nodePacks) ? o.nodePacks : []).slice(0, 500).flatMap((p) => {+ const nodePacks = (Array.isArray(o.nodePacks) ? o.nodePacks : []).slice(0, 500).flatMap((p): NodePack[] => {const x = p as Record<string, unknown>;const name = text(x?.name, 128);- return name ? [{ name, commit: text(x?.commit, 64) }] : [];+ if (!name) return [];+ // The pack's catalog classes its ComfyUI didn't load (a worker that read them; none said: its folder counts).+ const missing = Array.isArray(x.missingClasses) ? x.missingClasses.slice(0, 500).filter((c): c is string => typeof c === "string" && c.length > 0 && c.length <= 128) : undefined;+ return [{ name, commit: text(x?.commit, 64), ...(missing && { missingClasses: missing }) }];});// The kinds of input it takes. None said: an older worker, which doesn't make clips and sound again, so lanesFor gives// it pictures only (the list is kept as sent, so its hash stays the one the worker computes).@@ -438,7 +441,7 @@ export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; wo/** The hash a worker sends with each beat, so the studio asks for the whole list only when it changed. */export function inventoryHash(inv: Inventory): string {const files = [...inv.files].map((f) => `${f.folder}/${f.name}:${f.size}:${f.sha256 ?? ""}`).sort();- const packs = [...inv.nodePacks].map((p) => `${p.name}@${p.commit ?? ""}`).sort();+ const packs = [...inv.nodePacks].map(packKey).sort();return sha(JSON.stringify({ files, packs, ...(inv.media && { media: [...inv.media].sort() }) }));}@@ -1255,6 +1258,11 @@ export interface WorkerView {* worker that can run its own workflow), so Settings offers them with the count.*/partLanes: Record<string, { runnable: number; of: number }>;+ /**+ * Node packs whose folder it has but whose nodes its ComfyUI didn't load (it said so after its last start): the classes+ * missing, and the workflows that need them, which are never sent to it.+ */+ unloaded: { pack: string; classes: string[]; workflows: string[] }[];/** What its PC may ever run (null: no ceiling of its own), and the allowed lanes inside it. */ceiling: Ceiling | null;lanesInside: string[];@@ -1272,6 +1280,22 @@ export interface WorkerView {current: { taskId: string; generationId: string; lane: string | null; startedAt: number | null } | null;}+/** The packs a worker said its ComfyUI didn't load, each with the workflows that need one of those classes. */+export function unloadedPacks(inv: Inventory): WorkerView["unloaded"] {+ const index = loadIndex();+ const packs = new Map(inv.nodePacks.map((p) => [p.name, p]));+ return inv.nodePacks+ .filter((p) => p.missingClasses?.length)+ .map((p) => ({+ pack: p.name,+ classes: p.missingClasses!,+ workflows: Object.keys(index.workflows)+ .filter((id) => !index.workflows[id].isolated && unloadedNodes(index.workflows[id], packs).some((c) => c.startsWith(`${p.name}/`)))+ .sort(),+ }))+ .sort((a, b) => a.pack.localeCompare(b.pack));+}+export function workerView(w: WorkerRow, now = Date.now()): WorkerView {const s = workerState(w, now);const cur = db().prepare("SELECT id, generation_id, lane, started_at FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting') LIMIT 1").get(w.id) as@@ -1295,6 +1319,7 @@ export function workerView(w: WorkerRow, now = Date.now()): WorkerView {warmLane: w.warm_lane,lanes: capableOf(w).lanes,partLanes: partLanes(loadIndex(), capableOf(w).workflows, sha),+ unloaded: unloadedPacks(inventoryOf(w)),ceiling: ceilingOf(w),lanesInside: lanesInside(Object.keys(allowOf(w)), ceilingOf(w)),cpuSlot: cpuSlotOf(w),diff --git a/tests/worker-loaded-nodes.test.ts b/tests/worker-loaded-nodes.test.tsnew file mode 100644index 00000000..a4716f85--- /dev/null+++ b/tests/worker-loaded-nodes.test.ts@@ -0,0 +1,172 @@+import crypto from "node:crypto";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { inventoryHash as workerHash, loadedPacks, packsAsSeen } from "../bin/lib/worker/inventory.mjs";+import { tempDir } from "./helpers/temp-dir";++/**+ * A node pack whose folder is on a worker's PC but whose nodes its ComfyUI didn't load (an import that failed: the+ * NVIDIA RTX Video nodes without their Python package). The worker reads /object_info after its ComfyUI starts and says,+ * per pack, which of the catalog's classes are missing; the studio then never sends it a workflow that needs one, and+ * the owner sees why on the Workers page. A worker that doesn't say counts by its folders, as before.+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-worker-loaded-nodes-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+delete process.env.FUOBE_PASSWORD;++const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const pool = await import("@/server/computer/pool");+const workers = await import("@/server/computer/workers");+const { lanesFor, needsOf, laneOf, unloadedNodes } = await import("@/lib/lanes");+const { loadIndex } = await import("@/server/gpu/index-file");+const { unloadedLine } = await import("@/components/workers-admin");++const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");+const RTX = "ComfyUI_Nvidia_VFX_Nodes";+const RTX_WORKFLOWS = ["fps-rtx-framegen", "sdr-to-hdr-rtx", "upscale-video-rtx"];+const GB = 2 ** 30;++/** Everything the index names for these workflows: their files (verified) and every pack they need (by folder). */+function inventoryFor(ids: string[]) {+ const index = loadIndex();+ const needs = ids.map((id) => needsOf(index, id)!);+ const files = [...new Map(needs.flatMap((n) => n.files).map((f) => [`${f.folder}/${f.name}`, { ...f, sha256: f.sha256 ?? "0".repeat(64) }])).values()];+ const nodePacks = [...new Set(needs.flatMap((n) => n.packs))].sort().map((name) => ({ name, commit: null as string | null }));+ return { files, nodePacks, media: ["image", "video", "audio"] as ("image" | "video" | "audio")[] };+}++describe("the worker reads what its ComfyUI loaded", () => {+ const index = { packs: { [RTX]: { classes: ["RTXTrueHDR", "RTXVideoFrameGeneration", "RTXVideoSuperResolution"] }, "ComfyUI-VideoHelperSuite": { classes: ["VHS_LoadVideo", "VHS_VideoCombine"] } } };+ const packs = [+ { name: RTX, folder: RTX, commit: "38d790ded00650681fa3645362efe28c8560cf40" },+ { name: "ComfyUI-VideoHelperSuite", folder: "comfyui-videohelpersuite", commit: null },+ ];++ it("lists, per pack it has, the catalog's classes /object_info leaves out (all of them for a pack that failed to import)", () => {+ const info = { VHS_LoadVideo: {}, VHS_VideoCombine: {}, KSampler: {} };+ expect(loadedPacks(packs, index, info)).toEqual({+ [RTX]: { commit: packs[0].commit, missing: ["RTXTrueHDR", "RTXVideoFrameGeneration", "RTXVideoSuperResolution"] },+ "ComfyUI-VideoHelperSuite": { commit: null, missing: [] },+ });+ expect(loadedPacks(packs, index, { ...info, RTXTrueHDR: {}, RTXVideoFrameGeneration: {}, RTXVideoSuperResolution: {} })[RTX].missing).toEqual([]);+ });++ it("sends a reading only for the commit it was made at; before any reading a pack goes as it always did", () => {+ const loaded = loadedPacks(packs, index, { VHS_LoadVideo: {}, VHS_VideoCombine: {} });+ expect(packsAsSeen(packs, {})).toEqual([+ { name: RTX, commit: packs[0].commit },+ { name: "ComfyUI-VideoHelperSuite", commit: null },+ ]);+ expect(packsAsSeen(packs, loaded)[0]).toEqual({ name: RTX, commit: packs[0].commit, missingClasses: ["RTXTrueHDR", "RTXVideoFrameGeneration", "RTXVideoSuperResolution"] });+ expect(packsAsSeen(packs, loaded)[1]).toEqual({ name: "ComfyUI-VideoHelperSuite", commit: null, missingClasses: [] });+ // The pack moved to another commit since: its old reading doesn't count until its ComfyUI starts again.+ expect(packsAsSeen([{ ...packs[0], commit: "f".repeat(40) }], loaded)[0]).toEqual({ name: RTX, commit: "f".repeat(40) });+ });++ it("hashes as the studio does; with nothing missing, the hash is an older worker's", async () => {+ const { inventoryHash } = await import("@/server/computer/pool");+ const base = { files: [{ folder: "loras", name: "a.safetensors", size: 7, sha256: null }], nodePacks: [{ name: RTX, commit: null }] };+ const broken = { ...base, nodePacks: [{ name: RTX, commit: null, missingClasses: ["RTXVideoSuperResolution", "RTXTrueHDR"] }] };+ const fine = { ...base, nodePacks: [{ name: RTX, commit: null, missingClasses: [] }] };+ expect(workerHash(broken)).toBe(inventoryHash(broken));+ expect(workerHash(broken)).not.toBe(workerHash(base));+ expect(workerHash(fine)).toBe(workerHash(base));+ expect(inventoryHash(fine)).toBe(inventoryHash(base));+ });+});++describe("the studio's lanes from a worker's packs", () => {+ it("a workflow whose pack's nodes didn't load isn't the worker's to run; its other workflows are", () => {+ const index = loadIndex();+ const inv = inventoryFor(RTX_WORKFLOWS);+ // No reading (an older worker, or before its ComfyUI started): its folders count, as before.+ for (const id of RTX_WORKFLOWS) expect(lanesFor(index, inv, sha).workflows, id).toContain(id);+ // Read, and every node there.+ const fine = { ...inv, nodePacks: inv.nodePacks.map((p) => ({ ...p, missingClasses: [] as string[] })) };+ for (const id of RTX_WORKFLOWS) expect(lanesFor(index, fine, sha).workflows, id).toContain(id);+ // The RTX pack's import failed: none of its three workflows.+ const failed = { ...inv, nodePacks: inv.nodePacks.map((p) => (p.name === RTX ? { ...p, missingClasses: ["RTXTrueHDR", "RTXVideoFrameGeneration", "RTXVideoSuperResolution"] } : p)) };+ const r = lanesFor(index, failed, sha);+ for (const id of RTX_WORKFLOWS) expect(r.workflows, id).not.toContain(id);+ expect(r.missing.flatMap((m) => m.files)).toEqual(expect.arrayContaining([`node:${RTX}/RTXTrueHDR`, `node:${RTX}/RTXVideoFrameGeneration`, `node:${RTX}/RTXVideoSuperResolution`]));+ // Only HDR's node missing: the frame generation and the upscale still run there.+ const partly = { ...inv, nodePacks: inv.nodePacks.map((p) => (p.name === RTX ? { ...p, missingClasses: ["RTXTrueHDR"] } : p)) };+ const w = lanesFor(index, partly, sha).workflows;+ expect(w).not.toContain("sdr-to-hdr-rtx");+ expect(w).toEqual(expect.arrayContaining(["fps-rtx-framegen", "upscale-video-rtx"]));+ expect(laneOf(index, "sdr-to-hdr-rtx", sha)).toBeTruthy();+ });++ it("names the classes a workflow needs that didn't load, by pack", () => {+ const packs = new Map([[RTX, { name: RTX, commit: null, missingClasses: ["RTXTrueHDR"] }]]);+ expect(unloadedNodes({ packs: { [RTX]: ["RTXTrueHDR"], "ComfyUI-VideoHelperSuite": ["VHS_LoadVideo"] } }, packs)).toEqual([`${RTX}/RTXTrueHDR`]);+ expect(unloadedNodes({ packs: { [RTX]: ["RTXVideoSuperResolution"] } }, packs)).toEqual([]);+ });+});++describe("a worker that says its RTX nodes didn't load", () => {+ beforeEach(() => {+ resetRates();+ db().prepare("DELETE FROM relay_workers").run();+ setSetting("comfyWhere", "workers");+ });++ const put = async (w: { token: string }, body: unknown) => {+ const { PUT } = await import("@/app/api/gpu/computer/inventory/route");+ const res = await PUT(new Request("http://localhost:3000/api/gpu/computer/inventory", { method: "PUT", headers: { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" }, body: JSON.stringify(body) }));+ return { status: res.status, body: (await res.json()) as { workflows?: string[] } };+ };+ const beatWith = (w: { id: string }, inventoryHash: string | null) =>+ pool.workerBeat(workers.getWorker(w.id)!, pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 2, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash, running: [], stopped: [] }), Date.now());++ it("isn't offered its workflows, isn't asked for its list again, and the owner sees why", async () => {+ const index = loadIndex();+ const w = pool.addWorker("rtx-pc");+ const lanes = [...new Set(RTX_WORKFLOWS.map((id) => laneOf(index, id, sha)!))];+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l, { delayMs: 0 }])), claimAfterMs: 0 });+ db().prepare("UPDATE relay_workers SET facts_json = ? WHERE id = ?").run(JSON.stringify({ vramBytes: 32 * GB, device: "NVIDIA GeForce RTX 5090" }), w.id);+ const inv = inventoryFor(RTX_WORKFLOWS);++ // Before its ComfyUI said anything: the folder counts (an older worker's way).+ expect((await put(w, inv)).body.workflows).toEqual(expect.arrayContaining(RTX_WORKFLOWS));+ for (const id of RTX_WORKFLOWS) expect(pool.workersCanRun(id), id).toBe(true);+ expect(pool.workerView(workers.getWorker(w.id)!).unloaded).toEqual([]);++ // After its start: the RTX pack didn't load.+ const failed = { ...inv, nodePacks: inv.nodePacks.map((p) => ({ ...p, missingClasses: p.name === RTX ? ["RTXTrueHDR", "RTXVideoFrameGeneration", "RTXVideoSuperResolution"] : [] })) };+ expect(beatWith(w, workerHash(failed)).worker.sendInventory).toBe(true);+ const r = await put(w, failed);+ expect(r.status).toBe(200);+ for (const id of RTX_WORKFLOWS) {+ expect(r.body.workflows, id).not.toContain(id);+ expect(pool.workersCanRun(id), id).toBe(false);+ }+ // The studio's hash of what it kept is the worker's: no list asked for again on every beat.+ expect(beatWith(w, workerHash(failed)).worker.sendInventory).toBe(false);+ const view = pool.workerView(workers.getWorker(w.id)!);+ expect(view.unloaded).toEqual([{ pack: RTX, classes: ["RTXTrueHDR", "RTXVideoFrameGeneration", "RTXVideoSuperResolution"], workflows: RTX_WORKFLOWS }]);+ const line = unloadedLine(view.unloaded[0]);+ expect(line).toContain(`${RTX} didn't load in this PC's ComfyUI`);+ expect(line).toContain("The 3 workflows that need it aren't sent here: fps-rtx-framegen, sdr-to-hdr-rtx, upscale-video-rtx.");++ // Fixed on the PC (its package installed, ComfyUI started again): offered again.+ const fixed = { ...inv, nodePacks: inv.nodePacks.map((p) => ({ ...p, missingClasses: [] as string[] })) };+ expect((await put(w, fixed)).body.workflows).toEqual(expect.arrayContaining(RTX_WORKFLOWS));+ for (const id of RTX_WORKFLOWS) expect(pool.workersCanRun(id), id).toBe(true);+ expect(pool.workerView(workers.getWorker(w.id)!).unloaded).toEqual([]);+ });++ it("keeps only class names it can read, and never more than it was sent", async () => {+ const w = pool.addWorker("odd-pc");+ const inv = inventoryFor(["sdr-to-hdr-rtx"]);+ const odd = { ...inv, nodePacks: inv.nodePacks.map((p) => (p.name === RTX ? { ...p, missingClasses: ["RTXTrueHDR", 7, "", "x".repeat(200)] } : p)) };+ expect((await put(w, odd)).status).toBe(200);+ const kept = JSON.parse(workers.getWorker(w.id)!.inventory_json ?? "{}") as { nodePacks: { name: string; missingClasses?: string[] }[] };+ expect(kept.nodePacks.find((p) => p.name === RTX)?.missingClasses).toEqual(["RTXTrueHDR"]);+ });+});diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.tsindex e004f2f8..987e1cdf 100644--- a/tests/worker-recovery.test.ts+++ b/tests/worker-recovery.test.ts@@ -19,6 +19,8 @@* - A model folder that isn't there yet (a drive still locked after a restart): the worker waits for it, says so, and* sends no list of files meanwhile; once the folder is there, the waiting job is taken within one look.* - New worker code installed mid-job: it takes no new job, finishes the one it has, and ends to start again on it.+ * - A node pack whose folder is there but whose nodes its ComfyUI didn't load is said in its list, with the missing+ * classes, and kept for its next start.*/import { spawnSync } from "node:child_process";import crypto from "node:crypto";@@ -883,3 +885,39 @@ describe("its model folders", () => {}});});++describe("what its ComfyUI loaded", () => {+ it("a pack whose folder is there but whose nodes didn't load is said, with its classes, and kept for the next start", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ for (const f of ["PackGood", "PackBroken"]) fs.mkdirSync(path.join(p.comfyDir, "custom_nodes", f), { recursive: true });+ const requirements = {+ folders: [],+ files: {},+ packs: { PackGood: { repo: "https://github.com/example/PackGood", classes: ["GoodNode"] }, PackBroken: { repo: "https://github.com/example/PackBroken", classes: ["BrokenA", "BrokenB"] } },+ workflows: {},+ };+ // Its ComfyUI lists the good pack's node and the core ones, none of the broken pack's (its import failed).+ const has = path.join(p.home, "has.json");+ fs.writeFileSync(has, JSON.stringify({ folders: [], files: {}, workflows: { x: { core: ["KSampler", "SaveImage"], packs: { PackGood: ["GoodNode"] } } } }));+ const command = [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--worker-guard", "1", "--has", has];+ const packsOf = (i: Record<string, unknown>) => i.nodePacks as { name: string; commit: string | null; missingClasses?: string[] }[];+ const first = start(w, s, p, { requirements, command });+ const sent = await until(() => s.inventories.find((i) => packsOf(i).some((n) => n.missingClasses)));+ expect(packsOf(sent).sort((a, b) => a.name.localeCompare(b.name))).toEqual([+ { name: "PackBroken", commit: null, missingClasses: ["BrokenA", "BrokenB"] },+ { name: "PackGood", commit: null, missingClasses: [] },+ ]);+ expect(p.logs.some((l) => /The node pack PackBroken didn't load in its ComfyUI \(BrokenA, BrokenB; see comfyui\.log\)/.test(l))).toBe(true);+ expect(p.logs.some((l) => /PackGood/.test(l))).toBe(false);+ expect(JSON.parse(fs.readFileSync(path.join(p.workDir, "loaded-packs.json"), "utf8"))).toEqual({ PackGood: { commit: null, missing: [] }, PackBroken: { commit: null, missing: ["BrokenA", "BrokenB"] } });+ first.ctrl.abort();+ await first.done;+ // The next start says it from its first list, before its ComfyUI answers again.+ const before = s.inventories.length;+ start(w, s, p, { requirements, command });+ const again = await until(() => s.inventories[before]);+ expect(packsOf(again).find((n) => n.name === "PackBroken")?.missingClasses).toEqual(["BrokenA", "BrokenB"]);+ });+});