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
Tests: stand-ins that fail on cue, for checks of runs that recover
Adarsh16714793db4f
diff --git a/tests/helpers/app-process-child.ts b/tests/helpers/app-process-child.tsnew file mode 100644index 00000000..ccbe5aec--- /dev/null+++ b/tests/helpers/app-process-child.ts@@ -0,0 +1,119 @@+/**+ * A second app process on the same data folder (tests/helpers/app-process.ts starts it): the studio's own server code,+ * with its own memory and its own database connection, as the second server of a deploy has. It answers on a random+ * high port:+ *+ * - /api/gpu/computer/*: the worker routes, as the studio serves them.+ * - GET /__app/generation/<id>: a run as GET /api/generations/<id> answers it.+ * - POST /__app/tick: one turn of its runner (it never turns on its own), and every run that turn polls.+ * - POST /__app/billing: one sweep of its billing reports.+ * - POST /__app/pause { marker, release }: the next result it moves into the files folder waits there, with `marker`+ * written, until the file `release` exists (a test acts while this process is in the middle of saving a result).+ *+ * Run with: node --import tests/helpers/ts-register.mjs tests/helpers/app-process-child.ts+ * Requests to anything but the addresses in FUOBE_TEST_ALLOW (comma-separated) answer 599: no real network.+ */+import fs from "node:fs";+import http from "node:http";+import { register } from "node:module";+import type net from "node:net";++// next/server as the tests mock it (connection() has no request to wait for here).+register("./app-process-hooks.mjs", import.meta.url);++declare global {+ var __fuobeTestDiskFree: number | undefined;+}+globalThis.__fuobeTestDiskFree = 1e13;++const allow = (process.env.FUOBE_TEST_ALLOW ?? "").split(",").filter(Boolean);+const realFetch = globalThis.fetch;+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input instanceof Request ? input.url : input);+ if (allow.some((a) => url.startsWith(a))) return realFetch(input, init);+ return new Response("not reachable in this test", { status: 599 });+}) as typeof fetch;++// The pause point: a result's move out of the worker's upload folder.+let pause: { marker: string; release: string } | null = null;+const realRename = fs.renameSync;+fs.renameSync = ((from: fs.PathLike, to: fs.PathLike) => {+ const p = pause;+ if (p && /[\\/]relay[\\/]tasks[\\/][^\\/]+[\\/]out-\d+$/.test(String(from))) {+ pause = null;+ fs.writeFileSync(p.marker, "");+ const wait = new Int32Array(new SharedArrayBuffer(4));+ const until = Date.now() + 60_000;+ while (!fs.existsSync(p.release) && Date.now() < until) Atomics.wait(wait, 0, 0, 10);+ }+ return realRename(from, to);+}) as typeof fs.renameSync;++const { ensureRunner } = await import("@/server/generations");+const { sweepBilling } = await import("@/server/billing-outbox");+const { loadRoutes, apiAs } = await import("./computer-tab");+const one = await import("@/app/api/generations/[id]/route");+const routes = await loadRoutes();++// Its runner turns only when asked (reading a run starts no timer of its own again: the cleared ones stay in place).+ensureRunner();+const state = globalThis.__fuobeRunner!;+clearInterval(state.timer);+if (state.fastTimer) clearInterval(state.fastTimer);++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++const read = (req: http.IncomingMessage) =>+ new Promise<Buffer>((resolve) => {+ const chunks: Buffer[] = [];+ req.on("data", (c: Buffer) => chunks.push(c));+ req.on("end", () => resolve(Buffer.concat(chunks)));+ });++const server = http.createServer(async (req, res) => {+ const body = await read(req);+ const url = new URL(req.url ?? "/", "http://app");+ const send = async (r: Response) => {+ const data = Buffer.from(await r.arrayBuffer());+ res.writeHead(r.status, Object.fromEntries(r.headers));+ res.end(data);+ };+ try {+ if (url.pathname.startsWith("/api/gpu/computer/")) {+ const headers: Record<string, string> = {};+ for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string" && k !== "host" && k !== "content-length") headers[k] = v;+ const api = apiAs(routes, null, headers);+ return await send(await api(url.pathname + url.search, { method: req.method, headers, ...(body.length && { body: new Uint8Array(body) }) }));+ }+ const g = /^\/__app\/generation\/([^/]+)$/.exec(url.pathname);+ if (g && req.method === "GET") {+ return await send(await one.GET(new Request(`http://localhost:3000/api/generations/${g[1]}`), { params: Promise.resolve({ id: g[1] }) } as never));+ }+ if (url.pathname === "/__app/tick") {+ await state.tick();+ for (let i = 0; i < 2000 && state.polling?.size; i++) await sleep(5);+ return await send(Response.json({ ok: true }));+ }+ if (url.pathname === "/__app/billing") {+ await sweepBilling();+ return await send(Response.json({ ok: true }));+ }+ if (url.pathname === "/__app/pause") {+ pause = JSON.parse(body.toString("utf8")) as { marker: string; release: string };+ return await send(Response.json({ ok: true }));+ }+ if (url.pathname === "/__app/exit") {+ res.writeHead(200).end();+ setTimeout(() => process.exit(0), 10);+ return;+ }+ res.writeHead(404).end();+ } catch (e) {+ res.writeHead(500, { "content-type": "text/plain" });+ res.end(String((e as Error).stack ?? e));+ }+});++server.listen(0, "127.0.0.1", () => {+ console.log(`READY ${(server.address() as net.AddressInfo).port}`);+});diff --git a/tests/helpers/app-process-hooks.mjs b/tests/helpers/app-process-hooks.mjsnew file mode 100644index 00000000..7d2ad53d--- /dev/null+++ b/tests/helpers/app-process-hooks.mjs@@ -0,0 +1,13 @@+/**+ * The second app process's own loader hook (tests/helpers/app-process-child.ts registers it after ts-register.mjs's):+ * "next/server" is tests/stubs/next-server.ts, as the tests mock it.+ */+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const stub = pathToFileURL(path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "stubs", "next-server.ts")).href;++export async function resolve(specifier, context, next) {+ if (specifier === "next/server") return { url: stub, shortCircuit: true };+ return next(specifier, context);+}diff --git a/tests/helpers/app-process.ts b/tests/helpers/app-process.tsnew file mode 100644index 00000000..b407ab8b--- /dev/null+++ b/tests/helpers/app-process.ts@@ -0,0 +1,116 @@+/**+ * Two app processes on one database, as a deploy runs them for a moment: this test process is one, and+ * startAppProcess() starts the other (tests/helpers/app-process-child.ts) on the same data folder. Both runners turn+ * only when a test says so: runnerByHand() stops this process's timers, and tick() turns it once and waits for every+ * run that turn polls.+ */+import { spawn, type ChildProcess } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { pathToFileURL } from "node:url";++const ROOT = path.resolve(import.meta.dirname, "..", "..");++export interface AppProcess {+ url: string;+ /** Its worker routes, for a worker driver's via(). */+ api: (p: string, init?: RequestInit) => Promise<Response>;+ /** A run as GET /api/generations/<id> answers it there. */+ generation: (id: string) => Promise<Record<string, unknown> | null>;+ /** One turn of its runner, and every run that turn polls. */+ tick: () => Promise<void>;+ /** One sweep of its billing reports. */+ sweepBilling: () => Promise<void>;+ /**+ * The next result it moves into the files folder waits in the middle of that move: `paused` resolves when it is+ * there, and release() lets it go on.+ */+ pauseNextSave: () => Promise<{ paused: Promise<void>; release: () => void }>;+ /** What it wrote to its error output. */+ errors: () => string;+ stop: () => Promise<void>;+}++const realFetch = globalThis.fetch;++export async function startAppProcess(o: { dataDir: string; env?: Record<string, string | undefined>; allow?: string[] }): Promise<AppProcess> {+ const env: NodeJS.ProcessEnv = { ...process.env };+ for (const [k, v] of Object.entries({ ...o.env, FUOBE_DATA_DIR: o.dataDir, FUOBE_TEST_ALLOW: (o.allow ?? []).join(",") })) {+ if (v === undefined) delete env[k];+ else env[k] = v;+ }+ delete env.NODE_OPTIONS;+ const child: ChildProcess = spawn(process.execPath, ["--no-warnings", "--import", pathToFileURL(path.join(ROOT, "tests/helpers/ts-register.mjs")).href, path.join(ROOT, "tests/helpers/app-process-child.ts")], {+ cwd: ROOT,+ env,+ stdio: ["ignore", "pipe", "pipe"],+ });+ let err = "";+ child.stderr!.on("data", (d) => (err += d));+ const port = await new Promise<number>((resolve, reject) => {+ let out = "";+ const timer = setTimeout(() => reject(new Error(`The second app process didn't start in 120 s:\n${err}`)), 120_000);+ child.stdout!.on("data", (d) => {+ out += d;+ const m = /READY (\d+)/.exec(out);+ if (m) {+ clearTimeout(timer);+ resolve(Number(m[1]));+ }+ });+ child.on("exit", (code) => {+ clearTimeout(timer);+ reject(new Error(`The second app process ended (${code}):\n${err}`));+ });+ });+ const url = `http://127.0.0.1:${port}`;+ const post = async (p: string, body?: unknown) => {+ const r = await realFetch(`${url}${p}`, { method: "POST", ...(body !== undefined && { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) });+ if (!r.ok) throw new Error(`${p}: ${r.status} ${await r.text()}`);+ };+ let n = 0;+ return {+ url,+ api: (p, init = {}) => realFetch(`${url}${p}`, init),+ generation: async (id) => {+ const r = await realFetch(`${url}/__app/generation/${encodeURIComponent(id)}`);+ return r.ok ? ((await r.json()) as Record<string, unknown>) : null;+ },+ tick: () => post("/__app/tick"),+ sweepBilling: () => post("/__app/billing"),+ pauseNextSave: async () => {+ const marker = path.join(o.dataDir, `.pause-${process.pid}-${++n}`);+ const release = `${marker}.go`;+ await post("/__app/pause", { marker, release });+ const paused = (async () => {+ for (let i = 0; i < 1500 && !fs.existsSync(marker); i++) await new Promise((r) => setTimeout(r, 10));+ if (!fs.existsSync(marker)) throw new Error("The second app process never reached the pause");+ })();+ return { paused, release: () => fs.writeFileSync(release, "") };+ },+ errors: () => err,+ stop: async () => {+ if (child.exitCode !== null) return;+ const ended = new Promise((r) => child.once("exit", r));+ await post("/__app/exit").catch(() => child.kill());+ await Promise.race([ended, new Promise((r) => setTimeout(r, 5000))]);+ if (child.exitCode === null) child.kill();+ },+ };+}++/** This process's runner turns only when a test says so (its timers stop; reading a run starts none again). */+export function runnerByHand(): void {+ const s = globalThis.__fuobeRunner;+ if (!s) throw new Error("Start the runner first (getGeneration or ensureRunner)");+ clearInterval(s.timer);+ if (s.fastTimer) clearInterval(s.fastTimer);+}++/** One turn of this process's runner, and every run that turn polls (an account's runs are polled on their own). */+export async function tick(): Promise<void> {+ const s = globalThis.__fuobeRunner;+ if (!s) return;+ await s.tick();+ for (let i = 0; i < 2000 && s.polling?.size; i++) await new Promise((r) => setTimeout(r, 5));+}diff --git a/tests/helpers/run-watch.ts b/tests/helpers/run-watch.tsnew file mode 100644index 00000000..06b313d9--- /dev/null+++ b/tests/helpers/run-watch.ts@@ -0,0 +1,98 @@+/**+ * What a person sees of a run on this install's GPUs, as the recovery tests check it: every look at the run (a refresh,+ * a second session, the list, another app process) is written down, and checked against the rule that the run shows+ * only "In line" (with its place), "Working" (with its progress) and then its result. A recovery shows "In line" again+ * with the place it had. No error, no word about the machines, no pause.+ */+import { POOL_WORDS } from "@/lib/relay";++/** A run as the studio answers it (GET /api/generations/<id>, a list item, getGeneration). */+export interface RunLike {+ id?: string;+ status: string;+ message?: string | null;+ error?: string | null;+ progress?: number | null;+ queue?: { place: number; etaSeconds: number | null } | null;+ outputs?: unknown[];+ notCharged?: boolean;+ fix?: unknown;+}++export interface Seen {+ where: string;+ status: string;+ message: string | null;+ error: string | null;+ place: number | null;+ progress: number | null;+ outputs: number;+}++export const seenOf = (where: string, g: RunLike): Seen => ({+ where,+ status: g.status,+ message: g.message ?? null,+ error: g.error ?? null,+ place: g.queue?.place ?? null,+ progress: typeof g.progress === "number" ? g.progress : null,+ outputs: g.outputs?.length ?? 0,+});++/** Words a person never reads on a run on this install's GPUs. */+const MACHINE_WORDS = /comfy|gpu|worker|pause|paused|error|crash|restart|computer|\bpc\b|server|timed out|lost|busy/i;++export class RunWatch {+ readonly seen: Seen[] = [];++ /** `views`: each place the person can look from (where → a read of the run). */+ constructor(private views: Record<string, () => RunLike | null | Promise<RunLike | null>>) {}++ /** Look from every view now. */+ async look(): Promise<Seen[]> {+ const now: Seen[] = [];+ for (const [where, read] of Object.entries(this.views)) {+ const g = await read();+ if (g) now.push(seenOf(where, g));+ }+ this.seen.push(...now);+ return now;+ }++ /** Everything seen that breaks the rule (empty: seamless). `place`: the place the run had when it was made. */+ problems(o: { place?: number } = {}): string[] {+ const out: string[] = [];+ let best = o.place ?? Infinity;+ for (const s of this.seen) {+ const at = `${s.where}: ${JSON.stringify(s)}`;+ if (!["queued", "running", "succeeded"].includes(s.status)) out.push(`a state that isn't In line, Working or the result (${at})`);+ if (s.status === "queued" && s.message !== POOL_WORDS.inLine) out.push(`a waiting run that doesn't say In line (${at})`);+ if (s.status === "running" && s.message !== POOL_WORDS.working) out.push(`a started run that doesn't say Working (${at})`);+ if (s.status === "succeeded" && s.outputs < 1) out.push(`a result with nothing in it (${at})`);+ if (s.error) out.push(`an error (${at})`);+ for (const w of [s.message, s.error]) if (w && MACHINE_WORDS.test(w)) out.push(`words about the machines (${at})`);+ if (s.status === "queued" && s.place !== null) {+ if (s.place > best) out.push(`its place went back from ${best} to ${s.place} (${at})`);+ best = Math.min(best, s.place);+ }+ }+ return out;+ }++ /** The states seen, without repeats in a row ("queued", "running", "queued", "running", "succeeded"). */+ path(where?: string): string[] {+ const out: string[] = [];+ for (const s of this.seen) if (!where || s.where === where) if (out[out.length - 1] !== s.status) out.push(s.status);+ return out;+ }+}++/** A run that truly can't finish: one plain sentence, nothing about the machines, and not charged when it had a hold. */+export function plainFailure(g: RunLike, o: { held: boolean }): string[] {+ const out: string[] = [];+ if (g.status !== "failed") out.push(`it is ${g.status}, not failed`);+ if (g.error !== POOL_WORDS.failed) out.push(`its words are ${JSON.stringify(g.error)}`);+ if (g.fix) out.push("it offers a fix");+ if (o.held && !g.notCharged) out.push("it doesn't say Not charged");+ return out;+}diff --git a/tests/helpers/standin-billing.ts b/tests/helpers/standin-billing.tsnew file mode 100644index 00000000..8d7d13ab--- /dev/null+++ b/tests/helpers/standin-billing.ts@@ -0,0 +1,247 @@+/**+ * A stand-in for an install's external billing service (docs/billing-hook.md), for the recovery tests. It keeps its+ * holds and reports across a stop and a start, as a service with its own database would, and it can be:+ *+ * - stopped and started again (nothing answers while it is stopped: the connection is refused);+ * - made slow (`slowMs` before every answer), or made to hold its answers to one call until a number of them have come+ * in (`gather`: two servers that both send a report are both seen, however their timing falls);+ * - reached over HTTP on a random high port, or over a Unix socket (a named pipe on Windows).+ *+ * By default every run is free: the quote says "Free" with an amount of 0, and a reserve sets nothing aside. `priced`+ * gives runs a price (`price` per run). A repeated reserve with the same request id is the same+ * hold. A hold is kept until its deadline (`closeBy`: the run's wait limit plus `holdLifeMs`); a report after it is+ * refused and counted as late.+ */+import fs from "node:fs";+import http from "node:http";+import type net from "node:net";+import os from "node:os";+import path from "node:path";++export interface StandInCall {+ method: string;+ path: string;+ body: unknown;+ at: number;+}++export interface StandInHold {+ id: string;+ requestId: string;+ account: string;+ amount: number;+ createdAt: number;+ closeBy: number;+ released: boolean;+ /** Every report for each run row, in order ("succeeded", "failed", …), with what it carried. */+ reports: Map<string, { kind: "settle" | "refund"; status: string; gpuMs: unknown; device: unknown; at: number }[]>;+}++export interface StandInBilling {+ /** FUOBE_BILLING_URL for this service: http://127.0.0.1:<port> or unix:<path>. */+ address: string;+ token: string;+ calls: StandInCall[];+ holds: Map<string, StandInHold>;+ /** Reports that came after their hold's deadline (refused). */+ late: { holdId: string; generationId: string }[];+ /** Runs have a price: each costs `price`. Off (the default): every run is free. */+ priced: boolean;+ price: number;+ /** The policy every account and guest gets. */+ policy: Record<string, unknown>;+ /** The longest a run may wait before its first start (the reserve's maxWaitMs). */+ maxWaitMs: number;+ /** How long a hold lasts after its run's wait limit. */+ holdLifeMs: number;+ /** Wait this long before every answer. */+ slowMs: number;+ /**+ * Hold every call to `path` until `count` of them have come in, or `maxMs` has passed since the first: then answer+ * them all. Null: answer each at once.+ */+ gather: { path: string; count: number; maxMs: number } | null;+ /** Is it answering? */+ up: () => boolean;+ stop: () => Promise<void>;+ start: () => Promise<void>;+ /** Stop now, and start again after `ms`. */+ downFor: (ms: number) => Promise<void>;+ callsOf: (p: string) => StandInCall[];+ /** Holds made for this account. */+ holdsOf: (account: string) => StandInHold[];+ /** Every report sent for one run row, across holds. */+ reportsFor: (generationId: string) => { holdId: string; kind: "settle" | "refund"; status: string }[];+ close: () => Promise<void>;+}++/** Runs on this install's GPUs open to every account, for every kind of run and file, within rate limits. */+export const FREE_RUNS_POLICY = {+ hosted: true,+ pool: {},+ uploads: { image: true, video: true, audio: true },+ limits: { activeRuns: 2, waiting: 2, runsPerHour: 20, outputsPerRun: 4, maxMegapixels: 0, maxSeconds: 0, keepDays: 0, spaceBytes: 0 },+ ttlS: 60,+};++const readBody = (req: http.IncomingMessage) =>+ new Promise<Buffer>((resolve) => {+ const chunks: Buffer[] = [];+ req.on("data", (c: Buffer) => chunks.push(c));+ req.on("end", () => resolve(Buffer.concat(chunks)));+ });++let socketN = 0;++/** A socket path for this process: a named pipe on Windows, a file in a temp folder elsewhere. */+function socketPath(): string {+ const name = `fuobe-standin-billing-${process.pid}-${++socketN}-${Math.random().toString(36).slice(2, 8)}`;+ if (process.platform === "win32") return `\\\\.\\pipe\\${name}`;+ return path.join(fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-billing-")), "billing.sock");+}++export async function startStandInBilling(o: { socket?: boolean; token?: string } = {}): Promise<StandInBilling> {+ const token = o.token ?? "standin-billing-token";+ const sock = o.socket ? socketPath() : null;+ let port = 0;+ let server: http.Server | null = null;+ let n = 0;++ const f = {+ token,+ calls: [] as StandInCall[],+ holds: new Map<string, StandInHold>(),+ late: [] as { holdId: string; generationId: string }[],+ priced: false,+ price: 3,+ policy: JSON.parse(JSON.stringify(FREE_RUNS_POLICY)) as Record<string, unknown>,+ maxWaitMs: 20 * 60_000,+ holdLifeMs: 2 * 3_600_000,+ slowMs: 0,+ gather: null as StandInBilling["gather"],+ };++ let waiting: (() => void)[] = [];+ let gatherTimer: NodeJS.Timeout | undefined;+ const releaseAll = () => {+ clearTimeout(gatherTimer);+ gatherTimer = undefined;+ const go = waiting;+ waiting = [];+ for (const r of go) r();+ };+ const gathered = (g: NonNullable<StandInBilling["gather"]>) =>+ new Promise<void>((resolve) => {+ waiting.push(resolve);+ if (waiting.length >= g.count) return releaseAll();+ gatherTimer ??= setTimeout(releaseAll, g.maxMs);+ });++ const quote = () => (f.priced ? { allowed: true, amount: f.price, priceVersion: "p1", text: `${f.price} units` } : { allowed: true, amount: 0, priceVersion: "free", text: "Free" });++ const answer = async (req: http.IncomingMessage, res: http.ServerResponse) => {+ const raw = await readBody(req);+ let body: Record<string, unknown> = {};+ try {+ body = raw.length ? (JSON.parse(raw.toString("utf8")) as Record<string, unknown>) : {};+ } catch {}+ const url = req.url ?? "/";+ f.calls.push({ method: req.method ?? "GET", path: url, body, at: Date.now() });+ if (f.slowMs) await new Promise((r) => setTimeout(r, f.slowMs));+ const g = f.gather;+ if (g && url.split("?")[0] === g.path) await gathered(g);+ const json = (status: number, v: unknown) => {+ if (res.destroyed) return;+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(v));+ };+ if (req.headers.authorization !== `Bearer ${token}`) return json(401, { error: "unknown caller" });+ const p = url.split("?")[0];+ const now = Date.now();+ if (p === "/v1/health") return json(200, { ok: true });+ if (p === "/v1/policy") return json(200, f.policy);+ if (p === "/v1/quote") return json(200, quote());+ if (p === "/v1/reserve") {+ const requestId = String(body.requestId ?? "");+ const account = String((body.account as { id?: unknown } | undefined)?.id ?? "");+ const same = [...f.holds.values()].find((h) => h.requestId === requestId);+ const ok = (h: StandInHold) => json(200, { ok: true, holdId: h.id, amount: h.amount, boostMs: 0, maxWaitMs: f.maxWaitMs, class: "free", text: f.priced ? `${h.amount} units` : "Free" });+ if (same) return ok(same);+ const shown = (body.shown ?? {}) as { amount?: number };+ const q = quote();+ if (q.amount > Number(shown.amount ?? 0)) return json(200, { ok: false, code: "price-changed", text: `It now costs ${q.amount}.`, quote: q });+ const h: StandInHold = { id: `hold_${++n}`, requestId, account, amount: q.amount, createdAt: now, closeBy: now + f.maxWaitMs + f.holdLifeMs, released: false, reports: new Map() };+ f.holds.set(h.id, h);+ return ok(h);+ }+ if (p === "/v1/settle" || p === "/v1/refund") {+ const h = f.holds.get(String(body.holdId));+ if (!h) return json(404, { error: "no such hold" });+ const generationId = String(body.generationId);+ if (now > h.closeBy) {+ f.late.push({ holdId: h.id, generationId });+ return json(409, { ok: false, error: "the hold has closed" });+ }+ const list = h.reports.get(generationId) ?? [];+ list.push({ kind: p === "/v1/settle" ? "settle" : "refund", status: String(body.status), gpuMs: body.gpuMs, device: body.device, at: now });+ h.reports.set(generationId, list);+ return json(200, p === "/v1/settle" ? { ok: true, charged: h.amount } : { ok: true, text: "Not charged" });+ }+ if (p === "/v1/release") {+ const h = f.holds.get(String(body.holdId));+ if (h) h.released = true;+ return json(200, { ok: true });+ }+ if (p === "/v1/balance") return json(200, f.priced ? { amount: 20, chip: "20 units", text: "20 units left", detail: [] } : { amount: 0, chip: "Free", text: "Free", detail: [] });+ if (p === "/v1/account-event") return json(200, { ok: true });+ if (p === "/v1/interest") return json(200, { ok: true, text: "Noted." });+ json(404, { error: "not found" });+ };++ const listen = () =>+ new Promise<void>((resolve, reject) => {+ const s = http.createServer((req, res) => void answer(req, res));+ s.once("error", reject);+ const done = () => {+ if (!sock) port = (s.address() as net.AddressInfo).port;+ server = s;+ resolve();+ };+ if (sock) {+ if (process.platform !== "win32") fs.rmSync(sock, { force: true });+ s.listen(sock, done);+ } else s.listen(port, "127.0.0.1", done);+ });++ const stop = () =>+ new Promise<void>((resolve) => {+ const s = server;+ server = null;+ if (!s) return resolve();+ s.closeAllConnections?.();+ s.close(() => resolve());+ });++ await listen();+ const start = async () => {+ if (!server) await listen();+ };++ // (A start after a stop listens on the same port or socket, so the address never changes.)+ const service: StandInBilling = Object.assign(f, {+ address: sock ? `unix:${sock}` : `http://127.0.0.1:${port}`,+ up: () => server !== null,+ stop,+ start,+ downFor: async (ms: number) => {+ await stop();+ setTimeout(() => void start().catch(() => {}), ms);+ },+ callsOf: (p: string) => f.calls.filter((c) => c.path.split("?")[0] === p),+ holdsOf: (account: string) => [...f.holds.values()].filter((h) => h.account === account),+ reportsFor: (generationId: string) =>+ [...f.holds.values()].flatMap((h) => (h.reports.get(generationId) ?? []).map((r) => ({ holdId: h.id, kind: r.kind, status: r.status }))),+ close: stop,+ }) as StandInBilling;+ return service;+}diff --git a/tests/helpers/standin-comfy.ts b/tests/helpers/standin-comfy.tsnew file mode 100644index 00000000..56ab0307--- /dev/null+++ b/tests/helpers/standin-comfy.ts@@ -0,0 +1,193 @@+/**+ * A stand-in ComfyUI for the recovery tests: tests/helpers/fake-local-comfy.ts (/prompt, /history, /view, /queue,+ * /interrupt, /system_stats and the progress socket), behind a small front of its own on a random high port that adds+ * /free and the ways a real one goes wrong:+ *+ * - crash(): the process dies. Nothing answers on its port, and its queue, history and sockets are gone (its input+ * folder stays). start() brings it back on the same port, empty.+ * - hang(): the next prompt starts and never moves.+ * - stall(): nothing starts; prompts wait in its queue.+ * - fail("missing_node" | "missing_model"): the next prompt is refused.+ * - outOfMemory(): the next prompt runs out of graphics memory at its end.+ * - lose(n): the next n prompts are taken and then gone (a restart while they waited).+ *+ * Ports come from the system's free high ports, never ComfyUI's own (8188 to 8191).+ */+import http from "node:http";+import net from "node:net";+import { startLocalComfy, type LocalComfy, type LocalComfyLog, type LocalComfyOptions } from "./fake-local-comfy";++export interface StandInComfy {+ url: string;+ port: number;+ /** The ComfyUI behind the front (its options, history and inputs). */+ inner: LocalComfy;+ /** Every request, in order: the inner ComfyUI's log, plus the front's own /free calls. */+ log: () => LocalComfyLog[];+ /** The bodies of POST /free, in order. */+ frees: unknown[];+ /** Prompts posted since it started (a crash doesn't reset the count). */+ posts: () => number;+ /** Prompts posted with this prompt id. */+ postsOf: (promptId: string) => number;+ /** Is it answering? */+ up: () => boolean;+ crash: () => Promise<void>;+ start: () => Promise<void>;+ hang: () => void;+ stall: (on?: boolean) => void;+ fail: (kind: "missing_node" | "missing_model") => void;+ outOfMemory: () => void;+ lose: (n?: number) => void;+ close: () => Promise<void>;+}++/** Ports ComfyUI uses on a real machine: a stand-in never takes them. */+const COMFY_PORTS = new Set([8188, 8189, 8190, 8191]);++/** A free port from the system's high range (never one of ComfyUI's own). */+export async function freeHighPort(): Promise<number> {+ for (let i = 0; i < 20; i++) {+ const port = await new Promise<number>((resolve, reject) => {+ const s = net.createServer();+ s.once("error", reject);+ s.listen(0, "127.0.0.1", () => {+ const a = s.address() as net.AddressInfo;+ s.close(() => resolve(a.port));+ });+ });+ if (port >= 1024 && !COMFY_PORTS.has(port)) return port;+ }+ throw new Error("No free high port");+}++/** Start a stand-in. Options are the inner ComfyUI's (tests/helpers/fake-local-comfy.ts); `cors` defaults to "*". */+export async function startStandInComfy(o: Partial<LocalComfyOptions> = {}): Promise<StandInComfy> {+ const inner = await startLocalComfy({ cors: "*", steps: 4, stepMs: 10, latencyMs: 10, ...o }, await freeHighPort());+ const frontLog: LocalComfyLog[] = [];+ const frees: unknown[] = [];+ let server: http.Server | null = null;+ let port = 0;+ /** Progress sockets passed through (a server's close() waits for them, so a crash ends them itself). */+ const upgraded = new Set<net.Socket>();++ const handler = (req: http.IncomingMessage, res: http.ServerResponse) => {+ const url = new URL(req.url ?? "/", "http://stand-in");+ if (url.pathname === "/free" || url.pathname === "/api/free") {+ const chunks: Buffer[] = [];+ req.on("data", (c: Buffer) => chunks.push(c));+ req.on("end", () => {+ let body: unknown = {};+ try {+ body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");+ } catch {}+ frontLog.push({ method: req.method ?? "GET", path: url.pathname, at: Date.now(), body });+ if (req.method !== "POST") return void res.writeHead(405, { connection: "close" }).end();+ frees.push(body);+ res.writeHead(200, { "content-type": "application/json", "access-control-allow-origin": "*", connection: "close" });+ res.end("{}");+ });+ return;+ }+ // Everything else is ComfyUI's own: passed through as it came. No connection is kept open after an answer, so a+ // client never reuses one a crash ended.+ const up = http.request({ host: "127.0.0.1", port: inner.port, method: req.method, path: req.url, headers: req.headers }, (answer) => {+ res.writeHead(answer.statusCode ?? 502, { ...answer.headers, connection: "close" });+ answer.pipe(res);+ });+ up.on("error", () => {+ if (!res.headersSent) res.writeHead(502);+ res.end();+ });+ req.pipe(up);+ };++ const upgrade = (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => {+ upgraded.add(socket);+ socket.on("close", () => upgraded.delete(socket));+ const to = net.connect(inner.port, "127.0.0.1", () => {+ const lines = [`${req.method} ${req.url} HTTP/1.1`, ...Object.entries(req.headers).flatMap(([k, v]) => (Array.isArray(v) ? v.map((x) => `${k}: ${x}`) : [`${k}: ${v}`])), "", ""];+ to.write(lines.join("\r\n"));+ if (head.length) to.write(head);+ socket.pipe(to).pipe(socket);+ });+ const drop = () => {+ socket.destroy();+ to.destroy();+ };+ to.on("error", drop);+ socket.on("error", drop);+ socket.on("close", () => to.destroy());+ to.on("close", () => socket.destroy());+ };++ const listen = () =>+ new Promise<void>((resolve, reject) => {+ const s = http.createServer(handler);+ s.on("upgrade", upgrade);+ s.once("error", reject);+ s.listen(port, "127.0.0.1", () => {+ port = (s.address() as net.AddressInfo).port;+ server = s;+ resolve();+ });+ });++ const shut = () =>+ new Promise<void>((resolve) => {+ const s = server;+ server = null;+ if (!s) return resolve();+ for (const u of upgraded) u.destroy();+ upgraded.clear();+ s.closeAllConnections?.();+ s.close(() => resolve());+ });++ port = await freeHighPort();+ await listen();++ const fake: StandInComfy = {+ get url() {+ return `http://127.0.0.1:${port}`;+ },+ get port() {+ return port;+ },+ inner,+ log: () => [...inner.log, ...frontLog].sort((a, b) => (a.at ?? 0) - (b.at ?? 0)),+ frees,+ posts: () => inner.posts(),+ postsOf: (promptId) => inner.log.filter((e) => e.prompt?.prompt_id === promptId).length,+ up: () => server !== null,+ crash: async () => {+ await shut();+ // Its memory goes with it: the queue, the history and the sockets (the log of what it was asked stays).+ inner.restart();+ },+ start: async () => {+ if (server) return;+ await listen();+ },+ hang: () => {+ inner.opts.failNext = "never";+ },+ stall: (on = true) => {+ inner.opts.stall = on;+ },+ fail: (kind) => {+ inner.opts.failNext = kind;+ },+ outOfMemory: () => {+ inner.opts.failNext = "oom";+ },+ lose: (n = 1) => {+ inner.opts.loseNext = (inner.opts.loseNext ?? 0) + n;+ },+ close: async () => {+ await shut();+ await inner.close();+ },+ };+ return fake;+}diff --git a/tests/helpers/ts-hooks.mjs b/tests/helpers/ts-hooks.mjsindex dd26e00d..22aa0aab 100644--- a/tests/helpers/ts-hooks.mjs+++ b/tests/helpers/ts-hooks.mjs@@ -1,6 +1,8 @@/*** Lets a child `node` process load the server's TypeScript the way the tests do: "@/…" from src, the "server-only"- * stub, and imports written without an extension. Used with --import tests/helpers/ts-register.mjs.+ * stub, imports written without an extension (a package's own files too, "next/server"), and JSON imports without an+ * import attribute. Used with+ * --import tests/helpers/ts-register.mjs.*/import fs from "node:fs";import path from "node:path";@@ -19,12 +21,20 @@ export async function resolve(specifier, context, next) {}const file = base && tryFile(base);if (file) return { url: pathToFileURL(file).href, shortCircuit: true };- return next(specifier, context);+ try {+ return await next(specifier, context);+ } catch (e) {+ // A package's file named without its extension ("next/server"), as the bundler allows.+ if (e?.code !== "ERR_MODULE_NOT_FOUND" || specifier.startsWith(".") || !specifier.includes("/") || specifier.endsWith(".js")) throw e;+ return next(`${specifier}.js`, context);+ }}-/** TypeScript to JavaScript (the typescript package, as the editor sees it), as ES modules. */+/** TypeScript to JavaScript (the typescript package, as the editor sees it), as ES modules; JSON as the bundler reads it. */let ts;export async function load(url, context, next) {+ // The server imports JSON files (the catalog) with no import attribute, as the bundler allows.+ if (url.startsWith("file:") && url.endsWith(".json")) return { format: "json", source: fs.readFileSync(fileURLToPath(url), "utf8"), shortCircuit: true };if (!url.startsWith("file:") || !/\.tsx?$/.test(url)) return next(url, context);ts ??= (await import("typescript")).default;const source = fs.readFileSync(fileURLToPath(url), "utf8");diff --git a/tests/helpers/worker-driver.ts b/tests/helpers/worker-driver.tsnew file mode 100644index 00000000..b5d6488f--- /dev/null+++ b/tests/helpers/worker-driver.ts@@ -0,0 +1,188 @@+/**+ * A worker for the recovery tests: the runner the worker program uses (src/lib/computer-runner.ts), calling the+ * studio's real worker routes with a worker token (Authorization: Bearer), against a stand-in ComfyUI+ * (tests/helpers/standin-comfy.ts). A test can:+ *+ * - stop it right after any step (`stopAfter`): the studio has done that step, and the worker is gone before it reads+ * the answer, as a worker whose process was killed. Nothing it had in flight comes back to it.+ * - make the studio answer some calls with an error (`answer`), as a deploy or a proxy does for a while.+ * - send its calls to another app process (`via`), as a deploy's second server.+ * - say it is paused here (`pause`), as a worker that stepped aside for another program does in its beats.+ *+ * Start a new driver with the same token to bring the worker back.+ */+import { ComputerRunner } from "@/lib/computer-runner";+import type { BeatAnswer } from "@/lib/relay";+import { apiAs, sha256, type ComputerRoutes } from "./computer-tab";+import type { StandInComfy } from "./standin-comfy";++/** The steps a worker's job goes through, by the call it makes to the studio. */+export type WorkerStep = "beat" | "claim" | "input" | "sent" | "queued" | "running" | "finished" | "passes" | "gone" | "failed" | "part" | "release" | "other";++export type StudioApi = (path: string, init?: RequestInit) => Promise<Response>;++export type StepHook = (step: WorkerStep, path: string, report: Record<string, unknown> | null) => void | Promise<void>;++export interface WorkerDriver {+ runner: ComputerRunner;+ /** Every call it made to the studio, as "<step> <path>". */+ calls: string[];+ /** The steps the studio answered, in order. */+ steps: WorkerStep[];+ /** Gone (stopped after a step, or stop() called). */+ readonly dead: boolean;+ beat: () => Promise<BeatAnswer | null>;+ /**+ * Take a job and run it: resolves true when one ran to its end, false when there was none, and "stopped" when the+ * worker stopped part way (its job stays where the studio last heard of it).+ */+ runOne: () => Promise<boolean | "stopped">;+ /** Stop right after the `n`th (default: first) answered call of this step from now on. */+ stopAfter: (step: WorkerStep, n?: number) => void;+ /** The studio answers the next `times` calls of this step with `status`, without seeing them. */+ answer: (step: WorkerStep, status: number, times: number) => void;+ /** Send its calls to another app process from now on (null: this one's routes). */+ via: (api: StudioApi | null) => void;+ /** Its beats say it paused here (`why` as the worker program says it: "gpu-busy:<program>", "here-now"), or not. */+ pause: (why: string | null) => void;+ /**+ * Called after each answered step, before the worker reads the answer (a test acts at that moment: crash the ComfyUI,+ * restart the app, …). A report's event comes with it.+ */+ onStep: (fn: StepHook | null) => void;+ stop: () => void;+}++const never = <T,>() => new Promise<T>(() => {});++/** The step a call to the studio is, by its path and (for a report) its event. */+export function stepOf(path: string, init: RequestInit = {}): WorkerStep {+ const p = path.split("?")[0];+ if (p.endsWith("/beat")) return "beat";+ if (p.endsWith("/claim")) return "claim";+ if (/\/inputs\/[^/]+$/.test(p)) return "input";+ if (/\/outputs\/[^/]+$/.test(p) && (init.method ?? "GET") === "PUT") return "part";+ if (p.endsWith("/release")) return "release";+ if (p.endsWith("/report")) {+ try {+ const e = (JSON.parse(String(init.body ?? "{}")) as { event?: string }).event;+ if (e === "sent" || e === "queued" || e === "running" || e === "finished" || e === "passes" || e === "gone" || e === "failed") return e;+ } catch {}+ }+ return "other";+}++export function workerDriver(o: {+ routes: ComputerRoutes;+ token: string;+ comfy: StandInComfy;+ clientId?: string;+ /** How long its waits are, at most (the runner's own waits are seconds; tests keep them short). */+ sleepCapMs?: number;+}): WorkerDriver {+ const local = apiAs(o.routes, null, { authorization: `Bearer ${o.token}` });+ let target: StudioApi | null = null;+ let dead = false;+ let stopAt: { step: WorkerStep; left: number } | null = null;+ const answers: { step: WorkerStep; status: number; left: number }[] = [];+ let paused: string | null = null;+ let hook: StepHook | null = null;+ let died: () => void = () => {};+ const diedP = new Promise<"stopped">((r) => (died = () => r("stopped")));+ const calls: string[] = [];+ const steps: WorkerStep[] = [];++ const die = () => {+ if (dead) return;+ dead = true;+ runner.stop();+ died();+ };++ const api: StudioApi = async (path, init = {}) => {+ if (dead) return never();+ const step = stepOf(path, init);+ calls.push(`${step} ${path.split("?")[0]}`);+ const fake = answers.find((a) => a.step === step && a.left > 0);+ if (fake) {+ fake.left--;+ return new Response(JSON.stringify({ error: "busy" }), { status: fake.status, headers: { "content-type": "application/json" } });+ }+ const withToken = (init: RequestInit): RequestInit => ({ ...init, headers: { ...Object.fromEntries(new Headers(init.headers)), authorization: `Bearer ${o.token}` } });+ const res = await (target ? target(path, withToken(init)) : local(path, init));+ if (dead) return never();+ steps.push(step);+ if (hook) {+ let report: Record<string, unknown> | null = null;+ if (path.split("?")[0].endsWith("/report")) {+ try {+ report = JSON.parse(String(init.body)) as Record<string, unknown>;+ } catch {}+ }+ await hook(step, path, report);+ }+ if (stopAt && stopAt.step === step && --stopAt.left <= 0) {+ stopAt = null;+ die();+ return never();+ }+ return res;+ };++ const runner = new ComputerRunner(+ {+ api,+ local: (url, init) => (dead ? never() : fetch(url, init)),+ socket: (url) => (dead ? null : (new WebSocket(url) as never)),+ sha256,+ origin: "http://localhost:3000",+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, o.sleepCapMs ?? 50))),+ beatExtra: () => ({ protocol: 1, version: "test", local: { paused: !!paused, why: paused, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null }),+ // As the worker program does when a job ends here: its prompt leaves its ComfyUI's history (once its ComfyUI has+ // stopped it, when the job was taken back).+ ended: async (t) => {+ if (dead) return;+ for (let i = 0; i < 100; i++) {+ const q = (await fetch(`${o.comfy.url}/queue`)+ .then((r) => r.json())+ .catch(() => null)) as { queue_running?: unknown[][]; queue_pending?: unknown[][] } | null;+ if (!q || ![...(q.queue_running ?? []), ...(q.queue_pending ?? [])].some((r) => r[1] === t.promptId)) break;+ await new Promise((r) => setTimeout(r, 20));+ }+ await fetch(`${o.comfy.url}/history`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delete: [t.promptId] }) }).catch(() => null);+ },+ },+ { device: "worker", port: o.comfy.port, clientId: o.clientId ?? `worker-${Math.random().toString(36).slice(2, 8)}` },+ );++ return {+ runner,+ calls,+ steps,+ get dead() {+ return dead;+ },+ beat: () => (dead ? Promise.resolve(null) : Promise.race([runner.beat(), diedP.then(() => null)])),+ runOne: async () => {+ if (dead) return "stopped";+ const r = await Promise.race([runner.claimAndRun(), diedP]);+ return dead ? "stopped" : r;+ },+ stopAfter: (step, n = 1) => {+ stopAt = { step, left: n };+ },+ answer: (step, status, times) => {+ answers.push({ step, status, left: times });+ },+ via: (api) => {+ target = api;+ },+ pause: (why) => {+ paused = why;+ },+ onStep: (fn) => {+ hook = fn;+ },+ stop: die,+ };+}diff --git a/tests/recovery-standins.test.ts b/tests/recovery-standins.test.tsnew file mode 100644index 00000000..470f739f--- /dev/null+++ b/tests/recovery-standins.test.ts@@ -0,0 +1,272 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { startStandInBilling, type StandInBilling } from "./helpers/standin-billing";+import { freeHighPort, startStandInComfy, type StandInComfy } from "./helpers/standin-comfy";+import { stepOf } from "./helpers/worker-driver";+import { plainFailure, RunWatch } from "./helpers/run-watch";++/**+ * The recovery tests' stand-ins (tests/recovery-server.test.ts): a ComfyUI that can crash, hang, fail, run out of+ * memory or lose a prompt; a billing service that can stop, start again and be slow, over HTTP or a socket; and the+ * check of what a person sees of a run.+ */++const { hookCall, hookTarget } = await import("@/server/hook-client");+const { POOL_WORDS } = await import("@/lib/relay");++const GRAPH = { "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["3", 0], filename_prefix: "fuobe/standin" } } };+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++describe("the stand-in ComfyUI", () => {+ let comfy: StandInComfy;+ beforeAll(async () => {+ comfy = await startStandInComfy({ steps: 3, stepMs: 10 });+ });+ afterAll(async () => {+ await comfy.close();+ });++ const post = (path: string, body: unknown) => fetch(`${comfy.url}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });+ const prompt = async (id = crypto.randomUUID(), clientId?: string) => {+ const r = await post("/prompt", { prompt: GRAPH, prompt_id: id, ...(clientId && { client_id: clientId }) });+ return { id, status: r.status, body: (await r.json()) as Record<string, unknown> };+ };+ const history = async (id: string) => ((await (await fetch(`${comfy.url}/history/${id}`)).json()) as Record<string, { status: { status_str: string } }>)[id];+ const until = async <T,>(fn: () => Promise<T>, ms = 3000) => {+ const end = Date.now() + ms;+ let v = await fn();+ while (!v && Date.now() < end) {+ await sleep(20);+ v = await fn();+ }+ return v;+ };++ it("listens on a free high port, never one of ComfyUI's own", async () => {+ expect(comfy.port).toBeGreaterThan(1024);+ expect([8188, 8189, 8190, 8191]).not.toContain(comfy.port);+ expect(await freeHighPort()).toBeGreaterThan(1024);+ const stats = (await (await fetch(`${comfy.url}/system_stats`)).json()) as { system: { comfyui_version: string } };+ expect(stats.system.comfyui_version).toBeTruthy();+ });++ it("runs a prompt: its queue, its history, its file, and its progress on the socket", async () => {+ const ws = new WebSocket(`ws://127.0.0.1:${comfy.port}/ws?clientId=watcher`);+ const events: string[] = [];+ ws.onmessage = (e) => {+ if (typeof e.data === "string") events.push((JSON.parse(e.data) as { type: string }).type);+ };+ await new Promise((r) => (ws.onopen = r));+ const p = await prompt(undefined, "watcher");+ expect(p.status).toBe(200);+ const entry = await until(() => history(p.id));+ expect(entry.status.status_str).toBe("success");+ const outputs = Object.values((entry as unknown as { outputs: Record<string, { images: { filename: string; subfolder: string }[] }> }).outputs)[0].images;+ const file = await fetch(`${comfy.url}/view?filename=${outputs[0].filename}&subfolder=${outputs[0].subfolder}&type=output`);+ expect(file.status).toBe(200);+ expect(events).toContain("progress");+ expect(events).toContain("execution_success");+ const queue = (await (await fetch(`${comfy.url}/queue`)).json()) as { queue_running: unknown[]; queue_pending: unknown[] };+ expect(queue).toEqual({ queue_running: [], queue_pending: [] });+ expect(comfy.postsOf(p.id)).toBe(1);+ ws.close();+ });++ it("frees its memory when asked (POST /free)", async () => {+ const r = await post("/free", { unload_models: true, free_memory: true });+ expect(r.status).toBe(200);+ expect(comfy.frees.at(-1)).toEqual({ unload_models: true, free_memory: true });+ expect(comfy.log().some((e) => e.path === "/free")).toBe(true);+ });++ it("crashes: nothing answers, and when it starts again its queue and history are gone (what it was asked stays counted)", async () => {+ const p = await prompt();+ await until(() => history(p.id));+ const posts = comfy.posts();+ await comfy.crash();+ expect(comfy.up()).toBe(false);+ await expect(fetch(`${comfy.url}/system_stats`)).rejects.toThrow();+ await comfy.start();+ expect(comfy.up()).toBe(true);+ expect(await history(p.id)).toBeUndefined();+ expect(comfy.posts()).toBe(posts);+ });++ it("crashes with a progress socket open: the socket ends, and the crash doesn't wait for it", async () => {+ const ws = new WebSocket(`ws://127.0.0.1:${comfy.port}/ws?clientId=crash-watcher`);+ await new Promise((r) => (ws.onopen = r));+ const closed = new Promise((r) => (ws.onclose = r));+ await comfy.crash();+ await closed;+ await comfy.start();+ });++ it("hangs: the next prompt starts and never moves", async () => {+ comfy.hang();+ const p = await prompt();+ await sleep(200);+ expect(await history(p.id)).toBeUndefined();+ const queue = (await (await fetch(`${comfy.url}/queue`)).json()) as { queue_running: unknown[][] };+ expect(queue.queue_running.map((r) => r[1])).toEqual([p.id]);+ // Stopped by hand, it is gone from the queue.+ await post("/interrupt", { prompt_id: p.id });+ await comfy.crash();+ await comfy.start();+ });++ it("stalls: nothing starts until it is told to go on", async () => {+ comfy.stall();+ try {+ const p = await prompt();+ await sleep(100);+ const queue = (await (await fetch(`${comfy.url}/queue`)).json()) as { queue_pending: unknown[][] };+ expect(queue.queue_pending.map((r) => r[1])).toContain(p.id);+ } finally {+ comfy.stall(false);+ await comfy.crash();+ await comfy.start();+ }+ });++ it("refuses a prompt, runs out of memory, or loses a prompt, once each", async () => {+ comfy.fail("missing_node");+ expect((await prompt()).status).toBe(400);+ expect((await prompt()).status).toBe(200);++ comfy.outOfMemory();+ const oom = await prompt();+ const entry = await until(() => history(oom.id));+ expect(entry.status.status_str).toBe("error");+ expect(JSON.stringify(entry)).toMatch(/out of memory/i);++ comfy.lose();+ const lost = await prompt();+ expect(lost.status).toBe(200);+ await sleep(100);+ expect(await history(lost.id)).toBeUndefined();+ const queue = (await (await fetch(`${comfy.url}/queue`)).json()) as { queue_running: unknown[][]; queue_pending: unknown[][] };+ expect([...queue.queue_running, ...queue.queue_pending].map((r) => r[1])).not.toContain(lost.id);+ });+});++describe("the stand-in billing service", () => {+ const call = (svc: StandInBilling, path: string, body?: unknown, timeoutMs = 2000) =>+ hookCall<Record<string, unknown>>({ hook: "test", target: hookTarget(svc.address)!, token: svc.token, method: body === undefined ? "GET" : "POST", path, body, timeoutMs });+ const account = { id: "acct-1", email: null, emailVerified: false, signIn: "password", createdAt: 0, adultAt: null };+ const reserve = (svc: StandInBilling, requestId: string, shown = { amount: 0, priceVersion: "free" }) => call(svc, "/v1/reserve", { requestId, account, run: {}, queue: null, shown });++ for (const socket of [false, true]) {+ describe(socket ? "on a socket" : "over HTTP", () => {+ let svc: StandInBilling;+ beforeAll(async () => {+ svc = await startStandInBilling({ socket });+ });+ afterAll(async () => {+ await svc.close();+ });++ it("makes every run free, keeps one hold per press, and keeps each report", async () => {+ expect(svc.address).toMatch(socket ? /^unix:/ : /^http:\/\/127\.0\.0\.1:\d+$/);+ expect(await call(svc, "/v1/quote", { account, run: {}, queue: null })).toEqual({ allowed: true, amount: 0, priceVersion: "free", text: "Free" });+ expect(await call(svc, "/v1/policy?account=acct-1")).toMatchObject({ hosted: true, limits: { activeRuns: 2 } });+ const a = await reserve(svc, "press-1");+ const again = await reserve(svc, "press-1");+ expect(a).toMatchObject({ ok: true, amount: 0, text: "Free", class: "free" });+ expect(again.holdId).toBe(a.holdId);+ expect(svc.holdsOf("acct-1")).toHaveLength(1);+ await call(svc, "/v1/settle", { holdId: a.holdId, generationId: "g1", rows: 1, status: "succeeded" });+ expect(svc.reportsFor("g1")).toEqual([{ holdId: a.holdId, kind: "settle", status: "succeeded" }]);+ });++ it("stops (nothing answers) and starts again with its holds kept", async () => {+ const a = await reserve(svc, "press-2");+ await svc.stop();+ expect(svc.up()).toBe(false);+ await expect(call(svc, "/v1/health")).rejects.toThrow();+ await svc.start();+ expect(await call(svc, "/v1/health")).toEqual({ ok: true });+ expect(svc.holds.has(String(a.holdId))).toBe(true);+ });++ it("comes back by itself after downFor", async () => {+ await svc.downFor(150);+ await expect(call(svc, "/v1/health")).rejects.toThrow();+ await sleep(400);+ expect(await call(svc, "/v1/health")).toEqual({ ok: true });+ });+ });+ }++ it("is slow when told to be, holds answers until others come, refuses unknown callers, prices runs when told to, and refuses a report after its hold closed", async () => {+ const svc = await startStandInBilling();+ try {+ svc.slowMs = 300;+ const t0 = Date.now();+ await call(svc, "/v1/health");+ expect(Date.now() - t0).toBeGreaterThanOrEqual(250);+ await expect(call(svc, "/v1/health", undefined, 100)).rejects.toThrow(/no answer/);+ // (The call it gave up on is still being answered: let it end first.)+ await sleep(400);+ svc.slowMs = 0;+ // Answers to one call held until two of them come in (or the time is up).+ svc.gather = { path: "/v1/health", count: 2, maxMs: 2000 };+ const t1 = Date.now();+ const both = await Promise.all([call(svc, "/v1/health"), call(svc, "/v1/health")]);+ expect(both).toEqual([{ ok: true }, { ok: true }]);+ expect(Date.now() - t1).toBeLessThan(1500);+ const t2 = Date.now();+ await call(svc, "/v1/health", undefined, 3000);+ expect(Date.now() - t2).toBeGreaterThanOrEqual(1900);+ svc.gather = null;+ await expect(hookCall({ hook: "test", target: hookTarget(svc.address)!, token: "wrong", method: "GET", path: "/v1/health", timeoutMs: 1000 })).rejects.toThrow();++ svc.priced = true;+ expect(await call(svc, "/v1/quote", { account, run: {}, queue: null })).toMatchObject({ allowed: true, amount: 3 });+ expect(await reserve(svc, "press-3")).toMatchObject({ ok: false, code: "price-changed" });+ const held = await reserve(svc, "press-4", { amount: 3, priceVersion: "p1" });+ expect(held).toMatchObject({ ok: true, amount: 3 });++ // A hold whose deadline has passed takes no report.+ svc.holds.get(String(held.holdId))!.closeBy = Date.now() - 1;+ await expect(call(svc, "/v1/settle", { holdId: held.holdId, generationId: "g-late", rows: 1, status: "succeeded" })).rejects.toThrow();+ expect(svc.late).toEqual([{ holdId: held.holdId, generationId: "g-late" }]);+ expect(svc.reportsFor("g-late")).toEqual([]);+ } finally {+ await svc.close();+ }+ });+});++describe("what the harness checks", () => {+ it("names each call a worker makes by its step", () => {+ expect(stepOf("/api/gpu/computer/beat")).toBe("beat");+ expect(stepOf("/api/gpu/computer/claim")).toBe("claim");+ expect(stepOf("/api/gpu/computer/tasks/abc/inputs/0")).toBe("input");+ expect(stepOf("/api/gpu/computer/tasks/abc/outputs/0?offset=0&total=9", { method: "PUT" })).toBe("part");+ expect(stepOf("/api/gpu/computer/tasks/abc/outputs/0")).toBe("other");+ expect(stepOf("/api/gpu/computer/tasks/abc/release")).toBe("release");+ for (const e of ["sent", "queued", "running", "finished", "passes", "gone", "failed"]) expect(stepOf("/api/gpu/computer/tasks/abc/report", { body: JSON.stringify({ event: e }) })).toBe(e);+ expect(stepOf("/api/gpu/computer/tasks/abc/report", { body: JSON.stringify({ event: "comfy-down" }) })).toBe("other");+ });++ it("lets a run show only In line with its place, Working and its result", async () => {+ const at = (g: Record<string, unknown>) => async () => g as never;+ const good = new RunWatch({ a: at({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 2, etaSeconds: 9 } }) });+ await good.look();+ expect(good.problems({ place: 2 })).toEqual([]);++ const cases: [Record<string, unknown>, RegExp][] = [+ [{ status: "failed", error: "Timed out after 45 minutes" }, /a state that isn't/],+ [{ status: "queued", message: "Waiting for a GPU · 2 ahead", queue: { place: 3 } }, /doesn't say In line/],+ [{ status: "running", message: "ComfyUI restarted" }, /doesn't say Working/],+ [{ status: "queued", message: POOL_WORDS.inLine, queue: { place: 3 } }, /place went back from 2 to 3/],+ [{ status: "succeeded", outputs: [] }, /nothing in it/],+ ];+ for (const [g, why] of cases) {+ const w = new RunWatch({ a: at(g) });+ await w.look();+ expect(w.problems({ place: 2 }).join("\n"), JSON.stringify(g)).toMatch(why);+ }+ expect(plainFailure({ status: "failed", error: POOL_WORDS.failed, notCharged: true }, { held: true })).toEqual([]);+ expect(plainFailure({ status: "failed", error: "Can't reach ComfyUI", fix: {} }, { held: true })).toHaveLength(3);+ });+});diff --git a/tests/stubs/next-server.ts b/tests/stubs/next-server.tsnew file mode 100644index 00000000..3f9a69ad--- /dev/null+++ b/tests/stubs/next-server.ts@@ -0,0 +1,4 @@+// next/server for the studio's code run outside Next (tests/helpers/app-process-child.ts), as the tests mock it:+// connection() has no request to wait for, so it resolves at once. Everything else is Next's own.+export * from "next/server.js";+export const connection = async (): Promise<void> => {};