The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Your GPU: the owner's ComfyUI on a hosted studio is never called at a local address
Adarsh7a3d4bec485e
diff --git a/src/app/api/account/gpu/route.ts b/src/app/api/account/gpu/route.tsindex b0fc551f..4e5382c5 100644--- a/src/app/api/account/gpu/route.ts+++ b/src/app/api/account/gpu/route.ts@@ -1,10 +1,10 @@import { connection } from "next/server";import { z } from "zod";-import { checkGpuAddress, GpuError, testGpu } from "@/server/account-gpu";+import { checkGpuAddress, computerView, GpuError, testGpu } from "@/server/account-gpu";import { accountGpu, gpuLink, requestAccount, setAccountGpu } from "@/server/auth";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "@/server/account-files";import { clearAccountLoras } from "@/server/account-loras";-import { forgetComputer, runnerFacts } from "@/server/computer/tasks";+import { forgetComputer } from "@/server/computer/tasks";import { dropSnapshots } from "@/server/gpu/snapshots";import { hit } from "@/server/rate";@@ -20,27 +20,14 @@ const account = async (request: Request) => requestAccount(request);const notAccount = () => Response.json({ error: "Your GPU is for accounts. The studio's own ComfyUI is in Settings → Open-source engine." }, { status: 400 });/** What a computer's tab last said: its GPU, memory, ComfyUI version and port, and whether it is open now. */-function computerView(id: string) {- const f = runnerFacts(`acct:${id}`);- return {- mode: "computer" as const,- online: !!f?.online,- ...(f?.comfy && { comfy: f.comfy }),- ...(f?.guard !== undefined && { guard: f.guard }),- ...(f?.device && { device: f.device }),- ...(f?.vramBytes && { vramBytes: f.vramBytes }),- ...(f?.version && { version: f.version }),- ...(f?.port && { port: f.port }),- ...(f?.cors && { cors: f.cors }),- };-}+const accountComputer = (id: string) => computerView(`acct:${id}`);export async function GET(request: Request) {await connection();const a = await account(request);if (!a) return notAccount();const gpu = accountGpu(a.id);- if (gpu?.mode === "computer") return Response.json({ gpu: computerView(a.id) });+ if (gpu?.mode === "computer") return Response.json({ gpu: accountComputer(a.id) });const link = gpuLink(gpu);return Response.json({ gpu: link ? { mode: "link", url: link.url, hasToken: !!link.token } : null });}@@ -63,7 +50,7 @@ export async function PUT(request: Request) {clearAccountLoras(a.id);dropSnapshots(`acct:${a.id}`);}- return Response.json({ gpu: computerView(a.id) });+ return Response.json({ gpu: accountComputer(a.id) });}const body = parsed.data as { url: string; token?: string };try {diff --git a/src/app/api/comfyui/route.ts b/src/app/api/comfyui/route.tsindex d0bb3032..303f93ac 100644--- a/src/app/api/comfyui/route.ts+++ b/src/app/api/comfyui/route.ts@@ -1,16 +1,43 @@import { connection } from "next/server";+import { basename } from "@/lib/gpu/requirements";import { requestViewer } from "@/server/auth";+import { runnerFacts } from "@/server/computer/tasks";+import { readSnapshot } from "@/server/gpu/snapshots";import { loadManifest, modelInventory, probeComfy } from "@/server/providers/comfyui";+import { getSetting } from "@/server/settings";/*** Workflow library + which required models are present on the connected server. A guest or an account (public* sign-up) gets the library only: the studio's own ComfyUI is neither asked nor described to them (its files* aren't theirs, and an open read would let anyone make the studio's GPU answer). Their own GPU is on /connect.+ * When the owner's ComfyUI runs on the owner's computer, nothing is asked from here: whether it is online is what the+ * owner's Fuobe tab there last said, and the models are from the last check that tab sent in (`where: "computer"`,+ * `checkedAt`; none yet: every `present` is null).*/export async function GET(request?: Request) {await connection();const manifest = loadManifest();const visitor = !!request && requestViewer(request).kind !== "owner";+ if (!visitor && getSetting("comfyWhere") === "computer") {+ const snap = readSnapshot({ kind: "computer", key: "install", via: "browser" });+ const inv = snap?.inventory.reachable ? snap.inventory : null;+ // Folder → the file names that check found there (as the index names them, compared without case).+ const has = (folder: string, file: string): boolean | null => {+ const f = inv?.models[folder];+ if (!f) return null;+ if (f.folderMissing) return false;+ const want = basename(file).toLowerCase();+ return Object.keys(f.have).some((n) => basename(n).toLowerCase() === want);+ };+ return Response.json({+ reachable: !!runnerFacts("owner")?.online,+ where: "computer",+ checkedAt: inv ? snap!.checkedAt : null,+ generatedAt: manifest.generatedAt,+ comfyuiCommit: manifest.comfyuiCommit,+ workflows: manifest.workflows.map((w) => ({ ...w, models: w.models.map((m) => ({ ...m, present: has(m.folder, m.file) })) })),+ });+ }const reachable = visitor ? null : await probeComfy(true);const inventory = reachable ? await modelInventory() : null;const present = new Set(Object.values(inventory ?? {}).flat());diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 445e1614..ed17ef56 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -2,13 +2,16 @@ import { connection } from "next/server";import { CONNECT_GPU_HEADER, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";import { missingFilesMessage } from "@/lib/missing-files";import { ADD_KEY_HEADER } from "@/lib/your-keys";-import { requestViewer } from "@/server/auth";+import { requestViewer, validToken } from "@/server/auth";import { accountEngineMode } from "@/server/account-keys";+import { computerScope, ISOLATED_ON_COMPUTER, workerFor } from "@/server/providers/comfyui";+import { getSetting } from "@/server/settings";+import { RUNS_ON_COMPUTER_NOTE } from "@/lib/relay";import { OPERATION_LABELS } from "@/lib/catalog/types";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { accountInputProblem } from "@/server/account-inputs";import { db } from "@/server/db";-import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, createGenerations, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";+import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, ConnectComfyError, createGenerations, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";import { ensureTrashPurge, listOptionsFrom } from "@/server/library";import { hit, unhit } from "@/server/rate";import { GenerationRequestSchema } from "@/server/request-schema";@@ -50,6 +53,8 @@ const refuse = (status: number, error: string, extra: Record<string, unknown> =/** Start a generation; `?preview=1` only says what it would run as (model, operation, jobs, outputs, cost). */export async function POST(request: Request) {const viewer = requestViewer(request);+ // An API token (a script, the CLI, MCP): never a page that can open a dialog or keep a tab open.+ const token = validToken(request.headers.get("authorization"));const account = viewer.kind === "account" ? viewer.account : null;const preview = new URL(request.url).searchParams.get("preview") === "1";// Without a viewer only a price check: a run is the owner's or an account's, never "nobody, so the owner".@@ -128,6 +133,12 @@ export async function POST(request: Request) {if ("error" in own) return refused(own);}if (planned) {+ // A workflow for the isolated worker (LatentSync 1.6, ThinkSound) on someone's computer: its tab reaches no second+ // ComfyUI yet. Said now, before anything is staged or queued.+ if (planned.route.provider === "comfyui" && workerFor(planned.route.endpoint) === "isolated" && onOwn(() => computerScope())) {+ if (account) unhit(`run:${account.id}`);+ return refuse(422, ISOLATED_ON_COMPUTER, { code: "isolated-on-computer" });+ }// A 3D model from someone else's ComfyUI is finished on this server (decimate, web GLB, turntable): accounts// don't get Image to 3D until that finish runs under an account's own limits.if (account && outputKind(planned.op, planned.model) === "model3d") {@@ -159,6 +170,8 @@ export async function POST(request: Request) {return refuse(429, ACCOUNT_MESSAGES.activeRuns, {}, { "Retry-After": "30" });}const items = onOwn(() => createGenerations(req));+ // A script's open-source run while ComfyUI is on the owner's computer: it waits for the owner's Fuobe tab there.+ if (viewer.kind === "owner" && token && getSetting("comfyWhere") === "computer" && items.some((g) => g.provider === "comfyui")) notes.push(RUNS_ON_COMPUTER_NOTE);// What the run leaves out or changes (a model that replaced a retired one, a LoRA that runs only on a GPU, a length the API rounds).const all = [...new Set([...notes, ...items.flatMap((g) => g.notes ?? [])])];return Response.json({ items, ...(all.length && { notes: all }), ...(gpuWarning && { gpuWarning }) }, { status: 201 });@@ -167,6 +180,12 @@ export async function POST(request: Request) {// A price check of a paid model the account has no key for says so, without opening "Add your key".if (refusal && !preview) return refused(refusal);if (account && !preview) unhit(`run:${account.id}`);- return Response.json({ error: (e as Error).message, ...(refusal && { code: refusal.code, ...(refusal.provider && { provider: refusal.provider }) }) }, { status: 422 });+ // Nothing connected runs this, and ComfyUI could: the owner's own browser (never a script's token) opens "Connect+ // your GPU" for it, and the run starts once it is connected.+ const connect = e instanceof ConnectComfyError && viewer.kind === "owner" && !preview && !token;+ return Response.json(+ { error: (e as Error).message, ...(refusal && { code: refusal.code, ...(refusal.provider && { provider: refusal.provider }) }), ...(connect && { code: "connect-gpu" }) },+ { status: 422, ...(connect && { headers: { [CONNECT_GPU_HEADER]: "1" } }) },+ );}}diff --git a/src/app/api/providers/test/route.ts b/src/app/api/providers/test/route.tsindex 59206797..31f1d059 100644--- a/src/app/api/providers/test/route.ts+++ b/src/app/api/providers/test/route.ts@@ -2,6 +2,7 @@ import { candidateValues, isTestProvider, PROVIDER_SETTINGS, settingProblem } frimport { testCivitaiKey } from "@/server/loras";import { testAiToolkit } from "@/server/training";import { PROVIDERS } from "@/server/providers";+import { hostedAddressRefusal } from "@/server/providers/comfy-address";import { validateSetting, withCandidates, type SettingName } from "@/server/settings";/**@@ -9,10 +10,11 @@ import { validateSetting, withCandidates, type SettingName } from "@/server/sett* name), the test runs with those unsaved values instead of the saved ones, so Settings can check a* key or an address before saving it. `field` names the setting being checked (else the first* unsaved one), so a provider that reaches several servers tests that one: the Anthropic key is- * checked with Anthropic even when text steps run on Ollama. Nothing is stored here.+ * checked with Anthropic even when text steps run on Ollama. Nothing is stored here. `place: "hosted"` (the page isn't+ * on this server's machine) refuses a ComfyUI address on this machine or its network without calling it.*/export async function POST(request: Request) {- const body = (await request.json().catch(() => ({}))) as { provider?: unknown; value?: unknown; values?: unknown; field?: unknown };+ const body = (await request.json().catch(() => ({}))) as { provider?: unknown; value?: unknown; values?: unknown; field?: unknown; place?: unknown };const provider = body.provider;// The civitai key isn't a model provider's (it downloads LoRAs), nor is AI-Toolkit (it trains them).const adapter =@@ -28,6 +30,13 @@ export async function POST(request: Request) {const focus = typeof body.field === "string" && settings.includes(body.field) ? body.field : Object.keys(values)[0];const check = adapter.test.bind(adapter);const test = () => check({ focus });+ // The page says it isn't on this server's machine: a ComfyUI address on this machine or its network is never called+ // for it (it would be the server's own, not the owner's computer). Only ever skips a test.+ if (provider === "comfyui" && body.place === "hosted") {+ const field = focus === "comfyIsolatedUrl" ? "comfyIsolatedUrl" : "comfyUrl";+ const refused = await hostedAddressRefusal(field, values[field]);+ if (refused) return Response.json(refused);+ }try {const res = await withCandidates(values, test);// A rejected key that doesn't look like one: say what it should look like.diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.tsindex 52172a60..280edcc9 100644--- a/src/app/api/settings/route.ts+++ b/src/app/api/settings/route.ts@@ -4,7 +4,8 @@ import { getSetting, publicSettings, setSetting, SETTINGS, validateSetting, typeexport async function GET() {await connection();- return Response.json({ settings: publicSettings() });+ // allowPrivate (FUOBE_ALLOW_PRIVATE_URLS): a hosted page may send a private address (a VPN such as Tailscale) to test.+ return Response.json({ settings: publicSettings(), allowPrivate: process.env.FUOBE_ALLOW_PRIVATE_URLS === "1" });}export async function PUT(request: Request) {diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.tsindex 1c1ea6a1..4ca40248 100644--- a/src/app/api/status/route.ts+++ b/src/app/api/status/route.ts@@ -1,5 +1,5 @@import { connection } from "next/server";-import { visitorStatus } from "@/server/account-gpu";+import { computerView, visitorStatus } from "@/server/account-gpu";import { requestViewer } from "@/server/auth";import { aiHelper, localSummary } from "@/server/llm";import { PROVIDERS } from "@/server/providers";@@ -34,12 +34,16 @@ export async function GET(request?: Request) {setSetting("onboarded", "1");onboarded = true;}+ // ComfyUI runs on the owner's computer: what the owner's Fuobe tab there last said (ComfyUI stays "configured", so runs+ // wait for that tab instead of turning into demos).+ const ownerGpu = getSetting("comfyWhere") === "computer" ? computerView("owner") : undefined;return Response.json({providers,demoMode: getSetting("demoMode"),engineMode,cloudProvider: getSetting("cloudProvider"),onboarded,+ ...(ownerGpu && { ownerGpu }),// Settings → Models & licences: the models switched off, so pickers leave them out (absent while everything is on)....(access && { access }),// The text LLM: the AI helper setting, whether Claude takes text steps, and the local server (no keys).diff --git a/src/components/gpu/use-local-comfy.ts b/src/components/gpu/use-local-comfy.tsindex 8884fa4e..a5130998 100644--- a/src/components/gpu/use-local-comfy.ts+++ b/src/components/gpu/use-local-comfy.ts@@ -2,8 +2,7 @@import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";import { loopbackFetch } from "@/lib/gpu/browser-check";-import { browserSupport, localBase, pageCanReach, portsToLook, sameFinder, settled, type Finder, type PortLook, type SystemStats } from "@/lib/local-comfy";-import { rememberedComfy } from "./computer-runtime";+import { browserSupport, localBase, pageCanReach, portsToLook, sameFinder, settled, type Finder, type PortLook, type SystemStats } from "@/lib/local-comfy";import { rememberedComfy } from "./computer-runtime";/*** Finding the ComfyUI on this computer from the page ("Use the ComfyUI on this computer"). It looks at the ports@@ -75,9 +74,11 @@ export function useComputerSupport(): "ok" | "safari" | "phone" | "http" {const coarse = window.matchMedia("(pointer: coarse)").matches && !window.matchMedia("(hover: hover)").matches;const b = browserSupport(navigator as Navigator & { userAgentData?: { mobile?: boolean; platform?: string } }, { narrow, coarse });if (b !== "ok") return b;- return pageCanReach(window.location.origin) ? "ok" : "http";+ return pageCanReach(window.location.origin, window.isSecureContext) ? "ok" : "http";}+export { usePagePlace } from "./use-page-place";+const visible = () => typeof document === "undefined" || document.visibilityState === "visible";/** The finder, while `active` (the card is open). */diff --git a/src/components/gpu/use-page-place.ts b/src/components/gpu/use-page-place.tsnew file mode 100644index 00000000..0e4ddf10--- /dev/null+++ b/src/components/gpu/use-page-place.ts@@ -0,0 +1,14 @@+"use client";++import { useSyncExternalStore } from "react";+import { pagePlace, type PagePlace } from "@/lib/page-place";++const never = () => () => {};++/**+ * Where this page is (lib/page-place.ts): on the server's machine ("here"), its network, or a hosted studio. Null until+ * hydrated (the server's HTML can't know): callers draw a fixed-height placeholder then, never the hosted layout.+ */+export function usePagePlace(): PagePlace | null {+ return useSyncExternalStore(never, () => pagePlace(window.location.hostname), () => null);+}diff --git a/src/lib/api.ts b/src/lib/api.tsindex b3cbb754..30d4d6bd 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -4,7 +4,8 @@ import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClieimport { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";import { toast } from "sonner";import type { AssistThread, AssistThreadSummary, AssistThreadView } from "./assist";-import type { TestProvider } from "./connections";+import type { OwnerGpuView, TestProvider } from "./connections";+import { pagePlace } from "./page-place";import type { ElementKind, StudioElement } from "./catalog/elements";import type { Engine, Generation, GenerationRequest, MediaKind, ReviewStatus } from "./catalog/types";import {@@ -847,20 +848,35 @@ export interface StatusInfo {keys?: CloudProvider[];paidAllowed?: boolean;};+ /**+ * The owner's ComfyUI runs on the owner's computer (Settings): what the owner's Fuobe tab there last said. Never+ * `viewer` (that is a visitor's view of the studio).+ */+ ownerGpu?: OwnerGpuView;+}++/** The viewer's own GPU for the status strip and the header pill: an account's, or the owner's computer. */+export function ownGpuOf(s: StatusInfo | undefined): NonNullable<StatusInfo["viewer"]>["gpu"] | undefined {+ if (s?.viewer) return s.viewer.gpu;+ const g = s?.ownerGpu;+ return g ? { connected: true, mode: "computer", online: g.online, ...(g.comfy && { comfy: g.comfy }), ...(g.device && { device: g.device }), ...(g.vramBytes && { vramBytes: g.vramBytes }) } : undefined;}-/** A connection test's answer (POST /api/providers/test). */+/** A connection test's answer (POST /api/providers/test). `code` "on-your-computer": a hosted page's local address, not called. */export interface ConnectionTest {ok: boolean;detail: string;+ code?: "on-your-computer";}/*** Test a provider, with unsaved values (by setting name) in place of the saved ones when given.* `field` is the setting being checked (the Anthropic key, Ollama's address…), so the test checks that one.+ * `place: "hosted"`: the page isn't on the server's machine (lib/page-place.ts), so a ComfyUI address on the server's+ * own machine or network is refused without a call.*/-export async function testConnection(provider: TestProvider, values?: Record<string, string>, field?: string): Promise<ConnectionTest> {- const res = await fetch("/api/providers/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, values, field }) });+export async function testConnection(provider: TestProvider, values?: Record<string, string>, field?: string, o: { place?: "hosted" } = {}): Promise<ConnectionTest> {+ const res = await fetch("/api/providers/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, values, field, ...(o.place && { place: o.place }) }) });const body = (await res.json().catch(() => null)) as ConnectionTest | null;return body && typeof body.ok === "boolean" ? body : { ok: false, detail: `The test didn't answer (${res.status})` };}@@ -1310,6 +1326,9 @@ export function watchGuestRefusals(): void {const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();if (res.status === 401 && res.headers.get("x-fuobe-guest") === "1" && method !== "GET" && method !== "HEAD") open(res, "guest", requestPath(input));if (res.status === 403 && res.headers.get("x-fuobe-connect-gpu") === "1") open(res, "gpu", requestPath(input));+ // The owner's run with nothing connected that runs it, on a hosted studio: "Connect your GPU" too (a page on the+ // server's own machine keeps its toast: its ComfyUI is in Settings).+ if (res.status === 422 && res.headers.get("x-fuobe-connect-gpu") === "1" && pagePlace(window.location.hostname) === "hosted") open(res, "gpu", requestPath(input));// A run started here, on the ComfyUI on this computer: the tab that runs it asks for it at once.if (res.status === 201 && method === "POST" && requestPath(input) === "/api/generations") {window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));diff --git a/src/lib/connections.ts b/src/lib/connections.tsindex 641ce224..2169e52d 100644--- a/src/lib/connections.ts+++ b/src/lib/connections.ts@@ -11,7 +11,8 @@ export type TestProvider = "fal" | "replicate" | "comfyui" | "llm" | "civitai" |export const PROVIDER_SETTINGS = {fal: ["falKey"],replicate: ["replicateToken"],- comfyui: ["comfyUrl", "comfyToken", "comfyIsolatedUrl"],+ // comfyWhere "server": a server address tested while ComfyUI runs on the owner's computer is tested as a server.+ comfyui: ["comfyUrl", "comfyToken", "comfyIsolatedUrl", "comfyWhere"],// Claude, and the local model servers of Settings → AI helper (Ollama, LM Studio, Unsloth Studio, any OpenAI-compatible one).llm: ["anthropicKey",@@ -159,6 +160,26 @@ export interface ConnectionState {onboarded?: boolean;/** Settings → Demo mode: auto (a demo when no provider hosts the model), on (always a demo), off (never). */demoMode?: string;+ /** The owner's ComfyUI runs on the owner's computer: what its Fuobe tab last said (GET /api/status). */+ ownerGpu?: OwnerGpuView;+}++/** The owner's computer, as its Fuobe tab last said (the same view as an account's "this computer"). */+export interface OwnerGpuView {+ mode: "computer";+ online: boolean;+ comfy?: "down" | "no-setting";+ guard?: boolean;+ device?: string;+ vramBytes?: number;+ version?: string;+ port?: number;+ cors?: "exact" | "any" | "other";+}++/** "Online", "ComfyUI not running", "Needs a setting" or "Offline": a computer's ComfyUI in a few words. */+export function computerWords(g: { online?: boolean; comfy?: "down" | "no-setting" }): string {+ return g.online ? "Online" : g.comfy === "down" ? "ComfyUI not running" : g.comfy === "no-setting" ? "Needs a setting" : "Offline";}const CLOUD_PROVIDERS = ["fal", "replicate"] as const;@@ -238,18 +259,28 @@ export interface ConnectionItem {unused: boolean;}-/** One line per connection for Settings' status strip, in the order the page lists them. */-export function connectionSummary(s: ConnectionState): ConnectionItem[] {+/**+ * One line per connection for Settings' status strip, in the order the page lists them. ComfyUI on the owner's+ * computer reads as "Your GPU · Your computer · Online" (or what's wrong); on a hosted studio with nothing connected,+ * "Your GPU · Connect" (`place`: where the page is, lib/page-place.ts).+ */+export function connectionSummary(s: ConnectionState, place?: "here" | "network" | "hosted" | null): ConnectionItem[] {const key = (id: "fal" | "replicate", label: string): ConnectionItem => {const ok = !!s.providers[id]?.configured;return { id, label, ok, text: ok ? "Key set" : "Not set", href: `#${id}`, unused: s.engineMode === "open" };};const comfy = !!s.providers.comfyui?.configured;const llm = !!s.providers.llm?.configured;+ const unused = s.engineMode === "cloud";+ const gpu: ConnectionItem = s.ownerGpu+ ? { id: "comfyui", label: "Your GPU", ok: s.ownerGpu.online, text: `Your computer · ${computerWords(s.ownerGpu)}`, href: "#comfyui", unused }+ : !comfy && place === "hosted"+ ? { id: "comfyui", label: "Your GPU", ok: false, text: "Connect", href: "#comfyui", unused }+ : { id: "comfyui", label: "ComfyUI", ok: comfy, text: comfy ? "Online" : "Offline", href: "#comfyui", unused };return [key("fal", "fal.ai"),key("replicate", "Replicate"),- { id: "comfyui", label: "ComfyUI", ok: comfy, text: comfy ? "Online" : "Offline", href: "#comfyui", unused: s.engineMode === "cloud" },+ gpu,{ id: "llm", label: "AI helper", ok: llm, text: llm ? "On" : "Off", href: "#text-ai", unused: false },];}diff --git a/src/lib/gpu/gather.ts b/src/lib/gpu/gather.tsindex 64cc96ba..cd99f08f 100644--- a/src/lib/gpu/gather.ts+++ b/src/lib/gpu/gather.ts@@ -12,8 +12,8 @@ import type { CheckLine, GpuInventory, GpuProblem, RequirementIndex } from "./ty* fails leaves its part empty and is listed in `errors`: a partial inventory still counts.*/export interface GatherOptions {- /** How the copy names the place: "at your link" (a tunnel) or "on this computer" (browser-direct). */- where?: "link" | "computer";+ /** How the copy names the place: "at your link" (a tunnel), "on this computer" (browser-direct), or the studio's own server address. */+ where?: "link" | "computer" | "install";/** A targeted re-check: only these classes (per-class reads) and folders. */classes?: string[];folders?: string[];@@ -45,8 +45,11 @@ const PROBLEM_TEXT: Record<GpuProblem, string> = {/** A ComfyUI on the person's own computer that doesn't answer (read from their tab, there's no link). */const COMPUTER_UNREACHABLE = "ComfyUI isn't answering on this computer. Start it, then check again.";+/** The studio's own ComfyUI (the owner's server address) that doesn't answer. */+const INSTALL_UNREACHABLE = "ComfyUI at the server address didn't answer. Is it running?";-export const problemText = (p: GpuProblem, where: "link" | "computer" = "link"): string => (where === "computer" && p === "unreachable" ? COMPUTER_UNREACHABLE : PROBLEM_TEXT[p]);+export const problemText = (p: GpuProblem, where: "link" | "computer" | "install" = "link"): string =>+ p === "unreachable" && where === "computer" ? COMPUTER_UNREACHABLE : p === "unreachable" && where === "install" ? INSTALL_UNREACHABLE : PROBLEM_TEXT[p];const clip = (s: unknown, n: number) => String(s ?? "").slice(0, n);diff --git a/src/lib/gpu/readiness.ts b/src/lib/gpu/readiness.tsindex 7aad3f92..2fce0c73 100644--- a/src/lib/gpu/readiness.ts+++ b/src/lib/gpu/readiness.ts@@ -83,6 +83,8 @@ export const packLabel = (name: string) => name.replace(/^ComfyUI[-_]/i, "").repexport interface ReadinessContext {/** An account's own GPU (isolated workflows aren't supported there yet). */account: boolean;+ /** A ComfyUI on someone's own computer, which their Fuobe tab runs (it reaches no second ComfyUI yet). */+ computer?: boolean;/** The owner has an isolated worker set up. */isolatedUrl?: boolean;/** The tool's output kind, for labels ("Video model"). */@@ -130,6 +132,7 @@ export function workflowReadiness(id: string, inv: GpuInventory, idx: Requiremenconst base: WorkflowReadiness = { state: "unknown", needs: [], have: [], vram: { needGb: 0, fit: "any" }, firstRun: [], unvalidated: false, unobservable: [] };if (!w || !inv.reachable) return base;const out: WorkflowReadiness = { ...base, state: "ready", firstRun: w.firstRun, unvalidated: !w.validated, vram: vramFit(w.vramGb, inv) };+ if (w.isolated && ctx.computer) return { ...out, state: "unsupported", reason: "This one needs a second ComfyUI running alongside the first, which Fuobe doesn't connect from your computer yet." };if (w.isolated && ctx.account) return { ...out, state: "unsupported", reason: "This one needs a second ComfyUI running alongside the first, which Your GPU doesn't connect yet." };if (w.isolated && !ctx.isolatedUrl) {out.needs.push({ key: "isolated-worker", kind: "isolated-worker", label: "A second ComfyUI (the isolated worker)", detail: "Some add-ons change process-wide settings, so they run on a separate ComfyUI." });diff --git a/src/lib/local-comfy.ts b/src/lib/local-comfy.tsindex 387b52ca..ce06a32e 100644--- a/src/lib/local-comfy.ts+++ b/src/lib/local-comfy.ts@@ -282,9 +282,11 @@ export function browserSupport(/*** Can a page at this address ask for the permission at all? Chrome turns it down for a page on plain http at a network- * address (a self-hosted studio on the LAN); https and localhost are fine.+ * address (a self-hosted studio on the LAN); https and localhost are fine, and so is any page the browser itself calls+ * secure (`secure`: window.isSecureContext).*/-export function pageCanReach(origin: string): boolean {+export function pageCanReach(origin: string, secure?: boolean): boolean {+ if (secure === true) return true;try {const u = new URL(origin);return u.protocol === "https:" || LOCAL_HOSTS.has(u.hostname === "::1" ? "[::1]" : u.hostname) || u.hostname.endsWith(".localhost");diff --git a/src/lib/page-place.ts b/src/lib/page-place.tsnew file mode 100644index 00000000..d8681a23--- /dev/null+++ b/src/lib/page-place.ts@@ -0,0 +1,150 @@+/**+ * Is this page on the same machine as Fuobe's server, and what does an address typed into Fuobe mean from the+ * server's side? Pure, for the browser and the server alike (no DOM, no `node:` modules).+ *+ * A page at localhost or 127.0.0.1 is "here": the browser and the server share one machine, so 127.0.0.1:8188 is the+ * same ComfyUI to both. A page at a LAN address or a local name is "network": the server is on the person's own network,+ * where its own 127.0.0.1 and the LAN mean something to it. Any other page is "hosted" (fuobe.com): the server is+ * somewhere else, and a loopback or private address typed there would make it call itself or its own network, never+ * the person's computer. The answer steers what the page offers first. It is never a security boundary: the server+ * never trusts it, and it only ever skips a call.+ */++/** Names nobody on the internet can point at a machine: this machine, the LAN, reserved suffixes. */+export const LOCAL_SUFFIXES = [".localhost", ".local", ".lan", ".home.arpa", ".internal", ".localdomain"];++export type PagePlace = "here" | "network" | "hosted";++/** What an address means to a server: this machine, a private network, link-local, a LAN name, the internet, or not an address. */+export type AddressKind = "loopback" | "private" | "link-local" | "local-name" | "public" | "invalid";++const V4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;++function v4Parts(host: string): number[] | null {+ const m = V4.exec(host);+ if (!m) return null;+ const parts = m.slice(1).map(Number);+ return parts.every((n) => n <= 255) ? parts : null;+}++function v4Kind([a, b]: number[]): Exclude<AddressKind, "local-name" | "invalid"> {+ if (a === 127 || a === 0) return "loopback";+ if (a === 169 && b === 254) return "link-local";+ if (a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127)) return "private";+ return "public";+}++/** An IPv6 literal as eight numbers, or null. Takes the forms a URL's hostname has (compressed, an IPv4 tail). */+function v6Hextets(host: string): number[] | null {+ if (!host.includes(":") || !/^[0-9a-f:.]+$/.test(host)) return null;+ let s = host;+ const tail = /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(s);+ if (tail) {+ const p = v4Parts(tail[1]);+ if (!p) return null;+ s = `${s.slice(0, -tail[1].length)}${((p[0] << 8) | p[1]).toString(16)}:${((p[2] << 8) | p[3]).toString(16)}`;+ }+ const halves = s.split("::");+ if (halves.length > 2) return null;+ const read = (part: string) => (part ? part.split(":") : []);+ const head = read(halves[0]);+ const rest = halves.length === 2 ? read(halves[1]) : [];+ const fill = halves.length === 2 ? 8 - head.length - rest.length : 0;+ if (fill < 0 || (halves.length === 1 && head.length !== 8)) return null;+ const all = [...head, ...Array<string>(fill).fill("0"), ...rest];+ if (all.length !== 8 || all.some((h) => !/^[0-9a-f]{1,4}$/.test(h))) return null;+ return all.map((h) => parseInt(h, 16));+}++function v6Kind(h: number[]): Exclude<AddressKind, "local-name" | "invalid"> {+ const zeros = (n: number) => h.slice(0, n).every((x) => x === 0);+ // ::1 and :: (this host), and an IPv4 address carried inside (::ffff:a.b.c.d, ::a.b.c.d, 64:ff9b::a.b.c.d).+ if (zeros(7) && (h[7] === 1 || h[7] === 0)) return "loopback";+ const inner = (zeros(5) && (h[5] === 0xffff || h[5] === 0)) || (h[0] === 0x64 && h[1] === 0xff9b && h.slice(2, 6).every((x) => x === 0));+ if (inner) return v4Kind([h[6] >> 8, h[6] & 0xff, h[7] >> 8, h[7] & 0xff]);+ if ((h[0] & 0xffc0) === 0xfe80) return "link-local";+ if ((h[0] & 0xfe00) === 0xfc00) return "private";+ return "public";+}++/** A host as a URL gives it, lower case, without brackets or a trailing dot. */+const bare = (host: string) => host.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");++/** What a host name or IP literal means to a server. */+export function hostKind(rawHost: string): Exclude<AddressKind, "invalid"> {+ const host = bare(rawHost);+ if (host === "localhost" || host.endsWith(".localhost")) return "loopback";+ const v4 = v4Parts(host);+ if (v4) return v4Kind(v4);+ const v6 = v6Hextets(host);+ if (v6) return v6Kind(v6);+ if (!host.includes(".") || LOCAL_SUFFIXES.some((s) => host.endsWith(s))) return "local-name";+ return "public";+}++/** Where this page is, from its own hostname (window.location.hostname). */+export function pagePlace(hostname: string): PagePlace {+ const k = hostKind(hostname);+ return k === "loopback" ? "here" : k === "public" ? "hosted" : "network";+}++/** An address as typed: "127.0.0.1:8188" and "localhost:8188" count as http:// ones (people leave it off). */+function parsed(raw: string): URL | null {+ const s = raw.trim();+ if (!s) return null;+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : /^(\[[0-9a-f:.]+\]|[a-z0-9.-]+)(:\d+)?(\/\S*)?$/i.test(s) ? `http://${s}` : s;+ try {+ const u = new URL(withScheme);+ return (u.protocol === "http:" || u.protocol === "https:") && u.hostname ? u : null;+ } catch {+ return null;+ }+}++/** What a ComfyUI address means to a server. Ports, paths, brackets, a trailing dot and upper case are all fine. */+export function addressKind(url: string): AddressKind {+ const u = parsed(url);+ return u ? hostKind(u.hostname) : "invalid";+}++/** The host of an address, as shown in a sentence ("127.0.0.1", "nas.local", "[::1]"); "" when it isn't one. */+export function addressHost(url: string): string {+ return parsed(url)?.hostname ?? "";+}++/**+ * On a hosted page, an address Fuobe's server must not be asked to call for the person's own ComfyUI: this machine,+ * link-local, and (unless the server allows private addresses: FUOBE_ALLOW_PRIVATE_URLS, a VPN such as Tailscale) a+ * private network or a LAN name.+ */+export const refusedOnHosted = (k: AddressKind, allowPrivate: boolean): boolean =>+ k === "loopback" || k === "link-local" || ((k === "private" || k === "local-name") && !allowPrivate);++/** The one line a refused address gets: what that address means here. */+export function refusedLine(k: AddressKind, host: string): string {+ if (k === "loopback") return `On this website, ${host} is Fuobe's server, not your computer.`;+ return `${host} is on your own network, which Fuobe's server can't reach.`;+}++/** The line the server's own refusal of a name that leads to a private address gets. */+export const resolvesPrivateLine = (host: string) => `${host} leads to a private address, so Fuobe's server won't call it.`;++/** Said when nothing was typed and only the built-in address (this machine's) is there to test. */+export const TYPE_AN_ADDRESS = "Type the address of a ComfyUI that Fuobe's server can reach.";++/**+ * How the owner's GPU choice is offered on this page:+ * - "computer": ComfyUI runs on the owner's computer (their Fuobe tab);+ * - "server": a ComfyUI on the server answers (a connected one always wins, wherever the page is);+ * - "hosted": nothing connected, and the page is not on the server's machine: the computer first, a server address second;+ * - "local": the page is on the server's machine or its network: today's server address.+ * Null until the page knows where it is (hydration).+ */+export type OwnerSteer = "computer" | "server" | "hosted" | "local";++export function ownerSteer(place: PagePlace | null, s: { engineMode?: string; providers?: Record<string, { configured: boolean } | undefined> } | undefined, comfyWhere: string | undefined): OwnerSteer | null {+ if (comfyWhere === "computer") return "computer";+ if (!s || place === null) return null;+ if (s.providers?.comfyui?.configured) return "server";+ return place === "hosted" && s?.engineMode !== "cloud" ? "hosted" : "local";+}diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 62576948..287d859d 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -280,6 +280,9 @@ export const RELAY_WORDS = {switched: "This run stopped because ComfyUI now runs somewhere else. Press Retry.",} as const;+/** A script's open-source run (an API token) while the owner's ComfyUI is on the owner's computer. */+export const RUNS_ON_COMPUTER_NOTE = "Runs when Fuobe is open on your computer.";+/** The words for a tab's own failure. */export function tabFailureWords(reason: TabFailure, status?: number): string {switch (reason) {diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.tsindex ed24d9c8..5bf6fc27 100644--- a/src/server/account-gpu.ts+++ b/src/server/account-gpu.ts@@ -4,7 +4,8 @@ import net from "node:net";import { isCloudProvider, type CloudProvider } from "@/lib/your-keys";import { accountEngineMode, accountProviders, paidAllowed } from "./account-keys";import { accountGpu, type Account, type AccountGpu } from "./auth";-import { runnerFacts } from "./computer/tasks";+import type { OwnerGpuView } from "@/lib/connections";+import { runnerFacts, type Principal } from "./computer/tasks";import { offeredSummary } from "./model-access";import { PROVIDERS } from "./providers";import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";@@ -141,6 +142,26 @@ export function lastGpuDevice(id: string): string | undefined {return /^[a-z]+/i.exec(hit.info.device ?? "")?.[0].toLowerCase();}+/**+ * What someone's computer's Fuobe tab last said (an account's "this computer", or the owner's when ComfyUI runs on the+ * owner's computer): its GPU, memory, ComfyUI version and port, the guard and the cross-site setting, and whether it+ * is open now. Never an address, a token or anything of the server's.+ */+export function computerView(principal: Principal): OwnerGpuView {+ const f = runnerFacts(principal);+ return {+ mode: "computer" as const,+ online: !!f?.online,+ ...(f?.comfy && { comfy: f.comfy }),+ ...(f?.guard !== undefined && { guard: f.guard }),+ ...(f?.device && { device: f.device }),+ ...(f?.vramBytes && { vramBytes: f.vramBytes }),+ ...(f?.version && { version: f.version }),+ ...(f?.port && { port: f.port }),+ ...(f?.cors && { cors: f.cors }),+ };+}+/** What a visitor's status strip shows (GET /api/status): its own GPU, never the install's providers, servers or Demo mode. */export interface VisitorView {kind: "guest" | "account";diff --git a/src/server/auth.ts b/src/server/auth.tsindex 239d63a5..2a127c03 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -19,6 +19,7 @@ import fs from "node:fs";import net from "node:net";import os from "node:os";import path from "node:path";+import { LOCAL_SUFFIXES } from "@/lib/page-place";const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));const FILE = path.join(DATA_DIR, "auth.json");@@ -639,8 +640,6 @@ function hostName(host: string): string {return (colon >= 0 && colon === h.lastIndexOf(":") ? h.slice(0, colon) : h).replace(/\.$/, "");}-/** Names nobody on the internet can point at this machine: this machine, the LAN, reserved suffixes. */-const LOCAL_SUFFIXES = [".localhost", ".local", ".lan", ".home.arpa", ".internal", ".localdomain"];/*** Is this a name the studio may be reached at without a password? A page on attacker.example candiff --git a/src/server/generations.ts b/src/server/generations.tsindex 4e818196..7a3afbdc 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -508,11 +508,16 @@ export function chooseRoute(candidates: ModelRoute[], images = 0, loras: LoraRefif (cloud) throw new AccountRunError(paidAllowed() ? { error: addKeyMessage(cloud), code: "add-key", provider: cloud } : { error: OPEN_ONLY_RUN, code: "open-only" });if (routes.every((r) => r.provider === "llm")) throw new Error(llmMissing(routes[0]));const names = [...new Set(routes.map((r) => provider(r.provider).label))].join(" or ");- throw new Error(`Connect ${names} in Settings to run this model`);+ const message = `Connect ${names} in Settings to run this model`;+ // ComfyUI could run it: the owner's own browser opens "Connect your GPU" for it (generations/route.ts).+ throw routes.some((r) => r.provider === "comfyui") ? new ConnectComfyError(message) : new Error(message);}return { route: routes[0], demo: true };}+/** A run nothing connected can make, and ComfyUI could: connecting a GPU is the way (same words as before). */+export class ConnectComfyError extends Error {}+/** Text steps depend on which LLM the route may use (the open model never calls Claude). */const routeReady = (r: ModelRoute) => (r.provider === "llm" ? llmBackends(r).length > 0 : provider(r.provider).isConfigured());diff --git a/src/server/gpu/readiness-service.ts b/src/server/gpu/readiness-service.tsindex cdf25d3d..a241b400 100644--- a/src/server/gpu/readiness-service.ts+++ b/src/server/gpu/readiness-service.ts@@ -18,7 +18,7 @@ import { urlHash, type ReadTarget } from "./target";*/export function contextFor(t: ReadTarget): ReadinessContext {- return { account: t.kind === "account" || (t.kind === "computer" && t.key !== "install"), isolatedUrl: t.kind === "install" && !!getSetting("comfyIsolatedUrl") };+ return { account: t.kind === "account" || (t.kind === "computer" && t.key !== "install"), computer: t.kind === "computer", isolatedUrl: t.kind === "install" && !!getSetting("comfyIsolatedUrl") };}export function readinessOf(tool: Tool, inv: GpuInventory, idx: RequirementIndex, ctx: ReadinessContext): ToolReadiness {@@ -96,7 +96,7 @@ export function readinessView(t: ReadTarget): ReadinessView {if (!snap) return { ...base, checkedAt: null };const inv = snap.inventory;if (!inv.reachable) {- return { ...base, checkedAt: snap.checkedAt, stale: snap.stale, problem: inv.problem ?? "unreachable", problemText: problemText(inv.problem ?? "unreachable", t.via === "browser" ? "computer" : "link"), ...(inv.problemDetail && { problemDetail: inv.problemDetail }) };+ return { ...base, checkedAt: snap.checkedAt, stale: snap.stale, problem: inv.problem ?? "unreachable", problemText: problemText(inv.problem ?? "unreachable", t.via === "browser" ? "computer" : t.kind === "install" ? "install" : "link"), ...(inv.problemDetail && { problemDetail: inv.problemDetail }) };}return { ...base, checkedAt: snap.checkedAt, stale: snap.stale, report: viewsOf(t, snap).report };}diff --git a/src/server/gpu/snapshots.ts b/src/server/gpu/snapshots.tsindex c1ad1b91..917897f2 100644--- a/src/server/gpu/snapshots.ts+++ b/src/server/gpu/snapshots.ts@@ -178,7 +178,7 @@ export async function probe(t: ServerTarget, o: ProbeOptions): Promise<GpuInventconst entry = { promise: null as unknown as Promise<GpuInventory>, lines: [] as CheckLine[], listeners: new Set<(l: CheckLine) => void>(), full: !targeted };if (o.onLine) entry.listeners.add(o.onLine);const opts: GatherOptions = {- where: "link",+ where: t.kind === "install" ? "install" : "link",onLine: (l) => {entry.lines.push(l);for (const fn of entry.listeners) fn(l);diff --git a/src/server/providers/comfy-address.ts b/src/server/providers/comfy-address.tsnew file mode 100644index 00000000..3f281651--- /dev/null+++ b/src/server/providers/comfy-address.ts@@ -0,0 +1,61 @@+import "server-only";+import dns from "node:dns/promises";+import net from "node:net";+import { addressHost, addressKind, refusedLine, refusedOnHosted, resolvesPrivateLine, TYPE_AN_ADDRESS } from "@/lib/page-place";+import { blockedForAccounts, selfAddresses } from "../remote-fetch";+import { savedSetting, settingSource } from "../settings";++/**+ * The owner's ComfyUI address on a hosted studio (the page says it isn't on the server's machine: lib/page-place.ts).+ * There, an address on this machine, link-local, or on a private network (unless FUOBE_ALLOW_PRIVATE_URLS) would make+ * the server call itself or its own network, never the owner's computer: the test answers why, and makes no request.+ * A name that leads to such an address is refused the same way. This steers the owner's own Settings (the route is the+ * owner's only); it is not a security boundary, and a request without the page's word is tested as before.+ */++export interface AddressRefusal {+ ok: false;+ code: "on-your-computer";+ detail: string;+}++const allowPrivate = () => process.env.FUOBE_ALLOW_PRIVATE_URLS === "1";++const refusal = (detail: string): AddressRefusal => ({ ok: false, code: "on-your-computer", detail });++type Resolve = (host: string) => Promise<string[]>;++const lookup: Resolve = async (host) => (await dns.lookup(host, { all: true, verbatim: true })).map((a) => a.address);++/**+ * Should the server not test this ComfyUI address for a hosted page? `field`: comfyUrl or comfyIsolatedUrl; `typed`:+ * the value typed for the test, if any. Null: go on and test it.+ * - Nothing typed and only the built-in address: there is nothing of the owner's to test.+ * - Nothing typed and the address comes from COMFYUI_URL: tested as before (a GPU box that runs both).+ * - A loopback, link-local, private or LAN address (typed or saved): refused, no request.+ * - A name: looked up; any loopback, link-local, private or this machine's own address refuses it. A name that+ * doesn't resolve goes on, and the test says it can't reach it. The answer never shows what it resolved to.+ */+export async function hostedAddressRefusal(field: "comfyUrl" | "comfyIsolatedUrl", typed: string | undefined, o: { resolve?: Resolve } = {}): Promise<AddressRefusal | null> {+ let url = typed?.trim() ?? "";+ if (!url) {+ const source = settingSource(field);+ if (source === "env") return null;+ if (source === "default") return field === "comfyUrl" ? refusal(TYPE_AN_ADDRESS) : null;+ url = savedSetting(field);+ }+ const kind = addressKind(url);+ if (kind === "invalid") return null;+ const host = addressHost(url);+ if (refusedOnHosted(kind, allowPrivate())) return refusal(refusedLine(kind, host));+ const bare = host.replace(/^\[|\]$/g, "");+ // An address literal the server won't call: one of this machine's own, or a reserved or private range.+ if (net.isIP(bare)) return blockedForAccounts(bare) ? refusal(refusedLine(selfAddresses().has(bare) ? "loopback" : "private", host)) : null;+ let addrs: string[];+ try {+ addrs = await (o.resolve ?? lookup)(bare);+ } catch {+ return null;+ }+ return addrs.some(blockedForAccounts) ? refusal(resolvesPrivateLine(host)) : null;+}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex a97256d6..2542ccf4 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -175,15 +175,24 @@ function relayPrincipal(): Principal {return account ? `acct:${account}` : "owner";}+/**+ * Said when a workflow for the isolated worker (LatentSync 1.6, ThinkSound) would go to someone's computer: it needs a+ * second ComfyUI beside the first, which the tab doesn't reach yet. Refused before anything is staged or queued.+ */+export const ISOLATED_ON_COMPUTER = "This one needs a second ComfyUI running alongside the first, which Fuobe doesn't connect from your computer yet.";+/** Said when something would call a ComfyUI that only the person's own tab may reach. */export const ON_COMPUTER_ONLY = "This ComfyUI is on your own computer: only your Fuobe tab there talks to it.";/** The most an account's ComfyUI may send back for one output file, and how long it may take. */export const OWN_OUTPUT_LIMITS = { maxBytes: 2 ** 30, deadlineMs: 15 * 60_000 };-/** A result a computer sent in (relay:<task>/view?…&n=…): the file its task received, for that task's principal only. */+/**+ * A result a computer sent in (relay:<task>/view?…&n=…): the file its task received, for that task's principal only:+ * whose run this is (an account, as its tenant; else the owner), whatever ComfyUI's place is now, as poll and cancel.+ */export function relayFile(url: string): { path: string; contentType?: string } | null {- const principal = computerScope();+ const principal = relayPrincipal();const m = /^relay:([A-Za-z0-9_-]{16})\/view\?(.*)$/.exec(url);const n = m ? Number(new URLSearchParams(m[2]).get("n")) : NaN;return principal && m && Number.isInteger(n) ? receivedFile(principal, m[1], n) : null;@@ -1627,6 +1636,7 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,// On someone's computer: kept here for the run's task, under the name ComfyUI will get from their tab.const computer = computerScope();if (computer) {+ if (worker === "isolated") throw new ProviderError(ISOLATED_ON_COMPUTER);const staged = stageInput(computer, data, contentType, name);rememberSent(staged, data, contentType, name);return staged;@@ -1839,6 +1849,7 @@ export const comfyProvider: ProviderAdapter = {async submit({ route, input, generationId, model }) {const worker = workerFor(route.endpoint);+ if (worker === "isolated" && computerScope()) throw new ProviderError(ISOLATED_ON_COMPUTER);// A route's own graph settings (Fuobe Speak's InfiniteTalk recipe) go in unless the run sets them.const asked = route.extra ? { ...input, extra: { ...route.extra, ...input.extra } } : input;const { manifest, workflow: wf, meta } = await prepareWorkflow(route.endpoint, asked, {diff --git a/src/server/settings.ts b/src/server/settings.tsindex cd3ea961..c7a09030 100644--- a/src/server/settings.ts+++ b/src/server/settings.ts@@ -147,6 +147,13 @@ export function savedSetting(name: SettingName): string {return candidates.exit(() => getSetting(name));}+/** Where the saved value in effect comes from: saved here, an environment variable, or the built-in default (or nothing). */+export function settingSource(name: SettingName): "saved" | "env" | "default" {+ const def: SettingDef = SETTINGS[name];+ const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(def.key) as { value: string } | undefined;+ return row && row.value !== "" ? "saved" : envValue(def) ? "env" : "default";+}+export function getSetting(name: SettingName): string {const def: SettingDef = SETTINGS[name];const candidate = candidates.getStore()?.[name];diff --git a/tests/computer-pure.test.ts b/tests/computer-pure.test.tsindex 303f6573..bd437c41 100644--- a/tests/computer-pure.test.ts+++ b/tests/computer-pure.test.ts@@ -376,6 +376,9 @@ describe("which browsers can reach the ComfyUI on this computer", () => {expect(pageCanReach("http://127.0.0.1:3370")).toBe(true);expect(pageCanReach("http://192.168.1.20:3000")).toBe(false);expect(pageCanReach("http://studio.lan")).toBe(false);+ // Whatever the address, a page the browser itself calls secure may ask.+ expect(pageCanReach("http://studio.test:3375", true)).toBe(true);+ expect(pageCanReach("http://192.168.1.20:3000", false)).toBe(false);});});diff --git a/tests/computer-security.test.ts b/tests/computer-security.test.tsindex 370111ca..0f06bd0b 100644--- a/tests/computer-security.test.ts+++ b/tests/computer-security.test.ts@@ -20,7 +20,8 @@ const { resetRates } = await import("@/server/rate");const { setSetting } = await import("@/server/settings");const tasks = await import("@/server/computer/tasks");const { onComputer, outputFetch } = await import("@/server/providers/comfyui");-const { accountMayChange, accountOwnRead, guestRead } = await import("@/lib/guest-access");+const guestAccess = await import("@/lib/guest-access");+const { accountMayChange, accountOwnRead, guestRead } = guestAccess;type Principal = import("@/server/computer/tasks").Principal;@@ -241,6 +242,62 @@ describe("one account can't touch another's jobs", () => {});});+describe("the owner's computer and an account's never mix", () => {+ it("the owner's job is 404 to an account on every route, and an account's computer never claims it", async () => {+ setSetting("comfyWhere", "computer");+ const t = waitingTask("owner");+ expect((await call("a", "POST", "/api/gpu/computer/beat", { body: { device: "device-a-0002" } })).status).toBe(200);+ expect((await call("a", "POST", "/api/gpu/computer/claim", { body: { device: "device-a-0002" } })).status).toBe(204);+ const c = await claimed("owner", "device-owner-0001");+ expect(c.id).toBe(t.id);+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { event: "sent", promptId: c.promptId } })).status).toBe(404);+ expect((await put("a", c.id, 0, c.lease, FAKE_PNG)).status).toBe(404);+ expect((await call("a", "GET", `/api/gpu/computer/tasks/${c.id}/outputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(404);+ expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/release`, { body: { lease: c.lease } })).status).toBe(404);+ expect(state(c.id)).toBe("sending");+ expect((await call("owner", "GET", `/api/gpu/computer/tasks/${c.id}/inputs/0`, { headers: { "x-fuobe-lease": c.lease } })).status).toBe(200);+ });++ it("the owner's computer never claims an account's job, even while it runs the owner's", async () => {+ setSetting("comfyWhere", "computer");+ waitingTask(`acct:${a}`);+ expect((await call("owner", "POST", "/api/gpu/computer/beat", { body: { device: "device-owner-0002" } })).status).toBe(200);+ expect((await call("owner", "POST", "/api/gpu/computer/claim", { body: { device: "device-owner-0002" } })).status).toBe(204);+ });++ it("an account's run goes to its own computer, or nowhere, never the owner's, whatever the owner's Settings say", async () => {+ const { asAccount } = await import("@/server/generations");+ const { computerScope } = await import("@/server/providers/comfyui");+ setSetting("comfyWhere", "computer");+ expect((await call("owner", "POST", "/api/gpu/computer/beat", { body: { device: "device-owner-0003" } })).status).toBe(200);+ expect(computerScope()).toBe("owner");+ expect(asAccount(a, () => computerScope())).toBe(`acct:${a}`);+ expect(asAccount(link, () => computerScope())).toBeUndefined();+ const none = auth.createAccount("[email protected]", "long enough").id;+ expect(asAccount(none, () => computerScope())).toBeUndefined();+ });++ it("the owner's results are read only as the owner", async () => {+ const { relayFile } = await import("@/server/providers/comfyui");+ const { asAccount } = await import("@/server/generations");+ setSetting("comfyWhere", "computer");+ const t = waitingTask("owner");+ const url = `relay:${t.id}/view?filename=x.png&n=0`;+ expect(asAccount(a, () => relayFile(url))).toBeNull();+ expect((await onComputer(`acct:${a}`, () => outputFetch(url))).status).toBe(404);+ });++ it("the owner's connection settings and tests stay the owner's", () => {+ const { ownerOnly } = guestAccess;+ expect(ownerOnly("POST", "/api/providers/test")).toBe(true);+ expect(ownerOnly("PUT", "/api/settings")).toBe(true);+ // Reading them: not an account's (its own read list) nor a guest's.+ expect(accountOwnRead("/api/settings")).toBe(false);+ expect(guestRead("/api/settings")).toEqual({ kind: "closed" });+ });+});+describe("a job's token", () => {it("a wrong token, or the one before the latest claim, gets 409", async () => {waitingTask(`acct:${a}`);diff --git a/tests/connections.test.ts b/tests/connections.test.tsindex 4512c784..3e3728df 100644--- a/tests/connections.test.ts+++ b/tests/connections.test.ts@@ -2,7 +2,7 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";import { afterAll, describe, expect, it, vi } from "vitest";-import { candidateValues, connectionSummary, FIRST_RUN_KEY, FIRST_RUN_SCRIPT, isTestProvider, nothingConnected, settingProblem, showFirstRun, type ConnectionState } from "@/lib/connections";+import { candidateValues, connectionSummary, FIRST_RUN_KEY, FIRST_RUN_SCRIPT, isTestProvider, nothingConnected, PROVIDER_SETTINGS, settingProblem, showFirstRun, type ConnectionState } from "@/lib/connections";/** Settings' "Save & test", the first-run guide's rule and the connection status strip (R4-02, R4-03, R4-33). */@@ -138,6 +138,24 @@ describe("first-run guide and status strip", () => {expect(s.map((c) => c.href)).toEqual(["#fal", "#replicate", "#comfyui", "#text-ai"]);});+ it("says the owner's computer as Your GPU, and Connect on a hosted studio with nothing connected", () => {+ const gpu = (g: ConnectionState["ownerGpu"], place?: "here" | "network" | "hosted") => connectionSummary({ ...state(["comfyui"], "open"), ownerGpu: g }, place).find((c) => c.id === "comfyui");+ expect(gpu({ mode: "computer", online: true, device: "cuda:0 NVIDIA GeForce RTX 5090" })).toMatchObject({ label: "Your GPU", text: "Your computer · Online", ok: true, href: "#comfyui" });+ expect(gpu({ mode: "computer", online: false, comfy: "down" })).toMatchObject({ label: "Your GPU", text: "Your computer · ComfyUI not running", ok: false });+ expect(gpu({ mode: "computer", online: false, comfy: "no-setting" })).toMatchObject({ text: "Your computer · Needs a setting", ok: false });+ expect(gpu({ mode: "computer", online: false }, "hosted")).toMatchObject({ text: "Your computer · Offline", ok: false });+ const hosted = connectionSummary(state([], "open"), "hosted").find((c) => c.id === "comfyui");+ expect(hosted).toMatchObject({ label: "Your GPU", text: "Connect", ok: false, href: "#comfyui" });+ // On the server's own machine, or once a server ComfyUI answers: as before.+ expect(connectionSummary(state([], "open"), "here").find((c) => c.id === "comfyui")).toMatchObject({ label: "ComfyUI", text: "Offline" });+ expect(connectionSummary(state(["comfyui"], "open"), "hosted").find((c) => c.id === "comfyui")).toMatchObject({ label: "ComfyUI", text: "Online" });+ });++ it("lets a ComfyUI test say where ComfyUI runs, so a server address is tested as a server", () => {+ expect(PROVIDER_SETTINGS.comfyui).toContain("comfyWhere");+ expect(candidateValues("comfyui", { comfyUrl: "https://gpu.example.com", comfyWhere: "server" })).toEqual({ comfyUrl: "https://gpu.example.com", comfyWhere: "server" });+ });+it("quotes a first image and clip on the default paid models", () => {expect(starterPriceLine()).toMatch(/^Nano Banana Pro ≈ \$[\d.]+ an image · Seedance 2\.5 ≈ \$[\d.]+ a 5 s clip$/);});diff --git a/tests/owner-computer.test.ts b/tests/owner-computer.test.tsnew file mode 100644index 00000000..84b36191--- /dev/null+++ b/tests/owner-computer.test.ts@@ -0,0 +1,378 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";+import { loadRoutes, tab, type ComputerRoutes } from "./helpers/computer-tab";++/**+ * The owner's ComfyUI on a hosted studio: an address on the server's own machine or network is never called for a+ * hosted page, the owner's computer is reported honestly (GET /api/status ownerGpu, GET /api/comfyui), the isolated+ * worker's workflows are refused on a computer, a run nothing connected can make opens "Connect your GPU" for the+ * owner's own browser only, and a finished result is kept whatever ComfyUI's place is by then.+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-owner-computer-"));+process.env.FUOBE_DATA_DIR = dir;+// Nothing answers here: no test may reach a real ComfyUI on this machine.+const DEAD = "http://127.0.0.1:9";+process.env.COMFYUI_URL = DEAD;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+globalThis.__fuobeTestDiskFree = 1e13;++// The server's own fetch: recorded. Anything but the stand-ins answers 599 at once (no real network).+const realFetch = globalThis.fetch;+const fetched: string[] = [];+let allowed: string[] = [];+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input instanceof Request ? input.url : input);+ fetched.push(url);+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);+ return new Response("not reachable in this test", { status: 599 });+}) as typeof fetch;++const auth = await import("@/server/auth");+const testRoute = await import("@/app/api/providers/test/route");+const statusRoute = await import("@/app/api/status/route");+const comfyuiRoute = await import("@/app/api/comfyui/route");+const generationsRoute = await import("@/app/api/generations/route");+const meRoute = await import("@/app/api/auth/me/route");+const { hostedAddressRefusal } = await import("@/server/providers/comfy-address");+const { getSetting, setSetting } = await import("@/server/settings");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { writeSnapshot } = await import("@/server/gpu/snapshots");+const { relayFile, ISOLATED_ON_COMPUTER } = await import("@/server/providers/comfyui");+const { asAccount, getGeneration } = await import("@/server/generations");+const { RELAY_WORDS, RUNS_ON_COMPUTER_NOTE } = await import("@/lib/relay");+const { CONNECT_GPU_HEADER } = await import("@/lib/guest-access");++let fake: LocalComfy;+let routes: ComputerRoutes;+let owner = "";+let account = "";+let accountId = "";+const HOST = "localhost:3000";+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };++beforeAll(async () => {+ fake = await startLocalComfy({ cors: `http://${HOST}`, steps: 2, stepMs: 10, latencyMs: 10 });+ allowed = [fake.url];+ routes = await loadRoutes();+ auth.setPassword("install password");+ owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ accountId = auth.createAccount("[email protected]", "long enough").id;+ auth.setAccountGpu(accountId, { mode: "computer" });+ account = `${auth.SESSION_COOKIE}=${auth.createSession(accountId).value}`;+});+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestDiskFree = undefined;+ await fake.close();+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});+beforeEach(() => {+ resetRates();+ setSetting("comfyWhere", "server");+ setSetting("comfyUrl", "");+ setSetting("engineMode", "open");+ setSetting("demoMode", "off");+ process.env.COMFYUI_URL = DEAD;+ delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+ db().prepare("DELETE FROM relay_runners").run();+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+});++const request = (url: string, o: { method?: string; body?: unknown; cookie?: string | null; headers?: Record<string, string> } = {}) => {+ const text = o.body === undefined ? undefined : JSON.stringify(o.body);+ const headers: Record<string, string> = { ...SITE_HEADERS, ...(o.cookie !== null && { cookie: o.cookie ?? owner }), ...(text && { "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }), ...o.headers };+ return new Request(`http://${HOST}${url}`, { method: o.method ?? (text ? "POST" : "GET"), headers, body: text });+};++/** POST /api/providers/test as the owner's page; what it answered, and every fetch the server made meanwhile. */+async function connectTest(body: Record<string, unknown>) {+ fetched.length = 0;+ const res = await testRoute.POST(request("/api/providers/test", { body: { provider: "comfyui", field: "comfyUrl", ...body } }));+ return { body: (await res.json()) as { ok: boolean; detail: string; code?: string }, fetched: [...fetched] };+}++const beat = (cookie: string, body: Record<string, unknown>) => routes.beat.POST(request("/api/gpu/computer/beat", { body: { device: "device-owner-1", ...body }, cookie }), { params: Promise.resolve({}) });+const status = async (cookie: string | null = owner) => (await (await statusRoute.GET(request("/api/status", { cookie }))).json()) as Record<string, unknown> & { providers: Record<string, { configured: boolean }>; ownerGpu?: Record<string, unknown> };++describe("a hosted page never makes the server call a ComfyUI address on its own machine or network", () => {+ const REFUSED = ["http://127.0.0.1:3399", "localhost:3399", "http://localhost:3399", "http://10.255.255.1:3399", "http://169.254.169.254", "http://169.254.0.1:3399", "http://nas.local:3399", "http://[::1]:3399", "http://studio:3399"];++ it.each(REFUSED)("%s: refused with one line, and nothing is fetched", async (url) => {+ const r = await connectTest({ values: { comfyUrl: url }, place: "hosted" });+ expect(r.body).toMatchObject({ ok: false, code: "on-your-computer" });+ expect(r.body.detail).toMatch(/is Fuobe's server, not your computer|is on your own network, which Fuobe's server can't reach/);+ expect(r.fetched).toEqual([]);+ });++ it("with nothing typed and only the built-in address, asks for one instead of calling it", async () => {+ // The built-in address is this machine's 8188: in effect only for this one synchronous call, so nothing else in the+ // test run can reach a real ComfyUI there meanwhile.+ fetched.length = 0;+ process.env.COMFYUI_URL = "";+ const answer = hostedAddressRefusal("comfyUrl", undefined);+ process.env.COMFYUI_URL = DEAD;+ expect(await answer).toEqual({ ok: false, code: "on-your-computer", detail: "Type the address of a ComfyUI that Fuobe's server can reach." });+ expect(fetched).toEqual([]);+ });++ it("a saved local address is refused too; the isolated worker's address as well", async () => {+ setSetting("comfyUrl", "http://127.0.0.1:3399");+ expect((await connectTest({ place: "hosted" })).body.code).toBe("on-your-computer");+ const iso = await connectTest({ field: "comfyIsolatedUrl", values: { comfyIsolatedUrl: "http://127.0.0.1:8189" }, place: "hosted" });+ expect(iso.body.code).toBe("on-your-computer");+ expect(iso.fetched).toEqual([]);+ });++ it("FUOBE_ALLOW_PRIVATE_URLS=1 lets a private address (a VPN) be tested, never this machine", async () => {+ process.env.FUOBE_ALLOW_PRIVATE_URLS = "1";+ const lan = await connectTest({ values: { comfyUrl: "http://10.255.255.1:3399" }, place: "hosted" });+ expect(lan.body.code).toBeUndefined();+ expect(lan.fetched.some((u) => u.startsWith("http://10.255.255.1:3399/system_stats"))).toBe(true);+ const self = await connectTest({ values: { comfyUrl: "http://127.0.0.1:3399" }, place: "hosted" });+ expect(self.body.code).toBe("on-your-computer");+ expect(self.fetched).toEqual([]);+ expect((await connectTest({ values: { comfyUrl: "http://169.254.169.254" }, place: "hosted" })).body.code).toBe("on-your-computer");+ });++ it("an address from COMFYUI_URL with nothing typed is tested as before (a GPU box that runs both)", async () => {+ process.env.COMFYUI_URL = fake.url;+ const r = await connectTest({ place: "hosted" });+ expect(r.body.ok).toBe(true);+ expect(r.fetched.some((u) => u.startsWith(`${fake.url}/system_stats`))).toBe(true);+ });++ it("without the page's word (a local install), a loopback address is tested as before", async () => {+ const r = await connectTest({ values: { comfyUrl: fake.url } });+ expect(r.body).toMatchObject({ ok: true });+ expect(r.body.detail).toMatch(/^ComfyUI 0\.42\.0/);+ expect(r.fetched.some((u) => u.startsWith(`${fake.url}/system_stats`))).toBe(true);+ });++ it("a public address is tested", async () => {+ const r = await connectTest({ values: { comfyUrl: "https://93.184.216.34:8188" }, place: "hosted" });+ expect(r.body.code).toBeUndefined();+ expect(r.fetched.some((u) => u.startsWith("https://93.184.216.34:8188/system_stats"))).toBe(true);+ // A reserved range the server won't call: refused, said as a network it can't reach.+ const reserved = await connectTest({ values: { comfyUrl: "http://203.0.113.9:8188" }, place: "hosted" });+ expect(reserved.body).toEqual({ ok: false, code: "on-your-computer", detail: "203.0.113.9 is on your own network, which Fuobe's server can't reach." });+ expect(reserved.fetched).toEqual([]);+ });++ it("a name that leads to this machine or a private network is refused, without saying where it leads", async () => {+ const to = (ips: string[]) => async () => ips;+ expect(await hostedAddressRefusal("comfyUrl", "https://sneaky.example.com", { resolve: to(["127.0.0.1"]) })).toEqual({ ok: false, code: "on-your-computer", detail: "sneaky.example.com leads to a private address, so Fuobe's server won't call it." });+ const priv = await hostedAddressRefusal("comfyUrl", "https://lan.example.com", { resolve: to(["93.184.216.34", "10.0.0.5"]) });+ expect(priv?.code).toBe("on-your-computer");+ expect(priv?.detail).not.toContain("10.");+ expect(await hostedAddressRefusal("comfyUrl", "https://meta.example.com", { resolve: to(["169.254.169.254"]) })).not.toBeNull();+ expect(await hostedAddressRefusal("comfyUrl", "https://gpu.example.com", { resolve: to(["93.184.216.34"]) })).toBeNull();+ // A name that doesn't resolve goes on: the test itself says it can't reach it.+ expect(await hostedAddressRefusal("comfyUrl", "https://nowhere.example.com", { resolve: async () => Promise.reject(new Error("ENOTFOUND")) })).toBeNull();+ });++ it("while ComfyUI runs on the owner's computer, a server address is tested as a server when the page says so", async () => {+ setSetting("comfyWhere", "computer");+ // As before: the computer's word (no tab open).+ expect((await connectTest({ values: { comfyUrl: fake.url } })).body).toEqual({ ok: false, detail: RELAY_WORDS.noComputer });+ // With comfyWhere "server" among the values: the address itself answers.+ const r = await connectTest({ values: { comfyUrl: fake.url, comfyWhere: "server" } });+ expect(r.body.ok).toBe(true);+ expect(r.body.detail).not.toMatch(/on your computer/);+ expect(r.fetched.some((u) => u.startsWith(`${fake.url}/system_stats`))).toBe(true);+ // Nothing was saved by the test.+ expect(getSetting("comfyWhere")).toBe("computer");+ });+});++describe("the owner's computer in GET /api/status", () => {+ const KEYS = ["mode", "online", "comfy", "guard", "device", "vramBytes", "version", "port", "cors"];++ it("is absent in server mode, and said honestly in computer mode while ComfyUI stays configured", async () => {+ expect((await status()).ownerGpu).toBeUndefined();+ setSetting("comfyWhere", "computer");+ let s = await status();+ expect(s.ownerGpu).toEqual({ mode: "computer", online: false });+ expect(s.providers.comfyui.configured).toBe(true);++ expect((await beat(owner, { port: 8188, facts: { device: "cuda:0 NVIDIA GeForce RTX 5090 : cudaMallocAsync", vramBytes: 34_190_000_000, version: "0.42.0", cors: "exact", guard: true } })).status).toBe(200);+ s = await status();+ expect(s.ownerGpu).toEqual({ mode: "computer", online: true, guard: true, device: "cuda:0 NVIDIA GeForce RTX 5090 : cudaMallocAsync", vramBytes: 34_190_000_000, version: "0.42.0", port: 8188, cors: "exact" });+ for (const k of Object.keys(s.ownerGpu!)) expect(KEYS).toContain(k);++ await beat(owner, { ready: false });+ s = await status();+ expect(s.ownerGpu).toMatchObject({ online: false, comfy: "down" });+ await beat(owner, { ready: false, why: "setting" });+ expect((await status()).ownerGpu).toMatchObject({ online: false, comfy: "no-setting" });+ expect((await status()).providers.comfyui.configured).toBe(true);+ });++ it("is never in a guest's or an account's", async () => {+ setSetting("comfyWhere", "computer");+ await beat(owner, { facts: { device: "cuda:0 NVIDIA GeForce RTX 5090" } });+ for (const who of [null, account]) {+ const s = await status(who);+ expect(s.ownerGpu, String(who)).toBeUndefined();+ expect(JSON.stringify(s)).not.toContain("RTX 5090");+ }+ });+});++describe("GET /api/comfyui while ComfyUI runs on the owner's computer", () => {+ it("never asks a ComfyUI from here: checkmarks come from the computer's last check, none before one", async () => {+ setSetting("comfyWhere", "computer");+ fetched.length = 0;+ let body = await (await comfyuiRoute.GET(request("/api/comfyui"))).json();+ expect(body).toMatchObject({ reachable: false, where: "computer", checkedAt: null });+ const models = (body.workflows as { models: { file: string; folder: string; present: boolean | null }[] }[]).flatMap((w) => w.models);+ expect(models.length).toBeGreaterThan(0);+ expect(models.every((m) => m.present === null)).toBe(true);++ // The computer's tab sent a check: one folder has one file.+ const first = models[0];+ const have = { [first.file.split("/").pop()!]: 123 };+ const at = Date.now();+ writeSnapshot(+ { kind: "computer", key: "install", via: "browser" },+ { v: 1, via: "browser", checkedAt: at, tookMs: 10, reachable: true, devices: [], manager: { api: "none" }, nodes: { have: [], missing: [], total: 0, readAt: at, how: "object_info" }, combos: {}, packs: {}, models: { [first.folder]: { have, total: 1 } }, loras: {}, fingerprint: "x", errors: [] } as never,+ );+ await beat(owner, {});+ body = await (await comfyuiRoute.GET(request("/api/comfyui"))).json();+ expect(body).toMatchObject({ reachable: true, where: "computer", checkedAt: at });+ const after = (body.workflows as { models: { file: string; folder: string; present: boolean | null }[] }[]).flatMap((w) => w.models);+ expect(after.find((m) => m.file === first.file && m.folder === first.folder)?.present).toBe(true);+ expect(after.some((m) => m.folder === first.folder && m.file !== first.file && m.present === false)).toBe(true);+ // Folders the check didn't read stay unknown.+ expect(after.some((m) => m.folder !== first.folder && m.present === null)).toBe(true);+ expect(fetched).toEqual([]);+ });++ it("tells an account nothing of the owner's", async () => {+ setSetting("comfyWhere", "computer");+ const body = await (await comfyuiRoute.GET(request("/api/comfyui", { cookie: account }))).json();+ expect(body.reachable).toBeNull();+ expect(body.where).toBeUndefined();+ expect((body.workflows as { models: { present: unknown }[] }[]).every((w) => w.models.every((m) => m.present === null))).toBe(true);+ });+});++describe("runs", () => {+ const run = (body: Record<string, unknown>, o: { cookie?: string; headers?: Record<string, string> } = {}) => generationsRoute.POST(request("/api/generations", { body, ...o }));+ const relayTasks = () => (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n;++ it("a workflow for the isolated worker is refused on the owner's computer before anything is queued", async () => {+ setSetting("comfyWhere", "computer");+ const before = relayTasks();+ const r = await run({ feature: "audio", modelId: "oss-thinksound", prompt: "a door slams" });+ const j = await r.json();+ expect(r.status, JSON.stringify(j)).toBe(422);+ expect(j.error).toBe(ISOLATED_ON_COMPUTER);+ expect(relayTasks()).toBe(before);+ });++ it("nothing connected runs it: the owner's own page gets the Connect your GPU marker, a script's token never does", async () => {+ const page = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" });+ expect(page.status).toBe(422);+ expect(page.headers.get(CONNECT_GPU_HEADER)).toBe("1");+ expect(await page.json()).toMatchObject({ code: "connect-gpu", error: "Connect ComfyUI in Settings to run this model" });++ const { token } = auth.createToken("script");+ const script = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" }, { cookie: null as never, headers: { authorization: `Bearer ${token}` } });+ expect(script.status).toBe(422);+ expect(script.headers.get(CONNECT_GPU_HEADER)).toBeNull();+ expect((await script.json()).code).toBeUndefined();++ // An account's refusal is its own (403), as before.+ auth.setAccountGpu(accountId, null);+ try {+ const acct = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" }, { cookie: account });+ expect(acct.status).toBe(403);+ expect(acct.headers.get(CONNECT_GPU_HEADER)).toBe("1");+ } finally {+ auth.setAccountGpu(accountId, { mode: "computer" });+ }+ });++ it("a script's open-source run while ComfyUI is on the owner's computer says it waits for that computer", async () => {+ setSetting("comfyWhere", "computer");+ const { token } = auth.createToken("script 2");+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" }, { cookie: null as never, headers: { authorization: `Bearer ${token}` } });+ const j = await r.json();+ expect(r.status, JSON.stringify(j)).toBe(201);+ expect(j.notes).toContain(RUNS_ON_COMPUTER_NOTE);+ });++ it("a finished result on the owner's computer is the owner's alone, and is kept if ComfyUI moved meanwhile", async () => {+ setSetting("comfyWhere", "computer");+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk" });+ expect(r.status).toBe(201);+ const id = ((await r.json()).items as { id: string }[])[0].id;+ const tick = () => globalThis.__fuobeRunner?.tick();+ const task = async () => db().prepare("SELECT id, state, principal FROM relay_tasks WHERE generation_id = ?").get(id) as { id: string; state: string; principal: string } | undefined;+ for (let i = 0; i < 200 && !(await task()); i++) {+ await tick();+ await new Promise((res) => setTimeout(res, 20));+ }+ expect((await task())?.principal).toBe("owner");+ // An account's tab never gets the owner's job.+ const theirs = tab(routes, account, fake.port, { device: "device-acct-1" });+ await theirs.runner.beat();+ await theirs.runner.claimAndRun();+ expect((await task())?.state).toBe("waiting");+ // The owner's tab runs it to the end of the task (the server hasn't kept the result yet).+ const mine = tab(routes, owner, fake.port, { device: "device-owner-1" });+ await mine.runner.beat();+ await mine.runner.claimAndRun();+ const t = await task();+ expect(t?.state).toBe("done");+ const url = `relay:${t!.id}/view?filename=x.png&n=0`;+ // ComfyUI moves to the server just then: the owner's result is still found, never as an account.+ setSetting("comfyWhere", "server");+ expect(relayFile(url)).not.toBeNull();+ expect(asAccount(accountId, () => relayFile(url))).toBeNull();+ for (let i = 0; i < 100; i++) {+ await tick();+ const g = getGeneration(id);+ if (g && g.status !== "queued" && g.status !== "running") break;+ await new Promise((res) => setTimeout(res, 30));+ }+ expect(getGeneration(id)?.status).toBe("succeeded");+ });+});++describe("no owner secret reaches a page", () => {+ it("not the ComfyUI token, not a key, not in any answer the owner's or a visitor's page reads", async () => {+ setSetting("comfyToken", "comfy-secret-token-123456");+ setSetting("anthropicKey", "sk-ant-secret-key-123456");+ setSetting("comfyWhere", "computer");+ await beat(owner, { facts: { device: "cuda:0 NVIDIA GeForce RTX 5090" } });+ try {+ const answers = [+ await (await statusRoute.GET(request("/api/status"))).text(),+ await (await statusRoute.GET(request("/api/status", { cookie: account }))).text(),+ await (await meRoute.GET(request("/api/auth/me"))).text(),+ await (await comfyuiRoute.GET(request("/api/comfyui"))).text(),+ await (await routes.claim.POST(request("/api/gpu/computer/claim", { body: { device: "device-owner-1" } }), { params: Promise.resolve({}) })).text(),+ ];+ for (const a of answers) {+ expect(a).not.toContain("comfy-secret-token");+ expect(a).not.toContain("sk-ant-secret");+ }+ } finally {+ setSetting("comfyToken", "");+ setSetting("anthropicKey", "");+ }+ });+});diff --git a/tests/page-place.test.ts b/tests/page-place.test.tsnew file mode 100644index 00000000..ce3d81c7--- /dev/null+++ b/tests/page-place.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from "vitest";+import { addressHost, addressKind, hostKind, ownerSteer, pagePlace, refusedLine, refusedOnHosted } from "@/lib/page-place";++describe("where the page is (its own hostname)", () => {+ it("on the server's machine: localhost, *.localhost, 127/8 and ::1", () => {+ for (const h of ["localhost", "a.localhost", "127.0.0.1", "127.0.0.2", "[::1]", "::1", "LOCALHOST", "localhost."]) expect(pagePlace(h), h).toBe("here");+ });+ it("on its network: private and link-local literals, CGNAT, ULA, single-label and LAN names", () => {+ for (const h of ["192.168.1.10", "10.1.2.3", "172.16.0.9", "100.101.102.103", "169.254.1.1", "[fd00::1]", "[fe80::1]", "studio", "nas.lan", "x.home.arpa", "box.local", "pc.internal", "pc.localdomain"])+ expect(pagePlace(h), h).toBe("network");+ });+ it("hosted: a public name or a public address, in any case and with a trailing dot", () => {+ for (const h of ["fuobe.com", "FUOBE.COM", "fuobe.com.", "studio.test", "203.0.113.9", "[2001:db8::1]"]) expect(pagePlace(h), h).toBe("hosted");+ });+});++describe("what a typed ComfyUI address means to a server", () => {+ const cases: [string, ReturnType<typeof addressKind>][] = [+ ["http://127.0.0.1:8188", "loopback"],+ ["127.0.0.1:8188", "loopback"],+ ["http://localhost:8188/", "loopback"],+ ["localhost:3399", "loopback"],+ ["http://comfy.localhost:8188", "loopback"],+ ["http://0.0.0.0:8188", "loopback"],+ ["http://[::1]:8188", "loopback"],+ ["http://[::]:8188", "loopback"],+ ["http://[::ffff:127.0.0.1]:8188", "loopback"],+ ["HTTP://LOCALHOST:8188", "loopback"],+ ["http://10.255.255.1:3399", "private"],+ ["http://172.20.1.1", "private"],+ ["http://192.168.1.5:8188/api", "private"],+ ["http://100.101.102.103:8188", "private"],+ ["http://[fd00::1]:8188", "private"],+ ["http://[::ffff:10.0.0.5]", "private"],+ ["http://169.254.169.254", "link-local"],+ ["http://169.254.0.1:3399", "link-local"],+ ["http://[fe80::1]:8188", "link-local"],+ ["http://nas.local:3399", "local-name"],+ ["http://studio:8188", "local-name"],+ ["http://box.lan.", "local-name"],+ ["https://abc.trycloudflare.com", "public"],+ ["https://gpu.example.com:8443/comfy", "public"],+ ["http://203.0.113.9:8188", "public"],+ ["http://172.32.0.1", "public"],+ ["http://100.128.0.1", "public"],+ ["ftp://example.com", "invalid"],+ ["not an address at all", "invalid"],+ ["http://", "invalid"],+ ["", "invalid"],+ ];+ it.each(cases)("%s is %s", (url, kind) => expect(addressKind(url)).toBe(kind));++ it("names the host as the sentence shows it", () => {+ expect(addressHost("http://127.0.0.1:8188/x")).toBe("127.0.0.1");+ expect(addressHost("localhost:3399")).toBe("localhost");+ expect(addressHost("http://[::1]:8188")).toBe("[::1]");+ expect(addressHost("nope nope")).toBe("");+ });++ it("is the same for a bare host", () => {+ expect(hostKind("127.0.0.1")).toBe("loopback");+ expect(hostKind("[fe80::1]")).toBe("link-local");+ expect(hostKind("gpu.example.com")).toBe("public");+ });+});++describe("what a hosted page never sends", () => {+ it("loopback and link-local always; private and LAN names unless the server allows private addresses", () => {+ expect(refusedOnHosted("loopback", false)).toBe(true);+ expect(refusedOnHosted("loopback", true)).toBe(true);+ expect(refusedOnHosted("link-local", true)).toBe(true);+ expect(refusedOnHosted("private", false)).toBe(true);+ expect(refusedOnHosted("private", true)).toBe(false);+ expect(refusedOnHosted("local-name", false)).toBe(true);+ expect(refusedOnHosted("local-name", true)).toBe(false);+ expect(refusedOnHosted("public", false)).toBe(false);+ expect(refusedOnHosted("invalid", false)).toBe(false);+ });++ it("says what the address means here, in one line", () => {+ expect(refusedLine("loopback", "127.0.0.1")).toBe("On this website, 127.0.0.1 is Fuobe's server, not your computer.");+ expect(refusedLine("private", "10.0.0.5")).toBe("10.0.0.5 is on your own network, which Fuobe's server can't reach.");+ expect(refusedLine("local-name", "nas.local")).toBe("nas.local is on your own network, which Fuobe's server can't reach.");+ });+});++describe("how the owner's GPU is offered", () => {+ const off = { engineMode: "open", providers: { comfyui: { configured: false } } };+ const on = { engineMode: "open", providers: { comfyui: { configured: true } } };+ it("ComfyUI on the owner's computer, wherever the page is", () => {+ expect(ownerSteer("hosted", off, "computer")).toBe("computer");+ expect(ownerSteer("here", on, "computer")).toBe("computer");+ });+ it("a connected server ComfyUI wins, wherever the page is", () => {+ expect(ownerSteer("hosted", on, "server")).toBe("server");+ expect(ownerSteer("here", on, "server")).toBe("server");+ });+ it("hosted with nothing connected: the computer first; local: as before", () => {+ expect(ownerSteer("hosted", off, "server")).toBe("hosted");+ expect(ownerSteer("here", off, "server")).toBe("local");+ expect(ownerSteer("network", off, "server")).toBe("local");+ expect(ownerSteer("hosted", { ...off, engineMode: "cloud" }, "server")).toBe("local");+ });+ it("unknown until the page and the status are", () => {+ expect(ownerSteer(null, off, "server")).toBeNull();+ expect(ownerSteer("hosted", undefined, "server")).toBeNull();+ });+});