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
Runs on the workers: live progress and a preview picture every app process sees
Adarshe6ddb2b07b73
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex bc1365ff..290bb7cb 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -574,6 +574,12 @@ its target), at most once an hour each.than once counts once: the attempt whose result was kept. The studio keeps at most the run ceiling of the job's lane,and at most the time since the job was sent to its ComfyUI (plus a minute, because ComfyUI starts a job a momentbefore 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.- `give-back` with `why` (`stalled`, `run-limit` or `media`) puts the job back in line. The job keeps its place andcounts 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/src/app/api/generations/[id]/preview/route.ts b/src/app/api/generations/[id]/preview/route.tsnew file mode 100644index 00000000..d9882d37--- /dev/null+++ b/src/app/api/generations/[id]/preview/route.ts@@ -0,0 +1,27 @@+import fs from "node:fs";+import { connection } from "next/server";+import { 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. */+const HEADERS = { "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff" };++/**+ * 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.+ */+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;+ let data: Buffer | null = null;+ try {+ data = p ? fs.readFileSync(p.path) : null;+ } catch {+ // Dropped between the look and the read (the run moved on).+ }+ if (!data) return Response.json({ error: "Not found" }, { status: 404, headers: HEADERS });+ return new Response(new Uint8Array(data), { headers: { ...HEADERS, "Content-Type": "image/jpeg", "Content-Length": String(data.length) } });+}diff --git a/src/app/api/generations/[id]/route.ts b/src/app/api/generations/[id]/route.tsindex 0df61598..118c01c9 100644--- a/src/app/api/generations/[id]/route.ts+++ b/src/app/api/generations/[id]/route.ts@@ -3,15 +3,14 @@ import { getGeneration, setFavorite } from "@/server/generations";import { deleteForever, setPinned, setReview, trashGenerations } from "@/server/library";import { isReviewStatus } from "@/lib/library";import { requestAccount } from "@/server/auth";-import { queueOfGeneration } from "@/server/computer/pool";export async function GET(_req: Request, ctx: RouteContext<"/api/generations/[id]">) {await connection();const { id } = await ctx.params;const g = getGeneration(id);if (!g) return Response.json({ error: "Not found" }, { status: 404 });- const queue = queueOfGeneration(id);- return Response.json(queue ? { ...g, queue } : g);+ // (A run waiting for the workers carries its place in line, as in the list: generations.ts toGeneration.)+ return Response.json(g);}/** Favorite, pin (`pinned`) or set the review status (`review`, null clears it). */diff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.tsindex d2ca0b42..4e0ae9b1 100644--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts@@ -2,7 +2,7 @@ import { GIVE_BACK, RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/rimport { gateAsProxy, readBodyWithin } from "@/server/direct-gate";import { callerKey, principalOf, rateOf, relayAnswer } from "@/server/computer/http";import { noteFinished } from "@/server/computer/bench";-import { leased, report, type TaskRow } from "@/server/computer/tasks";+import { leased, PREVIEW_LIMITS, report, type TaskRow } from "@/server/computer/tasks";import { onComputer, planRelayOutputs } from "@/server/providers/comfyui";import { enter } from "@/server/rate";@@ -10,8 +10,13 @@ const EVENTS = new Set(["sent", "refused", "queued", "running", "finished", "pas/** Reports read at once: one person's, and across the server (each holds its body in memory while it is read). */const AT_ONCE = { person: 2, all: 16 };-/** A report over this size counts against a lower limit a minute. */-const LARGE_BYTES = 64 * 1024;+/**+ * A "running" report may carry a worker's preview picture (64 KB at most, as base64): with its other fields it stays+ * 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;/** The event as the tab sent it, with only the fields each one has, or null. */function eventOf(b: Record<string, unknown>): ReportEvent | null {@@ -30,7 +35,15 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {case "queued":return { event: e, position: num(b.position) ?? -1 };case "running":- return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }) };+ return {+ event: e,+ value: num(b.value),+ max: num(b.max),+ nodesDone: num(b.nodesDone),+ ...(typeof b.node === "string" && { node: b.node }),+ // A worker's preview picture (base64 JPEG): checked and kept by notePreview, dropped when it isn't one.+ ...(typeof b.preview === "string" && b.preview.length <= PREVIEW_REPORT_BYTES && { preview: b.preview }),+ };case "finished":return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never, ...(num(b.peakVramBytes) !== undefined && { peakVramBytes: num(b.peakVramBytes) }), ...exec } : null;case "passes":@@ -77,8 +90,10 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/computeconst { id } = await ctx.params;const lease = request.headers.get("x-fuobe-lease");let cap: number;+ let t0: TaskRow;try {- cap = capFor(leased(principal, id, lease));+ t0 = leased(principal, id, lease);+ cap = capFor(t0);} catch (e) {return relayAnswer(e);}@@ -104,7 +119,8 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute} catch {}const event = body && typeof body === "object" ? eventOf(body) : null;if (!event) return no(400, "Not a report");- if (!LARGE_EVENTS.has(event.event) && raw!.length > RELAY_LIMITS.smallReportBytes) return no(413, "That report is too large");+ const small = event.event === "running" && t0.pools ? PREVIEW_REPORT_BYTES : RELAY_LIMITS.smallReportBytes;+ if (!LARGE_EVENTS.has(event.event) && raw!.length > small) return no(413, "That report is too large");// Where the job is now (it may have moved while the body arrived).const t = leased(principal, id, lease);const answer = report(t, event, (entries, passes) => onComputer(t.principal, () => planRelayOutputs(t, entries, passes)));diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex a2c4deea..1890627a 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -85,15 +85,17 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {// The bar: the steps, or how much of the result has reached the studio.const bar = saving ? Math.round((local.job.phase === "done" ? 1 : (local.job.saved ?? 0)) * 100) : pct;const where = local ? (local.here ? "Keep this tab open" : "Running in another Fuobe tab") : null;+ // A live frame: from the ComfyUI on this computer, or (Working on this studio's GPUs) the latest preview picture.+ const frame = local?.preview ?? (pool && !inLine ? g.preview : undefined);return (// max-w-full: in a grid row stretched by a taller neighbour (a card with a footer), h-full + aspect-ratio would// otherwise make the tile wider than its column and spill over the next card.<div className="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }} data-run-state={pool ? (inLine ? "in-line" : "working") : undefined}><div className="skeleton-sweep absolute inset-0 animate-skeleton" />- {local?.preview && (- // eslint-disable-next-line @next/next/no-img-element -- a live frame from the person's own ComfyUI (a blob: address)+ {frame && (+ // eslint-disable-next-line @next/next/no-img-element -- a live frame (a blob: address, or the run's own preview picture)<img- src={local.preview}+ src={frame}alt=""// Shown once a frame decodes (a frame that doesn't keeps the shimmer).onLoad={(e) => (e.currentTarget.style.opacity = "0.9")}@@ -101,7 +103,7 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {className="absolute inset-0 size-full object-cover opacity-0 transition-opacity duration-300"/>)}- <div className={cn("absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3", local?.preview && "bg-gradient-to-t from-background/85 to-transparent pt-8")}>+ <div className={cn("absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3", frame && "bg-gradient-to-t from-background/85 to-transparent pt-8")}><div className="min-w-0"><p title={label} className="shimmer-text animate-shimmer-text line-clamp-2 text-[13px] font-medium">{label}diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex c0d500b1..d8b033e2 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1487,6 +1487,11 @@ export interface Generation {stage?: "checking";/** A run waiting for this install's GPUs: its place in line and the wait, about (GET /api/generations/<id>). */queue?: { place: number; etaSeconds: number | null };+ /**+ * A run working on this install's GPUs: the address of its latest preview picture (a JPEG, for the run's own account+ * only), while there is one.+ */+ preview?: string;/*** What the run leaves out or changes, said when it is created (LoRAs a cloud run can't carry, a clip length* the API rounds). Only on the answer that creates it; not stored.diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex bd1e7742..92173fbc 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -157,6 +157,9 @@ export function accountGeneration(method: string, pathname: string): string | un// Cancel, and Fuobe Soul's finished picture for its own result.const step = /^\/api\/generations\/([^/]+)\/(cancel|finish)$/.exec(pathname);if (method === "POST" && step) return step[1];+ // A run's live preview picture while it works.+ const preview = /^\/api\/generations\/([^/]+)\/preview$/.exec(pathname);+ if ((method === "GET" || method === "HEAD") && preview) return preview[1];const one = GENERATION.exec(pathname);// PATCH: a like, a pin or a review status (all the route changes).return one && (method === "GET" || method === "HEAD" || method === "PATCH" || method === "DELETE") ? one[1] : undefined;diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 5719a5d9..1ab2f6c2 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -49,8 +49,11 @@ export type ReportEvent =| { event: "refused"; status: number; body: unknown }/** Waiting in ComfyUI's queue: how many prompts are before it. */| { event: "queued"; position: number }- /** Running: the sampler's steps, and the node. */- | { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number }+ /**+ * Running: the sampler's steps, and the node. A worker may add `preview`: its latest preview picture of the job, a+ * JPEG of at most 64 KB as base64, at most one every 2 s (the run's tile shows it while it works).+ */+ | { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number; preview?: string }/*** Finished: its /history entry. A worker adds the most VRAM it took (for the benchmarks), how long its ComfyUI spent* executing the job (`execMs`: execution only, no waits, no uploads), its GPU's name (`device`), and `kept` when thediff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 54e44592..3a139b67 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -5,7 +5,7 @@ import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type Compuimport { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";import { db } from "../db";import { loadIndex } from "../gpu/index-file";-import { cleanFacts, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, type TaskRow } from "./tasks";+import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, type TaskRow } from "./tasks";import { queueSettings, runCeilingMs } from "../queue-settings";import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";@@ -532,6 +532,8 @@ export function backInLine(t: TaskRow, o: { blame: boolean; why?: string; last?:...(o.lostAt && t.worker_id && { extra_json: JSON.stringify({ ...json<Record<string, unknown>>(t.extra_json, {}), lost: { worker: t.worker_id, at: o.lostAt } }) }),});d.prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);+ // In line again: nothing of the attempt before shows (no step, no preview).+ dropProgress(t.id);return true;}).immediate();}diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 7a7eadd7..413105d1 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -51,10 +51,8 @@ const inputFile = (name: string) => path.join(relayDir(), "in", name);const taskDir = (id: string) => path.join(relayDir(), "tasks", id);export const outputFile = (id: string, n: number) => path.join(taskDir(id), `out-${n}`);-declare global {- /** Live progress by task id (written on every step, so kept in memory, not in SQLite). */- var __fuobeRelayProgress: Map<string, Progress> | undefined;-}+/** A task's latest preview picture (a worker's JPEG while the job renders), in the task's folder. */+const previewFile = (id: string) => path.join(taskDir(id), "preview.jpg");export interface Progress {value?: number;@@ -65,8 +63,14 @@ export interface Progress {at: number;}-const progressMap = () => (globalThis.__fuobeRelayProgress ??= new Map());-export const taskProgress = (id: string): Progress | undefined => progressMap().get(id);+/**+ * A task's live progress, as its last report or beat said it. Kept in the database (relay_tasks.progress_json), not in+ * one process's memory: a refresh, a second device and the other app process during a deploy all see the same step.+ */+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;/** The relay's tables are made with the database (db.ts RELAY_TABLES). */const rdb = () => db();@@ -110,6 +114,9 @@ export interface TaskRow {worker_id: string | null;/** Its class in the line: "paid", "free" (people's runs) or "owner" (the owner's own jobs, served last). NULL: from before classes, read as "owner" with no account and "free" with one. */class: string | null;+ /** Its live progress as JSON (taskProgress), and when its latest preview picture came (null: none kept). */+ progress_json: string | null;+ preview_at: number | null;created_at: number;updated_at: number;claimed_at: number | null;@@ -485,6 +492,7 @@ export function beat(principal: Principal, b: BeatInput, now = Date.now()): Beatreturn { 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) {const p: Progress = { at: now };for (const k of ["value", "max", "nodesDone", "position"] as const) {@@ -493,9 +501,62 @@ export function noteProgress(id: string, r: Record<string, unknown>, now: number}const node = str(r.node, 64);if (node) p.node = node;- progressMap().set(id, { ...progressMap().get(id), ...p });+ 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;+ if (!cur) return;+ d.prepare("UPDATE relay_tasks SET progress_json = ? WHERE id = ?").run(JSON.stringify({ ...taskProgress(cur), ...p }), id);+ })();+}++/** Is this a JPEG picture (its first bytes)? */+const isJpeg = (b: Buffer) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff;++/**+ * 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.+ */+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;+ 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;+ 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;+}++/** Forget a task's progress and its preview picture (it ended, or went back in line, or its ComfyUI starts it again). */+export function dropProgress(id: string): void {+ rdb().prepare("UPDATE relay_tasks SET progress_json = NULL, preview_at = NULL WHERE id = ?").run(id);+ fs.rmSync(previewFile(id), { force: true });+}++/**+ * The latest preview picture of a run's job on the workers while it works, and when it came; null when there is none.+ * The caller has checked that the run is the viewer's own.+ */+export function runPreview(generationId: string): { path: string; at: number } | null {+ const t = previewTask(generationId);+ if (!t) return null;+ const file = previewFile(t.id);+ return fs.existsSync(file) ? { path: file, at: t.preview_at } : null;}+const previewTask = (generationId: string) =>+ rdb()+ .prepare("SELECT id, preview_at FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND state IN ('queued','running') AND preview_at IS NOT NULL ORDER BY created_at DESC LIMIT 1")+ .get(generationId) as { id: string; preview_at: number } | undefined;++/** When a run's latest preview picture came (null: it has none now), for the address its tile loads it from. */+export const runPreviewAt = (generationId: string): number | null => previewTask(generationId)?.preview_at ?? null;+/*** A computer asks for work: first a task it took before and lost track of (a reload: not in `running`), then, when it is* the runner, the oldest waiting task. Null when there is none. The claim gets a new lease each time.@@ -594,7 +655,7 @@ export function endTask(id: string, state: "done" | "failed" | "canceled", fieldsetTask(id, { state, finished_at: Date.now(), down_at: null, down_why: null, ...(stop && { stop }), ...fields });// A task a worker held ends: the workers' log says how.if (t?.pools && t.worker_id && (ACTIVE_STATES as readonly string[]).includes(t.state)) logWorkerJob(state, t, t.worker_id);- progressMap().delete(id);+ dropProgress(id);for (const i of rdb().prepare("SELECT name FROM relay_inputs WHERE task_id = ?").all(id) as { name: string }[]) fs.rmSync(inputFile(i.name), { force: true });rdb().prepare("DELETE FROM relay_inputs WHERE task_id = ?").run(id);}@@ -673,6 +734,8 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLikecase "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);return { ok: true };case "finished":case "passes": {@@ -722,6 +785,7 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike// A worker's task sends its files again: its sending clock (pool.ts SENDING_MS) starts again from now. The// attempt's own deadline stays where its claim put it (pool.ts attemptDeadline).setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null, ...(t.pools && { sending_since: now }) });+ dropProgress(t.id);rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);return { ok: true };}@@ -851,7 +915,6 @@ function sweepPrincipal(principal?: Principal) {export function purgeComputer(principal: Principal): void {const d = rdb();for (const t of d.prepare("SELECT id FROM relay_tasks WHERE principal = ?").all(principal) as { id: string }[]) {- progressMap().delete(t.id);fs.rmSync(taskDir(t.id), { recursive: true, force: true });}for (const i of d.prepare("SELECT name FROM relay_inputs WHERE principal = ?").all(principal) as { name: string }[]) fs.rmSync(inputFile(i.name), { force: true });diff --git a/src/server/db.ts b/src/server/db.tsindex dbb9d74c..abb0714e 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1009,6 +1009,10 @@ const RELAY_COLUMNS: [string, string, string][] = [["relay_tasks", "class", "TEXT"],// Since when a worker's task has been sending its files again on the same claim (NULL: since its claim).["relay_tasks", "sending_since", "INTEGER"],+ // A task's live progress (its step, its node, its place in its ComfyUI's queue) as JSON, and when its latest preview+ // picture came (the picture is a file in the task's folder): kept in the database, so every app process sees them.+ ["relay_tasks", "progress_json", "TEXT"],+ ["relay_tasks", "preview_at", "INTEGER"],// A pool worker's next token (workers.ts offerNextToken) and where its token was used from (hashed networks).["relay_workers", "next_token_hash", "TEXT"],["relay_workers", "next_expires_at", "INTEGER"],diff --git a/src/server/generations.ts b/src/server/generations.tsindex be8c8f77..036f9062 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -106,7 +106,8 @@ import { accountSend } from "./account-send";import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";import { placeInLine, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";-import { poolLane } from "./computer/pool";+import { poolLane, queueOfGeneration } from "./computer/pool";+import { runPreviewAt } from "./computer/tasks";import { runCeilingMs } from "./queue-settings";import { sweepBilling } from "./billing-outbox";import { inDemoScope, outsideDemo } from "./demo-scope";@@ -225,9 +226,25 @@ export function toGeneration(r: Row): Generation {...(checking && !pool && { stage: "checking" as const }),// Waiting in line on this install's GPUs: its place and the wait, about....(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)),};}+/** The owner's job waiting for the workers: its place in their line, as the Generation field. */+function workerQueue(id: string): { queue: { place: number; etaSeconds: number | null } } | Record<string, never> {+ const q = queueOfGeneration(id);+ return q ? { queue: q } : {};+}++/** A run's latest preview picture from the workers, as the address its tile loads (it changes with each picture). */+function livePreview(id: string): { preview: string } | Record<string, never> {+ const at = runPreviewAt(id);+ return at ? { preview: `/api/generations/${encodeURIComponent(id)}/preview?at=${at}` } : {};+}+/** A pool row's words while it goes: in line, or working on it. */function poolMessage(r: Pick<Row, "status" | "message">): string | null {if (r.status === "queued") return POOL_WORDS.inLine;diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 492a135c..526155cc 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -2738,7 +2738,7 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,/** Where a task is (on someone's computer, or with a worker), in the words its tile shows. */async function pollTask(principal: Principal, t: TaskRow, meta: Record<string, unknown>, manifest: ManifestWorkflow | undefined, made: string | undefined): Promise<PollResult> {- const p = taskProgress(t.id);+ const p = taskProgress(t);const kind = extraOf(t).made ?? made ?? "image";const waitMs = tenantAccount() ? ACCOUNT_LIMITS.queueMs : 4 * 3_600_000;const sentAt = t.sent_at ?? undefined;diff --git a/tests/helpers/worker-driver.ts b/tests/helpers/worker-driver.tsindex b04fa833..faa4f552 100644--- a/tests/helpers/worker-driver.ts+++ b/tests/helpers/worker-driver.ts@@ -60,6 +60,11 @@ export interface WorkerDriver {* restart the app, …). A report's event comes with it.*/onStep: (fn: StepHook | null) => void;+ /**+ * Its "running" reports carry a preview picture (base64, as the worker program sends one), from `fn` at each report+ * (undefined: none with that report). Null: none.+ */+ previews: (fn: (() => string | undefined) | null) => void;stop: () => void;}@@ -97,6 +102,7 @@ export function workerDriver(o: {const answers: { step: WorkerStep; status: number; left: number }[] = [];let paused: string | null = null;let hook: StepHook | null = null;+ let preview: (() => string | undefined) | null = null;let died: () => void = () => {};const diedP = new Promise<"stopped">((r) => (died = () => r("stopped")));const calls: string[] = [];@@ -112,6 +118,13 @@ export function workerDriver(o: {const api: StudioApi = async (path, init = {}) => {if (dead) return never();const step = stepOf(path, init);+ if (step === "running" && preview && typeof init.body === "string") {+ const picture = preview();+ if (picture) {+ const body = JSON.stringify({ ...(JSON.parse(init.body) as Record<string, unknown>), preview: picture });+ init = { ...init, body, headers: { ...Object.fromEntries(new Headers(init.headers)), "content-length": String(Buffer.byteLength(body)) } };+ }+ }calls.push(`${step} ${path.split("?")[0]}`);const fake = answers.find((a) => a.step === step && a.left > 0);if (fake) {@@ -204,6 +217,9 @@ export function workerDriver(o: {onStep: (fn) => {hook = fn;},+ previews: (fn) => {+ preview = fn;+ },stop: die,};}diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex fe105d7e..2cfc7573 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -1,4 +1,6 @@import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { runnerByHand, startAppProcess, tick, type AppProcess } from "./helpers/app-process";import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";@@ -49,6 +51,7 @@ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {const auth = await import("@/server/auth");const generationsRoute = await import("@/app/api/generations/route");const oneRoute = await import("@/app/api/generations/[id]/route");+const previewRoute = await import("@/app/api/generations/[id]/preview/route");const { proxy } = await import("@/proxy");const { NextRequest } = await import("next/server");const { db } = await import("@/server/db");@@ -194,6 +197,21 @@ async function sessionGet(cookie: string, id: string): Promise<{ status: number;return { status: r.status, run: r.ok ? ((await r.json()) as RunLike) : null };}+/** A small JPEG as a worker sends its preview picture (base64): its bytes start as a JPEG's, then `n` and filler. */+const jpegBase64 = (n: number, size = 2000) => Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from(`preview ${n} `), Buffer.alloc(size, n % 251)]).toString("base64");++/** GET a run's preview picture as a session's browser asks it: the response. */+const previewGet = (cookie: string, url: string) => {+ const id = /^\/api\/generations\/([^/]+)\/preview/.exec(url)![1];+ return browserGet(url, cookie, (req) => previewRoute.GET(req, { params: Promise.resolve({ id }) } as never));+};++/** The picture's first bytes (hex) as the session gets it, or its status when it gets none. */+async function previewOf(cookie: string, url: string): Promise<string> {+ const r = await previewGet(cookie, url);+ return r.ok ? Buffer.from(await r.arrayBuffer()).subarray(0, 12).toString("hex") : String(r.status);+}+/** A run as a session reads it (an answer that isn't OK throws: a person would see an error). */const sessionRead = (cookie: string) => async (id: string) => {const { status, run } = await sessionGet(cookie, id);@@ -470,6 +488,136 @@ describe("a refresh, a second session and the list see the same run", () => {});});+describe("a run's preview picture while it works", () => {+ it("the Working tile gets the worker's latest picture, for the run's own account only and never kept by a cache; it goes when the run ends", async () => {+ const w = standInWorker();+ const { id, task } = await pressRun();+ const watch = watchOf(id);+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 100;+ const d = driver(w);+ let n = 0;+ d.previews(() => jpegBase64(++n));+ const seen: { session?: string; list?: string; picture: string; headers: Record<string, string | null>; other: number; guest: number }[] = [];+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running" || seen.length) return;+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ if (!g.preview) return;+ const listed = (await listRead(a1)(id)) as (RunLike & { preview?: string }) | null;+ const r = await previewGet(a2, g.preview);+ seen.push({+ session: g.preview,+ list: listed?.preview,+ picture: Buffer.from(await r.arrayBuffer()).subarray(0, 3).toString("hex"),+ headers: { type: r.headers.get("content-type"), cache: r.headers.get("cache-control"), sniff: r.headers.get("x-content-type-options") },+ other: (await previewGet(b1, g.preview)).status,+ guest: (await previewGet("", g.preview)).status,+ });+ });+ await workAll(d);+ expect(seen).toHaveLength(1);+ const [s] = seen;+ expect(s.session).toMatch(new RegExp(`^/api/generations/${id}/preview\\?at=\\d+$`));+ expect(s.list, "the list carries it too").toBe(s.session);+ expect(s.picture).toBe("ffd8ff");+ expect(s.headers).toEqual({ type: "image/jpeg", cache: "private, no-store", sniff: "nosniff" });+ expect(s.other, "another account").toBe(403);+ expect(s.guest, "a guest").toBe(401);+ // Ended: no picture is left, and its address answers nothing.+ const g = (await expectOnce(id, watch, { prompts: 1, place: 1 })) as RunLike & { preview?: string };+ expect(g.preview).toBeUndefined();+ expect((await previewGet(a1, s.session!)).status).toBe(404);+ expect(taskOf(id)!.preview_at).toBeNull();+ expect(tasks.runPreview(id)).toBeNull();+ expect(fs.existsSync(path.join(tasks.relayDir(), "tasks", task.id, "preview.jpg"))).toBe(false);+ });++ it("back in line, the run shows no picture of the attempt before", async () => {+ clock();+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 100;+ const d = driver(w);+ d.previews(() => jpegBase64(1));+ let had = "";+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running" || had) return;+ had = ((await sessionRead(a1)(id)) as RunLike & { preview?: string }).preview ?? "";+ if (!had) return;+ d.pause("gpu-busy:game.exe");+ await d.beat();+ });+ await workAll(d);+ expect(had).toMatch(/\/preview\?at=/);+ await tick();+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ expect(g).toMatchObject({ status: "queued", queue: { place: 1 } });+ expect(g.preview).toBeUndefined();+ expect((await previewGet(a1, had)).status).toBe(404);+ d.pause(null);+ d.previews(null);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { place: 1 });+ });++ it("a picture that isn't a JPEG, is over 64 KB or comes within 2 s of the last is dropped; a person's own computer keeps none", () => {+ const now = 1_000_000;+ const t = { id: "t".repeat(16), pools: "pool", preview_at: null };+ expect(tasks.notePreview(t, Buffer.from("not a picture").toString("base64"), now)).toBe(false);+ expect(tasks.notePreview(t, jpegBase64(1, 70 * 1024), now)).toBe(false);+ expect(tasks.notePreview(t, "%%%", now)).toBe(false);+ expect(tasks.notePreview({ ...t, pools: null }, jpegBase64(1), now)).toBe(false);+ expect(tasks.notePreview({ ...t, preview_at: now - 1000 }, jpegBase64(1), now)).toBe(false);+ expect(tasks.notePreview({ ...t, preview_at: now - 2000 }, jpegBase64(1), now)).toBe(true);+ tasks.dropProgress(t.id);+ });++ it("a worker's report with a picture over 64 KB is taken without the picture, and the run goes on", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ d.previews(() => jpegBase64(1, 66 * 1024));+ const previews: (string | undefined)[] = [];+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step === "running") previews.push(((await sessionRead(a1)(id)) as RunLike & { preview?: string }).preview);+ });+ await workAll(d);+ expect(d.steps).toContain("running");+ expect(previews.length).toBeGreaterThan(0);+ expect(previews.every((p) => p === undefined)).toBe(true);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });+});++describe("the owner's own job on the workers", () => {+ it("waiting, it carries its place in their line in the list as after a refresh", async () => {+ const w = standInWorker();+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ const theirs = await pressRun(IMAGE, b1);+ const { id } = await pressRun(IMAGE, owner);+ expect(taskOf(id)!.principal).toBe("owner");+ const one = (await sessionRead(owner)(id)) as RunLike & { queue?: { place: number } };+ const listed = (await listRead(owner)(id)) as (RunLike & { queue?: { place: number } }) | null;+ // People's runs go first: the owner's job is second.+ expect(one.queue?.place).toBe(2);+ expect(listed?.queue).toEqual(one.queue);+ const d = driver(w);+ lookAtEveryStep(d, watchOf(theirs.id));+ await workAll(d);+ expect((await ended(id))?.status).toBe("succeeded");+ });+});+describe("a press of Run sent twice (a network drop at submit)", () => {it("makes a second run and a second hold today: the run route reads no request id from the page, so each press reserves under an id of its own", async () => {standInWorker();@@ -880,7 +1028,7 @@ describe("two app processes on one database (a deploy's overlap)", () => {await expect(app2.generation(id, b1)).rejects.toThrow(/answered 403/);});- it("a step the worker reports to the other process isn't seen here today: live progress stays in the memory of the process that took the report, so every look shows no step", async () => {+ it("a step and a preview picture the worker reports to the other process are seen here too: a refresh, both sessions, the list and the other process show the same step", async () => {const w = standInWorker();const { id } = await pressRun();const watch = watchOf(id, { "other process": there(id) });@@ -889,15 +1037,25 @@ describe("two app processes on one database (a deploy's overlap)", () => {const d = driver(w);// The worker's calls reach the other process; this one's runner turns.d.via(app2.api);+ let n = 0;+ d.previews(() => jpegBase64(++n));const steps: (number | null)[][] = [];+ const pictures: (string | null)[] = [];d.onStep(async (step, _path, report) => {if (step !== "running" || Number(report?.value ?? 0) < 2) return;await tick();steps.push((await watch.look()).map((s) => s.progress));+ const g = (await sessionRead(a2)(id)) as RunLike & { preview?: string };+ pictures.push(g.preview ? await previewOf(a2, g.preview) : null);});await workAll(d);expect(steps.length, "looks while the worker said it was past step 2").toBeGreaterThan(0);- for (const at of steps) for (const p of at) expect(p ?? 0, "the step a look shows").toBe(0);+ for (const at of steps) {+ for (const p of at) expect(p ?? 0, "the step a look shows").toBeGreaterThan(0);+ expect(Math.max(...at.map((p) => p ?? 0)) - Math.min(...at.map((p) => p ?? 0)), "every look at one moment, the same step").toBeLessThanOrEqual(1 / 10 + 1e-9);+ }+ // The second device loads the picture from this process, though the other one took it.+ expect(pictures.some((p) => p && p.startsWith("ffd8ff"))).toBe(true);await expectOnce(id, watch, { prompts: 1, place: 1 });});