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: the worker program, fuobe worker
Adarsha9bf360cc52e
diff --git a/.gitignore b/.gitignoreindex 00a62366..c044a6f3 100644--- a/.gitignore+++ b/.gitignore@@ -52,3 +52,6 @@ next-env.d.ts/scripts/eval/results//scripts/eval/metrics/.venv/__pycache__/++# The worker's built parts (scripts/build-worker.mjs)+/bin/lib/worker/dist/diff --git a/bin/lib/commands.mjs b/bin/lib/commands.mjsindex ad446b31..a611c877 100644--- a/bin/lib/commands.mjs+++ b/bin/lib/commands.mjs@@ -905,6 +905,14 @@ export const COMMANDS = {passthrough: true,run: evalHarness,},+ worker: {+ summary: "Run this PC's GPU as a worker for a studio (docs/gpu-workers.md)",+ usage: "fuobe worker <setup | run | pause [--now] [--for 2h] | resume | status | bench | install [--yes]>",+ examples: ["fuobe worker setup", "fuobe worker run", "fuobe worker pause --for 2h", "fuobe worker pause --now", "fuobe worker resume"],+ passthrough: true,+ ownConfig: true,+ run: async (ctx) => (await import("./worker/index.mjs")).worker(ctx.positionals, ctx.io),+ },};/** Other names people type. */diff --git a/bin/lib/worker/checks.mjs b/bin/lib/worker/checks.mjsnew file mode 100644index 00000000..4b01745b--- /dev/null+++ b/bin/lib/worker/checks.mjs@@ -0,0 +1,61 @@+// The worker's own checks of a job before its ComfyUI sees it (docs/gpu-workers.md), and its cleanup after.+//+// 1. Every node type is on the allowlist built into this worker (dist/allowed-nodes.json), plus a file the PC's owner+// passes with --allow-nodes. The studio can never add to it: a studio taken over can't run new code on this PC.+// 2. Every file the graph reads was sent with the job (the shared runner's graphProblem does this one).+// 3. No string input names a path: an absolute path, a drive letter, a network share, or a ".." step.+// 4. Every model file the graph names is one this worker verified (its inventory).+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const here = path.dirname(fileURLToPath(import.meta.url));++export function allowedNodes(extraFile) {+ const built = JSON.parse(fs.readFileSync(path.join(here, "dist", "allowed-nodes.json"), "utf8")).nodes;+ const extra = extraFile ? JSON.parse(fs.readFileSync(extraFile, "utf8")) : [];+ return new Set([...built, ...(Array.isArray(extra) ? extra : (extra.nodes ?? []))]);+}++const PATHLIKE = [/^[A-Za-z]:[\\/]/, /^\\\\/, /^\/(?!\/)[^\s]*\//, /(^|[\\/])\.\.([\\/]|$)/, /^~[\\/]/];+const MODEL = /\.(safetensors|gguf|ckpt|pt|pth|bin|sft)$/i;++/** The first problem with a job's graph for this worker, or null. */+export function vetGraph(graph, allowed, verified) {+ for (const node of Object.values(graph ?? {})) {+ if (!node || typeof node.class_type !== "string" || !allowed.has(node.class_type)) return "unknown-node";+ }+ for (const node of Object.values(graph)) {+ for (const v of Object.values(node.inputs ?? {})) {+ if (typeof v !== "string") continue;+ if (PATHLIKE.some((r) => r.test(v))) return "unsafe-path";+ }+ }+ for (const node of Object.values(graph)) {+ for (const v of Object.values(node.inputs ?? {})) {+ if (typeof v !== "string" || !MODEL.test(v)) continue;+ const name = v.replace(/\\/g, "/");+ if (!verified.has(name) && !verified.has(name.split("/").pop())) return "model-unverified";+ }+ }+ return null;+}++/** Delete everything in the worker's own input, output and temp folders (at start: whatever a crash left). */+export function emptyFolders(f) {+ for (const dir of [f.input, f.output, f.temp]) {+ fs.mkdirSync(dir, { recursive: true });+ for (const e of fs.readdirSync(dir)) fs.rmSync(path.join(dir, e), { recursive: true, force: true });+ }+}++/** After a job: its inputs and results leave this PC, its history entry goes, and the temp folder is emptied. */+export async function cleanJob(task, f, comfyBase, fetchFn = fetch) {+ for (const i of task.inputs ?? []) if (/^fuobe_[A-Za-z0-9_-]{8,24}\.[a-z0-9]{1,5}$/.test(i.name)) fs.rmSync(path.join(f.input, i.name), { force: true });+ // Everything in output and temp is this worker's (its own ComfyUI writes only there), and it runs one job at a time.+ for (const dir of [f.output, f.temp]) {+ if (!fs.existsSync(dir)) continue;+ for (const e of fs.readdirSync(dir)) fs.rmSync(path.join(dir, e), { recursive: true, force: true });+ }+ await fetchFn(`${comfyBase}/history`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delete: [task.promptId] }) }).catch(() => null);+}diff --git a/bin/lib/worker/comfy.mjs b/bin/lib/worker/comfy.mjsnew file mode 100644index 00000000..26990f17--- /dev/null+++ b/bin/lib/worker/comfy.mjs@@ -0,0 +1,173 @@+// The worker's own ComfyUI (docs/gpu-workers.md): it always starts and stops its own process, on its own port, with its+// own folders, and it never uses a ComfyUI it didn't start.+//+// The port guard: before each start the worker binds the port itself and lets it go at once. If that fails, something+// else listens there: the worker refuses to start, pauses itself ("port-busy"), and never connects to that port. So it+// can never take over, or even talk to, another ComfyUI (the one on 8188 included).+import { spawn } from "node:child_process";+import fs from "node:fs";+import net from "node:net";+import path from "node:path";++export class PortBusy extends Error {}++/** Can this worker have the port? (A bind test: nothing is sent to whatever listens there.) */+export function portFree(port, host = "127.0.0.1") {+ return new Promise((resolve) => {+ const s = net.createServer();+ s.once("error", () => resolve(false));+ s.listen({ port, host, exclusive: true }, () => s.close(() => resolve(true)));+ });+}++/** The Python that runs ComfyUI: the portable one beside it, its venv, else python on the PATH. */+export function pythonFor(comfyDir) {+ const win = process.platform === "win32";+ const tries = win+ ? [path.join(comfyDir, "..", "python_embeded", "python.exe"), path.join(comfyDir, "venv", "Scripts", "python.exe"), path.join(comfyDir, ".venv", "Scripts", "python.exe")]+ : [path.join(comfyDir, "venv", "bin", "python"), path.join(comfyDir, ".venv", "bin", "python")];+ return tries.find((p) => fs.existsSync(p)) ?? (win ? "python" : "python3");+}++/** The worker's folders under its worker folder: ComfyUI's user, input, output and temp folders, its own. */+export const folders = (workDir) => ({+ user: path.join(workDir, "user"),+ input: path.join(workDir, "input"),+ output: path.join(workDir, "output"),+ temp: path.join(workDir, "temp"),+});++/** extra_model_paths.yaml: the model folders, for reading. */+export function modelPathsYaml(modelDirs, folderNames) {+ const lines = [];+ modelDirs.forEach((dir, i) => {+ lines.push(`fuobe_worker_${i}:`, ` base_path: ${JSON.stringify(dir)}`);+ for (const f of folderNames) lines.push(` ${f}: ${f}`);+ });+ return `${lines.join("\n")}\n`;+}++/** ComfyUI's start arguments (3.3): localhost only, its own folders, no metadata, no browser, only the packs it needs. */+export function comfyArgs(cfg, packs = []) {+ const f = folders(cfg.workDir);+ return [+ "--listen", "127.0.0.1",+ "--port", String(cfg.port),+ "--disable-auto-launch",+ "--disable-metadata",+ "--user-directory", f.user,+ "--input-directory", f.input,+ "--output-directory", f.output,+ "--temp-directory", f.temp,+ "--extra-model-paths-config", path.join(cfg.workDir, "extra_model_paths.yaml"),+ "--disable-all-custom-nodes",+ ...(packs.length ? ["--whitelist-custom-nodes", ...packs] : []),+ ];+}++/** At most this many restarts an hour; then the worker pauses itself ("comfy-crashes"). */+export const MAX_RESTARTS_AN_HOUR = 3;++export class OwnComfy {+ /**+ * @param cfg the worker's settings (comfyDir, workDir, port, modelDirs; `comfyCommand` replaces the whole command, for tests)+ * @param o { now, log, fetch, folderNames }+ */+ constructor(cfg, o = {}) {+ this.cfg = cfg;+ this.o = o;+ this.child = null;+ this.ready = false;+ this.starts = [];+ this.expectExit = false;+ this.onCrash = null;+ }++ get base() {+ return `http://127.0.0.1:${this.cfg.port}`;+ }++ get pid() {+ return this.child?.pid ?? null;+ }++ alive() {+ return !!this.child && this.child.exitCode === null && !this.child.killed;+ }++ /** Restarts in the last hour have used up the allowance. */+ crashedTooOften(now = Date.now()) {+ return this.starts.filter((t) => now - t < 3_600_000).length > MAX_RESTARTS_AN_HOUR;+ }++ /** Start its own ComfyUI and wait until it answers. Throws PortBusy when the port is taken. */+ async start(packs = []) {+ if (this.alive()) return;+ if (!(await portFree(this.cfg.port))) throw new PortBusy(`Port ${this.cfg.port} is in use by another program`);+ const f = folders(this.cfg.workDir);+ for (const dir of Object.values(f)) fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(this.cfg.workDir, "extra_model_paths.yaml"), modelPathsYaml(this.cfg.modelDirs ?? [], this.o.folderNames ?? []));+ const cmd = this.cfg.comfyCommand+ ? this.cfg.comfyCommand.map((a) => String(a).replaceAll("{port}", String(this.cfg.port)))+ : [this.cfg.python || pythonFor(this.cfg.comfyDir), path.join(this.cfg.comfyDir, "main.py"), ...comfyArgs(this.cfg, packs)];+ this.starts.push((this.o.now ?? Date.now)());+ this.expectExit = false;+ this.ready = false;+ const child = spawn(cmd[0], cmd.slice(1), { cwd: this.cfg.comfyDir || this.cfg.workDir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });+ this.child = child;+ const log = fs.createWriteStream(path.join(this.cfg.workDir, "comfyui.log"), { flags: "a" });+ child.stdout.pipe(log);+ child.stderr.pipe(log);+ child.once("exit", (code) => {+ this.ready = false;+ if (!this.expectExit) this.onCrash?.(code);+ });+ // Only now, with its own process up, does the worker talk to the port.+ const fetchFn = this.o.fetch ?? fetch;+ for (let i = 0; i < 360; i++) {+ if (!this.alive()) throw new Error("ComfyUI stopped while starting (see comfyui.log in the worker folder)");+ try {+ const r = await fetchFn(`${this.base}/system_stats`);+ if (r.ok) {+ this.ready = true;+ return;+ }+ } catch {}+ await new Promise((r) => setTimeout(r, 500));+ }+ await this.stop();+ throw new Error("ComfyUI didn't answer within 3 minutes");+ }++ /** Stop its ComfyUI (the whole process tree), so its VRAM and RAM go back. */+ async stop() {+ const child = this.child;+ if (!child) return;+ this.expectExit = true;+ this.ready = false;+ if (child.exitCode === null) {+ if (process.platform === "win32" && child.pid) {+ await new Promise((r) => spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).once("exit", r).once("error", r));+ } else child.kill("SIGTERM");+ await new Promise((r) => {+ if (child.exitCode !== null) return r();+ const t = setTimeout(() => (child.kill("SIGKILL"), r()), 10_000);+ child.once("exit", () => (clearTimeout(t), r()));+ });+ }+ this.child = null;+ }++ /** Its own VRAM, from its own /system_stats (MB), or null. */+ async vramMb() {+ if (!this.ready) return null;+ try {+ const s = await (await (this.o.fetch ?? fetch)(`${this.base}/system_stats`)).json();+ const d = s?.devices?.[0];+ const bytes = d?.torch_vram_total ?? null;+ return typeof bytes === "number" ? Math.round(bytes / 2 ** 20) : null;+ } catch {+ return null;+ }+ }+}diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjsnew file mode 100644index 00000000..22a68498--- /dev/null+++ b/bin/lib/worker/config.mjs@@ -0,0 +1,74 @@+// The worker's own files (docs/gpu-workers.md): its settings (worker.json, readable by this user only), the pause+// switch the `pause` and `resume` commands flip (control.json), and what the running worker last said (status.json).+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++export const PROTOCOL = 1;++/** Where the worker keeps its settings: %LOCALAPPDATA%\FuobeWorker on Windows, ~/.config/fuobe-worker elsewhere. */+export function workerHome(env = process.env, home = os.homedir()) {+ if (env.FUOBE_WORKER_HOME) return env.FUOBE_WORKER_HOME;+ if (process.platform === "win32") return path.join(env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "FuobeWorker");+ return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "fuobe-worker");+}++export const DEFAULTS = {+ port: 8190,+ /** Another program's VRAM above this pauses the worker. */+ busyVramMb: 1024,+ /** The automatic resume: off unless switched on for this PC. */+ autoResume: false,+ /** The GPU must stay free this long before an automatic resume, and be cooler than this. */+ resumeAfterMin: 10,+ resumeBelowC: 75,+ nvidiaSmi: "nvidia-smi",+};++const file = (home, name) => path.join(home, name);++function readJson(p, fallback) {+ try {+ return JSON.parse(fs.readFileSync(p, "utf8"));+ } catch {+ return fallback;+ }+}++function writePrivate(p, data) {+ fs.mkdirSync(path.dirname(p), { recursive: true });+ const tmp = `${p}.tmp`;+ fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });+ fs.renameSync(tmp, p);+ try {+ fs.chmodSync(p, 0o600);+ } catch {}+}++/** The settings, with defaults; the token from FUOBE_WORKER_TOKEN when set (a rented machine keeps it out of files). */+export function loadConfig(home, env = process.env) {+ const c = { ...DEFAULTS, ...readJson(file(home, "worker.json"), {}) };+ if (env.FUOBE_WORKER_TOKEN) c.token = env.FUOBE_WORKER_TOKEN;+ if (env.FUOBE_WORKER_SITE) c.site = env.FUOBE_WORKER_SITE;+ return c;+}++export const saveConfig = (home, c) => writePrivate(file(home, "worker.json"), c);++/** The pause switch on this PC: { paused, now, until, at }. */+export const readControl = (home) => readJson(file(home, "control.json"), { paused: false });+export const writeControl = (home, c) => writePrivate(file(home, "control.json"), { ...c, at: Date.now() });+export const readStatus = (home) => readJson(file(home, "status.json"), null);+export const writeStatus = (home, s) => writePrivate(file(home, "status.json"), s);++/** "2h", "90m", "45s" → ms (null when it isn't one). */+export function parseFor(text) {+ const m = /^(\d+(?:\.\d+)?)\s*(h|m|s)$/i.exec(String(text ?? "").trim());+ if (!m) return null;+ return Math.round(Number(m[1]) * { h: 3_600_000, m: 60_000, s: 1000 }[m[2].toLowerCase()]);+}++/** A folder a cloud drive syncs (its files would leave this PC) or the search index reads. */+export function syncedFolder(dir) {+ return /[\\/](OneDrive|Dropbox|Google Drive|GoogleDrive|iCloudDrive|iCloud Drive|Box|MEGA)([\\/ -]|$)/i.test(path.resolve(dir));+}diff --git a/bin/lib/worker/gpu.mjs b/bin/lib/worker/gpu.mjsnew file mode 100644index 00000000..bf3c02bc--- /dev/null+++ b/bin/lib/worker/gpu.mjs@@ -0,0 +1,106 @@+// "Your GPU is busy": the worker pauses itself the moment another program uses the GPU, and (only when its automatic+// resume is on) resumes by itself once the GPU stayed free for the whole cool-down. It reads nvidia-smi and nothing else:+// it never contacts another program's port (not a ComfyUI on 8188, not any ComfyUI it didn't start). A pause by hand+// always wins: the automatic resume never ends it.+import { execFile } from "node:child_process";++/** Memory a ComfyUI's CUDA context takes beyond what torch reports. */+export const CONTEXT_ALLOWANCE_MB = 600;++const num = (s) => {+ const v = Number(String(s ?? "").trim());+ return Number.isFinite(v) ? v : null;+};++/** `nvidia-smi --query-gpu=memory.used,temperature.gpu --format=csv,noheader,nounits` → the first GPU. */+export function parseGpu(text) {+ const line = String(text ?? "").split(/\r?\n/).find((l) => l.trim());+ if (!line) return null;+ const [used, temp] = line.split(",");+ const usedMb = num(used);+ return usedMb === null ? null : { usedMb, tempC: num(temp) };+}++/** `--query-compute-apps=pid,process_name,used_memory --format=csv,noheader,nounits`; used_memory is often [N/A] on Windows. */+export function parseApps(text) {+ return String(text ?? "")+ .split(/\r?\n/)+ .map((l) => l.trim())+ .filter(Boolean)+ .map((l) => {+ const parts = l.split(",").map((p) => p.trim());+ const used = parts.at(-1);+ return { pid: num(parts[0]) ?? 0, name: (parts.slice(1, -1).join(",").split(/[\\/]/).pop() || "?").slice(0, 64), usedMb: num(used) };+ })+ .filter((a) => a.pid > 0);+}++const run = (cmd, args) =>+ new Promise((resolve) => {+ execFile(cmd, args, { timeout: 5000, windowsHide: true }, (err, stdout) => resolve(err ? null : String(stdout)));+ });++/**+ * One reading of the GPU, or null when nvidia-smi isn't there (no NVIDIA GPU: nothing to watch). `cmd`: its path, or a+ * command and its first arguments (["node", "fake-smi.mjs"] in the tests).+ */+export async function readGpu(cmd = "nvidia-smi") {+ const [bin, ...pre] = Array.isArray(cmd) ? cmd : [cmd];+ const call = (args) => run(bin, [...pre, ...args]);+ const gpu = await call(["--query-gpu=memory.used,temperature.gpu", "--format=csv,noheader,nounits"]);+ if (gpu === null) return null;+ const g = parseGpu(gpu);+ if (!g) return null;+ const apps = parseApps((await call(["--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader,nounits"])) ?? "");+ return { ...g, apps };+}++/**+ * Is another program using the GPU? Others' VRAM is the GPU's used memory minus what the worker's own ComfyUI holds+ * (`ownMb`, with an allowance for its CUDA context while it runs). Busy above `busyVramMb`, or when another process+ * shows its own use above it. The total rule always works, also when per-process memory reads [N/A].+ */+export function othersOf(reading, own, busyVramMb) {+ const ownMb = own.running ? (own.mb ?? 0) + CONTEXT_ALLOWANCE_MB : 0;+ const othersMb = Math.max(0, reading.usedMb - ownMb);+ const others = reading.apps.filter((a) => a.pid !== own.pid);+ const loud = others.find((a) => a.usedMb !== null && a.usedMb > busyVramMb);+ const busy = othersMb > busyVramMb || !!loud;+ const who = loud?.name ?? others.find((a) => a.usedMb === null || a.usedMb > 0)?.name ?? (busy ? "another program" : null);+ return { busy, othersMb, who };+}++/**+ * The automatic pause and resume. `update` takes each reading's verdict; `paused` says whether the GPU keeps the worker+ * paused now. Busy pauses at once; with `autoResume`, it resumes once the GPU stayed free for `resumeAfterMs` in a row+ * and is cooler than `resumeBelowC`. Any busy reading starts the cool-down again. Without autoResume, only `clear()` (a+ * resume by hand) ends it.+ */+export class GpuWatch {+ constructor(o) {+ this.o = o;+ this.paused = false;+ this.who = null;+ this.freeSince = null;+ }++ update(verdict, tempC, now) {+ if (verdict.busy) {+ this.paused = true;+ this.who = verdict.who;+ this.freeSince = null;+ return;+ }+ this.freeSince ??= now;+ if (this.paused && this.o.autoResume && now - this.freeSince >= this.o.resumeAfterMs && (tempC === null || tempC === undefined || tempC < this.o.resumeBelowC)) {+ this.paused = false;+ this.who = null;+ }+ }++ /** A resume by hand clears a GPU pause too. */+ clear() {+ this.paused = false;+ this.who = null;+ }+}diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjsnew file mode 100644index 00000000..e570b986--- /dev/null+++ b/bin/lib/worker/index.mjs@@ -0,0 +1,152 @@+// `fuobe worker <setup | run | pause | resume | status | bench | install>` (docs/gpu-workers.md).+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { portFree } from "./comfy.mjs";+import { DEFAULTS, loadConfig, parseFor, readControl, readStatus, saveConfig, syncedFolder, workerHome, writeControl } from "./config.mjs";+import { installScript } from "./install.mjs";++const here = path.dirname(fileURLToPath(import.meta.url));++export const WORKER_USAGE = "fuobe worker <setup | run | pause [--now] [--for 2h] | resume | status | bench | install [--yes]>";++const flag = (args, name) => args.includes(`--${name}`);+const value = (args, name) => {+ const i = args.indexOf(`--${name}`);+ return i >= 0 ? args[i + 1] : undefined;+};++/** The worker command. Returns the exit code. */+export async function worker(args, io) {+ const [sub = "status", ...rest] = args;+ const home = workerHome(io.env, io.home);+ const say = (line) => io.stdout.write(`${line}\n`);+ switch (sub) {+ case "setup":+ return setup(home, io, say);+ case "run": {+ const cfg = loadConfig(home, io.env);+ if (!cfg.site || !cfg.token || !cfg.workDir) {+ io.stderr.write("This worker isn't set up yet. Run: fuobe worker setup\n");+ return 2;+ }+ if (!fs.existsSync(path.join(here, "dist", "computer-runner.mjs"))) {+ io.stderr.write("The worker's shared parts aren't built. Run: node scripts/build-worker.mjs\n");+ return 2;+ }+ const { runWorker } = await import("./run.mjs");+ const ctrl = new AbortController();+ const off = io.onInterrupt?.(() => ctrl.abort());+ say(`Fuobe worker for ${cfg.site}. Its own ComfyUI uses port ${cfg.port}. Ctrl+C stops it.`);+ try {+ await runWorker(cfg, { home, signal: ctrl.signal });+ } finally {+ off?.();+ }+ return 0;+ }+ case "pause": {+ const forMs = value(rest, "for") ? parseFor(value(rest, "for")) : null;+ if (value(rest, "for") && !forMs) {+ io.stderr.write("Say how long, like --for 2h or --for 30m.\n");+ return 2;+ }+ writeControl(home, { paused: true, now: flag(rest, "now"), until: forMs ? Date.now() + forMs : null });+ say(flag(rest, "now") ? "Paused now: its job goes back in line, and its ComfyUI stops." : "Paused: it finishes its job, then stops its ComfyUI.");+ if (forMs) say(`It resumes by itself at ${new Date(Date.now() + forMs).toLocaleTimeString()}.`);+ return 0;+ }+ case "resume":+ writeControl(home, { paused: false, resumedAt: Date.now() });+ say("Resumed on this PC. (A pause on the website stays until it's resumed there.)");+ return 0;+ case "status": {+ const s = readStatus(home);+ const c = readControl(home);+ say(s ? `${s.state}${Date.now() - s.at > 30_000 ? " (the worker isn't running)" : ""}` : "The worker hasn't run yet.");+ if (c.paused) say(c.until ? `Paused here until ${new Date(c.until).toLocaleTimeString()}.` : "Paused here.");+ return 0;+ }+ case "bench": {+ const cfg = loadConfig(home, io.env);+ const res = await io.fetch(`${cfg.site.replace(/\/+$/, "")}/api/gpu/computer/bench`, { method: "POST", headers: { Authorization: `Bearer ${cfg.token}`, "Content-Type": "application/json" }, body: "{}" });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ io.stderr.write(`${body.error ?? `The studio answered HTTP ${res.status}`}\n`);+ return 1;+ }+ say(body.tasks ? `${body.tasks} bench jobs are waiting for this worker. Keep it running.` : "No bench jobs for its lanes yet. Its times come from the jobs it runs.");+ return 0;+ }+ case "install": {+ const script = installScript({ node: process.execPath, bin: path.resolve(here, "../../fuobe.mjs"), home });+ if (!flag(rest, "yes")) {+ say("This adds a task that starts the worker when you sign in (and again if it stops), and two desktop shortcuts:");+ say('"Pause Fuobe worker" (Ctrl+Alt+P) and "Resume Fuobe worker". To do it, run: fuobe worker install --yes');+ say("");+ say(script.text);+ return 0;+ }+ if (process.platform !== "win32") {+ io.stderr.write("worker install is for Windows. Elsewhere, run `fuobe worker run` from systemd or a login item.\n");+ return 2;+ }+ fs.mkdirSync(home, { recursive: true });+ const file = path.join(home, "install.ps1");+ fs.writeFileSync(file, script.text);+ const { spawnSync } = await import("node:child_process");+ const r = spawnSync("powershell", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", file], { stdio: "inherit" });+ return r.status ?? 1;+ }+ default:+ io.stderr.write(`Unknown worker command "${sub}". Usage: ${WORKER_USAGE}\n`);+ return 2;+ }+}++async function setup(home, io, say) {+ const old = loadConfig(home, io.env);+ const ask = async (q, def, o = {}) => ((await io.ask(`${q}${def ? ` [${def}]` : ""}: `, o)) || def || "").trim();+ say("Set up this PC as a Fuobe worker. It takes the studio's jobs over HTTPS and runs them on its own ComfyUI.");+ const site = await ask("The studio's address", old.site ?? "https://");+ const token = await ask("The worker's token (Settings → Workers → Add a worker)", "", { hidden: true });+ if (!/^fuobe_wkr_/.test(token) && !old.token) {+ io.stderr.write("That isn't a worker token (they start with fuobe_wkr_).\n");+ return 2;+ }+ const comfyDir = await ask("ComfyUI's folder (where its main.py is)", old.comfyDir);+ if (!fs.existsSync(path.join(comfyDir, "main.py"))) {+ io.stderr.write("There's no main.py in that folder.\n");+ return 2;+ }+ const modelDirs = (await ask("Model folders, separated by ; (each holds checkpoints, loras…)", (old.modelDirs ?? [path.join(comfyDir, "models")]).join(";")))+ .split(";")+ .map((s) => s.trim())+ .filter(Boolean);+ const workDir = await ask("A worker folder for jobs' files", old.workDir ?? (process.platform === "win32" ? "D:\\FuobeWorker" : path.join(io.home, "fuobe-worker")));+ if (syncedFolder(workDir)) {+ io.stderr.write("That folder is synced to a cloud drive. Pick one outside OneDrive, Dropbox and the like: people's files must stay on this PC.\n");+ return 2;+ }+ const port = Number(await ask("The port for the worker's own ComfyUI", String(old.port ?? DEFAULTS.port)));+ if (!Number.isInteger(port) || port < 1024 || port > 65535 || port === 8188) {+ io.stderr.write("Pick a free port above 1024 other than 8188 (your own ComfyUI's).\n");+ return 2;+ }+ if (!(await portFree(port))) {+ io.stderr.write(`Something already listens on port ${port}. The worker only uses a ComfyUI it starts itself: pick another port.\n`);+ return 2;+ }+ const autoResume = /^y/i.test(await ask("Resume by itself when the GPU has been free for 10 minutes? (y/N)", old.autoResume ? "y" : "n"));+ fs.mkdirSync(workDir, { recursive: true });+ if (process.platform === "win32") {+ // Not content indexed: jobs' files stay out of Windows Search.+ const { spawnSync } = await import("node:child_process");+ spawnSync("attrib", ["+I", workDir], { windowsHide: true });+ }+ saveConfig(home, { ...old, site: site.replace(/\/+$/, ""), token: token || old.token, comfyDir, modelDirs, workDir, port, autoResume });+ writeControl(home, { paused: true, now: false, until: null });+ say(`Saved in ${path.join(home, "worker.json")} (readable by you only). The worker starts paused here.`);+ say("Next: fuobe worker run. Resume it here with fuobe worker resume, and on the website in Settings → Workers.");+ return 0;+}diff --git a/bin/lib/worker/install.mjs b/bin/lib/worker/install.mjsnew file mode 100644index 00000000..bb0637c0--- /dev/null+++ b/bin/lib/worker/install.mjs@@ -0,0 +1,27 @@+// `fuobe worker install` (Windows): a Task Scheduler task "Fuobe worker" that starts the worker when you sign in and+// starts it again if it stops, and two desktop shortcuts with hotkeys: "Pause Fuobe worker" (Ctrl+Alt+P) and "Resume+// Fuobe worker". It prints the PowerShell first; it runs it only with --yes.++const q = (s) => `'${String(s).replaceAll("'", "''")}'`;++export function installScript({ node, bin, home }) {+ const text = `# Fuobe worker: start at sign-in (restarted if it stops), and pause / resume shortcuts.+$ErrorActionPreference = "Stop"+$action = New-ScheduledTaskAction -Execute ${q(node)} -Argument ${q(`"${bin}" worker run`)} -WorkingDirectory ${q(home)}+$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME+$settings = New-ScheduledTaskSettingsSet -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries+Register-ScheduledTask -TaskName "Fuobe worker" -Action $action -Trigger $trigger -Settings $settings -RunLevel Limited -Force | Out-Null+$shell = New-Object -ComObject WScript.Shell+$desktop = [Environment]::GetFolderPath("Desktop")+foreach ($s in @(@("Pause Fuobe worker", "worker pause", "CTRL+ALT+P"), @("Resume Fuobe worker", "worker resume", ""))) {+ $lnk = $shell.CreateShortcut((Join-Path $desktop ($s[0] + ".lnk")))+ $lnk.TargetPath = ${q(node)}+ $lnk.Arguments = '"${bin.replaceAll("'", "''")}" ' + $s[1]+ $lnk.WindowStyle = 7+ if ($s[2]) { $lnk.Hotkey = $s[2] }+ $lnk.Save()+}+Write-Host "Done: the worker starts when you sign in. Ctrl+Alt+P pauses it."+`;+ return { text };+}diff --git a/bin/lib/worker/inventory.mjs b/bin/lib/worker/inventory.mjsnew file mode 100644index 00000000..1aec2afc--- /dev/null+++ b/bin/lib/worker/inventory.mjs@@ -0,0 +1,100 @@+// What this worker has (docs/gpu-workers.md): the model files in its model folders that the studio's catalog names,+// each checked by folder, name and exact size, and by SHA-256 where the catalog pins one; and its ComfyUI's node packs+// with their commits. Hashes are cached by path, size and modified time, so a restart doesn't read hundreds of GB again.+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";++const KINDS = /\.(safetensors|gguf)$/i;++function sha256File(file) {+ return new Promise((resolve, reject) => {+ const h = crypto.createHash("sha256");+ fs.createReadStream(file)+ .on("data", (d) => h.update(d))+ .on("end", () => resolve(h.digest("hex")))+ .on("error", reject);+ });+}++/** The pack folders in ComfyUI's custom_nodes, named as the catalog names them, with their git commit. */+export function nodePacks(comfyDir, index) {+ const dir = path.join(comfyDir ?? "", "custom_nodes");+ if (!comfyDir || !fs.existsSync(dir)) return [];+ const known = new Map();+ for (const [name, p] of Object.entries(index.packs ?? {})) {+ known.set(name.toLowerCase(), name);+ const repo = String(p.repo ?? "").split("/").pop()?.replace(/\.git$/, "");+ if (repo) known.set(repo.toLowerCase(), name);+ }+ const out = [];+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {+ if (!e.isDirectory() || e.name.startsWith(".") || e.name === "__pycache__") continue;+ const name = known.get(e.name.toLowerCase());+ if (!name) continue;+ out.push({ name, commit: gitCommit(path.join(dir, e.name)) });+ }+ return out;+}++function gitCommit(dir) {+ try {+ const head = fs.readFileSync(path.join(dir, ".git", "HEAD"), "utf8").trim();+ if (/^[0-9a-f]{40}$/.test(head)) return head;+ const ref = /^ref: (.+)$/.exec(head)?.[1];+ if (!ref) return null;+ const loose = path.join(dir, ".git", ref);+ if (fs.existsSync(loose)) return fs.readFileSync(loose, "utf8").trim().slice(0, 40);+ const packed = fs.readFileSync(path.join(dir, ".git", "packed-refs"), "utf8");+ return packed.split("\n").find((l) => l.endsWith(` ${ref}`))?.slice(0, 40) ?? null;+ } catch {+ return null;+ }+}++/**+ * The verified files: for every file the catalog names, found in one of the model folders under its folder with the+ * exact size (and the pinned SHA-256, when there is one). A file of the wrong size isn't reported at all.+ */+export async function modelFiles(modelDirs, index, cacheFile) {+ const cache = (() => {+ try {+ return JSON.parse(fs.readFileSync(cacheFile, "utf8"));+ } catch {+ return {};+ }+ })();+ const out = [];+ for (const f of Object.values(index.files ?? {})) {+ if (!KINDS.test(f.file) && !(f.sha256 && /\.pth$/i.test(f.file))) continue;+ for (const root of modelDirs ?? []) {+ const p = path.join(root, f.folder, f.file);+ let st;+ try {+ st = fs.statSync(p);+ } catch {+ continue;+ }+ if (!st.isFile() || st.size !== f.sizeBytes) continue;+ let sha = null;+ if (f.sha256) {+ const key = `${p}|${st.size}|${st.mtimeMs}`;+ sha = cache[key] ?? (cache[key] = await sha256File(p));+ if (sha !== f.sha256) continue;+ }+ out.push({ folder: f.folder, name: f.file, size: st.size, sha256: sha });+ break;+ }+ }+ try {+ fs.writeFileSync(cacheFile, JSON.stringify(cache));+ } catch {}+ return out;+}++/** The same hash the studio computes (src/server/computer/pool.ts inventoryHash). */+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();+ return crypto.createHash("sha256").update(JSON.stringify({ files, packs })).digest("hex");+}diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsnew file mode 100644index 00000000..262127e8--- /dev/null+++ b/bin/lib/worker/run.mjs@@ -0,0 +1,207 @@+// `fuobe worker run`: the worker's loop (docs/gpu-workers.md). It beats to the studio, keeps its own ComfyUI running+// only while it may work, takes one job at a time with the same runner the browser uses, checks each graph itself,+// cleans up after each job, and pauses itself when another program uses the GPU.+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { cleanJob, emptyFolders, allowedNodes, vetGraph } from "./checks.mjs";+import { folders, OwnComfy, PortBusy } from "./comfy.mjs";+import { PROTOCOL, readControl, writeControl, writeStatus } from "./config.mjs";+import { GpuWatch, othersOf, readGpu } from "./gpu.mjs";+import { inventoryHash, modelFiles, nodePacks } from "./inventory.mjs";++const here = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(here, "../../..");++export const VERSION = (() => {+ try {+ return JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version ?? "0.0.0";+ } catch {+ return "0.0.0";+ }+})();++/** The studio's catalog, as this worker build has it. */+export function loadRequirements(file = path.join(ROOT, "workflows/comfyui/requirements.json")) {+ return JSON.parse(fs.readFileSync(file, "utf8"));+}++/**+ * The worker's local pause, from its switch (`worker pause`), the GPU, and its ComfyUI: { paused, why, until }.+ * A pause by hand ("here", "here-until:<ms>", "here-now") always wins over the GPU's.+ */+export function localPause(control, gpu, comfyTrouble, now) {+ if (control.paused && control.until && now >= control.until) return null; // its --for ran out: the caller clears it+ if (control.paused) return { paused: true, why: control.now ? "here-now" : control.until ? `here-until:${control.until}` : "here", until: control.until ?? null };+ if (gpu.paused) return { paused: true, why: `gpu-busy:${gpu.who ?? "another program"}`, until: null };+ if (comfyTrouble) return { paused: true, why: comfyTrouble, until: null };+ return { paused: false, why: null, until: null };+}++/**+ * Run until `signal` aborts. `deps`: { fetch, now, sleep, readGpu, log, home, requirements, ComputerRunner }.+ */+export async function runWorker(cfg, deps) {+ const now = deps.now ?? Date.now;+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));+ const log = deps.log ?? ((line) => console.log(`[${new Date().toISOString().slice(11, 19)}] ${line}`));+ const fetchFn = deps.fetch ?? fetch;+ const index = deps.requirements ?? loadRequirements();+ const { ComputerRunner } = deps.ComputerRunner ? { ComputerRunner: deps.ComputerRunner } : await import("./dist/computer-runner.mjs");+ const site = cfg.site.replace(/\/+$/, "");+ const f = folders(cfg.workDir);+ fs.mkdirSync(cfg.workDir, { recursive: true });+ emptyFolders(f);+ const allowed = allowedNodes(cfg.allowNodesFile);+ const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [] });+ const gpu = new GpuWatch({ autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000, resumeBelowC: cfg.resumeBelowC ?? 75 });+ let comfyTrouble = null;+ let troubleAt = 0;+ let answer = null;+ let inv = { files: [], nodePacks: [] };+ let invHash = null;+ let gpuInfo = { otherApps: [], tempC: null };+ let lastGpuAt = 0;+ let pause = { paused: true, why: "here", until: null };+ let busyJob = false;+ comfy.onCrash = (code) => log(`ComfyUI stopped (exit ${code}).`);++ const api = (p, init = {}) => fetchFn(`${site}${p}`, { ...init, headers: { ...(init.headers ?? {}), Authorization: `Bearer ${cfg.token}`, "User-Agent": `FuobeWorker/${VERSION}` } });++ async function scan() {+ inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json")), nodePacks: nodePacks(cfg.comfyDir, index) };+ invHash = inventoryHash(inv);+ }+ await scan();+ const verified = () => new Set(inv.files.flatMap((x) => [x.name, `${x.folder}/${x.name}`]));++ const runner = new ComputerRunner(+ {+ api,+ // Only its own ComfyUI, and only while the process it started is up: never whatever else listens on that port.+ local: (url, init) => (comfy.alive() && comfy.ready ? fetchFn(url, init) : Promise.reject(new Error("Its own ComfyUI isn't running"))),+ sha256: async (data) => crypto.createHash("sha256").update(Buffer.from(data)).digest("hex"),+ origin: site,+ socket: typeof WebSocket === "function" ? (url) => new WebSocket(url) : undefined,+ now,+ sleep,+ vet: (t) => vetGraph(t.graph, allowed, verified()),+ ended: (t, phase) => {+ log(`Job ${t.id} ${phase}.`);+ return cleanJob(t, f, comfy.base, fetchFn);+ },+ beatExtra: () => ({+ protocol: PROTOCOL,+ version: VERSION,+ local: pause,+ gpu: gpuInfo,+ inventoryHash: invHash,+ warmLane: null,+ }),+ onBeat: (a) => (answer = a),+ },+ { device: "worker", port: cfg.port, clientId: crypto.randomBytes(8).toString("hex") },+ );++ const mayWork = () => !pause.paused && answer?.worker && !answer.worker.paused && answer.worker.insideHours && !answer.worker.drain;+ const state = () => (pause.paused ? `Paused here (${pause.why})` : !answer ? "Connecting" : answer.worker?.paused ? "Paused on the website" : !answer.worker?.insideHours ? "Outside its hours" : answer.worker?.drain ? "Finishing, then pausing" : comfy.ready ? "Ready" : "Starting ComfyUI");++ let beatAt = 0;+ let lastState = "";+ while (!deps.signal?.aborted) {+ const t = now();+ // Its own switch, and --for running out.+ let control = readControl(deps.home);+ if (control.paused && control.until && t >= control.until) {+ writeControl(deps.home, { paused: false });+ control = { paused: false };+ gpu.clear();+ log("The pause ran out: back to work.");+ }+ if (control.resumedAt && control.resumedAt > (gpu.clearedAt ?? 0)) {+ gpu.clear();+ gpu.clearedAt = control.resumedAt;+ }+ // The GPU, every 5 s, from nvidia-smi only.+ if (t - lastGpuAt >= 5000) {+ lastGpuAt = t;+ const reading = await (deps.readGpu ?? readGpu)(cfg.nvidiaSmi);+ if (reading) {+ const verdict = othersOf(reading, { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid }, cfg.busyVramMb ?? 1024);+ const was = gpu.paused;+ gpu.update(verdict, reading.tempC, t);+ gpuInfo = { otherApps: reading.apps.filter((a) => a.pid !== comfy.pid).map((a) => ({ pid: a.pid, name: a.name, vramBytes: (a.usedMb ?? 0) * 2 ** 20 })), tempC: reading.tempC };+ if (!was && gpu.paused) log(`Another program is using the GPU (${gpu.who}): pausing.`);+ if (was && !gpu.paused) log("The GPU stayed free for the whole cool-down: resuming.");+ }+ }+ if (comfyTrouble === "comfy-crashes" && !comfy.crashedTooOften(t)) comfyTrouble = null;+ const next = localPause(control, gpu, comfyTrouble, t) ?? { paused: false, why: null, until: null };+ const changed = next.paused !== pause.paused || next.why !== pause.why;+ pause = next;+ // A new pause, or every 5 s while busy and 10 s otherwise: beat.+ if (changed || t - beatAt >= (busyJob ? 5000 : 10_000)) {+ beatAt = t;+ try {+ const a = await runner.beat();+ if (runner.view.stopped) {+ log(runner.view.stopped === "signed-out" ? "The studio doesn't know this worker's token. Run fuobe worker setup again." : "The studio stopped this worker.");+ break;+ }+ if (a?.worker?.sendInventory) {+ await scan();+ const r = await api("/api/gpu/computer/inventory", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(inv) });+ if (r.ok) {+ const body = await r.json();+ log(`Sent its files: it can run ${body.workflows?.length ?? 0} of the studio's workflows.`);+ }+ }+ } catch (e) {+ log(`Can't reach the studio: ${e.message}`);+ }+ }+ // Its own ComfyUI runs only while it may work; a pause (and a stop-now) frees the GPU.+ const stopNow = pause.paused && (pause.why === "here-now" || pause.why?.startsWith("gpu-busy")) || answer?.worker?.pauseNow;+ if (mayWork()) {+ if (!comfy.alive() && !comfyTrouble) {+ if (comfy.crashedTooOften(t)) {+ comfyTrouble = "comfy-crashes";+ log("ComfyUI keeps stopping: pausing for an hour.");+ } else {+ try {+ log("Starting its own ComfyUI.");+ await comfy.start(inv.nodePacks.map((p) => p.name));+ } catch (e) {+ if (e instanceof PortBusy) {+ comfyTrouble = "port-busy";+ troubleAt = t;+ log(`${e.message}: it won't start ComfyUI there, and won't connect to it.`);+ } else log(`ComfyUI didn't start: ${e.message}`);+ }+ }+ }+ if (comfy.ready && answer?.runner && !busyJob) {+ busyJob = true;+ void runner+ .claimAndRun()+ .catch((e) => log(`A job stopped: ${e.message}`))+ .finally(() => (busyJob = false));+ }+ } else if (comfy.alive() && (stopNow || !busyJob)) {+ log("Stopping its own ComfyUI (paused).");+ await comfy.stop();+ }+ // A taken port is tried again (a bind test, never a connection) once a minute.+ if (comfyTrouble === "port-busy" && t - troubleAt >= 60_000) comfyTrouble = null;+ const s = state();+ if (s !== lastState) {+ lastState = s;+ log(s);+ }+ writeStatus(deps.home, { state: s, pause, at: t, comfy: comfy.alive() ? comfy.pid : null, answer: answer?.worker ?? null });+ await sleep(1000);+ }+ runner.stop();+ await comfy.stop();+}diff --git a/package.json b/package.jsonindex bb9e158c..63c8692b 100644--- a/package.json+++ b/package.json@@ -8,7 +8,8 @@"scripts": {"dev": "next dev","dev:clean": "rm -rf .next && next dev",- "build": "next build",+ "build": "node scripts/build-worker.mjs && next build",+ "build:worker": "node scripts/build-worker.mjs","start": "next start","lint": "eslint","test": "vitest run",diff --git a/scripts/build-worker.mjs b/scripts/build-worker.mjsnew file mode 100644index 00000000..d6f9a429--- /dev/null+++ b/scripts/build-worker.mjs@@ -0,0 +1,51 @@+#!/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.+// `pnpm build` runs it first. No new dependency.+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import ts from "typescript";++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const out = path.join(root, "bin/lib/worker/dist");+const SOURCES = ["computer-runner", "comfy-guard", "comfy-ws", "local-comfy", "relay", "lanes", "worker-hours"];++fs.mkdirSync(out, { recursive: true });+for (const name of SOURCES) {+ const src = fs.readFileSync(path.join(root, "src/lib", `${name}.ts`), "utf8");+ const { outputText } = ts.transpileModule(src, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, verbatimModuleSyntax: false, isolatedModules: true }, fileName: `${name}.ts` });+ const js = outputText.replace(/from "\.\/([\w-]+)"/g, (m, dep) => {+ if (!SOURCES.includes(dep)) throw new Error(`${name}.ts imports ./${dep}, which the worker build doesn't include`);+ return `from "./${dep}.mjs"`;+ });+ if (/from "(@\/|\.\.\/)/.test(js)) throw new Error(`${name}.ts imports something outside src/lib's worker files`);+ fs.writeFileSync(path.join(out, `${name}.mjs`), `// Built from src/lib/${name}.ts by scripts/build-worker.mjs. Don't edit.\n${js}`);+}++// The node allowlist.+const index = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/requirements.json"), "utf8"));+const nodes = new Set();+for (const wf of Object.values(index.workflows)) {+ for (const c of wf.core) nodes.add(c);+ for (const cs of Object.values(wf.packs)) for (const c of cs) nodes.add(c);+}+for (const f of fs.readdirSync(path.join(root, "workflows/comfyui"))) {+ if (!f.endsWith(".json") || f === "requirements.json" || f === "manifest.json") continue;+ try {+ const g = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui", f), "utf8"));+ for (const n of Object.values(g)) if (n && typeof n === "object" && typeof n.class_type === "string") nodes.add(n.class_type);+ } catch {}+}+// What the graph builders add on their own (LoRA loaders, video joins, overlays…).+const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : /\.tsx?$/.test(e.name) ? [path.join(dir, e.name)] : []));+for (const file of [...walk(path.join(root, "src/lib")), ...walk(path.join(root, "src/server"))]) {+ for (const m of fs.readFileSync(file, "utf8").matchAll(/class_type: "([^"]+)"/g)) nodes.add(m[1]);+}+for (const extra of ["LoraLoader", "LoraLoaderModelOnly"]) nodes.add(extra);+const list = [...nodes].sort();+fs.writeFileSync(path.join(out, "allowed-nodes.json"), `${JSON.stringify({ built: "scripts/build-worker.mjs", nodes: list }, null, 1)}\n`);+console.log(`worker: ${SOURCES.length} modules, ${list.length} allowed node types -> ${path.relative(root, out)}`);diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.tsindex cc1b962c..7b74855a 100644--- a/src/lib/computer-runner.ts+++ b/src/lib/computer-runner.ts@@ -10,7 +10,7 @@import { isGuard } from "./comfy-guard";import { parseComfyBinary, parseComfyText } from "./comfy-ws";import { graphProblem, localBase, mayDownload, readPath, statsFacts, viewPath, writePath, type SystemStats } from "./local-comfy";-import { DONE_SHOWN_MS, RELAY_LIMITS, RELAY_TIMES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type HistoryEntryLike, type RelayState, type ReportEvent, type WantedFile } from "./relay";+import { DONE_SHOWN_MS, RELAY_LIMITS, RELAY_TIMES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type HistoryEntryLike, type RelayState, type ReportEvent, type TabFailure, type WantedFile } from "./relay";/** The parts of a WebSocket the runner uses (the browser's, or Node's). */export interface SocketLike {@@ -41,6 +41,16 @@ export interface RunnerDeps {moved?: (port: number, host: string) => void;now?: () => number;sleep?: (ms: number) => Promise<void>;+ /**+ * A worker program's own checks (docs/gpu-workers.md) before a graph goes to its ComfyUI: its node allowlist, path+ * strings, verified models. The failure, or null. (A browser tab has none: graphProblem is its check.)+ */+ vet?: (t: ClaimedTask) => TabFailure | null;+ /** A job ended here, done or not: a worker deletes its files. */+ ended?: (t: ClaimedTask, phase: LocalJob["phase"]) => void | Promise<void>;+ /** More to say in each beat (a worker's pause, its GPU, its inventory), and what the studio answered. */+ beatExtra?: () => Record<string, unknown>;+ onBeat?: (a: BeatAnswer) => void;}/** What the page shows about one job this tab runs. */@@ -349,6 +359,7 @@ export class ComputerRunner {const stopped = [...this.stoppedDone];return this.beatWith({+ ...this.deps.beatExtra?.(),device: this.o.device,port: this.o.port,ready: !!read,@@ -377,6 +388,7 @@ export class ComputerRunner {const a = (await res.json()) as BeatAnswer;Object.assign(this.view, { runner: a.runner, heldElsewhere: a.heldElsewhere, waiting: a.waiting });this.emit();+ this.deps.onBeat?.(a);if (!this.o.access) for (const s of a.stops) void this.takeOff(s);return a;}@@ -455,6 +467,15 @@ export class ComputerRunner {/** A whole job, from wherever it was. */async run(t: ClaimedTask): Promise<void> {+ try {+ await this.runJob(t);+ } finally {+ const phase = this.view.jobs.find((j) => j.taskId === t.id)?.phase;+ if (this.deps.ended && (phase === "done" || phase === "failed")) await Promise.resolve(this.deps.ended(t, phase)).catch(() => {});+ }+ }++ private async runJob(t: ClaimedTask): Promise<void> {this.promptOf.set(t.id, t.promptId);this.job(t, { phase: t.resume === "collecting" ? "saving" : t.resume === "running" ? "running" : t.resume === "queued" ? "queued" : "sending" });try {@@ -463,6 +484,11 @@ export class ComputerRunner {await this.report(t, { event: "failed", reason: "unsafe-graph" });return this.job(t, { phase: "failed" });}+ const refused = this.deps.vet?.(t);+ if (refused) {+ await this.report(t, { event: "failed", reason: refused });+ return this.job(t, { phase: "failed" });+ }let entries: HistoryEntryLike[] | null = null;let wanted = t.wanted;let phase = t.resume ?? "sending";diff --git a/tests/e2e/worker.mjs b/tests/e2e/worker.mjsnew file mode 100644index 00000000..9d417f00--- /dev/null+++ b/tests/e2e/worker.mjs@@ -0,0 +1,195 @@+// Workers end to end: a studio on 3361 with a throwaway data folder, and `fuobe worker run` (bin/lib/worker) with its+// own stand-in ComfyUI on 3362 (tests/helpers/fake-local-comfy.ts, started and stopped by the worker itself) and a+// stand-in nvidia-smi. Nothing touches any other port, and no real GPU or ComfyUI is used.+//+// pnpm build && node tests/e2e/worker.mjs+// E2E_DEV=1 node tests/e2e/worker.mjs (next dev instead of a build)+//+// Checks: the owner adds a worker, and it starts paused; resumed in both places with hours and a lane, it runs the+// owner's run to the end and cleans up its ComfyUI's history; another program on the GPU (per-process memory [N/A])+// pauses it and its ComfyUI is gone within 10 s; with the automatic resume off it stays paused, and a resume by hand+// brings it back; pause --now sends a running job back in line and stops its ComfyUI; a port another program holds is+// never used or connected to.+import { spawn } from "node:child_process";+import fs from "node:fs";+import net from "node:net";+import os from "node:os";+import path from "node:path";+import { root } from "./_browser.mjs";++const APP_PORT = Number(process.env.E2E_APP_PORT ?? 3361);+const COMFY_PORT = Number(process.env.E2E_FAKE_PORT ?? 3362);+const SITE = `http://127.0.0.1:${APP_PORT}`;+const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-worker-e2e-"));+const home = path.join(data, "worker-home");+const workDir = path.join(data, "worker-folder");+const smiState = path.join(data, "smi.json");+const results = [];+const check = (name, ok, detail = "") => {+ results.push({ name, ok: !!ok, detail });+ console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);+};+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function until(fn, ms = 30_000, every = 250) {+ const end = Date.now() + ms;+ for (;;) {+ try {+ const v = await fn();+ if (v) return v;+ } catch {}+ if (Date.now() > end) return null;+ await sleep(every);+ }+}+const smi = (s) => fs.writeFileSync(smiState, JSON.stringify(s));+const comfyUp = () => fetch(`http://127.0.0.1:${COMFY_PORT}/__fake/stats`).then((r) => r.ok, () => false);++const password = `e2e-${Math.random().toString(36).slice(2)}`;+const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), process.env.E2E_DEV ? "dev" : "start", "-p", String(APP_PORT), "-H", "127.0.0.1"], {+ cwd: root,+ env: { ...process.env, FUOBE_DATA_DIR: data, FUOBE_PASSWORD: password, COMFYUI_URL: "http://127.0.0.1:3399", ...(process.env.E2E_DEV ? {} : { NODE_ENV: "production" }) },+ stdio: ["ignore", "pipe", "pipe"],+});+let serverLog = "";+server.stdout.on("data", (d) => (serverLog += d));+server.stderr.on("data", (d) => (serverLog += d));++let workerProc = null;+let workerLog = "";+function startWorker(steps = 4) {+ fs.mkdirSync(home, { recursive: true });+ const cfg = JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8"));+ cfg.comfyCommand = [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", path.join(root, "tests/helpers/fake-local-comfy.ts"), "--port", "{port}", "--cors", "off", "--steps", String(steps), "--step-ms", "500", "--has", path.join(root, "workflows/comfyui/requirements.json")];+ fs.writeFileSync(path.join(home, "worker.json"), JSON.stringify(cfg));+ workerProc = spawn(process.execPath, [path.join(root, "bin/fuobe.mjs"), "worker", "run"], { env: { ...process.env, FUOBE_WORKER_HOME: home }, stdio: ["ignore", "pipe", "pipe"] });+ workerProc.stdout.on("data", (d) => (workerLog += d));+ workerProc.stderr.on("data", (d) => (workerLog += d));+}+async function stopWorker() {+ if (!workerProc) return;+ workerProc.kill();+ await until(() => workerProc.exitCode !== null || workerProc.signalCode, 10_000);+ workerProc = null;+ await until(async () => !(await comfyUp()), 15_000);+}+const cli = (...args) => new Promise((r) => spawn(process.execPath, [path.join(root, "bin/fuobe.mjs"), "worker", ...args], { env: { ...process.env, FUOBE_WORKER_HOME: home }, stdio: "ignore" }).once("exit", r));++async function finish() {+ await stopWorker().catch(() => {});+ server.kill();+ await sleep(500);+ try {+ fs.rmSync(data, { recursive: true, force: true });+ } catch {}+ const failed = results.filter((r) => !r.ok);+ console.log(`\n${results.length - failed.length}/${results.length} passed.`);+ if (failed.length) console.log(`--- worker\n${workerLog.split("\n").slice(-40).join("\n")}\n--- studio\n${serverLog.split("\n").slice(-30).join("\n")}`);+ process.exit(failed.length ? 1 : 0);+}++try {+ if (!(await until(() => fetch(`${SITE}/api/auth/me`).then((r) => r.ok), 180_000, 500))) throw new Error(`the studio didn't start:\n${serverLog}`);+ const login = await fetch(`${SITE}/api/auth/login`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password }) });+ const cookie = (login.headers.get("set-cookie") ?? "").split(";")[0];+ const owner = async (url, init = {}) => {+ const r = await fetch(`${SITE}${url}`, { ...init, headers: { cookie, origin: SITE, "content-type": "application/json", ...(init.headers ?? {}) } });+ return { status: r.status, body: await r.json().catch(() => null) };+ };++ // The owner adds a worker: paused, no hours, no lanes.+ const added = await owner("/api/admin/workers", { method: "POST", body: JSON.stringify({ name: "e2e-pc" }) });+ check("the owner adds a worker and sees its token once", added.status === 201 && added.body.token.startsWith("fuobe_wkr_"));+ const id = added.body.id;+ const view = async () => (await owner("/api/admin/workers")).body.workers.find((w) => w.id === id);+ check("a new worker starts paused on the website", (await view()).pausedServer === true);++ // This PC: set up (as `worker setup` writes it), paused here at first.+ fs.mkdirSync(home, { recursive: true });+ fs.writeFileSync(path.join(home, "worker.json"), JSON.stringify({ site: SITE, token: added.body.token, comfyDir: workDir, workDir, modelDirs: [], port: COMFY_PORT, nvidiaSmi: [process.execPath, path.join(root, "tests/helpers/fake-nvidia-smi.mjs"), smiState], autoResume: false, busyVramMb: 1024 }));+ fs.writeFileSync(path.join(home, "control.json"), JSON.stringify({ paused: true }));+ smi({ usedMb: 300, tempC: 45, apps: [] });+ startWorker();+ const heard = await until(async () => (await view()).seenAt, 30_000);+ check("the worker beats, paused here, and doesn't start ComfyUI", !!heard && (await view()).words === "Paused here" && !(await comfyUp()), (await view()).words);++ // Resumed in both places, with hours and the "small" lane: its own ComfyUI starts.+ await owner(`/api/admin/workers/${id}`, { method: "PATCH", body: JSON.stringify({ paused: false, hours: { always: true }, allow: { small: { delayMs: 0 } } }) });+ await owner("/api/settings", { method: "PUT", body: JSON.stringify({ comfyWhere: "workers" }) });+ await cli("resume");+ check("resumed in both places, it starts its own ComfyUI", !!(await until(comfyUp, 30_000)));+ check("its state says Ready", !!(await until(async () => (await view()).words === "Ready", 30_000)), (await view()).words);+ check("it sent its files: the studio knows what it can run", !!(await until(async () => (await view()).lanes, 20_000)));++ // A run of the owner's goes to the worker.+ const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC", "base64");+ const form = new FormData();+ form.append("file", new Blob([png], { type: "image/png" }), "in.png");+ const up = await fetch(`${SITE}/api/uploads`, { method: "POST", headers: { cookie, origin: SITE }, body: form }).then((r) => r.json());+ const run = async (prompt) => {+ const r = await owner("/api/generations", { method: "POST", body: JSON.stringify({ feature: "selftest", modelId: "oss-selftest-image", op: "edit", prompt, inputs: { images: [up.url] } }) });+ return r.body?.items?.[0]?.id;+ };+ const gid = await run("worker run one");+ const done = await until(async () => {+ const g = (await owner(`/api/generations/${gid}`)).body;+ return ["succeeded", "failed", "canceled"].includes(g?.status) ? g : null;+ }, 90_000, 1000);+ check("the owner's run finishes on the worker", done?.status === "succeeded", done ? `${done.status} ${done.error ?? ""}` : `timed out; upload ${JSON.stringify(up).slice(0, 120)}`);+ const stats = await until(async () => {+ const s = await fetch(`http://127.0.0.1:${COMFY_PORT}/__fake/stats`).then((r) => r.json());+ return s.posts >= 1 && s.history === 0 ? s : null;+ }, 15_000);+ check("after the job, its history entry is gone from the worker's ComfyUI", !!stats, JSON.stringify(stats));+ check("the worker's input and output folders are empty", ["input", "output", "temp"].every((d) => !fs.existsSync(path.join(workDir, d)) || fs.readdirSync(path.join(workDir, d)).length === 0));++ // Another program takes the GPU ([N/A] per process, as on Windows): it pauses, and its ComfyUI is gone within 10 s.+ smi({ usedMb: 6000, tempC: 60, apps: [{ pid: 999999, name: "blender.exe", usedMb: null }] });+ const t0 = Date.now();+ const gone = await until(async () => !(await comfyUp()), 15_000);+ check("another program on the GPU: its ComfyUI is stopped within 10 s", !!gone && Date.now() - t0 <= 10_000 + 1000, `${Date.now() - t0} ms`);+ check("the website says why", !!(await until(async () => /busy/.test((await view()).words), 15_000)), (await view()).words);+ smi({ usedMb: 300, tempC: 45, apps: [] });+ await sleep(12_000);+ check("with the automatic resume off, it stays paused when the GPU is free again", !(await comfyUp()) && /busy/.test((await view()).words), (await view()).words);+ await cli("resume");+ check("a resume by hand brings it back", !!(await until(comfyUp, 30_000)));++ // pause --now: a running job goes back in line and its ComfyUI stops within 30 s.+ await stopWorker();+ startWorker(60);+ await until(comfyUp, 30_000);+ await until(async () => (await view()).words === "Ready", 30_000);+ const long = await run("worker run two");+ const running = await until(async () => (await view()).current, 30_000);+ check("a long run starts on the worker", !!running);+ await cli("pause", "--now");+ const t1 = Date.now();+ check("pause --now: its ComfyUI is gone within 30 s", !!(await until(async () => !(await comfyUp()), 30_000)) && Date.now() - t1 <= 30_000, `${Date.now() - t1} ms`);+ const back = await until(async () => {+ const q = (await owner("/api/admin/queue")).body;+ const g = (await owner(`/api/generations/${long}`)).body;+ return q?.lanes?.some((l) => l.waiting >= 1) && !["failed", "canceled"].includes(g?.status) ? q : null;+ }, 20_000);+ check("pause --now: the job is back in line, not failed", !!back, JSON.stringify(back)?.slice(0, 160));+ await owner(`/api/generations/${long}/cancel`, { method: "POST" }).catch(() => {});++ // Another program holds the worker's port: it never starts ComfyUI there, and never connects to it.+ await stopWorker();+ let connections = 0;+ const squatter = net.createServer((s) => {+ connections++;+ s.destroy();+ });+ await new Promise((r) => squatter.listen(COMFY_PORT, "127.0.0.1", r));+ await cli("resume");+ startWorker();+ const refused = await until(() => /won't start ComfyUI there/.test(workerLog), 30_000);+ await sleep(3000);+ check("a port another program holds: the worker refuses it and never connects to it", !!refused && connections === 0, `connections ${connections}`);+ check("the website says its port is taken", !!(await until(async () => /port/.test((await view()).words), 15_000)), (await view()).words);+ await stopWorker();+ squatter.close();+} catch (e) {+ check("the run", false, String(e?.stack ?? e));+}+await finish();diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.tsindex 8f1749b0..efb90da4 100644--- a/tests/helpers/fake-local-comfy.ts+++ b/tests/helpers/fake-local-comfy.ts@@ -435,7 +435,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc};if (req.method === "OPTIONS") return reply(200, "");// The stand-in's own count, for a test driving it from another process (never a ComfyUI route).- if (url.pathname === "/__fake/stats") return reply(200, { posts, uploads: inputs.size });+ if (url.pathname === "/__fake/stats") return reply(200, { posts, uploads: inputs.size, history: history.size, pid: process.pid });const p = url.pathname;if (p === "/system_stats" || p === "/api/system_stats") {const argv = ["main.py", ...(opts.cors === "off" ? [] : ["--enable-cors-header", opts.cors]), "--base-directory", "C:\\Users\\someone\\private"];@@ -543,6 +543,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locreturn reply(200, h ? { [id]: h } : {});}if (p === "/history" && req.method === "POST") {+ // ComfyUI's own: { delete: [ids] } or { clear: true } (a worker cleans up after each job).const asked = JSON.parse(body.toString("utf8") || "{}") as { delete?: string[]; clear?: boolean };entry.body = asked;if (asked.clear) history.clear();diff --git a/tests/helpers/fake-nvidia-smi.mjs b/tests/helpers/fake-nvidia-smi.mjsnew file mode 100644index 00000000..44aa205a--- /dev/null+++ b/tests/helpers/fake-nvidia-smi.mjs@@ -0,0 +1,12 @@+// A stand-in for nvidia-smi (the worker's GPU check, bin/lib/worker/gpu.mjs): it answers the two queries the worker+// makes from a JSON file the test writes: { "usedMb": 900, "tempC": 50, "apps": [{ "pid": 1, "name": "python.exe",+// "usedMb": null }] } (usedMb null prints [N/A], as Windows does).+//+// node tests/helpers/fake-nvidia-smi.mjs <state.json> --query-gpu=memory.used,temperature.gpu --format=csv,noheader,nounits+import fs from "node:fs";++const [file, ...args] = process.argv.slice(2);+const s = JSON.parse(fs.readFileSync(file, "utf8"));+if (args.some((a) => a.startsWith("--query-gpu"))) process.stdout.write(`${s.usedMb}, ${s.tempC ?? 40}\n`);+else if (args.some((a) => a.startsWith("--query-compute-apps"))) for (const a of s.apps ?? []) process.stdout.write(`${a.pid}, ${a.name}, ${a.usedMb === null || a.usedMb === undefined ? "[N/A]" : a.usedMb}\n`);+else process.exit(2);diff --git a/tests/worker-program.test.ts b/tests/worker-program.test.tsnew file mode 100644index 00000000..925646c7--- /dev/null+++ b/tests/worker-program.test.ts@@ -0,0 +1,149 @@+import fs from "node:fs";+import net from "node:net";+import os from "node:os";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { GpuWatch, othersOf, parseApps, parseGpu } from "../bin/lib/worker/gpu.mjs";+import { cleanJob, vetGraph } from "../bin/lib/worker/checks.mjs";+import { comfyArgs, OwnComfy, PortBusy, portFree } from "../bin/lib/worker/comfy.mjs";+import { parseFor, syncedFolder } from "../bin/lib/worker/config.mjs";+import { localPause } from "../bin/lib/worker/run.mjs";+import { inventoryHash as workerHash } from "../bin/lib/worker/inventory.mjs";++const MIN = 60_000;+const PORT = 3367;++describe("the GPU check (check 11)", () => {+ it("reads nvidia-smi, [N/A] included", () => {+ expect(parseGpu("6144, 61\n")).toEqual({ usedMb: 6144, tempC: 61 });+ expect(parseApps("1234, C:\\Program Files\\Blender\\blender.exe, [N/A]\n77, python.exe, 2048\n")).toEqual([+ { pid: 1234, name: "blender.exe", usedMb: null },+ { pid: 77, name: "python.exe", usedMb: 2048 },+ ]);+ });++ it("counts others' VRAM as the total minus its own ComfyUI's", () => {+ const own = { running: true, mb: 9000, pid: 77 };+ expect(othersOf({ usedMb: 9800, apps: [{ pid: 77, name: "python.exe", usedMb: null }] }, own, 1024).busy).toBe(false);+ expect(othersOf({ usedMb: 12000, apps: [{ pid: 77, name: "python.exe", usedMb: null }, { pid: 5, name: "blender.exe", usedMb: null }] }, own, 1024)).toMatchObject({ busy: true, who: "blender.exe" });+ // Stopped, it holds nothing: a ComfyUI on 8188 that keeps its models loaded keeps the worker paused.+ expect(othersOf({ usedMb: 4000, apps: [] }, { running: false }, 1024).busy).toBe(true);+ expect(othersOf({ usedMb: 300, apps: [{ pid: 9, name: "game.exe", usedMb: 2000 }] }, { running: false }, 1024)).toMatchObject({ busy: true, who: "game.exe" });+ });++ it("pauses at once; with the automatic resume off, never resumes by itself", () => {+ const g = new GpuWatch({ autoResume: false, resumeAfterMs: 10 * MIN, resumeBelowC: 75 });+ g.update({ busy: true, who: "blender.exe" }, 60, 0);+ expect(g.paused).toBe(true);+ g.update({ busy: false }, 40, 1);+ g.update({ busy: false }, 40, 120 * MIN);+ expect(g.paused).toBe(true);+ g.clear();+ expect(g.paused).toBe(false);+ });++ it("with it on, resumes only after the whole cool-down; one busy reading starts it again; a hot GPU waits", () => {+ const g = new GpuWatch({ autoResume: true, resumeAfterMs: 10 * MIN, resumeBelowC: 75 });+ g.update({ busy: true, who: "x" }, 60, 0);+ g.update({ busy: false }, 50, 1 * MIN);+ g.update({ busy: false }, 50, 10 * MIN);+ expect(g.paused).toBe(true);+ g.update({ busy: true, who: "x" }, 60, 10.5 * MIN);+ g.update({ busy: false }, 50, 11 * MIN);+ g.update({ busy: false }, 50, 20.9 * MIN);+ expect(g.paused).toBe(true);+ g.update({ busy: false }, 80, 21 * MIN);+ expect(g.paused).toBe(true);+ g.update({ busy: false }, 70, 21.1 * MIN);+ expect(g.paused).toBe(false);+ });++ it("a pause by hand always wins over the GPU and its automatic resume", () => {+ const free = { paused: false, who: null };+ expect(localPause({ paused: true }, free, null, 0)).toEqual({ paused: true, why: "here", until: null });+ expect(localPause({ paused: true }, { paused: true, who: "x" }, null, 0)?.why).toBe("here");+ expect(localPause({ paused: false }, { paused: true, who: "blender.exe" }, null, 0)?.why).toBe("gpu-busy:blender.exe");+ expect(localPause({ paused: true, now: true }, free, null, 0)?.why).toBe("here-now");+ expect(localPause({ paused: false }, free, "port-busy", 0)).toEqual({ paused: true, why: "port-busy", until: null });+ });++ it("--for 2h ends by itself after 2 hours (check 10)", () => {+ const until = 2 * 60 * MIN;+ expect(parseFor("2h")).toBe(until);+ expect(parseFor("2 days")).toBeNull();+ expect(localPause({ paused: true, until }, { paused: false }, null, until - 1)?.why).toBe(`here-until:${until}`);+ expect(localPause({ paused: true, until }, { paused: false }, null, until)).toBeNull();+ });+});++describe("graph checks (check 7)", () => {+ const allowed = new Set(["LoadImage", "SaveImage", "KSampler", "CheckpointLoaderSimple"]);+ const verified = new Set(["model.safetensors", "checkpoints/model.safetensors"]);+ it("refuses an unknown node, a path, an unverified model; passes the rest", () => {+ const ok = { "1": { class_type: "CheckpointLoaderSimple", inputs: { ckpt_name: "model.safetensors" } }, "2": { class_type: "SaveImage", inputs: { filename_prefix: "fuobe/x", text: "wait.. a fox" } } };+ expect(vetGraph(ok, allowed, verified)).toBeNull();+ expect(vetGraph({ "1": { class_type: "ExecuteAnything", inputs: {} } }, allowed, verified)).toBe("unknown-node");+ for (const p of ["C:\\Windows\\win.ini", "/etc/passwd", "../../secrets.txt", "\\\\server\\share\\x", "~/x"]) {+ expect(vetGraph({ "1": { class_type: "LoadImage", inputs: { image: p } } }, allowed, verified)).toBe("unsafe-path");+ }+ expect(vetGraph({ "1": { class_type: "CheckpointLoaderSimple", inputs: { ckpt_name: "other.safetensors" } } }, allowed, verified)).toBe("model-unverified");+ });+});++describe("its own ComfyUI (check 12)", () => {+ it("a port another program holds: refused, and nothing connects to it", async () => {+ let connections = 0;+ const squatter = net.createServer((s) => {+ connections++;+ s.destroy();+ });+ await new Promise<void>((r) => squatter.listen(PORT, "127.0.0.1", r));+ try {+ expect(await portFree(PORT)).toBe(false);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-worker-port-"));+ const c = new OwnComfy({ port: PORT, workDir: dir, comfyDir: dir, comfyCommand: [process.execPath, "-e", "setTimeout(()=>{},1e6)"] });+ await expect(c.start()).rejects.toBeInstanceOf(PortBusy);+ expect(c.alive()).toBe(false);+ expect(connections).toBe(0);+ } finally {+ await new Promise((r) => squatter.close(r));+ }+ expect(await portFree(PORT)).toBe(true);+ });++ it("starts with its own folders, localhost only, no metadata, no browser, only the packs it needs", () => {+ const a = comfyArgs({ port: 8190, workDir: "/w" }, ["ComfyUI-VideoHelperSuite"]);+ expect(a).toEqual(expect.arrayContaining(["--listen", "127.0.0.1", "--port", "8190", "--disable-auto-launch", "--disable-metadata", "--disable-all-custom-nodes", "--whitelist-custom-nodes", "ComfyUI-VideoHelperSuite"]));+ expect(a[a.indexOf("--input-directory") + 1]).toBe(path.join("/w", "input"));+ });+});++describe("cleanup (check 13) and setup", () => {+ it("after a job, its files leave the worker folder and its history entry goes", async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-worker-clean-"));+ const f = { input: path.join(dir, "input"), output: path.join(dir, "output"), temp: path.join(dir, "temp") };+ for (const d of Object.values(f)) fs.mkdirSync(d, { recursive: true });+ fs.writeFileSync(path.join(f.input, "fuobe_abcdefgh12.png"), "x");+ fs.mkdirSync(path.join(f.output, "fuobe"));+ fs.writeFileSync(path.join(f.output, "fuobe", "out_00001_.png"), "x");+ fs.writeFileSync(path.join(f.temp, "preview.png"), "x");+ const calls: string[] = [];+ await cleanJob({ inputs: [{ name: "fuobe_abcdefgh12.png" }], promptId: "p-1" }, f, "http://127.0.0.1:1", (async (url: string, init: RequestInit) => {+ calls.push(`${init.method} ${url} ${init.body}`);+ return new Response("{}");+ }) as typeof fetch);+ expect(Object.values(f).flatMap((d) => fs.readdirSync(d))).toEqual([]);+ expect(calls).toEqual(['POST http://127.0.0.1:1/history {"delete":["p-1"]}']);+ });++ it("refuses a synced folder", () => {+ expect(syncedFolder("C:\\Users\\me\\OneDrive\\Worker")).toBe(true);+ expect(syncedFolder("D:\\FuobeWorker")).toBe(false);+ });++ it("hashes its inventory the way the studio does", async () => {+ const { inventoryHash } = await import("@/server/computer/pool");+ const inv = { files: [{ folder: "loras", name: "a.safetensors", size: 7, sha256: null }], nodePacks: [{ name: "P", commit: null }] };+ expect(workerHash(inv)).toBe(inventoryHash(inv));+ });+});