Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Worker program: a CPU slot, finishing jobs, pictures made again and live previews

Adarsh7b792b9ef6ca
diff --git a/bin/lib/worker/comfy.mjs b/bin/lib/worker/comfy.mjs
index a9e3b9cd..baa54069 100644
--- a/bin/lib/worker/comfy.mjs
+++ b/bin/lib/worker/comfy.mjs
@@ -105,7 +105,8 @@ export function partnerFlag(comfyDir) {
/**
* ComfyUI's start arguments (3.3): localhost only, its own folders, no metadata, no browser, only the packs it needs,
- * and no partner nodes where this ComfyUI has the flag. `o.port`: this start's port (else worker.json's).
+ * and no partner nodes where this ComfyUI has the flag. `o.port`: this start's port (else worker.json's). The CPU slot's
+ * ComfyUI (`cfg.cpuOnly`) runs on the CPU only, and never touches the GPU.
*/
export function comfyArgs(cfg, packs = [], o = {}) {
const f = folders(cfg.workDir);
@@ -122,6 +123,7 @@ export function comfyArgs(cfg, packs = [], o = {}) {
"--extra-model-paths-config", path.join(cfg.workDir, "extra_model_paths.yaml"),
"--disable-all-custom-nodes",
...(packs.length ? ["--whitelist-custom-nodes", ...packs] : []),
+ ...(cfg.cpuOnly ? ["--cpu"] : []),
];
}
@@ -427,7 +429,8 @@ export class OwnComfy {
this.crashes = this.crashes.filter((c) => (this.o.now ?? Date.now)() - c.at < 3_600_000);
this.expectExit = false;
this.ready = false;
- const env = { ...comfyEnv(this.o.env ?? process.env, this.cfg.comfyEnv), ...(this.guarded && { [GUARD.env]: this.key }) };
+ // The CPU slot's ComfyUI sees no GPU at all.
+ const env = { ...comfyEnv(this.o.env ?? process.env, this.cfg.comfyEnv), ...(this.cfg.cpuOnly && { CUDA_VISIBLE_DEVICES: "-1" }), ...(this.guarded && { [GUARD.env]: this.key }) };
if (!this.cfg.comfyCommand) {
// The guard is written into an emptied folder at each start (nothing else stays beside it), and ComfyUI starts
// through it in Python's isolated mode: no script folder, no user site and no PYTHON* variable on its import path.
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjs
index ee9f111d..3a9522e4 100644
--- a/bin/lib/worker/config.mjs
+++ b/bin/lib/worker/config.mjs
@@ -4,8 +4,11 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-/** 2: it says which inputs it takes, makes every clip and sound again, and keeps its ComfyUI behind the guard. */
-export const PROTOCOL = 2;
+/**
+ * 2: it says which inputs it takes, makes every clip and sound again, and keeps its ComfyUI behind the guard. 3: it makes
+ * every picture of a job ticket again from its pixels too, and may have a CPU slot.
+ */
+export const PROTOCOL = 3;
/** Where the worker keeps its settings: %LOCALAPPDATA%\FuobeWorker on Windows, ~/.config/fuobe-worker elsewhere. */
export function workerHome(env = process.env, home = os.homedir()) {
diff --git a/bin/lib/worker/finish.mjs b/bin/lib/worker/finish.mjs
new file mode 100644
index 00000000..d8a7068f
--- /dev/null
+++ b/bin/lib/worker/finish.mjs
@@ -0,0 +1,172 @@
+// Finishing jobs on the worker's CPU slot (docs/gpu-workers.md, "The CPU slot"; src/lib/finish-ticket.ts). Each one runs
+// in processes of its own at low priority, in an emptied folder of its own, with a short environment (never the worker's
+// token or this PC's other settings), and is stopped when its run limit ends:
+//
+// - "model3d": scripts/model3d/finish-glb.mjs checks the GLB first: only a self-contained binary glTF (every buffer and
+// picture inside the file) is finished; any other is refused ("unsafe-model") and never read further. It writes the web
+// GLB; then scripts/model3d/render-turntable.mjs renders the turntable and its poster (CPU only). With no browser or
+// ffmpeg for the turntable here, the model goes back without one ("skipped").
+// - "path": path-child.mjs draws the camera path through the still and its depth picture, and ffmpeg encodes it.
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(here, "../../..");
+
+/** Exit code 3 of the 3D scripts: the GLB isn't self-contained (finish-glb.mjs), or no browser or ffmpeg (render-turntable.mjs). */
+const REFUSED = 3;
+
+/** The variables the scripts read (and what Node, a browser and ffmpeg need to start): nothing else of this PC's. */
+const PASS = ["PATH", "Path", "SYSTEMROOT", "SystemRoot", "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "LANG", "CHROMIUM_PATH", "FUOBE_CHROMIUM", "PLAYWRIGHT_BROWSERS_PATH"];
+
+export function scriptEnv(env = process.env, ffmpeg = null) {
+ const out = {};
+ for (const k of PASS) if (env[k] !== undefined) out[k] = env[k];
+ if (ffmpeg) out.FFMPEG_PATH = ffmpeg;
+ out.FUOBE_PARENT_PIPE = "1";
+ return out;
+}
+
+/** Run a script with Node in `cwd`: its exit code and its output's end. Stopped (with all it started) on `signal`. */
+export function runScript(script, args, { cwd, signal, env, onLine, timeoutMs = 20 * 60_000 }) {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, [script, ...args], { cwd, env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
+ child.stdin.on("error", () => {});
+ try {
+ if (child.pid) os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
+ } catch {}
+ let stdout = "";
+ let stderr = "";
+ let partial = "";
+ child.stdout.on("data", (d) => {
+ stdout = (stdout + d).slice(-20_000);
+ if (!onLine) return;
+ const lines = (partial + d).split(/\r?\n/);
+ partial = lines.pop() ?? "";
+ for (const l of lines) onLine(l);
+ });
+ child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-4000)));
+ const kill = () => {
+ if (child.exitCode !== null || !child.pid) return;
+ if (process.platform === "win32") spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).on("error", () => child.kill());
+ else child.kill("SIGKILL");
+ };
+ const timer = setTimeout(kill, timeoutMs);
+ signal?.addEventListener("abort", kill, { once: true });
+ child.once("error", () => (clearTimeout(timer), resolve({ code: -1, stdout, stderr })));
+ child.once("close", (code) => {
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", kill);
+ resolve({ code, stdout, stderr });
+ });
+ });
+}
+
+/** The last line of a script's output that parses as JSON. */
+export function lastJson(stdout) {
+ for (const line of String(stdout).trim().split(/\r?\n/).reverse()) {
+ try {
+ return JSON.parse(line);
+ } catch {}
+ }
+ return null;
+}
+
+const tail = (s) => String(s).trim().split(/\r?\n/).slice(-1)[0]?.slice(0, 160) ?? "";
+
+/** Can this checkout's Node load a package (the 3D finish needs the glTF tools and sharp)? */
+function hasPackage(name) {
+ try {
+ import.meta.resolve(name);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The finishing jobs this worker runs, and the function its CPU slot calls for one (computer-runner.ts RunnerDeps.finish).
+ * `o`: { workDir (its CPU slot's folder), ffmpeg (null: none), env, root, distDir, scripts }. `scripts` names other
+ * scripts for the GLB finish and the turntable ({ finishGlb, turntable }: a test's stand-ins).
+ */
+export function finishers(o) {
+ const root = o.root ?? ROOT;
+ const finishGlb = o.scripts?.finishGlb ?? path.join(root, "scripts/model3d/finish-glb.mjs");
+ const turntableScript = o.scripts?.turntable ?? path.join(root, "scripts/model3d/render-turntable.mjs");
+ const dist = o.distDir ?? path.join(here, "dist");
+ const env = scriptEnv(o.env ?? process.env, o.ffmpeg);
+ const kinds = [];
+ if (hasPackage("@gltf-transform/core") && hasPackage("sharp")) kinds.push("model3d");
+ if (o.ffmpeg && ["camera-path.mjs", "path-splat.mjs", "scene3d.mjs"].every((f) => fs.existsSync(path.join(dist, f))) && hasPackage("sharp")) kinds.push("path");
+
+ async function finish(t, inputs, { signal, progress }) {
+ const kind = t.finish?.kind;
+ if (!kinds.includes(kind)) return { refused: "finish-failed" };
+ // Its own emptied folder: nothing of another job is beside it, and nothing of it stays.
+ const dir = path.join(o.workDir, "finish", String(t.id).replace(/[^A-Za-z0-9_-]/g, "_"));
+ fs.rmSync(dir, { recursive: true, force: true });
+ fs.mkdirSync(dir, { recursive: true });
+ const put = (name, data) => {
+ fs.writeFileSync(path.join(dir, name), Buffer.from(data), { mode: 0o600 });
+ return path.join(dir, name);
+ };
+ try {
+ if (kind === "model3d") {
+ const raw = put("raw.glb", inputs.model);
+ const web = path.join(dir, "web.glb");
+ const r = await runScript(finishGlb, ["--in", raw, "--out", web, "--material", String(t.finish.settings.material ?? "auto"), "--limits", "account"], { cwd: dir, signal, env, timeoutMs: 5 * 60_000 });
+ if (r.code === REFUSED) return { refused: "unsafe-model" };
+ const stats = r.code === 0 && fs.existsSync(web) ? lastJson(r.stdout) : null;
+ if (!stats) return { refused: "finish-failed" };
+ progress(0.3);
+ const files = [{ role: "web", name: "web.glb", data: fs.readFileSync(web), contentType: "model/gltf-binary" }];
+ let turntable;
+ if (t.finish.settings.turntable === true) {
+ const clip = path.join(dir, "turntable.mp4");
+ const poster = path.join(dir, "poster.webp");
+ const tt = await runScript(turntableScript, ["--glb", web, "--out", clip, "--poster", poster, "--material", stats.material ?? "auto"], {
+ cwd: dir,
+ signal,
+ env,
+ timeoutMs: 10 * 60_000,
+ onLine: (line) => {
+ const m = /^frame (\d+)\/(\d+)$/.exec(line.trim());
+ if (m) progress(0.3 + 0.7 * (Number(m[1]) / Number(m[2])));
+ },
+ });
+ if (tt.code === 0 && fs.existsSync(clip)) {
+ files.push({ role: "turntable", name: "turntable.mp4", data: fs.readFileSync(clip), contentType: "video/mp4" });
+ if (fs.existsSync(poster)) files.push({ role: "poster", name: "poster.webp", data: fs.readFileSync(poster), contentType: "image/webp" });
+ } else turntable = tt.code === REFUSED ? `skipped: ${tail(tt.stderr) || "no turntable here"}` : `failed: ${tail(tt.stderr) || `exit ${tt.code}`}`;
+ }
+ const stat = { material: stats.material, triangles: stats.triangles, bytesIn: stats.bytesIn, bytesOut: stats.bytesOut };
+ return { files, stats: stat, ...(turntable && { turntable }) };
+ }
+ // "path"
+ const photo = put("photo.png", inputs.photo);
+ const depth = put("depth.png", inputs.depth);
+ const out = path.join(dir, "path.mp4");
+ const settings = path.join(dir, "settings.json");
+ fs.writeFileSync(settings, JSON.stringify(t.finish.settings));
+ const r = await runScript(path.join(here, "path-child.mjs"), [photo, depth, settings, out, o.ffmpeg, dist], {
+ cwd: dir,
+ signal,
+ env,
+ timeoutMs: 10 * 60_000,
+ onLine: (line) => {
+ const m = /^frame (\d+)\/(\d+)$/.exec(line.trim());
+ if (m) progress(Number(m[1]) / Number(m[2]));
+ },
+ });
+ if (r.code !== 0 || !fs.existsSync(out)) return { refused: "finish-failed" };
+ return { files: [{ role: "path", name: "path.mp4", data: fs.readFileSync(out), contentType: "video/mp4" }] };
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
+ }
+ }
+
+ return { kinds, finish };
+}
diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjs
index ca927f2e..25420798 100644
--- a/bin/lib/worker/index.mjs
+++ b/bin/lib/worker/index.mjs
@@ -232,6 +232,8 @@ async function setup(home, io, say) {
}
// The owner's own jobs come as full graphs; answering no takes job tickets only.
const acceptGraphs = !/^n/i.test(await ask("Also run the studio owner's own jobs, which come as whole graphs? (Y/n)", old.acceptGraphs === false ? "n" : "y"));
+ // The CPU slot: light CPU work and finishing jobs beside the GPU's job (a second ComfyUI that runs on the CPU only).
+ const cpuSlot = /^y/i.test(await ask("Also run light CPU work (joins, trims, filters) and finishing jobs (3D models, camera paths) beside the GPU's job? (y/N)", old.cpuSlot === true ? "y" : "n"));
fs.mkdirSync(workDir, { recursive: true });
if (process.platform === "win32") {
// Not content indexed: jobs' files stay out of Windows Search.
@@ -245,7 +247,7 @@ async function setup(home, io, say) {
// A token given in FUOBE_WORKER_TOKEN stays out of the file.
const { ceiling: _was, ...rest } = saved;
void _was;
- saveConfig(home, { ...rest, port, site: site.replace(/\/+$/, ""), token: token || saved.token, comfyDir, modelDirs, workDir, ffmpeg, autoResume, ...(limits.ceiling && { ceiling: limits.ceiling }), acceptGraphs });
+ saveConfig(home, { ...rest, port, site: site.replace(/\/+$/, ""), token: token || saved.token, comfyDir, modelDirs, workDir, ffmpeg, autoResume, ...(limits.ceiling && { ceiling: limits.ceiling }), acceptGraphs, cpuSlot });
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(`This PC runs ${ceilingWords(limits.ceiling)}. Run fuobe worker setup again to change it.`);
diff --git a/bin/lib/worker/path-child.mjs b/bin/lib/worker/path-child.mjs
new file mode 100644
index 00000000..1baafcff
--- /dev/null
+++ b/bin/lib/worker/path-child.mjs
@@ -0,0 +1,65 @@
+// Run by finish.mjs in a process of its own: node path-child.mjs <photo> <depth> <settings.json> <out.mp4> <ffmpeg> <dist>.
+// The camera path of a finishing job (src/lib/finish-ticket.ts, "path"), drawn as the studio's own path render does
+// (src/server/path-render.ts): the still and its depth picture become a point cloud (src/lib/scene3d.ts, built into
+// <dist>), drawn along the path's keys frame by frame (src/lib/camera-path.ts, src/lib/path-splat.ts), and encoded to an
+// H.264 MP4 by ffmpeg. Prints "frame i/N" as it goes. Exit 0 when it wrote the clip.
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import { createRequire } from "node:module";
+// sharp comes from the worker's checkout (pnpm install): the CLI package itself imports only Node's own modules.
+const sharp = (await import(pathToFileURL(createRequire(import.meta.url).resolve("sharp")).href)).default;
+
+const [photoFile, depthFile, settingsFile, out, ffmpeg, dist] = process.argv.slice(2);
+if (process.env.FUOBE_PARENT_PIPE === "1") {
+ process.stdin.on("end", () => process.exit(1));
+ process.stdin.on("error", () => process.exit(1));
+ process.stdin.resume();
+ process.stdin.unref?.();
+}
+const load = (name) => import(pathToFileURL(path.join(dist, name)).href);
+const { framePoses, renderSize } = await load("camera-path.mjs");
+const { splatFrame } = await load("path-splat.mjs");
+const { LENS, buildPointCloud, lensFov } = await load("scene3d.mjs");
+
+/** At most this many points (as the studio's own render). */
+const MAX_POINTS = 300_000;
+const LIMIT = { failOn: "error", limitInputPixels: 64 * 2 ** 20 };
+
+async function pixels(data, size) {
+ const { data: raw, info } = await sharp(data, LIMIT).rotate().removeAlpha().ensureAlpha().resize(size.width, size.height, { fit: "fill" }).raw().toBuffer({ resolveWithObject: true });
+ return { width: info.width, height: info.height, data: raw };
+}
+
+try {
+ const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
+ const photoData = fs.readFileSync(photoFile);
+ const meta = await sharp(photoData, LIMIT).metadata();
+ const aspect = (meta.autoOrient?.width ?? meta.width ?? 1) / (meta.autoOrient?.height ?? meta.height ?? 1);
+ const size = renderSize(aspect);
+ const photo = await pixels(photoData, size);
+ const depth = await pixels(fs.readFileSync(depthFile), size);
+ const hFov = lensFov(LENS.default, aspect).h;
+ const cloud = buildPointCloud(photo, depth, { hFov, maxPoints: MAX_POINTS });
+ const poses = framePoses(settings.keys, settings.frames, cloud.depth, hFov, size);
+ const count = poses.poses.length;
+ const args = ["-hide_banner", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", `${size.width}x${size.height}`, "-r", String(settings.fps), "-i", "pipe:0"];
+ args.push("-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-f", "mp4", "-y", out);
+ const child = spawn(ffmpeg, args, { stdio: ["pipe", "ignore", "ignore"], windowsHide: true });
+ const done = new Promise((resolve) => {
+ child.once("error", () => resolve(1));
+ child.once("close", (code) => resolve(code));
+ });
+ child.stdin.on("error", () => {});
+ for (let i = 0; i < count; i++) {
+ const frame = splatFrame(cloud, poses.poses[i], poses.intrinsic, size.width, size.height);
+ if (!child.stdin.write(frame)) await new Promise((r) => child.stdin.once("drain", r));
+ console.log(`frame ${i + 1}/${count}`);
+ }
+ child.stdin.end();
+ process.exit((await done) === 0 && fs.existsSync(out) ? 0 : 1);
+} catch (e) {
+ console.error(String(e?.message ?? e).slice(0, 200));
+ process.exit(1);
+}
diff --git a/bin/lib/worker/picture-child.mjs b/bin/lib/worker/picture-child.mjs
new file mode 100644
index 00000000..d43a419d
--- /dev/null
+++ b/bin/lib/worker/picture-child.mjs
@@ -0,0 +1,18 @@
+// Run by picture.mjs in a process of its own: node picture-child.mjs <src> <dst> <max pixels>. Reads one picture as it
+// came (sharp, at most <max pixels>, any error in the file refused), turns it upright by its EXIF orientation and writes
+// it as a fresh PNG with no metadata. Exit 0 when it wrote one.
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import { pathToFileURL } from "node:url";
+// sharp comes from the worker's checkout (pnpm install): the CLI package itself imports only Node's own modules.
+const sharp = (await import(pathToFileURL(createRequire(import.meta.url).resolve("sharp")).href)).default;
+
+const [src, dst, max] = process.argv.slice(2);
+try {
+ sharp.concurrency(1);
+ const png = await sharp(fs.readFileSync(src), { failOn: "error", limitInputPixels: Number(max) || 64 * 2 ** 20 }).rotate().png().toBuffer();
+ fs.writeFileSync(dst, png, { mode: 0o600 });
+ process.exit(0);
+} catch {
+ process.exit(1);
+}
diff --git a/bin/lib/worker/picture.mjs b/bin/lib/worker/picture.mjs
new file mode 100644
index 00000000..26418c42
--- /dev/null
+++ b/bin/lib/worker/picture.mjs
@@ -0,0 +1,72 @@
+// Pictures for the worker's ComfyUI (docs/gpu-workers.md). Every picture of an account's job ticket, and of a finishing
+// job, is made again from its pixels before anything on this PC reads it: turned upright by its EXIF orientation, then
+// written as a fresh PNG with nothing else of the file (no EXIF, no GPS, no XMP, no colour profile's text, no comment).
+// Only one short-lived process at low priority ever reads the picture as it came (picture-child.mjs, with sharp), with
+// a cap on its pixels and a time limit. The studio sends an account's pictures as they came, so this is the only place
+// they are decoded.
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+
+const PICTURE_EXT = new Set(["png", "jpg", "jpeg", "webp", "gif", "bmp", "tif", "tiff", "avif", "heic", "heif"]);
+const extOf = (name) => (String(name).includes(".") ? String(name).split(".").pop().toLowerCase() : "");
+
+/** Is this input a picture: by its type, else by its name. */
+export function isPicture(input) {
+ const type = String(input?.contentType ?? "").split(";")[0].trim().toLowerCase();
+ if (type) return type.startsWith("image/");
+ return PICTURE_EXT.has(extOf(input?.name));
+}
+
+/** Can this checkout make pictures again: is sharp installed beside it (pnpm install in the worker's checkout)? */
+export function canCleanPictures(resolve = (name) => createRequire(import.meta.url).resolve(name)) {
+ try {
+ resolve("sharp");
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** The most pixels a picture may have (the studio's own limit for a picture it makes again). */
+export const PICTURE_MAX_PIXELS = 64 * 2 ** 20;
+
+/** The environment of the process that reads a picture: where things are, and nothing else of this PC's. */
+function childEnv(env = process.env) {
+ const out = {};
+ for (const k of ["PATH", "Path", "SYSTEMROOT", "SystemRoot", "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "LANG"]) if (env[k] !== undefined) out[k] = env[k];
+ return out;
+}
+
+/**
+ * Make a picture again (`src` as it came, `dst` the new PNG) in its own process at low priority, stopped after
+ * `timeoutMs`. True when it made one.
+ */
+export function cleanPicture({ src, dst, timeoutMs = 2 * 60_000, spawnFn = spawn, node = process.execPath }) {
+ return new Promise((resolve) => {
+ let child;
+ try {
+ child = spawnFn(node, [path.join(here, "picture-child.mjs"), src, dst, String(PICTURE_MAX_PIXELS)], { stdio: ["ignore", "ignore", "ignore"], windowsHide: true, env: childEnv(), cwd: path.dirname(dst) });
+ } catch {
+ return resolve(false);
+ }
+ try {
+ if (child.pid) os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
+ } catch {}
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
+ child.once("error", () => (clearTimeout(timer), resolve(false)));
+ child.once("exit", (code) => {
+ clearTimeout(timer);
+ let ok = false;
+ try {
+ ok = code === 0 && fs.statSync(dst).size > 0;
+ } catch {}
+ resolve(ok);
+ });
+ });
+}
diff --git a/bin/lib/worker/preview.mjs b/bin/lib/worker/preview.mjs
new file mode 100644
index 00000000..e0dde215
--- /dev/null
+++ b/bin/lib/worker/preview.mjs
@@ -0,0 +1,70 @@
+// Live previews for the studio (docs/gpu-workers.md, "Live previews"). Its ComfyUI sends the latest preview of a job as
+// a PNG or a JPEG. The studio keeps only a JPEG of at most 64 KB, so a PNG or a bigger JPEG is made again by ffmpeg:
+// at most 512 pixels on its long side, as a JPEG, in a process of its own at low priority for at most 10 seconds. It
+// reads the picture only as a local PNG or JPEG file. When that can't make one small enough, nothing is sent.
+import { spawn } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+/** The most a preview the studio keeps may weigh (src/lib/relay.ts PREVIEW_LIMITS.maxBytes). */
+export const PREVIEW_MAX_BYTES = 64 * 1024;
+/** The long side of a preview made again. */
+export const PREVIEW_SIDE = 512;
+
+/** ffmpeg's arguments for one preview: a local PNG or JPEG in, one JPEG of at most PREVIEW_SIDE pixels out. */
+export function previewArgs(src, dst, quality = 6) {
+ const fit = `scale='min(${PREVIEW_SIDE},iw)':'min(${PREVIEW_SIDE},ih)':force_original_aspect_ratio=decrease`;
+ return ["-hide_banner", "-loglevel", "error", "-nostdin", "-protocol_whitelist", "file", "-format_whitelist", "png_pipe,jpeg_pipe,image2", "-i", src, "-frames:v", "1", "-vf", fit, "-map_metadata", "-1", "-q:v", String(quality), "-f", "mjpeg", "-y", dst];
+}
+
+function run(ffmpeg, args, { spawnFn = spawn, timeoutMs = 10_000 } = {}) {
+ return new Promise((resolve) => {
+ let child;
+ try {
+ child = spawnFn(ffmpeg, args, { stdio: ["ignore", "ignore", "ignore"], windowsHide: true });
+ } catch {
+ return resolve(false);
+ }
+ try {
+ if (child.pid) os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
+ } catch {}
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
+ child.once("error", () => (clearTimeout(timer), resolve(false)));
+ child.once("exit", (code) => (clearTimeout(timer), resolve(code === 0)));
+ });
+}
+
+/**
+ * The function the runner calls for a preview it can't send as it is (computer-runner.ts WorkerHooks.shrinkPreview):
+ * a small JPEG Blob, or null. `dir`: a folder of its own, emptied after each try. Without ffmpeg: always null.
+ */
+export function previewShrinker({ ffmpeg, dir, spawnFn = spawn }) {
+ return async (blob) => {
+ if (!ffmpeg || !blob || blob.size === 0 || blob.size > 16 * 2 ** 20) return null;
+ const head = new Uint8Array(await blob.slice(0, 8).arrayBuffer());
+ const png = head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47;
+ const jpeg = head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff;
+ if (!png && !jpeg) return null;
+ fs.mkdirSync(dir, { recursive: true });
+ const id = crypto.randomBytes(6).toString("hex");
+ const src = path.join(dir, `${id}.${png ? "png" : "jpg"}`);
+ const dst = path.join(dir, `${id}-small.jpg`);
+ try {
+ fs.writeFileSync(src, Buffer.from(await blob.arrayBuffer()), { mode: 0o600 });
+ // A busy picture may need a lower quality to fit.
+ for (const q of [6, 14]) {
+ if (!(await run(ffmpeg, previewArgs(src, dst, q), { spawnFn }))) return null;
+ const out = fs.readFileSync(dst);
+ if (out.length > 0 && out.length <= PREVIEW_MAX_BYTES) return new Blob([out], { type: "image/jpeg" });
+ }
+ return null;
+ } catch {
+ return null;
+ } finally {
+ fs.rmSync(src, { force: true });
+ fs.rmSync(dst, { force: true });
+ }
+ };
+}
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index ec69a161..8ebd00d3 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -12,6 +12,11 @@
// Studio jobs first (turns.mjs, local-work.mjs): with a turns folder set, local ComfyUI work on the PC is told apart
// from other programs. Another program still pauses the worker as before. Local ComfyUI work instead gets a request for
// a turn, and the worker waits for the answer with its jobs kept in their place.
+//
+// The CPU slot (worker.json `cpuSlot: true`): beside its GPU's job it runs one CPU task at a time, claimed for itself:
+// light CPU work (joins, trims, adding sound, loops, Ken Burns, filters) on a second ComfyUI of its own that runs on the
+// CPU only, and finishing jobs (finish.mjs: the 3D finish, camera paths) with its own code. Every picture of an account's
+// job is made again from its pixels before anything reads it (picture.mjs).
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
@@ -25,7 +30,10 @@ import { Hold } from "./hold.mjs";
import { inventoryHash, missingModelDirs, modelFiles, packFolders } from "./inventory.mjs";
import { readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";
import { takeLock, workerLives } from "./lock.mjs";
+import { finishers } from "./finish.mjs";
import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";
+import { canCleanPictures, cleanPicture, isPicture } from "./picture.mjs";
+import { previewShrinker } from "./preview.mjs";
import { withPlainResults } from "./results.mjs";
import { retrying } from "./retry.mjs";
import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";
@@ -352,8 +360,15 @@ async function work(saved, deps, owner) {
log(`${missing.length === 1 ? "A model folder isn't" : `${missing.length} model folders aren't`} there yet (${missing.join(", ")}): it takes no new job until ${missing.length === 1 ? "it is" : "they are"}, and looks again every minute.`);
if (modelsMissing.length) sayMissing(modelsMissing);
- /** An input for its ComfyUI: read from the studio once, kept by its SHA-256, and a clip or sound made again. */
- async function takeInput(t, input, read) {
+ // Pictures of an account's job are made again here: without the tool for it (pnpm install in its checkout), such a
+ // job goes back to the line for another worker.
+ const pictureTool = deps.canCleanPictures ?? canCleanPictures();
+ if (!pictureTool) log("It can't make pictures again here (run pnpm install in its checkout): an account's job with a picture goes back to the line.");
+ /**
+ * An input for its ComfyUI: read from the studio once, kept by its SHA-256 (in the slot's own `cacheDir`), a clip or
+ * sound made again by ffmpeg, and a picture of an account's job ticket or of a finishing job made again from its pixels.
+ */
+ const takeInputIn = (cacheDir) => async (t, input, read) => {
if (!/^[0-9a-f]{64}$/.test(String(input.sha256))) return "input-changed";
fs.mkdirSync(cacheDir, { recursive: true });
const kept = path.join(cacheDir, input.sha256);
@@ -369,7 +384,22 @@ async function work(saved, deps, owner) {
fs.writeFileSync(kept, data, { mode: 0o600 });
}
const kind = mediaKind(input, t.graph);
- if (!kind) return arrayBuffer(data);
+ if (!kind) {
+ // The studio sends an account's pictures as they came: no EXIF, GPS or other metadata of them reaches its ComfyUI.
+ if (!(t.ticket || t.finish) || !isPicture(input)) return arrayBuffer(data);
+ if (!pictureTool) return "give-back";
+ const clean = path.join(cacheDir, `${input.sha256}.png`);
+ if (!fs.existsSync(clean)) {
+ const part = `${clean}.part`;
+ if (!(await (deps.cleanPicture ?? cleanPicture)({ src: kept, dst: part }))) {
+ fs.rmSync(part, { force: true });
+ log(`Job ${t.id}: one of its pictures couldn't be read.`);
+ return "input-unreadable";
+ }
+ fs.renameSync(part, clean);
+ }
+ return arrayBuffer(fs.readFileSync(clean));
+ }
// Without ffmpeg it takes no clip or sound: another worker that can make them again runs the job.
if (!ffmpeg) return "give-back";
const made = path.join(cacheDir, `${input.sha256}.${kind}`);
@@ -389,15 +419,16 @@ async function work(saved, deps, owner) {
return "input-unreadable";
}
return arrayBuffer(fs.readFileSync(made));
- }
+ };
+ const takeInput = takeInputIn(cacheDir);
- /** A job ticket's graph, composed here (or why it is refused). */
- async function composeJob(t) {
+ /** A job ticket's graph, composed here (or why it is refused), from the facts of the ComfyUI that runs it. */
+ async function composeJob(t, ownFetch = own, base = comfy.base) {
if (!catalogVersion) return { refused: "update-worker" };
composer ??= await import("./dist/compose/lib/ticket-compose.mjs");
// Each workflow's lane, when its ceiling names lanes.
if (ceiling?.lanes && !laneOf) laneOf = laneMap(index, deps.allLanes ?? (await import("./dist/lanes.mjs")).allLanes);
- const facts = composer.workerFactsFrom(await readPcAnswers(own, comfy.base));
+ const facts = composer.workerFactsFrom(await readPcAnswers(ownFetch, base));
const r = await composer.composeTicket({ ticket: t.ticket, generationId: t.generationId, inputs: t.inputs }, { catalog: workerCatalog(catalogDir), catalogVersion, ceiling, laneOf, facts });
if (r.ok) return { graph: r.graph, made: r.made };
// Why, for the PC's owner (never a setting's value: those are someone's prompt).
@@ -405,6 +436,64 @@ async function work(saved, deps, owner) {
return { refused: r.reason };
}
+ /** The worker's own checks of a job's graph before its ComfyUI sees it (checks.mjs): the reason it refuses it, or null. */
+ async function vetJob(t) {
+ const check = () => graphCheck(t.graph, allowed, inv.files, { rules, staged: (t.inputs ?? []).map((i) => i.name) });
+ let problem = check();
+ // A model file it doesn't have yet (a drive that came back after a restart): look again once before refusing.
+ if (problem?.reason === "model-unverified") {
+ log(`Job ${t.id} needs a model file it hasn't found: looking at its model folders again.`);
+ await rescan();
+ problem = check();
+ }
+ // Which node and input, for the PC's owner (never a value: those are someone's prompt or file).
+ if (problem) log(`Refused job ${t.id}: ${problem.reason} at node ${problem.node}${problem.cls ? ` (${problem.cls}${problem.input ? `.${problem.input}` : ""})` : ""}.`);
+ return problem?.reason ?? null;
+ }
+
+ // The CPU slot (worker.json `cpuSlot: true`): its own ComfyUI on the CPU only (its own folders, port, key and kept
+ // inputs), its own kept results, and the finishing jobs this PC can run.
+ const cpuOn = cfg.cpuSlot === true;
+ const cpuDir = path.join(cfg.workDir, "cpu");
+ const fc = folders(cpuDir);
+ const cpuCacheDir = path.join(cpuDir, "cache");
+ // Its kept inputs, and anything a finishing job left behind (a stop mid-job), go after each job, at start and at exit.
+ const emptyCpuCache = () => {
+ fs.rmSync(cpuCacheDir, { recursive: true, force: true });
+ fs.rmSync(path.join(cpuDir, "finish"), { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });
+ };
+ const cpuComfy = cpuOn
+ ? new OwnComfy(
+ { ...cfg, workDir: cpuDir, port: null, cpuOnly: true, ...(cfg.cpuComfyCommand && { comfyCommand: cfg.cpuComfyCommand }) },
+ { now, fetch: fetchFn, folderNames: index.folders ?? [], log, owner, workerLives: (rec) => workerLives(rec, { commandLineOf: deps.comfy?.commandLineOf }), ...deps.comfy },
+ )
+ : null;
+ const cpuHold = cpuOn ? new Hold(path.join(cfg.workDir, "hold-cpu")) : null;
+ const cpuOwnFetch = withPlainResults((url, init) => cpuComfy.fetch(url, init));
+ const cpuOwn = (url, init) => (cpuComfy?.alive() && cpuComfy.ready ? cpuOwnFetch(url, init) : Promise.reject(new Error("Its CPU slot's ComfyUI isn't running")));
+ const finish = cpuOn ? (deps.finishers ?? finishers({ workDir: cpuDir, ffmpeg: ffmpeg ? ffmpegBin : null })) : null;
+ if (cpuOn) {
+ fs.mkdirSync(cpuDir, { recursive: true });
+ emptyFolders(fc);
+ emptyCpuCache();
+ await cpuComfy.stopLeftover();
+ cpuComfy.onCrash = (code, task) => {
+ log(`Its CPU slot's ComfyUI stopped (exit ${code}).`);
+ if (!task) return;
+ crashes[task] = (crashes[task] ?? 0) + 1;
+ saveCrashes();
+ };
+ log(`It has a CPU slot: light CPU work${finish.kinds.length ? ` and finishing jobs (${finish.kinds.join(", ")})` : ""} run beside its GPU's job.`);
+ }
+ let cpuRunner = null;
+ let busyCpu = false;
+ let cpuJob = Promise.resolve();
+ let cpuStarting = null;
+ let lastCpuTask = null;
+ /** What a slot's runner says it works on, for the beat. */
+ const runningOf = (r) =>
+ r.view.jobs.filter((j) => j.phase !== "done" && j.phase !== "failed").map((j) => ({ task: j.taskId, ...(j.position !== undefined && { position: j.position }), ...(j.phase === "running" && { value: j.value, max: j.max }) }));
+
const runner = new ComputerRunner(
{
api: call,
@@ -416,19 +505,7 @@ async function work(saved, deps, owner) {
socket: typeof WebSocket === "function" ? (url) => (comfy.ready ? new WebSocket(comfy.rebase(url), { headers: comfy.headers() }) : null) : undefined,
now,
sleep,
- vet: async (t) => {
- const check = () => graphCheck(t.graph, allowed, inv.files, { rules, staged: (t.inputs ?? []).map((i) => i.name) });
- let problem = check();
- // A model file it doesn't have yet (a drive that came back after a restart): look again once before refusing.
- if (problem?.reason === "model-unverified") {
- log(`Job ${t.id} needs a model file it hasn't found: looking at its model folders again.`);
- await rescan();
- problem = check();
- }
- // Which node and input, for the PC's owner (never a value: those are someone's prompt or file).
- if (problem) log(`Refused job ${t.id}: ${problem.reason} at node ${problem.node}${problem.cls ? ` (${problem.cls}${problem.input ? `.${problem.input}` : ""})` : ""}.`);
- return problem?.reason ?? null;
- },
+ vet: vetJob,
ended: async (t, phase) => {
log(`Job ${t.id} ${phase}.`);
// Done: the studio has every result. Otherwise its kept results wait for the next claim to say whose job it is,
@@ -455,9 +532,11 @@ async function work(saved, deps, owner) {
catalogVersion,
...(ceiling && { ceiling }),
// The jobs whose results it keeps: a pause doesn't send them back in line, so they go up instead of running again.
- held: hold.ids().slice(0, 16),
+ held: [...hold.ids(), ...(cpuHold?.ids() ?? [])].slice(0, 16),
// The PC slept: a job taken back from it meanwhile goes on with no blame.
...(slept > 0 && { slept }),
+ // Its CPU slot: the finishing jobs it runs, and the task it works on.
+ ...(cpuOn && { cpuSlot: { finishes: finish.kinds }, cpuRunning: cpuRunner ? runningOf(cpuRunner) : [] }),
};
},
onBeat: (a) => {
@@ -492,6 +571,8 @@ async function work(saved, deps, owner) {
stallMs: 10 * 60_000,
stallLocalMs: Number(cfg.stallMin) > 0 ? Number(cfg.stallMin) * 60_000 : null,
free: () => comfy.free(),
+ // A live preview that isn't a small JPEG is made again by ffmpeg (none without it).
+ shrinkPreview: deps.shrinkPreview ?? previewShrinker({ ffmpeg: ffmpeg ? ffmpegBin : null, dir: path.join(cfg.workDir, "preview") }),
crashes: (t) => crashes[t.id] ?? 0,
stuck: async () => {
log("Its ComfyUI didn't let go of a job: starting it again.");
@@ -522,6 +603,68 @@ async function work(saved, deps, owner) {
{ device: "worker", port: cfg.port || 8190, clientId: crypto.randomBytes(8).toString("hex") },
);
+ // The CPU slot's runner: the same runner, on its CPU-only ComfyUI, claiming for its CPU slot. It never beats (the
+ // worker's beat says what it works on), and its jobs never wait for the GPU's.
+ if (cpuOn) {
+ cpuRunner = new ComputerRunner(
+ {
+ api: call,
+ local: cpuOwn,
+ compose: (t) => composeJob(t, cpuOwn, cpuComfy.base),
+ sha256: async (data) => sha256(Buffer.from(data)),
+ origin: site,
+ socket: typeof WebSocket === "function" ? (url) => (cpuComfy.ready ? new WebSocket(cpuComfy.rebase(url), { headers: cpuComfy.headers() }) : null) : undefined,
+ now,
+ sleep,
+ vet: vetJob,
+ finish: (t, inputs, o) => finish.finish(t, inputs, o),
+ ended: async (t, phase) => {
+ log(`CPU slot job ${t.id} ${phase}.`);
+ if (phase === "done") cpuHold.drop(t.id);
+ delete crashes[t.id];
+ saveCrashes();
+ await cleanJob(fc, cpuComfy.base, cpuOwn);
+ emptyCpuCache();
+ },
+ worker: {
+ hold: cpuHold,
+ input: takeInputIn(cpuCacheDir),
+ graphs: cfg.acceptGraphs !== false,
+ inside: (t) => graphInside(ceiling, t),
+ stallMs: 10 * 60_000,
+ stallLocalMs: Number(cfg.stallMin) > 0 ? Number(cfg.stallMin) * 60_000 : null,
+ free: () => cpuComfy.free(),
+ crashes: (t) => crashes[t.id] ?? 0,
+ stuck: async () => {
+ log("Its CPU slot's ComfyUI didn't let go of a job: starting it again.");
+ await cpuComfy.stop();
+ },
+ claimed: async (t) => {
+ if (!t) return void emptyCpuCache();
+ cpuHold.dropAllBut(t.id);
+ cpuComfy.task = t.id;
+ if (t.id !== lastCpuTask) {
+ await cleanJob(fc, cpuComfy.base, cpuOwn);
+ emptyCpuCache();
+ lastCpuTask = t.id;
+ }
+ },
+ },
+ },
+ { device: "worker-cpu", port: 8191, clientId: crypto.randomBytes(8).toString("hex"), slot: "cpu" },
+ );
+ }
+ const takeCpu = () => {
+ busyCpu = true;
+ cpuJob = cpuRunner
+ .claimAndRun()
+ .catch((e) => log(`A CPU slot job stopped: ${e.message}`))
+ .finally(() => {
+ busyCpu = false;
+ cpuComfy.task = null;
+ });
+ };
+
const mayWork = () => !pause.paused && answer?.worker && !answer.worker.paused && answer.worker.insideHours && !answer.worker.drain;
const state = () =>
pause.why === "models-not-ready"
@@ -749,6 +892,26 @@ async function work(saved, deps, owner) {
log("Stopping its own ComfyUI (paused).");
await comfy.stop();
}
+ // The CPU slot: its ComfyUI runs only while the worker may work, and it takes its own work beside the GPU's job (it
+ // needs no turn and no free GPU). Another program on the GPU lets its task finish; a stop-now stops it too.
+ if (cpuOn) {
+ if (mayWork()) {
+ if (!cpuComfy.alive() && !cpuStarting && t >= cpuComfy.restartAt && !cpuComfy.crashedTooOften(t)) {
+ cpuStarting = cpuComfy
+ .start(
+ packs.map((p) => p.folder),
+ { signal: stopStarts.signal },
+ )
+ .catch((e) => {
+ if (!stopStarts.signal.aborted && mayWork()) log(`Its CPU slot's ComfyUI didn't start: ${e.message}`);
+ })
+ .finally(() => (cpuStarting = null));
+ }
+ if (cpuComfy.ready && answer?.runner && !busyCpu) takeCpu();
+ } else if (cpuComfy.alive() && (!busyCpu || pause.why === "here-now" || answer?.worker?.pauseNow)) {
+ await cpuComfy.stop();
+ }
+ }
// Kept results the studio never took are deleted after a day.
if (t - holdCheckedAt >= 60_000) {
holdCheckedAt = t;
@@ -757,7 +920,7 @@ async function work(saved, deps, owner) {
// Kept results go up first, and even while it may not work (or waits for its turn): they need no GPU and no ComfyUI.
if (!busyJob && answer && heldFirst) take({ onlyHeld: true });
// Awake while it holds a job, has results to send, or waits for work.
- awake.set(!!answer?.worker && (busyJob || hold.ids().length > 0 || !!mayWork()));
+ awake.set(!!answer?.worker && (busyJob || busyCpu || hold.ids().length > 0 || !!mayWork()));
// 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();
@@ -779,7 +942,8 @@ async function work(saved, deps, owner) {
// Every way out: the job in hand stops (its kept results stay for the next start), its ComfyUI stops, the PC may
// sleep again, and no input, result or cached file stays in its folders.
runner.stop();
- await Promise.race([job, new Promise((r) => setTimeout(r, 10_000).unref?.())]);
+ cpuRunner?.stop();
+ await Promise.race([Promise.all([job, cpuJob]), new Promise((r) => setTimeout(r, 10_000).unref?.())]);
awake.set(false);
// No turn any more: local ComfyUI work may go on at once.
if (turns?.folderOk()) writeTurn(now(), { siteWaiting: 0, oldestWaitS: 0, interrupt: false, interruptAt: null });
@@ -790,6 +954,13 @@ async function work(saved, deps, owner) {
await comfy.stop();
emptyFolders(f);
emptyCache();
+ if (cpuOn) {
+ await cpuComfy.stop();
+ await cpuStarting;
+ await cpuComfy.stop();
+ emptyFolders(fc);
+ emptyCpuCache();
+ }
}
return deps.signal?.aborted ? "aborted" : (runner.view.stopped ?? "disconnected");
}
diff --git a/scripts/lib/worker-build.mjs b/scripts/lib/worker-build.mjs
index 82b37887..423a336e 100644
--- a/scripts/lib/worker-build.mjs
+++ b/scripts/lib/worker-build.mjs
@@ -24,7 +24,7 @@ import { unruledPathInputs } from "./catalog-checks.mjs";
import { allowedNodeList, filePins, inputRules, missingRules, readCatalog } from "./worker-catalog.mjs";
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
-export const SOURCES = ["computer-runner", "comfy-guard", "comfy-ws", "fetch-within", "local-comfy", "relay", "lanes", "worker-hours"];
+export const SOURCES = ["computer-runner", "comfy-guard", "comfy-ws", "fetch-within", "local-comfy", "relay", "lanes", "worker-hours", "finish-ticket", "camera-path", "path-splat", "scene3d"];
/**
* What the worker learns from the catalog: its node allowlist, its input rules and its file pins. Throws when an input
diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.ts
index 108a3a53..55ca8677 100644
--- a/tests/helpers/fake-local-comfy.ts
+++ b/tests/helpers/fake-local-comfy.ts
@@ -12,7 +12,8 @@
* Runs under plain Node too: only erasable TypeScript.
*/
import { createHash, createHmac, randomUUID } from "node:crypto";
-import { appendFileSync, readFileSync } from "node:fs";
+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
import http from "node:http";
import type { Duplex } from "node:stream";
import { pathToFileURL } from "node:url";
@@ -82,6 +83,8 @@ export interface LocalComfyOptions {
countFile?: string;
/** Each prompt posted adds its graph to this file, as one line of JSON (what a test in another process sent). */
graphFile?: string;
+ /** A folder that keeps a copy of every upload, under its name (a test reads what reached ComfyUI). */
+ uploadDir?: string;
}
/** One live render the stand-in made (for the bookkeeping checks). */
@@ -521,6 +524,10 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
if (!image || !name || /[\\/]|\.\./.test(name)) return reply(400, { error: "bad name" });
inputs.set(name, Buffer.from(image.data));
entry.upload = { name, bytes: Buffer.from(image.data) };
+ if (opts.uploadDir) {
+ mkdirSync(opts.uploadDir, { recursive: true });
+ writeFileSync(join(opts.uploadDir, name), Buffer.from(image.data));
+ }
void pictureSize(Buffer.from(image.data)).then((sz) => sz && sizes.set(name, sz));
return reply(200, { name, subfolder: "", type: parts.get("type")?.data.toString() ?? "input" });
}
@@ -761,7 +768,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
// [--connect <origin>]: Fuobe Connect is installed, trusting that origin. [--worker-guard 1]: a worker's guard, with the
// key in FUOBE_WORKER_GUARD_KEY (as a worker starts its ComfyUI). [--count-file <path>]: a line for each prompt posted.
// [--graph-file <path>]: each prompt's graph, a line of JSON each. [--fail-next oom|never]: what the first prompt does.
-// [--outputs video,audio]: what a job saves.
+// [--outputs video,audio]: what a job saves. [--upload-dir <path>]: a copy of every upload, under its name.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
@@ -782,6 +789,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
...(workerGuard && { workerGuard }),
...(arg("count-file") && { countFile: arg("count-file") }),
...(arg("graph-file") && { graphFile: arg("graph-file") }),
+ ...(arg("upload-dir") && { uploadDir: arg("upload-dir") }),
...(arg("fail-next") && { failNext: arg("fail-next") as LocalComfyOptions["failNext"] }),
...(arg("outputs") && { outputs: arg("outputs")!.split(",") as LocalComfyOptions["outputs"] }),
has,
diff --git a/tests/worker-cpu-slot.test.ts b/tests/worker-cpu-slot.test.ts
new file mode 100644
index 00000000..c9a34af3
--- /dev/null
+++ b/tests/worker-cpu-slot.test.ts
@@ -0,0 +1,573 @@
+/**
+ * The CPU slot in the worker program (bin/lib/worker/run.mjs) against the studio's real routes, with the worker's own
+ * stand-in ComfyUIs (processes of its own, behind the worker's guard). Never a real ComfyUI, never a GPU.
+ *
+ * - A CPU task runs on the CPU slot while a GPU job runs.
+ * - A 3D model whose GLB names an outside file is refused on the worker, and its run keeps the model as it is.
+ * - A 3D model's finish comes back with its web GLB, its turntable and its poster, stored on the run.
+ * - An account's picture with EXIF reaches its ComfyUI made again from its pixels, with no EXIF.
+ * - A live preview reaches the studio as a small JPEG; one over 64 KB is dropped.
+ * - With a worker that finishes 3D models, an account's Image to 3D run on this install's GPUs is taken.
+ */
+import { spawnSync } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { finishers } from "../bin/lib/worker/finish.mjs";
+import { previewArgs, previewShrinker, PREVIEW_MAX_BYTES } from "../bin/lib/worker/preview.mjs";
+import { workerFiles } from "../scripts/lib/worker-build.mjs";
+import { runWorker } from "../bin/lib/worker/run.mjs";
+import { inputRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";
+import { FAKE_MP4, FAKE_PNG } from "./helpers/fake-local-comfy";
+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 120_000 });
+
+const dir = tempDir("fuobe-worker-cpu-slot-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const finish = await import("@/server/computer/finish");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const { comfyProvider } = await import("@/server/providers/comfyui");
+const hosted = await import("@/server/hosted");
+const { saveFile, getAsset, absolutePath } = await import("@/server/storage");
+const { runAsTenant } = await import("@/server/tenant");
+const { asAccount, createGenerations } = await import("@/server/generations");
+const { withRunStamp } = await import("@/server/run-stamp");
+const { getModel } = await import("@/lib/catalog");
+const { allLanes } = await import("@/lib/lanes");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { ComputerRunner } = await import("@/lib/computer-runner");
+const composer = await import("@/lib/ticket-compose");
+
+const ROOT = path.resolve(__dirname, "..");
+const FAKE = path.join(ROOT, "tests/helpers/fake-local-comfy.ts");
+const SITE = "http://127.0.0.1:9";
+const RULES = inputRules(readCatalog(ROOT));
+const ALLOWED = new Set(["LoadImage", "ImageInvert", "SaveImage", "KSampler"]);
+const VERSION = catalogVersion()!;
+const realFetch = globalThis.fetch;
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;
+/** Workflows the requirements index marks as light CPU work (the self-test only inverts a picture), and one that uses the GPU. */
+const CPU_WORKFLOW = "video-trim";
+const GPU_WORKFLOW = "bg-remove-rmbg";
+
+let routes: ComputerRoutes;
+let accountId = "";
+beforeAll(async () => {
+ routes = await loadRoutes();
+ setSetting("comfyWhere", "workers");
+ auth.setPassword("install password");
+ accountId = auth.createAccount("[email protected]", "long enough").id;
+});
+afterAll(() => {
+ globalThis.__fuobeTestDiskFree = undefined;
+});
+beforeEach(() => {
+ resetRates();
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+});
+
+type W = { id: string; token: string };
+type TaskRow = import("@/server/computer/tasks").TaskRow;
+const row = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;
+const LANE = pool.poolLane("selftest-image");
+
+/** A worker the owner added and resumed, all day, allowed every lane, able to run every workflow. */
+function addWorker(): W {
+ const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);
+ const lanes = allLanes(loadIndex(), sha);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ const workflows = (JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/manifest.json"), "utf8")) as { workflows: { id: string }[] }).workflows.map((x) => x.id);
+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);
+ return w;
+}
+
+let gens = 0;
+function generation(account: string | null, op = "edit") {
+ const gid = `cpu-slot-worker-gen-${++gens}`;
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-selftest-image', 'open', 'comfyui', ?, 'image', 'running', ?, '[]', ?, ?)")
+ .run(gid, op, JSON.stringify(account ? { account, place: "pool" } : {}), now, now);
+ return gid;
+}
+
+/** The owner's own job of this workflow on the workers: a whole graph that inverts a picture. */
+function ownerTask(workflowId: string, o: { preview?: boolean } = {}) {
+ const gid = generation(null);
+ const picture = tasks.stageInput("owner", FAKE_PNG, "image/png", "in.png");
+ const graph = { "1": { class_type: "LoadImage", inputs: { image: picture } }, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/cpu-slot" } } };
+ const t = tasks.createTask({ principal: "owner", generationId: gid, graph, workflowId, ...(o.preview && { preview: true }), pool: pool.poolFields(workflowId, { class: "owner" }) });
+ return { id: t.id, gid };
+}
+
+/** A one-triangle GLB; `image` adds a picture (and a texture that uses it) with that URI. */
+function glb(image?: string): Buffer {
+ const bin = Buffer.alloc(36);
+ [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => bin.writeFloatLE(v, i * 4));
+ const json: Record<string, unknown> = {
+ asset: { version: "2.0" },
+ buffers: [{ byteLength: 36 }],
+ bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }],
+ accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: "VEC3", min: [0, 0, 0], max: [1, 1, 0] }],
+ meshes: [{ primitives: [{ attributes: { POSITION: 0 }, ...(image && { material: 0 }) }] }],
+ nodes: [{ mesh: 0 }],
+ scenes: [{ nodes: [0] }],
+ scene: 0,
+ ...(image && { images: [{ uri: image, mimeType: "image/png" }], textures: [{ source: 0 }], materials: [{ emissiveTexture: { index: 0 }, emissiveFactor: [1, 1, 1] }] }),
+ };
+ let j = Buffer.from(JSON.stringify(json));
+ j = Buffer.concat([j, Buffer.alloc((4 - (j.length % 4)) % 4, 0x20)]);
+ const header = Buffer.alloc(12);
+ header.writeUInt32LE(0x46546c67, 0);
+ header.writeUInt32LE(2, 4);
+ header.writeUInt32LE(12 + 8 + j.length + 8 + bin.length, 8);
+ const jh = Buffer.alloc(8);
+ jh.writeUInt32LE(j.length, 0);
+ jh.writeUInt32LE(0x4e4f534a, 4);
+ const bh = Buffer.alloc(8);
+ bh.writeUInt32LE(bin.length, 0);
+ bh.writeUInt32LE(0x004e4942, 4);
+ return Buffer.concat([header, jh, j, bh, bin]);
+}
+
+/** A stand-in for the turntable render (no browser here): it writes a clip and a poster, and says its frames. */
+function standInTurntable(): string {
+ const file = path.join(tempDir("fuobe-cpu-slot-turntable-"), "turntable.mjs");
+ fs.writeFileSync(
+ file,
+ `import fs from "node:fs";
+const arg = (n) => process.argv[process.argv.indexOf("--" + n) + 1];
+if (!fs.existsSync(arg("glb"))) process.exit(1);
+for (let i = 1; i <= 4; i++) console.log("frame " + i + "/4");
+fs.writeFileSync(arg("out"), Buffer.from(${JSON.stringify(FAKE_MP4.toString("hex"))}, "hex"));
+fs.writeFileSync(arg("poster"), Buffer.from("RIFF0000WEBPVP8 poster"));
+console.log(JSON.stringify({ frames: 4, fps: 24 }));
+`,
+ );
+ return file;
+}
+
+// ---------------------------------------------------------------------------
+// The worker program
+
+interface Studio {
+ reports: (Record<string, unknown> & { task: string })[];
+ claims: { slot?: string }[];
+}
+const studio = (): Studio => ({ reports: [], claims: [] });
+
+/** fetch for the worker: the studio's routes for SITE, its own ComfyUIs for the rest. */
+function router(w: W, s: Studio) {
+ const api = apiAs(routes, null);
+ return async (url: string, init: RequestInit = {}) => {
+ if (!String(url).startsWith(SITE)) return realFetch(url, init);
+ const u = new URL(url);
+ const p = u.pathname + u.search;
+ if (p === "/api/gpu/computer/inventory") return Response.json({ ok: true, lanes: [LANE], workflows: ["selftest-image"], missing: [] });
+ if (typeof init.body === "string" && init.body.startsWith("{")) {
+ const body = JSON.parse(init.body) as Record<string, unknown>;
+ const m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/report$/.exec(u.pathname);
+ if (m) s.reports.push({ ...body, task: m[1] });
+ if (u.pathname === "/api/gpu/computer/claim") s.claims.push(body as { slot?: string });
+ }
+ expect(new Headers(init.headers).get("authorization")).toBe(`Bearer ${w.token}`);
+ return api(p, init);
+ };
+}
+
+interface Pc {
+ home: string;
+ workDir: string;
+ comfyDir: string;
+ uploadDir: string;
+ logs: string[];
+}
+function pc(): Pc {
+ const base = tempDir("fuobe-cpu-slot-pc-");
+ const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), uploadDir: path.join(base, "uploads"), logs: [] as string[] };
+ for (const d of [p.home, p.workDir, p.comfyDir]) fs.mkdirSync(d, { recursive: true });
+ return p;
+}
+
+const running: { ctrl: AbortController; done: Promise<unknown> }[] = [];
+afterEach(async () => {
+ for (const r of running.splice(0)) {
+ r.ctrl.abort();
+ await r.done.catch(() => {});
+ }
+});
+
+const standIn = (o: { steps: number; stepMs: number; uploadDir?: string }) => [
+ process.execPath,
+ "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON",
+ FAKE,
+ "--port",
+ "{port}",
+ "--cors",
+ "off",
+ "--steps",
+ String(o.steps),
+ "--step-ms",
+ String(o.stepMs),
+ "--worker-guard",
+ "1",
+ ...(o.uploadDir ? ["--upload-dir", o.uploadDir] : []),
+];
+
+/** Start `fuobe worker run` in this process with a CPU slot (`cpuSlot`), its ComfyUIs stand-in processes of their own. */
+function start(w: W, s: Studio, p: Pc, o: { gpu?: { steps: number; stepMs: number }; cpu?: { steps: number; stepMs: number }; cpuSlot?: boolean; finishers?: unknown; shrinkPreview?: (b: Blob) => Promise<Blob | null> } = {}) {
+ const ctrl = new AbortController();
+ const cfg = {
+ site: SITE,
+ token: w.token,
+ comfyDir: p.comfyDir,
+ workDir: p.workDir,
+ modelDirs: [],
+ comfyCommand: standIn({ ...(o.gpu ?? { steps: 3, stepMs: 30 }), uploadDir: p.uploadDir }),
+ cpuComfyCommand: standIn({ ...(o.cpu ?? { steps: 2, stepMs: 20 }), uploadDir: p.uploadDir }),
+ comfyGuard: true,
+ stallMin: 10,
+ ffmpeg: null,
+ cpuSlot: o.cpuSlot !== false,
+ };
+ const done = runWorker(cfg, {
+ fetch: router(w, s),
+ home: p.home,
+ signal: ctrl.signal,
+ requirements: { folders: [], files: {}, packs: {}, workflows: {} },
+ ComputerRunner,
+ rules: RULES,
+ pins: {},
+ allowed: ALLOWED,
+ readGpu: async () => null,
+ readGpuGen: async () => "8.9",
+ ffmpegVersion: async () => null,
+ awake: { set: () => {} },
+ sleep: (ms: number) => sleep(Math.min(ms, 50)),
+ log: (line: string) => void p.logs.push(line),
+ composer,
+ catalogVersion: VERSION,
+ allLanes,
+ ...(o.finishers !== undefined && { finishers: o.finishers }),
+ ...(o.shrinkPreview && { shrinkPreview: o.shrinkPreview }),
+ });
+ const r = { ctrl, done };
+ running.push(r);
+ return r;
+}
+
+async function until<T>(fn: () => T | Promise<T>, ms = 60_000, every = 100): Promise<Exclude<T, false | null | undefined | 0 | "">> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = await fn();
+ if (v) return v as Exclude<T, false | null | undefined | 0 | "">;
+ if (Date.now() > end) throw new Error(`Timed out after ${ms} ms`);
+ await sleep(every);
+ }
+}
+const ENDED = ["done", "failed", "canceled"];
+const ended = (id: string) => until(() => ENDED.includes(row(id).state) && row(id), 90_000);
+
+describe("the worker program's CPU slot", () => {
+ it("runs a CPU task while its GPU's job runs, each claimed for its own slot", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const gpu = ownerTask(GPU_WORKFLOW);
+ const cpu = ownerTask(CPU_WORKFLOW);
+ expect(row(cpu.id).slot).toBe("cpu");
+ expect(row(gpu.id).slot).toBeNull();
+ // A slow GPU job (about 4 s) and a quick CPU task.
+ start(w, s, p, { gpu: { steps: 40, stepMs: 100 } });
+ const cpuDone = await ended(cpu.id);
+ expect(cpuDone.state, cpuDone.error ?? "").toBe("done");
+ // The GPU's job was still going when the CPU task ended.
+ expect(["sending", "queued", "running", "collecting"]).toContain(row(gpu.id).state);
+ expect(cpuDone.device).toBe(`wkr-${w.id}-cpu`);
+ const gpuDone = await ended(gpu.id);
+ expect(gpuDone.state, gpuDone.error ?? "").toBe("done");
+ expect(gpuDone.device).toBe(`wkr-${w.id}`);
+ expect(fs.readFileSync(tasks.outputFile(cpu.id, 0)).length).toBeGreaterThan(0);
+ expect(s.claims.some((c) => c.slot === "cpu")).toBe(true);
+ // The studio heard its CPU slot in its beat.
+ expect(JSON.parse(db().prepare("SELECT cpu_slot_json FROM relay_workers WHERE id = ?").pluck().get(w.id) as string)).toHaveProperty("finishes");
+ });
+
+ it("without a CPU slot, it takes light CPU work in its GPU's slot, as before", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const cpu = ownerTask(CPU_WORKFLOW);
+ start(w, s, p, { cpuSlot: false });
+ const t = await ended(cpu.id);
+ expect(t.state, t.error ?? "").toBe("done");
+ expect(t.device).toBe(`wkr-${w.id}`);
+ expect(s.claims.some((c) => c.slot === "cpu")).toBe(false);
+ });
+});
+
+describe("the 3D finish on the worker", () => {
+ it("refuses a GLB that names an outside file, and never reads it; the run keeps its model as it is", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const gid = generation(accountId, "image-to-3d");
+ const raw = saveFile({ data: glb("../secret-marker.png"), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid });
+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];
+ let finished: unknown[] | null = null;
+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void (finished = o) });
+ const id = finish.finishTask(gid, "model3d")!.id;
+ start(w, s, p);
+ const t = await ended(id);
+ expect(t.state).toBe("failed");
+ expect(t.error).toBe("tab:unsafe-model");
+ expect(s.reports).toContainEqual(expect.objectContaining({ task: id, event: "failed", reason: "unsafe-model" }));
+ const kept = await until(() => finished, 30_000);
+ expect(kept).toHaveLength(1);
+ expect((kept[0] as { meta: { finish: { error: string }; web?: string } }).meta.finish.error).toMatch(/self-contained/);
+ expect((kept[0] as { meta: { web?: string } }).meta.web).toBeUndefined();
+ // Nothing of the job stays in the CPU slot's folder.
+ expect(fs.existsSync(path.join(p.workDir, "cpu", "finish"))).toBe(false);
+ });
+
+ it("sends back the web GLB with its turntable and poster, and the run stores them", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const gid = generation(accountId, "image-to-3d");
+ const raw = saveFile({ data: glb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid });
+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];
+ let finished: import("@/lib/catalog/types").OutputFile[] | null = null;
+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void (finished = o) });
+ const id = finish.finishTask(gid, "model3d")!.id;
+ const made = finishers({ workDir: path.join(p.workDir, "cpu"), ffmpeg: null, scripts: { turntable: standInTurntable() } });
+ expect(made.kinds).toContain("model3d");
+ start(w, s, p, { finishers: made });
+ const t = await ended(id);
+ expect(t.state, t.error ?? "").toBe("done");
+ const got = await until(() => finished, 30_000);
+ const mesh = got.find((o) => o.kind === "model3d")!;
+ const meta = mesh.meta as { web: string; poster: string; finish: { turntable: string; webAsset: string; triangles: number } };
+ expect(meta.finish.turntable).toBe("done");
+ expect(meta.finish.triangles).toBe(1);
+ expect(meta.web).toBeTruthy();
+ expect(meta.poster).toBeTruthy();
+ // The web GLB is a binary glTF the worker wrote; the turntable is the clip it rendered.
+ const web = getAsset(meta.finish.webAsset)!;
+ expect(fs.readFileSync(absolutePath(web.relPath)).subarray(0, 4).toString()).toBe("glTF");
+ const clip = got.find((o) => o.kind === "video" && o.meta?.role === "turntable")!;
+ expect(fs.readFileSync(absolutePath(getAsset(clip.assetId!)!.relPath)).equals(FAKE_MP4)).toBe(true);
+ // Stored as the account's files.
+ expect(db().prepare("SELECT account_id FROM assets WHERE id = ?").pluck().get(clip.assetId)).toBe(accountId);
+ });
+
+ it("the studio keeps an account's 3D model from the workers only as a binary glTF with every part inside it", async () => {
+ const { outputType } = await import("@/server/computer/http");
+ const want = { n: 0, filename: "m.glb", subfolder: "", type: "output" as const, kind: "model3d" as const, maxBytes: 1e6 };
+ expect(finish.glbSelfContained(glb())).toBe(true);
+ expect(finish.glbSelfContained(glb(`data:image/png;base64,${FAKE_PNG.toString("base64")}`))).toBe(true);
+ for (const uri of ["../secret.png", "file:///etc/passwd", "https://example.com/x.png", "C:\\x.png"]) expect(finish.glbSelfContained(glb(uri)), uri).toBe(false);
+ const ply = Buffer.from("ply\nformat ascii 1.0\n");
+ expect(finish.glbSelfContained(ply)).toBe(false);
+ const file = path.join(tempDir("fuobe-cpu-slot-glb-"), "m.glb");
+ fs.writeFileSync(file, glb("../secret.png"));
+ expect(finish.glbFileSelfContained(file)).toBe(false);
+ fs.writeFileSync(file, glb());
+ expect(finish.glbFileSelfContained(file)).toBe(true);
+ // An account's run: a glTF only when its 3D finish runs on a worker, and never a PLY.
+ expect(() => outputType(glb(), want, false)).toThrow(/3D model/);
+ expect(outputType(glb(), want, false, { glb: true })).toBe("model/gltf-binary");
+ expect(() => outputType(ply, want, false, { glb: true })).toThrow(/3D model/);
+ expect(outputType(ply, want, true)).toBe("model/ply");
+ });
+
+ it("with a worker that finishes 3D models, an account's Image to 3D run on this install's GPUs is taken", () => {
+ const photo = saveFile({ data: FAKE_PNG, contentType: "image/png", source: "upload", accountId }).url;
+ const request = { feature: "image-to-3d", modelId: "oss-pixal3d", op: "image-to-3d", prompt: "", inputs: { images: [photo] }, engine: "open" } as Parameters<typeof createGenerations>[0];
+ const onPool = () => asAccount(accountId, () => withRunStamp({ place: "pool" }, () => createGenerations(request)));
+ expect(onPool).toThrow();
+ const w = addWorker();
+ pool.workerBeat(
+ db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as never,
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: VERSION, cpuSlot: { finishes: ["model3d"] } }),
+ );
+ const made = onPool();
+ expect(made[0].kind).toBe("model3d");
+ expect(JSON.parse(db().prepare("SELECT request_json FROM generations WHERE id = ?").pluck().get(made[0].id) as string).place).toBe("pool");
+ });
+});
+
+describe("camera paths on the worker", () => {
+ /** The worker's built parts the path render reads (camera-path, path-splat and scene3d), in a folder of their own. */
+ function builtParts(): string {
+ const out = tempDir("fuobe-cpu-slot-dist-");
+ const files = workerFiles().files as unknown as Record<string, string>;
+ for (const f of ["camera-path.mjs", "path-splat.mjs", "scene3d.mjs"]) fs.writeFileSync(path.join(out, f), files[f]);
+ return out;
+ }
+
+ it.runIf(hasFfmpeg)("draws a step's camera path on the worker's CPU slot, and the run keeps the clip once", async () => {
+ const sharp = (await import("sharp")).default;
+ const photo = saveFile({ data: await sharp({ create: { width: 64, height: 48, channels: 3, background: "#36c" } }).png().toBuffer(), contentType: "image/png", name: "still.png", source: "upload", accountId });
+ const depth = saveFile({ data: await sharp({ create: { width: 64, height: 48, channels: 3, background: "#808080" } }).png().toBuffer(), contentType: "image/png", name: "depth.png", source: "derived", accountId });
+ const gid = generation(accountId, "image-to-video");
+ const keys = [
+ { t: 0, azimuth: 0, elevation: 0, distance: 1 },
+ { t: 1, azimuth: 20, elevation: 4, distance: 0.8 },
+ ];
+ const step = () => runAsTenant({ kind: "account", id: accountId }, () => finish.pathOnWorker(gid, 0, { photo: photo.url, depth: depth.url, keys, frames: 9, fps: 16 }));
+ expect(await step()).toEqual({ state: "waiting" });
+ // Asked again before it is done: the same job, still waiting.
+ expect(await step()).toEqual({ state: "waiting" });
+ const id = finish.finishTask(gid, "path")!.id;
+ expect(db().prepare("SELECT COUNT(*) FROM relay_tasks WHERE generation_id = ?").pluck().get(gid)).toBe(1);
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const made = finishers({ workDir: path.join(p.workDir, "cpu"), ffmpeg: "ffmpeg", distDir: builtParts() });
+ expect(made.kinds).toContain("path");
+ start(w, s, p, { finishers: made });
+ const t = await ended(id);
+ expect(t.state, t.error ?? "").toBe("done");
+ const got = await step();
+ expect(got.state).toBe("done");
+ const url = (got as { url: string }).url;
+ const clip = (db().prepare("SELECT id FROM assets WHERE generation_id = ? AND name = 'path-render.mp4'").all(gid) as { id: string }[]).map((r) => getAsset(r.id)!);
+ expect(clip).toHaveLength(1);
+ expect(clip[0].url).toBe(url);
+ expect(fs.readFileSync(absolutePath(clip[0].relPath)).subarray(4, 8).toString()).toBe("ftyp");
+ // Kept once: asked again, the same clip.
+ expect(await step()).toEqual({ state: "done", url });
+ expect(db().prepare("SELECT COUNT(*) FROM assets WHERE generation_id = ? AND name = 'path-render.mp4'").pluck().get(gid)).toBe(1);
+ });
+});
+
+describe("an account's pictures on the worker", () => {
+ it("a picture with EXIF reaches its ComfyUI made again from its pixels, with no EXIF", async () => {
+ const sharp = (await import("sharp")).default;
+ const jpeg = await sharp({ create: { width: 64, height: 48, channels: 3, background: "#c33" } })
+ .jpeg()
+ .withExif({ IFD0: { Copyright: "private note", Artist: "someone" } })
+ .toBuffer();
+ expect((await sharp(jpeg).metadata()).exif).toBeDefined();
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const gid = generation(accountId);
+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;
+ const { picture, sent } = await hosted.runOnPool(accountId, async () => {
+ const name = (await comfyProvider.prepareFile!(jpeg, "image/jpeg", "me.jpg", route))!;
+ return { picture: name, sent: await comfyProvider.submit({ route, input: { images: [name], seed: 5 }, generationId: gid, model: getModel("oss-selftest-image") } as never) };
+ });
+ const id = String((sent.meta as { relay: string }).relay);
+ // The studio keeps it as it came.
+ expect(fs.readFileSync(path.join(dir, "relay", "in", picture)).equals(jpeg)).toBe(true);
+ start(w, s, p);
+ const t = await ended(id);
+ expect(t.state, t.error ?? "").toBe("done");
+ const reached = fs.readFileSync(path.join(p.uploadDir, picture));
+ const meta = await sharp(reached).metadata();
+ expect(meta.format).toBe("png");
+ expect(meta.exif).toBeUndefined();
+ expect([meta.width, meta.height]).toEqual([64, 48]);
+ expect(reached.includes(Buffer.from("private note"))).toBe(false);
+ });
+});
+
+describe("live previews from the worker", () => {
+ const jpeg = (bytes: number) => {
+ const b = Buffer.alloc(bytes, 7);
+ b[0] = 0xff;
+ b[1] = 0xd8;
+ b[2] = 0xff;
+ return b;
+ };
+ const previews = (s: Studio, id: string) => s.reports.filter((r) => r.task === id && r.event === "running" && typeof r.preview === "string");
+
+ it("sends its ComfyUI's preview as a small JPEG, at most one every 2 s, and the studio keeps it", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const t = ownerTask(GPU_WORKFLOW, { preview: true });
+ const small = jpeg(20_000);
+ const asked: string[] = [];
+ // Its ComfyUI's previews are PNGs: the worker makes each one again as a JPEG.
+ start(w, s, p, { gpu: { steps: 12, stepMs: 400 }, shrinkPreview: async (b) => (asked.push(b.type), new Blob([small], { type: "image/jpeg" })) });
+ const got = await until(() => tasks.taskPreview(t.id), 30_000);
+ expect(got.jpeg.equals(small)).toBe(true);
+ expect(asked[0]).toBe("image/png");
+ expect((await ended(t.id)).state).toBe("done");
+ const sent = previews(s, t.id);
+ expect(sent.length).toBeGreaterThan(0);
+ // At most one every 2 s: a 5 s job sends at most 3.
+ expect(sent.length).toBeLessThanOrEqual(3);
+ });
+
+ it("drops a preview over 64 KB, keeping the progress", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const t = ownerTask(GPU_WORKFLOW, { preview: true });
+ start(w, s, p, { gpu: { steps: 8, stepMs: 400 }, shrinkPreview: async () => new Blob([jpeg(70 * 1024)], { type: "image/jpeg" }) });
+ expect((await ended(t.id)).state).toBe("done");
+ expect(previews(s, t.id)).toEqual([]);
+ expect(s.reports.some((r) => r.task === t.id && r.event === "running")).toBe(true);
+ expect(tasks.taskPreview(t.id)).toBeNull();
+ });
+
+ it("sends none for a run that doesn't ask for previews", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const t = ownerTask(GPU_WORKFLOW);
+ let asked = 0;
+ start(w, s, p, { gpu: { steps: 8, stepMs: 300 }, shrinkPreview: async () => (asked++, new Blob([jpeg(1000)], { type: "image/jpeg" })) });
+ expect((await ended(t.id)).state).toBe("done");
+ expect(previews(s, t.id)).toEqual([]);
+ expect(asked).toBe(0);
+ });
+
+ it.runIf(hasFfmpeg)("ffmpeg makes a PNG preview again as a JPEG under 64 KB, and nothing of it stays", async () => {
+ const sharp = (await import("sharp")).default;
+ const png = await sharp({ create: { width: 1024, height: 768, channels: 3, background: "#a5c" } }).png().toBuffer();
+ const dir2 = tempDir("fuobe-cpu-slot-preview-");
+ const shrink = previewShrinker({ ffmpeg: "ffmpeg", dir: dir2 });
+ const out = (await shrink(new Blob([png], { type: "image/png" })))!;
+ expect(out.type).toBe("image/jpeg");
+ expect(out.size).toBeLessThanOrEqual(PREVIEW_MAX_BYTES);
+ const meta = await sharp(Buffer.from(await out.arrayBuffer())).metadata();
+ expect(meta.format).toBe("jpeg");
+ expect(Math.max(meta.width!, meta.height!)).toBeLessThanOrEqual(512);
+ expect(fs.readdirSync(dir2)).toEqual([]);
+ // Not a picture: nothing.
+ expect(await shrink(new Blob([Buffer.from("<html>")], { type: "image/png" }))).toBeNull();
+ expect(await previewShrinker({ ffmpeg: null, dir: dir2 })(new Blob([png]))).toBeNull();
+ });
+
+ it("ffmpeg makes a preview again only from a local PNG or JPEG, at most 512 pixels, with no metadata", () => {
+ const a = previewArgs("in.png", "out.jpg");
+ expect(a.slice(a.indexOf("-protocol_whitelist"), a.indexOf("-protocol_whitelist") + 2)).toEqual(["-protocol_whitelist", "file"]);
+ expect(a[a.indexOf("-vf") + 1]).toMatch(/min\(512,iw\).*min\(512,ih\)/);
+ expect(a).toEqual(expect.arrayContaining(["-map_metadata", "-1", "-frames:v", "1"]));
+ expect(a[a.length - 1]).toBe("out.jpg");
+ });
+});