Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Your computer's ComfyUI: the server keeps each job for the person's own tab

Adarsh5b71cfa34c23
diff --git a/src/app/api/account/gpu/route.ts b/src/app/api/account/gpu/route.ts
index 7ad5a8e7..d6641224 100644
--- a/src/app/api/account/gpu/route.ts
+++ b/src/app/api/account/gpu/route.ts
@@ -1,29 +1,49 @@
import { connection } from "next/server";
import { z } from "zod";
import { checkGpuAddress, GpuError, testGpu } from "@/server/account-gpu";
-import { accountGpu, requestAccount, setAccountGpu } from "@/server/auth";
+import { accountGpu, gpuLink, requestAccount, setAccountGpu } from "@/server/auth";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "@/server/account-files";
import { clearAccountLoras } from "@/server/account-loras";
+import { forgetComputer, runnerFacts } from "@/server/computer/tasks";
+import { dropSnapshots } from "@/server/gpu/snapshots";
import { hit } from "@/server/rate";
/**
- * "Your GPU" (public sign-up): the account's own ComfyUI, where its runs go. GET says what is
- * connected (never the token); PUT checks the address and asks the ComfyUI for /system_stats, then
- * saves it (`?test=1`: check only); DELETE disconnects. Accounts only: the owner's ComfyUI is in Settings.
+ * "Your GPU" (public sign-up): the account's own ComfyUI, where its runs go. Either the ComfyUI on the person's own
+ * computer, which their Fuobe tab runs ({ mode: "computer" }), or one at a public address (a link). GET says what is
+ * connected (never the token; for a computer, what its tab last said about it); PUT connects: a computer at once, a
+ * link after checking the address and asking the ComfyUI for /system_stats (`?test=1`: check only); DELETE
+ * disconnects (a computer's runs still waiting stop). Accounts only: the owner's ComfyUI is in Settings.
*/
const account = async (request: Request) => requestAccount(request);
const notAccount = () => Response.json({ error: "Your GPU is for accounts. The studio's own ComfyUI is in Settings → Open-source engine." }, { status: 400 });
+/** What a computer's tab last said: its GPU, memory, ComfyUI version and port, and whether it is open now. */
+function computerView(id: string) {
+ const f = runnerFacts(`acct:${id}`);
+ return {
+ mode: "computer" as const,
+ online: !!f?.online,
+ ...(f?.device && { device: f.device }),
+ ...(f?.vramBytes && { vramBytes: f.vramBytes }),
+ ...(f?.version && { version: f.version }),
+ ...(f?.port && { port: f.port }),
+ ...(f?.cors && { cors: f.cors }),
+ };
+}
+
export async function GET(request: Request) {
await connection();
const a = await account(request);
if (!a) return notAccount();
const gpu = accountGpu(a.id);
- return Response.json({ gpu: gpu ? { url: gpu.url, hasToken: !!gpu.token } : null });
+ if (gpu?.mode === "computer") return Response.json({ gpu: computerView(a.id) });
+ const link = gpuLink(gpu);
+ return Response.json({ gpu: link ? { mode: "link", url: link.url, hasToken: !!link.token } : null });
}
-const Body = z.object({ url: z.string().min(1).max(500), token: z.string().max(500).optional() });
+const Body = z.union([z.object({ mode: z.literal("computer") }).strict(), z.object({ mode: z.literal("link").optional(), url: z.string().min(1).max(500), token: z.string().max(500).optional() })]);
export async function PUT(request: Request) {
const a = await account(request);
@@ -33,17 +53,30 @@ export async function PUT(request: Request) {
if (!rate.ok) return Response.json({ error: ACCOUNT_MESSAGES.gpuChecks }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Enter your ComfyUI's address" }, { status: 400 });
+ const before = accountGpu(a.id);
+ // The ComfyUI on this computer: nothing for the server to reach, so nothing to check here (the tab found it).
+ if ("mode" in parsed.data && parsed.data.mode === "computer") {
+ if (before?.mode !== "computer") {
+ setAccountGpu(a.id, { mode: "computer" });
+ clearAccountLoras(a.id);
+ dropSnapshots(`acct:${a.id}`);
+ }
+ return Response.json({ gpu: computerView(a.id) });
+ }
+ const body = parsed.data as { url: string; token?: string };
try {
- const url = await checkGpuAddress(parsed.data.url);
+ const url = await checkGpuAddress(body.url);
// A token left empty keeps the saved one when the address is the same.
- const saved = accountGpu(a.id);
- const token = parsed.data.token?.trim() || (saved?.url === url ? saved.token : undefined);
+ const saved = gpuLink(before);
+ const token = body.token?.trim() || (saved?.url === url ? saved.token : undefined);
const info = await testGpu({ url, token });
if (new URL(request.url).searchParams.get("test") !== "1") {
setAccountGpu(a.id, { url, token });
clearAccountLoras(a.id);
+ // Runs waiting for a computer stop: they go to the link from now on.
+ if (before?.mode === "computer") forgetComputer(`acct:${a.id}`);
}
- return Response.json({ gpu: { url, hasToken: !!token }, info });
+ return Response.json({ gpu: { mode: "link", url, hasToken: !!token }, info });
} catch (e) {
if (e instanceof GpuError) return Response.json({ error: e.message }, { status: 422 });
throw e;
@@ -55,5 +88,6 @@ export async function DELETE(request: Request) {
if (!a) return notAccount();
setAccountGpu(a.id, null);
clearAccountLoras(a.id);
+ forgetComputer(`acct:${a.id}`);
return Response.json({ gpu: null });
}
diff --git a/src/app/api/gpu/check/route.ts b/src/app/api/gpu/check/route.ts
index 14caca94..5fc1a83b 100644
--- a/src/app/api/gpu/check/route.ts
+++ b/src/app/api/gpu/check/route.ts
@@ -21,6 +21,8 @@ export async function POST(request: Request) {
const error = t.reason === "refused" ? "Fuobe can't use this address. Connect your own ComfyUI." : "Connect your GPU first.";
return Response.json({ error, code: "connect-gpu" }, { status: 409 });
}
+ // The ComfyUI on the person's own computer: their Fuobe tab checks it and sends what it found (PUT /api/gpu/inventory).
+ if (t.kind === "computer") return Response.json({ error: "Your ComfyUI is on your computer: Fuobe checks it from this browser.", code: "browser" }, { status: 409 });
const wait = checkWait(t);
if (wait > 0 && !probeRunning(t)) {
return Response.json({ error: `Checked a moment ago. Try again in ${wait} s.`, wait }, { status: 429, headers: { "Retry-After": String(wait) } });
diff --git a/src/app/api/gpu/computer/beat/route.ts b/src/app/api/gpu/computer/beat/route.ts
new file mode 100644
index 00000000..2c491972
--- /dev/null
+++ b/src/app/api/gpu/computer/beat/route.ts
@@ -0,0 +1,33 @@
+import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { beat, type BeatInput } from "@/server/computer/tasks";
+
+/** What a beat may weigh: the facts, with up to 20,000 LoRA names. */
+const MAX_BYTES = 3 * 2 ** 20;
+
+/**
+ * "Use the ComfyUI on this computer": the person's Fuobe tab says it is there, every few seconds. The first computer to
+ * beat runs the waiting jobs (another takes over when this one goes quiet for a minute, or when the person asks); the
+ * answer says whether it does, how many wait, and which prompts to take off its ComfyUI. It may send its ComfyUI's
+ * facts (the GPU, memory, version, LoRA names), never its command line.
+ */
+export async function POST(request: Request) {
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const limited = rateOf(principal, "beat", 30);
+ if (limited) return limited;
+ const text = await request.text().catch(() => "");
+ if (text.length > MAX_BYTES) return Response.json({ error: "Too much at once" }, { status: 413 });
+ let body: BeatInput;
+ try {
+ body = JSON.parse(text) as BeatInput;
+ } catch {
+ return Response.json({ error: "Send JSON" }, { status: 400 });
+ }
+ try {
+ return Response.json(beat(principal, { device: String(body?.device ?? ""), port: body?.port, facts: body?.facts, running: Array.isArray(body?.running) ? body.running : [], takeover: body?.takeover === true, stopped: Array.isArray(body?.stopped) ? body.stopped : [] }), {
+ headers: { "Cache-Control": "no-store" },
+ });
+ } catch (e) {
+ return relayAnswer(e);
+ }
+}
diff --git a/src/app/api/gpu/computer/claim/route.ts b/src/app/api/gpu/computer/claim/route.ts
new file mode 100644
index 00000000..875bcf5a
--- /dev/null
+++ b/src/app/api/gpu/computer/claim/route.ts
@@ -0,0 +1,24 @@
+import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { claim } from "@/server/computer/tasks";
+
+/**
+ * The person's Fuobe tab asks for a job to run on its ComfyUI: one it started before and lost track of (a reload), or,
+ * when this computer runs the waiting jobs, the oldest one. The answer is the graph exactly as the server built it, the
+ * inputs to send under the names it chose, the prompt id it minted, and a new token for every call about it. No job:
+ * 204.
+ */
+export async function POST(request: Request) {
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const limited = rateOf(principal, "claim", 60);
+ if (limited) return limited;
+ const body = (await request.json().catch(() => null)) as { device?: unknown; running?: unknown } | null;
+ const running = Array.isArray(body?.running) ? body.running.filter((x): x is string => typeof x === "string").slice(0, 32) : [];
+ try {
+ const task = claim(principal, String(body?.device ?? ""), running);
+ if (!task) return new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } });
+ return Response.json({ task }, { headers: { "Cache-Control": "no-store" } });
+ } catch (e) {
+ return relayAnswer(e);
+ }
+}
diff --git a/src/app/api/gpu/computer/tasks/[id]/inputs/[n]/route.ts b/src/app/api/gpu/computer/tasks/[id]/inputs/[n]/route.ts
new file mode 100644
index 00000000..097e5ce7
--- /dev/null
+++ b/src/app/api/gpu/computer/tasks/[id]/inputs/[n]/route.ts
@@ -0,0 +1,35 @@
+import fs from "node:fs";
+import { Readable } from "node:stream";
+import { connection } from "next/server";
+import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { inputFor, leased } from "@/server/computer/tasks";
+
+/**
+ * One input of a job, for the tab that took it (its token in X-Fuobe-Lease), while it sends the job's files to its
+ * ComfyUI: a few reads each, as bytes that are never a page (no-sniff, never cached). The tab checks its SHA-256 before
+ * it passes it on.
+ */
+export async function GET(request: Request, ctx: RouteContext<"/api/gpu/computer/tasks/[id]/inputs/[n]">) {
+ await connection();
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const limited = rateOf(principal, "input", 120);
+ if (limited) return limited;
+ const { id, n } = await ctx.params;
+ try {
+ const t = leased(principal, id, request.headers.get("x-fuobe-lease"));
+ const file = inputFor(t, Number.parseInt(n, 10));
+ const stream = Readable.toWeb(fs.createReadStream(file.path)) as ReadableStream<Uint8Array>;
+ return new Response(stream, {
+ headers: {
+ "Content-Type": "application/octet-stream",
+ "Content-Length": String(file.size),
+ "X-Content-Type-Options": "nosniff",
+ "Cache-Control": "no-store",
+ "X-Fuobe-Sha256": file.sha256,
+ },
+ });
+ } catch (e) {
+ return relayAnswer(e);
+ }
+}
diff --git a/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts b/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts
new file mode 100644
index 00000000..c35e2cb0
--- /dev/null
+++ b/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts
@@ -0,0 +1,127 @@
+import fs from "node:fs";
+import { connection } from "next/server";
+import { RELAY_LIMITS } from "@/lib/relay";
+import { gateAsProxy } from "@/server/direct-gate";
+import { isUtf8File, outputType, principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { failTask, getTask, leased, outputFile, outputStatus, receivePart, RelayError, SNIFF_BYTES, wantedOf, type TaskRow } from "@/server/computer/tasks";
+import { enter } from "@/server/rate";
+
+/** Nothing arriving for this long ends a part. */
+const IDLE_MS = 60_000;
+/** Parts of results arriving at once across the server. */
+const AT_ONCE = 8;
+
+const no = (status: number, error: string, headers: Record<string, string> = {}) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store", ...headers } });
+
+/** Append the request body to `file`: exactly `length` bytes, or less when it stops (the caller drops a short part). */
+async function writeBody(request: Request, file: string, append: boolean, length: number): Promise<{ bytes: number; head: Buffer }> {
+ const out = fs.openSync(file, append ? "a" : "w", 0o600);
+ const reader = request.body?.getReader();
+ let bytes = 0;
+ const head: Buffer[] = [];
+ let headBytes = 0;
+ try {
+ if (!reader) return { bytes: 0, head: Buffer.alloc(0) };
+ for (;;) {
+ let timer: NodeJS.Timeout | undefined;
+ const idle = new Promise<"idle">((resolve) => (timer = setTimeout(() => resolve("idle"), IDLE_MS)));
+ const step = await Promise.race([reader.read(), idle]).finally(() => clearTimeout(timer));
+ if (step === "idle") {
+ reader.cancel().catch(() => {});
+ break;
+ }
+ if (step.done) break;
+ const chunk = Buffer.from(step.value.buffer, step.value.byteOffset, step.value.byteLength);
+ if (bytes + chunk.length > length) {
+ reader.cancel().catch(() => {});
+ throw new RelayError(413, "More than the part said");
+ }
+ fs.writeSync(out, chunk);
+ bytes += chunk.length;
+ if (headBytes < SNIFF_BYTES) {
+ head.push(chunk.subarray(0, SNIFF_BYTES - headBytes));
+ headBytes += Math.min(chunk.length, SNIFF_BYTES - headBytes);
+ }
+ }
+ } finally {
+ fs.closeSync(out);
+ }
+ return { bytes, head: Buffer.concat(head) };
+}
+
+/**
+ * A result of a job, uploaded by the tab that took it (its token in X-Fuobe-Lease) in parts of up to 16 MB:
+ * `?offset=` where this part starts, `&total=` the file's size. Only a file the server asked for, only at the exact
+ * offset already received, only once, never past its limit; its type comes from its first bytes and must be what the
+ * job makes (a picture that is really a page is refused, and the run fails). One upload at a time per person, a few
+ * across the server. GET says how far it got, so a reloaded tab goes on from there. The proxy doesn't run on this route
+ * (a big body): its checks run here.
+ */
+export async function PUT(request: Request, ctx: RouteContext<"/api/gpu/computer/tasks/[id]/outputs/[n]">) {
+ const denied = gateAsProxy(request);
+ if (denied) return denied;
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const limited = rateOf(principal, "output", 600);
+ if (limited) return limited;
+ const declared = request.headers.get("content-length");
+ if (declared === null || !/^\d+$/.test(declared)) return no(411, "Send the part with its size (Content-Length).");
+ const length = Number(declared);
+ const q = new URL(request.url).searchParams;
+ const offset = Number(q.get("offset"));
+ const total = Number(q.get("total"));
+ if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(total) || total < 1) return no(400, "Say where the part goes (offset) and the file's size (total).");
+ if (length > RELAY_LIMITS.partBytes) return no(413, "Send results in parts of 16 MB at most.");
+ const { id, n: nRaw } = await ctx.params;
+ const n = Number.parseInt(nRaw, 10);
+ let t: TaskRow;
+ try {
+ t = leased(principal, id, request.headers.get("x-fuobe-lease"));
+ } catch (e) {
+ return relayAnswer(e);
+ }
+ const mine = enter(`relay-out:${principal}`, 1);
+ if (!mine) return no(429, "Another result of yours is uploading. Fuobe tries again by itself.", { "Retry-After": "2" });
+ const all = enter("relay-out", AT_ONCE);
+ if (!all) {
+ mine();
+ return no(429, "The studio is busy saving other results. Fuobe tries again by itself.", { "Retry-After": "3" });
+ }
+ try {
+ const owner = principal === "owner";
+ const r = await receivePart(t, n, { offset, total, length }, (file, append) => writeBody(request, file, append, length), (head, w) => outputType(head, w, owner));
+ // A text result is UTF-8 through to its end.
+ const w = wantedOf(t).find((x) => x.n === n);
+ if (r.done && w?.kind === "text" && !isUtf8File(outputFile(t.id, n))) {
+ fs.rmSync(outputFile(t.id, n), { force: true });
+ failTask(getTask(principal, t.id) ?? t, "Couldn't save a result from your ComfyUI: it isn't text.");
+ return no(415, "That isn't text.");
+ }
+ return Response.json({ received: r.bytes, total: r.total, done: r.done }, { headers: { "Cache-Control": "no-store" } });
+ } catch (e) {
+ if (e instanceof RelayError && e.extra.fail) {
+ // A result that isn't what the job makes, or past what it may keep: the run fails, with why.
+ failTask(getTask(principal, t.id) ?? t, e.message);
+ }
+ return relayAnswer(e);
+ } finally {
+ all();
+ mine();
+ }
+}
+
+export async function GET(request: Request, ctx: RouteContext<"/api/gpu/computer/tasks/[id]/outputs/[n]">) {
+ await connection();
+ const denied = gateAsProxy(request);
+ if (denied) return denied;
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const { id, n } = await ctx.params;
+ try {
+ const t = leased(principal, id, request.headers.get("x-fuobe-lease"));
+ const r = outputStatus(t, Number.parseInt(n, 10));
+ return Response.json({ received: r.bytes, total: r.total, done: r.done }, { headers: { "Cache-Control": "no-store" } });
+ } catch (e) {
+ return relayAnswer(e);
+ }
+}
diff --git a/src/app/api/gpu/computer/tasks/[id]/release/route.ts b/src/app/api/gpu/computer/tasks/[id]/release/route.ts
new file mode 100644
index 00000000..81fb7c61
--- /dev/null
+++ b/src/app/api/gpu/computer/tasks/[id]/release/route.ts
@@ -0,0 +1,19 @@
+import { principalOf, relayAnswer } from "@/server/computer/http";
+import { leased, release } from "@/server/computer/tasks";
+
+/**
+ * The tab lets go of a job as it closes (sent with keepalive): one it hadn't sent to ComfyUI yet waits for the next tab
+ * or computer at once; one ComfyUI has stays with this computer, which picks it up again when Fuobe opens there.
+ */
+export async function POST(request: Request, ctx: RouteContext<"/api/gpu/computer/tasks/[id]/release">) {
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const body = (await request.json().catch(() => null)) as { lease?: unknown } | null;
+ const { id } = await ctx.params;
+ try {
+ release(leased(principal, id, body?.lease));
+ return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });
+ } catch (e) {
+ return relayAnswer(e);
+ }
+}
diff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
new file mode 100644
index 00000000..3c5b9367
--- /dev/null
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@ -0,0 +1,65 @@
+import { RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";
+import { gateAsProxy, readBodyWithin } from "@/server/direct-gate";
+import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { leased, report } from "@/server/computer/tasks";
+import { onComputer, planRelayOutputs } from "@/server/providers/comfyui";
+
+const EVENTS = new Set(["sent", "refused", "queued", "running", "finished", "passes", "gone", "comfy-down", "stopped", "failed"]);
+
+/** The event as the tab sent it, with only the fields each one has, or null. */
+function eventOf(b: Record<string, unknown>): ReportEvent | null {
+ const e = b.event;
+ if (typeof e !== "string" || !EVENTS.has(e)) return null;
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
+ switch (e) {
+ case "sent":
+ return typeof b.promptId === "string" ? { event: e, promptId: b.promptId, number: num(b.number) } : null;
+ case "refused":
+ return { event: e, status: num(b.status) ?? 400, body: b.body };
+ case "queued":
+ return { event: e, position: num(b.position) ?? -1 };
+ case "running":
+ return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }) };
+ case "finished":
+ return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never } : null;
+ case "passes":
+ return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never } : null;
+ case "failed":
+ return typeof b.reason === "string" && (TAB_FAILURES as readonly string[]).includes(b.reason) ? { event: e, reason: b.reason as never, status: num(b.status) } : null;
+ default:
+ return { event: e as "gone" | "comfy-down" | "stopped" };
+ }
+}
+
+/**
+ * The tab's report about a job it took (its token in the body): sent, refused, where it is in the queue, its steps, its
+ * finished /history entry (up to 8 MB), ComfyUI gone or down, a stop done. Each is taken only where the job is. The
+ * answer to a finished prompt names the files to upload. The proxy doesn't run on this route (a big entry): its checks
+ * run here.
+ */
+export async function POST(request: Request, ctx: RouteContext<"/api/gpu/computer/tasks/[id]/report">) {
+ const denied = gateAsProxy(request);
+ if (denied) return denied;
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const limited = rateOf(principal, "report", 300);
+ if (limited) return limited;
+ const raw = await readBodyWithin(request, RELAY_LIMITS.reportBytes);
+ if (raw === "too-big") return Response.json({ error: "That report is too large" }, { status: 413 });
+ let body: Record<string, unknown> | null = null;
+ try {
+ body = raw ? (JSON.parse(raw.toString("utf8")) as Record<string, unknown>) : null;
+ } catch {}
+ const event = body && typeof body === "object" ? eventOf(body) : null;
+ if (!event) return Response.json({ error: "Not a report" }, { status: 400 });
+ const { id } = await ctx.params;
+ try {
+ const t = leased(principal, id, body!.lease);
+ return Response.json(
+ report(t, event, (entries, passes) => onComputer(principal, () => planRelayOutputs(t, entries, passes))),
+ { headers: { "Cache-Control": "no-store" } },
+ );
+ } catch (e) {
+ return relayAnswer(e);
+ }
+}
diff --git a/src/app/api/gpu/inventory/route.ts b/src/app/api/gpu/inventory/route.ts
index 1ec9a8f7..fe8dabfc 100644
--- a/src/app/api/gpu/inventory/route.ts
+++ b/src/app/api/gpu/inventory/route.ts
@@ -1,21 +1,35 @@
+import { readBodyWithin } from "@/server/direct-gate";
+import { BROWSER_INVENTORY_BYTES, cleanInventory } from "@/server/gpu/browser-inventory";
import { preflightOn } from "@/server/gpu/index-file";
import { interactiveRefusal } from "@/server/gpu/gate";
+import { readinessView } from "@/server/gpu/readiness-service";
+import { writeSnapshot } from "@/server/gpu/snapshots";
import { gpuTargetFor } from "@/server/gpu/target";
+import { hit } from "@/server/rate";
/**
- * GPU pre-flight, browser-direct mode: the tab reads a ComfyUI on the visitor's own computer and sends what it
- * found. Accepted only for an account whose GPU is in browser mode, never for the studio's own ComfyUI, and a
- * browser's facts never stand in for a server check (review 18). Browser mode isn't part of an account's GPU
- * yet, so every request is refused for now.
+ * GPU pre-flight, browser-direct: the person's Fuobe tab read the ComfyUI on their own computer ("Use the ComfyUI on
+ * this computer") and sends what it found. Taken only for that person's own computer (an account in that mode, or the
+ * owner when Settings says ComfyUI runs on the owner's computer), never for a ComfyUI the server reads itself: a
+ * browser's facts never stand in for a server check (review 18). The answer is the board, as GET /api/gpu/readiness.
*/
export async function PUT(request: Request) {
if (!preflightOn()) return Response.json({ error: "The GPU pre-flight is switched off on this studio." }, { status: 404 });
const refused = interactiveRefusal(request);
if (refused) return Response.json({ error: refused }, { status: 403 });
const t = gpuTargetFor(request, "read");
- if (t.kind === "install") return Response.json({ error: "The studio's own ComfyUI is checked by the server." }, { status: 403 });
- return Response.json(
- { error: "Checking a ComfyUI from this browser isn't available yet. Connect it with a tunnel link instead.", code: "browser-mode-off" },
- { status: 409 },
- );
+ if (t.kind === "install" || t.kind === "account") return Response.json({ error: "This ComfyUI is checked by the server.", code: "server-check" }, { status: 409 });
+ if (t.kind === "none") return Response.json({ error: "Connect your GPU first.", code: "connect-gpu" }, { status: 409 });
+ const rate = hit(`gpu-inventory:${t.key}`, 12, 60_000);
+ if (!rate.ok) return Response.json({ error: "Checked a moment ago." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
+ const raw = await readBodyWithin(request, BROWSER_INVENTORY_BYTES);
+ if (raw === "too-big") return Response.json({ error: "That check is too large." }, { status: 413 });
+ let body: unknown = null;
+ try {
+ body = raw ? JSON.parse(raw.toString("utf8")) : null;
+ } catch {}
+ const inventory = cleanInventory(body);
+ if (!inventory) return Response.json({ error: "That isn't a check of a ComfyUI." }, { status: 400 });
+ writeSnapshot(t, inventory);
+ return Response.json(readinessView(t), { headers: { "Cache-Control": "private, no-store" } });
}
diff --git a/src/app/api/gpu/plan/route.ts b/src/app/api/gpu/plan/route.ts
index fd7d716c..610c2d84 100644
--- a/src/app/api/gpu/plan/route.ts
+++ b/src/app/api/gpu/plan/route.ts
@@ -18,7 +18,7 @@ export async function GET(request: Request) {
if (!REF.test(ref)) return Response.json({ error: "Name a tool (ref)" }, { status: 400, headers });
const t = gpuTargetFor(request, "read");
if (t.kind === "none") return Response.json({ error: "Connect your GPU first.", code: "connect-gpu" }, { status: 409, headers });
- const plan = await planFor(t, ref, t.kind === "account" ? t.accountId : "owner");
+ const plan = await planFor(t, ref, t.kind === "account" ? t.accountId : t.kind === "computer" ? (t.accountId ?? "owner") : "owner");
if (!plan) return Response.json({ error: "Check your GPU first, or that tool doesn't run on ComfyUI.", code: "no-check" }, { status: 404, headers });
return Response.json(plan, { headers });
}
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index ff6ff650..12cd5ce5 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -13,6 +13,10 @@ export async function register() {
// Public sign-up: accounts' uploads leave after 14 days and their runs after 30 (then daily); a deleted account's files go.
const { ensureAccountSweep } = await import("./server/account-sweep");
ensureAccountSweep();
+ // "Use the ComfyUI on this computer": jobs whose run stopped going end, and the relay's leftover files go.
+ const { ensureRelaySweep } = await import("./server/computer/tasks");
+ const { onAccountDeleted } = await import("./server/account-files");
+ ensureRelaySweep(onAccountDeleted);
// Faceless / Explainer renders whose narration was timed while the server was down continue with their scenes.
const { ensureFacelessRunner } = await import("./server/faceless");
ensureFacelessRunner();
diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.ts
new file mode 100644
index 00000000..6fe5f7c8
--- /dev/null
+++ b/src/lib/computer-runner.ts
@@ -0,0 +1,613 @@
+/**
+ * The Fuobe tab's side of "Use the ComfyUI on this computer" (DESIGN.md): it beats to the server, takes the person's
+ * jobs one at a time, sends each one's inputs and exact graph to the ComfyUI on 127.0.0.1, follows it (the live socket
+ * for steps and previews, the job and history reads for where it is), reports back, and uploads the results the server
+ * asks for. It decides nothing about the result. Every address it uses on the person's computer comes from
+ * lib/local-comfy.ts, which allows only what a run needs, and it refuses a graph that would read files the run didn't
+ * send. No React and no browser-only API is needed: the page (src/components/gpu/computer-runner.tsx) gives it fetch,
+ * a socket and a clock, and the tests drive it from Node against a stand-in ComfyUI.
+ */
+import { parseComfyBinary, parseComfyText } from "./comfy-ws";
+import { graphProblem, localBase, mayDownload, readPath, statsFacts, viewPath, writePath, type SystemStats } from "./local-comfy";
+import { RELAY_LIMITS, RELAY_TIMES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type HistoryEntryLike, type RelayState, type ReportEvent, type WantedFile } from "./relay";
+
+/** The parts of a WebSocket the runner uses (the browser's, or Node's). */
+export interface SocketLike {
+ binaryType: string;
+ onmessage: ((e: { data: unknown }) => void) | null;
+ onclose: ((e?: unknown) => void) | null;
+ onerror: ((e?: unknown) => void) | null;
+ onopen: ((e?: unknown) => void) | null;
+ close(): void;
+}
+
+export interface RunnerDeps {
+ /** Fuobe's own API on this site (the session cookie goes with it). */
+ api: (path: string, init?: RequestInit) => Promise<Response>;
+ /** The ComfyUI on this computer: no headers of Fuobe's own, no cookies. */
+ local: (url: string, init?: RequestInit) => Promise<Response>;
+ /** A socket to the ComfyUI on this computer (null: none, progress comes from reading the job). */
+ socket?: (url: string) => SocketLike | null;
+ sha256: (data: ArrayBuffer) => Promise<string>;
+ /** This site's address, as ComfyUI's setting must name it. */
+ origin: string;
+ now?: () => number;
+ sleep?: (ms: number) => Promise<void>;
+}
+
+/** What the page shows about one job this tab runs. */
+export interface LocalJob {
+ taskId: string;
+ generationId: string;
+ phase: "sending" | "queued" | "running" | "saving" | "done" | "failed";
+ value?: number;
+ max?: number;
+ position?: number;
+ /** The latest live preview (an image the page shows under the tile's shimmer). */
+ preview?: Blob;
+ saved?: number;
+}
+
+export interface RunnerView {
+ /** This computer runs the waiting jobs. */
+ runner: boolean;
+ /** Another computer does. */
+ heldElsewhere: boolean;
+ waiting: number;
+ /** ComfyUI here: answering, not answering, or answering without Fuobe's setting. */
+ comfy: "ok" | "down" | "no-setting";
+ /** The session ended, or the person disconnected: the runner stopped. */
+ stopped?: "signed-out" | "disconnected";
+ jobs: LocalJob[];
+ facts?: ComputerFacts;
+}
+
+class Gone extends Error {}
+class Stopped extends Error {}
+
+const PROGRESS_EVERY_MS = 500;
+const POLL_MS = 1000;
+
+/** The prompts of a meta-batch job: their entries name the job's filename prefix. */
+const hasPrefix = (prompt: unknown, prefix: string) =>
+ !!prompt && typeof prompt === "object" && Object.values(prompt as Record<string, { inputs?: Record<string, unknown> }>).some((n) => n?.inputs?.filename_prefix === prefix);
+
+/** A history entry as the server needs it: status and outputs (not the whole graph again). */
+const slim = (e: HistoryEntryLike & { prompt?: unknown[] }): HistoryEntryLike => ({ prompt: e.prompt ? [e.prompt[0], e.prompt[1]] : undefined, status: e.status, outputs: e.outputs });
+
+export class ComputerRunner {
+ readonly view: RunnerView = { runner: false, heldElsewhere: false, waiting: 0, comfy: "ok", jobs: [] };
+ private listeners = new Set<(v: RunnerView) => void>();
+ private busy = false;
+ private stopping = new Set<string>();
+ private ws: SocketLike | null = null;
+ private wsOpen = false;
+ private events = new Map<string, { value?: number; max?: number; node?: string; nodesDone: number; done?: boolean }>();
+ private factsSentAt = 0;
+ private factsWithLoras = 0;
+ private jobsApi: boolean | undefined;
+ private alive = true;
+ private now: () => number;
+ private sleep: (ms: number) => Promise<void>;
+ private base: string;
+
+ constructor(
+ private deps: RunnerDeps,
+ private o: { device: string; port: number; host?: string; clientId: string },
+ ) {
+ this.now = deps.now ?? Date.now;
+ this.sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ this.base = localBase(o.port, o.host);
+ }
+
+ onChange(fn: (v: RunnerView) => void): () => void {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+
+ private emit() {
+ for (const fn of this.listeners) fn(this.view);
+ }
+
+ private job(t: Pick<ClaimedTask, "id" | "generationId">, patch: Partial<LocalJob>) {
+ const at = this.view.jobs.findIndex((j) => j.taskId === t.id);
+ const next = { ...(at >= 0 ? this.view.jobs[at] : { taskId: t.id, generationId: t.generationId, phase: "sending" as const }), ...patch };
+ this.view.jobs = at >= 0 ? this.view.jobs.map((j, i) => (i === at ? next : j)) : [...this.view.jobs, next];
+ this.emit();
+ }
+
+ /** Stop for good (the page closes, the person disconnects, the session ended). */
+ stop(reason?: RunnerView["stopped"]) {
+ this.alive = false;
+ if (reason) this.view.stopped = reason;
+ try {
+ this.ws?.close();
+ } catch {}
+ this.emit();
+ }
+
+ // -------------------------------------------------------------------------
+ // The ComfyUI here
+
+ private async read<T>(path: string): Promise<T> {
+ const res = await this.deps.local(`${this.base}${readPath(path)}`, { credentials: "omit", cache: "no-store" });
+ if (!res.ok) throw Object.assign(new Error(`ComfyUI ${path.split("?")[0]} answered HTTP ${res.status}`), { status: res.status });
+ return (await res.json()) as T;
+ }
+
+ private async send(path: string, check: unknown, own: { promptIds: string[]; names?: string[] }, init: RequestInit): Promise<Response> {
+ return this.deps.local(`${this.base}${writePath(path, check, own)}`, { ...init, method: "POST", credentials: "omit", cache: "no-store" });
+ }
+
+ /** What ComfyUI here is, for the server (its GPU, memory, version; its LoRA names now and then). */
+ async facts(withLoras = false): Promise<ComputerFacts | null> {
+ try {
+ const stats = await this.read<SystemStats>("/system_stats");
+ const f: ComputerFacts = statsFacts(stats, this.deps.origin);
+ if (withLoras) {
+ const loras = await this.read<unknown>("/models/loras").catch(() => null);
+ if (Array.isArray(loras)) f.loras = loras.filter((x): x is string => typeof x === "string");
+ }
+ this.view.comfy = "ok";
+ this.view.facts = f;
+ return f;
+ } catch (e) {
+ // A browser can't read a ComfyUI that doesn't let this site in, but a no-cors look sees that something answers.
+ const answers = (e as { status?: number }).status === 403 || (await this.deps.local(`${this.base}/system_stats`, { mode: "no-cors", credentials: "omit", cache: "no-store" }).then(() => true, () => false));
+ this.view.comfy = answers ? "no-setting" : "down";
+ return null;
+ }
+ }
+
+ private socket() {
+ if (this.wsOpen || this.ws || !this.deps.socket) return;
+ let ws: SocketLike | null;
+ try {
+ ws = this.deps.socket(`${this.base.replace(/^http/, "ws")}${readPath(`/ws?clientId=${this.o.clientId}`)}`);
+ } catch {
+ ws = null;
+ }
+ if (!ws) return;
+ this.ws = ws;
+ ws.binaryType = "arraybuffer";
+ ws.onopen = () => (this.wsOpen = true);
+ ws.onclose = ws.onerror = () => {
+ this.wsOpen = false;
+ if (this.ws === ws) this.ws = null;
+ };
+ ws.onmessage = (m) => {
+ if (typeof m.data === "string") {
+ const e = parseComfyText(m.data);
+ if (!e || !("promptId" in e) || !e.promptId) return;
+ const cur = this.events.get(e.promptId) ?? { nodesDone: 0 };
+ if (e.type === "progress") Object.assign(cur, { value: e.value, max: e.max, node: e.node });
+ else if (e.type === "executing" && e.node) Object.assign(cur, { node: e.node, nodesDone: cur.nodesDone + 1, value: undefined, max: undefined });
+ else if (e.type === "success" || e.type === "error" || e.type === "interrupted" || (e.type === "executing" && !e.node)) cur.done = true;
+ this.events.set(e.promptId, cur);
+ return;
+ }
+ const p = parseComfyBinary(m.data as ArrayBuffer);
+ if (!p) return;
+ // A preview goes only to the prompt's own client: this tab's job (a newer ComfyUI also names the prompt).
+ const job = this.view.jobs.find((j) => j.phase === "running" && (!p.promptId || this.events.has(p.promptId)));
+ if (job) this.job({ id: job.taskId, generationId: job.generationId }, { preview: new Blob([p.data as BlobPart], { type: p.type }) });
+ };
+ }
+
+ /** Where a prompt is on ComfyUI here. */
+ private async where(promptId: string, prefix?: string): Promise<{ s: "pending"; ahead: number } | { s: "running" } | { s: "done"; entry: HistoryEntryLike } | { s: "absent" }> {
+ if (this.jobsApi === undefined) this.jobsApi = await this.read("/api/jobs").then(() => true, () => false);
+ const history = async () => (await this.read<Record<string, HistoryEntryLike>>(`/history/${promptId}`))[promptId];
+ if (this.jobsApi) {
+ const res = await this.deps.local(`${this.base}${readPath(`/api/jobs/${promptId}`)}`, { credentials: "omit", cache: "no-store" });
+ if (res.status === 404) return prefix ? this.whereByQueue(promptId) : { s: "absent" };
+ if (!res.ok) throw Object.assign(new Error(`ComfyUI answered HTTP ${res.status}`), { status: res.status });
+ const j = (await res.json()) as { status?: string };
+ if (j.status === "in_progress") return { s: "running" };
+ if (j.status === "pending") return this.whereByQueue(promptId);
+ const entry = await history();
+ return entry ? { s: "done", entry } : { s: "absent" };
+ }
+ const entry = await history();
+ if (entry && (entry.status?.completed || entry.status?.status_str)) return { s: "done", entry };
+ return this.whereByQueue(promptId);
+ }
+
+ private async whereByQueue(promptId: string): Promise<{ s: "pending"; ahead: number } | { s: "running" } | { s: "done"; entry: HistoryEntryLike } | { s: "absent" }> {
+ const q = await this.read<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue");
+ if ((q.queue_running ?? []).some((r) => r[1] === promptId)) return { s: "running" };
+ const pending = [...(q.queue_pending ?? [])].sort((a, b) => Number(a[0]) - Number(b[0]));
+ const at = pending.findIndex((r) => r[1] === promptId);
+ if (at >= 0) return { s: "pending", ahead: at + (q.queue_running?.length ?? 0) };
+ // It may have finished between the two reads.
+ const entry = (await this.read<Record<string, HistoryEntryLike>>(`/history/${promptId}`))[promptId];
+ return entry ? { s: "done", entry } : { s: "absent" };
+ }
+
+ // -------------------------------------------------------------------------
+ // The server
+
+ private async report(t: ClaimedTask, e: ReportEvent): Promise<{ wanted?: WantedFile[]; follow?: string; stop?: boolean; state?: RelayState }> {
+ for (let i = 0; ; i++) {
+ const res = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/report`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lease: t.lease, ...e }) });
+ if (res.ok) return (await res.json()) as { wanted?: WantedFile[]; follow?: string; stop?: boolean; state?: RelayState };
+ if (res.status === 401) {
+ this.stop("signed-out");
+ throw new Stopped();
+ }
+ // The job ended or another tab has it: this tab lets go.
+ if (res.status === 404 || res.status === 409) throw new Stopped();
+ if (i >= 4) throw new Error(`The studio answered HTTP ${res.status}`);
+ await this.sleep(res.status === 429 ? 2000 : 1000 * (i + 1));
+ }
+ }
+
+ /** One beat: say this computer is here, keep its jobs alive, and stop what the server says to stop. */
+ async beat(takeover = false): Promise<BeatAnswer | null> {
+ if (!this.alive) return null;
+ const t = this.now();
+ // Facts every minute; the LoRA names every 5 minutes.
+ const loras = t - this.factsWithLoras > 5 * 60_000;
+ const facts = t - this.factsSentAt > 60_000 ? await this.facts(loras) : null;
+ if (facts) {
+ this.factsSentAt = t;
+ if (loras) this.factsWithLoras = t;
+ } else if (this.view.comfy !== "ok") await this.facts(false);
+ const running = this.view.jobs
+ .filter((j) => j.phase !== "done" && j.phase !== "failed")
+ .map((j) => {
+ const ev = this.events.get(this.promptOf.get(j.taskId) ?? "");
+ return { task: j.taskId, ...(j.position !== undefined && { position: j.position }), ...(j.phase === "running" && ev && { value: ev.value, max: ev.max, nodesDone: ev.nodesDone }) };
+ });
+ const stopped = [...this.stoppedDone];
+ const res = await this.deps.api("/api/gpu/computer/beat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ device: this.o.device, port: this.o.port, ...(facts && { facts }), running, ...(stopped.length && { stopped }), ...(takeover && { takeover: true }) }),
+ });
+ if (res.ok) for (const s of stopped) this.stoppedDone.delete(s);
+ if (res.status === 401) {
+ this.stop("signed-out");
+ return null;
+ }
+ if (res.status === 403 || res.status === 409) {
+ this.stop("disconnected");
+ return null;
+ }
+ if (!res.ok) return null;
+ const a = (await res.json()) as BeatAnswer;
+ Object.assign(this.view, { runner: a.runner, heldElsewhere: a.heldElsewhere, waiting: a.waiting });
+ this.emit();
+ for (const s of a.stops) void this.takeOff(s);
+ return a;
+ }
+
+ /** Take a job's prompt (and a meta-batch's later passes) off ComfyUI here, then tell the server. */
+ private async takeOff(s: BeatAnswer["stops"][number]) {
+ if (this.stopping.has(s.task)) return;
+ this.stopping.add(s.task);
+ try {
+ const own = { promptIds: [s.promptId] };
+ if (this.jobsApi !== false) {
+ const res = await this.send(`/api/jobs/${s.promptId}/cancel`, {}, own, {}).catch(() => null);
+ if (res?.status === 404) this.jobsApi = false;
+ }
+ if (this.jobsApi === false) {
+ await this.send("/queue", { delete: [s.promptId] }, own, { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delete: [s.promptId] }) }).catch(() => null);
+ const q = await this.read<{ queue_running?: unknown[][] }>("/queue").catch(() => null);
+ if (q?.queue_running?.some((r) => r[1] === s.promptId)) {
+ await this.send("/interrupt", { prompt_id: s.promptId }, own, { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt_id: s.promptId }) }).catch(() => null);
+ }
+ }
+ // A meta-batch queues its next pass under a new id: sweep its prefix a few times.
+ if (s.prefix) {
+ for (let i = 0; i < 5; i++) {
+ const q = await this.read<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue").catch(() => null);
+ const ids = [...(q?.queue_running ?? []), ...(q?.queue_pending ?? [])].filter((r) => hasPrefix(r[2], s.prefix!)).map((r) => String(r[1]));
+ if (!ids.length) break;
+ for (const id of ids) await this.send(`/api/jobs/${id}/cancel`, {}, { promptIds: ids }, {}).catch(() => null);
+ await this.sleep(1000);
+ }
+ }
+ // Said at the next beat (a stop can be for a job an earlier tab took: this one has no token for it).
+ this.stoppedDone.add(s.task);
+ } finally {
+ this.stopping.delete(s.task);
+ const j = this.view.jobs.find((x) => x.taskId === s.task);
+ if (j && j.phase !== "done") this.job({ id: j.taskId, generationId: j.generationId }, { phase: "failed" });
+ }
+ }
+
+ private leases = new Map<string, string>();
+ private promptOf = new Map<string, string>();
+ private stoppedDone = new Set<string>();
+
+ /** Ask for a job and run it (one at a time). True when there was one. */
+ async claimAndRun(): Promise<boolean> {
+ if (!this.alive || this.busy) return false;
+ this.busy = true;
+ try {
+ const running = this.view.jobs.filter((j) => j.phase !== "done" && j.phase !== "failed").map((j) => j.taskId);
+ const res = await this.deps.api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: this.o.device, running }) });
+ if (res.status !== 200) {
+ if (res.status === 401) this.stop("signed-out");
+ return false;
+ }
+ const { task } = (await res.json()) as { task: ClaimedTask };
+ this.leases.set(task.id, task.lease);
+ await this.run(task);
+ return true;
+ } finally {
+ this.busy = false;
+ }
+ }
+
+ /** A whole job, from wherever it was. */
+ async run(t: ClaimedTask): Promise<void> {
+ this.promptOf.set(t.id, t.promptId);
+ this.job(t, { phase: t.resume === "collecting" ? "saving" : t.resume === "running" ? "running" : t.resume === "queued" ? "queued" : "sending" });
+ try {
+ const problem = graphProblem(t.graph, t.inputs.map((i) => i.name));
+ if (problem) {
+ await this.report(t, { event: "failed", reason: "unsafe-graph" });
+ return this.job(t, { phase: "failed" });
+ }
+ let entries: HistoryEntryLike[] | null = null;
+ let wanted = t.wanted;
+ let phase = t.resume ?? "sending";
+ for (let attempt = 0; phase !== "collecting" && attempt < 3; attempt++) {
+ if (phase === "sending") {
+ const sent = await this.sendJob(t);
+ if (!sent) return;
+ }
+ this.socket();
+ const done = await this.follow(t);
+ if (done === "gone") {
+ const a = await this.report(t, { event: "gone" });
+ if (a.state !== "sending") return this.job(t, { phase: "failed" });
+ phase = "sending";
+ continue;
+ }
+ entries = done.entries;
+ if (!done.answer.wanted) return this.job(t, { phase: done.answer.state === "done" ? "done" : "failed" });
+ wanted = done.answer.wanted;
+ phase = "collecting";
+ }
+ if (phase !== "collecting" || !wanted) return;
+ if (!entries) entries = await this.ownEntries(t);
+ await this.collect(t, wanted, entries, t.received ?? []);
+ } catch (e) {
+ if (e instanceof Stopped) return this.job(t, { phase: "failed" });
+ throw e;
+ }
+ }
+
+ /** The job's own entries on ComfyUI here, to check a resumed upload against. */
+ private async ownEntries(t: ClaimedTask): Promise<HistoryEntryLike[]> {
+ const own = (await this.read<Record<string, HistoryEntryLike>>(`/history/${t.promptId}`).catch(() => ({}) as Record<string, HistoryEntryLike>))[t.promptId];
+ const passes = t.prefix ? Object.values(await this.read<Record<string, HistoryEntryLike>>("/history?max_items=64").catch(() => ({}))).filter((e) => hasPrefix(e.prompt?.[2], t.prefix!)) : [];
+ return [...(own ? [own] : []), ...passes];
+ }
+
+ /** Send the inputs and the prompt, unless ComfyUI has it already (a resumed job). False when the job ended. */
+ private async sendJob(t: ClaimedTask): Promise<boolean> {
+ this.job(t, { phase: "sending" });
+ const there = await this.where(t.promptId).catch(() => null);
+ if (there && there.s !== "absent") {
+ await this.report(t, { event: "sent", promptId: t.promptId });
+ return true;
+ }
+ if (!there) await this.waitForComfy(t);
+ const names = t.inputs.map((i) => i.name);
+ for (const input of t.inputs) {
+ const res = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/inputs/${input.n}`, { headers: { "X-Fuobe-Lease": t.lease } });
+ if (res.status === 404 || res.status === 409) throw new Stopped();
+ if (!res.ok) throw new Error(`The studio answered HTTP ${res.status} for a file`);
+ const data = await res.arrayBuffer();
+ if ((await this.deps.sha256(data)) !== input.sha256) {
+ await this.report(t, { event: "failed", reason: "input-changed" });
+ this.job(t, { phase: "failed" });
+ return false;
+ }
+ const form = new FormData();
+ form.append("image", new Blob([data], { type: input.contentType }), input.name);
+ form.append("type", "input");
+ form.append("overwrite", "true");
+ const up = await this.send("/upload/image", { name: input.name, type: "input", overwrite: "true" }, { promptIds: [], names }, { body: form }).catch(() => null);
+ if (!up) {
+ await this.waitForComfy(t);
+ return this.sendJob(t);
+ }
+ if (!up.ok) {
+ await this.report(t, { event: "failed", reason: up.status === 413 ? "input-too-big" : "comfy-error", status: up.status });
+ this.job(t, { phase: "failed" });
+ return false;
+ }
+ }
+ const body = { prompt: t.graph, prompt_id: t.promptId, client_id: this.o.clientId, ...(t.preview && { extra_data: { preview_method: "auto" } }) };
+ const res = await this.send("/prompt", body, { promptIds: [t.promptId] }, { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);
+ if (!res) {
+ await this.waitForComfy(t);
+ return this.sendJob(t);
+ }
+ const answer = (await res.json().catch(() => ({}))) as { prompt_id?: string; number?: number };
+ if (res.status === 400) {
+ await this.report(t, { event: "refused", status: 400, body: answer });
+ this.job(t, { phase: "failed" });
+ return false;
+ }
+ if (!res.ok || typeof answer.prompt_id !== "string") {
+ await this.report(t, { event: "failed", reason: "comfy-error", status: res.status });
+ this.job(t, { phase: "failed" });
+ return false;
+ }
+ // An older ComfyUI mints its own id: that is the one to follow.
+ if (answer.prompt_id !== t.promptId) {
+ t.promptId = answer.prompt_id;
+ this.promptOf.set(t.id, t.promptId);
+ }
+ await this.report(t, { event: "sent", promptId: answer.prompt_id, number: answer.number });
+ return true;
+ }
+
+ /** ComfyUI here stopped answering: say so once, then wait until it answers again. */
+ private async waitForComfy(t: ClaimedTask) {
+ let told = false;
+ for (;;) {
+ if (!this.alive) throw new Stopped();
+ const ok = await this.read("/system_stats").then(
+ () => true,
+ () => false,
+ );
+ if (ok) {
+ this.view.comfy = "ok";
+ this.emit();
+ return;
+ }
+ this.view.comfy = "down";
+ this.emit();
+ if (!told) {
+ const a = await this.report(t, { event: "comfy-down" });
+ if (a.stop) throw new Stopped();
+ told = true;
+ }
+ await this.sleep(3000);
+ }
+ }
+
+ /** Follow a sent prompt until it finishes (its entry reported, the server's answer back), or ComfyUI lost it. */
+ private async follow(t: ClaimedTask): Promise<"gone" | { entries: HistoryEntryLike[]; answer: { wanted?: WantedFile[]; state?: RelayState } }> {
+ let lastSent = 0;
+ let lastKey = "";
+ let following: string | undefined;
+ for (;;) {
+ if (!this.alive) throw new Stopped();
+ if (following) {
+ // A meta-batch: its passes run under new ids, all with its prefix.
+ const q = await this.read<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue").catch(() => null);
+ if (!q) {
+ await this.waitForComfy(t);
+ continue;
+ }
+ const running = [...(q.queue_running ?? []), ...(q.queue_pending ?? [])].some((r) => hasPrefix(r[2], following!));
+ const passes = Object.values(await this.read<Record<string, HistoryEntryLike>>("/history?max_items=64").catch(() => ({}))).filter((e) => hasPrefix(e.prompt?.[2], following!));
+ const a = await this.report(t, { event: "passes", running, entries: running ? [] : passes.map(slim) });
+ if (a.stop) throw new Stopped();
+ if (!running) return { entries: passes, answer: a };
+ this.job(t, { phase: "running" });
+ await this.sleep(POLL_MS * 2);
+ continue;
+ }
+ const w = await this.where(t.promptId).catch(() => null);
+ if (!w) {
+ await this.waitForComfy(t);
+ continue;
+ }
+ if (w.s === "absent") return "gone";
+ if (w.s === "done") {
+ const a = await this.report(t, { event: "finished", entry: slim(w.entry) });
+ if (a.stop) throw new Stopped();
+ if (a.follow) {
+ following = a.follow;
+ continue;
+ }
+ return { entries: [w.entry], answer: a };
+ }
+ const ev = this.events.get(t.promptId);
+ const report: ReportEvent = w.s === "pending" ? { event: "queued", position: w.ahead } : { event: "running", value: ev?.value, max: ev?.max, node: ev?.node, nodesDone: ev?.nodesDone };
+ const key = JSON.stringify(report);
+ if (key !== lastKey && this.now() - lastSent >= PROGRESS_EVERY_MS) {
+ const a = await this.report(t, report);
+ if (a.stop) throw new Stopped();
+ lastKey = key;
+ lastSent = this.now();
+ }
+ this.job(t, w.s === "pending" ? { phase: "queued", position: w.ahead } : { phase: "running", value: ev?.value, max: ev?.max });
+ // The socket says when steps move; without it, a read a second.
+ await this.sleep(this.wsOpen ? PROGRESS_EVERY_MS : POLL_MS);
+ }
+ }
+
+ /** Upload the results the server asked for, each in parts, from where each got to. */
+ private async collect(t: ClaimedTask, wanted: WantedFile[], entries: HistoryEntryLike[], received: { n: number; bytes: number; done: boolean }[]) {
+ this.job(t, { phase: "saving", saved: 0 });
+ for (const w of wanted) {
+ const got = received.find((r) => r.n === w.n);
+ if (got?.done) continue;
+ // Only a file this job's own prompt saved (a wrong answer from the server can't reach any other).
+ if (!mayDownload(w, entries)) {
+ await this.report(t, { event: "failed", reason: "output-missing" });
+ return this.job(t, { phase: "failed" });
+ }
+ const res = await this.deps.local(`${this.base}${readPath(viewPath(w))}`, { credentials: "omit", cache: "no-store" }).catch(() => null);
+ if (!res?.ok) {
+ await this.report(t, { event: "failed", reason: "output-missing" });
+ return this.job(t, { phase: "failed" });
+ }
+ const blob = await res.blob();
+ if (blob.size > w.maxBytes) {
+ // The server says why (too big, or the account's files are full) when it refuses the size.
+ await this.upload(t, w, blob, 0);
+ return this.job(t, { phase: "failed" });
+ }
+ let offset = got?.bytes ?? 0;
+ if (offset > 0) {
+ const s = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/outputs/${w.n}`, { headers: { "X-Fuobe-Lease": t.lease } });
+ offset = s.ok ? ((await s.json()) as { received: number }).received : 0;
+ }
+ if (!(await this.upload(t, w, blob, offset))) return this.job(t, { phase: "failed" });
+ }
+ this.job(t, { phase: "done", preview: undefined });
+ }
+
+ /** One file in parts of 16 MB; a failed part is tried again (three times in a row at most). */
+ private async upload(t: ClaimedTask, w: WantedFile, blob: Blob, from: number): Promise<boolean> {
+ let offset = from;
+ let fails = 0;
+ while (offset < blob.size || blob.size === 0) {
+ if (!this.alive) throw new Stopped();
+ const part = blob.slice(offset, Math.min(blob.size, offset + RELAY_LIMITS.partBytes));
+ const res = await this.deps
+ .api(`/api/gpu/computer/tasks/${t.id}/outputs/${w.n}?offset=${offset}&total=${blob.size}`, {
+ method: "PUT",
+ headers: { "X-Fuobe-Lease": t.lease, "Content-Type": "application/octet-stream" },
+ body: part,
+ })
+ .catch(() => null);
+ if (res?.ok) {
+ const r = (await res.json()) as { received: number; done: boolean };
+ offset = r.received;
+ fails = 0;
+ this.job(t, { saved: offset / Math.max(1, blob.size) });
+ if (r.done) return true;
+ continue;
+ }
+ if (res && (res.status === 404 || res.status === 413 || res.status === 415)) return false;
+ if (res?.status === 409) {
+ // Out of step (a part arrived twice): go on from what the server has.
+ const s = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/outputs/${w.n}`, { headers: { "X-Fuobe-Lease": t.lease } });
+ if (!s.ok) return false;
+ const r = (await s.json()) as { received: number; done: boolean };
+ if (r.done) return true;
+ offset = r.received;
+ }
+ if (++fails >= 3) {
+ await this.report(t, { event: "failed", reason: "save-failed" }).catch(() => null);
+ return false;
+ }
+ await this.sleep(res?.status === 429 ? 2000 : 1500 * fails);
+ }
+ return true;
+ }
+
+ /** Let go of the jobs not sent yet (the tab closes): another tab or computer can take them at once. */
+ releaseAll(send: (path: string, body: string) => void) {
+ for (const j of this.view.jobs) {
+ const lease = this.leases.get(j.taskId);
+ if (lease && j.phase === "sending") send(`/api/gpu/computer/tasks/${j.taskId}/release`, JSON.stringify({ lease }));
+ }
+ }
+}
+
+/** How often the runner beats: faster while it has work. */
+export const beatEvery = (busy: boolean) => (busy ? RELAY_TIMES.busyBeatMs : RELAY_TIMES.beatMs);
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 5dc15d72..5e6f74bd 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -165,12 +165,23 @@ export function accountGeneration(method: string, pathname: string): string | un
*/
export function accountOwnRead(pathname: string): boolean {
if (ACCOUNT_LISTS.has(pathname)) return true;
- return pathname === "/api/generations" || pathname === "/api/account/gpu" || GPU_READS.has(pathname);
+ return pathname === "/api/generations" || pathname === "/api/account/gpu" || GPU_READS.has(pathname) || COMPUTER_READ.test(pathname);
}
/** The Library's counts and its Uploads (its stored files): each route answers an account with its own only. */
const ACCOUNT_LISTS = new Set(["/api/generations/facets", "/api/assets"]);
+/**
+ * "Use the ComfyUI on this computer": the routes the person's own Fuobe tab runs their jobs through. Each takes whose
+ * jobs from the session, and only that person's (src/server/computer/http.ts principalOf).
+ */
+const COMPUTER_READ = /^\/api\/gpu\/computer\/tasks\/[^/]+\/(inputs|outputs)\/[^/]+$/;
+const COMPUTER_CHANGES: [method: string, path: RegExp][] = [
+ ["POST", /^\/api\/gpu\/computer\/(beat|claim)$/],
+ ["POST", /^\/api\/gpu\/computer\/tasks\/[^/]+\/(report|release)$/],
+ ["PUT", /^\/api\/gpu\/computer\/tasks\/[^/]+\/outputs\/[^/]+$/],
+];
+
/** GPU pre-flight reads: each answers for the account's own GPU only (src/server/gpu/target.ts). */
const GPU_READS = new Set(["/api/gpu/readiness", "/api/gpu/badges", "/api/gpu/plan"]);
@@ -184,6 +195,8 @@ export function accountMayChange(method: string, pathname: string, search: strin
if ((method === "PUT" || method === "DELETE") && pathname === "/api/account/gpu") return true;
// GPU pre-flight: checking its own ComfyUI (reads only; the routes check the target and the request themselves).
if ((method === "POST" && pathname === "/api/gpu/check") || (method === "PUT" && pathname === "/api/gpu/inventory")) return true;
+ // Running its own jobs on its own computer.
+ if (COMPUTER_CHANGES.some(([m, p]) => m === method && p.test(pathname))) return true;
if (method === "POST" && (pathname === "/api/uploads" || pathname === "/api/media/probe")) return true;
// Like, pin or review many of its own runs at once (the route checks each is its own, and refuses the rest).
if (method === "POST" && pathname === "/api/generations/bulk") return true;
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 36cf18e3..2237c319 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -92,6 +92,8 @@ export interface TaskInput {
/** What a claim hands the tab. */
export interface ClaimedTask {
id: string;
+ /** The run it is for (the person's own), so the tab can show its progress there. */
+ generationId: string;
/** The claim's token: every call about this task carries it. */
lease: string;
graph: Record<string, { class_type: string; inputs: Record<string, unknown> }>;
diff --git a/src/proxy.ts b/src/proxy.ts
index e2a25f02..8149638d 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -327,8 +327,9 @@ export const config = {
// SVGs at the root. Generated SVGs under /api/files stay behind sign-in. The routes that take a file in a form
// (/api/uploads, a Soul finish, a Layers render, a skill upload, an Assist source, an explainer document), and Split
// soundtrack's mix export (a WAV in parts of 16 MB), make the same checks themselves (src/server/direct-gate.ts): the
- // proxy would hold the whole file in memory first.
+ // proxy would hold the whole file in memory first. So do a computer's report of a finished job and its results
+ // (src/app/api/gpu/computer/tasks).
matcher: [
- "/((?!_next/static|_next/image|favicon\\.ico$|apple-icon\\.png$|samples/|previews/|vendor/|api/uploads$|api/generations/[^/]+/finish$|api/layers/renders$|api/assist/skills/upload$|api/assist/projects/[^/]+/sources$|api/explainer/document$|api/audio-tools/export$|[^/]+\\.svg$).*)",
+ "/((?!_next/static|_next/image|favicon\\.ico$|apple-icon\\.png$|samples/|previews/|vendor/|api/uploads$|api/generations/[^/]+/finish$|api/layers/renders$|api/assist/skills/upload$|api/assist/projects/[^/]+/sources$|api/explainer/document$|api/audio-tools/export$|api/gpu/computer/tasks/[^/]+/(?:report|outputs/[^/]+)$|[^/]+\\.svg$).*)",
],
};
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index c3cd6561..6f62fce7 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -2,6 +2,7 @@ import "server-only";
import dns from "node:dns/promises";
import net from "node:net";
import { accountGpu, type Account, type AccountGpu } from "./auth";
+import { runnerFacts } from "./computer/tasks";
import { PROVIDERS } from "./providers";
import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
@@ -65,7 +66,7 @@ export interface GpuInfo {
}
/** Ask the account's ComfyUI for /system_stats, the check the studio makes of its own. */
-export async function testGpu(gpu: AccountGpu, o: { resolve?: (host: string) => Promise<string[]>; timeoutMs?: number; maxBytes?: number } = {}): Promise<GpuInfo> {
+export async function testGpu(gpu: { url: string; token?: string }, o: { resolve?: (host: string) => Promise<string[]>; timeoutMs?: number; maxBytes?: number } = {}): Promise<GpuInfo> {
let res: Response;
try {
res = await fetchPublic(`${gpu.url}/system_stats`, { headers: gpu.token ? { Authorization: `Bearer ${gpu.token}` } : {} }, { timeoutMs: o.timeoutMs ?? 10_000, deadlineMs: (o.timeoutMs ?? 10_000) + 5_000, maxBytes: o.maxBytes ?? 1 * 2 ** 20, resolve: o.resolve });
@@ -95,6 +96,11 @@ const STATUS_MAX_BYTES = 64 * 1024;
* status requests that arrive while one is on its way share its answer.
*/
export async function gpuState(id: string, gpu: AccountGpu): Promise<{ online: boolean } & GpuInfo> {
+ // On the person's own computer: what its Fuobe tab last said (online while it beats).
+ if (gpu.mode === "computer") {
+ const f = runnerFacts(`acct:${id}`);
+ return { online: !!f?.online, ...(f?.device && { device: f.device }), ...(f?.vramBytes && { vramBytes: f.vramBytes }), ...(f?.version && { version: f.version }) };
+ }
const cache = (globalThis.__fuobeAccountGpus ??= new Map());
const hit = cache.get(id);
if (hit && hit.url === gpu.url && Date.now() - hit.at < 30_000) return { online: hit.online, ...hit.info };
@@ -124,6 +130,8 @@ export async function gpuState(id: string, gpu: AccountGpu): Promise<{ online: b
*/
export function lastGpuDevice(id: string): string | undefined {
const gpu = accountGpu(id);
+ // On the person's own computer: what its Fuobe tab last said.
+ if (gpu?.mode === "computer") return /^[a-z]+/i.exec(runnerFacts(`acct:${id}`)?.device ?? "")?.[0].toLowerCase();
const hit = globalThis.__fuobeAccountGpus?.get(id);
if (!gpu || hit?.url !== gpu.url) return undefined;
return /^[a-z]+/i.exec(hit.info.device ?? "")?.[0].toLowerCase();
@@ -132,7 +140,8 @@ export function lastGpuDevice(id: string): string | undefined {
/** What a visitor's status strip shows (GET /api/status): its own GPU, never the install's providers, servers or Demo mode. */
export interface VisitorView {
kind: "guest" | "account";
- gpu: { connected: boolean; online?: boolean; device?: string; vramBytes?: number };
+ /** `mode` "computer": the ComfyUI on the person's own computer, which their Fuobe tab runs. */
+ gpu: { connected: boolean; mode?: "link" | "computer"; online?: boolean; device?: string; vramBytes?: number };
}
/**
@@ -145,7 +154,9 @@ export async function visitorStatus(account: Account | null) {
const live = account && gpu ? await gpuState(account.id, gpu) : null;
const viewer: VisitorView = {
kind: account ? "account" : "guest",
- gpu: gpu ? { connected: true, online: !!live?.online, ...(live?.device && { device: live.device }), ...(live?.vramBytes && { vramBytes: live.vramBytes }) } : { connected: false },
+ gpu: gpu
+ ? { connected: true, mode: gpu.mode === "computer" ? "computer" : "link", online: !!live?.online, ...(live?.device && { device: live.device }), ...(live?.vramBytes && { vramBytes: live.vramBytes }) }
+ : { connected: false },
};
return {
providers: Object.fromEntries(Object.values(PROVIDERS).map((p) => [p.id, { label: p.id === "comfyui" ? "Your GPU" : p.label, configured: p.id === "comfyui" ? (gpu ? !!live?.online : true) : false }])),
diff --git a/src/server/account-loras.ts b/src/server/account-loras.ts
index 350a87ad..87c66dd2 100644
--- a/src/server/account-loras.ts
+++ b/src/server/account-loras.ts
@@ -21,8 +21,9 @@ const cache = () => (globalThis.__fuobeAccountLoras ??= new Map());
/** The LoRA files on the account's ComfyUI (inside its run: onOwnGpu), cached a minute; null when it can't say. */
export async function accountLoraList(route?: ModelRoute): Promise<string[] | null> {
const gpu = ownGpu();
- if (!gpu?.url) return null;
- const key = `${tenantAccount() ?? ""}|${gpu.url}`;
+ const where = gpu?.kind === "computer" ? "computer" : gpu?.url;
+ if (!where) return null;
+ const key = `${tenantAccount() ?? ""}|${where}`;
const hit = cache().get(key);
if (hit && Date.now() - hit.at < TTL_MS) return hit.files;
const files = await comfyLoraFiles(route);
diff --git a/src/server/auth.ts b/src/server/auth.ts
index 18417005..b31e6189 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -36,11 +36,14 @@ export interface ApiToken {
lastUsedAt?: number;
}
-/** An account's own ComfyUI ("Your GPU"): where its runs go, never the install's. A public address (a tunnel). */
-export interface AccountGpu {
- url: string;
- token?: string;
-}
+/**
+ * An account's own ComfyUI ("Your GPU"): where its runs go, never the install's. A public address (a tunnel), or the
+ * ComfyUI on the person's own computer, which only their Fuobe tab reaches (src/server/computer).
+ */
+export type AccountGpu = { mode?: "link"; url: string; token?: string } | { mode: "computer" };
+
+/** A GPU reached at a public address (a link), not the person's own computer. */
+export const gpuLink = (gpu: AccountGpu | null | undefined): { url: string; token?: string } | null => (gpu && gpu.mode !== "computer" ? gpu : null);
/** A signed-up visitor (public sign-up). */
export interface Account {
@@ -424,7 +427,8 @@ function withoutGpu(a: Account): Account {
export function setAccountGpu(id: string, gpu: AccountGpu | null): void {
const d = read();
if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);
- write({ ...d, accounts: d.accounts.map((a) => (a.id !== id ? a : gpu ? { ...a, gpu: { url: gpu.url, ...(gpu.token && { token: gpu.token }) } } : withoutGpu(a))) });
+ const kept = (g: AccountGpu): AccountGpu => (g.mode === "computer" ? { mode: "computer" } : { url: g.url, ...(g.token && { token: g.token }) });
+ write({ ...d, accounts: d.accounts.map((a) => (a.id !== id ? a : gpu ? { ...a, gpu: kept(gpu) } : withoutGpu(a))) });
}
/** Who is asking: the owner (also everyone while no password is set), an account (public sign-up on), or a guest. */
diff --git a/src/server/computer/http.ts b/src/server/computer/http.ts
new file mode 100644
index 00000000..8c3e8350
--- /dev/null
+++ b/src/server/computer/http.ts
@@ -0,0 +1,95 @@
+import "server-only";
+import fs from "node:fs";
+import { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE, GUEST_HEADER, GUEST_RUN_MESSAGE } from "@/lib/guest-access";
+import type { WantedFile } from "@/lib/relay";
+import { sniffMedia } from "@/lib/sniff";
+import { accountGpu, authEnabled, crossSite, hostAllowed, requestViewer, validToken } from "../auth";
+import { hit } from "../rate";
+import { getSetting } from "../settings";
+import { RelayError, type Principal } from "./tasks";
+
+/**
+ * What every "computer" route (src/app/api/gpu/computer) checks first: a person in a browser on this site (no API
+ * token, no other website, the browser says the request comes from this site's own page), signed in, and running on
+ * their own computer: an account whose GPU is "this computer", or the owner when Settings says ComfyUI runs on the
+ * owner's computer. Whose tasks the request is about comes only from the session, never from the request.
+ */
+export function principalOf(request: Request): Principal | Response {
+ const no = (status: number, error: string, extra: Record<string, unknown> = {}, headers: Record<string, string> = {}) =>
+ Response.json({ error, ...extra }, { status, headers: { "Cache-Control": "no-store", ...headers } });
+ if (validToken(request.headers.get("authorization"))) return no(403, "Only Fuobe open in a browser runs jobs on your computer.");
+ const host = request.headers.get("host") ?? new URL(request.url).host;
+ if (crossSite(request, host)) return no(403, "Blocked a request from another website.");
+ const site = request.headers.get("sec-fetch-site");
+ if (site ? site !== "same-origin" : !request.headers.get("origin")) return no(403, "Only Fuobe's own page can do this.");
+ if (!authEnabled() && !hostAllowed(host)) return no(403, "Blocked a request for an address this studio isn't reached at.");
+ const viewer = requestViewer(request);
+ if (viewer.kind === "guest") return no(401, GUEST_RUN_MESSAGE, {}, { [GUEST_HEADER]: "1" });
+ if (viewer.kind === "owner") {
+ return getSetting("comfyWhere") === "computer" ? "owner" : no(409, "This studio's ComfyUI runs on its server.", { code: "server-mode" });
+ }
+ const gpu = accountGpu(viewer.account.id);
+ if (!gpu) return no(403, CONNECT_GPU_MESSAGE, { code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });
+ if (gpu.mode !== "computer") return no(409, "Your GPU is connected with a link, so the server runs it.", { code: "link-mode" });
+ return `acct:${viewer.account.id}`;
+}
+
+/** At most `limit` calls a minute of one kind for a principal. */
+export function rateOf(principal: Principal, what: string, limit: number): Response | null {
+ const r = hit(`relay-${what}:${principal}`, limit, 60_000);
+ return r.ok ? null : Response.json({ error: "Too many at once. Fuobe tries again by itself." }, { status: 429, headers: { "Retry-After": String(r.retryAfterS), "Cache-Control": "no-store" } });
+}
+
+/** A RelayError as its answer (anything else is thrown on). */
+export function relayAnswer(e: unknown): Response {
+ if (e instanceof RelayError) return Response.json({ error: e.message, ...e.extra }, { status: e.status, headers: { "Cache-Control": "no-store" } });
+ throw e;
+}
+
+const KIND_WORDS: Record<WantedFile["kind"], string> = { image: "a picture", video: "a clip", audio: "sound", text: "text", model3d: "a 3D model", frame: "an EXR frame" };
+
+/** A text result's type, by its name. */
+const textType = (name: string, owner: boolean) => (/\.srt$/i.test(name) ? "application/x-subrip" : /\.vtt$/i.test(name) ? "text/vtt" : owner && /\.json$/i.test(name) ? "application/json" : "text/plain");
+
+/**
+ * What a result from someone's ComfyUI is, from its first bytes (as an upload's type is: lib/sniff.ts), and whether it
+ * is what the server asked for. Never a page or a script: a picture that is really HTML is refused. Throws the words.
+ */
+export function outputType(head: Buffer, w: WantedFile, owner: boolean): string {
+ const s = head.length >= 4 ? sniffMedia(head, undefined, { gif: true }) : null;
+ switch (w.kind) {
+ case "image":
+ if (s?.kind === "image") return s.contentType;
+ break;
+ case "video":
+ // VideoHelperSuite also saves animations as GIF or WebP.
+ if (s?.kind === "video" || s?.contentType === "image/gif" || s?.contentType === "image/webp") return s.contentType;
+ break;
+ case "audio":
+ if (s?.kind === "audio") return s.contentType;
+ if (s?.contentType === "video/webm") return "audio/webm";
+ if (s?.contentType === "video/mp4") return "audio/mp4";
+ break;
+ case "frame":
+ if (head.length >= 4 && head.readUInt32BE(0) === 0x762f3101) return "image/x-exr";
+ break;
+ case "text":
+ if (!head.includes(0)) return textType(w.filename, owner);
+ break;
+ case "model3d":
+ if (owner && head.subarray(0, 4).toString("latin1") === "glTF") return "model/gltf-binary";
+ if (owner && /^ply\r?\n/.test(head.subarray(0, 8).toString("latin1"))) return "model/ply";
+ break;
+ }
+ throw new Error(`Couldn't save a result from your ComfyUI: it isn't ${KIND_WORDS[w.kind] ?? "what this run makes"}.`);
+}
+
+/** A whole text result is UTF-8 (checked once it has all arrived). */
+export function isUtf8File(file: string): boolean {
+ try {
+ new TextDecoder("utf-8", { fatal: true }).decode(fs.readFileSync(file));
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
new file mode 100644
index 00000000..74f48a9b
--- /dev/null
+++ b/src/server/computer/tasks.ts
@@ -0,0 +1,716 @@
+import "server-only";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { nanoid } from "nanoid";
+import {
+ ACTIVE_STATES,
+ DEVICE_ID,
+ FACT_LIMITS,
+ INPUT_NAME,
+ RELAY_LIMITS,
+ RELAY_TIMES,
+ reportAllowed,
+ SENT_STATES,
+ UUID,
+ type BeatAnswer,
+ type ClaimedTask,
+ type ComputerFacts,
+ type HistoryEntryLike,
+ type RelayState,
+ type ReportEvent,
+ type TaskInput,
+ type WantedFile,
+} from "@/lib/relay";
+import { DATA_DIR, db } from "../db";
+
+/**
+ * "Use the ComfyUI on this computer" (DESIGN.md): the server keeps each ComfyUI job of a run on someone's computer as a
+ * task, and that person's Fuobe tab does it. A task holds the graph exactly as the server built it, the inputs it
+ * staged (under names it chose), the prompt id it minted, and later the files it asks for. Tasks belong to a principal
+ * ("owner", or "acct:<id>"), which every route takes from the session cookie, never from the request: one principal
+ * can't see, take, read or fill another's task (an unknown or foreign task is a 404). A task is taken by one tab at a
+ * time: each claim hands out a new lease, and every call about the task carries it. One computer at a time runs a
+ * principal's waiting tasks (the runner, renewed by its beats); a task a computer took stays with that computer.
+ */
+
+export type Principal = "owner" | `acct:${string}`;
+
+/** The relay's own folder: staged inputs and received outputs. Never served as it is. */
+export const relayDir = () => path.join(DATA_DIR, "relay");
+const inputFile = (name: string) => path.join(relayDir(), "in", name);
+const taskDir = (id: string) => path.join(relayDir(), "tasks", id);
+export const outputFile = (id: string, n: number) => path.join(taskDir(id), `out-${n}`);
+
+declare global {
+ /** Live progress by task id (written on every step, so kept in memory, not in SQLite). */
+ var __fuobeRelayProgress: Map<string, Progress> | undefined;
+}
+
+export interface Progress {
+ value?: number;
+ max?: number;
+ node?: string;
+ nodesDone?: number;
+ position?: number;
+ at: number;
+}
+
+const progressMap = () => (globalThis.__fuobeRelayProgress ??= new Map());
+export const taskProgress = (id: string): Progress | undefined => progressMap().get(id);
+
+/** The relay's tables are made with the database (db.ts RELAY_TABLES). */
+const rdb = () => db();
+
+export interface TaskRow {
+ id: string;
+ principal: Principal;
+ generation_id: string;
+ state: RelayState;
+ device: string | null;
+ lease_hash: string | null;
+ graph_json: string | null;
+ prompt_id: string;
+ prefix: string | null;
+ meta_batch: number;
+ preview: number;
+ workflow_id: string | null;
+ extra_json: string | null;
+ wanted_json: string | null;
+ received_json: string | null;
+ result_json: string | null;
+ error: string | null;
+ refusal_json: string | null;
+ stop: number;
+ attempts: number;
+ down_at: number | null;
+ note: string | null;
+ created_at: number;
+ updated_at: number;
+ claimed_at: number | null;
+ sent_at: number | null;
+ started_at: number | null;
+ finished_at: number | null;
+ device_seen_at: number | null;
+}
+
+interface InputRow {
+ name: string;
+ principal: string;
+ task_id: string | null;
+ n: number | null;
+ content_type: string;
+ size: number;
+ sha256: string;
+ reads: number;
+ created_at: number;
+}
+
+export interface Received {
+ n: number;
+ bytes: number;
+ total: number;
+ done: boolean;
+ contentType?: string;
+}
+
+const hash = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+const json = <T,>(s: string | null, fallback: T): T => {
+ if (!s) return fallback;
+ try {
+ return JSON.parse(s) as T;
+ } catch {
+ return fallback;
+ }
+};
+
+function setTask(id: string, fields: Partial<TaskRow>): void {
+ const keys = Object.keys(fields);
+ if (!keys.length) return;
+ rdb()
+ .prepare(`UPDATE relay_tasks SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @updated_at WHERE id = @id`)
+ .run({ ...fields, updated_at: Date.now(), id });
+}
+
+/** A principal's task, or null (another principal's task is no task at all). */
+export function getTask(principal: Principal, id: string): TaskRow | null {
+ if (typeof id !== "string" || !/^[A-Za-z0-9_-]{16}$/.test(id)) return null;
+ return (rdb().prepare("SELECT * FROM relay_tasks WHERE id = ? AND principal = ?").get(id, principal) as TaskRow | undefined) ?? null;
+}
+
+// ---------------------------------------------------------------------------
+// Inputs: staged by the server when it plans the run (comfyui.ts prepareFile, ctx.upload)
+
+const extOf = (name: string, contentType: string) => {
+ const fromName = name.includes(".") ? name.split(".").pop()!.toLowerCase() : "";
+ const ext = /^[a-z0-9]{1,5}$/.test(fromName) ? fromName : (contentType.split("/")[1] ?? "bin").replace(/[^a-z0-9]/g, "").slice(0, 5);
+ return ext || "bin";
+};
+
+/** Keep an input for a principal's next task: returns the name its graph uses (and ComfyUI will get). */
+export function stageInput(principal: Principal, data: Buffer, contentType: string, name: string): string {
+ const staged = `fuobe_${nanoid(12).replace(/[^A-Za-z0-9_-]/g, "_")}.${extOf(name, contentType)}`;
+ if (!INPUT_NAME.test(staged)) throw new Error("Couldn't name that file");
+ fs.mkdirSync(path.dirname(inputFile(staged)), { recursive: true });
+ fs.writeFileSync(inputFile(staged), data, { mode: 0o600 });
+ rdb()
+ .prepare("INSERT INTO relay_inputs (name, principal, task_id, n, content_type, size, sha256, reads, created_at) VALUES (?, ?, NULL, NULL, ?, ?, ?, 0, ?)")
+ .run(staged, principal, contentType.split(";")[0].trim().toLowerCase() || "application/octet-stream", data.length, crypto.createHash("sha256").update(data).digest("hex"), Date.now());
+ return staged;
+}
+
+/** Every string a graph's nodes take (the names of the inputs it loads are among them). */
+function graphStrings(graph: Record<string, { inputs?: Record<string, unknown> }>): Set<string> {
+ const out = new Set<string>();
+ for (const n of Object.values(graph)) for (const v of Object.values(n?.inputs ?? {})) if (typeof v === "string") out.add(v.replace(/ \[input\]$/, ""));
+ return out;
+}
+
+export interface NewTask {
+ principal: Principal;
+ generationId: string;
+ graph: Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+ prefix?: string;
+ metaBatch?: boolean;
+ preview?: boolean;
+ workflowId?: string;
+ /** What the run makes ("image", "video", "audio"…), for the tile's words. */
+ made?: string;
+ /** The run's LoRAs (for the words of a refusal). */
+ loras?: { file: string; url?: string }[];
+}
+
+/** A ComfyUI job for a computer: the graph, the inputs it names, and a prompt id minted here. */
+export function createTask(t: NewTask): { id: string; promptId: string } {
+ const id = nanoid(16).replace(/[^A-Za-z0-9_-]/g, "_");
+ const promptId = crypto.randomUUID();
+ const now = Date.now();
+ const d = rdb();
+ const named = graphStrings(t.graph);
+ d.transaction(() => {
+ d.prepare(
+ `INSERT INTO relay_tasks (id, principal, generation_id, state, graph_json, prompt_id, prefix, meta_batch, preview, workflow_id, extra_json, created_at, updated_at)
+ VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ ).run(
+ id,
+ t.principal,
+ t.generationId,
+ JSON.stringify(t.graph),
+ promptId,
+ t.prefix ?? null,
+ t.metaBatch ? 1 : 0,
+ t.preview ? 1 : 0,
+ t.workflowId ?? null,
+ JSON.stringify({ made: t.made, loras: t.loras ?? [] }),
+ now,
+ now,
+ );
+ const free = d.prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL ORDER BY created_at").all(t.principal) as { name: string }[];
+ let n = 0;
+ for (const f of free) if (named.has(f.name)) d.prepare("UPDATE relay_inputs SET task_id = ?, n = ? WHERE name = ?").run(id, n++, f.name);
+ })();
+ return { id, promptId };
+}
+
+const inputsOf = (taskId: string) => rdb().prepare("SELECT * FROM relay_inputs WHERE task_id = ? ORDER BY n").all(taskId) as InputRow[];
+
+// ---------------------------------------------------------------------------
+// The runner: one computer at a time runs a principal's waiting tasks
+
+interface RunnerRow {
+ principal: string;
+ device: string;
+ lease_until: number;
+ seen_at: number;
+ port: number | null;
+ facts_json: string | null;
+}
+
+const runnerOf = (principal: Principal) => rdb().prepare("SELECT * FROM relay_runners WHERE principal = ?").get(principal) as RunnerRow | undefined;
+
+/** Is a computer of this principal's online (it beat in the last 30 s)? */
+export function runnerOnline(principal: Principal, now = Date.now()): boolean {
+ const r = runnerOf(principal);
+ return !!r && now - r.seen_at < RELAY_TIMES.onlineMs;
+}
+
+/** What the computer said about its ComfyUI (the last report), and its port. */
+export function runnerFacts(principal: Principal): (ComputerFacts & { port?: number; seenAt: number; online: boolean }) | null {
+ const r = runnerOf(principal);
+ if (!r) return null;
+ return { ...json<ComputerFacts>(r.facts_json, {}), ...(r.port && { port: r.port }), seenAt: r.seen_at, online: Date.now() - r.seen_at < RELAY_TIMES.onlineMs };
+}
+
+/** Forget a principal's computer (it disconnected, or the account went). */
+export function forgetComputer(principal: Principal): void {
+ rdb().prepare("DELETE FROM relay_runners WHERE principal = ?").run(principal);
+ for (const t of rdb().prepare(`SELECT id FROM relay_tasks WHERE principal = ? AND state IN (${ACTIVE_STATES.map(() => "?").join(",")})`).all(principal, ...ACTIVE_STATES) as { id: string }[]) {
+ endTask(t.id, "canceled", { error: "Stopped" });
+ }
+}
+
+const str = (v: unknown, max: number) => (typeof v === "string" && v ? v.slice(0, max) : undefined);
+const nonNeg = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
+
+/** Facts as kept: known keys, capped lengths, at most 20,000 LoRA names. */
+export function cleanFacts(f: unknown, keep?: ComputerFacts): ComputerFacts {
+ const o = (f && typeof f === "object" ? f : {}) as Record<string, unknown>;
+ const loras = Array.isArray(o.loras)
+ ? o.loras.filter((x): x is string => typeof x === "string" && x.length > 0 && x.length <= FACT_LIMITS.loraName).slice(0, FACT_LIMITS.loras)
+ : keep?.loras;
+ return {
+ ...(str(o.device, FACT_LIMITS.text) && { device: str(o.device, FACT_LIMITS.text) }),
+ ...(nonNeg(o.vramBytes) !== undefined && { vramBytes: nonNeg(o.vramBytes) }),
+ ...(nonNeg(o.ramBytes) !== undefined && { ramBytes: nonNeg(o.ramBytes) }),
+ ...(str(o.version, 40) && { version: str(o.version, 40) }),
+ ...(str(o.os, 40) && { os: str(o.os, 40) }),
+ ...(typeof o.portable === "boolean" && { portable: o.portable }),
+ ...((o.cors === "exact" || o.cors === "any" || o.cors === "other") && { cors: o.cors }),
+ ...(loras && { loras }),
+ };
+}
+
+export interface BeatInput {
+ device: string;
+ port?: number;
+ facts?: unknown;
+ /** Tasks this tab is working on, with where each is. */
+ running?: { task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number }[];
+ takeover?: boolean;
+ /** Tasks whose prompts this computer took off its ComfyUI, as the server asked. */
+ stopped?: string[];
+}
+
+/**
+ * A computer's beat: it takes or renews the runner's place when that is free, lapsed, its own, or taken over; it keeps
+ * the tasks it works on alive; and it hears which of its prompts to stop.
+ */
+export function beat(principal: Principal, b: BeatInput, now = Date.now()): BeatAnswer {
+ if (!DEVICE_ID.test(b.device)) throw new RelayError(400, "Bad device");
+ const d = rdb();
+ sweepPrincipal(principal);
+ const cur = runnerOf(principal);
+ const free = !cur || cur.device === b.device || cur.lease_until < now || b.takeover === true;
+ const port = Number.isInteger(b.port) && b.port! > 0 && b.port! < 65536 ? b.port! : null;
+ if (free) {
+ const facts = b.facts !== undefined ? cleanFacts(b.facts, json<ComputerFacts>(cur?.facts_json ?? null, {})) : json<ComputerFacts>(cur?.device === b.device ? cur.facts_json : null, {});
+ d.prepare(
+ `INSERT INTO relay_runners (principal, device, lease_until, seen_at, port, facts_json) VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT(principal) DO UPDATE SET device = excluded.device, lease_until = excluded.lease_until, seen_at = excluded.seen_at, port = excluded.port, facts_json = excluded.facts_json`,
+ ).run(principal, b.device, now + RELAY_TIMES.leaseMs, now, port, JSON.stringify(facts));
+ }
+ // The tasks this computer works on stay alive, and their live progress is kept.
+ for (const r of (b.running ?? []).slice(0, 32)) {
+ const t = typeof r?.task === "string" ? getTask(principal, r.task) : null;
+ if (!t || t.device !== b.device || !(SENT_STATES as readonly string[]).includes(t.state)) continue;
+ setTask(t.id, { device_seen_at: now });
+ noteProgress(t.id, r, now);
+ }
+ for (const id of (b.stopped ?? []).slice(0, 64)) {
+ const t = typeof id === "string" ? getTask(principal, id) : null;
+ if (t?.device === b.device) setTask(t.id, { stop: 0 });
+ }
+ const stops = (
+ d.prepare("SELECT id, prompt_id, prefix FROM relay_tasks WHERE principal = ? AND device = ? AND stop = 1").all(principal, b.device) as { id: string; prompt_id: string; prefix: string | null }[]
+ ).map((s) => ({ task: s.id, promptId: s.prompt_id, ...(s.prefix && { prefix: s.prefix }) }));
+ const waiting = (d.prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE principal = ? AND state = 'waiting'").get(principal) as { n: number }).n;
+ return { runner: free, heldElsewhere: !free, waiting, stops };
+}
+
+function noteProgress(id: string, r: Record<string, unknown>, now: number) {
+ const p: Progress = { at: now };
+ for (const k of ["value", "max", "nodesDone", "position"] as const) {
+ const v = nonNeg(r[k]);
+ if (v !== undefined) p[k] = Math.min(v, 1e6);
+ }
+ const node = str(r.node, 64);
+ if (node) p.node = node;
+ progressMap().set(id, { ...progressMap().get(id), ...p });
+}
+
+/**
+ * A computer asks for work: first a task it took before and lost track of (a reload: not in `running`), then, when it is
+ * the runner, the oldest waiting task. Null when there is none. The claim gets a new lease each time.
+ */
+export function claim(principal: Principal, device: string, running: string[], now = Date.now()): ClaimedTask | null {
+ if (!DEVICE_ID.test(device)) throw new RelayError(400, "Bad device");
+ const d = rdb();
+ return d.transaction((): ClaimedTask | null => {
+ const mine = d
+ .prepare(`SELECT * FROM relay_tasks WHERE principal = ? AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY created_at LIMIT 40`)
+ .all(principal, device) as TaskRow[];
+ let t: TaskRow | undefined = mine.find((x) => !running.includes(x.id));
+ if (!t) {
+ const r = runnerOf(principal);
+ if (!r || r.device !== device || r.lease_until < now) return null;
+ // The oldest waiting task, or one another computer took but never sent and went quiet on.
+ t = d
+ .prepare(
+ `SELECT * FROM relay_tasks WHERE principal = ? AND stop = 0 AND (state = 'waiting' OR (state = 'sending' AND sent_at IS NULL AND device != ? AND device_seen_at < ?))
+ ORDER BY created_at LIMIT 1`,
+ )
+ .get(principal, device, now - RELAY_TIMES.leaseMs) as TaskRow | undefined;
+ if (!t) return null;
+ }
+ const lease = crypto.randomBytes(32).toString("hex");
+ const resume = t.state === "waiting" || t.device !== device ? undefined : (t.state as ClaimedTask["resume"]);
+ const fresh = t.state === "waiting" || t.device !== device;
+ setTask(t.id, { device, lease_hash: hash(lease), state: t.state === "waiting" ? "sending" : t.state, claimed_at: now, device_seen_at: now });
+ if (fresh) d.prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
+ const inputs: TaskInput[] = inputsOf(t.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));
+ return {
+ id: t.id,
+ generationId: t.generation_id,
+ lease,
+ graph: json(t.graph_json, {}),
+ promptId: t.prompt_id,
+ preview: !!t.preview,
+ ...(t.prefix && { prefix: t.prefix }),
+ ...(t.meta_batch && { metaBatch: true }),
+ inputs,
+ ...(resume && { resume }),
+ ...(t.state === "collecting" && { wanted: json<WantedFile[]>(t.wanted_json, []), received: json<Received[]>(t.received_json, []).map((r) => ({ n: r.n, bytes: r.bytes, done: r.done })) }),
+ };
+ })();
+}
+
+export class RelayError extends Error {
+ constructor(
+ readonly status: number,
+ message: string,
+ readonly extra: Record<string, unknown> = {},
+ ) {
+ super(message);
+ }
+}
+
+/** A task call: the principal's task, taken with this lease. Unknown or foreign: 404. Another tab took it since: 409. */
+export function leased(principal: Principal, id: string, lease: unknown): TaskRow {
+ const t = getTask(principal, id);
+ if (!t) throw new RelayError(404, "Not found");
+ if (typeof lease !== "string" || !/^[0-9a-f]{64}$/.test(lease) || !t.lease_hash || !crypto.timingSafeEqual(Buffer.from(hash(lease)), Buffer.from(t.lease_hash))) {
+ throw new RelayError(409, "Another tab is running this now", { code: "lease" });
+ }
+ return t;
+}
+
+/** An input's file for its task's tab, while it sends (a few reads each). */
+export function inputFor(t: TaskRow, n: number): { path: string; size: number; contentType: string; sha256: string } {
+ if (t.state !== "sending") throw new RelayError(409, "This run isn't sending files now");
+ const row = rdb().prepare("SELECT * FROM relay_inputs WHERE task_id = ? AND n = ?").get(t.id, n) as InputRow | undefined;
+ if (!row) throw new RelayError(404, "Not found");
+ if (row.reads >= RELAY_LIMITS.inputReads) throw new RelayError(429, "That file was sent enough times. Press Retry on the run.");
+ rdb().prepare("UPDATE relay_inputs SET reads = reads + 1 WHERE name = ?").run(row.name);
+ setTask(t.id, { device_seen_at: Date.now() });
+ return { path: inputFile(row.name), size: row.size, contentType: row.content_type, sha256: row.sha256 };
+}
+
+/**
+ * Ends a task (its inputs go; its outputs stay until the run has kept them). `takeOff`: a prompt already on the
+ * computer's ComfyUI is taken off it there (the computer hears it at its next beat): a cancel, or a timeout.
+ */
+function endTask(id: string, state: "done" | "failed" | "canceled", fields: Partial<TaskRow> = {}, takeOff = state === "canceled") {
+ const t = rdb().prepare("SELECT state, device FROM relay_tasks WHERE id = ?").get(id) as { state: RelayState; device: string | null } | undefined;
+ const stop = takeOff && t && t.device && (SENT_STATES as readonly string[]).includes(t.state) ? 1 : 0;
+ setTask(id, { state, finished_at: Date.now(), down_at: null, ...(stop && { stop }), ...fields });
+ progressMap().delete(id);
+ for (const i of rdb().prepare("SELECT name FROM relay_inputs WHERE task_id = ?").all(id) as { name: string }[]) fs.rmSync(inputFile(i.name), { force: true });
+ rdb().prepare("DELETE FROM relay_inputs WHERE task_id = ?").run(id);
+}
+
+/** What the server does with a finished prompt: the files it wants, a meta-batch to follow, or a failure. */
+export type FinishedPlan = { wanted: WantedFile[]; outputs: unknown[]; budget: number } | { follow: string } | { error: string };
+
+export interface ReportAnswer {
+ ok: true;
+ /** Where the task is now (the tab stops when it has ended). */
+ state?: RelayState;
+ wanted?: WantedFile[];
+ follow?: string;
+ stop?: boolean;
+}
+
+/**
+ * A tab's report about its task (each taken only in its state: lib/relay.ts). `plan` turns a finished entry into the
+ * files to collect (comfyui.ts, which knows the workflow's outputs).
+ */
+export function report(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike[], last: boolean) => FinishedPlan, now = Date.now()): ReportAnswer {
+ const a = reportOnce(t, e, plan, now);
+ return { ...a, state: getTask(t.principal, t.id)?.state ?? t.state };
+}
+
+function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike[], last: boolean) => FinishedPlan, now: number): ReportAnswer {
+ if (t.stop && e.event !== "stopped") return { ok: true, stop: true };
+ if (!reportAllowed(e.event, t.state)) {
+ if (t.state === "canceled") return { ok: true, stop: true };
+ throw new RelayError(409, `That doesn't fit this run now (${t.state})`);
+ }
+ const seen = { device_seen_at: now, down_at: null };
+ switch (e.event) {
+ case "sent": {
+ const promptId = typeof e.promptId === "string" && UUID.test(e.promptId) ? e.promptId : typeof e.promptId === "string" && /^[\w-]{1,64}$/.test(e.promptId) ? e.promptId : null;
+ if (!promptId) throw new RelayError(400, "Bad prompt id");
+ setTask(t.id, { ...seen, state: "queued", prompt_id: promptId, sent_at: now, attempts: t.attempts + 1 });
+ return { ok: true };
+ }
+ case "refused": {
+ const body = JSON.stringify(e.body ?? null);
+ setTask(t.id, { refusal_json: body.length <= 256 * 1024 ? JSON.stringify({ status: Number(e.status) || 400, body: e.body ?? null }) : JSON.stringify({ status: Number(e.status) || 400, body: null }) });
+ endTask(t.id, "failed");
+ return { ok: true };
+ }
+ case "queued":
+ setTask(t.id, seen);
+ noteProgress(t.id, { position: e.position }, now);
+ return { ok: true };
+ case "running":
+ setTask(t.id, { ...seen, state: "running", ...(!t.started_at && { started_at: now }), note: null });
+ noteProgress(t.id, { ...e, position: undefined }, now);
+ return { ok: true };
+ case "finished":
+ case "passes": {
+ if (e.event === "passes" && e.running) {
+ setTask(t.id, { ...seen, state: "running" });
+ return { ok: true };
+ }
+ const entries = e.event === "finished" ? [e.entry] : e.entries;
+ if (!Array.isArray(entries) || entries.some((x) => !x || typeof x !== "object")) throw new RelayError(400, "Bad history entry");
+ const p = plan(entries, e.event === "passes");
+ if ("follow" in p) {
+ if (!t.meta_batch) {
+ endTask(t.id, "failed", { error: "Workflow finished without saving any output" });
+ return { ok: true };
+ }
+ setTask(t.id, { ...seen, state: "running" });
+ return { ok: true, follow: p.follow };
+ }
+ if ("error" in p) {
+ endTask(t.id, "failed", { error: p.error });
+ return { ok: true };
+ }
+ const received: Received[] = p.wanted.map((w) => ({ n: w.n, bytes: 0, total: 0, done: false }));
+ if (!p.wanted.length) {
+ endTask(t.id, "done", { result_json: JSON.stringify(p.outputs), wanted_json: "[]", received_json: "[]" });
+ return { ok: true, wanted: [] };
+ }
+ setTask(t.id, {
+ ...seen,
+ state: "collecting",
+ result_json: JSON.stringify(p.outputs),
+ wanted_json: JSON.stringify(p.wanted),
+ received_json: JSON.stringify(received),
+ extra_json: JSON.stringify({ ...extraOf(t), budget: p.budget }),
+ });
+ return { ok: true, wanted: p.wanted };
+ }
+ case "gone":
+ if (t.attempts < 2 && t.state !== "sending") {
+ setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null });
+ rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
+ return { ok: true };
+ }
+ if (t.state === "sending") return { ok: true };
+ endTask(t.id, "failed", { error: "lost" });
+ return { ok: true };
+ case "comfy-down":
+ setTask(t.id, { device_seen_at: now, ...(t.down_at ? {} : { down_at: now }) });
+ return { ok: true };
+ case "stopped":
+ setTask(t.id, { stop: 0 });
+ return { ok: true };
+ case "failed":
+ endTask(t.id, "failed", { error: `tab:${e.reason}${e.status ? `:${Number(e.status) | 0}` : ""}` });
+ return { ok: true };
+ }
+}
+
+/** Where an upload of an output stands. */
+export function outputStatus(t: TaskRow, n: number): Received {
+ const r = json<Received[]>(t.received_json, []).find((x) => x.n === n);
+ if (!r) throw new RelayError(404, "Not found");
+ return r;
+}
+
+/** Bytes in the first part of a file: enough to say what it is. */
+export const SNIFF_BYTES = 64;
+
+/**
+ * Take part of a wanted output: only while collecting, only a file the server asked for, at exactly the offset already
+ * received, never past its size limit, and only once (a finished file can't be sent again). `check` reads the first part
+ * and says what the file is (or throws); `write` appends the part.
+ */
+export async function receivePart(
+ t: TaskRow,
+ n: number,
+ o: { offset: number; total: number; length: number },
+ write: (file: string, append: boolean) => Promise<{ bytes: number; head: Buffer }>,
+ check: (head: Buffer, w: WantedFile, total: number) => string,
+): Promise<Received> {
+ if (t.state !== "collecting") throw new RelayError(409, "This run isn't saving results now");
+ const wanted = json<WantedFile[]>(t.wanted_json, []).find((w) => w.n === n);
+ if (!wanted) throw new RelayError(404, "Not found");
+ const all = json<Received[]>(t.received_json, []);
+ const cur = all.find((r) => r.n === n)!;
+ if (cur.done) throw new RelayError(409, "That file was saved already");
+ if (!Number.isInteger(o.total) || o.total < 1 || o.total > wanted.maxBytes) {
+ throw new RelayError(413, wanted.maxBytes >= 2 ** 30 ? "tooBig" : "Your ComfyUI made a file bigger than this run can keep", { fail: true });
+ }
+ if (cur.total && cur.total !== o.total) throw new RelayError(409, "The file's size changed");
+ // All the files together fit the room the run had when it finished.
+ const others = all.filter((r) => r.n !== n).reduce((s, r) => s + r.total, 0);
+ const budget = extraOf(t).budget ?? Infinity;
+ if (others + o.total > budget) throw new RelayError(413, "full", { fail: true });
+ if (o.offset !== cur.bytes) throw new RelayError(409, "Wrong place in the file", { received: cur.bytes });
+ if (o.offset + o.length > o.total || o.length > RELAY_LIMITS.partBytes) throw new RelayError(413, "Too much at once");
+ const file = outputFile(t.id, n);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const part = `${file}.part`;
+ if (o.offset === 0) fs.rmSync(part, { force: true });
+ const got = await write(part, o.offset > 0);
+ if (got.bytes !== o.length) {
+ // Cut short: what arrived is dropped, so the next try starts where this part did.
+ fs.truncateSync(part, o.offset);
+ throw new RelayError(400, "The part didn't arrive whole");
+ }
+ let contentType = cur.contentType;
+ if (o.offset === 0) {
+ try {
+ contentType = check(got.head, wanted, o.total);
+ } catch (e) {
+ fs.rmSync(part, { force: true });
+ throw new RelayError(415, (e as Error).message, { fail: true });
+ }
+ }
+ const bytes = o.offset + got.bytes;
+ const done = bytes === o.total;
+ if (done) fs.renameSync(part, file);
+ const fresh = getTask(t.principal, t.id);
+ const list = json<Received[]>(fresh?.received_json ?? null, all).map((r) => (r.n === n ? { n, bytes, total: o.total, done, ...(contentType && { contentType }) } : r));
+ setTask(t.id, { received_json: JSON.stringify(list), device_seen_at: Date.now() });
+ if (list.every((r) => r.done)) endTask(t.id, "done");
+ return list.find((r) => r.n === n)!;
+}
+
+/** A task failed while saving a result (a file that isn't what it should be, or too big). */
+export function failTask(t: TaskRow, error: string): void {
+ if ((ACTIVE_STATES as readonly string[]).includes(t.state)) endTask(t.id, "failed", { error });
+}
+
+/** The tab let go of a task it hadn't sent yet (the tab closes): another tab or computer may take it at once. */
+export function release(t: TaskRow): void {
+ if (t.state === "sending" && !t.sent_at) {
+ setTask(t.id, { state: "waiting", device: null, lease_hash: null });
+ rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
+ } else setTask(t.id, { lease_hash: null });
+}
+
+/**
+ * Stop a task (the run was canceled or timed out): a waiting one ends at once; one a computer took is taken off its
+ * ComfyUI at the computer's next beat.
+ */
+export function requestStop(principal: Principal, id: string): void {
+ const t = getTask(principal, id);
+ if (!t || !(ACTIVE_STATES as readonly string[]).includes(t.state)) return;
+ endTask(t.id, "canceled", { error: "Stopped" });
+}
+
+/** The tasks whose run is no longer going (deleted, canceled from elsewhere) stop: a principal's, or everyone's. */
+function sweepPrincipal(principal?: Principal) {
+ const orphans = rdb()
+ .prepare(
+ `SELECT t.id FROM relay_tasks t LEFT JOIN generations g ON g.id = t.generation_id
+ WHERE ${principal ? "t.principal = ? AND " : ""}t.state IN (${ACTIVE_STATES.map(() => "?").join(",")}) AND (g.id IS NULL OR g.status NOT IN ('queued','running'))`,
+ )
+ .all(...(principal ? [principal] : []), ...ACTIVE_STATES) as { id: string }[];
+ for (const o of orphans) endTask(o.id, "canceled", { error: "Stopped" });
+}
+
+/** A deleted account's computer: its place as runner, its tasks and every file the relay kept for it go. */
+export function purgeComputer(principal: Principal): void {
+ const d = rdb();
+ for (const t of d.prepare("SELECT id FROM relay_tasks WHERE principal = ?").all(principal) as { id: string }[]) {
+ progressMap().delete(t.id);
+ fs.rmSync(taskDir(t.id), { recursive: true, force: true });
+ }
+ for (const i of d.prepare("SELECT name FROM relay_inputs WHERE principal = ?").all(principal) as { name: string }[]) fs.rmSync(inputFile(i.name), { force: true });
+ d.transaction(() => {
+ d.prepare("DELETE FROM relay_inputs WHERE principal = ?").run(principal);
+ d.prepare("DELETE FROM relay_tasks WHERE principal = ?").run(principal);
+ d.prepare("DELETE FROM relay_runners WHERE principal = ?").run(principal);
+ })();
+}
+
+declare global {
+ var __fuobeRelaySweep: NodeJS.Timeout | undefined;
+}
+
+/** Sweep the relay every 15 minutes (once per process), and forget a deleted account's computer with its account. */
+export function ensureRelaySweep(onDeleted: (hook: (id: string) => void) => void): void {
+ if (globalThis.__fuobeRelaySweep) return;
+ const run = () => {
+ try {
+ sweepRelay();
+ } catch (e) {
+ console.warn(`[fuobe] relay sweep failed: ${(e as Error).message}`);
+ }
+ };
+ globalThis.__fuobeRelaySweep = setInterval(run, 15 * 60_000);
+ globalThis.__fuobeRelaySweep.unref?.();
+ onDeleted((id) => purgeComputer(`acct:${id}`));
+ run();
+}
+
+/**
+ * Files and rows nobody needs: tasks whose run stopped going, inputs staged for a task that never came (an hour), and
+ * ended tasks (their folders once the run is no longer going, their rows after a day). Every 15 minutes
+ * (ensureRelaySweep); a beat sweeps its own principal's.
+ */
+export function sweepRelay(now = Date.now()): { inputs: number; tasks: number } {
+ const d = rdb();
+ sweepPrincipal();
+ const stale = d.prepare("SELECT name FROM relay_inputs WHERE task_id IS NULL AND created_at < ?").all(now - RELAY_TIMES.stagedMs) as { name: string }[];
+ for (const s of stale) fs.rmSync(inputFile(s.name), { force: true });
+ d.prepare("DELETE FROM relay_inputs WHERE task_id IS NULL AND created_at < ?").run(now - RELAY_TIMES.stagedMs);
+ const ended = d
+ .prepare(
+ `SELECT t.id, t.finished_at FROM relay_tasks t LEFT JOIN generations g ON g.id = t.generation_id
+ WHERE t.state IN ('done','failed','canceled') AND (g.id IS NULL OR g.status NOT IN ('queued','running') OR t.finished_at < ?)`,
+ )
+ .all(now - RELAY_TIMES.keepMs) as { id: string; finished_at: number | null }[];
+ for (const t of ended) {
+ fs.rmSync(taskDir(t.id), { recursive: true, force: true });
+ d.prepare("UPDATE relay_tasks SET graph_json = NULL WHERE id = ?").run(t.id);
+ }
+ const old = d.prepare("DELETE FROM relay_tasks WHERE state IN ('done','failed','canceled') AND finished_at < ?").run(now - RELAY_TIMES.keepMs);
+ return { inputs: stale.length, tasks: old.changes };
+}
+
+/**
+ * The clocks a task's own computer runs on (the run's queue and running clocks are the runner's, generations.ts): a
+ * computer that took it and went quiet for 30 minutes, or a ComfyUI that stopped answering for 30 minutes, fails it.
+ * Returns the task as it is now.
+ */
+export function checkClocks(t: TaskRow, now = Date.now()): TaskRow {
+ if (!(SENT_STATES as readonly string[]).includes(t.state)) return t;
+ if (t.device_seen_at && now - t.device_seen_at > RELAY_TIMES.silentMs) endTask(t.id, "failed", { error: "silent" }, true);
+ else if (t.down_at && now - t.down_at > RELAY_TIMES.comfyDownMs) endTask(t.id, "failed", { error: "down" }, true);
+ else return t;
+ return getTask(t.principal, t.id) ?? t;
+}
+
+/** The file of a received output, for the principal whose task it is (anyone else: null). */
+export function receivedFile(principal: Principal, taskId: string, n: number): { path: string; contentType?: string } | null {
+ const t = getTask(principal, taskId);
+ if (!t) return null;
+ const r = json<Received[]>(t.received_json, []).find((x) => x.n === n);
+ if (!r?.done) return null;
+ const p = outputFile(t.id, n);
+ return fs.existsSync(p) ? { path: p, contentType: r.contentType } : null;
+}
+
+export const wantedOf = (t: TaskRow) => json<WantedFile[]>(t.wanted_json, []);
+export const receivedOf = (t: TaskRow) => json<Received[]>(t.received_json, []);
+export const resultOf = <T,>(t: TaskRow) => json<T[]>(t.result_json, []);
+export const extraOf = (t: TaskRow) => json<{ made?: string; loras?: { file: string; url?: string }[]; budget?: number }>(t.extra_json, {});
+export const refusalOf = (t: TaskRow) => json<{ status: number; body: unknown } | null>(t.refusal_json, null);
+export const inputKinds = (t: TaskRow) => (rdb().prepare("SELECT content_type FROM relay_inputs WHERE task_id = ?").all(t.id) as { content_type: string }[]).map((r) => r.content_type);
diff --git a/src/server/db.ts b/src/server/db.ts
index 821de8bf..08c8719f 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -607,6 +607,66 @@ export const MIGRATIONS: string[] = [
CREATE INDEX IF NOT EXISTS assets_generation ON assets(generation_id);`,
];
+/**
+ * "Use the ComfyUI on this computer" (src/server/computer/tasks.ts). relay_runners: each principal's computer (the one
+ * that runs its waiting jobs, until its lease lapses) and what its tab said about its ComfyUI. relay_tasks: one per
+ * ComfyUI job of a run on someone's computer, with the graph as the server built it and where the job is. relay_inputs:
+ * the files staged for a job, under the names ComfyUI gets. Safe to run on every start.
+ */
+export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (
+ principal TEXT PRIMARY KEY,
+ device TEXT NOT NULL,
+ lease_until INTEGER NOT NULL,
+ seen_at INTEGER NOT NULL,
+ port INTEGER,
+ facts_json TEXT
+ );
+ CREATE TABLE IF NOT EXISTS relay_tasks (
+ id TEXT PRIMARY KEY,
+ principal TEXT NOT NULL,
+ generation_id TEXT NOT NULL,
+ state TEXT NOT NULL,
+ device TEXT,
+ lease_hash TEXT,
+ graph_json TEXT,
+ prompt_id TEXT NOT NULL,
+ prefix TEXT,
+ meta_batch INTEGER NOT NULL DEFAULT 0,
+ preview INTEGER NOT NULL DEFAULT 0,
+ workflow_id TEXT,
+ extra_json TEXT,
+ wanted_json TEXT,
+ received_json TEXT,
+ result_json TEXT,
+ error TEXT,
+ refusal_json TEXT,
+ stop INTEGER NOT NULL DEFAULT 0,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ down_at INTEGER,
+ note TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ claimed_at INTEGER,
+ sent_at INTEGER,
+ started_at INTEGER,
+ finished_at INTEGER,
+ device_seen_at INTEGER
+ );
+ CREATE INDEX IF NOT EXISTS relay_tasks_principal ON relay_tasks(principal, state, created_at);
+ CREATE INDEX IF NOT EXISTS relay_tasks_generation ON relay_tasks(generation_id);
+ CREATE TABLE IF NOT EXISTS relay_inputs (
+ name TEXT PRIMARY KEY,
+ principal TEXT NOT NULL,
+ task_id TEXT,
+ n INTEGER,
+ content_type TEXT NOT NULL,
+ size INTEGER NOT NULL,
+ sha256 TEXT NOT NULL,
+ reads INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS relay_inputs_task ON relay_inputs(task_id);`;
+
declare global {
var __fuobeDb: Database.Database | undefined;
}
@@ -652,6 +712,9 @@ function open(): Database.Database {
if (!(db.prepare("PRAGMA table_info(assist_thread_state)").all() as { name: string }[]).some((c) => c.name === "provider")) {
db.exec("ALTER TABLE assist_thread_state ADD COLUMN provider TEXT");
}
+ // "Use the ComfyUI on this computer" (src/server/computer): its tables, made here rather than as a numbered migration,
+ // since other branches add migrations at the same time and a migration is known by its place in the list.
+ db.exec(RELAY_TABLES);
// An account's own runs (its list, its active runs) are found through this index, not by reading every run. Not a
// numbered migration, so branches that add migrations never clash over it; a failure only leaves lists slower.
try {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 94f399a0..b8c314f6 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -54,8 +54,8 @@ import { createExtendChain, createKeyframeFilm, createMosaicRun, createRelitClip
import { enhancePrompt, enhanceSoulWords, ideogramCaption } from "./enhance";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
-import { comfyLoraFiles, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, probeComfy } from "./providers/comfyui";
-import { accountGpu } from "./auth";
+import { comfyLoraFiles, computerScope, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, probeComfy, relayFile, type OwnGpu } from "./providers/comfyui";
+import { accountGpu, gpuLink, type AccountGpu } from "./auth";
import { CONNECT_GPU_MESSAGE, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
import { outsideTenant, runAsTenant, tenant, tenantAccount } from "./tenant";
import { generationAccount } from "./account-library";
@@ -1256,7 +1256,13 @@ export function accountRun(accountId: string, providerId: string): { run: <T>(fn
if (!gpu) return { error: CONNECT_GPU_MESSAGE };
if (providerId !== "comfyui") return { error: OWN_GPU_ONLY };
// As the account (tenant.ts: only its own files and runs), on its own ComfyUI, the open engine, no demo outputs.
- return { run: (fn) => runAsTenant({ kind: "account", id: accountId }, () => onOwnGpu(gpu, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn))) };
+ const own = ownGpuOf(accountId, gpu);
+ return { run: (fn) => runAsTenant({ kind: "account", id: accountId }, () => onOwnGpu(own, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn))) };
+}
+
+/** Where an account's ComfyUI is, as the provider takes it: a link, or the person's own computer (its tab runs the jobs). */
+function ownGpuOf(accountId: string, gpu: AccountGpu): OwnGpu {
+ return gpu.mode === "computer" ? { kind: "computer", principal: `acct:${accountId}` } : { url: gpu.url, token: gpu.token };
}
/**
@@ -1304,9 +1310,9 @@ export async function accountLoraFix(req: GenerationRequest): Promise<MissingFil
* yet: an empty address that reaches nothing), the open engine, no demo outputs. For previews; a run goes through
* accountRun.
*/
-export function asVisitor<T>(gpu: { url: string; token?: string } | null, fn: () => T, accountId?: string): T {
+export function asVisitor<T>(gpu: AccountGpu | null, fn: () => T, accountId?: string): T {
return runAsTenant(accountId ? { kind: "account", id: accountId } : { kind: "guest" }, () =>
- onOwnGpu(gpu ?? { url: "" }, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn)),
+ onOwnGpu(gpu && accountId ? ownGpuOf(accountId, gpu) : { url: gpuLink(gpu)?.url ?? "" }, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn)),
);
}
@@ -1472,8 +1478,8 @@ async function submitNow(
// file mirrored once to the provider's storage (the civitai key never leaves this server).
if (input.loras?.length && (providerId === "fal" || providerId === "replicate")) {
input.loras = await prepareCloudLoras(input.loras, providerId, (data, name) => adapter.prepareFile(data, "application/octet-stream", name, route), (message) => update(id, { message }));
- } else if (providerId === "comfyui" && !req.account && (input.loras?.length || graphLoras(route.endpoint, input.extra).length)) {
- // (Not for an account's own ComfyUI: the download writes to the install's LoRA folder.)
+ } else if (providerId === "comfyui" && !req.account && !computerScope() && (input.loras?.length || graphLoras(route.endpoint, input.extra).length)) {
+ // (Not for an account's own ComfyUI, nor one on the owner's computer: the download writes to the install's LoRA folder.)
// A graph that loads its own LoRAs (Genjutsu's Character swap: the Turbo and swap LoRAs) gets them downloaded too.
await ensureLorasOnComfy([...(input.loras ?? []), ...graphLoras(route.endpoint, input.extra)], await comfyLoraFiles(route), (message) => update(id, { message }));
}
@@ -1712,6 +1718,12 @@ async function pollOne(r: Row): Promise<void> {
const account = accountOf(r);
const queueMs = account ? ACCOUNT_LIMITS.queueMs : QUEUE_TIMEOUT_MS;
if (!res || res.state === "queued" || res.state === "running") {
+ // A job on someone's own computer reached their ComfyUI later than it was handed over (it waited for their tab): its
+ // queue clock starts then.
+ if (res?.sentAt && res.sentAt > run.submitted_at) {
+ recordSubmission(r.id, res.sentAt);
+ run = { submitted_at: res.sentAt, started_at: null };
+ }
// A job that has just left the queue gets its full running time from now.
const startsNow = res?.state === "running" && !run.started_at;
const overdue = run.started_at ? now - run.started_at > TIMEOUT_MS : !startsNow && now - run.submitted_at > queueMs;
@@ -1724,7 +1736,9 @@ async function pollOne(r: Row): Promise<void> {
status: "failed",
error: run.started_at
? `Timed out after ${TIMEOUT_MS / 60_000} minutes`
- : account
+ : res?.state === "queued" && res.timeoutError
+ ? res.timeoutError
+ : account
? `Timed out waiting ${queueMs / 60_000} minutes in your ComfyUI's queue`
: `Timed out waiting ${QUEUE_TIMEOUT_MS / 3_600_000} hours in the provider's queue`,
completed_at: now,
@@ -1738,7 +1752,9 @@ async function pollOne(r: Row): Promise<void> {
return;
}
if (res.state === "failed") {
- update(r.id, { status: "failed", error: res.error, completed_at: Date.now(), message: null });
+ // What the GPU was missing (a model, a node class): the tile offers "Fix it", and the GPU's check counts as stale.
+ update(r.id, { status: "failed", error: res.error, completed_at: Date.now(), message: null, ...(res.fix && { fix_json: JSON.stringify(res.fix) }) });
+ if (res.fix) markStale(account ? `acct:${account}` : "install");
return;
}
// Mark first so a slow download isn't polled twice.
@@ -2063,9 +2079,34 @@ async function persistAccountOutput(o: RichOutput, generationId: string, account
};
}
+/**
+ * A result a computer sent in (its task received and checked it, src/server/computer): moved into the files folder as it
+ * is, no second copy, as the type its bytes said. An account's counts against its files first.
+ */
+async function persistRelayOutput(o: RichOutput, generationId: string, account: string | undefined, linked: Record<string, unknown> | undefined): Promise<OutputFile> {
+ const file = relayFile(o.url);
+ if (!file) throw new Error("The result isn't here any more");
+ const from = file.path;
+ const contentType = o.contentType ?? file.contentType ?? "application/octet-stream";
+ const size = fs.statSync(from).size;
+ if (account) roomFor(account, size);
+ const asset = adoptFile({ from, contentType: account ? accountType(contentType) : contentType, source: "generation", generationId, ...(account && { accountId: account }) });
+ const meta = relinkMain(linked, o.url, asset.url);
+ const text = o.text ?? (asset.kind === "text" && asset.size <= MAX_INLINE_TEXT * 4 ? fs.readFileSync(absolutePath(asset.relPath), "utf8") : undefined);
+ return {
+ url: asset.url,
+ kind: asset.contentType === "application/octet-stream" ? (o.kind ?? asset.kind) : asset.kind,
+ contentType: asset.contentType,
+ assetId: asset.id,
+ ...inlineText(text, meta),
+ ...(o.draftId ? { draftId: o.draftId } : {}),
+ };
+}
+
async function persistOutput(o: RichOutput, generationId: string): Promise<OutputFile> {
const linked = await persistArtifacts(o.meta, generationId, o.url);
const account = tenantAccount();
+ if (o.url?.startsWith("relay:")) return persistRelayOutput(o, generationId, account, linked);
if (account && o.url && /^https?:\/\//.test(o.url)) return persistAccountOutput(o, generationId, account, linked);
let data: Buffer;
let contentType = o.contentType;
diff --git a/src/server/gpu/browser-inventory.ts b/src/server/gpu/browser-inventory.ts
new file mode 100644
index 00000000..6d93e5de
--- /dev/null
+++ b/src/server/gpu/browser-inventory.ts
@@ -0,0 +1,63 @@
+import "server-only";
+import { z } from "zod";
+import type { GpuInventory } from "@/lib/gpu/types";
+
+/**
+ * A check a Fuobe tab made of the ComfyUI on its own computer (lib/gpu/gather.ts run in the browser), as the server
+ * keeps it: every field checked and capped, unknown ones dropped. It comes from the person's own machine, so it can
+ * only say what that person's own board and badges show; nothing else reads it.
+ */
+const text = (n: number) => z.string().max(n);
+const count = z.number().finite().nonnegative();
+const names = (n: number, len = 256) => z.array(text(len)).max(n);
+
+const Inventory = z.object({
+ v: z.literal(1),
+ via: z.literal("browser"),
+ checkedAt: count,
+ tookMs: count,
+ reachable: z.boolean(),
+ problem: z.enum(["unreachable", "auth", "not-comfy", "timeout", "cors-off", "lna-blocked", "redirect"]).optional(),
+ problemDetail: text(300).optional(),
+ comfy: z
+ .object({
+ version: text(40),
+ os: text(20),
+ python: text(20).optional(),
+ torch: text(40).optional(),
+ embeddedPython: z.boolean(),
+ deployEnv: text(40),
+ flags: z.object({
+ listen: text(200).nullable(),
+ loopbackOnly: z.boolean(),
+ corsOrigin: text(200).nullable(),
+ enableManager: z.boolean(),
+ managerLegacyUi: z.boolean(),
+ lowvram: z.boolean(),
+ cpuOnly: z.boolean(),
+ }),
+ modelRoots: z.record(text(64), names(16, 512)).optional(),
+ apiPrefix: z.enum(["", "/api"]).optional(),
+ })
+ .optional(),
+ devices: z.array(z.object({ name: text(120), type: text(20), index: count, vramTotal: count, vramFree: count })).max(8),
+ ram: z.object({ total: count, free: count }).optional(),
+ manager: z.object({ api: z.enum(["v4", "v3", "none", "unknown"]), version: text(40).optional(), legacyUi: z.boolean().optional(), csrfPost: z.boolean().optional(), busy: z.boolean().optional() }),
+ nodes: z.object({ have: names(20_000, 128), missing: names(20_000, 128), total: count, readAt: count, how: z.enum(["object_info", "per-class"]) }),
+ combos: z.record(text(200), names(5_000)),
+ packs: z.record(text(200), z.object({ dir: text(200), version: text(80).optional(), enabled: z.boolean(), importError: text(2_000).optional() })),
+ models: z.record(text(64), z.object({ have: z.record(text(256), count.nullable()), total: count, folderMissing: z.boolean().optional() })),
+ loras: z.record(text(256), count.nullable()),
+ fingerprint: text(128),
+ errors: z.array(z.object({ step: text(64), message: text(300) })).max(50),
+});
+
+/** The biggest check a tab may send. */
+export const BROWSER_INVENTORY_BYTES = 2 * 2 ** 20;
+
+/** The check as kept, or null when it isn't one. Its time is the server's (a computer's clock can't make it look fresh). */
+export function cleanInventory(raw: unknown, now = Date.now()): GpuInventory | null {
+ const r = Inventory.safeParse(raw);
+ if (!r.success) return null;
+ return { ...r.data, checkedAt: now } as GpuInventory;
+}
diff --git a/src/server/gpu/gate.ts b/src/server/gpu/gate.ts
index 4cf995b1..09b33f59 100644
--- a/src/server/gpu/gate.ts
+++ b/src/server/gpu/gate.ts
@@ -62,8 +62,12 @@ export async function gateGeneration(t: GpuTarget, g: GateInput): Promise<GateRe
if (!snap?.inventory.reachable) return { ok: true };
let r = toolReadiness(ref, name, [id], loras, snap.inventory, idx, ctx, model?.cloud);
if (!blocks(r)) return { ok: true };
- // Confirm with a live read of just these classes and folders, unless the snapshot is from the last 10 s.
- if (Date.now() - snap.checkedAt > 10_000 && r.state !== "unsupported") {
+ // A ComfyUI on the person's computer is read by their tab, which checks the tool right before the run: only a check
+ // from the last 10 s counts as confirmed (an older one never blocks; ComfyUI's own answer has the last word).
+ if (t.via === "browser") {
+ if (Date.now() - snap.checkedAt > 10_000) return { ok: true };
+ } else if (Date.now() - snap.checkedAt > 10_000 && r.state !== "unsupported") {
+ // Confirm with a live read of just these classes and folders, unless the snapshot is from the last 10 s.
const fresh = await probe(t, { actor: g.actor, ...needTargets(r.needs, idx), loraNames: loras.map((l) => l.file) }).catch(() => null);
if (!fresh?.reachable) return { ok: true };
snap = readSnapshot(t);
@@ -72,9 +76,9 @@ export async function gateGeneration(t: GpuTarget, g: GateInput): Promise<GateRe
if (!blocks(r)) return { ok: true };
}
const dev = snap.inventory.devices[0];
- const plan = fixPlan(r, snap.inventory, idx, { hash: sha256, urlHash: urlHash(t), account: t.kind === "account", loras, gpu: dev ? deviceLabel(dev.name) : undefined });
+ const plan = fixPlan(r, snap.inventory, idx, { hash: sha256, urlHash: urlHash(t), account: ctx.account, loras, gpu: dev ? deviceLabel(dev.name) : undefined });
const what = r.state === "unsupported" ? "needs a second ComfyUI" : `needs ${r.needs.filter((n) => n.kind !== "hf-licence").length} more thing${r.needs.length > 1 ? "s" : ""} on your ComfyUI`;
- if (t.kind === "install") return { ok: true, warning: `${name} ${what}. Open Connect your GPU to see them.` };
+ if (t.key === "install") return { ok: true, warning: `${name} ${what}. Open Connect your GPU to see them.` };
return { ok: false, ref, plan, message: `${name} ${what} before it can run.` };
}
diff --git a/src/server/gpu/readiness-service.ts b/src/server/gpu/readiness-service.ts
index eb9fcae4..758bdfe9 100644
--- a/src/server/gpu/readiness-service.ts
+++ b/src/server/gpu/readiness-service.ts
@@ -9,7 +9,7 @@ import { getSetting } from "../settings";
import { loadIndex } from "./index-file";
import { probe, readSnapshot, saveViews, checkWait, type Snapshot } from "./snapshots";
import { STUDIO_ROWS, openModelTools, presetTools, studioOthers, studioTool, toolFor, type Tool } from "./tools";
-import { urlHash, type ServerTarget } from "./target";
+import { urlHash, type ReadTarget } from "./target";
/**
* The views of a snapshot (SPEC §7.3, §10): the readiness board, the badge map, and one tool's fix plan.
@@ -17,8 +17,8 @@ import { urlHash, type ServerTarget } from "./target";
* plan's re-check of its own classes and folders when the snapshot is more than 60 s old.
*/
-export function contextFor(t: ServerTarget): ReadinessContext {
- return { account: t.kind === "account", isolatedUrl: t.kind === "install" && !!getSetting("comfyIsolatedUrl") };
+export function contextFor(t: ReadTarget): ReadinessContext {
+ return { account: t.kind === "account" || (t.kind === "computer" && t.key !== "install"), isolatedUrl: t.kind === "install" && !!getSetting("comfyIsolatedUrl") };
}
export function readinessOf(tool: Tool, inv: GpuInventory, idx: RequirementIndex, ctx: ReadinessContext): ToolReadiness {
@@ -65,7 +65,7 @@ export function buildViews(inv: GpuInventory, idx: RequirementIndex, ctx: Readin
}
/** The views for a snapshot, cached on it. */
-export function viewsOf(t: ServerTarget, snap: Snapshot): Views {
+export function viewsOf(t: ReadTarget, snap: Snapshot): Views {
const idx = loadIndex();
const cached = snap.views as { indexHash: string; data: Views } | undefined;
if (cached && cached.indexHash === idx.hash) return cached.data;
@@ -77,8 +77,8 @@ export function viewsOf(t: ServerTarget, snap: Snapshot): Views {
/** GET /api/gpu/readiness: the stored check's board (never probes). */
export interface ReadinessView {
connected: boolean;
- /** Whose ComfyUI: the studio's own, or the account's. */
- target?: "install" | "account";
+ /** Whose ComfyUI: the studio's own, the account's, or the one on the person's computer (its tab checks it). */
+ target?: "install" | "account" | "computer";
reason?: "guest" | "no-gpu" | "token" | "refused" | "off";
checkedAt?: number | null;
stale?: boolean;
@@ -90,9 +90,9 @@ export interface ReadinessView {
report?: ReadinessReport;
}
-export function readinessView(t: ServerTarget): ReadinessView {
+export function readinessView(t: ReadTarget): ReadinessView {
const snap = readSnapshot(t);
- const base: ReadinessView = { connected: true, target: t.kind, wait: checkWait(t) };
+ const base: ReadinessView = { connected: true, target: t.kind, wait: t.via === "server" ? checkWait(t) : 0 };
if (!snap) return { ...base, checkedAt: null };
const inv = snap.inventory;
if (!inv.reachable) {
@@ -101,7 +101,7 @@ export function readinessView(t: ServerTarget): ReadinessView {
return { ...base, checkedAt: snap.checkedAt, stale: snap.stale, report: viewsOf(t, snap).report };
}
-export function badgesView(t: ServerTarget): BadgeMap {
+export function badgesView(t: ReadTarget): BadgeMap {
const snap = readSnapshot(t);
if (!snap || !snap.inventory.reachable) return { connected: true, ...(snap && { checkedAt: snap.checkedAt }), models: {}, presets: {} };
// Badges count as fresh for 10 minutes; past that they still show (the board offers "Check again").
@@ -114,7 +114,7 @@ const sha256 = (s: string) => crypto.createHash("sha256").update(s).digest("hex"
* A tool's fix plan from the snapshot. When the snapshot is more than 60 s old and says something is missing,
* the plan's own classes and folders are read again first (sharing the target's probe and its 10 s limit).
*/
-export async function planFor(t: ServerTarget, ref: string, actor: string): Promise<FixPlan | null> {
+export async function planFor(t: ReadTarget, ref: string, actor: string): Promise<FixPlan | null> {
const tool = toolFor(ref);
if (!tool) return null;
const idx = loadIndex();
@@ -122,7 +122,8 @@ export async function planFor(t: ServerTarget, ref: string, actor: string): Prom
let snap = readSnapshot(t);
if (!snap) return null;
let r = readinessOf(tool, snap.inventory, idx, ctx);
- if (snap.inventory.reachable && r.needs.length && Date.now() - snap.checkedAt > 60_000 && checkWait(t) === 0) {
+ // (A computer's ComfyUI is read by its tab: the plan is from what it sent last.)
+ if (t.via === "server" && snap.inventory.reachable && r.needs.length && Date.now() - snap.checkedAt > 60_000 && checkWait(t) === 0) {
const targets = needTargets(r.needs, idx);
await probe(t, { actor, ...targets, loraNames: tool.loras.map((l) => l.file) }).catch(() => null);
snap = readSnapshot(t) ?? snap;
@@ -130,11 +131,11 @@ export async function planFor(t: ServerTarget, ref: string, actor: string): Prom
}
const fits = fitsFor(tool, t, snap.inventory, idx, ctx);
const gpu = snap.inventory.devices[0] ? deviceLabel(snap.inventory.devices[0].name) : undefined;
- return fixPlan(r, snap.inventory, idx, { hash: sha256, urlHash: urlHash(t), account: t.kind === "account", loras: tool.loras, fits, gpu: gpu && vramGb(snap.inventory.devices[0].vramTotal) ? gpu : undefined });
+ return fixPlan(r, snap.inventory, idx, { hash: sha256, urlHash: urlHash(t), account: ctx.account, loras: tool.loras, fits, gpu: gpu && vramGb(snap.inventory.devices[0].vramTotal) ? gpu : undefined });
}
/** Other tools of the same studio that fit this GPU (for the "needs a bigger GPU" sheet). */
-function fitsFor(tool: Tool, t: ServerTarget, inv: GpuInventory, idx: RequirementIndex, ctx: ReadinessContext): { ref: ToolRef; name: string; state: "ready" | "almost" }[] {
+function fitsFor(tool: Tool, t: ReadTarget, inv: GpuInventory, idx: RequirementIndex, ctx: ReadinessContext): { ref: ToolRef; name: string; state: "ready" | "almost" }[] {
const op = /#(.+)$/.exec(tool.ref)?.[1];
const row = STUDIO_ROWS.find((s) => s.config && (s.config.defaultModels.open === tool.ref.replace(/^model:|#.*$/g, "") || (op && s.config.ops.includes(op as never) && s.config.kind === tool.kind)));
if (!row) return [];
diff --git a/src/server/gpu/snapshots.ts b/src/server/gpu/snapshots.ts
index 3904753c..c1ad1b91 100644
--- a/src/server/gpu/snapshots.ts
+++ b/src/server/gpu/snapshots.ts
@@ -3,7 +3,7 @@ import { db } from "../db";
import { gatherInventory, type GatherOptions } from "@/lib/gpu/gather";
import type { CheckLine, GpuInventory } from "@/lib/gpu/types";
import { loadIndex } from "./index-file";
-import { targetHost, transportFor, urlHash, type ServerTarget, type TransportOptions } from "./target";
+import { targetHost, transportFor, urlHash, type ReadTarget, type ServerTarget, type TransportOptions } from "./target";
/**
* Snapshots of what a target's ComfyUI had (SPEC §5.2, §15), in memory and in SQLite, per target and per way it
@@ -51,12 +51,12 @@ export const CHECK_INTERVAL_MS = 10_000;
const memKey = (key: string, via: string) => `${key}|${via}`;
-export function readSnapshot(t: ServerTarget): Snapshot | null {
+export function readSnapshot(t: ReadTarget): Snapshot | null {
const hash = urlHash(t);
- const k = memKey(t.key, "server");
+ const k = memKey(t.key, t.via);
const hit = mem().get(k);
if (hit) return hit.urlHash === hash ? hit : null;
- const row = db().prepare("SELECT * FROM gpu_snapshots WHERE target_key = ? AND via = 'server'").get(t.key) as Row | undefined;
+ const row = db().prepare("SELECT * FROM gpu_snapshots WHERE target_key = ? AND via = ?").get(t.key, t.via) as Row | undefined;
if (!row || row.url_hash !== hash) return null;
let inventory: GpuInventory;
try {
@@ -68,22 +68,23 @@ export function readSnapshot(t: ServerTarget): Snapshot | null {
try {
views = row.report_json ? (JSON.parse(row.report_json) as Snapshot["views"]) : undefined;
} catch {}
- const snap: Snapshot = { targetKey: row.target_key, via: "server", urlHash: row.url_hash, checkedAt: row.checked_at, indexHash: row.index_hash, inventory, views, stale: !!row.stale };
+ const snap: Snapshot = { targetKey: row.target_key, via: t.via, urlHash: row.url_hash, checkedAt: row.checked_at, indexHash: row.index_hash, inventory, views, stale: !!row.stale };
mem().set(k, snap);
return snap;
}
-export function writeSnapshot(t: ServerTarget, inventory: GpuInventory): Snapshot {
- const snap: Snapshot = { targetKey: t.key, via: "server", urlHash: urlHash(t), checkedAt: inventory.checkedAt, indexHash: loadIndex().hash, inventory, stale: false };
+/** Keep a check (the server's own, or one a computer's tab sent in for its own ComfyUI). */
+export function writeSnapshot(t: ReadTarget, inventory: GpuInventory): Snapshot {
+ const snap: Snapshot = { targetKey: t.key, via: t.via, urlHash: urlHash(t), checkedAt: inventory.checkedAt, indexHash: loadIndex().hash, inventory, stale: false };
db()
.prepare(
`INSERT INTO gpu_snapshots (target_key, via, url_hash, checked_at, index_hash, inventory_json, report_json, stale)
- VALUES (@target_key, 'server', @url_hash, @checked_at, @index_hash, @inventory_json, NULL, 0)
+ VALUES (@target_key, @via, @url_hash, @checked_at, @index_hash, @inventory_json, NULL, 0)
ON CONFLICT(target_key, via) DO UPDATE SET url_hash = excluded.url_hash, checked_at = excluded.checked_at, index_hash = excluded.index_hash,
inventory_json = excluded.inventory_json, report_json = NULL, stale = 0`,
)
- .run({ target_key: t.key, url_hash: snap.urlHash, checked_at: snap.checkedAt, index_hash: snap.indexHash, inventory_json: JSON.stringify(inventory) });
- mem().set(memKey(t.key, "server"), snap);
+ .run({ target_key: t.key, via: t.via, url_hash: snap.urlHash, checked_at: snap.checkedAt, index_hash: snap.indexHash, inventory_json: JSON.stringify(inventory) });
+ mem().set(memKey(t.key, t.via), snap);
return snap;
}
diff --git a/src/server/gpu/target.ts b/src/server/gpu/target.ts
index eca8d624..891aba17 100644
--- a/src/server/gpu/target.ts
+++ b/src/server/gpu/target.ts
@@ -10,24 +10,34 @@ import { isInstallHost } from "./hosts";
/**
* Whose ComfyUI the pre-flight reads (SPEC §3). The owner's session reads the install's own ComfyUI; an
* account reads only the ComfyUI it connected ("Your GPU"), never the install's (R4); a guest reads nothing.
- * An API token may read the install's, but never starts a fix (R1).
+ * An API token may read the install's, but never starts a fix (R1). A ComfyUI on the person's own computer ("Use the
+ * ComfyUI on this computer": an account's, or the owner's when Settings says so) is read by their Fuobe tab, never by
+ * the server: its target is "computer", and the tab sends what it found (PUT /api/gpu/inventory).
*/
export type GpuTarget =
| { kind: "install"; key: "install"; via: "server" }
- | { kind: "account"; key: `acct:${string}`; accountId: string; via: "server"; gpu: AccountGpu }
+ | { kind: "account"; key: `acct:${string}`; accountId: string; via: "server"; gpu: { url: string; token?: string } }
+ | { kind: "computer"; key: "install" | `acct:${string}`; accountId?: string; via: "browser" }
| { kind: "none"; reason: "guest" | "no-gpu" | "token" | "refused" };
export type ServerTarget = Extract<GpuTarget, { via: "server" }>;
+export type BrowserTarget = Extract<GpuTarget, { via: "browser" }>;
+/** A target whose last check can be read (by the server, or sent in by the person's tab). */
+export type ReadTarget = ServerTarget | BrowserTarget;
export function gpuTargetFor(request: Request, purpose: "read" | "fix"): GpuTarget {
const viewer = requestViewer(request);
if (viewer.kind === "guest") return { kind: "none", reason: "guest" };
if (viewer.kind === "owner") {
if (purpose === "fix" && validToken(request.headers.get("authorization"))) return { kind: "none", reason: "token" };
+ // ComfyUI on the owner's own computer: only the owner's tab there reads it (an API token reads nothing then).
+ if (getSetting("comfyWhere") === "computer") return validToken(request.headers.get("authorization")) ? { kind: "none", reason: "token" } : { kind: "computer", key: "install", via: "browser" };
return { kind: "install", key: "install", via: "server" };
}
const gpu = accountGpu(viewer.account.id);
if (!gpu) return { kind: "none", reason: "no-gpu" };
+ // The ComfyUI on the person's own computer: the server never reads it (the person's tab does).
+ if (gpu.mode === "computer") return { kind: "computer", key: `acct:${viewer.account.id}`, accountId: viewer.account.id, via: "browser" };
// The install's own ComfyUI under any scheme, port or path (its address may have changed since the link was saved).
if (isInstallHost(gpu.url)) return { kind: "none", reason: "refused" };
return { kind: "account", key: `acct:${viewer.account.id}`, accountId: viewer.account.id, via: "server", gpu };
@@ -38,7 +48,9 @@ export function targetUrl(t: ServerTarget): string {
return (t.kind === "install" ? getSetting("comfyUrl") : t.gpu.url).trim().replace(/\/+$/, "");
}
-export function urlHash(t: ServerTarget): string {
+export function urlHash(t: ReadTarget): string {
+ // A computer's ComfyUI has no address the server knows: one per principal, as its tab reads it.
+ if (t.via === "browser") return crypto.createHash("sha256").update(`${t.key}|computer|browser`).digest("hex");
return crypto.createHash("sha256").update(`${targetUrl(t).toLowerCase()}|server`).digest("hex");
}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 656f9cd9..6fa1c5bd 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -2,6 +2,7 @@ import "server-only";
import { AsyncLocalStorage } from "node:async_hooks";
import fs from "node:fs";
import path from "node:path";
+import { Readable } from "node:stream";
import { tracksFor, type MotionPaths } from "@/lib/motion-paths";
import { nanoid } from "nanoid";
import {
@@ -67,9 +68,31 @@ import { discardBody, fetchPublic, RemoteFetchError } from "../remote-fetch";
import { zipToFile } from "../zip";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "../account-files";
import { accountSend } from "../account-send";
-import { tenantAccount } from "../tenant";
+import { outsideTenant, runAsTenant, tenantAccount } from "../tenant";
import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";
-import { ProviderError, type ProviderAdapter, type RemoteOutput } from "./types";
+import { ProviderError, type PollResult, type ProviderAdapter, type RemoteOutput } from "./types";
+import { isOutOfMemory } from "@/lib/gpu/fix-codes";
+import { makingWords, queueWords, RELAY_WORDS, savingWords, sendingWords, tabFailureWords, type HistoryEntryLike, type TabFailure, type WantedFile } from "@/lib/relay";
+import type { GenerationFix } from "@/lib/catalog/types";
+import {
+ checkClocks,
+ createTask,
+ extraOf,
+ getTask,
+ inputKinds,
+ receivedFile,
+ receivedOf,
+ refusalOf,
+ requestStop,
+ resultOf,
+ runnerFacts,
+ runnerOnline,
+ stageInput,
+ taskProgress,
+ type FinishedPlan,
+ type Principal,
+ type TaskRow,
+} from "../computer/tasks";
export const WORKFLOW_DIR = path.join(process.cwd(), "workflows", "comfyui");
@@ -105,11 +128,11 @@ export const ISOLATED_SETTING = "Settings → Open-source engine · ComfyUI →
// ---------------------------------------------------------------------------
// An account's own ComfyUI (public sign-up, "Your GPU")
-/** Where an account's run goes: its own ComfyUI (a public address), with its own token. */
-export interface OwnGpu {
- url: string;
- token?: string;
-}
+/**
+ * Where an account's run goes: its own ComfyUI at a public address (a link: a tunnel), with its own token; or the
+ * ComfyUI on the person's own computer ("computer"), which only their Fuobe tab reaches (src/server/computer).
+ */
+export type OwnGpu = { kind?: "link"; url: string; token?: string } | { kind: "computer"; principal: `acct:${string}` };
const ownGpuStore = new AsyncLocalStorage<OwnGpu>();
@@ -117,23 +140,60 @@ const ownGpuStore = new AsyncLocalStorage<OwnGpu>();
* Run `fn` on an account's own ComfyUI: every ComfyUI call inside (uploads, the prompt, polls, outputs)
* goes to `gpu` through fetchPublic, which connects only to public addresses, so it can't reach the
* install's own ComfyUI, even when the account's name is re-pointed at this machine. The install's
- * address and token are never used. Without a socket: progress comes from polling.
+ * address and token are never used. Without a socket: progress comes from polling. On the account's own
+ * computer, every ComfyUI job becomes a task its Fuobe tab runs, and nothing is fetched from here.
*/
export function onOwnGpu<T>(gpu: OwnGpu, fn: () => T): T {
- return ownGpuStore.run({ url: gpu.url.replace(/\/+$/, ""), token: gpu.token }, fn);
+ return ownGpuStore.run(gpu.kind === "computer" ? { kind: "computer", principal: gpu.principal } : { url: gpu.url.replace(/\/+$/, ""), token: gpu.token }, fn);
}
/** Inside onOwnGpu: the account's ComfyUI. */
export const ownGpu = (): OwnGpu | undefined => ownGpuStore.getStore();
+/** Inside onOwnGpu with a link: its address and token. */
+const ownLink = (): { url: string; token?: string } | undefined => {
+ const own = ownGpu();
+ return own && own.kind !== "computer" ? own : undefined;
+};
+
/** Run `fn` outside any account's ComfyUI (the install's own again). */
export const outsideOwnGpu = <T,>(fn: () => T): T => ownGpuStore.exit(fn);
+/**
+ * The ComfyUI in scope runs on someone's own computer, reached only through their Fuobe tab: whose (an account's
+ * "acct:<id>", or the owner's when Settings says ComfyUI runs on the owner's computer), else undefined.
+ */
+export function computerScope(): Principal | undefined {
+ const own = ownGpu();
+ if (own) return own.kind === "computer" ? own.principal : undefined;
+ return getSetting("comfyWhere") === "computer" ? "owner" : undefined;
+}
+
+/** Said when something would call a ComfyUI that only the person's own tab may reach. */
+export const ON_COMPUTER_ONLY = "This ComfyUI is on your own computer: only your Fuobe tab there talks to it.";
+
/** The most an account's ComfyUI may send back for one output file, and how long it may take. */
export const OWN_OUTPUT_LIMITS = { maxBytes: 2 ** 30, deadlineMs: 15 * 60_000 };
+/** A result a computer sent in (relay:<task>/view?…&n=…): the file its task received, for that task's principal only. */
+export function relayFile(url: string): { path: string; contentType?: string } | null {
+ const principal = computerScope();
+ const m = /^relay:([A-Za-z0-9_-]{16})\/view\?(.*)$/.exec(url);
+ const n = m ? Number(new URLSearchParams(m[2]).get("n")) : NaN;
+ return principal && m && Number.isInteger(n) ? receivedFile(principal, m[1], n) : null;
+}
+
+/** A computer's result as a fetch() answer (bundleFrames and the layer boxes read results this way). */
+function relayResponse(url: string): Response {
+ const file = relayFile(url);
+ if (!file) return new Response("Not found", { status: 404 });
+ const stream = Readable.toWeb(fs.createReadStream(file.path)) as ReadableStream<Uint8Array>;
+ return new Response(stream, { headers: { "content-type": file.contentType ?? "application/octet-stream", "content-length": String(fs.statSync(file.path).size) } });
+}
+
/** fetch() for a provider's file: through fetchPublic on an account's own ComfyUI (1 GB and 15 minutes at most, or less). */
export function outputFetch(url: string, init: RequestInit = {}, o: { maxBytes?: number } = {}): Promise<Response> {
+ if (url.startsWith("relay:")) return Promise.resolve(relayResponse(url));
if (!ownGpu()) return fetch(url, init);
const maxBytes = Math.max(1, Math.min(OWN_OUTPUT_LIMITS.maxBytes, o.maxBytes ?? Infinity));
return fetchPublic(url, init, { timeoutMs: 120_000, ...OWN_OUTPUT_LIMITS, maxBytes });
@@ -160,7 +220,8 @@ export const PROMPT_ID = /^[\w-]{1,64}$/;
function baseUrl(worker: ComfyWorker = "main"): string {
const own = ownGpu();
- if (own) return own.url;
+ if (own) return own.kind === "computer" ? "" : own.url;
+ if (computerScope()) return "";
return getSetting(worker === "isolated" ? "comfyIsolatedUrl" : "comfyUrl").replace(/\/+$/, "");
}
@@ -174,7 +235,8 @@ const sameAddress = (a: string, b: string) => a.replace(/\/+$/, "") === b.replac
function authHeaders(worker: ComfyWorker = "main"): Record<string, string> {
const own = ownGpu();
- if (own) return own.token ? { Authorization: `Bearer ${own.token}` } : {};
+ if (own) return own.kind !== "computer" && own.token ? { Authorization: `Bearer ${own.token}` } : {};
+ if (computerScope()) return {};
// Save & test of an address that isn't the saved one: the saved token stays with the server it
// was saved for. Only a token typed for this test goes to the new address.
const address = worker === "isolated" ? "comfyIsolatedUrl" : "comfyUrl";
@@ -184,6 +246,9 @@ function authHeaders(worker: ComfyWorker = "main"): Record<string, string> {
}
async function comfyFetch(p: string, init: RequestInit = {}, worker: ComfyWorker = "main"): Promise<Response> {
+ // A ComfyUI on someone's own computer is never called from here: not the install's, not a link (every caller in that
+ // scope goes through its task instead; this is the last guard).
+ if (computerScope()) throw new ProviderError(ON_COMPUTER_ONLY);
const base = baseUrl(worker);
if (ownGpu()) {
// A visitor without a GPU of its own (a price check): nothing to reach, and never the install's.
@@ -271,8 +336,8 @@ function setSocket(worker: ComfyWorker, s: ComfySocket | undefined) {
}
function ensureSocket(worker: ComfyWorker = "main"): { clientId: string; progress: Map<string, Progress> } {
- // An account's own ComfyUI: no socket (the install's stays as it is); its progress comes from polling.
- if (ownGpu()) return { clientId: "fuobe-account", progress: new Map() };
+ // An account's own ComfyUI: no socket (the install's stays as it is); its progress comes from polling, or from its tab.
+ if (ownGpu() || computerScope()) return { clientId: "fuobe-account", progress: new Map() };
const url = baseUrl(worker);
const cur = socketOf(worker);
if (cur && cur.url === url && cur.ws.readyState <= 1) return cur;
@@ -573,8 +638,9 @@ async function checkComfy(url: string): Promise<boolean> {
/** Is the ComfyUI server reachable? Cached for 10 s (`force` checks now); one check runs at a time. */
export async function probeComfy(force = false): Promise<boolean> {
- // An account's own ComfyUI is taken as there: its run says so when it isn't (the install's state stays its own).
- if (ownGpu()) return true;
+ // An account's own ComfyUI is taken as there: its run says so when it isn't (the install's state stays its own). So is
+ // one on a computer: its runs wait for a tab there.
+ if (ownGpu() || computerScope()) return true;
const url = baseUrl();
const cur = globalThis.__fuobeComfyReach;
if (!force && cur && cur.url === url && Date.now() - cur.at < 10_000) return cur.ok;
@@ -606,6 +672,9 @@ declare global {
* (devices[0], as Settings' test reads it), kept for a minute; undefined when the server doesn't say or can't be reached.
*/
export async function comfyDevice(worker: ComfyWorker = "main"): Promise<string | undefined> {
+ // On someone's computer: what its Fuobe tab last said ("cuda:0 NVIDIA …").
+ const computer = computerScope();
+ if (computer) return /^[a-z]+/i.exec(runnerFacts(computer)?.device ?? "")?.[0].toLowerCase();
const url = baseUrl(worker);
if (!url) return undefined;
const cache = (globalThis.__fuobeComfyDevice ??= new Map());
@@ -645,6 +714,8 @@ export async function comfyDbsModels(worker: ComfyWorker = "main", maxAgeMs = 10
/** The connected ComfyUI's RAM in bytes, as the last reachability check read it (whole-clip tools' budget). */
export function comfyRam(): number | undefined {
+ const computer = computerScope();
+ if (computer) return runnerFacts(computer)?.ramBytes;
if (ownGpu()) return undefined;
const cur = globalThis.__fuobeComfyReach;
return cur?.ok && cur.url === baseUrl() ? cur.ram : undefined;
@@ -656,7 +727,7 @@ export function comfyRam(): number | undefined {
* the background to say for sure.
*/
export function probeComfySync(timeoutMs = 1500): boolean {
- if (ownGpu()) return true;
+ if (ownGpu() || computerScope()) return true;
const url = baseUrl();
const { reach, sure } = reachSync(url, `${url}/system_stats`, timeoutMs, authHeaders());
globalThis.__fuobeComfyReach = reach;
@@ -677,12 +748,26 @@ declare global {
const MEDIA_FILE = /^(video|audio)\//;
const MEDIA_EXT = /\.(mp4|m4v|mov|m4a|wav|flac|mp3)$/i;
-/** A file name as remembered: an account's ComfyUI names its own files, so they are kept apart by its address. */
+/** A file name as remembered: an account's ComfyUI names its own files, so they are kept apart by its address (or whose computer). */
const mediaKey = (name: string) => {
const own = ownGpu();
- return own ? `${own.url}|${name}` : name;
+ const computer = computerScope();
+ if (computer) return `${computer}|${name}`;
+ return own && own.kind !== "computer" ? `${own.url}|${name}` : name;
};
+/** What the server reads from a file it sends to ComfyUI (a clip's length and size, a picture's size), by its name there. */
+function rememberSent(uploaded: string, data: Buffer, contentType: string, name: string) {
+ if (MEDIA_FILE.test(contentType) || MEDIA_EXT.test(name) || /\.(webm|mkv|avi)$/i.test(name)) {
+ const info = probeMedia(data) ?? webmInfo(data) ?? aviInfo(data);
+ if (info) rememberMedia(uploaded, info);
+ } else if (/^image\//.test(contentType)) {
+ // A start frame's size: "auto" makes an image-to-video clip in the picture's own shape.
+ const size = imageSize(data);
+ if (size) rememberMedia(uploaded, { container: "image", ...size, hasVideo: false, hasAudio: false });
+ }
+}
+
function rememberMedia(name: string, info: MediaInfo) {
const seen = (globalThis.__fuobeComfyMedia ??= new Map());
seen.set(mediaKey(name), info);
@@ -1462,10 +1547,42 @@ export function withoutAnchor(wf: ComfyWorkflow, loaderId: string): ComfyWorkflo
return out;
}
+/** What ComfyUI's /prompt answers when it refuses a graph. */
+export type PromptRefusalBody = { error?: { type?: string; message?: string; extra_info?: { class_type?: string } }; node_errors?: unknown };
+
+/**
+ * A /prompt refusal in words, with what was missing as a code its failed tile turns into "Fix it" (the GPU pre-flight's
+ * guided fix). The same for the server's own ComfyUI, a link, and one on someone's computer (its tab reports the answer).
+ */
+export function promptRefusal(body: PromptRefusalBody, status: number, manifest: ManifestWorkflow, loras: { file: string; url?: string }[], worker: ComfyWorker = "main"): { message?: string; fix?: ReturnType<typeof fixFromPromptError> } {
+ // The index names the pack a missing class comes from, so the message names that pack, not every pack the workflow uses.
+ let packOf: (cls: string) => string | undefined = () => undefined;
+ try {
+ const idx = loadIndex();
+ packOf = (cls) => Object.entries(idx.packs).find(([, p]) => p.classes.includes(cls))?.[0];
+ } catch {}
+ const fix = fixFromPromptError(body, manifest.id, manifest.models, packOf);
+ const missingClass = fix?.code === "comfy_missing_node" ? fix.items[0] : undefined;
+ // A node class the server doesn't have: name the pack to install (opt-in packs like ComfyUI-Whisper).
+ const packs = missingClass?.pack ? [missingClass.pack] : manifest.customNodes.map((c) => c.name);
+ const where = worker === "isolated" ? "the isolated ComfyUI worker" : "your ComfyUI";
+ const missingPack =
+ body.error?.type === "missing_node_type" && packs.length ? `This workflow needs the ${packs.join(" + ")} node pack${packs.length > 1 ? "s" : ""} on ${where} (see scripts/comfy/README.md)` : undefined;
+ // A LoRA it lacks: point at its model card (a civitai download URL answers 401 without the key) and the LoRA folder setting.
+ const loraModels = loras.map((l) => ({ file: l.file, folder: "loras", url: loraByFile(l.file)?.page ?? (l.url && !needsToken(l.url) ? l.url : undefined) }));
+ let detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...loraModels] }) : (missingPack ?? body.error?.message);
+ // (Settings → LoRAs is the owner's page, for the server's own ComfyUI: an account's, or one on a computer, gets its LoRAs by hand.)
+ if (detail && !ownGpu() && !computerScope() && loraModels.some((l) => detail!.includes(`"${l.file}"`))) detail = `${detail}\nSet the LoRA folder in Settings → LoRAs and Fuobe downloads LoRAs before a run`;
+ void status;
+ return { message: detail, ...(fix && { fix }) };
+}
+
/** Friendlier words for errors that a workflow's nodes report in their own terms. */
function explainExecutionError(err: { exception_message?: string; node_type?: string } | undefined, manifest?: ManifestWorkflow): string {
if (!err) return "Execution error";
const msg = (err.exception_message ?? "").trim();
+ // On someone's own computer the words are theirs: their GPU ran out (the server's own runs keep ComfyUI's words).
+ if (computerScope() && isOutOfMemory(msg)) return RELAY_WORDS.outOfMemory;
const outOfClip = /division by zero|failed to slice video|failed to trim video|no frames exist/i.test(msg);
if (manifest?.expand === "captions" && outOfClip) return "A caption starts after the end of the video — check the cue times";
if (manifest?.capability === "trim" && outOfClip) return "The start time is past the end of the clip";
@@ -1501,6 +1618,13 @@ async function followMetaBatch(prefix: string, manifest: ManifestWorkflow | unde
/** Upload a file to a worker's input folder; returns the name LoadImage / LoadAudio / LoadVideo take there. */
async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string, name: string): Promise<string> {
+ // On someone's computer: kept here for the run's task, under the name ComfyUI will get from their tab.
+ const computer = computerScope();
+ if (computer) {
+ const staged = stageInput(computer, data, contentType, name);
+ rememberSent(staged, data, contentType, name);
+ return staged;
+ }
const form = new FormData();
const ext = name.includes(".") ? name.split(".").pop() : contentType.split("/")[1];
form.append("image", new Blob([new Uint8Array(data)], { type: contentType }), `fuobe_${nanoid(8)}.${ext}`);
@@ -1520,14 +1644,7 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,
const j = (await res.json()) as { name: string; subfolder?: string };
const uploaded = j.subfolder ? `${j.subfolder}/${j.name}` : j.name;
// Remember a clip's / track's header facts (length, size, fps, audio) for prepareWorkflow.
- if (MEDIA_FILE.test(contentType) || MEDIA_EXT.test(name) || /\.(webm|mkv|avi)$/i.test(name)) {
- const info = probeMedia(data) ?? webmInfo(data) ?? aviInfo(data);
- if (info) rememberMedia(uploaded, info);
- } else if (/^image\//.test(contentType)) {
- // A start frame's size: "auto" makes an image-to-video clip in the picture's own shape.
- const size = imageSize(data);
- if (size) rememberMedia(uploaded, { container: "image", ...size, hasVideo: false, hasAudio: false });
- }
+ rememberSent(uploaded, data, contentType, name);
return uploaded;
}
@@ -1563,11 +1680,141 @@ async function sweepPasses(prefix: string, worker: ComfyWorker = "main"): Promis
}
}
+// ---------------------------------------------------------------------------
+// A ComfyUI on someone's own computer: its runs are tasks their Fuobe tab does (src/server/computer)
+
+/** Run `fn` as a principal's work on its own computer: an account's (as that account), or the owner's. */
+export function onComputer<T>(principal: Principal, fn: () => T): T {
+ if (principal === "owner") return outsideTenant(() => outsideOwnGpu(fn));
+ return runAsTenant({ kind: "account", id: principal.slice(5) }, () => onOwnGpu({ kind: "computer", principal }, fn));
+}
+
+/** The most one result may weigh when it comes from a computer: an account's 1 GB (less when its files are fuller); the owner's 8 GB. */
+const OWNER_RESULT_BYTES = 8 * 2 ** 30;
+/** A text result (a transcript, captions). */
+const TEXT_RESULT_BYTES = 8 * 2 ** 20;
+
+/**
+ * A computer's finished prompt (its /history entry, or a meta-batch's passes): the results to collect, as the server's
+ * own run would collect them (collectOutputs), each one a file the tab uploads under its number. An account keeps up to
+ * 16 results and 1,800 EXR frames, never more than its files have room for. Call it as the task's principal (onComputer).
+ */
+export function planRelayOutputs(t: Pick<TaskRow, "id" | "workflow_id" | "meta_batch" | "prefix">, entries: HistoryEntryLike[], passes: boolean): FinishedPlan {
+ let manifest: ManifestWorkflow | undefined;
+ try {
+ manifest = t.workflow_id ? getWorkflow(t.workflow_id).manifest : undefined;
+ } catch {}
+ const list = (passes ? [...entries].sort((a, c) => Number(c.prompt?.[0] ?? 0) - Number(a.prompt?.[0] ?? 0)) : entries.slice(0, 1)) as HistoryEntry[];
+ // A pass that failed (out of memory, a node exception) ends the job: say why instead of "no output".
+ const failed = list.find((e) => e?.status?.status_str === "error");
+ if (failed) {
+ const interrupted = failed.status?.messages?.some(([type]) => type === "execution_interrupted");
+ return { error: interrupted ? RELAY_WORDS.stopped : explainExecutionError(executionError(failed), manifest) };
+ }
+ let outputs: ComfyOutput[] = [];
+ for (const e of list) {
+ outputs = collectOutputs(e, manifest, `relay:${t.id}`);
+ if (outputs.length) break;
+ }
+ if (!outputs.length) return t.meta_batch && !passes && t.prefix ? { follow: t.prefix } : { error: "Workflow finished without saving any output" };
+ const account = tenantAccount();
+ let budget = Infinity;
+ if (account) {
+ const frames = outputs.filter((o) => o.meta?.role === "frames");
+ if (frames.length > ACCOUNT_LIMITS.framesPerJob) return { error: `Your ComfyUI made ${frames.length} EXR frames. A run on your GPU keeps up to ${ACCOUNT_LIMITS.framesPerJob}: export a shorter clip.` };
+ outputs = [...outputs.filter((o) => o.meta?.role !== "frames").slice(0, ACCOUNT_LIMITS.outputsPerJob), ...frames];
+ if (!diskHasRoom()) return { error: ACCOUNT_MESSAGES.diskLow };
+ budget = accountTotalBytes(account) - accountUsage(account).total;
+ if (budget <= 0) return { error: filesFullMessage(account) };
+ }
+ const wanted: WantedFile[] = [];
+ outputs = outputs.map((o) => {
+ if (!o.url.startsWith("relay:")) return o;
+ const q = new URLSearchParams(o.url.split("?")[1] ?? "");
+ const n = wanted.length;
+ const frame = o.meta?.role === "frames";
+ const kind: WantedFile["kind"] = frame ? "frame" : o.kind === "image" || o.kind === "video" || o.kind === "audio" || o.kind === "text" || o.kind === "model3d" ? o.kind : "image";
+ const cap = frame ? OWN_FRAME_MAX_BYTES : kind === "text" ? TEXT_RESULT_BYTES : account ? OWN_OUTPUT_LIMITS.maxBytes : OWNER_RESULT_BYTES;
+ wanted.push({ n, filename: q.get("filename") ?? "", subfolder: q.get("subfolder") ?? "", type: q.get("type") === "temp" ? "temp" : "output", kind, maxBytes: Math.max(1, Math.min(cap, budget)) });
+ return { ...o, url: `${o.url}&n=${n}`, headers: undefined };
+ });
+ return { wanted, outputs, budget: Number.isFinite(budget) ? budget : Number.MAX_SAFE_INTEGER };
+}
+
+/** A task's error as the run's words (and what was missing, for "Fix it"). */
+function relayFailure(t: TaskRow, manifest: ManifestWorkflow | undefined): { error: string; fix?: GenerationFix } {
+ const refusal = refusalOf(t);
+ if (refusal && manifest) {
+ const r = promptRefusal((refusal.body ?? {}) as PromptRefusalBody, refusal.status, manifest, extraOf(t).loras ?? []);
+ return { error: r.message ?? `Your ComfyUI refused the job (HTTP ${refusal.status})`, ...(r.fix && { fix: r.fix }) };
+ }
+ if (refusal) return { error: `Your ComfyUI refused the job (HTTP ${refusal.status})` };
+ const e = t.error ?? "";
+ const tab = /^tab:([a-z-]+)(?::(\d+))?$/.exec(e);
+ if (tab) return { error: tabFailureWords(tab[1] as TabFailure, tab[2] ? Number(tab[2]) : undefined) };
+ const words: Record<string, string> = { lost: RELAY_WORDS.lost, silent: RELAY_WORDS.computerSilent, down: RELAY_WORDS.comfyDownTooLong, tooBig: RELAY_WORDS.tooBig };
+ if (e === "full") {
+ const account = tenantAccount();
+ return { error: account ? filesFullMessage(account) : "There's no room to keep this result." };
+ }
+ return { error: words[e] ?? (e || "Your ComfyUI couldn't finish this run") };
+}
+
+/** A run on someone's computer: where its task is, in the words its tile shows. */
+async function pollComputer(principal: Principal, meta: Record<string, unknown>, manifest: ManifestWorkflow | undefined, made: string | undefined): Promise<PollResult> {
+ const found = typeof meta.relay === "string" ? getTask(principal, meta.relay) : null;
+ if (!found) return { state: "failed", error: "This run was lost. Press Retry." };
+ const t = checkClocks(found);
+ const p = taskProgress(t.id);
+ const kind = extraOf(t).made ?? made ?? "image";
+ const waitMinutes = Math.round((tenantAccount() ? ACCOUNT_LIMITS.queueMs : 4 * 3_600_000) / 60_000);
+ const sentAt = t.sent_at ?? undefined;
+ const down = t.down_at ? RELAY_WORDS.comfyDown : undefined;
+ switch (t.state) {
+ case "waiting":
+ return { state: "queued", message: runnerOnline(principal) ? RELAY_WORDS.starting : RELAY_WORDS.noComputer, timeoutError: RELAY_WORDS.waitedTooLong(waitMinutes) };
+ case "sending":
+ return { state: "queued", message: down ?? (t.note === "resent" ? RELAY_WORDS.resent : sendingWords(inputKinds(t))), timeoutError: RELAY_WORDS.waitedTooLong(waitMinutes), ...(sentAt && { sentAt }) };
+ case "queued":
+ return { state: "queued", message: down ?? queueWords(p?.position), ...(sentAt && { sentAt }) };
+ case "running": {
+ const total = Number(meta.nodeCount ?? 0);
+ const stepFrac = p?.max ? (p.value ?? 0) / p.max : 0;
+ const value = total ? Math.min(0.99, (Math.max(1, p?.nodesDone ?? 1) - 1 + stepFrac) / total) : stepFrac || undefined;
+ return { state: "running", progress: value && value > 0 ? value : undefined, message: down ?? makingWords(kind, p?.value, p?.max), ...(sentAt && { sentAt }) };
+ }
+ case "collecting": {
+ const got = receivedOf(t);
+ const total = got.reduce((s, r) => s + r.total, 0);
+ return { state: "running", progress: 0.99, message: down ?? savingWords(total ? got.reduce((s, r) => s + r.bytes, 0) / total : undefined), ...(sentAt && { sentAt }) };
+ }
+ case "done": {
+ const types = new Map(receivedOf(t).map((r) => [r.n, r.contentType]));
+ let outputs = resultOf<ComfyOutput>(t).map((o) => {
+ const n = Number(new URLSearchParams(o.url.split("?")[1] ?? "").get("n"));
+ const type = o.url.startsWith("relay:") ? types.get(n) : undefined;
+ return type ? { ...o, contentType: type } : o;
+ });
+ if (!outputs.length) return { state: "failed", error: "Workflow finished without saving any output" };
+ try {
+ outputs = await bundleFrames(outputs, String(meta.generationId ?? ""));
+ } catch (e) {
+ return { state: "failed", error: (e as Error).message };
+ }
+ return { state: "succeeded", outputs: await withLayerBoxes(outputs) };
+ }
+ case "canceled":
+ return { state: "failed", error: RELAY_WORDS.stopped };
+ default:
+ return { state: "failed", ...relayFailure(t, manifest) };
+ }
+}
+
export const comfyProvider: ProviderAdapter = {
id: "comfyui",
label: "ComfyUI",
isConfigured: () => {
- if (ownGpu()) return true;
+ if (ownGpu() || computerScope()) return true;
const cur = globalThis.__fuobeComfyReach;
// First check for this server: wait for the answer, so a request right after start isn't sent to demo.
if (!cur || cur.url !== baseUrl()) return probeComfySync();
@@ -1580,7 +1827,7 @@ export const comfyProvider: ProviderAdapter = {
return uploadTo(workerFor(route?.endpoint), data, contentType, name);
},
- async submit({ route, input, generationId }) {
+ async submit({ route, input, generationId, model }) {
const worker = workerFor(route.endpoint);
// A route's own graph settings (Fuobe Speak's InfiniteTalk recipe) go in unless the run sets them.
const asked = route.extra ? { ...input, extra: { ...route.extra, ...input.extra } } : input;
@@ -1590,11 +1837,33 @@ export const comfyProvider: ProviderAdapter = {
loraSlot: route.loraSlot === true,
upload: (data, contentType, name) => uploadTo(worker, data, contentType, name),
media: mediaInfoFor,
- serverRam: async () => (await comfyJson<{ system?: { ram_total?: number } }>("/system_stats", worker).catch(() => undefined))?.system?.ram_total,
+ serverRam: async () => {
+ const computer = computerScope();
+ if (computer) return runnerFacts(computer)?.ramBytes;
+ return (await comfyJson<{ system?: { ram_total?: number } }>("/system_stats", worker).catch(() => undefined))?.system?.ram_total;
+ },
device: () => comfyDevice(worker),
- // Fresh: a model installed a moment ago runs.
+ // Fresh: a model installed a moment ago runs. (On someone's computer, nothing to ask: its ComfyUI has the last word.)
dbsModels: () => comfyDbsModels(worker, 0),
});
+ // On someone's computer: the job waits for their Fuobe tab, which sends exactly this graph under the prompt id minted
+ // here. A refusal comes back in its report, and the poll explains it as below.
+ const computer = computerScope();
+ if (computer) {
+ const metaBatch = !!meta.metaBatch;
+ const task = createTask({
+ principal: computer,
+ generationId,
+ graph: wf,
+ prefix: typeof meta.prefix === "string" ? meta.prefix : undefined,
+ metaBatch,
+ preview: true,
+ workflowId: manifest.id,
+ made: model?.kind,
+ loras: (input.loras ?? []).map((l) => ({ file: l.file, ...(l.url && { url: l.url }) })),
+ });
+ return { externalId: task.promptId, meta: { ...meta, generationId, relay: task.id }, payload: wf };
+ }
const { clientId } = ensureSocket(worker);
const res = await comfyFetch(
"/prompt",
@@ -1605,29 +1874,11 @@ export const comfyProvider: ProviderAdapter = {
},
worker,
);
- const body = (await res.json().catch(() => ({}))) as { prompt_id?: string; error?: { type?: string; message?: string; extra_info?: { class_type?: string } }; node_errors?: unknown };
+ const body = (await res.json().catch(() => ({}))) as PromptRefusalBody & { prompt_id?: string };
if (!res.ok || !body.prompt_id) {
- // What was missing, as a code its failed tile turns into "Fix it" (the GPU pre-flight's guided fix). The index names
- // the pack a missing class comes from, so the message names that pack, not every pack the workflow uses.
- let packOf: (cls: string) => string | undefined = () => undefined;
- try {
- const idx = loadIndex();
- packOf = (cls) => Object.entries(idx.packs).find(([, p]) => p.classes.includes(cls))?.[0];
- } catch {}
- const fix = fixFromPromptError(body, manifest.id, manifest.models, packOf);
- const missingClass = fix?.code === "comfy_missing_node" ? fix.items[0] : undefined;
- // A node class the server doesn't have: name the pack to install (opt-in packs like ComfyUI-Whisper).
- const packs = missingClass?.pack ? [missingClass.pack] : manifest.customNodes.map((c) => c.name);
- const where = worker === "isolated" ? "the isolated ComfyUI worker" : "your ComfyUI";
- const missingPack =
- body.error?.type === "missing_node_type" && packs.length ? `This workflow needs the ${packs.join(" + ")} node pack${packs.length > 1 ? "s" : ""} on ${where} (see scripts/comfy/README.md)` : undefined;
- // A LoRA it lacks: point at its model card (a civitai download URL answers 401 without the key) and the LoRA folder setting.
- const loraModels = (input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: loraByFile(l.file)?.page ?? (l.url && !needsToken(l.url) ? l.url : undefined) }));
- let detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...loraModels] }) : (missingPack ?? body.error?.message);
- // (Settings → LoRAs is the owner's page: an account's ComfyUI gets its LoRAs by hand.)
- if (detail && !ownGpu() && loraModels.some((l) => detail!.includes(`"${l.file}"`))) detail = `${detail}\nSet the LoRA folder in Settings → LoRAs and Fuobe downloads LoRAs before a run`;
- if (!detail && !res.ok && worker === "isolated") throw isolatedAnswer("the prompt", res.status);
- throw Object.assign(new ProviderError(detail ?? `ComfyUI /prompt failed (${res.status})`, res.status), fix ? { fix } : {});
+ const refusal = promptRefusal(body, res.status, manifest, input.loras ?? [], worker);
+ if (!refusal.message && !res.ok && worker === "isolated") throw isolatedAnswer("the prompt", res.status);
+ throw Object.assign(new ProviderError(refusal.message ?? `ComfyUI /prompt failed (${res.status})`, res.status), refusal.fix ? { fix: refusal.fix } : {});
}
if (!PROMPT_ID.test(body.prompt_id)) {
// Stop it there: an id Fuobe can't use would never be collected.
@@ -1636,13 +1887,15 @@ export const comfyProvider: ProviderAdapter = {
return { externalId: body.prompt_id, meta: { ...meta, generationId, ...(worker === "isolated" && { worker }) }, payload: wf };
},
- async poll({ externalId, meta }) {
+ async poll({ externalId, meta, model }) {
if (!PROMPT_ID.test(externalId)) return { state: "failed", error: "ComfyUI answered with a job id Fuobe can't use." };
const worker: ComfyWorker = meta.worker === "isolated" ? "isolated" : "main";
let manifest: ManifestWorkflow | undefined;
try {
manifest = getWorkflow(String(meta.workflowId)).manifest;
} catch {}
+ const computer = computerScope();
+ if (computer) return pollComputer(computer, meta, manifest, model?.kind);
const finished = async (entry: HistoryEntry) => {
if (entry.status?.status_str === "error") {
forget(externalId);
@@ -1702,6 +1955,12 @@ export const comfyProvider: ProviderAdapter = {
},
async cancel({ externalId, meta }) {
+ // On someone's computer: the task ends now, and its prompt comes off their ComfyUI at their tab's next beat.
+ const computer = computerScope();
+ if (computer) {
+ if (typeof meta?.relay === "string") requestStop(computer, meta.relay);
+ return;
+ }
const worker: ComfyWorker = meta?.worker === "isolated" ? "isolated" : "main";
forget(externalId);
// A meta-batch job's later passes have prompt ids of their own (and jump the queue): find them by prefix.
@@ -1711,6 +1970,13 @@ export const comfyProvider: ProviderAdapter = {
},
async test(opts) {
+ // On someone's computer: what its tab last said about it.
+ const computer = computerScope();
+ if (computer) {
+ const f = runnerFacts(computer);
+ if (!f?.online) return { ok: false, detail: RELAY_WORDS.noComputer };
+ return { ok: true, detail: `ComfyUI ${f.version ?? ""} · ${f.device ?? "unknown device"}${f.vramBytes ? ` · ${(f.vramBytes / 2 ** 30).toFixed(0)} GB` : ""} · on your computer`.replace(/\s+/g, " ") };
+ }
const describe = async (worker: ComfyWorker) => {
const res = await comfyFetch("/system_stats", {}, worker);
if (!res.ok) {
@@ -1750,6 +2016,9 @@ export const comfyProvider: ProviderAdapter = {
/** The LoRA files the ComfyUI server that runs `route` has (GET /models/loras), or null when it can't say. */
export async function comfyLoraFiles(route?: ModelRoute): Promise<string[] | null> {
+ // On someone's computer: the list its tab last sent (null: it can't say, and ComfyUI's own check has the last word).
+ const computer = computerScope();
+ if (computer) return runnerFacts(computer)?.loras ?? null;
try {
const res = await comfyFetch("/models/loras", {}, workerFor(route?.endpoint));
if (!res.ok) discardBody(res);
@@ -1761,6 +2030,7 @@ export async function comfyLoraFiles(route?: ModelRoute): Promise<string[] | nul
/** Which manifest models are present on the connected ComfyUI server. */
export async function modelInventory(): Promise<Record<string, string[]> | null> {
+ if (computerScope()) return null;
try {
const listed = await comfyFetch("/models");
const folders = listed.ok ? ((await listed.json()) as string[]) : ["diffusion_models", "checkpoints", "text_encoders", "vae", "loras"];
diff --git a/src/server/providers/types.ts b/src/server/providers/types.ts
index bc585382..3cde0f8e 100644
--- a/src/server/providers/types.ts
+++ b/src/server/providers/types.ts
@@ -1,4 +1,4 @@
-import type { GenInput, MediaKind, ModelDef, ModelRoute, ProviderId } from "@/lib/catalog/types";
+import type { GenerationFix, GenInput, MediaKind, ModelDef, ModelRoute, ProviderId } from "@/lib/catalog/types";
export interface SubmitContext {
generationId: string;
@@ -28,11 +28,16 @@ export interface RemoteOutput {
headers?: Record<string, string>;
}
+/**
+ * What a poll found. A job on someone's own computer (comfyui.ts) also says when it reached their ComfyUI (`sentAt`: the
+ * queue clock starts there, not while it waited for their tab), what to say if it waits too long (`timeoutError`), and
+ * what was missing when it failed (`fix`: the tile's "Fix it").
+ */
export type PollResult =
- | { state: "queued"; progress?: number; message?: string }
- | { state: "running"; progress?: number; message?: string }
+ | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string }
+ | { state: "running"; progress?: number; message?: string; sentAt?: number }
| { state: "succeeded"; outputs: RemoteOutput[]; message?: string }
- | { state: "failed"; error: string };
+ | { state: "failed"; error: string; fix?: GenerationFix };
export interface PollContext {
externalId: string;
diff --git a/src/server/settings.ts b/src/server/settings.ts
index dc569e9d..cd3ea961 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -71,6 +71,11 @@ export const SETTINGS = {
comfyToken: { key: "comfyui.token", env: "COMFYUI_TOKEN", secret: true },
/** A second ComfyUI for workflows whose node packs can't share the main install (LatentSync 1.6, ThinkSound; scripts/comfy/README.md). */
comfyIsolatedUrl: { key: "comfyui.isolatedUrl", env: "COMFYUI_ISOLATED_URL" },
+ /**
+ * Where the owner's ComfyUI runs: on this server (its address above), or on the computer the owner uses, reached
+ * through the owner's own Fuobe tab (a studio on a server, a ComfyUI at home: src/server/computer).
+ */
+ comfyWhere: { key: "comfyui.where", env: "COMFYUI_WHERE", default: "server", options: ["server", "computer"] },
/**
* ComfyUI's models/loras folder, when it's on this machine: trained LoRAs are copied there, and a recipe's
* LoRAs (looks, motions) are downloaded there before a run needs them (src/server/loras.ts).
diff --git a/tests/account-gpu.test.ts b/tests/account-gpu.test.ts
index f2f07a5a..45ac67fc 100644
--- a/tests/account-gpu.test.ts
+++ b/tests/account-gpu.test.ts
@@ -160,7 +160,7 @@ describe("the status strip", () => {
const a = auth.createAccount("[email protected]", "long enough");
auth.setAccountGpu(a.id, { url: "http://127.0.0.1:8188" });
const acct = await visitorStatus(auth.accountById(a.id)!);
- expect(acct.viewer).toEqual({ kind: "account", gpu: { connected: true, online: false } });
+ expect(acct.viewer).toEqual({ kind: "account", gpu: { connected: true, mode: "link", online: false } });
expect(acct.providers.comfyui.configured).toBe(false);
expect(JSON.stringify(acct)).not.toContain("owner-comfy.test");
});
diff --git a/tests/account-tenant.test.ts b/tests/account-tenant.test.ts
index 7804cb08..61519c4a 100644
--- a/tests/account-tenant.test.ts
+++ b/tests/account-tenant.test.ts
@@ -148,7 +148,7 @@ describe("every step an account's run starts is its own", () => {
await run(() => {
expect(getSetting("demoMode")).toBe("off");
expect(tenant()).toEqual({ kind: "account", id: a });
- expect(ownGpu()?.url).toBe(fake.url);
+ expect(ownGpu()).toMatchObject({ url: fake.url });
outsideRuns(() => {
expect(tenant()).toBeUndefined();
expect(ownGpu()).toBeUndefined();
diff --git a/tests/computer-relay.test.ts b/tests/computer-relay.test.ts
new file mode 100644
index 00000000..102f63b8
--- /dev/null
+++ b/tests/computer-relay.test.ts
@@ -0,0 +1,359 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { FAKE_PNG, startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";
+import { loadRoutes, tab, type ComputerRoutes } from "./helpers/computer-tab";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-computer-relay-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+// The server's own fetch: recorded. Nothing of a run on someone's computer may reach any ComfyUI from here.
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ fetched.push(url);
+ if (url.startsWith("http://owner-comfy.test")) return new Response("the install's ComfyUI must not be called", { status: 599 });
+ return realFetch(input, init);
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const { getGeneration } = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { RELAY_WORDS } = await import("@/lib/relay");
+
+let fake: LocalComfy;
+let routes: ComputerRoutes;
+let a = "";
+let cookie = "";
+const SITE_HEADERS = { host: "localhost:3000", "sec-fetch-site": "same-origin", origin: "http://localhost:3000" };
+
+beforeAll(async () => {
+ fake = await startLocalComfy({ cors: "http://localhost:3000", steps: 3, stepMs: 10, latencyMs: 10 });
+ routes = await loadRoutes();
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fake.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ Object.assign(fake.opts, { failNext: undefined, outputs: ["image"], metaBatch: undefined, steps: 3, stepMs: 10 });
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ db().prepare("DELETE FROM relay_runners").run();
+});
+
+const json = (url: string, method: string, body: unknown) => {
+ const text = JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, { method, headers: { cookie, ...SITE_HEADERS, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text });
+};
+
+async function uploadPng(): Promise<{ url: string; id: string }> {
+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { cookie, ...SITE_HEADERS, "content-type": "image/png", "x-file-name": "me.png", "content-length": String(FAKE_PNG.length) }, body: FAKE_PNG }));
+ expect(r.status).toBe(201);
+ return r.json();
+}
+
+async function run(body: Record<string, unknown>): Promise<string[]> {
+ const r = await generationsRoute.POST(json("/api/generations", "POST", body));
+ const j = await r.json();
+ expect(r.status, JSON.stringify(j)).toBe(201);
+ return (j.items as { id: string }[]).map((g) => g.id);
+}
+
+const tick = () => globalThis.__fuobeRunner?.tick();
+
+/** Until the run has been handed over (its job exists), ticking the runner. */
+async function handedOver(id: string) {
+ const handed = () => (db().prepare("SELECT external_id FROM generations WHERE id = ?").get(id) as { external_id: string | null } | undefined)?.external_id;
+ for (let i = 0; i < 200 && !handed(); i++) {
+ await tick();
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ await tick();
+}
+
+/** Tick the server's runner until the row is done (or the time is up). */
+async function settle(id: string, ms = 20_000) {
+ const end = Date.now() + ms;
+ for (;;) {
+ await tick();
+ const g = getGeneration(id, { includeDeleted: true });
+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;
+ await new Promise((r) => setTimeout(r, 60));
+ }
+}
+
+const going = () => (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE status IN ('queued', 'running')").get() as { n: number }).n;
+
+/** The tab runs every job there is, while the server's runner keeps polling, until no run is going (or the time is up). */
+async function work(t: ReturnType<typeof tab>, ms = 20_000) {
+ const end = Date.now() + ms;
+ while (going() && Date.now() < end) {
+ await t.runner.beat();
+ await t.runner.claimAndRun();
+ await tick();
+ await new Promise((r) => setTimeout(r, 30));
+ }
+}
+
+describe("a run on the ComfyUI on the person's own computer", () => {
+ it("connects with one call, waits for the tab, then runs there end to end", async () => {
+ const put = await gpuRoute.PUT(json("/api/account/gpu", "PUT", { mode: "computer" }));
+ expect(put.status).toBe(200);
+ expect((await put.json()).gpu).toMatchObject({ mode: "computer", online: false });
+ const pic = await uploadPng();
+ fetched.length = 0;
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await handedOver(id);
+ // No tab yet: the tile says what to do, and the run waits.
+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: RELAY_WORDS.noComputer });
+ const t = tab(routes, cookie, fake.port);
+ const beat = await t.runner.beat();
+ expect(beat).toMatchObject({ runner: true, heldElsewhere: false, waiting: 1 });
+ await tick();
+ expect(getGeneration(id)?.message).toBe(RELAY_WORDS.starting);
+ // The GPU's facts reached the account's state, never its command line.
+ const state = await (await gpuRoute.GET(new Request("http://localhost:3000/api/account/gpu", { headers: { cookie, ...SITE_HEADERS } }))).json();
+ expect(state.gpu).toMatchObject({ mode: "computer", online: true, device: "cuda:0 NVIDIA GeForce RTX 5090 : cudaMallocAsync", version: "0.42.0", port: fake.port, cors: "exact" });
+ expect(JSON.stringify(state)).not.toMatch(/private|base-directory/);
+
+ fake.log.length = 0;
+ expect(await t.runner.claimAndRun()).toBe(true);
+ const g = await settle(id);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ // The picture went to ComfyUI under the name the server chose, byte for byte; then the server's own graph and id.
+ const up = fake.log.find((e) => e.path === "/upload/image");
+ expect(up?.upload?.name).toMatch(/^fuobe_[A-Za-z0-9_-]{12}\.png$/);
+ expect(up?.upload?.bytes.equals(FAKE_PNG)).toBe(true);
+ const posted = fake.log.find((e) => e.path === "/prompt")!.prompt!;
+ expect(JSON.stringify(posted.prompt)).toContain(up!.upload!.name);
+ expect(posted.prompt_id).toBe((db().prepare("SELECT external_id FROM generations WHERE id = ?").get(id) as { external_id: string }).external_id);
+ expect(posted.extra_data).toEqual({ preview_method: "auto" });
+ expect(fake.log.every((e) => e.origin === "http://localhost:3000" || e.method === "WS")).toBe(true);
+ // The result is the account's own, stored as what its bytes are.
+ const out = g!.outputs[0];
+ expect(out).toMatchObject({ kind: "image", contentType: "image/png" });
+ const asset = db().prepare("SELECT account_id, rel_path FROM assets WHERE id = ?").get(out.assetId) as { account_id: string; rel_path: string };
+ expect(asset.account_id).toBe(a);
+ expect(fs.readFileSync(path.join(dir, "files", asset.rel_path)).equals(FAKE_PNG)).toBe(true);
+ // Nothing of it reached a ComfyUI from the server.
+ // (The owner's own reachability check of the studio's ComfyUI is the owner's, not the run's.)
+ expect(fetched.filter((u) => (u.includes("owner-comfy.test") && !u.endsWith("/system_stats")) || u.includes(`:${fake.port}`))).toEqual([]);
+ // The tab saw it through: sending, running with steps, saving, done.
+ expect(t.runner.view.jobs.find((j) => j.generationId === id)?.phase).toBe("done");
+ });
+
+ it("explains a refusal for a missing model or node with the guided fix, and running out of memory in plain words", async () => {
+ const t = tab(routes, cookie, fake.port);
+ await t.runner.beat();
+ const pic = await uploadPng();
+ fake.opts.failNext = "missing_model";
+ const [m] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await work(t);
+ const missing = await settle(m);
+ expect(missing?.status).toBe("failed");
+ expect(missing?.fix).toMatchObject({ code: "comfy_missing_model" });
+ fake.opts.failNext = "missing_node";
+ const [n] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await work(t);
+ const node = await settle(n);
+ expect(node?.fix).toMatchObject({ code: "comfy_missing_node", items: [{ class: "FancyNode" }] });
+ fake.opts.failNext = "oom";
+ const [o] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await work(t);
+ expect((await settle(o))?.error).toBe(RELAY_WORDS.outOfMemory);
+ });
+
+ it("runs a two-step run step by step on the computer: the second step gets the first one's result", async () => {
+ const t = tab(routes, cookie, fake.port);
+ await t.runner.beat();
+ const pic = await uploadPng();
+ fake.log.length = 0;
+ const ids = await run({ feature: "video", modelId: "fuobe-dop", presetId: "effect-window", prompt: "", inputs: { images: [pic.url] } });
+ const all = () => db().prepare("SELECT id, status, depends_on FROM generations WHERE batch_id = (SELECT batch_id FROM generations WHERE id = ?) OR id = ? OR depends_on = ?").all(ids[0], ids[0], ids[0]) as { id: string; status: string; depends_on: string | null }[];
+ // The first step makes a picture, the second a clip from it.
+ fake.opts.outputs = ["image"];
+ for (let i = 0; i < 400 && going(); i++) {
+ await t.runner.beat();
+ await t.runner.claimAndRun();
+ await tick();
+ const rows = all();
+ const second = rows.find((r) => r.depends_on);
+ if (second && rows.find((r) => r.id !== second.id)?.status === "succeeded") fake.opts.outputs = ["video"];
+ await new Promise((r) => setTimeout(r, 30));
+ }
+ const rows = all();
+ expect(rows.length).toBe(2);
+ for (const r of rows) expect(getGeneration(r.id)?.status, getGeneration(r.id)?.error ?? "").toBe("succeeded");
+ const prompts = fake.log.filter((e) => e.path === "/prompt");
+ expect(prompts).toHaveLength(2);
+ // The second prompt loads what the first one made, sent to ComfyUI again under a name of its own.
+ const uploads = fake.log.filter((e) => e.path === "/upload/image");
+ expect(uploads).toHaveLength(2);
+ expect(uploads[1].upload!.bytes.equals(FAKE_PNG)).toBe(true);
+ expect(JSON.stringify(prompts[1].prompt!.prompt)).toContain(uploads[1].upload!.name);
+ });
+
+ it("picks a job up again after a reload, without sending it twice", async () => {
+ fake.opts.steps = 30;
+ fake.opts.stepMs = 30;
+ const first = tab(routes, cookie, fake.port, { device: "device-reload-1" });
+ await first.runner.beat();
+ const pic = await uploadPng();
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await handedOver(id);
+ const posts = fake.posts();
+ // The tab sends it, then the page reloads mid-run (the old runner is gone).
+ const running = first.runner.claimAndRun();
+ for (let i = 0; i < 100 && fake.posts() === posts; i++) await new Promise((r) => setTimeout(r, 20));
+ first.runner.stop();
+ await running.catch(() => {});
+ const again = tab(routes, cookie, fake.port, { device: "device-reload-1", clientId: "client-test-1" });
+ fake.opts.stepMs = 5;
+ await work(again);
+ const g = await settle(id);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ expect(fake.posts() - posts).toBe(1);
+ });
+
+ it("sends a job again once when ComfyUI restarts and loses it, and fails it kindly the second time", async () => {
+ const t = tab(routes, cookie, fake.port);
+ await t.runner.beat();
+ const pic = await uploadPng();
+ fake.opts.failNext = "gone";
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ const posts = fake.posts();
+ await work(t);
+ const g = await settle(id);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ expect(fake.posts() - posts).toBe(2);
+ // Lost twice: the run says what happened, and how to go on.
+ fake.opts.loseNext = 2;
+ const [lost] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await work(t);
+ expect((await settle(lost))?.error).toBe(RELAY_WORDS.lost);
+ expect(fake.opts.loseNext).toBe(0);
+ });
+
+ it("takes a canceled job off the computer's ComfyUI", async () => {
+ fake.opts.steps = 200;
+ fake.opts.stepMs = 30;
+ const t = tab(routes, cookie, fake.port);
+ await t.runner.beat();
+ const pic = await uploadPng();
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await handedOver(id);
+ fake.log.length = 0;
+ const running = t.runner.claimAndRun();
+ for (let i = 0; i < 100 && !fake.log.some((e) => e.path === "/prompt"); i++) await new Promise((r) => setTimeout(r, 20));
+ const { cancelGeneration } = await import("@/server/generations");
+ await cancelGeneration(id);
+ await t.runner.beat();
+ await running;
+ for (let i = 0; i < 50 && !fake.log.some((e) => /^\/api\/jobs\/[^/]+\/cancel$/.test(e.path)); i++) await new Promise((r) => setTimeout(r, 20));
+ expect(fake.log.some((e) => /^\/api\/jobs\/[^/]+\/cancel$/.test(e.path))).toBe(true);
+ expect(getGeneration(id)?.status).toBe("canceled");
+ await t.runner.beat();
+ expect(db().prepare("SELECT stop FROM relay_tasks WHERE generation_id = ?").get(id)).toEqual({ stop: 0 });
+ });
+
+ it("says Fuobe couldn't reach the computer after 30 minutes without a tab", async () => {
+ const pic = await uploadPng();
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await handedOver(id);
+ db().prepare("UPDATE generation_runs SET submitted_at = submitted_at - ? WHERE id = ?").run(31 * 60_000, id);
+ const g = await settle(id);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toBe("Fuobe couldn't reach your computer for 30 minutes. Open Fuobe there, then press Retry.");
+ expect((db().prepare("SELECT state FROM relay_tasks WHERE generation_id = ?").get(id) as { state: string }).state).toBe("canceled");
+ });
+
+ it("runs the owner's runs on the owner's computer when Settings says so, and never calls the studio's own ComfyUI", async () => {
+ const { setSetting } = await import("@/server/settings");
+ setSetting("comfyWhere", "computer");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ try {
+ const asOwner = (url: string, method: string, body: unknown) => {
+ const text = JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, { method, headers: { cookie: owner, ...SITE_HEADERS, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text });
+ };
+ fetched.length = 0;
+ const r = await generationsRoute.POST(asOwner("/api/generations", "POST", { feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk" }));
+ const j = await r.json();
+ expect(r.status, JSON.stringify(j)).toBe(201);
+ const id = (j.items as { id: string }[])[0].id;
+ await handedOver(id);
+ expect((db().prepare("SELECT principal FROM relay_tasks WHERE generation_id = ?").get(id) as { principal: string }).principal).toBe("owner");
+ const t = tab(routes, owner, fake.port, { device: "device-owner-1" });
+ await work(t);
+ const g = await settle(id);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ expect((db().prepare("SELECT account_id FROM assets WHERE id = ?").get(g!.outputs[0].assetId) as { account_id: string | null }).account_id).toBeNull();
+ expect(fetched.filter((u) => u.includes("owner-comfy.test"))).toEqual([]);
+ // A run on a computer can't reach the studio's ComfyUI even by mistake.
+ const { comfyLoraFiles, onComputer } = await import("@/server/providers/comfyui");
+ expect(await onComputer("owner", () => comfyLoraFiles())).toBeNull();
+ } finally {
+ setSetting("comfyWhere", "server");
+ }
+ });
+
+ it("stops a job whose run went, and forgets a deleted account's computer and files", async () => {
+ const { createTask, purgeComputer, stageInput, sweepRelay, relayDir } = await import("@/server/computer/tasks");
+ const name = stageInput(`acct:${a}`, FAKE_PNG, "image/png", "x.png");
+ const task = createTask({ principal: `acct:${a}`, generationId: "no-such-run", graph: { "1": { class_type: "LoadImage", inputs: { image: name } } } });
+ expect(fs.existsSync(path.join(relayDir(), "in", name))).toBe(true);
+ sweepRelay();
+ expect((db().prepare("SELECT state FROM relay_tasks WHERE id = ?").get(task.id) as { state: string }).state).toBe("canceled");
+ expect(fs.existsSync(path.join(relayDir(), "in", name))).toBe(false);
+ stageInput(`acct:${a}`, FAKE_PNG, "image/png", "y.png");
+ purgeComputer(`acct:${a}`);
+ expect(db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE principal = ?").get(`acct:${a}`)).toEqual({ n: 0 });
+ expect(db().prepare("SELECT COUNT(*) AS n FROM relay_inputs WHERE principal = ?").get(`acct:${a}`)).toEqual({ n: 0 });
+ });
+
+ it("follows a meta-batch job pass by pass and keeps the last pass's clip", async () => {
+ const { createTask } = await import("@/server/computer/tasks");
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, external_id, external_meta_json, outputs_json, created_at, updated_at) VALUES ('meta-gen', 'video', 'oss-x', 'open', 'comfyui', 'v2v', 'video', 'queued', ?, NULL, '{}', '[]', ?, ?)")
+ .run(JSON.stringify({ account: a }), now, now);
+ const graph = { "1": { class_type: "VHS_BatchManager", inputs: {} }, "9": { class_type: "VHS_VideoCombine", inputs: { filename_prefix: "fuobe/meta-gen" } } };
+ const task = createTask({ principal: `acct:${a}`, generationId: "meta-gen", graph, prefix: "fuobe/meta-gen", metaBatch: true, preview: false });
+ fake.opts.metaBatch = 3;
+ fake.opts.outputs = ["video"];
+ const posts = fake.posts();
+ const t = tab(routes, cookie, fake.port);
+ await t.runner.beat();
+ await t.runner.claimAndRun();
+ const row = db().prepare("SELECT state, wanted_json, result_json FROM relay_tasks WHERE id = ?").get(task.id) as { state: string; wanted_json: string; result_json: string };
+ expect(row.state).toBe("done");
+ expect(JSON.parse(row.wanted_json)).toEqual([expect.objectContaining({ kind: "video", filename: "meta-gen_00001_.mp4", subfolder: "fuobe" })]);
+ // One prompt from the tab; the other passes were ComfyUI's own.
+ expect(fake.posts() - posts).toBe(1);
+ expect([...fake.history.values()].filter((h) => JSON.stringify(h.prompt).includes("fuobe/meta-gen"))).toHaveLength(3);
+ });
+});
diff --git a/tests/computer-security.test.ts b/tests/computer-security.test.ts
new file mode 100644
index 00000000..cf9b7670
--- /dev/null
+++ b/tests/computer-security.test.ts
@@ -0,0 +1,430 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { FAKE_PNG } from "./helpers/fake-local-comfy";
+import { loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-computer-security-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const { onComputer, outputFetch } = await import("@/server/providers/comfyui");
+const { accountMayChange, accountOwnRead, guestRead } = await import("@/lib/guest-access");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+
+type Principal = import("@/server/computer/tasks").Principal;
+
+let routes: ComputerRoutes;
+let a = "";
+let b = "";
+let link = "";
+const cookies: Record<string, string> = {};
+const HOST = "localhost:3000";
+const SITE = `http://${HOST}`;
+
+beforeAll(async () => {
+ routes = await loadRoutes();
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ b = auth.createAccount("[email protected]", "long enough").id;
+ link = auth.createAccount("[email protected]", "long enough").id;
+ auth.setAccountGpu(a, { mode: "computer" });
+ auth.setAccountGpu(b, { mode: "computer" });
+ auth.setAccountGpu(link, { url: "https://gpu.example.com" });
+ cookies.a = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+ cookies.b = `${auth.SESSION_COOKIE}=${auth.createSession(b).value}`;
+ cookies.link = `${auth.SESSION_COOKIE}=${auth.createSession(link).value}`;
+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+});
+afterAll(() => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ setSetting("comfyWhere", "server");
+ db().prepare("DELETE FROM relay_runners").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+});
+
+type Who = "a" | "b" | "link" | "owner" | "guest";
+
+/** A request from Fuobe's own page as `who` (or as told by `headers`), straight to the route handler. */
+function call(who: Who, method: string, url: string, o: { body?: unknown; raw?: Buffer; headers?: Record<string, string> } = {}): Promise<Response> {
+ const headers = new Headers({ host: HOST, "sec-fetch-site": "same-origin", origin: SITE, ...(who !== "guest" && { cookie: cookies[who] }) });
+ let body: BodyInit | undefined;
+ if (o.raw) {
+ body = new Uint8Array(o.raw);
+ headers.set("content-type", "application/octet-stream");
+ headers.set("content-length", String(o.raw.length));
+ } else if (o.body !== undefined) {
+ body = JSON.stringify(o.body);
+ headers.set("content-type", "application/json");
+ headers.set("content-length", String(Buffer.byteLength(body)));
+ }
+ for (const [k, v] of Object.entries(o.headers ?? {})) (v === "" ? headers.delete(k) : headers.set(k, v));
+ const req = new Request(`${SITE}${url}`, { method, headers, body, duplex: "half" } as RequestInit);
+ const params = (p: Record<string, string>) => ({ params: Promise.resolve(p) });
+ const u = new URL(req.url).pathname;
+ let m: RegExpExecArray | null;
+ if (u === "/api/gpu/computer/beat") return Promise.resolve(routes.beat.POST(req, params({})));
+ if (u === "/api/gpu/computer/claim") return Promise.resolve(routes.claim.POST(req, params({})));
+ if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/inputs\/([^/]+)$/.exec(u))) return Promise.resolve(routes.inputs.GET(req, params({ id: m[1], n: m[2] })));
+ if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/report$/.exec(u))) return Promise.resolve(routes.report.POST(req, params({ id: m[1] })));
+ if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/outputs\/([^/]+)$/.exec(u))) return Promise.resolve((method === "PUT" ? routes.outputs.PUT : routes.outputs.GET)(req, params({ id: m[1], n: m[2] })));
+ if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/release$/.exec(u))) return Promise.resolve(routes.release.POST(req, params({ id: m[1] })));
+ throw new Error(`no route ${u}`);
+}
+
+const SAVE = { "9": { class_type: "SaveImage", inputs: { filename_prefix: "fuobe/x", images: ["3", 0] } }, "3": { class_type: "KSampler", inputs: {} } };
+
+/** A run of `principal` on its computer with one job waiting (an input staged under the name its graph loads). */
+function waitingTask(principal: Principal, graph: Record<string, { class_type: string; inputs: Record<string, unknown> }> = SAVE): { id: string; generationId: string; input: string } {
+ const generationId = `gen-${Math.random().toString(36).slice(2, 10)}`;
+ const now = Date.now();
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, external_id, external_meta_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-x', 'open', 'comfyui', 't2i', 'image', 'queued', ?, NULL, '{}', '[]', ?, ?)",
+ )
+ .run(generationId, JSON.stringify(principal === "owner" ? {} : { account: principal.slice(5) }), now, now);
+ const input = onComputer(principal, () => tasks.stageInput(principal, FAKE_PNG, "image/png", "me.png"));
+ const t = tasks.createTask({ principal, generationId, graph: { ...graph, "1": { class_type: "LoadImage", inputs: { image: input } } } });
+ return { id: t.id, generationId, input };
+}
+
+const DEVICE = "device-security-1";
+
+/** The account's computer becomes the runner and claims its oldest job: the claim's lease. */
+async function claimed(who: "a" | "b" | "owner", device = DEVICE): Promise<{ id: string; lease: string; promptId: string }> {
+ expect((await call(who, "POST", "/api/gpu/computer/beat", { body: { device } })).status).toBe(200);
+ const res = await call(who, "POST", "/api/gpu/computer/claim", { body: { device } });
+ expect(res.status).toBe(200);
+ const { task } = await res.json();
+ return { id: task.id, lease: task.lease, promptId: task.promptId };
+}
+
+/** A claimed job of A's that ComfyUI finished with these outputs: what the server now wants uploaded. */
+async function collecting(outputs: Record<string, unknown>, graph = SAVE) {
+ const t = waitingTask(`acct:${a}`, graph);
+ const c = await claimed("a");
+ expect(c.id).toBe(t.id);
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } })).status).toBe(200);
+ const fin = await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, {
+ body: { lease: c.lease, event: "finished", entry: { status: { status_str: "success", completed: true }, outputs } },
+ });
+ expect(fin.status).toBe(200);
+ return { ...c, generationId: t.generationId, answer: (await fin.json()) as { wanted?: { n: number; kind: string; maxBytes: number }[]; state?: string } };
+}
+
+const ONE_PNG = { "9": { images: [{ filename: "x_00001_.png", subfolder: "fuobe", type: "output" }] } };
+const put = (who: Who, id: string, n: number, lease: string, data: Buffer, offset = 0, total = data.length, headers: Record<string, string> = {}) =>
+ call(who, "PUT", `/api/gpu/computer/tasks/${id}/outputs/${n}?offset=${offset}&total=${total}`, { raw: data, headers: { "x-fuobe-lease": lease, ...headers } });
+const state = (id: string) => (db().prepare("SELECT state, error FROM relay_tasks WHERE id = ?").get(id) as { state: string; error: string | null }).state;
+
+describe("who may use the routes a computer runs jobs through", () => {
+ const ROUTES: [string, string, unknown?][] = [
+ ["POST", "/api/gpu/computer/beat", { device: DEVICE }],
+ ["POST", "/api/gpu/computer/claim", { device: DEVICE }],
+ ["GET", "/api/gpu/computer/tasks/AAAAAAAAAAAAAAAA/inputs/0"],
+ ["POST", "/api/gpu/computer/tasks/AAAAAAAAAAAAAAAA/report", { lease: "0".repeat(64), event: "gone" }],
+ ["GET", "/api/gpu/computer/tasks/AAAAAAAAAAAAAAAA/outputs/0"],
+ ["POST", "/api/gpu/computer/tasks/AAAAAAAAAAAAAAAA/release", { lease: "0".repeat(64) }],
+ ];
+
+ it("a guest gets 401 on every one", async () => {
+ for (const [method, url, body] of ROUTES) expect((await call("guest", method, url, { body })).status, url).toBe(401);
+ expect((await put("guest", "AAAAAAAAAAAAAAAA", 0, "0".repeat(64), FAKE_PNG)).status).toBe(401);
+ });
+
+ it("the proxy lets an account through to them and nothing new reaches a guest", () => {
+ expect(accountMayChange("POST", "/api/gpu/computer/beat", "")).toBe(true);
+ expect(accountMayChange("PUT", "/api/gpu/computer/tasks/x/outputs/0", "")).toBe(true);
+ expect(accountMayChange("DELETE", "/api/gpu/computer/tasks/x/outputs/0", "")).toBe(false);
+ expect(accountOwnRead("/api/gpu/computer/tasks/x/inputs/0")).toBe(true);
+ expect(accountOwnRead("/api/gpu/computer/tasks/x/report")).toBe(false);
+ for (const p of ["/api/gpu/computer/beat", "/api/gpu/computer/tasks/x/inputs/0", "/api/gpu/computer/tasks/x/outputs/0"]) expect(guestRead(p)).toEqual({ kind: "closed" });
+ });
+
+ it("an API token gets 403, even the owner's", async () => {
+ setSetting("comfyWhere", "computer");
+ const { token } = auth.createToken("script");
+ for (const [method, url, body] of ROUTES) expect((await call("owner", method, url, { body, headers: { authorization: `Bearer ${token}` } })).status, url).toBe(403);
+ });
+
+ it("another website gets 403: a cross-site request, a foreign Origin, or neither header", async () => {
+ expect((await call("a", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE }, headers: { "sec-fetch-site": "cross-site", origin: "https://evil.example" } })).status).toBe(403);
+ expect((await call("a", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE }, headers: { "sec-fetch-site": "", origin: "https://evil.example" } })).status).toBe(403);
+ expect((await call("a", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE }, headers: { "sec-fetch-site": "same-site" } })).status).toBe(403);
+ expect((await call("a", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE }, headers: { "sec-fetch-site": "", origin: "" } })).status).toBe(403);
+ });
+
+ it("an account whose GPU is a link gets 409; the owner gets 409 until Settings says ComfyUI runs on the owner's computer", async () => {
+ expect((await call("link", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE } })).status).toBe(409);
+ expect((await call("owner", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE } })).status).toBe(409);
+ setSetting("comfyWhere", "computer");
+ expect((await call("owner", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE } })).status).toBe(200);
+ });
+
+ it("a disabled account gets 401", async () => {
+ const c = auth.createAccount("[email protected]", "long enough").id;
+ auth.setAccountGpu(c, { mode: "computer" });
+ cookies.c = `${auth.SESSION_COOKIE}=${auth.createSession(c).value}`;
+ auth.setAccountDisabled(c, true);
+ const res = await call("guest", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE }, headers: { cookie: cookies.c } });
+ expect(res.status).toBe(401);
+ });
+
+ it("too many beats answer 429 with Retry-After", async () => {
+ for (let i = 0; i < 30; i++) expect((await call("a", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE } })).status).toBe(200);
+ const res = await call("a", "POST", "/api/gpu/computer/beat", { body: { device: DEVICE } });
+ expect(res.status).toBe(429);
+ expect(Number(res.headers.get("retry-after"))).toBeGreaterThan(0);
+ });
+});
+
+describe("one account can't touch another's jobs", () => {
+ it("B's computer never claims A's waiting job", async () => {
+ waitingTask(`acct:${a}`);
+ expect((await call("b", "POST", "/api/gpu/computer/beat", { body: { device: "device-b-0001" } })).status).toBe(200);
+ expect((await call("b", "POST", "/api/gpu/computer/claim", { body: { device: "device-b-0001" } })).status).toBe(204);
+ });
+
+ it("A's job, with A's own token, is 404 to B on every route: inputs, report, outputs, release", async () => {
+ const t = waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ expect(c.id).toBe(t.id);
+ expect((await call("b", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);
+ expect((await call("b", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } })).status).toBe(404);
+ expect((await put("b", c.id, 0, c.lease, FAKE_PNG)).status).toBe(404);
+ expect((await call("b", "GET", `/api/gpu/computer/tasks/${c.id}/outputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);
+ expect((await call("b", "POST", `/api/gpu/computer/tasks/${c.id}/release`, { body: { lease: c.lease } })).status).toBe(404);
+ // And the owner's session is no way in either.
+ setSetting("comfyWhere", "computer");
+ expect((await call("owner", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);
+ // A still has it, untouched.
+ expect(state(c.id)).toBe("sending");
+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(200);
+ });
+
+ it("a result A's computer sent in is read only as A: as anyone else it's not found", async () => {
+ const c = await collecting(ONE_PNG);
+ expect((await put("a", c.id, 0, c.lease, FAKE_PNG)).status).toBe(200);
+ const url = `relay:${c.id}/view?filename=x_00001_.png&subfolder=fuobe&type=output&n=0`;
+ expect((await onComputer(`acct:${b}`, () => outputFetch(url))).status).toBe(404);
+ expect((await onComputer("owner", () => outputFetch(url))).status).toBe(404);
+ const mine = await onComputer(`acct:${a}`, () => outputFetch(url));
+ expect(mine.status).toBe(200);
+ expect(Buffer.from(await mine.arrayBuffer()).equals(FAKE_PNG)).toBe(true);
+ });
+});
+
+describe("a job's token", () => {
+ it("a wrong token, or the one before the latest claim, gets 409", async () => {
+ waitingTask(`acct:${a}`);
+ const first = await claimed("a");
+ const wrong = "f".repeat(64);
+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${first.id}/inputs/0`, { headers: { "x-fuobe-lease": wrong } })).status).toBe(409);
+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${first.id}/inputs/0`, { headers: { "x-fuobe-lease": "not-hex" } })).status).toBe(409);
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${first.id}/report`, { body: { event: "gone" } })).status).toBe(409);
+ // The page reloads: its computer claims the job again, and the old token stops working.
+ const again = await call("a", "POST", "/api/gpu/computer/claim", { body: { device: DEVICE } });
+ const second = (await again.json()).task;
+ expect(second.id).toBe(first.id);
+ expect(second.lease).not.toBe(first.lease);
+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${first.id}/inputs/0`, { headers: { "x-fuobe-lease": first.lease } })).status).toBe(409);
+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${first.id}/inputs/0`, { headers: { "x-fuobe-lease": second.lease } })).status).toBe(200);
+ });
+
+ it("another computer of the same account doesn't get a job this one took", async () => {
+ waitingTask(`acct:${a}`);
+ await claimed("a", "device-first-01");
+ expect(await (await call("a", "POST", "/api/gpu/computer/beat", { body: { device: "device-second-1" } })).json()).toMatchObject({ runner: false, heldElsewhere: true });
+ expect((await call("a", "POST", "/api/gpu/computer/claim", { body: { device: "device-second-1" } })).status).toBe(204);
+ // Taking over makes it the runner for jobs still waiting, not for the one the first took.
+ expect(await (await call("a", "POST", "/api/gpu/computer/beat", { body: { device: "device-second-1", takeover: true } })).json()).toMatchObject({ runner: true });
+ expect((await call("a", "POST", "/api/gpu/computer/claim", { body: { device: "device-second-1" } })).status).toBe(204);
+ });
+});
+
+describe("inputs", () => {
+ it("are read only while the job sends them, a few times each, as bytes that are never a page", async () => {
+ waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ const res = await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } });
+ expect(res.headers.get("content-type")).toBe("application/octet-stream");
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff");
+ expect(Buffer.from(await res.arrayBuffer()).equals(FAKE_PNG)).toBe(true);
+ for (let i = 1; i < 6; i++) expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(200);
+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(429);
+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/1`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } })).status).toBe(200);
+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(409);
+ });
+
+ it("only a job's own staged files reach it, never another account's", async () => {
+ const theirs = onComputer(`acct:${b}`, () => tasks.stageInput(`acct:${b}`, FAKE_PNG, "image/png", "b.png"));
+ const t = waitingTask(`acct:${a}`, { ...SAVE, "2": { class_type: "LoadImage", inputs: { image: theirs } } });
+ const c = await claimed("a");
+ expect(c.id).toBe(t.id);
+ const res = await call("a", "POST", "/api/gpu/computer/claim", { body: { device: DEVICE } });
+ const task = (await res.json()).task as { inputs: { name: string }[] };
+ expect(task.inputs.map((i) => i.name)).toEqual([t.input]);
+ });
+});
+
+describe("reports", () => {
+ it("each is taken only where the job is", async () => {
+ waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ const report = (body: Record<string, unknown>) => call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, ...body } });
+ expect((await report({ event: "finished", entry: { outputs: ONE_PNG } })).status).toBe(409);
+ expect((await report({ event: "running", value: 1, max: 2 })).status).toBe(409);
+ expect((await report({ event: "nonsense" })).status).toBe(400);
+ expect((await report({ event: "sent", promptId: "../../etc" })).status).toBe(400);
+ expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(200);
+ expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(409);
+ });
+
+ it("a finished entry over 8 MB is refused", async () => {
+ waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } });
+ const big = { lease: c.lease, event: "finished", entry: { outputs: { "9": { text: ["x".repeat(9 * 2 ** 20)] } } } };
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: big })).status).toBe(413);
+ expect(state(c.id)).toBe("queued");
+ });
+
+ it("a forged entry with 500 pictures gets 16 wanted, the most an account's run keeps", async () => {
+ const images = Array.from({ length: 500 }, (_, i) => ({ filename: `x_${String(i + 1).padStart(5, "0")}_.png`, subfolder: "fuobe", type: "output" }));
+ const c = await collecting({ "9": { images } });
+ expect(c.answer.wanted).toHaveLength(16);
+ });
+});
+
+describe("results are checked like uploads", () => {
+ it("only a wanted file, only at the right place, only once", async () => {
+ const c = await collecting(ONE_PNG);
+ expect(c.answer.wanted).toEqual([expect.objectContaining({ n: 0, kind: "image" })]);
+ expect((await put("a", c.id, 1, c.lease, FAKE_PNG)).status).toBe(404);
+ expect((await put("a", c.id, 0, c.lease, FAKE_PNG, 5)).status).toBe(409);
+ expect((await put("a", c.id, 0, c.lease, FAKE_PNG, 0, FAKE_PNG.length, { "content-length": "" })).status).toBe(411);
+ const ok = await put("a", c.id, 0, c.lease, FAKE_PNG);
+ expect(ok.status).toBe(200);
+ expect(await ok.json()).toMatchObject({ done: true });
+ expect(state(c.id)).toBe("done");
+ expect([409, 404]).toContain((await put("a", c.id, 0, c.lease, FAKE_PNG)).status);
+ });
+
+ it("goes on from where a cut-off upload got to", async () => {
+ const c = await collecting(ONE_PNG);
+ const half = FAKE_PNG.length >> 1;
+ expect((await put("a", c.id, 0, c.lease, FAKE_PNG.subarray(0, half), 0, FAKE_PNG.length)).status).toBe(200);
+ expect(await (await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/outputs/0`, { headers: { "x-fuobe-lease": c.lease } })).json()).toEqual({ received: half, total: FAKE_PNG.length, done: false });
+ expect((await put("a", c.id, 0, c.lease, FAKE_PNG.subarray(half), half, FAKE_PNG.length)).status).toBe(200);
+ expect(state(c.id)).toBe("done");
+ const file = tasks.receivedFile(`acct:${a}`, c.id, 0)!;
+ expect(fs.readFileSync(file.path).equals(FAKE_PNG)).toBe(true);
+ });
+
+ it("a page dressed as a picture is refused, nothing is kept, and the run fails saying why", async () => {
+ const c = await collecting(ONE_PNG);
+ const page = Buffer.from("<!doctype html><script>alert(1)</script>".padEnd(120, " "));
+ const res = await put("a", c.id, 0, c.lease, page);
+ expect(res.status).toBe(415);
+ expect(state(c.id)).toBe("failed");
+ expect(fs.existsSync(path.join(tasks.relayDir(), "tasks", c.id, "out-0"))).toBe(false);
+ expect(fs.existsSync(path.join(tasks.relayDir(), "tasks", c.id, "out-0.part"))).toBe(false);
+ const svg = await collecting(ONE_PNG);
+ expect((await put("a", svg.id, 0, svg.lease, Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>`.padEnd(80, " ")))).status).toBe(415);
+ });
+
+ it("a real picture sent as a web page is kept as the picture its bytes say", async () => {
+ const c = await collecting(ONE_PNG);
+ expect((await put("a", c.id, 0, c.lease, FAKE_PNG, 0, FAKE_PNG.length, { "content-type": "text/html" })).status).toBe(200);
+ expect(tasks.receivedFile(`acct:${a}`, c.id, 0)?.contentType).toBe("image/png");
+ });
+
+ it("a text result that isn't UTF-8 is refused", async () => {
+ const c = await collecting({ "9": { text_files: [{ filename: "x_00001_.txt", subfolder: "fuobe", type: "output" }] } }, { "9": { class_type: "SaveText|pysssss", inputs: { filename_prefix: "fuobe/x" } } } as never);
+ const want = c.answer.wanted ?? [];
+ expect(want).toEqual([expect.objectContaining({ kind: "text" })]);
+ const res = await put("a", c.id, want[0].n, c.lease, Buffer.from([0x68, 0x69, 0xff, 0xfe, 0x00, 0x41]));
+ expect(res.status).toBe(415);
+ expect(state(c.id)).toBe("failed");
+ });
+
+ it("past a file's limit, or past the room the account's files have, is refused and the run fails", async () => {
+ const c = await collecting(ONE_PNG);
+ const limit = c.answer.wanted![0].maxBytes;
+ const res = await put("a", c.id, 0, c.lease, FAKE_PNG, 0, limit + 1);
+ expect(res.status).toBe(413);
+ expect(state(c.id)).toBe("failed");
+ });
+});
+
+describe("a computer's own GPU check (the tab reads its ComfyUI and sends what it found)", () => {
+ const inventoryRoute = import("@/app/api/gpu/inventory/route");
+ const readinessRoute = import("@/app/api/gpu/readiness/route");
+ const checkRoute = import("@/app/api/gpu/check/route");
+ const sent = (who: Who, body: unknown, headers: Record<string, string> = {}) =>
+ inventoryRoute.then((r) =>
+ r.PUT(new Request(`${SITE}/api/gpu/inventory`, { method: "PUT", headers: { host: HOST, "sec-fetch-site": "same-origin", origin: SITE, "content-type": "application/json", ...(who !== "guest" && { cookie: cookies[who] }), ...headers }, body: JSON.stringify(body) })),
+ );
+ const board = (who: Who) => readinessRoute.then(async (r) => (await r.GET(new Request(`${SITE}/api/gpu/readiness`, { headers: { host: HOST, cookie: cookies[who] } }))).json());
+
+ async function gathered() {
+ const { gatherInventory } = await import("@/lib/gpu/gather");
+ const { fetchTransport } = await import("@/lib/gpu/transport");
+ const { loadIndex } = await import("@/server/gpu/index-file");
+ const { startLocalComfy } = await import("./helpers/fake-local-comfy");
+ const { browserLocal } = await import("./helpers/computer-tab");
+ const fake = await startLocalComfy({ cors: SITE });
+ try {
+ const local = browserLocal(SITE);
+ return await gatherInventory(fetchTransport("browser", fake.url, (url, init) => local(url, init), { decodes: true }), loadIndex(), { where: "computer", statsTimeoutMs: 1500 });
+ } finally {
+ await fake.close();
+ }
+ }
+
+ it("is kept for that account's own board, in the server's time; the server never checks it itself", async () => {
+ const inv = await gathered();
+ expect(inv).toMatchObject({ via: "browser", reachable: true });
+ const res = await sent("a", { ...inv, checkedAt: 1 });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toMatchObject({ connected: true, target: "computer" });
+ const view = await board("a");
+ expect(view).toMatchObject({ connected: true, target: "computer" });
+ expect(view.checkedAt).toBeGreaterThan(Date.now() - 60_000);
+ expect(view.report?.studios?.length).toBeGreaterThan(0);
+ // B's board knows nothing of it.
+ expect(await board("b")).toMatchObject({ connected: true, target: "computer", checkedAt: null });
+ const check = await (await checkRoute).POST(new Request(`${SITE}/api/gpu/check`, { method: "POST", headers: { host: HOST, "sec-fetch-site": "same-origin", origin: SITE, cookie: cookies.a } }));
+ expect(check.status).toBe(409);
+ expect((await check.json()).code).toBe("browser");
+ });
+
+ it("refuses a check that isn't one, one too large, one from a link account, a guest, a token or another site", async () => {
+ expect((await sent("a", { hello: "there" })).status).toBe(400);
+ expect((await sent("a", { v: 1, via: "server" })).status).toBe(400);
+ expect((await sent("a", "x".repeat(3 * 2 ** 20))).status).toBe(413);
+ expect((await sent("link", {})).status).toBe(409);
+ expect([401, 403, 409]).toContain((await sent("guest", {})).status);
+ expect((await sent("a", {}, { "sec-fetch-site": "cross-site", origin: "https://evil.example" })).status).toBe(403);
+ const { token } = auth.createToken("inv");
+ expect((await sent("owner", {}, { authorization: `Bearer ${token}` })).status).toBe(403);
+ });
+});
diff --git a/tests/helpers/computer-tab.ts b/tests/helpers/computer-tab.ts
new file mode 100644
index 00000000..c1b4ac32
--- /dev/null
+++ b/tests/helpers/computer-tab.ts
@@ -0,0 +1,96 @@
+/**
+ * A Fuobe tab in tests: the real runner (src/lib/computer-runner.ts) with the routes of src/app/api/gpu/computer called
+ * as handlers (the session cookie, this site's own origin), and a ComfyUI on this computer reached as a browser on the
+ * site reaches it: the site's Origin and Sec-Fetch-Site go with every request, and an answer without the CORS header for
+ * the site is a network error, as in a browser.
+ */
+import { ComputerRunner, type RunnerDeps } from "@/lib/computer-runner";
+
+export const SITE = "http://localhost:3000";
+const realFetch = globalThis.fetch;
+
+type Handler = (req: Request, ctx: { params: Promise<Record<string, string>> }) => Promise<Response> | Response;
+
+export interface ComputerRoutes {
+ beat: { POST: Handler };
+ claim: { POST: Handler };
+ inputs: { GET: Handler };
+ report: { POST: Handler };
+ outputs: { PUT: Handler; GET: Handler };
+ release: { POST: Handler };
+}
+
+export async function loadRoutes(): Promise<ComputerRoutes> {
+ return {
+ beat: (await import("@/app/api/gpu/computer/beat/route")) as never,
+ claim: (await import("@/app/api/gpu/computer/claim/route")) as never,
+ inputs: (await import("@/app/api/gpu/computer/tasks/[id]/inputs/[n]/route")) as never,
+ report: (await import("@/app/api/gpu/computer/tasks/[id]/report/route")) as never,
+ outputs: (await import("@/app/api/gpu/computer/tasks/[id]/outputs/[n]/route")) as never,
+ release: (await import("@/app/api/gpu/computer/tasks/[id]/release/route")) as never,
+ };
+}
+
+/** Requests from Fuobe's own page with this cookie (and any headers given), sent to the route handlers. */
+export function apiAs(routes: ComputerRoutes, cookie: string | null, extra: Record<string, string> = {}): RunnerDeps["api"] & { calls: string[] } {
+ const calls: string[] = [];
+ const api = async (p: string, init: RequestInit = {}) => {
+ const url = new URL(p, SITE);
+ const headers = new Headers(init.headers);
+ if (cookie) headers.set("cookie", cookie);
+ headers.set("host", "localhost:3000");
+ if (!headers.has("sec-fetch-site")) headers.set("sec-fetch-site", "same-origin");
+ if (!headers.has("origin")) headers.set("origin", SITE);
+ for (const [k, v] of Object.entries(extra)) headers.set(k, v);
+ let body = init.body as BodyInit | null | undefined;
+ if (body instanceof Blob) body = Buffer.from(await body.arrayBuffer());
+ if (body instanceof Uint8Array || typeof body === "string") headers.set("content-length", String(typeof body === "string" ? Buffer.byteLength(body) : body.byteLength));
+ const req = new Request(url, { method: init.method ?? "GET", headers, body: body ?? undefined, duplex: "half" } as RequestInit);
+ const method = req.method;
+ calls.push(`${method} ${url.pathname}`);
+ const params = (o: Record<string, string>) => ({ params: Promise.resolve(o) });
+ let m: RegExpExecArray | null;
+ if (url.pathname === "/api/gpu/computer/beat") return routes.beat.POST(req, params({}));
+ if (url.pathname === "/api/gpu/computer/claim") return routes.claim.POST(req, params({}));
+ if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/inputs\/([^/]+)$/.exec(url.pathname))) return routes.inputs.GET(req, params({ id: m[1], n: m[2] }));
+ if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/report$/.exec(url.pathname))) return routes.report.POST(req, params({ id: m[1] }));
+ if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/outputs\/([^/]+)$/.exec(url.pathname))) return (method === "PUT" ? routes.outputs.PUT : routes.outputs.GET)(req, params({ id: m[1], n: m[2] }));
+ if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/release$/.exec(url.pathname))) return routes.release.POST(req, params({ id: m[1] }));
+ return new Response("no such route", { status: 404 });
+ };
+ return Object.assign(api, { calls });
+}
+
+/** fetch() to the ComfyUI on this computer, as a browser on SITE sends it and reads the answer. */
+export function browserLocal(site = SITE): RunnerDeps["local"] & { urls: string[] } {
+ const urls: string[] = [];
+ const local = async (url: string, init: RequestInit = {}) => {
+ urls.push(url);
+ const headers = new Headers(init.headers);
+ headers.set("origin", site);
+ headers.set("sec-fetch-site", "cross-site");
+ const { mode, ...rest } = init;
+ const res = await realFetch(url, { ...rest, headers });
+ if (mode === "no-cors") return new Response(null, { status: 200 });
+ const allow = res.headers.get("access-control-allow-origin");
+ if (allow !== site && allow !== "*") {
+ await res.body?.cancel().catch(() => {});
+ throw new TypeError("Failed to fetch");
+ }
+ return res;
+ };
+ return Object.assign(local, { urls });
+}
+
+export const sha256 = async (data: ArrayBuffer) => Buffer.from(await crypto.subtle.digest("SHA-256", data)).toString("hex");
+
+/** A tab on this computer for `cookie`, its ComfyUI on `port`. */
+export function tab(routes: ComputerRoutes, cookie: string, port: number, o: { device?: string; clientId?: string } = {}) {
+ const api = apiAs(routes, cookie);
+ const local = browserLocal();
+ const runner = new ComputerRunner(
+ { api, local, socket: (url) => new WebSocket(url) as never, sha256, origin: SITE, sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))) },
+ { device: o.device ?? "device-test-1", port, clientId: o.clientId ?? "client-test-1" },
+ );
+ return { runner, api, local };
+}
diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.ts
index 519dd876..540213e3 100644
--- a/tests/helpers/fake-local-comfy.ts
+++ b/tests/helpers/fake-local-comfy.ts
@@ -30,6 +30,8 @@ export interface LocalComfyOptions {
steps?: number;
/** What the next prompt does. */
failNext?: "oom" | "missing_node" | "missing_model" | "gone" | "never";
+ /** Lose this many prompts in a row (taken, then gone: a restart while it waited). */
+ loseNext?: number;
/** What a job saves (default: one picture). "fake-png" is a web page named .png. */
outputs?: ("image" | "video" | "audio" | "exr" | "text" | "fake-png")[];
/** VHS meta-batch: the job finishes without outputs and queues this many more passes (the last one saves the clip). */
@@ -77,6 +79,10 @@ export interface LocalComfy {
close: () => Promise<void>;
}
+/** The ports a stand-in takes when none is given. */
+export const TEST_PORTS = [3360, 3399] as const;
+let nextPort = 0;
+
export const FAKE_PNG = Buffer.from(
"89504e470d0a1a0a0000000d494844520000000200000002080600000072b60d240000001149444154789c63381150f11f8419600c005a940a3db632c1b20000000049454e44ae426082",
"hex",
@@ -275,7 +281,8 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
devices: [{ name: "cuda:0 NVIDIA GeForce RTX 5090 : cudaMallocAsync", type: "cuda", vram_total: 32 * 2 ** 30 }],
});
}
- if (p === "/models/loras") return reply(200, opts.loras ?? []);
+ // No list given: an older ComfyUI without the route (the run goes ahead, and ComfyUI has the last word).
+ if (p === "/models/loras") return opts.loras ? reply(200, opts.loras) : reply(404, { error: "not found" });
if (p === "/models") return reply(200, ["checkpoints", "loras", "vae"]);
if (p.startsWith("/models/")) return reply(200, []);
if (p === "/object_info") return reply(200, {});
@@ -316,6 +323,10 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
});
}
const id = opts.clientPromptId && typeof json.prompt_id === "string" ? json.prompt_id : randomUUID();
+ if (opts.loseNext && opts.loseNext > 0) {
+ opts.loseNext--;
+ return reply(200, { prompt_id: id, number: ++number, node_errors: {} });
+ }
if (fail === "gone") return reply(200, { prompt_id: id, number: ++number, node_errors: {} });
const job: Job = { id, number: ++number, graph: json.prompt ?? {}, clientId: json.client_id, preview: !!json.extra_data?.preview_method && json.extra_data.preview_method !== "none", fail };
queue.push(job);
@@ -345,6 +356,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
const max = Number(url.searchParams.get("max_items") ?? 64);
return reply(200, Object.fromEntries([...history.entries()].slice(-max)));
}
+ if (p === "/api/jobs" && opts.jobsApi) return reply(200, { jobs: [...queue.map((j) => ({ id: j.id, status: "pending" })), ...(running ? [{ id: running.id, status: "in_progress" }] : [])] });
const job = /^\/api\/jobs\/([^/]+)(\/cancel)?$/.exec(p);
if (job && opts.jobsApi) {
if (job[2] && req.method === "POST") return reply(200, { cancelled: cancel(job[1]) });
@@ -397,15 +409,31 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
if (running && running.clientId === clientId) event(clientId, "executing", { node: "1", prompt_id: running.id });
};
- const listen = (at: number) =>
- new Promise<number>((resolve) => {
+ const listenOn = (at: number) =>
+ new Promise<number>((resolve, reject) => {
server = http.createServer(handler);
server.on("upgrade", upgrade);
+ server.once("error", reject);
server.listen(at, "127.0.0.1", () => {
const addr = server.address();
resolve(typeof addr === "object" && addr ? addr.port : at);
});
});
+ // No port given: a free one of the test ports (never ComfyUI's own 8188 and its neighbours), not the one the last
+ // stand-in had (a client may still hold a connection to it).
+ const listen = async (at: number): Promise<number> => {
+ if (at) return listenOn(at);
+ const span = TEST_PORTS[1] - TEST_PORTS[0] + 1;
+ for (let i = 0; i < span; i++) {
+ const p = TEST_PORTS[0] + ((nextPort++ + process.pid) % span);
+ try {
+ return await listenOn(p);
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== "EADDRINUSE") throw e;
+ }
+ }
+ throw new Error(`No free port in ${TEST_PORTS.join("–")}`);
+ };
const closeSockets = () => {
for (const set of sockets.values()) for (const s of set) s.destroy();