Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Set it up with my AI: the AI buttons work at once, plain words, and a web address keeps its protection

Adarshcd9384206bab
diff --git a/docs/public-signup.md b/docs/public-signup.md
index ececb649..abefe43f 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -494,7 +494,8 @@ step as the account's open tab sees it. It ends with a first picture made on the
- **The tab.** The account's open tab reports what it sees
(`POST /api/setup/session/<code>/report`, fixed values and whole numbers only, unknown keys answer
400) and waits for its AI's reads (`GET /api/setup/session/<code>/wait`, 25 seconds at most). One
- tab leads a setup at a time. Another account's code answers 404.
+ tab leads a setup at a time: the tab opened last, or a tab in view once the leading one closes, hides
+ or goes quiet. Another account's code answers 404.
- **The status.** Anyone with the code can read `GET /api/setup/<code>` without signing in: the
steps, the port and the kind of install, and the next step, in fixed words (plain text, or JSON
with `?format=json`). It never holds the email, a run, a key, an address, a token, a file name or
@@ -505,10 +506,15 @@ step as the account's open tab sees it. It ends with a first picture made on the
network), `GET /api/setup/files/fuobe_guard.py` and `GET /api/setup/files/start/<port>` (the
Windows start file) are open to everyone. The steps tell the AI to show each command and wait for
a yes, to use exactly `--enable-cors-header <the studio's address>`, never `--listen`, and to
- check Fuobe's files by their SHA-256.
+ check Fuobe's files by their SHA-256. For a web address, they run the tunnel in a window the
+ person sees, keep its log where only that user can read it, warn when ComfyUI-Manager is
+ installed (anyone with the address can use it), and stop the tunnel when the person is done. When
+ the address asks for a password or a token, they keep it and put it in Fuobe's Access token.
- **Limits.** 6 new codes a minute and 20 an hour per account. 30 status reads a minute per code.
Unknown codes: 10 per 10 minutes per visitor (behind a trusted proxy, `FUOBE_TRUST_PROXY=1`) and
- 600 per 10 minutes for everyone together. All answer 429 with `Retry-After`.
+ 600 per 10 minutes for everyone together. The steps and Fuobe's files: 60 a minute per visitor
+ (behind a trusted proxy), and no budget shared by everyone, so no visitor can use up another
+ person's. All answer 429 with `Retry-After`.
The code is `src/server/ai-setup.ts`, `src/lib/ai-setup/`, `src/components/gpu/ai-setup/` and
`src/app/api/setup/`.
diff --git a/src/app/api/setup/files/fuobe_guard.py/route.ts b/src/app/api/setup/files/fuobe_guard.py/route.ts
index 74ad377f..833c23ff 100644
--- a/src/app/api/setup/files/fuobe_guard.py/route.ts
+++ b/src/app/api/setup/files/fuobe_guard.py/route.ts
@@ -1,7 +1,7 @@
import { connection } from "next/server";
import { GUARD_FILE_NAME, GUARD_SOURCE } from "@/lib/comfy-guard";
import { inMinutes } from "@/server/ai-setup-http";
-import { visitorBudget } from "@/server/ai-setup-http";
+import { ownBudget } from "@/server/ai-setup-http";
/**
* Fuobe's guard for ComfyUI (src/lib/comfy-guard.ts), as a download for the person's AI: the guide checks it against
@@ -9,7 +9,7 @@ import { visitorBudget } from "@/server/ai-setup-http";
*/
export async function GET(request: Request) {
await connection();
- const r = visitorBudget("setup:file", request.headers, 60, 600, 60_000);
+ const r = ownBudget("setup:file", request.headers, 60, 60_000);
if (!r.ok) return new Response(`Too many downloads. Try again in ${inMinutes(r.retryAfterS)}.\n`, { status: 429, headers: { "Retry-After": String(r.retryAfterS), "Cache-Control": "no-store" } });
return new Response(GUARD_SOURCE, {
headers: {
diff --git a/src/app/api/setup/files/start/[port]/route.ts b/src/app/api/setup/files/start/[port]/route.ts
index 89ed8dc9..a06374ca 100644
--- a/src/app/api/setup/files/start/[port]/route.ts
+++ b/src/app/api/setup/files/start/[port]/route.ts
@@ -3,7 +3,7 @@ import { SETUP_BAT } from "@/lib/ai-setup/guide";
import { startFile } from "@/lib/comfy-install";
import { siteOf } from "@/server/ai-setup";
import { inMinutes, SETUP_HEADERS } from "@/server/ai-setup-http";
-import { visitorBudget } from "@/server/ai-setup-http";
+import { ownBudget } from "@/server/ai-setup-http";
/**
* Fuobe's Windows start file for the ComfyUI on a port (src/lib/comfy-install.ts startFile, the same file the setup card
@@ -16,7 +16,7 @@ export async function GET(request: Request, ctx: RouteContext<"/api/setup/files/
const port = /^\d{1,5}$/.test(raw) ? Number(raw) : NaN;
const site = siteOf(request.headers, request.url);
if (!Number.isInteger(port) || port < 1 || port > 65535 || !site) return new Response("Not found.\n", { status: 404, headers: { ...SETUP_HEADERS, "Content-Type": "text/plain; charset=utf-8" } });
- const r = visitorBudget("setup:file", request.headers, 60, 600, 60_000);
+ const r = ownBudget("setup:file", request.headers, 60, 60_000);
if (!r.ok) return new Response(`Too many downloads. Try again in ${inMinutes(r.retryAfterS)}.\n`, { status: 429, headers: { ...SETUP_HEADERS, "Retry-After": String(r.retryAfterS) } });
return new Response(startFile(port, site), {
headers: {
diff --git a/src/app/api/setup/guide/[way]/[os]/route.ts b/src/app/api/setup/guide/[way]/[os]/route.ts
index 67d75689..c1d83ac0 100644
--- a/src/app/api/setup/guide/[way]/[os]/route.ts
+++ b/src/app/api/setup/guide/[way]/[os]/route.ts
@@ -5,7 +5,7 @@ import { FUOBE_CONNECT_PUBLISHED } from "@/lib/fuobe-connect";
import { siteOf } from "@/server/ai-setup";
import { guideModels } from "@/server/ai-setup-guide";
import { inMinutes, SETUP_HEADERS } from "@/server/ai-setup-http";
-import { visitorBudget } from "@/server/ai-setup-http";
+import { ownBudget } from "@/server/ai-setup-http";
/**
* The steps for the person's AI, for one way and one computer (docs/public-signup.md "Set it up with my AI"): plain
@@ -20,7 +20,7 @@ export async function GET(request: Request, ctx: RouteContext<"/api/setup/guide/
if (!isWay(way) || !isOs(os) || (way === "connect" && !FUOBE_CONNECT_PUBLISHED)) return NOT_HERE();
const site = siteOf(request.headers, request.url);
if (!site) return NOT_HERE();
- const r = visitorBudget("setup:guide", request.headers, 60, 600, 60_000);
+ const r = ownBudget("setup:guide", request.headers, 60, 60_000);
if (!r.ok)
return new Response(`Too many reads. Try again in ${inMinutes(r.retryAfterS)}.\n`, {
status: 429,
diff --git a/src/components/gpu/ai-setup/ai-setup-panel.tsx b/src/components/gpu/ai-setup/ai-setup-panel.tsx
index 0171ccba..f3019e65 100644
--- a/src/components/gpu/ai-setup/ai-setup-panel.tsx
+++ b/src/components/gpu/ai-setup/ai-setup-panel.tsx
@@ -2,6 +2,7 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { BotMessageSquare, Check, ChevronDown, ChevronLeft, ClipboardPaste, Copy, Ellipsis, Loader2, RefreshCw, Search, Send, Terminal } from "lucide-react";
+import Link from "next/link";
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { isLocalAddress } from "@/components/gpu/comfy-finder";
@@ -18,6 +19,7 @@ import { addressCauseOf, type AddressCause, type TabFacts } from "@/lib/ai-setup
import { FIRST_MODEL_NAME, firstModelOf, type FirstModel } from "@/lib/ai-setup/first-picture";
import { agentLine, AGENTS, AI_TARGETS, chatLink, fullInstructions, isAgent, prefillText, type Agent, type AiTarget } from "@/lib/ai-setup/handoff";
import { nextOf } from "@/lib/ai-setup/next-step";
+import { personWords } from "@/lib/ai-setup/person-words";
import { isConnected, isDone, stepsOf } from "@/lib/ai-setup/steps";
import { BROWSER_LABEL, browserOf, OS_NAME, pickWay, WAY_LABEL, waysFor, type Os, type Way } from "@/lib/ai-setup/ways";
import { useStatus } from "@/lib/api";
@@ -56,6 +58,8 @@ type GpuView = { gpu: { mode: "computer" } | { mode?: "link"; url: string } | nu
const AGENT_KEY = "fuobe.ai-setup.agent";
const STUCK_MS = 240_000;
const GUARD_WAIT_MS = 60_000;
+/** ComfyUI stopped answering this recently: it is restarting (or was closed), not missing. */
+const GONE_MS = 90_000;
function readAgent(): Agent {
try {
@@ -149,9 +153,28 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
const model = firstModelOf(badges ? { ...badges, vramGb: badges.vramGb ?? probe.vramGb } : undefined);
const picture = useFirstPicture();
+ const now = useNow(5000);
const browserState: TabFacts["browser"] =
way !== "direct" ? "unknown" : support !== "ok" ? "unsupported" : probe.state.s === "blocked" ? "blocked" : probe.perm === "granted" ? "granted" : probe.state.s === "start" ? "ask" : "unknown";
- const comfy = probe.state.s === "found" ? "found" : probe.state.s === "needs-setting" ? "unreadable" : probe.state.s === "waiting" ? "waiting" : probe.state.s === "none" ? "none" : undefined;
+ // Where ComfyUI last answered, and when it stopped: a ComfyUI that went quiet a moment ago is restarting (Fuobe's
+ // start file, the AI), so the setup says so and doesn't ask to install it.
+ const s0 = probe.state;
+ const answering = s0.s === "found" || s0.s === "needs-setting" || s0.s === "waiting" ? s0.port : s0.s === "looking" ? undefined : null;
+ const [lastComfy, setLastComfy] = useState<{ port: number | null; gone: { port: number; at: number } | null }>({ port: null, gone: null });
+ if (answering !== undefined && answering !== lastComfy.port)
+ setLastComfy({ port: answering, gone: answering === null ? (lastComfy.port !== null ? { port: lastComfy.port, at: now } : lastComfy.gone) : null });
+ const goneAt = s0.s === "none" && lastComfy.gone && now - lastComfy.gone.at < GONE_MS ? lastComfy.gone.port : null;
+ const comfy = goneAt
+ ? "waiting"
+ : probe.state.s === "found"
+ ? "found"
+ : probe.state.s === "needs-setting"
+ ? "unreadable"
+ : probe.state.s === "waiting"
+ ? "waiting"
+ : probe.state.s === "none"
+ ? "none"
+ : undefined;
const [visible, setVisible] = useState(true);
useEffect(() => {
const on = () => setVisible(document.visibilityState === "visible");
@@ -167,7 +190,7 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
browserName: browser,
...(way !== "address" && {
...(comfy && { comfy }),
- ...(probe.port && { port: probe.port }),
+ ...((goneAt ?? probe.port) && { port: goneAt ?? probe.port }),
...(probe.install && { install: probe.install }),
...(probe.cors && { cors: probe.cors }),
...(found && { listen: probe.listen }),
@@ -176,9 +199,11 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
...(skipGuard && { guardSkipped: true }),
...((connectedHere || (saved === "computer" && online && found)) && { connected: true }),
...(probe.cpu && { cpu: true }),
+ ...(probe.cpu && probe.cpuFlag && { cpuFlag: true }),
}),
...(way === "address" && { address: address.state === "none" && saved === "link" ? "ok" : address.state, ...(address.cause && { addressCause: address.cause }) }),
model: model.state === "checking" ? "checking" : model.state,
+ ...(model.state === "none" && { modelWhy: model.why }),
...(model.state !== "checking" && model.state !== "none" && { modelId: model.model }),
...(model.state === "download" && { modelGbTenths: model.gbTenths }),
picture: picture.state,
@@ -187,23 +212,38 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
...(fromRun && { fromRun: true }),
};
const server = { gpu: saved, online: saved === "none" ? false : status.data ? online : null } as const;
- const now = useNow(5000);
const viewNow = { site: typeof window === "undefined" ? "" : window.location.origin, way, os: os ?? "other", phone, tab: { ...facts, tabId: "this-tab-0" }, tabAt: now, server };
const steps = stepsOf(viewNow);
const connected = isConnected(viewNow);
const done = isDone(viewNow);
- const session = useSetupSession({ way, os: os ?? "other", phone, facts, onPoke: probe.poke });
+ // The AI read the status: a fresh look, and while a model is missing, a fresh check of what ComfyUI has.
+ const afterPoke = useRef<() => void>(() => {});
+ const session = useSetupSession({
+ way,
+ os: os ?? "other",
+ phone,
+ facts,
+ onPoke: () => {
+ probe.poke();
+ afterPoke.current();
+ },
+ });
const site = session.site ?? (typeof window === "undefined" ? "" : window.location.origin);
- // Connected: what this ComfyUI has (once), and again every 45 s while it needs a model download.
+ // Connected: what this ComfyUI has (once), and again every 45 s while it needs a model download or none fits (its AI
+ // may download one, update ComfyUI, or move it onto the graphics card).
const checkedFor = useRef<string | null>(null);
// Only stable values here: a new recheck on every render would start the 45 s timer over each time.
const startCheck = check.start;
+ const refreshProbe = probe.refresh;
const recheck = useCallback(async () => {
if (way === "address") await startCheck();
- else if (probe.port && probe.host) await checkHere(qc, probe.port, probe.host).catch(() => {});
- }, [way, startCheck, probe.port, probe.host, qc]);
+ else if (probe.port && probe.host) {
+ await refreshProbe().catch(() => false);
+ await checkHere(qc, probe.port, probe.host).catch(() => {});
+ }
+ }, [way, startCheck, refreshProbe, probe.port, probe.host, qc]);
useEffect(() => {
if (!connected) return;
const key = `${way}:${saved}`;
@@ -212,10 +252,18 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
const t = setTimeout(() => void recheck(), 2500);
return () => clearTimeout(t);
}
- if (model.state !== "download") return;
+ if (model.state !== "download" && model.state !== "none") return;
const id = setInterval(() => document.visibilityState === "visible" && void recheck(), 45_000);
return () => clearInterval(id);
}, [connected, model.state, way, saved, recheck, check.running]);
+ const pokeCheckAt = useRef(0);
+ useEffect(() => {
+ afterPoke.current = () => {
+ if (!connected || (model.state !== "download" && model.state !== "none") || check.running || Date.now() - pokeCheckAt.current < 15_000) return;
+ pokeCheckAt.current = Date.now();
+ void recheck();
+ };
+ });
// Opened by a refused run: once connected, that run starts (it is the first picture).
useEffect(() => {
@@ -247,8 +295,6 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
if (guardWait.on !== waitsForGuard) setGuardWait({ on: waitsForGuard, at: now });
const allowedAt = guardWait.on ? guardWait.at : null;
- // The browser's one question comes first (Chrome closes it when its tab loses focus): the hand-offs wait for it.
- const handoffsLocked = way === "direct" && support === "ok" && probe.state.s === "start" && !(saved === "computer" && online);
const finished = picture.state === "ok";
const gpuName = probe.stats?.devices?.[0]?.name ? deviceLabel(probe.stats.devices[0].name) : viewerGpu?.device ? deviceLabel(viewerGpu.device) : undefined;
@@ -259,12 +305,19 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
if (s === "start")
extras.comfyui = (
<>
+ <p className="text-[12px] text-muted-foreground">Is ComfyUI running? Let Fuobe look for it. If you don&apos;t have ComfyUI yet, your AI installs it first.</p>
<Button className="h-11 sm:h-9" onClick={() => void probe.look()}>
<Search /> Let Fuobe look
</Button>
{probe.perm !== "granted" && <AllowNote />}
</>
);
+ else if (goneAt)
+ extras.comfyui = (
+ <p className="flex items-center gap-2 text-[12px] text-muted-foreground">
+ <Loader2 className="size-3.5 animate-spin" /> ComfyUI stopped answering on port {goneAt}. Waiting for it to start again…
+ </p>
+ );
else if (s === "looking") extras.comfyui = <p className="flex items-center gap-2 text-[12px] text-muted-foreground"><Loader2 className="size-3.5 animate-spin" /> Looking for ComfyUI on this computer…</p>;
else if (s === "blocked")
extras.comfyui = (
@@ -305,17 +358,32 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
if (auto.error) extras.guard = <p className="text-[12px] text-destructive">{auto.error}</p>;
}
if (way === "address" && !(saved === "link" && online && address.state !== "failed"))
- extras.address = <AddressForm saved={saved === "link"} state={address} onState={setAddress} onConnected={() => void check.start()} />;
+ extras.address = <AddressForm saved={saved === "link"} state={address} onState={setAddress} onConnected={() => void check.start()} phone={phone} site={site} />;
if (connected && !fromRun) {
if (model.state === "download") extras.model = <ModelDownload model={model.model} gbTenths={model.gbTenths} os={os ?? "other"} onCheck={() => void recheck()} checking={check.running} />;
else if (model.state === "none")
extras.model = (
- <p className="text-[12px] text-muted-foreground">
- None of the small picture models fits this GPU.{" "}
- <a href="/connect" className="text-brand-text underline-offset-4 hover:underline">
- See what runs on it
- </a>
- </p>
+ <div className="space-y-1.5">
+ <p className="text-[12px] text-muted-foreground">
+ {probe.cpu
+ ? "ComfyUI runs on your computer's processor, not on its graphics card, so no picture model fits. Your AI can make ComfyUI use the graphics card."
+ : model.why === "setup"
+ ? "These picture models need more than a download on your ComfyUI, most often an update. Your AI can update it."
+ : "Your GPU has too little memory for the small picture models (the smallest needs 8 GB)."}
+ {model.why === "small" && (
+ <>
+ {" "}
+ Or use your own fal.ai or Replicate key.{" "}
+ <Link href="/settings#your-keys" className="text-brand-text underline-offset-4 hover:underline">
+ Your keys
+ </Link>
+ </>
+ )}
+ </p>
+ <Button size="sm" variant="ghost" onClick={() => void recheck()} disabled={check.running}>
+ {check.running ? <Loader2 className="animate-spin" /> : <RefreshCw />} Check again
+ </Button>
+ </div>
);
if (model.state === "ready" && picture.state !== "running" && picture.state !== "ok")
extras.picture = (
@@ -337,7 +405,9 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
if (fromRun && connected) extras.picture = <p className="text-[12px] text-muted-foreground">Your run starts in a moment.</p>;
const handoff = os && session.code ? { way, os, site, code: session.code, browser, phone } : null;
- const lead = phone ? "ComfyUI runs on your computer, so the steps run there." : "Your AI does the steps, after you say yes to each one. Fuobe checks every step here.";
+ const lead = phone
+ ? "ComfyUI is the free app that runs AI models on your computer's graphics card. It runs on your computer, so the steps run there."
+ : "ComfyUI is the free app that runs AI models on your own graphics card. Your AI sets it up with you and asks before each step. Fuobe checks each step here.";
return (
<div className="w-full min-w-0 space-y-4 sm:max-w-[36rem]">
@@ -349,6 +419,13 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
Set it up with your AI
</h2>
<p className="text-[13px] text-muted-foreground">{lead}</p>
+ <p className="text-[12px] text-muted-foreground">
+ You need an NVIDIA graphics card with 8 GB or more, or a Mac with Apple silicon and 16 GB. No such computer? Use your own fal.ai or Replicate key in{" "}
+ <Link href="/settings#your-keys" className="text-brand-text underline-offset-4 hover:underline">
+ Your keys
+ </Link>
+ .
+ </p>
</div>
{/* What Fuobe picked for this browser, and the way to change it. */}
@@ -400,19 +477,18 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
{!session.mine && (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-xl bg-muted px-3 py-2.5 text-[13px]">
- <span>This setup goes on in another tab or device.</span>
+ <span className="min-w-0 flex-1">This setup is open in another tab or on another device. Your AI sees the checks from there. To use this tab, press Continue here.</span>
<Button size="sm" variant="secondary" onClick={session.takeOver}>
Continue here
</Button>
</div>
)}
- {!finished && !handoffsLocked && (
+ {!finished && (
<HandOffs
input={handoff}
waiting={!session.code && !session.failed && !session.ended}
needOs={!os}
- locked={handoffsLocked}
phone={phone}
failed={session.failed}
onRetry={session.retry}
@@ -425,7 +501,7 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
/>
)}
- {/* The checklist, or the finish in its place (the box keeps its height). Before the browser's question, the hand-offs come after it. */}
+ {/* The checklist, or the finish in its place (the box keeps its height). */}
<section aria-label="Fuobe checks as your AI works" className="min-h-[18rem] rounded-2xl bg-brand-faint/50 p-4">
{finished ? (
<FinishCard picture={picture} gpu={gpuName} cpu={probe.cpu} onClose={onBack} />
@@ -451,23 +527,6 @@ export function AiSetupPanel({ onBack, fromRun, onStart, onNotNow }: AiSetupPane
</>
)}
</section>
- {!finished && handoffsLocked && (
- <HandOffs
- input={handoff}
- waiting={!session.code && !session.failed && !session.ended}
- needOs={!os}
- locked
- phone={phone}
- failed={session.failed}
- onRetry={session.retry}
- guideUrl={way && os ? `/api/setup/guide/${way}/${os}` : null}
- code={session.code}
- ended={session.ended}
- renewed={session.renewed}
- onEnd={() => void session.end()}
- onFresh={() => void session.fresh()}
- />
- )}
{fromRun && !connected && onNotNow && (
<div className="flex justify-end">
<Button variant="ghost" size="sm" onClick={onNotNow}>
@@ -507,15 +566,14 @@ function NoComfy({ onLook, missed, notComfy }: { onLook: (port: number, host: st
/**
* The hand-offs: Open in ChatGPT, Open in Claude (each also copies the message, in case the chat opens empty), Copy the
- * steps for any other AI, and one command for a coding agent on this computer. Locked until the browser's one question
- * is answered (this browser's way), so the AI's first look at the status already says whether ComfyUI runs. After a
- * hand-off the box folds to one line, and the checklist is the main view.
+ * steps for any other AI, and one command for a coding agent on this computer. Ready as soon as the code is: the AI's
+ * first status says what to do whether or not Fuobe has looked for ComfyUI yet. After a hand-off the box folds to one
+ * line (with the steps to copy, for a chat that can't open links), and the checklist is the main view.
*/
function HandOffs({
input,
waiting,
needOs,
- locked,
phone,
failed,
onRetry,
@@ -529,7 +587,6 @@ function HandOffs({
input: Parameters<typeof prefillText>[0] | null;
waiting: boolean;
needOs: boolean;
- locked: boolean;
phone: boolean;
failed: string | null;
onRetry: () => void;
@@ -565,15 +622,16 @@ function HandOffs({
line = input ? agentLine(agent, input) : "";
} catch {}
const full = input && guide.data ? fullInstructions(input, guide.data) : null;
- const ready = !!input && !locked && !ended;
+ const ready = !!input && !ended;
const openChat = (t: AiTarget) => {
// The message goes on the clipboard too: a chat that opens empty (a sign-in first, an app) takes it with a paste.
void copyText(text).then((ok) => ok && toast("Message copied too", { description: "If the chat opens empty, paste it.", duration: 4000 }));
setSent(AI_TARGETS[t].label);
};
- const copyFull = async () => {
- if (full && (await copyWithToast(full, "Steps copied"))) setSent("your AI");
+ /** Copy the steps (`keep`: from the folded box, which stays as it is). */
+ const copyFull = async (keep = false) => {
+ if (full && (await copyWithToast(full, "Steps copied")) && !keep) setSent("your AI");
};
if (failed && !code)
@@ -589,16 +647,23 @@ function HandOffs({
return (
<div className="space-y-3 rounded-2xl border bg-background p-4">
{sent && ready ? (
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px]">
- <span className="flex items-center gap-1.5 font-medium">
+ <div className="space-y-1.5 text-[13px]">
+ <p className="flex items-center gap-1.5 font-medium">
<Check className="size-4 text-brand-text" /> Sent to {sent}.
- </span>
- <Quiet onClick={() => setSent(null)}>Use another AI</Quiet>
+ </p>
+ {sent !== "your AI" && <p className="text-[12px] text-muted-foreground">If {sent} says it can&apos;t open links, copy the steps and paste them into the chat.</p>}
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1">
+ {sent !== "your AI" && (
+ <Quiet onClick={() => void copyFull(true)} className={cn(!full && "pointer-events-none opacity-50")}>
+ Copy the steps
+ </Quiet>
+ )}
+ <Quiet onClick={() => setSent(null)}>Use another AI</Quiet>
+ </div>
</div>
) : (
<>
<p className="text-[13px] font-medium">Give your AI the steps</p>
- {locked && <p className="text-[12px] text-muted-foreground">These open once Fuobe has looked for ComfyUI above, so your AI&apos;s first check already knows what runs.</p>}
{needOs && <p className="text-[12px] text-muted-foreground">Pick the computer that runs ComfyUI first.</p>}
<div className="grid gap-2 sm:grid-cols-2">
{(Object.keys(AI_TARGETS) as AiTarget[])
@@ -618,9 +683,7 @@ function HandOffs({
),
)}
</div>
- <p className="text-[12px] text-muted-foreground">
- Chat apps tell you what to paste. Apps on your computer do the steps after you say yes. Claude and ChatGPT may ask you to check the message first.
- </p>
+ <p className="text-[12px] text-muted-foreground">ChatGPT and Claude tell you each command to run. An AI app on your computer runs them for you, after you say yes.</p>
<div className="flex flex-wrap items-center gap-x-4 gap-y-1">
<Quiet onClick={() => void copyFull()} className={cn((!ready || !full) && "pointer-events-none opacity-50")}>
Copy the steps for another AI
@@ -633,7 +696,7 @@ function HandOffs({
</div>
{apps && !phone && (
<div className="space-y-2">
- <p className="text-[12px] text-muted-foreground">Paste this in a terminal. The app asks before each command.</p>
+ <p className="text-[12px] text-muted-foreground">Paste this in a terminal on this computer. The app asks before each command.</p>
<TabRow role="tablist" aria-label="Coding agent" fade={false} className="w-fit">
{(Object.keys(AGENTS) as Agent[]).map((a) => (
<button key={a} type="button" role="tab" aria-selected={a === agent} onClick={() => setAgent(a)} className={TAB_PILL} {...onAttr(a === agent)}>
@@ -642,7 +705,7 @@ function HandOffs({
))}
</TabRow>
{ready && line ? <CopyLine text={line} label="the command" /> : <div className="h-11 rounded-lg bg-muted" />}
- <p className="text-[12px] text-muted-foreground">Cursor or another app? Copy the steps works with any AI.</p>
+ <p className="text-[12px] text-muted-foreground">Don&apos;t have this app, or use Cursor? Copy the steps works with any AI.</p>
</div>
)}
</>
@@ -687,6 +750,7 @@ function CodeLine({ code, ended, renewed, onEnd, onFresh }: { code: string | nul
</DropdownMenuContent>
</DropdownMenu>
</div>
+ <p className="text-[12px] text-muted-foreground">Your AI reads Fuobe&apos;s checks with this code. It can only read them, and the code ends by itself.</p>
</div>
);
}
@@ -733,7 +797,7 @@ function Presence({
<div className="space-y-2 rounded-xl bg-background p-3">
<p>Tell your AI: Check Fuobe&apos;s status again.</p>
<p className="text-muted-foreground">
- What Fuobe sees now: <span className="text-foreground">{next.say}</span>
+ What Fuobe sees now: <span className="text-foreground">{personWords(next)}</span>
</p>
<div className="flex flex-wrap items-center gap-x-4 gap-y-1">
<Button size="sm" variant="secondary" onClick={() => void copyWithToast(forAi, "Copied for your AI")}>
@@ -748,29 +812,65 @@ function Presence({
);
}
-/** The web address form: paste the address cloudflared made, and Fuobe tests it (the same check as Your GPU). */
-function AddressForm({ saved, state, onState, onConnected }: { saved: boolean; state: { state: string; words?: string }; onState: (s: { state: "none" | "testing" | "ok" | "failed"; cause?: AddressCause; words?: string }) => void; onConnected: () => void }) {
+/** The address form's own words for each kind of problem (the check's words, for the rest). */
+const ADDRESS_WORDS: Partial<Record<AddressCause, string>> = {
+ local: "That address works only on your own network. Paste the one that ends in trycloudflare.com.",
+ "not-found": "Fuobe can't find this address. Make sure that you pasted all of it, and that the cloudflared window is still open. If it closed, your AI starts it again, and you get a new address.",
+ "no-answer": "Nothing answers at this address. Make sure that ComfyUI and the cloudflared window are both open. A new address can take a minute to work.",
+ "not-comfy": "This address doesn't lead to ComfyUI. Ask your AI to check the port in the cloudflared command.",
+ password: "This address asks for a password or a token. Type it under Access token, then press Connect.",
+};
+
+/** The web address form: paste the address cloudflared made (and its token, if it has one), and Fuobe tests it (the same check as Your GPU). */
+function AddressForm({
+ saved,
+ state,
+ onState,
+ onConnected,
+ phone,
+ site,
+}: {
+ saved: boolean;
+ state: { state: string; cause?: AddressCause; words?: string };
+ onState: (s: { state: "none" | "testing" | "ok" | "failed"; cause?: AddressCause; words?: string }) => void;
+ onConnected: () => void;
+ phone: boolean;
+ site: string;
+}) {
const qc = useQueryClient();
const id = useId();
const [url, setUrl] = useState("");
+ const [token, setToken] = useState("");
+ const [withToken, setWithToken] = useState(false);
const canPaste = typeof navigator !== "undefined" && !!navigator.clipboard?.readText;
const value = url.trim();
const local = !!value && isLocalAddress(/^[a-z]+:\/\//i.test(value) ? value : `http://${value}`);
+ const showToken = withToken || state.cause === "password" || !!token;
const connect = async () => {
if (!value || local) return;
onState({ state: "testing" });
- const res = await fetch("/api/account/gpu", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url: value }) }).catch(() => null);
+ const res = await fetch("/api/account/gpu", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ url: value, ...(token.trim() && { token: token.trim() }) }),
+ }).catch(() => null);
const j = res ? ((await res.json().catch(() => ({}))) as { error?: string; trouble?: { cause?: string; words?: string } }) : {};
if (res?.ok) {
onState({ state: "ok" });
setUrl("");
+ setToken("");
for (const k of [["account-gpu"], ["status"], ["viewer"]]) void qc.invalidateQueries({ queryKey: k });
onConnected();
return;
}
- // The check's own words under the box; the AI gets only the kind of problem.
- onState({ state: "failed", cause: res ? addressCauseOf(j.trouble?.cause) : "unknown", words: j.trouble?.words ?? j.error ?? "Fuobe can't reach its server right now. Try again." });
+ // Plain words under the box; the AI gets only the kind of problem.
+ const cause = res ? addressCauseOf(j.trouble?.cause) : "unknown";
+ onState({ state: "failed", cause, words: ADDRESS_WORDS[cause] ?? j.trouble?.words ?? j.error ?? "Fuobe can't reach its server right now. Try again." });
};
+ let host = site;
+ try {
+ host = new URL(site).host;
+ } catch {}
return (
<div className="space-y-1.5">
<Label htmlFor={`${id}-url`} className="text-[12px]">
@@ -805,13 +905,37 @@ function AddressForm({ saved, state, onState, onConnected }: { saved: boolean; s
{state.state === "testing" && <Loader2 className="animate-spin" />} Connect
</Button>
</div>
- {local && <p className="text-[12px] text-destructive">That address only works on your own computer or network. Paste the one that ends in trycloudflare.com.</p>}
+ {showToken ? (
+ <div className="space-y-1">
+ <Label htmlFor={`${id}-token`} className="text-[12px]">
+ Access token <span className="text-muted-foreground">(only if the address asks for one)</span>
+ </Label>
+ <Input
+ id={`${id}-token`}
+ type="password"
+ autoComplete="off"
+ value={token}
+ onChange={(e) => setToken(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && void connect()}
+ className="h-11 sm:h-9"
+ />
+ </div>
+ ) : null}
+ {local && <p className="text-[12px] text-destructive">{ADDRESS_WORDS.local}</p>}
{!local && state.state === "failed" && state.words && (
<p role="status" className="text-[12px] text-destructive">
{state.words}
</p>
)}
- <p className="text-[12px] text-muted-foreground">Keep the address to yourself. Paste it here, not in your AI&apos;s chat.</p>
+ <p className="text-[12px] text-muted-foreground">
+ Keep the address to yourself. Paste it here, not in your AI&apos;s chat.{" "}
+ {!showToken && <Quiet onClick={() => setWithToken(true)}>Has a password or token?</Quiet>}
+ </p>
+ {phone && (
+ <p className="text-[12px] text-muted-foreground">
+ The address goes on your computer&apos;s clipboard. Open {host}/connect on that computer, sign in, and paste it there. Or paste it here if your phone shares that clipboard.
+ </p>
+ )}
</div>
);
}
@@ -860,7 +984,9 @@ function PhoneSend({ site, os, onOs }: { site: string; os: Os | null; onOs: (os:
<Send /> {share ? "Send to my computer" : "Copy link for my computer"}
</Button>
<div className="space-y-1.5">
- <p className="text-[12px] text-muted-foreground">Or use an AI app now. Its chats show on your computer too. Which computer runs ComfyUI?</p>
+ <p className="text-[12px] text-muted-foreground">
+ Or start with an AI app on this phone. The commands run on your computer, and at the end you paste an address into Fuobe there, so sign in to Fuobe on that computer too. Which computer runs ComfyUI?
+ </p>
<TabRow role="tablist" aria-label="Computer" fade={false} className="w-fit">
{(["windows", "mac", "linux"] as Os[]).map((o) => (
<button key={o} type="button" role="tab" aria-selected={o === os} onClick={() => onOs(o)} className={TAB_PILL} {...onAttr(o === os)}>
diff --git a/src/components/gpu/ai-setup/use-setup-probe.ts b/src/components/gpu/ai-setup/use-setup-probe.ts
index 49d2ec4f..1b917931 100644
--- a/src/components/gpu/ai-setup/use-setup-probe.ts
+++ b/src/components/gpu/ai-setup/use-setup-probe.ts
@@ -1,7 +1,7 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
-import { listensWide } from "@/lib/ai-setup/facts";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { listensWide, startedOnCpu } from "@/lib/ai-setup/facts";
import { installFromStats, guessInstall, platformOf, type ComfyInstall } from "@/lib/comfy-install";
import { isGuard } from "@/lib/comfy-guard";
import { isConnectAnswer } from "@/lib/fuobe-connect";
@@ -42,33 +42,44 @@ export function useSetupProbe(active: boolean, watch: boolean) {
const key = found ? `${found.host}:${found.port}` : null;
const mine = read && read.key === key ? read : null;
const stats = mine?.stats ?? found?.stats;
+ const place = useRef<{ key: string; port: number; host: string } | null>(null);
+ useEffect(() => {
+ place.current = found && key ? { key, port: found.port, host: found.host } : null;
+ });
+
+ /** ComfyUI read again now, with its guard (a restart goes back to the finder). */
+ const readNow = useCallback(async (): Promise<boolean> => {
+ const at = place.current;
+ if (!at) return false;
+ const [l, guard] = await Promise.all([lookOn(at.port, at.host), guardOn(at.port, at.host)]);
+ if (place.current?.key !== at.key) return false;
+ if (l.state === "found") setRead({ key: at.key, stats: l.stats, guard });
+ else void look({ quiet: true });
+ return true;
+ }, [look]);
- // Found: its guard, and while the panel watches, ComfyUI again every few seconds (a restart goes back to the finder).
+ // Found: its guard, and while the panel watches, ComfyUI again every few seconds.
useEffect(() => {
- if (!found || !key) return;
- let alive = true;
- const once = async () => {
- const [l, guard] = await Promise.all([lookOn(found.port, found.host), guardOn(found.port, found.host)]);
- if (!alive) return;
- if (l.state === "found") setRead({ key, stats: l.stats, guard });
- else void look({ quiet: true });
- };
- void once();
- if (!watch) return () => void (alive = false);
- const id = setInterval(() => visible() && void once(), WATCH_MS);
- return () => {
- alive = false;
- clearInterval(id);
- };
- // The found state's own object changes on every look; its place is what counts.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [key, watch, look]);
+ if (!key) return;
+ void readNow();
+ if (!watch) return;
+ const id = setInterval(() => visible() && void readNow(), WATCH_MS);
+ return () => clearInterval(id);
+ }, [key, watch, readNow]);
const port = found?.port ?? (state.s === "needs-setting" || state.s === "waiting" ? state.port : undefined);
const facts = stats ? statsFacts(stats, typeof window === "undefined" ? "" : window.location.origin) : null;
const install: ComfyInstall | undefined = port ? (stats ? installFromStats(stats, port, platformOf(nav())) : ((stored("install") as ComfyInstall | null) ?? guessInstall(port, platformOf(nav())))) : undefined;
- /** A quiet look now (the AI asked for a fresh one). */
- const poke = useCallback(() => void look({ quiet: true }), [look]);
+ /**
+ * A quiet look now (the AI asked for a fresh one): at every port while nothing answers. Never before the person's
+ * own first look (the browser may still ask), nor while the browser blocks it.
+ */
+ const s = state.s;
+ const poke = useCallback(() => {
+ if (s === "start" || s === "looking" || s === "blocked" || s === "unsupported") return;
+ if (s === "found") void readNow();
+ else void look({ quiet: true, wide: true });
+ }, [look, readNow, s]);
return {
...finder,
port,
@@ -79,9 +90,12 @@ export function useSetupProbe(active: boolean, watch: boolean) {
guard: mine?.guard,
install,
cpu: !!stats?.devices?.length && stats.devices.every((d) => d.type === "cpu"),
+ cpuFlag: startedOnCpu(stats?.system?.argv),
vramGb: stats?.devices?.[0]?.vram_total ? Math.round(stats.devices[0].vram_total / 2 ** 30) : undefined,
restarted: state.s === "needs-setting" && state.back,
poke,
+ /** ComfyUI read again now (after its AI changed it): false when none is found here. */
+ refresh: readNow,
};
}
diff --git a/src/components/gpu/ai-setup/use-setup-session.ts b/src/components/gpu/ai-setup/use-setup-session.ts
index 66d07301..a321e574 100644
--- a/src/components/gpu/ai-setup/use-setup-session.ts
+++ b/src/components/gpu/ai-setup/use-setup-session.ts
@@ -80,7 +80,8 @@ export function useSetupSession(o: { way: Way; os: Os; phone: boolean; facts: Om
const facts = useRef(o.facts);
const onPoke = useRef(o.onPoke);
const failures = useRef(0);
- const claim = useRef(false);
+ // The tab the person opened last leads (its first report takes the setup over), unless it opened out of view.
+ const claim = useRef(typeof document === "undefined" || document.visibilityState === "visible");
useEffect(() => {
facts.current = o.facts;
onPoke.current = o.onPoke;
@@ -204,6 +205,25 @@ export function useSetupSession(o: { way: Way; os: Os; phone: boolean; facts: Om
return () => document.removeEventListener("visibilitychange", on);
}, [report]);
+ // Closed or left: one last report says this tab is out of view, so a tab still open (or the next one) leads at once.
+ useEffect(() => {
+ const bye = () => {
+ const c = code.current;
+ const f = facts.current;
+ if (!c || !f) return;
+ void fetch(`/api/setup/session/${c}/report`, {
+ method: "POST",
+ keepalive: true,
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ...f, visible: false, tabId: tabId.current }),
+ }).catch(() => null);
+ };
+ window.addEventListener("pagehide", bye);
+ return () => {
+ window.removeEventListener("pagehide", bye);
+ };
+ }, []);
+
/** End this code: the AI can't read it any more. */
const end = useCallback(async () => {
const c = code.current;
diff --git a/src/components/gpu/use-local-comfy.ts b/src/components/gpu/use-local-comfy.ts
index 7c53d5b9..81cbe344 100644
--- a/src/components/gpu/use-local-comfy.ts
+++ b/src/components/gpu/use-local-comfy.ts
@@ -12,9 +12,10 @@ import { useComputerSupport } from "./open-connect";
* 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
+ * back), every 3 s at that port and 8188 while ComfyUI restarts (every port every 30 s), and every 5 s at 8188, the
+ * remembered port and any port where ComfyUI answered in the last few minutes while nothing answers (every port every
+ * 30 s: a ComfyUI that restarted on a port Fuobe doesn't wait for, or one just installed, is found again). 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).
*/
@@ -30,6 +31,8 @@ const REREAD_MS = 10_000;
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;
+/** A port where ComfyUI answered this recently is looked at again with the usual ones while nothing answers. */
+const RECENT_MS = 5 * 60_000;
async function timed(url: string, init: RequestInit, ms: number): Promise<Response> {
const ctrl = new AbortController();
@@ -111,7 +114,7 @@ export function useLocalComfy(active: boolean, o: { auto?: boolean } = {}) {
/** 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 }>());
+ const seen = useRef(new Map<number, { state: PortLook["state"]; read: number; answered?: number }>());
/** When every port was last looked at (or the wait for a restarting ComfyUI began). */
const lastFull = useRef(0);
@@ -132,10 +135,11 @@ export function useLocalComfy(active: boolean, o: { auto?: boolean } = {}) {
/**
* 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.
+ * port from the others. `wide`: a quiet look at every port while nothing answers or ComfyUI restarts (something
+ * changed on this computer: the person's AI asked).
*/
const look = useCallback(
- async (o: { ports?: { port: number; host?: string }[]; quiet?: boolean; chosen?: number } = {}) => {
+ async (o: { ports?: { port: number; host?: string }[]; quiet?: boolean; chosen?: number; wide?: boolean } = {}) => {
if (support !== "ok" || (o.quiet && running.current)) return;
const g = o.quiet ? gen.current : ++gen.current;
running.current++;
@@ -146,16 +150,18 @@ export function useLocalComfy(active: boolean, o: { auto?: boolean } = {}) {
const remembered = rememberedComfy();
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).
+ // Quietly: the port shown (and ComfyUI's usual one while only a weak port is shown); 8188, the remembered port
+ // and the ports where ComfyUI answered lately while nothing answers; the port waited for and those while ComfyUI
+ // restarts. Every port now and then, or when asked (it may come back elsewhere, or be new).
+ const recent = [...seen.current].filter(([, v]) => v.answered && Date.now() - v.answered < RECENT_MS).map(([port]) => port);
+ const rescan = !!o.wide || Date.now() - lastFull.current >= RESCAN_MS;
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)])]
+ : was.s === "none" && !rescan
+ ? [...new Set([...firstPorts(remembered?.port), ...recent])]
+ : was.s === "waiting" && !rescan
+ ? [...new Set([was.port, ...firstPorts(remembered?.port), ...recent])]
: 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);
@@ -171,7 +177,8 @@ export function useLocalComfy(active: boolean, o: { auto?: boolean } = {}) {
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 });
+ const answered = l.state === "found" || l.state === "unreadable" ? now : last?.answered;
+ seen.current.set(l.port, { state: l.state, read: pinged ? last.read : now, ...(answered && { answered }) });
}
// The person asked for a newer look meanwhile: that one decides.
if (g !== gen.current) return;
diff --git a/src/lib/ai-setup/facts.ts b/src/lib/ai-setup/facts.ts
index 41c7bbe1..e289e3b5 100644
--- a/src/lib/ai-setup/facts.ts
+++ b/src/lib/ai-setup/facts.ts
@@ -41,10 +41,14 @@ export interface TabFacts {
connected?: boolean;
/** The GPU is the computer's processor (no graphics card ComfyUI uses). */
cpu?: boolean;
+ /** ComfyUI was started with --cpu (read from its command line, which the tab never sends). */
+ cpuFlag?: boolean;
address?: "none" | "testing" | "ok" | "failed";
addressCause?: AddressCause;
/** A picture model for the first picture. */
model?: "checking" | "ready" | "download" | "none";
+ /** No model fits: the GPU is too small for each, or one needs more than a download here. */
+ modelWhy?: "small" | "setup";
modelId?: FirstModel;
/** The download it needs, in tenths of a GB. */
modelGbTenths?: number;
@@ -72,9 +76,11 @@ export const TabFactsSchema = z.strictObject({
guardSkipped: z.boolean().optional(),
connected: z.boolean().optional(),
cpu: z.boolean().optional(),
+ cpuFlag: z.boolean().optional(),
address: z.enum(["none", "testing", "ok", "failed"]).optional(),
addressCause: z.enum(ADDRESS_CAUSES).optional(),
model: z.enum(["checking", "ready", "download", "none"]).optional(),
+ modelWhy: z.enum(["small", "setup"]).optional(),
modelId: z.enum(FIRST_PICTURE_MODELS).optional(),
modelGbTenths: z.number().int().min(0).max(10_000).optional(),
picture: z.enum(["none", "running", "ok", "failed", "no-model"]).optional(),
@@ -140,3 +146,6 @@ export function listensWide(argv: readonly string[] | undefined): boolean {
if (!value || value.startsWith("--")) return true;
return value.split(",").some((a) => !["127.0.0.1", "localhost", "::1"].includes(a.trim()));
}
+
+/** ComfyUI was started with --cpu: it never uses the graphics card, whatever the computer has. */
+export const startedOnCpu = (argv: readonly string[] | undefined): boolean => !!argv?.includes("--cpu");
diff --git a/src/lib/ai-setup/first-picture.ts b/src/lib/ai-setup/first-picture.ts
index 7723888b..c5afb5ac 100644
--- a/src/lib/ai-setup/first-picture.ts
+++ b/src/lib/ai-setup/first-picture.ts
@@ -52,8 +52,8 @@ export type FirstModelState =
| { state: "ready"; model: FirstModel }
/** One download makes it ready: `gbTenths` its size in tenths of a GB. */
| { state: "download"; model: FirstModel; gbTenths: number }
- /** None of them can run on this GPU. */
- | { state: "none" };
+ /** None of them can run here yet. `why`: the GPU is too small for each, or one needs more than a download (an update). */
+ | { state: "none"; why: "small" | "setup" };
export function firstModelOf(badges: { connected: boolean; models: Record<string, Badge>; vramGb?: number } | undefined): FirstModelState {
if (!badges?.connected || !Object.keys(badges.models).length) return { state: "checking" };
@@ -63,7 +63,7 @@ export function firstModelOf(badges: { connected: boolean; models: Record<string
const order = modelOrder(badges.vramGb);
const near = order.find((m) => badge(m)?.[0] === "a");
if (near) return { state: "download", model: near, gbTenths: badge(near)![2] };
- return { state: "none" };
+ return { state: "none", why: FIRST_PICTURE_MODELS.some((m) => badge(m)?.[0] === "s") ? "setup" : "small" };
}
/** The finish's frame: a portrait, when the model makes one. */
diff --git a/src/lib/ai-setup/guide.ts b/src/lib/ai-setup/guide.ts
index abb80345..4aadb4ac 100644
--- a/src/lib/ai-setup/guide.ts
+++ b/src/lib/ai-setup/guide.ts
@@ -91,7 +91,7 @@ function rules(i: GuideInput): string {
"2. This way needs no new ComfyUI setting. Do not add --enable-cors-header. Never use --listen.",
"3. Do not open ports in a firewall or a router. Do not turn off antivirus, the firewall, SmartScreen or Gatekeeper.",
"4. Do not run cloudflared login, and do not make a named tunnel. The quick tunnel below needs no account.",
- "5. The web address works like a key. Anyone who has it can use this ComfyUI while the tunnel runs. Do not print it, keep it or post it anywhere. It goes only into Fuobe.",
+ "5. The web address works like a key. Anyone who has it can use all of this ComfyUI while the tunnel runs, including the installs of ComfyUI-Manager if it is there. Do not print it, keep it or post it anywhere. It goes only into Fuobe. Run the tunnel in a window the person can see, and only while they use Fuobe: they stop it when they are done (the last step).",
"6. Do not install custom nodes. Do not change models or other settings, except the picture model the status asks for.",
"7. Use the setup code only with the status address.",
...(shell ? ["", shell] : []),
@@ -114,6 +114,8 @@ function rules(i: GuideInput): string {
}
const curl = (os: Os) => (os === "windows" ? "curl.exe" : "curl");
+/** The quick tunnel on a Mac or Linux, with its log in the folder only this user reads. */
+const TUNNEL = "cloudflared tunnel --url http://127.0.0.1:8188 --logfile ~/.fuobe/tunnel.log";
const sep = (os: Os) => (os === "windows" ? "\\" : "/");
function stepZero(i: GuideInput): string {
@@ -148,7 +150,7 @@ function stepZero(i: GuideInput): string {
);
}
-function findComfy(i: GuideInput, portOnly: boolean): string {
+function findComfy(i: GuideInput): string {
const c = curl(i.os);
const ask = lines(
"1. Ask ComfyUI for its facts:",
@@ -157,7 +159,6 @@ function findComfy(i: GuideInput, portOnly: boolean): string {
? ["2. If nothing answers, ask the person to start ComfyUI and to read its port in its window."]
: ["2. If nothing answers, try the port of ComfyUI Desktop:", ` ${c} -s http://127.0.0.1:8000/system_stats`, '3. If neither answers, ask the person to start ComfyUI and to read the port in its window ("To see the GUI go to: http://127.0.0.1:PORT").']),
);
- if (portOnly) return lines(`## Step 1: Find ComfyUI's port`, "", ask, "Below, put that port in place of 8188.");
const where =
i.os === "windows"
? lines(
@@ -195,13 +196,21 @@ function findComfy(i: GuideInput, portOnly: boolean): string {
" tr '\\0' ' ' < /proc/PID/cmdline; echo",
" readlink /proc/PID/cwd",
" If the command has --base-directory <folder>, that folder holds custom_nodes and models. If not, custom_nodes and models are next to main.py.",
- "4. If ComfyUI runs as a service or in Docker, the setting goes into the start command of that service or container. Ask the person before you change a service or a container.",
+ i.way !== "address" &&
+ "4. If ComfyUI runs as a service or in Docker, the setting goes into the start command of that service or container. Ask the person before you change a service or a container.",
"",
"Common places for custom_nodes:",
"- A git install: ~/ComfyUI/custom_nodes",
"- Stability Matrix: ComfyUI's three-dot menu, then Open folder, then custom_nodes",
);
- return lines("## Step 1: Find ComfyUI", "", ask, where);
+ const manager =
+ i.way === "address" &&
+ lines(
+ "",
+ "Below, put that port in place of 8188. The models folder is next to custom_nodes (Step 5 needs it).",
+ "If custom_nodes holds a folder named ComfyUI-Manager (or comfyui-manager), tell the person before Step 3: anyone who has the web address can install add-ons with ComfyUI-Manager while the tunnel runs. In Chrome, Edge or Firefox on this computer, Fuobe needs no web address (the way This browser in Fuobe).",
+ );
+ return lines("## Step 1: Find ComfyUI", "", ask, where, manager);
}
function guardStep(i: GuideInput): string {
@@ -392,39 +401,47 @@ function addressSteps(i: GuideInput): string {
: lines(
"## Step 3: Start the web address",
"",
- "1. Remove an old log, so that the address you read is the new one:",
- " rm -f /tmp/fuobe-tunnel.log",
- "2. Start the tunnel in the background, with its log in a file:",
- " nohup cloudflared tunnel --url http://127.0.0.1:8188 --logfile /tmp/fuobe-tunnel.log >/dev/null 2>&1 &",
+ "1. Make a folder that only this user can read, for the tunnel's log, and remove an old log, so that the address you read is the new one:",
+ " mkdir -p -m 700 ~/.fuobe && rm -f ~/.fuobe/tunnel.log",
+ ...(os === "mac"
+ ? [
+ "2. Start the tunnel in a Terminal window of its own, so the person sees it run. macOS can ask the person to let your app control Terminal: they press OK.",
+ ` osascript -e 'tell application "Terminal" to do script "${TUNNEL}"'`,
+ ` If that doesn't work, ask the person to open a new Terminal window and to run this in it: ${TUNNEL}`,
+ ]
+ : [
+ "2. Ask the person to open a new terminal window and to run this in it, so they see the tunnel run. On GNOME, gnome-terminal -- <the command> opens that window for them:",
+ ` ${TUNNEL}`,
+ ]),
"3. Wait about 10 seconds. Then put the address on the clipboard without showing it:",
os === "mac"
- ? " grep -o 'https://[-a-z0-9]*\\.trycloudflare\\.com' /tmp/fuobe-tunnel.log | tail -1 | pbcopy"
- : " grep -o 'https://[-a-z0-9]*\\.trycloudflare\\.com' /tmp/fuobe-tunnel.log | tail -1 | xclip -selection clipboard",
- os === "linux" ? " On Wayland, use wl-copy in place of xclip -selection clipboard. If neither is there, ask the person to open /tmp/fuobe-tunnel.log and copy the address that ends in trycloudflare.com." : false,
+ ? " grep -o 'https://[-a-z0-9]*\\.trycloudflare\\.com' ~/.fuobe/tunnel.log | tail -1 | pbcopy"
+ : " grep -o 'https://[-a-z0-9]*\\.trycloudflare\\.com' ~/.fuobe/tunnel.log | tail -1 | xclip -selection clipboard",
+ os === "linux" ? " On Wayland, use wl-copy in place of xclip -selection clipboard. If neither is there, ask the person to copy the address that ends in trycloudflare.com from the tunnel's window." : false,
" If the clipboard stays empty, wait 10 seconds more and run it again.",
- "4. Do not print, read out or keep the address. cloudflared runs until the computer restarts or you stop it (the last step).",
+ "4. Do not print, read out or keep the address. Tell the person to keep the tunnel's window open while Fuobe runs. Closing it stops the address.",
);
const give = lines(
"## Step 4: Give the address to Fuobe",
"",
- "1. Ask the person to paste the address (it is on the clipboard) into Your ComfyUI's web address in Fuobe, then press Connect. Fuobe tests it. In a chat, do not ask the person to paste it into the chat.",
+ `1. Ask the person to paste the address (it is on this computer's clipboard) into Your ComfyUI's web address in Fuobe, then press Connect. Fuobe tests it. If Fuobe is open only on a phone, the person opens ${i.site}/connect?setup=ai on this computer, signs in, and pastes it there. In a chat, do not ask the person to paste it into the chat.`,
"2. Read the status. When the web address works and Fuobe is connected, go on.",
);
const stop = lines(
`## Step ${STOP_STEP}: When the person is done`,
"",
- "Runs reach ComfyUI only while cloudflared runs. To stop this tunnel (and no other cloudflared the person runs), in the same folder as Step 3:",
- os === "windows" ? " Stop-Process -Id (Get-Content fuobe-tunnel.pid)" : " pkill -f fuobe-tunnel.log",
+ "Runs reach ComfyUI only while cloudflared runs, and so does anyone else who has the address. When the person is done, they close the tunnel's window. Or stop this tunnel (and no other cloudflared the person runs)" + (os === "windows" ? ", in the same folder as Step 3:" : ":"),
+ os === "windows" ? " Stop-Process -Id (Get-Content fuobe-tunnel.pid)" : " pkill -f .fuobe/tunnel.log",
"The next time cloudflared starts, it makes a new address. The person pastes the new one in Fuobe.",
);
- return lines(stepZero(i), "", findComfy(i, true), "", install, "", start, "", give, "", modelStep(i), "", stop);
+ return lines(stepZero(i), "", findComfy(i), "", install, "", start, "", give, "", modelStep(i), "", stop);
}
function connectSteps(i: GuideInput): string {
return lines(
stepZero(i),
"",
- findComfy(i, false),
+ findComfy(i),
"",
"## Step 2: Install Fuobe Connect",
"",
@@ -463,7 +480,7 @@ export function guideText(i: GuideInput, code?: string): string {
? addressSteps(i)
: i.way === "connect"
? connectSteps(i)
- : lines(stepZero(i), "", findComfy(i, false), "", guardStep(i), "", settingStep(i), "", checkStep(i), "", finishDirect(i), "", modelStep(i));
+ : lines(stepZero(i), "", findComfy(i), "", guardStep(i), "", settingStep(i), "", checkStep(i), "", finishDirect(i), "", modelStep(i));
return lines(top, "", body, "", "If you are stuck, read the next step in the status and do it.") + "\n";
}
diff --git a/src/lib/ai-setup/next-step.ts b/src/lib/ai-setup/next-step.ts
index 4640a09a..0fd5ebd9 100644
--- a/src/lib/ai-setup/next-step.ts
+++ b/src/lib/ai-setup/next-step.ts
@@ -7,7 +7,7 @@ import { COMFY_PORTS } from "@/lib/local-comfy";
import { FIRST_MODEL_NAME } from "./first-picture";
import type { AddressCause, InstallKind, SetupView } from "./facts";
import { isConnected, isDone } from "./steps";
-import type { BrowserName, Way } from "./ways";
+import type { BrowserName, Os, Way } from "./ways";
export interface NextStep {
id: string;
@@ -57,11 +57,28 @@ const ADDRESS_SAY: Record<AddressCause, string> = {
"no-answer":
"Nothing answered at that address. Make sure that ComfyUI and cloudflared are both running, and that the port in the cloudflared command is ComfyUI's port. A new address can take up to a minute to work.",
"not-comfy": "That address isn't a ComfyUI. Make sure that the port in the cloudflared command is ComfyUI's port.",
- password: "Something in front of ComfyUI asks for a password. This way needs none. Start the tunnel straight to ComfyUI's port.",
+ password:
+ "Something in front of ComfyUI asks for a password or a token. Keep that protection. Ask the person to type the token in Access token, under the address in Fuobe, then press Connect again. Fuobe sends it as a Bearer token. If it is a sign-in page, Fuobe can't pass it: ask the person what they want to do. Don't ask for the token in this chat.",
format: "Fuobe couldn't use that address. Ask the person what Fuobe says under the box.",
unknown: "Fuobe couldn't use that address. Ask the person what Fuobe says under the box.",
};
+/** ComfyUI runs on the processor: how to let it use the graphics card, by computer. */
+const CPU_HOW: Record<Os, string[]> = {
+ windows: [
+ "If nvidia-smi (guide Step 0) shows an NVIDIA card, ComfyUI's PyTorch can't use it. Portable or Easy-Install: start ComfyUI with run_nvidia_gpu.bat, not run_cpu.bat. Other installs: install the CUDA build of PyTorch, as ComfyUI's own page shows (https://github.com/comfyanonymous/ComfyUI, the part named Manual Install).",
+ ],
+ linux: [
+ "If nvidia-smi (guide Step 0) shows an NVIDIA card, ComfyUI's PyTorch can't use it. Install the CUDA build of PyTorch in ComfyUI's Python, as ComfyUI's own page shows (https://github.com/comfyanonymous/ComfyUI, the part named Manual Install).",
+ ],
+ mac: [
+ "On Apple silicon, ComfyUI uses the GPU through PyTorch's mps. Install a PyTorch with mps, as ComfyUI's own page shows (https://github.com/comfyanonymous/ComfyUI, the part named Apple Mac silicon). On an Intel Mac, ComfyUI can only use the processor.",
+ ],
+ other: ["If the computer has a graphics card, ComfyUI's PyTorch can't use it. Install the PyTorch build for that card, as ComfyUI's own page shows (https://github.com/comfyanonymous/ComfyUI)."],
+};
+
+const OWN_KEY = "With no usable graphics card, Fuobe also runs with the person's own fal.ai or Replicate key: {site}/settings, then Your keys.";
+
const gb = (tenths: number) => `${(tenths / 10).toFixed(tenths >= 100 ? 0 : 1)} GB`;
/** The status words' site: the studio's own address (never a visitor's word). */
@@ -90,7 +107,7 @@ export function nextOf(v: SetupView, now: number): NextStep {
way === "address"
? [
"Keep cloudflared running while runs go. Each time cloudflared starts again, it makes a new address: paste the new one in Fuobe.",
- `When the person is done for the day, stop cloudflared (guide Step ${STOP_STEP}).`,
+ `Tell the person that closing the cloudflared window stops the address, and that anyone with the address can use ComfyUI while it runs. When they are done for the day, stop cloudflared (guide Step ${STOP_STEP}).`,
]
: ["Keep a Fuobe tab open on this computer while runs go."];
return say("done", "Done. Fuobe uses this GPU now. Nothing else to do.", keep);
@@ -107,7 +124,9 @@ export function nextOf(v: SetupView, now: number): NextStep {
if (linked) return say("checking-link", "Fuobe is checking the saved address. Wait a few seconds, then check again.");
return say(
"start-tunnel",
- "Fuobe doesn't have ComfyUI's web address yet. Start cloudflared (guide Steps 2 and 3), then ask the person to paste the address into Fuobe and press Connect. Don't paste the address into this chat.",
+ v.phone
+ ? "Fuobe doesn't have ComfyUI's web address yet. Start cloudflared (guide Steps 2 and 3). The address is then on the computer's clipboard, not the phone's: ask the person to open {site}/connect?setup=ai on that computer, sign in, paste the address under Your ComfyUI's web address and press Connect. Don't paste the address into this chat."
+ : "Fuobe doesn't have ComfyUI's web address yet. Start cloudflared (guide Steps 2 and 3), then ask the person to paste the address into Fuobe and press Connect. Don't paste the address into this chat.",
[],
2,
);
@@ -115,7 +134,12 @@ export function nextOf(v: SetupView, now: number): NextStep {
if (t.browser === "unsupported") return say("use-address", "This browser can't reach ComfyUI from a website. Ask the person to choose A web address in Fuobe.");
if (t.browser === "ask")
- return say("allow-browser", "Fuobe needs the person's OK to look for ComfyUI on this computer. Ask them to press Let Fuobe look in Fuobe, then Allow when the browser asks.", [], 5);
+ return say(
+ "allow-browser",
+ "Fuobe hasn't looked for ComfyUI on this computer yet. If ComfyUI runs now, ask the person to press Let Fuobe look in Fuobe, and Allow if the browser asks. If ComfyUI isn't installed yet, start with guide Step 0, and ask for the press once it runs.",
+ [],
+ 5,
+ );
if (t.browser === "blocked")
return say("unblock-browser", "The browser blocks Fuobe from reaching apps on this computer.", [BLOCKED_HOW[t.browserName ?? "other"], "Or the person switches to A web address in Fuobe."], 5);
if (!t.comfy || t.comfy === "none")
@@ -126,7 +150,11 @@ export function nextOf(v: SetupView, now: number): NextStep {
0,
);
if (t.comfy === "other") return say("wrong-app", `Another app answers on port ${t.port ?? 8188}, not ComfyUI. Find ComfyUI's port in its window or its settings.`, [], 1);
- if (t.comfy === "waiting") return say("restarting", "ComfyUI is restarting. Wait a few seconds, then check again.");
+ if (t.comfy === "waiting")
+ return say(
+ "restarting",
+ `ComfyUI stopped answering on port ${t.port ?? 8188} a moment ago: it is restarting, or it was closed. Wait a few seconds, then check again. If it isn't back in a minute, ask the person to start it again.`,
+ );
if (way === "connect") {
if (t.guard !== "connect") return say("install-connect", "Fuobe Connect isn't in ComfyUI yet. Install it (guide Step 2), then restart ComfyUI.", [], 2);
return say("connecting", "Fuobe sees ComfyUI and is connecting. Wait a few seconds, then check again.");
@@ -180,7 +208,21 @@ export function nextOf(v: SetupView, now: number): NextStep {
["The person can also press Copy download commands in Fuobe and run them."],
MODEL_STEP[way],
);
- if (t.model === "none") return say("no-model-fits", "This GPU can't run the small picture models Fuobe starts with. Ask the person to open {site}/connect to see what runs on it.");
+ if (t.model === "none") {
+ if (t.cpu)
+ return say(
+ "cpu-only",
+ "ComfyUI runs on the processor, not on a graphics card, so no picture model fits. Make ComfyUI use the graphics card, restart it (ask the person first), then check again.",
+ [...(t.cpuFlag ? ["ComfyUI was started with --cpu. Start it again without --cpu."] : CPU_HOW[os]), OWN_KEY],
+ 0,
+ );
+ if (t.modelWhy === "setup")
+ return say(
+ "model-setup",
+ "None of the small picture models Fuobe starts with is ready, and each needs more than one download on this ComfyUI, most often a newer ComfyUI. Update ComfyUI (ask the person first: it restarts), then check again.",
+ );
+ return say("no-model-fits", "This GPU has too little memory for the small picture models Fuobe starts with (the smallest, SDXL, needs 8 GB). Tell the person plainly.", [OWN_KEY], 0);
+ }
if (t.model !== "ready") return say("checking-models", "ComfyUI is connected. Fuobe is checking which models it has. Wait a few seconds, then check again.");
return say("make-picture", `ComfyUI is connected and has a picture model. Ask the person to press Make your first picture in Fuobe.${cpu}`);
}
diff --git a/src/lib/ai-setup/person-words.ts b/src/lib/ai-setup/person-words.ts
new file mode 100644
index 00000000..e1215ef9
--- /dev/null
+++ b/src/lib/ai-setup/person-words.ts
@@ -0,0 +1,46 @@
+/**
+ * The next step as the panel's "Stuck?" says it to the person (their AI gets the full next step with "Copy for my AI"):
+ * what Fuobe sees, in the person's own terms, with no guide steps, commands or flags. Pure.
+ */
+import type { NextStep } from "./next-step";
+
+const WORDS: Record<string, string> = {
+ "wake-fuobe": "Fuobe can check only while this tab is open.",
+ "open-fuobe": "Fuobe can check only while this tab is open.",
+ done: "All done. Fuobe uses your GPU now.",
+ "use-address": "This browser can't reach ComfyUI on your computer. A web address works instead.",
+ "allow-browser": "Fuobe hasn't looked for ComfyUI yet. If ComfyUI runs, press Let Fuobe look. If you don't have it yet, your AI installs it first.",
+ "unblock-browser": "Your browser stops Fuobe from reaching apps on this computer. Allow it next to the address bar, then reload.",
+ "start-comfyui": "Fuobe doesn't see ComfyUI on this computer. Start ComfyUI, or ask your AI to install it.",
+ "wrong-app": "Another app answers on that port, not ComfyUI.",
+ restarting: "ComfyUI stopped answering for a moment. It is restarting, or it was closed.",
+ "install-connect": "Fuobe Connect isn't in ComfyUI yet. Your AI installs it next.",
+ connecting: "Fuobe sees ComfyUI and is connecting. It takes a few seconds.",
+ "setting-not-taken": "ComfyUI restarted, but it still doesn't let Fuobe in. Your AI checks the setting.",
+ "add-setting": "ComfyUI runs, but it doesn't let Fuobe in yet. Your AI adds Fuobe's setting next.",
+ "remove-listen": "ComfyUI is open to other computers on your network. Your AI turns that off.",
+ "fix-any": "ComfyUI lets every website in. Your AI changes that to Fuobe only.",
+ "fix-setting": "ComfyUI lets another website in, not Fuobe. Your AI changes the setting.",
+ "add-guard": "Fuobe's guard isn't in ComfyUI yet. It keeps other websites out. Your AI adds it next.",
+ "address-testing": "Fuobe is testing your web address.",
+ "checking-link": "Fuobe is checking your web address.",
+ "link-offline": "Fuobe can't reach ComfyUI at your web address. If the cloudflared window closed, your AI starts it again and you paste the new address.",
+ "start-tunnel": "Fuobe doesn't have your ComfyUI's web address yet. Your AI makes one with cloudflared.",
+ "address-local": "That address works only on your own network. Paste the one that ends in trycloudflare.com.",
+ "address-not-found": "Fuobe can't find that address. Paste all of it, and keep the cloudflared window open.",
+ "address-no-answer": "Nothing answers at that address. Keep ComfyUI and the cloudflared window open.",
+ "address-not-comfy": "That address doesn't lead to ComfyUI.",
+ "address-password": "Your web address asks for a password or a token. Type it under Access token, then press Connect.",
+ "checking-models": "Fuobe is checking which models ComfyUI has.",
+ "get-model": "ComfyUI needs a picture model. Your AI can download it, after you say yes.",
+ "cpu-only": "ComfyUI runs on your computer's processor, not on its graphics card. Your AI can fix that.",
+ "model-setup": "These picture models need more than a download on your ComfyUI, most often an update. Your AI can update it.",
+ "no-model-fits": "Your GPU has too little memory for the small picture models. Your own fal.ai or Replicate key works instead.",
+ "make-picture": "All set. Press Make your first picture.",
+ "picture-running": "Fuobe is making your first picture.",
+ "picture-failed": "The first picture didn't finish. Try again.",
+};
+
+export function personWords(next: Pick<NextStep, "id">): string {
+ return WORDS[next.id] ?? (next.id.startsWith("address-") ? "Fuobe couldn't use that web address. Read what Fuobe says under the box." : "Fuobe is waiting for the next step.");
+}
diff --git a/src/lib/ai-setup/steps.ts b/src/lib/ai-setup/steps.ts
index c7ecd4bc..ae70938b 100644
--- a/src/lib/ai-setup/steps.ts
+++ b/src/lib/ai-setup/steps.ts
@@ -25,9 +25,9 @@ export const INSTALL_LABEL: Record<InstallKind, string> = {
export const STEP_LABEL: Record<StepId, string> = {
comfyui: "ComfyUI is running",
- allowed: "Fuobe is allowed in",
- guard: "The guard is in place",
- connect: "Fuobe Connect is in place",
+ allowed: "ComfyUI lets Fuobe in",
+ guard: "Other websites are kept out",
+ connect: "Fuobe Connect is installed",
address: "Web address works",
connected: "Fuobe is connected",
model: "A picture model is ready",
@@ -68,7 +68,7 @@ function modelStep(v: SetupView, connected: boolean): Step {
case "download":
return step("model", "todo", t.modelId && `${FIRST_MODEL_NAME[t.modelId]}: one download, ${gb(t.modelGbTenths ?? 0)}`);
case "none":
- return step("model", "warn", "No small picture model fits this GPU");
+ return step("model", "warn", t.cpu ? "ComfyUI runs on the processor" : t.modelWhy === "setup" ? "ComfyUI needs an update first" : "No small picture model fits this GPU");
default:
return step("model", "working", "Checking what ComfyUI has");
}
@@ -118,9 +118,9 @@ export function stepsOf(v: SetupView): Step[] {
t?.browser === "blocked"
? step("comfyui", "warn", "The browser blocks Fuobe")
: t?.comfy === "found" || t?.comfy === "unreadable"
- ? step("comfyui", "done", t.port ? `Port ${t.port}${t.install ? `, ${INSTALL_LABEL[t.install]}` : ""}` : undefined)
+ ? step("comfyui", "done", t.port ? `${t.install ? `${INSTALL_LABEL[t.install]}, on` : "On"} port ${t.port}` : undefined)
: t?.comfy === "waiting"
- ? step("comfyui", "working", "Restarting")
+ ? step("comfyui", "working", "Restarting, or closed")
: t?.comfy === "other"
? step("comfyui", "warn", t.port ? `Another app answers on port ${t.port}` : "Another app answers")
: step("comfyui", "todo");
@@ -145,7 +145,7 @@ export function stepsOf(v: SetupView): Step[] {
: step("allowed", "todo");
const guard =
t?.guard === "guard" || t?.guard === "connect"
- ? step("guard", "done", "Other websites stay out")
+ ? step("guard", "done", "Fuobe's guard is on")
: allowed.state === "done" && t?.guardSkipped
? step("guard", "warn", "Connected without the guard")
: step("guard", "todo");
diff --git a/src/server/ai-setup-http.ts b/src/server/ai-setup-http.ts
index 999ee981..b8bb770c 100644
--- a/src/server/ai-setup-http.ts
+++ b/src/server/ai-setup-http.ts
@@ -31,6 +31,16 @@ export const inMinutes = (s: number) => (s <= 60 ? `${Math.max(1, s)} s` : `${Ma
export const tooMany = (error: string, retryAfterS: number) =>
Response.json({ error, retryAfterS }, { status: 429, headers: { ...SETUP_HEADERS, "Retry-After": String(retryAfterS) } });
+/**
+ * A visitor's budget for Fuobe's own fixed files (the steps, the guard, the start file): its own only, when the studio
+ * can tell visitors apart. No budget shared by everyone: these are the same few lines for every visitor, and a shared
+ * one would let a few visitors use it up and keep every other person's AI from its steps.
+ */
+export function ownBudget(name: string, headers: Headers, perVisitor: number, windowMs: number): { ok: boolean; retryAfterS: number } {
+ const key = visitorKey(headers);
+ return key ? hit(`${name}:${key}`, perVisitor, windowMs) : { ok: true, retryAfterS: 0 };
+}
+
/**
* A visitor's budget for a public read: its own when the studio can tell visitors apart (FUOBE_TRUST_PROXY), and
* always one shared by everyone, much larger (so one busy visitor can't use it up for the rest, and a studio that can't
diff --git a/tests/ai-setup-guide.test.ts b/tests/ai-setup-guide.test.ts
index 59004cd2..b2716abd 100644
--- a/tests/ai-setup-guide.test.ts
+++ b/tests/ai-setup-guide.test.ts
@@ -62,14 +62,34 @@ describe("the guide", () => {
// The address is never printed or tested from the agent: it goes to the clipboard.
expect(g.text).toMatch(/Set-Clipboard|pbcopy|xclip/);
expect(g.text).not.toMatch(/<address>\/system_stats/);
- expect(g.text).toMatch(/Stop-Process -Id \(Get-Content fuobe-tunnel\.pid\)|pkill -f fuobe-tunnel\.log/);
+ expect(g.text).toMatch(/Stop-Process -Id \(Get-Content fuobe-tunnel\.pid\)|pkill -f \.fuobe\/tunnel\.log/);
// Only this tunnel: never every cloudflared the person runs.
expect(g.text).not.toMatch(/Stop-Process -Name cloudflared|pkill -f "cloudflared tunnel --url"/);
// An old log can't give a dead address.
- expect(g.text).toMatch(/Remove-Item fuobe-tunnel\.log|rm -f \/tmp\/fuobe-tunnel\.log/);
+ expect(g.text).toMatch(/Remove-Item fuobe-tunnel\.log|rm -f ~\/\.fuobe\/tunnel\.log/);
}
});
+ it("keeps a web address visible, private and short-lived, and warns about ComfyUI-Manager", () => {
+ for (const g of guides.filter((g) => g.way === "address" && g.os !== "other")) {
+ // Never a tunnel hidden in the background, nor a log other users of the computer can read.
+ expect(g.text).not.toMatch(/nohup|\/tmp\//);
+ expect(g.text).toContain("ComfyUI-Manager");
+ expect(g.text).toContain("Closing it stops the address.");
+ expect(g.text).toMatch(/they close the tunnel's window/);
+ if (g.os !== "windows") expect(g.text).toContain("mkdir -p -m 700 ~/.fuobe");
+ // The models folder the model step names is found first.
+ expect(g.text).toContain("Common places for custom_nodes:");
+ expect(g.text).toContain("The models folder is next to custom_nodes");
+ // The address goes into Fuobe on the computer, even when Fuobe was opened on a phone.
+ expect(g.text).toContain(`${SITE}/connect?setup=ai on this computer`);
+ }
+ const mac = guides.find((x) => x.way === "address" && x.os === "mac")!.text;
+ expect(mac).toContain(`osascript -e 'tell application "Terminal" to do script "cloudflared tunnel --url http://127.0.0.1:8188 --logfile ~/.fuobe/tunnel.log"'`);
+ const win = guides.find((x) => x.way === "address" && x.os === "windows")!.text;
+ expect(win).toContain("Get-NetTCPConnection -LocalPort 8188 -State Listen");
+ });
+
it("Windows commands have no $ and no braces, so they also run through powershell.exe -Command", () => {
for (const g of guides.filter((g) => g.os === "windows")) {
for (const line of commands(g.text)) {
diff --git a/tests/ai-setup-routes.test.ts b/tests/ai-setup-routes.test.ts
index cc892158..75b27bcf 100644
--- a/tests/ai-setup-routes.test.ts
+++ b/tests/ai-setup-routes.test.ts
@@ -178,7 +178,7 @@ describe("the tab's reports and waits", () => {
await report(body.code, a, facts({ comfy: "unreadable", port: 8188 }));
const status = await (await reading).json();
expect(Date.now() - t0).toBeLessThan(4000);
- expect(status.steps[0]).toMatchObject({ id: "comfyui", state: "done", detail: "Port 8188" });
+ expect(status.steps[0]).toMatchObject({ id: "comfyui", state: "done", detail: "On port 8188" });
// The tab's next report says the AI checked in.
expect((await (await report(body.code, a)).json()).aiReadAt).toBeGreaterThan(0);
});
@@ -208,7 +208,7 @@ describe("the public status", () => {
expect(text.headers.get("access-control-allow-origin")).toBeNull();
const words = await text.text();
expect(words).toMatch(/^[\x0a\x20-\x7e]*$/);
- expect(words).toContain("[done] ComfyUI is running: Port 8000, ComfyUI Desktop");
+ expect(words).toContain("[done] ComfyUI is running: ComfyUI Desktop, on port 8000");
expect(words).not.toContain("[email protected]");
const json = await (await read(body.code, "?format=json&n=2")).json();
expect(json).toMatchObject({ fuobe_setup: 1, code: body.code, way: "direct", port: 8000, install: "desktop" });
@@ -290,6 +290,22 @@ describe("the guide and Fuobe's files", () => {
expect((await startRoute.GET(req("/api/setup/files/start/99999"), ctx({ port: "99999" }))).status).toBe(404);
});
+ it("limit each visitor on its own: many visitors together never keep another one from the steps", async () => {
+ process.env.FUOBE_TRUST_PROXY = "1";
+ try {
+ const guide = (ip: string) => guideRoute.GET(req("/api/setup/guide/address/mac", { headers: { "x-forwarded-for": ip } }), ctx({ way: "address", os: "mac" }));
+ const guard = (ip: string) => guardRoute.GET(req("/api/setup/files/fuobe_guard.py", { headers: { "x-forwarded-for": ip } }));
+ // Eleven visitors use up their own minute (more than the 600 a minute a shared budget would allow).
+ for (let v = 1; v <= 11; v++) for (let i = 0; i < 60; i++) expect((await guide(`2001:db8:${v}::1`)).status).toBe(200);
+ expect((await guide("2001:db8:1::1")).status).toBe(429);
+ expect((await guide("198.51.100.20")).status).toBe(200);
+ for (let v = 1; v <= 11; v++) for (let i = 0; i < 60; i++) await guard(`2001:db8:${v}::1`);
+ expect((await guard("198.51.100.20")).status).toBe(200);
+ } finally {
+ delete process.env.FUOBE_TRUST_PROXY;
+ }
+ });
+
it("knows the studio's address from a fixed list", () => {
const h = (host: string, more: Record<string, string> = {}) => new Headers({ host, ...more });
expect(siteOf(h("fuobe.com"), "http://localhost:3000/x")).toBe("https://fuobe.com");
diff --git a/tests/ai-setup-status.test.ts b/tests/ai-setup-status.test.ts
index 06db27fc..21ec593c 100644
--- a/tests/ai-setup-status.test.ts
+++ b/tests/ai-setup-status.test.ts
@@ -3,6 +3,7 @@ import { newSetupCode, setupCode, showCode, spokenCode, SETUP_ALPHABET } from "@
import { addressCauseOf, listensWide, TabFactsSchema, type SetupView, type TabFacts } from "@/lib/ai-setup/facts";
import { FIRST_PICTURE_MODELS, firstModelOf, firstPictureRequest, modelOrder } from "@/lib/ai-setup/first-picture";
import { nextOf } from "@/lib/ai-setup/next-step";
+import { personWords } from "@/lib/ai-setup/person-words";
import { PUBLIC_KEYS, toPublic, toText } from "@/lib/ai-setup/status";
import { stepsOf } from "@/lib/ai-setup/steps";
import { browserOf, pickWay, waysFor } from "@/lib/ai-setup/ways";
@@ -107,6 +108,14 @@ describe("the steps and the next step", () => {
["address: local", { way: "address", address: "failed", addressCause: "local" }, {}, "address-local", "trycloudflare.com"],
["address: saved, offline", { way: "address", address: "ok" }, { server: { gpu: "link", online: false } }, "link-offline"],
["address: connected", { way: "address", address: "ok", model: "ready" }, { server: { gpu: "link", online: true } }, "make-picture"],
+ ["address: a password keeps its protection", { way: "address", address: "failed", addressCause: "password" }, {}, "address-password", "Keep that protection"],
+ ["address: from a phone, pasted on the computer", { way: "address" }, { phone: true }, "start-tunnel", "/connect?setup=ai on that computer"],
+ ["not looked yet: install first if needed", { browser: "ask" }, {}, "allow-browser", "guide Step 0"],
+ ["ComfyUI went quiet a moment ago", { comfy: "waiting", port: 8288 }, {}, "restarting", "port 8288"],
+ ["on the processor, started with --cpu", { comfy: "found", cors: "exact", guard: "guard", connected: true, model: "none", cpu: true, cpuFlag: true }, {}, "cpu-only", "without --cpu"],
+ ["on the processor, a PyTorch without CUDA", { comfy: "found", cors: "exact", guard: "guard", connected: true, model: "none", cpu: true }, {}, "cpu-only", "run_nvidia_gpu.bat"],
+ ["a GPU too small", { comfy: "found", cors: "exact", guard: "guard", connected: true, model: "none", modelWhy: "small" }, {}, "no-model-fits", "Your keys"],
+ ["a model needs more than a download", { comfy: "found", cors: "exact", guard: "guard", connected: true, model: "none", modelWhy: "setup" }, {}, "model-setup", "Update ComfyUI"],
];
it.each(cases)("%s", (_name, facts, o, id, words) => {
const v = view(facts, o);
@@ -115,6 +124,16 @@ describe("the steps and the next step", () => {
if (words) expect([next.say, ...next.how].join(" ")).toContain(words);
expect(next.guide.startsWith(`${SITE}/api/setup/guide/`)).toBe(true);
for (const s of [next.say, ...next.how, ...stepsOf(v).flatMap((s) => [s.label, s.detail ?? ""])]) expect(s).toMatch(/^[\x20-\x7e]*$/);
+ // The person's own words: no guide steps, flags or commands.
+ const mine = personWords(next);
+ expect(mine).not.toMatch(/guide|Step \d|--|\(|curl|cloudflared tunnel/);
+ expect(mine.length).toBeGreaterThan(10);
+ });
+
+ it("never tells the AI to take a password or token off a web address", () => {
+ const next = nextOf(view({ way: "address", address: "failed", addressCause: "password" }), NOW);
+ expect(next.say).toContain("Access token");
+ expect(next.say).not.toMatch(/needs none|straight to ComfyUI/);
});
it("ticks the rows off in order", () => {
@@ -155,8 +174,8 @@ describe("the public status", () => {
const text = toText(toPublic(input({ comfy: "unreadable", port: 8000, install: "desktop" }), NOW));
expect(text).toMatch(/^[\x0a\x20-\x7e]*$/);
expect(text).toContain("Fuobe setup status for code ABCD-EFGH-JKMN.");
- expect(text).toContain("[done] ComfyUI is running: Port 8000, ComfyUI Desktop");
- expect(text).toContain("[todo] Fuobe is allowed in");
+ expect(text).toContain("[done] ComfyUI is running: ComfyUI Desktop, on port 8000");
+ expect(text).toContain("[todo] ComfyUI lets Fuobe in");
expect(text).toContain("Next step: ComfyUI is running on port 8000");
expect(text).toContain("Documents -> ComfyUI");
expect(text).toContain("?r=k7q2abcd");
@@ -179,7 +198,8 @@ describe("the first picture", () => {
expect(firstModelOf({ connected: true, models: { "oss-sdxl#t2i": ["r", 0, 0, 0], "oss-z-image-turbo#t2i": ["a", 1, 207, 0] } })).toEqual({ state: "ready", model: "oss-sdxl" });
expect(firstModelOf({ connected: true, vramGb: 32, models: { "oss-sdxl#t2i": ["a", 1, 69, 0], "oss-z-image-turbo#t2i": ["a", 1, 207, 0] } })).toEqual({ state: "download", model: "oss-z-image-turbo", gbTenths: 207 });
expect(firstModelOf({ connected: true, vramGb: 8, models: { "oss-sdxl#t2i": ["a", 1, 69, 0], "oss-z-image-turbo#t2i": ["a", 1, 207, 0] } })).toEqual({ state: "download", model: "oss-sdxl", gbTenths: 69 });
- expect(firstModelOf({ connected: true, models: { "oss-sdxl#t2i": ["g", 0, 0, 0] } })).toEqual({ state: "none" });
+ expect(firstModelOf({ connected: true, models: { "oss-sdxl#t2i": ["g", 0, 0, 0] } })).toEqual({ state: "none", why: "small" });
+ expect(firstModelOf({ connected: true, models: { "oss-sdxl#t2i": ["g", 0, 0, 0], "oss-z-image-turbo#t2i": ["s", 2, 120, 0] } })).toEqual({ state: "none", why: "setup" });
expect(modelOrder(8)[0]).toBe("oss-sdxl");
});
});
diff --git a/tests/e2e/ai-setup.mjs b/tests/e2e/ai-setup.mjs
index aa8362c7..61eb82d7 100644
--- a/tests/e2e/ai-setup.mjs
+++ b/tests/e2e/ai-setup.mjs
@@ -164,8 +164,9 @@ try {
return t && /^[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}$/.test(t) ? t : null;
}, 15_000);
check(`${tag}: …with a setup code`, !!code, code ?? "");
- const chat = page.getByRole("button", { name: /Open in ChatGPT/ });
- check(`${tag}: the hand-offs wait for the browser's question first`, await chat.isDisabled().catch(() => false));
+ const chatNow = page.getByRole("link", { name: /Open in ChatGPT/ });
+ check(`${tag}: the hand-offs are ready before Fuobe looks (no browser question first)`, !!(await until(() => chatNow.isVisible(), 10_000)));
+ const checklistTop = await page.getByRole("list", { name: "Setup steps" }).boundingBox();
await page.screenshot({ path: path.join(shots, `${tag}-1-open.png`), fullPage: true });
// Nothing changes while nobody acts: the tab reports a change once, then only its heartbeat (every 25 s at most).
await sleep(2000);
@@ -177,9 +178,10 @@ try {
ctx.map = { 8188: CLOSED };
await page.getByRole("button", { name: "Let Fuobe look" }).click();
const steps = page.getByRole("list", { name: "Setup steps" });
- check(`${tag}: ComfyUI is running ticks, on port 8188`, !!(await until(() => steps.getByText("Port 8188").first().isVisible(), 20_000)));
+ check(`${tag}: ComfyUI is running ticks, on port 8188`, !!(await until(() => steps.getByText("port 8188").first().isVisible(), 20_000)));
const open = page.getByRole("link", { name: /Open in ChatGPT/ });
- check(`${tag}: the hand-offs unlock after the look`, !!(await until(() => open.isVisible(), 10_000)));
+ const checklistAfter = await page.getByRole("list", { name: "Setup steps" }).boundingBox();
+ check(`${tag}: the checklist stays put after the look`, !!checklistTop && !!checklistAfter && Math.abs(checklistTop.y - checklistAfter.y) < 4, `${checklistTop?.y} -> ${checklistAfter?.y}`);
const href = (await open.getAttribute("href")) ?? "";
const q = new URL(href).searchParams.get("q") ?? "";
check(`${tag}: Open in ChatGPT carries the steps, the status and the code`, href.startsWith("https://chatgpt.com/?q=") && q.includes(`${SITE}/api/setup/guide/direct/`) && q.includes(`${SITE}/api/setup/${code}`) && href.length <= 2000);
@@ -187,7 +189,7 @@ try {
check(`${tag}: Open in Claude too`, claudeHref.startsWith("https://claude.ai/new?q="));
let st = await until(async () => {
const s = await status(code);
- return s.body.includes("[done] ComfyUI is running: Port 8188") ? s : null;
+ return /\[done\] ComfyUI is running: .*port 8188/.test(s.body) ? s : null;
}, 20_000);
check(`${tag}: the AI's status follows, as text`, !!st && st.status === 200 && st.body.includes("Next step: ComfyUI is running on port 8188, but it doesn't let Fuobe in yet"), st?.body.split("\n").slice(0, 6).join(" | "));
check(`${tag}: …ASCII only, with the address to read next`, !!st && /^[\x0a\x20-\x7e]*$/.test(st.body) && st.body.includes("?r="));
@@ -195,7 +197,7 @@ try {
// ComfyUI restarted with the setting, but no guard yet.
ctx.map = { 8188: OPEN };
- check(`${tag}: Fuobe is allowed in ticks`, !!(await until(() => steps.getByText("127.0.0.1:3651 only").isVisible(), 30_000)));
+ check(`${tag}: ComfyUI lets Fuobe in ticks`, !!(await until(() => steps.getByText("127.0.0.1:3651 only").isVisible(), 30_000)));
st = await until(async () => {
const s = await status(code, true);
return s.body.next?.id === "add-guard" ? s : null;
@@ -206,7 +208,7 @@ try {
// With the guard (and every model): connects by itself, then the first picture.
ctx.map = { 8188: GUARDED };
- check(`${tag}: the guard ticks, and it connects by itself`, !!(await until(() => steps.getByText("Other websites stay out").isVisible(), 30_000)));
+ check(`${tag}: the guard ticks, and it connects by itself`, !!(await until(() => steps.getByText("Fuobe's guard is on").isVisible(), 30_000)));
const make = page.getByRole("button", { name: "Make your first picture" });
check(`${tag}: a picture model is ready, and Make your first picture shows`, !!(await until(() => make.isVisible(), 60_000)));
await page.screenshot({ path: path.join(shots, `${tag}-4-connected.png`), fullPage: true });
@@ -249,6 +251,36 @@ try {
await ctx.close();
}
+ // A ComfyUI on a port Fuobe doesn't wait for (8288) restarts with Fuobe's setting: it is found again by itself, and
+ // the status says it is restarting meanwhile, never to install ComfyUI.
+ {
+ const ctx = await context(browser, { viewport: { width: 1440, height: 1100 } });
+ const page = await ctx.newPage();
+ await page.goto(`${SITE}/connect`, { waitUntil: "load" });
+ await signUp(page);
+ await page.goto(`${SITE}/connect?setup=ai`, { waitUntil: "load" });
+ await page.getByRole("heading", { name: "Set it up with your AI" }).waitFor({ timeout: 30_000 });
+ const codeEl = page.locator("span[aria-label^='Setup code']");
+ const code = await until(async () => {
+ const t = (await codeEl.textContent())?.trim();
+ return t && /^[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}$/.test(t) ? t : null;
+ }, 15_000);
+ ctx.map = { 8288: CLOSED };
+ await page.getByRole("button", { name: "Let Fuobe look" }).click();
+ const steps = page.getByRole("list", { name: "Setup steps" });
+ check("restart on 8288: found there first", !!(await until(() => steps.getByText("port 8288").first().isVisible(), 30_000)));
+ ctx.map = {};
+ const quiet = await until(async () => {
+ const s = await status(code, true);
+ return s.body.next?.id === "restarting" ? s : null;
+ }, 30_000);
+ check("restart on 8288: the status says it is restarting, not to install it", !!quiet, quiet ? "" : JSON.stringify((await status(code, true)).body.next));
+ ctx.map = { 8288: OPEN };
+ check("restart on 8288: found again by itself with Fuobe's setting", !!(await until(() => steps.getByText("127.0.0.1:3651 only").isVisible(), 40_000)));
+ await page.screenshot({ path: path.join(shots, "restart-8288.png"), fullPage: true });
+ await ctx.close();
+ }
+
// Safari: the web address way.
{
const ctx = await context(browser, {