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: progress follows the sampler's steps
Adarshf0cbfdfc21d8
diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 5ac40697..857b7a09 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -551,8 +551,10 @@ export const RELAY_WORDS = {export const POOL_WORDS = {inLine: "In line",working: "Working",- /** Working, with its model still loading (the GPU had another one loaded): no progress yet. */- gettingReady: "Warming up · starting in a moment",+ /** Working, with its model still loading (the GPU had another one loaded): a small share that grows slowly. */+ gettingReady: "Loading the model",+ /** Its sampler is done: decoding, sound, its files. */+ finishing: "Finishing",/** The owner's own run, given back to the line so that a person's run could start first (pool.ts, people first). */paused: "Paused for a moment · starts again automatically",failed: "That one didn't come out right — try again, or try a similar model.",diff --git a/src/lib/run-progress.ts b/src/lib/run-progress.tsnew file mode 100644index 00000000..579ca19b--- /dev/null+++ b/src/lib/run-progress.ts@@ -0,0 +1,258 @@+/**+ * How far a ComfyUI job is, from what its socket reports (each node that starts, and the steps of a node that has+ * them), as one share from 0 to 0.99 that every place showing the run reads: its card, the studio feeds, the Library,+ * the API and the admin.+ *+ * Most of a job's time is its sampler's steps, while the sampler is one node of many, so the share of nodes run says+ * little: a graph whose loaders and encoders run first reads three quarters done before its first step. Here the bar has+ * stages instead:+ *+ * - getting ready (its models loading, its prompt encoding): a small share that grows slowly with time, at most+ * PROGRESS_BANDS.ready;+ * - sampling: most of the bar, by the steps of each sampler pass the graph has (in the order they run), and between two+ * steps by the time a step takes;+ * - finishing (decoding, sound, saving the files on the GPU): the next few percent, by the nodes after the sampler;+ * - collecting (the results coming to the studio): the last percent.+ *+ * The share never passes 0.99 before the run is done; the server keeps the highest share shown in one try (`shown`), so+ * it never moves backwards there. A new try starts again from its own first stage.+ *+ * Pure: the server and the tests share it.+ */++import { madeNoun, makingWords, POOL_WORDS, type MadeKind } from "./relay";++/** Where each stage ends on the bar. */+export const PROGRESS_BANDS = {+ /** Getting ready: up to here, slowly. */+ ready: 0.1,+ /** The sampler passes the graph has: up to here. */+ sampled: 0.9,+ /** Passes beyond the graph's own (a loop that runs its sampler again): each takes half of what is left, up to here. */+ extra: 0.94,+ /** The nodes after the sampler: up to here. */+ finished: 0.97,+ /** Never more before the run is done. */+ most: 0.99,+} as const;++/** The time over which getting ready grows to about two thirds of its band (a cold model load takes minutes). */+const READY_MS = 90_000;+/** Between two steps, the time a step takes fills at most this much of the next one. */+const IN_STEP = 0.9;+/** The step passes kept per try (the newest). */+const KEEP_PASSES = 16;++/** One pass of a node with steps, as its reports said. */+export interface StepPass {+ /** The node's id, when a report named it. */+ node?: string;+ /** How many nodes had started when it ran (the running node included): which node of the job it is. */+ at: number;+ value: number;+ max: number;+ /** The first value seen, and when; when the value now was first seen. */+ v0: number;+ t0: number;+ tv: number;+}++/** A job's live progress as the server keeps it (relay_tasks.progress_json, or the socket's own record). */+export interface LiveProgress {+ value?: number;+ max?: number;+ node?: string;+ nodesDone?: number;+ cold?: boolean;+ /** When this try first reported. */+ since?: number;+ /** The passes with steps of this try, oldest first. */+ passes?: StepPass[];+ /** The highest share shown in this try. */+ shown?: number;+}++/** What a graph says about its stages: its node count, the nodes that sample, and how many nodes come after them. */+export interface ProgressPlan {+ nodes: number;+ samplers: string[];+ after: number;+}++type GraphNode = { class_type?: unknown; inputs?: Record<string, unknown> };++/** A node that runs steps: KSampler, KSamplerAdvanced, SamplerCustom(Advanced), and a pack's own *Sampler nodes. */+const SAMPLER_CLASS = /^(?:SamplerCustom(?:Advanced)?|\w*[A-Za-z0-9]Sampler(?:Advanced)?)$/;++const isLink = (v: unknown): v is [string, number] => Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "number";++/**+ * A graph's plan (ComfyUI's API format: node id → { class_type, inputs }). A sampler is a node of a sampler class that+ * takes links (a sampler's settings node, such as KSamplerSelect or a pack's sampler choice, takes none, or feeds+ * another node's `sampler` input). `after`: the nodes that read a sampler's result, directly or not (the decode, the+ * sound, the file).+ */+export function progressPlan(graph: unknown): ProgressPlan {+ const g = graph && typeof graph === "object" ? (graph as Record<string, GraphNode | undefined>) : {};+ const ids = Object.keys(g).filter((k) => g[k] && typeof g[k] === "object");+ const settings = new Set<string>();+ const readers = new Map<string, string[]>();+ for (const id of ids) {+ for (const [name, v] of Object.entries(g[id]!.inputs ?? {})) {+ if (!isLink(v)) continue;+ if (name === "sampler") settings.add(v[0]);+ readers.set(v[0], [...(readers.get(v[0]) ?? []), id]);+ }+ }+ const samplers = ids.filter((id) => {+ const n = g[id]!;+ return typeof n.class_type === "string" && SAMPLER_CLASS.test(n.class_type) && !settings.has(id) && Object.values(n.inputs ?? {}).some(isLink);+ });+ const sampler = new Set(samplers);+ const after = new Set<string>();+ const todo = [...samplers];+ while (todo.length) {+ for (const r of readers.get(todo.pop()!) ?? []) {+ if (after.has(r) || sampler.has(r)) continue;+ after.add(r);+ todo.push(r);+ }+ }+ return { nodes: ids.length, samplers: samplers.slice(0, 64), after: after.size };+}++/** A plan kept in a run's meta, read back (null: none, or not one). */+export function planOf(v: unknown): ProgressPlan | null {+ if (!v || typeof v !== "object") return null;+ const p = v as Record<string, unknown>;+ const nodes = Number(p.nodes);+ const after = Number(p.after);+ if (!Number.isFinite(nodes) || !Number.isFinite(after) || !Array.isArray(p.samplers)) return null;+ return { nodes, after, samplers: p.samplers.filter((s): s is string => typeof s === "string").slice(0, 64) };+}++const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);++/**+ * A new report (a progress report or a beat) over what was kept: its fields over the old ones, and its steps noted as a+ * pass. A node that started since (more nodes started, no step yet) clears the step of the node before, so a finished+ * sampler's last step is never read as the step now. Fewer nodes started than before: its ComfyUI runs the job again+ * from the start, so its passes start again (the share shown stays).+ */+export function trackReport(prev: LiveProgress | undefined, r: { value?: unknown; max?: unknown; node?: unknown; nodesDone?: unknown }, now: number): LiveProgress {+ const value = num(r.value);+ const max = num(r.max);+ const done = num(r.nodesDone);+ const node = typeof r.node === "string" && r.node ? r.node.slice(0, 64) : undefined;+ // This try's clock starts with its first word from the running job (a place in a queue isn't one).+ const running = value !== undefined || max !== undefined || done !== undefined || node !== undefined;+ const next: LiveProgress = { ...prev };+ if (next.since === undefined && running) next.since = now;+ let passes = prev?.passes ?? [];+ if (done !== undefined && prev?.nodesDone !== undefined && done < prev.nodesDone) passes = [];+ const moved = done !== undefined && done !== prev?.nodesDone;+ if (done !== undefined) next.nodesDone = done;+ if (node) next.node = node;+ if (value !== undefined && max) {+ next.value = value;+ next.max = max;+ const at = done ?? prev?.nodesDone ?? 0;+ // A beat names no node: the node a report named at the same place is the one with these steps.+ const named = node ?? (at === prev?.nodesDone ? prev?.node : undefined);+ const last = passes.at(-1);+ const same = last && last.at === at && last.max === max && (!named || !last.node || last.node === named);+ // The same node again from its first steps (a loop that runs it once more): a new pass.+ const again = same && last.value >= max / 2 && value <= max / 4 && value < last.value;+ if (same && !again) {+ if (value > last.value || (named && !last.node)) passes = [...passes.slice(0, -1), { ...last, ...(value > last.value && { value, tv: now }), ...(named && !last.node && { node: named }) }];+ } else {+ passes = [...passes, { ...(named && { node: named }), at, value, max, v0: value, t0: now, tv: now }].slice(-KEEP_PASSES);+ }+ } else if (moved || (node && node !== prev?.node)) {+ delete next.value;+ delete next.max;+ }+ if (passes.length) next.passes = passes;+ else delete next.passes;+ return next;+}++/** The stages a running job shows. */+export type ProgressStage = "loading" | "preparing" | "sampling" | "finishing";++export interface ProgressView {+ /** 0 to 0.99. */+ share: number;+ stage: ProgressStage;+ /** The sampler's step now, while it samples. */+ step?: { value: number; max: number };+}++const clamp01 = (n: number) => Math.min(1, Math.max(0, n));++/**+ * How far a running job is (`plan`: its graph's plan, or null when the run has none: then every node with steps counts+ * as a sampler pass, and each pass seen so far as one of the graph's). `now`: the server's clock. Not floored: the+ * caller keeps the highest share shown (`shown`).+ */+export function progressView(p: LiveProgress | undefined, plan: ProgressPlan | null, now: number): ProgressView {+ const B = PROGRESS_BANDS;+ const since = p?.since ?? now;+ const all = p?.passes ?? (p?.max && p.value !== undefined ? [{ node: p.node, at: p.nodesDone ?? 0, value: p.value, max: p.max, v0: p.value, t0: now, tv: now }] : []);+ const named = plan?.samplers.length ? new Set(plan.samplers) : null;+ // The sampler passes: the graph's samplers' (a pass with no node name counts), or every pass with steps when the+ // graph names none or its names never come up.+ const mine = named ? all.filter((x) => !x.node || named.has(x.node)) : all;+ const passes = mine.length ? mine : all;+ if (!passes.length) {+ const ready = B.ready * (1 - Math.exp(-Math.max(0, now - since) / READY_MS));+ return { share: ready, stage: p?.cold ? "loading" : "preparing" };+ }+ const planned = Math.max(1, named && mine.length ? plan!.samplers.length : passes.length);+ const last = passes[passes.length - 1];+ const done = p?.nodesDone ?? last.at;+ // Still in the last pass's node: its steps, and the time since the last one (at the pace of the steps before it).+ const inLast = done <= last.at;+ const perStep = last.value > last.v0 ? (last.tv - last.t0) / (last.value - last.v0) : 0;+ const inStep = inLast && perStep > 0 && last.value < last.max ? Math.min(IN_STEP, Math.max(0, now - last.tv) / perStep) : 0;+ const frac = inLast ? clamp01((last.value + inStep) / last.max) : 1;+ // Pass k of `planned` (from 0): its share of the sampling band; a pass beyond the graph's own takes half of what is left.+ const k = passes.length - 1;+ const sampled = k < planned ? B.ready + (B.sampled - B.ready) * ((k + frac) / planned) : B.sampled + (B.extra - B.sampled) * (1 - Math.pow(0.5, k - planned + frac));+ if (inLast) return { share: Math.min(B.most, sampled), stage: "sampling", ...(last.value >= 1 && { step: { value: Math.min(last.value, last.max), max: last.max } }) };+ // Between two of the graph's passes.+ if (passes.length < planned) return { share: Math.min(B.most, sampled), stage: "sampling" };+ // After the last pass: the nodes that read its result, each started one counting as half done (or by its own steps).+ const after = Math.max(1, plan?.after || Math.max(1, (plan?.nodes ?? 0) - last.at));+ const own = p?.max && p.value !== undefined ? clamp01(p.value / p.max) : 0.5;+ const ran = clamp01((done - last.at - 1 + own) / after);+ const from = Math.max(sampled, B.sampled);+ return { share: Math.min(B.most, from + (B.finished - from) * ran), stage: "finishing" };+}++/** The share while the results come to the studio (`received`: the share of their bytes that arrived). */+export const collectingShare = (received: number | undefined) => PROGRESS_BANDS.finished + (PROGRESS_BANDS.most - PROGRESS_BANDS.finished) * clamp01(received ?? 0);++/** The share to show: never below the highest shown in this try, never above 0.99. */+export const floored = (share: number, shown: number | undefined) => Math.min(PROGRESS_BANDS.most, Math.max(share, shown ?? 0));++/** "Step 3 of 6". */+export const stepWords = (step: { value: number; max: number }) => `Step ${Math.min(step.value, step.max)} of ${step.max}`;++/** A person's words for a running job on this install's GPUs: "Loading the model", "Working · Step 3 of 6", "Finishing". */+export function poolRunWords(v: Pick<ProgressView, "stage" | "step">): string {+ if (v.stage === "loading") return POOL_WORDS.gettingReady;+ if (v.stage === "finishing") return POOL_WORDS.finishing;+ return v.step ? `${POOL_WORDS.working} · ${stepWords(v.step)}` : POOL_WORDS.working;+}++/** Is this one of poolRunWords' (the words a person's running job may show)? */+export const isPoolRunWords = (m: string | null | undefined): m is string =>+ !!m && (m === POOL_WORDS.working || m === POOL_WORDS.gettingReady || m === POOL_WORDS.finishing || /^Working · Step \d+ of \d+$/.test(m));++/** The owner's words for a running job: its stage, and the sampler's step ("Making your clip · step 3 of 6"). */+export function runWords(kind: MadeKind, v: Pick<ProgressView, "stage" | "step">): string {+ if (v.stage === "loading") return POOL_WORDS.gettingReady;+ if (v.stage === "finishing") return `Finishing your ${madeNoun(kind)}`;+ return makingWords(kind, v.step?.value, v.step?.max);+}diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 713e2c44..65d8a7e5 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -27,6 +27,7 @@ import {} from "@/lib/relay";import { reasonText } from "@/lib/comfy-reason";import { cleanNodeTimes } from "@/lib/node-times";+import { trackReport, type LiveProgress } from "@/lib/run-progress";import type { FinishTicket } from "@/lib/finish-ticket";import type { JobTicket } from "@/lib/job-ticket";import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";@@ -62,7 +63,7 @@ export const outputFile = (id: string, n: number) => path.join(taskDir(id), `out/** 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 {+export interface Progress extends LiveProgress {value?: number;max?: number;node?: string;@@ -649,7 +650,7 @@ export function showsPreview(t: Pick<TaskRow, "pools" | "preview" | "finish_json* 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 };+ const p: Omit<Progress, "at"> = {};for (const k of ["value", "max", "nodesDone", "position"] as const) {const v = nonNeg(r[k]);if (v !== undefined) p[k] = Math.min(v, 1e6);@@ -660,7 +661,8 @@ export function noteProgress(id: string, r: Record<string, unknown>, now: numberconst warmed = d.transaction((): boolean => {const cur = d.prepare(`SELECT progress_json, state FROM relay_tasks WHERE id = ? AND ${STILL_HELD}`).get(id, lease) as Pick<TaskRow, "progress_json" | "state"> | undefined;if (!cur) return false;- const next = { ...taskProgress(cur), ...p };+ // Its steps as passes (src/lib/run-progress.ts): a node started since clears the step of the node before.+ const next: Progress = { ...trackReport(taskProgress(cur), p, now), ...(p.position !== undefined && { position: p.position }), at: now };// Its first step reported: its model is loaded (noteCold), so it is no longer getting ready.const wasCold = next.cold === true;if (p.value !== undefined) delete next.cold;@@ -679,8 +681,26 @@ export function noteCold(id: string, now: number): void {rdb().prepare("UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND progress_json IS NULL").run(JSON.stringify({ cold: true, at: now } satisfies Progress), id);}+/**+ * Keep the highest share a task's run showed in this try (src/lib/run-progress.ts), so a later poll never shows less.+ * Only over the try's own progress, and only higher.+ */+export function noteShown(id: string, share: number): void {+ if (!Number.isFinite(share) || share <= 0) return;+ const v = Math.round(share * 10_000) / 10_000;+ rdb()+ .prepare(+ `UPDATE relay_tasks SET progress_json = json_set(progress_json, '$.shown', ?) WHERE id = ? AND state IN ('running','collecting')+ AND progress_json IS NOT NULL AND json_valid(progress_json) AND COALESCE(json_extract(progress_json, '$.shown'), 0) < ?`,+ )+ .run(v, id, v);+}+/** Is a task still getting ready: taken cold (noteCold), with no step reported since? */-export const taskCold = (t: Pick<TaskRow, "progress_json">): boolean => taskProgress(t)?.cold === true;+export const taskCold = (t: Pick<TaskRow, "progress_json">): boolean => {+ const p = taskProgress(t);+ return p?.cold === true && p.value === undefined && !p.passes?.length;+};/** 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 ?`;diff --git a/src/server/generations.ts b/src/server/generations.tsindex 3fa88b4d..109476a4 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -152,6 +152,7 @@ import { accountSend } from "./account-send";import { stamped, stampOf, withoutStamp, withRunStamp, type RunStamp } from "./run-stamp";import { anyHeld, dropGone, dropHold, HELD, NOT_HELD } from "./pool-holds";import { FILE_TROUBLE_WORDS, POOL_WORDS, RELAY_WORDS } from "@/lib/relay";+import { isPoolRunWords } from "@/lib/run-progress";import { heldLine, placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, requestFileKinds, runOnPool, type FileKind } from "./hosted";import { hostedRunsOn } from "./hosted-switch";import { catalogVersion } from "./computer/catalog-version";@@ -227,8 +228,8 @@ export function toGeneration(r: Row): Generation {// sentence when it can't finish: never the technical reason, which the owner reads in the accounts' runs.const pool = stored.place === "pool";const checking = r.stage === "checking";- // Working on the workers with its model still loading (taken by a worker that had another model loaded): "getting- // ready", with no progress yet.+ // Working on the workers with its model still loading (taken by a worker that had another model loaded): "Loading the+ // model", with the small share that grows while it loads.const ready = pool && r.status === "running" && !checking && gettingReady(r.id);const model = getModel(r.model_id);// What it is made at where that differs from what it asked (a 2K run on a model that makes up to 1080P), worked out from@@ -260,7 +261,7 @@ export function toGeneration(r: Row): Generation {kind: r.kind,status: again ? "running" : r.status,// In line on this install's GPUs (again, after an attempt): no progress.- progress: (pool && r.status === "queued") || ready ? null : r.progress,+ progress: pool && r.status === "queued" ? null : r.progress,message: again ?? (pool ? poolMessage(r, ready) : r.message),prompt: r.prompt,request,@@ -370,10 +371,13 @@ export function shownError(id: string, raw: string | null): string | null {return stored.place === "pool" ? poolError(id, raw, !!stored.hold && !!stored.charged) : raw;}-/** A pool row's words while it goes: in line, or working on it (`ready`: still getting ready, its model loading). */+/**+ * A pool row's words while it goes: in line, or working on it (`ready`: still getting ready, its model loading), with+ * its stage and the sampler's step when its poll said them ("Working · Step 3 of 6", "Finishing").+ */function poolMessage(r: Pick<Row, "status" | "message">, ready = false): string | null {if (r.status === "queued") return POOL_WORDS.inLine;- if (r.status === "running") return ready ? POOL_WORDS.gettingReady : POOL_WORDS.working;+ if (r.status === "running") return ready ? POOL_WORDS.gettingReady : isPoolRunWords(r.message) && r.message !== POOL_WORDS.gettingReady ? r.message : POOL_WORDS.working;return null;}@@ -4566,9 +4570,11 @@ async function pollOne(r: Row): Promise<void> {throw pollError;}if (startsNow) db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now(), r.id);- // Back in line (a worker paused, went quiet or gave it back): no progress of the attempt before is kept.+ // Back in line (a worker paused, went quiet or gave it back): no progress of the attempt before is kept. On this+ // install's GPUs each poll of a running try says its share; one that says none (its files still going to the GPU, a+ // new try not started yet) shows none, never the share of the try before.// (An Ideogram 4 run made again after it declined says so while it works.)- updateLive(r.id, { status: res.state, progress: ownClocks && res.state === "queued" ? null : (res.progress ?? r.progress), message: declinedWords(ctx.meta) ?? res.message ?? null });+ updateLive(r.id, { status: res.state, progress: ownClocks ? (res.state === "queued" ? null : (res.progress ?? null)) : (res.progress ?? r.progress), message: declinedWords(ctx.meta) ?? res.message ?? null });return;}if (res.state === "failed") {diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 623832eb..0023ca50 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -57,7 +57,6 @@ import type { FileKey } from "@/lib/gpu/types";import { isEngineWords, plainEngineFailure } from "@/lib/engine-error";import {FILE_TROUBLE_WORDS,- makingWords,META_BATCH_HISTORY,POOL_WORDS,queueWords,@@ -72,6 +71,7 @@ import {type WantedFile,} from "@/lib/relay";import type { GenerationFix } from "@/lib/catalog/types";+import { collectingShare, floored, planOf, poolRunWords, progressPlan, progressView, runWords, trackReport, type LiveProgress, type ProgressPlan, type ProgressView } from "@/lib/run-progress";import {checkClocks,createTask,@@ -88,6 +88,7 @@ import {runnerFacts,stageInput,stagedInput,+ noteShown,taskProgress,type FinishedPlan,type Principal,@@ -590,6 +591,8 @@ interface Progress {max: number;node?: string;nodesDone: number;+ /** The same events as stages and passes (src/lib/run-progress.ts), with the highest share shown. */+ live?: LiveProgress;}type ComfySocket = { url: string; ws: WebSocket; clientId: string; progress: Map<string, Progress> };@@ -647,6 +650,7 @@ function ensureSocket(worker: ComfyWorker = "main"): { clientId: string; progresp.max = 0;}}+ p.live = trackReport(p.live, { ...(p.max > 0 && { value: p.value, max: p.max }), node: p.node, nodesDone: p.nodesDone }, Date.now());progress.set(pid, p);} catch {}};@@ -677,17 +681,33 @@ export function queuePlace(pending: unknown[][], promptId: string): number {return pending.filter((q) => typeof q[0] === "number" && q[0] < n).length;}+/** Graph plans worked out from a task's own graph, for a run whose meta has none (one sent before plans were kept). */+const graphPlans = new Map<string, ProgressPlan | null>();++/** A run's progress plan: its meta's, else its task's graph's (null: neither says). */+function runPlan(meta: Record<string, unknown>, t?: Pick<TaskRow, "id" | "graph_json">): ProgressPlan | null {+ const kept = planOf(meta.plan);+ if (kept || !t?.graph_json) return kept;+ if (!graphPlans.has(t.id)) {+ if (graphPlans.size >= 256) graphPlans.delete(graphPlans.keys().next().value!);+ let plan: ProgressPlan | null = null;+ try {+ plan = progressPlan(JSON.parse(t.graph_json));+ } catch {}+ graphPlans.set(t.id, plan);+ }+ return graphPlans.get(t.id) ?? null;+}+/**- * A running job's progress (0 to 0.99), or undefined when nothing says yet: the share of the graph's nodes run so far- * (`nodesDone` of `total`, the running node counting as part done by its steps), and never less than the running- * node's own steps (`value` of `max`). The sampler takes most of a job's time while it is one node of many, so step 3- * of 8 shows as 3/8, not 3/8 of one node's share.+ * A task's running job, by its stages (src/lib/run-progress.ts): its share, never below the highest it showed in this+ * try. Not kept: the caller notes a higher share (noteShown).*/-export function runProgress(p: { nodesDone?: number; value?: number; max?: number } | undefined, total: number): number | undefined {- const stepFrac = p?.max ? Math.min(1, Math.max(0, (p.value ?? 0) / p.max)) : 0;- const nodeFrac = total > 0 ? (Math.max(1, p?.nodesDone ?? 1) - 1 + stepFrac) / total : 0;- const v = Math.min(0.99, Math.max(stepFrac, nodeFrac));- return v > 0 ? v : undefined;+export function taskView(t: Pick<TaskRow, "id" | "graph_json" | "progress_json" | "started_at" | "claimed_at">, meta: Record<string, unknown>, now = Date.now()): ProgressView {+ const p = taskProgress(t);+ const since = p?.since ?? t.started_at ?? t.claimed_at ?? now;+ const v = progressView({ ...p, since }, runPlan(meta, t), now);+ return { ...v, share: floored(v.share, p?.shown) };}// ---------------------------------------------------------------------------@@ -1875,7 +1895,10 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,const clocks = { ownClocks: true as const, ...(deadline && { deadline }) };// An account's run says only where it is: in line, or working on it (the owner's own runs keep the workers' words).if (!tenantAccount()) return { state: res.state, progress: res.progress, message: res.message, ...clocks };- return t.state === "waiting" ? { state: "queued", message: POOL_WORDS.inLine, ...clocks } : { state: "running", progress: res.progress, message: POOL_WORDS.working, ...clocks };+ if (t.state === "waiting") return { state: "queued", message: POOL_WORDS.inLine, ...clocks };+ // Working: its stage, with the sampler's step ("Working · Step 3 of 6"), as the server reads it.+ const words = res.state !== "running" ? POOL_WORDS.working : t.state === "collecting" ? POOL_WORDS.finishing : t.state === "running" ? poolRunWords(taskView(t, meta)) : POOL_WORDS.working;+ return { state: "running", progress: res.progress, message: words, ...clocks };}/**@@ -1939,12 +1962,18 @@ async function pollTask(principal: Principal, t: TaskRow, meta: Record<string, ucase "queued":return { state: "queued", message: down ?? queueWords(p?.position), ...(sentAt && { sentAt }) };case "running": {- return { state: "running", progress: runProgress(p, Number(meta.nodeCount ?? 0)), message: down ?? makingWords(kind, p?.value, p?.max), ...(sentAt && { sentAt }) };+ // Its stages: getting ready, the sampler's steps, then the nodes after it; never less than this try showed.+ const view = taskView(t, meta);+ noteShown(t.id, view.share);+ return { state: "running", progress: view.share, message: down ?? runWords(kind, view), ...(sentAt && { sentAt }) };}case "collecting": {const got = receivedOf(t);const total = got.reduce((s, r) => s + r.total, 0);- return { state: "running", progress: 0.99, message: down ?? savingWords(total ? got.reduce((s, r) => s + r.bytes, 0) / total : undefined), ...(sentAt && { sentAt }) };+ const received = total ? got.reduce((s, r) => s + r.bytes, 0) / total : undefined;+ const share = floored(collectingShare(received), p?.shown);+ noteShown(t.id, share);+ return { state: "running", progress: share, message: down ?? savingWords(received), ...(sentAt && { sentAt }) };}case "done": {const types = new Map(receivedOf(t).map((r) => [r.n, r.contentType]));@@ -2021,6 +2050,8 @@ export const comfyProvider: ProviderAdapter = {// MiniMax H3's 2K draft that kept its latent says where (the finish loads it only there: generations.ts latentHandOff).const latentAt = manifest.id === H3_LATENT_DRAFT_WORKFLOW ? comfyPlace() : null;if (latentAt) meta.latentAt = latentAt;+ // Its stages for the progress bar: the nodes that sample, and how many come after them (src/lib/run-progress.ts).+ meta.plan = progressPlan(wf);// On someone's computer: the job waits for their Fuobe tab, which sends exactly this graph under the prompt id minted// here. A refusal comes back in its report, and the poll explains it as below.const computer = computerScope();@@ -2222,9 +2253,13 @@ export const comfyProvider: ProviderAdapter = {const busy = queue.queue_running?.[0]?.[1];return { state: "queued", position: pendingIdx, ...(typeof busy === "string" && { busyWith: busy.slice(0, 64) }), message: pendingIdx === 0 ? "Next in ComfyUI's queue" : `In ComfyUI's queue · ${pendingIdx} ahead` };}+ // Its stages (src/lib/run-progress.ts), never less than it showed.+ const view = progressView(p?.live, planOf(meta.plan), Date.now());+ const share = floored(view.share, p?.live?.shown);+ if (p?.live) p.live.shown = share;return {state: "running",- progress: runProgress(p, Number(meta.nodeCount ?? 0)),+ progress: share,message: p?.max ? `Sampling ${p.value}/${p.max}` : worker === "isolated" ? "Running on the isolated ComfyUI worker" : "Running on ComfyUI",};},diff --git a/tests/comfy-provider.test.ts b/tests/comfy-provider.test.tsindex a2aa2ac9..ef109fa3 100644--- a/tests/comfy-provider.test.ts+++ b/tests/comfy-provider.test.ts@@ -11,7 +11,7 @@ process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://comfy.test:8188";const { setSetting } = await import("@/server/settings");-const { comfyProvider, collectOutputs, getWorkflow, loadManifest, mediaInfoFor, prepareWorkflow, runProgress } = await import("@/server/providers/comfyui");+const { comfyProvider, collectOutputs, getWorkflow, loadManifest, mediaInfoFor, prepareWorkflow } = await import("@/server/providers/comfyui");const { MODELS } = await import("@/lib/catalog");const { computeFrames } = await import("@/lib/comfy");@@ -149,27 +149,17 @@ describe("ComfyUI websocket (S15)", () => {});describe("a running job's progress", () => {- it("step 3 of 8 in the sampler shows as 3/8, not 3/8 of one node's share", () => {- expect(runProgress({ nodesDone: 1, value: 3, max: 8 }, 10)).toBeCloseTo(0.375);- // Most nodes run already: the node share wins over the sampler's own steps.- expect(runProgress({ nodesDone: 9, value: 1, max: 8 }, 10)).toBeCloseTo((8 + 1 / 8) / 10);- // Nothing yet says how far it is.- expect(runProgress(undefined, 10)).toBeUndefined();- expect(runProgress({ nodesDone: 0 }, 10)).toBeUndefined();- // With no node count, the steps alone; never past 0.99.- expect(runProgress({ value: 4, max: 8 }, 0)).toBeCloseTo(0.5);- expect(runProgress({ nodesDone: 12, value: 8, max: 8 }, 10)).toBe(0.99);- });-- it("a poll during sampling says step 3 of 8 as 0.375", async () => {+ it("a poll during sampling follows the sampler's steps, not the share of nodes run", async () => {+ const meta = { workflowId: "selftest-image", nodeCount: 10, plan: { nodes: 10, samplers: ["8"], after: 2 } };handler = (url) => (url.includes("/history/") ? json({}) : json({ queue_running: [[0, "p-steps"]], queue_pending: [] }));- await comfyProvider.poll(pollCtx("p-steps", { workflowId: "selftest-image", nodeCount: 10 }));+ await comfyProvider.poll(pollCtx("p-steps", meta));const ws = FakeSocket.all.at(-1)!;- ws.emit({ type: "executing", data: { prompt_id: "p-steps", node: "3" } });- ws.emit({ type: "progress", data: { prompt_id: "p-steps", value: 3, max: 8, node: "3" } });- const running = await comfyProvider.poll(pollCtx("p-steps", { workflowId: "selftest-image", nodeCount: 10 }));+ // Seven nodes (loaders, encoders) ran before the sampler: still only its steps say how far it is.+ for (const node of ["1", "2", "3", "4", "5", "6", "7", "8"]) ws.emit({ type: "executing", data: { prompt_id: "p-steps", node } });+ ws.emit({ type: "progress", data: { prompt_id: "p-steps", value: 3, max: 8, node: "8" } });+ const running = await comfyProvider.poll(pollCtx("p-steps", meta));expect(running.state).toBe("running");- expect((running as { progress?: number }).progress).toBeCloseTo(0.375);+ expect((running as { progress?: number }).progress).toBeCloseTo(0.1 + 0.8 * (3 / 8));});});diff --git a/tests/helpers/run-watch.ts b/tests/helpers/run-watch.tsindex 1c029325..71513469 100644--- a/tests/helpers/run-watch.ts+++ b/tests/helpers/run-watch.ts@@ -7,6 +7,7 @@*/import { isEngineWords } from "@/lib/engine-error";import { POOL_WORDS } from "@/lib/relay";+import { isPoolRunWords } from "@/lib/run-progress";/** A run as the studio answers it (GET /api/generations/<id>, a list item, getGeneration). */export interface RunLike {@@ -94,7 +95,7 @@ export class RunWatch {if (!["queued", "running", "succeeded"].includes(s.status)) out.push(`a state that isn't In line, Working or the result (${at})`);if (s.status === "queued" && s.message !== POOL_WORDS.inLine) out.push(`a waiting run that doesn't say In line (${at})`);if (s.status === "queued" && s.place === null) out.push(`a waiting run with no place in line (${at})`);- if (s.status === "running" && s.message !== POOL_WORDS.working && s.message !== POOL_WORDS.gettingReady) out.push(`a started run that doesn't say Working (${at})`);+ if (s.status === "running" && !isPoolRunWords(s.message)) out.push(`a started run that doesn't say Working (${at})`);if (s.status === "succeeded" && s.outputs < 1) out.push(`a result with nothing in it (${at})`);if (s.error) out.push(`an error (${at})`);for (const w of [s.message, s.error]) if (w && MACHINE_WORDS.test(w)) out.push(`words about the machines (${at})`);diff --git a/tests/hosted-run-tiles.test.ts b/tests/hosted-run-tiles.test.tsindex a8867149..ee7d9098 100644--- a/tests/hosted-run-tiles.test.ts+++ b/tests/hosted-run-tiles.test.ts@@ -62,10 +62,10 @@ describe("a run's tile on this studio's GPUs", () => {const html = render(createElement(PendingTile, { g: gen({ place: "pool", status: "queued", message: POOL_WORDS.inLine, queue: { place: 3, etaSeconds: null, unknown: true } }), ratio: 1 }));expect(html).toContain("Warming up · starts automatically");});- it("working while its model loads: Warming up · starting in a moment, with no %", () => {+ it("working while its model loads: Loading the model, with no % before its try reports one", () => {const html = render(createElement(PendingTile, { g: gen({ place: "pool", status: "running", message: POOL_WORDS.gettingReady, progress: null }), ratio: 1 }));expect(html).toContain('data-run-state="working"');- expect(html).toContain("Warming up · starting in a moment");+ expect(html).toContain("Loading the model");expect(html).not.toContain("%");});it("in line with no place known yet: In line", () => {diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsindex a7639a08..9a11c4f2 100644--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@ -451,7 +451,8 @@ describe("the line", () => {const g = getGeneration(id);return g?.status === "running" && (g.progress ?? 0) > 0 ? g : null;});- expect(working?.message).toBe(POOL_WORDS.working);+ // Working, with the sampler's step.+ expect(working?.message).toBe("Working · Step 3 of 4");// The worker pauses at once (its owner pressed the pause): the run goes back in line.pool.workerBeat(db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as never,diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.tsindex db610252..81f1405b 100644--- a/tests/pool-line-order.test.ts+++ b/tests/pool-line-order.test.ts@@ -603,7 +603,7 @@ describe("the run ceiling", () => {expect(g.progress).toBeNull();});- it("a worker with another model loaded: Warming up · starting in a moment until the first step reports; with its model loaded, Working at once", async () => {+ it("a worker with another model loaded: Loading the model until the first step reports; with its model loaded, Working at once", async () => {const w = standInWorker();const { id, t } = await accountRun("getting ready");const lane = rowOf(t.id).lane!;@@ -615,10 +615,10 @@ describe("the run ceiling", () => {tasks.report(rowOf(t.id), { event: "sent", promptId: first.promptId }, () => ({ error: "unused" }));await tick();expect(getGeneration(id)).toMatchObject({ status: "running", message: POOL_WORDS.gettingReady, progress: null });- // Its first step: the model is loaded.+ // Its first step: the model is loaded, and its words say the step.tasks.report(rowOf(t.id), { event: "running", value: 1, max: 4 }, () => ({ error: "unused" }));await tick();- expect(getGeneration(id)?.message).toBe(POOL_WORDS.working);+ expect(getGeneration(id)?.message).toBe("Working · Step 1 of 4");// Given back, and taken by a worker that has its model loaded: Working, with no getting ready.tasks.report(rowOf(t.id), { event: "give-back", why: "stalled" }, () => ({ error: "unused" }));beatWarm(lane);@@ -628,6 +628,55 @@ describe("the run ceiling", () => {expect(getGeneration(id)).toMatchObject({ status: "running", message: POOL_WORDS.working });});+ it("taken cold, its share follows the stages: loading, the sampler's steps, then the last few percent; never backwards, never 100% before done", async () => {+ const w = standInWorker();+ const { id, t } = await accountRun("its share follows the stages");+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion(), warmLane: "another-lane" }), Date.now());+ const first = claimAs(w)!;+ expect(first.id).toBe(t.id);+ tasks.report(rowOf(t.id), { event: "sent", promptId: first.promptId }, () => ({ error: "unused" }));+ // The run's plan: its graph's sampler, and the nodes after it.+ const meta = JSON.parse((db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").get(id) as { external_meta_json: string }).external_meta_json) as { plan: { nodes: number; samplers: string[]; after: number } };+ expect(meta.plan.samplers.length).toBeGreaterThan(0);+ const sampler = meta.plan.samplers[0];+ const before = meta.plan.nodes - meta.plan.after;+ const shares: number[] = [];+ const look = async (r: Record<string, unknown>) => {+ tasks.report(rowOf(t.id), { event: "running", ...r } as never, () => ({ error: "unused" }));+ await tick();+ const g = getGeneration(id)!;+ expect(g.status).toBe("running");+ shares.push(g.progress ?? 0);+ return g;+ };+ // Its model loads while the nodes before the sampler start: a small share, under its words.+ for (let n = 1; n < before; n++) {+ const g = await look({ nodesDone: n, node: `load-${n}` });+ expect(g.message).toBe(POOL_WORDS.gettingReady);+ expect(g.progress ?? 0).toBeLessThanOrEqual(0.1);+ }+ // The sampler's steps: most of the bar, with the step in its words.+ const at: number[] = [];+ for (let v = 1; v <= 6; v++) {+ const g = await look({ nodesDone: before, node: sampler, value: v, max: 6 });+ expect(g.message).toBe(`Working · Step ${v} of 6`);+ at.push(g.progress!);+ }+ expect(at[2]).toBeGreaterThan(0.45);+ expect(at[2]).toBeLessThan(0.6);+ // A late beat with the step before changes nothing.+ await look({ nodesDone: before, value: 5, max: 6 });+ // After the sampler: the decode and the file, the last few percent.+ for (let k = 1; k <= meta.plan.after; k++) {+ const g = await look({ nodesDone: before + k, node: `after-${k}` });+ expect(g.message).toBe(POOL_WORDS.finishing);+ expect(g.progress!).toBeGreaterThanOrEqual(0.9);+ expect(g.progress!).toBeLessThanOrEqual(0.97);+ }+ for (let i = 1; i < shares.length; i++) expect(shares[i]).toBeGreaterThanOrEqual(shares[i - 1]);+ expect(Math.max(...shares)).toBeLessThan(1);+ });+it("a poll that fails never ends a run in line by the runner's own wait, an account's or the owner's", async () => {standInWorker();const { id } = await accountRun("a poll that fails");diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex 21b8c374..6ef0323b 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -1501,7 +1501,7 @@ describe("the run ceiling per lane", () => {// The worker sent it again: 4 minutes into this attempt (11 since the first began), it is still working.resent = true;await pass(4 * MIN, [d], watch);- expect(getGeneration(id)).toMatchObject({ status: "running", message: POOL_WORDS.working });+ expect(getGeneration(id)).toMatchObject({ status: "running", message: expect.stringMatching(/^Working/) });}});await workAll(d);diff --git a/tests/run-progress.test.ts b/tests/run-progress.test.tsnew file mode 100644index 00000000..1b656729--- /dev/null+++ b/tests/run-progress.test.ts@@ -0,0 +1,210 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import {+ collectingShare,+ floored,+ isPoolRunWords,+ PROGRESS_BANDS,+ poolRunWords,+ progressPlan,+ progressView,+ runWords,+ trackReport,+ type LiveProgress,+ type ProgressPlan,+} from "@/lib/run-progress";+import { POOL_WORDS } from "@/lib/relay";++const graph = (name: string) => JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows", "comfyui", name), "utf8")) as Record<string, unknown>;++const SEC = 1000;++/**+ * A job's reports as a worker sends them, each followed by a poll (as the server reads them): the shares and stages+ * shown, the share floored by the highest shown before (as the server keeps it).+ */+function follow(plan: ProgressPlan | null, reports: { at: number; r: Record<string, unknown> }[], cold = false) {+ let p: LiveProgress | undefined = cold ? { cold: true } : undefined;+ const seen: { at: number; share: number; stage: string; words: string; r: Record<string, unknown> }[] = [];+ for (const { at, r } of reports) {+ p = trackReport(p, r, at);+ if (r.value !== undefined) delete p.cold;+ const v = progressView(p, plan, at);+ const share = floored(v.share, p.shown);+ p.shown = share;+ seen.push({ at, share, stage: v.stage, words: poolRunWords(v), r });+ }+ return seen;+}++/**+ * MiniMax H3 reference to video, taken cold: its loaders and encoders run first (16 nodes, five minutes of model load),+ * then its sampler's six steps (about a minute and a half each), then the decode, the sound and the file.+ */+function coldH3() {+ const out: { at: number; r: Record<string, unknown> }[] = [];+ let t = 0;+ // The model loads: nodes start one by one over five minutes, with a beat every 10 s.+ for (let n = 1; n <= 15; n++) {+ out.push({ at: t, r: { nodesDone: n, node: String(100 + n) } });+ t += 20 * SEC;+ }+ out.push({ at: t, r: { nodesDone: 16, node: "125" } });+ t += 10 * SEC;+ // The sampler's steps, with beats between them.+ for (let v = 0; v <= 6; v++) {+ out.push({ at: t, r: { nodesDone: 16, node: "125", value: v, max: 6 } });+ for (let b = 1; b <= 8; b++) out.push({ at: t + b * 10 * SEC, r: { nodesDone: 16, value: v, max: 6 } });+ t += 90 * SEC;+ }+ // After the sampler: the decode (a minute), the sound, the clip, its file.+ for (const [n, node, ms] of [[17, "122", 60], [18, "121", 10], [19, "130", 10], [20, "174", 10]] as const) {+ out.push({ at: t, r: { nodesDone: n, node } });+ t += ms * SEC;+ }+ return out;+}++describe("a graph's plan", () => {+ it("names the sampler of H3's reference to video and the nodes that read its result", () => {+ const plan = progressPlan(graph("minimax-h3-flex-ref2va.json"));+ expect(plan.samplers).toEqual(["125"]);+ // The video decode, the sound decode, the clip and its file.+ expect(plan.after).toBe(4);+ expect(plan.nodes).toBe(16);+ });++ it("never counts a sampler's settings node (KSamplerSelect, a pack's sampler choice) as a pass", () => {+ const plan = progressPlan(graph("minimax-h3-i2v.json"));+ expect(plan.samplers).toEqual(["125"]);+ });++ it("counts every sampler of a graph with several", () => {+ const plan = progressPlan({+ "1": { class_type: "CheckpointLoaderSimple", inputs: {} },+ "2": { class_type: "KSampler", inputs: { model: ["1", 0] } },+ "3": { class_type: "KSamplerAdvanced", inputs: { model: ["1", 0], latent_image: ["2", 0] } },+ "4": { class_type: "VAEDecode", inputs: { samples: ["3", 0] } },+ "5": { class_type: "SaveImage", inputs: { images: ["4", 0] } },+ });+ expect(plan.samplers).toEqual(["2", "3"]);+ expect(plan.after).toBe(2);+ });+});++describe("a cold H3 run's progress", () => {+ const plan = progressPlan(graph("minimax-h3-flex-ref2va.json"));+ const seen = follow(plan, coldH3(), true);++ it("while the model loads: a small share that grows slowly, with no jump, under its words", () => {+ const loading = seen.filter((s) => s.r.value === undefined && Number(s.r.nodesDone) <= 16);+ expect(loading.length).toBeGreaterThan(10);+ for (const s of loading) {+ expect(s.share).toBeLessThanOrEqual(PROGRESS_BANDS.ready);+ expect(s.stage).toBe("loading");+ expect(s.words).toBe(POOL_WORDS.gettingReady);+ }+ for (let i = 1; i < loading.length; i++) expect(loading[i].share - loading[i - 1].share).toBeLessThan(0.025);+ // 16 of 16 nodes started is not "nearly done".+ expect(loading.at(-1)!.share).toBeLessThan(0.11);+ });++ it("while it samples: the share follows the steps (step 3 of 6 is about half), never stalls high", () => {+ const at = (v: number) => seen.find((s) => s.r.value === v && s.r.node === "125")!;+ expect(at(3).share).toBeGreaterThan(0.45);+ expect(at(3).share).toBeLessThan(0.6);+ expect(at(3).words).toBe("Working · Step 3 of 6");+ for (let v = 1; v <= 6; v++) expect(at(v).share).toBeGreaterThan(at(v - 1).share + 0.1);+ // Between two steps it moves on by the time a step takes, never past the next step's share.+ const between = seen.filter((s) => s.r.value === 2 && s.r.node === undefined);+ for (let i = 1; i < between.length; i++) expect(between[i].share).toBeGreaterThan(between[i - 1].share);+ expect(between.at(-1)!.share).toBeLessThan(at(3).share);+ expect(at(6).share).toBeCloseTo(PROGRESS_BANDS.sampled);+ });++ it("after the sampler: the last few percent, never 100% before it is done", () => {+ const after = seen.filter((s) => Number(s.r.nodesDone) > 16);+ for (const s of after) {+ expect(s.stage).toBe("finishing");+ expect(s.words).toBe(POOL_WORDS.finishing);+ expect(s.share).toBeGreaterThanOrEqual(PROGRESS_BANDS.sampled);+ expect(s.share).toBeLessThanOrEqual(PROGRESS_BANDS.finished);+ }+ expect(collectingShare(0)).toBeGreaterThanOrEqual(after.at(-1)!.share);+ expect(collectingShare(1)).toBe(0.99);+ });++ it("never goes backwards and never reaches 1", () => {+ for (let i = 1; i < seen.length; i++) expect(seen[i].share).toBeGreaterThanOrEqual(seen[i - 1].share);+ for (const s of seen) expect(s.share).toBeLessThan(1);+ });+});++describe("following a job's reports", () => {+ it("clears a finished sampler's last step once the next node starts", () => {+ let p = trackReport(undefined, { nodesDone: 5, node: "9", value: 6, max: 6 }, 0);+ p = trackReport(p, { nodesDone: 6, node: "10" }, 1);+ expect(p.value).toBeUndefined();+ expect(p.max).toBeUndefined();+ expect(p.passes).toHaveLength(1);+ });++ it("a sampler that runs again from its first steps is a new pass", () => {+ let p = trackReport(undefined, { nodesDone: 5, node: "9", value: 6, max: 6 }, 0);+ p = trackReport(p, { nodesDone: 5, node: "9", value: 1, max: 6 }, 1);+ expect(p.passes).toHaveLength(2);+ // A late beat with a step before the last one is not.+ p = trackReport(p, { nodesDone: 5, value: 3, max: 6 }, 2);+ p = trackReport(p, { nodesDone: 5, value: 2, max: 6 }, 3);+ expect(p.passes).toHaveLength(2);+ expect(p.passes!.at(-1)!.value).toBe(3);+ });++ it("a graph with two sampler passes: each takes half of the sampling band, in order", () => {+ const plan: ProgressPlan = { nodes: 8, samplers: ["3", "5"], after: 2 };+ let p = trackReport(undefined, { nodesDone: 3, node: "3", value: 10, max: 10 }, 0);+ const first = progressView(p, plan, 0);+ expect(first.share).toBeCloseTo(PROGRESS_BANDS.ready + (PROGRESS_BANDS.sampled - PROGRESS_BANDS.ready) / 2);+ p = trackReport(p, { nodesDone: 4, node: "4" }, 1);+ expect(progressView(p, plan, 1)).toMatchObject({ stage: "sampling" });+ p = trackReport(p, { nodesDone: 5, node: "5", value: 5, max: 10 }, 2);+ expect(progressView(p, plan, 2).share).toBeCloseTo(PROGRESS_BANDS.ready + (PROGRESS_BANDS.sampled - PROGRESS_BANDS.ready) * 0.75);+ });++ it("a run sent before plans were kept: its steps lead", () => {+ // An older run's kept progress, with no passes: its step now.+ expect(progressView({ nodesDone: 16, node: "125", value: 3, max: 6 }, null, 0).share).toBeCloseTo(0.5);+ // A pass beyond the graph's own never takes the bar backwards or to 100%.+ const plan: ProgressPlan = { nodes: 4, samplers: ["2"], after: 1 };+ let p = trackReport(undefined, { nodesDone: 2, node: "2", value: 6, max: 6 }, 0);+ const one = progressView(p, plan, 0).share;+ p = trackReport(p, { nodesDone: 2, node: "2", value: 1, max: 6 }, 1);+ const two = progressView(p, plan, 1).share;+ expect(two).toBeGreaterThanOrEqual(one);+ expect(two).toBeLessThanOrEqual(PROGRESS_BANDS.extra);+ });++ it("its ComfyUI running the job again from the start starts its passes again", () => {+ let p = trackReport(undefined, { nodesDone: 9, node: "9", value: 4, max: 6 }, 0);+ p = trackReport(p, { nodesDone: 1, node: "1" }, 1);+ expect(p.passes).toBeUndefined();+ });+});++describe("its words", () => {+ it("a person's: the stage, with the step while it samples", () => {+ expect(poolRunWords({ stage: "loading" })).toBe("Loading the model");+ expect(poolRunWords({ stage: "preparing" })).toBe("Working");+ expect(poolRunWords({ stage: "sampling", step: { value: 3, max: 6 } })).toBe("Working · Step 3 of 6");+ expect(poolRunWords({ stage: "finishing" })).toBe("Finishing");+ for (const w of ["Loading the model", "Working", "Working · Step 3 of 6", "Finishing"]) expect(isPoolRunWords(w)).toBe(true);+ expect(isPoolRunWords("Making your clip · step 3 of 6")).toBe(false);+ });++ it("the owner's: the same stages, naming what it makes", () => {+ expect(runWords("video", { stage: "sampling", step: { value: 3, max: 6 } })).toBe("Making your clip · step 3 of 6");+ expect(runWords("video", { stage: "finishing" })).toBe("Finishing your clip");+ expect(runWords("video", { stage: "loading" })).toBe("Loading the model");+ });+});