The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Image to 3D: Refine detail, the TRELLIS.2 final and Make the other sides show to everyone
Adarsh1e91287b4992
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 3d6ef237..e19a99ea 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -330,8 +330,12 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188finished on this server (the web GLB the viewer loads) under its limits (`src/server/model3d-finish.ts`): one account'sfinish at a time across the server, at low priority; a model over 300 MB, a server or account short of room, or morethan 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. Film it photoreal runs as a Fly around (below). Refine detail, the TRELLIS.2 final and Idol 3D's other sides stay- the owner's, and Retexture opens once its cloud models pass a live call. On this install's+ the browser ("Record turntable"), not on the server. Film it photoreal runs as a Fly around (below). Refine detail (Hi3D), the TRELLIS.2 final,+ Idol 3D's other sides ("Make the other sides from the front") and Trim spikes show to everyone and run on the+ account's own GPU through the same route; each is labelled with what it runs on ("Runs on your own GPU · 24 GB")+ until its graph is validated on this studio's GPU (`graphs` in `src/lib/own-setup.ts`, read by the page with+ `ownSetupsNow`, `src/server/own-setup-live.ts`), when the label leaves by itself. Retexture opens once its cloud+ models pass a live call. On this install'sGPUs (hosted runs) 3D isn't offered yet. A guest gets the sign-up card.- **Character Swap Studio.** An account keeps Character Swap projects of its own (`/character-swap`; `GET`/`POST/api/swap-studio/projects`, `GET`/`PATCH`/`DELETE /api/swap-studio/projects/<id>`): its own only (another account's,diff --git a/src/app/(studio)/image-to-3d/page.tsx b/src/app/(studio)/image-to-3d/page.tsxindex aa23175a..8ffa0f8b 100644--- a/src/app/(studio)/image-to-3d/page.tsx+++ b/src/app/(studio)/image-to-3d/page.tsx@@ -1,14 +1,21 @@import type { Metadata } from "next";import { Model3dStudio, type Model3dInfo } from "@/components/model3d/model3d-studio";-import { ALL_MODELS_3D, RIG_MODEL } from "@/lib/av/model3d";+import { ALL_MODELS_3D, MODEL3D_SETUPS, RIG_MODEL } from "@/lib/av/model3d";import { HI3D_MODEL } from "@/lib/av/hi3d";import { getModel } from "@/lib/catalog";import { exampleRow } from "@/lib/examples/catalog";+import { ownSetupsNow } from "@/server/own-setup-live";export const metadata: Metadata = { title: "Image to 3D" };-/** The page passes the 3D models' names, so the client doesn't load the catalog. */+/**+ * The page passes the 3D models' names, so the client doesn't load the catalog, and what each extra step needs from a+ * visitor (its own GPU) until its graphs are validated on this studio's GPU.+ */export default function Page() {const info: Record<string, Model3dInfo> = Object.fromEntries([...ALL_MODELS_3D.map((m) => m.id), RIG_MODEL, HI3D_MODEL].map((id) => [id, { name: getModel(id)?.name ?? id }]));- return <Model3dStudio info={info} examples={exampleRow("tool:image-to-3d")} />;+ const keys = Object.keys(MODEL3D_SETUPS) as (keyof typeof MODEL3D_SETUPS)[];+ const now = ownSetupsNow(keys.map((k) => MODEL3D_SETUPS[k]));+ const setups = Object.fromEntries(keys.map((k) => [k, now[MODEL3D_SETUPS[k]]]));+ return <Model3dStudio info={info} setups={setups} examples={exampleRow("tool:image-to-3d")} />;}diff --git a/src/components/model3d/model-card.tsx b/src/components/model3d/model-card.tsxindex b7f1fcd1..7812d217 100644--- a/src/components/model3d/model-card.tsx+++ b/src/components/model3d/model-card.tsx@@ -26,6 +26,8 @@ import { recordableType, recordTurntable } from "./turntable";import { hasWebgl2, SplatViewer, useReducedMotion } from "./splat-viewer";import { FALLBACK_TEXT, hazeCutoffFor } from "@/lib/av/splat-view";import { TurnChips } from "./turn-chips";+import { OwnSetupChip, useOwnSetupPress } from "@/components/own-setup";+import { useModel3dSetup } from "./own-setups";/*** Left out of the card's next steps: its own Animate the spin button is that step (and knows a turntable recorded@@ -93,6 +95,10 @@ export function ModelCard({const focusViewer = useRef(false);const hydrated = useHydrated();const owner = useIsOwner();+ // A visitor's refine and final run on its own GPU: their labels until their graphs are validated on this studio's GPU.+ const refineSetup = useModel3dSetup("refine");+ const finalSetup = useModel3dSetup("final");+ const press = useOwnSetupPress();const canRecord = hydrated && !!recordableType();// A splat opens in the splat viewer where the browser draws WebGL2 and the file isn't too big for it (it says so).const [splatNote, setSplatNote] = useState<string | null>(null);@@ -466,8 +472,9 @@ export function ModelCard({</Button>)}{refinable && (- <Button variant="outline" size="sm" className="rounded-full" onClick={() => setRefining(true)}>+ <Button variant="outline" size="sm" className="rounded-full" onClick={() => press(refineSetup, () => setRefining(true))}><Wand2 className="size-3.5" /> Refine this mesh+ <OwnSetupChip setup={refineSetup} /></Button>)}{view.glb && !view.splat && g.op !== "splat" && !view.rigged && (@@ -514,6 +521,7 @@ export function ModelCard({<Button asChild variant="outline" size="sm" className="rounded-full"><Link href={final} prefetch={false} onClick={() => view.photo && onFinal?.(view.photo)}><Box className="size-3.5" /> {FINAL_3D.label}+ <OwnSetupChip setup={finalSetup} /></Link></Button><p className="text-[12px] text-muted-foreground">{FINAL_3D.note}</p>diff --git a/src/components/model3d/model3d-studio.tsx b/src/components/model3d/model3d-studio.tsxindex 1f9df461..ce489068 100644--- a/src/components/model3d/model3d-studio.tsx+++ b/src/components/model3d/model3d-studio.tsx@@ -18,7 +18,7 @@ import { MediaDrop } from "@/components/av/media-drop";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { HandoffImage } from "@/components/nav/next-steps";import { ExampleRow } from "@/components/studio/example-row";-import { useEngine, useGenerations, useHydrated, useIsOwner, useLikelyVisitor, useModelAccess, useStatus } from "@/lib/api";+import { useEngine, useGenerations, useHydrated, useIsOwner, useModelAccess, useStatus } from "@/lib/api";import {FINAL_3D,IDOL_QUALITIES,@@ -51,7 +51,8 @@ import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types"import { keepOffered, offered } from "@/lib/model-access";import type { ExampleRowData } from "@/lib/examples/types";import { cn } from "@/lib/utils";-import { OwnSetupChip } from "@/components/own-setup";+import { OwnSetupChip, useOwnSetupPress } from "@/components/own-setup";+import { Model3dSetupsProvider, useModel3dSetup, type Model3dSetups } from "./own-setups";import { toastError } from "@/lib/refusals";import { priceLine, useCreate3d, useRunPreview } from "./hooks";import { ModelCard } from "./model-card";@@ -124,6 +125,8 @@ function IdolSettings({}) {// Only the owner reads what trimming needs on the ComfyUI (it's theirs to set up).const owner = useIsOwner();+ // A visitor's trim runs on its own GPU: what that needs, until the trim's graph is validated here.+ const cleanSetup = useModel3dSetup("clean");const refs = useRef<(HTMLButtonElement | null)[]>([]);const move = (from: number, by: number) => {const i = (from + by + IDOL_QUALITIES.length) % IDOL_QUALITIES.length;@@ -179,7 +182,7 @@ function IdolSettings({Trim spikes</Label>{/* A visitor's run is on its own GPU: what that needs (the owner reads the line below instead). */}- {!owner && <OwnSetupChip setup="image-to-3d:idol-clean" className="ml-1.5 align-[1px]" />}+ <OwnSetupChip setup={cleanSetup} className="ml-1.5 align-[1px]" /><p id="m3d-idol-trim-hint" className="mt-0.5 text-[12px] text-muted-foreground">Drops the thin, needle-like bits around the edges of the 3D file.</p>@@ -242,12 +245,23 @@ function ModePicker({ mode, onChange }: { mode: Model3dMode; onChange: (m: Model* Image to 3D: a photo, several photos, words, an object in a photo or a splat → a model to spin, download, rig and animate.* examples: "See what it makes" (studioExamples("image-to-3d"), from the page), where the models go until there is one.*/-export function Model3dStudio({ info, examples }: { info: Record<string, Model3dInfo>; examples?: ExampleRowData | null }) {+export function Model3dStudio({ setups = {}, ...props }: { info: Record<string, Model3dInfo>; setups?: Model3dSetups; examples?: ExampleRowData | null }) {+ return (+ <Model3dSetupsProvider value={setups}>+ <Model3dStudioBody {...props} />+ </Model3dSetupsProvider>+ );+}++function Model3dStudioBody({ info, examples }: { info: Record<string, Model3dInfo>; examples?: ExampleRowData | null }) {const [engine, setEngine, engineMode] = useEngine();// 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();+ // uploads or runs. The extras (Refine detail, the TRELLIS.2 final, Idol 3D's other sides) show to everyone, marked+ // with what they run on until their graphs are validated on this studio's GPU (MODEL3D_SETUPS).const owner = useIsOwner();+ const refineSetup = useModel3dSetup("refine");+ const cleanSetup = useModel3dSetup("clean");+ const press = useOwnSetupPress();const access = useModelAccess();const create = useCreate3d();const results = useGenerations({ features: [MODEL3D_FEATURE, "app:app-image-to-3d", "app:app-photo-to-3d", MODEL3D_FILM_FEATURE], limit: 24 });@@ -353,13 +367,20 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3dconst preview = useRunPreview(engineKnown ? priced : null);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");+ // Hi3D runs on your GPU only: offered while the install runs open models and the model is switched on (a visitor's+ // runs on its own GPU, its label beside the switch).+ const refineAllowed = engineMode !== "cloud" && offered(access, HI3D_MODEL, "open");// "Build the final with TRELLIS.2" on an Idol 3D result: while TRELLIS.2 runs here and is switched on.- const finalAllowed = !visitor && engineMode !== "cloud" && offered(access, FINAL_3D.model, "open");+ const finalAllowed = engineMode !== "cloud" && offered(access, FINAL_3D.model, "open");const refining = refineAllowed && engine === "open" && (mode === "image" || mode === "multi") && refine !== null ? refine : null;+ // A run with a step on the visitor's own GPU: a guest gets the sign-up card, an account without a GPU "Connect your GPU".+ const needs = refining !== null ? refineSetup : idolSplat && engine === "open" && idolTrim ? cleanSetup : null;const go = () => {if (blocker) return void toast(blocker, { id: "3d-blocker" });+ if (needs) return void press(needs, start);+ start();+ };+ const start = () => {create.mutate(withRefine(model3dRequest(input), engine, refining), {onSuccess: () =>toast.success(diff --git a/src/components/model3d/other-sides.tsx b/src/components/model3d/other-sides.tsxindex 74cbc96e..0e7cd5e6 100644--- a/src/components/model3d/other-sides.tsx+++ b/src/components/model3d/other-sides.tsx@@ -3,25 +3,26 @@import { Loader2, Rotate3d } from "lucide-react";import { useEffect, useRef, useState } from "react";import { Button } from "@/components/ui/button";-import { useCreateGeneration, useEngine, useGenerations, useIsVisitor, useModelAccess } from "@/lib/api";+import { OwnSetupChip, useOwnSetupPress } from "@/components/own-setup";+import { useEngine, useGenerations, useModelAccess } from "@/lib/api";import { IDOL_MODELS } from "@/lib/av/model3d";import { forgetViewRun, IDOL_VIEWS_FEATURE, IDOL_VIEWS_NOTE, idolViewsOf, idolViewsRequest, rememberViewRun, viewRunFor } from "@/lib/av/idol-views";import type { ViewSide } from "@/lib/av/model3d";import { offered } from "@/lib/model-access";import { toastError } from "@/lib/refusals";import { cn } from "@/lib/utils";-import { priceLine, useRunPreview } from "./hooks";+import { priceLine, useCreate3d, useRunPreview } from "./hooks";+import { useModel3dSetup } from "./own-setups";/*** Whether "Make the other sides" is offered here: Idol 3D's views run on your GPU only (Idol's cloud endpoint returns a- * splat, not views), so not on an install that runs paid APIs only, not with Idol 3D switched off in Settings → Models &- * licences, and not for a guest or an account (3D models are the owner's for now).+ * splat, not views), so not on an install that runs paid APIs only, and not with Idol 3D switched off in Settings →+ * Models & licences. A guest or an account sees it too: its run goes to its own GPU (OtherSides marks what it needs).*/export function useOtherSidesOffered(): boolean {const [, , engineMode] = useEngine();const access = useModelAccess();- const visitor = useIsVisitor();- return !visitor && engineMode !== "cloud" && offered(access, IDOL_MODELS.open, "open");+ return engineMode !== "cloud" && offered(access, IDOL_MODELS.open, "open");}/**@@ -46,7 +47,11 @@ export function OtherSides({onBusy?: (busy: boolean) => void;className?: string;}) {- const create = useCreateGeneration();+ // The owner's as a studio run; an account's on its own GPU (POST /api/image-to-3d). A guest gets the sign-up card and+ // an account without a GPU "Connect your GPU" first; the label shows until the views' graph is validated here.+ const create = useCreate3d();+ const setup = useModel3dSetup("sides");+ const press = useOwnSetupPress();// The run for this picture lives for the tab (viewRunFor), so it's picked up again if the button comes back mid-run,// and a different front never gets another picture's views.const [, setTick] = useState(0);@@ -72,7 +77,8 @@ export function OtherSides({const working = create.isPending || (!!runId && !failed);useEffect(() => onBusy?.(working), [onBusy, working]);useEffect(() => () => onBusy?.(false), [onBusy]);- const start = () =>+ const start = () => void press(setup, make);+ const make = () =>create.mutate(idolViewsRequest(photo, { asPhoto }), {onSuccess: (items) => {if (items[0]?.id) rememberViewRun(photo, items[0].id);@@ -82,10 +88,13 @@ export function OtherSides({});return (<div className={cn("space-y-1.5", className)} data-testid="other-sides">- <Button type="button" variant="outline" size="sm" className="h-auto min-h-8 rounded-full py-1.5 text-left whitespace-normal" onClick={start} disabled={working}>- {working ? <Loader2 className="animate-spin" /> : <Rotate3d />}- {working ? "Making the other sides…" : label}- </Button>+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <Button type="button" variant="outline" size="sm" className="h-auto min-h-8 rounded-full py-1.5 text-left whitespace-normal" onClick={start} disabled={working}>+ {working ? <Loader2 className="animate-spin" /> : <Rotate3d />}+ {working ? "Making the other sides…" : label}+ </Button>+ <OwnSetupChip setup={setup} />+ </div><p className="text-[12px] text-muted-foreground" aria-live="polite">{failed ? (<span className="text-destructive">{failed.error ?? "The sides couldn't be made. Please try again."}</span>diff --git a/src/components/model3d/own-setups.tsx b/src/components/model3d/own-setups.tsxnew file mode 100644index 00000000..db1f294b--- /dev/null+++ b/src/components/model3d/own-setups.tsx@@ -0,0 +1,23 @@+"use client";++import { createContext, useContext } from "react";+import { useIsOwner } from "@/lib/api";+import type { Model3dSetupKey } from "@/lib/av/model3d";+import type { OwnSetup } from "@/lib/own-setup";++/**+ * What Image to 3D's extra steps need from a visitor, as the page read it (ownSetupsNow): a step whose graphs are+ * validated on this studio's GPU has none, so its label has left.+ */+export type Model3dSetups = Partial<Record<Model3dSetupKey, OwnSetup | null>>;++const Setups = createContext<Model3dSetups>({});++export const Model3dSetupsProvider = Setups.Provider;++/** A step's label for this viewer: null for the owner (today's view), and once the step needs nothing more. */+export function useModel3dSetup(key: Model3dSetupKey): OwnSetup | null {+ const owner = useIsOwner();+ const setups = useContext(Setups);+ return owner ? null : (setups[key] ?? null);+}diff --git a/src/components/model3d/refine-option.tsx b/src/components/model3d/refine-option.tsxindex 675f8201..772330db 100644--- a/src/components/model3d/refine-option.tsx+++ b/src/components/model3d/refine-option.tsx@@ -8,7 +8,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, Dimport { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";-import { useCreateGeneration } from "@/lib/api";+import { OwnSetupChip } from "@/components/own-setup";import {HI3D_CLOUD_NOTE,HI3D_DEFAULT,@@ -23,7 +23,8 @@ import {} from "@/lib/av/hi3d";import type { Engine } from "@/lib/catalog/types";import { toastError } from "@/lib/refusals";-import { priceLine, useRunPreview } from "./hooks";+import { priceLine, useCreate3d, useRunPreview } from "./hooks";+import { useModel3dSetup } from "./own-setups";/** "Powered by Hi3D 1.0", linked to Hi3D's site as its licence asks, wherever its results or its switch show. */export function PoweredByHi3d({ className }: { className?: string }) {@@ -71,6 +72,8 @@ export function RefineOption({onUseGpu: () => void;}) {const [last, setLast] = useState<Hi3dResolution>(value ?? HI3D_DEFAULT);+ // A visitor's refine runs on its own GPU: what that needs, until Hi3D's graph is validated on this studio's GPU.+ const setup = useModel3dSetup("refine");if (!openAllowed) return null;if (engine !== "open") {return (@@ -86,9 +89,12 @@ export function RefineOption({return (<div className="mt-3 rounded-xl border p-2.5"><div className="flex items-center justify-between gap-2">- <Label htmlFor="m3d-refine" className="text-[13px]">- {HI3D_LABEL}- </Label>+ <span className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5">+ <Label htmlFor="m3d-refine" className="text-[13px]">+ {HI3D_LABEL}+ </Label>+ <OwnSetupChip setup={setup} />+ </span><Switch id="m3d-refine" checked={on} onCheckedChange={(v) => onChange(v ? last : null)} aria-describedby="m3d-refine-hint" /></div><p id="m3d-refine-hint" className="mt-1 text-[12px] text-muted-foreground">@@ -114,7 +120,8 @@ export function RefineOption({/** "Refine this mesh" on a finished model: Hi3D refines its geometry from the photo it was made from. */export function RefineDialog({ glb, photo, open, onOpenChange, feature }: { glb: string; photo: string; open: boolean; onOpenChange: (v: boolean) => void; feature?: string }) {- const create = useCreateGeneration();+ // The owner's as a studio run; an account's on its own GPU (POST /api/image-to-3d).+ const create = useCreate3d();const [resolution, setResolution] = useState<Hi3dResolution>(HI3D_DEFAULT);const req = refineRequest({ glb, photo, resolution, feature });const preview = useRunPreview(open ? req : null);diff --git a/src/lib/av/model3d.ts b/src/lib/av/model3d.tsindex 6017f0b6..fe41d4b4 100644--- a/src/lib/av/model3d.ts+++ b/src/lib/av/model3d.ts@@ -95,6 +95,19 @@ export const isIdolMesh = (id: string | null | undefined) => id === IDOL_MESH_MO*/export const FINAL_3D = { model: "oss-trellis2", label: "Build the final with TRELLIS.2", note: "A textured, riggable .glb · 16 GB GPU" } as const;+/**+ * Image to 3D's extra steps that run on a visitor's own GPU, by the own-setup id each is labelled with+ * (src/lib/own-setup.ts): Refine detail (Hi3D), the TRELLIS.2 final, Idol 3D's other sides and its spike trim. The page+ * reads which still carry a label (ownSetupsNow) and the studio shows it next to each.+ */+export const MODEL3D_SETUPS = {+ refine: "image-to-3d:hi3d-refine",+ final: "image-to-3d:trellis-final",+ sides: "image-to-3d:idol-other-sides",+ clean: "image-to-3d:idol-clean",+} as const;+export type Model3dSetupKey = keyof typeof MODEL3D_SETUPS;+/*** Where "Build the final with TRELLIS.2" goes from a finished Idol 3D result on the open engine: Image to 3D with* TRELLIS.2 picked and the result's own picture filled in. null on any other result, without the picture, or whendiff --git a/src/lib/own-setup.ts b/src/lib/own-setup.tsindex 40830903..6c2d35ae 100644--- a/src/lib/own-setup.ts+++ b/src/lib/own-setup.ts@@ -35,6 +35,11 @@ interface Entry {setup: OwnSetup;/** A feature that opens on this studio's GPU once its real render passes (workflows/comfyui/gpu-tested.json). */passes?: string;+ /**+ * The ComfyUI graphs that run it on this studio's GPU: its label leaves once the manifest marks each one validated+ * (ownSetupNow in src/server/own-setup-live.ts; a page passes the answer to its client).+ */+ graphs?: readonly string[];}const gpu = (vramGb?: number, more: Omit<Extract<OwnSetup, { need: "gpu" }>, "need" | "vramGb"> = {}): OwnSetup => ({ need: "gpu", ...(vramGb && { vramGb }), ...more });@@ -82,10 +87,10 @@ const ITEMS: Record<string, Entry> = {// Kandinsky 6.0 (open) at Pro quality: an 80 GB card."oss-kandinsky6:pro": { setup: gpu(80) },// Image to 3D's extra steps on a GPU.- "image-to-3d:hi3d-refine": { setup: gpu(24, { files: true }) },- "image-to-3d:trellis-final": { setup: gpu(24) },- "image-to-3d:idol-other-sides": { setup: gpu(8, { files: true }) },- "image-to-3d:idol-clean": { setup: gpu(8, { files: true }) },+ "image-to-3d:hi3d-refine": { setup: gpu(24, { files: true }), graphs: ["mesh-refine-hi3d"] },+ "image-to-3d:trellis-final": { setup: gpu(24), graphs: ["image-to-3d-trellis2"] },+ "image-to-3d:idol-other-sides": { setup: gpu(8, { files: true }), graphs: ["image-to-views-idol"] },+ "image-to-3d:idol-clean": { setup: gpu(8, { files: true }), graphs: ["image-to-splat-idol-clean"] },// Tools whose steps run on a GPU of the visitor's own."audio:edit-speech": { setup: gpu(24, { files: true }) },"video-tools:restore": { setup: gpu(24, { files: true, orKey: "fal" }) },@@ -135,6 +140,11 @@ export function ownSetupItem(id: string): OwnSetup | null {return ITEMS[id]?.setup ?? null;}+/** The graphs whose validation opens an item on this studio's GPU (none: the label stays, or follows `passes`). */+export function ownSetupGraphs(id: string): readonly string[] {+ return ITEMS[id]?.graphs ?? [];+}+/** Every id this table holds (tests, and the hosted runs' checks). */export const OWN_SETUP_IDS: readonly string[] = Object.keys(ITEMS);diff --git a/src/server/own-setup-live.ts b/src/server/own-setup-live.tsindex d056c075..f13857f6 100644--- a/src/server/own-setup-live.ts+++ b/src/server/own-setup-live.ts@@ -2,9 +2,20 @@ import "server-only";import fs from "node:fs";import path from "node:path";import { getModel } from "@/lib/catalog";+import { ownSetupGraphs, ownSetupOnly, type OwnSetup } from "@/lib/own-setup";const MANIFEST = path.join(process.cwd(), "workflows", "comfyui", "manifest.json");+/** The graphs the manifest marks validated (empty when it can't be read). */+function validatedGraphs(manifest: string): Set<string> {+ try {+ const m = JSON.parse(fs.readFileSync(manifest, "utf8")) as { workflows?: { id?: string; validated?: boolean }[] };+ return new Set((m.workflows ?? []).filter((w) => w.validated === true && typeof w.id === "string").map((w) => w.id as string));+ } catch {+ return new Set();+ }+}+/*** Whether a model's ComfyUI graphs have all passed their check on this studio's GPU (the manifest's `validated`), read* when a page is made. Until then its surface marks it with what it runs on (src/lib/own-setup.ts); the mark leaves by@@ -13,11 +24,20 @@ const MANIFEST = path.join(process.cwd(), "workflows", "comfyui", "manifest.jsonexport function graphsReady(modelId: string, manifest = MANIFEST): boolean {const graphs = (getModel(modelId)?.routes ?? []).filter((r) => r.provider === "comfyui").map((r) => r.endpoint);if (!graphs.length) return false;- try {- const m = JSON.parse(fs.readFileSync(manifest, "utf8")) as { workflows?: { id?: string; validated?: boolean }[] };- const validated = new Set((m.workflows ?? []).filter((w) => w.validated === true).map((w) => w.id));- return graphs.every((g) => validated.has(g));- } catch {- return false;- }+ const validated = validatedGraphs(manifest);+ return graphs.every((g) => validated.has(g));+}++/**+ * The setups of these own-setup items as they stand now, by id: an item whose graphs (own-setup.ts `graphs`) the+ * manifest marks validated has none (null), so its label leaves without a code change; any other keeps ownSetupOnly's.+ * A page reads this when it is made and hands it to its client, which can't read the manifest.+ */+export function ownSetupsNow<K extends string>(ids: readonly K[], manifest = MANIFEST): Record<K, OwnSetup | null> {+ const validated = validatedGraphs(manifest);+ const now = (id: K): OwnSetup | null => {+ const graphs = ownSetupGraphs(id);+ return graphs.length && graphs.every((g) => validated.has(g)) ? null : ownSetupOnly(id);+ };+ return Object.fromEntries(ids.map((id) => [id, now(id)])) as Record<K, OwnSetup | null>;}diff --git a/tests/account-3d-extras.test.ts b/tests/account-3d-extras.test.tsnew file mode 100644index 00000000..5d23eee6--- /dev/null+++ b/tests/account-3d-extras.test.ts@@ -0,0 +1,126 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { NextRequest } from "next/server";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++/**+ * Image to 3D's extra steps for visitors (Refine detail with Hi3D, the TRELLIS.2 final, Idol 3D's other sides and its+ * spike trim): they run on an account's own GPU through POST /api/image-to-3d. A guest gets the sign-up card, an account+ * with no GPU "Connect your GPU" (connect-gpu, never own-gpu-tool), and nothing reaches this studio's ComfyUI.+ */+const dir = tempDir("fuobe-account-3d-extras-");+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;++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 gpuRoute = await import("@/app/api/account/gpu/route");+const { proxy } = await import("@/proxy");+const access = await import("@/lib/guest-access");+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 { refineRequest } = await import("@/lib/av/hi3d");+const { idolViewsRequest } = await import("@/lib/av/idol-views");+const { model3dRequest, FINAL_3D, IDOL_MODELS } = await import("@/lib/av/model3d");+const { ownSetupOnly } = await import("@/lib/own-setup");++let fake: FakeComfy;+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]"],+ ["c", "[email protected]"],+ ] as const) {+ const id = auth.createAccount(email, "long enough").id;+ cookies[k] = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;+ if (k === "c") c = id;+ }+ // A links its own ComfyUI; C has neither a GPU nor a key.+ expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: fake.url }, "a"))).status).toBe(200);+});+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestGpuPort = undefined;+ globalThis.__fuobeTestDiskFree = undefined;+ await fake.close();+});+beforeEach(() => resetRates());++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, who?: string) =>+ proxy(new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json", ...(who && { cookie: cookies[who] }) }, body: "{}" }));++describe("Image to 3D's extra steps run on an account's own GPU", () => {+ const steps = (photo: string) => ({+ "Refine this mesh (Hi3D)": refineRequest({ glb: photo.replace(/\.png$/, ".glb"), photo, resolution: 512 }),+ "Make the other sides (Idol 3D)": idolViewsRequest(photo),+ "Build the final with TRELLIS.2": model3dRequest({ engine: "open", mode: "image", modelId: FINAL_3D.model, photo }),+ "Idol 3D with Trim spikes": model3dRequest({ engine: "open", mode: "splat", modelId: IDOL_MODELS.open, photo, quality: "best", photoCrop: true, trimSpikes: true }),+ });++ it("each step is one of the labelled own-setup items", () => {+ for (const id of ["image-to-3d:hi3d-refine", "image-to-3d:trellis-final", "image-to-3d:idol-other-sides", "image-to-3d:idol-clean"]) expect(ownSetupOnly(id), id).not.toBeNull();+ });++ it("a guest gets the sign-up card, from the proxy and from the route", async () => {+ const g = viaProxy("/api/image-to-3d");+ expect(g.status).toBe(401);+ expect(g.headers.get(access.GUEST_HEADER)).toBe("1");+ for (const [name, req] of Object.entries(steps("/api/files/x.png"))) {+ const r = await route.POST(json("/api/image-to-3d", "POST", req));+ expect(r.status, name).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER), name).toBe("1");+ }+ });++ it("an account with no GPU is asked to connect one (connect-gpu, not own-gpu-tool), and nothing is made", async () => {+ expect(viaProxy("/api/image-to-3d", "a").headers.get("x-middleware-next")).toBe("1");+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "c.png" }).url);+ const count = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;+ const n = count();+ for (const [name, req] of Object.entries(steps(own))) {+ if (name.startsWith("Refine")) continue; // its GLB is checked as the account's own first (below)+ const r = await route.POST(json("/api/image-to-3d", "POST", req, "c"));+ expect(r.status, name).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER), name).toBe("1");+ const body = (await r.json()) as { code?: string; error?: string };+ expect(body.code, name).toBe("connect-gpu");+ expect(body.error, name).not.toMatch(/isn['’]t available/i);+ }+ expect(count()).toBe(n);+ // Refine reads a model of the account's own; one it doesn't own is never reached, and this studio's ComfyUI never is.+ const refine = await route.POST(json("/api/image-to-3d", "POST", steps(own)["Refine this mesh (Hi3D)"], "c"));+ expect([403, 404]).toContain(refine.status);+ expect(((await refine.json()) as { code?: string }).code).not.toBe("own-gpu-tool");+ expect(fetched.filter((u) => u.startsWith("http://owner-comfy.test:8188/prompt"))).toEqual([]);+ });+});diff --git a/tests/idol-final.test.ts b/tests/idol-final.test.tsindex a4669a03..059bd9c2 100644--- a/tests/idol-final.test.ts+++ b/tests/idol-final.test.ts@@ -60,13 +60,15 @@ describe("Build the final with TRELLIS.2", () => {expect(FINAL_3D.note).toBe("A textured, riggable .glb · 16 GB GPU");});- it("is wired into the card and the studio (model access, open models, no visitors; ?image= fills the picture)", () => {+ it("is wired into the card and the studio (model access, open models, a visitor's own GPU; ?image= fills the picture)", () => {const root = process.cwd();const card = fs.readFileSync(path.join(root, "src/components/model3d/model-card.tsx"), "utf8");const studio = fs.readFileSync(path.join(root, "src/components/model3d/model3d-studio.tsx"), "utf8");expect(card).toContain("finalBuildHref(g, view, finalAllowed)");expect(card).toContain("{FINAL_3D.note}");- expect(studio).toContain('const finalAllowed = !visitor && engineMode !== "cloud" && offered(access, FINAL_3D.model, "open");');+ expect(studio).toContain('const finalAllowed = engineMode !== "cloud" && offered(access, FINAL_3D.model, "open");');+ // A visitor's final runs on its own GPU: the link carries its label until TRELLIS.2's graph is validated here.+ expect(card).toContain("<OwnSetupChip setup={finalSetup} />");expect(studio).toContain("readModel3dLink(params)");expect(studio).toContain("onImage={fromImage}");// A second click on the same link still fills the form (the URL doesn't change, so UrlModel can't).diff --git a/tests/own-setup-3d.test.ts b/tests/own-setup-3d.test.tsnew file mode 100644index 00000000..f8e13116--- /dev/null+++ b/tests/own-setup-3d.test.ts@@ -0,0 +1,157 @@+import fs from "node:fs";+import path from "node:path";+import { createElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";++vi.mock("server-only", () => ({}));++/**+ * Image to 3D's extra steps on a visitor's own GPU (Refine detail with Hi3D, the TRELLIS.2 final, Idol 3D's other sides+ * and its spike trim): they show to guests and accounts, each labelled with what it runs on until its graphs are+ * validated on this studio's GPU, and the label leaves by itself once the manifest says so. The owner's view is today's.+ */++// Who is looking: the client hooks the studio reads, set per test.+const who = vi.hoisted(() => ({ owner: false, viewer: { kind: "guest" } as { kind: "guest" | "account"; gpu?: { connected: boolean }; keys?: string[] } | undefined }));+vi.mock("@/lib/api", () => ({+ useIsOwner: () => who.owner,+ useStatus: () => ({ data: who.owner ? {} : { viewer: who.viewer } }),+ useEngine: () => ["open", () => {}, "both"],+ useModelAccess: () => undefined,+ useGenerations: () => ({ data: [] }),+ askToSignUp: vi.fn(),+ CONNECT_GPU_EVENT: "fuobe:connect-gpu",+}));+vi.mock("@/components/keys/your-keys", () => ({ openAddKey: vi.fn() }));+vi.mock("@/components/model3d/hooks", () => ({+ useCreate3d: () => ({ mutate: vi.fn(), isPending: false }),+ useRunPreview: () => ({ data: undefined }),+ priceLine: () => null,+}));++const BANNED = /untested|not tested|unverified|not verified|not validated|validat|isn['’]t available|not available|unavailable|coming soon|held|owner|beta|experimental|soon/i;+const IDS = ["image-to-3d:hi3d-refine", "image-to-3d:trellis-final", "image-to-3d:idol-other-sides", "image-to-3d:idol-clean"] as const;+const GRAPHS: Record<(typeof IDS)[number], string> = {+ "image-to-3d:hi3d-refine": "mesh-refine-hi3d",+ "image-to-3d:trellis-final": "image-to-3d-trellis2",+ "image-to-3d:idol-other-sides": "image-to-views-idol",+ "image-to-3d:idol-clean": "image-to-splat-idol-clean",+};++const d = tempDir("fuobe-own-setup-3d-");+const manifest = (validated: Partial<Record<string, boolean>>) => {+ const file = path.join(d, `m-${Object.values(validated).join("-")}-${Object.keys(validated).length}.json`);+ fs.writeFileSync(file, JSON.stringify({ workflows: Object.entries(validated).map(([id, v]) => ({ id, validated: v })) }));+ return file;+};++afterEach(() => {+ who.owner = false;+ who.viewer = { kind: "guest" };+});++describe("Image to 3D's extra steps: the labels follow the manifest", () => {+ it("each step has a setup of its own and plain words", async () => {+ const { MODEL3D_SETUPS } = await import("@/lib/av/model3d");+ const { ownSetupOnly, ownSetupLabel, ownSetupShort, ownSetupDetail, ownSetupGraphs } = await import("@/lib/own-setup");+ expect(Object.values(MODEL3D_SETUPS).sort()).toEqual([...IDS].sort());+ for (const id of IDS) {+ const o = ownSetupOnly(id);+ expect(o, id).not.toBeNull();+ expect(ownSetupGraphs(id), id).toEqual([GRAPHS[id]]);+ for (const words of [ownSetupLabel(o!), ownSetupShort(o!), ownSetupDetail(o!)]) expect(words, id).not.toMatch(BANNED);+ }+ expect(ownSetupLabel(ownSetupOnly("image-to-3d:hi3d-refine")!)).toBe("Runs on your own GPU · 24 GB");+ expect(ownSetupLabel(ownSetupOnly("image-to-3d:idol-other-sides")!)).toBe("Runs on your own GPU · 8 GB");+ });++ it("keeps a step's label until its graph is validated, then drops it", async () => {+ const { ownSetupsNow } = await import("@/server/own-setup-live");+ const before = ownSetupsNow(IDS, manifest(Object.fromEntries(Object.values(GRAPHS).map((g) => [g, false]))));+ for (const id of IDS) expect(before[id], id).not.toBeNull();+ // One flag flips: only that step's label leaves.+ const one = ownSetupsNow(IDS, manifest({ ...Object.fromEntries(Object.values(GRAPHS).map((g) => [g, false])), "mesh-refine-hi3d": true }));+ expect(one["image-to-3d:hi3d-refine"]).toBeNull();+ expect(one["image-to-3d:idol-other-sides"]).not.toBeNull();+ const after = ownSetupsNow(IDS, manifest(Object.fromEntries(Object.values(GRAPHS).map((g) => [g, true]))));+ for (const id of IDS) expect(after[id], id).toBeNull();+ // No manifest: every label stays (never a step shown as if this studio's GPU ran it).+ const none = ownSetupsNow(IDS, path.join(d, "missing.json"));+ for (const id of IDS) expect(none[id], id).not.toBeNull();+ // An id with no graphs of its own keeps ownSetupOnly's answer; one outside the table has none.+ expect(ownSetupsNow(["oss-h3-regenerate", "nano-banana-pro"], manifest({}))).toEqual({ "oss-h3-regenerate": expect.objectContaining({ need: "gpu" }), "nano-banana-pro": null });+ });++ it("reads this repo's manifest: a step labelled now is one whose graph isn't validated yet", async () => {+ const { ownSetupsNow } = await import("@/server/own-setup-live");+ const m = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows", "comfyui", "manifest.json"), "utf8")) as { workflows: { id: string; validated?: boolean }[] };+ const validated = new Set(m.workflows.filter((w) => w.validated === true).map((w) => w.id));+ const now = ownSetupsNow(IDS);+ for (const id of IDS) expect(now[id] === null, id).toBe(validated.has(GRAPHS[id]));+ });+});++/** Renders a step under the page's setups, as the given viewer. */+async function render(node: () => ReactNode, setups: Record<string, unknown>) {+ const { Model3dSetupsProvider } = await import("@/components/model3d/own-setups");+ return renderToStaticMarkup(createElement(Model3dSetupsProvider, { value: setups }, node()));+}++describe("Image to 3D's extra steps show to everyone", () => {+ it("Refine detail and Make the other sides show to a guest and an account with their labels, and to the owner without", async () => {+ const { ownSetupOnly } = await import("@/lib/own-setup");+ const { RefineOption } = await import("@/components/model3d/refine-option");+ const { OtherSides } = await import("@/components/model3d/other-sides");+ const setups = { refine: ownSetupOnly("image-to-3d:hi3d-refine"), sides: ownSetupOnly("image-to-3d:idol-other-sides") };+ const refine = () => createElement(RefineOption, { engine: "open", value: null, onChange: () => {}, openAllowed: true, onUseGpu: () => {} });+ const sides = () => createElement(OtherSides, { photo: "/api/files/front.png", asPhoto: true, label: "Make the other sides from the front (Idol 3D)", onMade: () => {} });+ for (const viewer of [{ kind: "guest" as const }, { kind: "account" as const, gpu: { connected: false } }]) {+ who.viewer = viewer;+ const r = await render(refine, setups);+ expect(r).toContain("Refine detail · Hi3D 1.0");+ expect(r).toContain('data-slot="own-setup"');+ expect(r).toContain("Runs on your own GPU · 24 GB");+ const s = await render(sides, setups);+ expect(s).toContain("Make the other sides from the front (Idol 3D)");+ expect(s).toContain("Runs on your own GPU · 8 GB");+ for (const html of [r, s]) expect(html.replace(/<[^>]+>/g, " ")).not.toMatch(BANNED);+ }+ // Once the graphs are validated (the page passes null), the steps show with no label.+ const r = await render(refine, { refine: null, sides: null });+ expect(r).toContain("Refine detail · Hi3D 1.0");+ expect(r).not.toContain('data-slot="own-setup"');+ // The owner's view is today's: the step, no label.+ who.owner = true;+ const o = await render(refine, setups);+ expect(o).toContain("Refine detail · Hi3D 1.0");+ expect(o).not.toContain('data-slot="own-setup"');+ });++ it("Make the other sides is offered to visitors too (a visitor's run goes to its own GPU)", async () => {+ const { useOtherSidesOffered } = await import("@/components/model3d/other-sides");+ let offered: boolean | undefined;+ const Probe = () => {+ offered = useOtherSidesOffered();+ return null;+ };+ for (const viewer of [{ kind: "guest" as const }, { kind: "account" as const }]) {+ who.viewer = viewer;+ offered = undefined;+ renderToStaticMarkup(createElement(Probe));+ expect(offered).toBe(true);+ }+ });++ it("a press: a guest gets the sign-up card, an account without a GPU the connect card, one with a GPU and the owner run", async () => {+ const { ownSetupOnly, ownSetupStep } = await import("@/lib/own-setup");+ for (const id of IDS) {+ const o = ownSetupOnly(id);+ expect(ownSetupStep(o, { kind: "guest" })).toEqual({ kind: "sign-up" });+ expect(ownSetupStep(o, { kind: "account", gpu: { connected: false }, keys: ["fal"] })).toEqual({ kind: "connect-gpu", gpuOnly: true });+ expect(ownSetupStep(o, { kind: "account", gpu: { connected: true } })).toEqual({ kind: "run" });+ expect(ownSetupStep(o, null)).toEqual({ kind: "run" });+ }+ });+});