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: their ComfyUI starts with only the environment it needs
Adarshd600a5b20090
diff --git a/bin/lib/worker/comfy.mjs b/bin/lib/worker/comfy.mjsindex 26990f17..6e7237e0 100644--- a/bin/lib/worker/comfy.mjs+++ b/bin/lib/worker/comfy.mjs@@ -65,13 +65,55 @@ export function comfyArgs(cfg, packs = []) {];}+/**+ * What ComfyUI's process needs from this PC's environment, by name: the system's own variables, where things are+ * (PATH, the temp folder, the user's folders for model caches) and the graphics card's settings. Nothing else reaches+ * it: no keys, no tokens, no other program's settings.+ */+const PASS = new Set([+ "SYSTEMROOT", "WINDIR", "SYSTEMDRIVE", "COMSPEC", "PATHEXT", "PATH", "TEMP", "TMP", "TMPDIR", "OS",+ "NUMBER_OF_PROCESSORS", "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER", "PROCESSOR_LEVEL", "PROCESSOR_REVISION",+ "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "HOME", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA", "ALLUSERSPROFILE",+ "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432", "COMMONPROGRAMFILES", "COMMONPROGRAMFILES(X86)", "COMMONPROGRAMW6432",+ "LANG", "LANGUAGE", "LC_ALL", "LC_CTYPE", "TZ", "XDG_CACHE_HOME", "XDG_RUNTIME_DIR", "LD_LIBRARY_PATH",+ "PYTHONIOENCODING", "PYTHONUTF8", "OMP_NUM_THREADS", "MKL_NUM_THREADS",+ "HF_HOME", "HF_HUB_CACHE", "HUGGINGFACE_HUB_CACHE", "TRANSFORMERS_CACHE", "TORCH_HOME",+]);+/** The graphics card's and its libraries' settings. */+const PASS_PREFIX = /^(CUDA_|CUDNN_|NVIDIA_|PYTORCH_CUDA_)/;++/** Set for every start: models load only from what is on this PC, and nothing installs or downloads at run time. */+export const OFFLINE_ENV = { HF_HUB_OFFLINE: "1", TRANSFORMERS_OFFLINE: "1", HF_DATASETS_OFFLINE: "1", PIP_NO_INDEX: "1" };++/**+ * ComfyUI's environment: the variables it needs from this PC's (`env`), then the PC owner's own `comfyEnv` from+ * worker.json (never a FUOBE_ variable), then the offline settings, which nothing overrides.+ * @param {Record<string, string | undefined>} [env]+ * @param {Record<string, unknown>} [extra]+ * @returns {Record<string, string>}+ */+export function comfyEnv(env = process.env, extra = {}) {+ const out = {};+ for (const [k, v] of Object.entries(env)) {+ if (typeof v !== "string") continue;+ const name = k.toUpperCase();+ if (PASS.has(name) || PASS_PREFIX.test(name)) out[k] = v;+ }+ for (const [k, v] of Object.entries(extra && typeof extra === "object" ? extra : {})) {+ if (/^FUOBE_/i.test(k) || typeof v !== "string") continue;+ out[k] = v;+ }+ return { ...out, ...OFFLINE_ENV };+}+/** 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 }+ * @param cfg the worker's settings (comfyDir, workDir, port, modelDirs, comfyEnv; `comfyCommand` replaces the whole+ * command, for tests)+ * @param o { now, log, fetch, folderNames, env (this PC's environment, for tests) }*/constructor(cfg, o = {}) {this.cfg = cfg;@@ -113,7 +155,8 @@ export class OwnComfy {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 });+ const env = comfyEnv(this.o.env ?? process.env, this.cfg.comfyEnv);+ const child = spawn(cmd[0], cmd.slice(1), { cwd: this.cfg.comfyDir || this.cfg.workDir, env, 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);diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex aaab9cfe..1dcd64a5 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -71,7 +71,12 @@ The worker always starts and stops its own ComfyUI process. It never uses a Comf- gets the model folders through `extra_model_paths.yaml`;- starts with `--disable-metadata` and `--disable-auto-launch`;- loads only the custom node packs that the worker found (`--disable-all-custom-nodes --whitelist-custom-nodes …`).- The worker finds a pack whatever the case of its folder name, and gives ComfyUI the folder name as it is on disk.+ The worker finds a pack whatever the case of its folder name, and gives ComfyUI the folder name as it is on disk;+- gets only the environment variables that it needs: the system's own, `PATH`, the temp folder, the user folders+ (for model caches) and the graphics card's settings. Your keys, tokens and other settings do not reach it. To add a+ variable, put it in `comfyEnv` in `worker.json` (for example `{ "comfyEnv": { "MY_SETTING": "1" } }`);+- loads models only from this PC: `HF_HUB_OFFLINE=1`, `TRANSFORMERS_OFFLINE=1`, `HF_DATASETS_OFFLINE=1` and+ `PIP_NO_INDEX=1` are always set. A node that downloads its model on its first run needs that model on the PC first.**The port guard.** Before each start, the worker binds the port itself and releases it at once. If the bind fails,another program is using the port. The worker then does not start ComfyUI, pauses itself (its state says "port-busy")diff --git a/tests/worker-environment.test.ts b/tests/worker-environment.test.tsindex 3418a65a..11cf1b16 100644--- a/tests/worker-environment.test.ts+++ b/tests/worker-environment.test.ts@@ -1,12 +1,23 @@import fs from "node:fs";+import net from "node:net";import path from "node:path";import { describe, expect, it } from "vitest";-import { comfyArgs } from "../bin/lib/worker/comfy.mjs";+import { comfyArgs, comfyEnv, OFFLINE_ENV, OwnComfy } from "../bin/lib/worker/comfy.mjs";import { nodePacks, packFolders } from "../bin/lib/worker/inventory.mjs";import { minVramBytesFor, needsOf, VRAM_TOLERANCE } from "@/lib/lanes";import type { RequirementIndex } from "@/lib/gpu/types";import { tempDir } from "./helpers/temp-dir";+/** A port nothing listens on (the system picks it). */+const freePort = () =>+ new Promise<number>((resolve) => {+ const s = net.createServer();+ s.listen(0, "127.0.0.1", () => {+ const port = (s.address() as net.AddressInfo).port;+ s.close(() => resolve(port));+ });+ });+describe("the worker's node packs", () => {it("are found whatever the case of their folder, and ComfyUI gets the folder's own name", () => {const comfyDir = tempDir("fuobe-worker-packs-");@@ -28,6 +39,62 @@ describe("the worker's node packs", () => {});});+describe("its own ComfyUI's environment", () => {+ const pc = {+ SystemRoot: "C:\\Windows",+ Path: "C:\\Windows\\system32;C:\\ffmpeg\\bin",+ TEMP: "C:\\Temp",+ USERPROFILE: "C:\\Users\\me",+ CUDA_VISIBLE_DEVICES: "0",+ HF_HOME: "D:\\hf",+ HF_TOKEN: "hf_secret",+ OPENAI_API_KEY: "sk-secret",+ FUOBE_WORKER_TOKEN: "fuobe_wkr_secret",+ AWS_SECRET_ACCESS_KEY: "secret",+ PYTHONPATH: "C:\\elsewhere",+ HF_HUB_OFFLINE: "0",+ };++ it("holds only what ComfyUI needs, with downloads and installs off", () => {+ const env = comfyEnv(pc);+ expect(env).toEqual({ SystemRoot: "C:\\Windows", Path: "C:\\Windows\\system32;C:\\ffmpeg\\bin", TEMP: "C:\\Temp", USERPROFILE: "C:\\Users\\me", CUDA_VISIBLE_DEVICES: "0", HF_HOME: "D:\\hf", ...OFFLINE_ENV });+ expect(OFFLINE_ENV).toEqual({ HF_HUB_OFFLINE: "1", TRANSFORMERS_OFFLINE: "1", HF_DATASETS_OFFLINE: "1", PIP_NO_INDEX: "1" });+ });++ it("adds the PC owner's own variables from worker.json, but never a worker setting, and never turns downloads on", () => {+ const env = comfyEnv(pc, { COMFY_FLAG: "x", FUOBE_WORKER_TOKEN: "t", PIP_NO_INDEX: "0", HF_HUB_OFFLINE: "0" });+ expect(env.COMFY_FLAG).toBe("x");+ expect(env.FUOBE_WORKER_TOKEN).toBeUndefined();+ expect(env.PIP_NO_INDEX).toBe("1");+ expect(env.HF_HUB_OFFLINE).toBe("1");+ });++ it("is what the process it starts gets", async () => {+ const dir = tempDir("fuobe-worker-env-");+ const port = await freePort();+ const out = path.join(dir, "env.json");+ const script = `require("fs").writeFileSync(${JSON.stringify(out)}, JSON.stringify(process.env)); require("http").createServer((q, s) => s.end("{}")).listen(${port}, "127.0.0.1");`;+ const c = new OwnComfy({ port, workDir: dir, comfyDir: dir, comfyEnv: { COMFY_FLAG: "x" }, comfyCommand: [process.execPath, "-e", script] }, { env: { ...process.env, OPENAI_API_KEY: "sk-secret", FUOBE_WORKER_TOKEN: "fuobe_wkr_secret" } });+ try {+ await c.start();+ const seen = JSON.parse(fs.readFileSync(out, "utf8")) as Record<string, string>;+ expect(seen.OPENAI_API_KEY).toBeUndefined();+ expect(seen.FUOBE_WORKER_TOKEN).toBeUndefined();+ expect(seen.COMFY_FLAG).toBe("x");+ expect(seen.HF_HUB_OFFLINE).toBe("1");+ expect(seen.TRANSFORMERS_OFFLINE).toBe("1");+ expect(seen.PIP_NO_INDEX).toBe("1");+ // Nothing else of this process's, but what Windows itself needs in every new process (Node adds these when missing).+ const windows = process.platform === "win32" ? ["HOMEDRIVE", "HOMEPATH", "LOGONSERVER", "PATH", "SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "USERDOMAIN", "USERNAME", "USERPROFILE", "WINDIR"] : [];+ const allowed = new Set([...Object.keys(comfyEnv(process.env, { COMFY_FLAG: "x" })).map((k) => k.toUpperCase()), ...windows]);+ const extra = Object.keys(seen).filter((k) => !k.startsWith("=") && !allowed.has(k.toUpperCase()) && k in process.env);+ expect(extra).toEqual([]);+ } finally {+ await c.stop();+ }+ });+});+describe("VRAM: a card takes the lanes made for its size", () => {const index = {files: {},