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.

Connect your GPU: one step, install Fuobe Connect

Adarshdf77c6aa5fd9
diff --git a/src/components/gpu/account-gpu-section.tsx b/src/components/gpu/account-gpu-section.tsx
index 87921f51..0fb56fcf 100644
--- a/src/components/gpu/account-gpu-section.tsx
+++ b/src/components/gpu/account-gpu-section.tsx
@@ -1,6 +1,7 @@
"use client";
import { ConnectChoice } from "@/components/gpu/connect-choice";
+import { PairedComfyUIs } from "@/components/gpu/fuobe-connect";
import { useHydrated, useViewer } from "@/lib/api";
/**
@@ -21,7 +22,10 @@ export function AccountGpuSection() {
Connect your own ComfyUI to run open-source models.
</p>
</div>
- <ConnectChoice />
+ <div className="min-w-0 space-y-4">
+ <ConnectChoice />
+ <PairedComfyUIs className="sm:max-w-[36rem]" />
+ </div>
</section>
);
}
diff --git a/src/components/gpu/connect-choice.tsx b/src/components/gpu/connect-choice.tsx
index 5bc96549..b7113281 100644
--- a/src/components/gpu/connect-choice.tsx
+++ b/src/components/gpu/connect-choice.tsx
@@ -14,6 +14,7 @@ import type { OwnerGpuView } from "@/lib/connections";
import { addressKind, refusedOnHosted } from "@/lib/page-place";
import { cn } from "@/lib/utils";
import { restartComputerRunner, rememberComfy, rememberedComfy } from "./computer-runtime";
+import { PairedComfyUIs } from "./fuobe-connect";
import { GuardFix, SettingFix, ThisComputer, unsupportedWords } from "./this-computer";
import { lookOn, useComputerSupport, usePagePlace } from "./use-local-comfy";
import { openConnect, openFinder, useComputerState, type FindReason } from "./computer-runner";
@@ -654,6 +655,7 @@ export function OwnerComfyWhere({ value, onChange }: { value: string; onChange:
<OwnerComputerLine />
) : null}
{computer && <p className="text-[12px] text-muted-foreground">Moving ComfyUI to this server stops the runs still going on your computer.</p>}
+ <PairedComfyUIs />
</div>
);
}
diff --git a/src/components/gpu/connect-gpu.tsx b/src/components/gpu/connect-gpu.tsx
index ca461dd1..b43126f6 100644
--- a/src/components/gpu/connect-gpu.tsx
+++ b/src/components/gpu/connect-gpu.tsx
@@ -8,6 +8,7 @@ import { useEffect, useRef } from "react";
import { PreflightChecklist } from "@/components/gpu/preflight-checklist";
import { ReadinessBoard } from "@/components/gpu/readiness-board";
import { ConnectChoice } from "@/components/gpu/connect-choice";
+import { PairWithCode } from "@/components/gpu/fuobe-connect";
import { useSettings } from "@/components/connect-field";
import { openFinder, useComputerSupport } from "@/components/gpu/open-connect";
import { usePagePlace } from "@/components/gpu/use-local-comfy";
@@ -34,6 +35,8 @@ function Card({ children }: { children: React.ReactNode }) {
export function ConnectGpu() {
const params = useSearchParams();
const welcome = params.get("welcome") === "1";
+ // Fuobe Connect's pairing link (/connect?code=…): approve that ComfyUI first.
+ const code = params.get("code");
const next = safeNext(params.get("next"), typeof window === "undefined" ? "http://localhost" : window.location.origin);
const viewer = useViewer().data;
const isAccount = !!viewer?.account;
@@ -112,6 +115,37 @@ export function ConnectGpu() {
</div>
);
+ if (code)
+ return (
+ <div className="space-y-6">
+ <div className="space-y-1">
+ <span className="grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">
+ <Cpu aria-hidden className="size-5" />
+ </span>
+ <h1 className="font-heading text-[30px] leading-tight">Connect your ComfyUI</h1>
+ <p className="max-w-2xl text-[15px] text-muted-foreground">Fuobe Connect in your ComfyUI asked to run your Fuobe jobs. Check the computer, then approve it.</p>
+ </div>
+ <Card>
+ {guest ? (
+ <div className="space-y-3">
+ <p className="text-[14px]">Sign in to approve this ComfyUI. Its runs will be yours.</p>
+ <div className="flex flex-wrap gap-2">
+ <Button asChild className="h-11 sm:h-9">
+ <Link href={signInHref("login", `/connect?code=${encodeURIComponent(code)}`)}>Log in</Link>
+ </Button>
+ <Button asChild variant="secondary" className="h-11 sm:h-9">
+ <Link href={signInHref("signup", `/connect?code=${encodeURIComponent(code)}`)}>Sign up free</Link>
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <PairWithCode initial={code} />
+ )}
+ </Card>
+ {done(false)}
+ </div>
+ );
+
if (guest)
return (
<div className="space-y-6">
diff --git a/src/components/gpu/fuobe-connect.tsx b/src/components/gpu/fuobe-connect.tsx
new file mode 100644
index 00000000..9e4bce8d
--- /dev/null
+++ b/src/components/gpu/fuobe-connect.tsx
@@ -0,0 +1,244 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Check, Copy, Cpu, KeyRound, Loader2, Puzzle, Unplug } from "lucide-react";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { gib } from "@/components/gpu/comfy-finder";
+import { useNow } from "@/components/studio/use-now";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { copyWithToast } from "@/lib/clipboard";
+import { FUOBE_CONNECT, pairCode, pairedOnline, trustedByDefault, type PairedComfy } from "@/lib/fuobe-connect";
+import { deviceLabel } from "@/lib/gpu/readiness";
+import { cn } from "@/lib/utils";
+
+/**
+ * Fuobe Connect on this site's screens: the one step to install it, approving a pairing code, and the ComfyUIs paired
+ * with this person.
+ */
+
+const origin = () => (typeof window === "undefined" ? "https://fuobe.com" : window.location.origin);
+
+function Copyable({ text, label }: { text: string; label: string }) {
+ return (
+ <span className="inline-flex max-w-full items-center gap-1 rounded-md bg-muted py-0.5 pr-0.5 pl-2 align-middle">
+ <code aria-label={label} className="min-w-0 overflow-x-auto font-mono text-[12px] whitespace-nowrap">
+ {text}
+ </code>
+ <button type="button" onClick={() => void copyWithToast(text)} aria-label={`Copy ${label}`} className="grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-background hover:text-foreground">
+ <Copy className="size-3" />
+ </button>
+ </span>
+ );
+}
+
+/**
+ * "Install Fuobe Connect in ComfyUI-Manager": the search term to type, the git address for the other ways, and, on a
+ * studio Fuobe Connect doesn't trust by itself, the address to add in its setting.
+ */
+export function InstallConnect({ className, then }: { className?: string; then?: string }) {
+ const own = !trustedByDefault(origin());
+ return (
+ <div className={cn("space-y-2 rounded-xl border bg-background p-3", className)}>
+ <p className="flex items-center gap-2 text-[14px] font-medium">
+ <Puzzle aria-hidden className="size-4 shrink-0 text-brand-text" /> Install {FUOBE_CONNECT.name} in ComfyUI-Manager
+ </p>
+ <ol className="list-decimal space-y-1.5 pl-5 text-[13px] text-muted-foreground">
+ <li>
+ In ComfyUI, open <span className="text-foreground">Manager → Custom Nodes Manager</span> and search <Copyable text={FUOBE_CONNECT.search} label="the search term" />
+ </li>
+ <li>
+ Press <span className="text-foreground">Install</span>, then <span className="text-foreground">Restart</span>.
+ </li>
+ {own && (
+ <li>
+ In ComfyUI, open <span className="text-foreground">Settings → Fuobe Connect</span> and enter <Copyable text={origin()} label="this studio's address" />
+ </li>
+ )}
+ </ol>
+ <p className="text-[12px] text-muted-foreground">
+ No Manager? In ComfyUI&apos;s custom_nodes folder, run <Copyable text={`git clone ${FUOBE_CONNECT.gitUrl}`} label="the git command" /> and restart ComfyUI.
+ </p>
+ {then && <p className="text-[12px] text-muted-foreground">{then}</p>}
+ </div>
+ );
+}
+
+async function pairCall<T>(method: string, url: string, body?: unknown): Promise<T> {
+ const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+ const j = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);
+ return j;
+}
+
+export function usePaired(enabled = true, fast = false) {
+ return useQuery({
+ queryKey: ["gpu", "paired"],
+ queryFn: () => pairCall<{ paired: PairedComfy[] }>("GET", "/api/gpu/paired"),
+ enabled,
+ refetchInterval: fast ? 2000 : 30_000,
+ });
+}
+
+const factsLine = (f: PairedComfy["facts"]) => [f.device && deviceLabel(f.device), gib(f.vramBytes)].filter(Boolean).join(" · ");
+
+/**
+ * Approve the code a ComfyUI shows (Fuobe Connect's "Connect to Fuobe"): the person sees the computer first, then
+ * approves; the screen waits until that ComfyUI is heard from. `initial`: the code from the link ComfyUI opened.
+ */
+export function PairWithCode({ initial, className }: { initial?: string; className?: string }) {
+ const qc = useQueryClient();
+ const [typed, setTyped] = useState(initial ?? "");
+ const code = pairCode(typed);
+ const [found, setFound] = useState<{ code: string; name: string; facts: PairedComfy["facts"] } | null>(null);
+ const [approved, setApproved] = useState<{ id: string; name: string } | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const paired = usePaired(!!approved, !!approved);
+ const now = useNow(2000);
+ const mine = approved && paired.data?.paired.find((p) => p.id === approved.id);
+ const live = !!mine && pairedOnline(mine, now);
+
+ // A whole code: the computer behind it, for the person to check.
+ useEffect(() => {
+ if (!code || found?.code === code || approved) return;
+ let alive = true;
+ pairCall<{ code: string; name: string; facts: PairedComfy["facts"] }>("GET", `/api/gpu/pair?code=${encodeURIComponent(code)}`).then(
+ (f) => alive && setFound(f),
+ (e: Error) => alive && (setFound(null), setError(e.message)),
+ );
+ return () => {
+ alive = false;
+ };
+ }, [code, found?.code, approved]);
+
+ useEffect(() => {
+ if (!live) return;
+ for (const key of ["account-gpu", "viewer", "status", "settings"]) void qc.invalidateQueries({ queryKey: [key] });
+ }, [live, qc]);
+
+ const answer = async (deny: boolean) => {
+ if (!found) return;
+ setBusy(true);
+ setError(null);
+ try {
+ if (deny) {
+ await pairCall("POST", "/api/gpu/pair", { code: found.code, deny: true });
+ setFound(null);
+ setTyped("");
+ toast("That code won't work now.");
+ } else {
+ const r = await pairCall<{ worker: { id: string; name: string } }>("POST", "/api/gpu/pair", { code: found.code });
+ setApproved(r.worker);
+ }
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (approved)
+ return (
+ <div className={cn("space-y-1 rounded-xl bg-brand-faint p-3 text-[13px]", className)}>
+ {live ? (
+ <p className="flex items-center gap-2 font-medium">
+ <Check className="size-4 text-brand-text" /> {approved.name} is connected. Your runs go there now, even with this page closed.
+ </p>
+ ) : (
+ <p className="flex items-center gap-2 text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" /> Approved. Waiting for {approved.name} to answer…
+ </p>
+ )}
+ </div>
+ );
+ return (
+ <div className={cn("space-y-2", className)}>
+ <label className="flex flex-wrap items-center gap-2 text-[13px]">
+ <KeyRound aria-hidden className="size-4 text-muted-foreground" />
+ <span>The code ComfyUI shows</span>
+ <Input
+ value={typed}
+ onChange={(e) => {
+ setTyped(e.target.value);
+ setError(null);
+ }} placeholder="ABCD-EFGH" autoCapitalize="characters" autoComplete="off" spellCheck={false} className="h-9 w-36 font-mono tracking-widest uppercase" />
+ </label>
+ {found && (
+ <div className="space-y-2 rounded-xl border p-3">
+ <p className="flex items-center gap-2 text-[14px]">
+ <Cpu aria-hidden className="size-4 text-brand-text" /> Run your jobs on <span className="font-medium">{found.name}</span>
+ {factsLine(found.facts) && <span className="text-muted-foreground">· {factsLine(found.facts)}</span>}?
+ </p>
+ <p className="text-[12px] text-muted-foreground">Approve only a code your own ComfyUI shows. That ComfyUI then gets your runs, and nobody else&apos;s.</p>
+ <div className="flex gap-2">
+ <Button size="sm" disabled={busy} onClick={() => void answer(false)}>
+ Approve
+ </Button>
+ <Button size="sm" variant="ghost" disabled={busy} onClick={() => void answer(true)}>
+ Not my computer
+ </Button>
+ </div>
+ </div>
+ )}
+ {error && <p className="text-[12px] text-destructive">{error}</p>}
+ </div>
+ );
+}
+
+/** "Or pair your ComfyUI with a code": for a browser or page that can't reach this computer. */
+export function PairInstead({ className }: { className?: string }) {
+ return (
+ <div className={cn("space-y-2 rounded-xl border bg-background p-3", className)}>
+ <p className="text-[14px] font-medium">Pair your ComfyUI with a code</p>
+ <p className="text-[13px] text-muted-foreground">
+ Install {FUOBE_CONNECT.name} in ComfyUI-Manager (search <Copyable text={FUOBE_CONNECT.search} label="the search term" />), restart ComfyUI, then open
+ <span className="text-foreground"> Extensions → Connect to Fuobe</span>. Enter the code it shows here. Your runs then go to that ComfyUI, with no Fuobe tab open.
+ </p>
+ <PairWithCode />
+ </div>
+ );
+}
+
+/** The ComfyUIs paired with this person, each with Disconnect. Nothing when there are none. */
+export function PairedComfyUIs({ className }: { className?: string }) {
+ const qc = useQueryClient();
+ const q = usePaired();
+ const now = useNow(10_000);
+ const [busy, setBusy] = useState<string | null>(null);
+ const list = q.data?.paired ?? [];
+ if (!list.length) return null;
+ const drop = async (p: PairedComfy) => {
+ setBusy(p.id);
+ try {
+ await pairCall("DELETE", `/api/gpu/paired/${encodeURIComponent(p.id)}`);
+ void qc.invalidateQueries({ queryKey: ["gpu", "paired"] });
+ toast(`${p.name} is disconnected.`);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(null);
+ }
+ };
+ return (
+ <div className={cn("space-y-2", className)}>
+ <p className="text-[13px] font-medium">Paired with Fuobe Connect</p>
+ <ul className="space-y-1.5">
+ {list.map((p) => (
+ <li key={p.id} className="flex items-center gap-2 rounded-lg border px-3 py-2 text-[13px]">
+ <span className={cn("size-2 shrink-0 rounded-full", pairedOnline(p, now) ? "bg-brand-text" : "bg-muted-foreground/40")} aria-hidden />
+ <span className="min-w-0 flex-1 truncate">
+ {p.name}
+ {factsLine(p.facts) && <span className="text-muted-foreground"> · {factsLine(p.facts)}</span>}
+ <span className="text-muted-foreground"> · {pairedOnline(p, now) ? "online" : "offline"}</span>
+ </span>
+ <Button size="sm" variant="ghost" className="h-8" disabled={busy === p.id} onClick={() => void drop(p)}>
+ <Unplug /> Disconnect
+ </Button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/src/components/gpu/this-computer.tsx b/src/components/gpu/this-computer.tsx
index ce83b72a..61e08801 100644
--- a/src/components/gpu/this-computer.tsx
+++ b/src/components/gpu/this-computer.tsx
@@ -11,6 +11,7 @@ import type { ReadinessView } from "@/hooks/use-gpu";
import { copyWithToast } from "@/lib/clipboard";
import { GUARD_FILE_NAME, GUARD_SOURCE, isGuard } from "@/lib/comfy-guard";
import { LIVE_NODES_FILE_NAME, LIVE_NODES_SOURCE } from "@/lib/comfy-live-nodes";
+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";
@@ -18,6 +19,7 @@ import { localBase, statsFacts, typedPort, type SystemStats } from "@/lib/local-
import { madeNoun } from "@/lib/relay";
import { cn } from "@/lib/utils";
import { computerState, rememberComfy, rememberedComfy, restartComputerRunner, store, stored } from "./computer-runtime";
+import { InstallConnect, PairInstead } from "./fuobe-connect";
import { useLocalComfy, type Finder } from "./use-local-comfy";
/**
@@ -156,33 +158,27 @@ export function GuardFix({ port, install = installOf(port) }: { port: number; in
}
/**
- * The fix for the install the person has: a start file, a setting in an app, or a command; and, before it, what the
- * setting does to other websites and the guard that keeps them out. `back`: ComfyUI restarted, still without it.
- * `again`: it had the setting before (started the usual way this time). `others`: more ports where something answers.
+ * 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.
*/
export function SettingFix({ port, back, again, others, onChoose }: { port: number; back: boolean; again?: boolean; others?: number[]; onChoose?: (port: number) => void }) {
- const [install, setInstall] = useState<ComfyInstall>(() => installOf(port));
- const [choosing, setChoosing] = useState(false);
- const [yourself, setYourself] = useState(false);
- const fix = fixFor(install, origin(), port);
+ 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 without the setting yet."
+ ? "ComfyUI is back, but Fuobe can't use it yet."
: again
- ? "ComfyUI is running, but without Fuobe's setting this time."
+ ? "ComfyUI is running, but Fuobe can't use it this time."
: known
- ? "Found ComfyUI. It needs one setting to work with Fuobe."
- : `Something answers on port ${port}. If it's ComfyUI, it needs one setting to work with Fuobe.`;
+ ? "Found ComfyUI. One step to use it here:"
+ : `Something answers on port ${port}. If it's ComfyUI, one step to use it here:`;
return (
<div className="space-y-3">
- <div>
- <p className="text-[15px] font-medium">{heading}</p>
- <p className="mt-1 text-[13px] text-muted-foreground">{fix.lead}</p>
- {back && <p className="mt-1 text-[12px] text-muted-foreground">The address must be exactly {origin()}, with nothing after it.</p>}
- {again && fix.startFile && <p className="mt-1 text-[12px] text-muted-foreground">Next time, start ComfyUI with {START_FILE_NAME} (next to ComfyUI): it has the setting.</p>}
- </div>
+ <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?
@@ -193,6 +189,38 @@ export function SettingFix({ port, back, again, others, onChoose }: { port: numb
))}
</p>
)}
+ <InstallConnect />
+ <Watching>Fuobe connects by itself when ComfyUI is back.</Watching>
+ <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
+ </button>
+ {advanced && (
+ <div className="mt-2 rounded-xl border p-3">
+ <FlagFix port={port} back={back} again={again} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The way before Fuobe Connect: the start setting for the install the person has (a start file, a setting in an app,
+ * or a command), with Fuobe's guard, which keeps other websites out while the setting is on.
+ */
+function FlagFix({ port, back, again }: { port: number; back: boolean; again?: boolean }) {
+ const [install, setInstall] = useState<ComfyInstall>(() => installOf(port));
+ const [choosing, setChoosing] = useState(false);
+ const [yourself, setYourself] = useState(false);
+ const fix = fixFor(install, origin(), port);
+ return (
+ <div className="space-y-3">
+ <div>
+ <p className="text-[13px] text-muted-foreground">{fix.lead}</p>
+ {back && <p className="mt-1 text-[12px] text-muted-foreground">The address must be exactly {origin()}, with nothing after it.</p>}
+ {again && fix.startFile && <p className="mt-1 text-[12px] text-muted-foreground">Next time, start ComfyUI with {START_FILE_NAME} (next to ComfyUI): it has the setting.</p>}
+ </div>
<p className="flex items-start gap-1.5 rounded-lg bg-muted/60 px-2.5 py-2 text-[12px] text-muted-foreground">
<ShieldCheck className="mt-0.5 size-3.5 shrink-0 text-brand-text" />
{fix.startFile
@@ -201,7 +229,7 @@ export function SettingFix({ port, back, again, others, onChoose }: { port: numb
</p>
{fix.startFile ? (
<>
- <Button className="h-11 sm:h-9" onClick={() => save(START_FILE_NAME, startFile(port, origin()))}>
+ <Button size="sm" variant="secondary" onClick={() => save(START_FILE_NAME, startFile(port, origin()))}>
<Download /> Download start file
</Button>
<p className="text-[12px] text-muted-foreground">
@@ -252,7 +280,6 @@ export function SettingFix({ port, back, again, others, onChoose }: { port: numb
</div>
)}
</div>
- <Watching>Fuobe connects by itself when ComfyUI is back.</Watching>
</div>
);
}
@@ -280,7 +307,7 @@ function OtherPort({ onLook, missed }: { onLook: (port: number, host: string) =>
);
}
-type Connected = { port: number; stats: SystemStats; guard: boolean; board?: ReadinessView | null; checkFailed?: boolean };
+type Connected = { port: number; stats: SystemStats; guard: Guarded; board?: ReadinessView | null; checkFailed?: boolean };
function readyLine(board: ReadinessView | null | undefined): string | null {
const studios = board?.report?.studios;
@@ -292,7 +319,7 @@ function readyLine(board: ReadinessView | null | undefined): string | null {
/** The connected screen: the GPU, what's ready, and the run starting (when it was opened from one). */
function Celebration({ c, fromRun, kind, onStart, onNotNow, doneWords }: { c: Connected; fromRun?: boolean; kind?: string; onStart?: () => void; onNotNow?: () => void; doneWords?: string }) {
- const facts = statsFacts(c.stats, origin(), c.guard);
+ const facts = statsFacts(c.stats, origin(), !!c.guard);
const gpu = [facts.device && deviceLabel(facts.device), gib(facts.vramBytes), facts.version && `ComfyUI ${facts.version}`].filter(Boolean).join(" · ");
const ready = readyLine(c.board);
const checked = c.board !== undefined || c.checkFailed;
@@ -331,7 +358,7 @@ function Celebration({ c, fromRun, kind, onStart, onNotNow, doneWords }: { c: Co
</div>
) : c.guard ? (
<p className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
- <ShieldCheck className="size-3.5 text-brand-text" /> Fuobe&apos;s guard keeps other websites out of your ComfyUI.
+ <ShieldCheck className="size-3.5 text-brand-text" /> {c.guard === "connect" ? "Fuobe Connect" : "Fuobe's guard"} keeps other websites out of your ComfyUI.
</p>
) : (
<div className="space-y-1.5 text-[12px]">
@@ -411,12 +438,21 @@ export interface ThisComputerProps {
waitForTap?: boolean;
}
-/** Is Fuobe's guard in this ComfyUI (it answers at /fuobe/guard)? */
-const guardAt = (port: number, host: string) =>
- loopbackFetch(`${localBase(port, host)}/fuobe/guard`, { credentials: "omit", cache: "no-store" }).then(
- (r) => (r.ok ? r.json().then(isGuard, () => false) : false),
- () => false,
- );
+/**
+ * Does this ComfyUI keep other websites out: Fuobe Connect (it answers at /fuobe/connect, and leaves ComfyUI's own check
+ * on for every other site), or Fuobe's guard (at /fuobe/guard)?
+ */
+type Guarded = "connect" | "guard" | false;
+
+const guardAt = async (port: number, host: string): Promise<Guarded> => {
+ const read = (path: string, ok: (a: unknown) => boolean) =>
+ loopbackFetch(`${localBase(port, host)}${path}`, { credentials: "omit", cache: "no-store" }).then(
+ (r) => (r.ok ? r.json().then(ok, () => false) : false),
+ () => false,
+ );
+ if (await read("/fuobe/connect", isConnectAnswer)) return "connect";
+ return (await read("/fuobe/guard", isGuard)) ? "guard" : false;
+};
/** The whole flow, from "Find my ComfyUI" to connected. */
export function ThisComputer({ connect, fromRun, kind, onStart, onNotNow, autoLook, again, doneWords, lookNow, waitForTap }: ThisComputerProps) {
@@ -519,13 +555,17 @@ function Screen({ state, look, choose, again, asks }: { state: Finder; look: Ret
switch (state.s) {
case "unsupported":
return (
- <p className="flex items-start gap-2 text-muted-foreground">
- <MonitorSmartphone className="mt-0.5 size-4 shrink-0" /> {UNSUPPORTED[state.why]}
- </p>
+ <div className="space-y-3">
+ <p className="flex items-start gap-2 text-muted-foreground">
+ <MonitorSmartphone className="mt-0.5 size-4 shrink-0" /> {UNSUPPORTED[state.why]}
+ </p>
+ <PairInstead />
+ </div>
);
case "start":
return (
<div className="space-y-3">
+ <InstallConnect then="Already have it? Skip this step." />
<Button className="h-11 sm:h-9" onClick={() => void look()}>
<Search /> Find my ComfyUI
</Button>
@@ -578,6 +618,7 @@ function Screen({ state, look, choose, again, asks }: { state: Finder; look: Ret
<Button size="sm" variant="secondary" onClick={() => window.location.reload()}>
<RefreshCw /> Reload
</Button>
+ <PairInstead className="mt-2" />
</div>
);
}
diff --git a/src/lib/fuobe-connect.ts b/src/lib/fuobe-connect.ts
new file mode 100644
index 00000000..ca2c9333
--- /dev/null
+++ b/src/lib/fuobe-connect.ts
@@ -0,0 +1,39 @@
+/**
+ * Fuobe Connect: the ComfyUI custom node pack (integrations/fuobe-connect) that lets this page use the ComfyUI on the
+ * person's computer with one install, and can pair a ComfyUI with their account instead (for Safari, phones and PCs
+ * with no screen). What the "Connect your GPU" screens say about it. Pure.
+ */
+
+export const FUOBE_CONNECT = {
+ name: "Fuobe Connect",
+ /** What to type in ComfyUI-Manager's Custom Nodes Manager. */
+ search: "Fuobe Connect",
+ /** For "Install via Git URL", or a git clone in ComfyUI's custom_nodes folder. */
+ gitUrl: "https://github.com/workingprototype/ComfyUI-Fuobe-Connect",
+ /** The studios it trusts when the person names none. */
+ defaultStudios: ["https://fuobe.com", "https://www.fuobe.com"],
+} as const;
+
+/** Does Fuobe Connect trust this page's origin without a setting? (A self-hosted studio has to be added.) */
+export const trustedByDefault = (origin: string): boolean => (FUOBE_CONNECT.defaultStudios as readonly string[]).includes(origin.replace(/\/+$/, ""));
+
+/** Its answer at GET /fuobe/connect. */
+export const isConnectAnswer = (answer: unknown): boolean => !!answer && typeof answer === "object" && Number((answer as { connect?: unknown }).connect) >= 1;
+
+/** "abcd efgh" → "ABCD-EFGH" as the person types it (null until it is a whole code). */
+export function pairCode(input: string): string | null {
+ const s = input.toUpperCase().replace(/[\s-]/g, "");
+ return /^[A-HJKMNP-Z2-9]{8}$/.test(s) ? `${s.slice(0, 4)}-${s.slice(4)}` : null;
+}
+
+/** One ComfyUI paired with this person, as /api/gpu/paired lists it. */
+export interface PairedComfy {
+ id: string;
+ name: string;
+ createdAt: number;
+ lastUsedAt: number | null;
+ facts: { device?: string; vramBytes?: number; version?: string };
+}
+
+/** Heard from in the last minute. */
+export const pairedOnline = (p: Pick<PairedComfy, "lastUsedAt">, now: number): boolean => !!p.lastUsedAt && now - p.lastUsedAt < 60_000;
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index ab0da6b0..f046f23b 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -270,7 +270,7 @@ export const RELAY_WORDS = {
waitedTooLong: (ms: number) => `Fuobe couldn't reach your computer for ${duration(ms)}. Open Fuobe there, then press Retry.`,
computerSilent: "Your computer stopped answering. If ComfyUI finished, open Fuobe there and press Retry.",
comfyDown: "ComfyUI isn't answering. Start it again, and Fuobe goes on by itself.",
- comfyNoSetting: "ComfyUI is running without Fuobe's setting. Fuobe goes on once it has it.",
+ comfyNoSetting: "ComfyUI is running, but Fuobe can't use it yet. Install Fuobe Connect in ComfyUI, and Fuobe goes on by itself.",
comfyDownTooLong: "ComfyUI didn't come back within 30 minutes. Start it, then press Retry.",
resent: "ComfyUI restarted, so Fuobe sent it again",
lost: "ComfyUI restarted and lost this run. Press Retry.",
diff --git a/tests/e2e/computer-mode.mjs b/tests/e2e/computer-mode.mjs
index a380cebe..7c95af1e 100644
--- a/tests/e2e/computer-mode.mjs
+++ b/tests/e2e/computer-mode.mjs
@@ -45,7 +45,7 @@ async function until(fn, ms = 30_000, every = 250) {
// model the studio's workflows need, so the GPU check finds the tools ready.
let fakeProc = null;
async function startFake(cors, o = {}) {
- const args = ["--port", String(FAKE_PORT), "--cors", cors, "--steps", "8", "--step-ms", "300", "--has", path.join(root, "workflows/comfyui/requirements.json"), ...(o.guard ? ["--guard", "1"] : [])];
+ const args = ["--port", String(FAKE_PORT), "--cors", cors, "--steps", "8", "--step-ms", "300", "--has", path.join(root, "workflows/comfyui/requirements.json"), ...(o.guard ? ["--guard", "1"] : []), ...(o.connect ? ["--connect", o.connect] : [])];
fakeProc = spawn(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", path.join(root, "tests/helpers/fake-local-comfy.ts"), ...args], { stdio: ["ignore", "pipe", "inherit"] });
await until(() => fetch(`${FAKE}/__fake/stats`).then((r) => r.ok), 15_000);
}
@@ -158,10 +158,13 @@ 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("It needs one setting to work with Fuobe").waitFor({ timeout: 20_000 });
- check("ComfyUI without the setting: the one setting it needs", true);
- check("the fix says what the setting does to other websites, and that Fuobe's guard turns them away, before the download", await dialog.getByText(/other websites send work to your ComfyUI\. The start file adds Fuobe's guard/).isVisible());
+ await dialog.getByText("Found ComfyUI. One step to use it here:").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").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()));
await page.screenshot({ path: path.join(shots, "2-needs-setting.png") });
+ await dialog.getByRole("button", { name: /Advanced: a start setting instead/ }).click();
+ check("Advanced: what the setting does to other websites, and that Fuobe's guard turns them away, before the download", await dialog.getByText(/other websites send work to your ComfyUI\. The start file adds Fuobe's guard/).isVisible());
const startButton = dialog.getByRole("button", { name: "Download start file" });
if (await startButton.isVisible()) {
const [dl] = await Promise.all([page.waitForEvent("download"), startButton.click()]);
@@ -180,9 +183,10 @@ try {
await stopFake();
const waited = await until(() => dialog.getByText("Waiting for ComfyUI to start").isVisible(), 10_000);
check("ComfyUI restarting: waiting for it, by itself", !!waited);
- await startFake(SITE, { guard: true });
+ // ComfyUI comes back with Fuobe Connect installed (no start setting): it connects by itself.
+ await startFake("off", { connect: SITE });
await dialog.getByText("Your GPU is connected").waitFor({ timeout: 30_000 });
- check("the connected screen says Fuobe's guard keeps other websites out", await dialog.getByText("Fuobe's guard keeps other websites out of your ComfyUI.").isVisible());
+ check("the connected screen says Fuobe Connect keeps other websites out", await dialog.getByText("Fuobe Connect keeps other websites out of your ComfyUI.").isVisible());
check("nothing on the connected screen leads away from the run that's about to start", (await dialog.getByRole("link", { name: "See them" }).count()) === 0);
check("connected by itself, with no click", true);
check("the GPU is named", await dialog.getByText(/RTX 5090/).first().isVisible());
@@ -303,7 +307,7 @@ try {
const card = page.getByRole("dialog");
const opened = await until(() => card.getByText("Your ComfyUI needs Fuobe's setting again").isVisible(), 40_000);
check("ComfyUI without the setting on a later visit: the card with its fix opens by itself", !!opened);
- check("the card shows the fix for it", !!(await until(() => card.getByText(/without Fuobe's setting this time/).first().isVisible(), 15_000)));
+ check("the card shows the fix for it", !!(await until(() => card.getByText(/Fuobe can't use it this time/).first().isVisible(), 15_000)));
await page.screenshot({ path: path.join(shots, "7-setting-again.png") });
const seen = new Set();
for (let end = Date.now() + 12_000; Date.now() < end; await sleep(250)) {
@@ -312,7 +316,7 @@ try {
}
check("the note says the setting is missing, steadily, with its fix", seen.size > 0 && [...seen].every((t) => t.includes("without Fuobe's setting") && t.includes("Show me how")), [...seen].join(" | "));
const waiting = (await runs(page)).find((g) => g.id === rid);
- check("the run says the same", waiting?.message === "ComfyUI is running without Fuobe's setting. Fuobe goes on once it has it.", waiting?.message);
+ check("the run says the same", waiting?.message === "ComfyUI is running, but Fuobe can't use it yet. Install Fuobe Connect in ComfyUI, and Fuobe goes on by itself.", waiting?.message);
check("the status strip doesn't say all is well", !!(await until(() => page.getByText("needs a setting").first().isVisible(), 15_000)));
await stopFake();
await startFake(SITE, { guard: true });
diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.ts
index 8d49b981..8f1749b0 100644
--- a/tests/helpers/fake-local-comfy.ts
+++ b/tests/helpers/fake-local-comfy.ts
@@ -46,6 +46,11 @@ export interface LocalComfyOptions {
loras?: string[];
/** Fuobe's guard is in its custom nodes (it answers GET /fuobe/guard). */
guard?: boolean;
+ /**
+ * Fuobe Connect is in its custom nodes, trusting this origin: that origin gets CORS (with no start setting), every
+ * other site still meets ComfyUI's own check, and GET /fuobe/connect answers.
+ */
+ connect?: string;
/**
* Everything a requirement index names is installed (the studio's workflows/comfyui/requirements.json): its node
* classes, with the loaders listing its files, and its model files. Without it, this ComfyUI has nothing.
@@ -402,7 +407,10 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
const entry: LocalComfyLog = { method: req.method ?? "GET", path: url.pathname + url.search, at: Date.now(), ...(origin && { origin }) };
log.push(entry);
const headers: Record<string, string> = {};
- if (opts.cors !== "off") {
+ if (opts.cors === "off" && opts.connect && origin === opts.connect) {
+ Object.assign(headers, { "Access-Control-Allow-Origin": opts.connect, Vary: "Origin", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "content-type" });
+ if (req.headers["access-control-request-private-network"] === "true") headers["Access-Control-Allow-Private-Network"] = "true";
+ } else if (opts.cors !== "off") {
Object.assign(headers, {
"Access-Control-Allow-Origin": opts.cors,
"Access-Control-Allow-Methods": "POST, GET, DELETE, PUT, OPTIONS, PATCH",
@@ -439,6 +447,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
// No list given: an older ComfyUI without the route (the run goes ahead, and ComfyUI has the last word).
if (p === "/models/loras") return opts.loras ? reply(200, opts.loras) : reply(404, { error: "not found" });
if (p === "/fuobe/guard") return opts.guard ? reply(200, { guard: 1 }) : reply(404, { error: "not found" });
+ if (p === "/fuobe/connect") return opts.connect ? reply(200, { connect: 1, version: "1.0.0", guard: 1 }) : reply(404, { error: "not found" });
const has = opts.has ? installed(opts.has) : null;
const liveNodes = !!has?.info.SaveImageFuobeLive && !opts.noLiveNodes;
if (p === "/fuobe/live") return liveNodes ? reply(200, opts.oldLiveNodes ? { version: 1 } : { version: LIVE_NODES_VERSION, sha256: LIVE_NODES_SHA256 }) : reply(404, { error: "not found" });
@@ -691,6 +700,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
// Run on its own: node tests/helpers/fake-local-comfy.ts --port 3371 --cors http://127.0.0.1:3370
// [--has workflows/comfyui/requirements.json]: everything that index names is installed. [--guard 1]: Fuobe's guard answers.
+// [--connect <origin>]: Fuobe Connect is installed, trusting that origin.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
@@ -698,6 +708,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
};
const index = arg("has");
const has = index ? (JSON.parse(readFileSync(index, "utf8")) as IndexLike) : undefined;
- const fake = await startLocalComfy({ cors: arg("cors") ?? "off", steps: Number(arg("steps") ?? 8), stepMs: Number(arg("step-ms") ?? 250), portable: arg("portable") === "1", guard: arg("guard") === "1", has }, Number(arg("port") ?? 3371));
+ const fake = await startLocalComfy({ cors: arg("cors") ?? "off", steps: Number(arg("steps") ?? 8), stepMs: Number(arg("step-ms") ?? 250), portable: arg("portable") === "1", guard: arg("guard") === "1", ...(arg("connect") && { connect: arg("connect") }), has }, Number(arg("port") ?? 3371));
console.log(`fake ComfyUI on ${fake.url} (cross-site setting: ${fake.opts.cors})`);
}
diff --git a/tests/workers-pairing.test.ts b/tests/workers-pairing.test.ts
new file mode 100644
index 00000000..dc1ef0cb
--- /dev/null
+++ b/tests/workers-pairing.test.ts
@@ -0,0 +1,225 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-workers-pairing-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+
+const auth = await import("@/server/auth");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { getSetting, setSetting } = await import("@/server/settings");
+const workers = await import("@/server/computer/workers");
+const { principalOf, requestWorker } = await import("@/server/computer/http");
+const { proxy } = await import("@/proxy");
+const pairRoute = await import("@/app/api/gpu/pair/route");
+const startRoute = await import("@/app/api/gpu/pair/start/route");
+const pollRoute = await import("@/app/api/gpu/pair/poll/route");
+const pairedRoute = await import("@/app/api/gpu/paired/route");
+const pairedIdRoute = await import("@/app/api/gpu/paired/[id]/route");
+const unpairRoute = await import("@/app/api/gpu/computer/unpair/route");
+const tasks = await import("@/server/computer/tasks");
+const { accountMayChange, accountOwnRead } = await import("@/lib/guest-access");
+const { pairCode, trustedByDefault, isConnectAnswer } = await import("@/lib/fuobe-connect");
+
+const HOST = "localhost:3000";
+const SITE = `http://${HOST}`;
+let a = "";
+let b = "";
+const cookies: Record<string, string> = {};
+
+const browser = (who: string, url: string, init: RequestInit = {}) =>
+ new Request(`${SITE}${url}`, { ...init, headers: { host: HOST, cookie: cookies[who], origin: SITE, "sec-fetch-site": "same-origin", "content-type": "application/json", ...(init.headers ?? {}) } });
+const program = (url: string, token?: string, init: RequestInit = {}) =>
+ new Request(`${SITE}${url}`, { method: "POST", ...init, headers: { host: HOST, "content-type": "application/json", ...(token && { authorization: `Bearer ${token}` }), ...(init.headers ?? {}) } });
+
+/** Pair a ComfyUI for `who` through the routes, as Fuobe Connect and the person's browser do. */
+async function pair(who: string, name = "pc") {
+ const s = await (await startRoute.POST(program("/api/gpu/pair/start", undefined, { body: JSON.stringify({ name, facts: { device: "cuda:0 Test", vramBytes: 7 } }) }))).json();
+ const ok = await pairRoute.POST(browser(who, "/api/gpu/pair", { method: "POST", body: JSON.stringify({ code: s.code }) }));
+ expect(ok.status).toBe(200);
+ const p = await (await pollRoute.POST(program("/api/gpu/pair/poll", undefined, { body: JSON.stringify({ id: s.id, secret: s.secret }) }))).json();
+ expect(p.state).toBe("approved");
+ return { token: p.token as string, id: p.workerId as string, code: s.code as string, secret: s.secret as string, pairId: s.id as string };
+}
+
+beforeAll(() => {
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ b = auth.createAccount("[email protected]", "long enough").id;
+ cookies.a = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+ cookies.b = `${auth.SESSION_COOKIE}=${auth.createSession(b).value}`;
+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+});
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("DELETE FROM relay_pairings").run();
+});
+
+describe("pairing a ComfyUI", () => {
+ it("gives a short code and a link, and nothing else until a person approves", async () => {
+ const res = await startRoute.POST(program("/api/gpu/pair/start", undefined, { body: JSON.stringify({ name: "My PC <script>", facts: { device: "x", loras: ["a"] } }) }));
+ const s = await res.json();
+ expect(s.code).toMatch(/^[A-HJKMNP-Z2-9]{4}-[A-HJKMNP-Z2-9]{4}$/);
+ // The studio's own address, as the request reached it.
+ expect(s.url).toBe(`${SITE}/connect?code=${s.code}`);
+ expect(s.secret).toMatch(/^[0-9a-f]{64}$/);
+ const p = await (await pollRoute.POST(program("/api/gpu/pair/poll", undefined, { body: JSON.stringify({ id: s.id, secret: s.secret }) }))).json();
+ expect(p.state).toBe("waiting");
+ // The wrong secret learns nothing.
+ const wrong = await pollRoute.POST(program("/api/gpu/pair/poll", undefined, { body: JSON.stringify({ id: s.id, secret: "0".repeat(64) }) }));
+ expect(wrong.status).toBe(404);
+ const look = await (await pairRoute.GET(browser("a", `/api/gpu/pair?code=${s.code.toLowerCase().replace("-", " ")}`))).json();
+ expect(look.name).toBe("My PC script");
+ expect(look.facts).toEqual({ device: "x" });
+ });
+
+ it("approval needs a signed-in person in a browser, never a token", async () => {
+ const s = workers.startPairing({ name: "pc" });
+ const guest = await pairRoute.POST(new Request(`${SITE}/api/gpu/pair`, { method: "POST", headers: { host: HOST, "content-type": "application/json" }, body: JSON.stringify({ code: s.code }) }));
+ expect(guest.status).toBe(401);
+ const { token } = auth.createToken("script");
+ const tok = await pairRoute.POST(new Request(`${SITE}/api/gpu/pair`, { method: "POST", headers: { host: HOST, authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ code: s.code }) }));
+ expect(tok.status).toBe(403);
+ });
+
+ it("delivers the token once, only its hash is kept, and the account's GPU becomes its computer", async () => {
+ auth.setAccountGpu(a, null);
+ const p = await pair("a");
+ expect(p.token).toMatch(/^fuobe_wkr_[A-Za-z0-9_-]{43}$/);
+ expect(auth.accountGpu(a)?.mode).toBe("computer");
+ const rows = JSON.stringify(db().prepare("SELECT * FROM relay_workers").all()) + JSON.stringify(db().prepare("SELECT * FROM relay_pairings").all());
+ expect(rows).not.toContain(p.token);
+ const again = await pollRoute.POST(program("/api/gpu/pair/poll", undefined, { body: JSON.stringify({ id: p.pairId, secret: p.secret }) }));
+ expect(again.status).toBe(404);
+ const reuse = await pairRoute.POST(browser("b", "/api/gpu/pair", { method: "POST", body: JSON.stringify({ code: p.code }) }));
+ expect(reuse.status).toBe(404);
+ });
+
+ it("an expired or denied code can't be approved", async () => {
+ const old = workers.startPairing({ name: "pc" }, Date.now() - workers.PAIR_MS - 1000);
+ expect(workers.approvePairing(old.code, `acct:${a}`)).toBeNull();
+ const s = workers.startPairing({ name: "pc" });
+ expect(workers.denyPairing(s.code)).toBe(true);
+ expect(workers.approvePairing(s.code, `acct:${a}`)).toBeNull();
+ expect(workers.pollPairing(s.id, s.secret).state).toBe("gone");
+ });
+
+ it("the owner can pair too: ComfyUI then runs on the owner's computer", async () => {
+ setSetting("comfyWhere", "server");
+ const p = await pair("owner");
+ expect(getSetting("comfyWhere")).toBe("computer");
+ const req = program("/api/gpu/computer/beat", p.token);
+ expect(principalOf(req)).toBe("owner");
+ expect(requestWorker(req)?.id).toBe(p.id);
+ setSetting("comfyWhere", "server");
+ });
+
+ it("codes are case- and dash-blind", () => {
+ expect(pairCode("abcd efgh")).toBe("ABCD-EFGH");
+ expect(pairCode("abcd-efg")).toBeNull();
+ expect(pairCode("ABCD-EFG1")).toBeNull();
+ expect(workers.normaliseCode("abcdefgh")).toBe("ABCD-EFGH");
+ });
+});
+
+describe("a paired ComfyUI's token", () => {
+ it("acts only as its own person's computer", async () => {
+ const pa = await pair("a");
+ const pb = await pair("b");
+ expect(principalOf(program("/api/gpu/computer/claim", pa.token))).toBe(`acct:${a}`);
+ expect(principalOf(program("/api/gpu/computer/claim", pb.token))).toBe(`acct:${b}`);
+ // A's waiting task never reaches B's ComfyUI.
+ db().prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES ('g-a', 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)").run(JSON.stringify({ account: a }), Date.now(), Date.now());
+ tasks.createTask({ principal: `acct:${a}`, generationId: "g-a", graph: { "1": { class_type: "SaveImage", inputs: {} } } });
+ tasks.beat(`acct:${b}`, { device: "connect-bobpc01", ready: true });
+ expect(tasks.claim(`acct:${b}`, "connect-bobpc01", [])).toBeNull();
+ tasks.beat(`acct:${a}`, { device: "connect-alice01", ready: true });
+ expect(tasks.claim(`acct:${a}`, "connect-alice01", [])?.generationId).toBe("g-a");
+ });
+
+ it("is never the owner, and reaches no route but the computer's", async () => {
+ const p = await pair("a");
+ expect(auth.validToken(`Bearer ${p.token}`)).toBe(false);
+ const other = proxy(new NextRequest(`${SITE}/api/settings`, { headers: { host: HOST, authorization: `Bearer ${p.token}` } }));
+ expect(other.status).toBe(403);
+ const own = proxy(new NextRequest(`${SITE}/api/gpu/computer/beat`, { method: "POST", headers: { host: HOST, authorization: `Bearer ${p.token}` } }));
+ expect(own.headers.get("x-middleware-next")).toBe("1");
+ // A made-up worker token is no token.
+ const fake = principalOf(program("/api/gpu/computer/beat", `fuobe_wkr_${"A".repeat(43)}`));
+ expect((fake as Response).status).toBe(401);
+ });
+
+ it("an owner API token can't act as a worker", async () => {
+ const { token } = auth.createToken("script");
+ const r = principalOf(program("/api/gpu/computer/beat", token));
+ expect((r as Response).status).toBe(403);
+ });
+
+ it("stops at its next call when the person disconnects it, or it disconnects itself", async () => {
+ const p = await pair("a");
+ const list = await (await pairedRoute.GET(browser("a", "/api/gpu/paired"))).json();
+ expect(list.paired.map((x: { id: string }) => x.id)).toEqual([p.id]);
+ expect((await (await pairedRoute.GET(browser("b", "/api/gpu/paired"))).json()).paired).toEqual([]);
+ // B can't disconnect A's.
+ const notYours = await pairedIdRoute.DELETE(browser("b", `/api/gpu/paired/${p.id}`, { method: "DELETE" }), { params: Promise.resolve({ id: p.id }) });
+ expect(notYours.status).toBe(404);
+ const gone = await pairedIdRoute.DELETE(browser("a", `/api/gpu/paired/${p.id}`, { method: "DELETE" }), { params: Promise.resolve({ id: p.id }) });
+ expect(gone.status).toBe(200);
+ expect((principalOf(program("/api/gpu/computer/beat", p.token)) as Response).status).toBe(401);
+ const q = await pair("a");
+ expect((await unpairRoute.POST(program("/api/gpu/computer/unpair", q.token))).status).toBe(200);
+ expect((principalOf(program("/api/gpu/computer/beat", q.token)) as Response).status).toBe(401);
+ });
+
+ it("follows the person's own setting: a link-mode GPU, a disabled account or sign-up turned off stop it", async () => {
+ const p = await pair("a");
+ auth.setAccountGpu(a, { url: "https://gpu.example.com" });
+ expect((principalOf(program("/api/gpu/computer/beat", p.token)) as Response).status).toBe(409);
+ auth.setAccountGpu(a, { mode: "computer" });
+ auth.setAccountDisabled(a, true);
+ expect((principalOf(program("/api/gpu/computer/beat", p.token)) as Response).status).toBe(401);
+ auth.setAccountDisabled(a, false);
+ process.env.FUOBE_PUBLIC_SIGNUP = "0";
+ expect((principalOf(program("/api/gpu/computer/beat", p.token)) as Response).status).toBe(401);
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ expect(principalOf(program("/api/gpu/computer/beat", p.token))).toBe(`acct:${a}`);
+ });
+
+ it("goes with a deleted account", async () => {
+ const p = await pair("b");
+ tasks.purgeComputer(`acct:${b}`);
+ expect(workers.getWorker(p.id)).toBeNull();
+ });
+});
+
+describe("paths", () => {
+ it("accounts may pair and list their own; the start and poll calls are open", () => {
+ expect(accountOwnRead("/api/gpu/pair")).toBe(true);
+ expect(accountOwnRead("/api/gpu/paired")).toBe(true);
+ expect(accountMayChange("POST", "/api/gpu/pair", "")).toBe(true);
+ expect(accountMayChange("DELETE", "/api/gpu/paired/abc", "")).toBe(true);
+ const start = proxy(new NextRequest(`${SITE}/api/gpu/pair/start`, { method: "POST", headers: { host: HOST } }));
+ expect(start.headers.get("x-middleware-next")).toBe("1");
+ });
+
+ it("Fuobe Connect's words", () => {
+ expect(trustedByDefault("https://fuobe.com/")).toBe(true);
+ expect(trustedByDefault("https://studio.example.com")).toBe(false);
+ expect(isConnectAnswer({ connect: 1 })).toBe(true);
+ expect(isConnectAnswer({ guard: 1 })).toBe(false);
+ });
+});