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 shared runner keeps finished results, gives back stalled jobs, retries once after running out of memory
Adarshad534532fd59
diff --git a/bin/lib/worker/hold.mjs b/bin/lib/worker/hold.mjsnew file mode 100644index 00000000..6ea84165--- /dev/null+++ b/bin/lib/worker/hold.mjs@@ -0,0 +1,127 @@+// Finished results kept on the worker's own disk (docs/gpu-workers.md). The moment its ComfyUI finishes a job, before the+// studio hears of it, the worker copies every file the job's history entries name into hold/<task id>/ with a note of+// the entries (held.json). The results stay there until the studio has them all. If the worker or its ComfyUI stops in+// between, the next claim gives the job back to this worker, and it uploads the kept files from where the studio's copy+// got to, instead of running the job again. Kept results of a job that is no longer this worker's are deleted.+import fs from "node:fs";+import path from "node:path";+import { Readable } from "node:stream";+import { pipeline } from "node:stream/promises";++const TASK_ID = /^[A-Za-z0-9_-]{16}$/;+const NOTE = "held.json";++/** Every file the entries name in ComfyUI's output or temp folder (each once), with no path in its name. */+export function heldFiles(entries) {+ const out = new Map();+ for (const e of entries ?? []) {+ for (const ui of Object.values(e?.outputs ?? {})) {+ for (const v of Object.values(ui ?? {})) {+ if (!Array.isArray(v)) continue;+ for (const f of v) {+ if (!f || typeof f.filename !== "string" || (f.type !== "output" && f.type !== "temp")) continue;+ const subfolder = typeof f.subfolder === "string" ? f.subfolder : "";+ if (!f.filename || /[\\/]|^\.\.?$/.test(f.filename) || subfolder.split(/[\\/]/).some((s) => s === "..")) continue;+ out.set(`${f.type}\u0000${subfolder}\u0000${f.filename}`, { filename: f.filename, subfolder, type: f.type });+ }+ }+ }+ }+ return [...out.values()];+}++/** An entry as kept: its status, its outputs and its place (never the graph again, with someone's prompt in it). */+const slim = (e) => ({ ...(Array.isArray(e?.prompt) && { prompt: [e.prompt[0], e.prompt[1]] }), status: e?.status, outputs: e?.outputs });++export class Hold {+ constructor(dir) {+ this.dir = dir;+ }++ folder(id) {+ if (!TASK_ID.test(String(id))) throw new Error("Not a task id");+ return path.join(this.dir, id);+ }++ note(id) {+ try {+ return JSON.parse(fs.readFileSync(path.join(this.folder(id), NOTE), "utf8"));+ } catch {+ return null;+ }+ }++ /** The tasks with kept results. */+ ids() {+ try {+ return fs.readdirSync(this.dir).filter((id) => this.has(id));+ } catch {+ return [];+ }+ }++ has(id) {+ return TASK_ID.test(String(id)) && fs.existsSync(path.join(this.dir, id, NOTE));+ }++ /**+ * Keep a finished job's results: every file its entries name, read from its ComfyUI (`read`), then the note. The note+ * comes last, so a stop halfway keeps nothing that looks whole.+ */+ async keep(t, held, read) {+ const dir = this.folder(t.id);+ fs.rmSync(dir, { recursive: true, force: true });+ fs.mkdirSync(dir, { recursive: true });+ const files = [];+ try {+ for (const f of heldFiles(held.entries)) {+ const res = await read(f);+ if (!res?.ok || !res.body) throw new Error("A result couldn't be kept");+ const file = `f${files.length}`;+ await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(path.join(dir, file), { mode: 0o600 }));+ files.push({ ...f, file });+ }+ const note = { taskId: t.id, promptId: t.promptId, kind: held.kind, entries: held.entries.map(slim), ...(held.execMs !== undefined && { execMs: held.execMs }), files, at: Date.now() };+ fs.writeFileSync(path.join(dir, `${NOTE}.tmp`), JSON.stringify(note), { mode: 0o600 });+ fs.renameSync(path.join(dir, `${NOTE}.tmp`), path.join(dir, NOTE));+ } catch (e) {+ fs.rmSync(dir, { recursive: true, force: true });+ throw e;+ }+ }++ /** The results kept for this task's prompt: { kind, entries, execMs }, or null. */+ async get(t) {+ if (!this.has(t.id)) return null;+ const n = this.note(t.id);+ if (!n || n.taskId !== t.id || n.promptId !== t.promptId || !Array.isArray(n.entries)) return null;+ return { kind: n.kind === "passes" ? "passes" : "finished", entries: n.entries, ...(typeof n.execMs === "number" && { execMs: n.execMs }) };+ }++ /** One kept file of this task, as a Blob read from disk, or null. */+ async file(t, w) {+ const n = this.note(t.id);+ if (!n || n.taskId !== t.id) return null;+ const f = (n.files ?? []).find((x) => x.filename === w.filename && x.subfolder === (w.subfolder ?? "") && x.type === w.type);+ if (!f || !/^f\d+$/.test(f.file)) return null;+ const p = path.join(this.folder(t.id), f.file);+ if (!fs.existsSync(p)) return null;+ return typeof fs.openAsBlob === "function" ? fs.openAsBlob(p) : new Blob([fs.readFileSync(p)]);+ }++ /** Let go of one task's kept results. */+ drop(id) {+ if (TASK_ID.test(String(id))) fs.rmSync(path.join(this.dir, id), { recursive: true, force: true });+ }++ /** Let go of every task's kept results but `keep`'s, and of anything else in the folder. */+ dropAllBut(keep = null) {+ let names = [];+ try {+ names = fs.readdirSync(this.dir);+ } catch {+ return;+ }+ for (const name of names) if (name !== keep) fs.rmSync(path.join(this.dir, name), { recursive: true, force: true });+ }+}diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.tsindex 9ab67de2..bc0a9523 100644--- a/src/lib/computer-runner.ts+++ b/src/lib/computer-runner.ts@@ -11,7 +11,21 @@ import { isGuard } from "./comfy-guard";import { fetchWithin } from "./fetch-within";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 TabFailure, type WantedFile } from "./relay";+import {+ DONE_SHOWN_MS,+ RELAY_LIMITS,+ RELAY_TIMES,+ type BeatAnswer,+ type ClaimedTask,+ type ComputerFacts,+ type GiveBackWhy,+ type HistoryEntryLike,+ type RelayState,+ type ReportEvent,+ type TabFailure,+ type TaskInput,+ type WantedFile,+} from "./relay";/** The parts of a WebSocket the runner uses (the browser's, or Node's). */export interface SocketLike {@@ -46,14 +60,94 @@ export interface RunnerDeps {* 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;+ vet?: (t: ClaimedTask) => TabFailure | null | Promise<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 only a worker program does (docs/gpu-workers.md). A browser tab has none of it. */+ worker?: WorkerHooks;}+/** A finished job's results as a worker keeps them on its own disk: its entries (one, or a meta-batch's passes). */+export interface HeldResults {+ kind: "finished" | "passes";+ entries: HistoryEntryLike[];+ /** Its ComfyUI's execution time for the job (ms), when known. */+ execMs?: number;+}++/** A file a job's entries name in ComfyUI's output or temp folder. */+export type ResultFile = Pick<WantedFile, "filename" | "subfolder" | "type">;++/**+ * A worker program's part in a job (docs/gpu-workers.md): it keeps finished results until the studio has them, keeps+ * inputs by their SHA-256 and makes clips and sound again before its ComfyUI reads them, gives back a job that stalls+ * or runs past its run limit, retries once after running out of memory, and fails a job its ComfyUI stopped on twice.+ */+export interface WorkerHooks {+ hold: {+ /** Keep every file the entries name (`read` fetches one from its ComfyUI), before the studio hears of them. */+ keep(t: ClaimedTask, held: HeldResults, read: (f: ResultFile) => Promise<Response | null>): Promise<void>;+ /** The results kept for this task's prompt, or null. */+ get(t: ClaimedTask): Promise<HeldResults | null>;+ /** One kept file, or null. */+ file(t: ClaimedTask, w: ResultFile): Promise<Blob | null>;+ has(taskId: string): boolean;+ };+ /**+ * An input as its ComfyUI gets it. `read` fetches it from the studio (or says why it couldn't); the worker may keep a+ * copy by its SHA-256, so a job sent again reads nothing twice. A clip or a sound is made again first, or, when the+ * worker can't, the job goes back to the line ("give-back").+ */+ input(t: ClaimedTask, i: TaskInput, read: () => Promise<ArrayBuffer | TabFailure>): Promise<ArrayBuffer | TabFailure | "give-back">;+ /** A job with no progress for this long (ms) goes back to the line. */+ stallMs: number;+ /** Free its ComfyUI's memory (before the one retry after it ran out). */+ free(): Promise<void>;+ /** How many times its ComfyUI stopped while it ran this task. */+ crashes(t: ClaimedTask): number;+ /** Its ComfyUI won't let go of a prompt: stop it (the worker starts it again). */+ stuck(): Promise<void>;+ /** What a claim answered, before the job runs: a task, or null (none was this worker's or waiting for it). */+ claimed(t: ClaimedTask | null): void | Promise<void>;+}++/** ComfyUI's words for running out of memory (lib/gpu/fix-codes.ts says the same). */+const OUT_OF_MEMORY = /out of memory|OutOfMemoryError|allocation on device/i;++/** The prompt ran out of memory (its entry's execution error says so). */+export function outOfMemory(e: HistoryEntryLike): boolean {+ if (e.status?.status_str !== "error") return false;+ return (e.status.messages ?? []).some(([name, d]) => name === "execution_error" && OUT_OF_MEMORY.test(`${d?.exception_type ?? ""} ${d?.exception_message ?? ""}`));+}++/** How long ComfyUI spent executing these entries (ms), from its own timestamps; null when they don't say. */+export function execTime(entries: HistoryEntryLike[]): number | null {+ let total = 0;+ let known = false;+ for (const e of entries) {+ const messages = e?.status?.messages ?? [];+ const at = (names: string[]) => messages.find(([n]) => names.includes(n))?.[1]?.timestamp;+ const start = at(["execution_start"]);+ const end = at(["execution_success", "execution_error", "execution_interrupted"]);+ if (typeof start === "number" && typeof end === "number" && end >= start) {+ total += end - start;+ known = true;+ }+ }+ return known ? total : null;+}++/** A GPU's name as ComfyUI gives it ("cuda:0 <name> : cudaMallocAsync"), without the device number or the allocator. */+export const deviceName = (raw: string | undefined): string | undefined =>+ raw+ ?.replace(/^\s*cuda:\d+\s*/i, "")+ .replace(/\s*:\s*[A-Za-z]+\s*$/, "")+ .trim()+ .slice(0, 120) || undefined;+/** What the page shows about one job this tab runs. */export interface LocalJob {taskId: string;@@ -445,19 +539,30 @@ export class ComputerRunner {* Ask for a job and run it (one at a time). True when there was one. Only while ComfyUI here answers to this site: a* computer whose ComfyUI is closed, or runs without Fuobe's setting, keeps its place but takes nothing.*/- async claimAndRun(): Promise<boolean> {+ async claimAndRun(o: { onlyHeld?: boolean } = {}): Promise<boolean> {if (!this.alive || this.busy || this.o.access) return false;this.busy = true;try {- if ((await this.look()).comfy !== "ok") return false;+ // A worker's kept results go up without its ComfyUI (`onlyHeld`); anything else needs ComfyUI answering.+ if (!o.onlyHeld && (await this.look()).comfy !== "ok") return false;const running = this.view.jobs.filter((j) => j.phase !== "done" && j.phase !== "failed").map((j) => j.taskId);const res = await this.deps.api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: this.o.device, running }) });if (res.status !== 200) {if (res.status === 401) this.stop("signed-out");+ if (res.status === 204) await this.deps.worker?.claimed(null);return false;}const { task } = (await res.json()) as { task: ClaimedTask };this.leases.set(task.id, task.lease);+ const worker = this.deps.worker;+ if (worker) {+ await worker.claimed(task);+ // Only kept results now: any other job waits for its ComfyUI (one never sent goes back to the line at once).+ if (o.onlyHeld && !worker.hold.has(task.id)) {+ await this.deps.api(`/api/gpu/computer/tasks/${task.id}/release`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lease: task.lease }) }).catch(() => null);+ return false;+ }+ }try {await this.run(task);} catch (e) {@@ -487,32 +592,61 @@ export class ComputerRunner {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 {- const problem = graphProblem(t.graph, t.inputs.map((i) => i.name));- if (problem) {- 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" });+ const worker = this.deps.worker;+ // A worker names its GPU with each finished job: its facts, if no beat read them yet.+ if (worker && !this.view.facts) await this.facts().catch(() => null);+ // A worker's results kept from before (it stopped after its ComfyUI finished): they go up, the job doesn't run again.+ const held = worker ? await worker.hold.get(t).catch(() => null) : null;+ if (!held) {+ const problem = graphProblem(t.graph, t.inputs.map((i) => i.name));+ if (problem) {+ await this.report(t, { event: "failed", reason: "unsafe-graph" });+ return this.job(t, { phase: "failed" });+ }+ const refused = await 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 entries: HistoryEntryLike[] | null = held?.entries ?? null;let wanted = t.wanted;let phase = t.resume ?? "sending";+ if (held && phase !== "collecting") {+ // The studio hasn't heard that it finished (or it went back in line since, and came back here).+ if (phase === "sending") await this.report(t, { event: "sent", promptId: t.promptId });+ const a = await this.report(t, this.endReport(held));+ if (a.stop) throw new Stopped();+ if (!a.wanted) return this.job(t, { phase: a.state === "done" ? "done" : "failed" });+ wanted = a.wanted;+ phase = "collecting";+ }for (let attempt = 0; phase !== "collecting" && attempt < 3; attempt++) {if (phase === "sending") {const sent = await this.sendJob(t);+ if (sent === "give-back") {+ await this.giveBack(t, "media");+ return this.job(t, { phase: "failed" });+ }if (!sent) return;}this.socket();const done = await this.follow(t);if (done === "gone") {+ // A worker's ComfyUI that stopped twice on this job: the job fails, not the worker.+ if (worker && worker.crashes(t) >= 2) {+ await this.report(t, { event: "failed", reason: "input-crashed" });+ return this.job(t, { phase: "failed" });+ }const a = await this.report(t, { event: "gone" });if (a.state !== "sending") return this.job(t, { phase: "failed" });phase = "sending";continue;}+ if ("giveBack" in done) {+ await this.giveBack(t, done.giveBack);+ return this.job(t, { phase: "failed" });+ }entries = done.entries;if (!done.answer.wanted) return this.job(t, { phase: done.answer.state === "done" ? "done" : "failed" });wanted = done.answer.wanted;@@ -527,6 +661,67 @@ export class ComputerRunner {}}+ /** A worker's report of a finished job: its entries, its ComfyUI's execution time and its GPU's name. */+ private endReport(held: HeldResults): ReportEvent {+ const device = deviceName(this.view.facts?.device);+ const exec = { ...(held.execMs !== undefined && { execMs: Math.round(held.execMs) }), ...(device && { device }) };+ return held.kind === "passes" ? { event: "passes", running: false, entries: held.entries.map(slim), ...exec } : { event: "finished", entry: slim(held.entries[0] ?? {}), ...exec };+ }++ /** A worker keeps a finished job's files before the studio hears of them (a failure to keep only loses the copy). */+ private async keep(t: ClaimedTask, held: HeldResults) {+ const read = (f: ResultFile) => {+ try {+ return this.deps.local(`${this.base}${readPath(viewPath(f))}`, { credentials: "omit", cache: "no-store" }).catch(() => null);+ } catch {+ return Promise.resolve(null);+ }+ };+ await this.deps.worker?.hold.keep(t, held, read).catch(() => {});+ }++ /** A worker gives a job back to the line, after taking its prompt off its ComfyUI. */+ private async giveBack(t: ClaimedTask, why: GiveBackWhy) {+ await this.cancelHere(t);+ await this.report(t, { event: "give-back", why }).catch((e) => {+ if (!(e instanceof Stopped)) throw e;+ });+ }++ /** Take a worker's prompt off its ComfyUI; one that won't go within 15 s stops its ComfyUI. */+ private async cancelHere(t: ClaimedTask) {+ const own = { promptIds: [t.promptId] };+ const json = (body: unknown) => ({ headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });+ await this.send(`/api/jobs/${t.promptId}/cancel`, {}, own, {}).catch(() => null);+ await this.send("/queue", { delete: [t.promptId] }, own, json({ delete: [t.promptId] })).catch(() => null);+ await this.send("/interrupt", { prompt_id: t.promptId }, own, json({ prompt_id: t.promptId })).catch(() => null);+ for (let i = 0; i < 15; i++) {+ const w = await this.where(t.promptId).catch(() => null);+ if (w && (w.s === "done" || w.s === "absent")) {+ // Its entry goes too: the job may come back here under the same prompt id, and must run again then.+ await this.send("/history", { delete: [t.promptId] }, own, json({ delete: [t.promptId] })).catch(() => null);+ return;+ }+ await this.sleep(1000);+ }+ await this.deps.worker?.stuck().catch(() => {});+ }++ /** Send a worker's prompt again (the one retry after its ComfyUI ran out of memory). True when ComfyUI took it. */+ private async resend(t: ClaimedTask): Promise<boolean> {+ const own = { promptIds: [t.promptId] };+ await this.send("/history", { delete: [t.promptId] }, own, { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delete: [t.promptId] }) }).catch(() => null);+ const body = { prompt: t.graph, prompt_id: t.promptId, client_id: this.o.clientId, ...(t.preview && { extra_data: { preview_method: "auto" } }) };+ const res = await this.send("/prompt", body, own, { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);+ const answer = (await res?.json().catch(() => ({}))) as { prompt_id?: string } | undefined;+ if (!res?.ok || typeof answer?.prompt_id !== "string") return false;+ if (answer.prompt_id !== t.promptId) {+ t.promptId = answer.prompt_id;+ this.promptOf.set(t.id, t.promptId);+ }+ return true;+ }+/** The job's own entries on ComfyUI here, to check a resumed upload against. */private async ownEntries(t: ClaimedTask): Promise<HistoryEntryLike[]> {const own = (await this.read<Record<string, HistoryEntryLike>>(`/history/${t.promptId}`).catch(() => ({}) as Record<string, HistoryEntryLike>))[t.promptId];@@ -534,8 +729,11 @@ export class ComputerRunner {return [...(own ? [own] : []), ...passes];}- /** Send the inputs and the prompt, unless ComfyUI has it already (a resumed job). False when the job ended. */- private async sendJob(t: ClaimedTask): Promise<boolean> {+ /**+ * Send the inputs and the prompt, unless ComfyUI has it already (a resumed job). False when the job ended;+ * "give-back" when a worker can't take one of its inputs.+ */+ private async sendJob(t: ClaimedTask): Promise<boolean | "give-back"> {this.job(t, { phase: "sending" });const there = await this.where(t.promptId).catch(() => null);if (there && there.s !== "absent") {@@ -544,16 +742,26 @@ export class ComputerRunner {}if (!there) await this.waitForComfy(t);const names = t.inputs.map((i) => i.name);+ const worker = this.deps.worker;for (const input of t.inputs) {- const res = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/inputs/${input.n}`, { headers: { "X-Fuobe-Lease": t.lease } });- if (res.status === 404 || res.status === 409) throw new Stopped();- if (!res.ok) throw new Error(`The studio answered HTTP ${res.status} for a file`);- const data = await res.arrayBuffer();- if ((await this.deps.sha256(data)) !== input.sha256) {- await this.report(t, { event: "failed", reason: "input-changed" });+ // From the studio, checked against its SHA-256. A worker reads it at most once a job (it keeps a copy), so a+ // studio that says it was read enough times (429) means it failed.+ const read = async (): Promise<ArrayBuffer | TabFailure> => {+ const res = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/inputs/${input.n}`, { headers: { "X-Fuobe-Lease": t.lease } });+ if (res.status === 404 || res.status === 409) throw new Stopped();+ if (worker && res.status === 429) return "input-changed";+ if (!res.ok) throw new Error(`The studio answered HTTP ${res.status} for a file`);+ const data = await res.arrayBuffer();+ return (await this.deps.sha256(data)) === input.sha256 ? data : "input-changed";+ };+ const got = worker ? await worker.input(t, input, read) : await read();+ if (got === "give-back") return got;+ if (typeof got === "string") {+ await this.report(t, { event: "failed", reason: got });this.job(t, { phase: "failed" });return false;}+ const data = got;const form = new FormData();form.append("image", new Blob([data], { type: input.contentType }), input.name);form.append("type", "input");@@ -614,23 +822,56 @@ export class ComputerRunner {}}- /** Follow a sent prompt until it finishes (its entry reported, the server's answer back), or ComfyUI lost it. */- private async follow(t: ClaimedTask): Promise<"gone" | { entries: HistoryEntryLike[]; answer: { wanted?: WantedFile[]; state?: RelayState } }> {+ /**+ * Follow a sent prompt until it finishes (its entry reported, the server's answer back), or ComfyUI lost it. A worker+ * also keeps the results before it reports them, gives the job back when it stalls or runs past its run limit, and+ * sends it again once when its ComfyUI ran out of memory.+ */+ private async follow(t: ClaimedTask): Promise<"gone" | { giveBack: GiveBackWhy } | { entries: HistoryEntryLike[]; answer: { wanted?: WantedFile[]; state?: RelayState } }> {+ const worker = this.deps.worker;let lastSent = 0;let lastKey = "";let following: string | undefined;+ // A worker's watchdog: when the job started here, and when it last moved (a step, a node, its place, a pass).+ const began = this.now();+ let movedAt = began;+ let moveKey = "";+ const moved = (key: string) => {+ if (key !== moveKey) {+ moveKey = key;+ movedAt = this.now();+ }+ };+ // Execution time: what ComfyUI's entries say, else the time it was seen running here.+ let runningSince: number | null = null;+ let spentMs = 0;+ let oomRetried = false;+ const execOf = (entries: HistoryEntryLike[]) => spentMs + (execTime(entries) ?? (runningSince !== null ? this.now() - runningSince : 0));+ const exec = (ms: number) => {+ const device = deviceName(this.view.facts?.device);+ return worker ? { execMs: Math.round(ms), ...(device && { device }) } : {};+ };for (;;) {if (!this.alive) throw new Stopped();+ if (worker) {+ if (t.runLimitMs && this.now() - began > t.runLimitMs) return { giveBack: "run-limit" };+ if (this.now() - movedAt > worker.stallMs) return { giveBack: "stalled" };+ }if (following) {// A meta-batch: its passes run under new ids, all with its prefix.const q = await this.read<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue").catch(() => null);if (!q) {await this.waitForComfy(t);+ moved(`back:${this.now()}`);continue;}- const running = [...(q.queue_running ?? []), ...(q.queue_pending ?? [])].some((r) => hasPrefix(r[2], following!));+ const queued = [...(q.queue_running ?? []), ...(q.queue_pending ?? [])].filter((r) => hasPrefix(r[2], following!));+ const running = queued.length > 0;const passes = Object.values(await this.read<Record<string, HistoryEntryLike>>("/history?max_items=64").catch(() => ({}))).filter((e) => hasPrefix(e.prompt?.[2], following!));- const a = await this.report(t, { event: "passes", running, entries: running ? [] : passes.map(slim) });+ const ev = this.events.get(String(queued[0]?.[1] ?? ""));+ moved(JSON.stringify([queued.map((r) => r[1]), passes.length, ev?.value, ev?.node, ev?.nodesDone]));+ if (!running && worker) await this.keep(t, { kind: "passes", entries: passes, execMs: execOf(passes) });+ const a = await this.report(t, { event: "passes", running, entries: running ? [] : passes.map(slim), ...(!running && exec(execOf(passes))) });if (a.stop) throw new Stopped();if (!running) return { entries: passes, answer: a };this.job(t, { phase: "running" });@@ -640,11 +881,26 @@ export class ComputerRunner {const w = await this.where(t.promptId).catch(() => null);if (!w) {await this.waitForComfy(t);+ moved(`back:${this.now()}`);continue;}if (w.s === "absent") return "gone";if (w.s === "done") {- const a = await this.report(t, { event: "finished", entry: slim(w.entry) });+ // A worker's ComfyUI ran out of memory: free it, and send the prompt once more before saying anything.+ if (worker && !oomRetried && outOfMemory(w.entry)) {+ oomRetried = true;+ spentMs = execOf([w.entry]);+ runningSince = null;+ await worker.free().catch(() => {});+ if (await this.resend(t)) {+ moved(`retry:${this.now()}`);+ continue;+ }+ }+ const ms = execOf([w.entry]);+ // A worker keeps the results first: a stop from here on uploads them again instead of running the job again.+ if (worker && !t.metaBatch && w.entry.status?.status_str !== "error") await this.keep(t, { kind: "finished", entries: [w.entry], execMs: ms });+ const a = await this.report(t, { event: "finished", entry: slim(w.entry), ...exec(ms) });if (a.stop) throw new Stopped();if (a.follow) {following = a.follow;@@ -652,7 +908,9 @@ export class ComputerRunner {}return { entries: [w.entry], answer: a };}+ if (w.s === "running") runningSince ??= this.now();const ev = this.events.get(t.promptId);+ moved(JSON.stringify([w.s, w.s === "pending" ? w.ahead : null, ev?.value, ev?.max, ev?.node, ev?.nodesDone]));const report: ReportEvent = w.s === "pending" ? { event: "queued", position: w.ahead } : { event: "running", value: ev?.value, max: ev?.max, node: ev?.node, nodesDone: ev?.nodesDone };const key = JSON.stringify(report);if (key !== lastKey && this.now() - lastSent >= PROGRESS_EVERY_MS) {@@ -678,12 +936,14 @@ export class ComputerRunner {await this.report(t, { event: "failed", reason: "output-missing" });return this.job(t, { phase: "failed" });}- const res = await this.deps.local(`${this.base}${readPath(viewPath(w))}`, { credentials: "omit", cache: "no-store" }).catch(() => null);- if (!res?.ok) {+ // A worker's kept copy first (its ComfyUI may have restarted since), else ComfyUI's own file.+ const kept = this.deps.worker ? await this.deps.worker.hold.file(t, w).catch(() => null) : null;+ const res = kept ? null : await this.deps.local(`${this.base}${readPath(viewPath(w))}`, { credentials: "omit", cache: "no-store" }).catch(() => null);+ if (!kept && !res?.ok) {await this.report(t, { event: "failed", reason: "output-missing" });return this.job(t, { phase: "failed" });}- const blob = await res.blob();+ const blob = kept ?? (await res!.blob());if (blob.size > w.maxBytes) {// The server says why (too big, or the account's files are full) when it refuses the size.await this.upload(t, w, blob, 0);diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 7165a273..e0183b87 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -701,7 +701,7 @@ export function failTask(t: TaskRow, error: string): void {/** The tab let go of a task it hadn't sent yet (the tab closes): another tab or computer may take it at once. */export function release(t: TaskRow): void {if (t.state === "sending" && !t.sent_at) {- setTask(t.id, { state: "waiting", device: null, lease_hash: null });+ setTask(t.id, { state: "waiting", device: null, lease_hash: null, ...(t.pools && { worker_id: null }) });rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);} else setTask(t.id, { lease_hash: null });}diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.tsindex efb90da4..1ea521bd 100644--- a/tests/helpers/fake-local-comfy.ts+++ b/tests/helpers/fake-local-comfy.ts@@ -11,8 +11,8 @@** Runs under plain Node too: only erasable TypeScript.*/-import { createHash, randomUUID } from "node:crypto";-import { readFileSync } from "node:fs";+import { createHash, createHmac, randomUUID } from "node:crypto";+import { appendFileSync, readFileSync } from "node:fs";import http from "node:http";import type { Duplex } from "node:stream";import { pathToFileURL } from "node:url";@@ -73,6 +73,13 @@ export interface LocalComfyOptions {oldLiveNodes?: boolean;/** Nothing ever starts: prompts wait in the queue (a stuck ComfyUI). */stall?: boolean;+ /**+ * A worker's guard (bin/lib/worker/comfy_guard.py) with this key: any request whose Host isn't 127.0.0.1:<port> or+ * that lacks the key is 403; GET /fuobe-worker/hello signs a challenge with the key and names this process.+ */+ workerGuard?: string;+ /** Each prompt posted adds a line to this file (a count that outlives the process, for a test in another one). */+ countFile?: string;}/** One live render the stand-in made (for the bookkeeping checks). */@@ -216,6 +223,13 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locconst sizes = new Map<string, { w: number; h: number }>();let server: http.Server;let generation = 0;+ let currentStep = 0;+ /** A worker's guard (opts.workerGuard): the request names this ComfyUI exactly and carries the key. */+ const guardPort = () => {+ const a = server.address();+ return typeof a === "object" && a ? a.port : 0;+ };+ const guardOk = (req: http.IncomingMessage) => String(req.headers.host ?? "") === `127.0.0.1:${guardPort()}` && req.headers["x-fuobe-worker-key"] === opts.workerGuard;const send = (clientId: string | undefined, payload: Buffer, binary = false) => {for (const [id, set] of sockets) if (!clientId || id === clientId) for (const s of set) s.write(frame(binary ? 2 : 1, payload));@@ -327,11 +341,15 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locfunction run(job: Job) {if (isLiveGraph(job.graph)) return runLive(job);running = job;+ currentStep = 0;const gen = generation;const alive = () => gen === generation && running === job;const steps = opts.steps ?? 4;const stepMs = job.ms !== undefined ? job.ms / steps : opts.stepMs;const node = Object.keys(job.graph).find((k) => /KSampler|Sampler/.test(job.graph[k].class_type)) ?? Object.keys(job.graph)[0] ?? "1";+ // ComfyUI's own timestamps (ms) on the start and the end, as its history keeps them.+ const started = Date.now();+ const begin: [string, Record<string, unknown>] = ["execution_start", { prompt_id: job.id, timestamp: started }];event(job.clientId, "execution_start", { prompt_id: job.id });event(job.clientId, "executing", { node, prompt_id: job.id });let step = 0;@@ -340,6 +358,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locif (job.fail === "never") return;if (step < steps) {step++;+ currentStep = step;event(job.clientId, "progress", { value: step, max: steps, prompt_id: job.id, node });if (job.preview) {const meta = Buffer.from(JSON.stringify({ prompt_id: job.id, node_id: node, image_type: "image/png" }));@@ -353,7 +372,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locif (job.fail === "oom") {const err = { prompt_id: job.id, node_id: node, node_type: "KSampler", exception_message: "Allocation on device 0 would exceed allowed memory. (out of memory)", exception_type: "torch.OutOfMemoryError" };event(job.clientId, "execution_error", err);- return finish(job, { prompt: [job.number, job.id, job.graph, {}, []], outputs: {}, status: { status_str: "error", completed: false, messages: [["execution_error", err]] } });+ return finish(job, { prompt: [job.number, job.id, job.graph, {}, []], outputs: {}, status: { status_str: "error", completed: false, messages: [begin, ["execution_error", { ...err, timestamp: Date.now() }]] } });}// A meta-batch's first passes save nothing and queue the next pass (a new prompt id, the same prefix).const passes = opts.metaBatch ?? 0;@@ -363,7 +382,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locevent(job.clientId, "executed", { node: outputNode(job.graph), prompt_id: job.id, output: outputs[outputNode(job.graph)] ?? {} });event(job.clientId, "executing", { node: null, prompt_id: job.id });event(job.clientId, "execution_success", { prompt_id: job.id });- finish(job, { prompt: [job.number, job.id, job.graph, {}, []], outputs, status: { status_str: "success", completed: true, messages: [["execution_success", { prompt_id: job.id }]] } });+ finish(job, { prompt: [job.number, job.id, job.graph, {}, []], outputs, status: { status_str: "success", completed: true, messages: [begin, ["execution_success", { prompt_id: job.id, timestamp: Date.now() }]] } });};timer = setTimeout(next, opts.latencyMs);}@@ -406,6 +425,23 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locconst origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;const entry: LocalComfyLog = { method: req.method ?? "GET", path: url.pathname + url.search, at: Date.now(), ...(origin && { origin }) };log.push(entry);+ // The stand-in's own count (never a ComfyUI route) stays readable for a test in another process.+ if (opts.workerGuard && url.pathname !== "/__fake/stats") {+ const deny = () => {+ entry.status = 403;+ res.writeHead(403);+ res.end();+ };+ if (String(req.headers.host ?? "") !== `127.0.0.1:${guardPort()}`) return deny();+ if (req.method === "GET" && url.pathname === "/fuobe-worker/hello" && req.headers["x-fuobe-worker-key"] === undefined) {+ const challenge = String(req.headers["x-fuobe-worker-challenge"] ?? "");+ if (!/^[0-9a-f]{16,128}$/.test(challenge)) return deny();+ entry.status = 200;+ res.writeHead(200, { "content-type": "application/json" });+ return res.end(JSON.stringify({ proof: createHmac("sha256", opts.workerGuard).update(challenge).digest("hex"), pid: process.pid }));+ }+ if (!guardOk(req)) return deny();+ }const headers: Record<string, string> = {};if (opts.cors === "off" && opts.connect && origin === opts.connect) {Object.assign(headers, { "Access-Control-Allow-Origin": opts.connect, Vary: "Origin", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "content-type" });@@ -435,7 +471,12 @@ 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, history: history.size, pid: process.pid });+ if (url.pathname === "/__fake/stats") return reply(200, { posts, uploads: inputs.size, history: history.size, pid: process.pid, running: running?.id ?? null, step: running ? currentStep : null });+ // ComfyUI's own: unload models and free memory.+ if (url.pathname === "/free" && req.method === "POST") {+ entry.body = JSON.parse(body.toString("utf8") || "{}");+ return reply(200, {});+ }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"];@@ -483,6 +524,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc}entry.prompt = json;posts++;+ if (opts.countFile) appendFileSync(opts.countFile, `prompt ${json.prompt_id ?? "?"}\n`);const fail = opts.failNext;opts.failNext = undefined;if (fail === "missing_node") {@@ -589,6 +631,10 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loclog.push({ method: "WS", path: url.pathname + url.search, ...(origin && { origin }) });const key = req.headers["sec-websocket-key"];if (url.pathname !== "/ws" || typeof key !== "string") return socket.destroy();+ if (opts.workerGuard && !guardOk(req)) {+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");+ return socket.destroy();+ }// ComfyUI's own check applies to the socket too when the setting is off.if (opts.cors === "off" && origin && new URL(origin).host !== String(req.headers.host ?? "")) {socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");@@ -701,7 +747,9 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc// Run on its own: node tests/helpers/fake-local-comfy.ts --port 3371 --cors http://127.0.0.1:3370// [--has workflows/comfyui/requirements.json]: everything that index names is installed. [--guard 1]: Fuobe's guard answers.-// [--connect <origin>]: Fuobe Connect is installed, trusting that origin.+// [--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.+// [--fail-next oom|never]: what the first prompt does. [--outputs video,audio]: what a job saves.if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {const arg = (name: string) => {const i = process.argv.indexOf(`--${name}`);@@ -709,6 +757,23 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)};const index = arg("has");const has = index ? (JSON.parse(readFileSync(index, "utf8")) as IndexLike) : undefined;- const fake = await startLocalComfy({ cors: arg("cors") ?? "off", steps: Number(arg("steps") ?? 8), stepMs: Number(arg("step-ms") ?? 250), portable: arg("portable") === "1", guard: arg("guard") === "1", ...(arg("connect") && { connect: arg("connect") }), has }, Number(arg("port") ?? 3371));+ const workerGuard = arg("worker-guard") === "1" ? process.env.FUOBE_WORKER_GUARD_KEY : undefined;+ if (arg("worker-guard") === "1" && !workerGuard) throw new Error("No key for the worker's guard");+ const fake = await startLocalComfy(+ {+ cors: arg("cors") ?? "off",+ steps: Number(arg("steps") ?? 8),+ stepMs: Number(arg("step-ms") ?? 250),+ portable: arg("portable") === "1",+ guard: arg("guard") === "1",+ ...(arg("connect") && { connect: arg("connect") }),+ ...(workerGuard && { workerGuard }),+ ...(arg("count-file") && { countFile: arg("count-file") }),+ ...(arg("fail-next") && { failNext: arg("fail-next") as LocalComfyOptions["failNext"] }),+ ...(arg("outputs") && { outputs: arg("outputs")!.split(",") as LocalComfyOptions["outputs"] }),+ has,+ },+ Number(arg("port") ?? 3371),+ );console.log(`fake ComfyUI on ${fake.url} (cross-site setting: ${fake.opts.cors})`);}diff --git a/tests/worker-runner.test.ts b/tests/worker-runner.test.tsnew file mode 100644index 00000000..d0472469--- /dev/null+++ b/tests/worker-runner.test.ts@@ -0,0 +1,385 @@+/**+ * The shared runner (src/lib/computer-runner.ts) with a worker's hooks, against the studio's real routes and a stand-in+ * ComfyUI on this computer: results kept on disk until the studio has them (a stop before the upload never runs a job+ * twice), a job that stalls or runs past its run limit given back to the line, one retry after running out of memory,+ * a job its ComfyUI stopped on twice failed in plain words, inputs read from the studio once, and a job the worker can't+ * take given back. A browser tab's runner (no hooks) reports exactly as before.+ */+import fs from "node:fs";+import path from "node:path";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { HeldResults, WorkerHooks } from "@/lib/computer-runner";+import type { ClaimedTask, TaskInput } from "@/lib/relay";+import { Hold } from "../bin/lib/worker/hold.mjs";+import { FAKE_PNG, startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";+import { apiAs, loadRoutes, sha256, SITE, 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: 60_000 });++const dir = tempDir("fuobe-worker-runner-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+delete process.env.FUOBE_PASSWORD;+globalThis.__fuobeTestDiskFree = 1e13;++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 workers = await import("@/server/computer/workers");+const { ComputerRunner } = await import("@/lib/computer-runner");+const { tabFailureWords } = await import("@/lib/relay");++let fake: LocalComfy;+let routes: ComputerRoutes;+const realFetch = globalThis.fetch;+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++beforeAll(async () => {+ fake = await startLocalComfy({ cors: "off", steps: 4, stepMs: 20, latencyMs: 10 });+ routes = await loadRoutes();+ setSetting("comfyWhere", "workers");+});+afterAll(async () => {+ globalThis.__fuobeTestDiskFree = undefined;+ await fake.close();+});+beforeEach(() => {+ resetRates();+ fake.restart({ failNext: undefined, loseNext: 0, steps: 4, stepMs: 20, outputs: ["image"] });+ 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 };+const row = (w: W) => workers.getWorker(w.id)!;+const state = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;++function worker(): W {+ const w = pool.addWorker(`w-${Math.random().toString(36).slice(2, 8)}`);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { small: { delayMs: 0 } } });+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: ["small"], workflows: ["wf-test"] }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);+ beat(w);+ return w;+}++function beat(w: W) {+ pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));+}++let gens = 0;+/** A job for the workers: a picture it loads, a sampler, and a picture it saves. */+function task(): string {+ const gid = `runner-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', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', '{}', '[]', ?, ?)")+ .run(gid, now, now);+ const input = tasks.stageInput("owner", FAKE_PNG, "image/png", "in.png");+ const t = tasks.createTask({+ principal: "owner",+ generationId: gid,+ graph: {+ "1": { class_type: "LoadImage", inputs: { image: input } },+ "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } },+ "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } },+ },+ pool: { pools: ["pool"], rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },+ });+ return t.id;+}++/** The studio's routes as a worker calls them, every report written down, with a hook to answer a call itself. */+function studio(w: W) {+ const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });+ const reports: Record<string, unknown>[] = [];+ const reads: string[] = [];+ let intercept: ((p: string, init: RequestInit) => Promise<Response | undefined> | Response | undefined) | null = null;+ const call = async (p: string, init: RequestInit = {}) => {+ const mine = await intercept?.(p, init);+ if (mine) return mine;+ if (p.endsWith("/report")) reports.push(JSON.parse(String(init.body)));+ if (p.includes("/inputs/")) reads.push(p);+ return api(p, init);+ };+ return { call, reports, reads, set: (fn: typeof intercept) => (intercept = fn) };+}++const hooks = (o: Partial<WorkerHooks> = {}): WorkerHooks => ({+ hold: new Hold(tempDir("fuobe-worker-hold-")) as unknown as WorkerHooks["hold"],+ input: (_t: ClaimedTask, _i: TaskInput, read: () => Promise<ArrayBuffer | string>) => read() as never,+ stallMs: 60_000,+ free: async () => {},+ crashes: () => 0,+ stuck: async () => {},+ claimed: () => {},+ ...o,+});++function runner(s: ReturnType<typeof studio>, worker?: WorkerHooks) {+ return new ComputerRunner(+ { api: s.call, local: (url, init) => realFetch(url, init), socket: (url) => new WebSocket(url) as never, sha256, origin: SITE, sleep: (ms) => sleep(Math.min(ms, 30)), ...(worker && { worker }) },+ { device: "worker", port: fake.port, clientId: "client-worker-01" },+ );+}++/** Claim the next job as a worker's runner does, and run it (or `edit` it first). */+async function claimAndRun(r: InstanceType<typeof ComputerRunner>, s: ReturnType<typeof studio>, edit?: (t: ClaimedTask) => ClaimedTask) {+ if (!edit) return r.claimAndRun();+ const res = await s.call("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: "worker", running: [] }) });+ const { task: t } = (await res.json()) as { task: ClaimedTask };+ await r.run(edit(t));+}++const saved = (id: string) => fs.readFileSync(tasks.outputFile(id, 0));++describe("a worker's runner", () => {+ it("runs a job to the end and reports its ComfyUI's execution time and its GPU's name", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ await runner(s, hooks()).claimAndRun();+ expect(state(id).state).toBe("done");+ expect(saved(id).equals(FAKE_PNG)).toBe(true);+ const finished = s.reports.find((x) => x.event === "finished")!;+ expect(finished.execMs).toBeTypeOf("number");+ expect(finished.device).toMatch(/\S/);+ expect(String(finished.device)).not.toMatch(/^cuda:|cudaMallocAsync/);+ expect(tasks.execOf(state(id))).toEqual({ ms: finished.execMs, device: finished.device });+ });++ it("a browser tab's runner (no worker hooks) reports as it always did", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ await runner(s).claimAndRun();+ expect(state(id).state).toBe("done");+ const finished = s.reports.find((x) => x.event === "finished")!;+ expect(Object.keys(finished).sort()).toEqual(["entry", "event"]);+ });++ it("out of memory: frees its ComfyUI's memory and sends the job once more, and the studio never hears of the first try", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ let freed = 0;+ const before = fake.posts();+ fake.opts.failNext = "oom";+ await runner(s, hooks({ free: async () => void freed++ })).claimAndRun();+ expect(state(id).state).toBe("done");+ expect(fake.posts() - before).toBe(2);+ expect(freed).toBe(1);+ expect(s.reports.filter((x) => x.event === "finished")).toHaveLength(1);+ expect(s.reports.some((x) => x.event === "failed")).toBe(false);+ // A second time it ran out: the run fails, as ComfyUI said.+ const id2 = task();+ fake.opts.failNext = "oom";+ const r2 = runner(s, hooks({ free: async () => void (fake.opts.failNext = "oom") }));+ await r2.claimAndRun();+ expect(state(id2).state).toBe("failed");+ });++ it("a job that stalls goes back to the line within the stall limit, with its prompt taken off ComfyUI", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ fake.opts.failNext = "never";+ const t0 = Date.now();+ await runner(s, hooks({ stallMs: 600 })).claimAndRun();+ const took = Date.now() - t0;+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1, worker_id: null });+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "stalled" });+ expect(took).toBeLessThan(600 + 5_000);+ const q = (await (await realFetch(`${fake.url}/queue`)).json()) as { queue_running: unknown[]; queue_pending: unknown[] };+ expect([...q.queue_running, ...q.queue_pending]).toEqual([]);+ // Back in line, it runs to the end the next time.+ beat(w);+ await runner(s, hooks()).claimAndRun();+ expect(state(id).state).toBe("done");+ });++ it("a job past its run limit goes back to the line", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ fake.opts.steps = 40;+ fake.opts.stepMs = 50;+ await claimAndRun(runner(s, hooks()), s, (t) => ({ ...t, runLimitMs: 500 }));+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "run-limit" });+ });++ it("a job its ComfyUI stopped on twice fails in plain words; the worker goes on", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ fake.opts.steps = 20;+ fake.opts.stepMs = 40;+ const r = runner(s, hooks({ crashes: () => 2 }));+ const run = r.claimAndRun();+ // ComfyUI restarts mid-job (it loses its queue and history).+ for (let i = 0; i < 100 && !fake.log.some((l) => l.path === "/prompt"); i++) await sleep(20);+ await sleep(200);+ fake.restart();+ await run;+ expect(state(id)).toMatchObject({ state: "failed", error: "tab:input-crashed" });+ expect(tabFailureWords("input-crashed")).not.toMatch(/ComfyUI|GPU|worker/i);+ // The next job runs.+ const id2 = task();+ fake.opts.steps = 4;+ fake.opts.stepMs = 20;+ await runner(s, hooks()).claimAndRun();+ expect(state(id2).state).toBe("done");+ });++ it("reads each input from the studio once a job, even when the job is sent again", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ const cache = new Map<string, ArrayBuffer>();+ let reads = 0;+ fake.opts.loseNext = 1;+ const input: WorkerHooks["input"] = async (_t, i, read) => {+ const kept = cache.get(i.sha256);+ if (kept) return kept;+ reads++;+ const got = await read();+ if (typeof got !== "string") cache.set(i.sha256, got);+ return got;+ };+ await runner(s, hooks({ input })).claimAndRun();+ expect(state(id).state).toBe("done");+ expect(s.reports.some((x) => x.event === "gone")).toBe(true);+ expect(reads).toBe(1);+ expect(s.reads).toHaveLength(1);+ });++ it("a studio that won't send an input again (429) fails the job instead of looping", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ s.set((p) => (p.includes("/inputs/") ? Response.json({ error: "That file was sent enough times." }, { status: 429 }) : undefined));+ await runner(s, hooks()).claimAndRun();+ expect(state(id)).toMatchObject({ state: "failed", error: "tab:input-changed" });+ });++ it("an input it can't take (a clip, with no way to make it again) gives the job back", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ await runner(s, hooks({ input: async () => "give-back" })).claimAndRun();+ expect(state(id)).toMatchObject({ state: "waiting", requeues: 1 });+ expect(s.reports.at(-1)).toEqual({ event: "give-back", why: "media" });+ });+});++describe("results kept until the studio has them", () => {+ it("a stop before the upload: the next start uploads the kept results, and ComfyUI got exactly one prompt", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ const holdDir = tempDir("fuobe-worker-hold-");+ const before = fake.posts();+ // The worker stops as it starts the upload.+ const first = runner(s, hooks({ hold: new Hold(holdDir) as never }));+ s.set((p, init) => {+ if (!p.includes("/outputs/") || init.method !== "PUT") return undefined;+ first.stop();+ throw new TypeError("fetch failed");+ });+ await first.claimAndRun();+ expect(state(id).state).toBe("collecting");+ expect(new Hold(holdDir).ids()).toEqual([id]);+ // Its ComfyUI starts again (no history, no files), and so does the worker.+ fake.restart();+ s.set(null);+ let claimed: string | null | undefined;+ await runner(s, hooks({ hold: new Hold(holdDir) as never, claimed: (t) => void (claimed = t?.id ?? null) })).claimAndRun();+ expect(claimed).toBe(id);+ expect(state(id).state).toBe("done");+ expect(saved(id).equals(FAKE_PNG)).toBe(true);+ expect(fake.posts() - before).toBe(1);+ });++ it("a stop before the studio heard it finished: the kept results are reported and uploaded, never run again", async () => {+ const w = worker();+ const id = task();+ const s = studio(w);+ const holdDir = tempDir("fuobe-worker-hold-");+ const before = fake.posts();+ s.set((p, init) => {+ if (p.endsWith("/report") && JSON.parse(String(init.body)).event === "finished") throw new TypeError("fetch failed");+ return undefined;+ });+ await expect(runner(s, hooks({ hold: new Hold(holdDir) as never })).claimAndRun()).rejects.toThrow();+ expect(state(id).state).toBe("running");+ fake.restart();+ s.set(null);+ await runner(s, hooks({ hold: new Hold(holdDir) as never })).claimAndRun();+ expect(state(id).state).toBe("done");+ expect(saved(id).equals(FAKE_PNG)).toBe(true);+ expect(fake.posts() - before).toBe(1);+ const held = s.reports.filter((x) => x.event === "finished");+ expect(held).toHaveLength(1);+ expect(held[0].execMs).toBeTypeOf("number");+ });++ it("kept results go up without its ComfyUI; any other job claimed meanwhile goes straight back to the line", async () => {+ const w = worker();+ const s = studio(w);+ const holdDir = tempDir("fuobe-worker-hold-");+ // Nothing kept: a claim for kept results only lets a fresh job go at once.+ const id = task();+ let seen: (string | null)[] = [];+ const r = runner(s, hooks({ hold: new Hold(holdDir) as never, claimed: (t) => void seen.push(t?.id ?? null) }));+ expect(await r.claimAndRun({ onlyHeld: true })).toBe(false);+ expect(seen).toEqual([id]);+ expect(state(id)).toMatchObject({ state: "waiting", worker_id: null, device: null, requeues: 0 });+ // No job at all: the claim says so (null).+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE id = ?").run(id);+ seen = [];+ expect(await r.claimAndRun({ onlyHeld: true })).toBe(false);+ expect(seen).toEqual([null]);+ });++ it("keeps every file its entries name, under no path but its own, and nothing that looks whole when a copy fails", async () => {+ const holdDir = tempDir("fuobe-worker-hold-");+ const hold = new Hold(holdDir);+ const t = { id: "BBBBBBBBBBBBBBBB", promptId: "00000000-0000-4000-8000-000000000001" } as ClaimedTask;+ const entry = {+ prompt: [1, t.promptId, { secret: "someone's prompt" }],+ status: { status_str: "success", completed: true },+ outputs: {+ "9": {+ images: [+ { filename: "a_00001_.png", subfolder: "fuobe", type: "output" },+ { filename: "../escape.png", subfolder: "", type: "output" },+ { filename: "b.png", subfolder: "../..", type: "output" },+ { filename: "c.png", subfolder: "", type: "input" },+ ],+ },+ },+ };+ const asked: string[] = [];+ await hold.keep(t, { kind: "finished", entries: [entry] } as HeldResults, async (f) => {+ asked.push(`${f.type}/${f.subfolder}/${f.filename}`);+ return new Response(FAKE_PNG);+ });+ expect(asked).toEqual(["output/fuobe/a_00001_.png"]);+ const got = await hold.get(t);+ expect(got?.entries[0].prompt).toEqual([1, t.promptId]);+ const blob = await hold.file(t, { filename: "a_00001_.png", subfolder: "fuobe", type: "output" });+ expect(Buffer.from(await blob!.arrayBuffer()).equals(FAKE_PNG)).toBe(true);+ // Another prompt for the same task (sent again from the start): not these results.+ expect(await hold.get({ ...t, promptId: "00000000-0000-4000-8000-000000000002" })).toBeNull();+ // A copy that fails halfway keeps nothing.+ await expect(hold.keep(t, { kind: "finished", entries: [entry] } as HeldResults, async () => null)).rejects.toThrow();+ expect(hold.has(t.id)).toBe(false);+ expect(fs.readdirSync(holdDir)).toEqual([]);+ expect(() => hold.folder("../x")).toThrow();+ expect(path.basename(hold.folder(t.id))).toBe(t.id);+ });+});