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.

Your GPU: accounts run on their own ComfyUI, and see their own studio

Adarsh3a572dcbc97c
diff --git a/docs/public-signup.md b/docs/public-signup.md
index b3d70400..078d3254 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -50,13 +50,18 @@ An account is signed in, but it sees the owner's studio as a guest does:
owner's results, files, uploads, folders, shares, projects (Layers, Cinema, Canvas, storyboards,
elements…) and Assist threads are hidden: the lists come back empty, and other reads answer 403.
Every change to them (create, rename, move, share, delete, upload) answers 403 with
- `code: "library"`. Accounts don't have a library of their own yet.
+ `code: "library"`. Accounts have only their own runs (below), no uploads or projects yet.
- **Settings, keys and tokens are the owner's.** Changing settings or model switches, the password,
API tokens, Public sign-up, LoRA downloads, Assist connectors and the MCP endpoint answer 403 for
an account.
-- **Accounts never run on the owner's keys or GPU.** Anything that would reach a model (a
- generation, an AI helper, a retry) answers 403 with `code: "connect-gpu"`, and the studio shows a
- "Connect your GPU to run this" card. An account's own GPU connection comes in a later change.
+- **Accounts never run on the owner's keys or GPU.** An account runs only on its own ComfyUI (see
+ [Your GPU](#your-gpu)). Without one, anything that would reach a model (a generation, an AI
+ helper, a retry) answers 403 with `code: "connect-gpu"`, and the studio shows a "Connect your GPU
+ to run this" card.
+- **Its own runs are its own.** The runs an account starts on its GPU appear in its own lists
+ (`GET /api/generations`), and it can open, cancel and delete them and download their files. They
+ stay out of the owner's lists, and no other account can open them. The live-updates stream isn't
+ sent to accounts: their studios poll instead.
## Managing accounts
@@ -68,8 +73,52 @@ with `{ "disabled": true | false }`, and `DELETE /api/admin/accounts/<id>`, for
An account can delete itself: `DELETE /api/auth/me` with `{ "password" }`.
+## Your GPU
+
+An account connects its own ComfyUI in **Settings → Your GPU**, or from the "Connect your GPU" card.
+The studio's server calls that ComfyUI, so it must be reachable from the internet. Put a tunnel in
+front of a local ComfyUI and paste the https address it prints:
+
+```bash
+cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
+```
+
+- **Finding ComfyUI.** The page looks for a ComfyUI on the visitor's own computer, from the browser
+ (the server can't see that computer). It tries `http://127.0.0.1` on ports 8188, 8000 (ComfyUI
+ Desktop), 8189, 8190 and 8288. When ComfyUI answers, the page names the GPU and its VRAM and shows
+ the tunnel command. When a port answers but the browser can't read it, ComfyUI was started
+ without CORS: the page shows the flag to add, `--enable-cors-header https://fuobe.com`. Chrome
+ may ask to let the site reach devices on the local network. When nothing answers, the visitor
+ can enter a port or an address. A local address is used only by the browser and is never sent to
+ the server.
+- **Saving.** `PUT /api/account/gpu` with `{ "url", "token"? }` checks the address and asks that
+ ComfyUI for `/system_stats` (`?test=1` checks without saving). `DELETE` disconnects. The address
+ and the optional token (sent as `Authorization: Bearer`) are stored with the account in
+ `auth.json`, never as the studio's ComfyUI setting.
+- **Server-side requests.** Addresses on the server itself, on private networks or link-local
+ addresses are refused. The check runs again on the address each connection actually uses, so a
+ name that is later pointed at the server can't reach the studio's own ComfyUI. The studio's own
+ ComfyUI address is refused too. `FUOBE_ALLOW_PRIVATE_URLS=1` allows private addresses, for a LAN
+ install.
+- **Runs.** The Image, Video and Audio studios' generations (`POST /api/generations`) run on the
+ account's ComfyUI with the open-source engine. Polls, uploads, outputs and cancels go there too,
+ and nothing falls back to the studio's own providers. If the account's ComfyUI can't be reached,
+ the run fails and says so. A cloud model, an AI helper or the studio's local LLM is refused. Other
+ tools (Canvas, Cinema, Assist…) answer 403 with `code: "own-gpu-tool"`, because they plan with
+ the studio's own AI helpers. A LoRA must already be on the account's ComfyUI: the studio
+ downloads LoRAs only into its own folder. Accounts can't upload files yet, so runs that start
+ from a picture or a clip aren't available to them.
+- **What a visitor sees.** For a guest or an account, `GET /api/status` describes its own GPU
+ (`viewer`), with the open engine and no Demo mode. It says nothing about the studio's own
+ ComfyUI, providers, keys or local AI servers. The sidebar shows **Your GPU · Connect** (a guest
+ signs up first), or the account's ComfyUI as online or offline with its GPU and VRAM.
+ `GET /api/models` lists the open-source models for a visitor, and the studios price a visitor's
+ run as it would go on its own GPU. The studio's own settings page isn't shown to visitors.
+
`GET /api/auth/me` (open to everyone) says who is looking: `{ signedIn, owner, publicSignup,
account? }`.
The rules are in `src/lib/guest-access.ts` (which paths guests and accounts may use) and
-`src/proxy.ts` (where they are applied). The tests are in `tests/public-signup.test.ts`.
+`src/proxy.ts` (where they are applied). Your GPU is `src/server/account-gpu.ts`, `onOwnGpu` in
+`src/server/providers/comfyui.ts` and `accountRun` in `src/server/generations.ts`. The tests are in
+`tests/public-signup.test.ts`, `tests/accounts-admin.test.ts` and `tests/account-gpu.test.ts`.
diff --git a/src/app/(studio)/settings/page.tsx b/src/app/(studio)/settings/page.tsx
index fa454a9f..cc47de84 100644
--- a/src/app/(studio)/settings/page.tsx
+++ b/src/app/(studio)/settings/page.tsx
@@ -1,5 +1,7 @@
import type { Metadata } from "next";
import { AccountsAdmin } from "@/components/accounts-admin";
+import { AccountGpuSection } from "@/components/gpu/account-gpu-section";
+import { OwnerSettings } from "@/components/owner-settings";
import { PageHeader, PageShell } from "@/components/page-shell";
import { SettingsForm } from "@/components/settings-form";
import { starterPriceLine } from "@/lib/starter-prices";
@@ -10,7 +12,10 @@ export default function Page() {
return (
<PageShell>
<PageHeader title="Settings" description="Choose open source, paid APIs or both, connect providers, point Fuobe at your ComfyUI server, and choose how prompts get enhanced. Keys stay on this server." />
- <SettingsForm prices={starterPriceLine()} />
+ <AccountGpuSection />
+ <OwnerSettings>
+ <SettingsForm prices={starterPriceLine()} />
+ </OwnerSettings>
<AccountsAdmin />
</PageShell>
);
diff --git a/src/app/api/account/gpu/route.ts b/src/app/api/account/gpu/route.ts
new file mode 100644
index 00000000..083b1c83
--- /dev/null
+++ b/src/app/api/account/gpu/route.ts
@@ -0,0 +1,49 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { checkGpuAddress, GpuError, testGpu } from "@/server/account-gpu";
+import { accountGpu, requestAccount, setAccountGpu } from "@/server/auth";
+
+/**
+ * "Your GPU" (public sign-up): the account's own ComfyUI, where its runs go. GET says what is
+ * connected (never the token); PUT checks the address and asks the ComfyUI for /system_stats, then
+ * saves it (`?test=1`: check only); DELETE disconnects. Accounts only: the owner's ComfyUI is in Settings.
+ */
+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 });
+
+export async function GET(request: Request) {
+ await connection();
+ const a = await account(request);
+ if (!a) return notAccount();
+ const gpu = accountGpu(a.id);
+ return Response.json({ gpu: gpu ? { url: gpu.url, hasToken: !!gpu.token } : null });
+}
+
+const Body = z.object({ url: z.string().min(1).max(500), token: z.string().max(500).optional() });
+
+export async function PUT(request: Request) {
+ const a = await account(request);
+ if (!a) return notAccount();
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Enter your ComfyUI's address" }, { status: 400 });
+ try {
+ const url = await checkGpuAddress(parsed.data.url);
+ // A token left empty keeps the saved one when the address is the same.
+ const saved = accountGpu(a.id);
+ const token = parsed.data.token?.trim() || (saved?.url === url ? saved.token : undefined);
+ const info = await testGpu({ url, token });
+ if (new URL(request.url).searchParams.get("test") !== "1") setAccountGpu(a.id, { url, token });
+ return Response.json({ gpu: { url, hasToken: !!token }, info });
+ } catch (e) {
+ if (e instanceof GpuError) return Response.json({ error: e.message }, { status: 422 });
+ throw e;
+ }
+}
+
+export async function DELETE(request: Request) {
+ const a = await account(request);
+ if (!a) return notAccount();
+ setAccountGpu(a.id, null);
+ return Response.json({ gpu: null });
+}
diff --git a/src/app/api/ads/estimate/route.ts b/src/app/api/ads/estimate/route.ts
index ae2d9285..1f7c3ffa 100644
--- a/src/app/api/ads/estimate/route.ts
+++ b/src/app/api/ads/estimate/route.ts
@@ -1,8 +1,9 @@
import { BatchBody, estimateBatch } from "@/server/ads";
import { readBody } from "@/server/marketing";
+import { priceAs } from "@/server/visitor";
/** The total before the run: ads × price per ad (+ the copy), and which model renders them. */
-export async function POST(request: Request) {
+async function post(request: Request) {
const body = await readBody(request, BatchBody, "Pick products and how many ads to make");
if (body instanceof Response) return body;
try {
@@ -11,3 +12,8 @@ export async function POST(request: Request) {
return Response.json({ costUsd: null, total: 0, perAd: null, demo: false, blocker: (e as Error).message });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/ads/multiplier/estimate/route.ts b/src/app/api/ads/multiplier/estimate/route.ts
index a8d6f938..5b9c5c26 100644
--- a/src/app/api/ads/multiplier/estimate/route.ts
+++ b/src/app/api/ads/multiplier/estimate/route.ts
@@ -1,6 +1,7 @@
import { estimateMultiplier, MultiplierBody, readBody } from "@/server/marketing";
+import { priceAs } from "@/server/visitor";
-export async function POST(request: Request) {
+async function post(request: Request) {
const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");
if (body instanceof Response) return body;
try {
@@ -9,3 +10,8 @@ export async function POST(request: Request) {
return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/assist/skills/[name]/estimate/route.ts b/src/app/api/assist/skills/[name]/estimate/route.ts
index b9a851f9..d07f5cc7 100644
--- a/src/app/api/assist/skills/[name]/estimate/route.ts
+++ b/src/app/api/assist/skills/[name]/estimate/route.ts
@@ -1,8 +1,9 @@
import { badBody, recipeFailure, RunBody } from "@/server/recipe-routes";
import { estimateRecipe } from "@/server/recipes";
+import { priceAs } from "@/server/visitor";
/** Price a run of a skill's recipe, or many (`rows` or `csv`, priced together with a total). Starts nothing. */
-export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/estimate">) {
+async function post(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/estimate">) {
const parsed = RunBody.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) return badBody(parsed.error.issues);
try {
@@ -12,3 +13,8 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/skil
return recipeFailure(e);
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/estimate">) {
+ return priceAs(request, () => post(request, ctx));
+}
diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.ts
index 3eee0776..c5fc1079 100644
--- a/src/app/api/audio-tools/route.ts
+++ b/src/app/api/audio-tools/route.ts
@@ -1,7 +1,8 @@
import { AudioToolBody, AudioToolError, previewAudioTool, runAudioTool } from "@/server/audio-tools";
+import { priceAs } from "@/server/visitor";
/** Audio → Loop / extend and Join: start a run; `?preview=1` only plans and prices it. */
-export async function POST(request: Request) {
+async function post(request: Request) {
const parsed = AudioToolBody.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
const path = parsed.error.issues[0]?.path.join(".") ?? "";
@@ -25,3 +26,8 @@ export async function POST(request: Request) {
return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/content-factory/estimate/route.ts b/src/app/api/content-factory/estimate/route.ts
index e27435c2..b74f9048 100644
--- a/src/app/api/content-factory/estimate/route.ts
+++ b/src/app/api/content-factory/estimate/route.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import { BriefSchema, estimateSeries, handle, SeriesInputSchema } from "@/server/content-factory";
import { body } from "@/server/faceless";
+import { priceAs } from "@/server/visitor";
const Ask = SeriesInputSchema.extend({
seriesId: z.string().max(20).optional(),
@@ -9,6 +10,11 @@ const Ask = SeriesInputSchema.extend({
});
/** What the whole series would cost (one episode at the brief's pace × the episodes), and whether it runs as a demo. */
-export async function POST(request: Request) {
+async function post(request: Request) {
return handle(async () => Response.json(estimateSeries(await body(request, Ask, "Those settings aren't valid"))));
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/dub/[id]/voice/route.ts b/src/app/api/dub/[id]/voice/route.ts
index 88efd6d9..f56e7fd7 100644
--- a/src/app/api/dub/[id]/voice/route.ts
+++ b/src/app/api/dub/[id]/voice/route.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { CueSchema, getDubSession, previewVoiceDub, voiceDub } from "@/server/dub";
+import { priceAs } from "@/server/visitor";
const Body = z.object({
lang: z.string().min(2).max(12),
@@ -9,7 +10,7 @@ const Body = z.object({
});
/** Speak one language's reviewed lines in the cloned voice: the voice pipeline; `?preview=1` only prices it. */
-export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) {
+async function post(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) {
const { id } = await ctx.params;
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Pick the language to voice" }, { status: 400 });
@@ -22,3 +23,8 @@ export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/vo
return Response.json({ error: (e as Error).message }, { status: 422 });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) {
+ return priceAs(request, () => post(request, ctx));
+}
diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.ts
index d0ed2bdb..60ffef47 100644
--- a/src/app/api/dub/route.ts
+++ b/src/app/api/dub/route.ts
@@ -2,6 +2,7 @@ import { connection } from "next/server";
import { z } from "zod";
import { ONE_SHOT_MODELS } from "@/lib/av/dub";
import { createDubSession, listDubSessions, previewDub } from "@/server/dub";
+import { priceAs } from "@/server/visitor";
const Body = z.object({
engine: z.enum(["cloud", "open"]),
@@ -23,7 +24,7 @@ export async function GET(request: Request) {
}
/** Start a dub: one-shot jobs (cloud) or the prepare pipeline (both engines); `?preview=1` only prices it. */
-export async function POST(request: Request) {
+async function post(request: Request) {
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
const first = parsed.error.issues[0];
@@ -37,3 +38,8 @@ export async function POST(request: Request) {
return Response.json({ error: (e as Error).message }, { status: 422 });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/evolution/estimate/route.ts b/src/app/api/evolution/estimate/route.ts
index 2dabbcb7..99391f00 100644
--- a/src/app/api/evolution/estimate/route.ts
+++ b/src/app/api/evolution/estimate/route.ts
@@ -1,10 +1,16 @@
import { estimateEvolution, EvolutionEstimateSchema } from "@/server/evolution";
import { body, handle } from "@/server/shorts-schemas";
+import { priceAs } from "@/server/visitor";
/** The price, the pieces and the notes for the current settings, before anything runs ("Free" on your GPU). */
-export async function POST(request: Request) {
+async function post(request: Request) {
return handle(async () => {
const input = await body(request, EvolutionEstimateSchema, "Add a clip and pick how much should change");
return Response.json(estimateEvolution(input));
});
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/faceless/estimate/route.ts b/src/app/api/faceless/estimate/route.ts
index d69688fa..e71be54b 100644
--- a/src/app/api/faceless/estimate/route.ts
+++ b/src/app/api/faceless/estimate/route.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { BlockSchema, body, estimateEpisode, GenreSchema, handle, SettingsSchema } from "@/server/faceless";
+import { priceAs } from "@/server/visitor";
const Ask = z.object({
kind: z.enum(["faceless", "explainer"]),
@@ -9,6 +10,11 @@ const Ask = z.object({
});
/** What an episode would cost (by part), whether it runs as a demo, and what's in the way. */
-export async function POST(request: Request) {
+async function post(request: Request) {
return handle(async () => Response.json(estimateEpisode(await body(request, Ask, "Those settings aren't valid"))));
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index f6da8919..a0bb0b16 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,6 +1,8 @@
import { connection } from "next/server";
+import { CONNECT_GPU_HEADER } from "@/lib/guest-access";
+import { accountGpu, requestAccount, requestViewer } from "@/server/auth";
import { OPERATION_LABELS } from "@/lib/catalog/types";
-import { createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";
+import { accountRun, asVisitor, createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";
import { ensureTrashPurge, listOptionsFrom } from "@/server/library";
import { GenerationRequestSchema } from "@/server/request-schema";
@@ -13,7 +15,9 @@ import { GenerationRequestSchema } from "@/server/request-schema";
export async function GET(request: Request) {
await connection();
ensureTrashPurge();
- return Response.json({ items: listGenerations(listOptionsFrom(new URL(request.url).searchParams)) });
+ // An account (public sign-up) lists only its own runs; the owner only theirs.
+ const account = requestAccount(request);
+ return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), account: account?.id }) });
}
/** Start a generation; `?preview=1` only says what it would run as (model, operation, jobs, outputs, cost). */
@@ -24,13 +28,25 @@ export async function POST(request: Request) {
}
// A retired model id (an older script, a saved CLI or MCP call) runs on the model that replaced it, and the notes say
// so: previewGeneration and createGenerations move it (generations.ts currentRequest, replaced.ts).
- const req = parsed.data as Parameters<typeof createGenerations>[0];
+ const asked = parsed.data as Parameters<typeof createGenerations>[0];
+ // Public sign-up: an account runs on its own ComfyUI only (the open engine), never the install's providers.
+ const viewer = requestViewer(request);
+ const account = viewer.kind === "account" ? viewer.account : null;
+ const req = account ? { ...asked, account: account.id, engine: "open" as const } : { ...asked, account: undefined };
+ const own = account ? accountRun(account.id, "comfyui") : undefined;
+ const preview = new URL(request.url).searchParams.get("preview") === "1";
+ if (own && "error" in own && !preview) {
+ return Response.json({ error: own.error, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
+ }
+ const onOwn = <T,>(fn: () => T): T => (own && "run" in own ? own.run(fn) : fn());
+ // A visitor's price check: priced as it would run, on its own GPU (none yet: the open engine, no demo).
+ const priced = <T,>(fn: () => T): T => (viewer.kind === "owner" ? fn() : asVisitor(account ? accountGpu(account.id) : null, fn));
try {
- if (new URL(request.url).searchParams.get("preview") === "1") {
- const { model, ...p } = previewGeneration(req);
+ if (preview) {
+ const { model, ...p } = priced(() => previewGeneration(req));
return Response.json({ ...p, modelId: model.id, modelName: model.name, engine: model.engine, kind: outputKind(p.op, model), opLabel: OPERATION_LABELS[p.op] ?? p.op });
}
- const items = createGenerations(req);
+ const items = onOwn(() => createGenerations(req));
// 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 notes = [...new Set(items.flatMap((g) => g.notes ?? []))];
return Response.json({ items, ...(notes.length && { notes }) }, { status: 201 });
diff --git a/src/app/api/genjutsu/estimate/route.ts b/src/app/api/genjutsu/estimate/route.ts
index fdab6c41..b5465048 100644
--- a/src/app/api/genjutsu/estimate/route.ts
+++ b/src/app/api/genjutsu/estimate/route.ts
@@ -1,10 +1,16 @@
import { estimateGenjutsu, GenjutsuEstimateSchema } from "@/server/genjutsu";
import { body, handle } from "@/server/shorts-schemas";
+import { priceAs } from "@/server/visitor";
/** The price, the model, the pieces and the notes for the current settings, before anything runs. */
-export async function POST(request: Request) {
+async function post(request: Request) {
return handle(async () => {
const input = await body(request, GenjutsuEstimateSchema, "Add a clip and pick a mode");
return Response.json(await estimateGenjutsu(input));
});
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/influencer/estimate/route.ts b/src/app/api/influencer/estimate/route.ts
index 09326e16..b37e88a6 100644
--- a/src/app/api/influencer/estimate/route.ts
+++ b/src/app/api/influencer/estimate/route.ts
@@ -1,11 +1,17 @@
import { POST as influencer } from "../route";
+import { priceAs } from "@/server/visitor";
/**
* The price of an AI Influencer run without starting it: the same body as POST /api/influencer?preview=1, at the
* `<route>/estimate` path the evaluation harness prices studio routes at.
*/
-export async function POST(request: Request) {
+async function post(request: Request) {
const url = new URL(request.url.replace(/\/estimate(?=\/?(\?|$))/, ""));
url.searchParams.set("preview", "1");
return influencer(new Request(url, { method: "POST", headers: request.headers, body: await request.text() }));
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/katana/route.ts b/src/app/api/katana/route.ts
index ddf27759..bf5c6dc6 100644
--- a/src/app/api/katana/route.ts
+++ b/src/app/api/katana/route.ts
@@ -1,5 +1,6 @@
import { connection } from "next/server";
import { createKatana, KatanaBody, listKatana, previewKatana } from "@/server/katana";
+import { priceAs } from "@/server/visitor";
/** Recent Katana runs with the state of every step. */
export async function GET(request: Request) {
@@ -9,7 +10,7 @@ export async function GET(request: Request) {
}
/** Start a run; `?preview=1` only plans and prices it (segments, steps, cost). */
-export async function POST(request: Request) {
+async function post(request: Request) {
const parsed = KatanaBody.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
const path = String(parsed.error.issues[0]?.path[0] ?? "");
@@ -23,3 +24,8 @@ export async function POST(request: Request) {
return Response.json({ error: (e as Error).message }, { status: 422 });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/marketing/click-to-ad/estimate/route.ts b/src/app/api/marketing/click-to-ad/estimate/route.ts
index f62da1b4..06fc30d0 100644
--- a/src/app/api/marketing/click-to-ad/estimate/route.ts
+++ b/src/app/api/marketing/click-to-ad/estimate/route.ts
@@ -1,6 +1,7 @@
import { ClickToAdBody, estimateClickToAd, readBody } from "@/server/marketing";
+import { priceAs } from "@/server/visitor";
-export async function POST(request: Request) {
+async function post(request: Request) {
const body = await readBody(request, ClickToAdBody, "Select a product or enter a product URL");
if (body instanceof Response) return body;
try {
@@ -9,3 +10,8 @@ export async function POST(request: Request) {
return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/marketing/estimate/route.ts b/src/app/api/marketing/estimate/route.ts
index eb50509b..e07d30dd 100644
--- a/src/app/api/marketing/estimate/route.ts
+++ b/src/app/api/marketing/estimate/route.ts
@@ -1,7 +1,8 @@
import { estimateMarketing, MarketingBody, readBody } from "@/server/marketing";
+import { priceAs } from "@/server/visitor";
/** Price and check a Marketing Studio run before it starts; what's missing comes back as `blocker`. */
-export async function POST(request: Request) {
+async function post(request: Request) {
const body = await readBody(request, MarketingBody);
if (body instanceof Response) return body;
try {
@@ -10,3 +11,8 @@ export async function POST(request: Request) {
return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/mixed-media/estimate/route.ts b/src/app/api/mixed-media/estimate/route.ts
index 3f2dc7f1..dbc89c0c 100644
--- a/src/app/api/mixed-media/estimate/route.ts
+++ b/src/app/api/mixed-media/estimate/route.ts
@@ -1,10 +1,16 @@
import { estimateMixed } from "@/server/mixed-media";
import { MixedEstimateSchema, body, handle } from "@/server/shorts-schemas";
+import { priceAs } from "@/server/visitor";
/** Frames, cost of the render and of a preview frame, and notes for the current settings. */
-export async function POST(request: Request) {
+async function post(request: Request) {
return handle(async () => {
const input = await body(request, MixedEstimateSchema, "Pick a preset and the part of the clip to use");
return Response.json(await estimateMixed(input));
});
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts
index 06f9b58d..e3f45637 100644
--- a/src/app/api/models/route.ts
+++ b/src/app/api/models/route.ts
@@ -1,4 +1,5 @@
import { connection } from "next/server";
+import { requestViewer } from "@/server/auth";
import { getModel, MODELS } from "@/lib/catalog";
import { onEngine, runsOn } from "@/lib/catalog/engines";
import { ENGINE_MODELS } from "@/lib/catalog/faceless";
@@ -59,7 +60,9 @@ export async function GET(request: Request) {
if (engine && engine !== "open" && engine !== "cloud") return Response.json({ error: "engine is open or cloud" }, { status: 400 });
const op = p.get("op") || undefined;
if (op && !(op in OPERATION_LABELS)) return Response.json({ error: `Unknown operation ${op}` }, { status: 400 });
- const mode = engineMode();
+ // A guest or an account (public sign-up) runs open models on its own GPU: no cloud models, no demo.
+ const visitor = requestViewer(request).kind !== "owner";
+ const mode = visitor ? "open" : engineMode();
// A Fuobe Original runs on both engines: on a list for one engine (asked for, or the install's only one) it is
// that engine's model (its routes, its price), else it is listed once with both.
const only = (engine as Engine | undefined) ?? (mode === "both" ? undefined : mode);
@@ -73,6 +76,11 @@ export async function GET(request: Request) {
const defaults = Object.fromEntries(
Object.entries(DEFAULTS).map(([k, ids]) => [k, { ...(mode !== "open" && ids.cloud && { cloud: pick(ids.cloud, "cloud") }), ...(mode !== "cloud" && ids.open && { open: pick(ids.open, "open") }) }]),
);
- const demoMode = getSetting("demoMode");
- return Response.json({ engineMode: mode, demoMode, defaults, items: list.map((m) => ({ ...toModelInfo(m), connected: connected(m), runs: runsAs(m, demoMode) })) });
+ const demoMode = visitor ? "off" : getSetting("demoMode");
+ return Response.json({
+ engineMode: mode,
+ demoMode,
+ defaults,
+ items: list.map((m) => ({ ...toModelInfo(m), connected: visitor || connected(m), runs: visitor ? ("real" as const) : runsAs(m, demoMode) })),
+ });
}
diff --git a/src/app/api/remove-object/estimate/route.ts b/src/app/api/remove-object/estimate/route.ts
index 57e638d1..a5d54fae 100644
--- a/src/app/api/remove-object/estimate/route.ts
+++ b/src/app/api/remove-object/estimate/route.ts
@@ -1,10 +1,16 @@
import { estimateRemoval, RemovalEstimateSchema } from "@/server/remove-object";
import { body, handle } from "@/server/shorts-schemas";
+import { priceAs } from "@/server/visitor";
/** The price, the pieces and the notes for the current settings, before anything runs. */
-export async function POST(request: Request) {
+async function post(request: Request) {
return handle(async () => {
const input = await body(request, RemovalEstimateSchema, "Add a clip and pick how to point at what goes");
return Response.json(await estimateRemoval(input));
});
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/shorts/estimate/route.ts b/src/app/api/shorts/estimate/route.ts
index e9937d52..cce7d0ad 100644
--- a/src/app/api/shorts/estimate/route.ts
+++ b/src/app/api/shorts/estimate/route.ts
@@ -1,10 +1,16 @@
import { estimateShorts } from "@/server/shorts";
import { ShortsEstimateSchema, body, handle } from "@/server/shorts-schemas";
+import { priceAs } from "@/server/visitor";
/** What a session would cost (or that it runs as a demo), how many segments it makes, and notes. */
-export async function POST(request: Request) {
+async function post(request: Request) {
return handle(async () => {
const input = await body(request, ShortsEstimateSchema, "Pick a preset and the part of the clip to restyle");
return Response.json(await estimateShorts(input));
});
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.ts
index 71cdcf2b..1c1ea6a1 100644
--- a/src/app/api/status/route.ts
+++ b/src/app/api/status/route.ts
@@ -1,4 +1,6 @@
import { connection } from "next/server";
+import { visitorStatus } from "@/server/account-gpu";
+import { requestViewer } from "@/server/auth";
import { aiHelper, localSummary } from "@/server/llm";
import { PROVIDERS } from "@/server/providers";
import { comfyRam, probeComfy } from "@/server/providers/comfyui";
@@ -8,8 +10,11 @@ import { getSetting, setSetting } from "@/server/settings";
import { offeredSummary } from "@/server/model-access";
/** Which providers are usable right now — drives badges, the demo-mode notice and Home's first-run guide. */
-export async function GET() {
+export async function GET(request?: Request) {
await connection();
+ // A guest or an account (public sign-up) sees its own GPU, never the install's providers or servers.
+ const viewer = request ? requestViewer(request) : ({ kind: "owner" } as const);
+ if (viewer.kind !== "owner") return Response.json(await visitorStatus(viewer.kind === "account" ? viewer.account : null), { headers: { "Cache-Control": "no-store" } });
// Both asked first, so the llm provider's label and routing read fresh answers without waiting.
const [comfy, local] = await Promise.all([probeComfy(true), localSummary()]);
const ram = comfy ? comfyRam() : undefined;
diff --git a/src/app/api/storyboards/estimate/route.ts b/src/app/api/storyboards/estimate/route.ts
index d5ebde86..685728f5 100644
--- a/src/app/api/storyboards/estimate/route.ts
+++ b/src/app/api/storyboards/estimate/route.ts
@@ -1,7 +1,8 @@
import { estimateStoryboard, StoryboardBodySchema } from "@/server/storyboard";
+import { priceAs } from "@/server/visitor";
/** What a board costs before it runs ("Free" on your GPU): every frame, the look's model for frame 1. */
-export async function POST(request: Request) {
+async function post(request: Request) {
const parsed = StoryboardBodySchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => i.message).join("; ") }, { status: 400 });
try {
@@ -10,3 +11,8 @@ export async function POST(request: Request) {
return Response.json({ error: (e as Error).message }, { status: 422 });
}
}
+
+/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+export async function POST(request: Request) {
+ return priceAs(request, () => post(request));
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index b24cb806..fee3eab4 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -29,7 +29,7 @@ import { IntentLink } from "@/components/intent-link";
import { JobNotifications } from "@/components/job-notifications";
import { NAV, type NavGroupDef } from "@/components/nav-items";
import { SkillBuilderProvider } from "@/components/skills/skill-builder-provider";
-import { signInHref, useEngineMode, useIsGuest, useStatus } from "@/lib/api";
+import { CONNECT_GPU_EVENT, signInHref, useEngineMode, useIsGuest, useStatus, type StatusInfo } from "@/lib/api";
import { useModKey } from "@/lib/keys";
import { fullScreenStudio, groupId, NAV_CLOSED_KEY, navActive, parseClosed, sidebarCookie, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";
import { cn } from "@/lib/utils";
@@ -332,6 +332,42 @@ function GuestRow() {
);
}
+/**
+ * A visitor's status strip (public sign-up): its own GPU, never the install's. A guest is sent to sign
+ * up first; an account without one opens "Connect your GPU"; a connected one says whether it answers.
+ */
+function YourGpuChip({ viewer }: { viewer: NonNullable<StatusInfo["viewer"]> }) {
+ const cls = "flex w-full flex-col gap-1 rounded-md px-2 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden";
+ const g = viewer.gpu;
+ if (g.connected) {
+ const vram = g.vramBytes ? `${Math.round(g.vramBytes / 2 ** 30)} GB` : "";
+ return (
+ <IntentLink href="/settings#your-gpu" className={cls}>
+ <span className="flex items-center gap-2">
+ <StatusDot ok={g.online} /> Your GPU
+ <span className="ml-auto">{g.online ? "online" : "offline"}</span>
+ </span>
+ {(g.device || vram) && <span className="truncate text-[11px]">{[g.device, vram && `${vram} VRAM`].filter(Boolean).join(" · ")}</span>}
+ </IntentLink>
+ );
+ }
+ const body = (
+ <span className="flex items-center gap-2">
+ <StatusDot ok={false} /> Your GPU
+ <span className="ml-auto font-medium text-brand-text">Connect</span>
+ </span>
+ );
+ return viewer.kind === "guest" ? (
+ <a href={signInHref("signup", "/settings#your-gpu")} className={cls}>
+ {body}
+ </a>
+ ) : (
+ <button type="button" className={cls} onClick={() => window.dispatchEvent(new Event(CONNECT_GPU_EVENT))}>
+ {body}
+ </button>
+ );
+}
+
/** The GitHub mark (lucide has no brand icons). */
function GitHubMark() {
return (
@@ -414,6 +450,9 @@ export function AppSidebar() {
})}
</SidebarContent>
<SidebarFooter className="gap-1 border-t border-sidebar-border" onClick={closeOnLink}>
+ {status?.viewer ? (
+ <YourGpuChip viewer={status.viewer} />
+ ) : (
<IntentLink
href="/settings"
className="flex flex-col gap-1.5 rounded-md px-2 py-1.5 text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden"
@@ -437,6 +476,7 @@ export function AppSidebar() {
</span>
)}
</IntentLink>
+ )}
<SidebarMenu className="flex-row gap-1 group-data-[collapsible=icon]:flex-col">
<SidebarMenuItem className="min-w-0 flex-1">
<SidebarMenuButton tooltip="Toggle theme" className="h-8 text-[13px]" onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}>
diff --git a/src/components/get-started.tsx b/src/components/get-started.tsx
index 79f8acef..a24ccae3 100644
--- a/src/components/get-started.tsx
+++ b/src/components/get-started.tsx
@@ -110,7 +110,7 @@ export function GetStarted({
Get started
</h2>
<p className="mt-1 text-[13px] text-muted-foreground">
- {!status || nothingConnected(status)
+ {status && nothingConnected(status)
? "Nothing is connected yet, so every run is a free demo with placeholder results. Connect a model to make the real thing:"
: "Three ways to make things with Fuobe. Connect another one, or check one you set up:"}
</p>
diff --git a/src/components/gpu/account-gpu-section.tsx b/src/components/gpu/account-gpu-section.tsx
new file mode 100644
index 00000000..363d535c
--- /dev/null
+++ b/src/components/gpu/account-gpu-section.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { YourGpu } from "@/components/gpu/your-gpu";
+import { useViewer } from "@/lib/api";
+
+/** Settings for an account (public sign-up): "Your GPU", at the top of the page. Nothing for the owner or a guest. */
+export function AccountGpuSection() {
+ const account = useViewer().data?.account;
+ if (!account) return null;
+ return (
+ <section id="your-gpu" aria-labelledby="your-gpu-title" className="grid scroll-mt-28 grid-cols-[minmax(0,1fr)] gap-6 border-b py-8 md:scroll-mt-20 md:grid-cols-[260px_minmax(0,1fr)]">
+ <div className="min-w-0">
+ <h2 id="your-gpu-title" className="text-[15px] font-semibold">
+ Your GPU
+ </h2>
+ <p className="mt-1 text-[13px] text-muted-foreground">Signed in as {account.email}. Connect your own ComfyUI to run open-source models.</p>
+ </div>
+ <YourGpu />
+ </section>
+ );
+}
diff --git a/src/components/gpu/comfy-finder.tsx b/src/components/gpu/comfy-finder.tsx
new file mode 100644
index 00000000..5954baf9
--- /dev/null
+++ b/src/components/gpu/comfy-finder.tsx
@@ -0,0 +1,210 @@
+"use client";
+
+import { Check, Copy, Loader2, RefreshCw, Search } from "lucide-react";
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { copyWithToast } from "@/lib/clipboard";
+
+/**
+ * Finds a ComfyUI on the visitor's own computer, from the browser (the server can't see their
+ * machine): /system_stats on 127.0.0.1 at the usual ports. A CORS read that works names the GPU; a
+ * port that answers only a no-cors probe is a ComfyUI started without CORS, so it shows the launch
+ * flag to add. Reusable (Your GPU, a pre-flight board): it reports what it found and sends nothing
+ * to the server. A local address is for the browser only; the server needs a public one (a tunnel).
+ */
+
+export const COMFY_PORTS = [8188, 8000, 8189, 8190, 8288];
+const PROBE_MS = 1500;
+
+export type LocalComfy =
+ | { state: "found"; url: string; port: number; device?: string; vramBytes?: number; version?: string }
+ | { state: "no-cors"; url: string; port: number }
+ | { state: "none" };
+
+async function probe(url: string): Promise<LocalComfy | null> {
+ const port = Number(new URL(url).port) || (url.startsWith("https:") ? 443 : 80);
+ const timed = async (mode: RequestMode) => {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), PROBE_MS);
+ try {
+ return await fetch(`${url}/system_stats`, { mode, signal: ctrl.signal, cache: "no-store", credentials: "omit" });
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+ try {
+ const res = await timed("cors");
+ if (!res.ok) return null;
+ const s = (await res.json().catch(() => null)) as { system?: { comfyui_version?: string }; devices?: { name?: string; vram_total?: number }[] } | null;
+ if (!s?.system) return null;
+ const dev = s.devices?.[0];
+ return { state: "found", url, port, device: dev?.name, vramBytes: dev?.vram_total, version: s.system.comfyui_version };
+ } catch {
+ // Blocked by CORS, or nothing there: a no-cors probe tells them apart (an opaque answer means something listens).
+ try {
+ await timed("no-cors");
+ return { state: "no-cors", url, port };
+ } catch {
+ return null;
+ }
+ }
+}
+
+/** Look on 127.0.0.1 at COMFY_PORTS, all at once; the first ComfyUI that answers wins (a CORS-blocked one if none does). */
+export async function findLocalComfy(ports = COMFY_PORTS): Promise<LocalComfy> {
+ const found = await Promise.all(ports.map((p) => probe(`http://127.0.0.1:${p}`)));
+ return found.find((f) => f?.state === "found") ?? found.find((f) => f?.state === "no-cors") ?? { state: "none" };
+}
+
+/** "8188", "localhost:8188", "http://192.168.1.5:8188" or a tunnel's https address → a URL (null when it isn't one). */
+export function comfyAddress(input: string): string | null {
+ const s = input.trim().replace(/\/+$/, "");
+ if (!s) return null;
+ if (/^\d{2,5}$/.test(s)) return `http://127.0.0.1:${s}`;
+ try {
+ return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : `http://${s}`).toString().replace(/\/+$/, "");
+ } catch {
+ return null;
+ }
+}
+
+/** On this computer or its network: the browser can reach it, the server can't. */
+export function isLocalAddress(url: string): boolean {
+ let host: string;
+ try {
+ host = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ } catch {
+ return false;
+ }
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".lan") || !host.includes(".")) return true;
+ if (host === "::1" || host.startsWith("fe80:") || host.startsWith("fc") || host.startsWith("fd")) return true;
+ const v4 = host.split(".").map(Number);
+ if (v4.length !== 4 || v4.some((n) => !Number.isInteger(n))) return false;
+ const [a, b] = v4;
+ return a === 127 || a === 10 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
+}
+
+export const gib = (bytes?: number) => (bytes ? `${(bytes / 2 ** 30).toFixed(bytes >= 10 * 2 ** 30 ? 0 : 1)} GB` : undefined);
+
+/** The command that puts a public https address in front of a local ComfyUI. */
+export const tunnelCommand = (port: number) => `cloudflared tunnel --url http://localhost:${port}`;
+
+function CopyLine({ text, label }: { text: string; label: string }) {
+ return (
+ <div className="flex items-center gap-2 rounded-lg bg-muted px-2.5 py-2">
+ <code aria-label={label} className="min-w-0 flex-1 overflow-x-auto font-mono text-[11px] whitespace-nowrap">
+ {text}
+ </code>
+ <button
+ type="button"
+ onClick={() => void copyWithToast(text)}
+ className="grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-background hover:text-foreground"
+ aria-label={`Copy ${label}`}
+ >
+ <Copy className="size-3.5" />
+ </button>
+ </div>
+ );
+}
+
+/**
+ * The finder: looks on mount, then shows what it found. `onLocal` hears of a ComfyUI on this
+ * computer (for a caller that can use it from the browser); a tunnel address is the caller's to save.
+ */
+export function ComfyFinder({ onLocal }: { onLocal?: (found: Extract<LocalComfy, { state: "found" }>) => void }) {
+ const [result, setResult] = useState<LocalComfy | null>(null);
+ const [busy, setBusy] = useState(true);
+ const [typed, setTyped] = useState("");
+ const [tested, setTested] = useState<LocalComfy | "bad" | null>(null);
+ const origin = typeof window === "undefined" ? "https://fuobe.com" : window.location.origin;
+
+ const look = useCallback(async () => {
+ setBusy(true);
+ const r = await findLocalComfy();
+ setResult(r);
+ setBusy(false);
+ if (r.state === "found") onLocal?.(r);
+ }, [onLocal]);
+
+ // The first look, on mount (Retry and Look again call look()).
+ useEffect(() => {
+ let alive = true;
+ void findLocalComfy().then((r) => {
+ if (!alive) return;
+ setResult(r);
+ setBusy(false);
+ if (r.state === "found") onLocal?.(r);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [onLocal]);
+
+ const testTyped = async () => {
+ const url = comfyAddress(typed);
+ if (!url) return setTested("bad");
+ setTested(null);
+ setBusy(true);
+ setTested((await probe(url)) ?? { state: "none" });
+ setBusy(false);
+ };
+
+ const shown = tested && tested !== "bad" && tested.state !== "none" ? tested : result;
+ return (
+ <div className="space-y-3 text-[13px]">
+ {busy && !shown && (
+ <p className="flex items-center gap-2 text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" /> Looking for ComfyUI on this computer…
+ </p>
+ )}
+ {shown?.state === "found" && (
+ <div className="space-y-2 rounded-xl border border-primary/40 bg-brand-faint p-3">
+ <p className="flex items-center gap-2 font-medium">
+ <Check className="size-4 text-brand-text" /> Found ComfyUI on port {shown.port}
+ </p>
+ {(shown.device || shown.vramBytes) && (
+ <p className="text-[12px] text-muted-foreground">
+ {shown.device ?? "GPU"}
+ {gib(shown.vramBytes) ? ` · ${gib(shown.vramBytes)} VRAM` : ""}
+ {shown.version ? ` · ComfyUI ${shown.version}` : ""}
+ </p>
+ )}
+ <p className="text-[12px] text-muted-foreground">This studio runs on a server, which can&apos;t reach your computer. Give your ComfyUI a public address with a tunnel, then paste it below:</p>
+ <CopyLine text={tunnelCommand(shown.port)} label="tunnel command" />
+ <p className="text-[11px] text-muted-foreground">Or ngrok: ngrok http {shown.port}. Use the https address it prints.</p>
+ </div>
+ )}
+ {shown?.state === "no-cors" && (
+ <div className="space-y-2 rounded-xl border p-3">
+ <p className="font-medium">Something answers on port {shown.port}, but the browser can&apos;t read it</p>
+ <p className="text-[12px] text-muted-foreground">Start ComfyUI with this flag so this page can see it, then look again:</p>
+ <CopyLine text={`--enable-cors-header ${origin}`} label="ComfyUI launch flag" />
+ <Button size="sm" variant="secondary" onClick={() => void look()} disabled={busy}>
+ {busy ? <Loader2 className="animate-spin" /> : <RefreshCw />} Retry
+ </Button>
+ </div>
+ )}
+ {result?.state === "none" && !(tested && tested !== "bad" && tested.state !== "none") && (
+ <div className="space-y-2">
+ <p className="font-medium">Where&apos;s your ComfyUI?</p>
+ <p className="text-[12px] text-muted-foreground">
+ No ComfyUI answered on ports {COMFY_PORTS.join(", ")}. Enter its port or address (localhost, your network, or a tunnel&apos;s https address).
+ </p>
+ <div className="flex gap-2">
+ <Input aria-label="ComfyUI port or address" placeholder="8188 or https://…" value={typed} onChange={(e) => setTyped(e.target.value)} onKeyDown={(e) => e.key === "Enter" && void testTyped()} />
+ <Button size="sm" variant="secondary" className="h-9 shrink-0" onClick={() => void testTyped()} disabled={busy || !typed.trim()}>
+ {busy ? <Loader2 className="animate-spin" /> : <Search />} Test
+ </Button>
+ </div>
+ {tested === "bad" && <p className="text-[12px] text-destructive">That isn&apos;t a port or an address.</p>}
+ {tested && tested !== "bad" && tested.state === "none" && <p className="text-[12px] text-destructive">Nothing answered there as ComfyUI.</p>}
+ <Button size="sm" variant="ghost" onClick={() => void look()} disabled={busy}>
+ <RefreshCw /> Look again
+ </Button>
+ </div>
+ )}
+ <p className="text-[11px] text-muted-foreground">Chrome may ask to let this site reach devices on your local network. Allow it, so this page can look for your ComfyUI.</p>
+ </div>
+ );
+}
diff --git a/src/components/gpu/your-gpu.tsx b/src/components/gpu/your-gpu.tsx
new file mode 100644
index 00000000..0803b5ed
--- /dev/null
+++ b/src/components/gpu/your-gpu.tsx
@@ -0,0 +1,141 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Cpu, Loader2, Unplug } from "lucide-react";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { ComfyFinder, gib, isLocalAddress } from "@/components/gpu/comfy-finder";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+
+interface GpuState {
+ gpu: { url: string; hasToken: boolean } | null;
+}
+interface GpuInfo {
+ device?: string;
+ vramBytes?: number;
+ version?: string;
+}
+
+async function call<T>(method: string, body?: unknown, test = false): Promise<T> {
+ const res = await fetch(`/api/account/gpu${test ? "?test=1" : ""}`, {
+ 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;
+}
+
+/**
+ * "Your GPU" (public sign-up): an account's own ComfyUI, where its runs go (never this studio's keys
+ * or GPU). The server calls it, so it needs a public address: a Cloudflare Tunnel or ngrok in front
+ * of a local ComfyUI. The finder looks for one on this computer and shows the tunnel command.
+ */
+export function YourGpu() {
+ const qc = useQueryClient();
+ const id = useId();
+ const q = useQuery({ queryKey: ["account-gpu"], queryFn: () => call<GpuState>("GET") });
+ const [url, setUrl] = useState("");
+ const [token, setToken] = useState("");
+ const [busy, setBusy] = useState<"test" | "save" | "remove" | null>(null);
+ const [info, setInfo] = useState<GpuInfo | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const local = !!url.trim() && isLocalAddress(/^[a-z]+:\/\//i.test(url.trim()) ? url.trim() : `http://${url.trim()}`);
+ const send = async (test: boolean) => {
+ setBusy(test ? "test" : "save");
+ setError(null);
+ try {
+ const r = await call<GpuState & { info: GpuInfo }>("PUT", { url: url.trim(), token: token.trim() || undefined }, test);
+ setInfo(r.info);
+ if (!test) {
+ qc.setQueryData(["account-gpu"], { gpu: r.gpu });
+ toast.success("Your GPU is connected. Runs go to your ComfyUI now.");
+ setUrl("");
+ setToken("");
+ }
+ } catch (e) {
+ setInfo(null);
+ setError((e as Error).message);
+ } finally {
+ setBusy(null);
+ }
+ };
+ const remove = async () => {
+ setBusy("remove");
+ try {
+ qc.setQueryData(["account-gpu"], await call<GpuState>("DELETE"));
+ setInfo(null);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ if (q.isError) return <p className="text-[13px] text-muted-foreground">{q.error.message}</p>;
+ if (!q.data) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;
+ const gpu = q.data.gpu;
+
+ return (
+ <div className="space-y-4 sm:w-[36rem] sm:max-w-full">
+ <p className="text-[13px] text-muted-foreground">
+ Free accounts run on their own ComfyUI, never on this studio&apos;s keys or GPU. Runs from the Image, Video and Audio studios on open-source models go to it. It must be
+ reachable from the internet, for example through a Cloudflare Tunnel or ngrok in front of your ComfyUI.
+ </p>
+ {gpu ? (
+ <div className="flex items-start gap-2.5 rounded-xl bg-brand-faint px-3 py-2.5 text-[13px]">
+ <Cpu className="mt-0.5 size-4 shrink-0 text-brand-text" />
+ <div className="min-w-0 flex-1">
+ <p className="font-medium">Connected</p>
+ <p className="truncate font-mono text-[12px] text-muted-foreground">
+ {gpu.url}
+ {gpu.hasToken ? " · with a token" : ""}
+ </p>
+ </div>
+ <Button size="sm" variant="ghost" className="-my-1 h-7" onClick={() => void remove()} disabled={busy !== null}>
+ {busy === "remove" ? <Loader2 className="animate-spin" /> : <Unplug />} Disconnect
+ </Button>
+ </div>
+ ) : (
+ <ComfyFinder />
+ )}
+ <div className="space-y-3">
+ <div className="space-y-1.5">
+ <Label htmlFor={`${id}-url`} className="text-[13px]">
+ {gpu ? "Connect another address" : "Your ComfyUI's public address"}
+ </Label>
+ <Input id={`${id}-url`} placeholder="https://your-tunnel.trycloudflare.com" value={url} onChange={(e) => setUrl(e.target.value)} aria-invalid={!!error || local} />
+ {local && (
+ <p className="text-[12px] text-destructive">That address is on your own computer or network, and the server can&apos;t reach it. Start a tunnel and paste its https address.</p>
+ )}
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={`${id}-token`} className="text-[13px]">
+ Token <span className="text-muted-foreground">(optional, sent as Authorization: Bearer)</span>
+ </Label>
+ <Input id={`${id}-token`} type="password" autoComplete="off" value={token} onChange={(e) => setToken(e.target.value)} />
+ </div>
+ {error && <p className="text-[12px] text-destructive">{error}</p>}
+ {info && (
+ <p className="text-[12px] text-muted-foreground">
+ ComfyUI answered{info.device ? `: ${info.device}` : ""}
+ {gib(info.vramBytes) ? ` · ${gib(info.vramBytes)} VRAM` : ""}
+ {info.version ? ` · ComfyUI ${info.version}` : ""}
+ </p>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" onClick={() => void send(false)} disabled={!url.trim() || local || busy !== null}>
+ {busy === "save" && <Loader2 className="animate-spin" />} Connect
+ </Button>
+ <Button size="sm" variant="secondary" onClick={() => void send(true)} disabled={!url.trim() || local || busy !== null}>
+ {busy === "test" && <Loader2 className="animate-spin" />} Test
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsx
index f2f092ec..ee2c707f 100644
--- a/src/components/guest-prompt.tsx
+++ b/src/components/guest-prompt.tsx
@@ -3,6 +3,7 @@
import { Cpu, Sparkles } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
+import { YourGpu } from "@/components/gpu/your-gpu";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, signInHref, watchGuestRefusals } from "@/lib/api";
@@ -30,7 +31,7 @@ export function GuestPrompt() {
}, []);
return (
<Dialog open={prompt !== null} onOpenChange={(o) => !o && setPrompt(null)}>
- <DialogContent className="sm:max-w-sm">
+ <DialogContent className={prompt?.kind === "gpu" ? "max-h-[90svh] overflow-y-auto sm:max-w-xl" : "sm:max-w-sm"}>
{prompt?.kind === "gpu" ? (
<>
<DialogHeader>
@@ -39,17 +40,14 @@ export function GuestPrompt() {
</div>
<DialogTitle>Connect your GPU to run this</DialogTitle>
<DialogDescription>
- Free accounts run on their own ComfyUI, never on this studio&apos;s keys or GPU. Your ComfyUI must be reachable from the internet, for example through a Cloudflare
- Tunnel or ngrok. Or run Fuobe on your own computer: it&apos;s open source.
+ Or run Fuobe on your own computer: it&apos;s{" "}
+ <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer" className="underline underline-offset-4">
+ open source
+ </a>
+ .
</DialogDescription>
</DialogHeader>
- <DialogFooter className="gap-2 sm:justify-start">
- <Button asChild variant="secondary">
- <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer">
- Get Fuobe
- </a>
- </Button>
- </DialogFooter>
+ <YourGpu />
</>
) : (
<>
diff --git a/src/components/home-view.tsx b/src/components/home-view.tsx
index 6037e25f..f174c127 100644
--- a/src/components/home-view.tsx
+++ b/src/components/home-view.tsx
@@ -290,7 +290,7 @@ export function HomeView({
}}
/>
</>
- ) : nothingConnected && (
+ ) : nothingConnected && !status?.viewer && (
<p className="mt-4 text-[13px] text-muted-foreground">
You’re in <span className="font-medium text-foreground">demo mode</span> — outputs are placeholders.{" "}
<Link href="/settings#get-started" className="text-brand-text underline underline-offset-2">
diff --git a/src/components/owner-settings.tsx b/src/components/owner-settings.tsx
new file mode 100644
index 00000000..72d5409a
--- /dev/null
+++ b/src/components/owner-settings.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import Link from "next/link";
+import { Button } from "@/components/ui/button";
+import { signInHref, useViewer } from "@/lib/api";
+
+/**
+ * The install's settings, for its owner only. A guest (public sign-up) is offered an account, which
+ * connects its own GPU here; an account sees Your GPU (AccountGpuSection) and nothing of the install's.
+ */
+export function OwnerSettings({ children }: { children: React.ReactNode }) {
+ const v = useViewer().data;
+ if (!v) return null;
+ if (v.owner) return <>{children}</>;
+ if (v.account) return <p className="py-8 text-[13px] text-muted-foreground">The studio&apos;s own settings, keys and tokens are its owner&apos;s.</p>;
+ return (
+ <section className="space-y-3 py-8">
+ <h2 className="text-[15px] font-semibold">Run Fuobe on your own GPU</h2>
+ <p className="max-w-xl text-[13px] text-muted-foreground">
+ Create a free account, then connect your own ComfyUI: your runs go to your GPU. It must be reachable from the internet, for example through a Cloudflare Tunnel or ngrok.
+ </p>
+ <div className="flex gap-2">
+ <Button asChild size="sm">
+ <Link href={signInHref("signup", "/settings#your-gpu")}>Sign up free</Link>
+ </Button>
+ <Button asChild size="sm" variant="secondary">
+ <Link href={signInHref("login", "/settings#your-gpu")}>Log in</Link>
+ </Button>
+ </div>
+ </section>
+ );
+}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 854a9e0d..7dbeb46f 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -827,6 +827,11 @@ export interface StatusInfo {
onboarded?: boolean;
/** Settings → Models & licences: what is switched off (absent while everything is on). */
access?: AccessSummary;
+ /**
+ * Public sign-up: a guest or an account is looking. Then everything else here is its own view
+ * (its own GPU as ComfyUI, the open engine, no Demo mode), never the install's (src/server/account-gpu.ts).
+ */
+ viewer?: { kind: "guest" | "account"; gpu: { connected: boolean; online?: boolean; device?: string; vramBytes?: number } };
}
/** A connection test's answer (POST /api/providers/test). */
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 42bf40df..28fc47de 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -816,6 +816,11 @@ export type LoraField =
/** What the UI posts to /api/generations. Asset references are local asset ids or URLs. */
export interface GenerationRequest {
+ /**
+ * Public sign-up: the account whose own ComfyUI runs this ("Your GPU"), never the install's providers. Set by the
+ * server from the session only (the request schema drops it from what a client sends).
+ */
+ account?: string;
feature: string;
presetId?: string;
modelId: string;
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 7fc07cb3..05d9aa00 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -132,9 +132,30 @@ const LIBRARY_CHANGES: [methods: string, path: RegExp][] = [
["DELETE", /^\/api\/assist\/projects\/[^/]+\/sources\/[^/]+$/],
];
-/** A change an account may send: signing out, and price checks (reads go by guestRead, as a guest's). */
+/** A generation's own path (/api/generations/<id>), not one of the collection's routes. */
+const GENERATION = /^\/api\/generations\/(?!(?:facets|trash|stream|zip|bulk|local)$)([^/]+)$/;
+
+/** The generation an account's request is about (its own runs: the proxy checks it made it), or undefined. */
+export function accountGeneration(method: string, pathname: string): string | undefined {
+ const cancel = /^\/api\/generations\/([^/]+)\/cancel$/.exec(pathname);
+ if (method === "POST" && cancel) return cancel[1];
+ const one = GENERATION.exec(pathname);
+ return one && (method === "GET" || method === "HEAD" || method === "DELETE") ? one[1] : undefined;
+}
+
+/**
+ * A read of an account's own things, which the route (or the proxy, by accountGeneration) scopes to it:
+ * the list of its runs, a stored file (the proxy checks whose it is), its GPU.
+ */
+export function accountOwnRead(pathname: string): boolean {
+ return pathname === "/api/generations" || pathname === "/api/account/gpu";
+}
+
+/** A change an account may send: signing out, its own GPU, and price checks (reads go by guestRead, as a guest's). */
export function accountMayChange(method: string, pathname: string, search: string): boolean {
- return (method === "POST" && pathname === "/api/auth/logout") || isPriceCheck(method, pathname, search);
+ if (method === "POST" && pathname === "/api/auth/logout") return true;
+ if ((method === "PUT" || method === "DELETE") && pathname === "/api/account/gpu") return true;
+ return isPriceCheck(method, pathname, search);
}
/** A change to the studio's library or projects (refused for an account with LIBRARY_MESSAGE, not "Connect your GPU"). */
@@ -145,6 +166,17 @@ export function isLibraryChange(method: string, pathname: string): boolean {
export const ACCOUNT_LIBRARY_MESSAGE = "This studio's library is its owner's. Free accounts can't open or change it.";
export const LIBRARY_MESSAGE = "Free accounts can't save to this studio's library yet.";
+/**
+ * Runs an account may start once it has connected its own ComfyUI ("Your GPU"): the studios' generations, which
+ * the route sends to that ComfyUI only (src/app/api/generations/route.ts, generations.ts accountRun). Other tools
+ * plan with the install's AI helpers or its own ComfyUI, so they stay refused.
+ */
+export function ownGpuRun(method: string, pathname: string): boolean {
+ return method === "POST" && pathname === "/api/generations";
+}
+
+export const OWN_GPU_TOOL_MESSAGE = "This tool doesn't run on your own GPU yet. The Image, Video and Audio studios do: pick an open-source model there.";
+
/** Set on an account's refused run: the client shows "Connect your GPU to run this". */
export const CONNECT_GPU_HEADER = "x-fuobe-connect-gpu";
export const CONNECT_GPU_MESSAGE = "Connect your GPU to run this. Free accounts run on their own ComfyUI.";
diff --git a/src/proxy.ts b/src/proxy.ts
index 556146ed..768f2680 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -4,7 +4,9 @@ import { recordForPath, unknownHubMode } from "@/lib/record-pages";
import { countsAsView, SHARE_VIEW_HEADER, shareRoute } from "@/lib/share";
import {
ACCOUNT_LIBRARY_MESSAGE,
+ accountGeneration,
accountMayChange,
+ accountOwnRead,
CONNECT_GPU_HEADER,
CONNECT_GPU_MESSAGE,
GUEST_HEADER,
@@ -14,9 +16,12 @@ import {
isLibraryChange,
isPriceCheck,
LIBRARY_MESSAGE,
+ OWN_GPU_TOOL_MESSAGE,
ownerOnly,
+ ownGpuRun,
} from "@/lib/guest-access";
-import { authEnabled, crossSite, hostAllowed, LoginGuard, publicSignup, SESSION_COOKIE, sessionViewer, validSession, validToken, type Viewer } from "@/server/auth";
+import { authEnabled, crossSite, hostAllowed, LoginGuard, publicSignup, SESSION_COOKIE, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";
+import { fileAccount, generationAccount } from "@/server/account-library";
import { recordExists } from "@/server/records";
import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";
@@ -92,19 +97,30 @@ function readAsGuest(request: NextRequest, isAccount: boolean): NextResponse {
/**
* An account sees the owner's studio as a guest does: every page, the catalog, and none of the
- * owner's library or projects (hidden, and every change to them refused). Install-wide settings,
- * keys and tokens are the owner's, and anything that would reach a model is refused ("Connect your
- * GPU"): an account never runs on the owner's cloud keys or GPU.
+ * owner's library or projects (hidden, and every change to them refused). Its own runs are its own
+ * (accountGeneration, accountOwnRead: only what it made). Install-wide settings, keys and tokens are
+ * the owner's, and it never runs on the owner's cloud keys or GPU: with its own ComfyUI connected
+ * ("Your GPU") the studios' generations run there, and anything else that would reach a model is
+ * refused ("Connect your GPU" until it has one).
*/
-function account(request: NextRequest): NextResponse {
+const notYours = () => NextResponse.json({ error: ACCOUNT_LIBRARY_MESSAGE }, { status: 403, headers: { "Cache-Control": "no-store" } });
+
+function account(request: NextRequest, who: Account): NextResponse {
const { pathname, search } = request.nextUrl;
if (ownerOnly(request.method, pathname)) {
return NextResponse.json({ error: "Only the studio's owner can change settings, keys and tokens." }, { status: 403 });
}
- if (request.method === "GET" || request.method === "HEAD") return readAsGuest(request, true);
+ // Its own runs and their files: only what it made.
+ const gen = accountGeneration(request.method, pathname);
+ if (gen !== undefined) return generationAccount(gen) === who.id ? pass(request) : notYours();
+ const file = request.method === "GET" || request.method === "HEAD" ? /^\/api\/files\/(.+)$/.exec(pathname)?.[1] : undefined;
+ if (file !== undefined) return fileAccount(safeDecode(file)) === who.id ? pass(request) : notYours();
+ if (request.method === "GET" || request.method === "HEAD") return accountOwnRead(pathname) ? pass(request) : readAsGuest(request, true);
if (accountMayChange(request.method, pathname, search)) return pass(request);
if (isLibraryChange(request.method, pathname)) return NextResponse.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });
- return NextResponse.json({ error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
+ if (!who.gpu) return NextResponse.json({ error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
+ if (ownGpuRun(request.method, pathname)) return pass(request);
+ return NextResponse.json({ error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" }, { status: 403 });
}
const tooMany = (seconds: number) =>
@@ -178,7 +194,7 @@ export function proxy(request: NextRequest) {
const open = publicSignup(request.headers.get("host") ?? request.nextUrl.host);
const viewer = viewerOf(request, open);
if (viewer?.kind === "owner") return pass(request);
- if (viewer?.kind === "account") return account(request);
+ if (viewer?.kind === "account") return account(request, viewer.account);
if (open) return guest(request);
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Sign in, or send an API token as Authorization: Bearer fuobe_…" }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="fuobe"' } });
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
new file mode 100644
index 00000000..52fe550f
--- /dev/null
+++ b/src/server/account-gpu.ts
@@ -0,0 +1,132 @@
+import "server-only";
+import dns from "node:dns/promises";
+import net from "node:net";
+import { accountGpu, type Account, type AccountGpu } from "./auth";
+import { PROVIDERS } from "./providers";
+import { fetchPublic, isPrivateAddress } from "./remote-fetch";
+import { getSetting } from "./settings";
+
+/**
+ * "Your GPU" (public sign-up): the ComfyUI an account connects, where its runs go. The server calls
+ * it, so it must be reachable from the internet (a Cloudflare Tunnel or ngrok in front of a local
+ * ComfyUI). Addresses on this machine or a private network are refused, and so is the install's own
+ * ComfyUI. A ComfyUI on the visitor's own computer (localhost) is the browser's to reach, never sent here.
+ */
+
+export class GpuError extends Error {}
+
+const allowPrivate = () => process.env.FUOBE_ALLOW_PRIVATE_URLS === "1";
+
+export const LOCAL_GPU_MESSAGE =
+ "That address is on your own computer or network, and this server can't reach it. Put a tunnel in front of your ComfyUI (cloudflared tunnel --url http://localhost:8188, or ngrok http 8188) and paste the https address it prints.";
+
+/** An address as stored and compared: origin and path, no trailing slash. */
+const normal = (u: URL) => `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
+
+/** Check an account's ComfyUI address: http(s), a public host, not the install's own ComfyUI. Returns it normalised. */
+export async function checkGpuAddress(raw: string, o: { resolve?: (host: string) => Promise<string[]> } = {}): Promise<string> {
+ let u: URL;
+ try {
+ u = new URL(raw.trim());
+ } catch {
+ throw new GpuError("Enter the full address, like https://your-tunnel.trycloudflare.com");
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") throw new GpuError("Use an http or https address");
+ if (u.username || u.password) throw new GpuError("Put the token in the token field, not in the address");
+ if (u.search || u.hash) throw new GpuError("Use the address without ? or #");
+ const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ const local = host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".lan") || host.endsWith(".internal") || !host.includes(".");
+ if (!allowPrivate()) {
+ if (local && !net.isIP(host)) throw new GpuError(LOCAL_GPU_MESSAGE);
+ const resolve = o.resolve ?? (async (h: string) => (await dns.lookup(h, { all: true, verbatim: true })).map((a) => a.address));
+ let addrs: string[];
+ try {
+ addrs = net.isIP(host) ? [host] : await resolve(host);
+ } catch {
+ throw new GpuError(`Couldn't find ${host}. Check the address (is the tunnel running?)`);
+ }
+ if (!addrs.length) throw new GpuError(`Couldn't find ${host}. Check the address (is the tunnel running?)`);
+ if (addrs.some(isPrivateAddress)) throw new GpuError(LOCAL_GPU_MESSAGE);
+ }
+ const url = normal(u);
+ const same = (setting: string) => {
+ try {
+ return !!setting && normal(new URL(setting)).toLowerCase() === url.toLowerCase();
+ } catch {
+ return false;
+ }
+ };
+ if (same(getSetting("comfyUrl")) || same(getSetting("comfyIsolatedUrl"))) throw new GpuError("That's this studio's own ComfyUI. Connect yours.");
+ return url;
+}
+
+export interface GpuInfo {
+ device?: string;
+ vramBytes?: number;
+ version?: string;
+}
+
+/** Ask the account's ComfyUI for /system_stats, the check the studio makes of its own. */
+export async function testGpu(gpu: AccountGpu, o: { resolve?: (host: string) => Promise<string[]>; timeoutMs?: number } = {}): Promise<GpuInfo> {
+ let res: Response;
+ try {
+ res = await fetchPublic(`${gpu.url}/system_stats`, { headers: gpu.token ? { Authorization: `Bearer ${gpu.token}` } : {} }, { timeoutMs: o.timeoutMs ?? 10_000, resolve: o.resolve });
+ } catch (e) {
+ throw new GpuError(`Couldn't reach your ComfyUI at ${gpu.url}: ${(e as Error).message}`);
+ }
+ if (res.status === 401 || res.status === 403) throw new GpuError(`Your ComfyUI refused the request (HTTP ${res.status}): check the token`);
+ if (!res.ok) throw new GpuError(`Your ComfyUI answered HTTP ${res.status}. Is the tunnel pointing at ComfyUI?`);
+ const s = (await res.json().catch(() => null)) as { system?: { comfyui_version?: string }; devices?: { name?: string; vram_total?: number }[] } | null;
+ if (!s?.system) throw new GpuError("That address answers, but not as ComfyUI");
+ const dev = s.devices?.[0];
+ return { device: dev?.name, vramBytes: typeof dev?.vram_total === "number" ? dev.vram_total : undefined, version: s.system.comfyui_version };
+}
+
+declare global {
+ /** Each account's GPU as last asked (Your GPU: online or not, and what it is), for the status strip. */
+ var __fuobeAccountGpus: Map<string, { url: string; at: number; online: boolean; info: GpuInfo }> | undefined;
+}
+
+/** Is the account's ComfyUI answering, and what is it? Asked at most every 30 s per account. */
+export async function gpuState(id: string, gpu: AccountGpu): Promise<{ online: boolean } & GpuInfo> {
+ const cache = (globalThis.__fuobeAccountGpus ??= new Map());
+ const hit = cache.get(id);
+ if (hit && hit.url === gpu.url && Date.now() - hit.at < 30_000) return { online: hit.online, ...hit.info };
+ let online = false;
+ let info: GpuInfo = hit?.url === gpu.url ? hit.info : {};
+ try {
+ info = await testGpu(gpu, { timeoutMs: 5000 });
+ online = true;
+ } catch {}
+ cache.set(id, { url: gpu.url, at: Date.now(), online, info });
+ if (cache.size > 5000) cache.delete(cache.keys().next().value!);
+ return { online, ...info };
+}
+
+/** 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";
+ gpu: { connected: boolean; online?: boolean; device?: string; vramBytes?: number };
+}
+
+/**
+ * GET /api/status for a guest or an account: ComfyUI is its own GPU (taken as there until it has one,
+ * so the studios offer Generate and the run asks it to connect one), the open engine, no Demo mode,
+ * and nothing of the install's own servers, keys or addresses.
+ */
+export async function visitorStatus(account: Account | null) {
+ const gpu = account ? accountGpu(account.id) : null;
+ const live = account && gpu ? await gpuState(account.id, gpu) : null;
+ const viewer: VisitorView = {
+ kind: account ? "account" : "guest",
+ gpu: gpu ? { connected: true, online: !!live?.online, ...(live?.device && { device: live.device }), ...(live?.vramBytes && { vramBytes: live.vramBytes }) } : { connected: false },
+ };
+ return {
+ providers: Object.fromEntries(Object.values(PROVIDERS).map((p) => [p.id, { label: p.id === "comfyui" ? "Your GPU" : p.label, configured: p.id === "comfyui" ? (gpu ? !!live?.online : true) : false }])),
+ demoMode: "off",
+ engineMode: "open",
+ cloudProvider: "auto",
+ onboarded: true,
+ viewer,
+ };
+}
diff --git a/src/server/account-library.ts b/src/server/account-library.ts
new file mode 100644
index 00000000..3f2331ab
--- /dev/null
+++ b/src/server/account-library.ts
@@ -0,0 +1,22 @@
+import "server-only";
+import { db } from "./db";
+
+/**
+ * An account's own runs (public sign-up, "Your GPU"): a generation an account started carries its
+ * id in the stored request (`account`, set by the server only). Everything else is the owner's.
+ * The proxy lets an account read, cancel and delete only its own (src/proxy.ts).
+ */
+
+/** Who made this generation: an account id, null for the owner, undefined when there is no such generation. */
+export function generationAccount(id: string): string | null | undefined {
+ const row = db().prepare("SELECT json_extract(request_json, '$.account') AS account FROM generations WHERE id = ?").get(id) as { account: string | null } | undefined;
+ return row ? (row.account ?? null) : undefined;
+}
+
+/** Who made the generation this stored file came from (undefined: not a generation's file). */
+export function fileAccount(rel: string): string | null | undefined {
+ const row = db()
+ .prepare("SELECT json_extract(g.request_json, '$.account') AS account FROM assets a JOIN generations g ON g.id = a.generation_id WHERE a.rel_path = ? LIMIT 1")
+ .get(rel) as { account: string | null } | undefined;
+ return row ? (row.account ?? null) : undefined;
+}
diff --git a/src/server/auth.ts b/src/server/auth.ts
index cad9b4ef..3af31d67 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -35,6 +35,12 @@ export interface ApiToken {
lastUsedAt?: number;
}
+/** An account's own ComfyUI ("Your GPU"): where its runs go, never the install's. A public address (a tunnel). */
+export interface AccountGpu {
+ url: string;
+ token?: string;
+}
+
/** A signed-up visitor (public sign-up). */
export interface Account {
id: string;
@@ -47,6 +53,7 @@ export interface Account {
lastLoginAt?: number;
/** Switched off by the owner (Settings → Accounts): signed out, and can't log in. */
disabled?: boolean;
+ gpu?: AccountGpu;
}
interface AuthFile {
@@ -229,7 +236,7 @@ export interface AccountInfo {
export function listAccounts(): AccountInfo[] {
return (read().accounts ?? [])
- .map((a) => ({ id: a.id, email: a.email, createdAt: a.createdAt, lastLoginAt: a.lastLoginAt ?? null, disabled: !!a.disabled, gpu: "gpu" in a && !!(a as { gpu?: unknown }).gpu }))
+ .map((a) => ({ id: a.id, email: a.email, createdAt: a.createdAt, lastLoginAt: a.lastLoginAt ?? null, disabled: !!a.disabled, gpu: !!a.gpu }))
.sort((a, b) => b.createdAt - a.createdAt);
}
@@ -265,6 +272,51 @@ export function accountsCsv(items = listAccounts()): string {
return rows.map((r) => r.map(csvCell).join(",")).join("\r\n") + "\r\n";
}
+export const accountById = (id: string): Account | undefined => read().accounts?.find((a) => a.id === id);
+
+/** The account's own ComfyUI, or null when it hasn't connected one. */
+export const accountGpu = (id: string): AccountGpu | null => accountById(id)?.gpu ?? null;
+
+function withoutGpu(a: Account): Account {
+ const copy = { ...a };
+ delete copy.gpu;
+ return copy;
+}
+
+/** Save (or with null, forget) the account's own ComfyUI. The caller checks the address first (src/server/account-gpu.ts). */
+export function setAccountGpu(id: string, gpu: AccountGpu | null): void {
+ const d = read();
+ if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);
+ write({ ...d, accounts: d.accounts.map((a) => (a.id !== id ? a : gpu ? { ...a, gpu: { url: gpu.url, ...(gpu.token && { token: gpu.token }) } } : withoutGpu(a))) });
+}
+
+/** Who is asking: the owner (also everyone while no password is set), an account (public sign-up on), or a guest. */
+export type RequestViewer = { kind: "owner" } | { kind: "account"; account: Account } | { kind: "guest" };
+
+/** The session cookie a request carries (read from its Cookie header: works outside Next's request scope too). */
+export function sessionCookieOf(request: Request): string | undefined {
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
+ const eq = part.indexOf("=");
+ if (eq > 0 && part.slice(0, eq).trim() === SESSION_COOKIE) return part.slice(eq + 1).trim();
+ }
+ return undefined;
+}
+
+export function requestViewer(request: Request, cookie = sessionCookieOf(request)): RequestViewer {
+ if (!authEnabled() || validToken(request.headers.get("authorization"))) return { kind: "owner" };
+ const v = sessionViewer(cookie);
+ if (v?.kind === "owner") return v;
+ if (v?.kind === "account" && publicSignup(request.headers.get("host"))) return v;
+ return { kind: "guest" };
+}
+
+/** The account behind this request's session, while public sign-up is on for its address (null: the owner, a guest, or off). */
+export function requestAccount(request: Request, cookie = sessionCookieOf(request)): Account | null {
+ if (validToken(request.headers.get("authorization"))) return null;
+ const v = sessionViewer(cookie);
+ return v?.kind === "account" && publicSignup(request.headers.get("host")) ? v.account : null;
+}
+
// ---------------------------------------------------------------------------
// Public sign-up: the switch
diff --git a/src/server/generations.ts b/src/server/generations.ts
index b4a5af3f..d5131f72 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -49,7 +49,9 @@ import { createExtendChain, createKeyframeFilm, createMosaicRun, createRelitClip
import { enhancePrompt, enhanceSoulWords } from "./enhance";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
-import { comfyLoraFiles, probeComfy } from "./providers/comfyui";
+import { comfyLoraFiles, onOwnGpu, outputFetch, probeComfy } from "./providers/comfyui";
+import { accountGpu } from "./auth";
+import { CONNECT_GPU_MESSAGE } from "@/lib/guest-access";
import { graphLoras } from "@/lib/catalog/character-swap";
import { ensureLorasOnComfy, prepareCloudLoras, withoutUnreachableCivitai } from "./loras";
import { ACCESS_PLACE } from "@/lib/model-access";
@@ -59,7 +61,7 @@ import type { PollContext, PollResult, RemoteOutput } from "./providers/types";
import { mediaFacts } from "./media-facts";
import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";
import { convertMask, decodePng, encodePng } from "./png";
-import { engineMode, getSetting } from "./settings";
+import { engineMode, getSetting, withCandidates } from "./settings";
import { fetchRemoteToFile } from "./remote-fetch";
import { adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir } from "./storage";
@@ -215,6 +217,11 @@ export interface ListOptions {
*/
before?: number;
beforeId?: string;
+ /**
+ * Public sign-up: only this account's runs. Without it, only the owner's (an account's runs are its
+ * own: they stay out of the owner's lists).
+ */
+ account?: string;
/** Date range on createdAt: since ≤ t < until. */
since?: number;
until?: number;
@@ -231,6 +238,8 @@ export function listGenerations(o: ListOptions = {}): Generation[] {
args.push(...values);
};
const oneOf = (col: string, values: unknown[]) => add(`${col} IN (${values.map(() => "?").join(", ")})`, ...values);
+ if (o.account) add("json_extract(g.request_json, '$.account') = ?", o.account);
+ else add("json_extract(g.request_json, '$.account') IS NULL");
if (o.batchId) add("g.batch_id = ?", o.batchId);
if (o.feature) add("g.feature = ?", o.feature);
if (o.features?.length) add(`(${o.features.map(() => "g.feature LIKE ?").join(" OR ")})`, ...o.features.map(featureLike));
@@ -1102,7 +1111,10 @@ async function advanceDependents(): Promise<void> {
// Filled with the slots that have an input; stored with its whole chain (and what was skipped) for a retry.
const filled = withChainInputs({ ...request, chain: slots }, values as string[]);
const original: GenerationRequest = { ...filled, chain: request.chain, chainFilled: true };
- const prepared = prepare(original);
+ // An account's step is planned as its run was: on its own ComfyUI.
+ const own = original.account ? accountRun(original.account, "comfyui") : undefined;
+ if (own && "error" in own) throw new Error(own.error);
+ const prepared = own ? own.run(() => prepare(original)) : prepare(original);
const mode = chainMode(prepared, deps as Pick<Row, "provider">[], original);
if (mode.error) throw new Error(mode.error);
const p = mode.forceDemo ? { ...prepared, demo: true, providerId: "mock" as const, cost: 0 } : prepared;
@@ -1136,7 +1148,50 @@ function recordSubmission(id: string, at: number): void {
.run(id, at);
}
-async function submit(
+// ---------------------------------------------------------------------------
+// Public sign-up: an account's runs go to its own ComfyUI ("Your GPU"), never the install's providers
+
+export const OWN_GPU_ONLY = "Free accounts run only on their own ComfyUI: pick an open-source model.";
+
+/**
+ * How an account's job reaches a provider: inside onOwnGpu (its own ComfyUI, the open engine, no demo
+ * outputs), or not at all: no GPU connected, or a provider other than ComfyUI (the install's cloud
+ * keys, its local LLM). An unreachable GPU fails the job; it never falls back to the install's.
+ */
+export function accountRun(accountId: string, providerId: string): { run: <T>(fn: () => T) => T } | { error: string } {
+ const gpu = accountGpu(accountId);
+ if (!gpu) return { error: CONNECT_GPU_MESSAGE };
+ if (providerId !== "comfyui") return { error: OWN_GPU_ONLY };
+ return { run: (fn) => onOwnGpu(gpu, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn)) };
+}
+
+/**
+ * Plan (and price) as a visitor's run would go: on its own ComfyUI (none yet: an empty address that
+ * reaches nothing), the open engine, no demo outputs. For previews; a run goes through accountRun.
+ */
+export function asVisitor<T>(gpu: { url: string; token?: string } | null, fn: () => T): T {
+ return onOwnGpu(gpu ?? { url: "" }, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn));
+}
+
+const accountOf = (r: Pick<Row, "request_json">): string | undefined => {
+ try {
+ return (JSON.parse(r.request_json) as GenerationRequest).account;
+ } catch {
+ return undefined;
+ }
+};
+
+function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number): Promise<void> {
+ if (!req.account) return submitNow(id, route, providerId, plan, req, index);
+ const own = accountRun(req.account, providerId);
+ if ("error" in own) {
+ update(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
+ return Promise.resolve();
+ }
+ return own.run(() => submitNow(id, route, providerId, plan, req, index));
+}
+
+async function submitNow(
id: string,
route: ModelRoute,
providerId: ProviderId,
@@ -1241,7 +1296,8 @@ async function submit(
// file mirrored once to the provider's storage (the civitai key never leaves this server).
if (input.loras?.length && (providerId === "fal" || providerId === "replicate")) {
input.loras = await prepareCloudLoras(input.loras, providerId, (data, name) => adapter.prepareFile(data, "application/octet-stream", name, route), (message) => update(id, { message }));
- } else if (providerId === "comfyui" && (input.loras?.length || graphLoras(route.endpoint, input.extra).length)) {
+ } else if (providerId === "comfyui" && !req.account && (input.loras?.length || graphLoras(route.endpoint, input.extra).length)) {
+ // (Not for an account's own ComfyUI: the download writes to the install's LoRA folder.)
// A graph that loads its own LoRAs (Genjutsu's Character swap: the Turbo and swap LoRAs) gets them downloaded too.
await ensureLorasOnComfy([...(input.loras ?? []), ...graphLoras(route.endpoint, input.extra)], await comfyLoraFiles(route), (message) => update(id, { message }));
}
@@ -1351,7 +1407,11 @@ async function pollGuarded(r: Row): Promise<void> {
if (polling.has(r.id)) return;
polling.add(r.id);
try {
- await pollOne(r);
+ const account = accountOf(r);
+ const own = account ? accountRun(account, r.provider) : undefined;
+ if (own && "error" in own) update(r.id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
+ else if (own) await own.run(() => pollOne(r));
+ else await pollOne(r);
} catch (e) {
update(r.id, { message: `Poll error: ${(e as Error).message}` });
} finally {
@@ -1684,7 +1744,7 @@ async function persistOutput(o: RichOutput, generationId: string): Promise<Outpu
data = f.data;
contentType ??= f.contentType;
} else {
- const res = await fetch(o.url, { headers: o.headers });
+ const res = await outputFetch(o.url, { headers: o.headers });
if (!res.ok) throw new Error(`download ${res.status}`);
data = Buffer.from(await res.arrayBuffer());
const header = res.headers.get("content-type")?.split(";")[0];
@@ -1717,9 +1777,11 @@ export async function cancelGeneration(id: string): Promise<void> {
const model = getModel(r.model_id);
// Without an external id the job is still being handed over: submit() cancels it as soon as it lands.
if (r.external_id && model) {
- await provider(r.provider)
- .cancel?.(pollContext(r, model))
- .catch(() => {});
+ const account = accountOf(r);
+ const own = account ? accountRun(account, r.provider) : undefined;
+ const cancel = () => Promise.resolve(provider(r.provider).cancel?.(pollContext(r, model))).catch(() => {});
+ if (!own) await cancel();
+ else if ("run" in own) await own.run(cancel);
}
stopModelFinish(id);
update(id, { status: "canceled", completed_at: Date.now(), message: null });
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index b3d4a3a9..adb42e3b 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -1,4 +1,5 @@
import "server-only";
+import { AsyncLocalStorage } from "node:async_hooks";
import fs from "node:fs";
import path from "node:path";
import { tracksFor, type MotionPaths } from "@/lib/motion-paths";
@@ -56,6 +57,8 @@ import { decodePng, encodePng } from "../png";
import { probeAvi } from "../avi-probe";
import { probeWebm } from "../webm-probe";
import { adoptFile, readRef, scratchDir } from "../storage";
+import { CONNECT_GPU_MESSAGE } from "@/lib/guest-access";
+import { fetchPublic } from "../remote-fetch";
import { zipToFile } from "../zip";
import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";
import { ProviderError, type ProviderAdapter, type RemoteOutput } from "./types";
@@ -91,7 +94,38 @@ export type ComfyWorker = "main" | "isolated";
/** Where the isolated worker's address is set, for messages. */
export const ISOLATED_SETTING = "Settings → Open-source engine · ComfyUI → Isolated worker URL";
+// ---------------------------------------------------------------------------
+// An account's own ComfyUI (public sign-up, "Your GPU")
+
+/** Where an account's run goes: its own ComfyUI (a public address), with its own token. */
+export interface OwnGpu {
+ url: string;
+ token?: string;
+}
+
+const ownGpuStore = new AsyncLocalStorage<OwnGpu>();
+
+/**
+ * Run `fn` on an account's own ComfyUI: every ComfyUI call inside (uploads, the prompt, polls, outputs)
+ * goes to `gpu` through fetchPublic, which connects only to public addresses, so it can't reach the
+ * install's own ComfyUI, even when the account's name is re-pointed at this machine. The install's
+ * address and token are never used. Without a socket: progress comes from polling.
+ */
+export function onOwnGpu<T>(gpu: OwnGpu, fn: () => T): T {
+ return ownGpuStore.run({ url: gpu.url.replace(/\/+$/, ""), token: gpu.token }, fn);
+}
+
+/** Inside onOwnGpu: the account's ComfyUI. */
+export const ownGpu = (): OwnGpu | undefined => ownGpuStore.getStore();
+
+/** fetch() for a provider's file: through fetchPublic on an account's own ComfyUI. */
+export function outputFetch(url: string, init: RequestInit = {}): Promise<Response> {
+ return ownGpu() ? fetchPublic(url, init, { timeoutMs: 120_000 }) : fetch(url, init);
+}
+
function baseUrl(worker: ComfyWorker = "main"): string {
+ const own = ownGpu();
+ if (own) return own.url;
return getSetting(worker === "isolated" ? "comfyIsolatedUrl" : "comfyUrl").replace(/\/+$/, "");
}
@@ -104,6 +138,8 @@ export function workerFor(endpoint: string | undefined): ComfyWorker {
const sameAddress = (a: string, b: string) => a.replace(/\/+$/, "") === b.replace(/\/+$/, "");
function authHeaders(worker: ComfyWorker = "main"): Record<string, string> {
+ const own = ownGpu();
+ if (own) return own.token ? { Authorization: `Bearer ${own.token}` } : {};
// Save & test of an address that isn't the saved one: the saved token stays with the server it
// was saved for. Only a token typed for this test goes to the new address.
const address = worker === "isolated" ? "comfyIsolatedUrl" : "comfyUrl";
@@ -114,6 +150,15 @@ function authHeaders(worker: ComfyWorker = "main"): Record<string, string> {
async function comfyFetch(p: string, init: RequestInit = {}, worker: ComfyWorker = "main"): Promise<Response> {
const base = baseUrl(worker);
+ if (ownGpu()) {
+ // A visitor without a GPU of its own (a price check): nothing to reach, and never the install's.
+ if (!base) throw new ProviderError(CONNECT_GPU_MESSAGE);
+ try {
+ return await fetchPublic(`${base}${p}`, { ...init, headers: { ...authHeaders(worker), ...(init.headers ?? {}) } }, { timeoutMs: 120_000 });
+ } catch (e) {
+ throw new ProviderError(`Can't reach your ComfyUI at ${base} (${(e as Error).message}). Is it running, and is its tunnel up?`);
+ }
+ }
if (worker === "isolated" && !base) {
throw new ProviderError(`This model runs on the isolated ComfyUI worker, which isn't set up yet: add its address in ${ISOLATED_SETTING} (or COMFYUI_ISOLATED_URL). scripts/comfy/README.md shows how to start one, usually on port 8189`);
}
@@ -180,6 +225,8 @@ function setSocket(worker: ComfyWorker, s: ComfySocket | undefined) {
}
function ensureSocket(worker: ComfyWorker = "main"): { clientId: string; progress: Map<string, Progress> } {
+ // An account's own ComfyUI: no socket (the install's stays as it is); its progress comes from polling.
+ if (ownGpu()) return { clientId: "fuobe-account", progress: new Map() };
const url = baseUrl(worker);
const cur = socketOf(worker);
if (cur && cur.url === url && cur.ws.readyState <= 1) return cur;
@@ -375,7 +422,7 @@ async function withLayerBoxes(outputs: ComfyOutput[]): Promise<ComfyOutput[]> {
outputs.map(async (o) => {
if (o.kind !== "image" || typeof o.meta?.z !== "number" || o.url.startsWith("data:")) return o;
try {
- const res = await fetch(o.url, { headers: o.headers });
+ const res = await outputFetch(o.url, { headers: o.headers });
if (!res.ok) return o;
const data = Buffer.from(await res.arrayBuffer());
const png = decodePng(data);
@@ -402,7 +449,7 @@ async function bundleFrames(outputs: ComfyOutput[], generationId: string): Promi
const dest = path.join(scratchDir(), `${generationId || nanoid(8)}-${nanoid(6)}.zip`);
async function* files() {
for (const [i, f] of frames.entries()) {
- const res = await fetch(f.url, { headers: f.headers });
+ const res = await outputFetch(f.url, { headers: f.headers });
if (!res.ok) throw new ProviderError(`ComfyUI answered HTTP ${res.status} for EXR frame ${i + 1}`);
yield { name: `frame_${String(i + 1).padStart(5, "0")}.exr`, data: Buffer.from(await res.arrayBuffer()) };
}
@@ -443,6 +490,8 @@ async function checkComfy(url: string): Promise<boolean> {
/** Is the ComfyUI server reachable? Cached for 10 s (`force` checks now); one check runs at a time. */
export async function probeComfy(force = false): Promise<boolean> {
+ // An account's own ComfyUI is taken as there: its run says so when it isn't (the install's state stays its own).
+ if (ownGpu()) return true;
const url = baseUrl();
const cur = globalThis.__fuobeComfyReach;
if (!force && cur && cur.url === url && Date.now() - cur.at < 10_000) return cur.ok;
@@ -451,6 +500,7 @@ export async function probeComfy(force = false): Promise<boolean> {
/** The connected ComfyUI's RAM in bytes, as the last reachability check read it (whole-clip tools' budget). */
export function comfyRam(): number | undefined {
+ if (ownGpu()) return undefined;
const cur = globalThis.__fuobeComfyReach;
return cur?.ok && cur.url === baseUrl() ? cur.ram : undefined;
}
@@ -461,6 +511,7 @@ export function comfyRam(): number | undefined {
* the background to say for sure.
*/
export function probeComfySync(timeoutMs = 1500): boolean {
+ if (ownGpu()) return true;
const url = baseUrl();
const { reach, sure } = reachSync(url, `${url}/system_stats`, timeoutMs, authHeaders());
globalThis.__fuobeComfyReach = reach;
@@ -1338,6 +1389,7 @@ export const comfyProvider: ProviderAdapter = {
id: "comfyui",
label: "ComfyUI",
isConfigured: () => {
+ if (ownGpu()) return true;
const cur = globalThis.__fuobeComfyReach;
// First check for this server: wait for the answer, so a request right after start isn't sent to demo.
if (!cur || cur.url !== baseUrl()) return probeComfySync();
diff --git a/src/server/remote-fetch.ts b/src/server/remote-fetch.ts
index e70e7584..704d5a69 100644
--- a/src/server/remote-fetch.ts
+++ b/src/server/remote-fetch.ts
@@ -4,6 +4,7 @@ import fs from "node:fs";
import http from "node:http";
import https from "node:https";
import net from "node:net";
+import { Readable } from "node:stream";
/**
* Fetch a file from a URL someone handed us (API callers, MCP clients, the Assist LLM) without
@@ -216,3 +217,50 @@ function get(
req.end();
});
}
+
+/**
+ * fetch() for a server someone else named (an account's own ComfyUI, public sign-up): any method and
+ * body, the response streamed, but the connection only goes to a public address, checked on the
+ * address the socket actually connects to (so a name re-pointed at this machine after it was saved
+ * still can't reach the install's own ComfyUI or anything else on its network). Redirects aren't
+ * followed. FUOBE_ALLOW_PRIVATE_URLS=1 allows private addresses, as for fetchRemote.
+ */
+export async function fetchPublic(url: string, init: RequestInit = {}, o: Pick<RemoteFetchOptions, "resolve" | "blocked" | "timeoutMs"> = {}): Promise<Response> {
+ const target = new URL(url);
+ if (target.protocol !== "http:" && target.protocol !== "https:") throw new RemoteFetchError(`Only http(s) addresses, not ${target.protocol}`);
+ const blocked = o.blocked ?? ((ip: string) => !allowPrivate() && isPrivateAddress(ip));
+ const resolve = o.resolve ?? (async (host: string) => (await dns.lookup(host, { all: true, verbatim: true })).map((a) => a.address));
+ const host = target.hostname.replace(/^\[|\]$/g, "");
+ if (net.isIP(host) && blocked(host)) throw refuse(target.host);
+ // The body and headers as fetch would send them (FormData gets its boundary).
+ const asked = new Request(target, init);
+ const body = asked.method === "GET" || asked.method === "HEAD" ? undefined : Buffer.from(await asked.arrayBuffer());
+ const headers: Record<string, string> = {};
+ asked.headers.forEach((v, k) => (headers[k] = v));
+ if (body) headers["content-length"] = String(body.length);
+ const lookup: net.LookupFunction = (hostname, options, cb) => {
+ resolve(hostname).then(
+ (addrs) => {
+ if (!addrs.length) return cb(new RemoteFetchError(`Couldn't resolve ${hostname}`), "", 4);
+ if (addrs.some(blocked)) return cb(refuse(hostname), "", 4);
+ if (options.all) return (cb as unknown as (e: null, a: { address: string; family: number }[]) => void)(null, addrs.map((a) => ({ address: a, family: net.isIPv6(a) ? 6 : 4 })));
+ cb(null, addrs[0], net.isIPv6(addrs[0]) ? 6 : 4);
+ },
+ (e: Error) => cb(e, "", 4),
+ );
+ };
+ return new Promise<Response>((resolveRes, reject) => {
+ const req = (target.protocol === "https:" ? https : http).request(target, { method: asked.method, headers, lookup, timeout: o.timeoutMs ?? 60_000 }, (res) => {
+ const status = res.statusCode ?? 0;
+ const out = new Headers();
+ for (const [k, v] of Object.entries(res.headers)) if (v !== undefined) out.set(k, Array.isArray(v) ? v.join(", ") : v);
+ const empty = asked.method === "HEAD" || status === 204 || status === 304;
+ if (empty) res.resume();
+ resolveRes(new Response(empty ? null : (Readable.toWeb(res) as ReadableStream<Uint8Array>), { status, statusText: res.statusMessage, headers: out }));
+ });
+ req.on("timeout", () => req.destroy(new RemoteFetchError(`Timed out reaching ${target.host}`)));
+ req.on("error", (e) => reject(e instanceof RemoteFetchError ? e : new RemoteFetchError(`Couldn't reach ${target.host}: ${e.message}`)));
+ if (init.signal) init.signal.addEventListener("abort", () => req.destroy(new RemoteFetchError("Aborted")), { once: true });
+ req.end(body);
+ });
+}
diff --git a/src/server/visitor.ts b/src/server/visitor.ts
new file mode 100644
index 00000000..c4101abe
--- /dev/null
+++ b/src/server/visitor.ts
@@ -0,0 +1,14 @@
+import "server-only";
+import { accountGpu, requestViewer } from "./auth";
+import { asVisitor } from "./generations";
+
+/**
+ * Run a price check (an estimate route, or `?preview=1`) as the asker's run would go: the owner's
+ * as always; a guest's or an account's on its own GPU (none yet: an address that reaches nothing),
+ * the open engine and no demo outputs, so a visitor is never told a run is a free demo.
+ */
+export function priceAs<T>(request: Request, fn: () => T): T {
+ const v = requestViewer(request);
+ if (v.kind === "owner") return fn();
+ return asVisitor(v.kind === "account" ? accountGpu(v.account.id) : null, fn);
+}
diff --git a/tests/account-gpu.test.ts b/tests/account-gpu.test.ts
new file mode 100644
index 00000000..3ac96403
--- /dev/null
+++ b/tests/account-gpu.test.ts
@@ -0,0 +1,176 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-gpu-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+
+// Every plain fetch is recorded: an account's run must never reach the install's ComfyUI.
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL) => {
+ fetched.push(String(input instanceof Request ? input.url : input));
+ return new Response("not stubbed", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const { checkGpuAddress, GpuError } = await import("@/server/account-gpu");
+const { fetchPublic } = await import("@/server/remote-fetch");
+const { comfyProvider, onOwnGpu, ownGpu, probeComfy } = await import("@/server/providers/comfyui");
+const { accountRun, OWN_GPU_ONLY } = await import("@/server/generations");
+const { getSetting } = await import("@/server/settings");
+afterAll(() => {
+ globalThis.fetch = realFetch;
+ // The database stays open until the worker exits (Windows won't delete it before).
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const publicDns = async () => ["93.184.216.34"];
+
+describe("Your GPU: the address", () => {
+ it("takes a public address, normalised", async () => {
+ expect(await checkGpuAddress(" https://abc.trycloudflare.com/ ", { resolve: publicDns })).toBe("https://abc.trycloudflare.com");
+ });
+
+ it("refuses this machine, private networks and the install's own ComfyUI", async () => {
+ for (const url of ["http://localhost:8188", "http://127.0.0.1:8188", "http://192.168.1.5:8188", "http://169.254.169.254", "http://comfy:8188", "http://box.local:8188"]) {
+ await expect(checkGpuAddress(url, { resolve: publicDns }), url).rejects.toThrow(/own computer or network/);
+ }
+ // A public name that resolves to a private address.
+ await expect(checkGpuAddress("https://sneaky.example", { resolve: async () => ["10.0.0.7"] })).rejects.toThrow(/own computer or network/);
+ await expect(checkGpuAddress("http://owner-comfy.test:8188", { resolve: publicDns })).rejects.toThrow(/own ComfyUI/);
+ await expect(checkGpuAddress("ftp://x.example", { resolve: publicDns })).rejects.toBeInstanceOf(GpuError);
+ await expect(checkGpuAddress("https://user:[email protected]", { resolve: publicDns })).rejects.toThrow(/token field/);
+ });
+
+ it("connects to public addresses only, checked on the address actually used", async () => {
+ await expect(fetchPublic("http://rebound.example:8188/system_stats", {}, { resolve: async () => ["127.0.0.1"] })).rejects.toThrow(/won't fetch/);
+ await expect(fetchPublic("http://169.254.169.254/latest", {})).rejects.toThrow(/won't fetch/);
+ await expect(fetchPublic("http://[::1]:8188/", {})).rejects.toThrow(/won't fetch/);
+ });
+});
+
+describe("Your GPU: where an account's runs go", () => {
+ let id = "";
+ beforeAll(() => {
+ auth.setPassword("install password");
+ id = auth.createAccount("[email protected]", "long enough").id;
+ });
+
+ it("refuses an account without a GPU, and any provider but ComfyUI", () => {
+ const none = accountRun(id, "comfyui");
+ expect("error" in none && none.error).toMatch(/Connect your GPU/);
+ auth.setAccountGpu(id, { url: "https://gpu.example", token: "secret" });
+ expect(auth.accountGpu(id)).toEqual({ url: "https://gpu.example", token: "secret" });
+ for (const p of ["fal", "replicate", "llm", "mock"]) {
+ const r = accountRun(id, p);
+ expect("error" in r && r.error, p).toBe(OWN_GPU_ONLY);
+ }
+ });
+
+ it("runs on the account's ComfyUI, open engine, no demo outputs", async () => {
+ const r = accountRun(id, "comfyui");
+ if (!("run" in r)) throw new Error("expected a run");
+ const seen = await r.run(async () => ({ own: ownGpu(), mode: getSetting("engineMode"), demo: getSetting("demoMode"), reach: await probeComfy(true) }));
+ expect(seen).toEqual({ own: { url: "https://gpu.example", token: "secret" }, mode: "open", demo: "off", reach: true });
+ expect(ownGpu()).toBeUndefined();
+ });
+
+ it("never falls back to the install's ComfyUI when the account's can't be reached", async () => {
+ fetched.length = 0;
+ // A name re-pointed at this machine: refused at connect time, and the install's server is never asked.
+ const r = await onOwnGpu({ url: "http://127.0.0.1:8188" }, () => comfyProvider.test!());
+ expect(r.ok).toBe(false);
+ expect(r.detail).toMatch(/your ComfyUI/);
+ expect(fetched.filter((u) => u.includes("owner-comfy.test"))).toEqual([]);
+ });
+
+ it("forgets the GPU on disconnect", () => {
+ auth.setAccountGpu(id, null);
+ expect(auth.accountGpu(id)).toBeNull();
+ expect(JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).accounts[0]).not.toHaveProperty("gpu");
+ });
+});
+
+describe("an account's own runs", () => {
+ it("are its own: listed, opened, cancelled and deleted by it only, and out of the owner's lists", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const { NextRequest } = await import("next/server");
+ const { proxy } = await import("@/proxy");
+ const { db } = await import("@/server/db");
+ const { listGenerations } = await import("@/server/generations");
+ const a = auth.createAccount("[email protected]", "long enough");
+ const b = auth.createAccount("[email protected]", "long enough");
+ const row = (id: string, account?: string) =>
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 'text-to-image', 'image', 'succeeded', ?, '[]', ?, ?)",
+ )
+ .run(id, JSON.stringify({ feature: "image", modelId: "m", ...(account && { account }) }), Date.now(), Date.now());
+ row("owner-run");
+ row("a-run", a.id);
+ row("b-run", b.id);
+ db().prepare("INSERT INTO assets (id, kind, rel_path, content_type, size, source, generation_id, created_at) VALUES ('as1', 'image', 'outputs/a-run.png', 'image/png', 1, 'generation', 'a-run', ?)").run(Date.now());
+ expect(listGenerations({ steps: true }).map((g) => g.id)).toEqual(["owner-run"]);
+ expect(listGenerations({ steps: true, account: a.id }).map((g) => g.id)).toEqual(["a-run"]);
+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}`;
+ const at = (url: string, method = "GET") => proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { cookie }, ...(method !== "GET" && { body: "{}" }) }));
+ const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+ expect(passed(at("/api/generations"))).toBe(true);
+ expect(passed(at("/api/generations/a-run"))).toBe(true);
+ expect(passed(at("/api/generations/a-run", "DELETE"))).toBe(true);
+ expect(passed(at("/api/generations/a-run/cancel", "POST"))).toBe(true);
+ expect(passed(at("/api/files/outputs/a-run.png"))).toBe(true);
+ for (const [url, method] of [
+ ["/api/generations/owner-run", "GET"],
+ ["/api/generations/owner-run", "DELETE"],
+ ["/api/generations/b-run", "GET"],
+ ["/api/generations/b-run/cancel", "POST"],
+ ["/api/generations/a-run", "PATCH"],
+ ["/api/files/outputs/owner.png", "GET"],
+ ]) {
+ expect(at(url, method).status, `${method} ${url}`).toBe(403);
+ }
+ // The live stream carries everyone's events: not for an account (it polls).
+ expect(at("/api/generations/stream").status).toBe(404);
+ });
+});
+
+describe("the status strip", () => {
+ it("shows a visitor its own GPU, never the install's ComfyUI, servers or Demo mode", async () => {
+ const { visitorStatus } = await import("@/server/account-gpu");
+ const guest = await visitorStatus(null);
+ expect(guest).toMatchObject({ demoMode: "off", engineMode: "open", onboarded: true, viewer: { kind: "guest", gpu: { connected: false } } });
+ expect(guest.providers.comfyui).toEqual({ label: "Your GPU", configured: true });
+ expect(guest.providers.fal.configured).toBe(false);
+ expect(JSON.stringify(guest)).not.toContain("owner-comfy.test");
+ expect(guest).not.toHaveProperty("llm");
+ const a = auth.createAccount("[email protected]", "long enough");
+ auth.setAccountGpu(a.id, { url: "http://127.0.0.1:8188" });
+ const acct = await visitorStatus(auth.accountById(a.id)!);
+ expect(acct.viewer).toEqual({ kind: "account", gpu: { connected: true, online: false } });
+ expect(acct.providers.comfyui.configured).toBe(false);
+ expect(JSON.stringify(acct)).not.toContain("owner-comfy.test");
+ });
+});
+
+describe("a visitor's price checks", () => {
+ it("are priced as the run would go: its own GPU (none yet), the open engine, never a demo", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const { priceAs } = await import("@/server/visitor");
+ const seen = () => ({ own: ownGpu(), mode: getSetting("engineMode"), demo: getSetting("demoMode") });
+ expect(priceAs(new Request("http://localhost:3000/api/shorts/estimate"), seen)).toEqual({ own: { url: "" }, mode: "open", demo: "off" });
+ const a = auth.createAccount("[email protected]", "long enough");
+ auth.setAccountGpu(a.id, { url: "https://gpu.example" });
+ const asAccount = new Request("http://localhost:3000/api/shorts/estimate", { headers: { cookie: `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}` } });
+ expect(priceAs(asAccount, seen).own).toEqual({ url: "https://gpu.example" });
+ const asOwner = new Request("http://localhost:3000/api/shorts/estimate", { headers: { cookie: `${auth.SESSION_COOKIE}=${auth.createSession().value}` } });
+ expect(priceAs(asOwner, seen).own).toBeUndefined();
+ });
+});
diff --git a/tests/accounts-admin.test.ts b/tests/accounts-admin.test.ts
index 90caad64..bad8b022 100644
--- a/tests/accounts-admin.test.ts
+++ b/tests/accounts-admin.test.ts
@@ -12,7 +12,9 @@ const auth = await import("@/server/auth");
const { proxy } = await import("@/proxy");
afterAll(() => {
delete process.env.FUOBE_PUBLIC_SIGNUP;
- fs.rmSync(dir, { recursive: true, force: true });
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
});
const req = (url: string, method = "GET", cookie?: string) =>
diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.ts
index 9e5beaca..18d9d7b4 100644
--- a/tests/public-signup.test.ts
+++ b/tests/public-signup.test.ts
@@ -12,7 +12,12 @@ delete process.env.FUOBE_ALLOWED_ORIGINS;
const auth = await import("@/server/auth");
const { proxy } = await import("@/proxy");
const access = await import("@/lib/guest-access");
-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+afterAll(() => {
+ // The database stays open until the worker exits (Windows won't delete it before).
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
const toLogin = (r: Response) => r.status === 307 && new URL(r.headers.get("location") ?? "", "http://x").pathname === "/login";
@@ -243,7 +248,8 @@ describe("accounts never run on the owner's keys or GPU", () => {
describe("accounts never see or change the owner's library", () => {
const families: Record<string, { lists: string[]; records: string[]; changes: [string, string][] }> = {
generations: {
- lists: ["/api/generations", "/api/generations/trash", "/api/generations/facets"],
+ // (/api/generations itself goes to the route, which lists only the account's own runs: tests/account-gpu.test.ts.)
+ lists: ["/api/generations/trash", "/api/generations/facets"],
records: ["/api/generations/g1", "/api/generations/zip?ids=g1"],
changes: [["PATCH", "/api/generations/g1"], ["DELETE", "/api/generations/g1"], ["POST", "/api/generations/bulk"], ["DELETE", "/api/generations/trash"], ["POST", "/api/generations/g1/cancel"]],
},
@@ -304,3 +310,28 @@ describe("accounts never see or change the owner's library", () => {
expect(access.isPriceCheck("GET", "/api/shorts/estimate", "")).toBe(false);
});
});
+
+describe("accounts with their own GPU", () => {
+ it("run the studios' generations once connected; other tools still say so", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = auth.createAccount("[email protected]", "long enough");
+ const cookie = auth.createSession(a.id).value;
+ expect(passed(proxy(req("/api/account/gpu", { method: "PUT", cookie })))).toBe(true);
+ expect(passed(proxy(req("/api/account/gpu", { method: "DELETE", cookie })))).toBe(true);
+ expect(proxy(req("/api/generations", { method: "POST", cookie })).headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ auth.setAccountGpu(a.id, { url: "https://gpu.example" });
+ expect(passed(proxy(req("/api/generations", { method: "POST", cookie })))).toBe(true);
+ const tool = proxy(req("/api/canvases/c1/run", { method: "POST", cookie }));
+ expect(tool.status).toBe(403);
+ expect(tool.headers.get(access.CONNECT_GPU_HEADER)).toBeNull();
+ expect((await tool.json()).code).toBe("own-gpu-tool");
+ // Still never settings, keys or tokens.
+ expect(proxy(req("/api/settings", { method: "PUT", cookie })).status).toBe(403);
+ });
+
+ it("keeps a guest out of Your GPU", () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ expect(proxy(req("/api/account/gpu", { method: "PUT" })).status).toBe(401);
+ expect(proxy(req("/api/account/gpu")).status).toBe(401);
+ });
+});