The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Your computer's ComfyUI: what the tab and the server share
Adarshca900078f0b7
diff --git a/src/lib/comfy-install.ts b/src/lib/comfy-install.tsindex 8efc2847..73668745 100644--- a/src/lib/comfy-install.ts+++ b/src/lib/comfy-install.ts@@ -64,3 +64,160 @@ export function installScript(wf: Installable): string {});return ["COMFYUI=${COMFYUI:-$HOME/ComfyUI}", ...wf.customNodes.map(nodeInstall), ...accept, ...lines].join("\n");}++// ---------------------------------------------------------------------------+// "Use the ComfyUI on this computer": the one setting ComfyUI needs (its cross-site header naming this site), and the+// way to get it for the install the person has.++/** How the person's ComfyUI was installed, which says where its setting goes. */+export type ComfyInstall = "desktop" | "portable" | "stability-matrix" | "terminal";++export type Platform = "windows" | "mac" | "linux" | "other";++/** A site address the setting may name: no path, no quotes, nothing a start file could run. */+export const SAFE_ORIGIN = /^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;++/** ComfyUI's launch setting for this site (only this site, never every site). */+export function corsFlag(origin: string): string {+ if (!SAFE_ORIGIN.test(origin)) throw new Error("That isn't a site address");+ return `--enable-cors-header ${origin}`;+}++/** The person's computer, from the browser's own words. */+export function platformOf(nav: { userAgentData?: { platform?: string }; userAgent?: string; platform?: string }): Platform {+ const p = `${nav.userAgentData?.platform ?? ""} ${nav.platform ?? ""} ${nav.userAgent ?? ""}`.toLowerCase();+ if (/win/.test(p)) return "windows";+ if (/mac|iphone|ipad/.test(p)) return "mac";+ if (/linux|x11|cros/.test(p)) return "linux";+ return "other";+}++/**+ * Before the setting is on nothing of ComfyUI can be read, so the install is guessed from its port and the computer:+ * 8000 is ComfyUI Desktop, Windows on 8188 is the portable build or Easy-Install, a Mac or Linux on 8188 started it+ * from a terminal. The person can pick another.+ */+export function guessInstall(port: number, platform: Platform): ComfyInstall {+ if (port === 8000) return "desktop";+ return platform === "windows" ? "portable" : "terminal";+}++/** Once it can be read: the embedded Python of the portable builds, else the guess. */+export function installFromStats(stats: { system?: { embedded_python?: boolean } }, port: number, platform: Platform): ComfyInstall {+ if (stats.system?.embedded_python) return "portable";+ return guessInstall(port, platform);+}++export const START_FILE_NAME = "Start ComfyUI for Fuobe.bat";++export interface InstallFix {+ /** What to do, in a sentence. */+ lead: string;+ /** Where the setting is, step by step (Desktop, Stability Matrix). */+ path?: string[];+ /** What to copy: the whole setting, or only the address for a field that takes it. */+ copy: string;+ /** Windows portable or Easy-Install: a start file can do it. */+ startFile?: boolean;+}++/** The fix for each install, in the words the card shows. */+export function fixFor(install: ComfyInstall, origin: string): InstallFix {+ const flag = corsFlag(origin);+ switch (install) {+ case "desktop":+ return {+ lead: "In ComfyUI Desktop, open Settings, then Server-Config, and paste this into Enable CORS header. Restart when it asks.",+ path: ["Settings (the gear, bottom left)", "Server-Config", "Enable CORS header"],+ copy: origin,+ };+ case "stability-matrix":+ return {+ lead: "In Stability Matrix, open ComfyUI's Launch Options and add this to Extra Launch Arguments. Then stop and launch ComfyUI.",+ path: ["Packages", "ComfyUI's ⋮ menu", "Launch Options", "Extra Launch Arguments"],+ copy: flag,+ };+ case "portable":+ return {+ lead: "Download this start file and open it. It restarts ComfyUI with Fuobe allowed in, and keeps your other settings.",+ copy: flag,+ startFile: true,+ };+ default:+ return { lead: "Stop ComfyUI (Ctrl+C in its window) and start it again with this:", copy: `python main.py ${flag}` };+ }+}++/** Single quotes in a PowerShell string. */+const ps = (s: string) => `'${s.replaceAll("'", "''")}'`;++/**+ * "Start ComfyUI for Fuobe.bat", made in the browser for the port and this site: it finds the ComfyUI listening on the+ * port, asks before restarting it, and starts it again the same way with Fuobe's setting added. It leaves a start file+ * with that command next to ComfyUI, and offers to add the setting to the person's own start file (keeping a .bak).+ * It downloads nothing, sends nothing, and needs no admin rights. ComfyUI Desktop and Stability Matrix keep their own+ * settings: for those it says where the setting is instead. Windows line endings.+ */+export function startFile(port: number, origin: string): string {+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("That isn't a port");+ const flag = corsFlag(origin);+ const lines = [+ "@echo off",+ "rem Start ComfyUI for Fuobe",+ `rem Restarts the ComfyUI on port ${port} with one more setting, so ${origin} can use it from your browser:`,+ `rem ${flag}`,+ "rem It asks before it stops anything, keeps your other settings, downloads nothing and sends nothing.",+ "rem To undo it, start ComfyUI the usual way.",+ 'set "FUOBE_BAT=%~f0"',+ `powershell -NoProfile -ExecutionPolicy Bypass -Command "$s=[IO.File]::ReadAllText($env:FUOBE_BAT); iex $s.Substring($s.IndexOf('#FUOBE'+'-PS'))"`,+ "echo.",+ "pause",+ "exit /b",+ "#FUOBE-PS",+ `$Port = ${port}`,+ `$Flag = ${ps(flag)}`,+ "$conn = Get-NetTCPConnection -State Listen -LocalPort $Port -ErrorAction SilentlyContinue | Select-Object -First 1",+ 'if (-not $conn) { Write-Host "Nothing is running on port $Port. Start ComfyUI the usual way, then open this file again."; return }',+ '$proc = Get-CimInstance Win32_Process -Filter "ProcessId = $($conn.OwningProcess)"',+ '$parent = Get-CimInstance Win32_Process -Filter "ProcessId = $($proc.ParentProcessId)" -ErrorAction SilentlyContinue',+ "if ($proc.Name -match '^ComfyUI' -or $parent.Name -match '^ComfyUI') {",+ ` Write-Host "This is ComfyUI Desktop. Open its Settings, then Server-Config, and paste ${origin} into Enable CORS header. Restart when it asks."; return }`,+ "if ($parent.Name -match '^StabilityMatrix') {",+ ' Write-Host "This ComfyUI runs from Stability Matrix. Open ComfyUI\'s Launch Options there, add this to Extra Launch Arguments, then stop and launch it:"; Write-Host " $Flag"; return }',+ "$cmd = $proc.CommandLine",+ "if ($cmd -notmatch 'main\\.py') { Write-Host \"The program on port $Port isn't ComfyUI started from main.py, so this file leaves it alone.\"; return }",+ "$exe = $proc.ExecutablePath",+ "$dir = Split-Path (Split-Path $exe)",+ "if ($exe -match '\\\\Scripts\\\\python(w)?\\.exe$') { $dir = Split-Path $dir }",+ "if (-not (Test-Path (Join-Path $dir 'ComfyUI\\main.py')) -and -not (Test-Path (Join-Path $dir 'main.py'))) {",+ " if ($cmd -match '\"?([A-Za-z]:\\\\[^\"]*?main\\.py)') { $dir = Split-Path $Matches[1] } else { Write-Host \"Couldn't tell which folder ComfyUI runs from. Add this to the end of the line that starts it in your start file, then start it again:\"; Write-Host \" $Flag\"; return } }",+ "$args0 = if ($cmd.StartsWith('\"')) { $cmd.Substring($cmd.IndexOf('\"', 1) + 1) } else { $cmd.Substring(($cmd + ' ').IndexOf(' ')) }",+ "$args0 = ($args0 -replace '\\s--enable-cors-header(\\s+(\"[^\"]*\"|[^\\s-]\\S*))?', '').Trim()",+ '$line = "`"$exe`" $args0 $Flag"',+ 'Write-Host "ComfyUI is running on port $Port from $dir."',+ "$yes = Read-Host 'Restart it now so Fuobe can use it? Anything it is making right now stops. [Y/N]'",+ "if ($yes -notmatch '^[Yy]') { Write-Host 'Nothing was changed.'; return }",+ "$bat = if ($parent.Name -eq 'cmd.exe' -and $parent.CommandLine -match '([^\"]+\\.bat)') { $Matches[1].Trim() } else { $null }",+ "if ($bat -and -not [IO.Path]::IsPathRooted($bat)) { $bat = Join-Path $dir $bat }",+ "if ($parent.Name -eq 'cmd.exe' -and $bat) { Stop-Process -Id $parent.ProcessId -Force -ErrorAction SilentlyContinue }",+ "Stop-Process -Id $proc.ProcessId -Force",+ "for ($i = 0; $i -lt 40 -and (Get-NetTCPConnection -State Listen -LocalPort $Port -ErrorAction SilentlyContinue); $i++) { Start-Sleep -Milliseconds 250 }",+ `$mine = Join-Path $dir ${ps(START_FILE_NAME)}`,+ "Set-Content -Path $mine -Encoding OEM -Value @('@echo off', \"cd /d `\"$dir`\"\", \"title ComfyUI for Fuobe\", $line, 'pause')",+ "Start-Process -FilePath $mine -WorkingDirectory $dir",+ 'Write-Host "Started ComfyUI again with Fuobe\'s setting. Fuobe connects by itself when it is ready."',+ 'Write-Host "Next time, start it with: $mine"',+ "if ($bat -and (Test-Path $bat) -and ([IO.Path]::GetFileName($bat) -ne " + ps(START_FILE_NAME) + ")) {",+ " $text = Get-Content -Raw $bat; $runs = @(Select-String -Path $bat -Pattern 'main\\.py')",+ " if ($runs.Count -eq 1 -and $text -notmatch [regex]::Escape($Flag)) {",+ " $add = Read-Host \"Also add this setting to $([IO.Path]::GetFileName($bat)), so it's always on? [Y/N]\"",+ " if ($add -match '^[Yy]') {",+ " Copy-Item $bat \"$bat.bak\" -Force",+ // Code page 437 maps every byte to a character and back: the rest of their file stays byte for byte.+ " $enc = [Text.Encoding]::GetEncoding(437); $all = [IO.File]::ReadAllLines($bat, $enc); $n = $runs[0].LineNumber - 1",+ " $all[$n] = ($all[$n] -replace '\\s--enable-cors-header(\\s+(\"[^\"]*\"|[^\\s-]\\S*))?', '') + ' ' + $Flag",+ " [IO.File]::WriteAllLines($bat, $all, $enc)",+ ' Write-Host "Added it. The old file is kept as $bat.bak." } } }',+ ];+ return lines.join("\r\n") + "\r\n";+}diff --git a/src/lib/comfy-ws.ts b/src/lib/comfy-ws.tsnew file mode 100644index 00000000..9dc13c2f--- /dev/null+++ b/src/lib/comfy-ws.ts@@ -0,0 +1,98 @@+/**+ * ComfyUI's live socket (/ws?clientId=…), as the Fuobe tab reads it: JSON events (status, execution_start, progress,+ * executing, execution_success / error / interrupted, execution_cached) and binary preview frames. A binary frame is a+ * 4-byte big-endian event type, then: type 1, a 4-byte image type (1 JPEG, 2 PNG) and the image; type 4, a 4-byte+ * metadata length, its JSON (prompt_id, node_id, image_type) and the image. Anything else, or anything malformed, is+ * ignored. Pure.+ */++export type ComfyEvent =+ | { type: "status"; queueRemaining?: number }+ | { type: "execution_start"; promptId: string }+ | { type: "progress"; promptId?: string; value: number; max: number; node?: string }+ | { type: "executing"; promptId?: string; node: string | null }+ | { type: "executed"; promptId?: string; node?: string }+ | { type: "cached"; promptId?: string; nodes: string[] }+ | { type: "success"; promptId: string }+ | { type: "error"; promptId: string; message?: string; nodeType?: string }+ | { type: "interrupted"; promptId: string };++const str = (v: unknown) => (typeof v === "string" ? v : undefined);+const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);++export function parseComfyText(text: string): ComfyEvent | null {+ let msg: { type?: unknown; data?: Record<string, unknown> };+ try {+ msg = JSON.parse(text) as typeof msg;+ } catch {+ return null;+ }+ const d = msg?.data && typeof msg.data === "object" ? msg.data : {};+ const promptId = str(d.prompt_id);+ switch (msg?.type) {+ case "status": {+ const q = num((d.status as { exec_info?: { queue_remaining?: unknown } } | undefined)?.exec_info?.queue_remaining);+ return { type: "status", ...(q !== undefined && { queueRemaining: q }) };+ }+ case "execution_start":+ return promptId ? { type: "execution_start", promptId } : null;+ case "progress": {+ const value = num(d.value);+ const max = num(d.max);+ if (value === undefined || max === undefined) return null;+ return { type: "progress", promptId, value, max, ...(str(d.node) && { node: str(d.node) }) };+ }+ case "executing":+ return { type: "executing", promptId, node: str(d.node) ?? null };+ case "executed":+ return { type: "executed", promptId, node: str(d.node) };+ case "execution_cached":+ return { type: "cached", promptId, nodes: Array.isArray(d.nodes) ? d.nodes.filter((n): n is string => typeof n === "string") : [] };+ case "execution_success":+ return promptId ? { type: "success", promptId } : null;+ case "execution_error":+ return promptId ? { type: "error", promptId, message: str(d.exception_message), nodeType: str(d.node_type) } : null;+ case "execution_interrupted":+ return promptId ? { type: "interrupted", promptId } : null;+ default:+ return null;+ }+}++export interface ComfyPreview {+ /** image/jpeg or image/png. */+ type: string;+ data: Uint8Array;+ /** Set on type-4 frames (a newer ComfyUI): whose preview it is. */+ promptId?: string;+}++/** The longest preview metadata read (a few hundred bytes in practice). */+const MAX_META = 64 * 1024;++export function parseComfyBinary(buf: ArrayBuffer | Uint8Array): ComfyPreview | null {+ const b = buf instanceof Uint8Array ? buf : new Uint8Array(buf);+ if (b.length < 8) return null;+ const view = new DataView(b.buffer, b.byteOffset, b.byteLength);+ const event = view.getUint32(0);+ if (event === 1) {+ const kind = view.getUint32(4);+ const type = kind === 2 ? "image/png" : kind === 1 ? "image/jpeg" : null;+ if (!type || b.length <= 8) return null;+ return { type, data: b.subarray(8) };+ }+ if (event === 4) {+ const len = view.getUint32(4);+ if (len > MAX_META || 8 + len >= b.length) return null;+ let meta: { prompt_id?: unknown; image_type?: unknown };+ try {+ meta = JSON.parse(new TextDecoder().decode(b.subarray(8, 8 + len))) as typeof meta;+ } catch {+ return null;+ }+ const type = meta.image_type === "image/png" ? "image/png" : meta.image_type === "image/jpeg" ? "image/jpeg" : null;+ if (!type) return null;+ return { type, data: b.subarray(8 + len), ...(typeof meta.prompt_id === "string" && { promptId: meta.prompt_id }) };+ }+ return null;+}diff --git a/src/lib/local-comfy.ts b/src/lib/local-comfy.tsnew file mode 100644index 00000000..dc8461b7--- /dev/null+++ b/src/lib/local-comfy.ts@@ -0,0 +1,190 @@+/**+ * The ComfyUI on the person's own computer, as the Fuobe tab reaches it: the only module that builds its URLs. Only+ * 127.0.0.1 (localhost and [::1] when the person typed them), never a network address (that would need another+ * permission and could reach a router), and only the paths a run needs. Pure, so the tab's script and the tests share+ * it. The tab sends no headers of its own (ComfyUI's cross-site setting lets only Content-Type and Authorization+ * through) and never sends cookies.+ */+import { INPUT_NAME, UUID, type HistoryEntryLike, type WantedFile } from "./relay";++/** Where to look, in order: Desktop's port after the usual one, then the ports people move to. */+export const COMFY_PORTS = [8188, 8000, 8189, 8190, 8288, 8001, 7821] as const;++const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);++export class LocalComfyError extends Error {}++/** http://127.0.0.1:<port>, or the host the person typed when it is this computer. */+export function localBase(port: number, host = "127.0.0.1"): string {+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new LocalComfyError("That isn't a port");+ if (!LOCAL_HOSTS.has(host)) throw new LocalComfyError("Only a ComfyUI on this computer");+ return `http://${host}:${port}`;+}++/** A port typed by the person ("8188", "localhost:8188", "http://127.0.0.1:8188/"): the port, or null. */+export function typedPort(input: string): { port: number; host: string } | null {+ const s = input.trim().replace(/\/+$/, "");+ if (/^\d{2,5}$/.test(s)) return Number(s) <= 65535 ? { port: Number(s), host: "127.0.0.1" } : null;+ try {+ const u = new URL(/^[a-z]+:\/\//i.test(s) ? s : `http://${s}`);+ const host = u.hostname === "::1" ? "[::1]" : u.hostname;+ if (u.protocol !== "http:" || !LOCAL_HOSTS.has(host) || u.pathname.replace(/\/+$/, "") !== "") return null;+ return { port: Number(u.port || 80), host };+ } catch {+ return null;+ }+}++const MODEL_FOLDER = /^[A-Za-z0-9_.-]{1,64}$/;+const NODE_CLASS = /^[A-Za-z0-9_ .+()|-]{1,128}$/;++/**+ * A path the tab may GET on the local ComfyUI, with its query: the facts (/system_stats), what it has (/object_info,+ * /models, /embeddings), the queue, one prompt's history (by its UUID) or the last passes, one job, a result file+ * (/view of output or temp) and the socket. Anything else throws.+ */+export function readPath(path: string): string {+ const [p, query = ""] = path.split("?");+ const q = new URLSearchParams(query);+ const noQuery = () => {+ if (query) throw new LocalComfyError(`No query on ${p}`);+ return path;+ };+ if (["/system_stats", "/api/system_stats", "/object_info", "/models", "/embeddings", "/queue", "/api/jobs"].includes(p)) return noQuery();+ if (p.startsWith("/object_info/") && NODE_CLASS.test(decodeURIComponent(p.slice(13)))) return noQuery();+ if (p.startsWith("/models/") && MODEL_FOLDER.test(p.slice(8))) return noQuery();+ if (p.startsWith("/history/") && UUID.test(p.slice(9))) return noQuery();+ if (p === "/history" && [...q.keys()].join() === "max_items" && /^\d{1,3}$/.test(q.get("max_items")!)) return path;+ if (p.startsWith("/api/jobs/") && UUID.test(p.slice(10))) return noQuery();+ if (p === "/view") {+ const keys = [...q.keys()].sort().join();+ const type = q.get("type");+ const name = q.get("filename") ?? "";+ const sub = q.get("subfolder") ?? "";+ if (keys !== "filename,subfolder,type" || (type !== "output" && type !== "temp")) throw new LocalComfyError("Only results");+ if (!name || /[\\/]|^\.\.?$/.test(name) || sub.split(/[\\/]/).some((s) => s === "..")) throw new LocalComfyError("Only results");+ return path;+ }+ if (p === "/ws" && [...q.keys()].join() === "clientId" && /^[A-Za-z0-9_-]{8,64}$/.test(q.get("clientId")!)) return path;+ throw new LocalComfyError(`Fuobe doesn't read ${p} on your ComfyUI`);+}++/** The /view path of a wanted file. */+export const viewPath = (f: Pick<WantedFile, "filename" | "subfolder" | "type">) => `/view?${new URLSearchParams({ filename: f.filename, subfolder: f.subfolder, type: f.type })}`;++/** A POST the tab may send: an input under a name the server chose, the prompt, and taking its own prompts off. */+export function writePath(path: string, body: unknown, own: { promptIds: string[]; names?: string[] }): string {+ const ownId = (id: unknown) => typeof id === "string" && UUID.test(id) && own.promptIds.includes(id);+ if (path === "/upload/image") {+ const b = body as { name?: unknown; type?: unknown; overwrite?: unknown };+ if (typeof b?.name !== "string" || !INPUT_NAME.test(b.name) || !(own.names ?? []).includes(b.name) || b.type !== "input" || b.overwrite !== "true") {+ throw new LocalComfyError("Only the run's own inputs");+ }+ return path;+ }+ if (path === "/prompt") {+ const b = body as { prompt_id?: unknown; prompt?: unknown };+ if (!ownId(b?.prompt_id) || !b.prompt || typeof b.prompt !== "object") throw new LocalComfyError("Only the run's own prompt");+ return path;+ }+ if (path === "/queue") {+ const del = (body as { delete?: unknown })?.delete;+ if (!Array.isArray(del) || !del.length || !del.every(ownId) || Object.keys(body as object).length !== 1) throw new LocalComfyError("Only the run's own prompts");+ return path;+ }+ if (path === "/interrupt") {+ if (!ownId((body as { prompt_id?: unknown })?.prompt_id)) throw new LocalComfyError("Only the run's own prompt");+ return path;+ }+ const cancel = /^\/api\/jobs\/([^/]+)\/cancel$/.exec(path);+ if (cancel && ownId(cancel[1])) return path;+ throw new LocalComfyError(`Fuobe doesn't send ${path} to your ComfyUI`);+}++/** Loader classes and the input that names a file in ComfyUI's input folder. */+const FILE_LOADERS: Record<string, string[]> = {+ LoadImage: ["image"],+ LoadImageMask: ["image"],+ LoadImageOutput: ["image"],+ LoadVideo: ["file"],+ LoadAudio: ["audio"],+ VHS_LoadVideo: ["video"],+ VHS_LoadVideoPath: ["video"],+ VHS_LoadAudio: ["audio_file"],+ VHS_LoadAudioUpload: ["audio"],+ VHS_LoadImages: ["directory"],+ VHS_LoadImagesPath: ["directory"],+};++/**+ * The tab's own check of a graph before it goes to ComfyUI (in case the server were ever wrong or taken over): every+ * loader names one of the files this task uploads, or a value from another node. A graph that would read anything else+ * from the person's folders is refused. Returns the problem, or null.+ */+export function graphProblem(graph: Record<string, { class_type?: unknown; inputs?: Record<string, unknown> }>, staged: string[]): string | null {+ if (!graph || typeof graph !== "object") return "No graph";+ for (const [id, node] of Object.entries(graph)) {+ const cls = typeof node?.class_type === "string" ? node.class_type : "";+ const keys = FILE_LOADERS[cls] ?? (/^(Load|VHS_Load)/.test(cls) ? Object.keys(node?.inputs ?? {}).filter((k) => /image|video|audio|file|path|directory/i.test(k)) : []);+ for (const k of keys) {+ const v = node?.inputs?.[k];+ if (v === undefined || Array.isArray(v)) continue;+ if (typeof v !== "string" || !staged.includes(v.replace(/ \[input\]$/, ""))) return `Node ${id} (${cls}) reads ${typeof v === "string" ? `“${v.slice(0, 80)}”` : "a value"}, which this run didn't send`;+ }+ }+ return null;+}++type FileRef = { filename: string; subfolder?: string; type: string };+const isFileRef = (f: unknown): f is FileRef => !!f && typeof f === "object" && typeof (f as FileRef).filename === "string" && typeof (f as FileRef).type === "string";++/** Every file the entries list (a run's own history, and a meta-batch's passes). */+export function filesIn(entries: HistoryEntryLike[]): FileRef[] {+ const out: FileRef[] = [];+ for (const e of entries) for (const ui of Object.values(e?.outputs ?? {})) for (const v of Object.values(ui ?? {})) if (Array.isArray(v)) for (const f of v) if (isFileRef(f)) out.push(f);+ return out;+}++/** The tab downloads a file only when its own prompt's entries list it (so a server answer can't reach any other file). */+export function mayDownload(f: Pick<WantedFile, "filename" | "subfolder" | "type">, entries: HistoryEntryLike[]): boolean {+ return filesIn(entries).some((x) => x.filename === f.filename && (x.subfolder ?? "") === f.subfolder && x.type === f.type);+}++/** What a look on one port found. */+export type PortLook = { port: number; host?: string; state: "found"; stats: SystemStats } | { port: number; host?: string; state: "unreadable" } | { port: number; host?: string; state: "none" };++export interface SystemStats {+ system?: { os?: string; comfyui_version?: string; ram_total?: number; embedded_python?: boolean; argv?: string[]; python_version?: string };+ devices?: { name?: string; type?: string; vram_total?: number }[];+}++/**+ * The ComfyUI to use from several looks: one Fuobe can read before one it can't, the remembered port first, then the+ * lowest. "none" when nothing answered.+ */+export function pickLook(looks: PortLook[], remembered?: number): PortLook | { state: "none" } {+ const rank = (l: PortLook) => (l.state === "found" ? 0 : l.state === "unreadable" ? 1 : 2);+ const sorted = looks.filter((l) => l.state !== "none").sort((a, b) => rank(a) - rank(b) || Number(b.port === remembered) - Number(a.port === remembered) || a.port - b.port);+ return sorted[0] ?? { state: "none" };+}++/** The ports to look at, the remembered one first. */+export const portsToLook = (remembered?: number): number[] => [...new Set([...(remembered ? [remembered] : []), ...COMFY_PORTS])];++/** Facts for the server from /system_stats: never the command line, only whether its cross-site setting names this site. */+export function statsFacts(s: SystemStats, origin: string) {+ const argv = s.system?.argv ?? [];+ const at = argv.indexOf("--enable-cors-header");+ const value = at >= 0 ? argv[at + 1] : undefined;+ const cors = at < 0 ? undefined : !value || value.startsWith("--") || value === "*" ? ("any" as const) : value.replace(/\/+$/, "") === origin ? ("exact" as const) : ("other" as const);+ const dev = s.devices?.[0];+ return {+ ...(dev?.name && { device: dev.name.slice(0, 120) }),+ ...(typeof dev?.vram_total === "number" && { vramBytes: dev.vram_total }),+ ...(typeof s.system?.ram_total === "number" && { ramBytes: s.system.ram_total }),+ ...(s.system?.comfyui_version && { version: String(s.system.comfyui_version).slice(0, 40) }),+ ...(s.system?.os && { os: String(s.system.os).slice(0, 40) }),+ ...(typeof s.system?.embedded_python === "boolean" && { portable: s.system.embedded_python }),+ ...(cors && { cors }),+ };+}diff --git a/src/lib/relay.ts b/src/lib/relay.tsnew file mode 100644index 00000000..36cf18e3--- /dev/null+++ b/src/lib/relay.ts@@ -0,0 +1,235 @@+/**+ * "Use the ComfyUI on this computer": what the server and the person's own Fuobe tab say to each other. The server plans+ * every run as it always has; each ComfyUI job of a run on someone's computer becomes a task the server stores (the+ * graph exactly as it built it, the input files under names it chose, a prompt id it minted). One tab at a time takes+ * the tasks of that person (src/lib/computer-runner.ts), sends them to the ComfyUI on 127.0.0.1, follows them, and+ * hands back what ComfyUI said and the files the server then asks for. The tab decides nothing about the result.+ * Pure (no I/O): the server's checks and the tab's script share it. None of these words reach the UI.+ */++/** Where a task is. */+export type RelayState = "waiting" | "sending" | "queued" | "running" | "collecting" | "done" | "failed" | "canceled";++export const ACTIVE_STATES: readonly RelayState[] = ["waiting", "sending", "queued", "running", "collecting"];+/** States a computer is working on (it took the task). */+export const SENT_STATES: readonly RelayState[] = ["sending", "queued", "running", "collecting"];++export const isActive = (s: string): s is RelayState => (ACTIVE_STATES as readonly string[]).includes(s);++/** A ComfyUI /history entry, as the tab reports it. */+export interface HistoryEntryLike {+ prompt?: unknown[];+ status?: { status_str?: string; completed?: boolean; messages?: [string, Record<string, unknown>][] };+ outputs?: Record<string, Record<string, unknown>>;+}++/** Why the tab gave up on a task by itself (the server says it in plain words). */+export const TAB_FAILURES = ["input-too-big", "input-changed", "unsafe-graph", "output-missing", "comfy-error", "save-failed"] as const;+export type TabFailure = (typeof TAB_FAILURES)[number];++/** What the tab reports about one task. */+export type ReportEvent =+ /** ComfyUI took the prompt (`promptId`: the id it answered, the server's own unless an older ComfyUI minted one). */+ | { event: "sent"; promptId: string; number?: number }+ /** ComfyUI's /prompt refused it (its answer, as it was). */+ | { event: "refused"; status: number; body: unknown }+ /** Waiting in ComfyUI's queue: how many prompts are before it. */+ | { event: "queued"; position: number }+ /** Running: the sampler's steps, and the node. */+ | { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number }+ /** Finished: its /history entry. */+ | { event: "finished"; entry: HistoryEntryLike }+ /** A meta-batch job (VHS re-queues it pass by pass): whether a pass is still queued, and the passes' entries so far. */+ | { event: "passes"; running: boolean; entries: HistoryEntryLike[] }+ /** ComfyUI has no trace of it (restarted): the server sends it again once. */+ | { event: "gone" }+ /** The tab can't reach ComfyUI. */+ | { event: "comfy-down" }+ /** A stop the server asked for is done. */+ | { event: "stopped" }+ /** The tab gave up for one of its own reasons. */+ | { event: "failed"; reason: TabFailure; status?: number };++export type ReportEventName = ReportEvent["event"];++/** Which state each report is taken in. Anything else is refused (409). */+const ALLOWED: Record<ReportEventName, readonly RelayState[]> = {+ sent: ["sending"],+ refused: ["sending"],+ queued: ["queued", "running"],+ running: ["queued", "running"],+ finished: ["queued", "running"],+ passes: ["queued", "running"],+ gone: ["sending", "queued", "running"],+ "comfy-down": ["sending", "queued", "running", "collecting"],+ stopped: ["sending", "queued", "running", "collecting", "done", "failed", "canceled"],+ failed: ["sending", "queued", "running", "collecting"],+};++export function reportAllowed(event: ReportEventName, state: RelayState): boolean {+ return ALLOWED[event]?.includes(state) ?? false;+}++/** A file the server wants from ComfyUI's output folder (n: its place in the task's list). */+export interface WantedFile {+ n: number;+ filename: string;+ subfolder: string;+ type: "output" | "temp";+ kind: "image" | "video" | "audio" | "text" | "model3d" | "frame";+ maxBytes: number;+}++/** An input the tab uploads to ComfyUI under exactly this name. */+export interface TaskInput {+ n: number;+ name: string;+ size: number;+ sha256: string;+ contentType: string;+}++/** What a claim hands the tab. */+export interface ClaimedTask {+ id: string;+ /** The claim's token: every call about this task carries it. */+ lease: string;+ graph: Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ promptId: string;+ /** Ask ComfyUI for live previews of this prompt. */+ preview: boolean;+ /** VHS meta-batch: the filename prefix its passes share. */+ prefix?: string;+ metaBatch?: boolean;+ inputs: TaskInput[];+ /** A task this computer started before (a reload): where it was. */+ resume?: "sending" | "queued" | "running" | "collecting";+ /** Collecting: the files still to upload, and how far each got. */+ wanted?: WantedFile[];+ received?: { n: number; bytes: number; done: boolean }[];+}++/** The tab's facts about its ComfyUI (never its command line: that holds paths and user names). */+export interface ComputerFacts {+ device?: string;+ vramBytes?: number;+ ramBytes?: number;+ version?: string;+ os?: string;+ /** Python embedded in the install: Windows portable or Easy-Install. */+ portable?: boolean;+ /** Its --enable-cors-header: this site exactly, every site ("any"), or something else. */+ cors?: "exact" | "any" | "other";+ /** Its LoRA files (sent now and then, not on every beat). */+ loras?: string[];+}++export const FACT_LIMITS = { loras: 20_000, loraName: 256, text: 120 };++/** The beat's answer. */+export interface BeatAnswer {+ /** This computer runs the person's waiting tasks. */+ runner: boolean;+ /** Another computer does (it beat in the last minute). */+ heldElsewhere: boolean;+ /** Tasks waiting for a computer. */+ waiting: number;+ /** Prompts to take off this computer's ComfyUI. */+ stops: { task: string; promptId: string; prefix?: string }[];+}++/** Task timings (DESIGN 5.5): the runner lease, how often the tab beats, when a computer counts as gone. */+export const RELAY_TIMES = {+ leaseMs: 60_000,+ beatMs: 10_000,+ busyBeatMs: 5_000,+ /** A computer that beat this recently is online. */+ onlineMs: 30_000,+ /** A computer silent this long gives up the tasks it took. */+ silentMs: 30 * 60_000,+ /** ComfyUI not answering this long fails the task. */+ comfyDownMs: 30 * 60_000,+ /** Ended tasks (and their files) are kept this long. */+ keepMs: 24 * 60 * 60_000,+ /** An input staged for a task that never came. */+ stagedMs: 60 * 60_000,+};++/** The largest part of an output the tab sends at once, and the largest report. */+export const RELAY_LIMITS = { partBytes: 16 * 2 ** 20, reportBytes: 8 * 2 ** 20, inputReads: 6 };++/** A ComfyUI prompt id the server mints, and what the tab may name in a URL. */+export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;++/** A task id (nanoid 16) and a lease (32 random bytes, hex). */+export const TASK_ID = /^[A-Za-z0-9_-]{16}$/;+export const LEASE = /^[0-9a-f]{64}$/;+/** A browser's device id: a routing label, not a secret. */+export const DEVICE_ID = /^[A-Za-z0-9_-]{8,64}$/;++/** The name an input gets in ComfyUI's input folder: chosen by the server, unguessable. */+export const INPUT_NAME = /^fuobe_[A-Za-z0-9_-]{8,24}\.[a-z0-9]{1,5}$/;++// ---------------------------------------------------------------------------+// The words a run's tile shows++export type MadeKind = "image" | "video" | "audio" | string;++const MADE: Record<string, string> = { image: "picture", video: "clip", audio: "sound", text: "text", model3d: "3D model" };+const SENT: Record<string, string> = { image: "photo", video: "clip", audio: "sound" };++/** "Sending your photo to ComfyUI" (several kinds: "files"). */+export function sendingWords(inputKinds: string[]): string {+ const kinds = [...new Set(inputKinds.map((k) => k.split("/")[0]))];+ if (!kinds.length) return "Starting on your computer";+ const one = kinds.length === 1 && inputKinds.length === 1 ? SENT[kinds[0]] : undefined;+ const many = kinds.length === 1 && SENT[kinds[0]] ? `${SENT[kinds[0]]}s` : "files";+ return `Sending your ${one ?? many} to ComfyUI`;+}++/** "In ComfyUI's queue · 2 ahead", or "Next in ComfyUI's queue". */+export function queueWords(position: number | undefined): string {+ if (position === undefined || position < 0) return "In ComfyUI's queue";+ return position === 0 ? "Next in ComfyUI's queue" : `In ComfyUI's queue · ${position} ahead`;+}++/** "Making your picture · step 12 of 30". */+export function makingWords(kind: MadeKind, value?: number, max?: number): string {+ const noun = MADE[kind] ?? "result";+ return max && max > 1 && value !== undefined ? `Making your ${noun} · step ${Math.min(value, max)} of ${max}` : `Making your ${noun}`;+}++export const savingWords = (fraction: number | undefined) =>+ fraction !== undefined && fraction > 0 ? `Saving to Fuobe · ${Math.min(100, Math.floor(fraction * 100))}%` : "Saving to Fuobe";++export const RELAY_WORDS = {+ noComputer: "Open Fuobe on the computer with your ComfyUI to run this",+ starting: "Starting on your computer",+ waitedTooLong: (minutes: number) => `Fuobe couldn't reach your computer for ${minutes} minutes. Open Fuobe there, then press Retry.`,+ computerSilent: "Your computer stopped answering. If ComfyUI finished, open Fuobe there and press Retry.",+ comfyDown: "ComfyUI isn't answering. Start it again, and Fuobe goes on by itself.",+ comfyDownTooLong: "ComfyUI didn't come back within 30 minutes. Start it, then press Retry.",+ resent: "ComfyUI restarted, so Fuobe sent it again",+ lost: "ComfyUI restarted and lost this run. Press Retry.",+ outOfMemory: "Your GPU ran out of memory. Try a smaller size or a shorter clip.",+ tooBig: "Your ComfyUI made a file over 1 GB. Try a shorter clip or a lower size.",+ stopped: "Stopped",+} as const;++/** The words for a tab's own failure. */+export function tabFailureWords(reason: TabFailure, status?: number): string {+ switch (reason) {+ case "input-too-big":+ return "Your ComfyUI refused a file as too large. Start ComfyUI with a higher --max-upload-size, or use a smaller file.";+ case "input-changed":+ return "A file for this run didn't arrive whole. Press Retry.";+ case "unsafe-graph":+ return "Your browser stopped this run: it asked ComfyUI for files Fuobe didn't send. Press Retry.";+ case "output-missing":+ return "Your ComfyUI no longer has this run's result. Press Retry.";+ case "save-failed":+ return "Saving the result to Fuobe failed three times. Check your connection, then press Retry.";+ default:+ return `Your ComfyUI answered HTTP ${Number.isInteger(status) ? status : "?"}. Check that it's running, then press Retry.`;+ }+}diff --git a/tests/computer-pure.test.ts b/tests/computer-pure.test.tsnew file mode 100644index 00000000..3573b899--- /dev/null+++ b/tests/computer-pure.test.ts@@ -0,0 +1,231 @@+import { execFileSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { corsFlag, fixFor, guessInstall, installFromStats, platformOf, startFile, START_FILE_NAME } from "@/lib/comfy-install";+import { parseComfyBinary, parseComfyText } from "@/lib/comfy-ws";+import { COMFY_PORTS, graphProblem, localBase, mayDownload, pickLook, portsToLook, readPath, statsFacts, typedPort, viewPath, writePath } from "@/lib/local-comfy";+import { makingWords, queueWords, reportAllowed, savingWords, sendingWords, tabFailureWords, type RelayState } from "@/lib/relay";++const ID = "0f8fad5b-d9cb-469f-a165-70867728950e";+const OTHER = "7c9e6679-7425-40de-944b-e07fc1f90ae7";++describe("the local ComfyUI's addresses", () => {+ it("is 127.0.0.1 unless the person typed localhost or [::1], and never a network address", () => {+ expect(localBase(8188)).toBe("http://127.0.0.1:8188");+ expect(localBase(8000, "localhost")).toBe("http://localhost:8000");+ expect(() => localBase(8188, "192.168.1.5")).toThrow();+ expect(() => localBase(8188, "evil.example")).toThrow();+ expect(() => localBase(70000)).toThrow();+ expect(typedPort("8189")).toEqual({ port: 8189, host: "127.0.0.1" });+ expect(typedPort("localhost:8000")).toEqual({ port: 8000, host: "localhost" });+ expect(typedPort("http://127.0.0.1:7821/")).toEqual({ port: 7821, host: "127.0.0.1" });+ expect(typedPort("http://192.168.1.5:8188")).toBeNull();+ expect(typedPort("https://tunnel.example")).toBeNull();+ expect(typedPort("127.0.0.1:8188/api")).toBeNull();+ expect(typedPort("99999")).toBeNull();+ });++ it("looks at the remembered port first, then the usual ones (8188, then Desktop's 8000)", () => {+ expect(COMFY_PORTS.slice(0, 2)).toEqual([8188, 8000]);+ expect(portsToLook(8190)[0]).toBe(8190);+ expect(new Set(portsToLook(8188)).size).toBe(portsToLook(8188).length);+ });++ it("reads only what a run needs", () => {+ for (const ok of ["/system_stats", "/object_info", "/object_info/KSampler", "/models/loras", "/queue", `/history/${ID}`, "/history?max_items=64", `/api/jobs/${ID}`, "/ws?clientId=fuobe-abcdefgh"]) {+ expect(readPath(ok), ok).toBe(ok);+ }+ expect(readPath(viewPath({ filename: "fuobe_00001_.png", subfolder: "fuobe", type: "output" }))).toMatch(/^\/view\?/);+ for (const bad of [+ "/userdata/x",+ "/internal/logs",+ "/manager/reboot",+ "/history",+ "/history/../x",+ "/history/not-a-uuid",+ "/view?filename=x.png&type=input&subfolder=",+ "/view?filename=../x.png&type=output&subfolder=",+ "/view?filename=x.png&type=output&subfolder=../../secrets",+ "/view?filename=x.png&type=output",+ "/models/../../etc",+ "/system_stats?x=1",+ ]) {+ expect(() => readPath(bad), bad).toThrow();+ }+ });++ it("sends only the run's own inputs, prompt and stops", () => {+ const own = { promptIds: [ID], names: ["fuobe_abcdefgh12.png"] };+ expect(writePath("/upload/image", { name: "fuobe_abcdefgh12.png", type: "input", overwrite: "true" }, own)).toBe("/upload/image");+ expect(() => writePath("/upload/image", { name: "fuobe_zzzzzzzz12.png", type: "input", overwrite: "true" }, own)).toThrow();+ expect(() => writePath("/upload/image", { name: "../x.png", type: "input", overwrite: "true" }, own)).toThrow();+ expect(() => writePath("/upload/image", { name: "fuobe_abcdefgh12.png", type: "output", overwrite: "true" }, own)).toThrow();+ expect(writePath("/prompt", { prompt_id: ID, prompt: {} }, own)).toBe("/prompt");+ expect(() => writePath("/prompt", { prompt_id: OTHER, prompt: {} }, own)).toThrow();+ expect(writePath("/queue", { delete: [ID] }, own)).toBe("/queue");+ expect(() => writePath("/queue", { clear: true }, own)).toThrow();+ expect(() => writePath("/queue", { delete: [OTHER] }, own)).toThrow();+ expect(writePath("/interrupt", { prompt_id: ID }, own)).toBe("/interrupt");+ expect(() => writePath("/interrupt", {}, own)).toThrow();+ expect(writePath(`/api/jobs/${ID}/cancel`, {}, own)).toBe(`/api/jobs/${ID}/cancel`);+ expect(() => writePath(`/api/jobs/${OTHER}/cancel`, {}, own)).toThrow();+ for (const p of ["/free", "/customnode/install", "/manager/queue/install", "/upload/mask", "/settings/x"]) expect(() => writePath(p, {}, own), p).toThrow();+ });++ it("refuses a graph whose loaders read files the run didn't send", () => {+ const staged = ["fuobe_abcdefgh12.png"];+ expect(graphProblem({ "1": { class_type: "LoadImage", inputs: { image: "fuobe_abcdefgh12.png" } }, "2": { class_type: "KSampler", inputs: { seed: 1 } } }, staged)).toBeNull();+ expect(graphProblem({ "1": { class_type: "LoadImage", inputs: { image: "fuobe_abcdefgh12.png [input]" } } }, staged)).toBeNull();+ expect(graphProblem({ "1": { class_type: "VHS_LoadVideo", inputs: { video: ["5", 0] } } }, staged)).toBeNull();+ expect(graphProblem({ "1": { class_type: "LoadImage", inputs: { image: "private_photo.png" } } }, staged)).toMatch(/didn't send/);+ expect(graphProblem({ "1": { class_type: "VHS_LoadImagesPath", inputs: { directory: "C:/Users/me/Pictures" } } }, staged)).toMatch(/didn't send/);+ expect(graphProblem({ "1": { class_type: "LoadAudio", inputs: { audio: "secret.wav" } } }, staged)).toMatch(/didn't send/);+ expect(graphProblem({ "1": { class_type: "LoadSomethingNew", inputs: { file_path: "x.bin" } } }, staged)).toMatch(/didn't send/);+ });++ it("downloads only files its own prompt's entries list", () => {+ const entry = { outputs: { "9": { images: [{ filename: "fuobe_00001_.png", subfolder: "fuobe", type: "output" }] } } };+ expect(mayDownload({ filename: "fuobe_00001_.png", subfolder: "fuobe", type: "output" }, [entry])).toBe(true);+ expect(mayDownload({ filename: "someone_else.png", subfolder: "", type: "output" }, [entry])).toBe(false);+ expect(mayDownload({ filename: "fuobe_00001_.png", subfolder: "", type: "output" }, [entry])).toBe(false);+ });++ it("picks the ComfyUI it can read, then the remembered port, then the lowest", () => {+ const stats = { system: {} };+ expect(pickLook([{ port: 8000, state: "unreadable" }, { port: 8188, state: "found", stats }])).toMatchObject({ port: 8188, state: "found" });+ expect(pickLook([{ port: 8188, state: "unreadable" }, { port: 8000, state: "unreadable" }], 8000)).toMatchObject({ port: 8000 });+ expect(pickLook([{ port: 8189, state: "unreadable" }, { port: 8188, state: "unreadable" }])).toMatchObject({ port: 8188 });+ expect(pickLook([{ port: 8188, state: "none" }])).toEqual({ state: "none" });+ });++ it("tells the server about the machine, never its command line", () => {+ const f = statsFacts(+ {+ system: { os: "nt", comfyui_version: "0.42.0", ram_total: 64 * 2 ** 30, embedded_python: true, argv: ["main.py", "--base-directory", "C:\\Users\\Jo\\secret", "--enable-cors-header", "https://fuobe.com"] },+ devices: [{ name: "cuda:0 NVIDIA GeForce RTX 5090 : cudaMallocAsync", vram_total: 32 * 2 ** 30 }],+ },+ "https://fuobe.com",+ );+ expect(f).toEqual({ device: "cuda:0 NVIDIA GeForce RTX 5090 : cudaMallocAsync", vramBytes: 32 * 2 ** 30, ramBytes: 64 * 2 ** 30, version: "0.42.0", os: "nt", portable: true, cors: "exact" });+ expect(JSON.stringify(f)).not.toMatch(/secret|Users/);+ expect(statsFacts({ system: { argv: ["main.py", "--enable-cors-header"] } }, "https://fuobe.com").cors).toBe("any");+ expect(statsFacts({ system: { argv: ["main.py", "--enable-cors-header", "*"] } }, "https://fuobe.com").cors).toBe("any");+ expect(statsFacts({ system: { argv: ["main.py", "--enable-cors-header", "https://other.example"] } }, "https://fuobe.com").cors).toBe("other");+ });+});++describe("ComfyUI's live socket", () => {+ it("reads progress and the run's end", () => {+ expect(parseComfyText(JSON.stringify({ type: "progress", data: { value: 12, max: 30, prompt_id: ID, node: "3" } }))).toEqual({ type: "progress", value: 12, max: 30, promptId: ID, node: "3" });+ expect(parseComfyText(JSON.stringify({ type: "executing", data: { node: null, prompt_id: ID } }))).toEqual({ type: "executing", node: null, promptId: ID });+ expect(parseComfyText(JSON.stringify({ type: "execution_success", data: { prompt_id: ID } }))).toEqual({ type: "success", promptId: ID });+ expect(parseComfyText(JSON.stringify({ type: "execution_error", data: { prompt_id: ID, exception_message: "CUDA out of memory", node_type: "KSampler" } }))).toMatchObject({ type: "error", message: "CUDA out of memory" });+ expect(parseComfyText(JSON.stringify({ type: "status", data: { status: { exec_info: { queue_remaining: 2 } } } }))).toEqual({ type: "status", queueRemaining: 2 });+ expect(parseComfyText("not json")).toBeNull();+ expect(parseComfyText(JSON.stringify({ type: "progress", data: { value: "x" } }))).toBeNull();+ expect(parseComfyText(JSON.stringify({ type: "crystools.monitor", data: {} }))).toBeNull();+ });++ it("reads preview frames of both kinds, and ignores broken ones", () => {+ const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);+ const one = Buffer.concat([Buffer.from([0, 0, 0, 1, 0, 0, 0, 1]), jpeg]);+ expect(parseComfyBinary(one)).toMatchObject({ type: "image/jpeg" });+ expect(Buffer.from(parseComfyBinary(one)!.data).equals(jpeg)).toBe(true);+ const meta = Buffer.from(JSON.stringify({ prompt_id: ID, node_id: "3", image_type: "image/png" }));+ const len = Buffer.alloc(4);+ len.writeUInt32BE(meta.length);+ const four = Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, Buffer.from([0x89, 0x50, 0x4e, 0x47])]);+ expect(parseComfyBinary(four)).toMatchObject({ type: "image/png", promptId: ID });+ expect(parseComfyBinary(Buffer.from([0, 0, 0, 4, 0xff, 0xff, 0xff, 0xff, 1]))).toBeNull();+ expect(parseComfyBinary(Buffer.from([0, 0, 0, 1, 0, 0, 0, 9, 1]))).toBeNull();+ expect(parseComfyBinary(Buffer.from([0, 0, 0, 3, 0, 0, 0, 0, 1]))).toBeNull();+ expect(parseComfyBinary(Buffer.from([0, 0]))).toBeNull();+ });+});++describe("the run's words", () => {+ it("says what is happening, without jargon", () => {+ expect(sendingWords(["image/png"])).toBe("Sending your photo to ComfyUI");+ expect(sendingWords(["image/png", "image/jpeg"])).toBe("Sending your photos to ComfyUI");+ expect(sendingWords(["image/png", "video/mp4"])).toBe("Sending your files to ComfyUI");+ expect(sendingWords([])).toBe("Starting on your computer");+ expect(queueWords(0)).toBe("Next in ComfyUI's queue");+ expect(queueWords(2)).toBe("In ComfyUI's queue · 2 ahead");+ expect(makingWords("image", 12, 30)).toBe("Making your picture · step 12 of 30");+ expect(makingWords("video")).toBe("Making your clip");+ expect(savingWords(0.64)).toBe("Saving to Fuobe · 64%");+ for (const w of [sendingWords(["x"]), queueWords(1), makingWords("audio", 1, 2), savingWords(0.5), tabFailureWords("comfy-error", 500), tabFailureWords("save-failed")]) {+ expect(w).not.toMatch(/\b(CORS|relay|lease|task|claim)\b/i);+ }+ });++ it("takes each report only in its state", () => {+ const all: RelayState[] = ["waiting", "sending", "queued", "running", "collecting", "done", "failed", "canceled"];+ expect(all.filter((s) => reportAllowed("sent", s))).toEqual(["sending"]);+ expect(all.filter((s) => reportAllowed("finished", s))).toEqual(["queued", "running"]);+ expect(all.filter((s) => reportAllowed("running", s))).toEqual(["queued", "running"]);+ expect(reportAllowed("finished", "waiting")).toBe(false);+ expect(reportAllowed("refused", "running")).toBe(false);+ expect(reportAllowed("stopped", "canceled")).toBe(true);+ expect(reportAllowed("nonsense" as never, "running")).toBe(false);+ });+});++describe("ComfyUI's one setting", () => {+ it("names only this site", () => {+ expect(corsFlag("https://fuobe.com")).toBe("--enable-cors-header https://fuobe.com");+ expect(corsFlag("http://127.0.0.1:3370")).toBe("--enable-cors-header http://127.0.0.1:3370");+ for (const bad of ["*", "https://fuobe.com/", "https://fuobe.com' ; calc", 'https://a"b.com', "javascript:x", "https://fuobe.com & calc"]) expect(() => corsFlag(bad), bad).toThrow();+ });++ it("guesses the install from the port and the computer", () => {+ expect(guessInstall(8000, "windows")).toBe("desktop");+ expect(guessInstall(8000, "mac")).toBe("desktop");+ expect(guessInstall(8188, "windows")).toBe("portable");+ expect(guessInstall(8188, "mac")).toBe("terminal");+ expect(guessInstall(8189, "linux")).toBe("terminal");+ expect(installFromStats({ system: { embedded_python: true } }, 8000, "windows")).toBe("portable");+ expect(platformOf({ userAgentData: { platform: "Windows" } })).toBe("windows");+ expect(platformOf({ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0)" })).toBe("mac");+ expect(platformOf({ userAgent: "Mozilla/5.0 (X11; Linux x86_64)" })).toBe("linux");+ });++ it("gives each install its one fix", () => {+ expect(fixFor("desktop", "https://fuobe.com")).toMatchObject({ copy: "https://fuobe.com", path: ["Settings (the gear, bottom left)", "Server-Config", "Enable CORS header"] });+ expect(fixFor("portable", "https://fuobe.com")).toMatchObject({ startFile: true, copy: "--enable-cors-header https://fuobe.com" });+ expect(fixFor("terminal", "https://fuobe.com").copy).toBe("python main.py --enable-cors-header https://fuobe.com");+ expect(fixFor("stability-matrix", "https://fuobe.com").path).toContain("Extra Launch Arguments");+ });++ it("makes a Windows start file for the port and this site only", () => {+ const bat = startFile(8188, "https://fuobe.com");+ expect(bat).toMatch(/\r\n/);+ expect(bat.replace(/\r\n/g, "")).not.toMatch(/\n/);+ expect(bat.startsWith("@echo off\r\n")).toBe(true);+ expect(bat).toContain("$Port = 8188");+ expect(bat).toContain("$Flag = '--enable-cors-header https://fuobe.com'");+ expect(bat).toContain(START_FILE_NAME);+ // It asks before it stops anything, and keeps a copy of a start file it changes.+ expect(bat.indexOf("Read-Host")).toBeLessThan(bat.indexOf("Stop-Process"));+ expect(bat).toContain('.bak"');+ // It downloads nothing and sends nothing.+ expect(bat).not.toMatch(/Invoke-WebRequest|Invoke-RestMethod|DownloadString|curl|wget|bitsadmin|Net\.WebClient/i);+ expect(() => startFile(8188, "https://fuobe.com'; Remove-Item C:\\ -Recurse; '")).toThrow();+ expect(() => startFile(Number("8188; calc"), "https://fuobe.com")).toThrow();+ });++ it.runIf(process.platform === "win32")("is PowerShell that parses", () => {+ const bat = startFile(8189, "http://127.0.0.1:3370");+ const script = bat.slice(bat.indexOf("#FUOBE-PS"));+ const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-start-")), "s.ps1");+ fs.writeFileSync(file, script);+ const out = execFileSync(+ "powershell",+ ["-NoProfile", "-Command", `$e=$null; $t=$null; [void][System.Management.Automation.Language.Parser]::ParseFile('${file}', [ref]$t, [ref]$e); $e.Count`],+ { encoding: "utf8" },+ );+ expect(out.trim()).toBe("0");+ });+});diff --git a/tests/fake-local-comfy.test.ts b/tests/fake-local-comfy.test.tsnew file mode 100644index 00000000..e9b3bc8f--- /dev/null+++ b/tests/fake-local-comfy.test.ts@@ -0,0 +1,94 @@+import { randomUUID } from "node:crypto";+import { afterEach, describe, expect, it } from "vitest";+import { parseComfyBinary, parseComfyText, type ComfyEvent } from "@/lib/comfy-ws";+import { FAKE_PNG, startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";++const SITE = "http://127.0.0.1:3370";+let fake: LocalComfy | undefined;+afterEach(async () => {+ await fake?.close();+ fake = undefined;+});++/** A request as a browser on SITE sends it to a loopback ComfyUI. */+const browser = (url: string, init: RequestInit = {}) => fetch(url, { ...init, headers: { ...(init.headers as Record<string, string>), origin: SITE, "sec-fetch-site": "cross-site" } });++async function watch(url: string, clientId: string, until: (e: ComfyEvent) => boolean) {+ const ws = new WebSocket(`${url.replace("http", "ws")}/ws?clientId=${clientId}`);+ ws.binaryType = "arraybuffer";+ const events: ComfyEvent[] = [];+ let previews = 0;+ await new Promise<void>((resolve, reject) => {+ ws.onmessage = (m) => {+ if (typeof m.data !== "string") {+ if (parseComfyBinary(m.data as ArrayBuffer)) previews++;+ return;+ }+ const e = parseComfyText(m.data);+ if (!e) return;+ events.push(e);+ if (until(e)) resolve();+ };+ ws.onerror = () => reject(new Error("socket"));+ });+ ws.close();+ return { events, previews };+}++describe("the fake local ComfyUI", () => {+ it("answers another site 403 without the setting, as ComfyUI does", async () => {+ fake = await startLocalComfy({ cors: "off" });+ expect((await browser(`${fake.url}/system_stats`)).status).toBe(403);+ expect((await fetch(`${fake.url}/system_stats`)).status).toBe(200);+ });++ it("lets the one site in with the setting, and runs a prompt with live steps and previews", async () => {+ fake = await startLocalComfy({ cors: SITE, steps: 3, stepMs: 5 });+ const stats = await browser(`${fake.url}/system_stats`);+ expect(stats.headers.get("access-control-allow-origin")).toBe(SITE);+ expect((await fetch(`${fake.url}/prompt`, { method: "OPTIONS" })).status).toBe(200);+ const form = new FormData();+ form.append("image", new Blob([new Uint8Array(FAKE_PNG)], { type: "image/png" }), "fuobe_abcdefgh12.png");+ form.append("type", "input");+ form.append("overwrite", "true");+ const up = await browser(`${fake.url}/upload/image`, { method: "POST", body: form });+ expect(await up.json()).toEqual({ name: "fuobe_abcdefgh12.png", subfolder: "", type: "input" });+ expect(fake.inputs.get("fuobe_abcdefgh12.png")?.equals(FAKE_PNG)).toBe(true);+ const id = randomUUID();+ const seen = watch(fake.url, "client-12345678", (e) => e.type === "success");+ await new Promise((r) => setTimeout(r, 30));+ const res = await browser(`${fake.url}/prompt`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ prompt: { "3": { class_type: "KSampler", inputs: {} }, "9": { class_type: "SaveImage", inputs: { filename_prefix: "fuobe/gen1" } } }, prompt_id: id, client_id: "client-12345678", extra_data: { preview_method: "auto" } }),+ });+ expect((await res.json()).prompt_id).toBe(id);+ const { events, previews } = await seen;+ expect(events.filter((e) => e.type === "progress").map((e) => (e as { value: number }).value)).toEqual([1, 2, 3]);+ expect(previews).toBe(3);+ const hist = (await (await browser(`${fake.url}/history/${id}`)).json())[id];+ expect(hist.outputs["9"].images[0]).toEqual({ filename: "gen1_00001_.png", subfolder: "fuobe", type: "output" });+ const file = await browser(`${fake.url}/view?filename=gen1_00001_.png&subfolder=fuobe&type=output`);+ expect(Buffer.from(await file.arrayBuffer()).equals(FAKE_PNG)).toBe(true);+ expect((await (await browser(`${fake.url}/api/jobs/${id}`)).json()).status).toBe("completed");+ });++ it("refuses a prompt for a missing node or model the way ComfyUI does, and forgets everything on a restart", async () => {+ fake = await startLocalComfy({ cors: "*", failNext: "missing_node" });+ const post = (body: unknown) => fetch(`${fake!.url}/prompt`, { method: "POST", body: JSON.stringify(body) });+ const a = await post({ prompt: {}, prompt_id: randomUUID() });+ expect(a.status).toBe(400);+ expect((await a.json()).error.type).toBe("missing_node_type");+ fake.opts.failNext = "missing_model";+ const b = await post({ prompt: { "4": { class_type: "CheckpointLoaderSimple", inputs: { ckpt_name: "x.safetensors" } } }, prompt_id: randomUUID() });+ expect((await b.json()).node_errors["4"].errors[0].extra_info.received_value).toBe("x.safetensors");+ fake.opts.failNext = "never";+ const id = randomUUID();+ await post({ prompt: {}, prompt_id: id });+ await new Promise((r) => setTimeout(r, 60));+ expect((await (await fetch(`${fake.url}/queue`)).json()).queue_running[0][1]).toBe(id);+ fake.restart();+ expect((await fetch(`${fake.url}/api/jobs/${id}`)).status).toBe(404);+ expect(await (await fetch(`${fake.url}/history/${id}`)).json()).toEqual({});+ });+});diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.tsnew file mode 100644index 00000000..519dd876--- /dev/null+++ b/tests/helpers/fake-local-comfy.ts@@ -0,0 +1,464 @@+/**+ * A ComfyUI stand-in for "Use the ComfyUI on this computer": what the Fuobe tab talks to on 127.0.0.1. It behaves like+ * ComfyUI 0.42 where it matters: without the cross-site setting it answers 403 to another site's requests (its+ * origin_only_middleware); with it, it sends the CORS headers for that one origin (or every origin) and answers+ * OPTIONS. It takes uploads under the name given, prompts with a client's prompt_id and preview_method, runs one job at+ * a time (progress steps and preview frames on /ws), keeps a history, cancels jobs (/api/jobs, or /queue and+ * /interrupt on an older one), and serves result files. It can refuse a prompt (a missing node or model), run out of+ * memory, restart (losing its queue and history), stop and come back. Every request is logged.+ *+ * node tests/helpers/fake-local-comfy.ts --port 3371 --cors http://127.0.0.1:3370+ *+ * Runs under plain Node too: only erasable TypeScript.+ */+import { createHash, randomUUID } from "node:crypto";+import http from "node:http";+import type { Duplex } from "node:stream";+import { pathToFileURL } from "node:url";++export interface LocalComfyOptions {+ /** "off": ComfyUI's own check (other sites get 403); an origin, or "*". */+ cors: string;+ version?: string;+ /** /api/jobs exists (ComfyUI 0.42 and later). */+ jobsApi?: boolean;+ /** /prompt honours a client's prompt_id (else it mints its own, as older ComfyUI does). */+ clientPromptId?: boolean;+ /** Before a job starts, and between its steps. */+ latencyMs?: number;+ stepMs?: number;+ steps?: number;+ /** What the next prompt does. */+ failNext?: "oom" | "missing_node" | "missing_model" | "gone" | "never";+ /** 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). */+ metaBatch?: number;+ /** Embedded Python (portable / Easy-Install). */+ portable?: boolean;+ loras?: string[];+}++export interface LocalComfyLog {+ method: string;+ path: string;+ origin?: string;+ status?: number;+ upload?: { name: string; bytes: Buffer };+ prompt?: { prompt_id?: string; prompt?: Record<string, { class_type: string; inputs: Record<string, unknown> }>; extra_data?: Record<string, unknown>; client_id?: string };+}++type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>;+interface Job {+ id: string;+ number: number;+ graph: Graph;+ clientId?: string;+ preview: boolean;+ fail?: LocalComfyOptions["failNext"];+ pass?: number;+}+type Entry = { prompt: unknown[]; outputs: Record<string, Record<string, unknown>>; status: { status_str: string; completed: boolean; messages: [string, Record<string, unknown>][] } };++export interface LocalComfy {+ port: number;+ url: string;+ opts: LocalComfyOptions;+ log: LocalComfyLog[];+ inputs: Map<string, Buffer>;+ history: Map<string, Entry>;+ /** Prompts posted (a resumed task must not post twice). */+ posts: () => number;+ /** ComfyUI restarted: its queue, history and sockets are gone, the inputs folder stays. */+ restart: (o?: Partial<LocalComfyOptions>) => void;+ /** Stop listening (ComfyUI closed), and start again on the same port. */+ stop: () => Promise<void>;+ start: (o?: Partial<LocalComfyOptions>) => Promise<void>;+ close: () => Promise<void>;+}++export const FAKE_PNG = Buffer.from(+ "89504e470d0a1a0a0000000d494844520000000200000002080600000072b60d240000001149444154789c63381150f11f8419600c005a940a3db632c1b20000000049454e44ae426082",+ "hex",+);+export const FAKE_MP4 = Buffer.concat([Buffer.from("000000186674797069736f6d0000020069736f6d69736f32", "hex"), Buffer.alloc(64, 1)]);+const FAKE_WAV = Buffer.concat([Buffer.from("RIFF"), Buffer.from([36, 0, 0, 0]), Buffer.from("WAVEfmt "), Buffer.alloc(64, 0)]);+const FAKE_EXR = Buffer.concat([Buffer.from("762f3101", "hex"), Buffer.alloc(60, 2)]);+const PREVIEW_JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46, 0, 1]);++/** The parts of a multipart body: field name → {filename?, data}. */+function multipart(body: Buffer, contentType: string): Map<string, { filename?: string; data: Buffer }> {+ const out = new Map<string, { filename?: string; data: Buffer }>();+ const boundary = /boundary=(?:"([^"]+)"|([^;]+))/.exec(contentType);+ if (!boundary) return out;+ const marker = Buffer.from(`--${boundary[1] ?? boundary[2]}`);+ let at = body.indexOf(marker);+ while (at >= 0) {+ const next = body.indexOf(marker, at + marker.length);+ if (next < 0) break;+ const part = body.subarray(at + marker.length + 2, next - 2);+ const headEnd = part.indexOf("\r\n\r\n");+ if (headEnd >= 0) {+ const head = part.subarray(0, headEnd).toString("utf8");+ const name = /name="([^"]+)"/.exec(head)?.[1];+ const filename = /filename="([^"]*)"/.exec(head)?.[1];+ if (name) out.set(name, { filename, data: part.subarray(headEnd + 4) });+ }+ at = next;+ }+ return out;+}++/** A WebSocket frame from the server (never masked). */+function frame(opcode: number, payload: Buffer): Buffer {+ const n = payload.length;+ const head = n < 126 ? Buffer.from([0x80 | opcode, n]) : n < 65536 ? Buffer.from([0x80 | opcode, 126, n >> 8, n & 255]) : Buffer.concat([Buffer.from([0x80 | opcode, 127]), (() => { const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(n)); return b; })()]);+ return Buffer.concat([head, payload]);+}++export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<LocalComfy> {+ const opts: LocalComfyOptions = { version: "0.42.0", jobsApi: true, clientPromptId: true, latencyMs: 30, stepMs: 20, steps: 4, ...given };+ const log: LocalComfyLog[] = [];+ const inputs = new Map<string, Buffer>();+ const history = new Map<string, Entry>();+ let queue: Job[] = [];+ let running: Job | null = null;+ let number = 0;+ let posts = 0;+ let timer: NodeJS.Timeout | undefined;+ const sockets = new Map<string, Set<Duplex>>();+ let server: http.Server;+ let generation = 0;++ const send = (clientId: string | undefined, payload: Buffer, binary = false) => {+ for (const [id, set] of sockets) if (!clientId || id === clientId) for (const s of set) s.write(frame(binary ? 2 : 1, payload));+ };+ const event = (clientId: string | undefined, type: string, data: Record<string, unknown>) => send(clientId, Buffer.from(JSON.stringify({ type, data })));+ const status = () => event(undefined, "status", { status: { exec_info: { queue_remaining: queue.length + (running ? 1 : 0) } } });++ const outputNode = (g: Graph) => Object.keys(g).find((k) => /^(Save|VHS_VideoCombine|PreviewImage|CreateVideo)/.test(g[k].class_type)) ?? "9";+ const prefixOf = (g: Graph) => String(Object.values(g).find((n) => typeof n.inputs?.filename_prefix === "string")?.inputs.filename_prefix ?? "ComfyUI");++ function outputsFor(job: Job): Record<string, Record<string, unknown>> {+ const node = outputNode(job.graph);+ const prefix = prefixOf(job.graph);+ const sub = prefix.includes("/") ? prefix.slice(0, prefix.lastIndexOf("/")) : "";+ const base = prefix.split("/").pop();+ const ui: Record<string, unknown[]> = {};+ const add = (key: string, ext: string, i: number) => (ui[key] ??= []).push({ filename: `${base}_${String(i + 1).padStart(5, "0")}_.${ext}`, subfolder: sub, type: "output" });+ (opts.outputs ?? ["image"]).forEach((k, i) => {+ if (k === "image" || k === "fake-png") add("images", "png", i);+ else if (k === "video") add("gifs", "mp4", i);+ else if (k === "audio") add("audio", "wav", i);+ else if (k === "exr") add("images", "exr", i);+ else if (k === "text") add("text_files", "txt", i);+ });+ return { [node]: ui };+ }++ function finish(job: Job, entry: Entry) {+ history.set(job.id, entry);+ running = null;+ tick();+ }++ function run(job: Job) {+ running = job;+ const gen = generation;+ const alive = () => gen === generation && running === job;+ const steps = opts.steps ?? 4;+ const node = Object.keys(job.graph).find((k) => /KSampler|Sampler/.test(job.graph[k].class_type)) ?? Object.keys(job.graph)[0] ?? "1";+ event(job.clientId, "execution_start", { prompt_id: job.id });+ event(job.clientId, "executing", { node, prompt_id: job.id });+ let step = 0;+ const next = () => {+ if (!alive()) return;+ if (job.fail === "never") return;+ if (step < steps) {+ step++;+ event(job.clientId, "progress", { value: step, max: steps, prompt_id: job.id, node });+ if (job.preview) {+ const meta = Buffer.from(JSON.stringify({ prompt_id: job.id, node_id: node, image_type: "image/jpeg" }));+ const len = Buffer.alloc(4);+ len.writeUInt32BE(meta.length);+ send(job.clientId, Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, PREVIEW_JPEG]), true);+ }+ timer = setTimeout(next, opts.stepMs);+ return;+ }+ if (job.fail === "oom") {+ const err = { prompt_id: job.id, node_id: node, node_type: "KSampler", exception_message: "Allocation on device 0 would exceed allowed memory. (out of memory)", exception_type: "torch.OutOfMemoryError" };+ event(job.clientId, "execution_error", err);+ return finish(job, { prompt: [job.number, job.id, job.graph, {}, []], outputs: {}, status: { status_str: "error", completed: false, messages: [["execution_error", err]] } });+ }+ // A meta-batch's first passes save nothing and queue the next pass (a new prompt id, the same prefix).+ const passes = opts.metaBatch ?? 0;+ const pass = job.pass ?? 1;+ const outputs = passes && pass < passes ? {} : outputsFor(job);+ if (passes && pass < passes) queue.unshift({ ...job, id: randomUUID(), number: -++number, pass: pass + 1, preview: false });+ event(job.clientId, "executed", { node: outputNode(job.graph), prompt_id: job.id, output: outputs[outputNode(job.graph)] ?? {} });+ event(job.clientId, "executing", { node: null, prompt_id: job.id });+ event(job.clientId, "execution_success", { prompt_id: job.id });+ finish(job, { prompt: [job.number, job.id, job.graph, {}, []], outputs, status: { status_str: "success", completed: true, messages: [["execution_success", { prompt_id: job.id }]] } });+ };+ timer = setTimeout(next, opts.latencyMs);+ }++ function tick() {+ status();+ if (running || !queue.length) return;+ const job = queue.shift()!;+ run(job);+ }++ const jobStatus = (id: string) => {+ if (running?.id === id) return { id, status: "in_progress" };+ if (queue.some((j) => j.id === id)) return { id, status: "pending" };+ const h = history.get(id);+ if (h) return { id, status: h.status.status_str === "success" ? "completed" : "failed", outputs_count: Object.keys(h.outputs).length };+ return null;+ };++ const cancel = (id: string) => {+ if (running?.id === id) {+ event(running.clientId, "execution_interrupted", { prompt_id: id });+ history.set(id, { prompt: [running.number, id, running.graph, {}, []], outputs: {}, status: { status_str: "error", completed: false, messages: [["execution_interrupted", { prompt_id: id }]] } });+ running = null;+ clearTimeout(timer);+ tick();+ return true;+ }+ const before = queue.length;+ queue = queue.filter((j) => j.id !== id);+ return queue.length < before;+ };++ const handler = (req: http.IncomingMessage, res: http.ServerResponse) => {+ const chunks: Buffer[] = [];+ req.on("data", (c: Buffer) => chunks.push(c));+ req.on("end", () => {+ const body = Buffer.concat(chunks);+ const url = new URL(req.url ?? "/", "http://fake");+ const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;+ const entry: LocalComfyLog = { method: req.method ?? "GET", path: url.pathname + url.search, ...(origin && { origin }) };+ log.push(entry);+ const headers: Record<string, string> = {};+ if (opts.cors !== "off") {+ Object.assign(headers, {+ "Access-Control-Allow-Origin": opts.cors,+ "Access-Control-Allow-Methods": "POST, GET, DELETE, PUT, OPTIONS, PATCH",+ "Access-Control-Allow-Headers": "Content-Type, Authorization",+ "Access-Control-Allow-Credentials": "true",+ });+ } else {+ // ComfyUI's origin_only_middleware: another site's request, or an Origin that isn't this host.+ const site = req.headers["sec-fetch-site"];+ const host = String(req.headers.host ?? "");+ const otherOrigin = origin && new URL(origin).host !== host;+ if (site === "cross-site" || otherOrigin) {+ entry.status = 403;+ res.writeHead(403);+ return res.end();+ }+ }+ const reply = (code: number, value: unknown, type = "application/json") => {+ entry.status = code;+ res.writeHead(code, { ...headers, "content-type": type });+ res.end(Buffer.isBuffer(value) ? value : JSON.stringify(value));+ };+ if (req.method === "OPTIONS") return reply(200, "");+ const p = url.pathname;+ if (p === "/system_stats" || p === "/api/system_stats") {+ const argv = ["main.py", ...(opts.cors === "off" ? [] : ["--enable-cors-header", opts.cors]), "--base-directory", "C:\\Users\\someone\\private"];+ return reply(200, {+ system: { os: "nt", comfyui_version: opts.version, ram_total: 64 * 2 ** 30, embedded_python: !!opts.portable, argv, python_version: "3.12" },+ 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 ?? []);+ if (p === "/models") return reply(200, ["checkpoints", "loras", "vae"]);+ if (p.startsWith("/models/")) return reply(200, []);+ if (p === "/object_info") return reply(200, {});+ if (p.startsWith("/object_info/")) return reply(200, {});+ if (p === "/embeddings") return reply(200, []);+ if (p === "/upload/image" && req.method === "POST") {+ const parts = multipart(body, String(req.headers["content-type"] ?? ""));+ const image = parts.get("image");+ const name = image?.filename ?? "";+ if (!image || !name || /[\\/]|\.\./.test(name)) return reply(400, { error: "bad name" });+ inputs.set(name, Buffer.from(image.data));+ entry.upload = { name, bytes: Buffer.from(image.data) };+ return reply(200, { name, subfolder: "", type: parts.get("type")?.data.toString() ?? "input" });+ }+ if (p === "/prompt" && req.method === "POST") {+ let json: LocalComfyLog["prompt"] & { prompt?: Graph };+ try {+ json = JSON.parse(body.toString("utf8"));+ } catch {+ return reply(400, { error: { type: "invalid_prompt", message: "not json" } });+ }+ entry.prompt = json;+ posts++;+ const fail = opts.failNext;+ opts.failNext = undefined;+ if (fail === "missing_node") {+ return reply(400, {+ error: { type: "missing_node_type", message: "Node 'FancyNode' not found. The custom node may not be installed.", details: "Node ID '#3'", extra_info: { node_id: "3", class_type: "FancyNode", node_title: "FancyNode" } },+ node_errors: {},+ });+ }+ if (fail === "missing_model") {+ const [id, n] = Object.entries(json.prompt ?? {}).find(([, v]) => /Loader/.test(v.class_type)) ?? ["1", { class_type: "CheckpointLoaderSimple", inputs: {} }];+ const [input, value] = Object.entries(n.inputs).find(([k]) => /name/.test(k)) ?? ["ckpt_name", "model.safetensors"];+ return reply(400, {+ error: { type: "prompt_outputs_failed_validation", message: "Prompt outputs failed validation", details: "", extra_info: {} },+ node_errors: { [id]: { errors: [{ type: "value_not_in_list", message: "Value not in list", details: `${input}: '${value}' not in []`, extra_info: { input_name: input, received_value: value } }], dependent_outputs: [], class_type: n.class_type } },+ });+ }+ const id = opts.clientPromptId && typeof json.prompt_id === "string" ? json.prompt_id : randomUUID();+ 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);+ setImmediate(tick);+ return reply(200, { prompt_id: id, number: job.number, node_errors: {} });+ }+ if (p === "/queue") {+ if (req.method === "POST") {+ const del = (JSON.parse(body.toString("utf8") || "{}") as { delete?: string[] }).delete ?? [];+ queue = queue.filter((j) => !del.includes(j.id));+ return reply(200, {});+ }+ const row = (j: Job) => [j.number, j.id, j.graph, { client_id: j.clientId }, []];+ return reply(200, { queue_running: running ? [row(running)] : [], queue_pending: queue.map(row) });+ }+ if (p === "/interrupt" && req.method === "POST") {+ const id = (JSON.parse(body.toString("utf8") || "{}") as { prompt_id?: string }).prompt_id;+ if (id && running?.id === id) cancel(id);+ return reply(200, {});+ }+ if (p.startsWith("/history/")) {+ const id = decodeURIComponent(p.slice(9));+ const h = history.get(id);+ return reply(200, h ? { [id]: h } : {});+ }+ if (p === "/history") {+ const max = Number(url.searchParams.get("max_items") ?? 64);+ return reply(200, Object.fromEntries([...history.entries()].slice(-max)));+ }+ const job = /^\/api\/jobs\/([^/]+)(\/cancel)?$/.exec(p);+ if (job && opts.jobsApi) {+ if (job[2] && req.method === "POST") return reply(200, { cancelled: cancel(job[1]) });+ const s = jobStatus(job[1]);+ return s ? reply(200, s) : reply(404, { error: "Job not found" });+ }+ if (p === "/view") {+ const name = url.searchParams.get("filename") ?? "";+ const kind = (opts.outputs ?? ["image"])[Math.max(0, Number(/_(\d{5})_\./.exec(name)?.[1] ?? 1) - 1)];+ if (kind === "fake-png") return reply(200, Buffer.from("<!doctype html><script>alert(document.cookie)</script>".padEnd(200, " ")), "image/png");+ if (name.endsWith(".png")) return reply(200, FAKE_PNG, "image/png");+ if (name.endsWith(".mp4")) return reply(200, FAKE_MP4, "video/mp4");+ if (name.endsWith(".wav")) return reply(200, FAKE_WAV, "audio/wav");+ if (name.endsWith(".exr")) return reply(200, FAKE_EXR, "image/x-exr");+ if (name.endsWith(".txt")) return reply(200, Buffer.from("0.00-1.20: Hello there\n"), "text/plain");+ return reply(404, { error: "no file" });+ }+ reply(404, { error: "not found" });+ });+ };++ const upgrade = (req: http.IncomingMessage, socket: Duplex) => {+ const url = new URL(req.url ?? "/", "http://fake");+ const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;+ log.push({ method: "WS", path: url.pathname + url.search, ...(origin && { origin }) });+ const key = req.headers["sec-websocket-key"];+ if (url.pathname !== "/ws" || typeof key !== "string") return socket.destroy();+ // ComfyUI's own check applies to the socket too when the setting is off.+ if (opts.cors === "off" && origin && new URL(origin).host !== String(req.headers.host ?? "")) {+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");+ return socket.destroy();+ }+ const accept = createHash("sha1").update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64");+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);+ const clientId = url.searchParams.get("clientId") ?? randomUUID();+ const set = sockets.get(clientId) ?? new Set<Duplex>();+ sockets.set(clientId, set);+ set.add(socket);+ const drop = () => set.delete(socket);+ socket.on("data", (d: Buffer) => {+ if ((d[0] & 0x0f) === 0x8) {+ drop();+ socket.end();+ }+ });+ socket.on("close", drop);+ socket.on("error", drop);+ socket.write(frame(1, Buffer.from(JSON.stringify({ type: "status", data: { status: { exec_info: { queue_remaining: queue.length + (running ? 1 : 0) } }, sid: clientId } }))));+ // A client that comes back while its prompt runs hears which node it is on.+ if (running && running.clientId === clientId) event(clientId, "executing", { node: "1", prompt_id: running.id });+ };++ const listen = (at: number) =>+ new Promise<number>((resolve) => {+ server = http.createServer(handler);+ server.on("upgrade", upgrade);+ server.listen(at, "127.0.0.1", () => {+ const addr = server.address();+ resolve(typeof addr === "object" && addr ? addr.port : at);+ });+ });++ const closeSockets = () => {+ for (const set of sockets.values()) for (const s of set) s.destroy();+ sockets.clear();+ };++ const restart = (o: Partial<LocalComfyOptions> = {}) => {+ generation++;+ clearTimeout(timer);+ queue = [];+ running = null;+ history.clear();+ closeSockets();+ Object.assign(opts, o);+ };++ return listen(port).then((at) => {+ const fake: LocalComfy = {+ port: at,+ url: `http://127.0.0.1:${at}`,+ opts,+ log,+ inputs,+ history,+ posts: () => posts,+ restart,+ stop: () =>+ new Promise<void>((done) => {+ restart();+ server.closeAllConnections?.();+ server.close(() => done());+ }),+ start: async (o = {}) => {+ Object.assign(opts, o);+ await listen(at);+ },+ close: () =>+ new Promise<void>((done) => {+ restart();+ server.closeAllConnections?.();+ server.close(() => done());+ }),+ };+ return fake;+ });+}++// Run on its own: node tests/helpers/fake-local-comfy.ts --port 3371 --cors http://127.0.0.1:3370+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ const arg = (name: string) => {+ const i = process.argv.indexOf(`--${name}`);+ return i > 0 ? process.argv[i + 1] : undefined;+ };+ const fake = await startLocalComfy({ cors: arg("cors") ?? "off", steps: Number(arg("steps") ?? 8), stepMs: Number(arg("step-ms") ?? 250), portable: arg("portable") === "1" }, Number(arg("port") ?? 3371));+ console.log(`fake ComfyUI on ${fake.url} (cross-site setting: ${fake.opts.cors})`);+}