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.

Live edit: the server path, and who may use it

Adarsh4030556e6373
diff --git a/src/app/api/live/cancel/route.ts b/src/app/api/live/cancel/route.ts
new file mode 100644
index 00000000..9d7f26ae
--- /dev/null
+++ b/src/app/api/live/cancel/route.ts
@@ -0,0 +1,21 @@
+import { connection } from "next/server";
+import { liveWho } from "@/server/live/access";
+import { sessionOf } from "@/server/live/sessions";
+
+/**
+ * Take this tab's stale renders off (a backup for a browser whose aborted request doesn't reach the server):
+ * { sessionId, seqs?: number[], slot?: "live" | "settle" | "warm" }. Keeps are never cancelled here.
+ */
+export async function POST(request: Request) {
+ await connection();
+ const who = liveWho(request, { server: true });
+ if (who instanceof Response) return who;
+ const b = ((await request.json().catch(() => null)) ?? {}) as { sessionId?: unknown; seqs?: unknown; slot?: unknown };
+ const s = sessionOf(who.principal, b.sessionId);
+ if (!s) return Response.json({ error: "This live session ended", code: "session" }, { status: 410 });
+ const seqs = Array.isArray(b.seqs) ? new Set(b.seqs.filter((n): n is number => Number.isSafeInteger(n)).slice(0, 64)) : null;
+ const slot = b.slot === "live" || b.slot === "settle" || b.slot === "warm" ? b.slot : null;
+ if (!seqs && !slot) return Response.json({ error: "Name the renders to stop" }, { status: 400 });
+ s.scheduler.cancel((j) => j.slot !== "keep" && (!seqs || seqs.has(j.seq)) && (!slot || j.slot === slot));
+ return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/live/events/route.ts b/src/app/api/live/events/route.ts
new file mode 100644
index 00000000..83cad67a
--- /dev/null
+++ b/src/app/api/live/events/route.ts
@@ -0,0 +1,45 @@
+import { connection } from "next/server";
+import { liveWho } from "@/server/live/access";
+import { onLiveStatus, type LiveStatus } from "@/server/live/comfy-live";
+import { sessionOf } from "@/server/live/sessions";
+
+/**
+ * Live edit's status for this tab (server-sent events): `status` (online, who runs on ComfyUI, the queue, whether
+ * another job ran since our last render) whenever it changes, and a ping every 15 s. On a linked GPU there is no socket:
+ * one status, then pings.
+ */
+export async function GET(request: Request) {
+ await connection();
+ const who = liveWho(request, { server: true });
+ if (who instanceof Response) return who;
+ const s = sessionOf(who.principal, new URL(request.url).searchParams.get("session"));
+ if (!s) return Response.json({ error: "This live session ended", code: "session" }, { status: 410 });
+ const enc = new TextEncoder();
+ let stop = () => {};
+ const stream = new ReadableStream<Uint8Array>({
+ start(c) {
+ const send = (text: string) => {
+ try {
+ c.enqueue(enc.encode(text));
+ } catch {
+ stop();
+ }
+ };
+ const status = (st: LiveStatus) => send(`event: status\ndata: ${JSON.stringify(st)}\n\n`);
+ const off = s.gpu ? (status({ online: true, running: null, queue: 0, otherRan: false }), () => {}) : onLiveStatus(status);
+ const ping = setInterval(() => send(": ping\n\n"), 15_000);
+ stop = () => {
+ clearInterval(ping);
+ off();
+ try {
+ c.close();
+ } catch {}
+ };
+ request.signal.addEventListener("abort", () => stop(), { once: true });
+ },
+ cancel() {
+ stop();
+ },
+ });
+ return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store", "X-Accel-Buffering": "no" } });
+}
diff --git a/src/app/api/live/inputs/route.ts b/src/app/api/live/inputs/route.ts
new file mode 100644
index 00000000..f9bcb0b7
--- /dev/null
+++ b/src/app/api/live/inputs/route.ts
@@ -0,0 +1,61 @@
+import { connection } from "next/server";
+import { pictureExt } from "@/lib/live/names";
+import { MAX_MASTER_SIDE } from "@/lib/live/sizes";
+import { imageSize } from "@/lib/image-size";
+import { asWho, liveWho } from "@/server/live/access";
+import { LiveRenderError } from "@/server/live/comfy-live";
+import { sessionOf, stage } from "@/server/live/sessions";
+import { hit } from "@/server/rate";
+import { readRef, RefError } from "@/server/storage";
+
+/** The largest mask a tab sends (a painted region, PNG). */
+const MASK_BYTES = 8 * 2 ** 20;
+const FILE_REF = /^\/api\/files\/[\w./%-]{1,300}$/;
+
+/**
+ * Put a picture into ComfyUI's input folder for this session, under its content name: a Fuobe file (the picture
+ * being edited, a reference, or a kept master), JSON { sessionId, file }; or a painted mask, sent as a PNG body with
+ * the x-live-session header. Answers { name, width, height, sha256 }. Nothing is uploaded twice.
+ */
+export async function POST(request: Request) {
+ await connection();
+ const who = liveWho(request, { server: true });
+ if (who instanceof Response) return who;
+ const rate = hit(`live-inputs:${who.principal}`, 30, 60_000);
+ if (!rate.ok) return Response.json({ error: "Too many pictures at once. Try again in a moment." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
+ const type = request.headers.get("content-type") ?? "";
+ let sessionId: unknown;
+ let data: Uint8Array;
+ let reread: (() => Promise<Uint8Array>) | undefined;
+ if (type.startsWith("image/png")) {
+ sessionId = request.headers.get("x-live-session");
+ const buf = new Uint8Array(await request.arrayBuffer());
+ if (buf.length > MASK_BYTES) return Response.json({ error: "That mask is too large" }, { status: 413 });
+ data = buf;
+ } else {
+ const body = (await request.json().catch(() => null)) as { sessionId?: unknown; file?: unknown } | null;
+ sessionId = body?.sessionId;
+ const file = body?.file;
+ if (typeof file !== "string" || !FILE_REF.test(file)) return Response.json({ error: "Send a picture from your files" }, { status: 400 });
+ try {
+ const read = () => asWho(who, () => readRef(file)).then((r) => new Uint8Array(r.data));
+ data = await read();
+ reread = read;
+ } catch (e) {
+ if (e instanceof RefError) return Response.json({ error: e.message }, { status: e.status });
+ return Response.json({ error: "That picture can't be read" }, { status: 404 });
+ }
+ }
+ const s = sessionOf(who.principal, sessionId);
+ if (!s) return Response.json({ error: "This live session ended. Reload the page.", code: "session" }, { status: 410 });
+ if (!pictureExt(data)) return Response.json({ error: "Only PNG, JPEG or WebP pictures" }, { status: 415 });
+ const size = imageSize(data);
+ if (!size || Math.max(size.width, size.height) > MAX_MASTER_SIDE) return Response.json({ error: `Pictures up to ${MAX_MASTER_SIDE} px on the long side` }, { status: 413 });
+ try {
+ const st = await stage(s, data, reread);
+ return Response.json({ name: st.name, width: size.width, height: size.height, sha256: st.sha256 }, { headers: { "Cache-Control": "no-store" } });
+ } catch (e) {
+ const msg = e instanceof LiveRenderError ? e.message : "Couldn't send the picture to ComfyUI";
+ return Response.json({ error: msg, code: e instanceof LiveRenderError ? e.code : "failed" }, { status: 502 });
+ }
+}
diff --git a/src/app/api/live/masters/route.ts b/src/app/api/live/masters/route.ts
new file mode 100644
index 00000000..361d051c
--- /dev/null
+++ b/src/app/api/live/masters/route.ts
@@ -0,0 +1,56 @@
+import { connection } from "next/server";
+import { imageSize } from "@/lib/image-size";
+import { pictureExt } from "@/lib/live/names";
+import { MAX_MASTER_SIDE } from "@/lib/live/sizes";
+import { ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";
+import { gateAsProxy, readBodyWithin } from "@/server/direct-gate";
+import { liveWho } from "@/server/live/access";
+import { enter, hit, unhit } from "@/server/rate";
+import { saveFile } from "@/server/storage";
+
+/** A master is a PNG of at most 4096 px a side: this holds the largest with room to spare. */
+const MAX_BYTES = 80 * 2 ** 20;
+/** An account's kept masters per hour. */
+const ACCOUNT_MASTERS_PER_HOUR = 120;
+
+/**
+ * A kept step's master from a tab that renders on its own computer ("Use the ComfyUI on this computer"): the PNG body
+ * as the tab received it from ComfyUI. Stored as the owner's file, or as the account's own within its limits. Answers
+ * { id, url }. The proxy's matcher leaves this route out (a large body), so its rules run here first.
+ */
+export async function POST(request: Request) {
+ await connection();
+ const denied = gateAsProxy(request);
+ if (denied) return denied;
+ const who = liveWho(request, { server: false });
+ if (who instanceof Response) return who;
+ const refuse = (status: number, error: string, code?: string, headers: Record<string, string> = {}) =>
+ Response.json({ error, ...(code && { code }) }, { status, headers: { "Cache-Control": "no-store", ...headers } });
+ const reading = who.kind === "account" ? enter(`live-master-now:${who.account.id}`, 2) : () => {};
+ if (!reading) return refuse(429, "One master at a time. Try again in a moment.", undefined, { "Retry-After": "2" });
+ let body: Buffer | "too-big" | null;
+ try {
+ body = await readBodyWithin(request, MAX_BYTES);
+ } finally {
+ reading();
+ }
+ if (body === "too-big") return refuse(413, "That master is too large");
+ if (!body || pictureExt(body) !== "png") return refuse(415, "A master is a PNG picture");
+ const size = imageSize(body);
+ if (!size || Math.max(size.width, size.height) > MAX_MASTER_SIDE) return refuse(413, `Masters up to ${MAX_MASTER_SIDE} px on the long side`);
+ if (who.kind === "account") {
+ if (!diskHasRoom()) return refuse(507, ACCOUNT_MESSAGES.diskLow, "space");
+ if (accountUsage(who.account.id).total + body.length > accountTotalBytes(who.account.id)) return refuse(507, filesFullMessage(who.account.id), "space");
+ const rate = hit(`live-masters:${who.account.id}`, ACCOUNT_MASTERS_PER_HOUR, 60 * 60_000);
+ if (!rate.ok) return refuse(429, "That's a lot of kept steps for one hour. Download them, or try again later.", "rate", { "Retry-After": String(rate.retryAfterS) });
+ try {
+ const a = saveFile({ data: body, contentType: "image/png", name: "live-edit.png", source: "derived", accountId: who.account.id });
+ return Response.json({ id: a.id, url: a.url }, { status: 201, headers: { "Cache-Control": "no-store" } });
+ } catch (e) {
+ unhit(`live-masters:${who.account.id}`);
+ throw e;
+ }
+ }
+ const a = saveFile({ data: body, contentType: "image/png", name: "live-edit.png", source: "derived" });
+ return Response.json({ id: a.id, url: a.url }, { status: 201, headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/live/nodes/route.ts b/src/app/api/live/nodes/route.ts
new file mode 100644
index 00000000..9a9089bf
--- /dev/null
+++ b/src/app/api/live/nodes/route.ts
@@ -0,0 +1,16 @@
+import { LIVE_NODES_FILE_NAME, LIVE_NODES_SOURCE } from "@/lib/comfy-live-nodes";
+
+/**
+ * Fuobe's live edit nodes for ComfyUI (fuobe_live.py), as a download: put it in ComfyUI's custom_nodes folder and
+ * restart ComfyUI. The same file the Windows start file writes; open source, so anyone may fetch it.
+ */
+export function GET() {
+ return new Response(LIVE_NODES_SOURCE, {
+ headers: {
+ "Content-Type": "text/x-python; charset=utf-8",
+ "Content-Disposition": `attachment; filename="${LIVE_NODES_FILE_NAME}"`,
+ "Cache-Control": "public, max-age=300",
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+}
diff --git a/src/app/api/live/render/route.ts b/src/app/api/live/render/route.ts
new file mode 100644
index 00000000..dd8adaac
--- /dev/null
+++ b/src/app/api/live/render/route.ts
@@ -0,0 +1,175 @@
+import { connection } from "next/server";
+import { eventFrame, imageFrame, LIVE_STREAM_TYPE, type LiveEvent } from "@/lib/live/frames";
+import { MAX_GRAPH_PROMPT, slotBindings, type LiveGraphParams } from "@/lib/live/graph";
+import { LIVE_INPUT } from "@/lib/live/names";
+import { isAspect, isKeepRes, isLiveSize, editSize } from "@/lib/live/sizes";
+import { MAX_LIVE_TEXT, normalize, renderKey } from "@/lib/live/text";
+import { ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";
+import { asWho, liveWho } from "@/server/live/access";
+import { LiveRenderError } from "@/server/live/comfy-live";
+import { sessionOf, stage, submit, type Rendered } from "@/server/live/sessions";
+import { enter, hit } from "@/server/rate";
+import { readRef, saveFile } from "@/server/storage";
+
+const SLOTS = new Set(["live", "settle", "keep", "warm"]);
+
+interface Body {
+ sessionId?: unknown;
+ seq?: unknown;
+ slot?: unknown;
+ urgent?: unknown;
+ text?: unknown;
+ /** compose (an owner's lab method): the kept texts and the live text as one instruction. */
+ compose?: unknown;
+ seed?: unknown;
+ size?: unknown;
+ keepRes?: unknown;
+ base?: unknown;
+ refs?: unknown;
+ mask?: unknown;
+ aspect?: unknown;
+ method?: unknown;
+ fromSettled?: unknown;
+}
+
+const isName = (v: unknown): v is string => typeof v === "string" && LIVE_INPUT.test(v);
+
+/**
+ * One live render, answered as a framed stream (src/lib/live/frames.ts): queued, started, progress, then the picture
+ * (or dropped / error). Stale renders end when the tab aborts the request (deleted from ComfyUI's queue while waiting,
+ * interrupted while running); /api/live/cancel does the same for a request whose abort didn't arrive. A keep stores
+ * the picture as a full-size PNG master (the settled render on screen, when it is still held) and stages it as the
+ * next base.
+ */
+export async function POST(request: Request) {
+ await connection();
+ const who = liveWho(request, { server: true });
+ if (who instanceof Response) return who;
+ const b = ((await request.json().catch(() => null)) ?? {}) as Body;
+ const s = sessionOf(who.principal, b.sessionId);
+ if (!s) return Response.json({ error: "This live session ended. Reload the page.", code: "session" }, { status: 410 });
+ const seq = Number(b.seq);
+ const slot = String(b.slot);
+ if (!Number.isSafeInteger(seq) || seq < 0 || !SLOTS.has(slot)) return Response.json({ error: "Bad render" }, { status: 400 });
+ const live = hit(`live-render:${s.id}`, 12, 1000);
+ const all = hit(`live-render:${who.principal}`, 40, 1000);
+ if (!live.ok || !all.ok) return Response.json({ error: "Too many renders" }, { status: 429, headers: { "Retry-After": "1" } });
+
+ // What to render: every value checked against the session and the size tables.
+ const text = typeof b.text === "string" ? b.text : "";
+ const compose = who.kind === "owner" && b.method === "compose" && typeof b.compose === "string" ? b.compose : null;
+ const prompt = compose !== null ? compose.slice(0, MAX_GRAPH_PROMPT) : normalize(text.slice(0, MAX_LIVE_TEXT * 2));
+ const seed = Number(b.seed);
+ if (!Number.isSafeInteger(seed) || seed < 0) return Response.json({ error: "Bad seed" }, { status: 400 });
+ const base = b.base === undefined || b.base === null ? undefined : b.base;
+ if (base !== undefined && (!isName(base) || !s.staged.has(base))) return Response.json({ error: "That picture isn't in this session. Add it again.", code: "missing-input" }, { status: 409 });
+ const refs = Array.isArray(b.refs) ? b.refs.slice(0, 3) : [];
+ if (!refs.every((r) => isName(r) && s.staged.has(r))) return Response.json({ error: "A reference isn't in this session", code: "missing-input" }, { status: 409 });
+ const mask = b.mask === undefined || b.mask === null ? undefined : b.mask;
+ if (mask !== undefined && (!isName(mask) || !s.staged.has(mask))) return Response.json({ error: "The painted region isn't in this session", code: "missing-input" }, { status: 409 });
+ if (!base && slot !== "warm" && !prompt) return Response.json({ error: "Type what to make" }, { status: 400 });
+ const size = Number(b.size);
+ const keepRes = Number(b.keepRes);
+ if (!isLiveSize(size) || !isKeepRes(keepRes)) return Response.json({ error: "Bad size" }, { status: 400 });
+ const aspect = isAspect(b.aspect) ? b.aspect : "1:1";
+ const baseInfo = base ? s.staged.get(base) : undefined;
+ const liveLong = baseInfo?.w ? Math.max(...editSize(size, baseInfo.w, baseInfo.h)) : size;
+ const bind = slotBindings(slot as "live", { liveSize: size, keepRes, hasMask: !!mask, to: s.gpu ? "temp" : "socket", liveLongSide: liveLong });
+ const params: LiveGraphParams = {
+ prompt: slot === "warm" ? "warm-up" : prompt,
+ seed: slot === "warm" ? 0 : seed,
+ ...bind,
+ ...(base && { base }),
+ ...(refs.length && { refs: refs as string[] }),
+ ...(mask && { mask }),
+ ...(!base && { aspect }),
+ };
+ const quality = slot === "settle" || slot === "keep" ? "keep" : "live";
+ const key = renderKey({ base: base ?? "", refs: refs as string[], mask, text: prompt, seed, size: params.res, aspect, method: typeof b.method === "string" ? b.method : "hybrid", quality });
+ // Keep after a settle of the same text, seed and size: the settled picture on screen is stored as it is (no new render).
+ const fromSettled = slot === "keep" && b.fromSettled !== false ? key : undefined;
+
+ const leave = enter(`live-render-now:${s.id}`, 3);
+ if (!leave) return Response.json({ error: "Too many renders at once" }, { status: 429, headers: { "Retry-After": "1" } });
+ let closed = false;
+ let ctl!: ReadableStreamDefaultController<Uint8Array>;
+ const send = (u: Uint8Array) => {
+ if (closed) return;
+ try {
+ ctl.enqueue(u);
+ } catch {
+ closed = true;
+ }
+ };
+ const end = () => {
+ if (closed) return;
+ closed = true;
+ try {
+ ctl.close();
+ } catch {}
+ };
+ const onEvent = (e: LiveEvent) => send(eventFrame(e));
+ const stop = () => {
+ // A stale request: taken off (keeps are never cancelled by a lost connection).
+ if (slot !== "keep") s.scheduler.cancel((j) => j.seq === seq);
+ };
+ request.signal.addEventListener("abort", stop, { once: true });
+
+ const work = async () => {
+ try {
+ const out = await submit(s, { seq, slot: slot as "live", key, urgent: b.urgent === true, payload: { params, fromSettled, onEvent } });
+ if (!out.ok) {
+ if ("dropped" in out) onEvent({ type: "dropped", why: out.dropped });
+ else onEvent({ type: "error", message: out.error });
+ return;
+ }
+ const pic: Rendered = out.result;
+ let extra: { masterId?: string; url?: string; name?: string } = {};
+ if (slot === "keep") {
+ extra = await keepMaster(pic);
+ if ("error" in extra) return;
+ }
+ send(imageFrame({ seq, slot, key, w: pic.w, h: pic.h, type: pic.type, ms: pic.ms, sha256: pic.sha256, ...extra }, pic.data));
+ } catch (e) {
+ onEvent({ type: "error", message: e instanceof LiveRenderError ? e.message : "The render failed", ...(e instanceof LiveRenderError && { code: e.code }) });
+ } finally {
+ request.signal.removeEventListener("abort", stop);
+ leave();
+ end();
+ }
+ };
+
+ /** Store a kept picture as the step's master (the owner's file, or the account's own) and stage it as the next base. */
+ const keepMaster = async (pic: Rendered): Promise<{ masterId?: string; url?: string; name?: string } & { error?: true }> => {
+ if (pic.type !== "image/png") {
+ onEvent({ type: "error", message: "A kept picture must be a PNG master" });
+ return { error: true };
+ }
+ const data = Buffer.from(pic.data);
+ if (who.kind === "account") {
+ if (!diskHasRoom()) {
+ onEvent({ type: "error", message: ACCOUNT_MESSAGES.diskLow, code: "space" });
+ return { error: true };
+ }
+ if (accountUsage(who.account.id).total + data.length > accountTotalBytes(who.account.id)) {
+ onEvent({ type: "error", message: filesFullMessage(who.account.id), code: "space" });
+ return { error: true };
+ }
+ }
+ const asset = saveFile({ data, contentType: "image/png", name: `live-edit-${seq}.png`, source: "derived", ...(who.kind === "account" && { accountId: who.account.id }) });
+ const st = await stage(s, pic.data, () => asWho(who, () => readRef(asset.url)).then((r) => new Uint8Array(r.data)));
+ return { masterId: asset.id, url: asset.url, name: st.name };
+ };
+
+ const stream = new ReadableStream<Uint8Array>({
+ start(c) {
+ ctl = c;
+ void work();
+ },
+ cancel() {
+ closed = true;
+ stop();
+ },
+ });
+ return new Response(stream, { headers: { "Content-Type": LIVE_STREAM_TYPE, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "X-Live-Key": encodeURIComponent(key) } });
+}
diff --git a/src/app/api/live/save/route.ts b/src/app/api/live/save/route.ts
new file mode 100644
index 00000000..4682f1de
--- /dev/null
+++ b/src/app/api/live/save/route.ts
@@ -0,0 +1,25 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { LIBRARY_MESSAGE } from "@/lib/guest-access";
+import { liveWho } from "@/server/live/access";
+import { recordLiveEdit } from "@/server/generations";
+import { filesRel } from "@/server/storage";
+
+const FileRef = z.string().startsWith("/api/files/").max(500).refine((s) => filesRel(s) !== null);
+const Body = z.object({
+ master: FileRef,
+ original: FileRef.optional(),
+ steps: z.array(z.object({ text: z.string().max(2000), seed: z.number().int().min(0) })).max(200),
+ from: z.string().max(40).optional(),
+});
+
+/** Save a live edit's current picture to the Library (the owner's): its kept master, with the steps that made it. */
+export async function POST(request: Request) {
+ await connection();
+ const who = liveWho(request, { server: false });
+ if (who instanceof Response) return who;
+ if (who.kind !== "owner") return Response.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Nothing to save" }, { status: 400 });
+ return Response.json(recordLiveEdit(parsed.data), { status: 201 });
+}
diff --git a/src/app/api/live/session/route.ts b/src/app/api/live/session/route.ts
new file mode 100644
index 00000000..6d9eea6b
--- /dev/null
+++ b/src/app/api/live/session/route.ts
@@ -0,0 +1,35 @@
+import { connection } from "next/server";
+import { KEEP_LADDER, LIVE_LADDER } from "@/lib/live/sizes";
+import { MAX_LIVE_TEXT } from "@/lib/live/text";
+import { asWho, liveWho } from "@/server/live/access";
+import { liveFacts, liveSocket } from "@/server/live/comfy-live";
+import { openSession } from "@/server/live/sessions";
+import { onOwnGpu } from "@/server/providers/comfyui";
+
+/**
+ * Open (or renew) this tab's live edit session on the server path: the owner's local ComfyUI, or an account's linked
+ * GPU. The tab on "Use the ComfyUI on this computer" never calls it (it talks to its ComfyUI itself).
+ */
+export async function POST(request: Request) {
+ await connection();
+ const who = liveWho(request, { server: true });
+ if (who instanceof Response) return who;
+ const body = (await request.json().catch(() => ({}))) as { sessionId?: unknown };
+ const gpu = who.kind === "account" ? who.gpu : undefined;
+ const s = openSession(who.principal, gpu, typeof body.sessionId === "string" ? body.sessionId : undefined);
+ if (!gpu) liveSocket();
+ const facts = await asWho(who, () => (gpu ? onOwnGpu(gpu, liveFacts) : liveFacts()));
+ return Response.json(
+ {
+ sessionId: s.id,
+ mode: gpu ? "link" : "server",
+ seed: s.seed,
+ sizes: { live: LIVE_LADDER, keep: KEEP_LADDER },
+ nodes: { live: facts.nodes > 0, version: facts.nodes, ws: !gpu },
+ highvram: facts.highvram,
+ missing: facts.missing,
+ maxText: MAX_LIVE_TEXT,
+ },
+ { headers: { "Cache-Control": "no-store" } },
+ );
+}
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index c6b50f95..1288c282 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -21,7 +21,7 @@ export const GUEST_LIBRARY_MESSAGE = "Sign up to see your library.";
export const GUEST_RUN_MESSAGE = "Create a free account to run this.";
/** Catalog and status reads that hold nothing of the owner's library: a guest gets the real answer. */
-const GUEST_READS = new Set(["/api/status", "/api/models", "/api/search-index", "/api/comfyui", "/api/settings/models", "/api/gpu/requirements"]);
+const GUEST_READS = new Set(["/api/status", "/api/models", "/api/search-index", "/api/comfyui", "/api/settings/models", "/api/gpu/requirements", "/api/live/nodes"]);
/** Catalogs mixed with the owner's own items: the route leaves the owner's part out for a guest (GUEST_HEADER). */
const GUEST_FILTERED = new Set(["/api/moodboards", "/api/palettes", "/api/assist", "/api/assist/skills"]);
@@ -204,6 +204,25 @@ export function accountMayChange(method: string, pathname: string, search: strin
return isPriceCheck(method, pathname, search);
}
+/**
+ * Live edit (src/app/api/live): the route a path names, or null. "nodes" is the node file's download (open to anyone);
+ * every other route runs or stores live edits.
+ */
+export type LiveRoute = "session" | "inputs" | "render" | "cancel" | "events" | "masters" | "save" | "nodes";
+const LIVE_ROUTE = /^\/api\/live\/(session|inputs|render|cancel|events|masters|save|nodes)$/;
+export const liveRoute = (pathname: string): LiveRoute | null => (LIVE_ROUTE.exec(pathname)?.[1] as LiveRoute | undefined) ?? null;
+
+/**
+ * What an account gets on a live edit route, by its own GPU: it renders only there (a linked GPU through the server, or
+ * its own computer from its tab), keeps its masters in its own files, and has no Library to save to. A guest gets
+ * GUEST_RUN_MESSAGE on all of them but the node download.
+ */
+export function accountLive(route: LiveRoute, gpu: "link" | "computer" | null): "pass" | "connect-gpu" | "library" {
+ if (route === "nodes") return "pass";
+ if (route === "save") return "library";
+ return gpu ? "pass" : "connect-gpu";
+}
+
/** Assist (chats, skills, memory, projects, schedules): any change to it, which only the owner may make on a public studio. */
export function isAssistChange(method: string, pathname: string): boolean {
return method !== "GET" && method !== "HEAD" && (pathname === "/api/assist" || pathname.startsWith("/api/assist/"));
diff --git a/src/proxy.ts b/src/proxy.ts
index e410c6e1..1f774b3c 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -6,6 +6,9 @@ import { countsAsView, SHARE_VIEW_HEADER, shareRoute } from "@/lib/share";
import {
ACCOUNT_LIBRARY_MESSAGE,
accountGeneration,
+ accountLive,
+ CONNECT_GPU_MESSAGE,
+ liveRoute,
accountMayChange,
accountOwnRead,
ASSIST_OWNER_MESSAGE,
@@ -162,6 +165,9 @@ function priceCheck(request: NextRequest, who: string): NextResponse {
function guest(request: NextRequest): NextResponse {
const { pathname, search } = request.nextUrl;
const { method } = request;
+ // Live edit runs on a GPU of one's own: signing up is the next step (the node file's download is open).
+ const live = liveRoute(pathname);
+ if (live && live !== "nodes") return NextResponse.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: guestHeaders });
if (method === "GET" || method === "HEAD") return readAsGuest(request, false);
if (isPriceCheck(method, pathname, search)) return priceCheck(request, `guest:${LoginGuard.clientKey(request.headers)}`);
if (isAssistChange(method, pathname)) return assistOwner();
@@ -212,6 +218,14 @@ function account(request: NextRequest, who: Account): NextResponse {
const verb = request.method === "GET" || request.method === "HEAD" ? "see" : "change";
return NextResponse.json({ error: `Only the studio's owner can ${verb} settings, keys and tokens.` }, { status: 403 });
}
+ // Live edit: only on its own GPU, its masters in its own files, no Library.
+ const live = liveRoute(pathname);
+ if (live) {
+ const may = accountLive(live, who.gpu ? (who.gpu.mode === "computer" ? "computer" : "link") : null);
+ if (may === "library") return NextResponse.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });
+ if (may === "connect-gpu") return NextResponse.json({ error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
+ return pass(request);
+ }
// Its own runs and their files: only what it made.
const gen = accountGeneration(request.method, pathname);
if (gen !== undefined) return generationAccount(gen) === who.id ? pass(request) : notYours();
@@ -339,8 +353,8 @@ export const config = {
// (/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. So do a computer's report of a finished job and its results
- // (src/app/api/gpu/computer/tasks).
+ // (src/app/api/gpu/computer/tasks), and live edit's kept master from a tab on its own computer (src/app/api/live/masters).
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$|api/gpu/computer/tasks/[^/]+/(?:report|outputs/[^/]+)$|[^/]+\\.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/[^/]+)$|api/live/masters$|[^/]+\\.svg$).*)",
],
};
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 8669cf96..b3ace781 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -2338,6 +2338,57 @@ export function finishOutput(id: string, index: number, png: Buffer): Generation
// ---------------------------------------------------------------------------
// Results made in the browser (colour grading): stored as finished generations.
+/**
+ * A live edit saved to the Library (the owner's): the kept master as the result, the steps that made it in
+ * params.liveSteps, the joined step texts as the prompt. It ran on the owner's GPU already, so nothing is queued.
+ */
+export function recordLiveEdit(input: { master: string; original?: string; steps: { text: string; seed: number }[]; from?: string }): Generation {
+ const model = getModel("oss-qwen-image-21-live");
+ if (!model) throw new Error("Live edit's model is missing");
+ const now = Date.now();
+ const prompt = input.steps.map((s) => s.text).filter(Boolean).join(" · ").slice(0, 2000) || "Live edit";
+ const op: Generation["op"] = input.original ? "edit" : "t2i";
+ const req: GenerationRequest = {
+ feature: "live-edit",
+ modelId: model.id,
+ op,
+ prompt,
+ inputs: input.original ? { images: [input.original] } : {},
+ params: { extra: { liveSteps: input.steps, ...(input.from && { from: input.from }) } },
+ };
+ const row: Row = {
+ id: nanoid(12),
+ batch_id: null,
+ feature: "live-edit",
+ preset_id: null,
+ model_id: model.id,
+ engine: model.engine,
+ provider: "comfyui",
+ op,
+ kind: "image",
+ status: "succeeded",
+ progress: 1,
+ message: null,
+ prompt,
+ request_json: JSON.stringify(req),
+ provider_input_json: null,
+ external_id: "live",
+ external_meta_json: null,
+ outputs_json: JSON.stringify([{ url: input.master, kind: "image", contentType: "image/png" }]),
+ error: null,
+ cost_usd: 0,
+ favorite: 0,
+ created_at: now,
+ updated_at: now,
+ completed_at: now,
+ depends_on: null,
+ };
+ db()
+ .prepare(`INSERT INTO generations (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
+ .run(row);
+ return toGeneration(row);
+}
+
export function recordLocalGeneration(input: {
feature: string;
modelId: string;
diff --git a/src/server/live/access.ts b/src/server/live/access.ts
new file mode 100644
index 00000000..50cb1cdb
--- /dev/null
+++ b/src/server/live/access.ts
@@ -0,0 +1,44 @@
+import "server-only";
+import { getModel } from "@/lib/catalog";
+import { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE, GUEST_RUN_MESSAGE } from "@/lib/guest-access";
+import { LIVE_MODEL_ID } from "@/lib/live/graph";
+import { gpuLink, requestViewer, type Account } from "../auth";
+import { offeredModel } from "../model-access";
+import { computerScope, type OwnGpu } from "../providers/comfyui";
+import { runAsTenant } from "../tenant";
+
+/** Said when the owner turned live edit's model off. */
+export const LIVE_OFF_MESSAGE = "Live edit is turned off in Models & licences.";
+/** Said on the server path when ComfyUI runs on the person's own computer: the tab talks to it directly. */
+export const LIVE_ON_COMPUTER = "ComfyUI runs on your computer: live edit talks to it from this tab.";
+
+export type LiveWho = { kind: "owner"; principal: "owner" } | { kind: "account"; principal: `acct:${string}`; account: Account; gpu?: OwnGpu };
+
+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 } });
+
+/**
+ * Who may use live edit's routes, and on which GPU. The proxy has already refused guests and accounts without a GPU of
+ * their own; this checks again, and adds the model's switch. `server`: a route that reaches ComfyUI from the server (an
+ * account needs a linked GPU; the owner's ComfyUI must not be on the owner's computer).
+ */
+export function liveWho(request: Request, o: { server: boolean }): LiveWho | Response {
+ const model = getModel(LIVE_MODEL_ID);
+ if (!model || !offeredModel(model)) return no(403, LIVE_OFF_MESSAGE, { code: "off" });
+ const v = requestViewer(request);
+ if (v.kind === "guest") return no(401, GUEST_RUN_MESSAGE);
+ if (v.kind === "owner") {
+ if (o.server && computerScope()) return no(409, LIVE_ON_COMPUTER, { code: "computer" });
+ return { kind: "owner", principal: "owner" };
+ }
+ const account = v.account;
+ const link = gpuLink(account.gpu);
+ if (o.server && !link) {
+ return account.gpu?.mode === "computer" ? no(409, LIVE_ON_COMPUTER, { code: "computer" }) : no(403, CONNECT_GPU_MESSAGE, { code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });
+ }
+ if (!account.gpu) return no(403, CONNECT_GPU_MESSAGE, { code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });
+ return { kind: "account", principal: `acct:${account.id}`, account, ...(link && { gpu: { url: link.url, token: link.token } }) };
+}
+
+/** Run as the asker: an account's work reads only its own files. */
+export const asWho = <T,>(who: LiveWho, fn: () => T): T => (who.kind === "account" ? runAsTenant({ kind: "account", id: who.account.id }, fn) : fn());
diff --git a/src/server/live/comfy-live.ts b/src/server/live/comfy-live.ts
new file mode 100644
index 00000000..da861865
--- /dev/null
+++ b/src/server/live/comfy-live.ts
@@ -0,0 +1,393 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { parseComfyBinary, parseComfyText } from "@/lib/comfy-ws";
+import type { LiveEvent } from "@/lib/live/frames";
+import { LIVE_FILES, LIVE_OUTPUT, type LiveGraph } from "@/lib/live/graph";
+import { comfyRequest, ownGpu } from "../providers/comfyui";
+import { getSetting } from "../settings";
+
+/**
+ * Live edit's own line to ComfyUI (the server path: a local install, or an account's linked GPU). The provider's
+ * socket belongs to the job runner and ignores pictures, so live edit keeps its own, with its own client id: its save
+ * node sends each finished picture over it, and nothing is written to disk or read back through /view. A render is
+ * registered before its prompt is posted (a fast finish can't be missed), posted at the front of ComfyUI's queue, and
+ * taken out of the history once its picture is in. Stopping one deletes it while it waits and interrupts it while it
+ * runs; only Fuobe's own live prompts are ever touched.
+ *
+ * On an account's linked GPU there is no socket (fetchPublic only): the picture is saved to temp and read back, with
+ * the history polled every 80 ms.
+ */
+
+export interface LivePicture {
+ data: Uint8Array;
+ type: string;
+ w: number;
+ h: number;
+ /** ComfyUI's time, from the start of the render to the picture. */
+ ms: number;
+}
+
+export type LiveFailure = "offline" | "missing-input" | "missing-nodes" | "failed" | "stopped";
+
+export class LiveRenderError extends Error {
+ readonly code: LiveFailure;
+ constructor(message: string, code: LiveFailure) {
+ super(message);
+ this.code = code;
+ }
+}
+
+export interface LiveStatus {
+ online: boolean;
+ /** What ComfyUI is running now: one of ours, someone else's job, or nothing. */
+ running: "ours" | "other" | null;
+ /** Prompts waiting or running in ComfyUI. */
+ queue: number;
+ /** Another job ran since our last render (the model may have been unloaded: warm up first). */
+ otherRan: boolean;
+}
+
+interface Waiter {
+ id: string;
+ started: boolean;
+ startedAt: number;
+ onEvent: (e: LiveEvent) => void;
+ resolve: (p: LivePicture) => void;
+ reject: (e: Error) => void;
+}
+
+interface LiveSocket {
+ url: string;
+ clientId: string;
+ ws?: WebSocket;
+ online: boolean;
+ backoff: number;
+ timer?: ReturnType<typeof setTimeout>;
+ waiters: Map<string, Waiter>;
+ listeners: Set<(s: LiveStatus) => void>;
+ status: LiveStatus;
+ /** Ours, waiting in ComfyUI's queue. */
+ waiting: number;
+}
+
+declare global {
+ var __fuobeLiveSocket: LiveSocket | undefined;
+}
+
+const comfyUrl = () => getSetting("comfyUrl").replace(/\/+$/, "");
+
+/** The live socket for the install's ComfyUI (one per process, kept across hot reloads), connecting if it isn't. */
+export function liveSocket(): LiveSocket {
+ const url = comfyUrl();
+ let s = globalThis.__fuobeLiveSocket;
+ if (s && s.url !== url) {
+ closeSocket(s, "ComfyUI's address changed");
+ s = undefined;
+ }
+ if (!s) {
+ s = { url, clientId: `fuobe-live-${nanoid(10)}`, online: false, backoff: 250, waiters: new Map(), listeners: new Set(), status: { online: false, running: null, queue: 0, otherRan: false }, waiting: 0 };
+ globalThis.__fuobeLiveSocket = s;
+ }
+ if (!s.ws && !s.timer) connect(s);
+ return s;
+}
+
+function setStatus(s: LiveSocket, patch: Partial<LiveStatus>) {
+ const next = { ...s.status, ...patch };
+ if (JSON.stringify(next) === JSON.stringify(s.status)) return;
+ s.status = next;
+ for (const l of s.listeners) {
+ try {
+ l(next);
+ } catch {}
+ }
+}
+
+/** Hear the socket's status (online, who runs, the queue). Returns the unsubscribe. */
+export function onLiveStatus(fn: (s: LiveStatus) => void): () => void {
+ const s = liveSocket();
+ s.listeners.add(fn);
+ fn(s.status);
+ return () => s.listeners.delete(fn);
+}
+
+/** A live render ran (ours): the model is loaded again. */
+export function markWarm(): void {
+ const s = globalThis.__fuobeLiveSocket;
+ if (s) setStatus(s, { otherRan: false });
+}
+
+function closeSocket(s: LiveSocket, why: string) {
+ clearTimeout(s.timer);
+ s.timer = undefined;
+ const ws = s.ws;
+ s.ws = undefined;
+ if (ws) {
+ ws.onclose = null;
+ ws.onmessage = null;
+ ws.onerror = null;
+ try {
+ ws.close();
+ } catch {}
+ }
+ for (const w of s.waiters.values()) w.reject(new LiveRenderError(why, "offline"));
+ s.waiters.clear();
+ s.waiting = 0;
+}
+
+function connect(s: LiveSocket) {
+ s.timer = undefined;
+ let ws: WebSocket;
+ try {
+ ws = new WebSocket(`${s.url.replace(/^http/, "ws")}/ws?clientId=${s.clientId}`);
+ } catch {
+ return retry(s);
+ }
+ ws.binaryType = "arraybuffer";
+ s.ws = ws;
+ ws.onopen = () => {
+ s.online = true;
+ s.backoff = 250;
+ setStatus(s, { online: true });
+ };
+ ws.onclose = () => {
+ if (s.ws !== ws) return;
+ s.ws = undefined;
+ s.online = false;
+ for (const w of s.waiters.values()) w.reject(new LiveRenderError("ComfyUI went away. Reconnecting…", "offline"));
+ s.waiters.clear();
+ s.waiting = 0;
+ setStatus(s, { online: false, running: null });
+ retry(s);
+ };
+ ws.onerror = () => {};
+ ws.onmessage = (ev) => {
+ if (typeof ev.data !== "string") return picture(s, new Uint8Array(ev.data as ArrayBuffer));
+ const e = parseComfyText(ev.data);
+ if (!e) return;
+ if (e.type === "status") {
+ const queue = e.queueRemaining ?? 0;
+ const oursRunning = [...s.waiters.values()].some((w) => w.started);
+ const ours = s.waiting + (oursRunning ? 1 : 0);
+ const other = queue > ours;
+ setStatus(s, { queue, running: oursRunning ? "ours" : other ? "other" : null, ...(other && { otherRan: true }) });
+ return;
+ }
+ const w = "promptId" in e && e.promptId ? s.waiters.get(e.promptId) : undefined;
+ if (!w) return;
+ if (e.type === "execution_start") {
+ w.started = true;
+ w.startedAt = Date.now();
+ s.waiting = Math.max(0, s.waiting - 1);
+ setStatus(s, { running: "ours" });
+ w.onEvent({ type: "started" });
+ } else if (e.type === "progress" && e.max <= 8) {
+ w.onEvent({ type: "progress", value: e.value, max: e.max });
+ } else if (e.type === "error") {
+ w.reject(new LiveRenderError(e.message ?? "The render failed", e.nodeType === "LoadImageFuobeLive" ? "missing-input" : "failed"));
+ } else if (e.type === "interrupted") {
+ w.reject(new LiveRenderError("Stopped", "stopped"));
+ }
+ };
+}
+
+function retry(s: LiveSocket) {
+ if (globalThis.__fuobeLiveSocket !== s || s.timer) return;
+ // Jittered backoff, 250 ms to 3 s.
+ const wait = Math.min(3000, s.backoff) * (0.75 + Math.random() * 0.5);
+ s.backoff = Math.min(3000, s.backoff * 2);
+ s.timer = setTimeout(() => connect(s), wait);
+ s.timer.unref?.();
+}
+
+function picture(s: LiveSocket, bytes: Uint8Array) {
+ const p = parseComfyBinary(bytes);
+ if (!p?.promptId) return;
+ const w = s.waiters.get(p.promptId);
+ if (!w || (!p.live && p.node !== LIVE_OUTPUT)) return;
+ w.resolve({ data: p.data.slice(), type: p.type, w: p.width ?? 0, h: p.height ?? 0, ms: Date.now() - (w.startedAt || Date.now()) });
+}
+
+const post = (p: string, body: unknown) => comfyRequest(p, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+
+/** Wait until the install's ComfyUI socket is up again, at most `ms` (true on a linked GPU: no socket). */
+export async function waitOnline(ms: number): Promise<boolean> {
+ if (ownGpu()) return true;
+ return online(liveSocket(), ms);
+}
+
+/** Wait for the socket to be up, at most `ms`. */
+async function online(s: LiveSocket, ms: number): Promise<boolean> {
+ const end = Date.now() + ms;
+ while (!s.online && Date.now() < end) await new Promise((r) => setTimeout(r, 25));
+ return s.online;
+}
+
+async function refusal(res: Response): Promise<LiveRenderError> {
+ const text = await res.text().catch(() => "");
+ let body: { error?: { type?: string; message?: string; extra_info?: { class_type?: string } } } = {};
+ try {
+ body = JSON.parse(text);
+ } catch {}
+ if (body.error?.type === "missing_node_type") return new LiveRenderError("Fuobe's live nodes aren't installed in ComfyUI", "missing-nodes");
+ return new LiveRenderError(body.error?.message ? `ComfyUI refused the render: ${body.error.message}` : `ComfyUI answered ${res.status}`, "failed");
+}
+
+/**
+ * One render: the graph's picture, or a LiveRenderError. `signal` stops it (deleted while queued, interrupted while
+ * running). `onEvent` hears started and progress.
+ */
+export async function renderLive(graph: LiveGraph, signal: AbortSignal, onEvent: (e: LiveEvent) => void): Promise<LivePicture> {
+ if (ownGpu()) return renderPolling(graph, signal, onEvent);
+ const s = liveSocket();
+ if (!(await online(s, 3000))) throw new LiveRenderError("Can't reach ComfyUI. Reconnecting…", "offline");
+ const id = crypto.randomUUID();
+ let settle!: { resolve: (p: LivePicture) => void; reject: (e: Error) => void };
+ const done = new Promise<LivePicture>((resolve, reject) => (settle = { resolve, reject }));
+ // Awaited below; a rejection while the prompt is still being posted must not count as unhandled.
+ done.catch(() => {});
+ const waiter: Waiter = {
+ id,
+ started: false,
+ startedAt: 0,
+ onEvent,
+ resolve: (p) => {
+ s.waiters.delete(id);
+ settle.resolve(p);
+ },
+ reject: (e) => {
+ if (s.waiters.get(id) === waiter && !waiter.started) s.waiting = Math.max(0, s.waiting - 1);
+ s.waiters.delete(id);
+ settle.reject(e);
+ },
+ };
+ s.waiters.set(id, waiter);
+ s.waiting++;
+ const stop = () => {
+ const started = waiter.started;
+ waiter.reject(new LiveRenderError("Stopped", "stopped"));
+ void post("/queue", { delete: [id] }).catch(() => undefined);
+ if (started) void post("/interrupt", { prompt_id: id }).catch(() => undefined);
+ };
+ if (signal.aborted) stop();
+ else signal.addEventListener("abort", stop, { once: true });
+ try {
+ const res = await post("/prompt", { prompt: graph, prompt_id: id, client_id: s.clientId, front: true });
+ if (!res.ok) waiter.reject(await refusal(res));
+ else {
+ res.body?.cancel().catch(() => {});
+ onEvent({ type: "queued", pos: Math.max(0, s.status.queue) });
+ }
+ } catch (e) {
+ waiter.reject(new LiveRenderError((e as Error).message || "Can't reach ComfyUI", "offline"));
+ }
+ try {
+ const p = await done;
+ markWarm();
+ return p;
+ } finally {
+ signal.removeEventListener("abort", stop);
+ // Live renders don't pile up in ComfyUI's history.
+ void post("/history", { delete: [id] }).catch(() => undefined);
+ }
+}
+
+/** An account's linked GPU: no socket; the picture is saved to temp and read back. */
+async function renderPolling(graph: LiveGraph, signal: AbortSignal, onEvent: (e: LiveEvent) => void): Promise<LivePicture> {
+ const id = crypto.randomUUID();
+ const g = structuredClone(graph);
+ if (g[LIVE_OUTPUT]) g[LIVE_OUTPUT].inputs.to = "temp";
+ const t0 = Date.now();
+ const res = await post("/prompt", { prompt: g, prompt_id: id, client_id: "fuobe-live-link", front: true }).catch((e: Error) => {
+ throw new LiveRenderError(e.message, "offline");
+ });
+ if (!res.ok) throw await refusal(res);
+ res.body?.cancel().catch(() => {});
+ onEvent({ type: "queued", pos: 0 });
+ let started = false;
+ try {
+ for (;;) {
+ if (signal.aborted) throw new LiveRenderError("Stopped", "stopped");
+ await new Promise((r) => setTimeout(r, 80));
+ const h: Record<string, HistoryEntry> = await comfyRequest(`/history/${id}`).then((r) => (r.ok ? (r.json() as Promise<Record<string, HistoryEntry>>) : {}));
+ const entry = h[id];
+ if (!entry) {
+ if (!started) {
+ started = true;
+ onEvent({ type: "started" });
+ }
+ continue;
+ }
+ const err = entry.status?.messages?.find(([t]) => t === "execution_error")?.[1] as { exception_message?: string; node_type?: string } | undefined;
+ if (err) throw new LiveRenderError(err.exception_message ?? "The render failed", err.node_type === "LoadImageFuobeLive" ? "missing-input" : "failed");
+ const img = entry.outputs?.[LIVE_OUTPUT]?.images?.[0];
+ if (!img || img.type !== "temp" || !/^[\w.-]+$/.test(img.filename)) throw new LiveRenderError("The render made no picture", "failed");
+ const view = await comfyRequest(`/view?${new URLSearchParams({ filename: img.filename, subfolder: "", type: "temp" })}`);
+ if (!view.ok) throw new LiveRenderError("Couldn't read the picture", "failed");
+ const data = new Uint8Array(await view.arrayBuffer());
+ return { data, type: view.headers.get("content-type") ?? "image/webp", w: 0, h: 0, ms: Date.now() - t0 };
+ }
+ } catch (e) {
+ if (signal.aborted) {
+ void post("/queue", { delete: [id] }).catch(() => undefined);
+ void post("/interrupt", { prompt_id: id }).catch(() => undefined);
+ }
+ throw e;
+ } finally {
+ void post("/history", { delete: [id] }).catch(() => undefined);
+ }
+}
+
+type HistoryEntry = { outputs?: Record<string, { images?: { filename: string; subfolder?: string; type: string }[] }>; status?: { messages?: [string, unknown][] } };
+
+/** Put a picture in ComfyUI's input folder under its content name (skipped when it is already there). */
+export async function stageInput(name: string, data: Uint8Array, type: string, force = false): Promise<void> {
+ if (!force) {
+ const head = await comfyRequest(`/view?${new URLSearchParams({ filename: name, subfolder: "", type: "input" })}`, { method: "HEAD" }).catch(() => undefined);
+ if (head?.ok) return;
+ }
+ const form = new FormData();
+ form.append("image", new Blob([data as BlobPart], { type }), name);
+ form.append("type", "input");
+ form.append("overwrite", "true");
+ const res = await comfyRequest("/upload/image", { method: "POST", body: form }).catch((e: Error) => {
+ throw new LiveRenderError(e.message, "offline");
+ });
+ if (!res.ok) throw new LiveRenderError(`ComfyUI refused the picture (${res.status})`, "failed");
+ res.body?.cancel().catch(() => {});
+}
+
+/** The model files live edit reads, by folder. */
+const FILES: [string, string][] = [
+ ["diffusion_models", LIVE_FILES.unet],
+ ["text_encoders", LIVE_FILES.clip],
+ ["vae", LIVE_FILES.vae],
+ ["loras", LIVE_FILES.lora],
+];
+
+/**
+ * Whether ComfyUI has Fuobe's live nodes (their version, or 0), whether it runs with --highvram or --gpu-only, and the
+ * model files its folders don't list ("folder/file"; a folder that can't be read lists nothing missing).
+ */
+export async function liveFacts(): Promise<{ nodes: number; highvram: boolean | null; missing: string[] }> {
+ const missing = (
+ await Promise.all(
+ FILES.map(async ([folder, file]) => {
+ const list = await comfyRequest(`/models/${folder}`)
+ .then((r) => (r.ok ? (r.json() as Promise<unknown>) : null))
+ .catch(() => null);
+ return Array.isArray(list) && !list.includes(file) ? `${folder}/${file}` : null;
+ }),
+ )
+ ).filter((x): x is string => !!x);
+ const [nodes, stats] = await Promise.all([
+ comfyRequest("/fuobe/live")
+ .then(async (r) => (r.ok ? Number(((await r.json()) as { version?: unknown }).version) || 0 : 0))
+ .catch(() => 0),
+ comfyRequest("/system_stats")
+ .then(async (r) => (r.ok ? ((await r.json()) as { system?: { argv?: string[] } }) : null))
+ .catch(() => null),
+ ]);
+ const argv = stats?.system?.argv;
+ return { nodes, highvram: Array.isArray(argv) ? argv.includes("--highvram") || argv.includes("--gpu-only") : null, missing };
+}
diff --git a/src/server/live/sessions.ts b/src/server/live/sessions.ts
new file mode 100644
index 00000000..e7cf6fa2
--- /dev/null
+++ b/src/server/live/sessions.ts
@@ -0,0 +1,202 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import type { LiveEvent } from "@/lib/live/frames";
+import { buildLiveGraph, type LiveGraphParams } from "@/lib/live/graph";
+import { inputName, pictureExt, PICTURE_TYPES, pngSize } from "@/lib/live/names";
+import { LiveScheduler, type LiveJob, type Outcome, type Slot } from "@/lib/live/scheduler";
+import { onOwnGpu, type OwnGpu } from "../providers/comfyui";
+import { LiveRenderError, renderLive, stageInput, waitOnline, type LivePicture } from "./comfy-live";
+
+/**
+ * Live edit sessions on the server path (one per tab): the scheduler (src/lib/live/scheduler.ts) that keeps one render
+ * of the tab's in ComfyUI at a time, the pictures it staged (by content name, with Fuobe's copy, so a ComfyUI that
+ * restarted and lost its input folder gets them again), and the newest settled renders (full-quality PNG masters of
+ * the text on screen, held for 2 minutes so Keep stores exactly those bytes). Sessions end 10 minutes after their
+ * last use.
+ */
+
+export const SESSION_IDLE_MS = 10 * 60_000;
+const SETTLED_KEPT = 6;
+const SETTLED_MS = 2 * 60_000;
+/** Fuobe's copies of staged pictures kept in memory per session (masters at 2048 are ~10 MB): older ones are re-read. */
+const COPIES_KEPT = 12;
+
+export interface RenderPayload {
+ params: LiveGraphParams;
+ /** Keep: the settled render to store as it is, when it is still held. */
+ fromSettled?: string;
+ onEvent: (e: LiveEvent) => void;
+}
+
+export interface Rendered extends LivePicture {
+ sha256: string;
+ /** Reused a settled render (no new render). */
+ reused?: boolean;
+}
+
+export interface Staged {
+ name: string;
+ w: number;
+ h: number;
+ sha256: string;
+ /** Fuobe's copy, to stage again (a file URL to re-read when the bytes were let go). */
+ data?: Uint8Array;
+ type: string;
+ reread?: () => Promise<Uint8Array>;
+}
+
+export interface LiveSession {
+ id: string;
+ /** "owner" or "acct:<id>". */
+ principal: string;
+ gpu?: OwnGpu;
+ seed: number;
+ lastUsed: number;
+ scheduler: LiveScheduler<RenderPayload, Rendered>;
+ staged: Map<string, Staged>;
+ settled: Map<string, { pic: Rendered; at: number }>;
+}
+
+declare global {
+ var __fuobeLiveEdit: { sessions: Map<string, LiveSession>; sweep?: ReturnType<typeof setInterval> } | undefined;
+}
+
+type Store = { sessions: Map<string, LiveSession>; sweep?: ReturnType<typeof setInterval> };
+
+const store = (): Store => {
+ const s: Store = (globalThis.__fuobeLiveEdit ??= { sessions: new Map<string, LiveSession>() });
+ if (!s.sweep) {
+ s.sweep = setInterval(() => {
+ const now = Date.now();
+ for (const [id, x] of s.sessions) if (now - x.lastUsed > SESSION_IDLE_MS) endSession(id);
+ }, 60_000);
+ s.sweep.unref?.();
+ }
+ return s;
+};
+
+const SESSION_ID = /^lv_[A-Za-z0-9_-]{16}$/;
+
+/** A tab's session, renewed: the same one when the id is its own, else a new one. */
+export function openSession(principal: string, gpu: OwnGpu | undefined, id?: string): LiveSession {
+ const s = store();
+ const had = id && SESSION_ID.test(id) ? s.sessions.get(id) : undefined;
+ if (had && had.principal === principal) {
+ had.lastUsed = Date.now();
+ had.gpu = gpu;
+ return had;
+ }
+ const session: LiveSession = {
+ id: `lv_${nanoid(16)}`,
+ principal,
+ gpu,
+ seed: Math.floor(Math.random() * 2 ** 31),
+ lastUsed: Date.now(),
+ staged: new Map(),
+ settled: new Map(),
+ scheduler: undefined as unknown as LiveSession["scheduler"],
+ };
+ session.scheduler = new LiveScheduler<RenderPayload, Rendered>({ run: (job, signal) => run(session, job, signal) });
+ s.sessions.set(session.id, session);
+ return session;
+}
+
+/** The principal's own session, or null. */
+export function sessionOf(principal: string, id: unknown): LiveSession | null {
+ if (typeof id !== "string" || !SESSION_ID.test(id)) return null;
+ const s = store().sessions.get(id);
+ if (!s || s.principal !== principal) return null;
+ s.lastUsed = Date.now();
+ return s;
+}
+
+export function endSession(id: string): void {
+ const s = store().sessions.get(id);
+ if (!s) return;
+ s.scheduler.close();
+ store().sessions.delete(id);
+}
+
+const within = <T,>(s: LiveSession, fn: () => T): T => (s.gpu ? onOwnGpu(s.gpu, fn) : fn());
+
+/** Stage a picture for this session (by its content name) and remember Fuobe's copy. */
+export async function stage(s: LiveSession, data: Uint8Array, reread?: () => Promise<Uint8Array>): Promise<Staged> {
+ const ext = pictureExt(data);
+ if (!ext) throw new LiveRenderError("Only PNG, JPEG or WebP pictures", "failed");
+ const { name, sha256 } = await inputName(data, ext);
+ const had = s.staged.get(name);
+ if (had) {
+ had.data ??= data;
+ return had;
+ }
+ const size = ext === "png" ? pngSize(data) : await sizeOf(data);
+ const type = PICTURE_TYPES[ext];
+ await within(s, () => stageInput(name, data, type));
+ const st: Staged = { name, w: size?.w ?? 0, h: size?.h ?? 0, sha256, data, type, reread };
+ s.staged.set(name, st);
+ // Keep the newest copies in memory; older ones are read again from their file when needed.
+ const withData = [...s.staged.values()].filter((x) => x.data && x.reread);
+ for (const x of withData.slice(0, Math.max(0, withData.length - COPIES_KEPT))) x.data = undefined;
+ return st;
+}
+
+async function sizeOf(data: Uint8Array): Promise<{ w: number; h: number } | null> {
+ const { imageSize } = await import("@/lib/image-size");
+ const s = imageSize(Buffer.from(data));
+ return s ? { w: s.width, h: s.height } : null;
+}
+
+/** Stage every picture a graph reads again (ComfyUI restarted and lost its input folder). */
+async function restage(s: LiveSession, names: string[]) {
+ for (const n of names) {
+ const st = s.staged.get(n);
+ if (!st) throw new LiveRenderError("A picture of this session is gone. Add it again.", "missing-input");
+ const data = st.data ?? (st.reread ? await st.reread() : undefined);
+ if (!data) throw new LiveRenderError("A picture of this session is gone. Add it again.", "missing-input");
+ await within(s, () => stageInput(n, data, st.type, true));
+ }
+}
+
+async function run(s: LiveSession, job: LiveJob<RenderPayload>, signal: AbortSignal): Promise<Rendered> {
+ const { params, fromSettled, onEvent } = job.payload;
+ if (job.slot === "keep" && fromSettled) {
+ const held = s.settled.get(fromSettled);
+ if (held) return { ...held.pic, reused: true };
+ }
+ const { graph, staged } = buildLiveGraph(params);
+ for (const n of staged) if (!s.staged.has(n)) throw new LiveRenderError("That picture wasn't added to this session", "missing-input");
+ const once = () => within(s, () => renderLive(graph, signal, onEvent));
+ let pic: LivePicture | undefined;
+ for (let tries = 0; !pic; tries++) {
+ try {
+ pic = await once();
+ } catch (e) {
+ if (!(e instanceof LiveRenderError) || signal.aborted || tries >= 2) throw e;
+ if (e.code === "offline") {
+ // ComfyUI restarted or the line dropped: send it again once it is back (the tab hears "reconnecting").
+ onEvent({ type: "reconnecting" });
+ if (!(await within(s, () => waitOnline(8000)))) throw e;
+ } else if (e.code === "missing-input") {
+ // The input folder lost our pictures (a restart): stage them again from Fuobe's copies, then try once more.
+ await restage(s, staged);
+ } else throw e;
+ }
+ }
+ const size = pic.type === "image/png" ? pngSize(pic.data) : null;
+ const out: Rendered = { ...pic, w: pic.w || size?.w || 0, h: pic.h || size?.h || 0, sha256: (await inputName(pic.data, "png")).sha256 };
+ if (job.slot === "settle") {
+ const now = Date.now();
+ for (const [k, v] of s.settled) if (now - v.at > SETTLED_MS) s.settled.delete(k);
+ s.settled.set(job.key, { pic: out, at: now });
+ while (s.settled.size > SETTLED_KEPT) s.settled.delete(s.settled.keys().next().value!);
+ }
+ return out;
+}
+
+/** Submit a render for the session. */
+export function submit(s: LiveSession, job: { seq: number; slot: Slot; key: string; urgent?: boolean; payload: RenderPayload }): Promise<Outcome<Rendered>> {
+ return s.scheduler.submit(job);
+}
+
+/** Fuobe's copy of a staged picture (a kept master's bytes), if held. */
+export const stagedCopy = (s: LiveSession, name: string) => s.staged.get(name);
diff --git a/tests/live-api.test.ts b/tests/live-api.test.ts
new file mode 100644
index 00000000..0c7173b3
--- /dev/null
+++ b/tests/live-api.test.ts
@@ -0,0 +1,245 @@
+/**
+ * Live edit's routes on the server path (a local install), against the ComfyUI stand-in: a session, a staged picture,
+ * live frames over the stream, a settle and a Keep that stores exactly the settled bytes, a stale render taken off
+ * ComfyUI (only ours, never another client's), recovery after ComfyUI restarts and loses its input folder; and who may
+ * use which route (guests, accounts by their GPU, the owner).
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import sharp from "sharp";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+import { FrameReader, type Frame } from "@/lib/live/frames";
+import { CONNECT_GPU_MESSAGE, GUEST_RUN_MESSAGE, LIBRARY_MESSAGE, accountLive, liveRoute } from "@/lib/guest-access";
+import { startLocalComfy, type IndexLike, type LocalComfy } from "./helpers/fake-local-comfy";
+
+// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-live-api-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+globalThis.__fuobeTestDiskFree = 1e13;
+const has = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/requirements.json"), "utf8")) as IndexLike;
+const fake: LocalComfy = await startLocalComfy({ cors: "off", has, stepMsAt512: 10, latencyMs: 5 });
+process.env.COMFYUI_URL = fake.url;
+
+const auth = await import("@/server/auth");
+const { proxy } = await import("@/proxy");
+const uploads = await import("@/app/api/uploads/route");
+const session = await import("@/app/api/live/session/route");
+const inputs = await import("@/app/api/live/inputs/route");
+const render = await import("@/app/api/live/render/route");
+const masters = await import("@/app/api/live/masters/route");
+const save = await import("@/app/api/live/save/route");
+const { resetRates } = await import("@/server/rate");
+
+let owner = "";
+let acct = "";
+let acctCookie = "";
+let picture: Buffer;
+
+beforeAll(async () => {
+ auth.setPassword("install password");
+ owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ acct = auth.createAccount("[email protected]", "long enough password").id;
+ acctCookie = `${auth.SESSION_COOKIE}=${auth.createSession(acct).value}`;
+ const w = 768;
+ const h = 1024;
+ const px = Buffer.alloc(w * h * 3);
+ for (let i = 0; i < px.length; i++) px[i] = (i * 7919) % 251;
+ picture = await sharp(px, { raw: { width: w, height: h, channels: 3 } }).png().toBuffer();
+});
+afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ globalThis.__fuobeLiveSocket?.ws?.close();
+ await fake.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => resetRates());
+
+const req = (url: string, body: unknown, cookie = owner, init: RequestInit = {}) =>
+ new Request(`http://localhost:3000${url}`, { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json" }, body: JSON.stringify(body), ...init });
+
+async function frames(res: Response): Promise<Frame[]> {
+ const r = new FrameReader();
+ const out: Frame[] = [];
+ const reader = res.body!.getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ out.push(...r.push(value));
+ }
+ return out;
+}
+const image = (f: Frame[]) => f.find((x) => x.kind === "image") as Extract<Frame, { kind: "image" }> | undefined;
+const events = (f: Frame[]) => f.filter((x) => x.kind === "event").map((x) => (x as Extract<Frame, { kind: "event" }>).event);
+
+let sid = "";
+let base = "";
+let seq = 0;
+const ask = (o: Record<string, unknown>, init: RequestInit = {}) => render.POST(req("/api/live/render", { sessionId: sid, seq: ++seq, slot: "live", seed: 7, size: 512, keepRes: 1024, base, method: "hybrid", ...o }, owner, init));
+
+describe("the server path", () => {
+ it("opens a session and stages a picture under its content name", async () => {
+ const up = await uploads.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { cookie: owner, host: "localhost:3000", "content-type": "image/png", "x-file-name": "portrait.png", "content-length": String(picture.length) }, body: new Uint8Array(picture) }));
+ expect(up.status).toBe(201);
+ const file = ((await up.json()) as { url: string }).url;
+ const s = await session.POST(req("/api/live/session", {}));
+ expect(s.status).toBe(200);
+ const sj = (await s.json()) as { sessionId: string; mode: string; nodes: { live: boolean } };
+ expect(sj).toMatchObject({ mode: "server", nodes: { live: true } });
+ sid = sj.sessionId;
+ const i = await inputs.POST(req("/api/live/inputs", { sessionId: sid, file }));
+ expect(i.status).toBe(200);
+ const ij = (await i.json()) as { name: string; width: number; height: number };
+ expect(ij).toMatchObject({ width: 768, height: 1024 });
+ expect(ij.name).toMatch(/^fuobe_lv[\w-]{20}\.png$/);
+ base = ij.name;
+ expect(fake.inputs.get(base)?.equals(picture)).toBe(true);
+ // The same bytes again: no second upload.
+ const uploadsBefore = fake.log.filter((l) => l.path === "/upload/image").length;
+ await inputs.POST(req("/api/live/inputs", { sessionId: sid, file }));
+ expect(fake.log.filter((l) => l.path === "/upload/image").length).toBe(uploadsBefore);
+ });
+
+ it("renders a live frame: front of the queue, over the socket, then out of ComfyUI's history", async () => {
+ const posted = fake.log.length;
+ const f = await frames(await ask({ text: "add gold hoop earrings" }));
+ const img = image(f);
+ expect(events(f).map((e) => e.type)).toEqual(expect.arrayContaining(["queued", "started", "progress"]));
+ expect(img?.header).toMatchObject({ slot: "live", type: "image/webp" });
+ expect(Math.max(img!.header.w, img!.header.h)).toBeLessThanOrEqual(640);
+ const prompt = fake.log.slice(posted).find((l) => l.prompt)!;
+ expect(prompt.prompt).toMatchObject({ front: true });
+ expect(String(prompt.prompt!.client_id)).toMatch(/^fuobe-live-/);
+ expect(prompt.prompt!.prompt!["10"].inputs.image).toBe(base);
+ await vi.waitFor(() => expect(fake.log.slice(posted).some((l) => l.path === "/history" && l.method === "POST")).toBe(true));
+ expect(fake.history.has(prompt.prompt!.prompt_id!)).toBe(false);
+ });
+
+ it("keeps exactly the settled picture: the same bytes, no second render", async () => {
+ const settled = image(await frames(await ask({ slot: "settle", text: "add gold hoop earrings" })))!;
+ expect(settled.header.type).toBe("image/png");
+ expect([settled.header.w, settled.header.h]).toEqual([768, 1024]);
+ const posts = fake.posts();
+ const kept = image(await frames(await ask({ slot: "keep", text: "add gold hoop earrings." })))!;
+ expect(fake.posts()).toBe(posts);
+ expect(kept.header.sha256).toBe(settled.header.sha256);
+ expect(Buffer.from(kept.data).equals(Buffer.from(settled.data))).toBe(true);
+ expect(kept.header.url).toMatch(/^\/api\/files\//);
+ expect(kept.header.name).toMatch(/^fuobe_lv/);
+ // The master is staged as the next base.
+ expect(fake.inputs.get(kept.header.name!)?.equals(Buffer.from(kept.data))).toBe(true);
+ // A keep without a settle renders at keep quality.
+ const fresh = image(await frames(await ask({ slot: "keep", text: "a red silk scarf" })))!;
+ expect(fake.posts()).toBe(posts + 1);
+ expect(fresh.header).toMatchObject({ type: "image/png", w: 768, h: 1024 });
+ });
+
+ it("takes a stale render off ComfyUI when the tab lets go of it, and never another client's job", async () => {
+ fake.opts.stepMsAt512 = 400;
+ const theirs = fake.foreign(300);
+ const ctl = new AbortController();
+ const posted = fake.log.length;
+ const res = await ask({ text: "a velvet ribbon" }, { signal: ctl.signal });
+ const reading = frames(res).catch(() => []);
+ await vi.waitFor(() => expect(fake.log.slice(posted).some((l) => l.prompt)).toBe(true));
+ const id = fake.log.slice(posted).find((l) => l.prompt)!.prompt!.prompt_id;
+ const t0 = Date.now();
+ ctl.abort();
+ await vi.waitFor(() => expect(fake.log.slice(posted).some((l) => (l.path === "/queue" || l.path === "/interrupt") && l.method === "POST")).toBe(true));
+ expect(Date.now() - t0).toBeLessThan(500);
+ await reading;
+ const stops = fake.log.slice(posted).filter((l) => (l.path === "/queue" || l.path === "/interrupt") && l.method === "POST");
+ for (const s of stops) expect(JSON.stringify(s.body)).toContain(id!);
+ expect(stops.some((s) => JSON.stringify(s.body).includes(theirs))).toBe(false);
+ fake.opts.stepMsAt512 = 10;
+ await vi.waitFor(() => expect(fake.history.has(theirs)).toBe(true), { timeout: 5000 });
+ });
+
+ it("stages its pictures again after ComfyUI restarts and loses its input folder", async () => {
+ fake.restart({ wipeInputs: true });
+ expect(fake.inputs.size).toBe(0);
+ const f = await frames(await ask({ text: "copper hair" }));
+ expect(image(f)?.header.type).toBe("image/webp");
+ expect(fake.inputs.has(base)).toBe(true);
+ }, 15_000);
+
+ it("refuses pictures the session didn't stage", async () => {
+ const r = await ask({ text: "x", base: "fuobe_lvAAAAAAAAAAAAAAAAAAAA.png" });
+ expect(r.status).toBe(409);
+ });
+});
+
+describe("who may use live edit", () => {
+ const through = (method: string, url: string, cookie?: string) =>
+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { host: "localhost:3000", ...(cookie && { cookie }) } }));
+
+ it("names its routes", () => {
+ expect(liveRoute("/api/live/render")).toBe("render");
+ expect(liveRoute("/api/live/nodes")).toBe("nodes");
+ expect(liveRoute("/api/live/render/x")).toBeNull();
+ expect(accountLive("render", null)).toBe("connect-gpu");
+ expect(accountLive("render", "link")).toBe("pass");
+ expect(accountLive("masters", "computer")).toBe("pass");
+ expect(accountLive("save", "link")).toBe("library");
+ expect(accountLive("nodes", null)).toBe("pass");
+ });
+
+ it("a guest gets the sign-up answer on every route but the node download", async () => {
+ for (const [m, r] of [["POST", "session"], ["POST", "inputs"], ["POST", "render"], ["POST", "cancel"], ["GET", "events"], ["POST", "masters"], ["POST", "save"]] as const) {
+ const res = through(m, `/api/live/${r}`);
+ expect(res.status, r).toBe(401);
+ expect(((await res.json()) as { error: string }).error).toBe(GUEST_RUN_MESSAGE);
+ }
+ expect(through("GET", "/api/live/nodes").headers.get("x-middleware-next")).toBe("1");
+ });
+
+ it("an account: its own GPU only, its own files, no Library", async () => {
+ auth.setAccountGpu(acct, null);
+ for (const r of ["session", "inputs", "render", "cancel", "masters"]) {
+ const res = through("POST", `/api/live/${r}`, acctCookie);
+ expect(res.status, r).toBe(403);
+ expect(((await res.json()) as { error: string }).error).toBe(CONNECT_GPU_MESSAGE);
+ }
+ expect(through("GET", "/api/live/events", acctCookie).status).toBe(403);
+ auth.setAccountGpu(acct, { url: "https://gpu.example.com", token: "t" });
+ for (const r of ["session", "inputs", "render", "cancel", "masters"]) expect(through("POST", `/api/live/${r}`, acctCookie).headers.get("x-middleware-next"), r).toBe("1");
+ const s = through("POST", "/api/live/save", acctCookie);
+ expect(s.status).toBe(403);
+ expect(((await s.json()) as { error: string }).error).toBe(LIBRARY_MESSAGE);
+ auth.setAccountGpu(acct, { mode: "computer" });
+ expect(through("POST", "/api/live/masters", acctCookie).headers.get("x-middleware-next")).toBe("1");
+ // The server path isn't for a computer: the route says so.
+ const sess = await session.POST(req("/api/live/session", {}, acctCookie));
+ expect(sess.status).toBe(409);
+ });
+
+ it("stores a master from a tab on its own computer: the owner's file, or the account's own", async () => {
+ const png = await sharp({ create: { width: 64, height: 48, channels: 3, background: "#884422" } }).png().toBuffer();
+ const post = (cookie: string, body: Buffer) => masters.POST(new Request("http://localhost:3000/api/live/masters", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "image/png" }, body: new Uint8Array(body) }));
+ const o = await post(owner, png);
+ expect(o.status).toBe(201);
+ expect(((await o.json()) as { url: string }).url).toMatch(/^\/api\/files\//);
+ auth.setAccountGpu(acct, { mode: "computer" });
+ const a = await post(acctCookie, png);
+ expect(a.status).toBe(201);
+ const webp = await sharp(png).webp().toBuffer();
+ expect((await post(owner, webp)).status).toBe(415);
+ expect((await post("", png)).status).toBe(401);
+ });
+
+ it("only the owner saves to the Library", async () => {
+ const r = await save.POST(req("/api/live/save", { master: "/api/files/uploads/2026-11-01/x.png", steps: [{ text: "gold earrings", seed: 1 }] }));
+ expect(r.status).toBe(201);
+ const g = (await r.json()) as { feature: string; modelId: string; prompt: string };
+ expect(g).toMatchObject({ feature: "live-edit", modelId: "oss-qwen-image-21-live", prompt: "gold earrings" });
+ auth.setAccountGpu(acct, { url: "https://gpu.example.com" });
+ expect((await save.POST(req("/api/live/save", { master: "/api/files/x.png", steps: [] }, acctCookie))).status).toBe(403);
+ });
+});