Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Your computer's ComfyUI: fixes from the review

Adarsh1920077ccfcc
diff --git a/docs/public-signup.md b/docs/public-signup.md
index c2481a6b..74d83c2c 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -121,22 +121,48 @@ are deleted with it.
## Your GPU
-An account connects its own ComfyUI in **Settings → Your GPU**, or from the "Connect your GPU" card.
-The studio's server calls that ComfyUI, so it must be reachable from the internet. Put a tunnel in
-front of a local ComfyUI and paste the https address it prints:
+An account connects its own ComfyUI in **Settings → Your GPU**, or from the "Connect your GPU" card,
+in one of two ways.
+
+### The ComfyUI on this computer
+
+The first choice: the account's open Fuobe tab runs its jobs on the ComfyUI on the same computer.
+The server still plans every run (templates, inputs, checks, limits, history). Each ComfyUI call
+becomes a job that the tab takes (`/api/gpu/computer/*`), sends to `http://127.0.0.1:<port>`,
+follows, and whose results it uploads back; results are checked like uploads, and a job takes only
+its own results, once. The server never calls the person's computer. Runs wait while no tab is open
+("Open Fuobe on the computer with your ComfyUI to run this") and stop cleanly after a while.
+
+- **Finding ComfyUI.** The card looks on ports 8188, 8000 (ComfyUI Desktop), 8189, 8190, 8288, 8001
+ and 7821, or one the person types. While the browser would still ask to let the site reach apps
+ on this device, it looks only after a click, and explains that question first. A tab never
+ reaches the computer's apps by itself before that.
+- **Fuobe's setting.** A page can read a ComfyUI on the computer only when ComfyUI runs with
+ `--enable-cors-header <the site's address>`. The card gives the fix for the install it finds: a
+ start file for Windows portable or Easy-Install (it restarts ComfyUI with the setting and leaves a
+ start file with it for next time; it never changes the person's own start files), the place in
+ ComfyUI Desktop's Server-Config, Stability Matrix's launch options, or the flag for a terminal.
+ It notices by itself when ComfyUI is back with it.
+- **Fuobe's guard.** With that setting, ComfyUI stops turning away other websites' requests.
+ `fuobe_guard.py` (src/lib/comfy-guard.ts), a custom node that the start file puts in
+ `custom_nodes` and that the other installs download from the card, puts the check back: a request
+ from a web page gets in only from ComfyUI's own page or the site the setting names, the live
+ socket included. It answers `GET /fuobe/guard`, and the card warns while it's missing.
+- **Phones and Safari** can't reach a ComfyUI on the device: they get the link instead, with why.
+
+The owner can do the same on a deployed studio: **Settings → Where ComfyUI runs → On the computer
+you're using**. A studio with ComfyUI on its own machine keeps calling it from the server.
+
+### A link
+
+For runs that go on with the tab closed. The studio's server calls that ComfyUI, so it must be
+reachable from the internet. Put a tunnel in front of a local ComfyUI and paste the https address
+it prints:
```bash
cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
```
-- **Finding ComfyUI.** The page looks for a ComfyUI on the visitor's own computer, from the browser
- (the server can't see that computer). It tries `http://127.0.0.1` on ports 8188, 8000 (ComfyUI
- Desktop), 8189, 8190 and 8288. When ComfyUI answers, the page names the GPU and its VRAM and shows
- the tunnel command. When a port answers but the browser can't read it, ComfyUI was started
- without CORS: the page shows the flag to add, `--enable-cors-header https://fuobe.com`. Chrome
- may ask to let the site reach devices on the local network. When nothing answers, the visitor
- can enter a port or an address. A local address is used only by the browser and is never sent to
- the server.
- **Saving.** `PUT /api/account/gpu` with `{ "url", "token"? }` checks the address and asks that
ComfyUI for `/system_stats` (`?test=1` checks without saving). `DELETE` disconnects. The address
and the optional token (sent as `Authorization: Bearer`) are stored with the account in
diff --git a/src/app/api/account/gpu/route.ts b/src/app/api/account/gpu/route.ts
index d6641224..b0fc551f 100644
--- a/src/app/api/account/gpu/route.ts
+++ b/src/app/api/account/gpu/route.ts
@@ -25,6 +25,8 @@ function computerView(id: string) {
return {
mode: "computer" as const,
online: !!f?.online,
+ ...(f?.comfy && { comfy: f.comfy }),
+ ...(f?.guard !== undefined && { guard: f.guard }),
...(f?.device && { device: f.device }),
...(f?.vramBytes && { vramBytes: f.vramBytes }),
...(f?.version && { version: f.version }),
@@ -73,8 +75,8 @@ export async function PUT(request: Request) {
if (new URL(request.url).searchParams.get("test") !== "1") {
setAccountGpu(a.id, { url, token });
clearAccountLoras(a.id);
- // Runs waiting for a computer stop: they go to the link from now on.
- if (before?.mode === "computer") forgetComputer(`acct:${a.id}`);
+ // Runs on the computer stop (saying why): they go to the link from now on.
+ if (before?.mode === "computer") forgetComputer(`acct:${a.id}`, "switched");
}
return Response.json({ gpu: { mode: "link", url, hasToken: !!token }, info });
} catch (e) {
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
index 5c8bd553..76057c4e 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -2,6 +2,7 @@ import { cookies } from "next/headers";
import { connection } from "next/server";
import { z } from "zod";
import { accountGpu, authEnabled, deleteAccount, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken, verifyAccount } from "@/server/auth";
+import { runnerFacts } from "@/server/computer/tasks";
import { getSetting } from "@/server/settings";
import { purgeAccount } from "@/server/account-sweep";
import { hit } from "@/server/rate";
@@ -15,13 +16,15 @@ export async function GET(request: Request) {
const account = !owner && open && session?.kind === "account" ? session.account : null;
// Runs go to the ComfyUI on this person's own computer: their Fuobe tab runs them (never for an API token: a script isn't a tab).
const computer = account ? accountGpu(account.id)?.mode === "computer" : owner && !validToken(request.headers.get("authorization")) && getSetting("comfyWhere") === "computer";
+ // Where that computer's tab last found ComfyUI (another browser of theirs starts looking there).
+ const comfyPort = computer ? runnerFacts(account ? `acct:${account.id}` : "owner")?.port : undefined;
return Response.json(
{
signedIn: owner || !!account,
owner,
publicSignup: open,
...(account && { account: { email: account.email } }),
- ...(computer && { computer: true }),
+ ...(computer && { computer: true, ...(comfyPort && { comfyPort }) }),
},
{ headers: { "Cache-Control": "no-store" } },
);
diff --git a/src/app/api/gpu/computer/beat/route.ts b/src/app/api/gpu/computer/beat/route.ts
index 4398d7ed..78e74ac2 100644
--- a/src/app/api/gpu/computer/beat/route.ts
+++ b/src/app/api/gpu/computer/beat/route.ts
@@ -24,7 +24,7 @@ export async function POST(request: Request) {
return Response.json({ error: "Send JSON" }, { status: 400 });
}
try {
- return Response.json(beat(principal, { device: String(body?.device ?? ""), port: body?.port, facts: body?.facts, running: Array.isArray(body?.running) ? body.running : [], takeover: body?.takeover === true, stopped: Array.isArray(body?.stopped) ? body.stopped : [], ready: body?.ready !== false }), {
+ return Response.json(beat(principal, { device: String(body?.device ?? ""), port: body?.port, facts: body?.facts, running: Array.isArray(body?.running) ? body.running : [], takeover: body?.takeover === true, stopped: Array.isArray(body?.stopped) ? body.stopped : [], ready: body?.ready !== false, ...(body?.why === "setting" && { why: "setting" as const }), listen: body?.listen === true }), {
headers: { "Cache-Control": "no-store" },
});
} catch (e) {
diff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
index 3c5b9367..9919ad37 100644
--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@ -1,11 +1,17 @@
import { RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";
import { gateAsProxy, readBodyWithin } from "@/server/direct-gate";
import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";
-import { leased, report } from "@/server/computer/tasks";
+import { leased, report, type TaskRow } from "@/server/computer/tasks";
import { onComputer, planRelayOutputs } from "@/server/providers/comfyui";
+import { enter } from "@/server/rate";
const EVENTS = new Set(["sent", "refused", "queued", "running", "finished", "passes", "gone", "comfy-down", "stopped", "failed"]);
+/** Reports read at once: one person's, and across the server (each holds its body in memory while it is read). */
+const AT_ONCE = { person: 2, all: 16 };
+/** A report over this size counts against a lower limit a minute. */
+const LARGE_BYTES = 64 * 1024;
+
/** The event as the tab sent it, with only the fields each one has, or null. */
function eventOf(b: Record<string, unknown>): ReportEvent | null {
const e = b.event;
@@ -26,16 +32,26 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {
return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never } : null;
case "failed":
return typeof b.reason === "string" && (TAB_FAILURES as readonly string[]).includes(b.reason) ? { event: e, reason: b.reason as never, status: num(b.status) } : null;
+ case "comfy-down":
+ return { event: e, ...(b.why === "setting" && { why: "setting" as const }) };
default:
- return { event: e as "gone" | "comfy-down" | "stopped" };
+ return { event: e as "gone" | "stopped" };
}
}
+/** The most a report about this job may weigh now: a finished entry while ComfyUI has it, a refusal while it sends. */
+const capFor = (t: TaskRow) => (t.state === "queued" || t.state === "running" ? RELAY_LIMITS.reportBytes : t.state === "sending" ? RELAY_LIMITS.refusalBytes : RELAY_LIMITS.smallReportBytes);
+/** The reports that carry ComfyUI's own answer; every other one is a few words. */
+const LARGE_EVENTS = new Set(["finished", "passes", "refused"]);
+
+const no = (status: number, error: string, headers: Record<string, string> = {}) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store", ...headers } });
+
/**
- * The tab's report about a job it took (its token in the body): sent, refused, where it is in the queue, its steps, its
- * finished /history entry (up to 8 MB), ComfyUI gone or down, a stop done. Each is taken only where the job is. The
- * answer to a finished prompt names the files to upload. The proxy doesn't run on this route (a big entry): its checks
- * run here.
+ * The tab's report about a job it took (its token in X-Fuobe-Lease, checked before the body is read): sent, refused,
+ * where it is in the queue, its steps, its finished /history entry (up to 8 MB, only while ComfyUI has the job), ComfyUI
+ * gone or down, a stop done. Each is taken only where the job is. The answer to a finished prompt names the files to
+ * upload. Two of one person's reports are read at once, a few across the server. The proxy doesn't run on this route (a
+ * big entry): its checks run here.
*/
export async function POST(request: Request, ctx: RouteContext<"/api/gpu/computer/tasks/[id]/report">) {
const denied = gateAsProxy(request);
@@ -44,22 +60,47 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute
if (principal instanceof Response) return principal;
const limited = rateOf(principal, "report", 300);
if (limited) return limited;
- const raw = await readBodyWithin(request, RELAY_LIMITS.reportBytes);
- if (raw === "too-big") return Response.json({ error: "That report is too large" }, { status: 413 });
- let body: Record<string, unknown> | null = null;
- try {
- body = raw ? (JSON.parse(raw.toString("utf8")) as Record<string, unknown>) : null;
- } catch {}
- const event = body && typeof body === "object" ? eventOf(body) : null;
- if (!event) return Response.json({ error: "Not a report" }, { status: 400 });
const { id } = await ctx.params;
+ const lease = request.headers.get("x-fuobe-lease");
+ let cap: number;
+ try {
+ cap = capFor(leased(principal, id, lease));
+ } catch (e) {
+ return relayAnswer(e);
+ }
+ const declared = Number(request.headers.get("content-length") ?? NaN);
+ if (Number.isFinite(declared) && declared > cap) return no(413, "That report is too large");
+ if (cap > LARGE_BYTES && !(declared <= LARGE_BYTES)) {
+ const big = rateOf(principal, "report-large", 30);
+ if (big) return big;
+ }
+ const mine = enter(`relay-report:${principal}`, AT_ONCE.person);
+ if (!mine) return no(429, "Too many at once. Fuobe tries again by itself.", { "Retry-After": "1" });
+ const all = enter("relay-report", AT_ONCE.all);
+ if (!all) {
+ mine();
+ return no(429, "The studio is busy. Fuobe tries again by itself.", { "Retry-After": "2" });
+ }
try {
- const t = leased(principal, id, body!.lease);
+ const raw = await readBodyWithin(request, cap);
+ if (raw === "too-big") return no(413, "That report is too large");
+ let body: Record<string, unknown> | null = null;
+ try {
+ body = raw ? (JSON.parse(raw.toString("utf8")) as Record<string, unknown>) : null;
+ } catch {}
+ const event = body && typeof body === "object" ? eventOf(body) : null;
+ if (!event) return no(400, "Not a report");
+ if (!LARGE_EVENTS.has(event.event) && raw!.length > RELAY_LIMITS.smallReportBytes) return no(413, "That report is too large");
+ // Where the job is now (it may have moved while the body arrived).
+ const t = leased(principal, id, lease);
return Response.json(
report(t, event, (entries, passes) => onComputer(principal, () => planRelayOutputs(t, entries, passes))),
{ headers: { "Cache-Control": "no-store" } },
);
} catch (e) {
return relayAnswer(e);
+ } finally {
+ all();
+ mine();
}
}
diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.ts
index bf5ff8f5..52172a60 100644
--- a/src/app/api/settings/route.ts
+++ b/src/app/api/settings/route.ts
@@ -1,5 +1,6 @@
import { connection } from "next/server";
-import { publicSettings, setSetting, SETTINGS, validateSetting, type SettingName } from "@/server/settings";
+import { forgetComputer } from "@/server/computer/tasks";
+import { getSetting, publicSettings, setSetting, SETTINGS, validateSetting, type SettingName } from "@/server/settings";
export async function GET() {
await connection();
@@ -14,6 +15,9 @@ export async function PUT(request: Request) {
} catch (e) {
return Response.json({ error: (e as Error).message }, { status: 400 });
}
+ const onComputer = getSetting("comfyWhere") === "computer";
for (const [name, value] of entries) setSetting(name, value.trim());
+ // ComfyUI no longer runs on the owner's computer: the runs still going there stop, saying why.
+ if (onComputer && getSetting("comfyWhere") !== "computer") forgetComputer("owner", "switched");
return Response.json({ settings: publicSettings() });
}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index 69a1f2f1..5e3c373b 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -1,5 +1,6 @@
"use client";
+import dynamic from "next/dynamic";
import { useLinkStatus } from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { useTheme } from "next-themes";
@@ -44,6 +45,9 @@ import { useModKey } from "@/lib/keys";
import { fullScreenStudio, groupId, NAV_CLOSED_KEY, navActive, NEW_CREATION_HREF, parseClosed, scrollFades, sidebarCookie, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";
import { cn } from "@/lib/utils";
+// The note of a tab that runs the person's jobs on their own computer's ComfyUI (only for someone whose runs go there).
+const ComputerNote = dynamic(() => import("@/components/gpu/computer-runner").then((m) => m.ComputerNote), { ssr: false });
+
const NO_SEARCH = new URLSearchParams();
function StatusDot({ ok }: { ok: boolean | undefined }) {
@@ -437,7 +441,7 @@ function YourGpuChip({ viewer }: { viewer: NonNullable<StatusInfo["viewer"]> })
<IntentLink href="/connect" className={cls}>
<span className="flex items-center gap-2">
<StatusDot ok={g.online} /> Your GPU
- <span className="ml-auto">{g.online ? "online" : "offline"}</span>
+ <span className="ml-auto">{g.online ? "online" : g.comfy === "down" ? "ComfyUI not running" : g.comfy === "no-setting" ? "needs a setting" : "offline"}</span>
</span>
{(g.device || vram || g.mode === "computer") && (
<span className="truncate text-[11px]">{[g.mode === "computer" && "Your computer", deviceLabel(g.device), vram && `${vram} VRAM`].filter(Boolean).join(" · ")}</span>
@@ -535,6 +539,7 @@ export function AppSidebar() {
};
const content = useScrollFades<HTMLDivElement>();
const status = useStatus().data;
+ const computer = useViewer().data?.computer === true;
const cloud = status && (status.providers.fal?.configured || status.providers.replicate?.configured);
const comfy = status?.providers.comfyui?.configured;
const mode = useEngineMode();
@@ -610,6 +615,7 @@ export function AppSidebar() {
</Suspense>
</SidebarContent>
<SidebarFooter className="gap-1 border-t border-sidebar-border" onClick={closeOnLink}>
+ {computer && <ComputerNote />}
{status?.viewer ? (
<YourGpuChip viewer={status.viewer} />
) : !status ? (
diff --git a/src/components/gpu/comfy-finder.tsx b/src/components/gpu/comfy-finder.tsx
index 5954baf9..dc189c5f 100644
--- a/src/components/gpu/comfy-finder.tsx
+++ b/src/components/gpu/comfy-finder.tsx
@@ -1,74 +1,15 @@
"use client";
-import { Check, Copy, Loader2, RefreshCw, Search } from "lucide-react";
-import { useCallback, useEffect, useState } from "react";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
+import { Copy } from "lucide-react";
import { copyWithToast } from "@/lib/clipboard";
+import { rememberedComfy } from "./computer-runtime";
/**
- * Finds a ComfyUI on the visitor's own computer, from the browser (the server can't see their
- * machine): /system_stats on 127.0.0.1 at the usual ports. A CORS read that works names the GPU; a
- * port that answers only a no-cors probe is a ComfyUI started without CORS, so it shows the launch
- * flag to add. Reusable (Your GPU, a pre-flight board): it reports what it found and sends nothing
- * to the server. A local address is for the browser only; the server needs a public one (a tunnel).
+ * A ComfyUI's address for "Run from anywhere with a link" (Your GPU): the server calls it, so it needs a public one (a
+ * tunnel in front of the ComfyUI on the person's computer), never one on their computer or network. Finding the
+ * ComfyUI on this computer is the other option's job (this-computer.tsx); nothing here looks for one.
*/
-export const COMFY_PORTS = [8188, 8000, 8189, 8190, 8288];
-const PROBE_MS = 1500;
-
-export type LocalComfy =
- | { state: "found"; url: string; port: number; device?: string; vramBytes?: number; version?: string }
- | { state: "no-cors"; url: string; port: number }
- | { state: "none" };
-
-async function probe(url: string): Promise<LocalComfy | null> {
- const port = Number(new URL(url).port) || (url.startsWith("https:") ? 443 : 80);
- const timed = async (mode: RequestMode) => {
- const ctrl = new AbortController();
- const timer = setTimeout(() => ctrl.abort(), PROBE_MS);
- try {
- return await fetch(`${url}/system_stats`, { mode, signal: ctrl.signal, cache: "no-store", credentials: "omit" });
- } finally {
- clearTimeout(timer);
- }
- };
- try {
- const res = await timed("cors");
- if (!res.ok) return null;
- const s = (await res.json().catch(() => null)) as { system?: { comfyui_version?: string }; devices?: { name?: string; vram_total?: number }[] } | null;
- if (!s?.system) return null;
- const dev = s.devices?.[0];
- return { state: "found", url, port, device: dev?.name, vramBytes: dev?.vram_total, version: s.system.comfyui_version };
- } catch {
- // Blocked by CORS, or nothing there: a no-cors probe tells them apart (an opaque answer means something listens).
- try {
- await timed("no-cors");
- return { state: "no-cors", url, port };
- } catch {
- return null;
- }
- }
-}
-
-/** Look on 127.0.0.1 at COMFY_PORTS, all at once; the first ComfyUI that answers wins (a CORS-blocked one if none does). */
-export async function findLocalComfy(ports = COMFY_PORTS): Promise<LocalComfy> {
- const found = await Promise.all(ports.map((p) => probe(`http://127.0.0.1:${p}`)));
- return found.find((f) => f?.state === "found") ?? found.find((f) => f?.state === "no-cors") ?? { state: "none" };
-}
-
-/** "8188", "localhost:8188", "http://192.168.1.5:8188" or a tunnel's https address → a URL (null when it isn't one). */
-export function comfyAddress(input: string): string | null {
- const s = input.trim().replace(/\/+$/, "");
- if (!s) return null;
- if (/^\d{2,5}$/.test(s)) return `http://127.0.0.1:${s}`;
- try {
- return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : `http://${s}`).toString().replace(/\/+$/, "");
- } catch {
- return null;
- }
-}
-
/** On this computer or its network: the browser can reach it, the server can't. */
export function isLocalAddress(url: string): boolean {
let host: string;
@@ -108,103 +49,17 @@ function CopyLine({ text, label }: { text: string; label: string }) {
);
}
-/**
- * The finder: looks on mount, then shows what it found. `onLocal` hears of a ComfyUI on this
- * computer (for a caller that can use it from the browser); a tunnel address is the caller's to save.
- */
-export function ComfyFinder({ onLocal }: { onLocal?: (found: Extract<LocalComfy, { state: "found" }>) => void }) {
- const [result, setResult] = useState<LocalComfy | null>(null);
- const [busy, setBusy] = useState(true);
- const [typed, setTyped] = useState("");
- const [tested, setTested] = useState<LocalComfy | "bad" | null>(null);
- const origin = typeof window === "undefined" ? "https://fuobe.com" : window.location.origin;
-
- const look = useCallback(async () => {
- setBusy(true);
- const r = await findLocalComfy();
- setResult(r);
- setBusy(false);
- if (r.state === "found") onLocal?.(r);
- }, [onLocal]);
-
- // The first look, on mount (Retry and Look again call look()).
- useEffect(() => {
- let alive = true;
- void findLocalComfy().then((r) => {
- if (!alive) return;
- setResult(r);
- setBusy(false);
- if (r.state === "found") onLocal?.(r);
- });
- return () => {
- alive = false;
- };
- }, [onLocal]);
-
- const testTyped = async () => {
- const url = comfyAddress(typed);
- if (!url) return setTested("bad");
- setTested(null);
- setBusy(true);
- setTested((await probe(url)) ?? { state: "none" });
- setBusy(false);
- };
-
- const shown = tested && tested !== "bad" && tested.state !== "none" ? tested : result;
+/** How to give a ComfyUI a public address: a tunnel on the computer it runs on (its usual port, or the one last found). */
+export function TunnelSteps() {
+ const port = rememberedComfy()?.port ?? 8188;
return (
- <div className="space-y-3 text-[13px]">
- {busy && !shown && (
- <p className="flex items-center gap-2 text-muted-foreground">
- <Loader2 className="size-4 animate-spin" /> Looking for ComfyUI on this computer…
- </p>
- )}
- {shown?.state === "found" && (
- <div className="space-y-2 rounded-xl border border-primary/40 bg-brand-faint p-3">
- <p className="flex items-center gap-2 font-medium">
- <Check className="size-4 text-brand-text" /> Found ComfyUI on port {shown.port}
- </p>
- {(shown.device || shown.vramBytes) && (
- <p className="text-[12px] text-muted-foreground">
- {shown.device ?? "GPU"}
- {gib(shown.vramBytes) ? ` · ${gib(shown.vramBytes)} VRAM` : ""}
- {shown.version ? ` · ComfyUI ${shown.version}` : ""}
- </p>
- )}
- <p className="text-[12px] text-muted-foreground">This studio runs on a server, which can&apos;t reach your computer. Give your ComfyUI a public address with a tunnel, then paste it below:</p>
- <CopyLine text={tunnelCommand(shown.port)} label="tunnel command" />
- <p className="text-[11px] text-muted-foreground">Or ngrok: ngrok http {shown.port}. Use the https address it prints.</p>
- </div>
- )}
- {shown?.state === "no-cors" && (
- <div className="space-y-2 rounded-xl border p-3">
- <p className="font-medium">Something answers on port {shown.port}, but the browser can&apos;t read it</p>
- <p className="text-[12px] text-muted-foreground">Start ComfyUI with this flag so this page can see it, then look again:</p>
- <CopyLine text={`--enable-cors-header ${origin}`} label="ComfyUI launch flag" />
- <Button size="sm" variant="secondary" onClick={() => void look()} disabled={busy}>
- {busy ? <Loader2 className="animate-spin" /> : <RefreshCw />} Retry
- </Button>
- </div>
- )}
- {result?.state === "none" && !(tested && tested !== "bad" && tested.state !== "none") && (
- <div className="space-y-2">
- <p className="font-medium">Where&apos;s your ComfyUI?</p>
- <p className="text-[12px] text-muted-foreground">
- No ComfyUI answered on ports {COMFY_PORTS.join(", ")}. Enter its port or address (localhost, your network, or a tunnel&apos;s https address).
- </p>
- <div className="flex gap-2">
- <Input aria-label="ComfyUI port or address" placeholder="8188 or https://…" value={typed} onChange={(e) => setTyped(e.target.value)} onKeyDown={(e) => e.key === "Enter" && void testTyped()} />
- <Button size="sm" variant="secondary" className="h-9 shrink-0" onClick={() => void testTyped()} disabled={busy || !typed.trim()}>
- {busy ? <Loader2 className="animate-spin" /> : <Search />} Test
- </Button>
- </div>
- {tested === "bad" && <p className="text-[12px] text-destructive">That isn&apos;t a port or an address.</p>}
- {tested && tested !== "bad" && tested.state === "none" && <p className="text-[12px] text-destructive">Nothing answered there as ComfyUI.</p>}
- <Button size="sm" variant="ghost" onClick={() => void look()} disabled={busy}>
- <RefreshCw /> Look again
- </Button>
- </div>
- )}
- <p className="text-[11px] text-muted-foreground">Chrome may ask to let this site reach devices on your local network. Allow it, so this page can look for your ComfyUI.</p>
+ <div className="space-y-2 rounded-xl border p-3 text-[13px]">
+ <p className="font-medium">Give your ComfyUI a public address</p>
+ <p className="text-[12px] text-muted-foreground">On the computer that runs ComfyUI, start a tunnel, then paste the https address it prints below:</p>
+ <CopyLine text={tunnelCommand(port)} label="tunnel command" />
+ <p className="text-[11px] text-muted-foreground">
+ Or ngrok: ngrok http {port}. ComfyUI on another port? Use that port instead of {port}.
+ </p>
</div>
);
}
diff --git a/src/components/gpu/computer-runner.tsx b/src/components/gpu/computer-runner.tsx
index dcbf7b98..0505eb62 100644
--- a/src/components/gpu/computer-runner.tsx
+++ b/src/components/gpu/computer-runner.tsx
@@ -5,68 +5,144 @@ import { Cpu, TriangleAlert } from "lucide-react";
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import { toast } from "sonner";
import { CONNECT_GPU_EVENT, useViewer } from "@/lib/api";
+import type { Generation } from "@/lib/catalog/types";
import { shortGpu } from "@/lib/gpu/readiness";
import { RELAY_WORDS } from "@/lib/relay";
import { cn } from "@/lib/utils";
-import { computerState, jobFor, RESTART_EVENT, startComputerRunner, store, stored, subscribeComputer, takeOverHere, type ComputerState } from "./computer-runtime";
-import { useComputerSupport } from "./use-local-comfy";
+import { computerState, jobFor, RESTART_EVENT, startComputerRunner, store, stored, subscribeComputer, takeOverHere, type ComputerState, type RunnerStart } from "./computer-runtime";
+import { loopbackPermission, useComputerSupport } from "./use-local-comfy";
/**
* "Use the ComfyUI on this computer": while the page is open, one Fuobe tab of this browser runs the person's jobs on
* their ComfyUI (computer-runtime.ts). Mounted once, in the app's providers; it starts only for someone whose runs go
- * to their own computer, and shows a small note while their GPU works, or when ComfyUI needs them.
+ * to their own computer. The sidebar shows its note (ComputerNote) while their GPU works, or when ComfyUI needs them.
*/
+
+/** Why the "Connect your GPU" card opens from here: ComfyUI needs the setting again, find ComfyUI, or allow this browser. */
+export type FindReason = "setting" | "find" | "browser";
+export const openFinder = (reason: FindReason) => window.dispatchEvent(new CustomEvent(CONNECT_GPU_EVENT, { detail: { reason } }));
+
+/**
+ * May this browser reach ComfyUI on this computer without a question nobody explained? Allowed: yes. Told no:
+ * "blocked". It would ask (or doesn't say: Firefox): only a browser that reached ComfyUI before goes on; any other
+ * only listens ("ask") until the person connects from the card, which explains the question first.
+ */
+async function runnerAccess(): Promise<RunnerStart["access"]> {
+ const p = await loopbackPermission();
+ if (p.state === "denied") return "blocked";
+ if (p.state === "granted") return undefined;
+ return stored("reached") ? undefined : "ask";
+}
+
export function ComputerRunnerHost() {
const viewer = useViewer().data;
// A phone or Safari can't reach a ComfyUI: there the runs wait for the computer's own tab.
const support = useComputerSupport();
const computer = viewer?.computer === true && support === "ok";
+ // Where the person's computer last found ComfyUI (a browser that remembers none starts there); read at each start.
+ const port = useRef<number | undefined>(undefined);
+ useEffect(() => {
+ port.current = viewer?.comfyPort;
+ }, [viewer?.comfyPort]);
useEffect(() => {
if (!computer) return;
- let stop = startComputerRunner();
- const again = () => {
- stop();
- stop = startComputerRunner();
+ let alive = true;
+ let stop: (() => void) | null = null;
+ let status: PermissionStatus | undefined;
+ const start = async () => {
+ const access = await runnerAccess();
+ if (!alive) return;
+ stop?.();
+ stop = startComputerRunner({ port: port.current, ...(access && { access }) });
};
+ const again = () => void start();
+ // Started again when ComfyUI moved, the card connected, or the browser's answer changed (Allow, or Block).
window.addEventListener(RESTART_EVENT, again);
+ void loopbackPermission().then((p) => {
+ if (!alive) return;
+ status = p.status;
+ status?.addEventListener("change", again);
+ });
+ void start();
return () => {
+ alive = false;
window.removeEventListener(RESTART_EVENT, again);
- stop();
+ status?.removeEventListener("change", again);
+ stop?.();
};
}, [computer]);
return computer ? <ComputerNews /> : null;
}
-/** "Made on your RTX 5090 in 18 s." once, for the first run this computer finishes. */
-function useFirstRunToast(s: ComputerState) {
+/**
+ * Each job this tab saved: its run's result shows at once (the lists are asked again as soon as the run moves on), and
+ * for the first run this computer ever finishes, "Made on your RTX 5090 in 18 s." once the result is there.
+ */
+function useFinishedJobs(s: ComputerState) {
+ const qc = useQueryClient();
const started = useRef(new Map<string, number>());
+ const followed = useRef(new Set<string>());
useEffect(() => {
if (s.holder !== "this" || !s.view) return;
for (const j of s.view.jobs) {
if (!started.current.has(j.taskId)) started.current.set(j.taskId, Date.now());
- if (j.phase !== "done" || stored("firstRun")) continue;
- store("firstRun", "1");
- const secs = Math.max(1, Math.round((Date.now() - started.current.get(j.taskId)!) / 1000));
+ if (j.phase !== "done" || followed.current.has(j.taskId)) continue;
+ followed.current.add(j.taskId);
+ const secs = Math.max(1, Math.round(((j.endedAt ?? Date.now()) - started.current.get(j.taskId)!) / 1000));
const gpu = shortGpu(s.view.facts?.device);
- toast.success(`Made on your ${gpu || "GPU"} in ${secs} s.`);
+ void (async () => {
+ // The studio marks the run done at its next look (about a second): ask until it has.
+ for (let i = 0; i < 20; i++) {
+ await new Promise((r) => setTimeout(r, i === 0 ? 400 : 750));
+ const g = (await fetch(`/api/generations/${encodeURIComponent(j.generationId)}`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .catch(() => null)) as Pick<Generation, "status"> | null;
+ if (!g || g.status === "queued" || g.status === "running") continue;
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ void qc.invalidateQueries({ queryKey: ["library"] });
+ if (g.status === "succeeded" && !stored("firstRun")) {
+ store("firstRun", "1");
+ toast.success(`Made on your ${gpu || "GPU"} in ${secs} s.`);
+ }
+ return;
+ }
+ })();
}
- }, [s]);
+ }, [s, qc]);
}
-/** The status strip hears at once when this tab starts or stops running the jobs, or ComfyUI comes and goes. */
+/**
+ * The status strip hears at once when this tab starts or stops running the jobs, or ComfyUI comes and goes: now, and
+ * again once the beat that tells the server has landed.
+ */
function useStatusRefresh(s: ComputerState) {
const qc = useQueryClient();
- const key = s.holder === "this" && s.view ? `${s.view.runner}:${s.view.comfy}:${s.view.stopped ?? ""}` : s.holder;
+ const key = s.holder === "this" && s.view ? `${s.view.runner}:${s.view.comfy}:${s.view.access ?? ""}:${s.view.stopped ?? ""}` : s.holder;
useEffect(() => {
void qc.invalidateQueries({ queryKey: ["status"] });
+ const t = setTimeout(() => void qc.invalidateQueries({ queryKey: ["status"] }), 2500);
+ return () => clearTimeout(t);
}, [key, qc]);
}
+/** A run waits while ComfyUI here runs without Fuobe's setting: the card with the fix opens by itself, once. */
+function useSettingPrompt(s: ComputerState) {
+ const opened = useRef(false);
+ const v = s.view;
+ const due = s.holder === "this" && !!v && !v.stopped && !v.access && !v.heldElsewhere && v.comfy === "no-setting" && (v.waiting > 0 || v.jobs.some((j) => j.phase === "sending"));
+ useEffect(() => {
+ if (!due || opened.current) return;
+ opened.current = true;
+ openFinder("setting");
+ }, [due]);
+}
+
function ComputerNews() {
const s = useComputerState();
- useFirstRunToast(s);
+ useFinishedJobs(s);
useStatusRefresh(s);
- return <ComputerPill s={s} />;
+ useSettingPrompt(s);
+ return null;
}
const NONE: ComputerState = { holder: "none", view: null };
@@ -77,59 +153,72 @@ export function useComputerState(): ComputerState {
/**
* The job this browser runs for a run, if any: where it is, its steps, the latest live preview as an image address,
- * and whether this tab runs it or another Fuobe tab does.
+ * whether this tab runs it or another Fuobe tab does, and ComfyUI here as this tab last saw it (`now`: the tile's clock).
*/
-export function useLocalJob(generationId: string) {
+export function useLocalJob(generationId: string, now: number) {
const s = useComputerState();
- const job = jobFor(s, generationId);
+ const job = jobFor(s, generationId, now);
const frame = job?.preview;
const preview = useMemo(() => (frame ? URL.createObjectURL(frame) : null), [frame]);
useEffect(() => () => void (preview && URL.revokeObjectURL(preview)), [preview]);
- return job ? { job, preview, here: s.holder === "this" } : null;
+ return job ? { job, preview, here: s.holder === "this", comfy: s.holder === "this" ? (s.view?.comfy ?? "ok") : "ok" } : null;
}
-function ComputerPill({ s }: { s: ComputerState }) {
+type Note = { text: string; action?: string; go?: () => void; problem: boolean };
+
+/** What the note says now, or nothing: something for the person to do (only while there is work), or the GPU working. */
+function noteOf(s: ComputerState): Note | null {
const v = s.view;
if (s.holder !== "this" || !v || v.stopped) return null;
const working = v.jobs.some((j) => j.phase !== "done" && j.phase !== "failed");
const wanted = working || v.waiting > 0;
- // Something for the person to do (only when there is work: a closed ComfyUI with nothing to run is no news). When
- // another computer runs the jobs, this one's ComfyUI is no news either.
- const problem = !wanted
- ? null
- : v.heldElsewhere
- ? v.comfy === "ok" && v.waiting > 0
- ? { text: "Fuobe on another computer is running your ComfyUI runs.", action: "Run them here instead", go: takeOverHere }
- : null
- : v.comfy === "no-setting"
- ? { text: "ComfyUI is back, but without Fuobe's setting.", action: "Show me how", go: () => window.dispatchEvent(new CustomEvent(CONNECT_GPU_EVENT, { detail: { refind: true } })) }
- : v.comfy === "down"
- ? { text: RELAY_WORDS.comfyDown }
- : null;
- if (!problem && !working) return null;
+ if (!wanted) return null;
+ // Another computer runs the jobs: this one's ComfyUI is no news.
+ if (v.heldElsewhere) return v.comfy === "ok" && !v.access && v.waiting > 0 ? { text: "Fuobe on another computer is running your ComfyUI runs.", action: "Run them here instead", go: takeOverHere, problem: true } : null;
+ if (v.access === "ask") return { text: "Your runs are waiting for your ComfyUI. Run them from this browser?", action: "Connect", go: () => openFinder("browser"), problem: true };
+ if (v.access === "blocked") return { text: "Your browser is blocking Fuobe from reaching ComfyUI on this computer.", action: "Show me how", go: () => openFinder("browser"), problem: true };
+ if (v.comfy === "no-setting") return { text: "ComfyUI is running without Fuobe's setting.", action: "Show me how", go: () => openFinder("setting"), problem: true };
+ if (v.comfy === "down") return { text: RELAY_WORDS.comfyDown, action: "Find my ComfyUI", go: () => openFinder("find"), problem: true };
+ return working ? { text: "Your GPU is working. Keep this tab open.", problem: false } : null;
+}
+
+/**
+ * The note in the sidebar, above "Your GPU": the GPU working ("keep this tab open"), or the one thing to do. It sits in
+ * the sidebar's own space, so it never covers the page; with the sidebar folded, an icon says it.
+ */
+export function ComputerNote() {
+ const note = noteOf(useComputerState());
+ if (!note) return null;
+ const icon = note.problem ? (
+ <TriangleAlert className="size-4 shrink-0 text-amber-600 dark:text-amber-400" />
+ ) : (
+ <span className="relative grid size-4 shrink-0 place-items-center">
+ <Cpu className="size-4 text-brand-text" />
+ <span className="absolute -top-0.5 -right-0.5 size-1.5 animate-pulse rounded-full bg-primary" />
+ </span>
+ );
return (
- <div
- role="status"
- // Top right, under the page's header: the composer and its Generate button sit at the bottom.
- className={cn(
- "fixed top-16 right-4 z-40 flex max-w-[calc(100vw-2rem)] items-center gap-2 rounded-full border bg-background/95 py-1.5 pr-3 pl-2 text-[12px] shadow-lg backdrop-blur",
- problem && "border-amber-500/50",
- )}
- >
- {problem ? (
- <TriangleAlert className="size-4 shrink-0 text-amber-600 dark:text-amber-400" />
- ) : (
- <span className="relative grid size-5 shrink-0 place-items-center">
- <Cpu className="size-4 text-brand-text" />
- <span className="absolute -top-0.5 -right-0.5 size-2 animate-pulse rounded-full bg-primary" />
- </span>
- )}
- <span className="min-w-0 truncate">{problem ? problem.text : "Your GPU is working · keep this tab open"}</span>
- {problem && "action" in problem && problem.action && (
- <button type="button" onClick={problem.go} className="shrink-0 font-medium text-brand-text underline-offset-4 hover:underline">
- {problem.action}
- </button>
- )}
- </div>
+ <>
+ <div role="status" className={cn("flex gap-2 rounded-md border px-2 py-1.5 text-[12px] group-data-[collapsible=icon]:hidden", note.problem ? "border-amber-500/50" : "border-transparent bg-brand-faint")}>
+ {icon}
+ <div className="min-w-0 flex-1">
+ <p className="leading-snug">{note.text}</p>
+ {note.action && (
+ <button type="button" onClick={note.go} className="mt-0.5 font-medium text-brand-text underline-offset-4 hover:underline">
+ {note.action}
+ </button>
+ )}
+ </div>
+ </div>
+ <button
+ type="button"
+ title={note.action ? `${note.text} ${note.action}` : note.text}
+ aria-label={note.text}
+ onClick={note.go}
+ className="hidden size-8 place-items-center self-center rounded-md hover:bg-accent group-data-[collapsible=icon]:grid"
+ >
+ {icon}
+ </button>
+ </>
);
}
diff --git a/src/components/gpu/computer-runtime.ts b/src/components/gpu/computer-runtime.ts
index 324c90fd..e66e53b1 100644
--- a/src/components/gpu/computer-runtime.ts
+++ b/src/components/gpu/computer-runtime.ts
@@ -6,8 +6,10 @@
* component (computer-runner.tsx) starts it and the tiles read its store.
*/
import { COMPUTER_KICK_EVENT } from "@/lib/api";
-import { beatEvery, ComputerRunner, type LocalJob, type RunnerView } from "@/lib/computer-runner";
+import { beatEvery, ComputerRunner, tileJob, type LocalJob, type RunnerView } from "@/lib/computer-runner";
import { loopbackFetch } from "@/lib/gpu/browser-check";
+import { pickLook, portsToLook } from "@/lib/local-comfy";
+import { lookOn } from "./use-local-comfy";
export { COMPUTER_KICK_EVENT };
@@ -18,6 +20,8 @@ const KEYS = {
host: "fuobe.comfy.host",
install: "fuobe.comfy.install",
firstRun: "fuobe.computer.first-run",
+ /** This browser has read the ComfyUI on this computer before (so reaching it asks nothing new). */
+ reached: "fuobe.computer.reached",
} as const;
const memory = new Map<string, string>();
@@ -83,8 +87,11 @@ function set(next: ComputerState) {
for (const fn of listeners) fn();
}
-/** The job this browser runs for a run (its phase, steps and latest preview), wherever its tile is open. */
-export const jobFor = (s: ComputerState, generationId: string): LocalJob | undefined => s.view?.jobs.find((j) => j.generationId === generationId && j.phase !== "done");
+/**
+ * The job this browser runs for a run (its phase, steps and latest preview), wherever its tile is open. A saved one
+ * stays a few seconds, so the tile says it is saving until the run shows its result.
+ */
+export const jobFor = (s: ComputerState, generationId: string, now: number): LocalJob | undefined => (s.view ? tileJob(s.view.jobs, generationId, now) : undefined);
const active = (j: LocalJob) => j.phase !== "done" && j.phase !== "failed";
@@ -123,18 +130,25 @@ const sha256 = async (data: ArrayBuffer) => [...new Uint8Array(await crypto.subt
/** The jobs as another tab gets them (the previews go too: they're Blobs). */
type Heard = { holder: "this"; view: RunnerView } | { holder: "none" };
+/** How the runner starts: the port the server last heard of (when this browser remembers none), and its access. */
+export interface RunnerStart {
+ port?: number;
+ /** This browser may not reach apps on this computer yet ("ask"), or was told no ("blocked"): it only listens. */
+ access?: "ask" | "blocked";
+}
+
/**
* Run this person's jobs from this browser while the page is open: this tab when it gets the lock, else it listens to
* the tab that has it (and takes over when that one closes). Returns the stop.
*/
-export function startComputerRunner(): () => void {
+export function startComputerRunner(o: RunnerStart = {}): () => void {
const stop = new AbortController();
const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel("fuobe-computer") : null;
channel?.addEventListener("message", (e: MessageEvent<Heard>) => {
if (state.holder === "this") return;
set(e.data.holder === "this" ? { holder: "other", view: e.data.view } : { holder: "none", view: null });
});
- const run = () => hold(stop.signal, (view) => channel?.postMessage({ holder: "this", view } satisfies Heard)).finally(() => channel?.postMessage({ holder: "none" } satisfies Heard));
+ const run = () => hold(stop.signal, (view) => channel?.postMessage({ holder: "this", view } satisfies Heard), o).finally(() => channel?.postMessage({ holder: "none" } satisfies Heard));
if (navigator.locks?.request) {
navigator.locks.request("fuobe-runner", { signal: stop.signal }, run).catch(() => {});
} else {
@@ -148,9 +162,11 @@ export function startComputerRunner(): () => void {
}
/** This tab runs the jobs until the signal (or the session ends, or the person disconnects). */
-async function hold(signal: AbortSignal, publish: (v: RunnerView) => void): Promise<void> {
+async function hold(signal: AbortSignal, publish: (v: RunnerView) => void, o: RunnerStart): Promise<void> {
if (signal.aborted) return;
- const where = rememberedComfy() ?? { port: 8188, host: "127.0.0.1" };
+ // Where this browser found ComfyUI last; else where the person's computer said it was (another browser, cleared site
+ // data); else ComfyUI's usual port. When it stops answering there, the runner looks on the other usual ports.
+ const where = rememberedComfy() ?? { port: o.port ?? 8188, host: "127.0.0.1" };
const runner = new ComputerRunner(
{
api: (path, init) => fetch(path, { ...init, credentials: "same-origin" }),
@@ -158,12 +174,19 @@ async function hold(signal: AbortSignal, publish: (v: RunnerView) => void): Prom
socket: (url) => (typeof WebSocket === "function" ? (new WebSocket(url) as never) : null),
sha256,
origin: window.location.origin,
+ find: async (except) => {
+ const looks = await Promise.all(portsToLook().filter((p) => p !== except).map((p) => lookOn(p)));
+ const best = pickLook(looks);
+ return best.state === "none" ? null : { port: best.port, host: best.host };
+ },
+ moved: (port, host) => rememberComfy(port, host),
},
- { device: idFor("device"), port: where.port, host: where.host, clientId: `fuobe-${idFor("client")}` },
+ { device: idFor("device"), port: where.port, host: where.host, clientId: `fuobe-${idFor("client")}`, ...(o.access && { access: o.access }) },
);
let last = 0;
const show = (v: RunnerView) => {
set({ holder: "this", view: { ...v, jobs: [...v.jobs] } });
+ if (v.facts && !stored("reached")) store("reached", "1");
// Other tabs hear it a few times a second at most.
const now = Date.now();
if (now - last > 250 || !v.jobs.some(active)) {
@@ -187,11 +210,14 @@ async function hold(signal: AbortSignal, publish: (v: RunnerView) => void): Prom
window.addEventListener(COMPUTER_KICK_EVENT, kick);
window.addEventListener("pagehide", release);
window.addEventListener("beforeunload", leaving);
+ // ComfyUI here as the server last heard it: a change (closed, back, without the setting) is told at once.
+ let told = runner.view.comfy;
const tick = () => {
const now = Date.now();
- if (!beating && (now >= nextBeat || takeover)) {
+ if (!beating && (now >= nextBeat || takeover || runner.view.comfy !== told)) {
beating = true;
nextBeat = now + beatEvery(runner.view.jobs.some(active));
+ told = runner.view.comfy;
const take = takeover;
takeover = false;
runner
diff --git a/src/components/gpu/connect-choice.tsx b/src/components/gpu/connect-choice.tsx
index 98114147..8474a9fa 100644
--- a/src/components/gpu/connect-choice.tsx
+++ b/src/components/gpu/connect-choice.tsx
@@ -1,19 +1,20 @@
"use client";
import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { ChevronDown, Cpu, Globe, Loader2, Unplug } from "lucide-react";
+import { ChevronDown, Cpu, Globe, Loader2, TriangleAlert, Unplug } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { gib } from "@/components/gpu/comfy-finder";
import { YourGpu } from "@/components/gpu/your-gpu";
import { Button } from "@/components/ui/button";
import { deviceLabel } from "@/lib/gpu/readiness";
+import { useViewer } from "@/lib/api";
import { RELAY_WORDS } from "@/lib/relay";
import { cn } from "@/lib/utils";
import { restartComputerRunner, rememberComfy, rememberedComfy } from "./computer-runtime";
-import { ThisComputer, unsupportedWords } from "./this-computer";
+import { GuardFix, SettingFix, ThisComputer, unsupportedWords } from "./this-computer";
import { lookOn, useComputerSupport } from "./use-local-comfy";
-import { useComputerState } from "./computer-runner";
+import { openFinder, useComputerState, type FindReason } from "./computer-runner";
/**
* "Connect your GPU" for an account: the ComfyUI on this computer first (the quickest way: nothing to install, runs
@@ -22,7 +23,7 @@ import { useComputerState } from "./computer-runner";
*/
export type AccountGpuView =
- | { mode: "computer"; online: boolean; device?: string; vramBytes?: number; version?: string; port?: number; cors?: "exact" | "any" | "other" }
+ | { mode: "computer"; online: boolean; comfy?: "down" | "no-setting"; device?: string; vramBytes?: number; version?: string; port?: number; cors?: "exact" | "any" | "other"; guard?: boolean }
| { mode: "link"; url: string; hasToken: boolean };
async function gpuCall<T>(method: string, body?: unknown): Promise<T> {
@@ -41,30 +42,110 @@ export async function connectThisComputer(): Promise<void> {
await gpuCall("PUT", { mode: "computer" });
}
+/** The owner's: ComfyUI runs on the computer the owner uses (Settings → Where ComfyUI runs). */
+async function connectOwnerComputer(): Promise<void> {
+ const res = await fetch("/api/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ comfyWhere: "computer" }) });
+ if (!res.ok) throw new Error(((await res.json().catch(() => ({}))) as { error?: string }).error ?? `Request failed (${res.status})`);
+}
+
const ABOUT =
- "Fuobe's setting lets the Fuobe page use your ComfyUI. While it's on, other websites could also send work to your ComfyUI if your browser lets them reach apps on this computer. Chrome, Edge and Firefox ask you first. To turn it off, start ComfyUI the usual way.";
+ "Fuobe's setting lets the Fuobe page use your ComfyUI. On its own, it would also let other websites send work to your ComfyUI if your browser lets them reach apps on this computer (Chrome, Edge and Firefox ask you first). Fuobe's guard, a small file in ComfyUI's custom_nodes folder, turns them away. To turn the setting off, start ComfyUI the usual way.";
+
+/**
+ * What this browser knows of the ComfyUI on this computer, when one of its tabs runs the jobs (or would, once allowed):
+ * that tab's own look beats the server's word. Null when this browser doesn't run them (another computer has the jobs,
+ * or no tab of this browser holds them yet).
+ */
+function useHere() {
+ const local = useComputerState();
+ if (local.holder === "other") return { other: true as const };
+ const v = local.holder === "this" ? local.view : null;
+ if (!v || v.stopped || v.heldElsewhere) return null;
+ return { other: false as const, comfy: v.comfy, access: v.access, port: v.port, facts: v.facts };
+}
+
+const Act = ({ children, onClick }: { children: React.ReactNode; onClick: () => void }) => (
+ <button type="button" className="font-medium text-brand-text underline-offset-4 hover:underline" onClick={onClick}>
+ {children}
+ </button>
+);
+
+/** What is wrong with the ComfyUI on this computer, as this browser sees it, with its one fix; elsewhere the server's word. */
+function ComputerProblem({ here, server }: { here: ReturnType<typeof useHere>; server?: "down" | "no-setting" }) {
+ if (here?.other) return <p className="text-[12px] text-muted-foreground">Running in another Fuobe tab of this browser.</p>;
+ if (here) {
+ if (here.access === "ask")
+ return (
+ <p className="text-[12px] text-muted-foreground">
+ This browser hasn&apos;t been allowed to reach ComfyUI yet. <Act onClick={() => openFinder("browser")}>Connect</Act>
+ </p>
+ );
+ if (here.access === "blocked")
+ return (
+ <p className="text-[12px] text-muted-foreground">
+ Your browser is blocking Fuobe from reaching ComfyUI on this computer. <Act onClick={() => openFinder("browser")}>Show me how</Act>
+ </p>
+ );
+ if (here.comfy === "down")
+ return (
+ <p className="text-[12px] text-muted-foreground">
+ ComfyUI isn&apos;t running on this computer. Start it, and Fuobe connects by itself. <Act onClick={() => openFinder("find")}>Find my ComfyUI</Act>
+ </p>
+ );
+ if (here.comfy === "no-setting")
+ return (
+ <div className="mt-2">
+ <SettingFix key={here.port} port={here.port} back={false} again />
+ </div>
+ );
+ return null;
+ }
+ return (
+ <p className="text-[12px] text-muted-foreground">
+ {server === "down" ? "ComfyUI isn't running on your computer. Start it there." : server === "no-setting" ? "ComfyUI on your computer needs Fuobe's setting again. Open Fuobe there to see how." : RELAY_WORDS.noComputer}
+ </p>
+ );
+}
+
+/** "Other websites could also send work to your ComfyUI": the guard isn't in it yet. */
+function NoGuard({ port }: { port: number }) {
+ return (
+ <div className="space-y-1.5">
+ <p className="flex items-start gap-1.5 text-[12px] text-amber-700 dark:text-amber-400">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0" /> Other websites could also send work to your ComfyUI. Add Fuobe&apos;s guard to turn them away:
+ </p>
+ <GuardFix port={port} />
+ </div>
+ );
+}
/** "This computer · RTX 5090 · port 8188 · Ready", another port, a link instead, Disconnect. */
function ComputerStatus({ gpu, onLink }: { gpu: Extract<AccountGpuView, { mode: "computer" }>; onLink: () => void }) {
const qc = useQueryClient();
- const local = useComputerState();
+ const here = useHere();
const [busy, setBusy] = useState(false);
const [about, setAbout] = useState(false);
const [port, setPort] = useState(String(rememberedComfy()?.port ?? gpu.port ?? 8188));
const [note, setNote] = useState<string | null>(null);
- const here = local.holder === "this" && local.view?.comfy === "ok";
- const online = gpu.online || here;
- const facts = [gpu.device && deviceLabel(gpu.device), gib(gpu.vramBytes), (rememberedComfy()?.port ?? gpu.port) && `port ${rememberedComfy()?.port ?? gpu.port}`].filter(Boolean).join(" · ");
+ const [fixPort, setFixPort] = useState<number | null>(null);
+ // A tab of this browser runs the jobs: what it sees now. Elsewhere (a phone, another computer has them): the server.
+ const mine = here && !here.other ? here : null;
+ const online = mine ? mine.comfy === "ok" && !mine.access : gpu.online;
+ const shownPort = mine?.port ?? rememberedComfy()?.port ?? gpu.port;
+ const facts = [gpu.device && deviceLabel(gpu.device), gib(gpu.vramBytes), shownPort && `port ${shownPort}`].filter(Boolean).join(" · ");
+ const guard = mine?.facts ? mine.facts.guard : gpu.guard;
const lookAt = async () => {
const p = Number(port);
if (!Number.isInteger(p) || p < 1 || p > 65535) return setNote("Enter the port ComfyUI shows, like 8188.");
setNote(null);
+ setFixPort(null);
const l = await lookOn(p);
- if (l.state === "found") {
- rememberComfy(p);
- restartComputerRunner();
- setNote(`Found ComfyUI on port ${p}. Fuobe uses it from now on.`);
- } else setNote(l.state === "unreadable" ? `Something answers on port ${p}, but it needs Fuobe's setting. Disconnect, then connect again to see how.` : `Nothing answered on port ${p}.`);
+ if (l.state === "none") return setNote(`Nothing answered on port ${p}.`);
+ // The tab that runs the jobs goes there; it needs the setting first, the fix shows here.
+ rememberComfy(p);
+ restartComputerRunner();
+ if (l.state === "found") setNote(`Found ComfyUI on port ${p}. Fuobe uses it from now on.`);
+ else setFixPort(p);
};
const remove = async () => {
setBusy(true);
@@ -83,13 +164,14 @@ function ComputerStatus({ gpu, onLink }: { gpu: Extract<AccountGpuView, { mode:
<Cpu className="mt-0.5 size-4 shrink-0 text-brand-text" />
<div className="min-w-0 flex-1">
<p className="font-medium">This computer{online ? " · Ready" : ""}</p>
- <p className="truncate text-[12px] text-muted-foreground">{online ? facts || "Your ComfyUI" : RELAY_WORDS.noComputer}</p>
+ {online ? <p className="truncate text-[12px] text-muted-foreground">{facts || "Your ComfyUI"}</p> : <ComputerProblem here={here} server={gpu.comfy} />}
</div>
<Button size="sm" variant="ghost" className="-my-1 h-7" onClick={() => void remove()} disabled={busy}>
{busy ? <Loader2 className="animate-spin" /> : <Unplug />} Disconnect
</Button>
</div>
{gpu.cors === "any" && <p className="text-[12px] text-amber-700 dark:text-amber-400">Your ComfyUI lets every website in. To keep it private, start it with --enable-cors-header {window.location.origin} instead.</p>}
+ {online && guard === false && gpu.cors !== "any" && shownPort && <NoGuard port={shownPort} />}
<div className="flex flex-wrap items-center gap-2">
<span className="text-[12px] text-muted-foreground">ComfyUI on another port?</span>
<input aria-label="ComfyUI's port" inputMode="numeric" className="h-8 w-20 rounded-md border bg-background px-2 text-[13px]" value={port} onChange={(e) => setPort(e.target.value)} onKeyDown={(e) => e.key === "Enter" && void lookAt()} />
@@ -98,6 +180,7 @@ function ComputerStatus({ gpu, onLink }: { gpu: Extract<AccountGpuView, { mode:
</Button>
</div>
{note && <p className="text-[12px] text-muted-foreground">{note}</p>}
+ {fixPort && <SettingFix key={fixPort} port={fixPort} back={false} />}
<div className="flex flex-wrap gap-x-4 gap-y-1 text-[12px]">
<button type="button" className="text-muted-foreground underline-offset-4 hover:text-foreground hover:underline" onClick={onLink}>
Use a link instead
@@ -114,22 +197,34 @@ function ComputerStatus({ gpu, onLink }: { gpu: Extract<AccountGpuView, { mode:
export interface ConnectChoiceProps {
/** Opened from a run: once connected, the run starts by itself. */
fromRun?: boolean;
- /** ComfyUI came back without the setting: find it again, and show the fix. */
- refind?: boolean;
+ /** What that run makes (image, video, audio). */
+ kind?: string;
+ /**
+ * Opened by the note of the tab that runs the jobs: ComfyUI needs the setting again, or doesn't answer (both look at
+ * once), or this browser hasn't been allowed to reach it yet (the browser's question is explained first).
+ */
+ reason?: FindReason;
onStart?: () => void;
onNotNow?: () => void;
}
-export function ConnectChoice({ fromRun, refind, onStart, onNotNow }: ConnectChoiceProps) {
+export function ConnectChoice({ fromRun, kind, reason, onStart, onNotNow }: ConnectChoiceProps) {
const support = useComputerSupport();
- const q = useAccountGpu();
+ // The owner (whose runs go to their own computer when Settings says so) has no account GPU: only the finder.
+ const owner = useViewer().data?.owner === true;
+ const q = useAccountGpu(!owner);
const gpu = q.data?.gpu ?? null;
// Once the person starts finding their ComfyUI, the flow stays on screen through to "connected".
- const [flow, setFlow] = useState(!!refind);
+ const [flow, setFlow] = useState(!!reason);
const [link, setLink] = useState(false);
+ if (owner) {
+ if (support !== "ok") return <p className="text-[13px] text-muted-foreground">{unsupportedWords(support)}</p>;
+ return <ThisComputer connect={connectOwnerComputer} fromRun={fromRun} kind={kind} onStart={onStart} onNotNow={onNotNow} autoLook={reason === "setting" || reason === "find"} again={reason === "setting"} />;
+ }
if (q.isError) return <p className="text-[13px] text-muted-foreground">{q.error.message}</p>;
if (!q.data) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;
if (support !== "ok") {
+ // A phone, Safari, a plain-http page: only the link, and nothing looks for a ComfyUI on this device.
return (
<div className="space-y-4">
<p className="rounded-xl bg-muted px-3 py-2.5 text-[13px] text-muted-foreground">{unsupportedWords(support)}</p>
@@ -158,9 +253,11 @@ export function ConnectChoice({ fromRun, refind, onStart, onNotNow }: ConnectCho
await connectThisComputer();
}}
fromRun={fromRun}
+ kind={kind}
onStart={onStart}
onNotNow={onNotNow}
- autoLook={refind}
+ autoLook={reason === "setting" || reason === "find"}
+ again={reason === "setting"}
/>
</div>
</div>
@@ -233,22 +330,24 @@ export function OwnerComfyWhere({ value, onChange }: { value: string; onChange:
) : computer ? (
<OwnerComputerLine />
) : null}
+ {computer && <p className="text-[12px] text-muted-foreground">Moving ComfyUI to this server stops the runs still going on your computer.</p>}
</div>
);
}
function OwnerComputerLine() {
- const local = useComputerState();
- const facts = local.view?.facts;
- const ready = local.holder === "this" && local.view?.comfy === "ok";
+ const here = useHere();
+ const mine = here && !here.other ? here : null;
+ const facts = mine?.facts;
+ const ready = !!mine && mine.comfy === "ok" && !mine.access;
return (
- <p className="flex items-center gap-2 text-[13px] text-muted-foreground">
- <Cpu className="size-4 shrink-0 text-brand-text" />
- {ready
- ? ["This computer", facts?.device && deviceLabel(facts.device), gib(facts?.vramBytes), `port ${rememberedComfy()?.port ?? 8188}`, "Ready"].filter(Boolean).join(" · ")
- : local.holder === "other"
- ? "This computer · running in another Fuobe tab"
- : `This computer · ${RELAY_WORDS.noComputer}`}
- </p>
+ <div className="flex items-start gap-2 text-[13px] text-muted-foreground">
+ <Cpu className="mt-0.5 size-4 shrink-0 text-brand-text" />
+ <div className="min-w-0 flex-1 space-y-1">
+ <p>{ready && mine ? ["This computer", facts?.device && deviceLabel(facts.device), gib(facts?.vramBytes), `port ${mine.port}`, "Ready"].filter(Boolean).join(" · ") : "This computer"}</p>
+ {!ready && <ComputerProblem here={here} />}
+ {ready && mine && facts?.guard === false && facts.cors !== "any" && <NoGuard port={mine.port} />}
+ </div>
+ </div>
);
}
diff --git a/src/components/gpu/readiness-chip.tsx b/src/components/gpu/readiness-chip.tsx
index 9d6cf64a..0723d300 100644
--- a/src/components/gpu/readiness-chip.tsx
+++ b/src/components/gpu/readiness-chip.tsx
@@ -2,6 +2,7 @@
import { CheckCircle2, Cpu, Download, Layers } from "lucide-react";
import { badgeState, badgeText } from "@/hooks/use-gpu";
+import { useStatus } from "@/lib/api";
import type { Badge } from "@/lib/gpu/types";
import { cn } from "@/lib/utils";
@@ -49,14 +50,19 @@ export function CardChip({ badge, gpu }: { badge: Badge; gpu?: string }) {
);
}
-/** The header pill (StudioHeader, PresetHeader): a button when it opens the guided fix. */
+/**
+ * The header pill (StudioHeader, PresetHeader): a button when it opens the guided fix. A tool that's ready on a GPU that
+ * isn't there right now (ComfyUI closed, without Fuobe's setting, a link that doesn't answer) says that instead.
+ */
export function HeaderPill({ badge, gpu, onOpen, compact }: { badge: Badge; gpu?: string; onOpen?: () => void; compact?: boolean }) {
+ const own = useStatus().data?.viewer?.gpu;
const s = badgeState(badge);
const t = badgeText(badge, gpu);
const tenths = badge[2];
+ const away = s === "ready" && !(badge[3] & 4) && own?.connected && !own.online ? (own.comfy === "down" ? "ComfyUI isn't running" : own.comfy === "no-setting" ? "ComfyUI needs a setting" : "Your GPU is offline") : null;
const label =
- s === "ready" ? (badge[3] & 4 ? "Runs on any computer" : "Ready on your GPU") : s === "gpu" ? "Needs a bigger GPU" : s === "unsupported" ? "Not on your GPU yet" : `Set up${tenths ? ` · ${tenths / 10} GB` : ""}`;
- const Icon = s === "ready" ? CheckCircle2 : s === "gpu" ? Cpu : s === "unsupported" ? Layers : Download;
+ away ?? (s === "ready" ? (badge[3] & 4 ? "Runs on any computer" : "Ready on your GPU") : s === "gpu" ? "Needs a bigger GPU" : s === "unsupported" ? "Not on your GPU yet" : `Set up${tenths ? ` · ${tenths / 10} GB` : ""}`);
+ const Icon = away ? Cpu : s === "ready" ? CheckCircle2 : s === "gpu" ? Cpu : s === "unsupported" ? Layers : Download;
const cls = cn(
"inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[12px] font-medium",
s === "ready" ? "bg-secondary text-foreground" : s === "almost" || s === "setup" ? "bg-highlight text-highlight-foreground" : "bg-muted text-muted-foreground",
@@ -64,7 +70,7 @@ export function HeaderPill({ badge, gpu, onOpen, compact }: { badge: Badge; gpu?
);
const inner = (
<>
- <Icon aria-hidden className={cn("size-3.5", s === "ready" && "text-success")} />
+ <Icon aria-hidden className={cn("size-3.5", s === "ready" && !away && "text-success")} />
<span className={cn(compact && "max-sm:sr-only")}>{label}</span>
</>
);
diff --git a/src/components/gpu/this-computer.tsx b/src/components/gpu/this-computer.tsx
index 475f5083..1297fd52 100644
--- a/src/components/gpu/this-computer.tsx
+++ b/src/components/gpu/this-computer.tsx
@@ -1,25 +1,29 @@
"use client";
import { useQueryClient } from "@tanstack/react-query";
-import { Check, ChevronDown, Copy, Download, Loader2, MonitorSmartphone, RefreshCw, Search, TriangleAlert } from "lucide-react";
+import { Check, ChevronDown, Copy, Download, Loader2, MonitorSmartphone, RefreshCw, Search, ShieldCheck, TriangleAlert } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { gib } from "@/components/gpu/comfy-finder";
+import { useNow } from "@/components/studio/use-now";
import type { ReadinessView } from "@/hooks/use-gpu";
import { copyWithToast } from "@/lib/clipboard";
+import { GUARD_FILE_NAME, GUARD_SOURCE, isGuard } from "@/lib/comfy-guard";
import { corsFlag, fixFor, guessInstall, installFromStats, platformOf, startFile, START_FILE_NAME, type ComfyInstall } from "@/lib/comfy-install";
-import { checkThisComputer, sendCheck } from "@/lib/gpu/browser-check";
+import { checkThisComputer, loopbackFetch, sendCheck } from "@/lib/gpu/browser-check";
import { deviceLabel } from "@/lib/gpu/readiness";
-import { statsFacts, typedPort, type SystemStats } from "@/lib/local-comfy";
+import { localBase, statsFacts, typedPort, type SystemStats } from "@/lib/local-comfy";
+import { madeNoun } from "@/lib/relay";
import { cn } from "@/lib/utils";
-import { rememberComfy, rememberedComfy, store, stored } from "./computer-runtime";
+import { computerState, rememberComfy, rememberedComfy, restartComputerRunner, store, stored } from "./computer-runtime";
import { useLocalComfy, type Finder } from "./use-local-comfy";
/**
* "Use the ComfyUI on this computer": finds the person's ComfyUI from this page, gives the one fix its install needs
- * (a start file, a setting, a command), notices by itself when ComfyUI comes back with it, connects, checks what it
- * has, and, when it was opened from a run, starts that run. Every state has its own screen and words (DESIGN 9.1).
+ * (a start file, a setting, a command) with Fuobe's guard, notices by itself when ComfyUI comes back with it, connects,
+ * checks what it has, and, when it was opened from a run, starts that run. Every state has its own screen and words
+ * (DESIGN 9.1).
*/
const INSTALLS: { id: ComfyInstall; label: string }[] = [
@@ -93,29 +97,88 @@ const UNSUPPORTED: Record<"safari" | "phone" | "http", string> = {
export const unsupportedWords = (why: "safari" | "phone" | "http") => UNSUPPORTED[why];
-/** The fix for the install the person has: a start file, a setting in an app, or a command. */
-function SettingFix({ port, back }: { port: number; back: boolean }) {
- const [install, setInstall] = useState<ComfyInstall>(() => (stored("install") as ComfyInstall | null) ?? guessInstall(port, platformOf(nav())));
+/** Save a file the page made (the start file, the guard). */
+function save(name: string, text: string) {
+ const url = URL.createObjectURL(new Blob([text], { type: "application/octet-stream" }));
+ const a = Object.assign(document.createElement("a"), { href: url, download: name });
+ document.body.append(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 10_000);
+}
+
+const installOf = (port: number): ComfyInstall => (stored("install") as ComfyInstall | null) ?? guessInstall(port, platformOf(nav()));
+
+/**
+ * Fuobe's guard, for the person to add: the start file does it on Windows (portable, Easy-Install); for the other
+ * installs, the file and where it goes. ComfyUI loads it at its next start.
+ */
+export function GuardFix({ port, install = installOf(port) }: { port: number; install?: ComfyInstall }) {
+ const fix = fixFor(install, origin(), port);
+ if (fix.startFile) {
+ return (
+ <Button size="sm" variant="secondary" onClick={() => save(START_FILE_NAME, startFile(port, origin()))}>
+ <Download /> Download start file
+ </Button>
+ );
+ }
+ return (
+ <div className="space-y-1.5">
+ <Button size="sm" variant="secondary" onClick={() => save(GUARD_FILE_NAME, GUARD_SOURCE)}>
+ <Download /> Download Fuobe&apos;s guard
+ </Button>
+ <p className="text-[12px] text-muted-foreground">{fix.guard} Then restart ComfyUI.</p>
+ </div>
+ );
+}
+
+/**
+ * The fix for the install the person has: a start file, a setting in an app, or a command; and, before it, what the
+ * setting does to other websites and the guard that keeps them out. `back`: ComfyUI restarted, still without it.
+ * `again`: it had the setting before (started the usual way this time). `others`: more ports where something answers.
+ */
+export function SettingFix({ port, back, again, others, onChoose }: { port: number; back: boolean; again?: boolean; others?: number[]; onChoose?: (port: number) => void }) {
+ const [install, setInstall] = useState<ComfyInstall>(() => installOf(port));
const [choosing, setChoosing] = useState(false);
const [yourself, setYourself] = useState(false);
- const fix = fixFor(install, origin());
- const download = () => {
- const url = URL.createObjectURL(new Blob([startFile(port, origin())], { type: "application/octet-stream" }));
- const a = Object.assign(document.createElement("a"), { href: url, download: START_FILE_NAME });
- document.body.append(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 10_000);
- };
+ const fix = fixFor(install, origin(), port);
+ // ComfyUI's usual port, or the one it was found on before, is surely ComfyUI; another app may answer on another one
+ // (8000 is a common default).
+ const known = port === 8188 || rememberedComfy()?.port === port;
+ const heading = back
+ ? "ComfyUI is back, but without the setting yet."
+ : again
+ ? "ComfyUI is running, but without Fuobe's setting this time."
+ : known
+ ? "Found ComfyUI. It needs one setting to work with Fuobe."
+ : `Something answers on port ${port}. If it's ComfyUI, it needs one setting to work with Fuobe.`;
return (
<div className="space-y-3">
<div>
- <p className="text-[15px] font-medium">{back ? "ComfyUI is back, but without the setting yet." : "Found ComfyUI. It needs one setting to work with Fuobe."}</p>
+ <p className="text-[15px] font-medium">{heading}</p>
<p className="mt-1 text-[13px] text-muted-foreground">{fix.lead}</p>
+ {back && <p className="mt-1 text-[12px] text-muted-foreground">The address must be exactly {origin()}, with nothing after it.</p>}
+ {again && fix.startFile && <p className="mt-1 text-[12px] text-muted-foreground">Next time, start ComfyUI with {START_FILE_NAME} (next to ComfyUI): it has the setting.</p>}
</div>
+ {!!others?.length && onChoose && (
+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] text-muted-foreground">
+ Something answers on {others.length === 1 ? `port ${others[0]}` : `ports ${others.join(", ")}`} too. Is ComfyUI there?
+ {others.map((p) => (
+ <button key={p} type="button" onClick={() => onChoose(p)} className="font-medium text-brand-text underline-offset-4 hover:underline">
+ Use port {p}
+ </button>
+ ))}
+ </p>
+ )}
+ <p className="flex items-start gap-1.5 rounded-lg bg-muted/60 px-2.5 py-2 text-[12px] text-muted-foreground">
+ <ShieldCheck className="mt-0.5 size-3.5 shrink-0 text-brand-text" />
+ {fix.startFile
+ ? "On its own, this setting would also let other websites send work to your ComfyUI. The start file adds Fuobe's guard, which turns them away."
+ : "On its own, this setting would also let other websites send work to your ComfyUI. Add Fuobe's guard too: it turns them away."}
+ </p>
{fix.startFile ? (
<>
- <Button className="h-11 sm:h-9" onClick={download}>
+ <Button className="h-11 sm:h-9" onClick={() => save(START_FILE_NAME, startFile(port, origin()))}>
<Download /> Download start file
</Button>
<p className="text-[12px] text-muted-foreground">
@@ -129,6 +192,7 @@ function SettingFix({ port, back }: { port: number; back: boolean }) {
<div className="mt-2 space-y-1.5">
<p className="text-[12px] text-muted-foreground">Add this to the end of the line that starts ComfyUI in your start file, then start ComfyUI again:</p>
<CopyLine text={corsFlag(origin())} label="the setting" />
+ <GuardFix port={port} install="terminal" />
</div>
)}
</div>
@@ -137,6 +201,8 @@ function SettingFix({ port, back }: { port: number; back: boolean }) {
<>
<CopyLine text={fix.copy} label={install === "desktop" ? "the address" : "the setting"} />
{fix.path && <p className="text-[12px] text-muted-foreground">{fix.path.join(" → ")}</p>}
+ {fix.example && <p className="text-[12px] text-muted-foreground">For example: <code className="font-mono">{fix.example}</code></p>}
+ <GuardFix port={port} install={install} />
</>
)}
<div>
@@ -191,7 +257,7 @@ function OtherPort({ onLook, missed }: { onLook: (port: number, host: string) =>
);
}
-type Connected = { port: number; stats: SystemStats; board?: ReadinessView | null; checkFailed?: boolean };
+type Connected = { port: number; stats: SystemStats; guard: boolean; board?: ReadinessView | null; checkFailed?: boolean };
function readyLine(board: ReadinessView | null | undefined): string | null {
const studios = board?.report?.studios;
@@ -202,8 +268,8 @@ function readyLine(board: ReadinessView | null | undefined): string | null {
}
/** The connected screen: the GPU, what's ready, and the run starting (when it was opened from one). */
-function Celebration({ c, fromRun, onStart, onNotNow }: { c: Connected; fromRun?: boolean; onStart?: () => void; onNotNow?: () => void }) {
- const facts = statsFacts(c.stats, origin());
+function Celebration({ c, fromRun, kind, onStart, onNotNow }: { c: Connected; fromRun?: boolean; kind?: string; onStart?: () => void; onNotNow?: () => void }) {
+ const facts = statsFacts(c.stats, origin(), c.guard);
const gpu = [facts.device && deviceLabel(facts.device), gib(facts.vramBytes), facts.version && `ComfyUI ${facts.version}`].filter(Boolean).join(" · ");
const ready = readyLine(c.board);
const checked = c.board !== undefined || c.checkFailed;
@@ -220,6 +286,8 @@ function Celebration({ c, fromRun, onStart, onNotNow }: { c: Connected; fromRun?
const t = setTimeout(() => onStart?.(), 1200);
return () => clearTimeout(t);
}, [starting, stopped, onStart]);
+ // The run about to start stays this page's: what's ready is a link once it has started, or when there is none.
+ const waitingRun = fromRun && !stopped;
return (
<div className="space-y-3 rounded-2xl bg-brand-faint p-4">
<div className="flex items-center gap-3">
@@ -231,13 +299,24 @@ function Celebration({ c, fromRun, onStart, onNotNow }: { c: Connected; fromRun?
{gpu && <p className="truncate text-[13px] text-muted-foreground">{gpu}</p>}
</div>
</div>
- {facts.cors === "any" && (
+ {facts.cors === "any" ? (
<div className="space-y-1.5 text-[12px]">
<p className="flex items-center gap-1.5 text-amber-700 dark:text-amber-400">
<TriangleAlert className="size-3.5" /> Your ComfyUI lets every website in. To keep it private, use {origin()} instead:
</p>
<CopyLine text={corsFlag(origin())} label="the setting" />
</div>
+ ) : c.guard ? (
+ <p className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
+ <ShieldCheck className="size-3.5 text-brand-text" /> Fuobe&apos;s guard keeps other websites out of your ComfyUI.
+ </p>
+ ) : (
+ <div className="space-y-1.5 text-[12px]">
+ <p className="flex items-start gap-1.5 text-amber-700 dark:text-amber-400">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0" /> Other websites could also send work to your ComfyUI. Add Fuobe&apos;s guard to turn them away:
+ </p>
+ <GuardFix port={c.port} />
+ </div>
)}
<p className="text-[13px]">
{!checked ? (
@@ -247,15 +326,25 @@ function Celebration({ c, fromRun, onStart, onNotNow }: { c: Connected; fromRun?
) : ready ? (
<>
{ready}.{" "}
- <a href="/connect" className="text-brand-text underline-offset-4 hover:underline">
- See them
- </a>
+ {!waitingRun && (
+ <a href="/connect" className="text-brand-text underline-offset-4 hover:underline">
+ See them
+ </a>
+ )}
</>
) : null}
</p>
- {fromRun && !stopped ? (
+ {waitingRun ? (
<div className="flex items-center justify-between gap-2">
- <p className="flex items-center gap-2 text-[13px] text-muted-foreground">{starting ? <><Loader2 className="size-3.5 animate-spin" /> Starting your picture…</> : "Your run starts in a moment."}</p>
+ <p className="flex items-center gap-2 text-[13px] text-muted-foreground">
+ {starting ? (
+ <>
+ <Loader2 className="size-3.5 animate-spin" /> Starting your {madeNoun(kind)}…
+ </>
+ ) : (
+ "Your run starts in a moment."
+ )}
+ </p>
<Button
size="sm"
variant="ghost"
@@ -279,17 +368,28 @@ export interface ThisComputerProps {
connect: () => Promise<void>;
/** Opened from a run that needs a GPU: it starts by itself once connected. */
fromRun?: boolean;
+ /** What that run makes (image, video, audio). */
+ kind?: string;
/** Start the run (fromRun), then close. */
onStart?: () => void;
onNotNow?: () => void;
- /** Look at once (Settings, after the person picked this option). */
+ /** Look at once (Settings, after the person picked this option; ComfyUI needs the setting again). */
autoLook?: boolean;
+ /** ComfyUI had Fuobe's setting before, and runs without it now (the fix says so). */
+ again?: boolean;
}
+/** Is Fuobe's guard in this ComfyUI (it answers at /fuobe/guard)? */
+const guardAt = (port: number, host: string) =>
+ loopbackFetch(`${localBase(port, host)}/fuobe/guard`, { credentials: "omit", cache: "no-store" }).then(
+ (r) => (r.ok ? r.json().then(isGuard, () => false) : false),
+ () => false,
+ );
+
/** The whole flow, from "Find my ComfyUI" to connected. */
-export function ThisComputer({ connect, fromRun, onStart, onNotNow, autoLook }: ThisComputerProps) {
+export function ThisComputer({ connect, fromRun, kind, onStart, onNotNow, autoLook, again }: ThisComputerProps) {
const qc = useQueryClient();
- const { state, look } = useLocalComfy(true);
+ const { state, look, choose } = useLocalComfy(true);
const [done, setDone] = useState<Connected | null>(null);
const [error, setError] = useState<string | null>(null);
const connecting = useRef<string | null>(null);
@@ -312,9 +412,14 @@ export function ThisComputer({ connect, fromRun, onStart, onNotNow, autoLook }:
try {
await connect();
rememberComfy(port, host);
+ store("reached", "1");
store("install", installFromStats(stats, port, platformOf(nav())));
+ // The tab that runs the jobs goes there now (another port, or a browser that only listened until now).
+ const running = computerState().view;
+ if (running && (running.port !== port || running.access)) restartComputerRunner();
+ const guard = await guardAt(port, host);
setError(null);
- setDone({ port, stats });
+ setDone({ port, stats, guard });
void qc.invalidateQueries({ queryKey: ["viewer"] });
void qc.invalidateQueries({ queryKey: ["account-gpu"] });
try {
@@ -322,9 +427,9 @@ export function ThisComputer({ connect, fromRun, onStart, onNotNow, autoLook }:
qc.setQueryData(["gpu", "readiness"], board);
void qc.invalidateQueries({ queryKey: ["gpu", "badges"] });
void qc.invalidateQueries({ queryKey: ["gpu", "plan"] });
- setDone({ port, stats, board });
+ setDone({ port, stats, guard, board });
} catch {
- setDone({ port, stats, checkFailed: true });
+ setDone({ port, stats, guard, checkFailed: true });
}
} catch (e) {
connecting.current = null;
@@ -333,23 +438,40 @@ export function ThisComputer({ connect, fromRun, onStart, onNotNow, autoLook }:
})();
}, [state, connect, qc]);
- if (done) return <Celebration c={done} fromRun={fromRun} onStart={onStart} onNotNow={onNotNow} />;
+ if (done) return <Celebration c={done} fromRun={fromRun} kind={kind} onStart={onStart} onNotNow={onNotNow} />;
return (
<div className="space-y-3 text-[13px]">
- <Screen state={state} look={look} />
+ <Screen state={state} look={look} choose={choose} again={again} />
{error && <p className="text-[12px] text-destructive">{error}</p>}
</div>
);
}
-function Screen({ state, look }: { state: Finder; look: ReturnType<typeof useLocalComfy>["look"] }) {
- const [since, setSince] = useState(0);
- // "Still waiting" after two minutes.
- useEffect(() => {
- if (state.s !== "waiting") return;
- const t = setInterval(() => setSince(Date.now() - state.since), 5000);
- return () => clearInterval(t);
- }, [state]);
+/** Waiting for ComfyUI to start; after two minutes, what to check. */
+function WaitingScreen({ port, since, onLook }: { port: number; since: number; onLook: () => void }) {
+ const now = useNow(1000);
+ const long = now - since >= 120_000;
+ return (
+ <div className="space-y-2">
+ <p className="flex items-center gap-2 font-medium">
+ <Loader2 className="size-4 animate-spin" /> Waiting for ComfyUI to start…
+ </p>
+ {!long ? (
+ <p className="text-[12px] text-muted-foreground">This usually takes 10 to 30 seconds.</p>
+ ) : (
+ <div className="space-y-2 text-[12px] text-muted-foreground">
+ <p>Still waiting. Is ComfyUI&apos;s window open? It says &ldquo;To see the GUI go to: http://127.0.0.1:{port}&rdquo; when it&apos;s ready.</p>
+ <p>Check that the address is exactly {origin()}, with nothing after it.</p>
+ <Button size="sm" variant="secondary" onClick={onLook}>
+ <RefreshCw /> Look again
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function Screen({ state, look, choose, again }: { state: Finder; look: ReturnType<typeof useLocalComfy>["look"]; choose: (port: number) => void; again?: boolean }) {
const lookAt = (port: number, host: string) => void look({ ports: [{ port, host }] });
switch (state.s) {
case "unsupported":
@@ -383,26 +505,9 @@ function Screen({ state, look }: { state: Finder; look: ReturnType<typeof useLoc
</p>
);
case "needs-setting":
- return <SettingFix port={state.port} back={state.back} />;
+ return <SettingFix key={state.port} port={state.port} back={state.back} again={again} others={state.others} onChoose={choose} />;
case "waiting":
- return (
- <div className="space-y-2">
- <p className="flex items-center gap-2 font-medium">
- <Loader2 className="size-4 animate-spin" /> Waiting for ComfyUI to start…
- </p>
- {since < 120_000 ? (
- <p className="text-[12px] text-muted-foreground">This usually takes 10 to 30 seconds.</p>
- ) : (
- <div className="space-y-2 text-[12px] text-muted-foreground">
- <p>Still waiting. Is ComfyUI&apos;s window open? It says &ldquo;To see the GUI go to: http://127.0.0.1:{state.port}&rdquo; when it&apos;s ready.</p>
- <p>Check that the address is exactly {origin()}, with nothing after it.</p>
- <Button size="sm" variant="secondary" onClick={() => lookAt(state.port, "127.0.0.1")}>
- <RefreshCw /> Look again
- </Button>
- </div>
- )}
- </div>
- );
+ return <WaitingScreen port={state.port} since={state.since} onLook={() => lookAt(state.port, "127.0.0.1")} />;
case "none":
return (
<div className="space-y-3">
diff --git a/src/components/gpu/use-local-comfy.ts b/src/components/gpu/use-local-comfy.ts
index 50030dda..8884fa4e 100644
--- a/src/components/gpu/use-local-comfy.ts
+++ b/src/components/gpu/use-local-comfy.ts
@@ -2,32 +2,18 @@
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
import { loopbackFetch } from "@/lib/gpu/browser-check";
-import { browserSupport, localBase, pageCanReach, pickLook, portsToLook, type PortLook, type SystemStats } from "@/lib/local-comfy";
+import { browserSupport, localBase, pageCanReach, portsToLook, sameFinder, settled, type Finder, type PortLook, type SystemStats } from "@/lib/local-comfy";
import { rememberedComfy } from "./computer-runtime";
/**
* Finding the ComfyUI on this computer from the page ("Use the ComfyUI on this computer"). It looks at the ports
* ComfyUI uses (the one that answered last first), tells a ComfyUI it can read from one that answers without Fuobe's
- * setting, and, while the card is open and the tab is in view, looks again quietly: every 2 s while it waits for
- * ComfyUI to come back with the setting, every 5 s while nothing answers. It never looks on its own while the browser
- * would still ask (Chrome's advice): the person's click does the first look.
+ * setting, and, while the card is open and the tab is in view, looks again quietly at every port: every 2 s while it
+ * waits for ComfyUI to come back with the setting, every 5 s while nothing answers. It never looks on its own while the
+ * browser would still ask (Chrome's advice): the person's click does the first look.
*/
-export type Finder =
- /** The browser will ask to let Fuobe reach apps on this computer: a click starts the first look. */
- | { s: "start" }
- | { s: "looking" }
- /** Found and readable: the caller connects. */
- | { s: "found"; port: number; host: string; stats: SystemStats }
- /** ComfyUI answers but can't be read: it needs the setting (`back`: it restarted, still without it). */
- | { s: "needs-setting"; port: number; back: boolean }
- /** The port went quiet after it needed the setting: ComfyUI is restarting. */
- | { s: "waiting"; port: number; since: number }
- | { s: "none"; missed?: number }
- /** The browser keeps Fuobe from reaching apps on this computer. */
- | { s: "blocked" }
- /** This browser or page can't: Safari, a phone, or a studio on plain http at a network address. */
- | { s: "unsupported"; why: "safari" | "phone" | "http" };
+export type { Finder };
const LOOK_MS = 1500;
@@ -61,14 +47,18 @@ export async function lookOn(port: number, host = "127.0.0.1"): Promise<PortLook
type Permission = "granted" | "prompt" | "denied" | "unknown";
-/** Chrome's "Apps on device" permission for this site ("unknown" where the browser doesn't say: Firefox). */
-async function loopbackPermission(): Promise<{ state: Permission; status?: PermissionStatus }> {
- try {
- const status = await navigator.permissions.query({ name: "loopback-network" as PermissionName });
- return { state: status.state as Permission, status };
- } catch {
- return { state: "unknown" };
+/**
+ * Chrome's "Apps on device" permission for this site (its newer name, then the one before it), or "unknown" where the
+ * browser doesn't say (Firefox).
+ */
+export async function loopbackPermission(): Promise<{ state: Permission; status?: PermissionStatus }> {
+ for (const name of ["loopback-network", "local-network-access"]) {
+ try {
+ const status = await navigator.permissions.query({ name: name as PermissionName });
+ return { state: status.state as Permission, status };
+ } catch {}
}
+ return { state: "unknown" };
}
const NARROW = "(max-width: 767px)";
@@ -100,14 +90,17 @@ export function useLocalComfy(active: boolean) {
}, [state]);
const busy = useRef(false);
+ /** The screen for what the looks found; the same state (no new render) when nothing changed. */
const settle = useCallback((looks: PortLook[], port?: number) => {
- const best = pickLook(looks, rememberedComfy()?.port);
const was = cur.current;
- if (best.state === "found") return setState({ s: "found", port: best.port, host: best.host ?? "127.0.0.1", stats: best.stats });
- if (best.state === "unreadable") return setState({ s: "needs-setting", port: best.port, back: was.s === "waiting" || (was.s === "needs-setting" && was.back) });
- // Nothing answers: right after it needed the setting, that's ComfyUI restarting.
- if (was.s === "needs-setting" || (was.s === "waiting" && was.port === port)) return setState({ s: "waiting", port: was.port, since: was.s === "waiting" ? was.since : Date.now() });
- setState({ s: "none", ...(port && { missed: port }) });
+ const next = settled(was, looks, rememberedComfy()?.port, port, Date.now());
+ if (!sameFinder(was, next)) setState(next);
+ }, []);
+
+ /** "My ComfyUI is on that port": the fix and the quiet looks follow it. */
+ const choose = useCallback((port: number) => {
+ const was = cur.current;
+ if (was.s === "needs-setting") setState({ s: "needs-setting", port, back: false, others: [...new Set([was.port, ...(was.others ?? [])])].filter((p) => p !== port) });
}, []);
/** Look on every port (or the ones given), then say what was found. `quiet`: keep the screen as it is meanwhile. */
@@ -152,21 +145,14 @@ export function useLocalComfy(active: boolean) {
};
}, [active, support, look]);
- // Quiet looks while it waits for ComfyUI (with the setting) or for any ComfyUI to start.
+ // Quiet looks at every port while it waits for ComfyUI (with the setting: a readable ComfyUI on any port connects) or
+ // for any ComfyUI to start.
+ const every = state.s === "needs-setting" || state.s === "waiting" ? 2000 : state.s === "none" ? 5000 : 0;
useEffect(() => {
- if (!active) return;
- const s = state;
- // One port while it waits for that ComfyUI to come back; every port while nothing answers.
- const port = s.s === "needs-setting" || s.s === "waiting" ? s.port : undefined;
- const every = port ? 2000 : s.s === "none" ? 5000 : 0;
- if (!every) return;
- const id = setInterval(() => {
- if (!visible()) return;
- const remembered = rememberedComfy();
- void look({ quiet: true, ...(port && { ports: [{ port, host: remembered && remembered.port === port ? remembered.host : "127.0.0.1" }] }) });
- }, every);
+ if (!active || !every) return;
+ const id = setInterval(() => visible() && void look({ quiet: true }), every);
return () => clearInterval(id);
- }, [active, state, look]);
+ }, [active, every, look]);
- return { state: support !== "ok" ? ({ s: "unsupported", why: support } as Finder) : state, look, support };
+ return { state: support !== "ok" ? ({ s: "unsupported", why: support } as Finder) : state, look, choose, support };
}
diff --git a/src/components/gpu/your-gpu.tsx b/src/components/gpu/your-gpu.tsx
index 224e5e58..5235fb07 100644
--- a/src/components/gpu/your-gpu.tsx
+++ b/src/components/gpu/your-gpu.tsx
@@ -4,7 +4,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Cpu, Loader2, Unplug } from "lucide-react";
import { useId, useState } from "react";
import { toast } from "sonner";
-import { ComfyFinder, gib, isLocalAddress } from "@/components/gpu/comfy-finder";
+import { gib, isLocalAddress, TunnelSteps } from "@/components/gpu/comfy-finder";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -34,7 +34,7 @@ async function call<T>(method: string, body?: unknown, test = false): Promise<T>
/**
* "Your GPU" (public sign-up): an account's own ComfyUI, where its runs go (never this studio's keys
* or GPU). The server calls it, so it needs a public address: a Cloudflare Tunnel or ngrok in front
- * of a local ComfyUI. The finder looks for one on this computer and shows the tunnel command.
+ * of a local ComfyUI. Nothing here looks for a ComfyUI on this device: it shows the tunnel command.
*/
export function YourGpu() {
const qc = useQueryClient();
@@ -105,7 +105,7 @@ export function YourGpu() {
</Button>
</div>
) : (
- <ComfyFinder />
+ <TunnelSteps />
)}
<div className="space-y-3">
<div className="space-y-1.5">
diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsx
index d8310d6f..dca0c830 100644
--- a/src/components/guest-prompt.tsx
+++ b/src/components/guest-prompt.tsx
@@ -5,6 +5,7 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { Suspense, useCallback, useEffect, useState } from "react";
import { ConnectChoice } from "@/components/gpu/connect-choice";
+import type { FindReason } from "@/components/gpu/computer-runner";
import { takeGpuRetry } from "@/hooks/use-gpu";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -23,9 +24,9 @@ export function GuestPrompt() {
// The last card stays while the dialog animates out.
const [card, setCard] = useState<RefusalCard | null>(null);
const [open, setOpen] = useState(false);
- // ComfyUI came back without Fuobe's setting (the runner's note): find it again and show the fix.
- const [refind, setRefind] = useState(false);
- const [retry, setRetry] = useState<{ retry: () => void } | null>(null);
+ // Opened by the runner's note: ComfyUI needs Fuobe's setting again, find ComfyUI, or let this browser reach it.
+ const [reason, setReason] = useState<FindReason | undefined>(undefined);
+ const [retry, setRetry] = useState<{ retry: () => void; kind?: string } | null>(null);
const close = useCallback(() => {
setOpen(false);
setRetry(null);
@@ -45,7 +46,7 @@ export function GuestPrompt() {
const r = takeGpuRetry();
if (!show("gpu")) return;
setRetry(r);
- setRefind((e as CustomEvent<{ refind?: boolean } | undefined>).detail?.refind === true);
+ setReason((e as CustomEvent<{ reason?: FindReason } | undefined>).detail?.reason);
};
window.addEventListener(GUEST_PROMPT_EVENT, guest);
window.addEventListener(CONNECT_GPU_EVENT, gpu);
@@ -67,12 +68,13 @@ export function GuestPrompt() {
<div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">
<Cpu className="size-5" />
</div>
- <DialogTitle>{refind ? "Your ComfyUI needs Fuobe's setting again" : "Connect your GPU to run this"}</DialogTitle>
+ <DialogTitle>{TITLES[reason ?? "run"]}</DialogTitle>
<DialogDescription>Fuobe runs this on the ComfyUI on your computer. It&apos;s free and private.</DialogDescription>
</DialogHeader>
<ConnectChoice
fromRun={!!retry}
- refind={refind}
+ kind={retry?.kind}
+ reason={reason}
onStart={() => {
const r = retry;
close();
@@ -110,6 +112,13 @@ export function GuestPrompt() {
);
}
+const TITLES: Record<FindReason | "run", string> = {
+ run: "Connect your GPU to run this",
+ setting: "Your ComfyUI needs Fuobe's setting again",
+ find: "Find your ComfyUI",
+ browser: "Run your GPU jobs from this browser",
+};
+
/** Closes the card when the page changes. Reads the path (runtime data), so it sits under Suspense: routes still prerender. */
function CloseOnNavigation({ close }: { close: () => void }) {
const pathname = usePathname();
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 154d7430..8e90ec7e 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -534,6 +534,7 @@ export function Composer({ docked }: { docked: boolean }) {
setGpuRetry(
() => submitRef.current(),
() => submitRef.current(true),
+ model?.kind,
);
openGpuSetup({ ref: gpuRef, name: preset?.open ? preset.name : model?.name });
};
@@ -565,6 +566,7 @@ export function Composer({ docked }: { docked: boolean }) {
setGpuRetry(
() => submitRef.current(),
() => submitRef.current(true),
+ model?.kind,
);
create.mutate(skipGpu ? ({ ...sent.request, gpuCheck: "skip" } as typeof sent.request) : sent.request, {
// Stopped by the GPU pre-flight, or refused with its own card: the guided fix or the card is open already, so no error toast on top.
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index 3b32544f..fd4a9570 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -3,7 +3,7 @@
import { Cloud, Copy, Cpu, Download, FolderDown, Heart, MoreHorizontal, RotateCcw, Sparkles, Trash2, Wrench, X } from "lucide-react";
import { openGpuSetup } from "@/hooks/use-gpu";
import { useLocalJob } from "@/components/gpu/computer-runner";
-import { jobWords } from "@/lib/relay";
+import { jobFraction, jobWords } from "@/lib/relay";
import Link from "next/link";
import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
@@ -44,17 +44,25 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
const { cancel } = useGenerationActions();
// The clock runs between the job's reports (a fal queue or Higgsfield may report rarely).
const now = useNow(1000);
- const pct = g.progress != null ? Math.round(g.progress * 100) : null;
// Running on the ComfyUI on this computer: its live preview (sharper with each step), where it runs, and its step now.
- const local = useLocalJob(g.id);
- const label = (local && jobWords(local.job, g.kind, g.message ?? undefined)) ?? (g.status === "queued" ? (g.message ?? "Queued") : (g.message ?? "Generating…"));
+ // Its % and time left come from its own steps then, so they agree with "step 9 of 12".
+ const local = useLocalJob(g.id, now);
+ const label = (local && jobWords(local.job, g.kind, g.message ?? undefined, local.comfy)) ?? (g.status === "queued" ? (g.message ?? "Queued") : (g.message ?? "Generating…"));
+ const steps = local ? jobFraction(local.job) : null;
+ const saving = local && (local.job.phase === "saving" || local.job.phase === "done");
+ const fraction = local ? (saving ? null : steps) : g.progress;
+ const pct = fraction != null ? Math.round(fraction * 100) : null;
// When progress moved (not every poll: each one rewrites updatedAt) gives the pace, so the time left.
// Keyed by id: a chain's tile moves on to its next step's generation.
- const report = g.status === "running" ? g.progress : null;
- const [track, setTrack] = useState(() => ({ id: g.id, pace: notePace(null, g.updatedAt, report) }));
- const pace = track.id === g.id ? notePace(track.pace, g.updatedAt, report) : notePace(null, g.updatedAt, report);
+ const report = local ? steps : g.status === "running" ? g.progress : null;
+ const at = local ? now : g.updatedAt;
+ const [track, setTrack] = useState(() => ({ id: g.id, pace: notePace(null, at, report) }));
+ const pace = track.id === g.id ? notePace(track.pace, at, report) : notePace(null, at, report);
if (track.id !== g.id || pace !== track.pace) setTrack({ id: g.id, pace });
- const left = pace.first && pace.last ? timeLeft(pace.first, pace.last, now) : null;
+ const left = !saving && pace.first && pace.last ? timeLeft(pace.first, pace.last, now) : null;
+ // The bar: the steps, or how much of the result has reached the studio.
+ const bar = saving ? Math.round((local.job.phase === "done" ? 1 : (local.job.saved ?? 0)) * 100) : pct;
+ const where = local ? (local.here ? "Keep this tab open" : "Running in another Fuobe tab") : null;
return (
// max-w-full: in a grid row stretched by a taller neighbour (a card with a footer), h-full + aspect-ratio would
// otherwise make the tile wider than its column and spill over the next card.
@@ -73,8 +81,14 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
)}
<div className={cn("absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3", local?.preview && "bg-gradient-to-t from-background/85 to-transparent pt-8")}>
<div className="min-w-0">
- <p className="shimmer-text animate-shimmer-text truncate text-[13px] font-medium">{label}</p>
- {local && <p className="truncate text-[11px] text-muted-foreground">{local.here ? "On your computer · keep this tab open" : "Running in another Fuobe tab"}</p>}
+ <p title={label} className="shimmer-text animate-shimmer-text line-clamp-2 text-[13px] font-medium">
+ {label}
+ </p>
+ {where && (
+ <p title={where} className="line-clamp-2 text-[11px] text-muted-foreground">
+ {where}
+ </p>
+ )}
<p className="flex flex-wrap gap-x-1.5 font-mono text-[11px] text-muted-foreground tabular-nums">
{pct != null && <span>{pct}%</span>}
<span className={cn(pct != null && "before:mr-1.5 before:content-['·']")}>{elapsed(g.createdAt, Math.max(now, g.createdAt))}</span>
@@ -97,9 +111,9 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
<TooltipContent>Cancel</TooltipContent>
</Tooltip>
</div>
- {pct != null && (
+ {bar != null && (
<div className="absolute inset-x-0 top-0 h-0.5 bg-transparent">
- <div className="h-full bg-primary transition-[width] duration-500" style={{ width: `${pct}%` }} />
+ <div className="h-full bg-primary transition-[width] duration-500" style={{ width: `${bar}%` }} />
</div>
)}
</div>
diff --git a/src/hooks/use-gpu.ts b/src/hooks/use-gpu.ts
index d35cfed5..5559d02a 100644
--- a/src/hooks/use-gpu.ts
+++ b/src/hooks/use-gpu.ts
@@ -100,14 +100,15 @@ export interface GpuSetupDetail {
}
/** What "Try again" and "Run anyway" do for the request that was stopped (the composer that sent it sets them). */
-let pendingRetry: { at: number; retry: () => void; skip: () => void } | null = null;
+let pendingRetry: { at: number; retry: () => void; skip: () => void; kind?: string } | null = null;
-export function setGpuRetry(retry: () => void, skip: () => void): void {
- pendingRetry = { at: Date.now(), retry, skip };
+/** `kind`: what the run makes (image, video, audio), for the words of the card that starts it. */
+export function setGpuRetry(retry: () => void, skip: () => void, kind?: string): void {
+ pendingRetry = { at: Date.now(), retry, skip, ...(kind && { kind }) };
}
/** The composer's retry, when it asked within the last few seconds (another page's stale one never applies). */
-export function takeGpuRetry(): { retry: () => void; skip: () => void } | null {
+export function takeGpuRetry(): { retry: () => void; skip: () => void; kind?: string } | null {
const p = pendingRetry;
pendingRetry = null;
return p && Date.now() - p.at < 15_000 ? p : null;
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 5580d2e2..3ba970fb 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -839,7 +839,7 @@ export interface StatusInfo {
* Public sign-up: a guest or an account is looking. Then everything else here is its own view
* (its own GPU as ComfyUI, the open engine, no Demo mode), never the install's (src/server/account-gpu.ts).
*/
- viewer?: { kind: "guest" | "account"; gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; device?: string; vramBytes?: number } };
+ viewer?: { kind: "guest" | "account"; gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; comfy?: "down" | "no-setting"; device?: string; vramBytes?: number } };
}
/** A connection test's answer (POST /api/providers/test). */
@@ -1073,6 +1073,8 @@ export interface ViewerInfo {
account?: { email: string };
/** Runs go to the ComfyUI on the person's own computer, which a Fuobe tab of theirs runs (components/gpu/computer-runner.tsx). */
computer?: boolean;
+ /** The port their computer's tab last found ComfyUI on (a browser that remembers none starts there). */
+ comfyPort?: number;
}
export function useViewer() {
diff --git a/src/lib/comfy-guard.ts b/src/lib/comfy-guard.ts
new file mode 100644
index 00000000..7b8771e8
--- /dev/null
+++ b/src/lib/comfy-guard.ts
@@ -0,0 +1,110 @@
+/**
+ * Fuobe's guard for ComfyUI: one small custom node file that keeps every other website out while ComfyUI runs with
+ * Fuobe's setting (--enable-cors-header <this site>). ComfyUI replaces its own cross-site check with that setting, so
+ * without the guard any website the browser lets reach this computer could queue work on it, upload into it or stop it
+ * (it couldn't read the answers). The guard puts the check back for every site but the one the setting names: a request
+ * from a web page gets in only when the page is ComfyUI's own (same host) or that site. A program (no browser headers)
+ * gets in as before, and so does every page while ComfyUI runs without the setting (ComfyUI's own check is on then). It
+ * also answers GET /fuobe/guard, so the Fuobe tab can tell it is there.
+ *
+ * The Windows start file writes it into ComfyUI's custom_nodes folder; the other installs download it from the card.
+ * Plain ASCII (the start file carries it as base64). Pure: the card, the start file and the tests share it.
+ */
+
+export const GUARD_FILE_NAME = "fuobe_guard.py";
+
+/** Its version, as GET /fuobe/guard answers it. */
+export const GUARD_VERSION = 1;
+
+export const GUARD_SOURCE = `"""Fuobe's guard for ComfyUI.
+
+Started with --enable-cors-header, ComfyUI lets the website it names use it from your browser, but it also stops
+turning away requests from every other website. This file puts that check back: a request from a web page gets in only
+when the page is ComfyUI's own or the site the setting names. Programs (no browser) get in as before, and nothing
+changes while ComfyUI runs without the setting. It adds no nodes, reads no files and sends nothing anywhere.
+To remove it, delete this file and restart ComfyUI.
+"""
+import logging
+from urllib.parse import urlsplit
+
+from aiohttp import web
+
+import server
+from comfy.cli_args import args
+
+FUOBE_GUARD = ${GUARD_VERSION}
+NODE_CLASS_MAPPINGS = {}
+NODE_DISPLAY_NAME_MAPPINGS = {}
+
+_told = set()
+
+
+def _allowed():
+ value = (getattr(args, "enable_cors_header", None) or "").strip().rstrip("/").lower()
+ return value if value and value != "*" else None
+
+
+def _same_host(origin, host):
+ try:
+ o = urlsplit(origin)
+ h = urlsplit("//" + (host or "").strip().lower())
+ if not o.hostname or not h.hostname or o.hostname != h.hostname:
+ return False
+ return o.port is None or h.port is None or o.port == h.port
+ except ValueError:
+ return False
+
+
+def _refuse(why):
+ if why not in _told and len(_told) < 50:
+ _told.add(why)
+ logging.warning("[Fuobe guard] Turned away a request from %s", why)
+ return web.Response(status=403)
+
+
+async def fuobe_guard(request, handler):
+ allowed = _allowed()
+ if allowed is not None:
+ origin = request.headers.get("Origin")
+ if origin is not None:
+ o = origin.strip().rstrip("/").lower()
+ if o != allowed and not _same_host(o, request.headers.get("Host")):
+ return _refuse(origin[:120])
+ elif request.headers.get("Sec-Fetch-Site", "").lower() in ("cross-site", "same-site"):
+ return _refuse("another website")
+ return await handler(request)
+
+
+async def fuobe_guard_status(request):
+ return web.json_response({"guard": FUOBE_GUARD})
+
+
+def _install():
+ instance = getattr(server.PromptServer, "instance", None)
+ if instance is None:
+ return
+ app = instance.app
+ if any(getattr(m, "__name__", "") == "fuobe_guard" for m in app.middlewares):
+ return
+ try:
+ app.middlewares.insert(0, fuobe_guard)
+ except RuntimeError:
+ logging.warning("[Fuobe guard] ComfyUI had already started, so the guard is off. Restart ComfyUI.")
+ return
+ instance.routes.get("/fuobe/guard")(fuobe_guard_status)
+ if _allowed():
+ logging.info("[Fuobe guard] Only %s and ComfyUI's own page may use ComfyUI from a browser.", _allowed())
+
+
+_install()
+`;
+
+/** The guard as base64 (the start file writes it with PowerShell). */
+export function guardBase64(): string {
+ if (!/^[\x00-\x7f]*$/.test(GUARD_SOURCE)) throw new Error("The guard must be plain ASCII");
+ return btoa(GUARD_SOURCE);
+}
+
+/** Its answer at /fuobe/guard: there, and this version or newer. */
+export const isGuard = (answer: unknown): boolean => !!answer && typeof answer === "object" && Number((answer as { guard?: unknown }).guard) >= GUARD_VERSION;
diff --git a/src/lib/comfy-install.ts b/src/lib/comfy-install.ts
index 73668745..9f8281fe 100644
--- a/src/lib/comfy-install.ts
+++ b/src/lib/comfy-install.ts
@@ -3,6 +3,7 @@
* the model files it still lacks. Pure (no I/O), so it can be tested and run in the browser.
*/
import type { ManifestModel, ManifestWorkflow } from "./comfy";
+import { GUARD_FILE_NAME, guardBase64 } from "./comfy-guard";
import { FUOBE_REPO } from "./connections";
import { modelCardOf } from "./licences";
@@ -117,12 +118,16 @@ export interface InstallFix {
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. */
+ /** A whole command with the setting in it, as an example (a terminal). */
+ example?: string;
+ /** Windows portable or Easy-Install: a start file can do it (the setting and Fuobe's guard). */
startFile?: boolean;
+ /** Where Fuobe's guard goes (lib/comfy-guard.ts), for the installs whose guard the person puts in by hand. */
+ guard?: string;
}
-/** The fix for each install, in the words the card shows. */
-export function fixFor(install: ComfyInstall, origin: string): InstallFix {
+/** The fix for each install, in the words the card shows (`port`: where ComfyUI was found). */
+export function fixFor(install: ComfyInstall, origin: string, port = 8188): InstallFix {
const flag = corsFlag(origin);
switch (install) {
case "desktop":
@@ -130,21 +135,29 @@ export function fixFor(install: ComfyInstall, origin: string): InstallFix {
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,
+ guard: "Put it in the custom_nodes folder of your ComfyUI folder (Documents → ComfyUI, unless you chose another when you installed it).",
};
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,
+ guard: "Put it in ComfyUI's custom_nodes folder (ComfyUI's ⋮ menu → Open in Explorer).",
};
case "portable":
return {
- lead: "Download this start file and open it. It restarts ComfyUI with Fuobe allowed in, and keeps your other settings.",
+ lead: "Download this start file and open it. It restarts ComfyUI with Fuobe's setting and Fuobe's guard, 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}` };
+ // The setting goes into their own command (their python, their arguments); the example keeps the port it was on.
+ return {
+ lead: "Add this to the command you start ComfyUI with, then start it again (Ctrl+C in its window stops it):",
+ copy: flag,
+ example: `python main.py ${flag}${port !== 8188 ? ` --port ${port}` : ""}`,
+ guard: "Put it in ComfyUI's custom_nodes folder.",
+ };
}
}
@@ -153,21 +166,26 @@ 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.
+ * port, asks before restarting it, puts Fuobe's guard (lib/comfy-guard.ts) into its custom_nodes folder, and starts it
+ * again the same way with Fuobe's setting added. It leaves a start file with that command next to ComfyUI for next
+ * time, and never changes the person's own start files. 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 (Desktop
+ * gets the guard too, when its folder shows). 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);
+ // A --base-directory in a command line: ComfyUI's custom nodes are there.
+ const baseDir = "'--base-directory\\s+(\"([^\"]+)\"|(\\S+))'";
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 also puts Fuobe's guard (${GUARD_FILE_NAME}) in ComfyUI's custom_nodes folder: while the setting is on, it keeps`,
+ "rem every other website out of your ComfyUI.",
"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.",
+ "rem To undo it, start ComfyUI the usual way, and delete the guard from custom_nodes.",
'set "FUOBE_BAT=%~f0"',
`powershell -NoProfile -ExecutionPolicy Bypass -Command "$s=[IO.File]::ReadAllText($env:FUOBE_BAT); iex $s.Substring($s.IndexOf('#FUOBE'+'-PS'))"`,
"echo.",
@@ -176,11 +194,21 @@ export function startFile(port: number, origin: string): string {
"#FUOBE-PS",
`$Port = ${port}`,
`$Flag = ${ps(flag)}`,
+ "function Add-Guard($nodes) {",
+ " if (-not $nodes -or -not (Test-Path $nodes)) { return }",
+ ` [IO.File]::WriteAllBytes((Join-Path $nodes ${ps(GUARD_FILE_NAME)}), [Convert]::FromBase64String('${guardBase64()}'))`,
+ ` Write-Host "Added Fuobe's guard to $nodes. It keeps every other website out of your ComfyUI." }`,
+ "function Base-Nodes($cmdline, $from) {",
+ ` if ($cmdline -notmatch ${baseDir}) { return $null }`,
+ " $b = if ($Matches[2]) { $Matches[2] } else { $Matches[3] }",
+ " if (-not [IO.Path]::IsPathRooted($b)) { $b = Join-Path $from $b }",
+ " return (Join-Path $b 'custom_nodes') }",
"$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') {",
+ " Add-Guard (Base-Nodes $proc.CommandLine $env:USERPROFILE)",
` 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 }',
@@ -191,33 +219,25 @@ export function startFile(port: number, origin: string): string {
"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 } }",
+ "$comfy = if (Test-Path (Join-Path $dir 'ComfyUI\\main.py')) { Join-Path $dir 'ComfyUI' } else { $dir }",
"$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()",
+ "$nodes = Base-Nodes $args0 $dir",
+ "if (-not $nodes) { $nodes = Join-Path $comfy 'custom_nodes' }",
'$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 }",
+ "Add-Guard $nodes",
`$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.ts b/src/lib/comfy.ts
index c5a654c3..c69cdb59 100644
--- a/src/lib/comfy.ts
+++ b/src/lib/comfy.ts
@@ -300,22 +300,27 @@ export function referencedModels(wf: ComfyWorkflow): string[] {
export function explainComfyError(nodeErrors: unknown, manifest?: ManifestWorkflow): string {
const parts: string[] = [];
const errs = (nodeErrors ?? {}) as Record<string, { errors?: { message?: string; details?: string; extra_info?: { input_name?: string; received_value?: unknown } }[]; class_type?: string }>;
- for (const [nodeId, ne] of Object.entries(errs)) {
- for (const e of ne.errors ?? []) {
- const received = e.extra_info?.received_value;
- if (e.message?.includes("not in list") && typeof received === "string") {
+ // A ComfyUI's answer can be large (or, from someone's own computer, anything): its words are cut short, and few.
+ const cut = (v: unknown, n: number) => (typeof v === "string" ? v.slice(0, n) : undefined);
+ for (const [nodeId, ne] of Object.entries(errs).slice(0, 24)) {
+ for (const e of (Array.isArray(ne?.errors) ? ne.errors : []).slice(0, 6)) {
+ const received = cut(e?.extra_info?.received_value, 256);
+ const message = cut(e?.message, 300);
+ const cls = cut(ne?.class_type, 128) ?? `node ${nodeId.slice(0, 32)}`;
+ if (message?.includes("not in list") && received !== undefined) {
const m = manifest?.models.find((mm) => mm.file === received);
parts.push(
m
? `Missing model "${received}" — put it in ComfyUI/models/${m.folder}${m.url ? ` (download: ${m.url})` : ""}`
- : `ComfyUI can't find "${received}" (${ne.class_type ?? nodeId}.${e.extra_info?.input_name ?? "input"})`,
+ : `ComfyUI can't find "${received}" (${cls}.${cut(e.extra_info?.input_name, 64) ?? "input"})`,
);
} else {
- parts.push(`${ne.class_type ?? `node ${nodeId}`}: ${e.message ?? "error"}${e.details ? ` — ${e.details}` : ""}`);
+ const details = cut(e?.details, 300);
+ parts.push(`${cls}: ${message ?? "error"}${details ? ` — ${details}` : ""}`);
}
}
}
- return [...new Set(parts)].join("\n") || "ComfyUI rejected the workflow";
+ return [...new Set(parts)].slice(0, 20).join("\n") || "ComfyUI rejected the workflow";
}
// ---------------------------------------------------------------------------
diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.ts
index 1776ec87..cc1b962c 100644
--- a/src/lib/computer-runner.ts
+++ b/src/lib/computer-runner.ts
@@ -7,9 +7,10 @@
* send. No React and no browser-only API is needed: the page (src/components/gpu/computer-runner.tsx) gives it fetch,
* a socket and a clock, and the tests drive it from Node against a stand-in ComfyUI.
*/
+import { isGuard } from "./comfy-guard";
import { parseComfyBinary, parseComfyText } from "./comfy-ws";
import { graphProblem, localBase, mayDownload, readPath, statsFacts, viewPath, writePath, type SystemStats } from "./local-comfy";
-import { RELAY_LIMITS, RELAY_TIMES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type HistoryEntryLike, type RelayState, type ReportEvent, type WantedFile } from "./relay";
+import { DONE_SHOWN_MS, RELAY_LIMITS, RELAY_TIMES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type HistoryEntryLike, type RelayState, type ReportEvent, type WantedFile } from "./relay";
/** The parts of a WebSocket the runner uses (the browser's, or Node's). */
export interface SocketLike {
@@ -31,6 +32,13 @@ export interface RunnerDeps {
sha256: (data: ArrayBuffer) => Promise<string>;
/** This site's address, as ComfyUI's setting must name it. */
origin: string;
+ /**
+ * ComfyUI stopped answering where the runner looks: is it on another port now? (The page looks on ComfyUI's usual
+ * ports, only when the browser already lets Fuobe reach this computer.) The port and host, or null.
+ */
+ find?: (except: number) => Promise<{ port: number; host?: string } | null>;
+ /** The runner moved to another port (the page remembers it). */
+ moved?: (port: number, host: string) => void;
now?: () => number;
sleep?: (ms: number) => Promise<void>;
}
@@ -46,6 +54,10 @@ export interface LocalJob {
/** The latest live preview (an image the page shows under the tile's shimmer). */
preview?: Blob;
saved?: number;
+ /** Saving waits for the studio (it is busy saving other results). */
+ waiting?: boolean;
+ /** When it was saved, or failed (this tab's clock). */
+ endedAt?: number;
}
export interface RunnerView {
@@ -56,6 +68,13 @@ export interface RunnerView {
waiting: number;
/** ComfyUI here: answering, not answering, or answering without Fuobe's setting. */
comfy: "ok" | "down" | "no-setting";
+ /**
+ * This browser may not reach apps on this computer yet: it would ask first ("ask"), or it was told no ("blocked").
+ * Then the runner only listens (how many wait) and never touches ComfyUI.
+ */
+ access?: "ask" | "blocked";
+ /** Where it looks for ComfyUI. */
+ port: number;
/** The session ended, or the person disconnected: the runner stopped. */
stopped?: "signed-out" | "disconnected";
jobs: LocalJob[];
@@ -66,6 +85,15 @@ class Stopped extends Error {}
const PROGRESS_EVERY_MS = 500;
const POLL_MS = 1000;
+/** How often a ComfyUI that stopped answering is looked for on the other ports. */
+const FIND_EVERY_MS = 20_000;
+/** Ended jobs the view keeps (a tile shows the last preview until its run moves on). */
+const KEEP_ENDED = 6;
+/** How long a result may wait for a busy studio before the run gives up. */
+const SAVE_WAIT_MS = 60 * 60_000;
+
+/** Retry-After in ms (1 to 30 s; 2 s when it doesn't say). */
+const retryAfter = (res: Response) => Math.min(30, Math.max(1, Number(res.headers.get("retry-after")) || 2)) * 1000;
/** The prompts of a meta-batch job: their entries name the job's filename prefix. */
const hasPrefix = (prompt: unknown, prefix: string) =>
@@ -75,7 +103,7 @@ const hasPrefix = (prompt: unknown, prefix: string) =>
const slim = (e: HistoryEntryLike & { prompt?: unknown[] }): HistoryEntryLike => ({ prompt: e.prompt ? [e.prompt[0], e.prompt[1]] : undefined, status: e.status, outputs: e.outputs });
export class ComputerRunner {
- readonly view: RunnerView = { runner: false, heldElsewhere: false, waiting: 0, comfy: "ok", jobs: [] };
+ readonly view: RunnerView;
private listeners = new Set<(v: RunnerView) => void>();
private busy = false;
private stopping = new Set<string>();
@@ -84,6 +112,8 @@ export class ComputerRunner {
private events = new Map<string, { value?: number; max?: number; node?: string; nodesDone: number; done?: boolean }>();
private factsSentAt = 0;
private factsWithLoras = 0;
+ private foundAt = 0;
+ private guard: boolean | undefined;
private jobsApi: boolean | undefined;
private alive = true;
private now: () => number;
@@ -92,11 +122,12 @@ export class ComputerRunner {
constructor(
private deps: RunnerDeps,
- private o: { device: string; port: number; host?: string; clientId: string },
+ private o: { device: string; port: number; host?: string; clientId: string; access?: "ask" | "blocked" },
) {
this.now = deps.now ?? Date.now;
this.sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
this.base = localBase(o.port, o.host);
+ this.view = { runner: false, heldElsewhere: false, waiting: 0, comfy: "ok", port: o.port, ...(o.access && { access: o.access }), jobs: [] };
}
onChange(fn: (v: RunnerView) => void): () => void {
@@ -110,8 +141,17 @@ export class ComputerRunner {
private job(t: Pick<ClaimedTask, "id" | "generationId">, patch: Partial<LocalJob>) {
const at = this.view.jobs.findIndex((j) => j.taskId === t.id);
- const next = { ...(at >= 0 ? this.view.jobs[at] : { taskId: t.id, generationId: t.generationId, phase: "sending" as const }), ...patch };
- this.view.jobs = at >= 0 ? this.view.jobs.map((j, i) => (i === at ? next : j)) : [...this.view.jobs, next];
+ const was: LocalJob = at >= 0 ? this.view.jobs[at] : { taskId: t.id, generationId: t.generationId, phase: "sending" };
+ const ends = (patch.phase === "done" || patch.phase === "failed") && patch.phase !== was.phase;
+ const next = { ...was, ...patch, ...(ends && { endedAt: this.now() }) };
+ let jobs = at >= 0 ? this.view.jobs.map((j, i) => (i === at ? next : j)) : [...this.view.jobs, next];
+ // Ended jobs stay a while (their tile keeps the last preview until the run moves on), the newest few.
+ const ended = jobs.filter((j) => j.phase === "done" || j.phase === "failed");
+ if (ended.length > KEEP_ENDED) {
+ const drop = new Set(ended.slice(0, ended.length - KEEP_ENDED));
+ jobs = jobs.filter((j) => !drop.has(j));
+ }
+ this.view.jobs = jobs;
this.emit();
}
@@ -138,24 +178,60 @@ export class ComputerRunner {
return this.deps.local(`${this.base}${writePath(path, check, own)}`, { ...init, method: "POST", credentials: "omit", cache: "no-store" });
}
- /** What ComfyUI here is, for the server (its GPU, memory, version; its LoRA names now and then). */
- async facts(withLoras = false): Promise<ComputerFacts | null> {
+ /**
+ * ComfyUI here, as every caller sees it: readable (its facts), answering but not to this site (it runs without Fuobe's
+ * setting: a no-cors look sees that something answers), or not answering. One look, so the page never hears two
+ * stories. Not answering where it was, it is looked for on the other ports now and then (the page's `find`).
+ */
+ private async look(): Promise<{ comfy: "ok"; stats: SystemStats } | { comfy: "down" | "no-setting" }> {
+ let l: { comfy: "ok"; stats: SystemStats } | { comfy: "down" | "no-setting" };
try {
- const stats = await this.read<SystemStats>("/system_stats");
- const f: ComputerFacts = statsFacts(stats, this.deps.origin);
- if (withLoras) {
- const loras = await this.read<unknown>("/models/loras").catch(() => null);
- if (Array.isArray(loras)) f.loras = loras.filter((x): x is string => typeof x === "string");
- }
- this.view.comfy = "ok";
- this.view.facts = f;
- return f;
+ l = { comfy: "ok", stats: await this.read<SystemStats>("/system_stats") };
} catch (e) {
- // A browser can't read a ComfyUI that doesn't let this site in, but a no-cors look sees that something answers.
const answers = (e as { status?: number }).status === 403 || (await this.deps.local(`${this.base}/system_stats`, { mode: "no-cors", credentials: "omit", cache: "no-store" }).then(() => true, () => false));
- this.view.comfy = answers ? "no-setting" : "down";
- return null;
+ l = { comfy: answers ? "no-setting" : "down" };
+ if (!answers && (await this.findElsewhere())) return this.look();
+ }
+ if (this.view.comfy !== l.comfy) {
+ this.view.comfy = l.comfy;
+ this.emit();
+ }
+ return l;
+ }
+
+ /** ComfyUI isn't where the runner looks: when it answers on another port, the runner goes there. True when it moved. */
+ private async findElsewhere(): Promise<boolean> {
+ if (!this.deps.find || this.now() - this.foundAt < FIND_EVERY_MS) return false;
+ this.foundAt = this.now();
+ const there = await this.deps.find(this.o.port).catch(() => null);
+ if (!there || there.port === this.o.port) return false;
+ const host = there.host ?? "127.0.0.1";
+ this.base = localBase(there.port, host);
+ Object.assign(this.o, { port: there.port, host });
+ this.view.port = there.port;
+ this.guard = undefined;
+ this.jobsApi = undefined;
+ // The live socket was to the old port.
+ try {
+ this.ws?.close();
+ } catch {}
+ this.deps.moved?.(there.port, host);
+ this.emit();
+ return true;
+ }
+
+ /** What ComfyUI here is, for the server (its GPU, memory, version, Fuobe's guard; its LoRA names now and then). */
+ async facts(o: { loras?: boolean; guard?: boolean } = {}): Promise<ComputerFacts | null> {
+ const l = await this.look();
+ if (l.comfy !== "ok") return null;
+ if (o.guard || this.guard === undefined) this.guard = await this.read<unknown>("/fuobe/guard").then(isGuard, () => false);
+ const f: ComputerFacts = statsFacts(l.stats, this.deps.origin, this.guard);
+ if (o.loras) {
+ const loras = await this.read<unknown>("/models/loras").catch(() => null);
+ if (Array.isArray(loras)) f.loras = loras.filter((x): x is string => typeof x === "string");
}
+ this.view.facts = f;
+ return f;
}
private socket() {
@@ -226,9 +302,12 @@ export class ComputerRunner {
// -------------------------------------------------------------------------
// The server
+ /** A report about a job (its token in a header, so the studio checks it before it reads the report). */
private async report(t: ClaimedTask, e: ReportEvent): Promise<{ wanted?: WantedFile[]; follow?: string; stop?: boolean; state?: RelayState }> {
- for (let i = 0; ; i++) {
- const res = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/report`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lease: t.lease, ...e }) });
+ // A busy studio (429) is waited out, for a while; other failures are tried a few times.
+ const until = this.now() + 2 * 60_000;
+ for (let i = 0; ; ) {
+ const res = await this.deps.api(`/api/gpu/computer/tasks/${t.id}/report`, { method: "POST", headers: { "Content-Type": "application/json", "X-Fuobe-Lease": t.lease }, body: JSON.stringify(e) });
if (res.ok) return (await res.json()) as { wanted?: WantedFile[]; follow?: string; stop?: boolean; state?: RelayState };
if (res.status === 401) {
this.stop("signed-out");
@@ -236,8 +315,12 @@ export class ComputerRunner {
}
// The job ended or another tab has it: this tab lets go.
if (res.status === 404 || res.status === 409) throw new Stopped();
- if (i >= 4) throw new Error(`The studio answered HTTP ${res.status}`);
- await this.sleep(res.status === 429 ? 2000 : 1000 * (i + 1));
+ if (res.status === 429 && this.now() < until) {
+ await this.sleep(retryAfter(res));
+ continue;
+ }
+ if (++i > 4) throw new Error(`The studio answered HTTP ${res.status}`);
+ await this.sleep(1000 * i);
}
}
@@ -245,11 +328,13 @@ export class ComputerRunner {
async beat(takeover = false): Promise<BeatAnswer | null> {
if (!this.alive) return null;
const t = this.now();
+ // A browser that may not reach this computer yet only hears how many jobs wait (never ComfyUI, never the jobs).
+ if (this.o.access) return this.beatWith({ device: this.o.device, ready: false, listen: true, running: [] });
// A look at ComfyUI here every beat (only a computer whose ComfyUI answers takes the jobs); its facts go to the
// server every minute, the LoRA names every 5 minutes.
const due = t - this.factsSentAt > 60_000;
const loras = due && t - this.factsWithLoras > 5 * 60_000;
- const read = await this.facts(loras);
+ const read = await this.facts({ loras, guard: due });
const facts = due ? read : null;
if (facts) {
this.factsSentAt = t;
@@ -262,11 +347,23 @@ export class ComputerRunner {
return { task: j.taskId, ...(j.position !== undefined && { position: j.position }), ...(j.phase === "running" && ev && { value: ev.value, max: ev.max, nodesDone: ev.nodesDone }) };
});
const stopped = [...this.stoppedDone];
- const res = await this.deps.api("/api/gpu/computer/beat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ device: this.o.device, port: this.o.port, ready: !!read, ...(facts && { facts }), running, ...(stopped.length && { stopped }), ...(takeover && { takeover: true }) }),
- });
+ return this.beatWith(
+ {
+ device: this.o.device,
+ port: this.o.port,
+ ready: !!read,
+ ...(this.view.comfy === "no-setting" && { why: "setting" }),
+ ...(facts && { facts }),
+ running,
+ ...(stopped.length && { stopped }),
+ ...(takeover && { takeover: true }),
+ },
+ stopped,
+ );
+ }
+
+ private async beatWith(body: Record<string, unknown>, stopped: string[] = []): Promise<BeatAnswer | null> {
+ const res = await this.deps.api("/api/gpu/computer/beat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
if (res.ok) for (const s of stopped) this.stoppedDone.delete(s);
if (res.status === 401) {
this.stop("signed-out");
@@ -280,7 +377,7 @@ export class ComputerRunner {
const a = (await res.json()) as BeatAnswer;
Object.assign(this.view, { runner: a.runner, heldElsewhere: a.heldElsewhere, waiting: a.waiting });
this.emit();
- for (const s of a.stops) void this.takeOff(s);
+ if (!this.o.access) for (const s of a.stops) void this.takeOff(s);
return a;
}
@@ -324,11 +421,15 @@ export class ComputerRunner {
private promptOf = new Map<string, string>();
private stoppedDone = new Set<string>();
- /** Ask for a job and run it (one at a time). True when there was one. */
+ /**
+ * Ask for a job and run it (one at a time). True when there was one. Only while ComfyUI here answers to this site: a
+ * computer whose ComfyUI is closed, or runs without Fuobe's setting, keeps its place but takes nothing.
+ */
async claimAndRun(): Promise<boolean> {
- if (!this.alive || this.busy) return false;
+ if (!this.alive || this.busy || this.o.access) return false;
this.busy = true;
try {
+ if ((await this.look()).comfy !== "ok") return false;
const running = this.view.jobs.filter((j) => j.phase !== "done" && j.phase !== "failed").map((j) => j.taskId);
const res = await this.deps.api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: this.o.device, running }) });
if (res.status !== 200) {
@@ -460,26 +561,20 @@ export class ComputerRunner {
return true;
}
- /** ComfyUI here stopped answering: say so once, then wait until it answers again. */
+ /**
+ * ComfyUI here stopped answering, or answers without Fuobe's setting: say which (again when that changes), then wait
+ * until it answers to this site again.
+ */
private async waitForComfy(t: ClaimedTask) {
- let told = false;
+ let told: string | undefined;
for (;;) {
if (!this.alive) throw new Stopped();
- const ok = await this.read("/system_stats").then(
- () => true,
- () => false,
- );
- if (ok) {
- this.view.comfy = "ok";
- this.emit();
- return;
- }
- this.view.comfy = "down";
- this.emit();
- if (!told) {
- const a = await this.report(t, { event: "comfy-down" });
+ const l = await this.look();
+ if (l.comfy === "ok") return;
+ if (told !== l.comfy) {
+ const a = await this.report(t, { event: "comfy-down", ...(l.comfy === "no-setting" && { why: "setting" as const }) });
if (a.stop) throw new Stopped();
- told = true;
+ told = l.comfy;
}
await this.sleep(3000);
}
@@ -567,13 +662,18 @@ export class ComputerRunner {
}
if (!(await this.upload(t, w, blob, offset))) return this.job(t, { phase: "failed" });
}
- this.job(t, { phase: "done", preview: undefined });
+ // Saved: the tile says so (over the last preview) until the run itself moves on.
+ this.job(t, { phase: "done", saved: 1, waiting: false });
}
- /** One file in parts of 16 MB; a failed part is tried again (three times in a row at most). */
+ /**
+ * One file in parts of 16 MB; a failed part is tried again (three times in a row at most). A busy studio (429) isn't a
+ * failure: the part waits as long as it says, up to an hour in all.
+ */
private async upload(t: ClaimedTask, w: WantedFile, blob: Blob, from: number): Promise<boolean> {
let offset = from;
let fails = 0;
+ const until = this.now() + SAVE_WAIT_MS;
while (offset < blob.size || blob.size === 0) {
if (!this.alive) throw new Stopped();
const part = blob.slice(offset, Math.min(blob.size, offset + RELAY_LIMITS.partBytes));
@@ -588,10 +688,15 @@ export class ComputerRunner {
const r = (await res.json()) as { received: number; done: boolean };
offset = r.received;
fails = 0;
- this.job(t, { saved: offset / Math.max(1, blob.size) });
+ this.job(t, { saved: offset / Math.max(1, blob.size), waiting: false });
if (r.done) return true;
continue;
}
+ if (res?.status === 429 && this.now() < until) {
+ this.job(t, { waiting: true });
+ await this.sleep(retryAfter(res));
+ continue;
+ }
if (res && (res.status === 404 || res.status === 413 || res.status === 415)) return false;
if (res?.status === 409) {
// Out of step (a part arrived twice): go on from what the server has.
@@ -605,7 +710,7 @@ export class ComputerRunner {
await this.report(t, { event: "failed", reason: "save-failed" }).catch(() => null);
return false;
}
- await this.sleep(res?.status === 429 ? 2000 : 1500 * fails);
+ await this.sleep(1500 * fails);
}
return true;
}
@@ -619,5 +724,15 @@ export class ComputerRunner {
}
}
+/**
+ * The job a run's tile shows: the run's latest one. A saved one only for a short while (its tile says it is saving over
+ * the last preview until the run itself moves on), so a run's next step, or a run sent again, never shows an old job.
+ */
+export function tileJob(jobs: readonly LocalJob[], generationId: string, now: number): LocalJob | undefined {
+ const job = jobs.findLast((j) => j.generationId === generationId);
+ if (!job || (job.phase === "done" && now - (job.endedAt ?? 0) > DONE_SHOWN_MS)) return undefined;
+ return job;
+}
+
/** How often the runner beats: faster while it has work. */
export const beatEvery = (busy: boolean) => (busy ? RELAY_TIMES.busyBeatMs : RELAY_TIMES.beatMs);
diff --git a/src/lib/gpu/fix-codes.ts b/src/lib/gpu/fix-codes.ts
index fecc9659..a24acf1a 100644
--- a/src/lib/gpu/fix-codes.ts
+++ b/src/lib/gpu/fix-codes.ts
@@ -9,6 +9,9 @@ export interface PromptErrorBody {
node_errors?: unknown;
}
+/** "Node 'My Node' not found", "Cannot execute because node MyNode does not exist": the class, quoted or not. */
+const MISSING_NODE = /node (?:type )?(?:'([^'\n]{1,128})'|([^'"\s]{1,128})) (?:not found|does not exist)/i;
+
export function fixFromPromptError(
body: PromptErrorBody,
workflowId: string,
@@ -28,7 +31,9 @@ export function fixFromPromptError(
}
if (items.length) return { code: "comfy_missing_model", workflowId, items };
if (body.error?.type === "missing_node_type") {
- const cls = body.error.extra_info?.class_type ?? /node (?:type )?'?([^'"]+?)'? (?:not found|does not exist)/i.exec(body.error.message ?? "")?.[1];
+ // A bounded pattern on the message's start: a long message (a ComfyUI's answer, or what a tab reports) can't stall it.
+ const said = MISSING_NODE.exec(String(body.error.message ?? "").slice(0, 1024));
+ const cls = body.error.extra_info?.class_type ?? said?.[1] ?? said?.[2];
if (cls) {
const pack = packOf(cls);
return { code: "comfy_missing_node", workflowId, items: [{ class: cls, ...(pack && { pack }) }] };
diff --git a/src/lib/local-comfy.ts b/src/lib/local-comfy.ts
index 55cec8be..387b52ca 100644
--- a/src/lib/local-comfy.ts
+++ b/src/lib/local-comfy.ts
@@ -50,7 +50,7 @@ export function readPath(path: string): string {
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 (["/system_stats", "/api/system_stats", "/object_info", "/models", "/embeddings", "/queue", "/api/jobs", "/fuobe/guard"].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();
@@ -151,28 +151,84 @@ export function mayDownload(f: Pick<WantedFile, "filename" | "subfolder" | "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 type PortLook =
+ | { port: number; host?: string; state: "found"; stats: SystemStats; guard?: boolean }
+ | { 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 }[];
}
+/** A port's place among ComfyUI's usual ones (8188 first); one the person typed comes after them, lowest first. */
+const portRank = (port: number) => {
+ const at = (COMFY_PORTS as readonly number[]).indexOf(port);
+ return at >= 0 ? at : COMFY_PORTS.length + port;
+};
+
/**
* 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.
+ * usual order (8188 before Desktop's 8000: another app on 8000 doesn't win). "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);
+ const sorted = looks.filter((l) => l.state !== "none").sort((a, b) => rank(a) - rank(b) || Number(b.port === remembered) - Number(a.port === remembered) || portRank(a.port) - portRank(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) {
+/** What the "Use the ComfyUI on this computer" card shows (components/gpu/use-local-comfy.ts finds it). */
+export type Finder =
+ /** The browser will ask to let Fuobe reach apps on this computer: a click starts the first look. */
+ | { s: "start" }
+ | { s: "looking" }
+ /** Found and readable: the caller connects. */
+ | { s: "found"; port: number; host: string; stats: SystemStats }
+ /**
+ * ComfyUI answers but can't be read: it needs the setting (`back`: it restarted, still without it). `others`: other
+ * ports where something answers too (the person picks where their ComfyUI is).
+ */
+ | { s: "needs-setting"; port: number; back: boolean; others?: number[] }
+ /** The port went quiet after it needed the setting: ComfyUI is restarting. */
+ | { s: "waiting"; port: number; since: number }
+ | { s: "none"; missed?: number }
+ /** The browser keeps Fuobe from reaching apps on this computer. */
+ | { s: "blocked" }
+ /** This browser or page can't: Safari, a phone, or a studio on plain http at a network address. */
+ | { s: "unsupported"; why: "safari" | "phone" | "http" };
+
+/**
+ * The card's next screen after a look (`typed`: the one port the person asked about). A readable ComfyUI on any port
+ * connects. While it waits for one ComfyUI to come back with the setting, that port decides: quiet there is ComfyUI
+ * restarting, and another app answering on another port changes nothing.
+ */
+export function settled(was: Finder, looks: PortLook[], remembered: number | undefined, typed: number | undefined, now: number): Finder {
+ const best = pickLook(looks, remembered);
+ if (best.state === "found") return { s: "found", port: best.port, host: best.host ?? "127.0.0.1", stats: best.stats };
+ const answering = looks.filter((l) => l.state === "unreadable").map((l) => l.port);
+ const others = (port: number) => {
+ const rest = answering.filter((p) => p !== port);
+ return rest.length ? { others: rest } : {};
+ };
+ if ((was.s === "needs-setting" || was.s === "waiting") && looks.some((l) => l.port === was.port)) {
+ if (answering.includes(was.port)) return { s: "needs-setting", port: was.port, back: was.s === "waiting" || (was.s === "needs-setting" && was.back), ...others(was.port) };
+ return { s: "waiting", port: was.port, since: was.s === "waiting" ? was.since : now };
+ }
+ if (best.state === "unreadable") return { s: "needs-setting", port: best.port, back: false, ...others(best.port) };
+ return { s: "none", ...(typed && { missed: typed }) };
+}
+
+/** The same screen (a quiet look that found nothing new changes nothing). */
+export const sameFinder = (a: Finder, b: Finder): boolean => a.s === b.s && JSON.stringify({ ...a, stats: undefined }) === JSON.stringify({ ...b, stats: undefined });
+
+/**
+ * Facts for the server from /system_stats: never the command line, only whether its cross-site setting names this site;
+ * and whether Fuobe's guard answered (`guard`, when it was asked).
+ */
+export function statsFacts(s: SystemStats, origin: string, guard?: boolean) {
const argv = s.system?.argv ?? [];
const at = argv.indexOf("--enable-cors-header");
const value = at >= 0 ? argv[at + 1] : undefined;
@@ -186,6 +242,7 @@ export function statsFacts(s: SystemStats, origin: string) {
...(s.system?.os && { os: String(s.system.os).slice(0, 40) }),
...(typeof s.system?.embedded_python === "boolean" && { portable: s.system.embedded_python }),
...(cors && { cors }),
+ ...(guard !== undefined && { guard }),
};
}
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 31dd111e..62576948 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -43,8 +43,8 @@ export type ReportEvent =
| { 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" }
+ /** The tab can't use ComfyUI: it doesn't answer, or (`why: "setting"`) it answers without Fuobe's setting. */
+ | { event: "comfy-down"; why?: "setting" }
/** A stop the server asked for is done. */
| { event: "stopped" }
/** The tab gave up for one of its own reasons. */
@@ -122,6 +122,8 @@ export interface ComputerFacts {
portable?: boolean;
/** Its --enable-cors-header: this site exactly, every site ("any"), or something else. */
cors?: "exact" | "any" | "other";
+ /** Fuobe's guard is in its custom nodes (it turns away every other website while the setting is on). */
+ guard?: boolean;
/** Its LoRA files (sent now and then, not on every beat). */
loras?: string[];
}
@@ -157,8 +159,11 @@ export const RELAY_TIMES = {
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 };
+/**
+ * The largest part of an output the tab sends at once; the largest report (a finished entry, while ComfyUI has the job),
+ * a refusal's (while it sends) and any other's; how much of a refusal is kept.
+ */
+export const RELAY_LIMITS = { partBytes: 16 * 2 ** 20, reportBytes: 8 * 2 ** 20, refusalBytes: 256 * 1024, smallReportBytes: 8 * 1024, keptRefusalBytes: 16 * 1024, 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}$/;
@@ -195,50 +200,84 @@ export function queueWords(position: number | undefined): string {
return position === 0 ? "Next in ComfyUI's queue" : `In ComfyUI's queue · ${position} ahead`;
}
+/** "picture", "clip", "sound": what a run of this kind makes. */
+export const madeNoun = (kind: MadeKind | undefined): string => (kind && MADE[kind]) || "picture";
+
/** "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";
+/**
+ * How far a job on this computer is, from its own steps (so the tile's % and time left agree with "step 9 of 12"), or
+ * null when its steps don't say.
+ */
+export function jobFraction(job: { phase: string; value?: number; max?: number }): number | null {
+ if (job.phase !== "running" || !job.max || job.max < 2 || job.value === undefined) return null;
+ return Math.min(0.99, Math.max(0, job.value / job.max));
+}
+
+/** How long a saved job's tile says it is saving, at most, when its run doesn't move on first. */
+export const DONE_SHOWN_MS = 20_000;
+
+export const savingWords = (fraction: number | undefined, waiting = false) =>
+ waiting ? "Saving to Fuobe · waiting for the studio" : fraction !== undefined && fraction > 0 ? `Saving to Fuobe · ${Math.min(100, Math.floor(fraction * 100))}%` : "Saving to Fuobe";
+
+/** The server's words that say something is wrong (the tab shows them over its own). */
+const PROBLEM = (server: string | undefined) =>
+ !!server && [RELAY_WORDS.comfyDown, RELAY_WORDS.comfyNoSetting, RELAY_WORDS.resent, RELAY_WORDS.noComputer].includes(server as never);
/**
* A run's words in the tab that runs its job (lib/computer-runner.ts's LocalJob), at once: the server's own say the same
- * a poll later. Sending keeps the server's words (they name what is sent); done or failed leaves the last word to it.
+ * a poll later. ComfyUI here not answering, or answering without Fuobe's setting (`comfy`), says so whatever the job's
+ * phase until its results are saving. Sending keeps the server's words when they name what is sent or what is wrong;
+ * done says it is saving until the run's own status moves on; failed leaves the last word to the server.
*/
export function jobWords(
- job: { phase: "sending" | "queued" | "running" | "saving" | "done" | "failed"; position?: number; value?: number; max?: number; saved?: number },
+ job: { phase: "sending" | "queued" | "running" | "saving" | "done" | "failed"; position?: number; value?: number; max?: number; saved?: number; waiting?: boolean },
kind: MadeKind,
server: string | undefined,
+ comfy: "ok" | "down" | "no-setting" = "ok",
): string | undefined {
+ if (comfy !== "ok" && job.phase !== "saving" && job.phase !== "done" && job.phase !== "failed") return comfy === "down" ? RELAY_WORDS.comfyDown : RELAY_WORDS.comfyNoSetting;
switch (job.phase) {
case "sending":
- return server?.startsWith("Sending your") ? server : RELAY_WORDS.starting;
+ return server?.startsWith("Sending your") || PROBLEM(server) ? server : RELAY_WORDS.starting;
case "queued":
return queueWords(job.position);
case "running":
return makingWords(kind, job.value, job.max);
case "saving":
- return savingWords(job.saved);
+ return savingWords(job.saved, job.waiting);
+ case "done":
+ return savingWords(1);
default:
return server;
}
}
+/** "30 minutes", "4 hours", "1 hour". */
+export function duration(ms: number): string {
+ const minutes = Math.max(1, Math.round(ms / 60_000));
+ if (minutes % 60 === 0) return minutes === 60 ? "1 hour" : `${minutes / 60} hours`;
+ return minutes === 1 ? "1 minute" : `${minutes} minutes`;
+}
+
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.`,
+ waitedTooLong: (ms: number) => `Fuobe couldn't reach your computer for ${duration(ms)}. 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.",
+ comfyNoSetting: "ComfyUI is running without Fuobe's setting. Fuobe goes on once it has it.",
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",
+ switched: "This run stopped because ComfyUI now runs somewhere else. Press Retry.",
} as const;
/** The words for a tab's own failure. */
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 6f62fce7..1173409a 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -95,11 +95,12 @@ const STATUS_MAX_BYTES = 64 * 1024;
* Is the account's ComfyUI answering, and what is it? Asked at most every 30 s per account, and one check at a time:
* status requests that arrive while one is on its way share its answer.
*/
-export async function gpuState(id: string, gpu: AccountGpu): Promise<{ online: boolean } & GpuInfo> {
- // On the person's own computer: what its Fuobe tab last said (online while it beats).
+export async function gpuState(id: string, gpu: AccountGpu): Promise<{ online: boolean; comfy?: "down" | "no-setting" } & GpuInfo> {
+ // On the person's own computer: what its Fuobe tab last said (online while it beats and its ComfyUI answers; `comfy`:
+ // the tab is open, but ComfyUI is closed or runs without Fuobe's setting).
if (gpu.mode === "computer") {
const f = runnerFacts(`acct:${id}`);
- return { online: !!f?.online, ...(f?.device && { device: f.device }), ...(f?.vramBytes && { vramBytes: f.vramBytes }), ...(f?.version && { version: f.version }) };
+ return { online: !!f?.online, ...(f?.comfy && { comfy: f.comfy }), ...(f?.device && { device: f.device }), ...(f?.vramBytes && { vramBytes: f.vramBytes }), ...(f?.version && { version: f.version }) };
}
const cache = (globalThis.__fuobeAccountGpus ??= new Map());
const hit = cache.get(id);
@@ -141,7 +142,7 @@ export function lastGpuDevice(id: string): string | undefined {
export interface VisitorView {
kind: "guest" | "account";
/** `mode` "computer": the ComfyUI on the person's own computer, which their Fuobe tab runs. */
- gpu: { connected: boolean; mode?: "link" | "computer"; online?: boolean; device?: string; vramBytes?: number };
+ gpu: { connected: boolean; mode?: "link" | "computer"; online?: boolean; comfy?: "down" | "no-setting"; device?: string; vramBytes?: number };
}
/**
@@ -155,7 +156,7 @@ export async function visitorStatus(account: Account | null) {
const viewer: VisitorView = {
kind: account ? "account" : "guest",
gpu: gpu
- ? { connected: true, mode: gpu.mode === "computer" ? "computer" : "link", online: !!live?.online, ...(live?.device && { device: live.device }), ...(live?.vramBytes && { vramBytes: live.vramBytes }) }
+ ? { connected: true, mode: gpu.mode === "computer" ? "computer" : "link", online: !!live?.online, ...(live?.comfy && { comfy: live.comfy }), ...(live?.device && { device: live.device }), ...(live?.vramBytes && { vramBytes: live.vramBytes }) }
: { connected: false },
};
return {
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index bdd31bed..3582ea5a 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -84,6 +84,8 @@ export interface TaskRow {
stop: number;
attempts: number;
down_at: number | null;
+ /** Why the computer's ComfyUI can't take it: "setting" (it answers, without Fuobe's setting), else it doesn't answer. */
+ down_why: string | null;
note: string | null;
created_at: number;
updated_at: number;
@@ -224,28 +226,34 @@ interface RunnerRow {
seen_at: number;
port: number | null;
facts_json: string | null;
+ /** Its ComfyUI at the last beat: answering ("ok"), not ("down"), or answering without Fuobe's setting. */
+ comfy: "ok" | "down" | "no-setting";
}
const runnerOf = (principal: Principal) => rdb().prepare("SELECT * FROM relay_runners WHERE principal = ?").get(principal) as RunnerRow | undefined;
-/** Is a computer of this principal's online (it beat in the last 30 s)? */
+/** Is a computer of this principal's online: it beat in the last 30 s, and its ComfyUI answered? */
export function runnerOnline(principal: Principal, now = Date.now()): boolean {
const r = runnerOf(principal);
- return !!r && now - r.seen_at < RELAY_TIMES.onlineMs;
+ return !!r && r.comfy === "ok" && now - r.seen_at < RELAY_TIMES.onlineMs;
}
-/** What the computer said about its ComfyUI (the last report), and its port. */
-export function runnerFacts(principal: Principal): (ComputerFacts & { port?: number; seenAt: number; online: boolean }) | null {
+/**
+ * What the computer said about its ComfyUI (the last report), and its port. Online: it beat in the last 30 s and its
+ * ComfyUI answered then (a tab whose ComfyUI is closed, or runs without Fuobe's setting, keeps beating: not online).
+ */
+export function runnerFacts(principal: Principal): (ComputerFacts & { port?: number; seenAt: number; online: boolean; comfy?: "down" | "no-setting" }) | null {
const r = runnerOf(principal);
if (!r) return null;
- return { ...json<ComputerFacts>(r.facts_json, {}), ...(r.port && { port: r.port }), seenAt: r.seen_at, online: Date.now() - r.seen_at < RELAY_TIMES.onlineMs };
+ const here = Date.now() - r.seen_at < RELAY_TIMES.onlineMs;
+ return { ...json<ComputerFacts>(r.facts_json, {}), ...(r.port && { port: r.port }), seenAt: r.seen_at, online: here && r.comfy === "ok", ...(here && r.comfy !== "ok" && { comfy: r.comfy }) };
}
-/** Forget a principal's computer (it disconnected, or the account went). */
-export function forgetComputer(principal: Principal): void {
+/** Forget a principal's computer (it disconnected, its runs moved elsewhere: `switched`, or the account went). */
+export function forgetComputer(principal: Principal, why: "Stopped" | "switched" = "Stopped"): void {
rdb().prepare("DELETE FROM relay_runners WHERE principal = ?").run(principal);
for (const t of rdb().prepare(`SELECT id FROM relay_tasks WHERE principal = ? AND state IN (${ACTIVE_STATES.map(() => "?").join(",")})`).all(principal, ...ACTIVE_STATES) as { id: string }[]) {
- endTask(t.id, "canceled", { error: "Stopped" });
+ endTask(t.id, "canceled", { error: why });
}
}
@@ -266,6 +274,7 @@ export function cleanFacts(f: unknown, keep?: ComputerFacts): ComputerFacts {
...(str(o.os, 40) && { os: str(o.os, 40) }),
...(typeof o.portable === "boolean" && { portable: o.portable }),
...((o.cors === "exact" || o.cors === "any" || o.cors === "other") && { cors: o.cors }),
+ ...(typeof o.guard === "boolean" && { guard: o.guard }),
...(loras && { loras }),
};
}
@@ -281,6 +290,10 @@ export interface BeatInput {
stopped?: string[];
/** False: this computer's ComfyUI doesn't answer (a phone, a laptop without one, or ComfyUI restarting). */
ready?: boolean;
+ /** Not ready because ComfyUI answers without Fuobe's setting. */
+ why?: "setting";
+ /** A browser that may not reach this computer's apps yet (it hasn't been allowed): it hears how many wait, never runs them. */
+ listen?: boolean;
}
/**
@@ -294,14 +307,14 @@ export function beat(principal: Principal, b: BeatInput, now = Date.now()): Beat
sweepPrincipal(principal);
const cur = runnerOf(principal);
const elsewhere = !!cur && cur.device !== b.device && cur.lease_until >= now;
- const free = b.ready === false ? cur?.device === b.device : !elsewhere || b.takeover === true;
+ const free = b.listen ? false : b.ready === false ? cur?.device === b.device : !elsewhere || b.takeover === true;
const port = Number.isInteger(b.port) && b.port! > 0 && b.port! < 65536 ? b.port! : null;
if (free) {
const facts = b.facts !== undefined ? cleanFacts(b.facts, json<ComputerFacts>(cur?.facts_json ?? null, {})) : json<ComputerFacts>(cur?.device === b.device ? cur.facts_json : null, {});
d.prepare(
- `INSERT INTO relay_runners (principal, device, lease_until, seen_at, port, facts_json) VALUES (?, ?, ?, ?, ?, ?)
- ON CONFLICT(principal) DO UPDATE SET device = excluded.device, lease_until = excluded.lease_until, seen_at = excluded.seen_at, port = excluded.port, facts_json = excluded.facts_json`,
- ).run(principal, b.device, now + RELAY_TIMES.leaseMs, now, port, JSON.stringify(facts));
+ `INSERT INTO relay_runners (principal, device, lease_until, seen_at, port, facts_json, comfy) VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(principal) DO UPDATE SET device = excluded.device, lease_until = excluded.lease_until, seen_at = excluded.seen_at, port = excluded.port, facts_json = excluded.facts_json, comfy = excluded.comfy`,
+ ).run(principal, b.device, now + RELAY_TIMES.leaseMs, now, port ?? (cur?.device === b.device ? cur.port : null), JSON.stringify(facts), b.ready === false ? (b.why === "setting" ? "no-setting" : "down") : "ok");
}
// The tasks this computer works on stay alive, and their live progress is kept.
for (const r of (b.running ?? []).slice(0, 32)) {
@@ -416,12 +429,38 @@ export function inputFor(t: TaskRow, n: number): { path: string; size: number; c
function endTask(id: string, state: "done" | "failed" | "canceled", fields: Partial<TaskRow> = {}, takeOff = state === "canceled") {
const t = rdb().prepare("SELECT state, device FROM relay_tasks WHERE id = ?").get(id) as { state: RelayState; device: string | null } | undefined;
const stop = takeOff && t && t.device && (SENT_STATES as readonly string[]).includes(t.state) ? 1 : 0;
- setTask(id, { state, finished_at: Date.now(), down_at: null, ...(stop && { stop }), ...fields });
+ setTask(id, { state, finished_at: Date.now(), down_at: null, down_why: null, ...(stop && { stop }), ...fields });
progressMap().delete(id);
for (const i of rdb().prepare("SELECT name FROM relay_inputs WHERE task_id = ?").all(id) as { name: string }[]) fs.rmSync(inputFile(i.name), { force: true });
rdb().prepare("DELETE FROM relay_inputs WHERE task_id = ?").run(id);
}
+/**
+ * What is kept of ComfyUI's /prompt refusal, as the tab reported it: the parts the run's words and "Fix it" read (the
+ * error, and each node's errors with the value it got), each cut short, at most 16 KB in all.
+ */
+export function keptRefusal(body: unknown): { error?: Record<string, unknown>; node_errors?: Record<string, unknown> } | null {
+ if (!body || typeof body !== "object") return null;
+ const b = body as { error?: unknown; node_errors?: unknown };
+ const cut = (v: unknown, n: number) => (typeof v === "string" ? v.slice(0, n) : undefined);
+ const obj = (v: unknown) => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined);
+ const err = obj(b.error);
+ const info = obj(err?.extra_info);
+ const error = err && { type: cut(err.type, 64), message: cut(err.message, 1024), ...(info && { extra_info: { class_type: cut(info.class_type, 128) } }) };
+ const nodes: Record<string, unknown> = {};
+ for (const [id, raw] of Object.entries(obj(b.node_errors) ?? {}).slice(0, 24)) {
+ const ne = obj(raw);
+ const errors = (Array.isArray(ne?.errors) ? ne.errors : []).slice(0, 6).map((x) => {
+ const e = obj(x);
+ const ei = obj(e?.extra_info);
+ return { type: cut(e?.type, 64), message: cut(e?.message, 300), details: cut(e?.details, 300), extra_info: { input_name: cut(ei?.input_name, 64), received_value: cut(ei?.received_value, 256) } };
+ });
+ nodes[id.slice(0, 32)] = { class_type: cut(ne?.class_type, 128), errors };
+ }
+ const kept = { ...(error && { error }), node_errors: nodes };
+ return JSON.stringify(kept).length <= RELAY_LIMITS.keptRefusalBytes ? kept : { ...(error && { error }), node_errors: {} };
+}
+
/** What the server does with a finished prompt: the files it wants, a meta-batch to follow, or a failure. */
export type FinishedPlan = { wanted: WantedFile[]; outputs: unknown[]; budget: number } | { follow: string } | { error: string };
@@ -449,7 +488,7 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
if (t.state === "canceled") return { ok: true, stop: true };
throw new RelayError(409, `That doesn't fit this run now (${t.state})`);
}
- const seen = { device_seen_at: now, down_at: null };
+ const seen = { device_seen_at: now, down_at: null, down_why: null };
switch (e.event) {
case "sent": {
const promptId = typeof e.promptId === "string" && UUID.test(e.promptId) ? e.promptId : typeof e.promptId === "string" && /^[\w-]{1,64}$/.test(e.promptId) ? e.promptId : null;
@@ -457,12 +496,10 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
setTask(t.id, { ...seen, state: "queued", prompt_id: promptId, sent_at: now, attempts: t.attempts + 1 });
return { ok: true };
}
- case "refused": {
- const body = JSON.stringify(e.body ?? null);
- setTask(t.id, { refusal_json: body.length <= 256 * 1024 ? JSON.stringify({ status: Number(e.status) || 400, body: e.body ?? null }) : JSON.stringify({ status: Number(e.status) || 400, body: null }) });
+ case "refused":
+ setTask(t.id, { refusal_json: JSON.stringify({ status: Number(e.status) || 400, body: keptRefusal(e.body) }) });
endTask(t.id, "failed");
return { ok: true };
- }
case "queued":
setTask(t.id, seen);
noteProgress(t.id, { position: e.position }, now);
@@ -517,7 +554,7 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike
endTask(t.id, "failed", { error: "lost" });
return { ok: true };
case "comfy-down":
- setTask(t.id, { device_seen_at: now, ...(t.down_at ? {} : { down_at: now }) });
+ setTask(t.id, { device_seen_at: now, down_why: e.why ?? null, ...(t.down_at ? {} : { down_at: now }) });
return { ok: true };
case "stopped":
setTask(t.id, { stop: 0 });
diff --git a/src/server/db.ts b/src/server/db.ts
index 08c8719f..07a713aa 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -619,7 +619,8 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (
lease_until INTEGER NOT NULL,
seen_at INTEGER NOT NULL,
port INTEGER,
- facts_json TEXT
+ facts_json TEXT,
+ comfy TEXT NOT NULL DEFAULT 'ok'
);
CREATE TABLE IF NOT EXISTS relay_tasks (
id TEXT PRIMARY KEY,
@@ -643,6 +644,7 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (
stop INTEGER NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
down_at INTEGER,
+ down_why TEXT,
note TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
@@ -667,6 +669,12 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (
);
CREATE INDEX IF NOT EXISTS relay_inputs_task ON relay_inputs(task_id);`;
+/** Columns of the relay tables that came later: [table, column, type]. */
+const RELAY_COLUMNS: [string, string, string][] = [
+ ["relay_runners", "comfy", "TEXT NOT NULL DEFAULT 'ok'"],
+ ["relay_tasks", "down_why", "TEXT"],
+];
+
declare global {
var __fuobeDb: Database.Database | undefined;
}
@@ -715,6 +723,11 @@ function open(): Database.Database {
// "Use the ComfyUI on this computer" (src/server/computer): its tables, made here rather than as a numbered migration,
// since other branches add migrations at the same time and a migration is known by its place in the list.
db.exec(RELAY_TABLES);
+ // Columns added after the tables were first made (a data folder that ran an earlier build of this feature).
+ for (const [table, column, type] of RELAY_COLUMNS) {
+ const has = (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column);
+ if (!has) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
+ }
// An account's own runs (its list, its active runs) are found through this index, not by reading every run. Not a
// numbered migration, so branches that add migrations never clash over it; a failure only leaves lists slower.
try {
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 614c41d8..a97256d6 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -86,7 +86,6 @@ import {
requestStop,
resultOf,
runnerFacts,
- runnerOnline,
stageInput,
taskProgress,
type FinishedPlan,
@@ -160,9 +159,22 @@ export const outsideOwnGpu = <T,>(fn: () => T): T => ownGpuStore.exit(fn);
export function computerScope(): Principal | undefined {
const own = ownGpu();
if (own) return own.kind === "computer" ? own.principal : undefined;
+ if (serverScope.getStore()) return undefined;
return getSetting("comfyWhere") === "computer" ? "owner" : undefined;
}
+/** A run the owner sent to the studio's own ComfyUI before Settings moved ComfyUI to the owner's computer. */
+const serverScope = new AsyncLocalStorage<true>();
+
+/**
+ * Whose computer a run sent there belongs to, whatever ComfyUI's place is now: the account's (as its tenant), or the
+ * owner's.
+ */
+function relayPrincipal(): Principal {
+ const account = tenantAccount();
+ return account ? `acct:${account}` : "owner";
+}
+
/** Said when something would call a ComfyUI that only the person's own tab may reach. */
export const ON_COMPUTER_ONLY = "This ComfyUI is on your own computer: only your Fuobe tab there talks to it.";
@@ -1564,7 +1576,7 @@ export function promptRefusal(body: PromptRefusalBody, status: number, manifest:
body.error?.type === "missing_node_type" && packs.length ? `This workflow needs the ${packs.join(" + ")} node pack${packs.length > 1 ? "s" : ""} on ${where} (see scripts/comfy/README.md)` : undefined;
// A LoRA it lacks: point at its model card (a civitai download URL answers 401 without the key) and the LoRA folder setting.
const loraModels = loras.map((l) => ({ file: l.file, folder: "loras", url: loraByFile(l.file)?.page ?? (l.url && !needsToken(l.url) ? l.url : undefined) }));
- let detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...loraModels] }) : (missingPack ?? body.error?.message);
+ let detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...loraModels] }) : (missingPack ?? (typeof body.error?.message === "string" ? body.error.message.slice(0, 1024) : undefined));
// (Settings → LoRAs is the owner's page, for the server's own ComfyUI: an account's, or one on a computer, gets its LoRAs by hand.)
if (detail && !ownGpu() && !computerScope() && loraModels.some((l) => detail!.includes(`"${l.file}"`))) detail = `${detail}\nSet the LoRA folder in Settings → LoRAs and Fuobe downloads LoRAs before a run`;
void status;
@@ -1761,14 +1773,18 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,
const t = checkClocks(found);
const p = taskProgress(t.id);
const kind = extraOf(t).made ?? made ?? "image";
- const waitMinutes = Math.round((tenantAccount() ? ACCOUNT_LIMITS.queueMs : 4 * 3_600_000) / 60_000);
+ const waitMs = tenantAccount() ? ACCOUNT_LIMITS.queueMs : 4 * 3_600_000;
const sentAt = t.sent_at ?? undefined;
- const down = t.down_at ? RELAY_WORDS.comfyDown : undefined;
+ const down = t.down_at ? (t.down_why === "setting" ? RELAY_WORDS.comfyNoSetting : RELAY_WORDS.comfyDown) : undefined;
switch (t.state) {
- case "waiting":
- return { state: "queued", message: runnerOnline(principal) ? RELAY_WORDS.starting : RELAY_WORDS.noComputer, timeoutError: RELAY_WORDS.waitedTooLong(waitMinutes) };
+ case "waiting": {
+ // The computer's tab is open, but its ComfyUI is closed or runs without Fuobe's setting: say that, not "open Fuobe".
+ const f = runnerFacts(principal);
+ const message = f?.online ? RELAY_WORDS.starting : f?.comfy === "no-setting" ? RELAY_WORDS.comfyNoSetting : f?.comfy === "down" ? RELAY_WORDS.comfyDown : RELAY_WORDS.noComputer;
+ return { state: "queued", message, timeoutError: RELAY_WORDS.waitedTooLong(waitMs) };
+ }
case "sending":
- return { state: "queued", message: down ?? (t.note === "resent" ? RELAY_WORDS.resent : sendingWords(inputKinds(t))), timeoutError: RELAY_WORDS.waitedTooLong(waitMinutes), ...(sentAt && { sentAt }) };
+ return { state: "queued", message: down ?? (t.note === "resent" ? RELAY_WORDS.resent : sendingWords(inputKinds(t))), timeoutError: RELAY_WORDS.waitedTooLong(waitMs), ...(sentAt && { sentAt }) };
case "queued":
return { state: "queued", message: down ?? queueWords(p?.position), ...(sentAt && { sentAt }) };
case "running": {
@@ -1798,7 +1814,7 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,
return { state: "succeeded", outputs: await withLayerBoxes(outputs) };
}
case "canceled":
- return { state: "failed", error: RELAY_WORDS.stopped };
+ return { state: "failed", error: t.error === "switched" ? RELAY_WORDS.switched : RELAY_WORDS.stopped };
default:
return { state: "failed", ...relayFailure(t, manifest) };
}
@@ -1881,15 +1897,20 @@ export const comfyProvider: ProviderAdapter = {
return { externalId: body.prompt_id, meta: { ...meta, generationId, ...(worker === "isolated" && { worker }) }, payload: wf };
},
- async poll({ externalId, meta, model }) {
+ async poll({ externalId, meta, model, ...rest }) {
if (!PROMPT_ID.test(externalId)) return { state: "failed", error: "ComfyUI answered with a job id Fuobe can't use." };
const worker: ComfyWorker = meta.worker === "isolated" ? "isolated" : "main";
let manifest: ManifestWorkflow | undefined;
try {
manifest = getWorkflow(String(meta.workflowId)).manifest;
} catch {}
- const computer = computerScope();
- if (computer) return pollComputer(computer, meta, manifest, model?.kind);
+ // A run is followed where it was sent (Settings, or the account's GPU, may have moved since).
+ if (typeof meta.relay === "string") return pollComputer(relayPrincipal(), meta, manifest, model?.kind);
+ if (computerScope()) {
+ // Sent to a link before the account chose this computer: that link is gone.
+ if (ownGpu()) return { state: "failed", error: RELAY_WORDS.switched };
+ return serverScope.run(true, () => comfyProvider.poll({ externalId, meta, model, ...rest }));
+ }
const finished = async (entry: HistoryEntry) => {
if (entry.status?.status_str === "error") {
forget(externalId);
@@ -1948,11 +1969,13 @@ export const comfyProvider: ProviderAdapter = {
};
},
- async cancel({ externalId, meta }) {
+ async cancel(ctx) {
+ const { externalId, meta } = ctx;
// On someone's computer: the task ends now, and its prompt comes off their ComfyUI at their tab's next beat.
- const computer = computerScope();
- if (computer) {
- if (typeof meta?.relay === "string") requestStop(computer, meta.relay);
+ if (typeof meta?.relay === "string") return requestStop(relayPrincipal(), meta.relay);
+ if (computerScope()) {
+ // Sent before ComfyUI moved to a computer: the owner's goes off the studio's own ComfyUI (a link is gone).
+ if (!ownGpu()) await serverScope.run(true, () => comfyProvider.cancel!(ctx));
return;
}
const worker: ComfyWorker = meta?.worker === "isolated" ? "isolated" : "main";
diff --git a/tests/comfy-guard.test.ts b/tests/comfy-guard.test.ts
new file mode 100644
index 00000000..6105f483
--- /dev/null
+++ b/tests/comfy-guard.test.ts
@@ -0,0 +1,189 @@
+/**
+ * Fuobe's guard for ComfyUI (src/lib/comfy-guard.ts), run for real: the file is loaded the way ComfyUI loads a custom
+ * node (its `server` and `comfy.cli_args` stood in for) into an aiohttp app that has ComfyUI's cross-site middleware,
+ * and requests from other websites, from the site the setting names, from ComfyUI's own page and from a program are
+ * sent at it. Needs a Python with aiohttp (FUOBE_TEST_PYTHON, e.g. ComfyUI's own python_embeded\python.exe; else
+ * python3 or python when they have aiohttp): without one, it is skipped.
+ */
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import net from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { GUARD_FILE_NAME, GUARD_SOURCE, guardBase64, isGuard } from "@/lib/comfy-guard";
+
+function pythonWithAiohttp(): string | null {
+ for (const exe of [process.env.FUOBE_TEST_PYTHON, "python3", "python"].filter(Boolean) as string[]) {
+ const r = spawnSync(exe, ["-I", "-c", "import aiohttp"], { encoding: "utf8", timeout: 20_000 });
+ if (r.status === 0) return exe;
+ }
+ return null;
+}
+
+/** A free port in the range local test servers use (3360-3399). */
+async function freePort(): Promise<number> {
+ for (let p = 3360; p <= 3399; p++) {
+ const free = await new Promise<boolean>((resolve) => {
+ const s = net.createServer();
+ s.once("error", () => resolve(false));
+ s.listen(p, "127.0.0.1", () => s.close(() => resolve(true)));
+ });
+ if (free) return p;
+ }
+ throw new Error("No free port in 3360-3399");
+}
+
+const HARNESS = String.raw`
+import asyncio, importlib.util, json, sys, types
+from aiohttp import ClientSession, WSServerHandshakeError, web
+
+guard_path, port, allowed = sys.argv[1], int(sys.argv[2]), sys.argv[3]
+
+def cors(origin):
+ # ComfyUI's cors_middleware: headers only, no check of who asks.
+ @web.middleware
+ async def cors_middleware(request, handler):
+ response = web.Response() if request.method == "OPTIONS" else await handler(request)
+ response.headers["Access-Control-Allow-Origin"] = origin
+ response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
+ return response
+ return cors_middleware
+
+app = web.Application(middlewares=[cors(allowed)] if allowed else [])
+routes = web.RouteTableDef()
+server = types.ModuleType("server")
+class PromptServer: pass
+PromptServer.instance = PromptServer()
+PromptServer.instance.app, PromptServer.instance.routes = app, routes
+server.PromptServer = PromptServer
+comfy, cli = types.ModuleType("comfy"), types.ModuleType("comfy.cli_args")
+cli.args = types.SimpleNamespace(enable_cors_header=allowed or None)
+comfy.cli_args = cli
+sys.modules.update({"server": server, "comfy": comfy, "comfy.cli_args": cli})
+
+def load(name):
+ spec = importlib.util.spec_from_file_location(name, guard_path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+guard = load("fuobe_guard")
+load("fuobe_guard_copy") # a second copy in custom_nodes: still one guard
+
+queued = []
+async def prompt(request):
+ queued.append(await request.text())
+ return web.json_response({"prompt_id": "x"})
[email protected]("/system_stats")
+async def stats(request):
+ return web.json_response({"system": {}})
+async def ws(request):
+ s = web.WebSocketResponse()
+ await s.prepare(request)
+ await s.close()
+ return s
+app.add_routes(routes)
+
+async def main():
+ runner = web.AppRunner(app)
+ await runner.setup()
+ await web.TCPSite(runner, "127.0.0.1", port).start()
+ base, own = f"http://127.0.0.1:{port}", f"http://127.0.0.1:{port}"
+ out = {}
+ async with ClientSession(skip_auto_headers=["User-Agent"]) as s:
+ async def ask(name, method, p, headers):
+ async with s.request(method, base + p, headers=headers, data="{}" if method == "POST" else None) as r:
+ out[name] = r.status
+ if p == "/fuobe/guard" and r.status == 200:
+ out["guard_answer"] = await r.json()
+ evil = {"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site", "Content-Type": "text/plain"}
+ await ask("evil_prompt", "POST", "/prompt", evil)
+ await ask("evil_preflight", "OPTIONS", "/prompt", {"Origin": "https://evil.example", "Access-Control-Request-Method": "POST"})
+ await ask("evil_read", "GET", "/system_stats", {"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"})
+ await ask("null_origin", "POST", "/prompt", {"Origin": "null", "Sec-Fetch-Site": "cross-site"})
+ await ask("no_origin_cross_site", "GET", "/system_stats", {"Sec-Fetch-Site": "cross-site"})
+ await ask("no_origin_same_site", "GET", "/system_stats", {"Sec-Fetch-Site": "same-site"})
+ await ask("site_prompt", "POST", "/prompt", {"Origin": "https://fuobe.example", "Sec-Fetch-Site": "cross-site", "Content-Type": "application/json"})
+ await ask("site_slash", "POST", "/prompt", {"Origin": "https://FUOBE.example/", "Sec-Fetch-Site": "cross-site"})
+ await ask("site_preflight", "OPTIONS", "/prompt", {"Origin": "https://fuobe.example", "Access-Control-Request-Method": "POST"})
+ await ask("site_guard", "GET", "/fuobe/guard", {"Origin": "https://fuobe.example", "Sec-Fetch-Site": "cross-site"})
+ await ask("own_page", "POST", "/prompt", {"Origin": own, "Sec-Fetch-Site": "same-origin"})
+ await ask("own_page_get", "GET", "/system_stats", {"Sec-Fetch-Site": "same-origin"})
+ await ask("program", "POST", "/prompt", {})
+ for name, origin in (("evil_ws", "https://evil.example"), ("site_ws", "https://fuobe.example")):
+ try:
+ async with s.ws_connect(base + "/ws?clientId=abcdefgh", headers={"Origin": origin}) as w:
+ out[name] = 101
+ except WSServerHandshakeError as e:
+ out[name] = e.status
+ out["queued"] = len(queued)
+ out["guards"] = sum(1 for m in app.middlewares if getattr(m, "__name__", "") == "fuobe_guard")
+ print(json.dumps(out))
+ await runner.cleanup()
+
+asyncio.run(main())
+`;
+
+const python = pythonWithAiohttp();
+
+describe("Fuobe's guard for ComfyUI", () => {
+ it("is one plain-ASCII custom node file that adds no nodes and sends nothing", () => {
+ expect(GUARD_FILE_NAME).toMatch(/^[a-z_]+\.py$/);
+ expect(GUARD_SOURCE).toMatch(/^[\x00-\x7f]*$/);
+ expect(Buffer.from(guardBase64(), "base64").toString("latin1")).toBe(GUARD_SOURCE);
+ expect(GUARD_SOURCE).toContain("NODE_CLASS_MAPPINGS = {}");
+ expect(GUARD_SOURCE).not.toMatch(/^\s*(import|from)\s+(requests|urllib\.request|subprocess|socket|http\.client|os)\b/m);
+ expect(GUARD_SOURCE).not.toMatch(/\b(open|eval|exec|system|ClientSession)\(/);
+ expect(isGuard({ guard: 1 })).toBe(true);
+ expect(isGuard({ guard: 0 })).toBe(false);
+ expect(isGuard(null)).toBe(false);
+ });
+
+ const run = async (allowed: string) => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-guard-"));
+ const guard = path.join(dir, GUARD_FILE_NAME);
+ const harness = path.join(dir, "harness.py");
+ fs.writeFileSync(guard, GUARD_SOURCE);
+ fs.writeFileSync(harness, HARNESS);
+ try {
+ const r = spawnSync(python!, ["-I", harness, guard, String(await freePort()), allowed], { encoding: "utf8", timeout: 60_000 });
+ if (r.status !== 0) throw new Error(r.stderr || r.stdout);
+ return JSON.parse(r.stdout.trim().split("\n").pop()!) as Record<string, number> & { guard_answer?: unknown };
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ };
+
+ it.skipIf(!python)("with Fuobe's setting on: turns away every other website, lets the site, ComfyUI's own page and programs in", async () => {
+ const out = await run("https://fuobe.example");
+ expect(out).toMatchObject({
+ evil_prompt: 403,
+ evil_preflight: 403,
+ evil_read: 403,
+ null_origin: 403,
+ no_origin_cross_site: 403,
+ no_origin_same_site: 403,
+ evil_ws: 403,
+ site_prompt: 200,
+ site_slash: 200,
+ site_preflight: 200,
+ site_guard: 200,
+ site_ws: 101,
+ own_page: 200,
+ own_page_get: 200,
+ program: 200,
+ guards: 1,
+ });
+ expect(isGuard(out.guard_answer)).toBe(true);
+ // Only the requests let in queued anything.
+ expect(out.queued).toBe(4);
+ }, 90_000);
+
+ it.skipIf(!python)("with the setting off, it leaves ComfyUI as it was (ComfyUI's own check is on then)", async () => {
+ const out = await run("");
+ expect(out).toMatchObject({ evil_prompt: 200, own_page: 200, program: 200, site_guard: 200, guards: 1 });
+ }, 90_000);
+});
diff --git a/tests/computer-pure.test.ts b/tests/computer-pure.test.ts
index d6c85a64..303f6573 100644
--- a/tests/computer-pure.test.ts
+++ b/tests/computer-pure.test.ts
@@ -4,9 +4,13 @@ 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 { GUARD_FILE_NAME, GUARD_SOURCE, guardBase64 } from "@/lib/comfy-guard";
+import { explainComfyError } from "@/lib/comfy";
+import { fixFromPromptError } from "@/lib/gpu/fix-codes";
import { parseComfyBinary, parseComfyText } from "@/lib/comfy-ws";
-import { browserSupport, COMFY_PORTS, graphProblem, localBase, mayDownload, pageCanReach, pickLook, portsToLook, preflightPath, readPath, statsFacts, typedPort, viewPath, writePath } from "@/lib/local-comfy";
-import { jobWords, makingWords, queueWords, reportAllowed, savingWords, sendingWords, tabFailureWords, type RelayState } from "@/lib/relay";
+import { tileJob, type LocalJob } from "@/lib/computer-runner";
+import { browserSupport, COMFY_PORTS, graphProblem, localBase, mayDownload, pageCanReach, pickLook, portsToLook, preflightPath, readPath, sameFinder, settled, statsFacts, typedPort, viewPath, writePath, type Finder } from "@/lib/local-comfy";
+import { DONE_SHOWN_MS, duration, jobFraction, jobWords, madeNoun, makingWords, queueWords, RELAY_WORDS, reportAllowed, savingWords, sendingWords, tabFailureWords, type RelayState } from "@/lib/relay";
const ID = "0f8fad5b-d9cb-469f-a165-70867728950e";
const OTHER = "7c9e6679-7425-40de-944b-e07fc1f90ae7";
@@ -92,14 +96,49 @@ describe("the local ComfyUI's addresses", () => {
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", () => {
+ it("picks the ComfyUI it can read, then the remembered port, then the usual order (8188 before 8000)", () => {
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 });
+ // Another app on 8000 (a dev server, SillyTavern…) doesn't win over ComfyUI's own port.
+ expect(pickLook([{ port: 8000, state: "unreadable" }, { port: 8188, state: "unreadable" }])).toMatchObject({ port: 8188 });
+ expect(pickLook([{ port: 7821, state: "unreadable" }, { port: 8001, state: "unreadable" }, { port: 8189, state: "unreadable" }])).toMatchObject({ port: 8189 });
+ // A port the person typed, outside the usual ones, comes after them.
+ expect(pickLook([{ port: 3391, state: "unreadable" }, { port: 8190, state: "unreadable" }])).toMatchObject({ port: 8190 });
expect(pickLook([{ port: 8188, state: "none" }])).toEqual({ state: "none" });
});
+ it("the card's screens: several answering ports to pick from, one ComfyUI followed while it restarts, any readable one connects", () => {
+ const stats = { system: {} };
+ const start: Finder = { s: "start" };
+ // Two answer without the setting: ComfyUI's own port first, the other offered.
+ const two = settled(start, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "unreadable" }, { port: 8189, state: "none" }], undefined, undefined, 1);
+ expect(two).toEqual({ s: "needs-setting", port: 8188, back: false, others: [8000] });
+ // ComfyUI on 8188 restarts: waiting for it, though another app still answers on 8000.
+ const waiting = settled(two, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "none" }], undefined, undefined, 5);
+ expect(waiting).toEqual({ s: "waiting", port: 8188, since: 5 });
+ // Each quiet look while it waits keeps the same screen (the same "since", so the 2-minute help comes).
+ const again = settled(waiting, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "none" }], undefined, undefined, 9);
+ expect(again).toEqual(waiting);
+ expect(sameFinder(waiting, again)).toBe(true);
+ // Back without the setting yet.
+ expect(settled(waiting, [{ port: 8188, state: "unreadable" }], undefined, undefined, 11)).toEqual({ s: "needs-setting", port: 8188, back: true });
+ // Back with it on another port (ComfyUI moved): connects.
+ expect(settled(waiting, [{ port: 8188, state: "none" }, { port: 8189, state: "found", stats }], undefined, undefined, 12)).toMatchObject({ s: "found", port: 8189 });
+ // Nothing anywhere; a typed port that missed.
+ expect(settled(start, [{ port: 8188, state: "none" }], undefined, undefined, 1)).toEqual({ s: "none" });
+ expect(settled({ s: "none" }, [{ port: 3391, state: "none" }], undefined, 3391, 1)).toEqual({ s: "none", missed: 3391 });
+ expect(sameFinder({ s: "none" }, { s: "none", missed: 3391 })).toBe(false);
+ });
+
+ it("can tell Fuobe's guard is there", () => {
+ expect(readPath("/fuobe/guard")).toBe("/fuobe/guard");
+ expect(statsFacts({ system: { argv: ["main.py", "--enable-cors-header", "https://fuobe.com"] } }, "https://fuobe.com", true)).toMatchObject({ cors: "exact", guard: true });
+ expect(statsFacts({ system: {} }, "https://fuobe.com", false).guard).toBe(false);
+ expect(statsFacts({ system: {} }, "https://fuobe.com").guard).toBeUndefined();
+ });
+
it("tells the server about the machine, never its command line", () => {
const f = statsFacts(
{
@@ -145,6 +184,24 @@ describe("ComfyUI's live socket", () => {
});
});
+describe("a ComfyUI refusal", () => {
+ it("names a missing node from its message, quoted or not", () => {
+ const fix = (message: string) => fixFromPromptError({ error: { type: "missing_node_type", message } }, "wf", [], () => undefined);
+ expect(fix("Node 'Image Resize' not found. The custom node may not be installed.")).toMatchObject({ code: "comfy_missing_node", items: [{ class: "Image Resize" }] });
+ expect(fix("Cannot execute because node FancyNode does not exist.")).toMatchObject({ items: [{ class: "FancyNode" }] });
+ });
+
+ it("can't stall the server, however long the message (a tab reports what its ComfyUI said)", () => {
+ const at = performance.now();
+ expect(fixFromPromptError({ error: { type: "missing_node_type", message: "node ".repeat(52_000) } }, "wf", [], () => undefined)).toBeNull();
+ const nodeErrors = Object.fromEntries(Array.from({ length: 500 }, (_, i) => [String(i), { class_type: "X".repeat(5000), errors: Array.from({ length: 50 }, () => ({ message: "node ".repeat(2000), details: "d".repeat(5000) })) }]));
+ const words = explainComfyError(nodeErrors);
+ expect(performance.now() - at).toBeLessThan(500);
+ expect(words.split("\n").length).toBeLessThanOrEqual(20);
+ expect(words.length).toBeLessThan(20 * 1000);
+ });
+});
+
describe("the run's words", () => {
it("says what is happening, without jargon", () => {
expect(sendingWords(["image/png"])).toBe("Sending your photo to ComfyUI");
@@ -168,11 +225,50 @@ describe("the run's words", () => {
expect(jobWords({ phase: "running", value: 3, max: 8 }, "image", "Queued")).toBe("Making your picture · step 3 of 8");
expect(jobWords({ phase: "running" }, "video", undefined)).toBe("Making your clip");
expect(jobWords({ phase: "saving", saved: 0.5 }, "image", "Making your picture")).toBe("Saving to Fuobe · 50%");
- // Done or failed here: the server has the last word.
- expect(jobWords({ phase: "done" }, "image", "Saving to Fuobe")).toBe("Saving to Fuobe");
+ expect(jobWords({ phase: "saving", saved: 0.5, waiting: true }, "image", undefined)).toBe("Saving to Fuobe · waiting for the studio");
+ // Done here: still saving until the run itself moves on (never back to an older step the server said).
+ expect(jobWords({ phase: "done" }, "image", "Making your picture · step 6 of 8")).toBe("Saving to Fuobe · 100%");
+ // Failed here: the server has the last word.
expect(jobWords({ phase: "failed" }, "image", undefined)).toBeUndefined();
});
+ it("the tab never says all is well while ComfyUI here is closed or runs without Fuobe's setting", () => {
+ expect(jobWords({ phase: "sending" }, "image", "Queued", "down")).toBe(RELAY_WORDS.comfyDown);
+ expect(jobWords({ phase: "sending" }, "image", "Queued", "no-setting")).toBe(RELAY_WORDS.comfyNoSetting);
+ expect(jobWords({ phase: "running", value: 3, max: 8 }, "image", undefined, "down")).toBe(RELAY_WORDS.comfyDown);
+ // The server's own words for a problem come through while the job is sending.
+ for (const w of [RELAY_WORDS.comfyDown, RELAY_WORDS.comfyNoSetting, RELAY_WORDS.resent, RELAY_WORDS.noComputer]) expect(jobWords({ phase: "sending" }, "image", w)).toBe(w);
+ // Saving goes on from the studio's side whatever ComfyUI does now.
+ expect(jobWords({ phase: "saving", saved: 0.2 }, "image", undefined, "down")).toBe("Saving to Fuobe · 20%");
+ });
+
+ it("says long waits in hours", () => {
+ expect(RELAY_WORDS.waitedTooLong(30 * 60_000)).toContain("for 30 minutes");
+ expect(RELAY_WORDS.waitedTooLong(4 * 3_600_000)).toContain("for 4 hours");
+ expect(duration(3_600_000)).toBe("1 hour");
+ expect(duration(90 * 60_000)).toBe("90 minutes");
+ });
+
+ it("a tile's % and time left come from the job's own steps, and its words name what it makes", () => {
+ expect(jobFraction({ phase: "running", value: 9, max: 12 })).toBe(0.75);
+ expect(jobFraction({ phase: "running", value: 12, max: 12 })).toBe(0.99);
+ expect(jobFraction({ phase: "running" })).toBeNull();
+ expect(jobFraction({ phase: "saving", value: 12, max: 12 })).toBeNull();
+ expect([madeNoun("image"), madeNoun("video"), madeNoun("audio"), madeNoun(undefined)]).toEqual(["picture", "clip", "sound", "picture"]);
+ });
+
+ it("a saved job stays on its tile, saying it is saving, until its run moves on (or a short while)", () => {
+ const job = (taskId: string, phase: LocalJob["phase"], endedAt?: number): LocalJob => ({ taskId, generationId: "g", phase, ...(endedAt !== undefined && { endedAt }) });
+ const saved = job("t1", "done", 1000);
+ expect(tileJob([saved], "g", 1000 + DONE_SHOWN_MS - 1)).toBe(saved);
+ expect(jobWords(saved, "image", "Making your picture · step 6 of 8")).toBe("Saving to Fuobe · 100%");
+ expect(tileJob([saved], "g", 1000 + DONE_SHOWN_MS + 1)).toBeUndefined();
+ // The run's next step (or a run sent again) shows its own job, never the old one.
+ const next = job("t2", "sending");
+ expect(tileJob([saved, next], "g", 1001)).toBe(next);
+ expect(tileJob([saved, next], "other", 1001)).toBeUndefined();
+ });
+
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"]);
@@ -204,11 +300,21 @@ describe("ComfyUI's one setting", () => {
expect(platformOf({ userAgent: "Mozilla/5.0 (X11; Linux x86_64)" })).toBe("linux");
});
- it("gives each install its one fix", () => {
+ it("gives each install its one fix, with Fuobe's guard", () => {
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");
+ // The start file adds the guard itself; every other install gets it to put in custom_nodes.
+ expect(fixFor("portable", "https://fuobe.com").guard).toBeUndefined();
+ for (const i of ["desktop", "stability-matrix", "terminal"] as const) expect(fixFor(i, "https://fuobe.com").guard).toMatch(/custom_nodes/);
+ });
+
+ it("a terminal's fix is the setting to add to its own command, and keeps the port ComfyUI was found on", () => {
+ const usual = fixFor("terminal", "https://fuobe.com", 8188);
+ expect(usual.copy).toBe("--enable-cors-header https://fuobe.com");
+ expect(usual.lead).toMatch(/Add this to the command you start ComfyUI with/);
+ expect(usual.example).toBe("python main.py --enable-cors-header https://fuobe.com");
+ expect(fixFor("terminal", "https://fuobe.com", 8189).example).toBe("python main.py --enable-cors-header https://fuobe.com --port 8189");
});
it("makes a Windows start file for the port and this site only", () => {
@@ -219,9 +325,14 @@ describe("ComfyUI's one setting", () => {
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.
+ // It asks before it stops anything, and never changes the person's own start files.
expect(bat.indexOf("Read-Host")).toBeLessThan(bat.indexOf("Stop-Process"));
- expect(bat).toContain('.bak"');
+ expect(bat).not.toMatch(/\.bak|WriteAllLines|Also add this setting/);
+ // It puts Fuobe's guard into ComfyUI's custom_nodes before ComfyUI starts again, byte for byte.
+ expect(bat).toContain(`FromBase64String('${guardBase64()}')`);
+ expect(bat).toContain(GUARD_FILE_NAME);
+ expect(bat.indexOf(GUARD_FILE_NAME)).toBeLessThan(bat.indexOf("Start-Process"));
+ expect(Buffer.from(guardBase64(), "base64").toString("latin1")).toBe(GUARD_SOURCE);
// 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();
diff --git a/tests/computer-relay.test.ts b/tests/computer-relay.test.ts
index 80eaa9d5..5fca0044 100644
--- a/tests/computer-relay.test.ts
+++ b/tests/computer-relay.test.ts
@@ -262,6 +262,105 @@ describe("a run on the ComfyUI on the person's own computer", () => {
fake.opts.cors = "http://localhost:3000";
});
+ it("ComfyUI started without Fuobe's setting: the tab says so steadily, takes nothing, and the run and the status strip say the same", async () => {
+ const t = tab(routes, cookie, fake.port);
+ await t.runner.beat();
+ fake.opts.cors = "off";
+ try {
+ const pic = await uploadPng();
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await handedOver(id);
+ const seen = new Set<string>();
+ const off = t.runner.onChange((v) => seen.add(v.comfy));
+ const posts = fake.posts();
+ for (let i = 0; i < 3; i++) {
+ expect(await t.runner.beat()).toMatchObject({ runner: true, waiting: 1 });
+ expect(await t.runner.claimAndRun()).toBe(false);
+ }
+ off();
+ // One story, never "isn't answering" in between.
+ expect([...seen]).toEqual(["no-setting"]);
+ expect(fake.posts()).toBe(posts);
+ await tick();
+ expect(getGeneration(id)?.message).toBe(RELAY_WORDS.comfyNoSetting);
+ const { gpuState } = await import("@/server/account-gpu");
+ expect(await gpuState(a, { mode: "computer" })).toMatchObject({ online: false, comfy: "no-setting" });
+ // ComfyUI comes back with the setting: the run goes on by itself.
+ fake.opts.cors = "http://localhost:3000";
+ await work(t);
+ expect((await settle(id))?.status).toBe("succeeded");
+ expect(await gpuState(a, { mode: "computer" })).toMatchObject({ online: true });
+ } finally {
+ fake.opts.cors = "http://localhost:3000";
+ }
+ });
+
+ it("ComfyUI restarted without the setting while it ran a job: the run says the setting is missing, then goes on", async () => {
+ fake.opts.steps = 60;
+ fake.opts.stepMs = 30;
+ const t = tab(routes, cookie, fake.port);
+ await t.runner.beat();
+ const pic = await uploadPng();
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await handedOver(id);
+ const job = t.runner.claimAndRun();
+ for (let i = 0; i < 200 && !t.runner.view.jobs.some((j) => j.phase === "running"); i++) await new Promise((r) => setTimeout(r, 20));
+ fake.opts.cors = "off";
+ try {
+ for (let i = 0; i < 200 && (db().prepare("SELECT down_why FROM relay_tasks WHERE generation_id = ?").get(id) as { down_why: string | null }).down_why !== "setting"; i++) await new Promise((r) => setTimeout(r, 20));
+ await tick();
+ expect(getGeneration(id)?.message).toBe(RELAY_WORDS.comfyNoSetting);
+ expect(t.runner.view.comfy).toBe("no-setting");
+ } finally {
+ fake.opts.cors = "http://localhost:3000";
+ }
+ await job;
+ await work(t);
+ expect((await settle(id))?.status).toBe("succeeded");
+ });
+
+ it("a tab with nothing remembered finds ComfyUI on another port by itself, and runs there", async () => {
+ const { ComputerRunner } = await import("@/lib/computer-runner");
+ const { apiAs, browserLocal, sha256 } = await import("./helpers/computer-tab");
+ const moved: number[] = [];
+ // It starts where nothing answers (the port the studio last heard of, or 8188), as a second browser would.
+ const runner = new ComputerRunner(
+ {
+ api: apiAs(routes, cookie),
+ local: browserLocal(),
+ socket: (url) => new WebSocket(url) as never,
+ sha256,
+ origin: "http://localhost:3000",
+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))),
+ find: async () => ({ port: fake.port }),
+ moved: (port) => moved.push(port),
+ },
+ { device: "device-second-browser", port: 3399, clientId: "client-second-browser" },
+ );
+ await runner.beat();
+ expect(runner.view).toMatchObject({ port: fake.port, comfy: "ok" });
+ expect(moved).toEqual([fake.port]);
+ const pic = await uploadPng();
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await work({ runner } as never);
+ expect((await settle(id))?.status).toBe("succeeded");
+ });
+
+ it("a browser that may not reach this computer yet hears how many runs wait, and never touches ComfyUI or takes the jobs", async () => {
+ const urls: string[] = [];
+ const listening = tab(routes, cookie, fake.port, { device: "device-asking-1", access: "ask", local: async (u) => (urls.push(u), Promise.reject(new TypeError("no"))) });
+ const pic = await uploadPng();
+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });
+ await handedOver(id);
+ expect(await listening.runner.beat()).toMatchObject({ runner: false, waiting: 1 });
+ expect(await listening.runner.claimAndRun()).toBe(false);
+ expect(urls).toEqual([]);
+ const desk = tab(routes, cookie, fake.port, { device: "device-desk-2" });
+ expect(await desk.runner.beat()).toMatchObject({ runner: true });
+ await work(desk);
+ expect((await settle(id))?.status).toBe("succeeded");
+ });
+
it("sends a job again once when ComfyUI restarts and loses it, and fails it kindly the second time", async () => {
const t = tab(routes, cookie, fake.port);
await t.runner.beat();
@@ -346,6 +445,42 @@ describe("a run on the ComfyUI on the person's own computer", () => {
}
});
+ it("follows each run where it was sent when Settings moves ComfyUI: a run on the computer stops saying why, one on the studio's ComfyUI goes on there", async () => {
+ const { setSetting } = await import("@/server/settings");
+ const settingsRoute = await import("@/app/api/settings/route");
+ const { comfyProvider } = await import("@/server/providers/comfyui");
+ setSetting("comfyWhere", "computer");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ try {
+ const text = JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk" });
+ const r = await generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie: owner, ...SITE_HEADERS, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }));
+ expect(r.status).toBe(201);
+ const id = ((await r.json()).items as { id: string }[])[0].id;
+ await handedOver(id);
+ fetched.length = 0;
+ await settingsRoute.PUT(new Request("http://localhost:3000/api/settings", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ comfyWhere: "server" }) }));
+ const g = await settle(id);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toBe(RELAY_WORDS.switched);
+ expect(fetched.filter((u) => u.includes("owner-comfy.test"))).toEqual([]);
+
+ // The other way: a run sent to the studio's ComfyUI is still asked about there, and stopped there.
+ setSetting("comfyWhere", "computer");
+ fetched.length = 0;
+ const ctx = { externalId: "11111111-1111-4111-8111-111111111111", meta: {}, model: undefined } as unknown as Parameters<typeof comfyProvider.poll>[0];
+ const polled = await comfyProvider.poll(ctx).catch(() => null);
+ expect(polled?.state === "failed" && /lost|disappeared/i.test(polled.error ?? "")).toBe(false);
+ expect(fetched.some((u) => u.startsWith("http://owner-comfy.test:8188/history/11111111"))).toBe(true);
+ fetched.length = 0;
+ await comfyProvider.cancel!(ctx).catch(() => null);
+ expect(fetched.some((u) => u.startsWith("http://owner-comfy.test:8188/"))).toBe(true);
+ } finally {
+ setSetting("comfyWhere", "server");
+ }
+ });
+
it("stops a job whose run went, and forgets a deleted account's computer and files", async () => {
const { createTask, purgeComputer, stageInput, sweepRelay, relayDir } = await import("@/server/computer/tasks");
const name = stageInput(`acct:${a}`, FAKE_PNG, "image/png", "x.png");
diff --git a/tests/computer-runner.test.ts b/tests/computer-runner.test.ts
new file mode 100644
index 00000000..c8c7bbcb
--- /dev/null
+++ b/tests/computer-runner.test.ts
@@ -0,0 +1,81 @@
+/**
+ * The Fuobe tab's runner (src/lib/computer-runner.ts) on its own, against a stand-in studio: how it saves a result when
+ * the studio is busy, what it shows once a result is saved, and how it carries a job's token.
+ */
+import { describe, expect, it } from "vitest";
+import { ComputerRunner, tileJob } from "@/lib/computer-runner";
+import { jobWords } from "@/lib/relay";
+
+const TASK = { id: "AAAAAAAAAAAAAAAA", generationId: "g-1", lease: "a".repeat(64), graph: {}, promptId: "00000000-0000-4000-8000-000000000000", preview: false, inputs: [] };
+const WANTED = { n: 0, filename: "a_00001_.png", subfolder: "", type: "output" as const, kind: "image" as const, maxBytes: 100 };
+const ENTRY = { outputs: { "9": { images: [{ filename: WANTED.filename, subfolder: "", type: "output" }] } } };
+
+function studio(answer: (path: string, init: RequestInit, n: number) => Response | undefined) {
+ const reports: Record<string, unknown>[] = [];
+ const headers: Record<string, string>[] = [];
+ const slept: number[] = [];
+ let puts = 0;
+ const api = async (p: string, init: RequestInit = {}) => {
+ if (p.includes("/outputs/") && init.method === "PUT") {
+ puts++;
+ return answer(p, init, puts) ?? Response.json({ received: 4, total: 4, done: true });
+ }
+ if (p.endsWith("/report")) {
+ reports.push(JSON.parse(String(init.body)));
+ headers.push(Object.fromEntries(new Headers(init.headers).entries()));
+ return Response.json({ ok: true });
+ }
+ return new Response(null, { status: 204 });
+ };
+ const local = async () => new Response(new Uint8Array([137, 80, 78, 71]), { status: 200 });
+ const runner = new ComputerRunner({ api, local, sha256: async () => "", origin: "http://x", sleep: async (ms) => void slept.push(ms) }, { device: "device-0001", port: 8188, clientId: "client-0001" });
+ return { runner, reports, headers, slept, puts: () => puts };
+}
+
+const collect = (r: ComputerRunner) => (r as unknown as { collect: (...a: unknown[]) => Promise<void> }).collect(TASK, [WANTED], [ENTRY], []);
+const report = (r: ComputerRunner, e: Record<string, unknown>) => (r as unknown as { report: (...a: unknown[]) => Promise<unknown> }).report(TASK, e);
+
+describe("saving a result", () => {
+ it("waits for a busy studio (429) as long as it says, without counting it as a failure", async () => {
+ const busy = (n: number) => (n <= 5 ? new Response(JSON.stringify({ error: "busy" }), { status: 429, headers: { "Retry-After": "3" } }) : undefined);
+ const s = studio((_, __, n) => busy(n));
+ const waiting: boolean[] = [];
+ s.runner.onChange((v) => v.jobs[0] && waiting.push(!!v.jobs[0].waiting));
+ await collect(s.runner);
+ expect(s.puts()).toBe(6);
+ expect(s.reports).toEqual([]);
+ expect(s.runner.view.jobs[0].phase).toBe("done");
+ expect(s.slept.filter((ms) => ms === 3000)).toHaveLength(5);
+ expect(waiting).toContain(true);
+ expect(jobWords({ phase: "saving", waiting: true }, "image", undefined)).toBe("Saving to Fuobe · waiting for the studio");
+ });
+
+ it("still gives up after three real failures in a row", async () => {
+ const s = studio(() => new Response("no", { status: 500 }));
+ await collect(s.runner);
+ expect(s.puts()).toBe(3);
+ expect(s.reports).toEqual([{ event: "failed", reason: "save-failed" }]);
+ expect(s.runner.view.jobs[0].phase).toBe("failed");
+ });
+
+ it("once saved, keeps the job (and its last preview) for its tile, saying it is saving, until the run moves on", async () => {
+ const s = studio(() => undefined);
+ const frame = new Blob([new Uint8Array([1, 2, 3])], { type: "image/jpeg" });
+ (s.runner as unknown as { job: (t: unknown, p: unknown) => void }).job(TASK, { phase: "running", value: 7, max: 8, preview: frame });
+ await collect(s.runner);
+ const job = s.runner.view.jobs[0];
+ expect(job).toMatchObject({ phase: "done", saved: 1, preview: frame });
+ expect(job.endedAt).toBeTypeOf("number");
+ expect(tileJob(s.runner.view.jobs, TASK.generationId, job.endedAt!)).toBe(job);
+ expect(jobWords(job, "image", "Making your picture · step 6 of 8")).toBe("Saving to Fuobe · 100%");
+ });
+});
+
+describe("a report", () => {
+ it("carries the job's token in a header, not in the report", async () => {
+ const s = studio(() => undefined);
+ await report(s.runner, { event: "queued", position: 0 });
+ expect(s.headers[0]["x-fuobe-lease"]).toBe(TASK.lease);
+ expect(s.reports[0]).toEqual({ event: "queued", position: 0 });
+ });
+});
diff --git a/tests/computer-security.test.ts b/tests/computer-security.test.ts
index 0b87baa5..370111ca 100644
--- a/tests/computer-security.test.ts
+++ b/tests/computer-security.test.ts
@@ -91,6 +91,13 @@ function call(who: Who, method: string, url: string, o: { body?: unknown; raw?:
throw new Error(`no route ${u}`);
}
+/** A report whose body arrives as a stream (to see when the route reads it), with the job's token in its header. */
+function streamed(who: Who, id: string, lease: string, body: ReadableStream<Uint8Array>): Promise<Response> {
+ const headers = new Headers({ host: HOST, "sec-fetch-site": "same-origin", origin: SITE, "content-type": "application/json", "x-fuobe-lease": lease, ...(who !== "guest" && { cookie: cookies[who] }) });
+ const req = new Request(`${SITE}/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers, body, duplex: "half" } as RequestInit);
+ return Promise.resolve(routes.report.POST(req, { params: Promise.resolve({ id }) }));
+}
+
const SAVE = { "9": { class_type: "SaveImage", inputs: { filename_prefix: "fuobe/x", images: ["3", 0] } }, "3": { class_type: "KSampler", inputs: {} } };
/** A run of `principal` on its computer with one job waiting (an input staged under the name its graph loads). */
@@ -123,9 +130,10 @@ async function collecting(outputs: Record<string, unknown>, graph = SAVE) {
const t = waitingTask(`acct:${a}`, graph);
const c = await claimed("a");
expect(c.id).toBe(t.id);
- expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } })).status).toBe(200);
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { event: "sent", promptId: c.promptId } })).status).toBe(200);
const fin = await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, {
- body: { lease: c.lease, event: "finished", entry: { status: { status_str: "success", completed: true }, outputs } },
+ headers: { "x-fuobe-lease": c.lease },
+ body: { event: "finished", entry: { status: { status_str: "success", completed: true }, outputs } },
});
expect(fin.status).toBe(200);
return { ...c, generationId: t.generationId, answer: (await fin.json()) as { wanted?: { n: number; kind: string; maxBytes: number }[]; state?: string } };
@@ -209,7 +217,7 @@ describe("one account can't touch another's jobs", () => {
const c = await claimed("a");
expect(c.id).toBe(t.id);
expect((await call("b", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);
- expect((await call("b", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } })).status).toBe(404);
+ expect((await call("b", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { event: "sent", promptId: c.promptId } })).status).toBe(404);
expect((await put("b", c.id, 0, c.lease, FAKE_PNG)).status).toBe(404);
expect((await call("b", "GET", `/api/gpu/computer/tasks/${c.id}/outputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);
expect((await call("b", "POST", `/api/gpu/computer/tasks/${c.id}/release`, { body: { lease: c.lease } })).status).toBe(404);
@@ -272,7 +280,7 @@ describe("inputs", () => {
for (let i = 1; i < 6; i++) expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(200);
expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(429);
expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/1`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);
- expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } })).status).toBe(200);
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { event: "sent", promptId: c.promptId } })).status).toBe(200);
expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(409);
});
@@ -291,7 +299,7 @@ describe("reports", () => {
it("each is taken only where the job is", async () => {
waitingTask(`acct:${a}`);
const c = await claimed("a");
- const report = (body: Record<string, unknown>) => call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, ...body } });
+ const report = (body: Record<string, unknown>) => call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { ...body } });
expect((await report({ event: "finished", entry: { outputs: ONE_PNG } })).status).toBe(409);
expect((await report({ event: "running", value: 1, max: 2 })).status).toBe(409);
expect((await report({ event: "nonsense" })).status).toBe(400);
@@ -303,12 +311,87 @@ describe("reports", () => {
it("a finished entry over 8 MB is refused", async () => {
waitingTask(`acct:${a}`);
const c = await claimed("a");
- await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } });
- const big = { lease: c.lease, event: "finished", entry: { outputs: { "9": { text: ["x".repeat(9 * 2 ** 20)] } } } };
- expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: big })).status).toBe(413);
+ await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { event: "sent", promptId: c.promptId } });
+ const big = { event: "finished", entry: { outputs: { "9": { text: ["x".repeat(9 * 2 ** 20)] } } } };
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: big })).status).toBe(413);
expect(state(c.id)).toBe("queued");
});
+ it("its token goes in a header and is checked before the report is read: a report about no job of yours costs nothing", async () => {
+ let pulled = 0;
+ const body = new ReadableStream<Uint8Array>({
+ pull(c) {
+ pulled++;
+ c.enqueue(new Uint8Array(1024 * 1024));
+ if (pulled >= 8) c.close();
+ },
+ });
+ const res = await streamed("a", "AAAAAAAAAAAAAAAA", "0".repeat(64), body);
+ expect(res.status).toBe(404);
+ expect(pulled).toBeLessThanOrEqual(1);
+ // The token in the body (as before) is no token.
+ waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { body: { lease: c.lease, event: "sent", promptId: c.promptId } })).status).toBe(409);
+ });
+
+ it("a report other than ComfyUI's own answer is a few KB; a refusal is read only while the job sends", async () => {
+ waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ const report = (body: Record<string, unknown>) => call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body });
+ // Sending: a refusal may be large-ish, nothing more.
+ expect((await report({ event: "refused", status: 400, body: { pad: "x".repeat(300 * 1024) } })).status).toBe(413);
+ expect((await report({ event: "comfy-down", pad: "x".repeat(20 * 1024) })).status).toBe(413);
+ expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(200);
+ // ComfyUI has it: a finished entry may be large, a progress report may not.
+ expect((await report({ event: "running", value: 1, max: 2, node: "x".repeat(20 * 1024) })).status).toBe(413);
+ expect((await report({ event: "running", value: 1, max: 2 })).status).toBe(200);
+ });
+
+ it("reads two of one person's reports at once at most", async () => {
+ waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ let open!: () => void;
+ const gate = new Promise<void>((r) => (open = r));
+ const held = () =>
+ new ReadableStream<Uint8Array>({
+ async pull(ctl) {
+ await gate;
+ ctl.enqueue(new TextEncoder().encode(JSON.stringify({ event: "comfy-down" })));
+ ctl.close();
+ },
+ });
+ const first = streamed("a", c.id, c.lease, held());
+ const second = streamed("a", c.id, c.lease, held());
+ await new Promise((r) => setTimeout(r, 20));
+ const third = await streamed("a", c.id, c.lease, held());
+ expect(third.status).toBe(429);
+ expect(third.headers.get("retry-after")).toBeTruthy();
+ open();
+ expect((await first).status).toBe(200);
+ expect((await second).status).toBe(200);
+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { event: "comfy-down" } })).status).toBe(200);
+ });
+
+ it("keeps at most 16 KB of a refusal, and still says what was missing", async () => {
+ waitingTask(`acct:${a}`);
+ const c = await claimed("a");
+ const nodeErrors = Object.fromEntries(
+ Array.from({ length: 200 }, (_, i) => [String(i), { class_type: "UNETLoader", errors: [{ message: "Value not in list", details: "d".repeat(400), extra_info: { input_name: "unet_name", received_value: `model_${i}.safetensors` } }] }]),
+ );
+ const res = await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, {
+ headers: { "x-fuobe-lease": c.lease },
+ body: { event: "refused", status: 400, body: { error: { type: "prompt_outputs_failed_validation", message: "m".repeat(50_000) }, node_errors: nodeErrors } },
+ });
+ expect(res.status).toBe(200);
+ const kept = (db().prepare("SELECT refusal_json FROM relay_tasks WHERE id = ?").get(c.id) as { refusal_json: string }).refusal_json;
+ expect(kept.length).toBeLessThanOrEqual(16 * 1024 + 64);
+ expect(JSON.parse(kept).body.error.message.length).toBeLessThanOrEqual(1024);
+ expect(tasks.keptRefusal({ node_errors: { "4": { class_type: "UNETLoader", errors: [{ message: "Value not in list", extra_info: { received_value: "x.safetensors" } }] } } })).toMatchObject({
+ node_errors: { "4": { errors: [{ extra_info: { received_value: "x.safetensors" } }] } },
+ });
+ });
+
it("a forged entry with 500 pictures gets 16 wanted, the most an account's run keeps", async () => {
const images = Array.from({ length: 500 }, (_, i) => ({ filename: `x_${String(i + 1).padStart(5, "0")}_.png`, subfolder: "fuobe", type: "output" }));
const c = await collecting({ "9": { images } });
diff --git a/tests/e2e/computer-mode.mjs b/tests/e2e/computer-mode.mjs
index 709eeb36..a380cebe 100644
--- a/tests/e2e/computer-mode.mjs
+++ b/tests/e2e/computer-mode.mjs
@@ -5,10 +5,11 @@
//
// pnpm build && node tests/e2e/computer-mode.mjs
//
-// Checks: the dialog from a refused run, the setting's fix and start file, connecting by itself when ComfyUI comes
-// back, the celebration, the run starting by itself with its steps and live preview, the result in the library; a
-// two-step run; a reload mid-run; another account can't take or fill the job; a guest gets nothing new; a phone and
-// Safari get the link instead.
+// Checks: the dialog from a refused run, the setting's fix (with Fuobe's guard) and start file, connecting by itself
+// when ComfyUI comes back, the celebration, the run starting by itself with its steps and live preview, a tile that
+// never goes backwards, the result in the library; a two-step run; a reload mid-run; ComfyUI started without the
+// setting on a later visit, and closed; a browser not allowed yet, and another browser of the same account; another
+// account can't take or fill the job; a guest gets nothing new; a phone and Safari get the link instead.
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
@@ -43,8 +44,8 @@ async function until(fn, ms = 30_000, every = 250) {
// --- The stand-in ComfyUI, as its own process (a restart is a new process, as for the real one). It has every node and
// model the studio's workflows need, so the GPU check finds the tools ready.
let fakeProc = null;
-async function startFake(cors) {
- const args = ["--port", String(FAKE_PORT), "--cors", cors, "--steps", "8", "--step-ms", "300", "--has", path.join(root, "workflows/comfyui/requirements.json")];
+async function startFake(cors, o = {}) {
+ const args = ["--port", String(FAKE_PORT), "--cors", cors, "--steps", "8", "--step-ms", "300", "--has", path.join(root, "workflows/comfyui/requirements.json"), ...(o.guard ? ["--guard", "1"] : [])];
fakeProc = spawn(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", path.join(root, "tests/helpers/fake-local-comfy.ts"), ...args], { stdio: ["ignore", "pipe", "inherit"] });
await until(() => fetch(`${FAKE}/__fake/stats`).then((r) => r.ok), 15_000);
}
@@ -95,10 +96,13 @@ try {
browser = await launch();
/** A browser context of its own, signed up as `email`; every loopback port but the studio's and the stand-in's refused. */
- async function account(email, o = {}) {
+ async function account(email, o = {}, { port: rememberPort = true, login = false } = {}) {
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, acceptDownloads: true, ...o });
+ // Every request this browser makes to an app on this computer (not the studio), as it leaves the page.
+ ctx.loopback = [];
await ctx.route(/^(https?|wss?):\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+/, (route) => {
const port = Number(new URL(route.request().url()).port);
+ if (port !== APP_PORT) ctx.loopback.push(route.request().url());
return port === APP_PORT || port === FAKE_PORT ? route.continue() : route.abort("connectionrefused");
});
const page = await ctx.newPage();
@@ -106,13 +110,13 @@ try {
await page.goto(`${SITE}/status`, { waitUntil: "load" });
if (email) {
const status = await page.evaluate(
- (email) => fetch("/api/auth/signup", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email, password: "long enough password" }) }).then((r) => r.status),
- email,
+ ({ email, login }) => fetch(login ? "/api/auth/login" : "/api/auth/signup", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email, password: "long enough password" }) }).then((r) => r.status),
+ { email, login },
);
if (status !== 201 && status !== 200) throw new Error(`sign-up answered ${status}`);
}
// The finder looks at the stand-in's port first (and the others are refused anyway).
- await page.evaluate((port) => localStorage.setItem("fuobe.comfy.port", String(port)), FAKE_PORT);
+ if (rememberPort) await page.evaluate((port) => localStorage.setItem("fuobe.comfy.port", String(port)), FAKE_PORT);
return { ctx, page };
}
@@ -156,6 +160,7 @@ try {
await dialog.getByRole("button", { name: "Find my ComfyUI" }).click();
await dialog.getByText("It needs one setting to work with Fuobe").waitFor({ timeout: 20_000 });
check("ComfyUI without the setting: the one setting it needs", true);
+ check("the fix says what the setting does to other websites, and that Fuobe's guard turns them away, before the download", await dialog.getByText(/other websites send work to your ComfyUI\. The start file adds Fuobe's guard/).isVisible());
await page.screenshot({ path: path.join(shots, "2-needs-setting.png") });
const startButton = dialog.getByRole("button", { name: "Download start file" });
if (await startButton.isVisible()) {
@@ -167,6 +172,7 @@ try {
dl.suggestedFilename() === "Start ComfyUI for Fuobe.bat" && text.includes(`--enable-cors-header ${SITE}`) && text.includes(`$Port = ${FAKE_PORT}`) && text.includes("\r\n"),
dl.suggestedFilename(),
);
+ check("the start file adds Fuobe's guard and never changes the person's own start files", text.includes("fuobe_guard.py") && text.includes("Add-Guard $nodes") && !/WriteAllLines\(\$bat|\.bak/.test(text));
} else {
check("the fix for this computer is shown", await dialog.getByText("--enable-cors-header").first().isVisible());
}
@@ -174,8 +180,10 @@ try {
await stopFake();
const waited = await until(() => dialog.getByText("Waiting for ComfyUI to start").isVisible(), 10_000);
check("ComfyUI restarting: waiting for it, by itself", !!waited);
- await startFake(SITE);
+ await startFake(SITE, { guard: true });
await dialog.getByText("Your GPU is connected").waitFor({ timeout: 30_000 });
+ check("the connected screen says Fuobe's guard keeps other websites out", await dialog.getByText("Fuobe's guard keeps other websites out of your ComfyUI.").isVisible());
+ check("nothing on the connected screen leads away from the run that's about to start", (await dialog.getByRole("link", { name: "See them" }).count()) === 0);
check("connected by itself, with no click", true);
check("the GPU is named", await dialog.getByText(/RTX 5090/).first().isVisible());
await page.screenshot({ path: path.join(shots, "3-connected.png") });
@@ -188,22 +196,65 @@ try {
// The dialog closes into the run.
const closed = await until(async () => !(await dialog.isVisible().catch(() => false)), 20_000);
check("the run starts by itself and the dialog closes", !!closed);
- const firstToast = until(() => page.getByText(/^Made on your RTX 5090 in \d+ s\.$/).first().isVisible(), 60_000, 150);
- const tile = await until(() => page.getByText("On your computer · keep this tab open").first().isVisible(), 30_000);
- check("the run's tile says it runs on this computer", !!tile);
- const pill = page.getByRole("status").filter({ hasText: "Your GPU is working · keep this tab open" });
- const pillBox = await until(async () => ((await pill.isVisible()) ? pill.boundingBox() : null), 20_000);
- const sendBox = await page.locator("[data-composer-toolbar]").boundingBox();
- check("the pill says to keep the tab open, clear of the composer", !!pillBox && !!sendBox && pillBox.y + pillBox.height < sendBox.y, JSON.stringify({ pillBox, sendBox }));
+ // The toast, and when the picture showed, as they happen.
+ let toastAt = 0;
+ let pictureAt = 0;
+ const firstToast = until(async () => (await page.getByText(/^Made on your RTX 5090 in \d+ s\.$/).first().isVisible()) && (toastAt = Date.now()), 60_000, 100);
+ // The tile's words and %, as they change, until the run is done: they never go backwards.
+ const labels = [];
+ let sampling = true;
+ const sampler = (async () => {
+ while (sampling) {
+ const t = await page
+ .evaluate(() => {
+ const p = document.querySelector("p.shimmer-text");
+ if (!p) return document.querySelector('img[src^="/api/files/outputs/"]') ? "picture" : null;
+ const pct = /(\d+)%/.exec(p.parentElement?.querySelector("p.font-mono")?.textContent ?? "")?.[1];
+ return `${p.textContent}|${pct ?? ""}`;
+ })
+ .catch(() => null);
+ if (t === "picture" && !pictureAt) pictureAt = Date.now();
+ if (t && labels.at(-1) !== t) labels.push(t);
+ await sleep(100);
+ }
+ })();
+ const tile = await until(() => page.getByText("Keep this tab open", { exact: true }).first().isVisible(), 30_000);
+ check("the run's tile says to keep this tab open", !!tile);
+ const note = page.locator('[data-sidebar="footer"] [role="status"]').filter({ hasText: "Your GPU is working. Keep this tab open." });
+ const noted = await until(() => note.isVisible(), 20_000);
+ check("the note says the GPU is working, in the sidebar's own space", !!noted);
+ // Nothing of Fuobe's own sits over the page's buttons (the newest run's Reuse and More among them).
+ const covered = await page.evaluate(() =>
+ [...document.querySelectorAll("#content button")]
+ .filter((b) => {
+ const r = b.getBoundingClientRect();
+ if (!r.width || !r.height || r.bottom < 0 || r.top > innerHeight) return false;
+ const el = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2);
+ return !!el && !b.contains(el) && !!el.closest('[role="status"]');
+ })
+ .map((b) => b.getAttribute("aria-label") || b.textContent.trim()),
+ );
+ check("no note covers a button of the page", covered.length === 0, covered.join(", "));
const preview = await until(() => page.locator('img[src^="blob:"]').first().isVisible(), 20_000);
check("a live preview from ComfyUI shows on the tile", !!preview);
await page.screenshot({ path: path.join(shots, "4-running.png") });
const done = await until(async () => (await runs(page)).find((g) => g.status === "succeeded" || g.status === "failed"), 60_000);
check("the run finished on the computer", done?.status === "succeeded", done?.error ?? done?.status ?? "no run");
+ await until(() => pictureAt, 10_000, 100);
+ sampling = false;
+ await sampler;
+ const saving = labels.findIndex((l) => l.startsWith("Saving to Fuobe"));
+ const back = saving >= 0 ? labels.slice(saving).filter((l) => /step \d+ of/.test(l)) : [];
+ check("the tile never goes back once it is saving", saving >= 0 && back.length === 0, labels.join(" → "));
+ const off = labels
+ .map((l) => /step (\d+) of (\d+)\|(\d+)$/.exec(l))
+ .filter(Boolean)
+ .filter((m) => Math.abs(Number(m[3]) - (Number(m[1]) / Number(m[2])) * 100) > 15);
+ check("the tile's % agrees with its step count", off.length === 0, off.map((m) => m[0]).join(", "));
const out = done?.outputs?.[0];
const file = out ? await page.evaluate((u) => fetch(u).then((r) => r.headers.get("content-type")), out.url) : null;
check("the result is in the account's library, as a picture", !!out?.assetId && file === "image/png", `${out?.url} ${file}`);
- check("the first run on this computer says where it was made, and how fast", !!(await firstToast));
+ check("the first run on this computer says where it was made, and how fast, once its picture is there", !!(await firstToast) && !!pictureAt && toastAt >= pictureAt - 1500, `toast ${toastAt - pictureAt} ms after the picture`);
await page.screenshot({ path: path.join(shots, "5-done.png") });
const chip = await until(() => page.getByText(/^Your computer · NVIDIA GeForce RTX 5090/).first().isVisible(), 40_000);
check("the status strip says the GPU is this computer's", !!chip);
@@ -242,6 +293,57 @@ try {
const after = (await fakeStats()).posts;
check("a reload mid-run picks the job up again, sent once", again?.status === "succeeded" && after - before === 1, `${again?.status ?? "?"}, prompts sent: ${after - before}`);
+ // 3b. A later visit: ComfyUI started without the setting, and a run waits. The card with the fix opens by itself, the
+ // note, the run and the status strip all say the setting is missing (steadily), and the run goes on once it's there.
+ {
+ await stopFake();
+ await startFake("off");
+ const r = await api(page, "/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a green field" }) });
+ const rid = r.body?.items?.[0]?.id;
+ const card = page.getByRole("dialog");
+ const opened = await until(() => card.getByText("Your ComfyUI needs Fuobe's setting again").isVisible(), 40_000);
+ check("ComfyUI without the setting on a later visit: the card with its fix opens by itself", !!opened);
+ check("the card shows the fix for it", !!(await until(() => card.getByText(/without Fuobe's setting this time/).first().isVisible(), 15_000)));
+ await page.screenshot({ path: path.join(shots, "7-setting-again.png") });
+ const seen = new Set();
+ for (let end = Date.now() + 12_000; Date.now() < end; await sleep(250)) {
+ const t = await page.locator('[data-sidebar="footer"] [role="status"]').first().textContent().catch(() => null);
+ if (t) seen.add(t);
+ }
+ check("the note says the setting is missing, steadily, with its fix", seen.size > 0 && [...seen].every((t) => t.includes("without Fuobe's setting") && t.includes("Show me how")), [...seen].join(" | "));
+ const waiting = (await runs(page)).find((g) => g.id === rid);
+ check("the run says the same", waiting?.message === "ComfyUI is running without Fuobe's setting. Fuobe goes on once it has it.", waiting?.message);
+ check("the status strip doesn't say all is well", !!(await until(() => page.getByText("needs a setting").first().isVisible(), 15_000)));
+ await stopFake();
+ await startFake(SITE, { guard: true });
+ check("connected again by itself", !!(await until(() => card.getByText("Your GPU is connected").isVisible(), 30_000)));
+ await page.keyboard.press("Escape");
+ const ran = await until(async () => (await runs(page)).find((g) => g.id === rid && (g.status === "succeeded" || g.status === "failed")), 60_000);
+ check("the waiting run goes on once ComfyUI has the setting", ran?.status === "succeeded", ran?.error ?? ran?.status);
+ }
+
+ // 3c. ComfyUI closed: the note, the run and the status strip say so (never "starting" or "online"), and the run goes on
+ // once ComfyUI is back.
+ {
+ await stopFake();
+ const r = await api(page, "/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a quiet harbour" }) });
+ const rid = r.body?.items?.[0]?.id;
+ const down = await until(() => page.locator('[data-sidebar="footer"] [role="status"]').filter({ hasText: "ComfyUI isn't answering" }).isVisible(), 30_000);
+ check("ComfyUI closed: the note says so, with a way to find it", !!down && (await page.getByRole("button", { name: "Find my ComfyUI" }).isVisible()));
+ const waiting = await until(async () => (await runs(page)).find((g) => g.id === rid && g.message === "ComfyUI isn't answering. Start it again, and Fuobe goes on by itself."), 20_000);
+ check("the run says ComfyUI isn't answering", !!waiting);
+ check("the status strip says ComfyUI isn't running", !!(await until(() => page.getByText("ComfyUI not running").first().isVisible(), 20_000)));
+ await page.screenshot({ path: path.join(shots, "8-comfy-closed.png") });
+ // Settings → Your GPU, on this computer: what's wrong here and the one fix, never "open Fuobe on that computer".
+ await page.goto(`${SITE}/settings`, { waitUntil: "load" });
+ const settings = await until(() => page.getByText("ComfyUI isn't running on this computer. Start it, and Fuobe connects by itself.").first().isVisible(), 30_000);
+ check("Settings on this computer says ComfyUI isn't running here, with the fix", !!settings && !(await page.getByText("Open Fuobe on the computer with your ComfyUI").first().isVisible()));
+ await page.screenshot({ path: path.join(shots, "8b-settings-closed.png") });
+ await startFake(SITE, { guard: true });
+ const ran = await until(async () => (await runs(page)).find((g) => g.id === rid && (g.status === "succeeded" || g.status === "failed")), 60_000);
+ check("the run goes on once ComfyUI is back", ran?.status === "succeeded", ran?.error ?? ran?.status);
+ }
+
// 4. Another account can't take, read or fill A's job.
const { ctx: bctx, page: bpage } = await account("[email protected]");
await api(bpage, "/api/account/gpu", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ mode: "computer" }) });
@@ -265,7 +367,7 @@ try {
const s = async (p) => (await p).status;
return {
inputs: await s(fetch(`/api/gpu/computer/tasks/${tid}/inputs/0`, { headers: { "x-fuobe-lease": lease } })),
- report: await s(fetch(`/api/gpu/computer/tasks/${tid}/report`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ lease, event: "gone" }) })),
+ report: await s(fetch(`/api/gpu/computer/tasks/${tid}/report`, { method: "POST", headers: { "content-type": "application/json", "x-fuobe-lease": lease }, body: JSON.stringify({ event: "gone" }) })),
outputs: await s(fetch(`/api/gpu/computer/tasks/${tid}/outputs/0?offset=0&total=4`, { method: "PUT", headers: { "x-fuobe-lease": lease }, body: new Uint8Array([137, 80, 78, 71]) })),
release: await s(fetch(`/api/gpu/computer/tasks/${tid}/release`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ lease }) })),
};
@@ -279,6 +381,38 @@ try {
await ctx.close();
}
+ // 4b. A browser that hasn't been allowed to reach this computer's apps never does so by itself: its note asks, the card
+ // explains the browser's question, and once connected it runs the waiting run. Another browser of the same account
+ // then starts where that computer last found ComfyUI.
+ {
+ const { ctx, page } = await account("[email protected]", {}, { port: false });
+ await api(page, "/api/account/gpu", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ mode: "computer" }) });
+ await page.goto(`${SITE}/library`, { waitUntil: "load" });
+ const r = await api(page, "/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a paper boat" }) });
+ const rid = r.body?.items?.[0]?.id;
+ const ask = page.locator('[data-sidebar="footer"] [role="status"]').filter({ hasText: "Run them from this browser?" });
+ check("a browser not allowed yet: its note asks first", !!(await until(() => ask.isVisible(), 30_000)));
+ check("…and it never reached an app on this computer by itself", ctx.loopback.length === 0, ctx.loopback.slice(0, 3).join(" "));
+ await page.evaluate((port) => localStorage.setItem("fuobe.comfy.port", String(port)), FAKE_PORT);
+ await ask.getByRole("button", { name: "Connect" }).click();
+ const card = page.getByRole("dialog");
+ await card.getByText("Run your GPU jobs from this browser").waitFor({ timeout: 15_000 });
+ check("the card explains the browser's question before it comes", await card.getByText("Press Allow. Fuobe only talks to ComfyUI.").isVisible());
+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();
+ check("connected from the card", !!(await until(() => card.getByText("Your GPU is connected").isVisible(), 30_000)));
+ await page.keyboard.press("Escape");
+ const ran = await until(async () => (await runs(page)).find((g) => g.id === rid && (g.status === "succeeded" || g.status === "failed")), 60_000);
+ check("the waiting run ran once this browser was connected", ran?.status === "succeeded", ran?.error ?? ran?.status);
+ // Another browser of the same account, which remembers nothing: it looks where the computer last found ComfyUI.
+ const other = await account("[email protected]", {}, { port: false, login: true });
+ await other.page.evaluate(() => localStorage.setItem("fuobe.computer.reached", "1"));
+ await other.page.goto(`${SITE}/library`, { waitUntil: "load" });
+ const looked = await until(() => other.ctx.loopback.find((u) => u.includes("/system_stats")), 20_000);
+ check("another browser of the account starts where its computer last found ComfyUI", !!looked && looked.includes(`:${FAKE_PORT}/`) && !other.ctx.loopback.some((u) => u.includes(":8188/")), looked ?? other.ctx.loopback.slice(0, 3).join(" "));
+ await other.ctx.close();
+ await ctx.close();
+ }
+
// 5. A guest gets nothing new.
{
const { ctx, page } = await account(null);
@@ -304,6 +438,7 @@ try {
await page.goto(`${SITE}/connect`, { waitUntil: "load" });
const phone = await until(() => page.getByText("Your phone can't run ComfyUI.").first().isVisible(), 30_000);
check("a phone gets the link option, with why", !!phone && (await page.getByText(/public address/i).first().isVisible()));
+ check("…and only the tunnel steps: nothing looks for a ComfyUI on the phone", !(await page.getByText(/No ComfyUI answered|may ask to let this site reach/).first().isVisible().catch(() => false)) && ctx.loopback.length === 0, ctx.loopback.slice(0, 3).join(" "));
await page.screenshot({ path: path.join(shots, "6-phone.png") });
// In "this computer" mode, the phone's page never tries to run the jobs itself: they wait for the computer's tab.
await api(page, "/api/account/gpu", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ mode: "computer" }) });
diff --git a/tests/helpers/computer-tab.ts b/tests/helpers/computer-tab.ts
index e1894997..4b530213 100644
--- a/tests/helpers/computer-tab.ts
+++ b/tests/helpers/computer-tab.ts
@@ -85,12 +85,12 @@ export function browserLocal(site = SITE): RunnerDeps["local"] & { urls: string[
export const sha256 = async (data: ArrayBuffer) => Buffer.from(await crypto.subtle.digest("SHA-256", data)).toString("hex");
/** A tab on this computer for `cookie`, its ComfyUI on `port` (`local`: how it reaches it, when not as a browser does). */
-export function tab(routes: ComputerRoutes, cookie: string, port: number, o: { device?: string; clientId?: string; local?: RunnerDeps["local"] } = {}) {
+export function tab(routes: ComputerRoutes, cookie: string, port: number, o: { device?: string; clientId?: string; local?: RunnerDeps["local"]; access?: "ask" | "blocked" } = {}) {
const api = apiAs(routes, cookie);
const local = o.local ?? browserLocal();
const runner = new ComputerRunner(
{ api, local, socket: (url) => new WebSocket(url) as never, sha256, origin: SITE, sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))) },
- { device: o.device ?? "device-test-1", port, clientId: o.clientId ?? "client-test-1" },
+ { device: o.device ?? "device-test-1", port, clientId: o.clientId ?? "client-test-1", ...(o.access && { access: o.access }) },
);
return { runner, api, local };
}
diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.ts
index 63507e8d..aca71443 100644
--- a/tests/helpers/fake-local-comfy.ts
+++ b/tests/helpers/fake-local-comfy.ts
@@ -40,6 +40,8 @@ export interface LocalComfyOptions {
/** Embedded Python (portable / Easy-Install). */
portable?: boolean;
loras?: string[];
+ /** Fuobe's guard is in its custom nodes (it answers GET /fuobe/guard). */
+ guard?: boolean;
/**
* Everything a requirement index names is installed (the studio's workflows/comfyui/requirements.json): its node
* classes, with the loaders listing its files, and its model files. Without it, this ComfyUI has nothing.
@@ -323,6 +325,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
}
// No list given: an older ComfyUI without the route (the run goes ahead, and ComfyUI has the last word).
if (p === "/models/loras") return opts.loras ? reply(200, opts.loras) : reply(404, { error: "not found" });
+ if (p === "/fuobe/guard") return opts.guard ? reply(200, { guard: 1 }) : reply(404, { error: "not found" });
const has = opts.has ? installed(opts.has) : null;
if (p === "/models") return reply(200, has ? [...has.folders.keys()] : ["checkpoints", "loras", "vae"]);
if (p.startsWith("/models/")) return reply(200, (has?.folders.get(decodeURIComponent(p.slice(8))) ?? []).map((f) => f.name));
@@ -530,7 +533,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
}
// Run on its own: node tests/helpers/fake-local-comfy.ts --port 3371 --cors http://127.0.0.1:3370
-// [--has workflows/comfyui/requirements.json]: everything that index names is installed.
+// [--has workflows/comfyui/requirements.json]: everything that index names is installed. [--guard 1]: Fuobe's guard answers.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
@@ -538,6 +541,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
};
const index = arg("has");
const has = index ? (JSON.parse(readFileSync(index, "utf8")) as IndexLike) : undefined;
- const fake = await startLocalComfy({ cors: arg("cors") ?? "off", steps: Number(arg("steps") ?? 8), stepMs: Number(arg("step-ms") ?? 250), portable: arg("portable") === "1", has }, Number(arg("port") ?? 3371));
+ const fake = await startLocalComfy({ cors: arg("cors") ?? "off", steps: Number(arg("steps") ?? 8), stepMs: Number(arg("step-ms") ?? 250), portable: arg("portable") === "1", guard: arg("guard") === "1", has }, Number(arg("port") ?? 3371));
console.log(`fake ComfyUI on ${fake.url} (cross-site setting: ${fake.opts.cors})`);
}