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
/**
* 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?: Record<string, unknown>[] } = {}) {
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 } },
});
// Made at the test's clock (the line's 20-minute rule reads when a task came).
db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(clock, t.id);
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();
const person = task({ account: "acct-2" });
beat(w, { holding: { why: "local-work", since: clock - 12 * MIN } });
// It names the job it would take first, a person's before the owner's, so the panel can say whose it holds back.
expect(liveQueue(clock).holding).toEqual([
{ worker: "holds", task: null, generationId: person.gid, model: expect.anything(), op: expect.anything(), principal: "user", 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, in the order the workers serve them, with their place, why, and 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);
// People first: the account's run ahead of the owner's own, although the owner's came first.
expect(liveQueue(clock).queued).toEqual([
{ task: a.id, generationId: a.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "user", createdAt: clock, inLineAt: clock, rank: 1, why: "First run", order: "first-run", code: "class", override: null, person: expect.stringMatching(/^p-[0-9a-f]{12}$/), guest: false, fit: { needGb: null, workers: [] } },
{ 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, rank: 2, why: "Our work: after people's runs", order: "owner", code: "class", override: null, person: null, guest: false, fit: { needGb: null, workers: [] } },
]);
// 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(["controls", "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");
});
});
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();
});
});