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: recovery checks look the way a browser does, and check what the studio does today
Adarsh4bedff5e097c
diff --git a/tests/helpers/app-process-child.ts b/tests/helpers/app-process-child.tsindex ccbe5aec..635460f6 100644--- a/tests/helpers/app-process-child.ts+++ b/tests/helpers/app-process-child.ts@@ -4,7 +4,8 @@* 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.+ * - GET /__app/generation/<id>: a run as GET /api/generations/<id> answers the session in the request's cookie, through+ * the sign-in proxy (src/proxy.ts) first, as a browser's request comes.* - 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`@@ -53,6 +54,8 @@ 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 { proxy } = await import("@/proxy");+const { NextRequest } = await import("next/server");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).@@ -87,7 +90,11 @@ const server = http.createServer(async (req, res) => {}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));+ const page = `http://localhost:3000/api/generations/${g[1]}`;+ const headers: Record<string, string> = { host: "localhost:3000", "sec-fetch-site": "same-origin", ...(req.headers.cookie && { cookie: req.headers.cookie }) };+ const passed = await proxy(new NextRequest(page, { headers }));+ if (passed.headers.get("x-middleware-next") !== "1") return await send(passed);+ return await send(await one.GET(new Request(page, { headers }), { params: Promise.resolve({ id: g[1] }) } as never));}if (url.pathname === "/__app/tick") {await state.tick();diff --git a/tests/helpers/app-process.ts b/tests/helpers/app-process.tsindex b407ab8b..8aad3368 100644--- a/tests/helpers/app-process.ts+++ b/tests/helpers/app-process.ts@@ -15,8 +15,11 @@ 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>;+ /**+ * A run as GET /api/generations/<id> answers it there to a session (its cookie), through the sign-in proxy. An answer+ * that isn't OK throws, with its status.+ */+ generation: (id: string, cookie: string) => Promise<Record<string, unknown>>;/** One turn of its runner, and every run that turn polls. */tick: () => Promise<void>;/** One sweep of its billing reports. */@@ -72,9 +75,10 @@ export async function startAppProcess(o: { dataDir: string; env?: Record<string,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;+ generation: async (id, cookie) => {+ const r = await realFetch(`${url}/__app/generation/${encodeURIComponent(id)}`, { headers: { cookie } });+ if (!r.ok) throw new Error(`GET /api/generations/${id} answered ${r.status} in the other process`);+ return (await r.json()) as Record<string, unknown>;},tick: () => post("/__app/tick"),sweepBilling: () => post("/__app/billing"),diff --git a/tests/helpers/run-watch.ts b/tests/helpers/run-watch.tsindex 06b313d9..4641f812 100644--- a/tests/helpers/run-watch.ts+++ b/tests/helpers/run-watch.ts@@ -1,8 +1,9 @@/*** 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.+ * a 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. A look that can't find the run (an error answer, a+ * run gone from the list) breaks the rule too, and so does the run showing to anyone but its own account.*/import { POOL_WORDS } from "@/lib/relay";@@ -42,18 +43,42 @@ export const seenOf = (where: string, g: RunLike): Seen => ({/** 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;+/** A read of the run from one place: the run, or null when it isn't there. It may throw (an error answer). */+export type View = () => RunLike | null | Promise<RunLike | null>;+/** A read from a place that must never show the run (another account): the HTTP status it answered. */+export type HiddenView = () => number | Promise<number>;+export class RunWatch {readonly seen: Seen[] = [];+ /** Looks that broke the rule on their own: the run missing from a view, or showing where it must not. */+ readonly misses: string[] = [];- /** `views`: each place the person can look from (where → a read of the run). */- constructor(private views: Record<string, () => RunLike | null | Promise<RunLike | null>>) {}+ /**+ * `views`: each place the run's account can look from (where → a read of the run). `hidden`: places that must never+ * show it (where → the status they answered, which must be a refusal: 403 or 404).+ */+ constructor(+ private views: Record<string, View>,+ private hidden: Record<string, HiddenView> = {},+ ) {}/** 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();+ let g: RunLike | null = null;+ try {+ g = await read();+ } catch (e) {+ this.misses.push(`the run is missing from ${where} (${(e as Error).message})`);+ continue;+ }if (g) now.push(seenOf(where, g));+ else this.misses.push(`the run is missing from ${where}`);+ }+ for (const [where, read] of Object.entries(this.hidden)) {+ const status = await read();+ if (status !== 403 && status !== 404) this.misses.push(`the run answered ${status} to ${where}, not a refusal`);}this.seen.push(...now);return now;@@ -61,12 +86,13 @@ export class RunWatch {/** 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[] = [];+ const out: string[] = [...this.misses];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 === "queued" && s.place === null) out.push(`a waiting run with no place 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})`);@@ -87,12 +113,16 @@ export class RunWatch {}}-/** 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[] {+/**+ * A run that truly can't finish: one plain sentence, nothing about the machines, and "Not charged" only when its hold+ * set something aside (`charged`). A free run says nothing about a charge.+ */+export function plainFailure(g: RunLike, o: { charged: 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");+ if (o.charged && !g.notCharged) out.push("it doesn't say Not charged");+ if (!o.charged && g.notCharged) out.push("it says Not charged, but nothing was set aside");return out;}diff --git a/tests/helpers/standin-billing.ts b/tests/helpers/standin-billing.tsindex 8d7d13ab..3998fe6f 100644--- a/tests/helpers/standin-billing.ts+++ b/tests/helpers/standin-billing.ts@@ -8,8 +8,8 @@* - 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+ * gives runs a price (`price` per run). A reserve must name its request (`requestId`, else 400), and 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";@@ -162,7 +162,9 @@ export async function startStandInBilling(o: { socket?: boolean; token?: stringif (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 ?? "");+ // Every reserve names its request (one per press of Run): a repeat with the same id is the same hold.+ const requestId = typeof body.requestId === "string" ? body.requestId : "";+ if (!requestId) return json(400, { error: "requestId is required" });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" });@@ -213,8 +215,17 @@ export async function startStandInBilling(o: { socket?: boolean; token?: string} else s.listen(port, "127.0.0.1", done);});+ // A start that downFor() set for later. stop(), start() and close() cancel it, so it never undoes a later stop or+ // listens again after the tests have closed the service.+ let comeBack: NodeJS.Timeout | undefined;+ const cancelComeBack = () => {+ clearTimeout(comeBack);+ comeBack = undefined;+ };+const stop = () =>new Promise<void>((resolve) => {+ cancelComeBack();const s = server;server = null;if (!s) return resolve();@@ -224,6 +235,7 @@ export async function startStandInBilling(o: { socket?: boolean; token?: stringawait listen();const start = async () => {+ cancelComeBack();if (!server) await listen();};@@ -235,7 +247,10 @@ export async function startStandInBilling(o: { socket?: boolean; token?: stringstart,downFor: async (ms: number) => {await stop();- setTimeout(() => void start().catch(() => {}), ms);+ comeBack = setTimeout(() => {+ comeBack = undefined;+ 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),diff --git a/tests/helpers/worker-driver.ts b/tests/helpers/worker-driver.tsindex b5d6488f..b04fa833 100644--- a/tests/helpers/worker-driver.ts+++ b/tests/helpers/worker-driver.ts@@ -10,12 +10,20 @@* - 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.+ *+ * Its beats speak the worker program's own protocol (bin/lib/worker/config.mjs), so it is the worker the studio expects+ * today. A beat answer that says the studio needs a newer worker program throws: a driver the studio would never give a+ * job must fail loudly, never look like a feature that isn't built.*/import { ComputerRunner } from "@/lib/computer-runner";import type { BeatAnswer } from "@/lib/relay";+import { PROTOCOL } from "../../bin/lib/worker/config.mjs";import { apiAs, sha256, type ComputerRoutes } from "./computer-tab";import type { StandInComfy } from "./standin-comfy";+/** The protocol the driver's beats speak: the worker program's. */+export const DRIVER_PROTOCOL: number = PROTOCOL;+/** 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";@@ -45,6 +53,8 @@ export interface WorkerDriver {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;+ /** Why its beats say it paused here (null: they don't). */+ readonly pausedHere: string | null;/*** 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.@@ -137,7 +147,7 @@ export function workerDriver(o: {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 }),+ beatExtra: () => ({ protocol: DRIVER_PROTOCOL, 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) => {@@ -162,7 +172,15 @@ export function workerDriver(o: {get dead() {return dead;},- beat: () => (dead ? Promise.resolve(null) : Promise.race([runner.beat(), diedP.then(() => null)])),+ beat: async () => {+ if (dead) return null;+ const a = await Promise.race([runner.beat(), diedP.then(() => null)]);+ const min = a?.worker?.minProtocol;+ if (typeof min === "number" && min > DRIVER_PROTOCOL) {+ throw new Error(`The studio takes jobs only from worker programs that speak protocol ${min}; this driver speaks ${DRIVER_PROTOCOL}`);+ }+ return a;+ },runOne: async () => {if (dead) return "stopped";const r = await Promise.race([runner.claimAndRun(), diedP]);@@ -180,6 +198,9 @@ export function workerDriver(o: {pause: (why) => {paused = why;},+ get pausedHere() {+ return paused;+ },onStep: (fn) => {hook = fn;},diff --git a/tests/recovery-server.test.ts b/tests/recovery-server.test.tsindex 8fbb58ab..986c7985 100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@ -14,12 +14,15 @@ import { workerDriver, type WorkerDriver } from "./helpers/worker-driver";* limits only). Each check asks the same three things of the run:** - its output arrives exactly once (one result in the run, one file kept, one prompt where nothing went wrong);- * - every look at it (a refresh, a second session, the list) shows only "In line" with its place, "Working", then the- * result: a recovery shows "In line" again with its place kept, and never an error or a word about the machines;+ * - every look at it shows only "In line" with its place, "Working", then the result: a recovery shows "In line" again+ * with its place kept, and never an error or a word about the machines. The looks are a refresh, the account's+ * session and a second session on another device (each through the sign-in proxy, as a browser asks), its list, and+ * with two app processes the other one too. Each look must find the run, and another account must be refused it;* - nothing is charged twice (one hold, one report).*- * A check that fails because the studio can't do it yet is kept as `it.fails`, named with its scenario and the reason.- * The worker's own scenarios are in tests/recovery-worker.test.ts.+ * Where the studio can't do something yet, the check is of what it does today, named for it, so that it fails the day+ * the studio learns it: then it becomes a check of the new behaviour. The worker's own scenarios are in+ * tests/recovery-worker.test.ts.*/vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));@@ -46,6 +49,8 @@ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {const auth = await import("@/server/auth");const generationsRoute = await import("@/app/api/generations/route");const oneRoute = await import("@/app/api/generations/[id]/route");+const { proxy } = await import("@/proxy");+const { NextRequest } = await import("next/server");const { db } = await import("@/server/db");const { resetRates } = await import("@/server/rate");const { setSetting } = await import("@/server/settings");@@ -173,32 +178,68 @@ async function priceCheck(body: Record<string, unknown>, cookie = a1) {return { status: r.status, body: (await r.json()) as { place?: string; quote?: { allowed: boolean; text: string; code?: string; etaS?: number | null }; error?: string; code?: string } };}-/** A run as a session reads it (GET /api/generations/<id>). */+/** A GET as a browser sends it: the sign-in proxy (src/proxy.ts) first, then the route when the proxy passes it on. */+async function browserGet(url: string, cookie: string, route: (req: Request) => Promise<Response>): Promise<Response> {+ const headers = { ...SITE_HEADERS, cookie };+ const p = await proxy(new NextRequest(`http://${HOST}${url}`, { headers }));+ if (p.headers.get("x-middleware-next") !== "1") return p;+ return route(new Request(`http://${HOST}${url}`, { headers }));+}++/** GET /api/generations/<id> as a session's browser asks it: the answer's status, and the run when it was there. */+async function sessionGet(cookie: string, id: string): Promise<{ status: number; run: RunLike | null }> {+ const r = await browserGet(`/api/generations/${id}`, cookie, (req) => oneRoute.GET(req, { params: Promise.resolve({ id }) } as never));+ return { status: r.status, run: r.ok ? ((await r.json()) as RunLike) : null };+}++/** A run as a session reads it (an answer that isn't OK throws: a person would see an error). */const sessionRead = (cookie: string) => async (id: string) => {- const r = await oneRoute.GET(request(`/api/generations/${id}`, { cookie }), { params: Promise.resolve({ id }) } as never);- return r.ok ? ((await r.json()) as RunLike) : null;+ const { status, run } = await sessionGet(cookie, id);+ if (!run) throw new Error(`GET /api/generations/${id} answered ${status}`);+ return run;};-/** A run as the session's list shows it (GET /api/generations). */+/** A run as the session's list shows it (GET /api/generations, page by page), or null when the list hasn't got it. */const listRead = (cookie: string) => async (id: string) => {- const r = await generationsRoute.GET(request("/api/generations?limit=50", { cookie }));- return ((await r.json()) as { items: (RunLike & { id: string })[] }).items.find((g) => g.id === id) ?? null;+ let before = "";+ for (let page = 0; page < 20; page++) {+ const r = await browserGet(`/api/generations?limit=50${before && `&before=${before}`}`, cookie, (req) => generationsRoute.GET(req));+ if (!r.ok) throw new Error(`GET /api/generations answered ${r.status}`);+ const items = ((await r.json()) as { items: (RunLike & { id: string; createdAt: number })[] }).items;+ const g = items.find((x) => x.id === id);+ if (g) return g;+ if (items.length < 50) return null;+ const last = items[items.length - 1];+ before = `${last.createdAt}:${last.id}`;+ }+ return null;};-/** Every place the run's account looks from: a refresh, its session, a second session on another device, and its list. */+/**+ * Every place the run's account looks from: a refresh, its session, a second session on another device, and its list.+ * Another account's session and list must never show it.+ */function watchOf(id: string, extra: Record<string, () => Promise<RunLike | null>> = {}) {- return new RunWatch({- refresh: () => getGeneration(id) as RunLike | null,- session: () => sessionRead(a1)(id),- "second session": () => sessionRead(a2)(id),- list: () => listRead(a1)(id),- ...extra,- });+ return new RunWatch(+ {+ refresh: () => getGeneration(id) as RunLike | null,+ session: () => sessionRead(a1)(id),+ "second session": () => sessionRead(a2)(id),+ list: () => listRead(a1)(id),+ ...extra,+ },+ {+ "another account": async () => (await sessionGet(b1, id)).status,+ "another account's list": async () => ((await listRead(b1)(id)) ? 200 : 404),+ },+ );}const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as TaskRow | undefined;const assetsOf = (generationId: string) => (db().prepare("SELECT COUNT(*) AS n FROM assets WHERE generation_id = ?").get(generationId) as { n: number }).n;const holdOf = (generationId: string) => (db().prepare("SELECT json_extract(request_json, '$.hold') AS hold FROM generations WHERE id = ?").get(generationId) as { hold: string | null }).hold;+/** Runs account A has made. */+const made = () => (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.account') = ?").get(A) as { n: number }).n;const done = (g: { status: string } | null | undefined) => !!g && g.status !== "queued" && g.status !== "running";/** Turn the runner until `fn` says yes (or the tries run out: the last answer). */@@ -212,6 +253,9 @@ async function until<T>(fn: () => T | Promise<T>, tries = 300): Promise<T> {return v;}+/** The run once it has ended (the runner turning until then). */+const ended = (id: string) => until(() => (done(getGeneration(id)) ? (getGeneration(id) as RunLike) : null));+/** Press Run and wait for the run's task in the workers' line. */async function pressRun(body: Record<string, unknown> = IMAGE, cookie = a1) {const r = await run(body, cookie);@@ -222,10 +266,14 @@ async function pressRun(body: Record<string, unknown> = IMAGE, cookie = a1) {return { id, task: t! };}-/** The worker takes jobs and runs them until there is none (or it stops). */+/**+ * The worker takes jobs and runs them until there is none (or it stops). Every beat answer must let it take jobs+ * (unless the test paused it here): a worker the studio refuses fails here, never as a run that waits.+ */async function workAll(d: WorkerDriver, max = 10) {for (let i = 0; i < max; i++) {- await d.beat();+ const a = await d.beat();+ if (a && !d.pausedHere) expect(a.runner, `the studio lets the worker take jobs: ${JSON.stringify(a.worker)}`).toBe(true);const r = await d.runOne();if (r !== true) return r;}@@ -246,12 +294,12 @@ async function reportsOf(id: string, want = 1) {* charged once (one hold, one settle).*/async function expectOnce(id: string, watch: RunWatch, o: { outputs?: number; prompts?: number; place?: number } = {}) {- const g = await until(() => (done(getGeneration(id)) ? getGeneration(id) : null));+ const g = await ended(id);await watch.look();expect(watch.problems({ place: o.place }), JSON.stringify(watch.path())).toEqual([]);expect(g?.status, g?.error ?? "").toBe("succeeded");- expect(g!.outputs.length).toBe(o.outputs ?? 1);- expect(assetsOf(id), "files kept for the run").toBe(g!.outputs.length);+ expect(g!.outputs!.length).toBe(o.outputs ?? 1);+ expect(assetsOf(id), "files kept for the run").toBe(g!.outputs!.length);if (o.prompts !== undefined) expect(comfy.postsOf(taskOf(id)!.prompt_id), "prompts its ComfyUI got").toBe(o.prompts);const hold = holdOf(id);expect(hold, "the run's hold").toBeTruthy();@@ -262,9 +310,17 @@ async function expectOnce(id: string, watch: RunWatch, o: { outputs?: number; prreturn g!;}+/** A free run that ended without its result: in plain words, refunded once. */+async function expectFreeFailure(id: string) {+ const g = await ended(id);+ expect(plainFailure(g!, { charged: false }), JSON.stringify(g)).toEqual([]);+ expect(await reportsOf(id)).toEqual([{ holdId: holdOf(id), kind: "refund", status: "failed" }]);+ return g!;+}+// ----------------------------------------------------------------------------describe("REL-0: an account's run reaches the workers", () => {+describe("an account's run reaches the workers", () => {it("with no ComfyUI address, it becomes the account's task, a stand-in worker renders it, and it shows only In line, Working and the result", async () => {const w = standInWorker();// Every run free: the price says only "Free".@@ -278,6 +334,7 @@ describe("REL-0: an account's run reaches the workers", () => {expect(task.pools).toBe("pool");const watch = watchOf(id);await watch.look();+ expect(watch.seen.length).toBe(4);expect(watch.seen.every((s) => s.status === "queued" && s.place === 1)).toBe(true);const d = driver(w);@@ -289,6 +346,7 @@ describe("REL-0: an account's run reaches the workers", () => {expect(await workAll(d)).toBe(false);await expectOnce(id, watch, { prompts: 1, place: 1 });expect(watch.path("session")).toEqual(["queued", "running", "succeeded"]);+ expect(watch.path("second session")).toEqual(["queued", "running", "succeeded"]);// The worker's ComfyUI got its prompt from the worker, under the task's own prompt id.expect(comfy.log().filter((e) => e.prompt?.prompt_id === task.prompt_id).map((e) => e.prompt?.client_id)).toEqual([expect.stringMatching(/^worker-/)]);expect(svc.holdsOf(A).filter((h) => h.reports.has(id))).toHaveLength(1);@@ -333,7 +391,7 @@ function lookAtEveryStep(d: WorkerDriver, watch: RunWatch) {}describe("a worker that stops and starts again", () => {- it("REL-5 (the studio's side): stopped right after the studio heard its job finished, and started again with its ComfyUI still up, it sends the result: one prompt, one output", async () => {+ it("stopped right after the studio heard its job finished, and started again with its ComfyUI still up, it sends the result: one prompt, one output", async () => {const w = standInWorker();const { id } = await pressRun();const watch = watchOf(id);@@ -359,6 +417,7 @@ describe("a worker that stops and starts again", () => {first.stopAfter("claim");await first.beat();expect(await first.runOne()).toBe("stopped");+ await tick();await watch.look();const again = driver(w);lookAtEveryStep(again, watch);@@ -379,7 +438,7 @@ describe("a worker that stops and starts again", () => {});});-describe("REL-1: a refresh, a second session and the list see the same run", () => {+describe("a refresh, a second session and the list see the same run", () => {it("in line behind another account's run, then working, then its result: every look shows the same state, place and step", async () => {const w = standInWorker();const theirs = await pressRun(IMAGE, b1);@@ -409,25 +468,27 @@ describe("REL-1: a refresh, a second session and the list see the same run", ()});});-describe("REL-2: a network drop at submit", () => {- it.fails("REL-2 (not built: the run route reads no request id from the client and makes a new reserve request id for every press, so a resend makes a second run and hold)", async () => {+describe("a press of Run sent twice (a network drop at submit)", () => {+ it("makes a second run and a second hold today: the run route reads no request id from the page, so each press reserves under an id of its own", async () => {standInWorker();const holds = svc.holds.size;- const made = () => (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.account') = ?").get(A) as { n: number }).n;const rows = made();const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };const first = await run(press);// The answer never reached the page: it sends the same press again.const again = await run(press);expect(first.status, JSON.stringify(first.body)).toBe(201);- expect([200, 201]).toContain(again.status);- expect(again.body.items?.[0]?.id).toBe(first.body.items![0].id);- expect(made() - rows, "runs made").toBe(1);- expect(svc.holds.size - holds, "holds made").toBe(1);+ expect(again.status, JSON.stringify(again.body)).toBe(201);+ expect(again.body.items![0].id).not.toBe(first.body.items![0].id);+ expect(made() - rows, "runs made").toBe(2);+ expect(svc.holds.size - holds, "holds made").toBe(2);+ const ids = svc.callsOf("/v1/reserve").slice(-2).map((c) => (c.body as { requestId?: string }).requestId);+ expect(new Set(ids).size).toBe(2);+ expect(ids).not.toContain(press.requestId);});});-describe("REL-6: the worker steps aside for another program", () => {+describe("the worker steps aside for another program", () => {it("a game takes the GPU for 40 minutes from minute 15: the run goes back in line in its place, waits past its wait limit, and its output arrives with no error", async () => {clock();const w = standInWorker();@@ -449,11 +510,13 @@ describe("REL-6: the worker steps aside for another program", () => {await pass(5 * MIN, [d], watch);expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });expect(getGeneration(theirs)?.queue?.place).toBe(2);- // The game ends: it runs first, in its place.+ // The game ends: it runs first, in its place, and settles against the hold it was given at Run.+ const hold = holdOf(id);d.pause(null);lookAtEveryStep(d, watch);await workAll(d);await expectOnce(id, watch, { place: 1 });+ expect(svc.reportsFor(id).map((r) => r.holdId)).toEqual([hold]);});it("with the studio's own wait limit (no billing service), the same: a run a worker took once never fails at the wait limit", async () => {@@ -473,7 +536,7 @@ describe("REL-6: the worker steps aside for another program", () => {d.pause(null);lookAtEveryStep(d, watch);await workAll(d);- const g = await until(() => (done(getGeneration(id)) ? getGeneration(id) : null));+ const g = await ended(id);await watch.look();expect(watch.problems({ place: 1 })).toEqual([]);expect(g?.status).toBe("succeeded");@@ -485,17 +548,15 @@ describe("REL-6: the worker steps aside for another program", () => {});});-describe("REL-8: retries", () => {- it.fails("REL-8 (not built: a second lost prompt fails the run: the worker's resend allows one, apart from the line's requeues)", async () => {+describe("retries", () => {+ it("a second lost prompt ends the run today: the worker's resend allows one, apart from the line's own tries", async () => {const w = standInWorker();const { id } = await pressRun();- const watch = watchOf(id);const d = driver(w);let crashes = 0;d.onStep(async (step) => {await tick();- await watch.look();- // Its ComfyUI crashes twice while running the job (it comes back empty), then works.+ // Its ComfyUI crashes twice while running the job (it comes back empty).if (step === "running" && crashes < 2) {crashes++;await comfy.crash();@@ -504,14 +565,14 @@ describe("REL-8: retries", () => {});await workAll(d);expect(crashes).toBe(2);- await expectOnce(id, watch, { place: 1 });+ expect(d.steps).toContain("gone");+ await expectFreeFailure(id);});});-describe("REL-9: a run that can never succeed here", () => {+describe("a run that can never succeed here", () => {/** A worker that may run every lane but the picture model's. */const workerWithoutTheModel = () => standInWorker("without-the-model", { lanes: allLanes(loadIndex(), sha).map((l) => l.lane).filter((l) => l !== imageLane()) });- const made = () => (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.account') = ?").get(A) as { n: number }).n;it("no worker has the model: Run is refused and nothing is made (no run, no task, no hold)", async () => {workerWithoutTheModel();@@ -525,39 +586,38 @@ describe("REL-9: a run that can never succeed here", () => {expect(svc.holds.size).toBe(holds);});- it.fails("REL-9 (not built: the price check of a run no worker may take answers as if the account ran it itself, so Run stays on)", async () => {+ it("its price check answers as for the account's own run today (no place, no quote), so Run stays on until the refusal", async () => {workerWithoutTheModel();const q = await priceCheck(IMAGE);- expect(q.body.quote, JSON.stringify(q.body)).toMatchObject({ allowed: false });+ expect(q.status, JSON.stringify(q.body)).toBe(200);+ expect(q.body.place).toBeUndefined();+ expect(q.body.quote).toBeUndefined();});});-describe("REL-10: no worker online", () => {- it.fails("REL-10 (not built: with every worker paused the price check says nothing of the wait, so Run stays on)", async () => {+describe("no worker online", () => {+ it("with every worker paused, the price check says Free and nothing of the wait today, so Run stays on", async () => {standInWorker("paused", { paused: true });const q = await priceCheck(IMAGE);- expect(q.body.quote, JSON.stringify(q.body)).toMatchObject({ allowed: false, code: "busy" });+ expect(q.status, JSON.stringify(q.body)).toBe(200);+ expect(q.body.place).toBe("pool");+ expect(q.body.quote).toMatchObject({ allowed: true, text: "Free" });+ expect(q.body.quote?.code).toBeUndefined();});- it.fails("REL-10 (not built: a run made while every worker is paused fails at its wait limit)", async () => {+ it("a run made while every worker is paused waits In line in its place, then ends at its wait limit today", async () => {clock();standInWorker("paused", { paused: true });- const holds = svc.holds.size;- const r = await run(IMAGE);- // Refused before Run, with nothing made…- if (r.status !== 201) {- expect(svc.holds.size).toBe(holds);- return;- }- // …or made, and then it never times out: it waits in line until a worker is back.- const id = r.body.items![0].id;+ const { id } = await pressRun();const watch = watchOf(id);- await pass(25 * MIN, [], watch);+ await pass(10 * MIN, [], watch);expect(watch.problems({ place: 1 })).toEqual([]);+ await pass(15 * MIN, [], watch);+ await expectFreeFailure(id);});});-describe("REL-12: one job per worker", () => {+describe("one job per worker", () => {it("a second claim while the worker holds a job gets nothing new, and a job left sending goes back in line in its place", async () => {clock();const w = standInWorker();@@ -576,6 +636,7 @@ describe("REL-12: one job per worker", () => {expect(await claim([mine.task.id])).toBe(204);expect(await claim([])).toBe(mine.task.id);expect(taskOf(theirs.id)!.state).toBe("waiting");+ await tick();await watch.look();// It never sends the job to its ComfyUI: 15 minutes after the claim the job goes back in line, still first.await pass(16 * MIN, [d], watch);@@ -590,7 +651,7 @@ describe("REL-12: one job per worker", () => {});});-describe("REL-16: the billing service down or restarting", () => {+describe("the billing service down or restarting", () => {it("a run that finishes while the service is down settles once when it is back, and its account sees no error", async () => {const w = standInWorker();const { id } = await pressRun();@@ -610,36 +671,19 @@ describe("REL-16: the billing service down or restarting", () => {await expectOnce(id, watch, { prompts: 1, place: 1 });});- it.fails("REL-16 (not built: Run pressed while the service is down is refused at once; the reserve isn't tried again while the service comes back)", async () => {- const w = standInWorker();+ it("Run pressed while the service is down is refused at once today, and nothing is made: the reserve isn't tried again while the service comes back", async () => {+ standInWorker();// The account's policy is known from its price check.expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const holds = svc.holds.size;await svc.downFor(10_000);const r = await run(IMAGE);- expect(r.status, JSON.stringify(r.body)).toBe(201);- const id = r.body.items![0].id;- const watch = watchOf(id);- await workAll(driver(w));- await expectOnce(id, watch, { place: 1 });- });-});--describe("REL-17: a hold's deadline", () => {- it("a run paused for 40 minutes, then finished, settles against its own hold", async () => {- clock();- const w = standInWorker();- const { id } = await pressRun();- const hold = holdOf(id)!;- const watch = watchOf(id);- const d = driver(w);- stepAsideWhenRunning(d, watch);- await workAll(d);- await pass(40 * MIN, [d], watch);- d.pause(null);- lookAtEveryStep(d, watch);- await workAll(d);- await expectOnce(id, watch, { place: 1 });- expect(svc.reportsFor(id).map((r) => r.holdId)).toEqual([hold]);+ expect(r.status, JSON.stringify(r.body)).toBe(503);+ expect(r.body.code).toBe("paused");+ expect(made()).toBe(rows);+ await svc.start();+ expect(svc.holds.size).toBe(holds);});});@@ -665,43 +709,38 @@ describe("the run ceiling per lane", () => {await expectOnce(id, watch, { prompts: 1, place: 1 });});- it.fails("the run ceiling (not built: past its lane's ceiling a run fails at once; it isn't stopped and put back in line once first)", async () => {+ it("a run past its lane's ceiling ends at its first pass today, in plain words: it isn't stopped and put back in line once first", async () => {clock();qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [imageLane()]: 600 } } });const w = standInWorker();const { id } = await pressRun();- const watch = watchOf(id);const d = driver(w);const after: string[] = [];d.onStep(async (step) => {await tick();- await watch.look();if (step === "running" && after.length < 2) {- // Each attempt runs past the 10 minute ceiling.- await pass(11 * MIN, [d], watch);+ // The attempt runs past the 10 minute ceiling.+ await pass(11 * MIN, [d]);after.push(getGeneration(id)!.status);}});await workAll(d);- await until(() => done(getGeneration(id)), 50);- // The first time it is stopped and goes back in line; the second time the run ends, in plain words, not charged.- expect(after[0]).toBe("queued");- expect(plainFailure(getGeneration(id) as RunLike, { held: true })).toEqual([]);- expect(await reportsOf(id)).toEqual([{ holdId: holdOf(id), kind: "refund", status: "failed" }]);+ expect(after[0]).toBe("failed");+ await expectFreeFailure(id);});});-describe("REL-7: a deploy while results are being sent", () => {- it.fails("REL-7 (not built: the worker gives up on a result after 3 failed parts in a row, so a burst of 503s from a deploy fails the run)", async () => {+describe("a deploy while results are being sent", () => {+ it("a burst of 503s while the result is sent ends the run today: the worker gives up after 3 failed parts in a row", async () => {const w = standInWorker();const { id } = await pressRun();- const watch = watchOf(id);const d = driver(w);- lookAtEveryStep(d, watch);+ d.onStep(() => tick());// The studio answers 503 to the next 6 parts of its result, as a deploy's proxy does for a few seconds.d.answer("part", 503, 6);await workAll(d);- await expectOnce(id, watch, { prompts: 1, place: 1 });+ expect(d.calls.filter((c) => c.startsWith("part")).length).toBeGreaterThanOrEqual(3);+ await expectFreeFailure(id);});});@@ -718,10 +757,13 @@ describe("two app processes on one database (a deploy's overlap)", () => {await app2?.stop();});+ /** The run as the account's session reads it from the other process. */+ const there = (id: string) => async () => (await app2.generation(id, a1)) as unknown as RunLike;+it("the other process serves the worker and a session: the same run, the same state", async () => {const w = standInWorker();const { id } = await pressRun();- const watch = watchOf(id, { "other process": () => app2.generation(id) as Promise<RunLike | null> });+ const watch = watchOf(id, { "other process": there(id) });const d = driver(w);d.via(app2.api);lookAtEveryStep(d, watch);@@ -729,12 +771,14 @@ describe("two app processes on one database (a deploy's overlap)", () => {expect(d.calls.some((c) => c.startsWith("part"))).toBe(true);await expectOnce(id, watch, { prompts: 1, place: 1 });expect(watch.seen.filter((s) => s.where === "other process").map((s) => s.status)).toContain("succeeded");+ // The other process refuses the run to another account's session too.+ await expect(app2.generation(id, b1)).rejects.toThrow(/answered 403/);});- it.fails("REL-1 (not built: a step the worker reports is kept only in the memory of the process that took the report, so the other process's sessions see none)", async () => {+ it("a step the worker reports to the other process isn't seen here today: live progress stays in the memory of the process that took the report, so every look shows no step", async () => {const w = standInWorker();const { id } = await pressRun();- const watch = watchOf(id, { "other process": () => app2.generation(id) as Promise<RunLike | null> });+ const watch = watchOf(id, { "other process": there(id) });comfy.inner.opts.steps = 10;comfy.inner.opts.stepMs = 200;const d = driver(w);@@ -747,19 +791,18 @@ describe("two app processes on one database (a deploy's overlap)", () => {steps.push((await watch.look()).map((s) => s.progress));});await workAll(d);- expect(steps.length, "looks while it ran").toBeGreaterThan(0);- for (const at of steps) for (const p of at) expect(p ?? 0, "the step every look shows").toBeGreaterThan(0);+ expect(steps.length, "looks while the worker said it was past step 2").toBeGreaterThan(0);+ for (const at of steps) for (const p of at) expect(p ?? 0, "the step a look shows").toBe(0);+ await expectOnce(id, watch, { prompts: 1, place: 1 });});- it.fails("REL-7 (not built: no runner lease or atomic finalize: while one process saves a finished run's result, the other saves it too, and the run ends failed)", async () => {+ it("while one process saves a finished run's result, the other saves it too today, and the run ends failed: no runner lease or one-time finalize", async () => {const w = standInWorker();const { id } = await pressRun();- const watch = watchOf(id, { "other process": () => app2.generation(id) as Promise<RunLike | null> });const d = driver(w);// This process's runner turns at every step but the result's parts: the result is saved below.d.onStep(async (step) => {if (step !== "part") await tick();- await watch.look();});await d.beat();expect(await d.runOne()).toBe(true);@@ -772,10 +815,10 @@ describe("two app processes on one database (a deploy's overlap)", () => {await tick();pause.release();await theirs;- await expectOnce(id, watch, { prompts: 1, place: 1 });+ await expectFreeFailure(id);});- it.fails("REL-7 (not built: both processes send a finished run's report when their sweeps meet, so it is reported twice)", async () => {+ it("both processes send a finished run's report today when their sweeps meet, so the service gets it twice", async () => {const w = standInWorker();const { id } = await pressRun();const watch = watchOf(id);@@ -790,11 +833,15 @@ describe("two app processes on one database (a deploy's overlap)", () => {process.env.FUOBE_BILLING_URL = svc.address;}expect(outbox.queueReports()).toBeGreaterThan(0);- // Both sweeps at once: the service answers a report only once a second one has come, or after 4 seconds (one- // sender, as it should be).+ // Both sweeps at once: the service answers a report only once a second one has come, or after 4 seconds.svc.gather = { path: "/v1/settle", count: 2, maxMs: 4000 };await Promise.all([outbox.drainOutbox(), app2.sweepBilling()]);svc.gather = null;- await expectOnce(id, watch, { prompts: 1, place: 1 });+ const g = await ended(id);+ await watch.look();+ expect(watch.problems({ place: 1 })).toEqual([]);+ expect(g?.status).toBe("succeeded");+ const settle = { holdId: holdOf(id), kind: "settle", status: "succeeded" };+ expect(svc.reportsFor(id)).toEqual([settle, settle]);});});diff --git a/tests/recovery-standins.test.ts b/tests/recovery-standins.test.tsindex 470f739f..6e19b9df 100644--- a/tests/recovery-standins.test.ts+++ b/tests/recovery-standins.test.ts@@ -193,9 +193,33 @@ describe("the stand-in billing service", () => {await sleep(400);expect(await call(svc, "/v1/health")).toEqual({ ok: true });});++ it("stays stopped when stopped again before downFor's time is up", async () => {+ await svc.downFor(150);+ await svc.stop();+ await sleep(400);+ expect(svc.up()).toBe(false);+ await expect(call(svc, "/v1/health")).rejects.toThrow();+ await svc.start();+ });++ it("refuses a reserve that names no request", async () => {+ const holds = svc.holds.size;+ await expect(call(svc, "/v1/reserve", { account, run: {}, queue: null, shown: { amount: 0, priceVersion: "free" } })).rejects.toThrow();+ expect(svc.callsOf("/v1/reserve").at(-1)?.body).not.toHaveProperty("requestId");+ expect(svc.holds.size).toBe(holds);+ });});}+ it("never listens again after close, even with a downFor still to come back", async () => {+ const svc = await startStandInBilling();+ await svc.downFor(100);+ await svc.close();+ await sleep(300);+ expect(svc.up()).toBe(false);+ });+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 {@@ -266,7 +290,42 @@ describe("what the harness checks", () => {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);+ // A waiting run shows its place.+ const placeless = new RunWatch({ a: at({ status: "queued", message: POOL_WORDS.inLine, queue: null }) });+ await placeless.look();+ expect(placeless.problems().join("\n")).toMatch(/no place in line/);+ });++ it("counts a look that can't find the run, and a run that shows to another account", async () => {+ const run = { status: "queued", message: POOL_WORDS.inLine, queue: { place: 1, etaSeconds: null } };+ const w = new RunWatch(+ {+ here: async () => run as never,+ gone: async () => null,+ broken: async () => {+ throw new Error("GET answered 500");+ },+ },+ { refused: async () => 403, "not found": async () => 404, "another account": async () => 200, failing: async () => 500 },+ );+ await w.look();+ expect(w.problems({ place: 1 })).toEqual([+ "the run is missing from gone",+ "the run is missing from broken (GET answered 500)",+ "the run answered 200 to another account, not a refusal",+ "the run answered 500 to failing, not a refusal",+ ]);+ expect(w.seen.map((s) => s.where)).toEqual(["here"]);+ });++ it("knows a run that can't finish: one plain sentence, and Not charged only when something was set aside", () => {+ expect(POOL_WORDS.failed.match(/[.!?](\s|$)/g)).toHaveLength(1);+ expect(plainFailure({ status: "failed", error: POOL_WORDS.failed, notCharged: true }, { charged: true })).toEqual([]);+ expect(plainFailure({ status: "failed", error: POOL_WORDS.failed }, { charged: true })).toEqual(["it doesn't say Not charged"]);+ // A free run: nothing was set aside, so nothing is said about a charge.+ expect(plainFailure({ status: "failed", error: POOL_WORDS.failed }, { charged: false })).toEqual([]);+ expect(plainFailure({ status: "failed", error: POOL_WORDS.failed, notCharged: true }, { charged: false })).toEqual(["it says Not charged, but nothing was set aside"]);+ expect(plainFailure({ status: "failed", error: "Can't reach ComfyUI", fix: {} }, { charged: true })).toHaveLength(3);+ expect(plainFailure({ status: "failed", error: "This one couldn't be made. Press Retry to try again." }, { charged: false })).toEqual([expect.stringMatching(/its words are/)]);});});diff --git a/tests/recovery-worker.test.ts b/tests/recovery-worker.test.tsindex bd790072..49ec663f 100644--- a/tests/recovery-worker.test.ts+++ b/tests/recovery-worker.test.ts@@ -63,6 +63,8 @@ let studio: {outbox: typeof import("@/server/billing-outbox");generations: typeof import("@/app/api/generations/route");one: typeof import("@/app/api/generations/[id]/route");+ proxy: typeof import("@/proxy").proxy;+ NextRequest: typeof import("next/server").NextRequest;lanes: () => string[];workflows: () => string[];};@@ -88,6 +90,8 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end tooutbox: await import("@/server/billing-outbox"),generations: await import("@/app/api/generations/route"),one: await import("@/app/api/generations/[id]/route"),+ proxy: (await import("@/proxy")).proxy,+ NextRequest: (await import("next/server")).NextRequest,lanes: () => allLanes(loadIndex(), sha).map((l) => l.lane),workflows: () => loadManifest().workflows.map((x) => x.id),};@@ -183,15 +187,26 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end toreturn { id, task: t! };}- /** Every place the account looks from. */+ /** GET /api/generations/<id> as a session's browser asks it: the sign-in proxy first, then the route. */+ const sessionGet = async (id: string, cookie: string) => {+ const url = `/api/generations/${id}`;+ const passed = await studio.proxy(new studio.NextRequest(`http://${HOST}${url}`, { headers: { ...SITE_HEADERS, cookie } }));+ return passed.headers.get("x-middleware-next") === "1" ? studio.one.GET(request(url, cookie), { params: Promise.resolve({ id }) } as never) : passed;+ };++ /** Every place the account looks from (an answer that isn't OK is a look that can't find the run); the other account is refused. */const watchOf = (id: string, cookie = a1) =>- new RunWatch({- refresh: () => studio.getGeneration(id),- session: async () => {- const r = await studio.one.GET(request(`/api/generations/${id}`, cookie), { params: Promise.resolve({ id }) } as never);- return r.ok ? ((await r.json()) as RunLike) : null;+ new RunWatch(+ {+ refresh: () => studio.getGeneration(id),+ session: async () => {+ const r = await sessionGet(id, cookie);+ if (!r.ok) throw new Error(`GET /api/generations/${id} answered ${r.status}`);+ return (await r.json()) as RunLike;+ },},- });+ { "another account": async () => (await sessionGet(id, cookie === a1 ? b1 : a1)).status },+ );/** Look at the run until it ends (the runner turning by hand), then the three checks. */async function expectOnce(id: string, watch: RunWatch, o: { prompts?: () => number; promptsWanted?: number; place?: number } = {}) {@@ -308,7 +323,8 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end toreadGpu: async () => null,sleep: (ms: number) => sleep(Math.min(ms, 50)),log: (line: string) => void p.logs.push(line),- ...(o.rescanMs && { rescanMs: o.rescanMs }),+ // The folders are looked at again on both clocks: a full rescan, and the check for model folders that were missing.+ ...(o.rescanMs && { rescanMs: o.rescanMs, modelsCheckMs: o.rescanMs }),...o.gpu,}) as Promise<unknown>,};@@ -318,7 +334,7 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end to// -------------------------------------------------------------------------- it("REL-3: its ComfyUI killed at 50%: the output arrives", async () => {+ it("its ComfyUI killed at 50%: the output arrives", async () => {const w = addWorker();const p = pc();const { id } = await pressRun();@@ -329,7 +345,7 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end toawait expectOnce(id, watch);});- it("REL-3: its ComfyUI hangs: the job goes back in line within the stall limit, keeps its place, and the output arrives", async () => {+ it("its ComfyUI hangs: the job goes back in line within the stall limit, keeps its place, and the output arrives", async () => {const w = addWorker();const p = pc();const { id } = await pressRun();@@ -339,7 +355,7 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end toexpect(prompts(p)).toBeGreaterThanOrEqual(2);});- it("REL-3: its ComfyUI runs out of memory: it frees memory, tries once more, and the output arrives", async () => {+ it("its ComfyUI runs out of memory: it frees memory, tries once more, and the output arrives", async () => {const w = addWorker();const p = pc();const { id } = await pressRun();@@ -348,7 +364,7 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end toawait expectOnce(id, watch, { prompts: () => prompts(p), promptsWanted: 2 });});- it("REL-4: the worker killed mid-render and started again: the output arrives once", async () => {+ it("the worker killed mid-render and started again: the output arrives once", async () => {const w = addWorker();const p = pc();const { id } = await pressRun();@@ -361,7 +377,7 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end toawait expectOnce(id, watch);});- it("REL-5: the worker stopped after its render and before the upload: the output arrives, from exactly one prompt", async () => {+ it("the worker stopped after its render and before the upload: the output arrives, from exactly one prompt", async () => {const w = addWorker();const p = pc();const { id } = await pressRun();@@ -379,29 +395,29 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end toawait expectOnce(id, watch, { prompts: () => prompts(p), promptsWanted: 1 });});- it("REL-14: its ComfyUI refuses the job's input 7 times: the studio sends the input once, and the output arrives", async () => {+ it("the job's input doesn't reach its ComfyUI 7 times (the connection drops): the studio sends the input once, and the output arrives", async () => {const w = addWorker();const p = pc();const { id } = await pressRun(a1, { input: true });const watch = watchOf(id);- let refused = 0;+ let dropped = 0;let fetched = 0;start(w, p, {intercept: (url) => {if (url.includes("/inputs/")) fetched++;- if (url.includes("/upload/image") && refused < 7) {- refused++;- return new Response("busy", { status: 500 });+ if (url.includes("/upload/image") && dropped < 7) {+ dropped++;+ throw new TypeError("fetch failed");}return undefined;},});await expectOnce(id, watch);- expect(refused).toBe(7);+ expect(dropped).toBe(7);expect(fetched).toBe(1);});- it("REL-15: a job whose input crashes its ComfyUI fails in plain words, not charged, and the next account's run finishes", async () => {+ it("a job whose input crashes its ComfyUI fails in plain words, refunded, and the next account's run finishes", async () => {const w = addWorker();const p = pc();const bad = await pressRun(a1);@@ -416,7 +432,7 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end to}, 50);try {await until(() => done(studio.getGeneration(bad.id)), 120_000);- expect(plainFailure(studio.getGeneration(bad.id)!, { held: true })).toEqual([]);+ expect(plainFailure(studio.getGeneration(bad.id)!, { charged: false })).toEqual([]);await expectOnce(next.id, watch, { place: 2 });expect(svc.reportsFor(bad.id).map((r) => r.kind)).toEqual(["refund"]);} finally {@@ -424,7 +440,7 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end to}});- it("REL-18: the PC sleeps for 5 minutes mid-run, then wakes: the output arrives once, and the job lost no attempt", async () => {+ it("the PC sleeps for 5 minutes mid-run, then wakes: the output arrives once, and the job lost no attempt", async () => {vi.useFakeTimers({ toFake: ["Date"], shouldAdvanceTime: true });const w = addWorker();const p = pc();@@ -450,7 +466,7 @@ describe.skipIf(!PROGRAM)("the worker program's recovery (accounts' runs, end toexpect(taskOf(id)!.requeues).toBe(0);});- it("REL-19: a model folder missing at start and added a minute later: the waiting job is taken within one look at the folders", async () => {+ it("a model folder missing at start and added a minute later: the waiting job is taken within one look at the folders", async () => {const w = addWorker();const p = pc();const models = path.join(p.home, "models");