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.

Runs on the workers: the worker sends its ComfyUI's preview pictures

Adarshe50f0cfdec0d
diff --git a/bin/lib/worker/media.mjs b/bin/lib/worker/media.mjs
index af782af4..8a142b09 100644
--- a/bin/lib/worker/media.mjs
+++ b/bin/lib/worker/media.mjs
@@ -145,3 +145,92 @@ export function reencode({ ffmpeg, kind, name, src, dst, capBytes = outputCap(fi
});
});
}
+
+/** The picture formats a preview may come in from its ComfyUI, by the name of ffmpeg's reader for each. */
+const PREVIEW_READERS = { "image/png": "png_pipe", "image/jpeg": "jpeg_pipe", "image/webp": "webp_pipe" };
+
+/** The qualities a preview is made at (ffmpeg's -q:v: lower is better), best first, until it is small enough. */
+export const PREVIEW_QUALITIES = [4, 8, 14, 24];
+
+/** At most this many pixels on a preview's long side, keeping its shape. */
+const PREVIEW_SIDE = 512;
+const previewSide = (dim) => `min(${dim}\\,${PREVIEW_SIDE})`;
+const PREVIEW_FIT = `scale=w=if(gte(iw\\,ih)\\,${previewSide("iw")}\\,-2):h=if(gte(iw\\,ih)\\,-2\\,${previewSide("ih")})`;
+
+/**
+ * ffmpeg's arguments to make one preview picture (`type`, read from its standard input) a JPEG at quality `q`, at most
+ * PREVIEW_SIDE pixels on its long side, with no metadata, written to its standard output. Null for a type it doesn't take.
+ */
+export function previewArgs(type, q) {
+ const reader = PREVIEW_READERS[type];
+ if (!reader) return null;
+ return [
+ "-hide_banner", "-nostats", "-loglevel", "error",
+ "-protocol_whitelist", "pipe", "-f", reader, "-i", "pipe:0",
+ "-map_metadata", "-1", "-frames:v", "1", "-vf", PREVIEW_FIT,
+ "-c:v", "mjpeg", "-pix_fmt", "yuvj420p", "-q:v", String(q), "-f", "image2pipe", "pipe:1",
+ ];
+}
+
+/** Is this a JPEG picture (its first bytes)? */
+const isJpeg = (b) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff;
+
+/**
+ * Make a preview picture of a job (its ComfyUI's PNG, or a JPEG too big to send) a JPEG of at most `maxBytes`, for the
+ * studio's tile: at the best quality of PREVIEW_QUALITIES that fits. Each try is ffmpeg in its own short-lived process at
+ * low priority, stopped after `timeoutMs`. Null when none fits, or ffmpeg can't read it.
+ */
+export async function previewJpeg({ ffmpeg, data, type, maxBytes = 64 * 1024, timeoutMs = 10_000, spawnFn = spawn }) {
+ for (const q of PREVIEW_QUALITIES) {
+ const args = previewArgs(type, q);
+ if (!args) return null;
+ const out = await pipeThrough({ ffmpeg, args, data, limit: maxBytes * 8, timeoutMs, spawnFn });
+ if (out === "too-big") continue;
+ if (!out) return null;
+ if (isJpeg(out) && out.length <= maxBytes) return new Uint8Array(out);
+ }
+ return null;
+}
+
+/**
+ * Run ffmpeg with `data` on its standard input: what it wrote, "too-big" when that passed `limit` bytes (it is stopped
+ * there), or null when it failed.
+ */
+function pipeThrough({ ffmpeg, args, data, limit, timeoutMs, spawnFn }) {
+ return new Promise((resolve) => {
+ let child;
+ try {
+ child = spawnFn(ffmpeg, args, { stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
+ } catch {
+ return resolve(null);
+ }
+ try {
+ if (child.pid) os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
+ } catch {}
+ const chunks = [];
+ let size = 0;
+ let done = false;
+ const end = (v) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ resolve(v);
+ };
+ const timer = setTimeout(() => {
+ child.kill("SIGKILL");
+ end(null);
+ }, timeoutMs);
+ child.stdout?.on("data", (d) => {
+ size += d.length;
+ if (size > limit) {
+ child.kill("SIGKILL");
+ return end("too-big");
+ }
+ chunks.push(d);
+ });
+ child.stdin?.on("error", () => {});
+ child.once("error", () => end(null));
+ child.once("close", (code) => end(code === 0 ? Buffer.concat(chunks) : null));
+ child.stdin?.end(Buffer.from(data));
+ });
+}
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index b0c320c2..0669de8f 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -25,7 +25,7 @@ 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 { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";
+import { ffmpegVersion, fileSize, mediaKind, outputCap, previewJpeg, reencode } from "./media.mjs";
import { withPlainResults } from "./results.mjs";
import { retrying } from "./retry.mjs";
import { SiteTurns, writeSite } from "./turns.mjs";
@@ -150,8 +150,8 @@ export function siteOf(answer) {
/**
* Run until `signal` aborts or the studio stops it. Returns why it ended: "aborted" (Ctrl+C, the scheduled task's end),
* "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home, env,
- * signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own
- * options), readCounters, readListeners, gpuEveryMs }.
+ * signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, previewJpeg, awake, rescanMs,
+ * comfy (OwnComfy's own options), readCounters, readListeners, gpuEveryMs }.
*/
export async function runWorker(saved, deps) {
// One worker at a time on a worker folder: a second one would stop the first one's ComfyUI, empty its folders and
@@ -382,6 +382,8 @@ async function work(saved, deps, owner) {
local: own,
sha256: async (data) => sha256(Buffer.from(data)),
origin: site,
+ // A run's preview picture for the studio's tile: ComfyUI's PNG (or a big JPEG) made a small JPEG, with ffmpeg.
+ ...(ffmpeg && { jpeg: (data, type) => (deps.previewJpeg ?? previewJpeg)({ ffmpeg: ffmpegBin, data, type }) }),
socket: typeof WebSocket === "function" ? (url) => (comfy.ready ? new WebSocket(comfy.rebase(url), { headers: comfy.headers() }) : null) : undefined,
now,
sleep,
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 041d03c9..0af1c1cd 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -583,11 +583,16 @@ its target), at most once an hour each.
and at most the time since the job was sent to its ComfyUI (plus a minute, because ComfyUI starts a job a moment
before the studio hears that it was sent).
- `running` can carry `preview`: the latest preview picture of the job, a JPEG of at most 64 KB as base64, at most
- one every 2 seconds. The studio keeps only the latest one for the job, shows it in the run's tile while the run
- works, and serves it only to the run's own account (`GET /api/generations/<id>/preview`, never cached). It drops
- the picture when the job ends or goes back in line. A picture that is not a JPEG, is too big or comes too soon is
- dropped, and the rest of the report still counts. Progress from reports and beats is kept in the database, so
- every app process sees the same step.
+ one every 2 seconds. A claim says `reportPreview: true` when the run shows one. The worker keeps the latest
+ preview its ComfyUI sends on its socket and adds it to a `running` report. A PNG preview, or a JPEG over 64 KB, is
+ made a smaller JPEG with ffmpeg first (at most 512 pixels on its long side); a worker without ffmpeg sends only
+ ComfyUI's own small JPEGs. The studio keeps only the latest one for the job, shows it in the run's tile while the
+ run works, and serves it only to the run's own account (`GET /api/generations/<id>/preview`, never cached). It
+ drops the picture when the job ends, goes back in line or is claimed again. A picture that is not a JPEG, is too
+ big, comes too soon or comes from an attempt that no longer holds the job is dropped, and the rest of the report
+ still counts. A run whose outputs the moderation service checks first shows no preview
+ ([moderation-hook.md](moderation-hook.md)). Progress from reports and beats is kept in the database, so every app
+ process sees the same step.
- `give-back` with `why` (`stalled`, `run-limit` or `media`) puts the job back in line. The job keeps its place and
counts as an attempt. Only a worker's job can be given back.
- `failed` can also give `unknown-node`, `unsafe-path` (a path, or an input outside its rule), `model-unverified`,
diff --git a/docs/moderation-hook.md b/docs/moderation-hook.md
index 67744010..47cce400 100644
--- a/docs/moderation-hook.md
+++ b/docs/moderation-hook.md
@@ -39,13 +39,16 @@ outputs then show as soon as the run succeeds and `check-output` is never called
When outputs are checked:
-1. The run's files are saved and **held**: never served to the account, never by a shared link. The row stays running
- with the stage "Checking", and the tile says so.
-2. Each file goes to `check-output`. "wait", or no answer, asks again later.
-3. Every file "show": the files are served and the run succeeds.
-4. Any file "hide": that file is deleted, the others with it, and the run fails with the service's `text`. A billing
+1. While the run works, it shows no preview picture: the workers' ComfyUI is asked for none, and a picture a worker
+ sends anyway is dropped. Its preview address answers 404.
+2. The run's files are saved and **held**: never served to the account, never by a shared link. The row stays running
+ with the stage "Checking", and the tile says so. A run stopped while its files are saved stays stopped, and its
+ files are deleted.
+3. Each file goes to `check-output`. "wait", or no answer, asks again later.
+4. Every file "show": the files are served and the run succeeds.
+5. Any file "hide": that file is deleted, the others with it, and the run fails with the service's `text`. A billing
hold is refunded as `hidden`.
-5. Past `FUOBE_MODERATION_MAX_WAIT_H`: the run fails with "This result couldn't be checked in time" and its files are
+6. Past `FUOBE_MODERATION_MAX_WAIT_H`: the run fails with "This result couldn't be checked in time" and its files are
deleted. A billing hold is refunded as `unchecked`.
## Reports
diff --git a/src/app/api/generations/[id]/preview/route.ts b/src/app/api/generations/[id]/preview/route.ts
index d9882d37..507cd621 100644
--- a/src/app/api/generations/[id]/preview/route.ts
+++ b/src/app/api/generations/[id]/preview/route.ts
@@ -1,6 +1,6 @@
import fs from "node:fs";
import { connection } from "next/server";
-import { runPreview } from "@/server/computer/tasks";
+import { previewShown, runPreview } from "@/server/computer/tasks";
import { getGeneration } from "@/server/generations";
/** Never kept by a browser or a cache in between: the picture changes while the run works, and it is the account's own. */
@@ -9,13 +9,14 @@ const HEADERS = { "Cache-Control": "private, no-store", "X-Content-Type-Options"
/**
* A run's latest preview picture while it works on this install's GPUs (a JPEG its worker sent with its progress).
* Only the run's own account (or the owner) reaches it: the sign-in proxy checks whose run it is, as for the run
- * itself (guest-access.ts accountGeneration). Nothing once the run has ended or gone back in line: 404.
+ * itself (guest-access.ts accountGeneration). Nothing once the run has ended or gone back in line, and nothing ever for
+ * a run whose outputs the moderation service sees first: 404.
*/
export async function GET(_req: Request, ctx: RouteContext<"/api/generations/[id]/preview">) {
await connection();
const { id } = await ctx.params;
const g = getGeneration(id);
- const p = g && g.status === "running" ? runPreview(id) : null;
+ const p = g && g.status === "running" && g.preview && previewShown(id) ? runPreview(id) : null;
let data: Buffer | null = null;
try {
data = p ? fs.readFileSync(p.path) : null;
diff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
index 4e0ae9b1..23ac834f 100644
--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@ -15,8 +15,12 @@ const AT_ONCE = { person: 2, all: 16 };
* under this size.
*/
const PREVIEW_REPORT_BYTES = Math.ceil(PREVIEW_LIMITS.bytes / 3) * 4 + 4 * 1024;
-/** A report over this size counts against a lower limit a minute (a "running" report with its preview stays under it). */
-const LARGE_BYTES = PREVIEW_REPORT_BYTES;
+/**
+ * A report over this size counts against a lower limit a minute. A worker's "running" report with its preview stays
+ * under its own, larger bound; a person's own computer keeps 64 KB.
+ */
+const LARGE_BYTES = 64 * 1024;
+const largeFor = (t: Pick<TaskRow, "pools">) => (t.pools ? PREVIEW_REPORT_BYTES : LARGE_BYTES);
/** The event as the tab sent it, with only the fields each one has, or null. */
function eventOf(b: Record<string, unknown>): ReportEvent | null {
@@ -99,7 +103,8 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute
}
const declared = Number(request.headers.get("content-length") ?? NaN);
if (Number.isFinite(declared) && declared > cap) return no(413, "That report is too large");
- if (cap > LARGE_BYTES && !(declared <= LARGE_BYTES)) {
+ const large = largeFor(t0);
+ if (cap > large && !(declared <= large)) {
const big = rateOf(callerKey(request, principal), "report-large", 30);
if (big) return big;
}
diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.ts
index b92e52a2..f05cb791 100644
--- a/src/lib/computer-runner.ts
+++ b/src/lib/computer-runner.ts
@@ -14,6 +14,7 @@ import { graphProblem, localBase, mayDownload, readPath, statsFacts, viewPath, w
import {
DONE_SHOWN_MS,
META_BATCH_HISTORY,
+ PREVIEW_REPORT,
RELAY_LIMITS,
RELAY_TIMES,
type BeatAnswer,
@@ -69,6 +70,11 @@ export interface RunnerDeps {
onBeat?: (a: BeatAnswer) => void;
/** What only a worker program does (docs/gpu-workers.md). A browser tab has none of it. */
worker?: WorkerHooks;
+ /**
+ * A preview picture as a JPEG of at most PREVIEW_REPORT.bytes, or null (a worker program with ffmpeg makes one from
+ * ComfyUI's PNG or a bigger JPEG). Without it, only ComfyUI's own JPEG previews that small are sent.
+ */
+ jpeg?: (data: Uint8Array, type: string) => Promise<Uint8Array | null>;
}
/** A finished job's results as a worker keeps them on its own disk: its entries (one, or a meta-batch's passes). */
@@ -227,6 +233,16 @@ const BEAT_MS = 20_000;
/** How long a result may wait for a busy studio before the run gives up. */
const SAVE_WAIT_MS = 60 * 60_000;
+/** Is this a JPEG picture (its first bytes)? */
+const isJpeg = (b: Uint8Array) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff;
+
+/** Bytes as base64, in a browser and in Node alike. */
+function base64(b: Uint8Array): string {
+ let s = "";
+ for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000));
+ return btoa(s);
+}
+
/** Retry-After in ms (1 to 30 s; 2 s when it doesn't say). */
const retryAfter = (res: Response) => Math.min(30, Math.max(1, Number(res.headers.get("retry-after")) || 2)) * 1000;
@@ -245,6 +261,11 @@ export class ComputerRunner {
private ws: SocketLike | null = null;
private wsOpen = false;
private events = new Map<string, { value?: number; max?: number; node?: string; nodesDone: number; done?: boolean }>();
+ /**
+ * The jobs whose run shows a preview picture (the claim's `reportPreview`): ComfyUI's latest preview of each, and when
+ * the last one was made ready for the studio (and which frame it was).
+ */
+ private previewed = new Map<string, { frame?: { data: Uint8Array; type: string; at: number }; triedAt?: number; frameAt?: number }>();
private factsSentAt = 0;
private factsWithLoras = 0;
private foundAt = 0;
@@ -400,7 +421,11 @@ export class ComputerRunner {
if (!p) return;
// A preview goes only to the prompt's own client: this tab's job (a newer ComfyUI also names the prompt).
const job = this.view.jobs.find((j) => j.phase === "running" && (!p.promptId || this.events.has(p.promptId)));
- if (job) this.job({ id: job.taskId, generationId: job.generationId }, { preview: new Blob([p.data as BlobPart], { type: p.type }) });
+ if (!job) return;
+ this.job({ id: job.taskId, generationId: job.generationId }, { preview: new Blob([p.data as BlobPart], { type: p.type }) });
+ // Kept for the studio too, when the run shows one (a copy: the socket's buffer is reused).
+ const kept = this.previewed.get(job.taskId);
+ if (kept && (!p.promptId || p.promptId === this.promptOf.get(job.taskId))) kept.frame = { data: new Uint8Array(p.data), type: p.type, at: this.now() };
};
}
@@ -606,6 +631,7 @@ export class ComputerRunner {
try {
await this.runJob(t);
} finally {
+ this.previewed.delete(t.id);
const phase = this.view.jobs.find((j) => j.taskId === t.id)?.phase;
if (this.deps.ended && (phase === "done" || phase === "failed")) await Promise.resolve(this.deps.ended(t, phase)).catch(() => {});
}
@@ -613,6 +639,7 @@ export class ComputerRunner {
private async runJob(t: ClaimedTask): Promise<void> {
this.promptOf.set(t.id, t.promptId);
+ if (t.reportPreview) this.previewed.set(t.id, {});
this.job(t, { phase: t.resume === "collecting" ? "saving" : t.resume === "running" ? "running" : t.resume === "queued" ? "queued" : "sending" });
try {
const worker = this.deps.worker;
@@ -949,8 +976,11 @@ export class ComputerRunner {
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) {
- const a = await this.report(t, report);
+ const due = this.now() - lastSent >= PROGRESS_EVERY_MS;
+ // The run's latest preview picture goes with a "running" report, at most one every 2 s, even when the step is the same.
+ const preview = due && w.s === "running" ? await this.previewFor(t) : undefined;
+ if (due && (key !== lastKey || preview)) {
+ const a = await this.report(t, preview ? ({ ...report, preview } as ReportEvent) : report);
if (a.stop) throw new Stopped();
lastKey = key;
lastSent = this.now();
@@ -961,6 +991,22 @@ export class ComputerRunner {
}
}
+ /**
+ * The job's latest preview picture for the studio, as base64: a JPEG of at most PREVIEW_REPORT.bytes, newer than the
+ * last one, at most one every PREVIEW_REPORT.everyMs (a picture that can't be made that small is skipped, and the next
+ * try waits as long). Undefined when there is none to send.
+ */
+ private async previewFor(t: ClaimedTask): Promise<string | undefined> {
+ const p = this.previewed.get(t.id);
+ const f = p?.frame;
+ if (!p || !f || (p.frameAt !== undefined && f.at <= p.frameAt) || (p.triedAt !== undefined && this.now() - p.triedAt < PREVIEW_REPORT.everyMs)) return undefined;
+ p.frameAt = f.at;
+ p.triedAt = this.now();
+ const small = (b: Uint8Array | null | undefined) => (b && isJpeg(b) && b.length <= PREVIEW_REPORT.bytes ? b : null);
+ const jpeg = (f.type === "image/jpeg" && small(f.data)) || (this.deps.jpeg ? small(await this.deps.jpeg(f.data, f.type).catch(() => null)) : null);
+ return jpeg ? base64(jpeg) : undefined;
+ }
+
/** Upload the results the server asked for, each in parts, from where each got to. */
private async collect(t: ClaimedTask, wanted: WantedFile[], entries: HistoryEntryLike[], received: { n: number; bytes: number; done: boolean }[]) {
this.job(t, { phase: "saving", saved: 0 });
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 1ab2f6c2..b7abe870 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -147,8 +147,16 @@ export interface ClaimedTask {
notAfter?: number | null;
attempt?: number;
models?: { folder: string; name: string; size: number; sha256: string | null }[];
+ /**
+ * The run shows its latest preview picture while it works: the worker sends it with its "running" reports (a JPEG of
+ * at most PREVIEW_REPORT.bytes, as base64, at most one every PREVIEW_REPORT.everyMs). Absent: it sends none.
+ */
+ reportPreview?: boolean;
}
+/** A worker's preview picture of its job, as a "running" report carries it: its size at most, and how often at most. */
+export const PREVIEW_REPORT = { bytes: 64 * 1024, everyMs: 2000 } as const;
+
/** The tab's facts about its ComfyUI (never its command line: that holds paths and user names). */
export interface ComputerFacts {
device?: string;
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 48ad1767..aa539d69 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -204,7 +204,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
const t = typeof r?.task === "string" ? (d.prepare("SELECT * FROM relay_tasks WHERE id = ? AND worker_id = ?").get(r.task, w.id) as TaskRow | undefined) : undefined;
if (!t || !(SENT_STATES as readonly string[]).includes(t.state)) continue;
setTask(t.id, { device_seen_at: now });
- noteProgress(t.id, r as unknown as Record<string, unknown>, now);
+ noteProgress(t.id, r as unknown as Record<string, unknown>, now, t.lease_hash);
}
for (const id of b.stopped) d.prepare("UPDATE relay_tasks SET stop = 0 WHERE id = ? AND device = ?").run(id, device);
const stops = (d.prepare("SELECT id, prompt_id, prefix FROM relay_tasks WHERE device = ? AND stop = 1").all(device) as { id: string; prompt_id: string; prefix: string | null }[]).map((s) => ({
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index 413105d1..279d08d9 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -8,6 +8,7 @@ import {
DEVICE_ID,
FACT_LIMITS,
INPUT_NAME,
+ PREVIEW_REPORT,
RELAY_LIMITS,
RELAY_TIMES,
reportAllowed,
@@ -70,7 +71,7 @@ export interface Progress {
export const taskProgress = (t: Pick<TaskRow, "progress_json">): Progress | undefined => json<Progress | undefined>(t.progress_json, undefined);
/** The most a preview picture may weigh, and how often one is kept (one at most every 2 s, a little early allowed). */
-export const PREVIEW_LIMITS = { bytes: 64 * 1024, everyMs: 2000, slackMs: 300 } as const;
+export const PREVIEW_LIMITS = { ...PREVIEW_REPORT, slackMs: 300 } as const;
/** The relay's tables are made with the database (db.ts RELAY_TABLES). */
const rdb = () => db();
@@ -479,7 +480,7 @@ export function beat(principal: Principal, b: BeatInput, now = Date.now()): Beat
const t = typeof r?.task === "string" ? getTask(principal, r.task) : null;
if (!t || t.device !== b.device || !(SENT_STATES as readonly string[]).includes(t.state)) continue;
setTask(t.id, { device_seen_at: now });
- noteProgress(t.id, r, now);
+ noteProgress(t.id, r, now, t.lease_hash);
}
for (const id of (b.stopped ?? []).slice(0, 64)) {
const t = typeof id === "string" ? getTask(principal, id) : null;
@@ -492,8 +493,12 @@ export function beat(principal: Principal, b: BeatInput, now = Date.now()): Beat
return { runner: free, heldElsewhere: !free && elsewhere, waiting, stops };
}
-/** Note a task's live progress (a report or a beat), over what it said before. */
-export function noteProgress(id: string, r: Record<string, unknown>, now: number) {
+/**
+ * Note a task's live progress (a report or a beat), over what it said before. Only while the task is still with the
+ * computer or worker that said it (`lease`: the lease it held then, as read with the task): a late report from an attempt
+ * another app process sent back in line, ended or gave to another worker meanwhile leaves nothing behind.
+ */
+export function noteProgress(id: string, r: Record<string, unknown>, now: number, lease: string | null) {
const p: Progress = { at: now };
for (const k of ["value", "max", "nodesDone", "position"] as const) {
const v = nonNeg(r[k]);
@@ -503,10 +508,27 @@ export function noteProgress(id: string, r: Record<string, unknown>, now: number
if (node) p.node = node;
const d = rdb();
d.transaction(() => {
- const cur = d.prepare("SELECT progress_json FROM relay_tasks WHERE id = ?").get(id) as Pick<TaskRow, "progress_json"> | undefined;
+ const cur = d.prepare(`SELECT progress_json FROM relay_tasks WHERE id = ? AND ${STILL_HELD}`).get(id, lease) as Pick<TaskRow, "progress_json"> | undefined;
if (!cur) return;
- d.prepare("UPDATE relay_tasks SET progress_json = ? WHERE id = ?").run(JSON.stringify({ ...taskProgress(cur), ...p }), id);
- })();
+ d.prepare(`UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND ${STILL_HELD}`).run(JSON.stringify({ ...taskProgress(cur), ...p }), id, lease);
+ }).immediate();
+}
+
+/** A task still sent to the computer or worker that holds the lease given (the query's last parameter). */
+const STILL_HELD = `state IN (${SENT_STATES.map((x) => `'${x}'`).join(",")}) AND lease_hash IS ?`;
+
+/**
+ * Does this run show a preview picture while it works? Not when the moderation service asked to see its outputs before
+ * they show (its stamp's `checkOutputs`): a preview would show what the check holds back.
+ */
+export function previewShown(generationId: string): boolean {
+ const g = rdb().prepare("SELECT request_json FROM generations WHERE id = ?").get(generationId) as { request_json: string } | undefined;
+ if (!g) return false;
+ try {
+ return !(JSON.parse(g.request_json) as { checkOutputs?: boolean }).checkOutputs;
+ } catch {
+ return false;
+ }
}
/** Is this a JPEG picture (its first bytes)? */
@@ -515,21 +537,35 @@ const isJpeg = (b: Buffer) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 &&
/**
* Keep a worker's preview picture of its job (a JPEG of at most 64 KB, sent as base64 with a "running" report), in
* place of the one before. One every 2 s at most: one that comes sooner is dropped, as is anything that isn't a JPEG
- * or is too big. Only a worker's task keeps one; a person's own computer shows its own previews in its tab.
+ * or is too big. Only a worker's task keeps one, and only for a run that shows previews (previewShown); a person's own
+ * computer shows its own previews in its tab. Kept only while the attempt that sent it still holds the task: a picture
+ * that comes after another app process sent it back in line or ended it is dropped, and no file is left behind.
*/
-export function notePreview(t: Pick<TaskRow, "id" | "pools" | "preview_at">, base64: unknown, now = Date.now()): boolean {
- if (!t.pools || typeof base64 !== "string" || !base64 || base64.length > Math.ceil(PREVIEW_LIMITS.bytes / 3) * 4 + 4) return false;
+export function notePreview(t: Pick<TaskRow, "id" | "pools" | "preview" | "preview_at" | "lease_hash" | "generation_id">, base64: unknown, now = Date.now()): boolean {
+ if (!t.pools || !t.preview || typeof base64 !== "string" || !base64 || base64.length > Math.ceil(PREVIEW_LIMITS.bytes / 3) * 4 + 4) return false;
if (t.preview_at && now - t.preview_at < PREVIEW_LIMITS.everyMs - PREVIEW_LIMITS.slackMs) return false;
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) return false;
const data = Buffer.from(base64, "base64");
- if (data.length > PREVIEW_LIMITS.bytes || !isJpeg(data)) return false;
+ if (data.length > PREVIEW_LIMITS.bytes || !isJpeg(data) || !previewShown(t.generation_id)) return false;
const file = previewFile(t.id);
fs.mkdirSync(path.dirname(file), { recursive: true });
const part = `${file}.${process.pid}.part`;
fs.writeFileSync(part, data, { mode: 0o600 });
- fs.renameSync(part, file);
- rdb().prepare("UPDATE relay_tasks SET preview_at = ? WHERE id = ?").run(now, t.id);
- return true;
+ const d = rdb();
+ let kept = false;
+ try {
+ // The row and the file change together: dropProgress in another process waits for this, then removes both.
+ kept = d
+ .transaction((): boolean => {
+ const changed = d.prepare("UPDATE relay_tasks SET preview_at = ? WHERE id = ? AND state IN ('queued','running') AND lease_hash IS ?").run(now, t.id, t.lease_hash).changes > 0;
+ if (changed) fs.renameSync(part, file);
+ return changed;
+ })
+ .immediate();
+ } finally {
+ if (!kept) fs.rmSync(part, { force: true });
+ }
+ return kept;
}
/** Forget a task's progress and its preview picture (it ended, or went back in line, or its ComfyUI starts it again). */
@@ -597,7 +633,11 @@ export function takeTask(t: TaskRow, device: string, now: number, fields: Partia
// claim (the report "gone"). Across claims, only its requeues count (pool.ts MAX_ATTEMPTS). Its sending clock starts at
// the claim.
setTask(t.id, { device, lease_hash: hash(lease), state: t.state === "waiting" ? "sending" : t.state, claimed_at: now, device_seen_at: now, ...(fresh && t.pools && { attempts: 0, sending_since: null }), ...fields });
- if (fresh) rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
+ if (fresh) {
+ rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
+ // A new attempt: nothing of an earlier one shows (no step, no preview picture).
+ dropProgress(t.id);
+ }
const inputs: TaskInput[] = inputsOf(t.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));
return {
id: t.id,
@@ -606,6 +646,8 @@ export function takeTask(t: TaskRow, device: string, now: number, fields: Partia
graph: json(t.graph_json, {}),
promptId: t.prompt_id,
preview: !!t.preview,
+ // A worker's job whose run shows previews: its latest one comes with its "running" reports.
+ ...(t.pools && t.preview && previewShown(t.generation_id) && { reportPreview: true }),
...(t.prefix && { prefix: t.prefix }),
...(t.meta_batch && { metaBatch: true }),
inputs,
@@ -729,13 +771,14 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
return { ok: true };
case "queued":
setTask(t.id, seen);
- noteProgress(t.id, { position: e.position }, now);
+ noteProgress(t.id, { position: e.position }, now, t.lease_hash);
return { ok: true };
case "running":
setTask(t.id, { ...seen, state: "running", ...(!t.started_at && { started_at: now }), note: null });
- noteProgress(t.id, { ...e, position: undefined }, now);
- // A worker's preview picture of the job: the tile shows the latest one while the run works.
- if (e.preview) notePreview(taskById(t.id) ?? t, e.preview, now);
+ noteProgress(t.id, { ...e, position: undefined }, now, t.lease_hash);
+ // A worker's preview picture of the job: the tile shows the latest one while the run works (as the lease that sent
+ // it still holds the task).
+ if (e.preview) notePreview({ ...(taskById(t.id) ?? t), lease_hash: t.lease_hash }, e.preview, now);
return { ok: true };
case "finished":
case "passes": {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 8ce2f341..896a647c 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -228,8 +228,9 @@ export function toGeneration(r: Row): Generation {
...(stored.place === "pool" && (r.status === "queued" || r.status === "running") && !checking && poolQueue(r.id)),
// The owner's own job on the workers, waiting: its place in their line (in the list as after a refresh).
...(stored.place !== "pool" && r.status === "queued" && r.provider === "comfyui" && workerQueue(r.id)),
- // Working on this install's GPUs: the address of its latest preview picture, while there is one.
- ...(r.status === "running" && r.provider === "comfyui" && !checking && livePreview(r.id)),
+ // Working on this install's GPUs: the address of its latest preview picture, while there is one. None for a run
+ // whose outputs the moderation service sees first (a preview would show what its check holds back).
+ ...(r.status === "running" && r.provider === "comfyui" && !checking && !stored.checkOutputs && livePreview(r.id)),
};
}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 526155cc..fbd396c9 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -2865,7 +2865,9 @@ export const comfyProvider: ProviderAdapter = {
graph: forPool ? withoutSaveMetadata(wf) : wf,
prefix: typeof meta.prefix === "string" ? meta.prefix : undefined,
metaBatch,
- preview: true,
+ // On the workers, a run whose outputs the moderation service sees first shows no preview while it works (its
+ // ComfyUI makes none). A person's own computer shows its own previews in its tab, as before.
+ preview: !(forPool && runStamp()?.checkOutputs),
workflowId: manifest.id,
made: model?.kind,
loras: (input.loras ?? []).map((l) => ({ file: l.file, ...(l.url && { url: l.url }) })),
diff --git a/tests/computer-security.test.ts b/tests/computer-security.test.ts
index 81db25b0..d8226986 100644
--- a/tests/computer-security.test.ts
+++ b/tests/computer-security.test.ts
@@ -375,6 +375,19 @@ describe("reports", () => {
expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(409);
});
+ it("from a person's own computer, a report over 64 KB counts against the lower limit a minute, as before", async () => {
+ waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ const report = (body: Record<string, unknown>) => call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { ...body } });
+ expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(200);
+ // About 70 KB: under the bound a worker's report with its preview picture has, over a person's own computer's.
+ const big = { event: "running", value: 1, max: 4, padding: "x".repeat(70 * 1024) };
+ const statuses: number[] = [];
+ for (let i = 0; i < 31; i++) statuses.push((await report(big)).status);
+ expect(statuses.slice(0, 30).every((s) => s !== 429), JSON.stringify(statuses)).toBe(true);
+ expect(statuses[30]).toBe(429);
+ });
+
it("a finished entry over 8 MB is refused", async () => {
waitingTask(`acct:${a}`);
const c = await claimed("a");
diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.ts
index 108a3a53..2a396335 100644
--- a/tests/helpers/fake-local-comfy.ts
+++ b/tests/helpers/fake-local-comfy.ts
@@ -71,6 +71,11 @@ export interface LocalComfyOptions {
* execution_success.
*/
oldLiveNodes?: boolean;
+ /**
+ * The preview picture each step sends on /ws to a prompt that asked for previews (default: a small PNG). `step`: the
+ * step it comes with (from 1), so each one can differ.
+ */
+ previewPicture?: (step: number) => { type: "image/png" | "image/jpeg"; data: Buffer };
/** Nothing ever starts: prompts wait in the queue (a stuck ComfyUI). */
stall?: boolean;
/**
@@ -365,10 +370,11 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
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" }));
+ const picture = opts.previewPicture?.(step) ?? { type: "image/png", data: FAKE_PNG };
+ const meta = Buffer.from(JSON.stringify({ prompt_id: job.id, node_id: node, image_type: picture.type }));
const len = Buffer.alloc(4);
len.writeUInt32BE(meta.length);
- send(job.clientId, Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, FAKE_PNG]), true);
+ send(job.clientId, Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, picture.data]), true);
}
timer = setTimeout(next, stepMs);
return;
diff --git a/tests/helpers/worker-driver.ts b/tests/helpers/worker-driver.ts
index faa4f552..46560e84 100644
--- a/tests/helpers/worker-driver.ts
+++ b/tests/helpers/worker-driver.ts
@@ -94,6 +94,8 @@ export function workerDriver(o: {
clientId?: string;
/** How long its waits are, at most (the runner's own waits are seconds; tests keep them short). */
sleepCapMs?: number;
+ /** How it makes a preview picture a small JPEG, as the worker program does with ffmpeg (none: it can't). */
+ jpeg?: (data: Uint8Array, type: string) => Promise<Uint8Array | null>;
}): WorkerDriver {
const local = apiAs(o.routes, null, { authorization: `Bearer ${o.token}` });
let target: StudioApi | null = null;
@@ -159,6 +161,7 @@ export function workerDriver(o: {
socket: (url) => (dead ? null : (new WebSocket(url) as never)),
sha256,
origin: "http://localhost:3000",
+ ...(o.jpeg && { jpeg: o.jpeg }),
sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, o.sleepCapMs ?? 50))),
beatExtra: () => ({ protocol: DRIVER_PROTOCOL, version: "test", local: { paused: !!paused, why: paused, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null }),
// As the worker program does when a job ends here: its prompt leaves its ComfyUI's history (once its ComfyUI has
diff --git a/tests/worker-parts.test.ts b/tests/worker-parts.test.ts
index f558deef..6b50d3a5 100644
--- a/tests/worker-parts.test.ts
+++ b/tests/worker-parts.test.ts
@@ -9,7 +9,7 @@ import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { helperCommand, StayAwake } from "../bin/lib/worker/awake.mjs";
-import { encodeArgs, FIT, INPUT_FORMATS, MEDIA_LIMITS, mediaKind, outputCap, reencode } from "../bin/lib/worker/media.mjs";
+import { encodeArgs, FIT, INPUT_FORMATS, MEDIA_LIMITS, mediaKind, outputCap, PREVIEW_QUALITIES, previewArgs, previewJpeg, reencode } from "../bin/lib/worker/media.mjs";
import { RETRY, retrying } from "../bin/lib/worker/retry.mjs";
import { ffmpegOf } from "../bin/lib/worker/config.mjs";
import { takeLock, workerLives, WorkerRunning } from "../bin/lib/worker/lock.mjs";
@@ -216,6 +216,56 @@ describe("clips and sound, made again", () => {
expect(await reencode({ ffmpeg: "ffmpeg", kind: "video", name: "a.mp4", src, dst: path.join(dir, "big.part"), capBytes: 1000, spawnFn: spawnFn as never })).toBe(false);
});
+ it("a preview picture is made a JPEG from ffmpeg's standard input only, at the best quality that fits", async () => {
+ const args = previewArgs("image/png", 4)!;
+ expect(args).toEqual(expect.arrayContaining(["-protocol_whitelist", "pipe", "-f", "png_pipe", "-i", "pipe:0", "-c:v", "mjpeg", "pipe:1"]));
+ expect(args).not.toContain("file");
+ expect(previewArgs("image/jpeg", 4)).toContain("jpeg_pipe");
+ expect(previewArgs("text/html", 4)).toBeNull();
+ // Each try writes a JPEG of the size its quality gives; the first that fits is kept.
+ const sizes: Record<string, number> = { "4": 90_000, "8": 70_000, "14": 40_000, "24": 20_000 };
+ const tried: string[] = [];
+ const spawnFn = (_bin: string, a: string[]) => {
+ const q = a[a.indexOf("-q:v") + 1];
+ tried.push(q);
+ const child = new EventEmitter() as EventEmitter & { pid: number; kill: () => void; stdout: EventEmitter; stdin: EventEmitter & { end: () => void } };
+ child.pid = 0;
+ child.kill = () => {};
+ child.stdout = new EventEmitter();
+ child.stdin = Object.assign(new EventEmitter(), { end: () => {} });
+ setTimeout(() => {
+ child.stdout.emit("data", Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(sizes[q] - 4, 1)]));
+ child.emit("close", 0);
+ }, 2);
+ return child;
+ };
+ const out = await previewJpeg({ ffmpeg: "ffmpeg", data: new Uint8Array(8), type: "image/png", spawnFn: spawnFn as never });
+ expect(tried).toEqual(["4", "8", "14"]);
+ expect(out?.length).toBe(40_000);
+ // Nothing fits, or ffmpeg can't read it: none.
+ tried.length = 0;
+ expect(await previewJpeg({ ffmpeg: "ffmpeg", data: new Uint8Array(8), type: "image/png", maxBytes: 1000, spawnFn: spawnFn as never })).toBeNull();
+ expect(tried).toEqual(PREVIEW_QUALITIES.map(String));
+ const failing = () => Object.assign(new EventEmitter(), { pid: 0, kill: () => {}, stdout: new EventEmitter(), stdin: Object.assign(new EventEmitter(), { end() {} }) });
+ const broken = () => {
+ const c = failing();
+ setTimeout(() => c.emit("close", 1), 2);
+ return c;
+ };
+ expect(await previewJpeg({ ffmpeg: "ffmpeg", data: new Uint8Array(8), type: "image/png", spawnFn: broken as never })).toBeNull();
+ });
+
+ it.runIf(hasFfmpeg)("ffmpeg makes ComfyUI's PNG preview a JPEG of at most 64 KB", async () => {
+ const dir = tempDir("fuobe-worker-preview-");
+ const png = path.join(dir, "preview.png");
+ const made = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=768x512", "-frames:v", "1", png]);
+ expect(made.status).toBe(0);
+ const out = await previewJpeg({ ffmpeg: "ffmpeg", data: new Uint8Array(fs.readFileSync(png)), type: "image/png" });
+ expect(out).not.toBeNull();
+ expect([...out!.subarray(0, 3)]).toEqual([0xff, 0xd8, 0xff]);
+ expect(out!.length).toBeLessThanOrEqual(64 * 1024);
+ });
+
it.runIf(hasFfmpeg)("ffmpeg refuses a playlist that names another file on this PC, and makes a plain clip again", async () => {
const dir = tempDir("fuobe-worker-playlist-");
const clip = path.join(dir, "clip.mp4");