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
Queue: show the jobs workers run and hold, and the chains' next steps
Adarsh708c484d96cf
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex d9d332f9..be638c63 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -312,6 +312,8 @@ async function work(saved, deps, owner) {// How long the PC slept since the studio last answered a beat (ms), and how much of it the beat in flight carries.let slept = 0;let sleptSent = 0;+ // Why it doesn't start the line's work now although it may (the beat's `holding`: { why, since }), or null.+ let holding = null;// New code on disk (update.mjs): it takes no new job, finishes the one it has, and ends to start again on the new code.const codeWatch = deps.codeWatch ?? new CodeWatch({ root: ROOT, dist: path.join(here, "dist"), home: deps.home });let updating = false;@@ -650,6 +652,8 @@ async function work(saved, deps, owner) {...(slept > 0 && { slept }),// Its CPU slot: the finishing jobs it runs, and the task it works on....(cpuOn && { cpuSlot: { finishes: finish.kinds }, cpuRunning: cpuRunner ? runningOf(cpuRunner) : [] }),+ // Why the line's work waits on it now (the owner's queue view shows it); older studios ignore it.+ ...(holding && { holding }),};},onBeat: (a) => {@@ -1089,6 +1093,22 @@ async function work(saved, deps, owner) {// Kept results go up first, and even while it may not work (or waits for its turn): they need no GPU and no ComfyUI.// Not while it ends for new code: they stay for its next start.if (!busyJob && answer && heldFirst && !updating) take({ onlyHeld: true });+ // Why the line's work waits on it, while the studio says work waits that it could take (the beat's `holding`, with+ // since when): a pause of its own or on the website is said by the beat already, and a job of its own runs.+ {+ const s = siteOf(answer);+ let why = null;+ if ((s.claimable ?? 0) + s.owner > 0) {+ if (updating) why = "updating";+ else if ((busyJob && jobUsesGpu) || !mayWork() || !answer?.runner) why = null;+ else if (heldFirst || busyJob) why = "sending-kept";+ else if (!comfy.ready) why = "starting-comfy";+ else if (turn.waitForYield) why = "waiting-for-yield";+ else if (gpu.busyInARow > 0) why = "gpu-check";+ else if (holdBack) why = "local-work";+ }+ holding = why ? { why, since: holding?.why === why ? holding.since : now() } : null;+ }// Awake while it holds a job, has results to send, or waits for work.awake.set(!!answer?.worker && (busyJob || busyCpu || hold.ids().length > 0 || !!mayWork()));// A taken port is tried again (a bind test, never a connection) once a minute.diff --git a/docs/admin-api.md b/docs/admin-api.mdindex 04a76cf3..e8f5686b 100644--- a/docs/admin-api.md+++ b/docs/admin-api.md@@ -112,7 +112,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; 404 for the owner's own files (held or not) and unknown paths || `GET /api/admin/reports` | `limit` (1 to 500, default 100) | `{ items }`, newest first |-| `GET /api/admin/queue` | | `{ lanes }` |+| `GET /api/admin/queue` | | `{ held, lanes, running, holding, queued, next, nextTotal, text, now }` ([gpu-workers.md](gpu-workers.md#the-queue)) || `GET /api/admin/queue/settings` | | `{ settings: { runCeilingS: { default, lanes }, ownerWaitLimitS, fairShare, pickAllowanceMs, pausedBudgetS } }` ([gpu-workers.md](gpu-workers.md#the-queue)) || `PATCH /api/admin/queue/settings` | any of `runCeilingS: { default, lanes? }` (seconds, 60 to 86400; a given `runCeilingS` replaces the default and every lane's value), `ownerWaitLimitS` (seconds, 60 to 604800, or `null` for no limit), `fairShare` (boolean), `pickAllowanceMs` (0 to 3600000), `pausedBudgetS` (seconds, 0 to 604800) | `{ settings }`; 400 with the reason for a value out of bounds, an unknown setting or an unknown lane || `GET /api/admin/site/uploads` | | `{ switches: { soundConvert, soundTrim, videoTrim, photoConvert, photoCrop } }`: what a browser may do to a file that doesn't fit a tool before it is uploaded (convert a sound to MP3, offer a part of a sound or clip, convert or shrink a photo, offer a crop). All `true` by default. Every visitor reads the same values at `GET /api/site/uploads` |diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex b7b248f0..8f9205db 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -824,11 +824,15 @@ within 10 minutes of each other, each write an alert to the admin log (`worker.aits target), at most once an hour each.- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, canRotateToken?, local: { paused, why,- until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held, slept?, catalogVersion?, ceiling? }`. The answer+ until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held, slept?, catalogVersion?, ceiling?, holding? }`. The answeradds `worker: { paused, pauseNow, drain, autoResume, insideHours, nextChangeAt, lanes, lanesInside, minProtocol,sendInventory, token?, tokenExpiresAt?, catalogVersion? }` (`token`: the next token, above; `tokenExpiresAt`: whenthe token ends, for a token with a lifetime; `lanesInside`: the allowed lanes inside the PC's ceiling;`catalogVersion`: the studio's).+ - `holding: { why, since, task? }` says why it doesn't start the line's work now although it may work, while work+ waits that it could take: `starting-comfy`, `waiting-for-yield`, `local-work` (the owner's job waits for local+ ComfyUI work to finish), `gpu-check`, `updating` (it restarts on new code after its job) or `sending-kept`;+ `task` names a job it took that waits. A beat without it clears it. Older workers don't send it.- `catalogVersion` and `ceiling` say the catalog its build composes job tickets for and what its PC may ever run(see "Job tickets and the PC's ceiling"). The facts it sends with its ComfyUI's add `gpuGen`, its GPU'sgeneration (compute capability), when nvidia-smi can say.@@ -918,7 +922,12 @@ Each worker counts against its own rate limits, so three workers that beat everyrotate, revoke }`. Hours are `{ "always": true }` or `{ "tz": "Asia/Kolkata", "days": { "mon": [["01:00", "09:00"]] } }`.A window can go past midnight.- `GET /api/admin/queue`: the jobs that wait in each lane, the oldest job, the estimate, and which workers have the- lane warm.+ lane warm; and what the workers do now: `running` (each job a worker runs: its run, model, worker, step, progress,+ start, when its run was made, and whose run it is: `user`, `guest` or `owner`), `queued` (the oldest 50 jobs waiting+ in line, with when each run was made and its place in line), `holding` (a job a worker took that doesn't run yet, or a+ worker that holds back jobs it could take, with the reason in plain words and since when), `next` and `nextTotal`+ (the later steps of chains that wait for their earlier steps, with what they wait for and when each ended) and `text` (the text+ helper's jobs waiting and running).- `GET` and `PATCH /api/admin/queue/settings`: the queue's settings (above).### Behind Cloudflarediff --git a/src/app/api/admin/queue/route.ts b/src/app/api/admin/queue/route.tsindex f31ec0f4..f5af50df 100644--- a/src/app/api/admin/queue/route.ts+++ b/src/app/api/admin/queue/route.ts@@ -1,14 +1,17 @@import { connection } from "next/server";import { adminAccess } from "@/server/admin-tokens";import { queueView } from "@/server/computer/pool";+import { liveQueue } from "@/server/computer/queue-live";/*** The line for workers (owner only, or an admin token with queue:read): per lane, how many wait, the oldest, the- * estimate, and which workers have it warm.+ * estimate, and which workers have it warm; and what the workers do now (queue-live.ts): the jobs they run, the jobs+ * and the line they hold back and why, the later steps of chains that wait, and the text helper's line.*/export async function GET(request: Request) {await connection();const access = adminAccess(request, "queue:read", "Only the studio's owner sees the queue");if (access instanceof Response) return access;- return Response.json(queueView(), { headers: { "Cache-Control": "no-store" } });+ const now = Date.now();+ return Response.json({ ...queueView(now), ...liveQueue(now), now }, { headers: { "Cache-Control": "no-store" } });}diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 1c9b8b6e..301266cf 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -283,8 +283,31 @@ 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 }[];+ /**+ * 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.+ */+ holding?: WorkerHolding | null;+}++/** A worker's `holding` in its beat. */+export interface WorkerHolding {+ why: string;+ since: number;+ task?: string;}+/** What a worker's `holding.why` says, in plain words. Another value reads as HOLDING_OTHER. */+export const HOLDING_WHY: Record<string, string> = {+ "starting-comfy": "Starting its ComfyUI",+ "waiting-for-yield": "Waiting for local ComfyUI work to make room",+ "local-work": "Waiting for local ComfyUI work to finish",+ "gpu-check": "Checking what else uses its GPU",+ updating: "Restarting on new worker code after its job",+ "sending-kept": "Sending the results it kept first",+};+export const HOLDING_OTHER = "Not starting yet";+/** A worker's CPU slot: it takes light CPU work (catalog workflows marked cpu) and these finishing jobs. */export interface CpuSlot {finishes: string[];diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 84d6626a..02566ed0 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -3,7 +3,7 @@ import crypto from "node:crypto";import { FINISH_KINDS, type FinishTicket } from "@/lib/finish-ticket";import { ceilingProblem, cleanCeiling, insideCeiling, lanesInside, type Ceiling } from "@/lib/job-ticket";import { allLanes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, needsOf, packKey, partLanes, unloadedNodes, type FileNeed, type Inventory, type NodePack, type Needs } from "@/lib/lanes";-import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat } from "@/lib/relay";+import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat, type WorkerHolding } from "@/lib/relay";import { runtimeFileKeys } from "@/lib/runtime-files";import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";import { db } from "../db";@@ -256,9 +256,21 @@ export function cleanBeat(b: unknown): WorkerBeat {...((num(o.slept) ?? 0) > 0 && { slept: Math.min(num(o.slept)!, MAX_SLEPT_MS) }),cpuSlot: cleanCpuSlot(o.cpuSlot),cpuRunning: Array.isArray(o.cpuRunning) ? (o.cpuRunning.slice(0, MAX_RUNNING) as WorkerBeat["running"]) : [],+ ...(cleanHolding(o.holding) && { holding: cleanHolding(o.holding) }),};}+/** A beat's `holding` as it may be kept: a short reason in lower-case words, since when, and a task id; else null. */+export function cleanHolding(v: unknown): WorkerHolding | null {+ if (!v || typeof v !== "object") return null;+ const o = v as Record<string, unknown>;+ const why = typeof o.why === "string" && /^[a-z0-9][a-z0-9:-]{0,47}$/.test(o.why) ? o.why : null;+ const since = num(o.since);+ if (!why || since === null || since <= 0) return null;+ const task = typeof o.task === "string" && /^[\w-]{1,64}$/.test(o.task) ? o.task : null;+ return { why, since, ...(task && { task }) };+}+/*** A worker says it is here: its own pause and why, its GPU, its facts, what it runs. The answer: whether it is paused on* the website, a stop-now, drain, its hours, the lanes it is allowed, and the prompts to take off its ComfyUI.@@ -274,8 +286,24 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAconst facts = b.facts ? { ...b.facts, loras: undefined } : undefined;d.prepare(`UPDATE relay_workers SET seen_at = ?, device = ?, protocol = ?, version = ?, paused_local = ?, local_why = ?, local_until = ?,- warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ?, cpu_slot_json = ? WHERE id = ?`,- ).run(now, device, b.protocol, b.version, b.local.paused ? 1 : 0, b.local.why, b.local.until, b.warmLane, facts ? JSON.stringify(facts) : null, b.catalogVersion ?? null, b.ceiling ? JSON.stringify(b.ceiling) : null, b.cpuSlot ? JSON.stringify(b.cpuSlot) : null, w.id);+ warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ?, cpu_slot_json = ?, holding_json = ? WHERE id = ?`,+ ).run(+ now,+ device,+ b.protocol,+ b.version,+ b.local.paused ? 1 : 0,+ b.local.why,+ b.local.until,+ b.warmLane,+ facts ? JSON.stringify(facts) : null,+ b.catalogVersion ?? null,+ b.ceiling ? JSON.stringify(b.ceiling) : null,+ b.cpuSlot ? JSON.stringify(b.cpuSlot) : null,+ // Its own "since" is never later than now (a PC clock ahead of the studio's).+ b.holding ? JSON.stringify({ ...b.holding, since: Math.min(b.holding.since, now) }) : null,+ w.id,+ );// Its PC slept: a job taken back from it for going quiet meanwhile counts against no one.if (b.slept) forgiveSleep(w, b.slept, now);// The tasks of both its slots stay alive, with their progress.diff --git a/src/server/computer/queue-live.ts b/src/server/computer/queue-live.tsnew file mode 100644index 00000000..cf2fd9ed--- /dev/null+++ b/src/server/computer/queue-live.ts@@ -0,0 +1,228 @@+import "server-only";+import crypto from "node:crypto";+import { getModel } from "@/lib/catalog";+import { replacedBy } from "@/lib/catalog/replaced";+import { laneLabel } from "@/lib/lanes";+import { HOLDING_OTHER, HOLDING_WHY, SENT_STATES, type WorkerHolding } from "@/lib/relay";+import { db } from "../db";+import { loadIndex } from "../gpu/index-file";+import { claimableNow, ownerWaitingNow, workerState } from "./pool";+import { json, taskCold, taskProgress, type TaskRow } from "./tasks";+import type { WorkerRow } from "./workers";++/**+ * What the workers do right now, for the owner's queue view (GET /api/admin/queue): the jobs they run, the jobs and the+ * line they hold back and why, the later steps of chains that wait for their earlier steps, and the text helper's line.+ * Facts only: ids, models, workers' names, times and plain reasons; never a prompt, a file or an account's email.+ */++/** Whose run: an account's ("user"), a guest's, or the owner's own. */+export type PrincipalKind = "user" | "guest" | "owner";++/** A job a worker runs now. */+export interface RunningJob {+ task: string;+ generationId: string;+ model: string | null;+ op: string | null;+ kind: string | null;+ lane: string | null;+ laneLabel: string | null;+ worker: string | null;+ /** The worker's slot: its GPU's, or its CPU slot's. */+ slot: "gpu" | "cpu";+ /** 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;+ startedAt: number | null;+ claimedAt: number | null;+ /** When its run was made (pressed). */+ createdAt: number | null;+ principal: PrincipalKind;+}++/** A job waiting in line for a worker (the oldest first). */+export interface QueuedJob {+ task: string;+ generationId: string;+ model: string | null;+ op: string | null;+ lane: string | null;+ laneLabel: string | null;+ principal: PrincipalKind;+ /** When its run was made, and its place in line (a run back in line keeps its place). */+ createdAt: number | null;+ inLineAt: number;+}++/**+ * Held on a worker: a job a worker took that doesn't run yet (`task` set), or a worker that may take the line's work+ * and holds it back (`task` null; `waiting`: how many jobs in line it could take now). `why` in plain words, `code`+ * short, `since` when known.+ */+export interface HeldJob {+ worker: string;+ task: string | null;+ generationId: string | null;+ model: string | null;+ op: string | null;+ principal: PrincipalKind | null;+ why: string;+ code: string;+ since: number | null;+ /** When its run was made (a job it took). */+ createdAt?: number | null;+ waiting?: number;+}++/** A later step of a chain that waits for its earlier steps. */+export interface NextStep {+ generationId: string;+ model: string | null;+ op: string;+ principal: PrincipalKind;+ since: number;+ waitsFor: { generationId: string; model: string | null; op: string | null; status: string; step: string | null; endedAt: number | null }[];+}++/** The text helper's line (helper jobs: prompt writing, chat). */+export interface TextLine {+ waiting: number;+ running: number;+ oldestAt: number | null;+}++/** At most this many next steps are listed (oldest first); `nextTotal` counts them all. */+export const NEXT_LIMIT = 50;+/** At most this many jobs waiting in line are listed (the oldest first); `lanes` counts them all. */+export const QUEUED_LIMIT = 50;+/** A worker silent this long while it holds a job: the job counts as held, with how long it has been quiet. */+export const QUIET_MS = 60_000;+/** A worker's `holding` older than this (its beats stopped saying so) is no longer shown. */+const HOLDING_FRESH_MS = 60_000;++const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");++/** A task with no account is the owner's own; a guest's carries "guest" (or a "guest…" id). */+export const principalKind = (t: Pick<TaskRow, "account">): PrincipalKind => (!t.account ? "owner" : t.account.startsWith("guest") ? "guest" : "user");++export const modelLabel = (modelId: string | null | undefined): string | null => (modelId ? (getModel(modelId)?.name ?? replacedBy(modelId)?.was ?? modelId) : null);++const holdingOf = (w: Pick<WorkerRow, "holding_json">): WorkerHolding | null => json<WorkerHolding | null>(w.holding_json ?? null, null);+export const holdingWords = (why: string): string => HOLDING_WHY[why] ?? HOLDING_OTHER;++const mins = (ms: number) => Math.max(1, Math.round(ms / 60_000));++type GenFacts = { id: string; model_id: string; op: string; kind: string; status: string; message: string | null; created_at: number; completed_at: number | null };++export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: HeldJob[]; queued: QueuedJob[]; next: NextStep[]; nextTotal: number; text: TextLine } {+ const d = db();+ const index = loadIndex();+ const workers = d.prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL").all() as WorkerRow[];+ const byId = new Map(workers.map((w) => [w.id, w]));+ const gen = d.prepare("SELECT id, model_id, op, kind, status, message, created_at, completed_at FROM generations WHERE id = ?");+ const genOf = (id: string) => gen.get(id) as GenFacts | undefined;++ const running: RunningJob[] = [];+ const holding: HeldJob[] = [];+ const states = SENT_STATES.map((s) => `'${s}'`).join(",");+ const taken = d.prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state IN (${states}) ORDER BY COALESCE(claimed_at, created_at), id`).all() as TaskRow[];+ for (const t of taken) {+ const w = t.worker_id ? byId.get(t.worker_id) : undefined;+ const g = genOf(t.generation_id);+ const who = principalKind(t);+ const p = taskProgress(t);+ const h = w ? holdingOf(w) : null;+ const quiet = w?.seen_at ? now - w.seen_at : null;+ const base = { task: t.id, generationId: t.generation_id, model: modelLabel(g?.model_id), op: g?.op ?? null };+ // Held: the worker says it holds this job, it went quiet, or the job is still on its way to its ComfyUI.+ let held: { why: string; code: string; since: number | null } | null = null;+ if (h?.task === t.id && w?.seen_at && now - w.seen_at <= HOLDING_FRESH_MS) held = { why: holdingWords(h.why), code: h.why, since: h.since };+ else if (quiet !== null && quiet > QUIET_MS) held = { why: `No word from its worker for ${mins(quiet)} min`, code: "quiet", since: w!.seen_at };+ else if (t.state === "sending") held = { why: "Sending its files to the worker", code: "sending", since: t.sending_since ?? t.claimed_at };+ else if (t.state === "queued") held = { why: p?.position ? `In its worker's ComfyUI queue (place ${p.position})` : "In its worker's ComfyUI queue", code: "queued", since: t.sent_at ?? t.claimed_at };+ if (held) {+ holding.push({ worker: w?.name ?? "?", ...base, principal: who, ...held, createdAt: g?.created_at ?? null });+ continue;+ }+ const cold = taskCold(t);+ const step = t.state === "collecting" ? "Saving the results" : cold ? "Loading the model" : (g?.message ?? (p?.max ? `Step ${p.value ?? 0} of ${p.max}` : "Running"));+ running.push({+ ...base,+ kind: g?.kind ?? null,+ lane: t.lane,+ laneLabel: t.lane ? laneLabel(index, t.lane, sha) : null,+ worker: w?.name ?? null,+ 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,+ startedAt: t.started_at ?? t.sent_at ?? t.claimed_at,+ claimedAt: t.claimed_at,+ createdAt: g?.created_at ?? null,+ principal: who,+ });+ }++ // The jobs waiting in line, the oldest place first.+ const queued: QueuedJob[] = (+ d.prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' ORDER BY COALESCE(rank_at, created_at), id LIMIT ?").all(QUEUED_LIMIT) as TaskRow[]+ ).map((t) => {+ const g = genOf(t.generation_id);+ return {+ task: t.id,+ generationId: t.generation_id,+ model: modelLabel(g?.model_id),+ op: g?.op ?? null,+ lane: t.lane,+ laneLabel: t.lane ? laneLabel(index, t.lane, sha) : null,+ principal: principalKind(t),+ createdAt: g?.created_at ?? null,+ inLineAt: t.rank_at ?? t.created_at,+ };+ });++ // Workers that may take jobs waiting in line and hold them back: what they say (or their own pause) and since when.+ const busy = new Set(taken.map((t) => t.worker_id));+ for (const w of workers) {+ if (!w.seen_at || now - w.seen_at > QUIET_MS) continue;+ const h = holdingOf(w);+ if (h?.task && busy.has(w.id)) continue;+ const waiting = claimableNow(w, now) + ownerWaitingNow(w, now);+ if (!waiting) continue;+ const s = workerState(w, now);+ if (h && now - w.seen_at <= HOLDING_FRESH_MS) holding.push({ worker: w.name, task: null, generationId: null, model: null, op: null, principal: null, why: holdingWords(h.why), code: h.why, since: h.since, waiting });+ else if (!busy.has(w.id) && s.state !== "idle" && s.state !== "busy") holding.push({ worker: w.name, task: null, generationId: null, model: null, op: null, principal: null, why: s.words, code: s.state, since: null, waiting });+ }++ // Later steps of chains: queued, not handed to a provider, waiting for their earlier steps.+ const nextWhere = "status = 'queued' AND external_id IS NULL AND depends_on IS NOT NULL";+ const nextTotal = (d.prepare(`SELECT COUNT(*) AS n FROM generations WHERE ${nextWhere}`).get() as { n: number }).n;+ const next = (d.prepare(`SELECT id, model_id, op, request_json, depends_on, created_at FROM generations WHERE ${nextWhere} ORDER BY created_at, id LIMIT ?`).all(NEXT_LIMIT) as {+ id: string;+ model_id: string;+ op: string;+ request_json: string;+ depends_on: string;+ created_at: number;+ }[]).map((r) => {+ const deps = r.depends_on.startsWith("[") ? json<unknown[]>(r.depends_on, []).filter((x): x is string => typeof x === "string") : [r.depends_on];+ return {+ generationId: r.id,+ model: modelLabel(r.model_id),+ op: r.op,+ principal: json<{ account?: string }>(r.request_json, {}).account ? ("user" as const) : ("owner" as const),+ since: r.created_at,+ waitsFor: deps.slice(0, 16).map((id) => {+ const g = genOf(id);+ return { generationId: id, model: modelLabel(g?.model_id), op: g?.op ?? null, status: g?.status ?? "gone", step: g?.status === "queued" || g?.status === "running" ? g.message : null, endedAt: g?.completed_at ?? null };+ }),+ };+ });++ const tx = d.prepare("SELECT SUM(CASE WHEN state = 'waiting' THEN 1 ELSE 0 END) AS waiting, SUM(CASE WHEN state = 'running' THEN 1 ELSE 0 END) AS running, MIN(CASE WHEN state = 'waiting' THEN created_at END) AS oldest FROM helper_jobs WHERE state IN ('waiting','running')").get() as {+ waiting: number | null;+ running: number | null;+ oldest: number | null;+ };+ return { running, holding, queued, next, nextTotal, text: { waiting: tx.waiting ?? 0, running: tx.running ?? 0, oldestAt: tx.oldest ?? null } };+}diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.tsindex 4dc107b7..cc434203 100644--- a/src/server/computer/workers.ts+++ b/src/server/computer/workers.ts@@ -76,6 +76,8 @@ export interface WorkerRow {ceiling_json?: string | null;/** Its CPU slot (src/lib/relay.ts CpuSlot), as its last beat said. NULL: none. */cpu_slot_json?: string | null;+ /** Why it doesn't start the line's work now (src/lib/relay.ts WorkerHolding), as its last beat said. NULL: none. */+ holding_json?: string | null;}const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");diff --git a/src/server/db.ts b/src/server/db.tsindex 0bc4fc7c..d71ad8dd 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1084,6 +1084,8 @@ const RELAY_COLUMNS: [string, string, string][] = [["relay_tasks", "slot", "TEXT"],["relay_tasks", "finish_json", "TEXT"],["relay_workers", "cpu_slot_json", "TEXT"],+ // Why a worker that may work doesn't start the line's work now, as its last beat said (WorkerBeat.holding; NULL: none).+ ["relay_workers", "holding_json", "TEXT"],];declare global {diff --git a/src/server/generations.ts b/src/server/generations.tsindex 1cdfb679..c8a661ce 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -917,6 +917,7 @@ export const ASSET_FREE: Record<string, string> = {"relay_workers.seen_json": "the countries and network hashes a worker's token was used from","relay_workers.ceiling_json": "the most a worker's PC may run: lanes, workflow ids and sizes","relay_workers.cpu_slot_json": "the kinds of finishing job a worker's CPU slot runs",+ "relay_workers.holding_json": "why a worker doesn't start the line's work now: a short reason, since when and a task id","relay_pairings.facts_json": "what a paired ComfyUI said about itself: its name, GPU and version","account_canvases.summary_json": "an account board's list line: node and page counts, and its outline (node types, places and short labels)","account_chat_shares.snapshot_json": "a shared chat's words and its character's name and colours; its portrait is the row's portrait_url",diff --git a/tests/admin-queue-live.test.ts b/tests/admin-queue-live.test.tsnew file mode 100644index 00000000..f287957e--- /dev/null+++ b/tests/admin-queue-live.test.ts@@ -0,0 +1,245 @@+/**+ * The owner's queue view of what the workers do now (GET /api/admin/queue, src/server/computer/queue-live.ts): the jobs+ * they run, the jobs and the line they hold back and why (the worker's beat `holding`), the later steps of chains that+ * wait for their earlier steps, and the text helper's line. The earlier fields (`held`, `lanes`) stay as they were.+ */+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-admin-queue-live-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+delete process.env.FUOBE_PASSWORD;++const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const admin = await import("@/server/admin-tokens");+const tasks = await import("@/server/computer/tasks");+const pool = await import("@/server/computer/pool");+const workers = await import("@/server/computer/workers");+const { liveQueue, NEXT_LIMIT } = await import("@/server/computer/queue-live");+const queueRoute = await import("@/app/api/admin/queue/route");++const LANE = "aaaaaaaaaaaa";+const MIN = 60_000;+let clock = Date.now();++type W = { id: string; token: string };+const row = (w: W) => workers.getWorker(w.id)!;++function worker(name: string): W {+ const w = pool.addWorker(name);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { [LANE]: { delayMs: 0 } }, claimAfterMs: 0 });+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: [LANE], workflows: ["wf-a"] }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);+ beat(w);+ return w;+}++function beat(w: W, o: { holding?: unknown; local?: { paused?: boolean; why?: string | null }; running?: { task: string; value?: number; max?: number }[] } = {}) {+ return pool.workerBeat(+ row(w),+ pool.cleanBeat({+ device: `wkr-${w.id}`,+ protocol: 2,+ version: "1.0.0",+ local: { paused: o.local?.paused ?? false, why: o.local?.why ?? null, until: null },+ gpu: {},+ inventoryHash: null,+ running: o.running ?? [],+ stopped: [],+ ...(o.holding !== undefined && { holding: o.holding }),+ }),+ clock,+ );+}++let gens = 0;+function gen(o: { status?: string; message?: string | null; account?: string; dependsOn?: string | string[]; model?: string; createdAt?: number } = {}): string {+ const id = `live-gen-${++gens}`;+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, message, request_json, outputs_json, created_at, updated_at, depends_on) VALUES (?, 'image', ?, 'open', 'comfyui', 't2i', 'image', ?, ?, ?, '[]', ?, ?, ?)",+ )+ .run(id, o.model ?? "m-test", o.status ?? "queued", o.message ?? null, JSON.stringify(o.account ? { account: o.account } : {}), o.createdAt ?? clock, clock, o.dependsOn === undefined ? null : Array.isArray(o.dependsOn) ? JSON.stringify(o.dependsOn) : o.dependsOn);+ return id;+}++function task(o: { account?: string; message?: string | null } = {}): { id: string; gid: string } {+ const gid = gen({ account: o.account, message: o.message });+ const t = tasks.createTask({+ principal: "owner",+ generationId: gid,+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },+ pool: { pools: ["pool"], account: o.account, rankAt: clock, lane: LANE, needs: { workflowId: "wf-a", files: [], packs: [], minVramBytes: 0 } },+ });+ return { id: t.id, gid };+}++const claim = (w: W) => pool.workerClaim(row(w), [], clock)!;+const setState = (id: string, set: Record<string, unknown>) => {+ const keys = Object.keys(set);+ db().prepare(`UPDATE relay_tasks SET ${keys.map((k) => `${k} = @${k}`).join(", ")} WHERE id = @id`).run({ ...set, id });+};++beforeAll(() => setSetting("comfyWhere", "workers"));+beforeEach(() => {+ resetRates();+ clock += 60 * MIN;+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued','running')").run();+ db().prepare("DELETE FROM helper_jobs").run();+});++describe("the beat's holding", () => {+ it("is kept as the worker says it, with a short reason, and cleared by a beat without it", () => {+ const w = worker("keeps");+ beat(w, { holding: { why: "local-work", since: clock - 5 * MIN } });+ expect(JSON.parse(row(w).holding_json!)).toEqual({ why: "local-work", since: clock - 5 * MIN });+ // A "since" later than the studio's clock is the studio's now.+ beat(w, { holding: { why: "starting-comfy", since: clock + 10 * MIN, task: "t-1" } });+ expect(JSON.parse(row(w).holding_json!)).toEqual({ why: "starting-comfy", since: clock, task: "t-1" });+ beat(w);+ expect(row(w).holding_json).toBeNull();+ });++ it("drops what isn't a short reason with a time", () => {+ expect(pool.cleanHolding({ why: "Local Work!", since: 1 })).toBeNull();+ expect(pool.cleanHolding({ why: "local-work" })).toBeNull();+ expect(pool.cleanHolding({ why: "x".repeat(49), since: 1 })).toBeNull();+ expect(pool.cleanHolding("local-work")).toBeNull();+ expect(pool.cleanHolding({ why: "local-work", since: 5, task: "../x" })).toEqual({ why: "local-work", since: 5 });+ });+});++describe("what the workers do now", () => {+ it("a job on its way to the worker's ComfyUI is held; once it reports steps it runs, with its step and progress", () => {+ const w = worker("runs");+ const { id, gid } = task({ account: "acct-1", message: "Making your picture · step 36 of 48" });+ claim(w);+ expect(liveQueue(clock).holding).toEqual([expect.objectContaining({ worker: "runs", task: id, generationId: gid, code: "sending", why: "Sending its files to the worker", principal: "user", since: clock })]);+ expect(liveQueue(clock).running).toEqual([]);++ setState(id, { state: "running", started_at: clock + 1000 });+ clock += 2000;+ beat(w, { running: [{ task: id, value: 36, max: 48 }] });+ const live = liveQueue(clock);+ expect(live.holding).toEqual([]);+ expect(live.running).toEqual([+ expect.objectContaining({ task: id, generationId: gid, model: "m-test", op: "t2i", worker: "runs", slot: "gpu", step: "Making your picture · step 36 of 48", progress: { value: 36, max: 48 }, startedAt: clock - 1000, principal: "user", lane: LANE }),+ ]);+ });++ it("a job taken cold runs as \"Loading the model\"; its results being saved as \"Saving the results\"; the owner's own is the owner's", () => {+ const w = worker("cold");+ const { id } = task();+ claim(w);+ setState(id, { state: "running", started_at: clock, progress_json: JSON.stringify({ cold: true, at: clock }) });+ expect(liveQueue(clock).running).toEqual([expect.objectContaining({ task: id, step: "Loading the model", progress: null, principal: "owner" })]);+ setState(id, { state: "collecting", progress_json: null });+ expect(liveQueue(clock).running).toEqual([expect.objectContaining({ task: id, step: "Saving the results" })]);+ });++ it("the worker's own reason for a job it took wins, and a worker gone quiet holds its job", () => {+ const w = worker("says");+ const { id } = task();+ claim(w);+ setState(id, { state: "queued", sent_at: clock });+ beat(w, { holding: { why: "updating", since: clock - MIN, task: id } });+ expect(liveQueue(clock).holding).toEqual([expect.objectContaining({ task: id, code: "updating", why: "Restarting on new worker code after its job", since: clock - MIN })]);+ beat(w);+ expect(liveQueue(clock).holding).toEqual([expect.objectContaining({ task: id, code: "queued", why: "In its worker's ComfyUI queue" })]);+ expect(liveQueue(clock + 3 * MIN).holding).toEqual([expect.objectContaining({ task: id, code: "quiet", why: "No word from its worker for 3 min", since: clock })]);+ });++ it("a worker that holds back the line's work: its reason, since when and how many jobs it could take", () => {+ const w = worker("holds");+ task();+ task({ account: "acct-2" });+ beat(w, { holding: { why: "local-work", since: clock - 12 * MIN } });+ expect(liveQueue(clock).holding).toEqual([{ worker: "holds", task: null, generationId: null, model: null, op: null, principal: null, why: "Waiting for local ComfyUI work to finish", code: "local-work", since: clock - 12 * MIN, waiting: 2 }]);+ // An unknown reason from a newer worker reads plainly.+ beat(w, { holding: { why: "something-new", since: clock } });+ expect(liveQueue(clock).holding[0]).toMatchObject({ why: "Not starting yet", code: "something-new" });+ });++ it("a worker paused here with work it could take shows its own state; one with nothing to take, nothing", () => {+ const w = worker("paused-here");+ beat(w, { local: { paused: true, why: "gpu-busy:game.exe" } });+ expect(liveQueue(clock).holding).toEqual([]);+ task({ account: "acct-3" });+ beat(w, { local: { paused: true, why: "gpu-busy:game.exe" } });+ expect(liveQueue(clock).holding).toEqual([expect.objectContaining({ worker: "paused-here", task: null, code: "gpu-busy", why: "Your GPU is busy (game.exe)", since: null, waiting: 1 })]);+ });++ it("the later steps of chains, with what they wait for", () => {+ const first = gen({ status: "running", message: "Making your picture · step 3 of 8", model: "m-first" });+ const second = gen({ status: "succeeded", model: "m-second" });+ db().prepare("UPDATE generations SET completed_at = ? WHERE id = ?").run(clock - MIN, second);+ const step = gen({ dependsOn: [first, second], account: "acct-4", model: "m-step", createdAt: clock - 4 * MIN });+ const live = liveQueue(clock);+ expect(live.nextTotal).toBe(1);+ expect(live.next).toEqual([+ {+ generationId: step,+ model: "m-step",+ op: "t2i",+ principal: "user",+ since: clock - 4 * MIN,+ waitsFor: [+ { generationId: first, model: "m-first", op: "t2i", status: "running", step: "Making your picture · step 3 of 8", endedAt: null },+ { generationId: second, model: "m-second", op: "t2i", status: "succeeded", step: null, endedAt: clock - MIN },+ ],+ },+ ]);+ for (let i = 0; i < NEXT_LIMIT + 2; i++) gen({ dependsOn: first });+ expect(liveQueue(clock).next).toHaveLength(NEXT_LIMIT);+ expect(liveQueue(clock).nextTotal).toBe(NEXT_LIMIT + 3);+ });++ it("the jobs waiting in line, by their place, with when their run was made", () => {+ const a = task({ account: "acct-5" });+ const b = task();+ db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(clock - 9 * MIN, b.id);+ expect(liveQueue(clock).queued).toEqual([+ { task: b.id, generationId: b.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "owner", createdAt: clock, inLineAt: clock - 9 * MIN },+ { task: a.id, generationId: a.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "user", createdAt: clock, inLineAt: clock },+ ]);+ // A worker takes the account's run first (people's runs go before the owner's own): the owner's stays in line.+ const w = worker("takes");+ claim(w);+ expect(liveQueue(clock).queued.map((q) => q.task)).toEqual([b.id]);+ expect(liveQueue(clock).holding).toEqual([expect.objectContaining({ task: a.id, createdAt: clock })]);+ });++ it("the text helper's line: waiting, running and the oldest", () => {+ const add = db().prepare("INSERT INTO helper_jobs (id, who, task, system, user, max_tokens, state, created_at) VALUES (?, 'owner', 'enhance', '', '', 10, ?, ?)");+ add.run("h1", "waiting", clock - 2 * MIN);+ add.run("h2", "waiting", clock - MIN);+ add.run("h3", "running", clock - 5 * MIN);+ add.run("h4", "done", clock - 9 * MIN);+ expect(liveQueue(clock).text).toEqual({ waiting: 2, running: 1, oldestAt: clock - 2 * MIN });+ });+});++describe("GET /api/admin/queue", () => {+ it("keeps its fields and adds what the workers do now; never a prompt or an account's id", async () => {+ // The route reads the real clock (a task is claimable once its time has come: the claim is a moment after it).+ clock = Date.now() + 2000;+ const w = worker("route");+ const { id } = task({ account: "acct-secret" });+ claim(w);+ const { token } = admin.createAdminToken({ name: "queue reader", scopes: ["queue:read"], expiresInDays: null });+ const res = await queueRoute.GET(new NextRequest("http://localhost:3000/api/admin/queue", { headers: { authorization: `Bearer ${token}` } }));+ expect(res.status).toBe(200);+ const body = (await res.json()) as Record<string, unknown>;+ expect(Object.keys(body).sort()).toEqual(["held", "holding", "lanes", "next", "nextTotal", "now", "queued", "running", "text"]);+ expect(body.held).toMatchObject({ mine: 0, oldestAt: null });+ expect(body.holding).toEqual([expect.objectContaining({ task: id, principal: "user" })]);+ expect(JSON.stringify(body)).not.toContain("acct-secret");+ });+});diff --git a/tests/worker-turns-run.test.ts b/tests/worker-turns-run.test.tsindex abbda14b..ace3d71e 100644--- a/tests/worker-turns-run.test.ts+++ b/tests/worker-turns-run.test.ts@@ -62,7 +62,9 @@ beforeEach(() => {type W = { id: string; token: string };const task = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;-const workerRow = (w: W) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as { local_why: string | null; paused_local: number; local_until: number | null };+const workerRow = (w: W) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as { local_why: string | null; paused_local: number; local_until: number | null; holding_json: string | null };+/** Why the worker holds the line's work back, as its last beat said (the owner's queue view shows it). */+const holdingWhy = (w: W) => (JSON.parse(workerRow(w).holding_json ?? "null") as { why: string } | null)?.why ?? null;function addWorker(): W {const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);@@ -289,6 +291,8 @@ describe("studio jobs first", () => {await until(() => workerRow(w).local_why === "waiting-for-yield");expect(workerRow(w).paused_local).toBe(0);await until(() => comfyAnswers(p));+ // Its beat says why the job waits on it.+ await until(() => holdingWhy(w) === "waiting-for-yield");await sleep(1500);expect(task(id).state).toBe("waiting");expect(task(id).worker_id).toBeNull();@@ -303,6 +307,8 @@ describe("studio jobs first", () => {await until(() => site(p)?.siteWaiting === 0, 20_000);expect(p.logs.some((l) => /lets go of its memory/.test(l))).toBe(true);expect(workerRow(w).local_why).toBeNull();+ // Nothing waits for it: it holds nothing back.+ expect(holdingWhy(w)).toBeNull();});it("a game holds the GPU: the busy pause, and no turn is asked for", async () => {@@ -363,6 +369,11 @@ describe("studio jobs first", () => {expect(local.calls.length).toBeGreaterThan(0);expect(new Set(local.calls)).toEqual(new Set(["GET 127.0.0.1:8188/queue"]));expect(p.logs.some((l) => /owner's job waits for local ComfyUI work to finish/.test(l))).toBe(true);+ // The studio hears why: the owner's queue view shows the worker holding the job back, and since when.+ await until(() => holdingWhy(w) === "local-work");+ const { liveQueue } = await import("@/server/computer/queue-live");+ expect(liveQueue().holding).toEqual([expect.objectContaining({ task: null, code: "local-work", why: "Waiting for local ComfyUI work to finish", waiting: 1 })]);+ expect(liveQueue().holding[0].since).toBeLessThanOrEqual(Date.now());});it("only the owner's own job waits and local ComfyUI work runs nothing: it is asked to free its memory, and the job runs", async () => {