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.

Image to 3D: accounts make 3D models on their own GPU or key

Adarsh82468ef0768c
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 07f3d6b5..ee17de0d 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -264,8 +264,8 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
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; "Enhance prompt" uses Fuobe's offline wording. Other tools
(Canvas, Cinema, Shorts, Assist, Marketing…) answer 403 with `code: "own-gpu-tool"`, because they
- plan with the studio's own AI helpers or keep projects of their own. Image to 3D and text to 3D
- answer the same for now: a 3D model is finished on the server. So do the Audio hub's Split
+ plan with the studio's own AI helpers or keep projects of their own. A 3D model sent here answers the
+ same: Image to 3D has its own route (below). So do the Audio hub's Split
soundtrack and Edit speech and Video tools → Remove dialogue (all `POST /api/audio-tools`) and the
turnaround video (`POST /api/turnaround`), though their price checks work, priced for the account's
own GPU. Split soundtrack's, Edit speech's and Remove dialogue's pages say so up front ("Split
@@ -298,6 +298,16 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
find that storyboard."). "From one idea" splits the story into a shot list without the studio's AI helper. One
sheet takes as many panels for an account as its recorded GPU test showed (`ONE_SHEET_GPU_TEST`; with none recorded
a one-sheet board answers 422 for an account). A guest gets the sign-up card.
+- **Image to 3D.** An account makes its 3D models on its own ComfyUI, or on its own fal.ai or Replicate key on the
+ cloud engine (`POST /api/image-to-3d`, which takes the same request as `POST /api/generations`): From an image, From
+ several images, From text, Pick an object and Splat, and a finished model's Rig & animate. It gets the checks every
+ tool run gets, and its models show under "Your 3D models", to view in 3D and download. A GLB from its ComfyUI is
+ finished on this server (the web GLB the viewer loads) under its limits (`src/server/model3d-finish.ts`): one account's
+ finish at a time across the server, at low priority; a model over 300 MB, a server or account short of room, or more
+ than 60 finishes in an hour keep the model as it came (still viewable and downloadable). Its turntable is recorded in
+ the browser ("Record turntable"), not on the server. Refine detail, the TRELLIS.2 final, Idol 3D's other sides and
+ Film it photoreal stay the owner's, and Retexture opens once its cloud models pass a live call. On this install's
+ GPUs (hosted runs) 3D isn't offered yet. A guest gets the sign-up card.
- **Files a run takes.** A run on your GPU takes only files you uploaded here, or your own results.
A link or a `data:` URI answers 400 with `code: "input-not-allowed"`, someone else's file 403
(`input-not-yours`), and a file that has expired 404 (`input-gone`, "That file has expired.
@@ -375,7 +385,7 @@ account with that provider. The studio's own keys are never used for an account'
- **Limits.** Every account limit applies to paid runs too (4 at once, 60 an hour, 4 outputs a run,
its space), checked before anything reaches the provider. Runs with a key send the prompt and the
attached files to that provider. civitai LoRAs are left out of runs on an account's key (copying
- them would use the studio's civitai key). Assist, text steps, 3D and the other tools stay closed.
+ them would use the studio's civitai key). Image to 3D runs on its key too; Assist, text steps and the other tools stay closed.
- An account on a studio set to **Open source only** keeps its keys, but they aren't used.
## Hosted runs
diff --git a/src/app/api/image-to-3d/route.ts b/src/app/api/image-to-3d/route.ts
new file mode 100644
index 00000000..08a3ecff
--- /dev/null
+++ b/src/app/api/image-to-3d/route.ts
@@ -0,0 +1,71 @@
+import { POST as runGeneration } from "@/app/api/generations/route";
+import { getModel } from "@/lib/catalog";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "@/server/account-files";
+import { accountInputProblem } from "@/server/account-inputs";
+import { accountEngineMode } from "@/server/account-keys";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createGenerations } from "@/server/generations";
+import { GenerationRequestSchema } from "@/server/request-schema";
+
+/**
+ * Image to 3D's runs: a model from a photo, several photos, words or an object in a photo, a splat, and a finished
+ * model's rig or retexture. The body is a generation request, as POST /api/generations takes it (plus an optional
+ * `requestId`, and `gpuCheck: "skip"`).
+ *
+ * The owner's run goes through POST /api/generations, as always. An account's runs on its own GPU or its own fal.ai or
+ * Replicate key, with only its own files, after the checks every tool run gets (src/server/account-tool-run.ts), and its
+ * model is finished on this server under its own limits (src/server/model3d-finish.ts). A guest signs up first.
+ */
+export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "owner") return runGeneration(request);
+ const account = viewer.account;
+ const big = bodyTooBig(request);
+ if (big) return big;
+ const text = await request.text().catch(() => "");
+ if (Buffer.byteLength(text) > ACCOUNT_LIMITS.runBodyBytes) return refuse(413, ACCOUNT_MESSAGES.bodyTooBig);
+ let raw: unknown = null;
+ try {
+ raw = JSON.parse(text);
+ } catch {}
+ const parsed = GenerationRequestSchema.safeParse(raw);
+ if (!parsed.success) return refuse(400, parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "));
+ const extra = (raw ?? {}) as { requestId?: unknown; gpuCheck?: unknown };
+ const requestId = typeof extra.requestId === "string" && extra.requestId.length <= 100 ? extra.requestId : undefined;
+ let req = parsed.data as GenerationRequest;
+ // This route makes 3D models only; everything else runs in the studios (POST /api/generations).
+ if (getModel(req.modelId)?.kind !== "model3d") return refuse(422, "Pick a 3D model.");
+ // As in the studios: without a key of its own the account stays on the open engine, and a run makes up to 4 models.
+ req = { ...req, engine: accountEngineMode(account.id) === "open" ? "open" : req.engine };
+ const notes: string[] = [];
+ if ((req.params?.numOutputs ?? 1) > ACCOUNT_LIMITS.outputsPerRun) {
+ req = { ...req, params: { ...req.params, numOutputs: ACCOUNT_LIMITS.outputsPerRun } };
+ notes.push(ACCOUNT_MESSAGES.outputsCapped);
+ }
+ // Every file it names (its photos, the model it rigs, a file in its settings): only its own uploads and results.
+ const problem = accountInputProblem(req, account.id);
+ if (problem) return refuse(problem.status, problem.error, { code: problem.code });
+ const files = Object.values(req.inputs ?? {}).flatMap((v) => (Array.isArray(v) ? v : [v]));
+ const run = req;
+ return onceForAccount(
+ account,
+ "image-to-3d",
+ requestId,
+ () =>
+ runAccountTool(request, account, {
+ tool: "image-to-3d",
+ files,
+ plan: () => [{ request: run }],
+ start: () => createGenerations(run),
+ skipGpuCheck: extra.gpuCheck === "skip",
+ }),
+ ({ value, gpuWarning }) => {
+ const all = [...new Set([...notes, ...value.flatMap((g) => g.notes ?? [])])];
+ return Response.json({ items: value, ...(all.length && { notes: all }), ...(gpuWarning && { gpuWarning }) }, { status: 201, headers: { "Cache-Control": "no-store" } });
+ },
+ );
+}
+
+const refuse = (status: number, error: string, more: Record<string, unknown> = {}) => Response.json({ error, ...more }, { status, headers: { "Cache-Control": "no-store" } });
diff --git a/src/components/model3d/hooks.ts b/src/components/model3d/hooks.ts
index ea516f62..85553590 100644
--- a/src/components/model3d/hooks.ts
+++ b/src/components/model3d/hooks.ts
@@ -1,10 +1,52 @@
"use client";
-import { useQuery } from "@tanstack/react-query";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
-import type { GenerationRequest } from "@/lib/catalog/types";
+import { toast } from "sonner";
+import { COMPUTER_KICK_EVENT, useCreateGeneration, useIsOwner } from "@/lib/api";
+import type { Generation, GenerationRequest } from "@/lib/catalog/types";
import { responseError } from "@/lib/refusals";
+/**
+ * An account's Image to 3D run (a model, a splat, a rig, a retexture): POST /api/image-to-3d, which runs it on the
+ * account's own GPU or key and finishes the model under its limits. Its cards show when the lists load again.
+ */
+function useAccountRun3d() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async (req: GenerationRequest): Promise<Generation[]> => {
+ const res = await fetch("/api/image-to-3d", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(req) });
+ const body = (await res.json().catch(() => ({}))) as { items?: Generation[]; notes?: string[]; gpuWarning?: string; error?: string; code?: unknown };
+ // Stopped by the GPU pre-flight: the guided fix opens (watchGuestRefusals), so no error toast on top of it.
+ if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") throw Object.assign(new Error(body.error ?? "This tool needs setting up on your GPU"), { gpuSetup: true });
+ if (!res.ok) {
+ const code = typeof body.code === "string" ? body.code : undefined;
+ throw responseError(res, Object.assign(new Error(body.error ?? "Something went wrong. Please try again."), { status: res.status }, code && { code }));
+ }
+ if (body.notes?.length) toast.warning(body.notes.length > 1 ? "This run changes a few things" : "This run changes one thing", { description: body.notes.join(". ") });
+ if (body.gpuWarning) toast.warning(body.gpuWarning);
+ return body.items ?? [];
+ },
+ onSuccess: () => {
+ // A run on the ComfyUI on this computer: the tab that runs it asks for it at once.
+ window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ void qc.invalidateQueries({ queryKey: ["library-facets"] });
+ },
+ });
+}
+
+/**
+ * Start an Image to 3D run: the owner's as a studio run (POST /api/generations); anyone else's through
+ * POST /api/image-to-3d (a guest gets the sign-up card there).
+ */
+export function useCreate3d() {
+ const owner = useIsOwner();
+ const studio = useCreateGeneration();
+ const account = useAccountRun3d();
+ return owner ? studio : account;
+}
+
/** What /api/generations?preview=1 says a request would run as (the parts the page shows). */
export interface RunPreview {
costUsd: number | null;
diff --git a/src/components/model3d/model-card.tsx b/src/components/model3d/model-card.tsx
index 054e4963..321c5526 100644
--- a/src/components/model3d/model-card.tsx
+++ b/src/components/model3d/model-card.tsx
@@ -5,8 +5,9 @@ import Link from "next/link";
import { createElement, useCallback, useEffect, useEffectEvent, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
-import { uploadFile, useEngine, useHydrated, useIsOwner } from "@/lib/api";
-import { FINAL_3D, animateSpinHref, animationName, finalBuildHref, FRONT_YAW, model3dView, photorealAngle, photorealBody, stillOf, turnOrbit, type Model3dView } from "@/lib/av/model3d";
+import { uploadFile, useEngine, useHydrated, useIsOwner, useModelAccess } from "@/lib/api";
+import { offered } from "@/lib/model-access";
+import { FINAL_3D, RETEXTURE_MODELS, animateSpinHref, animationName, finalBuildHref, FRONT_YAW, model3dView, photorealAngle, photorealBody, stillOf, turnOrbit, type Model3dView } from "@/lib/av/model3d";
import { anyAngleHref } from "@/lib/catalog/any-angle";
import { PATH_FPS, PATH_FRAMES } from "@/lib/camera-path";
import { useFlyAround } from "@/components/fly-around-run";
@@ -138,8 +139,12 @@ export function ModelCard({
const [filming, setFilming] = useState<number | null>(null);
const pendingFilm = useRef(false);
const photorealStand = engine === "open" ? "/api/files/placeholder.mp4" : undefined;
- const photoreal = photorealBody(view, engine, photorealStand, drawn);
+ // Filmed by this studio's own worker (WorldCast), so the owner's only.
+ const photoreal = owner ? photorealBody(view, engine, photorealStand, drawn) : null;
const fly = useFlyAround(photoreal && !view.rigged && (view.glb || view.turntable) ? photoreal : null);
+ // Retexture's cloud models, where this viewer may run one (an account's own key runs only the ones checked live).
+ const access = useModelAccess();
+ const canRetexture = RETEXTURE_MODELS.some((m) => offered(access, m.id, "cloud"));
const photoSrc = view.photo ?? drawn;
const recordFilm = async (el: HTMLElement) => {
setFilming(0);
@@ -231,7 +236,7 @@ export function ModelCard({
pendingFilm.current = true;
setShow("3d");
};
- const canFilm = !!photoreal && !view.rigged && (engine === "cloud" || (view.glb ? canRecord && !failed : !!view.turntable));
+ const canFilm = owner && !!photoreal && !view.rigged && (engine === "cloud" || (view.glb ? canRecord && !failed : !!view.turntable));
const filmBusy = filming !== null || fly.run.isPending;
const spin = view.rigged ? null : animateSpinHref(view, recorded?.saved);
// Draft then final (idol-6): an Idol 3D splat's picture, rebuilt as a textured mesh with TRELLIS.2.
@@ -474,7 +479,7 @@ export function ModelCard({
</Link>
</Button>
)}
- {view.glb && !view.rigged && !view.splat && g.op !== "splat" && (
+ {view.glb && !view.rigged && !view.splat && g.op !== "splat" && canRetexture && (
<Button variant="outline" size="sm" className="rounded-full" onClick={() => setRetexturing(true)}>
<Paintbrush className="size-3.5" /> Retexture
</Button>
diff --git a/src/components/model3d/model3d-studio.tsx b/src/components/model3d/model3d-studio.tsx
index 53db7f79..85a0677a 100644
--- a/src/components/model3d/model3d-studio.tsx
+++ b/src/components/model3d/model3d-studio.tsx
@@ -16,10 +16,9 @@ import { FailedTile, PendingTile } from "@/components/studio/feed";
import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";
import { MediaDrop } from "@/components/av/media-drop";
import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
-import { SelfHostNote } from "@/components/self-host-note";
import { HandoffImage } from "@/components/nav/next-steps";
import { ExampleRow } from "@/components/studio/example-row";
-import { useCreateGeneration, useEngine, useGenerations, useHydrated, useIsOwner, useLikelyVisitor, useModelAccess, useStatus } from "@/lib/api";
+import { useEngine, useGenerations, useHydrated, useIsOwner, useLikelyVisitor, useModelAccess, useStatus } from "@/lib/api";
import {
FINAL_3D,
IDOL_QUALITIES,
@@ -53,7 +52,7 @@ import { keepOffered, offered } from "@/lib/model-access";
import type { ExampleRowData } from "@/lib/examples/types";
import { cn } from "@/lib/utils";
import { toastError } from "@/lib/refusals";
-import { priceLine, useRunPreview } from "./hooks";
+import { priceLine, useCreate3d, useRunPreview } from "./hooks";
import { ModelCard } from "./model-card";
import { RefineOption } from "./refine-option";
import { OtherSides, useOtherSidesOffered } from "./other-sides";
@@ -242,11 +241,12 @@ function ModePicker({ mode, onChange }: { mode: Model3dMode; onChange: (m: Model
*/
export function Model3dStudio({ info, examples }: { info: Record<string, Model3dInfo>; examples?: ExampleRowData | null }) {
const [engine, setEngine, engineMode] = useEngine();
- // A 3D model is finished on this server, so accounts don't get Image to 3D yet, even on their own GPU or key: said up
- // front, and the uploads and Make it 3D are off, instead of a run the server refuses.
+ // An account makes its models on its own GPU or key (POST /api/image-to-3d); a guest gets the sign-up card when it
+ // uploads or runs. The extras that need this studio's own setup (Refine detail, the TRELLIS.2 final) stay the owner's.
const visitor = useLikelyVisitor();
+ const owner = useIsOwner();
const access = useModelAccess();
- const create = useCreateGeneration();
+ const create = useCreate3d();
const results = useGenerations({ features: [MODEL3D_FEATURE, "app:app-image-to-3d", "app:app-photo-to-3d", MODEL3D_FILM_FEATURE], limit: 24 });
const [mode, setMode] = useState<Model3dMode>("image");
const router = useRouter();
@@ -342,16 +342,13 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
...(idol && { quality: idolQuality, photoCrop: idolPhoto, ...(engine === "open" && { trimSpikes: idolTrim }) }),
};
const uploading = !!photo?.uploading || VIEW_SIDES.some((s) => views[s]?.uploading);
- // A guest or an account reads why the button is off, not a step on an upload that is off too.
- const blocker = visitor ? "Image to 3D isn't available here" : (model3dBlocker(input) ?? (uploading ? "Uploading…" : null));
+ const blocker = model3dBlocker(input) ?? (uploading ? "Uploading…" : null);
// The price before anything is attached: placeholders stand in for the files and the words.
const priced: GenerationRequest | null = modelId
? model3dRequest({ ...input, photo: input.photo || PLACEHOLDER, views: { front: PLACEHOLDER, left: PLACEHOLDER, ...sides }, prompt: input.prompt?.trim() || "an object" })
: null;
const preview = useRunPreview(engineKnown ? priced : null);
- // A free run (open weights) is free on a self-hosted Fuobe: a guest or an account reads that, not "your ComfyUI".
- const free = !!preview.data && !preview.data.demo && (preview.data.engine === "open" || preview.data.costUsd === 0);
- const price = visitor && free ? "Not available here" : priceLine(preview.data);
+ const price = priceLine(preview.data);
const cloudAllowed = engineMode !== "open";
// Hi3D runs on your GPU only: offered while the install runs open models and the model is switched on.
const refineAllowed = !visitor && engineMode !== "cloud" && offered(access, HI3D_MODEL, "open");
@@ -359,7 +356,6 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
const finalAllowed = !visitor && engineMode !== "cloud" && offered(access, FINAL_3D.model, "open");
const refining = refineAllowed && engine === "open" && (mode === "image" || mode === "multi") && refine !== null ? refine : null;
const go = () => {
- if (visitor) return;
if (blocker) return void toast(blocker, { id: "3d-blocker" });
create.mutate(withRefine(model3dRequest(input), engine, refining), {
onSuccess: () =>
@@ -384,14 +380,12 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
}, []);
const showsMade = mode === "multi" && VIEW_SIDES.some((s) => s !== "front" && !!views[s] && madeSides.includes(views[s]!.ref));
return (
- <ToolShell title="Image to 3D" selfHostedOnly>
+ <ToolShell title="Image to 3D">
<Suspense fallback={null}>
<UrlModel onModel={fromUrl} onMode={setMode} onRig={showRigHint} onImage={fromImage} />
<HandoffImage onImage={takeHandoff} />
</Suspense>
- <ToolHero title="Your product, in 3D" subtitle={HINTS[mode]}>
- {visitor && <SelfHostNote className="mt-3 max-w-xl">Image to 3D isn&apos;t available here.</SelfHostNote>}
- </ToolHero>
+ <ToolHero title="Your product, in 3D" subtitle={HINTS[mode]} />
<ModePicker mode={mode} onChange={pickMode} />
{rigHint && (
<p role="status" className="mx-auto mt-4 max-w-[880px] rounded-2xl border bg-brand-faint px-4 py-3 text-[13px] text-brand-text">
@@ -414,8 +408,7 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
<Panel title="Photos of each side" aside={<span className="text-[12px] text-muted-foreground">{Object.keys(sides).length} of 4</span>}>
{/* Four 80 px slots in a row when the panel has room for them (22rem), two by two when it doesn't. */}
<div className="@container">
- {/* A guest's or an account's photos would be uploaded for a model that can't be made here. */}
- <div inert={visitor} className={cn("grid grid-cols-2 justify-items-center gap-2 @[22rem]:grid-cols-4", visitor && "opacity-50")}>
+ <div className="grid grid-cols-2 justify-items-center gap-2 @[22rem]:grid-cols-4">
{VIEW_SIDES.map((s) => (
<div key={s} className="flex flex-col items-center gap-1">
<MediaSlot label={SIDE_LABELS[s]} kind="image" value={views[s] ?? null} onChange={setSide(s)} required={s === "front"} size="lg" caption />
@@ -454,7 +447,7 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
</Panel>
) : (
<div className="grid min-w-0 gap-3">
- <div inert={visitor} className={cn("min-w-0", visitor && "opacity-50")}>
+ <div className="min-w-0">
<MediaDrop
kind="image"
value={photo}
@@ -517,7 +510,7 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
))}
</SelectContent>
</Select>
- <p className="text-[12px] text-muted-foreground">{choices.find((m) => m.id === modelId)?.note}</p>
+ <p className="text-[12px] text-muted-foreground">{modelNote(choices.find((m) => m.id === modelId)?.note, owner)}</p>
</div>
{!idolSplat && (mode === "image" || mode === "multi") && <RefineOption engine={engine} value={refine} onChange={setRefine} openAllowed={refineAllowed} onUseGpu={() => setEngine("open")} />}
{idol && (
@@ -534,11 +527,12 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
{MAKE_3D_HINT}
</p>
)}
- <Button size="lg" className={cn("mt-4 w-full rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={go} disabled={create.isPending || visitor}>
+ <Button size="lg" className={cn("mt-4 w-full rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={go} disabled={create.isPending}>
{create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Box className="size-4" />} {mode === "splat" ? "Make the splat" : "Make it 3D"}
</Button>
<p className="mt-2 text-[12px] text-muted-foreground" aria-live="polite">
- {visitor ? blocker : <>{blocker ? `${blocker} · ` : ""}{preview.isError ? (preview.error as Error).message : (price ?? "Working out the price…")}</>}
+ {blocker ? `${blocker} · ` : ""}
+ {preview.isError ? (preview.error as Error).message : (price ?? "Working out the price…")}
</p>
<p className="mt-1 text-[12px] text-muted-foreground">
{idolSplat
@@ -549,7 +543,7 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
? engine === "open"
? "Cuts the subject out and comes with an orbit video."
: "Cuts the subject out, ready to download."
- : engine === "open"
+ : engine === "open" && owner
? "Comes with a turntable video of your model."
: "Download your model, or record a turntable right here."}
</p>
@@ -557,7 +551,7 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
)}
</Panel>
</div>
- {examples && (visitor || (results.isSuccess && !items.length)) && <ExampleRow row={examples} layout="column" maxWidth={880} className="mt-12" />}
+ {examples && results.isSuccess && !items.length && <ExampleRow row={examples} layout="column" maxWidth={880} className="mt-12" />}
<section id="your-3d-models" className="mx-auto mt-12 max-w-[880px] scroll-mt-6" aria-labelledby="models3d">
{(results.isLoading || items.length > 0) && (
<h3 id="models3d" className="mb-3 font-heading text-[22px]">
@@ -581,6 +575,14 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d
);
}
+/**
+ * A model's note under the picker. This studio renders the turntable of a model made on its own GPU; anyone else's
+ * model comes without one (its card records one in the browser), so their note leaves it out.
+ */
+function modelNote(note: string | undefined, owner: boolean): string | undefined {
+ return owner ? note : note?.replace(/, with a turntable video$/, "");
+}
+
/** Retry runs the same request; a step of the open text-to-3D chain starts the chain again from the words. */
function retryOf(g: Generation): GenerationRequest {
const r = g.request;
@@ -603,7 +605,7 @@ function ResultCard({
finalAllowed: boolean;
onFinal: (photo: string) => void;
}) {
- const create = useCreateGeneration();
+ const create = useCreate3d();
if (g.status === "queued" || g.status === "running") return <PendingTile g={g} ratio={4 / 3} />;
if (g.status !== "succeeded") return <FailedTile g={g} ratio={4 / 3} onRetry={() => create.mutate(retryOf(g), { onError: (e) => toastError(e) })} />;
if (g.kind === "video") return <FilmCard g={g} />;
diff --git a/src/components/model3d/retexture-dialog.tsx b/src/components/model3d/retexture-dialog.tsx
index ff3c813a..2241ab45 100644
--- a/src/components/model3d/retexture-dialog.tsx
+++ b/src/components/model3d/retexture-dialog.tsx
@@ -8,10 +8,10 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
-import { uploadFile, useCreateGeneration } from "@/lib/api";
+import { uploadFile } from "@/lib/api";
import { RETEXTURE_MODELS, RETEXTURE_PROMPT_MAX, RETEXTURE_SIZES, retextureRequest, type RetextureModel } from "@/lib/av/model3d";
import { toastError } from "@/lib/refusals";
-import { priceLine, useRunPreview } from "./hooks";
+import { priceLine, useCreate3d, useRunPreview } from "./hooks";
const SIZE_LABEL: Record<(typeof RETEXTURE_SIZES)[number], string> = { "2k": "2K textures", "4k": "4K textures", "8k": "8K textures" };
@@ -20,7 +20,7 @@ const SIZE_LABEL: Record<(typeof RETEXTURE_SIZES)[number], string> = { "2k": "2K
* both are given). Cloud only (fal.ai): no open retexturer runs in ComfyUI here.
*/
export function RetextureDialog({ glb, open, onOpenChange, cloudAllowed }: { glb: string; open: boolean; onOpenChange: (v: boolean) => void; cloudAllowed: boolean }) {
- const create = useCreateGeneration();
+ const create = useCreate3d();
const [prompt, setPrompt] = useState("");
const [style, setStyle] = useState<{ url: string; preview: string } | null>(null);
const [uploading, setUploading] = useState(false);
diff --git a/src/components/model3d/rig-dialog.tsx b/src/components/model3d/rig-dialog.tsx
index 9b5277b4..d70aed89 100644
--- a/src/components/model3d/rig-dialog.tsx
+++ b/src/components/model3d/rig-dialog.tsx
@@ -8,10 +8,9 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { useCreateGeneration } from "@/lib/api";
import { ANIMATION_LIBRARY_URL, ANIMATION_MAX, ANIMATION_PRESETS, animationId, rigRequest } from "@/lib/av/model3d";
import { toastError } from "@/lib/refusals";
-import { priceLine, useRunPreview } from "./hooks";
+import { priceLine, useCreate3d, useRunPreview } from "./hooks";
const NONE = "none";
const NUMBER = "number";
@@ -21,7 +20,7 @@ const NUMBER = "number";
* animated GLB the card plays. Cloud only (fal.ai): UniRig, the open rigger, has no verified ComfyUI pack.
*/
export function RigDialog({ glb, open, onOpenChange, cloudAllowed }: { glb: string; open: boolean; onOpenChange: (v: boolean) => void; cloudAllowed: boolean }) {
- const create = useCreateGeneration();
+ const create = useCreate3d();
const [pick, setPick] = useState<string>("30");
const [typed, setTyped] = useState("");
const animation = pick === NONE ? null : pick === NUMBER ? animationId(typed) : Number(pick);
diff --git a/src/components/nav/next-steps.tsx b/src/components/nav/next-steps.tsx
index b10b07cd..6296577a 100644
--- a/src/components/nav/next-steps.tsx
+++ b/src/components/nav/next-steps.tsx
@@ -14,10 +14,12 @@ import { CoverThumb } from "./cover-thumb";
const NOUN: Record<string, string> = { image: "picture", video: "clip", audio: "sound", model3d: "model" };
/**
- * Studios that read a handed-over picture with their own small reader (`HandoffImage` below). Both run on a
- * self-hosted Fuobe only, so a guest or an account is never sent there.
+ * Studios that read a handed-over picture with their own small reader (`HandoffImage` below). Image to 3D runs for an
+ * account too (on its own GPU or key); Character Sheet on a self-hosted Fuobe only, so a guest or an account is never
+ * sent there.
*/
const ADAPTERS = { characterSheet: true, imageTo3d: true } as const;
+const VISITOR_ADAPTERS = { imageTo3d: true } as const;
/** The heading over the steps: "Keep going with this picture" (clip, sound, model). */
export function keepGoingTitle(kind: string | undefined): string {
@@ -51,7 +53,7 @@ export function NextSteps({
const engineMode = useEngineMode();
const visitor = useLikelyVisitor();
const titleId = useId();
- const steps = keepGoing(g, index, { engineMode, visitor, adapters: visitor ? undefined : ADAPTERS }, max + (skip?.length ?? 0))
+ const steps = keepGoing(g, index, { engineMode, visitor, adapters: visitor ? VISITOR_ADAPTERS : ADAPTERS }, max + (skip?.length ?? 0))
.filter((s) => !skip?.includes(s.id))
.slice(0, max);
if (!steps.length) return null;
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index d6c3b972..d410bdc9 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -278,6 +278,8 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [
/^\/api\/genjutsu(\/(scene|transcribe))?$/,
// Storyboard: a board, and its film (the route reads the account's own board only).
/^\/api\/storyboards(\/[^/]+\/film)?$/,
+ // Image to 3D's runs (a model, a splat, a rig, a retexture): the model is finished on this server under the account's limits.
+ /^\/api\/image-to-3d$/,
];
/**
diff --git a/src/lib/nav-model.ts b/src/lib/nav-model.ts
index 7a37f69c..325fc1aa 100644
--- a/src/lib/nav-model.ts
+++ b/src/lib/nav-model.ts
@@ -734,7 +734,6 @@ export const STUDIO_SUBS: Readonly<Record<string, StudioSubs>> = {
export const OWNER_RUNS: ReadonlySet<string> = new Set([
"audio-split",
"video-tools-remove-dialogue",
- ...STUDIO_SUBS["image-to-3d"].ids,
...STUDIO_SUBS["character-sheet"].ids,
...STUDIO_SUBS.photodump.ids,
]);
diff --git a/src/server/account-files.ts b/src/server/account-files.ts
index b39e35fb..75e5ba46 100644
--- a/src/server/account-files.ts
+++ b/src/server/account-files.ts
@@ -58,6 +58,8 @@ export const ACCOUNT_LIMITS = {
gpuChecksPerMinute: 10,
/** Fuobe Soul's finished pictures (the look's grade made in the browser) stored per hour: a run's 4 outputs, 60 runs. */
finishesPerHour: 240,
+ /** 3D models finished on this server (the web GLB, model3d-finish.ts) per hour; past it a model is kept as it came. */
+ modelFinishesPerHour: 60,
} as const;
export const RETENTION_MS = { upload: ACCOUNT_LIMITS.uploadDays * DAY, run: ACCOUNT_LIMITS.runDays * DAY };
diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.ts
index 49806d7e..04e0c52b 100644
--- a/src/server/account-tool-run.ts
+++ b/src/server/account-tool-run.ts
@@ -34,7 +34,8 @@ import { ShortsError } from "./shorts";
* ("Your keys"); never the install's GPU, keys or AI helper (accountRun: 403 connect-gpu, add-key or own-gpu-tool);
* - the GPU pre-flight on its own ComfyUI (409 gpu-setup with the guided fix), and the LoRAs a step adds (409
* comfy_missing_model);
- * - the moderation service's check, when one is set (hosted-run.ts moderateRun).
+ * - the moderation service's check, when one is set (hosted-run.ts moderateRun);
+ * - a 3D model only on the account's own GPU or key (model3dAllowed): its finish runs on this server under its limits.
*
* Then the tool's own start runs inside asAccount (tenant.ts): every generation it creates is stamped as the account's,
* reads only its files and goes to its GPU or key. Where a run goes is decided in one place (`placeOf`): today always the
@@ -138,8 +139,14 @@ export interface ToolStep {
deps?: number;
}
-/** Where an account's tool run goes. Today always its own GPU or key ("own"); hosted runs add the install's GPUs. */
-export type ToolPlace = { kind: "own" };
+/** Where an account's tool run goes. Today always its own GPU or key ("own"); hosted runs add the install's GPUs ("pool"). */
+export type ToolPlace = { kind: "own" } | { kind: "pool" };
+
+/**
+ * Whether a run placed here may make a 3D model. A 3D model is finished on this server under the account's own limits
+ * (model3d-finish.ts): allowed on the account's own GPU or key, never on this install's GPUs (hosted runs don't offer 3D yet).
+ */
+export const model3dAllowed = (place: ToolPlace): boolean => place.kind === "own";
/**
* Where this run goes. The one place a tool run's placement is decided: hosted runs (hosted-run.ts decidePlace, the
@@ -244,7 +251,7 @@ export async function runAccountTool<T>(request: Request, account: Account, run:
let kind: MediaKind = "video";
let onKey = false;
try {
- // Each step's provider must be one the account has; a 3D model is finished on the server (not for accounts yet).
+ // Each step's provider must be one the account has; a 3D model only where model3dAllowed says.
const planned: Planned[] = steps.map((s) => ({ step: s, p: asAccount(id, () => previewChained(s.request, s.deps ?? 0)) }));
if (place.kind === "own") {
for (const provider of new Set(planned.map((x) => x.p.route.provider))) {
@@ -252,7 +259,7 @@ export async function runAccountTool<T>(request: Request, account: Account, run:
if ("error" in own) return back(refusalResponse(own));
}
}
- if (planned.some(({ p }) => outputKind(p.op, p.model) === "model3d" && p.model.id !== ANY_ANGLE.buildModel)) return back(ownGpuTool());
+ if (!model3dAllowed(place) && planned.some(({ p }) => outputKind(p.op, p.model) === "model3d" && p.model.id !== ANY_ANGLE.buildModel)) return back(ownGpuTool());
// GPU pre-flight on its own ComfyUI: a step sure to fail for something missing stops the run with the plan that
// fixes it (never when the check is unknown). Each workflow once.
const target = gpuTargetFor(request, "read");
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 249bd99d..bce7648f 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -1027,9 +1027,9 @@ export function createGenerations(sent: GenerationRequest, opts: CreateOptions =
const catalogModel = getModel(original.modelId);
const found = catalogModel && offeredFor(catalogModel, original.engine);
const shotModel = found && dualEngine(found) ? onEngine(found, engineFor(found, original.engine)) : found;
- // An account's 3D model would be finished on this server, outside its own limits: not yet (the route refuses first).
+ // An account's 3D model is finished on this server under its own limits (model3d-finish.ts); on this install's GPUs it isn't offered yet.
// Any Angle's 3D view is the exception: a splat and its turntable, nothing to finish here.
- if (original.account && shotModel?.kind === "model3d" && shotModel.id !== ANY_ANGLE.buildModel) throw new Error(OWN_GPU_TOOL_MESSAGE);
+ if (original.account && original.place === "pool" && shotModel?.kind === "model3d" && shotModel.id !== ANY_ANGLE.buildModel) throw new Error(OWN_GPU_TOOL_MESSAGE);
if (!opts.dependsOn && shotModel?.options.multiShot?.mode === "concat" && (original.params?.shots?.filter((x) => x.prompt.trim()).length ?? 0) > 1) {
return createShotFilm(original, shotModel);
}
diff --git a/src/server/model3d-finish.ts b/src/server/model3d-finish.ts
index 488b15f3..5e288f57 100644
--- a/src/server/model3d-finish.ts
+++ b/src/server/model3d-finish.ts
@@ -6,6 +6,8 @@ import path from "node:path";
import type { OutputFile } from "@/lib/catalog/types";
import { absolutePath, deleteAsset, getAsset, saveFile } from "./storage";
import { inTurn } from "./account-send";
+import { ACCOUNT_LIMITS, accountTotalBytes, accountUsage, diskHasRoom } from "./account-files";
+import { hit } from "./rate";
/**
* The finish every image-to-3D GLB from ComfyUI gets on this server, in two steps:
@@ -23,6 +25,10 @@ import { inTurn } from "./account-send";
*
* Both scripts run as child processes (the work is CPU-heavy and must not stall the server's event loop),
* one turntable at a time, at below-normal priority. Any failure keeps what was made: the raw GLB always.
+ *
+ * An account's model (public sign-up, made on its own GPU or key) gets step 1 only, under its limits: one account's
+ * finish at a time across the server, the file's size, the server's and its files' room, and an hour's finishes
+ * (accountFinishProblem). Its browser records the turntable.
*/
/** Bump when the finish changes what it writes. */
@@ -182,6 +188,24 @@ const oneAccountAtATime = <T,>(account: string, fn: () => Promise<T>): Promise<T
/** An account's raw GLB over this is kept as it is, with no finish. */
export const ACCOUNT_FINISH_MAX_BYTES = 300 * 2 ** 20;
+/**
+ * Why an account's model isn't finished on this server (null: it is), by the account's limits. The raw GLB is kept
+ * either way, to view and download; only the web GLB is left out.
+ * - file size: a raw GLB over ACCOUNT_FINISH_MAX_BYTES;
+ * - disk room: the server keeps its free space and the accounts' share (diskHasRoom), and the account's files have room;
+ * - an hour's finishes: ACCOUNT_LIMITS.modelFinishesPerHour (counted only for a finish that runs).
+ */
+export function accountFinishProblem(account: string, rawBytes: number): string | null {
+ if (rawBytes > ACCOUNT_FINISH_MAX_BYTES) return "the model is over 300 MB, so it is kept as it is";
+ if (!diskHasRoom()) return "the server is short of room, so the model is kept as it is";
+ if (accountUsage(account).total >= accountTotalBytes(account)) return "the account's files are full, so the model is kept as it is";
+ if (!hit(`finish3d:${account}`, ACCOUNT_LIMITS.modelFinishesPerHour, 60 * 60_000).ok) return "this hour's finishes are used up, so the model is kept as it is";
+ return null;
+}
+
+/** Whether an account's files have room for a finished file of this size (its web GLB). */
+const accountHasRoomFor = (account: string, bytes: number) => accountUsage(account).total + bytes <= accountTotalBytes(account);
+
/** What an account's finished model says of its turntable: none on the server; the 3D page records one in the browser. */
export const ACCOUNT_TURNTABLE = "skipped: record it in your browser";
/** A job that came with an orbit clip of its splat keeps it as the turntable. */
@@ -205,8 +229,10 @@ export async function finishModel(
const raw = absolutePath(asset.relPath);
const finish: Record<string, unknown> = { version: MODEL_FINISH_VERSION };
const meta: Record<string, unknown> = { ...mesh.meta };
- if (o.account && asset.size > ACCOUNT_FINISH_MAX_BYTES) {
- finish.error = "web GLB: the model is over 300 MB, so it is kept as it is";
+ // An account's model is finished under its own limits (accountFinishProblem), or kept as it came.
+ const problem = o.account ? accountFinishProblem(o.account, asset.size) : null;
+ if (problem) {
+ finish.error = `web GLB: ${problem}`;
return outputs.map((x, j) => (j === i ? { ...mesh, meta: { ...meta, finish } } : x));
}
const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), "fuobe-3d-"));
@@ -224,6 +250,11 @@ export async function finishModel(
});
stats = run.code === 0 && fs.existsSync(webFile) ? lastJsonLine<FinishStats>(run.stdout) : null;
if (!stats) finish.error = `web GLB: ${tail(run.stderr) || `exit ${run.code}`}`;
+ // An account's web GLB is one of its files: stored only while the server and its files have room for it.
+ else if (o.account && (!diskHasRoom() || !accountHasRoomFor(o.account, fs.statSync(webFile).size))) {
+ stats = null;
+ finish.error = "web GLB: no room for it in the account's files, so the model is kept as it is";
+ }
} catch (e) {
if (signal.aborted) throw e;
finish.error = `web GLB: ${(e as Error).message}`;
diff --git a/tests/account-image-to-3d.test.ts b/tests/account-image-to-3d.test.ts
new file mode 100644
index 00000000..6a5c5c05
--- /dev/null
+++ b/tests/account-image-to-3d.test.ts
@@ -0,0 +1,334 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { NextRequest } from "next/server";
+import { startFakeComfy, TINY_GLB, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Image to 3D for a signed-in account (public sign-up): it runs on the account's own ComfyUI (a stand-in here) through
+ * POST /api/image-to-3d, with only its own files; its model is finished on this server under the account's limits, and
+ * its models and their files stay its own. A guest gets the sign-up card; another account and the owner's Library are
+ * never reached; on this install's GPUs (hosted runs) 3D stays refused.
+ */
+const dir = tempDir("fuobe-account-3d-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+delete process.env.FUOBE_HOSTED_RUNS;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+// Plain fetch is the install's own ComfyUI ("owner-comfy.test"): recorded, so a test sees that nothing reached it.
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = new URL(String(input instanceof Request ? input.url : input));
+ if (url.hostname === "127.0.0.1") return realFetch(input, init);
+ fetched.push(url.toString());
+ if (url.host !== "owner-comfy.test:8188") return new Response("not stubbed", { status: 599 });
+ if (url.pathname === "/system_stats") return Response.json({ system: { comfyui_version: "owner", ram_total: 1 }, devices: [] });
+ return Response.json({});
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const route = await import("@/app/api/image-to-3d/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const { proxy } = await import("@/proxy");
+const access = await import("@/lib/guest-access");
+const { createGenerations, getGeneration, listGenerations, asAccount } = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { saveFile } = await import("@/server/storage");
+const { runAsTenant } = await import("@/server/tenant");
+const { withRunStamp } = await import("@/server/run-stamp");
+const { ACCOUNT_LIMITS, accountTotalBytes, accountUsage } = await import("@/server/account-files");
+const { model3dAllowed } = await import("@/server/account-tool-run");
+const { ACCOUNT_TURNTABLE, accountFinishProblem, finishModel } = await import("@/server/model3d-finish");
+const { model3dRequest, rigRequest } = await import("@/lib/av/model3d");
+const { nanoid } = await import("nanoid");
+
+let fake: FakeComfy;
+let a = "";
+let b = "";
+let c = "";
+const cookies: Record<string, string> = {};
+beforeAll(async () => {
+ fake = await startFakeComfy({ loras: [], delayMs: 0, output: "model3d" });
+ globalThis.__fuobeTestGpuPort = fake.port;
+ auth.setPassword("install password");
+ for (const [k, email] of [
+ ["a", "[email protected]"],
+ ["b", "[email protected]"],
+ ["c", "[email protected]"],
+ ] as const) {
+ const id = auth.createAccount(email, "long enough").id;
+ cookies[k] = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ if (k === "a") a = id;
+ if (k === "b") b = id;
+ if (k === "c") c = id;
+ }
+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ // A and B link their own ComfyUI; C has neither a GPU nor a key.
+ for (const who of ["a", "b"]) expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: fake.url }, who))).status).toBe(200);
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestGpuPort = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ globalThis.__fuobeTestDiskFree = 1e13;
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') IS NOT NULL").run();
+});
+
+function json(url: string, method: string, body: unknown, who?: string): Request {
+ const text = JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, {
+ method,
+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(who && { cookie: cookies[who] }) },
+ body: text,
+ });
+}
+
+const viaProxy = (url: string, method = "GET", who?: string) =>
+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }), ...(method !== "GET" && { "content-type": "application/json" }) }, ...(method !== "GET" && { body: "{}" }) }));
+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+
+async function upload(who: string, data: Buffer, type: string, name: string): Promise<string> {
+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": type, "x-file-name": name, "content-length": String(data.length) }, body: new Uint8Array(data) }));
+ expect(r.status, await r.clone().text()).toBe(201);
+ return ((await r.json()) as { url: string }).url;
+}
+
+/** Tick the runner until the row is done (or the time is up). */
+async function settle(id: string, ms = 60_000) {
+ const end = Date.now() + ms;
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const g = getGeneration(id, { includeDeleted: true });
+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+const ownerOf = (assetId: string | undefined) => (db().prepare("SELECT account_id FROM assets WHERE id = ?").get(assetId) as { account_id: string | null } | undefined)?.account_id;
+const fromImage = (photo: string) => model3dRequest({ engine: "open", mode: "image", modelId: "oss-pixal3d", photo });
+const mine = (id: string) => listGenerations({ features: ["image-to-3d"], account: id });
+
+describe("the proxy opens Image to 3D's runs to accounts, and keeps the sign-up card for guests", () => {
+ it("a guest gets the sign-up card; an account with its own GPU reaches the route; one with neither a GPU nor a key is asked to connect one", async () => {
+ const g = viaProxy("/api/image-to-3d", "POST");
+ expect(g.status).toBe(401);
+ expect(g.headers.get(access.GUEST_HEADER)).toBe("1");
+ expect((await g.json()).error).toBe(access.GUEST_RUN_MESSAGE);
+ expect(passed(viaProxy("/api/image-to-3d", "POST", "a"))).toBe(true);
+ const r = viaProxy("/api/image-to-3d", "POST", "c");
+ expect(r.status).toBe(403);
+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ expect((await r.json()).code).toBe("connect-gpu");
+ expect(access.ownGpuRun("POST", "/api/image-to-3d")).toBe(true);
+ expect(access.ownGpuRun("GET", "/api/image-to-3d")).toBe(false);
+ expect(access.ownGpuRun("POST", "/api/image-to-3d/other")).toBe(false);
+ });
+
+ it("the route refuses a guest itself, and the owner's run goes through the studios' route", async () => {
+ const r = await route.POST(json("/api/image-to-3d", "POST", fromImage("/api/files/x.png")));
+ expect(r.status).toBe(401);
+ expect(r.headers.get(access.GUEST_HEADER)).toBe("1");
+ // The owner's request is POST /api/generations' own (its answer to a body it can't read).
+ const own = await route.POST(json("/api/image-to-3d", "POST", { nothing: true }, "owner"));
+ expect(own.status).toBe(400);
+ expect((await own.json()).error).toMatch(/feature/);
+ });
+});
+
+describe("an account makes a 3D model on its own ComfyUI", () => {
+ let photo = "";
+ let made = "";
+ beforeAll(async () => {
+ photo = await upload("a", TINY_PNG, "image/png", "lamp.png");
+ });
+
+ it("runs end to end: the model is made on its ComfyUI, finished here, and every file is its own", async () => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await route.POST(json("/api/image-to-3d", "POST", { ...fromImage(photo), requestId: "same-3d-request" }, "a"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const { items } = (await r.json()) as { items: { id: string }[] };
+ expect(items).toHaveLength(1);
+ made = items[0].id;
+ expect(getGeneration(made)!.request.account).toBe(a);
+ expect(getGeneration(made)!.provider).toBe("comfyui");
+ const done = await settle(made);
+ expect(done?.status, done?.error ?? "").toBe("succeeded");
+ // Made on its own ComfyUI; nothing reached the install's.
+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);
+ expect(fetched.filter((u) => !u.endsWith("/system_stats"))).toEqual([]);
+ // The raw GLB and the web GLB the finish made are its own files; no turntable on the server.
+ const model = done!.outputs.find((o) => o.kind === "model3d")!;
+ expect(model.contentType).toBe("model/gltf-binary");
+ expect(ownerOf(model.assetId)).toBe(a);
+ const finish = model.meta?.finish as { webAsset?: string; turntable?: string; error?: string };
+ expect(finish.error).toBeUndefined();
+ expect(finish.turntable).toBe(ACCOUNT_TURNTABLE);
+ expect(ownerOf(finish.webAsset)).toBe(a);
+ const web = model.meta?.web as string;
+ expect(web).toMatch(/^\/api\/files\//);
+ expect(web).not.toBe(model.url);
+ // It opens and downloads both (the proxy lets its own files through), and its list shows the model.
+ expect(passed(viaProxy(model.url, "GET", "a"))).toBe(true);
+ expect(passed(viaProxy(web, "GET", "a"))).toBe(true);
+ expect(passed(viaProxy(`/api/generations/${made}`, "GET", "a"))).toBe(true);
+ expect(mine(a).map((g) => g.id)).toContain(made);
+ }, 120_000);
+
+ it("a second click with the same request id gets the same run", async () => {
+ const r = await route.POST(json("/api/image-to-3d", "POST", { ...fromImage(photo), requestId: "same-3d-request" }, "a"));
+ expect(r.status).toBe(201);
+ expect(((await r.json()) as { items: { id: string }[] }).items[0].id).toBe(made);
+ });
+
+ it("another account never sees, opens, downloads or reuses its model", async () => {
+ const model = getGeneration(made)!.outputs.find((o) => o.kind === "model3d")!;
+ for (const url of [model.url, model.meta?.web as string, `/api/generations/${made}`]) {
+ expect(viaProxy(url, "GET", "b").status, url).toBe(403);
+ expect(viaProxy(url, "GET").status, url).toBe(401);
+ }
+ expect(viaProxy(`/api/generations/${made}`, "DELETE", "b").status).toBe(403);
+ expect(mine(b)).toEqual([]);
+ fake.log.length = 0;
+ // A's photo, or A's model to rig, in B's run: refused before anything is planned or sent.
+ for (const req of [fromImage(photo), rigRequest({ glb: model.url })]) {
+ const r = await route.POST(json("/api/image-to-3d", "POST", req, "b"));
+ expect(r.status, req.modelId).toBe(403);
+ expect((await r.json()).code).toBe("input-not-yours");
+ }
+ expect(fake.log.some((e) => e.path === "/prompt")).toBe(false);
+ // The same request id from B is B's own request, never A's run.
+ const own = await upload("b", TINY_PNG, "image/png", "b.png");
+ const r = await route.POST(json("/api/image-to-3d", "POST", { ...fromImage(own), requestId: "same-3d-request" }, "b"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const id = ((await r.json()) as { items: { id: string }[] }).items[0].id;
+ expect(id).not.toBe(made);
+ expect(getGeneration(id)!.request.account).toBe(b);
+ });
+
+ it("the owner's files and 3D models are never reachable", async () => {
+ const ownerPhoto = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "owner.png" }).url;
+ const ownerGlb = saveFile({ data: TINY_GLB, contentType: "model/gltf-binary", source: "generation", name: "owner.glb" }).url;
+ for (const req of [fromImage(ownerPhoto), rigRequest({ glb: ownerGlb })]) {
+ const r = await route.POST(json("/api/image-to-3d", "POST", req, "a"));
+ expect(r.status, req.modelId).toBe(403);
+ expect((await r.json()).code).toBe("input-not-yours");
+ }
+ const t = Date.now();
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES ('owner-3d', 'image-to-3d', 'oss-pixal3d', 'open', 'comfyui', 'image-to-3d', 'model3d', 'succeeded', ?, ?, ?, ?)",
+ )
+ .run(JSON.stringify({ feature: "image-to-3d", modelId: "oss-pixal3d" }), JSON.stringify([{ url: ownerGlb, kind: "model3d" }]), t, t);
+ expect(viaProxy("/api/generations/owner-3d", "GET", "a").status).toBe(403);
+ expect(viaProxy(ownerGlb, "GET", "a").status).toBe(403);
+ expect(mine(a).map((g) => g.id)).not.toContain("owner-3d");
+ // A link or a data: URI never goes in.
+ for (const url of ["https://example.com/a.png", "data:image/png;base64,AAAA"]) {
+ const r = await route.POST(json("/api/image-to-3d", "POST", fromImage(url), "a"));
+ expect(r.status, url).toBe(400);
+ }
+ });
+
+ it("takes 3D models only, and asks an account with neither a GPU nor a key to connect one before anything is made", async () => {
+ const r = await route.POST(json("/api/image-to-3d", "POST", { feature: "image", modelId: "oss-z-image-turbo", prompt: "a lamp" }, "a"));
+ expect(r.status).toBe(422);
+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "c.png" }).url);
+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const refused = await route.POST(json("/api/image-to-3d", "POST", fromImage(own), "c"));
+ expect(refused.status).toBe(403);
+ expect(refused.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ expect((await refused.json()).code).toBe("connect-gpu");
+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);
+ });
+
+ it("keeps the account's run limits: runs going at once, the hour, and what a request may weigh", async () => {
+ const now = Date.now();
+ const add = db().prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image-to-3d', 'oss-pixal3d', 'open', 'comfyui', 'image-to-3d', 'model3d', 'queued', ?, '[]', ?, ?)",
+ );
+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-3d-${i}`, JSON.stringify({ feature: "image-to-3d", modelId: "oss-pixal3d", account: a }), now, now);
+ const r = await route.POST(json("/api/image-to-3d", "POST", fromImage(photo), "a"));
+ expect(r.status).toBe(429);
+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);
+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-3d-%'").run();
+ const big = new Request("http://localhost:3000/api/image-to-3d", { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });
+ expect((await route.POST(big)).status).toBe(413);
+ });
+});
+
+describe("an account's 3D finish runs under its limits", () => {
+ /** A raw GLB of an account's run, as the runner stores it. */
+ const rawOf = (account: string) => {
+ const asset = runAsTenant({ kind: "account", id: account }, () => saveFile({ data: TINY_GLB, contentType: "model/gltf-binary", source: "generation", name: "raw.glb" }));
+ return [{ url: asset.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: asset.id }];
+ };
+ const finishOf = (o: { meta?: Record<string, unknown> }[]) => o[0].meta?.finish as { error?: string; webAsset?: string };
+
+ it("file size: a model over 300 MB is kept as it came", () => {
+ expect(accountFinishProblem(a, 300 * 2 ** 20 + 1)).toMatch(/over 300 MB/);
+ expect(accountFinishProblem(a, 1024)).toBeNull();
+ });
+
+ it("disk room: a server short of room keeps the model as it came, with no web GLB", async () => {
+ globalThis.__fuobeTestDiskFree = 0;
+ const out = await finishModel(`gen-${nanoid(6)}`, rawOf(a), { op: "image-to-3d", provider: "comfyui", account: a });
+ expect(finishOf(out).error).toMatch(/short of room/);
+ expect(finishOf(out).webAsset).toBeUndefined();
+ expect(out[0].meta?.web).toBeUndefined();
+ // The owner's model is finished as before.
+ const own = saveFile({ data: TINY_GLB, contentType: "model/gltf-binary", source: "generation", name: "own.glb" });
+ const mine = await finishModel(`gen-${nanoid(6)}`, [{ url: own.url, kind: "model3d", contentType: "model/gltf-binary", assetId: own.id }], { op: "image-to-3d", provider: "comfyui" });
+ expect(finishOf(mine).error).toBeUndefined();
+ }, 60_000);
+
+ it("its files' room: full files keep the model as it came, and a web GLB that wouldn't fit isn't stored", async () => {
+ const id = auth.createAccount(`threed-room-${nanoid(6)}@example.com`, "long enough").id;
+ const raw = rawOf(id);
+ const pad = db().prepare("INSERT INTO assets (id, kind, name, rel_path, content_type, size, source, generation_id, created_at, account_id) VALUES (?, 'other', 'pad', ?, 'application/octet-stream', ?, 'generation', NULL, ?, ?)");
+ // Just short of its room: the finish runs, but its web GLB has no room.
+ pad.run(`pad-${id}`, `outputs/pad-${id}.bin`, accountTotalBytes(id) - accountUsage(id).total - 8, Date.now(), id);
+ const tight = await finishModel(`gen-${nanoid(6)}`, raw, { op: "image-to-3d", provider: "comfyui", account: id });
+ expect(finishOf(tight).error).toMatch(/no room/);
+ expect(tight[0].meta?.web).toBeUndefined();
+ // Full: not even started.
+ db().prepare("UPDATE assets SET size = size + 8 WHERE id = ?").run(`pad-${id}`);
+ expect(accountFinishProblem(id, 1024)).toMatch(/files are full/);
+ db().prepare("DELETE FROM assets WHERE id = ?").run(`pad-${id}`);
+ }, 60_000);
+
+ it("an hour's finishes: past the limit the model is kept as it came", async () => {
+ for (let i = 0; i < ACCOUNT_LIMITS.modelFinishesPerHour; i++) expect(accountFinishProblem(b, 1024), String(i)).toBeNull();
+ expect(accountFinishProblem(b, 1024)).toMatch(/this hour/);
+ const out = await finishModel(`gen-${nanoid(6)}`, rawOf(b), { op: "image-to-3d", provider: "comfyui", account: b });
+ expect(finishOf(out).error).toMatch(/this hour/);
+ // Another account's hour is its own.
+ expect(accountFinishProblem(a, 1024)).toBeNull();
+ });
+});
+
+describe("3D is allowed on the account's own GPU or key, and refused on this install's GPUs", () => {
+ it("the tool runs' placement check", () => {
+ expect(model3dAllowed({ kind: "own" })).toBe(true);
+ expect(model3dAllowed({ kind: "pool" })).toBe(false);
+ });
+
+ it("a run stamped for this install's GPUs is refused when it is made; the account's own is made", () => {
+ const photo = runAsTenant({ kind: "account", id: a }, () => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "p.png" }).url);
+ const req = fromImage(photo);
+ expect(() => asAccount(a, () => withRunStamp({ place: "pool" }, () => createGenerations(req)))).toThrow(access.OWN_GPU_TOOL_MESSAGE);
+ const made = asAccount(a, () => createGenerations(req));
+ expect(made[0].kind).toBe("model3d");
+ expect(made[0].request.account).toBe(a);
+ });
+});
diff --git a/tests/any-angle-route.test.ts b/tests/any-angle-route.test.ts
index e48d1053..964e0896 100644
--- a/tests/any-angle-route.test.ts
+++ b/tests/any-angle-route.test.ts
@@ -4,7 +4,7 @@ import { tempDir } from "./helpers/temp-dir";
// Any Angle through POST /api/generations: a second build of the same photo answers with the first one (running or
// done) and gives the run back to the hourly count; one account never gets another's; an account may build the 3D view
-// on its own GPU (other 3D models wait for the server's finish).
+// on its own GPU (like any 3D model there; on this install's GPUs other 3D models are refused).
const dir = tempDir("fuobe-any-angle-route-");
process.env.FUOBE_DATA_DIR = dir;
@@ -16,7 +16,8 @@ globalThis.__fuobeTestDiskFree = 1e13;
const auth = await import("@/server/auth");
const generationsRoute = await import("@/app/api/generations/route");
const { saveFile } = await import("@/server/storage");
-const { createGenerations } = await import("@/server/generations");
+const { asAccount, createGenerations } = await import("@/server/generations");
+const { withRunStamp } = await import("@/server/run-stamp");
const { viewKeyOf } = await import("@/server/any-angle");
const { ANY_ANGLE } = await import("@/lib/catalog/any-angle");
const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");
@@ -82,7 +83,7 @@ describe("Any Angle's 3D view through the route", () => {
expect(body.items?.map((g) => g.id) ?? []).not.toContain("view-a");
});
- it("lets an account build the 3D view on its own GPU (other 3D models wait for the server's finish)", async () => {
+ it("lets an account build the 3D view on its own GPU (other 3D models aren't made on this install's GPUs)", async () => {
const photo = await upload(a, "build.png");
let refused: unknown = null;
try {
@@ -92,7 +93,7 @@ describe("Any Angle's 3D view through the route", () => {
}
// Whatever else stops it here (no GPU connected in this test), it isn't the 3D finish that keeps accounts out.
expect((refused as Error | null)?.message ?? "").not.toBe(OWN_GPU_TOOL_MESSAGE);
- expect(() => createGenerations({ feature: "image-to-3d", modelId: "oss-triposplat", op: "splat", engine: "open", inputs: { images: [photo] }, account: a } as never)).toThrow(OWN_GPU_TOOL_MESSAGE);
+ expect(() => asAccount(a, () => withRunStamp({ place: "pool" }, () => createGenerations({ feature: "image-to-3d", modelId: "oss-triposplat", op: "splat", engine: "open", inputs: { images: [photo] } } as never)))).toThrow(OWN_GPU_TOOL_MESSAGE);
});
});
diff --git a/tests/e2e/image-to-3d-accounts-live.mjs b/tests/e2e/image-to-3d-accounts-live.mjs
new file mode 100644
index 00000000..e5b8f589
--- /dev/null
+++ b/tests/e2e/image-to-3d-accounts-live.mjs
@@ -0,0 +1,78 @@
+// Image to 3D for visitors, in a browser (a studio with a password and public sign-up, fuobe.com by default): a guest and
+// a signed-in account see no "isn't available here" note, the photo drop and Make it 3D are on, a guest's run opens the
+// sign-up card, and the run of an account with neither a GPU nor a key opens "Connect your GPU". The account is a
+// throwaway one this script makes and deletes. No model is made (that needs the account's own GPU or key).
+// Usage: node tests/e2e/image-to-3d-accounts-live.mjs [appUrl] [--shots <dir>] Exits 1 on a failed check.
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { launch } from "./_browser.mjs";
+
+const argv = process.argv.slice(2);
+const flag = (k) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : undefined);
+const app = (argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--shots") ?? "https://fuobe.com").replace(/\/$/, "");
+const shots = flag("--shots");
+if (shots) fs.mkdirSync(shots, { recursive: true });
+
+const failures = [];
+const check = (label, ok, extra = "") => {
+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(72)}${extra ? ` ${extra}` : ""}`);
+ if (!ok) failures.push(label);
+};
+
+const browser = await launch();
+const email = `threed-ui-${crypto.randomBytes(5).toString("hex")}@example.com`;
+const password = crypto.randomBytes(18).toString("base64url");
+let signedUp = false;
+const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
+try {
+ const page = await context.newPage();
+ const make = page.getByRole("button", { name: /Make it 3D/ });
+ const look = async (who) => {
+ await page.goto(`${app}/image-to-3d`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(3000);
+ check(`${who}: no "isn't available here" note`, (await page.getByText(/isn't available here/).count()) === 0);
+ check(`${who}: the price never says "Not available here"`, (await page.getByText("Not available here").count()) === 0);
+ const disabled = await page.locator("input[type=file]").first().isDisabled().catch(() => true);
+ check(`${who}: the photo drop is on`, !disabled);
+ check(`${who}: Make it 3D is on`, await make.isEnabled());
+ if (shots) await page.screenshot({ path: path.join(shots, `image-to-3d-${who}.png`), fullPage: false });
+ };
+ /** From text: words, then Make it 3D; the card the run opens. */
+ const runFromText = async (who, card, name) => {
+ await page.goto(`${app}/image-to-3d?mode=text`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(2500);
+ await page.locator("#m3d-text").fill("A brass ship's lantern with a glass globe");
+ await page.waitForTimeout(800);
+ await make.click();
+ await page.waitForTimeout(3000);
+ check(`${who}: Make it 3D opens the ${name} card`, (await page.getByText(card).count()) > 0);
+ if (shots) await page.screenshot({ path: path.join(shots, `image-to-3d-${who}-run.png`) });
+ };
+
+ await look("guest");
+ // A guest's upload: the sign-up card, nothing uploaded.
+ const input = page.locator("input[type=file]").first();
+ if (await input.count()) {
+ await input.setInputFiles({ name: "lamp.png", mimeType: "image/png", buffer: Buffer.from("89504e470d0a1a0a0000000d494844520000000200000002080600000072b60d240000001149444154789c63381150f11f8419600c005a940a3db632c1b20000000049454e44ae426082", "hex") });
+ await page.waitForTimeout(2500);
+ check("guest: adding a photo opens the sign-up card", (await page.getByText(/Create a free account/).count()) > 0);
+ }
+ await runFromText("guest", /Create a free account/, "sign-up");
+
+ // A throwaway account (signed in in this browser), then the same page.
+ const res = await page.request.post(`${app}/api/auth/signup`, { data: { email, password }, headers: { origin: app } });
+ signedUp = res.ok();
+ check("signed up a throwaway account", signedUp, String(res.status()));
+ await look("account");
+ await runFromText("account", /Connect your GPU/, "Connect your GPU");
+} finally {
+ if (signedUp) {
+ const page = context.pages()[0];
+ const del = await page.request.delete(`${app}/api/auth/me`, { data: { password }, headers: { origin: app } });
+ console.log(`deleted the throwaway account: ${del.status()}`);
+ }
+ await browser.close();
+}
+console.log(failures.length ? `${failures.length} failed` : "all ok");
+process.exit(failures.length ? 1 : 0);
diff --git a/tests/glb-finish-safety.test.ts b/tests/glb-finish-safety.test.ts
index 2b5f309c..d4c2fe8d 100644
--- a/tests/glb-finish-safety.test.ts
+++ b/tests/glb-finish-safety.test.ts
@@ -9,7 +9,9 @@ process.env.FUOBE_DATA_DIR = path.join(dir, "data");
process.env.FUOBE_TEST_SECRET = "do-not-pass-this-on";
const { ACCOUNT_TURNTABLE, finishModel, pendingTurntable, scriptEnv } = await import("@/server/model3d-finish");
const { saveFile } = await import("@/server/storage");
-const { createGenerations } = await import("@/server/generations");
+const { asAccount, createGenerations } = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { withRunStamp } = await import("@/server/run-stamp");
const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");
afterAll(() => {
delete process.env.FUOBE_TEST_SECRET;
@@ -125,8 +127,31 @@ describe("the 3D finish reads only the model it was given", () => {
}, 60_000);
});
-describe("accounts don't run 3D models yet", () => {
- it("refuses an account's Image to 3D run before anything is queued", () => {
- expect(() => createGenerations({ feature: "image-to-3d", modelId: "oss-pixal3d", op: "image-to-3d", prompt: "", inputs: { images: ["data:image/png;base64,AA=="] }, account: "acct-1", engine: "open" })).toThrow(OWN_GPU_TOOL_MESSAGE);
+describe("an account's 3D model runs on its own GPU or key, never on this install's GPUs", () => {
+ const photo = () => saveFile({ data: Buffer.from("89504e470d0a1a0a", "hex"), contentType: "image/png", source: "upload", accountId: "acct-1" }).url;
+ const request = (extra: Record<string, unknown> = {}) =>
+ ({ feature: "image-to-3d", modelId: "oss-pixal3d", op: "image-to-3d", prompt: "", inputs: { images: [photo()] }, engine: "open", ...extra }) as Parameters<typeof createGenerations>[0];
+
+ it("makes an account's Image to 3D run on its own placement", () => {
+ const made = asAccount("acct-1", () => createGenerations(request()));
+ expect(made).toHaveLength(1);
+ expect(made[0].kind).toBe("model3d");
+ expect(made[0].request.account).toBe("acct-1");
+ expect(made[0].request.place).toBeUndefined();
+ });
+
+ it("refuses the same run on this install's GPUs (the pool's stamp) before anything is queued", () => {
+ const rows = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const before = rows();
+ expect(() => asAccount("acct-1", () => withRunStamp({ place: "pool" }, () => createGenerations(request())))).toThrow(OWN_GPU_TOOL_MESSAGE);
+ expect(rows()).toBe(before);
+ });
+
+ it("a place sent in the request changes nothing: it is stripped, and only the stamp counts", () => {
+ for (const place of ["pool", "own"]) {
+ const made = asAccount("acct-1", () => createGenerations(request({ place })));
+ expect(made[0].request.place, place).toBeUndefined();
+ }
+ expect(() => asAccount("acct-1", () => withRunStamp({ place: "pool" }, () => createGenerations(request({ place: "own" }))))).toThrow(OWN_GPU_TOOL_MESSAGE);
});
});
diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.ts
index e5b276ac..8221cc71 100644
--- a/tests/helpers/fake-comfy-runner.ts
+++ b/tests/helpers/fake-comfy-runner.ts
@@ -7,7 +7,8 @@
*
* Options for tests: `loras` (GET /models/loras), `delayMs` (until the history says done), `drip` (the history
* answers one byte every 2 s, never finishing), `huge` (/view streams without end), `promptId` (the job id /prompt
- * answers), `missing` (a file /prompt answers "not in list" for), `output` ("video" or "image"), `layers` (the
+ * answers), `missing` (a file /prompt answers "not in list" for), `output` ("video", "image" or "model3d": a one-triangle
+ * GLB), `layers` (the
* history lists that many Qwen-Image-Layered layers, node 60), `frames` (an EXR export: a preview clip, node 5, and
* that many frames, node 3), `historyError` (/history answers HTTP 500 and then sends nothing), `uploadStatus` (the HTTP
* status /upload/image answers, e.g. 500 to fail every upload), `refuseClass` (/prompt answers "not in list" for a graph with
@@ -25,7 +26,7 @@ export interface FakeComfyOptions {
huge?: boolean;
promptId?: string;
missing?: string;
- output?: "video" | "image";
+ output?: "video" | "image" | "model3d";
layers?: number;
frames?: number;
historyError?: boolean;
@@ -59,6 +60,35 @@ export const TINY_PNG = Buffer.from(
"hex",
);
+/** A one-triangle binary glTF 2 (a GLB the server's 3D finish can read). */
+export const TINY_GLB: Buffer = (() => {
+ const bin = Buffer.alloc(36);
+ [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => bin.writeFloatLE(v, i * 4));
+ const doc = {
+ asset: { version: "2.0" },
+ buffers: [{ byteLength: 36 }],
+ bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }],
+ accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: "VEC3", min: [0, 0, 0], max: [1, 1, 0] }],
+ meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }],
+ nodes: [{ mesh: 0 }],
+ scenes: [{ nodes: [0] }],
+ scene: 0,
+ };
+ let j = Buffer.from(JSON.stringify(doc));
+ j = Buffer.concat([j, Buffer.alloc((4 - (j.length % 4)) % 4, 0x20)]);
+ const header = Buffer.alloc(12);
+ header.writeUInt32LE(0x46546c67, 0);
+ header.writeUInt32LE(2, 4);
+ header.writeUInt32LE(12 + 8 + j.length + 8 + bin.length, 8);
+ const jh = Buffer.alloc(8);
+ jh.writeUInt32LE(j.length, 0);
+ jh.writeUInt32LE(0x4e4f534a, 4);
+ const bh = Buffer.alloc(8);
+ bh.writeUInt32LE(bin.length, 0);
+ bh.writeUInt32LE(0x004e4942, 4);
+ return Buffer.concat([header, jh, j, bh, bin]);
+})();
+
/** The start of an MP4 (an ftyp box), enough for the studio to store it as one. */
export const TINY_MP4 = Buffer.concat([Buffer.from("000000186674797069736f6d0000020069736f6d69736f32", "hex"), Buffer.alloc(64)]);
@@ -147,6 +177,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
const list = (n: number, ext: string) => Array.from({ length: n }, (_, i) => ({ filename: `fake_${String(i + 1).padStart(5, "0")}_.${ext}`, subfolder: "", type: "output" }));
if (opts.layers) return json(200, { [id]: { ...done, outputs: { "60": { images: list(opts.layers, "png") } } } });
if (opts.frames) return json(200, { [id]: { ...done, outputs: { "5": { gifs: list(1, "mp4") }, "3": { images: list(opts.frames, "exr") } } } });
+ if (opts.output === "model3d") return json(200, { [id]: { ...done, outputs: { "900": { "3d": [{ filename: "fake_00001_.glb", subfolder: "3D", type: "output" }] } } } });
const file = opts.output === "image" ? { filename: "fake_00001_.png", subfolder: "", type: "output" } : { filename: "fake_00001.mp4", subfolder: "", type: "output" };
const key = opts.output === "image" ? "images" : "gifs";
return json(200, { [id]: { status: { completed: true, status_str: "success" }, outputs: { "900": { [key]: [file] } } } });
@@ -176,6 +207,10 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
res.writeHead(200, { "content-type": "image/x-exr" });
return res.end(Buffer.from("762f3101", "hex"));
}
+ if (name.endsWith(".glb")) {
+ res.writeHead(200, { "content-type": "application/octet-stream" });
+ return res.end(TINY_GLB);
+ }
const png = name.endsWith(".png");
if (png && opts.echo && lastUpload) {
const jpeg = lastUpload[0] === 0xff && lastUpload[1] === 0xd8;
diff --git a/tests/hi3d-refine.test.ts b/tests/hi3d-refine.test.ts
index c5987b16..40801013 100644
--- a/tests/hi3d-refine.test.ts
+++ b/tests/hi3d-refine.test.ts
@@ -24,6 +24,7 @@ const { inferOperation, planGeneration } = await import("@/lib/catalog/plan");
const { OPERATION_OUTPUT } = await import("@/lib/catalog/types");
const { buildLicenceList, licenceInfo, licenceTerms, NODE_PACKS } = await import("@/lib/licences");
const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");
+const { withRunStamp } = await import("@/server/run-stamp");
const hi3d = await import("@/lib/av/hi3d");
const m3d = await import("@/lib/av/model3d");
const print = await import("@/lib/print3d");
@@ -183,9 +184,10 @@ describe("the chain per engine", () => {
}
});
- it("accounts: refused like every 3D model, before anything is queued", () => {
- expect(() => gens.createGenerations({ ...hi3d.refineRequest({ glb: "/api/files/placeholder.glb", photo }), account: "acct-1" })).toThrow(OWN_GPU_TOOL_MESSAGE);
- expect(() => gens.createGenerations({ ...hi3d.withRefine(m3d.model3dRequest({ engine: "open", mode: "image", photo }), "open", 1024), account: "acct-1" })).toThrow(OWN_GPU_TOOL_MESSAGE);
+ it("accounts: on this install's GPUs refused like every 3D model, before anything is queued", () => {
+ const onPool = <T,>(fn: () => T) => gens.asAccount("acct-1", () => withRunStamp({ place: "pool" }, fn));
+ expect(() => onPool(() => gens.createGenerations(hi3d.refineRequest({ glb: "/api/files/placeholder.glb", photo })))).toThrow(OWN_GPU_TOOL_MESSAGE);
+ expect(() => onPool(() => gens.createGenerations(hi3d.withRefine(m3d.model3dRequest({ engine: "open", mode: "image", photo }), "open", 1024)))).toThrow(OWN_GPU_TOOL_MESSAGE);
});
it("is free on the open engine, and the refined GLB gets the server's finish", () => {
diff --git a/tests/nav-nudges.test.ts b/tests/nav-nudges.test.ts
index af2fd54c..4f1c76c7 100644
--- a/tests/nav-nudges.test.ts
+++ b/tests/nav-nudges.test.ts
@@ -113,14 +113,15 @@ describe("Keep going with this: under a finished result", () => {
expect(out.length).toBeGreaterThanOrEqual(Math.min(3, all.length - 1));
});
- it("sends only the owner to the studios that run on a self-hosted Fuobe (Character Sheet, Image to 3D)", () => {
+ it("sends only the owner to Character Sheet (it runs on a self-hosted Fuobe); Image to 3D is everyone's", () => {
viewer.visitor = false;
expect(hrefs(steps(person())).some((h) => h.startsWith("/character-sheet?image="))).toBe(true);
expect(hrefs(steps(product())).some((h) => h.startsWith("/image-to-3d?image="))).toBe(true);
viewer.visitor = true;
for (const g of [person(), product(), gen([{ kind: "image" }])]) {
- for (const h of hrefs(steps(g))) expect(h).not.toMatch(/^\/(character-sheet|image-to-3d)\b/);
+ for (const h of hrefs(steps(g))) expect(h).not.toMatch(/^\/character-sheet\b/);
}
+ expect(hrefs(steps(product())).some((h) => h.startsWith("/image-to-3d?image="))).toBe(true);
});
it("goes on from clips, sounds and 3D models too", () => {
diff --git a/tests/nav-subfeatures.test.ts b/tests/nav-subfeatures.test.ts
index 8f8bd1dd..b0c68e14 100644
--- a/tests/nav-subfeatures.test.ts
+++ b/tests/nav-subfeatures.test.ts
@@ -153,8 +153,10 @@ describe("who sees a studio's features", () => {
}
}
expect(studioSubs("audio", "owner", "sheet").map((e) => e.id)).toContain("audio-split");
- expect(studioSubs("image-to-3d", "owner", "menu").length).toBe(3);
- expect(studioSubs("image-to-3d", "guest", "menu")).toEqual([]);
+ // Image to 3D runs for accounts too (on their own GPU or key): its modes are linked for everyone.
+ for (const kind of [...VISITORS, "owner" as const]) expect(studioSubs("image-to-3d", kind, "menu").length, String(kind)).toBe(3);
+ expect(studioSubs("character-sheet", "owner", "sheet").length).toBe(3);
+ expect(studioSubs("character-sheet", "guest", "sheet")).toEqual([]);
// Search still finds them, as before.
expect(entriesFor("guest").some((e) => e.id === "audio-split")).toBe(true);
});
diff --git a/tests/phone-nav.test.ts b/tests/phone-nav.test.ts
index 3de9e95b..4fc88ffc 100644
--- a/tests/phone-nav.test.ts
+++ b/tests/phone-nav.test.ts
@@ -252,11 +252,12 @@ describe("the Studios sheet", () => {
const people = at("/", () => sheet({ group: "people" }));
expect(pills(people)).toEqual(["Motion transfer", "Character swap", "Object swap", "Restyle", "Insert", "Finish"]);
// Pages that say "isn't available here" to a visitor, and the owner's own modes, aren't linked for them.
- for (const w of ["From a selfie", "From Reference", "From picture", "Split soundtrack", "Remove dialogue", "From an image", "Blockout"]) {
+ for (const w of ["From a selfie", "From Reference", "From picture", "Split soundtrack", "Remove dialogue", "Blockout"]) {
for (const g of LAUNCHER_GROUPS) expect(pills(at("/", () => sheet({ group: g.id }))), `${g.id}: ${w}`).not.toContain(w);
}
+ // Image to 3D runs for visitors with an account (on their own GPU or key): its modes are linked too.
const finish = at("/", () => sheet({ group: "finish" }));
- expect(pills(finish)).toEqual(["Image", "Video", "FPS Boost", "SDR to HDR", "Export"]);
+ expect(pills(finish)).toEqual(["Image", "Video", "FPS Boost", "SDR to HDR", "Export", "From an image", "From several images", "From text", "Pick an object", "Splat"]);
// Each pill links its feature (a route, or its studio with ?mode= / ?tab=).
expect(hrefs(sell)).toEqual(expect.arrayContaining(["/marketing/click-to-ad", "/ads", "/ads/multiplier"]));
expect(hrefs(people)).toEqual(expect.arrayContaining(["/genjutsu?mode=motion", "/genjutsu?mode=insert"]));