The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Your computer's ComfyUI: find it, connect, and run from the open tab
Adarsh5531897443f7
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.tsindex d24db036..5c8bd553 100644--- a/src/app/api/auth/me/route.ts+++ b/src/app/api/auth/me/route.ts@@ -1,7 +1,8 @@import { cookies } from "next/headers";import { connection } from "next/server";import { z } from "zod";-import { authEnabled, deleteAccount, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken, verifyAccount } from "@/server/auth";+import { accountGpu, authEnabled, deleteAccount, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken, verifyAccount } from "@/server/auth";+import { getSetting } from "@/server/settings";import { purgeAccount } from "@/server/account-sweep";import { hit } from "@/server/rate";@@ -12,12 +13,15 @@ export async function GET(request: Request) {const session = sessionViewer(sessionCookieOf(request));const owner = !authEnabled() || session?.kind === "owner" || validToken(request.headers.get("authorization"));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";return Response.json({signedIn: owner || !!account,owner,publicSignup: open,...(account && { account: { email: account.email } }),+ ...(computer && { computer: true }),},{ headers: { "Cache-Control": "no-store" } },);diff --git a/src/app/providers.tsx b/src/app/providers.tsxindex 31fa50fd..97afe4a6 100644--- a/src/app/providers.tsx+++ b/src/app/providers.tsx@@ -9,6 +9,8 @@ import { AUTH_CHANNEL } from "@/lib/api";/** The GPU pre-flight's guided fix: loaded after the page, listening for "fuobe:gpu-setup". */const GuidedFixHost = dynamic(() => import("@/components/gpu/guided-fix").then((m) => m.GuidedFixHost), { ssr: false });+/** "Use the ComfyUI on this computer": runs the person's jobs from this browser while it's open. */+const ComputerRunnerHost = dynamic(() => import("@/components/gpu/computer-runner").then((m) => m.ComputerRunnerHost), { ssr: false });import { Toaster } from "@/components/ui/sonner";import { TooltipProvider } from "@/components/ui/tooltip";@@ -41,6 +43,7 @@ export function Providers({ children }: { children: React.ReactNode }) {<Toaster position="top-center" gap={8} offset={29} /><GuestPrompt /><GuidedFixHost />+ <ComputerRunnerHost /></TooltipProvider></QueryClientProvider></ThemeProvider>diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 173f84aa..69a1f2f1 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -39,6 +39,7 @@ import { JobNotifications } from "@/components/job-notifications";import { NAV, type NavGroupDef } from "@/components/nav-items";import { SkillBuilderProvider } from "@/components/skills/skill-builder-provider";import { CONNECT_GPU_EVENT, signInHref, useEngineMode, useStatus, useViewer, type StatusInfo } from "@/lib/api";+import { deviceLabel } from "@/lib/gpu/readiness";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";@@ -438,7 +439,9 @@ function YourGpuChip({ viewer }: { viewer: NonNullable<StatusInfo["viewer"]> })<StatusDot ok={g.online} /> Your GPU<span className="ml-auto">{g.online ? "online" : "offline"}</span></span>- {(g.device || vram) && <span className="truncate text-[11px]">{[g.device, vram && `${vram} VRAM`].filter(Boolean).join(" · ")}</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>+ )}</IntentLink>);}diff --git a/src/components/gpu/account-gpu-section.tsx b/src/components/gpu/account-gpu-section.tsxindex 18cb3fb3..93431bb6 100644--- a/src/components/gpu/account-gpu-section.tsx+++ b/src/components/gpu/account-gpu-section.tsx@@ -1,7 +1,7 @@"use client";import { LogOut } from "lucide-react";-import { YourGpu } from "@/components/gpu/your-gpu";+import { ConnectChoice } from "@/components/gpu/connect-choice";import { Button } from "@/components/ui/button";import { useViewer } from "@/lib/api";@@ -30,7 +30,7 @@ export function AccountGpuSection() {<LogOut /> Sign out</Button></div>- <YourGpu />+ <ConnectChoice /></section>);}diff --git a/src/components/gpu/computer-runner.tsx b/src/components/gpu/computer-runner.tsxnew file mode 100644index 00000000..dcbf7b98--- /dev/null+++ b/src/components/gpu/computer-runner.tsx@@ -0,0 +1,135 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+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 { 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";++/**+ * "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.+ */+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";+ useEffect(() => {+ if (!computer) return;+ let stop = startComputerRunner();+ const again = () => {+ stop();+ stop = startComputerRunner();+ };+ window.addEventListener(RESTART_EVENT, again);+ return () => {+ window.removeEventListener(RESTART_EVENT, 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) {+ const started = useRef(new Map<string, number>());+ 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));+ const gpu = shortGpu(s.view.facts?.device);+ toast.success(`Made on your ${gpu || "GPU"} in ${secs} s.`);+ }+ }, [s]);+}++/** The status strip hears at once when this tab starts or stops running the jobs, or ComfyUI comes and goes. */+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;+ useEffect(() => {+ void qc.invalidateQueries({ queryKey: ["status"] });+ }, [key, qc]);+}++function ComputerNews() {+ const s = useComputerState();+ useFirstRunToast(s);+ useStatusRefresh(s);+ return <ComputerPill s={s} />;+}++const NONE: ComputerState = { holder: "none", view: null };++export function useComputerState(): ComputerState {+ return useSyncExternalStore(subscribeComputer, computerState, () => NONE);+}++/**+ * 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.+ */+export function useLocalJob(generationId: string) {+ const s = useComputerState();+ const job = jobFor(s, generationId);+ 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;+}++function ComputerPill({ s }: { s: ComputerState }) {+ 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;+ 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>+ );+}diff --git a/src/components/gpu/computer-runtime.ts b/src/components/gpu/computer-runtime.tsnew file mode 100644index 00000000..324c90fd--- /dev/null+++ b/src/components/gpu/computer-runtime.ts@@ -0,0 +1,236 @@+/**+ * "Use the ComfyUI on this computer", in the page: the one tab of this browser that runs the person's jobs (a Web Lock+ * picks it), its clock, and what every tab shows of those jobs. The tab that holds the lock beats to the server, takes+ * jobs and runs them on the ComfyUI on 127.0.0.1 (lib/computer-runner.ts); the other tabs hear its jobs on a+ * BroadcastChannel, so a run's tile shows its steps and live preview wherever it is open. No React here: the host+ * 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 { loopbackFetch } from "@/lib/gpu/browser-check";++export { COMPUTER_KICK_EVENT };++const KEYS = {+ device: "fuobe.computer.device",+ client: "fuobe.computer.client",+ port: "fuobe.comfy.port",+ host: "fuobe.comfy.host",+ install: "fuobe.comfy.install",+ firstRun: "fuobe.computer.first-run",+} as const;++const memory = new Map<string, string>();+/** localStorage, which can throw (private windows, blocked site data): then this tab remembers on its own. */+export function stored(key: keyof typeof KEYS): string | null {+ try {+ return localStorage.getItem(KEYS[key]) ?? memory.get(key) ?? null;+ } catch {+ return memory.get(key) ?? null;+ }+}+export function store(key: keyof typeof KEYS, value: string | null): void {+ if (value === null) memory.delete(key);+ else memory.set(key, value);+ try {+ if (value === null) localStorage.removeItem(KEYS[key]);+ else localStorage.setItem(KEYS[key], value);+ } catch {}+}++const randomId = (bytes = 18) => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(bytes)))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");++/** This browser's id with the server: a routing label (which computer took a job), not a secret. */+function idFor(key: "device" | "client"): string {+ let id = stored(key);+ if (!id || !/^[A-Za-z0-9_-]{8,64}$/.test(id)) {+ id = randomId();+ store(key, id);+ }+ return id;+}++/** Where this browser's ComfyUI answered last (the finder remembers it). */+export function rememberedComfy(): { port: number; host: string } | null {+ const port = Number(stored("port"));+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null;+ const host = stored("host");+ return { port, host: host === "localhost" || host === "[::1]" ? host : "127.0.0.1" };+}+export function rememberComfy(port: number, host = "127.0.0.1"): void {+ store("port", String(port));+ store("host", host);+}++// ---------------------------------------------------------------------------+// What the tiles read++export interface ComputerState {+ /** Which tab runs the jobs: this one, another Fuobe tab of this browser, or none yet. */+ holder: "this" | "other" | "none";+ view: RunnerView | null;+}++let state: ComputerState = { holder: "none", view: null };+const listeners = new Set<() => void>();+export const computerState = () => state;+export function subscribeComputer(fn: () => void): () => void {+ listeners.add(fn);+ return () => listeners.delete(fn);+}+function set(next: ComputerState) {+ state = next;+ 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");++const active = (j: LocalJob) => j.phase !== "done" && j.phase !== "failed";++const RESTART_EVENT = "fuobe:computer-restart";+/** Start the runner again (ComfyUI moved to another port). */+export const restartComputerRunner = () => window.dispatchEvent(new Event(RESTART_EVENT));+export { RESTART_EVENT };++let takeover = false;+/** "Run them here instead": this computer takes the person's waiting jobs from the one that has them. */+export function takeOverHere(): void {+ takeover = true;+ window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));+}++// ---------------------------------------------------------------------------+// The clock: a Worker's timer keeps ticking in a hidden tab (a page's own timers slow to once a minute there)++function workerClock(ms: number, tick: () => void): () => void {+ try {+ const url = URL.createObjectURL(new Blob([`setInterval(() => postMessage(0), ${ms})`], { type: "text/javascript" }));+ const w = new Worker(url);+ w.onmessage = tick;+ return () => {+ w.terminate();+ URL.revokeObjectURL(url);+ };+ } catch {+ const id = setInterval(tick, ms);+ return () => clearInterval(id);+ }+}++const sha256 = async (data: ArrayBuffer) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", data))].map((b) => b.toString(16).padStart(2, "0")).join("");++/** The jobs as another tab gets them (the previews go too: they're Blobs). */+type Heard = { holder: "this"; view: RunnerView } | { holder: "none" };++/**+ * 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 {+ 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));+ if (navigator.locks?.request) {+ navigator.locks.request("fuobe-runner", { signal: stop.signal }, run).catch(() => {});+ } else {+ void run();+ }+ return () => {+ stop.abort();+ channel?.close();+ set({ holder: "none", view: null });+ };+}++/** 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> {+ if (signal.aborted) return;+ const where = rememberedComfy() ?? { port: 8188, host: "127.0.0.1" };+ const runner = new ComputerRunner(+ {+ api: (path, init) => fetch(path, { ...init, credentials: "same-origin" }),+ local: loopbackFetch,+ socket: (url) => (typeof WebSocket === "function" ? (new WebSocket(url) as never) : null),+ sha256,+ origin: window.location.origin,+ },+ { device: idFor("device"), port: where.port, host: where.host, clientId: `fuobe-${idFor("client")}` },+ );+ let last = 0;+ const show = (v: RunnerView) => {+ set({ holder: "this", view: { ...v, jobs: [...v.jobs] } });+ // Other tabs hear it a few times a second at most.+ const now = Date.now();+ if (now - last > 250 || !v.jobs.some(active)) {+ last = now;+ publish(v);+ }+ };+ const off = runner.onChange(show);+ show(runner.view);+ let kicked = true;+ let beating = false;+ let claiming = false;+ let nextBeat = 0;+ let nextClaim = 0;+ const kick = () => (kicked = true);+ const release = () => runner.releaseAll((path, body) => void fetch(path, { method: "POST", keepalive: true, credentials: "same-origin", headers: { "Content-Type": "application/json" }, body }));+ // Leaving while a file is moving would cut it: the browser asks first.+ const leaving = (e: BeforeUnloadEvent) => {+ if (runner.view.jobs.some((j) => j.phase === "sending" || j.phase === "saving")) e.preventDefault();+ };+ window.addEventListener(COMPUTER_KICK_EVENT, kick);+ window.addEventListener("pagehide", release);+ window.addEventListener("beforeunload", leaving);+ const tick = () => {+ const now = Date.now();+ if (!beating && (now >= nextBeat || takeover)) {+ beating = true;+ nextBeat = now + beatEvery(runner.view.jobs.some(active));+ const take = takeover;+ takeover = false;+ runner+ .beat(take)+ .then((a) => {+ if (a && a.runner && a.waiting > 0) kicked = true;+ })+ .catch(() => {})+ .finally(() => (beating = false));+ }+ if (!claiming && (kicked || now >= nextClaim)) {+ claiming = true;+ kicked = false;+ nextClaim = now + 30_000;+ runner+ .claimAndRun()+ .then((had) => {+ // One job done: the next one at once.+ if (had) kicked = true;+ })+ .catch(() => {+ // The studio or the connection hiccupped mid-job: the job stays this computer's, and is picked up again soon.+ nextClaim = Date.now() + 5_000;+ })+ .finally(() => (claiming = false));+ }+ };+ const stopClock = workerClock(1000, tick);+ tick();+ await new Promise<void>((resolve) => {+ signal.addEventListener("abort", () => resolve());+ runner.onChange((v) => v.stopped && resolve());+ });+ stopClock();+ off();+ release();+ runner.stop();+ window.removeEventListener(COMPUTER_KICK_EVENT, kick);+ window.removeEventListener("pagehide", release);+ window.removeEventListener("beforeunload", leaving);+ set({ holder: "none", view: runner.view.stopped ? runner.view : null });+}diff --git a/src/components/gpu/connect-choice.tsx b/src/components/gpu/connect-choice.tsxnew file mode 100644index 00000000..98114147--- /dev/null+++ b/src/components/gpu/connect-choice.tsx@@ -0,0 +1,254 @@+"use client";++import { useQuery, useQueryClient } from "@tanstack/react-query";+import { ChevronDown, Cpu, Globe, Loader2, 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 { RELAY_WORDS } from "@/lib/relay";+import { cn } from "@/lib/utils";+import { restartComputerRunner, rememberComfy, rememberedComfy } from "./computer-runtime";+import { ThisComputer, unsupportedWords } from "./this-computer";+import { lookOn, useComputerSupport } from "./use-local-comfy";+import { useComputerState } from "./computer-runner";++/**+ * "Connect your GPU" for an account: the ComfyUI on this computer first (the quickest way: nothing to install, runs+ * while Fuobe is open in this browser), a link (a tunnel) second, for runs that go on with the tab closed. On a phone,+ * in Safari, or on a page that can't ask for the permission, only the link, with why.+ */++export type AccountGpuView =+ | { mode: "computer"; online: boolean; device?: string; vramBytes?: number; version?: string; port?: number; cors?: "exact" | "any" | "other" }+ | { mode: "link"; url: string; hasToken: boolean };++async function gpuCall<T>(method: string, body?: unknown): Promise<T> {+ const res = await fetch("/api/account/gpu", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });+ const j = (await res.json().catch(() => ({}))) as T & { error?: string };+ if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);+ return j;+}++export function useAccountGpu(enabled = true) {+ return useQuery({ queryKey: ["account-gpu"], queryFn: () => gpuCall<{ gpu: AccountGpuView | null }>("GET"), enabled });+}++/** Turn "this computer" on for the signed-in account. */+export async function connectThisComputer(): Promise<void> {+ await gpuCall("PUT", { mode: "computer" });+}++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.";++/** "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 [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 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);+ 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}.`);+ };+ const remove = async () => {+ setBusy(true);+ try {+ qc.setQueryData(["account-gpu"], await gpuCall("DELETE"));+ void qc.invalidateQueries({ queryKey: ["viewer"] });+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setBusy(false);+ }+ };+ return (+ <div className="space-y-3 text-[13px]">+ <div className="flex items-start gap-2.5 rounded-xl bg-brand-faint px-3 py-2.5">+ <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>+ </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>}+ <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()} />+ <Button size="sm" variant="secondary" className="h-8" onClick={() => void lookAt()}>+ Look+ </Button>+ </div>+ {note && <p className="text-[12px] text-muted-foreground">{note}</p>}+ <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+ </button>+ <button type="button" className="flex items-center gap-1 text-muted-foreground hover:text-foreground" onClick={() => setAbout((v) => !v)}>+ About this setting <ChevronDown className={cn("size-3.5 transition-transform", about && "rotate-180")} />+ </button>+ </div>+ {about && <p className="text-[12px] text-muted-foreground">{ABOUT}</p>}+ </div>+ );+}++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;+ onStart?: () => void;+ onNotNow?: () => void;+}++export function ConnectChoice({ fromRun, refind, onStart, onNotNow }: ConnectChoiceProps) {+ const support = useComputerSupport();+ const q = useAccountGpu();+ 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 [link, setLink] = useState(false);+ 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") {+ 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>+ <YourGpu />+ </div>+ );+ }+ if (gpu?.mode === "computer" && !flow && !link) return <ComputerStatus gpu={gpu} onLink={() => setLink(true)} />;+ const linked = gpu?.mode === "link";+ return (+ <div className="w-full min-w-0 space-y-3 sm:max-w-[36rem]">+ <div className={cn("space-y-3 rounded-2xl border bg-background p-4", !linked && "border-primary/40")}>+ <div className="flex items-start gap-3">+ <div className="grid size-9 shrink-0 place-items-center rounded-xl bg-primary text-primary-foreground">+ <Cpu className="size-4" />+ </div>+ <div className="min-w-0">+ <p className="text-[15px] font-medium">{linked ? "Use the ComfyUI on this computer instead" : "Use the ComfyUI on this computer"}</p>+ <p className="text-[13px] text-muted-foreground">The quickest way. Runs while Fuobe is open in this browser.</p>+ </div>+ </div>+ <div onClickCapture={() => setFlow(true)}>+ <ThisComputer+ connect={async () => {+ setFlow(true);+ await connectThisComputer();+ }}+ fromRun={fromRun}+ onStart={onStart}+ onNotNow={onNotNow}+ autoLook={refind}+ />+ </div>+ </div>+ <div className="rounded-2xl border border-dashed p-4">+ <button type="button" className="flex w-full items-start gap-3 text-left" onClick={() => setLink((v) => !v)} aria-expanded={link || linked}>+ <Globe className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1">+ <span className="block text-[13px] font-medium">Run from anywhere with a link</span>+ <span className="block text-[12px] text-muted-foreground">For runs that go on with this tab closed. You'll need a tunnel.</span>+ </span>+ <ChevronDown className={cn("mt-0.5 size-4 shrink-0 text-muted-foreground transition-transform", (link || linked) && "rotate-180")} />+ </button>+ {(link || linked) && (+ <div className="mt-3">+ <YourGpu />+ </div>+ )}+ </div>+ </div>+ );+}++/**+ * The owner's "Where ComfyUI runs" (Settings → Open-source engine · ComfyUI): on this server, at the address below, or+ * on the computer the owner uses, which the owner's own Fuobe tab runs (a studio on a server, a GPU at home).+ */+export function OwnerComfyWhere({ value, onChange }: { value: string; onChange: (v: "server" | "computer") => Promise<unknown> }) {+ const qc = useQueryClient();+ const support = useComputerSupport();+ const [picking, setPicking] = useState(false);+ const computer = value === "computer";+ const choices = [+ { id: "server" as const, title: "On this server", body: "Fuobe calls ComfyUI at the address below, with or without a tab open." },+ { id: "computer" as const, title: "On the computer you're using", body: "Your Fuobe tab runs the jobs on this computer's ComfyUI while it's open." },+ ];+ return (+ <div className="space-y-3">+ <div role="radiogroup" aria-label="Where ComfyUI runs" className="grid gap-2 sm:grid-cols-2">+ {choices.map((c) => {+ const active = c.id === "computer" ? computer || picking : !computer && !picking;+ return (+ <button+ key={c.id}+ type="button"+ role="radio"+ aria-checked={active}+ onClick={() => {+ if (c.id === "server") {+ setPicking(false);+ if (computer) void onChange("server").then(() => qc.invalidateQueries({ queryKey: ["viewer"] }));+ } else if (!computer) setPicking(true);+ }}+ className={cn("flex flex-col gap-1 rounded-xl border p-3 text-left transition-colors hover:bg-accent", active && "border-primary bg-brand-faint hover:bg-brand-faint")}+ >+ <span className="text-[14px] font-medium">{c.title}</span>+ <span className="text-[12px] text-muted-foreground">{c.body}</span>+ </button>+ );+ })}+ </div>+ {support !== "ok" && (picking || computer) ? (+ <p className="text-[13px] text-muted-foreground">{unsupportedWords(support)}</p>+ ) : picking && !computer ? (+ <ThisComputer+ connect={async () => {+ await onChange("computer");+ void qc.invalidateQueries({ queryKey: ["viewer"] });+ }}+ />+ ) : computer ? (+ <OwnerComputerLine />+ ) : null}+ </div>+ );+}++function OwnerComputerLine() {+ const local = useComputerState();+ const facts = local.view?.facts;+ const ready = local.holder === "this" && local.view?.comfy === "ok";+ 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>+ );+}diff --git a/src/components/gpu/connect-gpu.tsx b/src/components/gpu/connect-gpu.tsxindex 22f4dd7d..6629695f 100644--- a/src/components/gpu/connect-gpu.tsx+++ b/src/components/gpu/connect-gpu.tsx@@ -7,7 +7,7 @@ import { useSearchParams } from "next/navigation";import { useEffect, useRef } from "react";import { PreflightChecklist } from "@/components/gpu/preflight-checklist";import { ReadinessBoard } from "@/components/gpu/readiness-board";-import { YourGpu } from "@/components/gpu/your-gpu";+import { ConnectChoice } from "@/components/gpu/connect-choice";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";import { useGpuCheck, useGpuReadiness } from "@/hooks/use-gpu";@@ -39,10 +39,11 @@ export function ConnectGpu() {// The account's own address: when it changes (connected, edited), the board starts over.const gpu = useQuery({queryKey: ["account-gpu"],- queryFn: async () => (await (await fetch("/api/account/gpu")).json()) as { gpu: { url: string } | null },+ queryFn: async () => (await (await fetch("/api/account/gpu")).json()) as { gpu: { mode: "computer" } | { mode?: "link"; url: string } | null },enabled: isAccount,});- const url = gpu.data?.gpu?.url ?? null;+ const g = gpu.data?.gpu;+ const url = g ? (g.mode === "computer" ? "this computer" : g.url) : null;const lastUrl = useRef<string | null | undefined>(undefined);useEffect(() => {if (!isAccount || gpu.isLoading) return;@@ -130,7 +131,7 @@ export function ConnectGpu() {{header(1)}{isAccount ? (<Card>- <YourGpu />+ <ConnectChoice /></Card>) : (<p className="text-[14px] text-muted-foreground">The GPU check is switched off on this studio (FUOBE_GPU_PREFLIGHT=0).</p>@@ -145,7 +146,7 @@ export function ConnectGpu() {<Card><h2 className="mb-1 text-[16px] font-semibold">Where is ComfyUI running?</h2>{reason === "refused" && <p className="mb-3 text-[13px] text-destructive">Fuobe can't use this address. Connect your own ComfyUI.</p>}- <YourGpu />+ <ConnectChoice /></Card>{done}</div>@@ -162,7 +163,7 @@ export function ConnectGpu() {<h2 className="text-[16px] font-semibold">{check.running ? "Checking your setup" : "Your ComfyUI"}</h2>{isAccount ? (<Link href="/settings#your-gpu" className="text-[13px] text-brand-text underline-offset-2 hover:underline">- Change the link+ {view?.target === "computer" ? "Change where it runs" : "Change the link"}</Link>) : (<Link href="/settings#comfyui" className="text-[13px] text-brand-text underline-offset-2 hover:underline">diff --git a/src/components/gpu/this-computer.tsx b/src/components/gpu/this-computer.tsxnew file mode 100644index 00000000..475f5083--- /dev/null+++ b/src/components/gpu/this-computer.tsx@@ -0,0 +1,436 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { Check, ChevronDown, Copy, Download, Loader2, MonitorSmartphone, RefreshCw, Search, 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 type { ReadinessView } from "@/hooks/use-gpu";+import { copyWithToast } from "@/lib/clipboard";+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 { deviceLabel } from "@/lib/gpu/readiness";+import { statsFacts, typedPort, type SystemStats } from "@/lib/local-comfy";+import { cn } from "@/lib/utils";+import { rememberComfy, rememberedComfy, 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).+ */++const INSTALLS: { id: ComfyInstall; label: string }[] = [+ { id: "desktop", label: "ComfyUI Desktop" },+ { id: "portable", label: "Portable or Easy-Install" },+ { id: "stability-matrix", label: "Stability Matrix" },+ { id: "terminal", label: "Started from a terminal" },+];++const origin = () => (typeof window === "undefined" ? "https://fuobe.com" : window.location.origin);+const nav = () => navigator as Navigator & { userAgentData?: { platform?: string } };++function CopyLine({ text, label }: { text: string; label: string }) {+ return (+ <div className="flex items-center gap-2 rounded-lg bg-muted px-2.5 py-2">+ <code aria-label={label} className="min-w-0 flex-1 overflow-x-auto font-mono text-[12px] whitespace-nowrap">+ {text}+ </code>+ <button+ type="button"+ onClick={() => void copyWithToast(text)}+ className="grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-background hover:text-foreground"+ aria-label={`Copy ${label}`}+ >+ <Copy className="size-3.5" />+ </button>+ </div>+ );+}++/** A soft pulsing dot and a line: Fuobe is watching for something by itself. */+function Watching({ children }: { children: React.ReactNode }) {+ return (+ <p className="flex items-center gap-2 text-[12px] text-muted-foreground">+ <span className="relative flex size-2 shrink-0">+ <span className="absolute inline-flex size-full animate-ping rounded-full bg-primary/60" />+ <span className="relative inline-flex size-2 rounded-full bg-primary" />+ </span>+ {children}+ </p>+ );+}++/** What the browser's question looks like, with the button to press. */+function PromptPicture() {+ const host = typeof window === "undefined" ? "fuobe.com" : window.location.host;+ return (+ <div aria-hidden className="w-56 max-w-full shrink-0 rounded-lg border bg-background p-2.5 text-[11px] shadow-sm">+ <p className="font-medium">{host} wants to</p>+ <p className="mt-0.5 text-muted-foreground">Access other apps and services on this device</p>+ <div className="mt-2 flex justify-end gap-1.5">+ <span className="rounded-md border px-2 py-0.5 text-muted-foreground">Block</span>+ <span className="rounded-md bg-primary px-2 py-0.5 font-medium text-primary-foreground ring-2 ring-primary/40 ring-offset-1 ring-offset-background">Allow</span>+ </div>+ </div>+ );+}++function blockedSteps(): string {+ const ua = typeof navigator === "undefined" ? "" : navigator.userAgent;+ if (/Firefox\//.test(ua)) return "Click the icon to the left of the address and allow apps and services on this device, then reload.";+ if ((navigator as Navigator & { brave?: unknown }).brave) return "Click the Brave icon and allow localhost access, then reload.";+ return "Click the icon to the left of the address, turn on Apps on device, then reload.";+}++const UNSUPPORTED: Record<"safari" | "phone" | "http", string> = {+ phone: "Your phone can't run ComfyUI. Open Fuobe on your computer to use its ComfyUI, or run from anywhere with a link.",+ safari: "Safari can't reach apps on this computer from a website. Open Fuobe in Chrome, Edge or Firefox to use your ComfyUI directly, or run from anywhere with a link.",+ http: "Your browser only lets a secure page reach apps on this computer. Open the studio over https, or on the computer that runs ComfyUI, or run from anywhere with a link.",+};++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())));+ 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);+ };+ 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="mt-1 text-[13px] text-muted-foreground">{fix.lead}</p>+ </div>+ {fix.startFile ? (+ <>+ <Button className="h-11 sm:h-9" onClick={download}>+ <Download /> Download start file+ </Button>+ <p className="text-[12px] text-muted-foreground">+ Restarting stops anything ComfyUI is making right now. If Windows warns you about a file from the internet, press More info, then Run anyway.+ </p>+ <div>+ <button type="button" onClick={() => setYourself((v) => !v)} className="flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground">+ <ChevronDown className={cn("size-3.5 transition-transform", yourself && "rotate-180")} /> Rather do it yourself?+ </button>+ {yourself && (+ <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" />+ </div>+ )}+ </div>+ </>+ ) : (+ <>+ <CopyLine text={fix.copy} label={install === "desktop" ? "the address" : "the setting"} />+ {fix.path && <p className="text-[12px] text-muted-foreground">{fix.path.join(" → ")}</p>}+ </>+ )}+ <div>+ <button type="button" onClick={() => setChoosing((v) => !v)} className="text-[12px] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">+ Not what you use?+ </button>+ {choosing && (+ <div className="mt-2 flex flex-wrap gap-1.5">+ {INSTALLS.map((i) => (+ <Button+ key={i.id}+ size="sm"+ variant={i.id === install ? "secondary" : "ghost"}+ className="h-8"+ onClick={() => {+ setInstall(i.id);+ store("install", i.id);+ setChoosing(false);+ }}+ >+ {i.label}+ </Button>+ ))}+ </div>+ )}+ </div>+ <Watching>Fuobe connects by itself when ComfyUI is back.</Watching>+ </div>+ );+}++function OtherPort({ onLook, missed }: { onLook: (port: number, host: string) => void; missed?: number }) {+ const [typed, setTyped] = useState(String(rememberedComfy()?.port ?? 8188));+ const [bad, setBad] = useState(false);+ const go = () => {+ const p = typedPort(typed);+ setBad(!p);+ if (p) onLook(p.port, p.host);+ };+ return (+ <div className="space-y-1.5">+ <p className="text-[12px] text-muted-foreground">ComfyUI on another port?</p>+ <div className="flex gap-2">+ <Input aria-label="ComfyUI's port" inputMode="numeric" className="h-9 w-28" value={typed} onChange={(e) => setTyped(e.target.value)} onKeyDown={(e) => e.key === "Enter" && go()} />+ <Button size="sm" variant="secondary" className="h-9" onClick={go}>+ <Search /> Look+ </Button>+ </div>+ {bad && <p className="text-[12px] text-destructive">Enter the port ComfyUI shows, like 8188.</p>}+ {!bad && missed && <p className="text-[12px] text-muted-foreground">Nothing answered on port {missed}.</p>}+ </div>+ );+}++type Connected = { port: number; stats: SystemStats; board?: ReadinessView | null; checkFailed?: boolean };++function readyLine(board: ReadinessView | null | undefined): string | null {+ const studios = board?.report?.studios;+ if (!studios?.length) return null;+ const ready = studios.filter((s) => s.tool.state === "ready").length;+ const near = studios.filter((s) => s.tool.state === "almost" || s.tool.state === "setup").length;+ return `Ready now: ${ready} ${ready === 1 ? "studio" : "studios"}${near ? ` · ${near} need${near === 1 ? "s" : ""} a one-time download or setup` : ""}`;+}++/** 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());+ 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;+ const [starting, setStarting] = useState(false);+ const [stopped, setStopped] = useState(false);+ // Opened from a run: once the check is in (or after a few seconds), the run starts by itself.+ useEffect(() => {+ if (!fromRun || stopped) return;+ const t = setTimeout(() => setStarting(true), checked ? 300 : 4000);+ return () => clearTimeout(t);+ }, [fromRun, stopped, checked]);+ useEffect(() => {+ if (!starting || stopped) return;+ const t = setTimeout(() => onStart?.(), 1200);+ return () => clearTimeout(t);+ }, [starting, stopped, onStart]);+ return (+ <div className="space-y-3 rounded-2xl bg-brand-faint p-4">+ <div className="flex items-center gap-3">+ <div className="grid size-10 shrink-0 animate-in place-items-center rounded-full bg-primary text-primary-foreground duration-300 zoom-in-50 fade-in-0">+ <Check className="size-5" />+ </div>+ <div className="min-w-0">+ <p className="text-[15px] font-semibold">Your GPU is connected</p>+ {gpu && <p className="truncate text-[13px] text-muted-foreground">{gpu}</p>}+ </div>+ </div>+ {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>+ )}+ <p className="text-[13px]">+ {!checked ? (+ <span className="flex items-center gap-2 text-muted-foreground">+ <Loader2 className="size-3.5 animate-spin" /> Checking what your ComfyUI has…+ </span>+ ) : ready ? (+ <>+ {ready}.{" "}+ <a href="/connect" className="text-brand-text underline-offset-4 hover:underline">+ See them+ </a>+ </>+ ) : null}+ </p>+ {fromRun && !stopped ? (+ <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>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => {+ setStopped(true);+ onNotNow?.();+ }}+ >+ Not now+ </Button>+ </div>+ ) : (+ !fromRun && <p className="text-[13px] text-muted-foreground">Done. Runs from the Image, Video and Audio studios now use your GPU. Keep a Fuobe tab open while they run.</p>+ )}+ </div>+ );+}++export interface ThisComputerProps {+ /** Connect "this computer" on the server (an account's Your GPU, or the owner's setting). */+ connect: () => Promise<void>;+ /** Opened from a run that needs a GPU: it starts by itself once connected. */+ fromRun?: boolean;+ /** Start the run (fromRun), then close. */+ onStart?: () => void;+ onNotNow?: () => void;+ /** Look at once (Settings, after the person picked this option). */+ autoLook?: boolean;+}++/** The whole flow, from "Find my ComfyUI" to connected. */+export function ThisComputer({ connect, fromRun, onStart, onNotNow, autoLook }: ThisComputerProps) {+ const qc = useQueryClient();+ const { state, look } = useLocalComfy(true);+ const [done, setDone] = useState<Connected | null>(null);+ const [error, setError] = useState<string | null>(null);+ const connecting = useRef<string | null>(null);+ const autoLooked = useRef(false);++ useEffect(() => {+ if (!autoLook || autoLooked.current || state.s !== "start") return;+ autoLooked.current = true;+ void look();+ }, [autoLook, state.s, look]);++ // Found and readable: connect with no click, then check what it has.+ useEffect(() => {+ if (state.s !== "found") return;+ const key = `${state.host}:${state.port}`;+ if (connecting.current === key) return;+ connecting.current = key;+ const { port, host, stats } = state;+ void (async () => {+ try {+ await connect();+ rememberComfy(port, host);+ store("install", installFromStats(stats, port, platformOf(nav())));+ setError(null);+ setDone({ port, stats });+ void qc.invalidateQueries({ queryKey: ["viewer"] });+ void qc.invalidateQueries({ queryKey: ["account-gpu"] });+ try {+ const board = await sendCheck<ReadinessView>(await checkThisComputer(port, { host }));+ qc.setQueryData(["gpu", "readiness"], board);+ void qc.invalidateQueries({ queryKey: ["gpu", "badges"] });+ void qc.invalidateQueries({ queryKey: ["gpu", "plan"] });+ setDone({ port, stats, board });+ } catch {+ setDone({ port, stats, checkFailed: true });+ }+ } catch (e) {+ connecting.current = null;+ setError((e as Error).message);+ }+ })();+ }, [state, connect, qc]);++ if (done) return <Celebration c={done} fromRun={fromRun} onStart={onStart} onNotNow={onNotNow} />;+ return (+ <div className="space-y-3 text-[13px]">+ <Screen state={state} look={look} />+ {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]);+ const lookAt = (port: number, host: string) => void look({ ports: [{ port, host }] });+ switch (state.s) {+ case "unsupported":+ return (+ <p className="flex items-start gap-2 text-muted-foreground">+ <MonitorSmartphone className="mt-0.5 size-4 shrink-0" /> {UNSUPPORTED[state.why]}+ </p>+ );+ case "start":+ return (+ <div className="space-y-3">+ <Button className="h-11 sm:h-9" onClick={() => void look()}>+ <Search /> Find my ComfyUI+ </Button>+ <div className="flex flex-wrap items-center gap-3">+ <PromptPicture />+ <p className="min-w-[12rem] flex-1 text-[12px] text-muted-foreground">Your browser will ask to let Fuobe reach apps on this computer. Press Allow. Fuobe only talks to ComfyUI.</p>+ </div>+ </div>+ );+ case "looking":+ return (+ <p className="flex items-center gap-2 text-muted-foreground">+ <Loader2 className="size-4 animate-spin" /> Looking for ComfyUI on this computer…+ </p>+ );+ case "found":+ return (+ <p className="flex items-center gap-2">+ <Check className="size-4 text-brand-text" /> Found ComfyUI on port {state.port}. Connecting…+ </p>+ );+ case "needs-setting":+ return <SettingFix port={state.port} back={state.back} />;+ 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's window open? It says “To see the GUI go to: http://127.0.0.1:{state.port}” when it'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>+ );+ case "none":+ return (+ <div className="space-y-3">+ <div>+ <p className="text-[15px] font-medium">Start ComfyUI, then Fuobe finds it.</p>+ <p className="mt-1 text-muted-foreground">No ComfyUI is answering on this computer.</p>+ </div>+ <Watching>Fuobe looks again by itself every few seconds.</Watching>+ <OtherPort onLook={lookAt} missed={state.missed} />+ <p className="text-[12px] text-muted-foreground">+ Don't have ComfyUI?{" "}+ <a href="https://www.comfy.org/download" target="_blank" rel="noreferrer" className="text-brand-text underline-offset-4 hover:underline">+ Get ComfyUI Desktop+ </a>+ </p>+ </div>+ );+ case "blocked":+ return (+ <div className="space-y-2">+ <p className="flex items-center gap-2 font-medium">+ <TriangleAlert className="size-4 text-amber-600 dark:text-amber-400" /> Your browser is blocking Fuobe from reaching apps on this computer.+ </p>+ <p className="text-[12px] text-muted-foreground">{blockedSteps()}</p>+ <Button size="sm" variant="secondary" onClick={() => window.location.reload()}>+ <RefreshCw /> Reload+ </Button>+ </div>+ );+ }+}diff --git a/src/components/gpu/use-local-comfy.ts b/src/components/gpu/use-local-comfy.tsnew file mode 100644index 00000000..50030dda--- /dev/null+++ b/src/components/gpu/use-local-comfy.ts@@ -0,0 +1,172 @@+"use client";++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 { 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.+ */++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" };++const LOOK_MS = 1500;++async function timed(url: string, init: RequestInit): Promise<Response> {+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), LOOK_MS);+ try {+ return await loopbackFetch(url, { ...init, signal: ctrl.signal });+ } finally {+ clearTimeout(timer);+ }+}++/** One port: ComfyUI that this page can read, something that answers but can't be read, or nothing. */+export async function lookOn(port: number, host = "127.0.0.1"): Promise<PortLook> {+ const base = localBase(port, host);+ try {+ const res = await timed(`${base}/system_stats`, {});+ const stats = res.ok ? ((await res.json().catch(() => null)) as SystemStats | null) : null;+ return stats?.system ? { port, host, state: "found", stats } : { port, host, state: "none" };+ } catch {+ // Not readable: a look that can't read the answer still sees that something is there.+ try {+ await timed(`${base}/system_stats`, { mode: "no-cors" });+ return { port, host, state: "unreadable" };+ } catch {+ return { port, host, state: "none" };+ }+ }+}++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" };+ }+}++const NARROW = "(max-width: 767px)";+const subscribeNarrow = (cb: () => void) => {+ const m = window.matchMedia(NARROW);+ m.addEventListener("change", cb);+ return () => m.removeEventListener("change", cb);+};++/** Can this browser use the ComfyUI on its computer at all ("ok"), or why not. */+export function useComputerSupport(): "ok" | "safari" | "phone" | "http" {+ const narrow = useSyncExternalStore(subscribeNarrow, () => window.matchMedia(NARROW).matches, () => false);+ if (typeof window === "undefined") return "ok";+ const coarse = window.matchMedia("(pointer: coarse)").matches && !window.matchMedia("(hover: hover)").matches;+ const b = browserSupport(navigator as Navigator & { userAgentData?: { mobile?: boolean; platform?: string } }, { narrow, coarse });+ if (b !== "ok") return b;+ return pageCanReach(window.location.origin) ? "ok" : "http";+}++const visible = () => typeof document === "undefined" || document.visibilityState === "visible";++/** The finder, while `active` (the card is open). */+export function useLocalComfy(active: boolean) {+ const support = useComputerSupport();+ const [state, setState] = useState<Finder>({ s: "start" });+ const cur = useRef(state);+ useEffect(() => {+ cur.current = state;+ }, [state]);+ const busy = useRef(false);++ 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 }) });+ }, []);++ /** Look on every port (or the ones given), then say what was found. `quiet`: keep the screen as it is meanwhile. */+ const look = useCallback(+ async (o: { ports?: { port: number; host?: string }[]; quiet?: boolean } = {}) => {+ if (busy.current || support !== "ok") return;+ busy.current = true;+ if (!o.quiet) setState({ s: "looking" });+ try {+ const remembered = rememberedComfy();+ const ports = o.ports ?? portsToLook(remembered?.port).map((port) => ({ port, host: port === remembered?.port ? remembered.host : "127.0.0.1" }));+ const looks = await Promise.all(ports.map((p) => lookOn(p.port, p.host)));+ // Every port failed at once: the browser may have said no.+ if (looks.every((l) => l.state === "none") && (await loopbackPermission()).state === "denied") return setState({ s: "blocked" });+ settle(looks, o.ports?.length === 1 ? o.ports[0].port : undefined);+ } finally {+ busy.current = false;+ }+ },+ [settle, support],+ );++ // Open: when the browser already lets Fuobe in, look at once; when it would ask, wait for the click.+ useEffect(() => {+ if (!active || support !== "ok") return;+ let alive = true;+ let status: PermissionStatus | undefined;+ const onChange = () => {+ if (status?.state === "denied") setState({ s: "blocked" });+ else if (status?.state === "granted" && cur.current.s === "blocked") void look();+ };+ void loopbackPermission().then((p) => {+ if (!alive) return;+ status = p.status;+ status?.addEventListener("change", onChange);+ if (p.state === "granted" && cur.current.s === "start") void look();+ else if (p.state === "denied") setState({ s: "blocked" });+ });+ return () => {+ alive = false;+ status?.removeEventListener("change", onChange);+ };+ }, [active, support, look]);++ // Quiet looks while it waits for ComfyUI (with the setting) or for any ComfyUI to start.+ 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);+ return () => clearInterval(id);+ }, [active, state, look]);++ return { state: support !== "ok" ? ({ s: "unsupported", why: support } as Finder) : state, look, support };+}diff --git a/src/components/gpu/your-gpu.tsx b/src/components/gpu/your-gpu.tsxindex 518868bc..224e5e58 100644--- a/src/components/gpu/your-gpu.tsx+++ b/src/components/gpu/your-gpu.tsx@@ -11,7 +11,8 @@ import { Label } from "@/components/ui/label";import { responseError, toastError } from "@/lib/refusals";interface GpuState {- gpu: { url: string; hasToken: boolean } | null;+ /** A link, or the ComfyUI on this computer (connect-choice.tsx shows that one). */+ gpu: { mode?: "link"; url: string; hasToken: boolean } | { mode: "computer" } | null;}interface GpuInfo {device?: string;@@ -54,6 +55,8 @@ export function YourGpu() {setInfo(r.info);if (!test) {qc.setQueryData(["account-gpu"], { gpu: r.gpu });+ // Runs go to the link now, not to a Fuobe tab on this computer.+ void qc.invalidateQueries({ queryKey: ["viewer"] });toast.success("Your GPU is connected. Runs go to your ComfyUI now.");setUrl("");setToken("");@@ -79,10 +82,10 @@ export function YourGpu() {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" />;- const gpu = q.data.gpu;+ const gpu = q.data.gpu?.mode === "computer" ? null : q.data.gpu;return (- <div className="space-y-4 sm:w-[36rem] sm:max-w-full">+ <div className="w-full min-w-0 space-y-4 sm:max-w-[36rem]"><p className="text-[13px] text-muted-foreground">Free accounts run on their own ComfyUI, never on this studio's keys or GPU. Runs from the Image, Video and Audio studios on open-source models go to it. It must bereachable from the internet, for example through a Cloudflare Tunnel or ngrok in front of your ComfyUI.diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsxindex ad346070..d8310d6f 100644--- a/src/components/guest-prompt.tsx+++ b/src/components/guest-prompt.tsx@@ -4,7 +4,8 @@ import { Cpu, Sparkles } from "lucide-react";import Link from "next/link";import { usePathname } from "next/navigation";import { Suspense, useCallback, useEffect, useState } from "react";-import { YourGpu } from "@/components/gpu/your-gpu";+import { ConnectChoice } from "@/components/gpu/connect-choice";+import { takeGpuRetry } from "@/hooks/use-gpu";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, refusalCard, signInHref, watchGuestRefusals, type RefusalCard } from "@/lib/api";@@ -15,23 +16,37 @@ import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, refusalCard, signInHref, watchGu* change anything, and "Connect your GPU to run this" for an account (accounts run only on their* own ComfyUI, never the owner's keys or GPU). Mounted once, in the app's providers, so it outlives* the page: a card closes when the page changes (its own Sign up or Log in, Back), and never opens- * on the sign-in page (refusalCard).+ * on the sign-in page (refusalCard). Opened by a run that was refused, "Connect your GPU" keeps that+ * run and starts it by itself once the GPU is connected.*/export function GuestPrompt() {// The last card stays while the dialog animates out.const [card, setCard] = useState<RefusalCard | null>(null);const [open, setOpen] = useState(false);- const close = useCallback(() => setOpen(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);+ const close = useCallback(() => {+ setOpen(false);+ setRetry(null);+ }, []);useEffect(() => {watchGuestRefusals();const show = (kind: RefusalCard["kind"]) => {const next = refusalCard(kind, window.location);- if (!next) return;+ if (!next) return false;setCard(next);setOpen(true);+ return true;};const guest = () => show("guest");- const gpu = () => show("gpu");+ const gpu = (e: Event) => {+ // The run that was refused (the composer leaves its retry as it sends): kept until the GPU is connected.+ const r = takeGpuRetry();+ if (!show("gpu")) return;+ setRetry(r);+ setRefind((e as CustomEvent<{ refind?: boolean } | undefined>).detail?.refind === true);+ };window.addEventListener(GUEST_PROMPT_EVENT, guest);window.addEventListener(CONNECT_GPU_EVENT, gpu);return () => {@@ -52,16 +67,19 @@ 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>Connect your GPU to run this</DialogTitle>- <DialogDescription>- Or run Fuobe on your own computer: it's{" "}- <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer" className="underline underline-offset-4">- open source- </a>- .- </DialogDescription>+ <DialogTitle>{refind ? "Your ComfyUI needs Fuobe's setting again" : "Connect your GPU to run this"}</DialogTitle>+ <DialogDescription>Fuobe runs this on the ComfyUI on your computer. It's free and private.</DialogDescription></DialogHeader>- <YourGpu />+ <ConnectChoice+ fromRun={!!retry}+ refind={refind}+ onStart={() => {+ const r = retry;+ close();+ r?.retry();+ }}+ onNotNow={() => setRetry(null)}+ /></>) : (<>diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex 6d827f28..ced4da15 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -7,6 +7,7 @@ import { useRouter } from "next/navigation";import { useEffect, useState, useSyncExternalStore } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";+import { OwnerComfyWhere } from "@/components/gpu/connect-choice";import { Label } from "@/components/ui/label";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Skeleton } from "@/components/ui/skeleton";@@ -595,6 +596,7 @@ export function SettingsForm({ prices }: { prices?: string }) {}inactive={mode === "cloud" ? "Not used in Paid APIs only mode" : undefined}>+ <OwnerComfyWhere value={get("comfyWhere")?.value || "server"} onChange={(v) => save.mutateAsync({ comfyWhere: v })} /><ConnectField name="comfyUrl" setting={get("comfyUrl")} provider="comfyui" label="ComfyUI server URL" placeholder="http://127.0.0.1:8188" hint="Where ComfyUI listens; a local install is http://127.0.0.1:8188." /><ConnectField name="comfyToken" setting={get("comfyToken")} provider="comfyui" label="Auth token (optional)" hint="Sent as a Bearer token, for ComfyUI behind a proxy." /><ConnectFielddiff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex 67ba9ded..3b32544f 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -2,6 +2,8 @@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 Link from "next/link";import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";@@ -43,7 +45,9 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {// 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;- const label = g.status === "queued" ? (g.message ?? "Queued") : (g.message ?? "Generating…");+ // 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…"));// 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;@@ -56,9 +60,21 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {// otherwise make the tile wider than its column and spill over the next card.<div className="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}><div className="skeleton-sweep absolute inset-0 animate-skeleton" />- <div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3">+ {local?.preview && (+ // eslint-disable-next-line @next/next/no-img-element -- a live frame from the person's own ComfyUI (a blob: address)+ <img+ src={local.preview}+ alt=""+ // Shown once a frame decodes (a frame that doesn't keeps the shimmer).+ onLoad={(e) => (e.currentTarget.style.opacity = "0.9")}+ onError={(e) => (e.currentTarget.style.opacity = "0")}+ className="absolute inset-0 size-full object-cover opacity-0 transition-opacity duration-300"+ />+ )}+ <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 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>diff --git a/src/hooks/use-gpu.ts b/src/hooks/use-gpu.tsindex b902d862..d35cfed5 100644--- a/src/hooks/use-gpu.ts+++ b/src/hooks/use-gpu.ts@@ -2,7 +2,9 @@import { useQuery, useQueryClient } from "@tanstack/react-query";import { useCallback, useRef, useState } from "react";+import { rememberedComfy } from "@/components/gpu/computer-runtime";import { GPU_SETUP_EVENT } from "@/lib/api";+import { checkThisComputer, sendCheck } from "@/lib/gpu/browser-check";import { BADGE_STATE } from "@/lib/gpu/readiness";import type { Badge, BadgeMap, CheckLine, FixPlan, GpuProblem, ReadinessReport, Readiness } from "@/lib/gpu/types";import { responseError } from "@/lib/refusals";@@ -15,7 +17,8 @@ import { responseError } from "@/lib/refusals";export interface ReadinessView {connected: boolean;- target?: "install" | "account";+ /** Whose ComfyUI: the studio's own, a link, or the one on the person's computer (checked from this browser). */+ target?: "install" | "account" | "computer";reason?: "guest" | "no-gpu" | "token" | "refused" | "off";checkedAt?: number | null;stale?: boolean;@@ -119,11 +122,18 @@ export function openGpuSetup(detail: GpuSetupDetail): void {export type CheckEvent = ({ type: "line" } & CheckLine) | ({ type: "report" } & ReadinessView) | { type: "error"; error: string };-/** POST /api/gpu/check, reading its lines as they come. Resolves with the board (or throws the refusal). */+/**+ * POST /api/gpu/check, reading its lines as they come. Resolves with the board (or throws the refusal). A ComfyUI on+ * the person's own computer is checked from this tab instead, and what it found is sent to the server.+ */export async function runGpuCheck(onLine: (l: CheckLine) => void): Promise<ReadinessView> {const res = await fetch("/api/gpu/check", { method: "POST" });if (!res.ok || !res.body) {- const body = (await res.json().catch(() => ({}))) as { error?: string; wait?: number };+ const body = (await res.json().catch(() => ({}))) as { error?: string; wait?: number; code?: string };+ if (res.status === 409 && body.code === "browser") {+ const where = rememberedComfy() ?? { port: 8188, host: "127.0.0.1" };+ return sendCheck<ReadinessView>(await checkThisComputer(where.port, { host: where.host, onLine }));+ }throw Object.assign(responseError(res, body.error ?? `The check didn't start (${res.status})`), { status: res.status, wait: body.wait });}const reader = res.body.getReader();diff --git a/src/lib/api.ts b/src/lib/api.tsindex 89f436e7..5580d2e2 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; online?: boolean; device?: string; vramBytes?: number } };+ viewer?: { kind: "guest" | "account"; gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; device?: string; vramBytes?: number } };}/** A connection test's answer (POST /api/providers/test). */@@ -1071,6 +1071,8 @@ export interface ViewerInfo {/** Guests may browse and anyone may sign up. */publicSignup: boolean;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;}export function useViewer() {@@ -1144,6 +1146,8 @@ export function signInHref(mode: "signup" | "login", next?: string): string {export const GUEST_PROMPT_EVENT = "fuobe:guest-prompt";export const CONNECT_GPU_EVENT = "fuobe:connect-gpu";+/** A run started from this tab (components/gpu/computer-runtime.ts listens). */+export const COMPUTER_KICK_EVENT = "fuobe:computer-kick";/** The guided fix (src/components/gpu/guided-fix.tsx): { ref, plan? }. */export const GPU_SETUP_EVENT = "fuobe:gpu-setup";@@ -1184,6 +1188,10 @@ export function watchGuestRefusals(): void {if (method !== "GET" && method !== "HEAD") open(res, "guest");}if (res.status === 403 && res.headers.get("x-fuobe-connect-gpu") === "1") open(res, "gpu");+ // A run started here, on the ComfyUI on this computer: the tab that runs it asks for it at once.+ if (res.status === 201 && (init?.method ?? "").toUpperCase() === "POST" && new URL(input instanceof Request ? input.url : String(input), window.location.href).pathname === "/api/generations") {+ window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));+ }// A run the GPU pre-flight stopped (something missing on the viewer's ComfyUI): the guided fix opens with its plan.if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") {resdiff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.tsindex 6fe5f7c8..03677232 100644--- a/src/lib/computer-runner.ts+++ b/src/lib/computer-runner.ts@@ -62,7 +62,6 @@ export interface RunnerView {facts?: ComputerFacts;}-class Gone extends Error {}class Stopped extends Error {}const PROGRESS_EVERY_MS = 500;@@ -335,7 +334,15 @@ export class ComputerRunner {}const { task } = (await res.json()) as { task: ClaimedTask };this.leases.set(task.id, task.lease);- await this.run(task);+ try {+ await this.run(task);+ } catch (e) {+ // Something broke mid-job (the studio or the connection): forget it here, so the next claim picks it up again+ // from where it got to (the job stays this computer's on the server).+ this.view.jobs = this.view.jobs.filter((j) => j.taskId !== task.id);+ this.emit();+ throw e;+ }return true;} finally {this.busy = false;diff --git a/src/lib/gpu/browser-check.ts b/src/lib/gpu/browser-check.tsnew file mode 100644index 00000000..9a34df7a--- /dev/null+++ b/src/lib/gpu/browser-check.ts@@ -0,0 +1,58 @@+/**+ * The GPU check of the ComfyUI on this computer, made by the Fuobe tab ("Use the ComfyUI on this computer"): the same+ * check the server makes of a link (gather.ts), read from the browser through lib/local-comfy.ts's list of what may be+ * read, then sent to the server (PUT /api/gpu/inventory), which keeps it for this person's board, chips and fixes.+ */+import { localBase, preflightPath } from "../local-comfy";+import { gatherInventory } from "./gather";+import { parseIndex } from "./requirements";+import { fetchTransport } from "./transport";+import type { CheckLine, GpuInventory, RequirementIndex } from "./types";++/** fetch() to the ComfyUI on this computer: no cookies, nothing cached, and only to this computer (Chrome's own check). */+export function loopbackFetch(url: string, init: RequestInit = {}): Promise<Response> {+ return fetch(url, { ...init, credentials: "omit", cache: "no-store", targetAddressSpace: "loopback" } as RequestInit);+}++let index: Promise<RequirementIndex> | null = null;+const requirements = () =>+ (index ??= fetch("/api/gpu/requirements")+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`The studio answered HTTP ${r.status}`))))+ .then(parseIndex)+ .catch((e) => {+ index = null;+ throw e;+ }));++/** Read what the ComfyUI on this port has (GET requests and the Manager's read-only questions only). */+export async function checkThisComputer(port: number, o: { host?: string; onLine?: (l: CheckLine) => void; classes?: string[]; folders?: string[] } = {}): Promise<GpuInventory> {+ const base = localBase(port, o.host);+ const t = fetchTransport(+ "browser",+ base,+ (url, init) => {+ const u = new URL(url);+ preflightPath(init.method === "POST" ? "POST" : "GET", u.pathname + u.search);+ return loopbackFetch(url, init);+ },+ { decodes: true },+ );+ const inv = await gatherInventory(t, await requirements(), { where: "computer", statsTimeoutMs: 1500, onLine: o.onLine, classes: o.classes, folders: o.folders });+ // The browser can't read a ComfyUI started without Fuobe's setting: a look that can't read the answer still sees it's there.+ if (inv.problem === "unreachable") {+ const answers = await loopbackFetch(`${base}/system_stats`, { mode: "no-cors" }).then(+ () => true,+ () => false,+ );+ if (answers) return { ...inv, problem: "cors-off" };+ }+ return inv;+}++/** Send a check to the server: the board it makes of it (as GET /api/gpu/readiness answers). */+export async function sendCheck<T = unknown>(inv: GpuInventory): Promise<T> {+ const res = await fetch("/api/gpu/inventory", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(inv) });+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };+ if (!res.ok) throw Object.assign(new Error(body.error ?? `The studio answered HTTP ${res.status}`), { status: res.status });+ return body;+}diff --git a/src/lib/gpu/gather.ts b/src/lib/gpu/gather.tsindex 0d2bc3ac..64cc96ba 100644--- a/src/lib/gpu/gather.ts+++ b/src/lib/gpu/gather.ts@@ -43,7 +43,10 @@ const PROBLEM_TEXT: Record<GpuProblem, string> = {redirect: "That address sends Fuobe somewhere else. Use the final https address.",};-export const problemText = (p: GpuProblem): string => PROBLEM_TEXT[p];+/** A ComfyUI on the person's own computer that doesn't answer (read from their tab, there's no link). */+const COMPUTER_UNREACHABLE = "ComfyUI isn't answering on this computer. Start it, then check again.";++export const problemText = (p: GpuProblem, where: "link" | "computer" = "link"): string => (where === "computer" && p === "unreachable" ? COMPUTER_UNREACHABLE : PROBLEM_TEXT[p]);const clip = (s: unknown, n: number) => String(s ?? "").slice(0, n);@@ -143,7 +146,7 @@ export async function gatherInventory(t: ComfyTransport, idx: RequirementIndex,inv.problem = problem;if (detail) inv.problemDetail = clip(detail, 300);inv.tookMs = now() - start;- emit({ step: "found", state: "fail", text: PROBLEM_TEXT[problem], ...(detail && { detail: clip(detail, 300) }) });+ emit({ step: "found", state: "fail", text: problemText(problem, o.where), ...(detail && { detail: clip(detail, 300) }) });return inv;};diff --git a/src/lib/local-comfy.ts b/src/lib/local-comfy.tsindex dc8461b7..55cec8be 100644--- a/src/lib/local-comfy.ts+++ b/src/lib/local-comfy.ts@@ -188,3 +188,50 @@ export function statsFacts(s: SystemStats, origin: string) {...(cors && { cors }),};}++/**+ * The GPU check from the browser (lib/gpu/gather.ts): ComfyUI's facts and lists, and the Manager's read-only answers+ * (its version, whether it is busy, the packs it has, why a pack didn't load). Never a prompt, an upload, a file, an+ * install or a log. Throws for anything else. ComfyUI also answers under /api.+ */+export function preflightPath(method: "GET" | "POST", path: string): string {+ const [p0, query = ""] = path.split("?");+ const p = p0.startsWith("/api/") ? p0.slice(4) : p0;+ if (method === "POST") {+ if (!query && /^\/(v2\/)?customnode\/import_fail_info(_bulk)?$/.test(p)) return path;+ throw new LocalComfyError(`Fuobe doesn't send ${p0} to your ComfyUI`);+ }+ if (!query && /^\/(experiment\/models(\/[A-Za-z0-9_.-]{1,64})?|features|(v2\/)?manager\/(version|queue\/status)|(v2\/)?customnode\/installed)$/.test(p)) return path;+ if (p.startsWith("/api/") || p === "/view" || p === "/ws" || p === "/upload/image") throw new LocalComfyError(`Fuobe doesn't read ${p0} on your ComfyUI`);+ readPath(query ? `${p}?${query}` : p);+ return path;+}++/**+ * Can this browser reach a ComfyUI on its own computer? Chrome, Edge, Brave and Firefox on a computer can. Safari+ * can't (an https page may not call http://127.0.0.1), nor can any browser on an iPhone or iPad (all are Safari+ * underneath), nor a phone (no ComfyUI there): those get the link instead.+ */+export function browserSupport(+ nav: { userAgent?: string; userAgentData?: { mobile?: boolean; platform?: string } },+ screen: { narrow: boolean; coarse?: boolean },+): "ok" | "safari" | "phone" {+ const ua = nav.userAgent ?? "";+ if (/iPhone|iPad|iPod/.test(ua) || nav.userAgentData?.mobile || /Android.+Mobile|Mobile Safari/.test(ua)) return "phone";+ if (screen.narrow && screen.coarse !== false) return "phone";+ if (!nav.userAgentData && /Safari\//.test(ua) && !/Chrome|Chromium|CriOS|FxiOS|Edg|Firefox|OPR/.test(ua)) return "safari";+ return "ok";+}++/**+ * Can a page at this address ask for the permission at all? Chrome turns it down for a page on plain http at a network+ * address (a self-hosted studio on the LAN); https and localhost are fine.+ */+export function pageCanReach(origin: string): boolean {+ try {+ const u = new URL(origin);+ return u.protocol === "https:" || LOCAL_HOSTS.has(u.hostname === "::1" ? "[::1]" : u.hostname) || u.hostname.endsWith(".localhost");+ } catch {+ return false;+ }+}diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 2237c319..31dd111e 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -204,6 +204,29 @@ export function makingWords(kind: MadeKind, value?: number, max?: number): strinexport const savingWords = (fraction: number | undefined) =>fraction !== undefined && fraction > 0 ? `Saving to Fuobe · ${Math.min(100, Math.floor(fraction * 100))}%` : "Saving to Fuobe";+/**+ * 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.+ */+export function jobWords(+ job: { phase: "sending" | "queued" | "running" | "saving" | "done" | "failed"; position?: number; value?: number; max?: number; saved?: number },+ kind: MadeKind,+ server: string | undefined,+): string | undefined {+ switch (job.phase) {+ case "sending":+ return server?.startsWith("Sending your") ? 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);+ default:+ return server;+ }+}+export const RELAY_WORDS = {noComputer: "Open Fuobe on the computer with your ComfyUI to run this",starting: "Starting on your computer",diff --git a/src/server/gpu/readiness-service.ts b/src/server/gpu/readiness-service.tsindex 758bdfe9..cdf25d3d 100644--- a/src/server/gpu/readiness-service.ts+++ b/src/server/gpu/readiness-service.ts@@ -96,7 +96,7 @@ export function readinessView(t: ReadTarget): ReadinessView {if (!snap) return { ...base, checkedAt: null };const inv = snap.inventory;if (!inv.reachable) {- return { ...base, checkedAt: snap.checkedAt, stale: snap.stale, problem: inv.problem ?? "unreachable", problemText: problemText(inv.problem ?? "unreachable"), ...(inv.problemDetail && { problemDetail: inv.problemDetail }) };+ return { ...base, checkedAt: snap.checkedAt, stale: snap.stale, problem: inv.problem ?? "unreachable", problemText: problemText(inv.problem ?? "unreachable", t.via === "browser" ? "computer" : "link"), ...(inv.problemDetail && { problemDetail: inv.problemDetail }) };}return { ...base, checkedAt: snap.checkedAt, stale: snap.stale, report: viewsOf(t, snap).report };}diff --git a/src/server/gpu/target.ts b/src/server/gpu/target.tsindex 891aba17..b09be071 100644--- a/src/server/gpu/target.ts+++ b/src/server/gpu/target.ts@@ -1,6 +1,6 @@import "server-only";import crypto from "node:crypto";-import { accountGpu, requestViewer, validToken, type AccountGpu } from "../auth";+import { accountGpu, requestViewer, validToken } from "../auth";import { fetchPublic, isPrivateAddress, type RemoteFetchOptions } from "../remote-fetch";import { comfyRequest } from "../providers/comfyui";import { getSetting } from "../settings";diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 6fa1c5bd..614c41d8 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -150,12 +150,6 @@ export function onOwnGpu<T>(gpu: OwnGpu, fn: () => T): T {/** Inside onOwnGpu: the account's ComfyUI. */export const ownGpu = (): OwnGpu | undefined => ownGpuStore.getStore();-/** Inside onOwnGpu with a link: its address and token. */-const ownLink = (): { url: string; token?: string } | undefined => {- const own = ownGpu();- return own && own.kind !== "computer" ? own : undefined;-};-/** Run `fn` outside any account's ComfyUI (the install's own again). */export const outsideOwnGpu = <T,>(fn: () => T): T => ownGpuStore.exit(fn);diff --git a/tests/computer-pure.test.ts b/tests/computer-pure.test.tsindex 3573b899..d6c85a64 100644--- a/tests/computer-pure.test.ts+++ b/tests/computer-pure.test.ts@@ -5,8 +5,8 @@ import path from "node:path";import { describe, expect, it } from "vitest";import { corsFlag, fixFor, guessInstall, installFromStats, platformOf, startFile, START_FILE_NAME } from "@/lib/comfy-install";import { parseComfyBinary, parseComfyText } from "@/lib/comfy-ws";-import { COMFY_PORTS, graphProblem, localBase, mayDownload, pickLook, portsToLook, readPath, statsFacts, typedPort, viewPath, writePath } from "@/lib/local-comfy";-import { makingWords, queueWords, reportAllowed, savingWords, sendingWords, tabFailureWords, type RelayState } from "@/lib/relay";+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";const ID = "0f8fad5b-d9cb-469f-a165-70867728950e";const OTHER = "7c9e6679-7425-40de-944b-e07fc1f90ae7";@@ -161,6 +161,18 @@ describe("the run's words", () => {}});+ it("the tab that runs a job says where it is at once, ahead of the server's next word", () => {+ expect(jobWords({ phase: "sending" }, "image", "Sending your photo to ComfyUI")).toBe("Sending your photo to ComfyUI");+ expect(jobWords({ phase: "sending" }, "image", "Queued")).toBe("Starting on your computer");+ expect(jobWords({ phase: "queued", position: 2 }, "image", "Queued")).toBe("In ComfyUI's queue · 2 ahead");+ 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: "failed" }, "image", undefined)).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"]);@@ -229,3 +241,61 @@ describe("ComfyUI's one setting", () => {expect(out.trim()).toBe("0");});});++describe("which browsers can reach the ComfyUI on this computer", () => {+ const nav = (userAgent: string, o: { platform?: string; mobile?: boolean; brands?: boolean } = {}) => ({+ userAgent,+ ...(o.brands && { userAgentData: { platform: o.platform ?? "Windows", mobile: !!o.mobile } }),+ });+ it("Chrome, Edge and Firefox on a computer can; Safari, any iPhone or iPad browser and phones can't", () => {+ expect(browserSupport(nav("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Safari/537.36", { brands: true }), { narrow: false })).toBe("ok");+ expect(browserSupport(nav("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Safari/537.36 Edg/141.0", { brands: true }), { narrow: false })).toBe("ok");+ expect(browserSupport(nav("Mozilla/5.0 (X11; Linux x86_64; rv:151.0) Gecko/20100101 Firefox/151.0"), { narrow: false })).toBe("ok");+ expect(browserSupport(nav("Mozilla/5.0 (Macintosh; Intel Mac OS X 15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15"), { narrow: false })).toBe("safari");+ expect(browserSupport(nav("Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/141.0 Mobile/15E148 Safari/604.1"), { narrow: true })).toBe("phone");+ expect(browserSupport(nav("Mozilla/5.0 (iPad; CPU OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"), { narrow: false })).toBe("phone");+ expect(browserSupport(nav("Mozilla/5.0 (Linux; Android 15) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Mobile Safari/537.36", { brands: true, mobile: true, platform: "Android" }), { narrow: true })).toBe("phone");+ // A narrow window on a computer is still a computer; a phone-width page is a phone.+ expect(browserSupport(nav("Mozilla/5.0 (Windows NT 10.0) Chrome/141.0 Safari/537.36", { brands: true }), { narrow: true, coarse: true })).toBe("phone");+ });++ it("an http page on a network address can't ask Chrome for the permission; localhost and https can", () => {+ expect(pageCanReach("https://fuobe.com")).toBe(true);+ expect(pageCanReach("http://localhost:3000")).toBe(true);+ expect(pageCanReach("http://127.0.0.1:3370")).toBe(true);+ expect(pageCanReach("http://192.168.1.20:3000")).toBe(false);+ expect(pageCanReach("http://studio.lan")).toBe(false);+ });+});++describe("the GPU check from the browser", () => {+ it("reads only ComfyUI's facts and lists, and asks the Manager only its read-only questions", () => {+ for (const [m, p] of [+ ["GET", "/system_stats"],+ ["GET", "/api/system_stats"],+ ["GET", "/object_info"],+ ["GET", "/api/object_info/KSampler"],+ ["GET", "/models/checkpoints"],+ ["GET", "/experiment/models"],+ ["GET", "/experiment/models/loras"],+ ["GET", "/features"],+ ["GET", "/manager/version"],+ ["GET", "/v2/manager/queue/status"],+ ["GET", "/api/v2/customnode/installed"],+ ["POST", "/v2/customnode/import_fail_info_bulk"],+ ["POST", "/customnode/import_fail_info"],+ ] as const)+ expect(preflightPath(m, p), `${m} ${p}`).toBe(p);+ for (const [m, p] of [+ ["POST", "/prompt"],+ ["POST", "/upload/image"],+ ["GET", "/view?filename=a.png&subfolder=&type=input"],+ ["POST", "/manager/queue/install"],+ ["POST", "/v2/customnode/install"],+ ["GET", "/internal/logs"],+ ["GET", "/userdata/comfy.settings.json"],+ ["GET", "/api/api/system_stats"],+ ] as const)+ expect(() => preflightPath(m, p), `${m} ${p}`).toThrow();+ });+});diff --git a/tests/computer-security.test.ts b/tests/computer-security.test.tsindex cf9b7670..e44d53a2 100644--- a/tests/computer-security.test.ts+++ b/tests/computer-security.test.ts@@ -21,7 +21,6 @@ const { setSetting } = await import("@/server/settings");const tasks = await import("@/server/computer/tasks");const { onComputer, outputFetch } = await import("@/server/providers/comfyui");const { accountMayChange, accountOwnRead, guestRead } = await import("@/lib/guest-access");-const gpuRoute = await import("@/app/api/account/gpu/route");type Principal = import("@/server/computer/tasks").Principal;@@ -75,7 +74,10 @@ function call(who: Who, method: string, url: string, o: { body?: unknown; raw?:headers.set("content-type", "application/json");headers.set("content-length", String(Buffer.byteLength(body)));}- for (const [k, v] of Object.entries(o.headers ?? {})) (v === "" ? headers.delete(k) : headers.set(k, v));+ for (const [k, v] of Object.entries(o.headers ?? {})) {+ if (v === "") headers.delete(k);+ else headers.set(k, v);+ }const req = new Request(`${SITE}${url}`, { method, headers, body, duplex: "half" } as RequestInit);const params = (p: Record<string, string>) => ({ params: Promise.resolve(p) });const u = new URL(req.url).pathname;diff --git a/tests/e2e/computer-mode.mjs b/tests/e2e/computer-mode.mjsnew file mode 100644index 00000000..709eeb36--- /dev/null+++ b/tests/e2e/computer-mode.mjs@@ -0,0 +1,330 @@+// "Use the ComfyUI on this computer", end to end in Chromium: a production server on 3370 with a throwaway data+// folder, and the stand-in ComfyUI (tests/helpers/fake-local-comfy.ts) on 3371, first without Fuobe's setting, then+// restarted with it. The browser never reaches any other port on this computer (every other loopback address is+// refused before it leaves the browser), so a real ComfyUI on 8188 is never touched.+//+// 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.+import { spawn } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { launch, root } from "./_browser.mjs";++const APP_PORT = Number(process.env.E2E_APP_PORT ?? 3370);+const FAKE_PORT = Number(process.env.E2E_FAKE_PORT ?? 3371);+const SITE = `http://127.0.0.1:${APP_PORT}`;+const FAKE = `http://127.0.0.1:${FAKE_PORT}`;+const shots = process.env.E2E_SHOTS ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-computer-shots-"));+const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-computer-e2e-"));+const results = [];+const check = (name, ok, detail = "") => {+ results.push({ name, ok: !!ok, detail });+ console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);+};+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++async function until(fn, ms = 30_000, every = 250) {+ const end = Date.now() + ms;+ for (;;) {+ try {+ const v = await fn();+ if (v) return v;+ } catch {}+ if (Date.now() > end) return null;+ await sleep(every);+ }+}++// --- 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")];+ 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);+}+async function stopFake() {+ if (!fakeProc) return;+ const p = fakeProc;+ fakeProc = null;+ p.kill();+ await until(() => fetch(`${FAKE}/__fake/stats`).then(() => false, () => true), 10_000);+}+const fakeStats = () => fetch(`${FAKE}/__fake/stats`).then((r) => r.json());++// --- The studio.+const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), "start", "-p", String(APP_PORT), "-H", "127.0.0.1"], {+ cwd: root,+ env: {+ ...process.env,+ FUOBE_DATA_DIR: data,+ FUOBE_PASSWORD: `e2e-${Math.random().toString(36).slice(2)}`,+ FUOBE_PUBLIC_SIGNUP: "1",+ // The studio's own ComfyUI: an address where nothing listens (never the real one).+ COMFYUI_URL: "http://127.0.0.1:3398",+ NODE_ENV: "production",+ },+ stdio: ["ignore", "pipe", "pipe"],+});+let serverLog = "";+server.stdout.on("data", (d) => (serverLog += d));+server.stderr.on("data", (d) => (serverLog += d));++async function finish(code) {+ await stopFake().catch(() => {});+ server.kill();+ await sleep(500);+ try {+ fs.rmSync(data, { recursive: true, force: true });+ } catch {}+ const failed = results.filter((r) => !r.ok);+ console.log(`\n${results.length - failed.length}/${results.length} passed. Screenshots: ${shots}`);+ if (failed.length) console.log(serverLog.split("\n").slice(-40).join("\n"));+ process.exit(code ?? (failed.length ? 1 : 0));+}++let browser;+try {+ if (!(await until(() => fetch(`${SITE}/api/auth/me`).then((r) => r.ok), 90_000, 500))) throw new Error(`the studio didn't start:\n${serverLog}`);+ await startFake("off");+ 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 = {}) {+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, acceptDownloads: true, ...o });+ await ctx.route(/^(https?|wss?):\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+/, (route) => {+ const port = Number(new URL(route.request().url()).port);+ return port === APP_PORT || port === FAKE_PORT ? route.continue() : route.abort("connectionrefused");+ });+ const page = await ctx.newPage();+ if (process.env.E2E_CONSOLE) page.on("console", (m) => console.log(`[page] ${m.type()} ${m.text()}`));+ 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,+ );+ 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);+ return { ctx, page };+ }++ const api = (page, url, init = {}) =>+ page.evaluate(+ async ({ url, init }) => {+ const r = await fetch(url, init);+ return { status: r.status, body: await r.json().catch(() => null) };+ },+ { url, init },+ );+ const runs = async (page) => (await api(page, "/api/generations?limit=20")).body?.items ?? [];++ async function composer(page, url) {+ await page.goto(SITE + url, { waitUntil: "load", timeout: 120_000 });+ await page.waitForSelector("[data-composer-toolbar]", { timeout: 60_000 });+ await page.waitForFunction(() => Object.keys(document.querySelector("[data-composer-toolbar]") ?? {}).some((k) => k.startsWith("__react")), null, { timeout: 60_000 });+ }++ // 1. A refused run opens the dialog; the setting's fix; ComfyUI comes back with it; connected; the run starts by itself.+ {+ const { ctx, page } = await account("[email protected]");+ await composer(page, "/image?model=oss-z-image-turbo");+ await page.locator("[data-composer] textarea").fill("a lighthouse at dusk");+ await page.getByRole("button", { name: "Generate", exact: true }).click();+ const dialog = page.getByRole("dialog");+ await dialog.getByText("Connect your GPU to run this").waitFor({ timeout: 20_000 });+ const first = await until(() => dialog.getByText("Use the ComfyUI on this computer", { exact: true }).isVisible(), 15_000);+ check("a refused run opens the dialog, this computer first", !!first);+ check("the browser's question is explained before it comes", await dialog.getByText("Press Allow. Fuobe only talks to ComfyUI.").isVisible());+ check("no error toast on top of the dialog", (await page.locator("[data-sonner-toast]").filter({ hasText: "Free accounts run" }).count()) === 0);+ await page.screenshot({ path: path.join(shots, "1-choose.png") });+ // The link, the second choice, fits inside the dialog.+ const linkToggle = dialog.getByRole("button", { name: /Run from anywhere with a link/ });+ await linkToggle.click();+ const field = await until(() => dialog.locator("input").first().boundingBox(), 10_000);+ const box = await dialog.boundingBox();+ check("the link form fits inside the dialog", !!field && !!box && field.x + field.width <= box.x + box.width - 16, JSON.stringify({ field, box }));+ await page.screenshot({ path: path.join(shots, "1b-link.png") });+ await linkToggle.click();+ 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);+ await page.screenshot({ path: path.join(shots, "2-needs-setting.png") });+ const startButton = dialog.getByRole("button", { name: "Download start file" });+ if (await startButton.isVisible()) {+ const [dl] = await Promise.all([page.waitForEvent("download"), startButton.click()]);+ const file = await dl.path();+ const text = fs.readFileSync(file, "utf8");+ check(+ "the Windows start file names only this site and this port",+ dl.suggestedFilename() === "Start ComfyUI for Fuobe.bat" && text.includes(`--enable-cors-header ${SITE}`) && text.includes(`$Port = ${FAKE_PORT}`) && text.includes("\r\n"),+ dl.suggestedFilename(),+ );+ } else {+ check("the fix for this computer is shown", await dialog.getByText("--enable-cors-header").first().isVisible());+ }+ // ComfyUI restarts with the setting: Fuobe notices by itself.+ 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 dialog.getByText("Your GPU is connected").waitFor({ timeout: 30_000 });+ 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") });+ const ready = await until(() => dialog.getByText(/Ready now:|need a one-time download/).isVisible(), 20_000);+ check("the check says what's ready", !!ready);+ if (process.env.E2E_CONSOLE) for (let i = 0; i < 4; i++) {+ await sleep(1000);+ await page.screenshot({ path: path.join(shots, `3b-after-${i}.png`) });+ }+ // 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 }));+ 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");+ 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));+ 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);++ // 2. A two-step run (a picture, then a clip from it): both steps run on the computer.+ const pic = await page.evaluate(async () => {+ const c = document.createElement("canvas");+ c.width = 64;+ c.height = 64;+ c.getContext("2d").fillRect(0, 0, 64, 64);+ const blob = await new Promise((r) => c.toBlob(r, "image/png"));+ const r = await fetch("/api/uploads", { method: "POST", headers: { "content-type": "image/png", "x-file-name": "me.png" }, body: blob });+ return (await r.json()).url;+ });+ const two = await api(page, "/api/generations", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ feature: "video", modelId: "fuobe-dop", presetId: "effect-window", prompt: "", inputs: { images: [pic] } }),+ });+ const ids = (two.body?.items ?? []).map((g) => g.id);+ const batch = two.body?.items?.[0]?.batchId;+ const chain = await until(async () => {+ const all = await runs(page);+ const mine = all.filter((g) => ids.includes(g.id) || (batch && g.batchId === batch));+ return mine.length >= 2 && mine.every((g) => g.status === "succeeded" || g.status === "failed") ? mine : null;+ }, 120_000);+ check("a two-step run: both steps ran on the computer", chain?.every((g) => g.status === "succeeded"), (chain ?? []).map((g) => `${g.kind} ${g.status} ${g.error ?? ""}`).join(" · ") || `start ${two.status}`);++ // 3. A reload in the middle of a run picks it up again, without sending it twice.+ const before = (await fakeStats()).posts;+ const one = await api(page, "/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a red door" }) });+ const id = one.body?.items?.[0]?.id;+ await until(async () => (await fakeStats()).posts > before, 20_000, 100);+ await page.reload({ waitUntil: "load" });+ const again = await until(async () => (await runs(page)).find((g) => g.id === id && (g.status === "succeeded" || g.status === "failed")), 60_000);+ 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}`);++ // 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" }) });+ // A's job, taken by A from a script with A's own session (no tab), so its id and token are known here.+ await page.close();+ const apage = await ctx.newPage();+ await apage.route("**/*", (r) => (r.request().resourceType() === "document" ? r.fulfill({ body: "<!doctype html><title>bare</title>" }) : r.continue()));+ await apage.goto(`${SITE}/bare`);+ await api(apage, "/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a blue boat" }) });+ await sleep(1500);+ await api(apage, "/api/gpu/computer/beat", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ device: "e2e-device-a1", takeover: true }) });+ const claimed = await until(async () => {+ const r = await api(apage, "/api/gpu/computer/claim", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ device: "e2e-device-a1" }) });+ return r.status === 200 ? r.body.task : null;+ }, 15_000, 500);+ const bClaim = await api(bpage, "/api/gpu/computer/claim", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ device: "e2e-device-b1" }) });+ const lease = claimed?.lease ?? "0".repeat(64);+ const tid = claimed?.id ?? "AAAAAAAAAAAAAAAA";+ const b = await bpage.evaluate(+ async ({ tid, lease }) => {+ 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" }) })),+ 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 }) })),+ };+ },+ { tid, lease },+ );+ check("another account's computer never claims A's job", !!claimed && bClaim.status === 204, `A claimed: ${!!claimed}, B's claim: ${bClaim.status}`);+ check("A's job, with A's own token, is not found for B on every route", b.inputs === 404 && b.report === 404 && b.outputs === 404 && b.release === 404, JSON.stringify(b));+ await api(apage, `/api/gpu/computer/tasks/${tid}/release`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ lease }) });+ await bctx.close();+ await ctx.close();+ }++ // 5. A guest gets nothing new.+ {+ const { ctx, page } = await account(null);+ const g = await page.evaluate(async () => {+ const s = async (p) => (await p).status;+ return {+ beat: await s(fetch("/api/gpu/computer/beat", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ device: "e2e-guest-01" }) })),+ claim: await s(fetch("/api/gpu/computer/claim", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })),+ inputs: await s(fetch("/api/gpu/computer/tasks/AAAAAAAAAAAAAAAA/inputs/0")),+ outputs: await s(fetch("/api/gpu/computer/tasks/AAAAAAAAAAAAAAAA/outputs/0?offset=0&total=1", { method: "PUT", body: "x" })),+ inventory: await s(fetch("/api/gpu/inventory", { method: "PUT", headers: { "content-type": "application/json" }, body: "{}" })),+ me: await fetch("/api/auth/me").then((r) => r.json()),+ };+ });+ check("a guest gets 401 from every new route, and no runner", g.beat === 401 && g.claim === 401 && g.inputs === 401 && g.outputs === 401 && [401, 409].includes(g.inventory) && !g.me.computer, JSON.stringify(g));+ await ctx.close();+ }++ // 6. A phone, and Safari: the link, with why.+ {+ const iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1";+ const { ctx, page } = await account("[email protected]", { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, userAgent: iphone });+ 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()));+ 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" }) });+ const beats = [];+ page.on("request", (r) => r.url().includes("/api/gpu/computer/") && beats.push(r.url()));+ await page.reload({ waitUntil: "load" });+ await sleep(4000);+ check("a phone in this-computer mode never runs the jobs itself", beats.length === 0, beats.join(" "));+ await ctx.close();+ const safari = "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15";+ const s = await account("[email protected]", { userAgent: safari });+ // Safari has no navigator.userAgentData (Chromium keeps its own under another user agent).+ await s.ctx.addInitScript(() => Object.defineProperty(Navigator.prototype, "userAgentData", { get: () => undefined }));+ await s.page.goto(`${SITE}/connect`, { waitUntil: "load" });+ const sa = await until(() => s.page.getByText("Safari can't reach apps on this computer").first().isVisible(), 30_000);+ check("Safari gets the link option, with why", !!sa);+ await s.ctx.close();+ }+} catch (e) {+ check("the run didn't stop early", false, (e && e.stack) || String(e));+} finally {+ await browser?.close().catch(() => {});+ await finish();+}diff --git a/tests/fake-local-comfy.test.ts b/tests/fake-local-comfy.test.tsindex e9b3bc8f..81cc9fa0 100644--- a/tests/fake-local-comfy.test.ts+++ b/tests/fake-local-comfy.test.ts@@ -1,7 +1,13 @@import { randomUUID } from "node:crypto";+import fs from "node:fs";+import path from "node:path";import { afterEach, describe, expect, it } from "vitest";import { parseComfyBinary, parseComfyText, type ComfyEvent } from "@/lib/comfy-ws";-import { FAKE_PNG, startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";+import { gatherInventory } from "@/lib/gpu/gather";+import { workflowReadiness } from "@/lib/gpu/readiness";+import { parseIndex } from "@/lib/gpu/requirements";+import { fetchTransport } from "@/lib/gpu/transport";+import { FAKE_PNG, startLocalComfy, type IndexLike, type LocalComfy } from "./helpers/fake-local-comfy";const SITE = "http://127.0.0.1:3370";let fake: LocalComfy | undefined;@@ -91,4 +97,17 @@ describe("the fake local ComfyUI", () => {expect((await fetch(`${fake.url}/api/jobs/${id}`)).status).toBe(404);expect(await (await fetch(`${fake.url}/history/${id}`)).json()).toEqual({});});++ it("can have everything the studio's workflows need, so the GPU check finds a tool ready", async () => {+ const idx = parseIndex(JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/requirements.json"), "utf8")));+ const read = (base: string) => fetchTransport("browser", base, (url, init) => browser(url, init), { decodes: true });+ fake = await startLocalComfy({ cors: SITE });+ const bare = await gatherInventory(read(fake.url), idx, { where: "computer" });+ expect(workflowReadiness("z-image-turbo-t2i", bare, idx, { account: true }).state).not.toBe("ready");+ await fake.close();+ fake = await startLocalComfy({ cors: SITE, has: idx as unknown as IndexLike });+ const inv = await gatherInventory(read(fake.url), idx, { where: "computer" });+ expect(inv.nodes.missing).toEqual([]);+ expect(workflowReadiness("z-image-turbo-t2i", inv, idx, { account: true }).state).toBe("ready");+ });});diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.tsindex 540213e3..63507e8d 100644--- a/tests/helpers/fake-local-comfy.ts+++ b/tests/helpers/fake-local-comfy.ts@@ -12,6 +12,7 @@* Runs under plain Node too: only erasable TypeScript.*/import { createHash, randomUUID } from "node:crypto";+import { readFileSync } from "node:fs";import http from "node:http";import type { Duplex } from "node:stream";import { pathToFileURL } from "node:url";@@ -32,13 +33,44 @@ export interface LocalComfyOptions {failNext?: "oom" | "missing_node" | "missing_model" | "gone" | "never";/** Lose this many prompts in a row (taken, then gone: a restart while it waited). */loseNext?: number;- /** What a job saves (default: one picture). "fake-png" is a web page named .png. */+ /** What a job saves (default: what its save node makes: a clip, a sound, else a picture). "fake-png" is a web page named .png. */outputs?: ("image" | "video" | "audio" | "exr" | "text" | "fake-png")[];/** VHS meta-batch: the job finishes without outputs and queues this many more passes (the last one saves the clip). */metaBatch?: number;/** Embedded Python (portable / Easy-Install). */portable?: boolean;loras?: string[];+ /**+ * 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.+ */+ has?: IndexLike;+}++/** The parts of a requirement index (src/lib/gpu/types.ts) the stand-in reads. */+export interface IndexLike {+ folders: string[];+ files: Record<string, { folder: string; file: string; sizeBytes?: number; presence?: string; loaders?: [string, string][] }>;+ workflows: Record<string, { core: string[]; packs: Record<string, string[]> }>;+}++const made = new WeakMap<IndexLike, ReturnType<typeof install>>();+/** /object_info and the model folders of a ComfyUI that has everything in `idx`. */+const installed = (idx: IndexLike) => made.get(idx) ?? made.set(idx, install(idx)).get(idx)!;+function install(idx: IndexLike) {+ const info: Record<string, { input: { required: Record<string, unknown[]> } }> = {};+ const node = (cls: string) => (info[cls] ??= { input: { required: {} } });+ for (const w of Object.values(idx.workflows)) {+ for (const c of w.core) node(c);+ for (const cs of Object.values(w.packs)) for (const c of cs) node(c);+ }+ const folders = new Map<string, { name: string; size: number }[]>(idx.folders.map((f) => [f, []]));+ for (const f of Object.values(idx.files)) {+ if (!folders.has(f.folder)) folders.set(f.folder, []);+ folders.get(f.folder)!.push({ name: f.file, size: f.sizeBytes ?? 1 });+ if (f.presence === "loader") for (const [cls, input] of f.loaders ?? []) ((node(cls).input.required[input] ??= [[]])[0] as string[]).push(f.file);+ }+ return { info, folders };}export interface LocalComfyLog {@@ -90,9 +122,8 @@ export const FAKE_PNG = Buffer.from(export const FAKE_MP4 = Buffer.concat([Buffer.from("000000186674797069736f6d0000020069736f6d69736f32", "hex"), Buffer.alloc(64, 1)]);const FAKE_WAV = Buffer.concat([Buffer.from("RIFF"), Buffer.from([36, 0, 0, 0]), Buffer.from("WAVEfmt "), Buffer.alloc(64, 0)]);const FAKE_EXR = Buffer.concat([Buffer.from("762f3101", "hex"), Buffer.alloc(60, 2)]);-const PREVIEW_JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46, 0, 1]);-/** The parts of a multipart body: field name → {filename?, data}. */+/** The parts of a multipart body: field name → {filename?, data}. */function multipart(body: Buffer, contentType: string): Map<string, { filename?: string; data: Buffer }> {const out = new Map<string, { filename?: string; data: Buffer }>();const boundary = /boundary=(?:"([^"]+)"|([^;]+))/.exec(contentType);@@ -142,6 +173,13 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locconst event = (clientId: string | undefined, type: string, data: Record<string, unknown>) => send(clientId, Buffer.from(JSON.stringify({ type, data })));const status = () => event(undefined, "status", { status: { exec_info: { queue_remaining: queue.length + (running ? 1 : 0) } } });+ /** What a graph's save node makes. */+ const madeBy = (g: Graph): NonNullable<LocalComfyOptions["outputs"]> => {+ const classes = Object.values(g).map((n) => n.class_type);+ if (classes.some((c) => /VHS_VideoCombine|SaveVideo|SaveWEBM|CreateVideo|SaveAnimated/.test(c))) return ["video"];+ if (classes.some((c) => /SaveAudio/.test(c))) return ["audio"];+ return ["image"];+ };const outputNode = (g: Graph) => Object.keys(g).find((k) => /^(Save|VHS_VideoCombine|PreviewImage|CreateVideo)/.test(g[k].class_type)) ?? "9";const prefixOf = (g: Graph) => String(Object.values(g).find((n) => typeof n.inputs?.filename_prefix === "string")?.inputs.filename_prefix ?? "ComfyUI");@@ -152,7 +190,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locconst base = prefix.split("/").pop();const ui: Record<string, unknown[]> = {};const add = (key: string, ext: string, i: number) => (ui[key] ??= []).push({ filename: `${base}_${String(i + 1).padStart(5, "0")}_.${ext}`, subfolder: sub, type: "output" });- (opts.outputs ?? ["image"]).forEach((k, i) => {+ (opts.outputs ?? madeBy(job.graph)).forEach((k, i) => {if (k === "image" || k === "fake-png") add("images", "png", i);else if (k === "video") add("gifs", "mp4", i);else if (k === "audio") add("audio", "wav", i);@@ -184,10 +222,10 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locstep++;event(job.clientId, "progress", { value: step, max: steps, prompt_id: job.id, node });if (job.preview) {- const meta = Buffer.from(JSON.stringify({ prompt_id: job.id, node_id: node, image_type: "image/jpeg" }));+ const meta = Buffer.from(JSON.stringify({ prompt_id: job.id, node_id: node, image_type: "image/png" }));const len = Buffer.alloc(4);len.writeUInt32BE(meta.length);- send(job.clientId, Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, PREVIEW_JPEG]), true);+ send(job.clientId, Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, FAKE_PNG]), true);}timer = setTimeout(next, opts.stepMs);return;@@ -273,6 +311,8 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locres.end(Buffer.isBuffer(value) ? value : JSON.stringify(value));};if (req.method === "OPTIONS") return reply(200, "");+ // The stand-in's own count, for a test driving it from another process (never a ComfyUI route).+ if (url.pathname === "/__fake/stats") return reply(200, { posts, uploads: inputs.size });const p = url.pathname;if (p === "/system_stats" || p === "/api/system_stats") {const argv = ["main.py", ...(opts.cors === "off" ? [] : ["--enable-cors-header", opts.cors]), "--base-directory", "C:\\Users\\someone\\private"];@@ -283,10 +323,18 @@ 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 === "/models") return reply(200, ["checkpoints", "loras", "vae"]);- if (p.startsWith("/models/")) return reply(200, []);- if (p === "/object_info") return reply(200, {});- if (p.startsWith("/object_info/")) return reply(200, {});+ 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));+ if (p.startsWith("/experiment/models/") && has) {+ const files = has.folders.get(decodeURIComponent(p.slice(19)));+ return files ? reply(200, files.map((f) => ({ name: f.name, pathIndex: 0, size: f.size }))) : reply(404, { error: "not found" });+ }+ if (p === "/object_info") return reply(200, has?.info ?? {});+ if (p.startsWith("/object_info/")) {+ const cls = decodeURIComponent(p.slice(13));+ return reply(200, has?.info[cls] ? { [cls]: has.info[cls] } : {});+ }if (p === "/embeddings") return reply(200, []);if (p === "/upload/image" && req.method === "POST") {const parts = multipart(body, String(req.headers["content-type"] ?? ""));@@ -432,7 +480,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locif ((e as NodeJS.ErrnoException).code !== "EADDRINUSE") throw e;}}- throw new Error(`No free port in ${TEST_PORTS.join("–")}`);+ throw new Error(`No free port in ${TEST_PORTS.join("–")}`);};const closeSockets = () => {@@ -482,11 +530,14 @@ 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.if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {const arg = (name: string) => {const i = process.argv.indexOf(`--${name}`);return i > 0 ? process.argv[i + 1] : undefined;};- const fake = await startLocalComfy({ cors: arg("cors") ?? "off", steps: Number(arg("steps") ?? 8), stepMs: Number(arg("step-ms") ?? 250), portable: arg("portable") === "1" }, Number(arg("port") ?? 3371));+ 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));console.log(`fake ComfyUI on ${fake.url} (cross-site setting: ${fake.opts.cors})`);}