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.

GPU runs: report job motion and the running node; honest progress on the run card

Adarsh721d9b0c83ad
diff --git a/bin/lib/worker/gpu.mjs b/bin/lib/worker/gpu.mjs
index a7cf5209..94bc804c 100644
--- a/bin/lib/worker/gpu.mjs
+++ b/bin/lib/worker/gpu.mjs
@@ -20,13 +20,17 @@ const num = (s) => {
return Number.isFinite(v) ? v : null;
};
-/** `nvidia-smi --query-gpu=memory.used,temperature.gpu --format=csv,noheader,nounits` → the first GPU. */
+/**
+ * `nvidia-smi --query-gpu=memory.used,temperature.gpu,utilization.gpu --format=csv,noheader,nounits` → the first GPU.
+ * `busyPct`: how busy it is (0-100), null when nvidia-smi said nothing there ([N/A], or an answer without it).
+ */
export function parseGpu(text) {
const line = String(text ?? "").split(/\r?\n/).find((l) => l.trim());
if (!line) return null;
- const [used, temp] = line.split(",");
+ const [used, temp, util] = line.split(",");
const usedMb = num(used);
- return usedMb === null ? null : { usedMb, tempC: num(temp) };
+ const busy = String(util ?? "").trim() ? num(util) : null;
+ return usedMb === null ? null : { usedMb, tempC: num(temp), busyPct: busy === null ? null : Math.max(0, Math.min(100, Math.round(busy))) };
}
/** `--query-compute-apps=pid,process_name,used_memory --format=csv,noheader,nounits`; used_memory is often [N/A] on Windows. */
@@ -55,7 +59,7 @@ const run = (cmd, args) =>
export async function readGpu(cmd = "nvidia-smi") {
const [bin, ...pre] = Array.isArray(cmd) ? cmd : [cmd];
const call = (args) => run(bin, [...pre, ...args]);
- const gpu = await call(["--query-gpu=memory.used,temperature.gpu", "--format=csv,noheader,nounits"]);
+ const gpu = await call(["--query-gpu=memory.used,temperature.gpu,utilization.gpu", "--format=csv,noheader,nounits"]);
if (gpu === null) return null;
const g = parseGpu(gpu);
if (!g) return null;
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 4058f84a..d7fb5615 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -68,6 +68,8 @@ const HOUR = 3_600_000;
export const COUNTERS_REUSE_MS = 90_000;
/** Busy readings in a row (5 s apart) that only the GPU's total decided, before they pause the worker. */
export const TOTAL_BUSY_READINGS = 6;
+/** A GPU reading (every 5 s) says how busy the GPU is for this long; after that, how busy it is is unknown (null). */
+export const GPU_BUSY_FRESH_MS = 30_000;
/** The worker looks at its model folders again this often (a folder that comes back after a restart counts). */
export const RESCAN_MS = 10 * 60_000;
@@ -324,8 +326,10 @@ async function work(saved, deps, owner) {
let inv = { files: [], nodePacks: [], media: ffmpeg ? ["image", "video", "audio"] : ["image"] };
let packs = [];
let invHash = null;
- let gpuInfo = { otherApps: [], tempC: null };
+ let gpuInfo = { otherApps: [], tempC: null, busyPct: null };
let lastGpuAt = 0;
+ // When the GPU was last read: a reading older than GPU_BUSY_FRESH_MS says nothing about how busy it is now.
+ let gpuReadAt = 0;
let pause = { paused: true, why: "here", until: null };
let busyJob = false;
let job = Promise.resolve();
@@ -715,7 +719,7 @@ async function work(saved, deps, owner) {
let lastCpuTask = null;
/** What a slot's runner says it works on, for the beat. */
const runningOf = (r) =>
- r.view.jobs.filter((j) => j.phase !== "done" && j.phase !== "failed").map((j) => ({ task: j.taskId, ...(j.position !== undefined && { position: j.position }), ...(j.phase === "running" && { value: j.value, max: j.max }) }));
+ r.view.jobs.filter((j) => j.phase !== "done" && j.phase !== "failed").map((j) => ({ task: j.taskId, ...(j.position !== undefined && { position: j.position }), ...(j.phase === "running" && { value: j.value, max: j.max, ...r.motion?.(j.taskId) }) }));
const runner = new ComputerRunner(
{
@@ -828,6 +832,8 @@ async function work(saved, deps, owner) {
stallMs: 10 * 60_000,
stallLocalMs: Number(cfg.stallMin) > 0 ? Number(cfg.stallMin) * 60_000 : null,
free: () => comfy.free(),
+ // How busy its GPU is, sent with each running job: its latest reading, or null when there is no fresh one.
+ gpuBusy: () => (now() - gpuReadAt <= GPU_BUSY_FRESH_MS ? (gpuInfo.busyPct ?? null) : null),
// A live preview that isn't a small JPEG is made again by ffmpeg (none without it).
shrinkPreview: deps.shrinkPreview ?? previewShrinker({ ffmpeg: ffmpeg ? ffmpegBin : null, dir: path.join(cfg.workDir, "preview") }),
crashes: (t) => crashes[t.id] ?? 0,
@@ -1067,7 +1073,8 @@ async function work(saved, deps, owner) {
} else verdict = { ...othersOf(reading, own, busyMb), job: own.job };
const was = gpu.paused;
gpu.update(verdict, reading.tempC, t);
- gpuInfo = { otherApps: reading.apps.filter((a) => a.pid !== comfy.pid).map((a) => ({ pid: a.pid, name: a.name, vramBytes: (a.usedMb ?? 0) * 2 ** 20 })), tempC: reading.tempC };
+ gpuInfo = { otherApps: reading.apps.filter((a) => a.pid !== comfy.pid).map((a) => ({ pid: a.pid, name: a.name, vramBytes: (a.usedMb ?? 0) * 2 ** 20 })), tempC: reading.tempC, busyPct: reading.busyPct ?? null };
+ gpuReadAt = t;
if (!was && gpu.paused) log(`Another program is using the GPU (${gpu.who}): pausing (${Math.round(verdict.othersMb ?? 0)} MB not its own${verdict.source ? `, by ${verdict.source}` : ""}).`);
if (was && !gpu.paused) log("The GPU stayed free for the whole cool-down: resuming.");
}
diff --git a/docs/admin-api.md b/docs/admin-api.md
index aaf137e4..a56fb4a0 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -108,7 +108,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `GET /api/admin/accounts/{id}` | | one account with its numbers; 404 `No such account` |
| `PATCH /api/admin/accounts/{id}` | exactly one of `{ disabled: boolean }`, `{ signOut: true }`, `{ password: string }` or `{ email: string }` | the account (no numbers). `password`: a new password of at least 8 characters (400 otherwise), hashed as at sign-up. `email`: a new sign-in email, lower-cased as at sign-up (400 for one that isn't an email address, 409 when another account uses it). Either one ends every sign-in of the account, so it logs in again; its paired ComfyUIs stay paired. The log row names the account only, never the password or the email |
| `DELETE /api/admin/accounts/{id}` | | 204 |
-| `GET /api/admin/generations` | `account` (one account), else `whose` (`people`: accounts' and guests' runs, the default; `ours`: the owner's own; `everyone`); `source` (the owner's runs only: `hands-on`, or `batch` for any automated run: `batch`, `drill`, `example`, `test`, `api`); `where` (`pool`: this install's GPUs, the owner's runs on its ComfyUI too; `provider`: a cloud provider; `own`: an account's own GPU); `status` (`finished` or `done`, `failed`, `canceled`, `waiting`, `started`, and `running` for waiting and started); `kind` (`image`, `video`, `audio`, `model3d`, `text`); `model` (letters of the model id); `from` and `to` (`yyyy-mm-dd` in UTC, both days included); `q` (words of the prompt, or a run id); `ids` (a comma list of up to 100 run ids: those runs, whoever's they are); `before` (the last page's `next`); `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page. Each run has `whose`: `account`, `guest` or `owner`. Each output has a `state`: `shown`, `held` (hidden, or waiting for its check) or `removed` (its file is gone). A failed run on this install's GPUs (and the owner's own failed run) also has `detail`: the technical reason, which the account never sees. `account` is `{ id, email }` (`email` null: a deleted account), `{ id, emailHidden: true }` without `accounts:read`, or `null` for the owner's own run, which has `source` too (`hands-on` from the site; `batch`, `drill`, `example`, `test` as its script said; `api` for a run sent with an API token that said none) and `sourceName` when its script gave one |
+| `GET /api/admin/generations` | `account` (one account), else `whose` (`people`: accounts' and guests' runs, the default; `ours`: the owner's own; `everyone`); `source` (the owner's runs only: `hands-on`, or `batch` for any automated run: `batch`, `drill`, `example`, `test`, `api`); `where` (`pool`: this install's GPUs, the owner's runs on its ComfyUI too; `provider`: a cloud provider; `own`: an account's own GPU); `status` (`finished` or `done`, `failed`, `canceled`, `waiting`, `started`, and `running` for waiting and started); `kind` (`image`, `video`, `audio`, `model3d`, `text`); `model` (letters of the model id); `from` and `to` (`yyyy-mm-dd` in UTC, both days included); `q` (words of the prompt, or a run id); `ids` (a comma list of up to 100 run ids: those runs, whoever's they are); `before` (the last page's `next`); `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page. Each run has `whose`: `account`, `guest` or `owner`. Each output has a `state`: `shown`, `held` (hidden, or waiting for its check) or `removed` (its file is gone). A failed run on this install's GPUs (and the owner's own failed run) also has `detail`: the technical reason, which the account never sees. `account` is `{ id, email }` (`email` null: a deleted account), `{ id, emailHidden: true }` without `accounts:read`, or `null` for the owner's own run, which has `source` too (`hands-on` from the site; `batch`, `drill`, `example`, `test` as its script said; `api` for a run sent with an API token that said none) and `sourceName` when its script gave one. A run that is one step of a longer run (its steps wait for one another) has `step: { n, of }` |
| `GET /api/admin/generations/{id}` | needs `runs:read` and `outputs:view` | One run in full, an account's, a guest's or the owner's own: `{ run, stored, fix, trouble, where, model, preset, studio, prompt, negativePrompt, asked, settings, inputs, batch, near, chain, sent, timing, jobs, workerLog, money, madeBy, surface, providerId, progress, checks }`. `stored.detail` is the technical reason for the owner; `comfyReason`, when there is one, is ComfyUI's own reason in one short line (a node that isn't installed, a model file not in its list, an error in a node), and each of `jobs` has it as `comfyWhy`. A job on one of this site's workers may have `nodes`: its slowest nodes, slowest first, each `{ node, type, ms, beforeStepsMs, steps }` (`beforeStepsMs` and `steps` for a node with steps; [gpu-workers.md](gpu-workers.md)). `inputs` lists each input file by slot, with its `state` (`kept` with its `url`, `removed`, `example`, `inline`, `link`). `chain` is `{ before, after }`: the steps it waits for and the steps that wait for it. `rerunOf` and `rerunAs` (also on each run of the list): the run it is a re-run of, and the run it was re-run as. Keys, tokens and GPU addresses are never part of it. 404 for an unknown run |
| `DELETE /api/admin/generations/{id}` | | 204; 404 for an unknown run or the owner's own |
| `POST /api/admin/generations/{id}/rerun` | `{ reason? }`: a sentence for the admin log (up to 300 characters) | 201 `{ run, account, ids, held? }`: a new run in the same account with the same request (feature, model, words, settings and files), sent through the account's own Run: the same checks, limits and services, queued and priced the same way, on the place the run went before when it can go there. The account sees it as any run of its own. `held`: why it waits to enter the line. 404 for an unknown run, the owner's own or a deleted account; 409 for a run that didn't fail and wasn't cancelled, one in the Trash, a step of a longer run, an account switched off, a run re-run already (with `rerunAs`), or input files that are gone (`code: "input-gone"`); any other refusal (a limit, a service) is the Run's own answer, with its status and `code` |
@@ -117,7 +117,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `POST /api/admin/outputs/remove` | the same, and `evidence?: true` to keep the files in a locked folder | `{ removed }` |
| `GET /api/admin/files/{path}` | `Range` works | the file, an account's or the owner's own (held ones too); 404 for unknown paths |
| `GET /api/admin/reports` | `limit` (1 to 500, default 100) | `{ items }`, newest first |
-| `GET /api/admin/queue` | | `{ held, lanes, running, holding, queued, next, nextTotal, text, controls, now }`. `queued` is in the order the workers serve it, each with `rank` (null while no worker takes it), `why`, `code` (`class`, `next`, `boost`, `held`, `pinned`, `paused`), `override` and `person` (a key, never an account id). A `holding` row for a worker that holds back the line (`task` null) names the job it would take first (`generationId`, `model`, `op`, `principal`). A run of the owner's that the owner made by hand (no `source`) has `handsOn: true` in `queued`, `running` and `holding`: it waits with people's runs, and its `why` says "Your run". `controls`: `{ pools, workers, overrides, ended, modes }` ([gpu-workers.md](gpu-workers.md#the-queue)) |
+| `GET /api/admin/queue` | | `{ held, lanes, running, holding, queued, next, nextTotal, text, controls, now }`. `queued` is in the order the workers serve it, each with `rank` (null while no worker takes it), `why`, `code` (`class`, `next`, `boost`, `held`, `pinned`, `paused`), `override` and `person` (a key, never an account id). A `holding` row for a worker that holds back the line (`task` null) names the job it would take first (`generationId`, `model`, `op`, `principal`). A run of the owner's that the owner made by hand (no `source`) has `handsOn: true` in `queued`, `running` and `holding`: it waits with people's runs, and its `why` says "Your run". `controls`: `{ pools, workers, overrides, ended, modes }` (a run override has `generationId`, the run pressed, and `generations`, every step of that Run it covers) ([gpu-workers.md](gpu-workers.md#the-queue)) |
| `POST /api/admin/queue/mode` | `{ pool?, worker?, mode, forMin? }`: `mode` is `people-first`, `people-only`, `ours-first`, `balanced`, or `null` (back to normal); `forMin` is 1 to 10080, or `null` (until switched back) | `{ mode, before }`; 400 for a value out of bounds, 404 for no such worker |
| `GET /api/admin/queue/overrides` | | `{ live, ended }` (the last 20 that ended) |
| `POST /api/admin/queue/overrides` | `{ kind: "run", generationId, action: "next" | "hold", worker?, forMin? }` or `{ kind: "person", person | account, action: "boost" | "hold", forMin }` (`forMin` is needed for a boost) | 201 `{ override, replaced }`; 404 for no such run, worker or person with a run on the GPUs; 409 for a run that ended |
@@ -129,7 +129,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `PATCH /api/admin/site/uploads` | any of the five, each `true` or `false` | `{ switches }`; 400 with the reason for an unknown switch or a value that isn't a boolean. A switch that is off leaves that kind of file as it is: the tool says why it can't take it, and the server's checks apply. Browsers pick it up when they next load a page |
| `GET /api/admin/site/runs` | | `{ failureDetail }`: what a person reads when a run of theirs on this install's GPUs fails. `full`: the plain sentence and, under it, the cleaned technical reason (ComfyUI's own: no folders, addresses, keys or prompt text); `friendly`: the plain sentence only. Settings → Failed runs is the same choice. A new install starts with `full`; an install that had runs or settings before this choice existed keeps `friendly` |
| `PATCH /api/admin/site/runs` | `{ "failureDetail": "full" \| "friendly" }` | `{ failureDetail }`; 400 for any other body. Runs read it the next time they are shown. A person only ever sees the details of their own runs |
-| `GET /api/admin/workers` | | `{ workers, lanes }`. Each worker adds `asked: { at, words }` or null, `jobs` (each job it holds: `{ taskId, generationId, slot, lane, laneLabel, stage, state, claimedAt, startedAt, progress, progressAt, typicalMs, etaS, owners, feature?, modelName? }`) and `lastEvent: { at, kind, event, words }` or null |
+| `GET /api/admin/workers` | | `{ workers, lanes }`. Each worker adds `asked: { at, words }` or null, `jobs` (each job it holds: `{ taskId, generationId, slot, lane, laneLabel, stage, state, claimedAt, startedAt, progress, progressAt, movedAt, gpuBusy, stallMs, doing, typicalMs, etaS, owners, feature?, modelName?, op?, kind? }`: `doing` is what its ComfyUI runs now (`{ node, nodeClass, nodeTitle, value?, max?, pass? }`, or null), for the owner only; `movedAt` is when the worker last saw the job move, on the site clock, or null from an older worker; `gpuBusy` is its GPU use from 0 to 100, or null; past `stallMs` without a move the worker gives the job back; `etaS` is more than 0 or null, never 0 for a running job) and `lastEvent: { at, kind, event, words }` or null |
| `POST /api/admin/workers` | `{ name, pool? }` | 201 `{ id, token }`: the worker's token, once |
| `POST /api/admin/workers/{id}/update` | none | `{ worker }`: its next beat answer asks it to update now. It looks for new code at once and restarts on it after the job in hand (a person's job is never cut off). Each worker in `GET /api/admin/workers` has `update`: `state` (`current`, `updating` while behind the site's version for under 3 minutes, `behind` after), `since`, `behindMs`, `site`, `worker`, `commit` (first 12 hex), `peopleHeld`, `peopleWaiting`, `askedAt`, `words` and `needsOwner` |
| `PATCH /api/admin/workers/{id}` | any of `paused`, `pauseNow`, `drain`, `autoResume`, `hours`, `allow`, `claimAfterMs`, `switchAfterMs`, `rotate` (needs `workers:tokens`), `revoke` | `{ worker, token? }`: a new worker token after `rotate`, once |
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 75c82d36..aed0cec2 100644
--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@ -43,7 +43,11 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {
case "running": {
// A worker's live preview: kept only as a JPEG of at most 64 KB (a larger one is dropped, the report kept).
const preview = previewOf(b.preview);
- return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }), ...(preview && { preview }) };
+ // A worker's watchdog facts (JobMotion), when it sends them: noteProgress checks and keeps them.
+ const motion = { ...(num(b.movedAgoMs) !== undefined && { movedAgoMs: num(b.movedAgoMs) }), ...((b.gpuBusy === null || num(b.gpuBusy) !== undefined) && { gpuBusy: num(b.gpuBusy) ?? null }) };
+ // What its ComfyUI runs now, for the owner (noteProgress cleans it again).
+ const facts = { ...(typeof b.nodeClass === "string" && { nodeClass: b.nodeClass }), ...(typeof b.nodeTitle === "string" && { nodeTitle: b.nodeTitle }), ...(!!b.pass && typeof b.pass === "object" ? { pass: b.pass as never } : {}) };
+ return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }), ...(preview && { preview }), ...motion, ...facts };
}
case "finished": {
// A worker's slowest nodes, as its ComfyUI's socket timed them (cleaned: ids, classes, times and step counts only).
diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.ts
index 6d62f150..66e006e0 100644
--- a/src/lib/computer-runner.ts
+++ b/src/lib/computer-runner.ts
@@ -26,7 +26,11 @@ import {
type ComputerFacts,
type GiveBackWhy,
type HistoryEntryLike,
+ type JobMotion,
+ type NodeFacts,
type RelayState,
+ cleanNodeClass,
+ cleanNodeTitle,
type ReportEvent,
type TabFailure,
type TaskInput,
@@ -207,6 +211,8 @@ export interface WorkerHooks {
* JPEG (at most 512 pixels on its long side), or null when it can't. Without it, only a small JPEG is sent.
*/
shrinkPreview?(preview: Blob): Promise<Blob | null>;
+ /** How busy its GPU is now (0-100, its latest reading), or null when it can't say. Sent with each running job (JobMotion). */
+ gpuBusy?(): number | null;
}
/** ComfyUI's words for running out of memory (lib/gpu/fix-codes.ts says the same). */
@@ -347,6 +353,21 @@ export function batchPlan(graph: unknown): { node: string; perPass: number; load
* in the shape of a sampler's steps, so the run's card reads "Step 3 of 21" and fills by pass. Without the frame count
* yet (its loader hasn't reported), only the node: the run shows it is working.
*/
+/**
+ * The running node's facts from the job's graph (ComfyUI's API format), for the owner's view: its class, and its title
+ * when it has its own. A node inside a subgraph ("672:642") is the inner node, when the graph has it by its own id.
+ */
+export function nodeFactsOf(graph: unknown, node: string | undefined): NodeFacts {
+ if (!node || !graph || typeof graph !== "object") return {};
+ const g = graph as Record<string, { class_type?: unknown; _meta?: { title?: unknown } } | undefined>;
+ const parts = node.split(":");
+ const n = g[node] ?? g[parts.at(-1)!] ?? g[parts[0]!];
+ if (!n || typeof n !== "object") return {};
+ const nodeClass = cleanNodeClass(n.class_type);
+ const title = cleanNodeTitle(n._meta?.title);
+ return { ...(nodeClass && { nodeClass }), ...(title && title !== nodeClass && { nodeTitle: title }) };
+}
+
export function passProgress(plan: { node: string; perPass: number }, frames: number | undefined, done: number): { value?: number; max?: number; node: string; nodesDone: number } {
// One node "done" for every report: the passes are one stage of the run, never a node after another.
if (!frames || !Number.isFinite(frames) || frames <= 0) return { node: plan.node, nodesDone: 1 };
@@ -354,6 +375,9 @@ export function passProgress(plan: { node: string; perPass: number }, frames: nu
return { value: Math.max(0, Math.min(done, max)), max, node: plan.node, nodesDone: 1 };
}
+/** A meta-batch job's pass now (1-based) of all its passes, from its passProgress; nothing without the count yet. */
+export const passOf = (p: { value?: number; max?: number }): Pick<NodeFacts, "pass"> => (p.max ? { pass: { n: Math.min((p.value ?? 0) + 1, p.max), of: p.max } } : {});
+
/** Every string inside a value with its absolute paths as base names (engine-error.ts). */
function pathsOut<T>(v: T, depth = 0): T {
if (typeof v === "string") return withoutLocalPaths(v) as T;
@@ -386,6 +410,8 @@ 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; maxes?: Record<string, number> }>();
+ /** When each followed job last moved, by task (its watchdog's movedAt, this runner's clock): its reports and beats say how long ago. */
+ private movedOf = new Map<string, number>();
/** A meta-batch job's progress as passes (passProgress), by task: what its reports and beats send instead of a pass's own steps. */
private batchShown = new Map<string, ReturnType<typeof passProgress>>();
/** Each prompt's node times from the socket (a worker sends them with its "finished" report); the latest few. */
@@ -646,6 +672,17 @@ export class ComputerRunner {
else if (e.event === "give-back") this.whyOf.set(t.id, `given back to the line: ${e.why}`);
}
+ /**
+ * A followed job's motion (JobMotion): how long ago its watchdog last saw it move, and, on a worker that reads its GPU,
+ * how busy the GPU is. Empty for a job it doesn't follow (a browser tab sends no GPU reading either).
+ */
+ motion(taskId: string): JobMotion {
+ const at = this.movedOf.get(taskId);
+ if (at === undefined) return {};
+ const busy = this.deps.worker?.gpuBusy ? this.deps.worker.gpuBusy() : undefined;
+ return { movedAgoMs: Math.max(0, Math.round(this.now() - at)), ...(busy !== undefined && { gpuBusy: busy }) };
+ }
+
/** One beat: say this computer is here, keep its jobs alive, and stop what the server says to stop. */
async beat(takeover = false): Promise<BeatAnswer | null> {
if (!this.alive) return null;
@@ -667,7 +704,7 @@ export class ComputerRunner {
.map((j) => {
// A meta-batch job: its passes (passProgress), never its first pass's own steps.
const ev = this.batchShown.get(j.taskId) ?? this.events.get(this.promptOf.get(j.taskId) ?? "");
- return { task: j.taskId, ...(j.position !== undefined && { position: j.position }), ...(j.phase === "running" && ev && { value: ev.value, max: ev.max, nodesDone: ev.nodesDone }) };
+ return { task: j.taskId, ...(j.position !== undefined && { position: j.position }), ...(j.phase === "running" && ev && { value: ev.value, max: ev.max, nodesDone: ev.nodesDone }), ...(j.phase === "running" && this.motion(j.taskId)) };
});
const stopped = [...this.stoppedDone];
return this.beatWith(
@@ -804,6 +841,7 @@ export class ComputerRunner {
this.madeOf.delete(t.id);
this.finishMade.delete(t.id);
this.batchShown.delete(t.id);
+ this.movedOf.delete(t.id);
const why = this.whyOf.get(t.id);
this.whyOf.delete(t.id);
const phase = this.view.jobs.find((j) => j.taskId === t.id)?.phase;
@@ -1282,10 +1320,12 @@ export class ComputerRunner {
// A worker's watchdog: when the job last moved (a step, a node, its place, a pass).
let movedAt = this.now();
let moveKey = "";
+ this.movedOf.set(t.id, movedAt);
const moved = (key: string) => {
if (key !== moveKey) {
moveKey = key;
movedAt = this.now();
+ this.movedOf.set(t.id, movedAt);
}
};
// The run limit counts from when its ComfyUI first runs the job (its wait in ComfyUI's own queue doesn't count). A
@@ -1341,7 +1381,7 @@ export class ComputerRunner {
// which any studio takes); without one, only that a pass still runs.
const a = await this.report(
t,
- shown ? { event: "running", ...shown } : { event: "passes", running, entries: running ? [] : passes.map(slim), ...(!running && exec(execOf(passes))), ...(passWhy && { why: passWhy }) },
+ shown ? { event: "running", ...shown, ...this.motion(t.id), ...nodeFactsOf(t.graph, ev?.node ?? shown.node), ...passOf(shown) } : { event: "passes", running, entries: running ? [] : passes.map(slim), ...(!running && exec(execOf(passes))), ...(passWhy && { why: passWhy }) },
);
if (a.stop) throw new Stopped();
if (!running) return { entries: passes, answer: a };
@@ -1384,8 +1424,13 @@ export class ComputerRunner {
moved(JSON.stringify([w.s, w.s === "pending" ? w.ahead : null, ev?.value, ev?.max, ev?.node, ev?.nodesDone]));
// A meta-batch job's first pass: no pass has ended yet (its own steps would read as most of the run).
const first = batch && w.s === "running" ? batchNow(0) : null;
+ // The node it runs now, by its class and title, for the owner's view (a meta-batch job: its first pass).
const report: ReportEvent =
- w.s === "pending" ? { event: "queued", position: w.ahead } : first ? { event: "running", ...first } : { event: "running", value: ev?.value, max: ev?.max, node: ev?.node, nodesDone: ev?.nodesDone };
+ w.s === "pending"
+ ? { event: "queued", position: w.ahead }
+ : first
+ ? { event: "running", ...first, ...nodeFactsOf(t.graph, ev?.node ?? first.node), ...passOf(first) }
+ : { event: "running", value: ev?.value, max: ev?.max, node: ev?.node, nodesDone: ev?.nodesDone, ...nodeFactsOf(t.graph, ev?.node) };
const key = JSON.stringify(report);
// A worker sends its ComfyUI's latest preview with its progress, when the claim asks for one: a small JPEG, at most
// one every 2 s.
@@ -1395,7 +1440,9 @@ export class ComputerRunner {
const preview = due ? await previewForReport(shown, lastPreviewAt, this.now(), worker?.shrinkPreview?.bind(worker)) : undefined;
if (due) lastPreview = shown;
if ((key !== lastKey || preview) && this.now() - lastSent >= PROGRESS_EVERY_MS) {
- const a = await this.report(t, preview && report.event === "running" ? { ...report, preview } : report);
+ // Its motion goes with it (never part of the key: a report goes when the job moved, not when time passed).
+ const sent: ReportEvent = report.event === "running" ? { ...report, ...this.motion(t.id), ...(preview && { preview }) } : report;
+ const a = await this.report(t, sent);
if (a.stop) throw new Stopped();
lastKey = key;
lastSent = this.now();
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 857b7a09..4817d780 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -48,6 +48,41 @@ export type TabFailure = (typeof TAB_FAILURES)[number];
export const GIVE_BACK = ["stalled", "run-limit", "media", "update-worker", "outside-ceiling", "self-check"] as const;
export type GiveBackWhy = (typeof GIVE_BACK)[number];
+/**
+ * Is a running job really moving? What a worker adds to its "running" reports and to each running job in its beats.
+ * Both are optional: an older worker sends neither, and an older studio ignores them.
+ */
+export interface JobMotion {
+ /**
+ * How long ago (ms) its watchdog last saw the job move (a step, a node, its place, a pass). A length, never a clock
+ * time: the studio takes it from its own clock, so the PC's clock can't skew it.
+ */
+ movedAgoMs?: number;
+ /** How busy its GPU is now (nvidia-smi's utilization, 0-100), or null when it can't say. */
+ gpuBusy?: number | null;
+}
+
+/**
+ * What its ComfyUI runs now, for the owner's view (a "running" report): the running node's class and title from the
+ * job's graph (short and cleaned: never a file path or prompt text, NodeFacts), and a meta-batch job's pass.
+ */
+export interface NodeFacts {
+ nodeClass?: string;
+ nodeTitle?: string;
+ /** A meta-batch job: the pass it runs now, of all its passes. */
+ pass?: { n: number; of: number };
+}
+
+/** A node class as it may be shown: letters, digits and a few marks, at most 64 characters (else none). */
+export const cleanNodeClass = (v: unknown): string | undefined => (typeof v === "string" && /^[\w .+:|()-]{1,64}$/.test(v.trim()) ? v.trim() : undefined);
+
+/** A node's title as it may be shown: one short line with no path, at most 48 characters (else none). */
+export const cleanNodeTitle = (v: unknown): string | undefined => {
+ if (typeof v !== "string") return undefined;
+ const t = v.replace(/\s+/g, " ").trim();
+ return t && t.length <= 48 && !/[\\/<>{}"`]|https?:|\.(safetensors|ckpt|pt|pth|gguf|bin|png|jpe?g|webp|mp4|wav)\b/i.test(t) ? t : undefined;
+};
+
/** What the tab reports about one task. */
export type ReportEvent =
/**
@@ -65,8 +100,9 @@ export type ReportEvent =
/**
* Running: the sampler's steps, and the node. A worker may add its ComfyUI's latest preview (`preview`: a JPEG as
* base64, at most PREVIEW_LIMITS.maxBytes, at most one every PREVIEW_LIMITS.everyMs). A larger one is dropped.
+ * A worker adds its watchdog's facts (JobMotion).
*/
- | { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number; preview?: string }
+ | ({ event: "running"; value?: number; max?: number; node?: string; nodesDone?: number; preview?: string } & JobMotion & NodeFacts)
/**
* 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 the
@@ -276,11 +312,12 @@ export interface WorkerBeat {
* ("waiting-for-yield", "waiting-for-yield:no-answer").
*/
local: { paused: boolean; why: string | null; until: number | null };
- gpu: { otherApps: { pid: number; name: string; vramBytes: number }[]; tempC: number | null };
+ /** `busyPct`: how busy its GPU is (nvidia-smi utilization, 0-100); null or absent when unknown (an older worker). */
+ gpu: { otherApps: { pid: number; name: string; vramBytes: number }[]; tempC: number | null; busyPct?: number | null };
facts?: ComputerFacts;
inventoryHash: string | null;
warmLane: string | null;
- running: { task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number }[];
+ running: ({ task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number } & JobMotion)[];
stopped: string[];
/** The tasks whose finished results the worker keeps on its disk (a stop-now leaves them its own, to send them up). */
held?: string[];
@@ -299,7 +336,7 @@ export interface WorkerBeat {
*/
cpuSlot?: CpuSlot | null;
/** The tasks its CPU slot works on, with where each is (as `running` for its GPU's). */
- cpuRunning?: { task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number }[];
+ cpuRunning?: ({ task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number } & JobMotion)[];
/**
* Why it doesn't start the line's work now although it may work, when it says (absent: it holds nothing back, or it
* is an older worker program): one of HOLDING_WHY's keys, since when, and the task it took, if it holds one.
diff --git a/src/lib/run-progress.ts b/src/lib/run-progress.ts
index 579ca19b..94ff2f91 100644
--- a/src/lib/run-progress.ts
+++ b/src/lib/run-progress.ts
@@ -236,6 +236,46 @@ export const collectingShare = (received: number | undefined) => PROGRESS_BANDS.
/** 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));
+/** A bar by time never shows more than this while the job runs (the time is a lane's typical one, not this job's). */
+export const TIME_SHARE_MOST = 0.95;
+/** "About N min left" only while at least this much of the typical time is left (never "about 0 min left"). */
+const LEFT_MIN_MS = 60_000;
+
+/** What a person's card shows for a job on the workers: a share, or none, and about how many minutes are left. */
+export interface CardProgress {
+ /** 0 to 0.99, or null: no honest share to show. */
+ share: number | null;
+ /** About how many minutes are left (whole, at least 1), only from the lane's typical run time. */
+ leftMin?: number;
+}
+
+/**
+ * A running job's progress as a person's card shows it (a job on this install's GPUs), honest about what is known:
+ *
+ * - a step bar only while its sampler reports its steps (`view.step`);
+ * - otherwise a bar by time from the lane's typical run (`typicalMs`, against `runMs`, how long it has run), never above
+ * TIME_SHARE_MOST, and "about N min left" only from that typical time, while a minute or more of it is left;
+ * - otherwise no share at all (a count of nodes says little about the time a job takes).
+ *
+ * A share is never below the highest one shown in this try (`shown`), so the bar never moves back.
+ */
+export function cardProgress(view: Pick<ProgressView, "stage" | "share" | "step">, o: { runMs: number; typicalMs: number | null; shown?: number }): CardProgress {
+ if (view.stage === "sampling" && view.step) return { share: floored(view.share, o.shown) };
+ if (!o.typicalMs || o.typicalMs <= 0) return { share: null };
+ const ran = Math.max(0, o.runMs);
+ const left = o.typicalMs - ran;
+ return { share: floored(Math.min(TIME_SHARE_MOST, ran / o.typicalMs), o.shown), ...(left >= LEFT_MIN_MS && { leftMin: Math.max(1, Math.round(left / 60_000)) }) };
+}
+
+/** "about 4 min left" (null: nothing to say). */
+export const leftWords = (leftMin: number | undefined): string | null => (leftMin && leftMin >= 1 ? `about ${Math.round(leftMin)} min left` : null);
+
+/** Words with "about N min left" after them, when there is a time to say. */
+export const withLeft = (words: string, leftMin: number | undefined): string => {
+ const left = leftWords(leftMin);
+ return left ? `${words} · ${left}` : words;
+};
+
/** "Step 3 of 6". */
export const stepWords = (step: { value: number; max: number }) => `Step ${Math.min(step.value, step.max)} of ${step.max}`;
@@ -247,8 +287,12 @@ export function poolRunWords(v: Pick<ProgressView, "stage" | "step">): string {
}
/** 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));
+export const isPoolRunWords = (m: string | null | undefined): m is string => {
+ if (!m) return false;
+ // Each may say about how long is left (withLeft).
+ const words = m.replace(/ · about \d+ min left$/, "");
+ return words === POOL_WORDS.working || words === POOL_WORDS.gettingReady || words === POOL_WORDS.finishing || /^Working · Step \d+ of \d+$/.test(words);
+};
/** 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 {
diff --git a/src/server/account-admin.ts b/src/server/account-admin.ts
index e8a6c18d..64d7b4fe 100644
--- a/src/server/account-admin.ts
+++ b/src/server/account-admin.ts
@@ -6,6 +6,7 @@ import { listAccounts, type AccountInfo } from "./auth";
import { db } from "./db";
import { declinedCardsIn, getGeneration, listGenerations, type ListOptions } from "./generations";
import { cursorFrom, HELPER_SQL, KINDS } from "./library";
+import { SAME_PRESS } from "./computer/queue-controls";
/**
* Settings → Accounts (the owner only): what accounts make. Their numbers (runs, space) and their runs, newest first,
@@ -183,7 +184,62 @@ export type RunWhose = "account" | "guest" | "owner";
* A run in the owner's admin list: an account's or a guest's (as AccountRun), or the owner's own (`account` null, `whose`
* "owner", and `source`: what made it, "hands-on" when its runner said nothing).
*/
-export type AdminRun = Omit<AccountRun, "account"> & { account: AccountOfRun | null; source?: RunSource; sourceName?: string };
+export type AdminRun = Omit<AccountRun, "account"> & { account: AccountOfRun | null; source?: RunSource; sourceName?: string; step?: RunStep };
+
+/** Which step of its Run a run is: the n-th of `of` steps that wait for one another (one press of Run made them all). */
+export interface RunStep {
+ n: number;
+ of: number;
+}
+
+/** A run's own ids it waits for (depends_on: one id, or a JSON list). */
+function waitsFor(dependsOn: string | null): string[] {
+ if (!dependsOn) return [];
+ if (!dependsOn.startsWith("[")) return [dependsOn];
+ try {
+ const v = JSON.parse(dependsOn) as unknown;
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * The steps of the Run that made a run (its press: the same hold, else the same batch), each by its place in the chain:
+ * a step that waits for none is step 1, one that waits for step k is step k + 1. Null: the press made no steps that
+ * wait for one another (a run on its own, or a batch of runs side by side). `cache`: by press, for one page of runs.
+ */
+export function runStepOf(g: Pick<Generation, "id" | "batchId" | "request">, cache = new Map<string, Map<string, RunStep> | null>()): RunStep | null {
+ const hold = typeof g.request.hold === "string" && g.request.hold ? g.request.hold : null;
+ const batch = g.batchId ?? null;
+ if (!hold && !batch) return null;
+ const key = hold ? `h:${hold}` : `b:${batch}`;
+ if (!cache.has(key)) {
+ const rows = db()
+ .prepare(`SELECT g.id, g.depends_on FROM generations g WHERE ${SAME_PRESS} ORDER BY g.created_at, g.id LIMIT 64`)
+ .all({ hold, batch }) as { id: string; depends_on: string | null }[];
+ const ids = new Set(rows.map((r) => r.id));
+ const deps = new Map(rows.map((r) => [r.id, waitsFor(r.depends_on).filter((d) => ids.has(d))]));
+ const inChain = new Set<string>();
+ for (const [id, ds] of deps) if (ds.length) [id, ...ds].forEach((x) => inChain.add(x));
+ let steps: Map<string, RunStep> | null = null;
+ if (inChain.size) {
+ const depth = new Map<string, number>();
+ const depthOf = (id: string, seen: Set<string>): number => {
+ if (depth.has(id)) return depth.get(id)!;
+ if (seen.has(id)) return 0;
+ seen.add(id);
+ const d = Math.max(0, ...(deps.get(id) ?? []).map((x) => depthOf(x, seen) + 1));
+ depth.set(id, d);
+ return d;
+ };
+ const of = Math.max(...[...inChain].map((id) => depthOf(id, new Set()))) + 1;
+ steps = new Map([...inChain].map((id) => [id, { n: depthOf(id, new Set()) + 1, of }]));
+ }
+ cache.set(key, steps);
+ }
+ return cache.get(key)?.get(g.id) ?? null;
+}
/** Whose a run is: its email (null: the account was deleted), or no email and `emailHidden` for a reader that may not see emails. */
export type AccountOfRun = { id: string; email?: string | null; emailHidden?: true };
@@ -206,7 +262,7 @@ function withStates(outputs: OutputFile[]): (OutputFile & { state: OutputState }
*/
export type AccountRunFacts = Pick<
AdminRun,
- "id" | "batchId" | "feature" | "presetId" | "presetName" | "modelId" | "modelName" | "engine" | "provider" | "op" | "kind" | "status" | "progress" | "costUsd" | "createdAt" | "updatedAt" | "completedAt" | "place" | "account" | "whose" | "source" | "sourceName"
+ "id" | "batchId" | "feature" | "presetId" | "presetName" | "modelId" | "modelName" | "engine" | "provider" | "op" | "kind" | "status" | "progress" | "costUsd" | "createdAt" | "updatedAt" | "completedAt" | "place" | "account" | "whose" | "source" | "sourceName" | "step"
> & { outputs: { kind: OutputFile["kind"]; state: OutputState }[] };
function factsOnly(r: AdminRun): AccountRunFacts {
@@ -233,6 +289,7 @@ function factsOnly(r: AdminRun): AccountRunFacts {
whose: r.whose,
...(r.source && { source: r.source }),
...(r.sourceName && { sourceName: r.sourceName }),
+ ...(r.step && { step: r.step }),
outputs: r.outputs.map((x) => ({ kind: x.kind, state: x.state })),
};
}
@@ -270,9 +327,12 @@ export function listAdminRuns(o: ListOptions & { whose?: RunsWhose }, show: { co
const emails = new Map(listAccounts().map((a) => [a.id, a.email]));
const found = listGenerations(opts).filter((g) => (whose === "people" ? !!g.request.account : whose === "ours" ? !g.request.account : true));
const last = found.at(-1);
+ // Each run's step of its Run, when its press made steps that wait for one another ("step 1 of 2").
+ const presses = new Map<string, Map<string, RunStep> | null>();
return {
items: found.map((g) => {
- const run = asAdminRun(g, emails, show.emails);
+ const step = runStepOf(g, presses);
+ const run: AdminRun = { ...asAdminRun(g, emails, show.emails), ...(step && { step }) };
return show.content ? run : factsOnly(run);
}),
next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null,
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 65bbe6de..0ce90340 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -14,7 +14,7 @@ import { indexKey, loadIndex } from "../gpu/index-file";
import { hostedRunsOn } from "../hosted-switch";
import { heldView } from "../pool-holds";
import { catalogVersion } from "./catalog-version";
-import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteCold, noteProgress, noteStage, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, stageOf, takeTask, taskById, taskCold, taskProgress, type TaskRow } from "./tasks";
+import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteCold, noteProgress, noteStage, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, stageOf, takeTask, taskById, taskCold, taskProgress, jobNowOf, type JobNow, type TaskRow } from "./tasks";
import { queueSettings, runCeilingMs } from "../queue-settings";
import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
import { modelLabel } from "./queue-live";
@@ -287,6 +287,8 @@ export function cleanBeat(b: unknown): WorkerBeat {
gpu: {
otherApps: apps.map((a) => ({ pid: num((a as Record<string, unknown>)?.pid) ?? 0, name: text((a as Record<string, unknown>)?.name, 64) ?? "?", vramBytes: num((a as Record<string, unknown>)?.vramBytes) ?? 0 })),
tempC: num(gpu.tempC),
+ // How busy its GPU is (0-100); absent from an older worker, null when it can't say.
+ ...((gpu.busyPct === null || num(gpu.busyPct) !== null) && { busyPct: num(gpu.busyPct) === null ? null : Math.round(Math.max(0, Math.min(100, num(gpu.busyPct)!))) }),
},
...(o.facts !== undefined && { facts: cleanFacts(o.facts) }),
...(typeof o.catalogVersion === "string" && /^[0-9a-f]{64}$/.test(o.catalogVersion) && { catalogVersion: o.catalogVersion }),
@@ -1198,6 +1200,29 @@ export function typicalPoolMs(lane: string | null): number | null {
return (lane ? of(q("AND lane = ?", lane)) : null) ?? of(q(""));
}
+/** Each lane's typical run as cardTypicalMs read it last, and when (read again after LANE_TIME_MS). */
+const laneTimes = new Map<string, { at: number; ms: number | null }>();
+const LANE_TIME_MS = 60_000;
+
+/**
+ * How long a task's run usually takes, for a person's card (src/lib/run-progress.ts cardProgress): its worker's bench
+ * for its lane, else its lane's typical run (the middle of its last 20 finished runs). Null when neither says: then
+ * the card shows no time-based share. Never another lane's times.
+ */
+export function cardTypicalMs(t: Pick<TaskRow, "lane" | "worker_id">, now = Date.now()): number | null {
+ if (!t.lane) return null;
+ const w = t.worker_id ? (db().prepare("SELECT bench_json FROM relay_workers WHERE id = ?").get(t.worker_id) as Pick<WorkerRow, "bench_json"> | undefined) : undefined;
+ const bench = w ? benchOf(w as WorkerRow)[t.lane]?.medianMs : undefined;
+ if (bench && bench > 0) return bench;
+ const kept = laneTimes.get(t.lane);
+ if (kept && now - kept.at < LANE_TIME_MS) return kept.ms;
+ const rows = db().prepare("SELECT exec_ms AS ms FROM worker_jobs WHERE event = 'finished' AND exec_ms > 0 AND lane = ? ORDER BY id DESC LIMIT 20").all(t.lane) as { ms: number }[];
+ const ms = rows.length ? rows.map((r) => r.ms).sort((a, b) => a - b)[Math.floor(rows.length / 2)] : null;
+ if (laneTimes.size >= 256) laneTimes.delete(laneTimes.keys().next().value!);
+ laneTimes.set(t.lane, { at: now, ms });
+ return ms;
+}
+
/** How long a task should take: its lane's bench on the quickest of these workers, its own estimate, or the lane's typical run. */
function estFor(t: Pick<TaskRow, "lane" | "est_ms">, workers: WorkerRow[], typical: (lane: string | null) => number | null): number {
const bench = workers.map((w) => (t.lane && benchOf(w)[t.lane]?.medianMs) || 0).filter((ms) => ms > 0);
@@ -1794,13 +1819,37 @@ export interface ActiveJob {
startedAt: number | null;
progress: { value?: number; max?: number; node?: string; nodesDone?: number; position?: number; cold?: boolean } | null;
progressAt: number | null;
+ /**
+ * When the worker's watchdog last saw it move (a step, a node, its place, a pass), on this server's clock; null: the
+ * worker doesn't say (an older one). Past `stallMs` without a move, the worker gives the job back to the line.
+ */
+ movedAt: number | null;
+ /** How busy the worker's GPU was at its last word (0-100); null: unknown. */
+ gpuBusy: number | null;
+ /** What its ComfyUI runs now (its node's class and title, its step or pass); null: nothing said yet. */
+ doing: JobNow | null;
+ /** How long the job may go without moving before the worker gives it back (its lane's stall limit). */
+ stallMs: number;
/** How long a job like it takes on this worker (its lane's bench, the task's estimate, or the lane's typical run). */
typicalMs: number | null;
- /** About how long until it is done, from typicalMs and its start (null: unknown). */
+ /**
+ * About how long until it is done, from typicalMs and its start: more than 0, or null (unknown, or it already ran
+ * longer than typicalMs: never "0 s left" for a job still running).
+ */
etaS: number | null;
owners: "owner" | "account";
feature?: string;
modelName?: string;
+ /** Its run's operation and kind of result (t2i, i2v…; image, video…): what kind of task it is. */
+ op?: string;
+ kind?: string;
+}
+
+/** Seconds left from a typical run time and a start: at least 1, or null when there is no typical time or it has passed. */
+export function etaOf(typicalMs: number | null, since: number, now: number): number | null {
+ if (!typicalMs) return null;
+ const s = Math.round((since + typicalMs - now) / 1000);
+ return s >= 1 ? s : null;
}
/** A lane's label from the catalog's lanes (worked out once per index). */
@@ -1817,11 +1866,11 @@ setEventNames({
type ActiveRow = Pick<TaskRow, "id" | "generation_id" | "lane" | "state" | "device" | "slot" | "finish_json" | "claimed_at" | "started_at" | "progress_json" | "account" | "est_ms">;
function activeJobs(w: WorkerRow, rows: ActiveRow[], now: number, typical: (lane: string | null) => number | null): ActiveJob[] {
- const gen = db().prepare("SELECT feature, model_id FROM generations WHERE id = ?");
+ const gen = db().prepare("SELECT feature, model_id, op, kind FROM generations WHERE id = ?");
return rows.map((t) => {
const p = taskProgress(t);
const typicalMs = estOn(t as TaskRow, w) ?? typical(t.lane);
- const g = gen.get(t.generation_id) as { feature: string | null; model_id: string | null } | undefined;
+ const g = gen.get(t.generation_id) as { feature: string | null; model_id: string | null; op: string | null; kind: string | null } | undefined;
const model = modelLabel(g?.model_id);
const progress = p ? Object.fromEntries((["value", "max", "node", "nodesDone", "position", "cold"] as const).filter((k) => p[k] !== undefined).map((k) => [k, p[k]])) : null;
return {
@@ -1836,11 +1885,17 @@ function activeJobs(w: WorkerRow, rows: ActiveRow[], now: number, typical: (lane
startedAt: t.started_at,
progress,
progressAt: p?.at ?? null,
+ movedAt: p?.movedAt ?? null,
+ gpuBusy: p?.gpuBusy ?? null,
+ doing: t.state === "running" ? jobNowOf(p) : null,
+ stallMs: stallLimitMs(t.lane),
typicalMs,
- etaS: typicalMs ? Math.max(0, Math.round(((t.started_at ?? now) + typicalMs - now) / 1000)) : null,
+ etaS: etaOf(typicalMs, t.started_at ?? now, now),
owners: t.account ? "account" : "owner",
...(g?.feature && { feature: g.feature }),
...(model && { modelName: model }),
+ ...(g?.op && { op: g.op }),
+ ...(g?.kind && { kind: g.kind }),
};
});
}
diff --git a/src/server/computer/queue-controls.ts b/src/server/computer/queue-controls.ts
index 5b62fc55..fbd6e031 100644
--- a/src/server/computer/queue-controls.ts
+++ b/src/server/computer/queue-controls.ts
@@ -347,13 +347,15 @@ export function accountOfPerson(key: string): string | null {
return rows.find((r) => personKey(r.account) === key)?.account ?? null;
}
-/** An override as the admin API shows it: a person by their key (never an account id), a run by its id. */
+/** An override as the admin API shows it: a person by their key (never an account id), a run by its id and its rows. */
export function overrideView(o: QueueOverride) {
return {
id: o.id,
kind: o.kind,
action: o.action,
generationId: o.kind === "run" ? o.target : null,
+ // Every row of the run it covers (the run pressed and the other steps of the same Run): a hold on one step holds them all.
+ generations: o.kind === "run" ? o.generations : [],
person: o.kind === "person" ? personKey(o.target) : null,
guest: o.kind === "person" && o.target.startsWith("guest"),
workerId: o.workerId,
@@ -409,7 +411,7 @@ export function checkOverride(body: unknown, now = Date.now()): OverrideInput |
}
/** SQL: row `g` was made by the same press of Run as the row asked about (pool.ts SAME_PRESS). */
-const SAME_PRESS = "(CASE WHEN @hold IS NOT NULL THEN json_extract(g.request_json, '$.hold') IS @hold ELSE @batch IS NOT NULL AND g.batch_id IS @batch END)";
+export const SAME_PRESS = "(CASE WHEN @hold IS NOT NULL THEN json_extract(g.request_json, '$.hold') IS @hold ELSE @batch IS NOT NULL AND g.batch_id IS @batch END)";
/** A run's rows: it and every other step the same press made (null: no such run). */
export function runRows(generationId: string): { generations: string[]; account: string | null; status: string } | null {
diff --git a/src/server/computer/queue-live.ts b/src/server/computer/queue-live.ts
index 392540a9..668a907c 100644
--- a/src/server/computer/queue-live.ts
+++ b/src/server/computer/queue-live.ts
@@ -9,7 +9,7 @@ import { loadIndex } from "../gpu/index-file";
import { claimableNow, controlledLine, firstClaimableNow, localWorkOf, ownerHandsOn, ownerWaitingNow, workerState } from "./pool";
import { controlWords, effectiveMode, liveOverrides, MODE_WORDS, overrideView, personKey, poolMode, poolModes, recentOverrides, sweepControls, workerModeOf, type EffectiveMode, type OverrideView, type QueueMode } from "./queue-controls";
import type { LocalWork } from "@/lib/relay";
-import { json, taskCold, taskProgress, type TaskRow } from "./tasks";
+import { json, taskCold, taskProgress, type TaskRow, jobNowOf, type JobNow } from "./tasks";
import type { WorkerRow } from "./workers";
/**
@@ -36,6 +36,11 @@ export interface RunningJob {
/** Where it is, in words ("Making your picture · step 36 of 48", "Loading the model", "Saving the results"). */
step: string | null;
progress: { value: number; max: number } | null;
+ /** What its ComfyUI runs now (tasks.ts JobNow), when its worker said; the owner's view only. */
+ doing?: JobNow;
+ /** When its worker last saw it move (the site's clock), and how busy its GPU is (0-100), when its worker says. */
+ movedAt?: number;
+ gpuBusy?: number | null;
startedAt: number | null;
claimedAt: number | null;
/** When its run was made (pressed). */
@@ -197,6 +202,10 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H
slot: t.slot === "cpu" || t.finish_json ? "cpu" : "gpu",
step,
progress: !cold && p?.max ? { value: Math.min(p.value ?? 0, p.max), max: p.max } : null,
+ ...(() => {
+ const jn = t.state === "running" ? jobNowOf(p) : null;
+ return { ...(jn && { doing: jn }), ...(p?.movedAt !== undefined && { movedAt: p.movedAt }), ...(p?.gpuBusy !== undefined && { gpuBusy: p.gpuBusy }) };
+ })(),
startedAt: t.started_at ?? t.sent_at ?? t.claimed_at,
claimedAt: t.claimed_at,
createdAt: g?.created_at ?? null,
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index 65d8a7e5..fa9d155c 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -24,6 +24,8 @@ import {
type TaskInput,
type WantedFile,
previewOf,
+ cleanNodeClass,
+ cleanNodeTitle,
} from "@/lib/relay";
import { reasonText } from "@/lib/comfy-reason";
import { cleanNodeTimes } from "@/lib/node-times";
@@ -71,9 +73,64 @@ export interface Progress extends LiveProgress {
position?: number;
/** Taken by a worker with another model loaded (or none): loading its model, until its first step reports. */
cold?: boolean;
+ /**
+ * When the worker's watchdog last saw the job move (this server's clock: the worker says how long ago, JobMotion).
+ * Absent: an older worker, or a tab, which doesn't say.
+ */
+ movedAt?: number;
+ /** How busy the worker's GPU was at its last word (0-100); null when it couldn't say. Absent: it doesn't say. */
+ gpuBusy?: number | null;
+ /** The running node's class and title (the owner's view only, NodeFacts), as its last report named the node. */
+ nodeClass?: string;
+ nodeTitle?: string;
+ /** A meta-batch job's pass now, of all its passes. */
+ pass?: { n: number; of: number };
at: number;
}
+/** A report's NodeFacts, checked: kept only with the node they describe (a report that names another node clears them). */
+export function nodeFactsOf(r: Record<string, unknown>): Pick<Progress, "nodeClass" | "nodeTitle" | "pass"> {
+ const nodeClass = cleanNodeClass(r.nodeClass);
+ const nodeTitle = cleanNodeTitle(r.nodeTitle);
+ const p = r.pass && typeof r.pass === "object" ? (r.pass as Record<string, unknown>) : null;
+ const n = Number(p?.n);
+ const of = Number(p?.of);
+ const pass = Number.isInteger(n) && Number.isInteger(of) && n >= 1 && of >= n && of <= 1e5 ? { n, of } : undefined;
+ return { ...(nodeClass && { nodeClass }), ...(nodeTitle && { nodeTitle }), ...(pass && { pass }) };
+}
+
+/** What a running job's ComfyUI does now, for the owner's views (never a person's): its node, its step or pass. */
+export interface JobNow {
+ node: string | null;
+ nodeClass: string | null;
+ nodeTitle: string | null;
+ value?: number;
+ max?: number;
+ pass?: { n: number; of: number };
+}
+
+/** A task's JobNow from its kept progress (null: nothing said yet). */
+export function jobNowOf(p: Progress | undefined): JobNow | null {
+ if (!p || (p.node === undefined && p.nodeClass === undefined && p.max === undefined)) return null;
+ return {
+ node: p.node ?? null,
+ nodeClass: p.nodeClass ?? null,
+ nodeTitle: p.nodeTitle ?? null,
+ ...(p.max && p.value !== undefined && { value: Math.min(p.value, p.max), max: p.max }),
+ ...(p.pass && { pass: p.pass }),
+ };
+}
+
+/** A "moved ago" longer than this is read as this (a day): no stored time is ever before the job could have moved. */
+const MAX_MOVED_AGO_MS = 24 * 3_600_000;
+
+/** A report's or a beat's JobMotion, checked: when it last moved (on `now`'s clock) and how busy its GPU is (0-100, or null). */
+export function motionOf(r: Record<string, unknown>, now: number): Pick<Progress, "movedAt" | "gpuBusy"> {
+ const ago = typeof r.movedAgoMs === "number" && Number.isFinite(r.movedAgoMs) && r.movedAgoMs >= 0 ? Math.min(r.movedAgoMs, MAX_MOVED_AGO_MS) : undefined;
+ const busy = typeof r.gpuBusy === "number" && Number.isFinite(r.gpuBusy) ? Math.round(Math.max(0, Math.min(100, r.gpuBusy))) : r.gpuBusy === null ? null : undefined;
+ return { ...(ago !== undefined && { movedAt: Math.round(now - ago) }), ...(busy !== undefined && { gpuBusy: busy }) };
+}
+
/**
* 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.
@@ -662,7 +719,15 @@ export function noteProgress(id: string, r: Record<string, unknown>, now: number
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;
// 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 motion (a worker's watchdog, JobMotion) over what it said before; a word without it keeps the last.
+ const next: Progress = { ...trackReport(taskProgress(cur), p, now), ...(p.position !== undefined && { position: p.position }), ...motionOf(r, now), at: now };
+ // The node's class and title go with the node a report names: a report naming a node says them anew.
+ if (node) {
+ delete next.nodeClass;
+ delete next.nodeTitle;
+ delete next.pass;
+ Object.assign(next, nodeFactsOf(r));
+ }
// 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;
diff --git a/src/server/generations.ts b/src/server/generations.ts
index c725db13..76fdf995 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -379,7 +379,7 @@ export function shownError(id: string, raw: string | null): string | null {
*/
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 : isPoolRunWords(r.message) && r.message !== POOL_WORDS.gettingReady ? r.message : POOL_WORDS.working;
+ if (r.status === "running") return ready ? POOL_WORDS.gettingReady : isPoolRunWords(r.message) && !r.message.startsWith(POOL_WORDS.gettingReady) ? r.message : POOL_WORDS.working;
return null;
}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 0023ca50..5aa2597c 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -71,7 +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 { cardProgress, collectingShare, floored, planOf, poolRunWords, progressPlan, progressView, runWords, trackReport, withLeft, type CardProgress, type LiveProgress, type ProgressPlan, type ProgressView } from "@/lib/run-progress";
import {
checkClocks,
createTask,
@@ -94,7 +94,7 @@ import {
type Principal,
type TaskRow,
} from "../computer/tasks";
-import { attemptDeadline, ownerRunClass, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, runPlaceOf, workersCanRun, workersHold } from "../computer/pool";
+import { attemptDeadline, cardTypicalMs, ownerRunClass, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, runPlaceOf, workersCanRun, workersHold } from "../computer/pool";
import { notOnGpusText } from "../runs-here";
import { catalogVersion } from "../computer/catalog-version";
import { ticketProblem, type JobTicket } from "@/lib/job-ticket";
@@ -699,6 +699,15 @@ function runPlan(meta: Record<string, unknown>, t?: Pick<TaskRow, "id" | "graph_
return graphPlans.get(t.id) ?? null;
}
+/**
+ * A job on the workers as a person's card shows it (src/lib/run-progress.ts cardProgress): a step bar only from its
+ * sampler's steps, else a bar by time from its lane's typical run, else no share. `view`: taskView's.
+ */
+export function taskCard(t: Pick<TaskRow, "lane" | "worker_id" | "progress_json" | "started_at" | "claimed_at">, view: ProgressView, now = Date.now()): CardProgress {
+ const p = taskProgress(t);
+ return cardProgress(view, { runMs: now - (t.started_at ?? t.claimed_at ?? now), typicalMs: cardTypicalMs(t, now), shown: p?.shown });
+}
+
/**
* 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).
@@ -1897,7 +1906,8 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,
if (!tenantAccount()) return { state: res.state, progress: res.progress, message: res.message, ...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;
+ const view = t.state === "running" ? taskView(t, meta) : null;
+ const words = res.state !== "running" ? POOL_WORDS.working : t.state === "collecting" ? POOL_WORDS.finishing : view ? withLeft(poolRunWords(view), view.stage === "loading" ? undefined : taskCard(t, view).leftMin) : POOL_WORDS.working;
return { state: "running", progress: res.progress, message: words, ...clocks };
}
@@ -1964,6 +1974,12 @@ async function pollTask(principal: Principal, t: TaskRow, meta: Record<string, u
case "running": {
// Its stages: getting ready, the sampler's steps, then the nodes after it; never less than this try showed.
const view = taskView(t, meta);
+ // A job on the workers: honest about what is known (taskCard). A step bar, a bar by its lane's time, or none.
+ if (t.pools) {
+ const card = taskCard(t, view);
+ if (card.share !== null) noteShown(t.id, card.share);
+ return { state: "running", ...(card.share !== null && { progress: card.share }), message: down ?? withLeft(runWords(kind, view), card.leftMin), ...(sentAt && { sentAt }) };
+ }
noteShown(t.id, view.share);
return { state: "running", progress: view.share, message: down ?? runWords(kind, view), ...(sentAt && { sentAt }) };
}
diff --git a/tests/admin-queue-live.test.ts b/tests/admin-queue-live.test.ts
index 53e27396..1cff651e 100644
--- a/tests/admin-queue-live.test.ts
+++ b/tests/admin-queue-live.test.ts
@@ -39,7 +39,7 @@ function worker(name: string): W {
return w;
}
-function beat(w: W, o: { holding?: unknown; local?: { paused?: boolean; why?: string | null }; running?: { task: string; value?: number; max?: number }[] } = {}) {
+function beat(w: W, o: { holding?: unknown; local?: { paused?: boolean; why?: string | null }; running?: Record<string, unknown>[] } = {}) {
return pool.workerBeat(
row(w),
pool.cleanBeat({
@@ -247,3 +247,109 @@ describe("GET /api/admin/queue", () => {
expect(JSON.stringify(body)).not.toContain("acct-secret");
});
});
+
+describe("is the job really moving (a worker's JobMotion)", () => {
+ it("keeps when the job last moved on the studio's clock and how busy the GPU is, and the workers API says both", () => {
+ const w = worker("moves");
+ const { id } = task();
+ claim(w);
+ setState(id, { state: "running", started_at: clock });
+ clock += 30_000;
+ beat(w, { running: [{ task: id, value: 3, max: 30, movedAgoMs: 4000, gpuBusy: 97 }] });
+ const job = pool.listWorkers(clock).find((x) => x.id === w.id)!.jobs![0];
+ expect(job).toMatchObject({ taskId: id, movedAt: clock - 4000, gpuBusy: 97, stallMs: pool.stallLimitMs(LANE) });
+ // A beat without them (an older worker) keeps the last; one with nonsense is read safely.
+ clock += 20_000;
+ beat(w, { running: [{ task: id, value: 3, max: 30 }] });
+ expect(pool.listWorkers(clock).find((x) => x.id === w.id)!.jobs![0]).toMatchObject({ movedAt: clock - 24_000, gpuBusy: 97 });
+ beat(w, { running: [{ task: id, value: 3, max: 30, movedAgoMs: -5, gpuBusy: 250 }] });
+ expect(pool.listWorkers(clock).find((x) => x.id === w.id)!.jobs![0]).toMatchObject({ movedAt: clock - 24_000, gpuBusy: 100 });
+ beat(w, { running: [{ task: id, value: 3, max: 30, movedAgoMs: 1000, gpuBusy: null }] });
+ expect(pool.listWorkers(clock).find((x) => x.id === w.id)!.jobs![0]).toMatchObject({ movedAt: clock - 1000, gpuBusy: null });
+ });
+
+ it("an older worker's job says nothing about its motion", () => {
+ const w = worker("older");
+ const { id } = task();
+ claim(w);
+ setState(id, { state: "running", started_at: clock });
+ beat(w, { running: [{ task: id, value: 3, max: 30 }] });
+ expect(pool.listWorkers(clock).find((x) => x.id === w.id)!.jobs![0]).toMatchObject({ movedAt: null, gpuBusy: null });
+ });
+
+ it("checks a report's motion: a length on the studio's clock, a busy share from 0 to 100", () => {
+ expect(tasks.motionOf({ movedAgoMs: 4000, gpuBusy: 96.6 }, 100_000)).toEqual({ movedAt: 96_000, gpuBusy: 97 });
+ expect(tasks.motionOf({ movedAgoMs: "4000", gpuBusy: "x" }, 100_000)).toEqual({});
+ expect(tasks.motionOf({ gpuBusy: null }, 100_000)).toEqual({ gpuBusy: null });
+ // A PC that says it moved days ago is read as a day ago at most.
+ expect(tasks.motionOf({ movedAgoMs: 9e12 }, 1e13).movedAt).toBe(1e13 - 24 * 3_600_000);
+ });
+
+ it("never says 0 s left: a job past its typical time has no time left to say", () => {
+ expect(pool.etaOf(10 * MIN, clock, clock + 4 * MIN)).toBe(360);
+ expect(pool.etaOf(10 * MIN, clock, clock + 10 * MIN)).toBeNull();
+ expect(pool.etaOf(10 * MIN, clock, clock + 18 * MIN)).toBeNull();
+ expect(pool.etaOf(null, clock, clock)).toBeNull();
+ });
+
+ it("a card's typical time is its lane's own (never another lane's), from its finished runs", () => {
+ const add = (lane: string, ms: number) =>
+ db()
+ .prepare("INSERT INTO worker_jobs (at, event, worker_id, worker_name, task_id, generation_id, principal, lane, exec_ms, device) VALUES (?, 'finished', 'w', 'w', 't', 'g', 'pool:pool', ?, ?, NULL)")
+ .run(clock, lane, ms);
+ for (const ms of [8 * MIN, 10 * MIN, 12 * MIN]) add("lane-typical", ms);
+ add("lane-other", 2 * MIN);
+ expect(pool.cardTypicalMs({ lane: "lane-typical", worker_id: null }, clock)).toBe(10 * MIN);
+ expect(pool.cardTypicalMs({ lane: "lane-empty", worker_id: null }, clock)).toBeNull();
+ expect(pool.cardTypicalMs({ lane: null, worker_id: null }, clock)).toBeNull();
+ });
+});
+
+describe("what its ComfyUI runs now (the owner's view)", () => {
+ const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+ const report = (id: string, e: Record<string, unknown>) => tasks.report(rowOf(id), e as never, () => ({ error: "unused" }) as never, clock);
+
+ it("keeps the running node's class, title and step from a report, and the workers API and the queue say them", () => {
+ const w = worker("names");
+ const { id } = task();
+ claim(w);
+ setState(id, { state: "running", started_at: clock });
+ report(id, { event: "running", node: "61", nodeClass: "KSampler", nodeTitle: "Main sampler", value: 14, max: 30, nodesDone: 5, movedAgoMs: 3000, gpuBusy: 97 });
+ const job = pool.listWorkers(clock).find((x) => x.id === w.id)!.jobs![0];
+ expect(job.doing).toEqual({ node: "61", nodeClass: "KSampler", nodeTitle: "Main sampler", value: 14, max: 30 });
+ expect(liveQueue(clock).running[0]).toMatchObject({ doing: { node: "61", nodeClass: "KSampler" }, movedAt: clock - 3000, gpuBusy: 97 });
+ // A beat (no node) keeps them; a report naming the next node says its own (none here: they go).
+ beat(w, { running: [{ task: id, value: 15, max: 30 }] });
+ expect(pool.listWorkers(clock).find((x) => x.id === w.id)!.jobs![0].doing).toMatchObject({ nodeClass: "KSampler", value: 15 });
+ report(id, { event: "running", node: "601", nodesDone: 6 });
+ expect(pool.listWorkers(clock).find((x) => x.id === w.id)!.jobs![0].doing).toEqual({ node: "601", nodeClass: null, nodeTitle: null });
+ });
+
+ it("never keeps a path or a long text as a title, nor an odd class", () => {
+ expect(tasks.nodeFactsOf({ nodeClass: "VAEDecodeTiled", nodeTitle: "Decode" })).toEqual({ nodeClass: "VAEDecodeTiled", nodeTitle: "Decode" });
+ expect(tasks.nodeFactsOf({ nodeClass: "<script>", nodeTitle: "C:/models/x.safetensors" })).toEqual({});
+ expect(tasks.nodeFactsOf({ nodeTitle: "a woman in a red dress walks along the beach at sunset, cinematic" })).toEqual({});
+ expect(tasks.nodeFactsOf({ pass: { n: 3, of: 7 } })).toEqual({ pass: { n: 3, of: 7 } });
+ expect(tasks.nodeFactsOf({ pass: { n: 9, of: 7 } })).toEqual({});
+ });
+});
+
+describe("which step of its Run a run is (the admin runs list)", () => {
+ it("steps that wait for one another, by their place in the chain; a batch side by side has none", async () => {
+ const { runStepOf } = await import("@/server/account-admin");
+ const add = (id: string, batch: string, dependsOn: string | null) =>
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at, depends_on, batch_id) VALUES (?, 'video', 'm', 'open', 'comfyui', 'i2v', 'video', 'queued', '{}', '[]', ?, ?, ?, ?)")
+ .run(id, clock, clock, dependsOn, batch);
+ add("chain-a", "b-chain", null);
+ add("chain-b", "b-chain", "chain-a");
+ add("chain-c", "b-chain", JSON.stringify(["chain-b"]));
+ add("side-1", "b-side", null);
+ add("side-2", "b-side", null);
+ const g = (id: string, batchId: string) => ({ id, batchId, request: {} }) as never;
+ expect(runStepOf(g("chain-a", "b-chain"))).toEqual({ n: 1, of: 3 });
+ expect(runStepOf(g("chain-c", "b-chain"))).toEqual({ n: 3, of: 3 });
+ expect(runStepOf(g("side-1", "b-side"))).toBeNull();
+ expect(runStepOf({ id: "alone", batchId: null, request: {} } as never)).toBeNull();
+ });
+});
diff --git a/tests/computer-runner.test.ts b/tests/computer-runner.test.ts
index efb9f537..8d1207d6 100644
--- a/tests/computer-runner.test.ts
+++ b/tests/computer-runner.test.ts
@@ -3,7 +3,7 @@
* the studio is busy, what it shows once a result is saved, and how it carries a job's token.
*/
import { describe, expect, it } from "vitest";
-import { batchPlan, ComputerRunner, passProgress, tileJob } from "@/lib/computer-runner";
+import { batchPlan, ComputerRunner, nodeFactsOf, passOf, passProgress, tileJob } from "@/lib/computer-runner";
import { jobWords } from "@/lib/relay";
const TASK = { id: "AAAAAAAAAAAAAAAA", generationId: "g-1", lease: "a".repeat(64), graph: {}, promptId: "00000000-0000-4000-8000-000000000000", preview: false, inputs: [] };
@@ -105,3 +105,25 @@ describe("a meta-batch job's passes", () => {
expect(passProgress(plan, undefined, 0)).toEqual({ node: "2", nodesDone: 1 });
});
});
+
+describe("the running node's facts for the owner's view", () => {
+ const graph = {
+ "61": { class_type: "KSampler", inputs: {}, _meta: { title: "Main sampler" } },
+ "642": { class_type: "VAEDecode", inputs: {}, _meta: { title: "VAEDecode" } },
+ "578": { class_type: "UNETLoader", inputs: {}, _meta: { title: "D:/models/h3.safetensors" } },
+ };
+ it("names its class and its own title, a subgraph's inner node, and never a path", () => {
+ expect(nodeFactsOf(graph, "61")).toEqual({ nodeClass: "KSampler", nodeTitle: "Main sampler" });
+ // The title that only repeats the class says nothing more.
+ expect(nodeFactsOf(graph, "672:642")).toEqual({ nodeClass: "VAEDecode" });
+ expect(nodeFactsOf(graph, "578")).toEqual({ nodeClass: "UNETLoader" });
+ expect(nodeFactsOf(graph, "9")).toEqual({});
+ expect(nodeFactsOf(null, "61")).toEqual({});
+ expect(nodeFactsOf(graph, undefined)).toEqual({});
+ });
+ it("says a meta-batch job's pass from its passes", () => {
+ expect(passOf({ value: 2, max: 7 })).toEqual({ pass: { n: 3, of: 7 } });
+ expect(passOf({ value: 7, max: 7 })).toEqual({ pass: { n: 7, of: 7 } });
+ expect(passOf({})).toEqual({});
+ });
+});
diff --git a/tests/helpers/fake-nvidia-smi.mjs b/tests/helpers/fake-nvidia-smi.mjs
index 60dceab6..284fe01c 100644
--- a/tests/helpers/fake-nvidia-smi.mjs
+++ b/tests/helpers/fake-nvidia-smi.mjs
@@ -1,5 +1,5 @@
// A stand-in for nvidia-smi (the worker's GPU check, bin/lib/worker/gpu.mjs): it answers the queries the worker makes
-// from a JSON file the test writes: { "usedMb": 900, "tempC": 50, "computeCap": "8.9", "apps": [{ "pid": 1, "name":
+// from a JSON file the test writes: { "usedMb": 900, "tempC": 50, "busyPct": 97, "computeCap": "8.9", "apps": [{ "pid": 1, "name":
// "python.exe", "usedMb": null }] } (usedMb null prints [N/A], as Windows does; no computeCap: an older nvidia-smi).
//
// node tests/helpers/fake-nvidia-smi.mjs <state.json> --query-gpu=memory.used,temperature.gpu --format=csv,noheader,nounits
@@ -10,6 +10,6 @@ const s = JSON.parse(fs.readFileSync(file, "utf8"));
if (args.includes("--query-gpu=compute_cap")) {
if (!s.computeCap) process.exit(2);
process.stdout.write(`${s.computeCap}\n`);
-} else if (args.some((a) => a.startsWith("--query-gpu"))) process.stdout.write(`${s.usedMb}, ${s.tempC ?? 40}\n`);
+} else if (args.some((a) => a.startsWith("--query-gpu"))) process.stdout.write(`${s.usedMb}, ${s.tempC ?? 40}, ${s.busyPct ?? "[N/A]"}\n`);
else if (args.some((a) => a.startsWith("--query-compute-apps"))) for (const a of s.apps ?? []) process.stdout.write(`${a.pid}, ${a.name}, ${a.usedMb === null || a.usedMb === undefined ? "[N/A]" : a.usedMb}\n`);
else process.exit(2);
diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.ts
index a6f0b0a2..c1828ee2 100644
--- a/tests/pool-line-order.test.ts
+++ b/tests/pool-line-order.test.ts
@@ -628,7 +628,7 @@ 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 () => {
+ it("taken cold, its share is honest: none while loading, the sampler's steps, none after them (no typical time for its lane); 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());
@@ -646,32 +646,33 @@ describe("the run ceiling", () => {
await tick();
const g = getGeneration(id)!;
expect(g.status).toBe("running");
- shares.push(g.progress ?? 0);
+ if (g.progress !== null) shares.push(g.progress);
return g;
};
- // Its model loads while the nodes before the sampler start: a small share, under its words.
+ // Its model loads while the nodes before the sampler start: its words, and no share (no steps, no typical time).
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);
+ expect(g.progress).toBeNull();
}
// 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 });
+ // Its worker names the node for the owner; the person reads none of it.
+ const g = await look({ nodesDone: before, node: sampler, value: v, max: 6, nodeClass: "KSampler", nodeTitle: "Main sampler" });
expect(g.message).toBe(`Working · Step ${v} of 6`);
+ expect(JSON.stringify(g)).not.toMatch(/KSampler|Main sampler/);
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.
+ // After the sampler: the decode and the file. A count of nodes is no share: none, and no time left to say.
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);
+ expect(g.progress).toBeNull();
}
for (let i = 1; i < shares.length; i++) expect(shares[i]).toBeGreaterThanOrEqual(shares[i - 1]);
expect(Math.max(...shares)).toBeLessThan(1);
diff --git a/tests/run-progress.test.ts b/tests/run-progress.test.ts
index 1b656729..5cc1aa43 100644
--- a/tests/run-progress.test.ts
+++ b/tests/run-progress.test.ts
@@ -2,6 +2,7 @@ import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
+ cardProgress,
collectingShare,
floored,
isPoolRunWords,
@@ -10,7 +11,9 @@ import {
progressPlan,
progressView,
runWords,
+ TIME_SHARE_MOST,
trackReport,
+ withLeft,
type LiveProgress,
type ProgressPlan,
} from "@/lib/run-progress";
@@ -208,3 +211,38 @@ describe("its words", () => {
expect(runWords("video", { stage: "loading" })).toBe("Loading the model");
});
});
+
+describe("a person's card for a job on the workers (cardProgress)", () => {
+ const MIN = 60_000;
+ it("shows a step bar only while the sampler reports its steps", () => {
+ const view = { stage: "sampling" as const, share: 0.5, step: { value: 10, max: 20 } };
+ expect(cardProgress(view, { runMs: 2 * MIN, typicalMs: 10 * MIN })).toEqual({ share: 0.5 });
+ // Never back below what this try showed.
+ expect(cardProgress(view, { runMs: 2 * MIN, typicalMs: null, shown: 0.6 })).toEqual({ share: 0.6 });
+ });
+
+ it("with no steps, a bar by the lane's typical time, capped below the end, and minutes left only from that", () => {
+ const finishing = { stage: "finishing" as const, share: 0.97 };
+ expect(cardProgress(finishing, { runMs: 4 * MIN, typicalMs: 10 * MIN })).toEqual({ share: 0.4, leftMin: 6 });
+ // Past its typical time: capped, and no time left to say (never "about 0 min left").
+ const late = cardProgress(finishing, { runMs: 18 * MIN, typicalMs: 10 * MIN });
+ expect(late.share).toBe(TIME_SHARE_MOST);
+ expect(late.leftMin).toBeUndefined();
+ // Under a minute left: no time either.
+ expect(cardProgress(finishing, { runMs: 9.5 * MIN, typicalMs: 10 * MIN }).leftMin).toBeUndefined();
+ });
+
+ it("with no steps and no typical time, no share at all (a count of nodes is not progress)", () => {
+ expect(cardProgress({ stage: "finishing", share: 0.97 }, { runMs: 18 * MIN, typicalMs: null })).toEqual({ share: null });
+ expect(cardProgress({ stage: "preparing", share: 0.05 }, { runMs: MIN, typicalMs: null })).toEqual({ share: null });
+ });
+
+ it("says the minutes left after the words, and those words still count as a running job's", () => {
+ expect(withLeft("Working", 4)).toBe("Working · about 4 min left");
+ expect(withLeft("Working", undefined)).toBe("Working");
+ expect(withLeft("Working", 0)).toBe("Working");
+ expect(isPoolRunWords("Working · about 4 min left")).toBe(true);
+ expect(isPoolRunWords("Finishing · about 1 min left")).toBe(true);
+ expect(isPoolRunWords("Working · about 0 s left")).toBe(false);
+ });
+});
diff --git a/tests/worker-program.test.ts b/tests/worker-program.test.ts
index 2e6fdcf6..a7476810 100644
--- a/tests/worker-program.test.ts
+++ b/tests/worker-program.test.ts
@@ -16,7 +16,10 @@ const PORT = 3367;
describe("the GPU check (check 11)", () => {
it("reads nvidia-smi, [N/A] included", () => {
- expect(parseGpu("6144, 61\n")).toEqual({ usedMb: 6144, tempC: 61 });
+ expect(parseGpu("6144, 61\n")).toEqual({ usedMb: 6144, tempC: 61, busyPct: null });
+ // How busy it is: its utilization, kept from 0 to 100 ([N/A] is unknown).
+ expect(parseGpu("6144, 61, 97\n")).toEqual({ usedMb: 6144, tempC: 61, busyPct: 97 });
+ expect(parseGpu("6144, 61, [N/A]\n")).toEqual({ usedMb: 6144, tempC: 61, busyPct: null });
expect(parseApps("1234, C:\\Program Files\\Blender\\blender.exe, [N/A]\n77, python.exe, 2048\n")).toEqual([
{ pid: 1234, name: "blender.exe", usedMb: null },
{ pid: 77, name: "python.exe", usedMb: 2048 },
diff --git a/tests/worker-runner.test.ts b/tests/worker-runner.test.ts
index 822c980d..f3aba6df 100644
--- a/tests/worker-runner.test.ts
+++ b/tests/worker-runner.test.ts
@@ -161,6 +161,46 @@ describe("a worker's runner", () => {
expect(JSON.parse(String(state(id).exec_nodes))).toEqual(finished.nodes);
});
+ it("says with each running report and beat how long ago the job moved and how busy its GPU is, and the studio keeps both", async () => {
+ const w = worker();
+ const id = task();
+ const s = studio(w);
+ fake.opts.steps = 6;
+ fake.opts.stepMs = 150;
+ const beats: Record<string, unknown>[] = [];
+ s.set((p, init) => {
+ if (p.endsWith("/beat")) beats.push(JSON.parse(String(init.body)));
+ return undefined;
+ });
+ const r = runner(s, hooks({ gpuBusy: () => 97 }));
+ const done = r.claimAndRun();
+ // A beat while it runs: its running job carries its motion.
+ for (let i = 0; i < 200 && !s.reports.some((x) => x.event === "running" && typeof x.value === "number"); i++) await sleep(10);
+ await r.beat();
+ const kept = tasks.taskProgress(state(id));
+ await done;
+ expect(state(id).state).toBe("done");
+ const running = s.reports.filter((x) => x.event === "running");
+ expect(running.length).toBeGreaterThan(0);
+ for (const x of running) {
+ expect(x.movedAgoMs).toBeTypeOf("number");
+ expect(x.movedAgoMs as number).toBeGreaterThanOrEqual(0);
+ expect(x.gpuBusy).toBe(97);
+ }
+ const job = (beats.at(-1)!.running as Record<string, unknown>[]).find((j) => j.task === id)!;
+ expect(job).toMatchObject({ gpuBusy: 97 });
+ expect(job.movedAgoMs).toBeTypeOf("number");
+ // On the studio's clock: when it moved, at most a moment before now, and the GPU's reading as said.
+ expect(kept?.movedAt).toBeTypeOf("number");
+ expect(kept!.movedAt!).toBeLessThanOrEqual(Date.now());
+ expect(Date.now() - kept!.movedAt!).toBeLessThan(30_000);
+ expect(kept?.gpuBusy).toBe(97);
+ // The node it ran, by its class from the graph (the owner's view): in its reports, and kept with its progress.
+ expect(running.some((x) => x.nodeClass === "KSampler")).toBe(true);
+ // A finished job has no motion left to say.
+ expect(r.motion(id)).toEqual({});
+ });
+
it("a browser tab's runner (no worker hooks) reports as it always did", async () => {
const w = worker();
const id = task();
@@ -169,6 +209,8 @@ describe("a worker's runner", () => {
expect(state(id).state).toBe("done");
const finished = s.reports.find((x) => x.event === "finished")!;
expect(Object.keys(finished).sort()).toEqual(["entry", "event"]);
+ // It reads no GPU: no GPU reading goes with its progress.
+ expect(s.reports.filter((x) => x.event === "running").every((x) => !("gpuBusy" in x))).toBe(true);
});
it("out of memory: frees its ComfyUI's memory and sends the job once more, and the studio never hears of the first try", async () => {