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
Use the ComfyUI on this computer: one clear port, Other ports, and buttons that always answer
Adarsh531fa33d2c2f
diff --git a/src/components/gpu/computer-runtime.ts b/src/components/gpu/computer-runtime.tsindex e66e53b1..a33e707f 100644--- a/src/components/gpu/computer-runtime.ts+++ b/src/components/gpu/computer-runtime.ts@@ -8,7 +8,7 @@import { COMPUTER_KICK_EVENT } from "@/lib/api";import { beatEvery, ComputerRunner, tileJob, type LocalJob, type RunnerView } from "@/lib/computer-runner";import { loopbackFetch } from "@/lib/gpu/browser-check";-import { pickLook, portsToLook } from "@/lib/local-comfy";+import { lookStrength, pickLook, portsToLook } from "@/lib/local-comfy";import { lookOn } from "./use-local-comfy";export { COMPUTER_KICK_EVENT };@@ -176,8 +176,9 @@ async function hold(signal: AbortSignal, publish: (v: RunnerView) => void, o: Ruorigin: window.location.origin,find: async (except) => {const looks = await Promise.all(portsToLook().filter((p) => p !== except).map((p) => lookOn(p)));+ // Only ComfyUI, or something on its usual port: another app answering elsewhere is no place to run.const best = pickLook(looks);- return best.state === "none" ? null : { port: best.port, host: best.host };+ return best.state === "none" || lookStrength(best) < 2 ? null : { port: best.port, host: best.host };},moved: (port, host) => rememberComfy(port, host),},diff --git a/src/components/gpu/connect-choice.tsx b/src/components/gpu/connect-choice.tsxindex 70c96014..8a5d5935 100644--- a/src/components/gpu/connect-choice.tsx+++ b/src/components/gpu/connect-choice.tsx@@ -163,6 +163,7 @@ function ComputerStatus({ gpu, onDisconnect, other, look = true }: { gpu: ComputsetFixPort(null);const l = await lookOn(p);if (l.state === "none") return setNote(`Nothing answered on port ${p}.`);+ if (l.state === "other") return setNote(`Another app answers on port ${p}, not ComfyUI.`);// The tab that runs the jobs goes there; it needs the setting first, the fix shows here.rememberComfy(p);restartComputerRunner();diff --git a/src/components/gpu/this-computer.tsx b/src/components/gpu/this-computer.tsxindex 48a69b73..ceec4927 100644--- a/src/components/gpu/this-computer.tsx+++ b/src/components/gpu/this-computer.tsx@@ -15,7 +15,7 @@ import { isConnectAnswer } from "@/lib/fuobe-connect";import { corsFlag, fixFor, guessInstall, installFromStats, platformOf, startFile, START_FILE_NAME, type ComfyInstall } from "@/lib/comfy-install";import { checkThisComputer, loopbackFetch, sendCheck } from "@/lib/gpu/browser-check";import { deviceLabel } from "@/lib/gpu/readiness";-import { localBase, statsFacts, typedPort, type SystemStats } from "@/lib/local-comfy";+import { COMFY_PORT, DESKTOP_PORT, localBase, statsFacts, typedPort, type SystemStats } from "@/lib/local-comfy";import { madeNoun } from "@/lib/relay";import { cn } from "@/lib/utils";import { computerState, rememberComfy, rememberedComfy, restartComputerRunner, store, stored } from "./computer-runtime";@@ -157,40 +157,180 @@ export function GuardFix({ port, install = installOf(port) }: { port: number; in);}+/** The line about a port the person picked: Fuobe is looking there, nothing answers there now, or another app does. */+function PickedNote({ checking, missed, notComfy }: { checking?: number | null; missed?: number; notComfy?: number }) {+ if (checking != null)+ return (+ <p role="status" className="flex items-center gap-2 text-[12px] text-muted-foreground">+ <Loader2 className="size-3.5 animate-spin" /> Checking port {checking}…+ </p>+ );+ if (missed !== undefined)+ return (+ <p role="status" className="text-[12px] text-muted-foreground">+ Nothing answers on port {missed} right now. Is ComfyUI still running there?+ </p>+ );+ if (notComfy !== undefined)+ return (+ <p role="status" className="text-[12px] text-muted-foreground">+ Another app answers on port {notComfy}, not ComfyUI.+ </p>+ );+ return null;+}++/**+ * The other ports where something answers, behind a quiet disclosure: each can be picked ("Use port 8189"), which looks+ * there at once. While it looks, and when it isn't ComfyUI's there now, a line says so (never silence). `shown`: the+ * port the card is about, whose own line is said next to it instead.+ */+function OtherPorts({+ others,+ onChoose,+ checking,+ missed,+ notComfy,+ shown,+}: {+ others: number[];+ onChoose: (port: number) => void;+ checking?: number | null;+ missed?: number;+ notComfy?: number;+ shown?: number;+}) {+ const [open, setOpen] = useState(false);+ const mine = (p: number | null | undefined) => (p == null || p === shown ? undefined : p);+ return (+ <div data-other-ports className="space-y-1.5">+ {others.length > 0 && (+ <button type="button" onClick={() => setOpen((v) => !v)} aria-expanded={open} className="flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground">+ <ChevronDown className={cn("size-3.5 transition-transform", open && "rotate-180")} /> Other ports ({others.length})+ </button>+ )}+ {open && others.length > 0 && (+ <ul className="space-y-1 rounded-xl border p-2">+ {others.map((p) => (+ <li key={p} className="flex items-center justify-between gap-2 text-[12px]">+ <span className="text-muted-foreground">Something answers on port {p}</span>+ <Button size="sm" variant="ghost" className="h-7" disabled={checking === p} onClick={() => onChoose(p)}>+ {checking === p && <Loader2 className="animate-spin" />} Use port {p}+ </Button>+ </li>+ ))}+ </ul>+ )}+ <PickedNote checking={mine(checking)} missed={mine(missed)} notComfy={mine(notComfy)} />+ </div>+ );+}++/** What the card says about the port shown, and why this page can't use it yet. */+function settingWords(port: number, o: { back: boolean; again?: boolean }): { heading: string; why: string } {+ const trust = "ComfyUI only answers the websites it's told to trust, so this page can't use it yet. One step lets Fuobe in:";+ if (o.back) return { heading: "ComfyUI is back, but it still doesn't let this page in.", why: "Did ComfyUI restart after the install? Fuobe Connect starts with ComfyUI." };+ if (o.again) return { heading: "ComfyUI is running, but Fuobe can't use it this time.", why: trust };+ if (port === COMFY_PORT) return { heading: `Something is running on port ${port}, ComfyUI's usual port.`, why: trust };+ if (rememberedComfy()?.port === port) return { heading: `Something is running on port ${port}, where your ComfyUI was before.`, why: trust };+ if (port === DESKTOP_PORT) return { heading: `Something is running on port ${port}, ComfyUI Desktop's usual port.`, why: trust };+ // A port the person picked or typed: it may be another app.+ return { heading: `Something answers on port ${port}.`, why: "Fuobe can't read this port yet. If it's ComfyUI, one step lets Fuobe in:" };+}++/**+ * Something answers on a port that may be ComfyUI's, but this page can't read it. Shown only when nothing better+ * answers: no ComfyUI on its usual port, and another app may be what answers here.+ */+function WeakCandidate({ port, onCheck, onChoose, checking }: { port: number; onCheck: () => void; onChoose?: (port: number) => void; checking?: number | null }) {+ return (+ <div className="space-y-3">+ <div>+ <p className="text-[15px] font-medium">No ComfyUI found on port {COMFY_PORT}, its usual port.</p>+ <p className="mt-1 text-[13px] text-muted-foreground">Something answers on port {port}, but Fuobe can't tell if it's ComfyUI. Start ComfyUI, then check again.</p>+ </div>+ <Button className="h-11 sm:h-9" onClick={onCheck}>+ <RefreshCw /> Check again+ </Button>+ {onChoose &&+ (checking === port ? (+ <PickedNote checking={port} />+ ) : (+ <p className="text-[12px] text-muted-foreground">+ <button type="button" onClick={() => onChoose(port)} className="underline underline-offset-4 hover:text-foreground">+ Port {port} is my ComfyUI+ </button>+ </p>+ ))}+ </div>+ );+}+/*** ComfyUI answers, but this page can't use it yet: the one step is Fuobe Connect (it lets this studio in, and keeps every* other website out), and Fuobe connects by itself once ComfyUI restarts with it. The start setting with Fuobe's guard* (the way before Fuobe Connect) is under Advanced. `back`: ComfyUI restarted, still not usable. `again`: it was usable- * before (started the usual way this time). `others`: more ports where something answers.+ * before (started the usual way this time). `weak`: maybe not ComfyUI (another port, nothing on 8188). `chosen`: the+ * person picked this port. `others`: more ports where something answers, under "Other ports". `onCheck`: Check again.*/-export function SettingFix({ port, back, again, others, onChoose }: { port: number; back: boolean; again?: boolean; others?: number[]; onChoose?: (port: number) => void }) {+export function SettingFix({+ port,+ back,+ again,+ weak,+ others,+ missed,+ notComfy,+ checking,+ onChoose,+ onCheck,+}: {+ port: number;+ back: boolean;+ again?: boolean;+ weak?: boolean;+ others?: number[];+ missed?: number;+ notComfy?: number;+ checking?: number | null;+ onChoose?: (port: number) => void;+ onCheck?: () => void;+}) {const [advanced, setAdvanced] = useState(false);- // ComfyUI's usual port, or the one it was found on before, is surely ComfyUI; another app may answer on another one- // (8000 is a common default).- const known = port === 8188 || rememberedComfy()?.port === port;- const heading = back- ? "ComfyUI is back, but Fuobe can't use it yet."- : again- ? "ComfyUI is running, but Fuobe can't use it this time."- : known- ? "Found ComfyUI. One step to use it here:"- : `Something answers on port ${port}. If it's ComfyUI, one step to use it here:`;+ const asWeak = !!weak && !!onCheck && !back;+ const otherPorts = onChoose && (!!others?.length || missed !== undefined || notComfy !== undefined || checking != null) && (+ <OtherPorts others={others ?? []} onChoose={onChoose} checking={checking} missed={missed} notComfy={notComfy} shown={asWeak ? port : undefined} />+ );+ if (asWeak)+ return (+ <div className="space-y-3">+ <WeakCandidate port={port} onCheck={onCheck} onChoose={onChoose} checking={checking} />+ {otherPorts}+ </div>+ );+ const { heading, why } = settingWords(port, { back, again });return (<div className="space-y-3">- <p className="text-[15px] font-medium">{heading}</p>- {back && <p className="text-[12px] text-muted-foreground">Did ComfyUI restart after the install? Fuobe Connect starts with ComfyUI.</p>}- {!!others?.length && onChoose && (- <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] text-muted-foreground">- Something answers on {others.length === 1 ? `port ${others[0]}` : `ports ${others.join(", ")}`} too. Is ComfyUI there?- {others.map((p) => (- <button key={p} type="button" onClick={() => onChoose(p)} className="font-medium text-brand-text underline-offset-4 hover:underline">- Use port {p}- </button>- ))}+ <div>+ <p className="text-[15px] font-medium">{heading}</p>+ <p className="mt-1 text-[13px] text-muted-foreground">{why}</p>+ </div>+ <InstallConnect />+ {!advanced && (+ <p className="text-[12px] text-muted-foreground">+ Or start ComfyUI with one setting instead.{" "}+ <button type="button" onClick={() => setAdvanced(true)} className="underline underline-offset-4 hover:text-foreground">+ Show the setting+ </button></p>)}- <InstallConnect />- <Watching>Fuobe connects by itself when ComfyUI is back.</Watching>+ <Watching>Fuobe connects by itself once ComfyUI lets this page in.</Watching>+ {onCheck && (+ <Button size="sm" variant="secondary" onClick={onCheck}>+ <RefreshCw /> Check again+ </Button>+ )}+ {otherPorts}<div><button type="button" onClick={() => setAdvanced((v) => !v)} aria-expanded={advanced} className="flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground"><ChevronDown className={cn("size-3.5 transition-transform", advanced && "rotate-180")} /> Advanced: a start setting instead@@ -284,7 +424,7 @@ function FlagFix({ port, back, again }: { port: number; back: boolean; again?: b);}-function OtherPort({ onLook, missed }: { onLook: (port: number, host: string) => void; missed?: number }) {+function OtherPort({ onLook, missed, notComfy }: { onLook: (port: number, host: string) => void; missed?: number; notComfy?: number }) {const [typed, setTyped] = useState(String(rememberedComfy()?.port ?? 8188));const [bad, setBad] = useState(false);const go = () => {@@ -302,7 +442,8 @@ function OtherPort({ onLook, missed }: { onLook: (port: number, host: string) =></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>}+ {!bad && missed !== undefined && <p role="status" className="text-[12px] text-muted-foreground">Nothing answered on port {missed}.</p>}+ {!bad && notComfy !== undefined && <p role="status" className="text-[12px] text-muted-foreground">Another app answers on port {notComfy}, not ComfyUI.</p>}</div>);}@@ -457,7 +598,7 @@ const guardAt = async (port: number, host: string): Promise<Guarded> => {/** The whole flow, from "Find my ComfyUI" to connected. */export function ThisComputer({ connect, fromRun, kind, onStart, onNotNow, autoLook, again, doneWords, lookNow, waitForTap }: ThisComputerProps) {const qc = useQueryClient();- const { state, look, choose, perm } = useLocalComfy(true, { auto: !waitForTap });+ const { state, look, choose, checking, perm } = useLocalComfy(true, { auto: !waitForTap });const [done, setDone] = useState<Connected | null>(null);const [error, setError] = useState<string | null>(null);const connecting = useRef<string | null>(null);@@ -519,7 +660,7 @@ export function ThisComputer({ connect, fromRun, kind, onStart, onNotNow, autoLoif (done) return <Celebration c={done} fromRun={fromRun} kind={kind} onStart={onStart} onNotNow={onNotNow} doneWords={doneWords} />;return (<div className="space-y-3 text-[13px]">- <Screen state={state} look={look} choose={choose} again={again} asks={perm !== "granted"} />+ <Screen state={state} look={look} choose={choose} checking={checking} again={again} asks={perm !== "granted"} />{error && <p className="text-[12px] text-destructive">{error}</p>}</div>);@@ -541,7 +682,7 @@ function WaitingScreen({ port, since, onLook }: { port: number; since: number; o<p>Still waiting. Is ComfyUI's window open? It says “To see the GUI go to: http://127.0.0.1:{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={onLook}>- <RefreshCw /> Look again+ <RefreshCw /> Check again</Button></div>)}@@ -550,8 +691,23 @@ function WaitingScreen({ port, since, onLook }: { port: number; since: number; o}/** `asks`: the browser may still ask to let Fuobe reach apps on this computer (its question is explained). */-function Screen({ state, look, choose, again, asks }: { state: Finder; look: ReturnType<typeof useLocalComfy>["look"]; choose: (port: number) => void; again?: boolean; asks: boolean }) {+function Screen({+ state,+ look,+ choose,+ checking,+ again,+ asks,+}: {+ state: Finder;+ look: ReturnType<typeof useLocalComfy>["look"];+ choose: (port: number) => void;+ checking: number | null;+ again?: boolean;+ asks: boolean;+}) {const lookAt = (port: number, host: string) => void look({ ports: [{ port, host }] });+ const checkAgain = () => void look();switch (state.s) {case "unsupported":return (@@ -588,18 +744,35 @@ function Screen({ state, look, choose, again, asks }: { state: Finder; look: Ret</p>);case "needs-setting":- return <SettingFix key={state.port} port={state.port} back={state.back} again={again} others={state.others} onChoose={choose} />;+ return (+ <SettingFix+ key={state.port}+ port={state.port}+ back={state.back}+ again={again}+ weak={state.weak}+ others={state.others}+ missed={state.missed}+ notComfy={state.notComfy}+ checking={checking}+ onChoose={choose}+ onCheck={checkAgain}+ />+ );case "waiting":- return <WaitingScreen port={state.port} since={state.since} onLook={() => lookAt(state.port, "127.0.0.1")} />;+ return <WaitingScreen port={state.port} since={state.since} onLook={checkAgain} />;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>+ <p className="text-[15px] font-medium">No ComfyUI found on this computer.</p>+ <p className="mt-1 text-muted-foreground">Start ComfyUI, then check again.</p></div>- <Watching>Fuobe looks again by itself every few seconds.</Watching>- <OtherPort onLook={lookAt} missed={state.missed} />+ <Button className="h-11 sm:h-9" onClick={checkAgain}>+ <RefreshCw /> Check again+ </Button>+ <Watching>Fuobe also looks for it by itself every few seconds.</Watching>+ <OtherPort onLook={lookAt} missed={state.missed} notComfy={state.notComfy} /><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">diff --git a/src/components/gpu/use-local-comfy.ts b/src/components/gpu/use-local-comfy.tsindex 0a268b6f..7c53d5b9 100644--- a/src/components/gpu/use-local-comfy.ts+++ b/src/components/gpu/use-local-comfy.ts@@ -2,26 +2,38 @@import { useCallback, useEffect, useRef, useState } from "react";import { loopbackFetch } from "@/lib/gpu/browser-check";-import { localBase, portsToLook, sameFinder, settled, type Finder, type PortLook, type SystemStats } from "@/lib/local-comfy";+import { firstPorts, localBase, portsToLook, sameFinder, settled, type Finder, type PortLook, type SettleOptions, type SystemStats } from "@/lib/local-comfy";import { rememberedComfy } from "./computer-runtime";import { useComputerSupport } from "./open-connect";/**- * 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 at every port: every 2 s while it- * waits for ComfyUI to come back with the setting, every 5 s while nothing answers. It never looks on its own while the- * browser would still ask (Chrome's advice): the person's click does the first look. `auto: false`: not even when the- * browser lets Fuobe in already (a card that only shows the choice must never connect by itself).+ * Finding the ComfyUI on this computer from the page ("Use the ComfyUI on this computer"). A look is short and in+ * order: where ComfyUI was found before and its usual port (8188) first, and a ComfyUI read there ends it; only then the+ * other ports ComfyUI uses. It tells a ComfyUI it can read from one that answers without letting this page in. While+ * the card is open and the tab is in view, it looks again quietly: every 2 s at the port shown while it waits for+ * ComfyUI to let Fuobe in (a ping that leaves no line in the console, and a full look every 10 s or when the port comes+ * back), every 3 s at that port and 8188 while ComfyUI restarts (every port every 30 s), and every 5 s at 8188 and the+ * remembered port while nothing answers. Each look pings first, so a port where nothing answers costs one line in the+ * console. It never looks on its own while the browser would still ask (Chrome's advice): the person's click does the+ * first look. `auto: false`: not even when the browser lets Fuobe in already (a card that only shows the choice must+ * never connect by itself).*/export type { Finder };-const LOOK_MS = 1500;--async function timed(url: string, init: RequestInit): Promise<Response> {+/** How long a look waits for ComfyUI's answer (a busy ComfyUI can be slow), and for a ping. */+const READ_MS = 3000;+const PING_MS = 1500;+/** While a port answers without letting this page in, a full look there at most this often (pings in between). */+const REREAD_MS = 10_000;+/** While ComfyUI restarts, a look at every port at most this often (it may come back elsewhere). */+const RESCAN_MS = 30_000;+/** A note about a port the person picked ("Nothing answers on port 8189 right now") stays this long. */+const NOTE_MS = 30_000;++async function timed(url: string, init: RequestInit, ms: number): Promise<Response> {const ctrl = new AbortController();- const timer = setTimeout(() => ctrl.abort(), LOOK_MS);+ const timer = setTimeout(() => ctrl.abort(), ms);try {return await loopbackFetch(url, { ...init, signal: ctrl.signal });} finally {@@ -29,22 +41,34 @@ async function timed(url: string, init: RequestInit): Promise<Response> {}}-/** One port: ComfyUI that this page can read, something that answers but can't be read, or nothing. */+/** Does something answer on this port? A look that can't read the answer (and so leaves no line in the console). */+export async function pingOn(port: number, host = "127.0.0.1", ms = PING_MS): Promise<boolean> {+ try {+ await timed(`${localBase(port, host)}/system_stats`, { mode: "no-cors", credentials: "omit", cache: "no-store" }, ms);+ return true;+ } catch {+ return false;+ }+}++/**+ * One port: ComfyUI that this page can read ("found"), something that answers but won't let this page read it+ * ("unreadable": ComfyUI without Fuobe Connect or the setting, or another app), another app's readable answer+ * ("other"), or nothing.+ */export async function lookOn(port: number, host = "127.0.0.1"): Promise<PortLook> {- const base = localBase(port, host);+ // A ping first (as patient as the read: a busy ComfyUI can be slow): a port where nothing answers costs one line in+ // the console, not two.+ if (!(await pingOn(port, host, READ_MS))) return { port, host, state: "none" };+ let res: Response;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" };+ res = await timed(`${localBase(port, host)}/system_stats`, { credentials: "omit", cache: "no-store" }, READ_MS);} 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" };- }+ // Something answers, but this page may not read it.+ return { port, host, state: "unreadable" };}+ const stats = res.ok ? ((await res.json().catch(() => null)) as SystemStats | null) : null;+ return stats?.system ? { port, host, state: "found", stats } : { port, host, state: "other" };}type Permission = "granted" | "prompt" | "denied" | "unknown";@@ -68,51 +92,105 @@ export { usePagePlace } from "./use-page-place";const visible = () => typeof document === "undefined" || document.visibilityState === "visible";-/** The finder, while `active` (the card is open). `perm`: whether the browser would still ask, once known. */+/**+ * The finder, while `active` (the card is open). `perm`: whether the browser would still ask, once known. `checking`:+ * the port the person picked ("Use port 8189") while it is looked at.+ */export function useLocalComfy(active: boolean, o: { auto?: boolean } = {}) {const auto = o.auto !== false;const support = useComputerSupport();const [state, setState] = useState<Finder>({ s: "start" });const [perm, setPerm] = useState<Permission | null>(null);+ const [checking, setChecking] = useState<number | null>(null);const cur = useRef(state);useEffect(() => {cur.current = state;}, [state]);- const busy = useRef(false);-- /** The screen for what the looks found; the same state (no new render) when nothing changed. */- const settle = useCallback((looks: PortLook[], port?: number) => {+ /** Looks under way: a quiet look waits for none. */+ const running = useRef(0);+ /** Bumped by every look the person asks for: a look that ends after a newer one started never overrides it. */+ const gen = useRef(0);+ /** Each port's last answer, and when it was last read in full (quiet looks ping in between). */+ const seen = useRef(new Map<number, { state: PortLook["state"]; read: number }>());+ /** When every port was last looked at (or the wait for a restarting ComfyUI began). */+ const lastFull = useRef(0);++ const show = useCallback((next: Finder) => {const was = cur.current;- const next = settled(was, looks, rememberedComfy()?.port, port, Date.now());+ cur.current = next;+ if (next.s === "waiting" && was.s !== "waiting") lastFull.current = Date.now();if (!sameFinder(was, next)) setState(next);}, []);- /** "My ComfyUI is on that port": the fix and the quiet looks follow it. */- const choose = useCallback((port: number) => {- const was = cur.current;- if (was.s === "needs-setting") setState({ s: "needs-setting", port, back: false, others: [...new Set([was.port, ...(was.others ?? [])])].filter((p) => p !== port) });+ /** A quiet look at one port: while it answers without letting this page in, a ping says it is still there. */+ const quietOn = useCallback(async (port: number, host: string): Promise<PortLook> => {+ const last = seen.current.get(port);+ if (last?.state === "unreadable" && Date.now() - last.read < REREAD_MS) return (await pingOn(port, host)) ? { port, host, state: "unreadable" } : { port, host, state: "none" };+ return lookOn(port, host);}, []);- /** Look on every port (or the ones given), then say what was found. `quiet`: keep the screen as it is meanwhile. */+ /**+ * Look, then say what was found: every port in order (stopping early at a readable ComfyUI), or the ones given.+ * `quiet`: keep the screen as it is meanwhile, and look only where it matters now. `chosen`: the person picked that+ * port from the others.+ */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" });+ async (o: { ports?: { port: number; host?: string }[]; quiet?: boolean; chosen?: number } = {}) => {+ if (support !== "ok" || (o.quiet && running.current)) return;+ const g = o.quiet ? gen.current : ++gen.current;+ running.current++;+ // A look the person asks for ends any "Checking port…" before it (that look no longer decides).+ if (!o.quiet) setChecking(o.chosen ?? null);+ if (!o.quiet && o.chosen === undefined) show({ 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)));+ const hostOf = (port: number) => (port === remembered?.port ? remembered.host : "127.0.0.1");+ const was = cur.current;+ // Quietly: the port shown (and ComfyUI's usual one while only a weak port is shown); 8188 and the remembered+ // port while nothing answers; the port waited for and 8188 while ComfyUI restarts, and every port now and then+ // (it may come back elsewhere).+ const quietPorts =+ was.s === "needs-setting"+ ? [...new Set([was.port, ...(was.weak && !was.chosen ? firstPorts(remembered?.port) : [])])]+ : was.s === "none"+ ? firstPorts(remembered?.port)+ : was.s === "waiting" && Date.now() - lastFull.current < RESCAN_MS+ ? [...new Set([was.port, ...firstPorts(remembered?.port)])]+ : null;+ if (!o.ports && !(o.quiet && quietPorts)) lastFull.current = Date.now();+ const ports = o.ports ?? (o.quiet && quietPorts ? quietPorts.map((port) => ({ port, host: hostOf(port) })) : null);+ let looks: PortLook[];+ if (ports) {+ looks = await Promise.all(ports.map((p) => (o.quiet ? quietOn(p.port, p.host ?? "127.0.0.1") : lookOn(p.port, p.host))));+ } else {+ const first = await Promise.all(firstPorts(remembered?.port).map((port) => lookOn(port, hostOf(port))));+ const rest = first.some((l) => l.state === "found") ? [] : portsToLook(remembered?.port).filter((p) => !first.some((l) => l.port === p));+ looks = [...first, ...(await Promise.all(rest.map((port) => lookOn(port, hostOf(port)))))];+ }+ const now = Date.now();+ for (const l of looks) {+ const last = seen.current.get(l.port);+ const pinged = !!o.quiet && last?.state === "unreadable" && l.state === "unreadable" && now - last.read < REREAD_MS;+ seen.current.set(l.port, { state: l.state, read: pinged ? last.read : now });+ }+ // The person asked for a newer look meanwhile: that one decides.+ if (g !== gen.current) return;// 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);+ if (looks.every((l) => l.state === "none") && (await loopbackPermission()).state === "denied") return show({ s: "blocked" });+ const typed = !!o.ports && o.ports.length === 1 && !o.quiet && o.chosen === undefined ? o.ports[0].port : undefined;+ const so: SettleOptions = { ...(typed !== undefined && { typed }), ...(o.chosen !== undefined && { chosen: o.chosen }), partial: !!ports && (!!o.quiet || o.chosen !== undefined) };+ show(settled(cur.current, looks, remembered?.port, Date.now(), so));} finally {- busy.current = false;+ running.current--;+ if (o.chosen !== undefined) setChecking((c) => (c === o.chosen ? null : c));}},- [settle, support],+ [show, quietOn, support],);+ /** "Use port 8189": that port is looked at now, then its own screen shows (connected, the one step, or nothing there). */+ const choose = useCallback((port: number) => void look({ ports: [{ port, host: "127.0.0.1" }], chosen: port }), [look]);+// 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;@@ -120,7 +198,7 @@ export function useLocalComfy(active: boolean, o: { auto?: boolean } = {}) {let status: PermissionStatus | undefined;const onChange = () => {if (status) setPerm(status.state as Permission);- if (status?.state === "denied") setState({ s: "blocked" });+ if (status?.state === "denied") show({ s: "blocked" });else if (status?.state === "granted" && cur.current.s === "blocked") void look();};void loopbackPermission().then((p) => {@@ -129,22 +207,31 @@ export function useLocalComfy(active: boolean, o: { auto?: boolean } = {}) {setPerm(p.state);status?.addEventListener("change", onChange);if (p.state === "granted" && cur.current.s === "start" && auto) void look();- else if (p.state === "denied") setState({ s: "blocked" });+ else if (p.state === "denied") show({ s: "blocked" });});return () => {alive = false;status?.removeEventListener("change", onChange);};- }, [active, support, look, auto]);+ }, [active, support, look, auto, show]);- // Quiet looks at every port while it waits for ComfyUI (with the setting: a readable ComfyUI on any port connects) or- // for any ComfyUI to start.- const every = state.s === "needs-setting" || state.s === "waiting" ? 2000 : state.s === "none" ? 5000 : 0;+ // Quiet looks while it waits for ComfyUI to let Fuobe in, to come back, or to start.+ const every = state.s === "needs-setting" ? 2000 : state.s === "waiting" ? 3000 : state.s === "none" ? 5000 : 0;useEffect(() => {if (!active || !every) return;const id = setInterval(() => visible() && void look({ quiet: true }), every);return () => clearInterval(id);}, [active, every, look]);- return { state: support !== "ok" ? ({ s: "unsupported", why: support } as Finder) : state, look, choose, support, perm };+ // A note about a port the person picked or typed goes after a while (quiet looks would otherwise keep it up).+ useEffect(() => {+ if (state.s !== "needs-setting" || (state.missed === undefined && state.notComfy === undefined)) return;+ const t = setTimeout(() => {+ const now = cur.current;+ if (now.s === "needs-setting" && sameFinder(now, state)) show({ ...now, missed: undefined, notComfy: undefined });+ }, NOTE_MS);+ return () => clearTimeout(t);+ }, [state, show]);++ return { state: support !== "ok" ? ({ s: "unsupported", why: support } as Finder) : state, look, choose, checking, support, perm };}diff --git a/src/lib/local-comfy.ts b/src/lib/local-comfy.tsindex 65de22c2..06822642 100644--- a/src/lib/local-comfy.ts+++ b/src/lib/local-comfy.ts@@ -167,10 +167,11 @@ export function mayDownload(f: Pick<WantedFile, "filename" | "subfolder" | "typereturn filesIn(entries).some((x) => x.filename === f.filename && (x.subfolder ?? "") === f.subfolder && x.type === f.type);}-/** What a look on one port found. */+/** What a look on one port found. "other": an answer this page can read that isn't ComfyUI's (another app). */export type PortLook =| { port: number; host?: string; state: "found"; stats: SystemStats; guard?: boolean }| { port: number; host?: string; state: "unreadable" }+ | { port: number; host?: string; state: "other" }| { port: number; host?: string; state: "none" };export interface SystemStats {@@ -178,6 +179,11 @@ export interface SystemStats {devices?: { name?: string; type?: string; vram_total?: number }[];}+/** ComfyUI's usual port. */+export const COMFY_PORT = 8188;+/** ComfyUI Desktop's usual port. */+export const DESKTOP_PORT = 8000;+/** A port's place among ComfyUI's usual ones (8188 first); one the person typed comes after them, lowest first. */const portRank = (port: number) => {const at = (COMFY_PORTS as readonly number[]).indexOf(port);@@ -185,18 +191,34 @@ const portRank = (port: number) => {};/**- * The ComfyUI to use from several looks: one Fuobe can read before one it can't, the remembered port first, then the- * usual order (8188 before Desktop's 8000: another app on 8000 doesn't win). "none" when nothing answered.+ * How sure Fuobe is that a look is the person's ComfyUI. 3: it read ComfyUI's own answer. 2: something answers but+ * won't let this page read it, on ComfyUI's usual port (or Desktop's, which ranks after it), where ComfyUI was found+ * before, or on the port the person chose or typed. 1: the same on any other port (another app answers there just as+ * well). 0: nothing, or another app's answer Fuobe can read (it isn't ComfyUI, so it is never offered).+ */+export function lookStrength(l: PortLook, remembered?: number, chosen?: number): number {+ if (l.state === "found") return 3;+ if (l.state === "unreadable") return l.port === COMFY_PORT || l.port === DESKTOP_PORT || l.port === remembered || l.port === chosen ? 2 : 1;+ return 0;+}++/**+ * The ComfyUI to use from several looks: one Fuobe can read first; then something on ComfyUI's usual port or where it+ * was found before; another app's port last. Among equals: the remembered port, then the usual order (8188 before+ * Desktop's 8000). "none" when nothing answered.*/-export function pickLook(looks: PortLook[], remembered?: number): PortLook | { state: "none" } {- const rank = (l: PortLook) => (l.state === "found" ? 0 : l.state === "unreadable" ? 1 : 2);- const sorted = looks.filter((l) => l.state !== "none").sort((a, b) => rank(a) - rank(b) || Number(b.port === remembered) - Number(a.port === remembered) || portRank(a.port) - portRank(b.port));+export function pickLook(looks: PortLook[], remembered?: number, chosen?: number): PortLook | { state: "none" } {+ const s = (l: PortLook) => lookStrength(l, remembered, chosen);+ const sorted = looks.filter((l) => s(l) > 0).sort((a, b) => s(b) - s(a) || Number(b.port === remembered) - Number(a.port === remembered) || portRank(a.port) - portRank(b.port));return sorted[0] ?? { state: "none" };}/** The ports to look at, the remembered one first. */export const portsToLook = (remembered?: number): number[] => [...new Set([...(remembered ? [remembered] : []), ...COMFY_PORTS])];+/** The first ports of a look (the remembered one, then ComfyUI's usual one): a readable ComfyUI there ends the look. */+export const firstPorts = (remembered?: number): number[] => [...new Set([...(remembered ? [remembered] : []), COMFY_PORT])];+/** What the "Use the ComfyUI on this computer" card shows (components/gpu/use-local-comfy.ts finds it). */export type Finder =/** The browser will ask to let Fuobe reach apps on this computer: a click starts the first look. */@@ -205,37 +227,99 @@ export type Finder =/** Found and readable: the caller connects. */| { s: "found"; port: number; host: string; stats: SystemStats }/**- * ComfyUI answers but can't be read: it needs the setting (`back`: it restarted, still without it). `others`: other- * ports where something answers too (the person picks where their ComfyUI is).+ * Something answers but won't let this page read it: ComfyUI has to let Fuobe in (`back`: it restarted, still+ * without it). `weak`: a port ComfyUI doesn't usually use, and nothing better answers (it may be another app).+ * `chosen`: the person said their ComfyUI is on this port. `others`: the other ports where something answers, best+ * first. `missed`: the person chose a port where nothing answers any more.*/- | { s: "needs-setting"; port: number; back: boolean; others?: number[] }+ | { s: "needs-setting"; port: number; back: boolean; weak?: true; chosen?: true; others?: number[]; missed?: number; notComfy?: number }/** The port went quiet after it needed the setting: ComfyUI is restarting. */- | { s: "waiting"; port: number; since: number }- | { s: "none"; missed?: number }+ | { s: "waiting"; port: number; since: number; chosen?: true }+ /** `missed`: the port the person typed or picked, where nothing answers. `notComfy`: another app answers there. */+ | { s: "none"; missed?: number; notComfy?: number }/** The browser keeps Fuobe from reaching apps on this computer. */| { s: "blocked" }/** This browser or page can't: Safari, a phone, or a studio on plain http at a network address. */| { s: "unsupported"; why: "safari" | "phone" | "http" };+export interface SettleOptions {+ /** The one port the person typed: counted as chosen, and a miss is said. */+ typed?: number;+ /** The port the person picked from the other ports ("Use port 8189"): followed from now on. */+ chosen?: number;+ /** Only some ports were looked at (a quiet look): the other ports found before are kept. */+ partial?: boolean;+}+/**- * The card's next screen after a look (`typed`: the one port the person asked about). A readable ComfyUI on any port- * connects. While it waits for one ComfyUI to come back with the setting, that port decides: quiet there is ComfyUI- * restarting, and another app answering on another port changes nothing.+ * The card's next screen after a look. A readable ComfyUI on any port connects. While it waits for one ComfyUI to let+ * Fuobe in, that port decides: quiet there is ComfyUI restarting, and another app answering elsewhere changes nothing.+ * A weak port the person didn't choose gives way as soon as something better answers (ComfyUI's own port).*/-export function settled(was: Finder, looks: PortLook[], remembered: number | undefined, typed: number | undefined, now: number): Finder {- const best = pickLook(looks, remembered);+export function settled(was: Finder, looks: PortLook[], remembered: number | undefined, now: number, o: SettleOptions = {}): Finder {+ const following = was.s === "needs-setting" || was.s === "waiting" ? was : null;+ const picked = o.chosen ?? o.typed;+ const chosen = picked ?? (following?.chosen ? following.port : undefined);+ const best = pickLook(looks, remembered, chosen);if (best.state === "found") return { s: "found", port: best.port, host: best.host ?? "127.0.0.1", stats: best.stats };- const answering = looks.filter((l) => l.state === "unreadable").map((l) => l.port);+ const strength = (l: PortLook) => lookStrength(l, remembered, chosen);+ const answering = looks+ .filter((l) => strength(l) > 0)+ .sort((a, b) => strength(b) - strength(a) || portRank(a.port) - portRank(b.port))+ .map((l) => l.port);+ const looked = new Set(looks.map((l) => l.port));+ /** The other answering ports: these looks', and, after a partial look, the ones found before that weren't looked at. */const others = (port: number) => {- const rest = answering.filter((p) => p !== port);+ const before = o.partial && was.s === "needs-setting" ? [was.port, ...(was.others ?? [])].filter((p) => !looked.has(p)) : [];+ const rest = [...new Set([...answering, ...before])].filter((p) => p !== port);return rest.length ? { others: rest } : {};};- if ((was.s === "needs-setting" || was.s === "waiting") && looks.some((l) => l.port === was.port)) {- if (answering.includes(was.port)) return { s: "needs-setting", port: was.port, back: was.s === "waiting" || (was.s === "needs-setting" && was.back), ...others(was.port) };- return { s: "waiting", port: was.port, since: was.s === "waiting" ? was.since : now };+ const at = (port: number) => looks.find((l) => l.port === port);+ const screen = (l: PortLook, back: boolean): Finder => ({+ s: "needs-setting",+ port: l.port,+ back,+ ...(strength(l) < 2 && { weak: true as const }),+ ...(l.port === chosen && { chosen: true as const }),+ ...others(l.port),+ });++ // The person picked or typed a port: its own screen, or, when it isn't ComfyUI's now, the screen before saying so.+ if (picked !== undefined) {+ const l = at(picked);+ if (l && strength(l) > 0) return screen(l, false);+ const why = l?.state === "other" ? { notComfy: picked } : { missed: picked };+ if (was.s === "needs-setting" && was.port !== picked) {+ const rest = (was.others ?? []).filter((p) => p !== picked);+ return { s: "needs-setting", port: was.port, back: was.back, ...(was.weak && { weak: true as const }), ...(was.chosen && { chosen: true as const }), ...(rest.length && { others: rest }), ...why };+ }+ // The port shown (a weak one the person said is theirs) is gone: the next port that answers, or none.+ if (was.s === "needs-setting" && was.others?.length) {+ const [next, ...rest] = was.others;+ return { s: "needs-setting", port: next, back: false, weak: true, ...(rest.length && { others: rest }), ...why };+ }+ return { s: "none", ...why };+ }++ if (following) {+ const l = at(following.port);+ // A weak port nobody chose is shown only until something better answers, and isn't waited for.+ const weakShown = following.s === "needs-setting" && !!following.weak && !following.chosen;+ const better = weakShown && !!l && best.state !== "none" && strength(best) > strength(l);+ if (l && !better) {+ if (strength(l) > 0) {+ const next = screen(l, following.s === "waiting" || (following.s === "needs-setting" && following.back));+ // A note about a port the person picked stays through quiet looks (the card clears it after a while).+ const note = following.s === "needs-setting" && o.partial ? { ...(following.missed && { missed: following.missed }), ...(following.notComfy && { notComfy: following.notComfy }) } : {};+ return next.s === "needs-setting" ? { ...next, ...note } : next;+ }+ if (!weakShown) return { s: "waiting", port: following.port, since: following.s === "waiting" ? following.since : now, ...(following.chosen && { chosen: true as const }) };+ }+ // A quiet look that didn't reach the port shown, and found nothing better, changes nothing.+ if (!l && o.partial && best.state === "none") return was;}- if (best.state === "unreadable") return { s: "needs-setting", port: best.port, back: false, ...others(best.port) };- return { s: "none", ...(typed && { missed: typed }) };+ if (best.state !== "none") return screen(best, false);+ return { s: "none" };}/** The same screen (a quiet look that found nothing new changes nothing). */diff --git a/tests/computer-pure.test.ts b/tests/computer-pure.test.tsindex bd437c41..dda6556f 100644--- a/tests/computer-pure.test.ts+++ b/tests/computer-pure.test.ts@@ -9,7 +9,7 @@ import { explainComfyError } from "@/lib/comfy";import { fixFromPromptError } from "@/lib/gpu/fix-codes";import { parseComfyBinary, parseComfyText } from "@/lib/comfy-ws";import { tileJob, type LocalJob } from "@/lib/computer-runner";-import { browserSupport, COMFY_PORTS, graphProblem, localBase, mayDownload, pageCanReach, pickLook, portsToLook, preflightPath, readPath, sameFinder, settled, statsFacts, typedPort, viewPath, writePath, type Finder } from "@/lib/local-comfy";+import { browserSupport, COMFY_PORTS, firstPorts, graphProblem, lookStrength, localBase, mayDownload, pageCanReach, pickLook, portsToLook, preflightPath, readPath, sameFinder, settled, statsFacts, typedPort, viewPath, writePath, type Finder } from "@/lib/local-comfy";import { DONE_SHOWN_MS, duration, jobFraction, jobWords, madeNoun, makingWords, queueWords, RELAY_WORDS, reportAllowed, savingWords, sendingWords, tabFailureWords, type RelayState } from "@/lib/relay";const ID = "0f8fad5b-d9cb-469f-a165-70867728950e";@@ -113,25 +113,120 @@ describe("the local ComfyUI's addresses", () => {const stats = { system: {} };const start: Finder = { s: "start" };// Two answer without the setting: ComfyUI's own port first, the other offered.- const two = settled(start, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "unreadable" }, { port: 8189, state: "none" }], undefined, undefined, 1);+ const two = settled(start, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "unreadable" }, { port: 8189, state: "none" }], undefined, 1);expect(two).toEqual({ s: "needs-setting", port: 8188, back: false, others: [8000] });// ComfyUI on 8188 restarts: waiting for it, though another app still answers on 8000.- const waiting = settled(two, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "none" }], undefined, undefined, 5);+ const waiting = settled(two, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "none" }], undefined, 5);expect(waiting).toEqual({ s: "waiting", port: 8188, since: 5 });// Each quiet look while it waits keeps the same screen (the same "since", so the 2-minute help comes).- const again = settled(waiting, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "none" }], undefined, undefined, 9);+ const again = settled(waiting, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "none" }], undefined, 9);expect(again).toEqual(waiting);expect(sameFinder(waiting, again)).toBe(true);// Back without the setting yet.- expect(settled(waiting, [{ port: 8188, state: "unreadable" }], undefined, undefined, 11)).toEqual({ s: "needs-setting", port: 8188, back: true });+ expect(settled(waiting, [{ port: 8188, state: "unreadable" }], undefined, 11)).toEqual({ s: "needs-setting", port: 8188, back: true });// Back with it on another port (ComfyUI moved): connects.- expect(settled(waiting, [{ port: 8188, state: "none" }, { port: 8189, state: "found", stats }], undefined, undefined, 12)).toMatchObject({ s: "found", port: 8189 });+ expect(settled(waiting, [{ port: 8188, state: "none" }, { port: 8189, state: "found", stats }], undefined, 12)).toMatchObject({ s: "found", port: 8189 });// Nothing anywhere; a typed port that missed.- expect(settled(start, [{ port: 8188, state: "none" }], undefined, undefined, 1)).toEqual({ s: "none" });- expect(settled({ s: "none" }, [{ port: 3391, state: "none" }], undefined, 3391, 1)).toEqual({ s: "none", missed: 3391 });+ expect(settled(start, [{ port: 8188, state: "none" }], undefined, 1)).toEqual({ s: "none" });+ expect(settled({ s: "none" }, [{ port: 3391, state: "none" }], undefined, 1, { typed: 3391 })).toEqual({ s: "none", missed: 3391 });expect(sameFinder({ s: "none" }, { s: "none", missed: 3391 })).toBe(false);});+ describe("ranking what answers on this computer", () => {+ const stats = { system: { comfyui_version: "0.42.0" } };+ const start: Finder = { s: "start" };++ it("ComfyUI on 8188 (even unreadable) and a 401 on 8189: 8188 is the one shown, 8189 only among the other ports", () => {+ // The browser sees the same for both (an answer it may not read): ComfyUI's usual port ranks first.+ const s = settled(start, [{ port: 8188, state: "unreadable" }, { port: 8189, state: "unreadable" }, { port: 8000, state: "none" }], undefined, 1);+ expect(s).toEqual({ s: "needs-setting", port: 8188, back: false, others: [8189] });+ // Readable on 8188: it connects, whatever answers elsewhere.+ expect(settled(start, [{ port: 8189, state: "unreadable" }, { port: 8188, state: "found", stats }], undefined, 1)).toMatchObject({ s: "found", port: 8188 });+ expect(lookStrength({ port: 8188, state: "unreadable" })).toBeGreaterThan(lookStrength({ port: 8189, state: "unreadable" }));+ });++ it("only a 401 on 8189: a weak candidate (it may not be ComfyUI), not a ComfyUI found", () => {+ const s = settled(start, [{ port: 8188, state: "none" }, { port: 8189, state: "unreadable" }], undefined, 1);+ expect(s).toEqual({ s: "needs-setting", port: 8189, back: false, weak: true });+ // Another app's readable answer isn't ComfyUI: never shown, never under Other ports.+ expect(settled(start, [{ port: 8000, state: "other" }, { port: 8189, state: "unreadable" }], undefined, 1)).toEqual({ s: "needs-setting", port: 8189, back: false, weak: true });+ expect(settled(start, [{ port: 8000, state: "other" }], undefined, 1)).toEqual({ s: "none" });+ expect(lookStrength({ port: 8188, state: "other" })).toBe(0);+ });++ it("something on 8000, ComfyUI Desktop's port, is a candidate (after 8188)", () => {+ expect(settled(start, [{ port: 8188, state: "none" }, { port: 8000, state: "unreadable" }], undefined, 1)).toEqual({ s: "needs-setting", port: 8000, back: false });+ expect(settled(start, [{ port: 8000, state: "unreadable" }, { port: 8188, state: "unreadable" }], undefined, 1)).toEqual({ s: "needs-setting", port: 8188, back: false, others: [8000] });+ // And it beats an app on a port ComfyUI doesn't usually use.+ expect(settled(start, [{ port: 8189, state: "unreadable" }, { port: 8000, state: "unreadable" }], undefined, 1)).toEqual({ s: "needs-setting", port: 8000, back: false, others: [8189] });+ });++ it("a port the person types counts as theirs: its screen, a miss, or another app there", () => {+ const none: Finder = { s: "none" };+ expect(settled(none, [{ port: 9188, state: "unreadable" }], undefined, 1, { typed: 9188 })).toEqual({ s: "needs-setting", port: 9188, back: false, chosen: true });+ expect(settled(none, [{ port: 9188, state: "found", stats }], undefined, 1, { typed: 9188 })).toMatchObject({ s: "found", port: 9188 });+ expect(settled(none, [{ port: 8000, state: "other" }], undefined, 1, { typed: 8000 })).toEqual({ s: "none", notComfy: 8000 });+ expect(settled(none, [{ port: 9188, state: "none" }], undefined, 1, { typed: 9188 })).toEqual({ s: "none", missed: 9188 });+ });++ it("a weak port shown gives way once ComfyUI's own port answers (it never sticks)", () => {+ const weak = settled(start, [{ port: 8188, state: "none" }, { port: 8189, state: "unreadable" }], undefined, 1);+ // A quiet look at 8189 and 8188: ComfyUI started on 8188.+ expect(settled(weak, [{ port: 8189, state: "unreadable" }, { port: 8188, state: "unreadable" }], undefined, 2, { partial: true })).toEqual({ s: "needs-setting", port: 8188, back: false, others: [8189] });+ // The weak port goes quiet: no "waiting for ComfyUI to start" for an app that may not be ComfyUI.+ expect(settled(weak, [{ port: 8189, state: "none" }, { port: 8188, state: "none" }], undefined, 3, { partial: true })).toEqual({ s: "none" });+ });++ it("a ComfyUI read on a port it doesn't usually use wins over an unreadable 8188", () => {+ expect(settled(start, [{ port: 8188, state: "unreadable" }, { port: 8190, state: "found", stats }], undefined, 1)).toMatchObject({ s: "found", port: 8190 });+ expect(pickLook([{ port: 8188, state: "unreadable" }, { port: 7821, state: "found", stats }])).toMatchObject({ port: 7821, state: "found" });+ // Where ComfyUI was found before counts as much as 8188.+ expect(settled(start, [{ port: 8188, state: "none" }, { port: 8190, state: "unreadable" }], 8190, 1)).toEqual({ s: "needs-setting", port: 8190, back: false });+ });++ it("nothing answers: not found", () => {+ expect(settled(start, COMFY_PORTS.map((port) => ({ port, state: "none" as const })), undefined, 1)).toEqual({ s: "none" });+ expect(pickLook([])).toEqual({ state: "none" });+ });++ it("the person picks another port: it is shown and followed, or the same screen says nothing answers there now", () => {+ const two = settled(start, [{ port: 8188, state: "unreadable" }, { port: 8189, state: "unreadable" }], undefined, 1);+ const picked = settled(two, [{ port: 8189, state: "unreadable" }], undefined, 2, { chosen: 8189, partial: true });+ expect(picked).toEqual({ s: "needs-setting", port: 8189, back: false, chosen: true, others: [8188] });+ // Followed: quiet looks at 8189 keep it (8188 is still offered).+ expect(settled(picked, [{ port: 8189, state: "unreadable" }], undefined, 3, { partial: true })).toEqual(picked);+ // And back to 8188.+ expect(settled(picked, [{ port: 8188, state: "unreadable" }], undefined, 4, { chosen: 8188, partial: true })).toEqual({ s: "needs-setting", port: 8188, back: false, chosen: true, others: [8189] });+ // Picked, and readable there: connects.+ expect(settled(two, [{ port: 8189, state: "found", stats }], undefined, 5, { chosen: 8189, partial: true })).toMatchObject({ s: "found", port: 8189 });+ // Picked, and gone: the screen stays, and says so.+ expect(settled(two, [{ port: 8189, state: "none" }], undefined, 6, { chosen: 8189, partial: true })).toEqual({ s: "needs-setting", port: 8188, back: false, missed: 8189 });+ // Picked, and another app answers there now: the screen stays, and says so.+ expect(settled(two, [{ port: 8189, state: "other" }], undefined, 7, { chosen: 8189, partial: true })).toEqual({ s: "needs-setting", port: 8188, back: false, notComfy: 8189 });+ // A port that only answered weakly, picked by the person, is no longer weak.+ const weak = settled(start, [{ port: 8189, state: "unreadable" }], undefined, 1);+ expect(settled(weak, [{ port: 8189, state: "unreadable" }], undefined, 2, { chosen: 8189, partial: true })).toEqual({ s: "needs-setting", port: 8189, back: false, chosen: true });+ // The weak port shown, picked and gone: not still shown as answering; the next one that answers, or none.+ expect(settled(weak, [{ port: 8189, state: "none" }], undefined, 3, { chosen: 8189, partial: true })).toEqual({ s: "none", missed: 8189 });+ const weak2 = settled(start, [{ port: 8189, state: "unreadable" }, { port: 8190, state: "unreadable" }], undefined, 1);+ expect(settled(weak2, [{ port: 8189, state: "none" }], undefined, 3, { chosen: 8189, partial: true })).toEqual({ s: "needs-setting", port: 8190, back: false, weak: true, missed: 8189 });+ });++ it("a quiet look at the port shown keeps the other ports found before", () => {+ const two = settled(start, [{ port: 8188, state: "unreadable" }, { port: 8189, state: "unreadable" }, { port: 8000, state: "unreadable" }], undefined, 1);+ expect(two).toMatchObject({ port: 8188, others: [8000, 8189] });+ const quiet = settled(two, [{ port: 8188, state: "unreadable" }], undefined, 2, { partial: true });+ expect(quiet).toEqual(two);+ expect(sameFinder(quiet, two)).toBe(true);+ });++ it("looks first where ComfyUI was found before and on 8188", () => {+ expect(firstPorts()).toEqual([8188]);+ expect(firstPorts(8190)).toEqual([8190, 8188]);+ expect(firstPorts(8188)).toEqual([8188]);+ });+ });+it("can tell Fuobe's guard is there", () => {expect(readPath("/fuobe/guard")).toBe("/fuobe/guard");expect(statsFacts({ system: { argv: ["main.py", "--enable-cors-header", "https://fuobe.com"] } }, "https://fuobe.com", true)).toMatchObject({ cors: "exact", guard: true });diff --git a/tests/e2e/comfy-detect.mjs b/tests/e2e/comfy-detect.mjsnew file mode 100644index 00000000..c298cb31--- /dev/null+++ b/tests/e2e/comfy-detect.mjs@@ -0,0 +1,348 @@+// "Use the ComfyUI on this computer": which port the card shows when several answer, at 390 and 1440 wide. A+// production server on 3650 with a throwaway data folder, and stand-ins: a ComfyUI that lets this page in on 18188+// (tests/helpers/fake-local-comfy.ts), the same without it on 18190, and an app that answers 401 with no CORS headers on+// 18189. The browser's requests to ComfyUI's ports are sent to the stand-ins before they leave it (8188 to 18188 or+// 18190, 8189 to 18189), every other loopback port is refused, and its sockets to them are closed: a real ComfyUI on+// 8188 is never touched.+//+// pnpm build && node tests/e2e/comfy-detect.mjs+//+// Checks: ComfyUI on 8188 and a 401 on 8189 show 8188 alone, with 8189 under "Other ports"; "Use port 8189" and+// "Use port 8188" each look at once and change the screen; ComfyUI letting this page in later connects by itself; a+// readable ComfyUI on 8188 connects without looking at any other port; only the 401 is a weak candidate; nothing is+// "No ComfyUI found", and Check again looks again; quiet looks reach only the port shown.+import { spawn } from "node:child_process";+import fs from "node:fs";+import http from "node:http";+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 ?? 3650);+const COMFY_OPEN = 18188;+const OTHER_APP = 18189;+const COMFY_CLOSED = 18190;+const READABLE_APP = 18191;+const DEAD_PORT = 3659;+const SITE = `http://127.0.0.1:${APP_PORT}`;+const shots = process.env.E2E_SHOTS ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-detect-shots-"));+fs.mkdirSync(shots, { recursive: true });+const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-detect-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 = 200) {+ 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);+ }+}++// --- Stand-ins.+const procs = [];+async function startFake(port, cors) {+ const args = ["--port", String(port), "--cors", cors, "--has", path.join(root, "workflows/comfyui/requirements.json")];+ const p = spawn(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", path.join(root, "tests/helpers/fake-local-comfy.ts"), ...args], { stdio: ["ignore", "ignore", "inherit"] });+ procs.push(p);+ if (!(await until(() => fetch(`http://127.0.0.1:${port}/__fake/stats`).then((r) => r.ok), 15_000))) throw new Error(`the stand-in on ${port} didn't start`);+}+// Another app: 401 to everything, no CORS headers (the browser can't read it, as with the one on the owner's 8189).+const otherApp = http.createServer((req, res) => {+ res.writeHead(401, { "content-type": "application/json", "www-authenticate": 'Bearer realm="app"' });+ res.end('{"error":"unauthorized"}');+});+// Another app the page can read (it lets this site in), and isn't ComfyUI.+const readableApp = http.createServer((req, res) => {+ res.writeHead(200, { "content-type": "application/json", "access-control-allow-origin": SITE, vary: "Origin" });+ res.end('{"status":"ok"}');+});++// --- 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",+ COMFYUI_URL: `http://127.0.0.1:${DEAD_PORT}`,+ 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) {+ for (const p of procs) p.kill();+ otherApp.close();+ readableApp.close();+ 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(-30).join("\n"));+ process.exit(code ?? (failed.length ? 1 : 0));+}++const WIDTHS = [+ { name: "1440", viewport: { width: 1440, height: 1000 } },+ { name: "390", viewport: { width: 390, height: 1400 } },+];++let browser;+let n = 0;+try {+ if (!(await until(() => fetch(`${SITE}/api/auth/me`).then((r) => r.ok), 120_000, 500))) throw new Error(`the studio didn't start:\n${serverLog}`);+ await startFake(COMFY_OPEN, SITE);+ await startFake(COMFY_CLOSED, "off");+ await new Promise((r) => otherApp.listen(OTHER_APP, "127.0.0.1", r));+ await new Promise((r) => readableApp.listen(READABLE_APP, "127.0.0.1", r));+ browser = await launch();++ /**+ * A signed-up account on Settings, with ComfyUI's ports mapped (`map`: the port the page asks for → a stand-in's;+ * a port not named has nothing there). Changing `map` later changes what answers. One account a width (sign-ups are+ * limited): each scenario after the first disconnects, forgets what the browser remembered, and opens Settings again.+ */+ const made = new Map();+ async function account(width, map) {+ const had = made.get(width.name);+ if (had) {+ const { ctx, page } = had;+ ctx.map = map;+ ctx.delay = {};+ ctx.loopback.length = 0;+ await page.evaluate(() => fetch("/api/account/gpu", { method: "DELETE" }).then((r) => r.status));+ await page.evaluate(() => localStorage.clear());+ await page.goto(`${SITE}/settings`, { waitUntil: "load" });+ const card = page.locator("#your-gpu");+ await card.getByRole("button", { name: "Find my ComfyUI" }).waitFor({ timeout: 30_000 });+ return { ...had, card };+ }+ const ctx = await browser.newContext({ viewport: width.viewport });+ ctx.map = map;+ ctx.delay = {};+ ctx.loopback = [];+ await ctx.route(/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+/, async (route) => {+ const u = new URL(route.request().url());+ const port = Number(u.port);+ if (port === APP_PORT) return route.continue();+ ctx.loopback.push({ port, path: u.pathname, cors: !!route.request().headers().origin, at: Date.now() });+ // A slow answer (`delay`: port → ms), to click again while a look is under way.+ if (ctx.delay[port]) await sleep(ctx.delay[port]);+ const to = ctx.map[port];+ if (!to) return route.abort("connectionrefused");+ u.port = String(to);+ return route.continue({ url: u.toString() });+ });+ // Sockets to ComfyUI's ports (the runner, once connected) never leave the browser.+ await ctx.routeWebSocket(/^wss?:\/\/(127\.0\.0\.1|localhost|\[::1\]):(?!3650)\d+/, (ws) => ws.close());+ 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}/settings`, { waitUntil: "load" });+ const email = `e2e-detect-${++n}-${Date.now()}@example.com`;+ 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}`);+ await page.goto(`${SITE}/settings`, { waitUntil: "load" });+ const card = page.locator("#your-gpu");+ await card.getByRole("button", { name: "Find my ComfyUI" }).waitFor({ timeout: 30_000 });+ made.set(width.name, { ctx, page });+ return { ctx, page, card };+ }+ const shot = (page, card, name) => card.screenshot({ path: path.join(shots, name) }).catch(() => page.screenshot({ path: path.join(shots, name) }));++ for (const w of WIDTHS) {+ // 1. The owner's computer: ComfyUI on 8188 that doesn't let this page in yet, and a 401 on 8189.+ {+ const { ctx, page, card } = await account(w, { 8188: COMFY_CLOSED, 8189: OTHER_APP });+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();+ const primary = card.getByText("Something is running on port 8188, ComfyUI's usual port.");+ check(`${w.name}: ComfyUI on 8188 and a 401 on 8189 show 8188`, !!(await until(() => primary.isVisible(), 20_000)));+ check(`${w.name}: …saying plainly why this page can't use it, with the one step`, (await card.getByText(/ComfyUI only answers the websites it's told to trust/).isVisible()) && (await card.getByText(/Install Fuobe Connect/).isVisible()));+ check(`${w.name}: …and 8189 is no second sentence, only under Other ports`, (await card.getByText(/Something answers on port 8189/).count()) === 0 && (await card.getByRole("button", { name: "Other ports (1)" }).isVisible()));+ await shot(page, card, `${w.name}-1-comfy-on-8188.png`);++ // Quiet looks: only the port shown, and at most one full look per 10 s there.+ const from = Date.now();+ await sleep(8_000);+ const quiet = ctx.loopback.filter((r) => r.at >= from);+ check(`${w.name}: quiet looks reach only 8188`, quiet.length > 0 && quiet.every((r) => r.port === 8188), JSON.stringify(quiet.map((r) => r.port)));+ check(`${w.name}: …and read it in full at most once in 8 s (pings in between)`, quiet.filter((r) => r.cors).length <= 1, `${quiet.filter((r) => r.cors).length} full of ${quiet.length}`);++ // "Use port 8189": it looks at once, and the screen changes to that port.+ await card.getByRole("button", { name: "Other ports (1)" }).click();+ await shot(page, card, `${w.name}-2-other-ports-open.png`);+ const t0 = Date.now();+ await card.getByRole("button", { name: "Use port 8189" }).click();+ const moved = await until(() => card.getByText("Something answers on port 8189.").isVisible(), 10_000, 50);+ check(`${w.name}: "Use port 8189" switches the card to 8189 at once`, !!moved, `${Date.now() - t0} ms`);+ check(`${w.name}: …which looked at 8189 when clicked`, ctx.loopback.some((r) => r.port === 8189 && r.at >= t0));+ check(`${w.name}: …saying Fuobe can't read that port yet (not that it is ComfyUI)`, await card.getByText(/Fuobe can't read this port yet. If it's ComfyUI, one step lets Fuobe in/).isVisible());+ check(`${w.name}: …and offers 8188 under Other ports`, await card.getByRole("button", { name: "Other ports (1)" }).isVisible());+ await shot(page, card, `${w.name}-3-chose-8189.png`);+ // Stays there: the quiet looks follow the port picked.+ await sleep(4_500);+ check(`${w.name}: …and stays on the port picked`, await card.getByText("Something answers on port 8189.").isVisible());++ // "Use port 8188": back, at once.+ await card.getByRole("button", { name: "Other ports (1)" }).click();+ const t1 = Date.now();+ await card.getByRole("button", { name: "Use port 8188" }).click();+ const back = await until(() => primary.isVisible(), 10_000, 50);+ check(`${w.name}: "Use port 8188" switches the card back to 8188 at once`, !!back, `${Date.now() - t1} ms`);+ await shot(page, card, `${w.name}-4-chose-8188.png`);++ // "Use port 8189", then "Check again" before that look ends: no "Checking port 8189…" left spinning.+ ctx.delay = { 8189: 1200 };+ await card.getByRole("button", { name: "Other ports (1)" }).click();+ await card.getByRole("button", { name: "Use port 8189" }).click();+ await card.getByText("Checking port 8189…").waitFor({ timeout: 5_000 });+ await card.getByRole("button", { name: "Check again" }).click();+ await until(() => primary.isVisible(), 15_000, 50);+ await sleep(4_000);+ ctx.delay = {};+ const spinning = await card.getByText(/Checking port/).count();+ await card.getByRole("button", { name: "Other ports (1)" }).click();+ check(`${w.name}: Use port, then Check again at once: no "Checking port…" left, and the port can be picked again`, spinning === 0 && (await card.getByRole("button", { name: "Use port 8189" }).isEnabled()), `${spinning} spinning`);+ await card.getByRole("button", { name: "Other ports (1)" }).click();++ // A port picked where nothing answers any more: the card says so.+ ctx.map = { 8188: COMFY_CLOSED };+ await card.getByRole("button", { name: "Other ports (1)" }).click();+ await card.getByRole("button", { name: "Use port 8189" }).click();+ check(`${w.name}: a port picked where nothing answers now: the card says so`, !!(await until(() => card.getByText("Nothing answers on port 8189 right now.", { exact: false }).isVisible(), 10_000)));+ check(`${w.name}: …and no longer offers it`, (await card.getByRole("button", { name: "Use port 8189" }).count()) === 0 && (await primary.isVisible()));+ await shot(page, card, `${w.name}-5-picked-port-gone.png`);++ // ComfyUI lets this page in (Fuobe Connect, no restart seen): connects by itself.+ ctx.map = { 8188: COMFY_OPEN };+ const connected = await until(() => card.getByText("Your GPU is connected").isVisible(), 20_000);+ check(`${w.name}: once ComfyUI lets this page in, it connects by itself`, !!connected);+ await shot(page, card, `${w.name}-6-connected.png`);+ }++ // 2. ComfyUI on 8188 that lets this page in: connects, and never looks at another port.+ {+ const { ctx, page, card } = await account(w, { 8188: COMFY_OPEN, 8189: OTHER_APP });+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();+ const ok = await until(() => card.getByText("Your GPU is connected").isVisible(), 20_000);+ check(`${w.name}: a readable ComfyUI on 8188 connects`, !!ok);+ check(`${w.name}: …without looking at any other port`, ctx.loopback.every((r) => r.port === 8188), [...new Set(ctx.loopback.map((r) => r.port))].join(","));+ await shot(page, card, `${w.name}-7-found-8188.png`);+ }++ // 3. Only the 401 on 8189: a weak candidate.+ {+ const { page, card, ctx } = await account(w, { 8189: OTHER_APP });+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();+ const weak = await until(() => card.getByText("No ComfyUI found on port 8188, its usual port.").isVisible(), 20_000);+ check(`${w.name}: only a 401 on 8189 is a weak candidate, not "found"`, !!weak && (await card.getByText(/Something answers on port 8189, but Fuobe can't tell if it's ComfyUI/).isVisible()));+ check(`${w.name}: …with one action, Check again`, (await card.getByRole("button", { name: "Check again" }).count()) === 1 && (await card.getByText(/Install Fuobe Connect/).count()) === 0);+ await shot(page, card, `${w.name}-8-weak-8189.png`);+ const t = Date.now();+ await card.getByRole("button", { name: "Port 8189 is my ComfyUI" }).click();+ check(`${w.name}: "Port 8189 is my ComfyUI" shows the one step for it`, !!(await until(() => card.getByText("Something answers on port 8189.").isVisible(), 10_000)) && (await card.getByText(/Install Fuobe Connect/).isVisible()));+ check(`${w.name}: …after looking at 8189 again`, ctx.loopback.some((r) => r.port === 8189 && r.at >= t));+ await shot(page, card, `${w.name}-9-weak-chosen.png`);+ }++ // 3b. Only the 401 on 8189, then ComfyUI starts on 8188: 8188 takes over with no click.+ {+ const { ctx, card } = await account(w, { 8189: OTHER_APP });+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();+ await until(() => card.getByText("No ComfyUI found on port 8188, its usual port.").isVisible(), 20_000);+ ctx.map = { 8188: COMFY_CLOSED, 8189: OTHER_APP };+ const took = await until(() => card.getByText("Something is running on port 8188, ComfyUI's usual port.").isVisible(), 15_000);+ check(`${w.name}: a weak 8189 gives way by itself once 8188 answers`, !!took && (await card.getByRole("button", { name: "Other ports (1)" }).isVisible()));+ }++ // 3c. Something on 8000, ComfyUI Desktop's port: a candidate with the one step, not "something else".+ {+ const { page, card } = await account(w, { 8000: COMFY_CLOSED });+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();+ const desk = await until(() => card.getByText("Something is running on port 8000, ComfyUI Desktop's usual port.").isVisible(), 20_000);+ check(`${w.name}: something on 8000 is ComfyUI Desktop's usual port, with the one step`, !!desk && (await card.getByText(/Install Fuobe Connect/).isVisible()) && (await card.getByText(/No ComfyUI found/).count()) === 0);+ check(`${w.name}: …and the one-line setting is offered next to it`, await card.getByText("Or start ComfyUI with one setting instead.").isVisible());+ await shot(page, card, `${w.name}-9b-desktop-8000.png`);+ }++ // 3d. Another app the page can read on 8000 (not ComfyUI), and ComfyUI on a port typed by the person.+ {+ const { page, card } = await account(w, { 8000: READABLE_APP, 9188: COMFY_CLOSED });+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();+ const none = await until(() => card.getByText("No ComfyUI found on this computer.").isVisible(), 20_000);+ check(`${w.name}: another app's readable answer is never offered as ComfyUI`, !!none && (await card.getByText(/port 8000/).count()) === 0 && (await card.getByRole("button", { name: /Other ports/ }).count()) === 0);+ const typeAndLook = async (port) => {+ const field = card.getByLabel("ComfyUI's port");+ await field.waitFor({ timeout: 15_000 });+ await field.fill(String(port));+ await card.getByRole("button", { name: "Look" }).click();+ };+ await typeAndLook(8000);+ check(`${w.name}: typing that app's port says it isn't ComfyUI`, !!(await until(() => card.getByText("Another app answers on port 8000, not ComfyUI.").isVisible(), 10_000)));+ await shot(page, card, `${w.name}-9c-typed-other-app.png`);+ await typeAndLook(9188);+ const typed = await until(() => card.getByText("Something answers on port 9188.").isVisible(), 10_000);+ check(`${w.name}: a typed port that answers is taken as the person's ComfyUI, with the one step`, !!typed && (await card.getByText(/Install Fuobe Connect/).isVisible()) && (await card.getByText(/can't tell if it's ComfyUI/).count()) === 0);+ await shot(page, card, `${w.name}-9d-typed-port.png`);+ }++ // 3e. ComfyUI on 8188 closes (restarting): waiting, and the quiet looks reach only 8188, with pings.+ {+ const { ctx, page, card } = await account(w, { 8188: COMFY_CLOSED, 8189: OTHER_APP });+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();+ await until(() => card.getByText("Something is running on port 8188, ComfyUI's usual port.").isVisible(), 20_000);+ ctx.map = { 8189: OTHER_APP };+ const waiting = await until(() => card.getByText("Waiting for ComfyUI to start…").isVisible(), 15_000);+ check(`${w.name}: ComfyUI closing on 8188 shows "Waiting for ComfyUI to start"`, !!waiting);+ const from = Date.now();+ await sleep(8_000);+ const quiet = ctx.loopback.filter((r) => r.at >= from);+ check(`${w.name}: …while waiting, quiet looks reach only 8188, and only with a ping`, quiet.length > 0 && quiet.every((r) => r.port === 8188 && !r.cors), JSON.stringify(quiet.map((r) => `${r.port}${r.cors ? "+read" : ""}`)));+ await shot(page, card, `${w.name}-9e-waiting.png`);+ ctx.map = { 8188: COMFY_OPEN, 8189: OTHER_APP };+ check(`${w.name}: …and ComfyUI back with Fuobe let in connects by itself`, !!(await until(() => card.getByText("Your GPU is connected").isVisible(), 20_000)));+ }++ // 4. Nothing answers: not found; Check again looks again.+ {+ const { ctx, page, card } = await account(w, {});+ await card.getByRole("button", { name: "Find my ComfyUI" }).click();+ const none = await until(() => card.getByText("No ComfyUI found on this computer.").isVisible(), 20_000);+ check(`${w.name}: nothing answers: "No ComfyUI found", start it, then check again`, !!none && (await card.getByText("Start ComfyUI, then check again.").isVisible()));+ await shot(page, card, `${w.name}-10-none.png`);+ const from = Date.now();+ await sleep(7_000);+ const quiet = ctx.loopback.filter((r) => r.at >= from);+ check(`${w.name}: …quiet looks then reach only 8188, one ping each`, quiet.length > 0 && quiet.every((r) => r.port === 8188 && !r.cors), JSON.stringify(quiet.map((r) => `${r.port}${r.cors ? "+read" : ""}`)));+ const t = Date.now();+ await card.getByRole("button", { name: "Check again" }).click();+ check(`${w.name}: Check again looks at every port again`, !!(await until(() => new Set(ctx.loopback.filter((r) => r.at >= t).map((r) => r.port)).size >= 7, 10_000)));+ // ComfyUI starts on 8188: found by the quiet look.+ ctx.map = { 8188: COMFY_OPEN };+ check(`${w.name}: ComfyUI started on 8188 is found by itself`, !!(await until(() => card.getByText("Your GPU is connected").isVisible(), 20_000)));+ }+ }+} catch (e) {+ console.error(e);+ check("the run finished", false, String(e?.message ?? e));+} finally {+ await browser?.close().catch(() => {});+ await finish();+}diff --git a/tests/e2e/computer-mode.mjs b/tests/e2e/computer-mode.mjsindex b55a439d..e5104443 100644--- a/tests/e2e/computer-mode.mjs+++ b/tests/e2e/computer-mode.mjs@@ -157,7 +157,7 @@ try {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/ });+ const linkToggle = dialog.getByRole("button", { name: /Keep it running with this tab closed/ });await linkToggle.click();const field = await until(() => dialog.locator("input").first().boundingBox(), 10_000);const box = await dialog.boundingBox();@@ -165,7 +165,7 @@ try {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("Found ComfyUI. One step to use it here:").waitFor({ timeout: 20_000 });+ await dialog.getByText(`Something is running on port ${FAKE_PORT}, where your ComfyUI was before.`).waitFor({ timeout: 20_000 });check("ComfyUI that this page can't use yet: one step, Fuobe Connect from ComfyUI-Manager", await dialog.getByText("Install Fuobe Connect in ComfyUI-Manager").isVisible());check("the step names the Manager's search term and a git address to copy", (await dialog.getByLabel("the search term").first().textContent()) === "Fuobe Connect" && /git clone https:\/\//.test((await dialog.getByLabel("the git command", { exact: true }).textContent()) ?? ""));check("the start setting and the guard are not shown until Advanced is opened", !(await dialog.getByRole("button", { name: "Download start file" }).isVisible()) && !(await dialog.getByText("--enable-cors-header").first().isVisible()));