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
Photodump, Fashion Factory, Character Sheet and AI Influencer: accounts run them on their own GPU or key
Adarsh4eff2e0a86b8
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex f672d517..c4c0036c 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -360,6 +360,17 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188deletes a take for good (it has no Trash). "Create 3D scene" and an exact orbit run there too: on its GPU their firststep is a 3D model, finished on this server under its limits as Image to 3D's are. Saving a still as an element, theelements list and sharing a project are left out: those are the owner's library. A guest gets the sign-up card.+- **Photodump, Fashion Factory, Character Sheet and AI Influencer.** An account runs them the same way+ (`POST /api/photodump`, `/api/photodump/fashion`, `/api/photodump/character`, `/api/influencer`, and a photo's retry+ `/api/photodump/retry`): every photo on its own ComfyUI or its own fal.ai or Replicate key, with only its own files,+ after the same checks, and a set counts once against its limits. Its packs (`/api/photodump/packs`) and its+ characters (`/api/photodump/characters`: a name and photos of one person, saved from New character or from a+ Character Sheet's "Save as character") are its own projects: up to 50 of each, from its own photos, deleted with the+ account; another account's or the owner's read as not found (404). An account's character goes into a run as its+ first photo (an @mention names the owner's elements only). Its runs are its own (each tool's History and recent+ sheets), and a retried photo replaces the failed one for good (it has no Trash). The price is its run's: free on its+ GPU, its own key's price on the cloud engine. A guest gets the sign-up card on Generate, on Create pack, on New+ character and before choosing a photo.- **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.diff --git a/src/app/api/influencer/estimate/route.ts b/src/app/api/influencer/estimate/route.tsindex b37e88a6..3dd27ba6 100644--- a/src/app/api/influencer/estimate/route.ts+++ b/src/app/api/influencer/estimate/route.ts@@ -1,17 +1,12 @@import { POST as influencer } from "../route";-import { priceAs } from "@/server/visitor";/*** The price of an AI Influencer run without starting it: the same body as POST /api/influencer?preview=1, at the- * `<route>/estimate` path the evaluation harness prices studio routes at.+ * `<route>/estimate` path the evaluation harness prices studio routes at. Priced as the asker's run would go: an+ * account's on its own GPU or key, a guest's on the open engine, never a demo (src/server/account-tool-run.ts priceAsRun).*/-async function post(request: Request) {+export async function POST(request: Request) {const url = new URL(request.url.replace(/\/estimate(?=\/?(\?|$))/, ""));url.searchParams.set("preview", "1");return influencer(new Request(url, { method: "POST", headers: request.headers, body: await request.text() }));}--/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */-export async function POST(request: Request) {- return priceAs(request, () => post(request));-}diff --git a/src/app/api/influencer/route.ts b/src/app/api/influencer/route.tsindex 237514d2..b0a9e882 100644--- a/src/app/api/influencer/route.ts+++ b/src/app/api/influencer/route.ts@@ -1,7 +1,7 @@import { z } from "zod";import { MAX_CLOTHING, MAX_DIRECTION } from "@/lib/influencer";-import { createInfluencer, previewInfluencer, type InfluencerBody } from "@/server/influencer";-import { refusedRun } from "@/server/connect-refusal";+import { createInfluencer, influencerSteps, previewInfluencer, type InfluencerBody } from "@/server/influencer";+import { photoRun, photoRunGate, RequestId } from "@/server/photo-apps-http";const File = z.string().startsWith("/api/files/").max(500);@@ -13,6 +13,7 @@ const Body = z.object({photo: File.optional(),clothing: z.array(File).max(MAX_CLOTHING).optional(),modelId: z.string().max(60).optional(),+ requestId: RequestId,});/** What's wrong with a body, in Higgsfield's words where it has them. */@@ -29,16 +30,21 @@ function bodyError(issues: z.core.$ZodIssue[]): string {/*** AI Influencer builder: a character sheet from the builder's picks — Fuobe Soul in the cloud (Nano Banana Pro or* Seedream 5.0 Pro when asked), the Soul Cast sheet workflow on the open engine, each followed by Qwen-Image-Edit 2511- * for a face, a reference or clothing. `?preview=1` (or POST /api/influencer/estimate) prices it instead.+ * for a face, a reference or clothing. `?preview=1` (or POST /api/influencer/estimate) prices it instead. An account's+ * runs on its own GPU or key, with its own photos (src/server/photo-apps-http.ts); a guest signs up first.*/export async function POST(request: Request) {+ const gate = photoRunGate(request);+ if (gate) return gate;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: bodyError(parsed.error.issues) }, { status: 400 });- const body = parsed.data as InfluencerBody;- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewInfluencer(body));- try {- return Response.json(createInfluencer(body), { status: 201 });- } catch (e) {- return refusedRun(e, request);- }+ const { requestId, ...rest } = parsed.data;+ const body = rest as InfluencerBody;+ return photoRun(request, requestId, {+ tool: "influencer",+ files: [body.photo, ...(body.clothing ?? [])],+ preview: () => previewInfluencer(body),+ steps: () => influencerSteps(body),+ start: () => createInfluencer(body),+ });}diff --git a/src/app/api/photodump/character/route.ts b/src/app/api/photodump/character/route.tsindex 80ce78c6..c46f993e 100644--- a/src/app/api/photodump/character/route.ts+++ b/src/app/api/photodump/character/route.ts@@ -1,18 +1,19 @@import { z } from "zod";-import { createSheet, previewSheet, type SheetRun } from "@/server/photodump";-import { refusedRun } from "@/server/connect-refusal";+import { photoRun, photoRunGate, RequestId } from "@/server/photo-apps-http";+import { createSheet, previewSheet, sheetSteps, type SheetRun } from "@/server/photodump";const Engine = z.enum(["cloud", "open"]);const Body = z.discriminatedUnion("mode", [- z.object({ mode: z.literal("reference"), engine: Engine, images: z.array(z.string().startsWith("/api/files/")).max(5), details: z.string().max(300).optional() }),+ z.object({ mode: z.literal("reference"), engine: Engine, images: z.array(z.string().startsWith("/api/files/")).max(5), details: z.string().max(300).optional(), requestId: RequestId }),z.object({mode: z.literal("cast"),engine: Engine,cast: z.record(z.string().max(40), z.union([z.string().max(300), z.number(), z.array(z.string().max(60)).max(8)])),details: z.string().max(300).optional(),+ requestId: RequestId,}),- z.object({ mode: z.literal("describe"), engine: Engine, prompt: z.string().max(2000) }),+ z.object({ mode: z.literal("describe"), engine: Engine, prompt: z.string().max(2000), requestId: RequestId }),]);/** What's wrong with a body, said for the mode it was meant for (Higgsfield's words where it has them). */@@ -31,17 +32,22 @@ function bodyError(mode: unknown, issues: z.core.$ZodIssue[]): string {/*** Character Sheet: a turnaround sheet from 1–5 reference photos, from a Soul Cast build, or from a- * description (the AI Influencer app). `?preview=1` prices it instead.+ * description (the AI Influencer app). `?preview=1` prices it instead. An account's runs on its own GPU or key, with+ * its own photos (src/server/photo-apps-http.ts); a guest signs up first.*/export async function POST(request: Request) {+ const gate = photoRunGate(request);+ if (gate) return gate;const body = (await request.json().catch(() => null)) as { mode?: unknown } | null;const parsed = Body.safeParse(body);if (!parsed.success) return Response.json({ error: bodyError(body?.mode, parsed.error.issues) }, { status: 400 });- const input = parsed.data as SheetRun;- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewSheet(input));- try {- return Response.json(createSheet(input), { status: 201 });- } catch (e) {- return refusedRun(e, request);- }+ const { requestId, ...rest } = parsed.data;+ const input = rest as SheetRun;+ return photoRun(request, requestId, {+ tool: "character-sheet",+ files: input.mode === "reference" ? input.images : [],+ preview: () => previewSheet(input),+ steps: () => sheetSteps(input),+ start: () => createSheet(input),+ });}diff --git a/src/app/api/photodump/characters/[id]/route.ts b/src/app/api/photodump/characters/[id]/route.tsnew file mode 100644index 00000000..c3c1843d--- /dev/null+++ b/src/app/api/photodump/characters/[id]/route.ts@@ -0,0 +1,13 @@+import { toolViewer } from "@/server/account-tool-run";+import { photoProjectChange } from "@/server/photo-apps-http";+import { deletePhotoCharacter } from "@/server/photodump";++/** Delete one of the account's own characters (another's, or none, reads as not found). */+export async function DELETE(request: Request, ctx: RouteContext<"/api/photodump/characters/[id]">) {+ const { id } = await ctx.params;+ return photoProjectChange(request, () => {+ const viewer = toolViewer(request);+ const done = viewer.kind === "account" && deletePhotoCharacter(viewer.account.id, id);+ return done ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });+ });+}diff --git a/src/app/api/photodump/characters/route.ts b/src/app/api/photodump/characters/route.tsnew file mode 100644index 00000000..45c15a67--- /dev/null+++ b/src/app/api/photodump/characters/route.ts@@ -0,0 +1,28 @@+import { connection } from "next/server";+import { z } from "zod";+import { toolViewer } from "@/server/account-tool-run";+import { photoProjectChange } from "@/server/photo-apps-http";+import { createPhotoCharacter, listPhotoCharacters } from "@/server/photodump";++const Body = z.object({ name: z.string().max(200), references: z.array(z.string().startsWith("/api/files/").max(500)).min(1).max(80) });++/**+ * An account's own characters for Photodump and Fashion Factory (a name and photos of one person, saved from New+ * character or a Character Sheet). The owner's characters are elements (/api/elements): none here. A guest has none.+ */+export async function GET(request: Request) {+ await connection();+ const viewer = toolViewer(request);+ return Response.json({ items: viewer.kind === "account" ? listPhotoCharacters(viewer.account.id) : [] });+}++/** Save one, from its own photos only. */+export async function POST(request: Request) {+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Add a name and a photo of them" }, { status: 400 });+ return photoProjectChange(request, () => {+ const viewer = toolViewer(request);+ if (viewer.kind !== "account") return Response.json({ error: "Save characters on the Elements page." }, { status: 404 });+ return Response.json(createPhotoCharacter(viewer.account.id, parsed.data), { status: 201 });+ });+}diff --git a/src/app/api/photodump/fashion/route.ts b/src/app/api/photodump/fashion/route.tsindex 90cf966f..7fb2b9ec 100644--- a/src/app/api/photodump/fashion/route.ts+++ b/src/app/api/photodump/fashion/route.ts@@ -1,28 +1,33 @@import { z } from "zod";-import { createFashion, previewFashion, type FashionRun } from "@/server/photodump";-import { refusedRun } from "@/server/connect-refusal";+import { photoRun, photoRunGate, RequestId } from "@/server/photo-apps-http";+import { createFashion, fashionSteps, previewFashion, type FashionRun } from "@/server/photodump";const File = z.string().startsWith("/api/files/").max(500);const Engine = z.enum(["cloud", "open"]);const Body = z.discriminatedUnion("step", [- z.object({ step: z.literal("base"), templateId: z.string().max(80), elementId: z.string().max(40), engine: Engine }),- z.object({ step: z.literal("outfit"), templateId: z.string().max(80), base: File, garment: File, engine: Engine, modelId: z.string().max(80).optional() }),- z.object({ step: z.literal("photoset"), templateId: z.string().max(80), dressed: File, engine: Engine, modelId: z.string().max(80).optional() }),+ z.object({ step: z.literal("base"), templateId: z.string().max(80), elementId: z.string().max(40), engine: Engine, requestId: RequestId }),+ z.object({ step: z.literal("outfit"), templateId: z.string().max(80), base: File, garment: File, engine: Engine, modelId: z.string().max(80).optional(), requestId: RequestId }),+ z.object({ step: z.literal("photoset"), templateId: z.string().max(80), dressed: File, engine: Engine, modelId: z.string().max(80).optional(), requestId: RequestId }),]);/*** Fashion Factory steps: 4 base shots of the character in the template's set, the outfit (try-on),- * and the photoset (one photo per template shot). `?preview=1` prices a step instead.+ * and the photoset (one photo per template shot). `?preview=1` prices a step instead. An account's runs on its own GPU+ * or key, with its own character and files (src/server/photo-apps-http.ts); a guest signs up first.*/export async function POST(request: Request) {+ const gate = photoRunGate(request);+ if (gate) return gate;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Template required" }, { status: 400 });- const input = parsed.data as FashionRun;- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewFashion(input));- try {- return Response.json(createFashion(input), { status: 201 });- } catch (e) {- return refusedRun(e, request);- }+ const { requestId, ...rest } = parsed.data;+ const input = rest as FashionRun;+ return photoRun(request, requestId, {+ tool: "fashion",+ files: input.step === "outfit" ? [input.base, input.garment] : input.step === "photoset" ? [input.dressed] : [],+ preview: () => previewFashion(input),+ steps: () => fashionSteps(input),+ start: () => createFashion(input),+ });}diff --git a/src/app/api/photodump/packs/[id]/route.ts b/src/app/api/photodump/packs/[id]/route.tsindex 3df0c708..e355cc71 100644--- a/src/app/api/photodump/packs/[id]/route.ts+++ b/src/app/api/photodump/packs/[id]/route.ts@@ -1,6 +1,8 @@+import { photoProjectChange } from "@/server/photo-apps-http";import { deleteUserPack } from "@/server/photodump";-export async function DELETE(_req: Request, ctx: RouteContext<"/api/photodump/packs/[id]">) {+/** Delete one of your own packs (an account's own only: another's reads as not found). */+export async function DELETE(request: Request, ctx: RouteContext<"/api/photodump/packs/[id]">) {const { id } = await ctx.params;- return deleteUserPack(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });+ return photoProjectChange(request, () => (deleteUserPack(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 })));}diff --git a/src/app/api/photodump/packs/route.ts b/src/app/api/photodump/packs/route.tsindex b37fcde7..52bdeb3b 100644--- a/src/app/api/photodump/packs/route.ts+++ b/src/app/api/photodump/packs/route.ts@@ -1,21 +1,20 @@import { connection } from "next/server";import { z } from "zod";+import { asViewer, toolViewer } from "@/server/account-tool-run";+import { photoProjectChange } from "@/server/photo-apps-http";import { createUserPack, listUserPacks } from "@/server/photodump";const Body = z.object({ name: z.string().max(200), refs: z.array(z.string().startsWith("/api/files/")).max(40) });-export async function GET() {+/** Your own packs: the owner's, or an account's own (never another's); a guest has none. */+export async function GET(request: Request) {await connection();- return Response.json({ packs: listUserPacks() });+ return Response.json({ packs: asViewer(toolViewer(request), listUserPacks) });}-/** Create a pack from up to 15 reference photos: each becomes one photo of the dump. */+/** Create a pack from up to 15 reference photos: each becomes one photo of the dump. An account's from its own photos. */export async function POST(request: Request) {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Upload your reference set up to 15 photos" }, { status: 400 });- try {- return Response.json(createUserPack(parsed.data), { status: 201 });- } catch (e) {- return Response.json({ error: (e as Error).message }, { status: 400 });- }+ return photoProjectChange(request, () => Response.json(createUserPack(parsed.data), { status: 201 }));}diff --git a/src/app/api/photodump/retry/route.ts b/src/app/api/photodump/retry/route.tsindex 127fb1dc..6c8377b3 100644--- a/src/app/api/photodump/retry/route.ts+++ b/src/app/api/photodump/retry/route.ts@@ -1,19 +1,36 @@import { z } from "zod";-import { retryPhoto } from "@/server/photodump";-import { refusedRun } from "@/server/connect-refusal";+import { asViewer, toolViewer } from "@/server/account-tool-run";+import { photoRun, photoRunGate, RequestId } from "@/server/photo-apps-http";+import { ownSteps, planRetry, retrySteps, startRetry, type RetryPlan } from "@/server/photodump";+import { ShortsError } from "@/server/shorts";-const Body = z.object({ id: z.string().min(1).max(40) });+const Body = z.object({ id: z.string().min(1).max(40), requestId: RequestId });/*** Retry a failed or canceled photo of a Photodump / Fashion Factory / Character Sheet run: the same- * request in the same batch, replacing the failed one (it goes to the Trash).+ * request in the same batch, replacing the failed one (the owner's goes to the Trash; an account's, which has no Trash,+ * is deleted). An account retries only its own photos, on its own GPU or key (src/server/photo-apps-http.ts).*/export async function POST(request: Request) {+ const gate = photoRunGate(request);+ if (gate) return gate;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Pick the photo to retry" }, { status: 400 });+ const { id, requestId } = parsed.data;+ const viewer = toolViewer(request);+ // Planned as the asker: another's photo (or the owner's, for an account) reads as gone, before anything else.+ let plan: RetryPlan;try {- return Response.json({ items: retryPhoto(parsed.data.id) }, { status: 201 });+ plan = asViewer(viewer, () => planRetry(id));} catch (e) {- return refusedRun(e, request);+ const status = e instanceof ShortsError ? e.status : 422;+ return Response.json({ error: (e as Error).message }, { status });}+ return photoRun(request, requestId, {+ tool: "photo-retry",+ files: [],+ preview: () => ({ error: "Pick the photo to retry", notes: [] }),+ steps: () => ownSteps(retrySteps(plan)),+ start: () => ({ items: startRetry(plan) }),+ });}diff --git a/src/app/api/photodump/route.ts b/src/app/api/photodump/route.tsindex c907ba2b..477404b0 100644--- a/src/app/api/photodump/route.ts+++ b/src/app/api/photodump/route.ts@@ -1,7 +1,8 @@import { connection } from "next/server";import { z } from "zod";-import { createPhotodump, listUserPacks, previewPhotodump } from "@/server/photodump";-import { refusedRun } from "@/server/connect-refusal";+import { asViewer, toolViewer } from "@/server/account-tool-run";+import { photoRun, photoRunGate, RequestId } from "@/server/photo-apps-http";+import { createPhotodump, listUserPacks, photodumpSteps, previewPhotodump } from "@/server/photodump";const Body = z.object({@@ -11,26 +12,32 @@ const Body = zselfie: z.string().startsWith("/api/files/").max(500).optional(),aspectRatio: z.string().max(10).optional(),modelId: z.string().max(80).optional(),+ requestId: RequestId,}).refine((b) => !!b.elementId || !!b.selfie, { message: "Pick a character or add a selfie" });-/** Your own packs (the built-in ones ship with the page). */-export async function GET() {+/** Your own packs (the built-in ones ship with the page): the owner's, or an account's own. */+export async function GET(request: Request) {await connection();- return Response.json({ packs: listUserPacks() });+ return Response.json({ packs: asViewer(toolViewer(request), listUserPacks) });}/*** Generate a photodump: one photo per pack shot, as one batch. `?preview=1` prices it instead- * (model, photo count, cost, demo, notes, or the error that would stop it).+ * (model, photo count, cost, demo, notes, or the error that would stop it). An account's runs on its own GPU or key+ * (src/server/photo-apps-http.ts); a guest signs up first.*/export async function POST(request: Request) {+ const gate = photoRunGate(request);+ if (gate) return gate;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues[0]?.message ?? "Pick a pack" }, { status: 400 });- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewPhotodump(parsed.data));- try {- return Response.json(createPhotodump(parsed.data), { status: 201 });- } catch (e) {- return refusedRun(e, request);- }+ const { requestId, ...input } = parsed.data;+ return photoRun(request, requestId, {+ tool: "photodump",+ files: [input.selfie],+ preview: () => previewPhotodump(input),+ steps: () => photodumpSteps(input),+ start: () => createPhotodump(input),+ });}diff --git a/src/components/fashion/character-sheet.tsx b/src/components/fashion/character-sheet.tsxindex 55753fbe..6e482090 100644--- a/src/components/fashion/character-sheet.tsx+++ b/src/components/fashion/character-sheet.tsx@@ -7,20 +7,19 @@ import { Suspense, useCallback, useMemo, useRef, useState, type ComponentProps }import { useSearchParams } from "next/navigation";import { toast } from "sonner";import { PageHeader, PageShell } from "@/components/page-shell";-import { SelfHostNote } from "@/components/self-host-note";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Textarea } from "@/components/ui/textarea";import { EngineSwitch } from "@/components/studio/engine-switch";import { fileToList, type SlotValue } from "@/components/studio/media-slot";import { radioKeys, radioTab } from "@/components/studio/radio-keys";-import { useRun, useRunPreview } from "@/components/photodump/hooks";+import { usePhotoCharacters, useRun, useRunPreview, useSaveCharacter } from "@/components/photodump/hooks";import { ResultsGrid } from "@/components/photodump/results";import { RunLine } from "@/components/photodump/steps";import { AnimatePosesButton } from "@/components/turnaround/animate-poses";import { TurnaroundButton } from "@/components/turnaround/turnaround-dialog";import { HandoffImage } from "@/components/nav/next-steps";-import { useElements, useEngine, useGenerations, useLikelyVisitor, useSaveElement } from "@/lib/api";+import { useAskBeforeUpload, useEngine, useGenerations } from "@/lib/api";import { castFieldVisible, castNameFor, randomCast, SHEET_MAX_REFS, type CastAnswers, type CastFieldData } from "@/lib/catalog/packs";import { sheetPictures } from "@/lib/catalog/turnaround";import type { Generation } from "@/lib/catalog/types";@@ -109,10 +108,24 @@ function CastForm({ fields, values, set }: { fields: CastFieldData[]; values: Ca*/export function SaveCharacter({ item, extra, defaultName }: { item: Generation; extra: string[]; defaultName: string }) {const [name, setName] = useState(defaultName);- const save = useSaveElement();- const elements = useElements();+ // The owner's character is an element (@mentions, its page); an account's is its own, picked by name in Photodump+ // and Fashion Factory.+ const save = useSaveCharacter();+ const elements = usePhotoCharacters();const refs = [...item.outputs.filter((o) => o.kind === "image").map((o) => o.url), ...extra].slice(0, 20);const saved = save.data ?? elements.data?.find((e) => e.kind === "character" && !!refs[0] && e.references.includes(refs[0]));+ if (saved && !save.owner)+ return (+ <div className="flex flex-wrap items-center gap-2 rounded-2xl border bg-background p-3">+ <span className="grid size-7 place-items-center rounded-full bg-success/15 text-success">+ <Check className="size-4" />+ </span>+ <p className="min-w-0 flex-1 text-[13px]">+ Saved as <span className="font-medium">{saved.name}</span> — pick it under My character in <Link href="/photodump" className="text-brand-text underline underline-offset-2">Photodump</Link> or{" "}+ <Link href="/fashion-factory" className="text-brand-text underline underline-offset-2">Fashion Factory</Link>.+ </p>+ </div>+ );if (saved)return (<div className="flex flex-wrap items-center gap-2 rounded-2xl border bg-background p-3">@@ -137,8 +150,8 @@ export function SaveCharacter({ item, extra, defaultName }: { item: Generation;<Buttondisabled={!name.trim() || save.isPending || elements.isLoading}onClick={() =>- save.mutate(- { name: name.trim(), kind: "character", references: refs },+ save.save(+ { name: name.trim(), references: refs },{// The card turns into "Saved as @handle · Open": no toast needed.onError: (e) => toastError(e),@@ -179,9 +192,9 @@ function SheetTurnaround(props: TurnaroundProps) {export function CharacterSheetView({ fields, defaults }: { fields: CastFieldData[]; defaults: CastAnswers }) {const [engine, setEngine] = useEngine();- // A sheet doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and the- // uploads and Create are off, instead of a run the server refuses.- const visitor = useLikelyVisitor();+ // A guest is asked to sign up before choosing photos, and an account with neither its own GPU nor its own key to+ // connect one.+ const askFirst = useAskBeforeUpload();const [mode, setMode] = useState<Mode>("reference");const [photos, setPhotos] = useState<SlotValue[]>([]);const [details, setDetails] = useState("");@@ -209,7 +222,7 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldData: null;const preview = useRunPreview("/api/photodump/character", body);const addFiles = (files: Iterable<File>) => {- if (visitor) return;+ if (askFirst()) return;const list = [...files].filter((f) => /^image\//.test(f.type));if (photos.length + list.length > SHEET_MAX_REFS) toast(`Maximum ${SHEET_MAX_REFS} images`);list.slice(0, SHEET_MAX_REFS - photos.length).forEach((f) => fileToList(f, setPhotos, "image"));@@ -220,7 +233,6 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldDatasetPhotos((xs) => (xs.some((x) => x.ref === url) ? xs : [{ ref: url, preview: url, kind: "image" as const, id: nanoid(8) }, ...xs].slice(0, SHEET_MAX_REFS)));}, []);const create = () => {- if (visitor) return;if (mode === "reference" && !photos.length) return toast("Upload at least 1 image");if (!body) return toast(mode === "describe" ? "Describe your character first" : "Wait for the uploads to finish");run.mutate(body, {@@ -237,9 +249,8 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldData</Suspense><TabFromLink param="mode" ids={MODE_IDS} onTab={setMode} /><PageHeader title="Character Sheet" description="Build your AI avatar: a consistent character for your videos, from a reference or defined from scratch.">- <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly />+ <EngineSwitch value={engine} onChange={setEngine} /></PageHeader>- {visitor && <SelfHostNote className="-mt-3 mb-6 max-w-2xl">Character Sheet isn't available here.</SelfHostNote>}<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]"><section className="min-w-0 space-y-4"><TabRow role="tablist" aria-label="How to build it" follow>@@ -271,12 +282,11 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldDataaddFiles(e.dataTransfer.files);}}onPaste={(e) => addFiles(e.clipboardData.files)}- className={cn("rounded-2xl border border-dashed transition-colors", over && !visitor && "border-primary bg-brand-faint")}+ className={cn("rounded-2xl border border-dashed transition-colors", over && "border-primary bg-brand-faint")}><buttontype="button"- onClick={() => fileInput.current?.click()}- disabled={visitor}+ onClick={() => askFirst() || fileInput.current?.click()}className="flex w-full flex-col items-center justify-center gap-2 rounded-2xl px-4 py-10 text-center outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset disabled:pointer-events-none disabled:opacity-50"><ImagePlus className="size-6 text-muted-foreground" />@@ -342,7 +352,7 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldData<div className="min-w-0 flex-1"><RunLine preview={body ? preview.data : undefined} loading={preview.isFetching} /></div>- <Button onClick={create} disabled={run.isPending || uploading || visitor}>+ <Button onClick={create} disabled={run.isPending || uploading}>{run.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} {run.isPending ? "Submitting..." : "Create AI Avatar"}</Button></div>diff --git a/src/components/fashion/fashion-view.tsx b/src/components/fashion/fashion-view.tsxindex 4187dc9e..ca84760b 100644--- a/src/components/fashion/fashion-view.tsx+++ b/src/components/fashion/fashion-view.tsx@@ -5,7 +5,6 @@ import Link from "next/link";import { useMemo, useState } from "react";import { toast } from "sonner";import { PageHeader, PageShell } from "@/components/page-shell";-import { SelfHostNote } from "@/components/self-host-note";import { Button } from "@/components/ui/button";import { EngineSwitch } from "@/components/studio/engine-switch";import type { SlotValue } from "@/components/studio/media-slot";@@ -15,7 +14,7 @@ import { useRun, useRunPreview } from "@/components/photodump/hooks";import { RunLine, Steps } from "@/components/photodump/steps";import { CharacterPicker } from "@/components/photodump/subject";import { UploadBox } from "@/components/photodump/upload-box";-import { useEngine, useGenerations, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useEngine, useGenerations, useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";import { FASHION, FASHION_MODELS, FASHION_START, FASHION_STEPS, fashionBlocker, fashionReducer, getTemplate, type FashionState } from "@/lib/catalog/packs";import type { Generation } from "@/lib/catalog/types";@@ -43,9 +42,6 @@ const MODEL_LABELS: Record<string, string> = {export function FashionView() {const [s, dispatch] = useStoredReducer<FashionState, Parameters<typeof fashionReducer>[1]>("fuobe.fashion", fashionReducer, FASHION_START);const [engine, setEngine] = useEngine();- // A shoot doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and the- // steps that run or upload are off. The templates stay open to browse.- const visitor = useLikelyVisitor();const [garment, setGarment] = useState<SlotValue | null>(null);const [pickedOutfit, setOutfitModel] = useState<string>();const [pickedSet, setSetModel] = useState<string>();@@ -87,21 +83,21 @@ export function FashionView() {return !!msg;};const startBase = () => {- if (visitor || block(fashionBlocker(s)) || !baseBody) return;+ if (block(fashionBlocker(s)) || !baseBody) return;base.mutate(baseBody, {onSuccess: (r) => dispatch({ type: "baseStarted", ids: r.items.map((g) => g.id) }),onError: (e) => toastError(e, "JobSet wasn't created"),});};const startOutfit = () => {- if (visitor || block(fashionBlocker(s, "outfit")) || !outfitBody) return;+ if (block(fashionBlocker(s, "outfit")) || !outfitBody) return;outfit.mutate(outfitBody, {onSuccess: (r) => dispatch({ type: "outfitStarted", ids: r.items.map((g) => g.id) }),onError: (e) => toastError(e, "JobSet wasn't created"),});};const startSet = () => {- if (visitor || block(fashionBlocker(s)) || !setBody) return;+ if (block(fashionBlocker(s)) || !setBody) return;photoset.mutate(setBody, {onSuccess: (r) => dispatch({ type: "photosetStarted", batchId: r.batchId ?? r.items[0]?.batchId ?? r.items[0]?.id }),onError: (e) => toastError(e, "JobSet wasn't created"),@@ -117,10 +113,9 @@ export function FashionView() {<RotateCcw /> Start over</Button>)}- <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly />+ <EngineSwitch value={engine} onChange={setEngine} /></div></PageHeader>- {visitor && <SelfHostNote className="-mt-3 mb-6 max-w-2xl">Fashion Factory isn't available here.</SelfHostNote>}<div className="mb-6"><Steps steps={LABELS} current={at} reached={reached} onGo={(i) => dispatch({ type: "goto", step: FASHION_STEPS[i] })} />@@ -176,7 +171,7 @@ export function FashionView() {</div><CharacterPicker value={s.elementId} onChange={(id) => dispatch({ type: "element", id })} /><Footer onBack={() => dispatch({ type: "back" })} line={<RunLine preview={baseBody ? preview.data : undefined} loading={preview.isFetching} />}>- <Button onClick={startBase} disabled={base.isPending || !!(baseBody && preview.data?.error) || visitor}>+ <Button onClick={startBase} disabled={base.isPending || !!(baseBody && preview.data?.error)}>{base.isPending ? <Loader2 className="animate-spin" /> : null} {base.isPending ? "Generating..." : "Next"}</Button></Footer>@@ -190,7 +185,7 @@ export function FashionView() {<h2 className="font-heading text-[26px] leading-tight">See instant variations of the selected character</h2><p className="text-[14px] text-muted-foreground">Pick the base shot to dress.</p></div>- <Button variant="outline" size="sm" onClick={startBase} disabled={base.isPending || busy(baseItems) || visitor}>+ <Button variant="outline" size="sm" onClick={startBase} disabled={base.isPending || busy(baseItems)}><RefreshCw /> Regenerate</Button></div>@@ -214,14 +209,11 @@ export function FashionView() {<img src={s.base} alt="Base shot" className="aspect-[3/4] w-full object-cover" />)}</div>- {/* A guest's or an account's outfit would be uploaded for a shoot that can't start here. */}- <div inert={visitor} className={cn(visitor && "opacity-50")}>- <UploadBox value={garmentValue} onChange={setGarmentValue} title="Upload outfit" hint="The product: a garment on a model or flat-lay" className="aspect-[3/4]" />- </div>+ <UploadBox value={garmentValue} onChange={setGarmentValue} title="Upload outfit" hint="The product: a garment on a model or flat-lay" className="aspect-[3/4]" /></div><ModelChips label="Outfit model" ids={outfitModels} value={outfitModel} onChange={setOutfitModel} /><RunLine preview={outfitBody && !s.outfit ? preview.data : undefined} loading={!s.outfit && preview.isFetching} />- <Button className="w-full" variant={s.outfitIds.length ? "outline" : "default"} onClick={startOutfit} disabled={outfit.isPending || visitor}>+ <Button className="w-full" variant={s.outfitIds.length ? "outline" : "default"} onClick={startOutfit} disabled={outfit.isPending}>{outfit.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} {outfit.isPending ? "Generating..." : "Generate outfit"}</Button></div>@@ -242,7 +234,7 @@ export function FashionView() {)}{s.outfit && <ModelChips label="Photoset model" ids={setModels} value={setModel} onChange={setSetModel} />}<Footer onBack={() => dispatch({ type: "back" })} line={s.outfit ? <RunLine preview={preview.data} loading={preview.isFetching} /> : undefined}>- <Button onClick={startSet} disabled={photoset.isPending || visitor}>+ <Button onClick={startSet} disabled={photoset.isPending}>{photoset.isPending ? <Loader2 className="animate-spin" /> : null} {photoset.isPending ? "Generating..." : "Get your photoset"}</Button></Footer>diff --git a/src/components/influencer/influencer-builder.tsx b/src/components/influencer/influencer-builder.tsxindex 32fc1f01..90fb4063 100644--- a/src/components/influencer/influencer-builder.tsx+++ b/src/components/influencer/influencer-builder.tsx@@ -9,14 +9,13 @@ import { PageHeader, PageShell } from "@/components/page-shell";import { useRun, useRunPreview, type RunPreview } from "@/components/photodump/hooks";import { ResultsGrid } from "@/components/photodump/results";import { UploadBox } from "@/components/photodump/upload-box";-import { SelfHostNote } from "@/components/self-host-note";import { EngineSwitch } from "@/components/studio/engine-switch";import { fileToList, type SlotValue } from "@/components/studio/media-slot";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Textarea } from "@/components/ui/textarea";-import { useEngine, useGenerations, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useAskBeforeUpload, useEngine, useGenerations, useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";import {categoriesFor,@@ -95,11 +94,11 @@ function useSettled<T>(value: T, ms = 250): T {return settled;}-function RunInfo({ preview, loading, blocker, visitor }: { preview?: RunPreview & { steps?: number }; loading: boolean; blocker: string | null; visitor: boolean }) {+function RunInfo({ preview, loading, blocker }: { preview?: RunPreview & { steps?: number }; loading: boolean; blocker: string | null }) {if (blocker) return <p className="text-[12.5px] text-destructive">{blocker}</p>;if (!preview) return <p className="h-5 text-[12.5px] text-muted-foreground">{loading ? "Pricing…" : ""}</p>;if (preview.error) return <p className="text-[12.5px] text-destructive">{preview.error}</p>;- const cost = visitor && (preview.demo || preview.costUsd === 0) ? "Not available here" : preview.demo ? "Placeholder · free" : preview.costUsd === 0 ? "Free · your GPU" : preview.costUsd == null ? "price unknown" : `≈ $${preview.costUsd.toFixed(2)}`;+ const cost = preview.demo ? "Placeholder · free" : preview.costUsd === 0 ? "Free · your GPU" : preview.costUsd == null ? "price unknown" : `≈ $${preview.costUsd.toFixed(2)}`;return (<div className="space-y-0.5 text-[12.5px] text-muted-foreground" aria-live="polite"><p>@@ -120,9 +119,9 @@ function RunInfo({ preview, loading, blocker, visitor }: { preview?: RunPreview*/export function InfluencerBuilder() {const [engine, setEngine] = useEngine();- // A sheet doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and the- // uploads and Generate are off. The builder itself stays open to play with.- const visitor = useLikelyVisitor();+ // A guest is asked to sign up before choosing photos, and an account with neither its own GPU nor its own key to+ // connect one.+ const askFirst = useAskBeforeUpload();const wide = useWide();const [state, setState] = useState<InfluencerState>(INFLUENCER_START);const [active, setActive] = useState("tier");@@ -188,12 +187,12 @@ export function InfluencerBuilder() {setMessage(null);};const addClothing = (files: Iterable<File>) => {+ if (askFirst()) return;const list = [...files].filter((f) => /^image\/(png|jpe?g|webp)$/.test(f.type));if (clothing.length + list.length > MAX_CLOTHING) toast("You can add up to three clothing references");list.slice(0, MAX_CLOTHING - clothing.length).forEach((f) => fileToList(f, setClothing, "image"));};const create = () => {- if (visitor) return;if (blocker) return toast(blocker);if (!body) return toast("Wait for the uploads to finish");run.mutate(body, {@@ -205,9 +204,8 @@ export function InfluencerBuilder() {return (<PageShell wide><PageHeader title="AI Influencer" description="Build an original character like in a game: pick a type, style it or hit Shuffle, then save the sheet.">- <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly />+ <EngineSwitch value={engine} onChange={setEngine} /></PageHeader>- {visitor && <SelfHostNote className="-mt-3 mb-6 max-w-2xl">AI Influencer isn't available here.</SelfHostNote>}<div className="grid gap-4 lg:grid-cols-[212px_minmax(0,1fr)] xl:grid-cols-[212px_minmax(0,1fr)_340px]">{/* The rail: Character type, then the categories this type shows. Phones scroll it sideways inside itself. */}@@ -322,16 +320,13 @@ export function InfluencerBuilder() {</div>{start !== "scratch" && (<div className="space-y-1.5">- {/* A guest's or an account's photo would be uploaded for a sheet that can't start here. */}- <div inert={visitor} className={cn(visitor && "opacity-50")}>- <UploadBox- value={photo}- onChange={setPhoto}- title={start === "face" ? "Your photo" : "Reference image"}- hint={start === "face" ? "A clear, front-facing photo of your face" : "A character whose look to start from"}- className="h-44"- />- </div>+ <UploadBox+ value={photo}+ onChange={setPhoto}+ title={start === "face" ? "Your photo" : "Reference image"}+ hint={start === "face" ? "A clear, front-facing photo of your face" : "A character whose look to start from"}+ className="h-44"+ /><p className="text-[12px] text-muted-foreground">{start === "face" ? "Your face goes on the character you build." : "The character starts from this look; your picks change it."} Shuffle keeps the gender, ethnicity and age{state.tier === "normal" ? ", skin and eye colour" : ""} the photo decides.</p>@@ -359,10 +354,9 @@ export function InfluencerBuilder() {{clothing.length < MAX_CLOTHING && (<buttontype="button"- onClick={() => clothingInput.current?.click()}+ onClick={() => askFirst() || clothingInput.current?.click()}onDragOver={(e) => e.preventDefault()}onDrop={(e) => (e.preventDefault(), addClothing(e.dataTransfer.files))}- disabled={visitor}className="grid aspect-square place-items-center rounded-lg border border-dashed text-muted-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"aria-label="Add clothing references">@@ -407,17 +401,11 @@ export function InfluencerBuilder() {</div>) : (<p className="text-[12.5px] text-muted-foreground">- {visitor ? "Fuobe Soul" : "Fuobe Soul on your GPU"}: drawn in its Realistic look. Add a photo or clothing and we dress them in it.- {!visitor && (- <>- {" "}- <span className="font-medium text-foreground">Free</span> on your GPU.- </>- )}+ Fuobe Soul on your GPU: drawn in its Realistic look. Add a photo or clothing and we dress them in it. <span className="font-medium text-foreground">Free</span> on your GPU.</p>)}- <RunInfo preview={blocker ? undefined : (settled ? preview.data : undefined)} loading={preview.isFetching} blocker={blocker} visitor={visitor} />- <Button className="w-full" onClick={create} disabled={run.isPending || uploading || visitor}>+ <RunInfo preview={blocker ? undefined : (settled ? preview.data : undefined)} loading={preview.isFetching} blocker={blocker} />+ <Button className="w-full" onClick={create} disabled={run.isPending || uploading}>{run.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} {run.isPending ? "Starting…" : "Generate character sheet"}</Button></div>diff --git a/src/components/nav/next-steps.tsx b/src/components/nav/next-steps.tsxindex 6296577a..0aec98c8 100644--- a/src/components/nav/next-steps.tsx+++ b/src/components/nav/next-steps.tsx@@ -14,12 +14,11 @@ 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). 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.+ * Studios that read a handed-over picture with their own small reader (`HandoffImage` below). Image to 3D and+ * Character Sheet run for an account too (on its own GPU or key).*/const ADAPTERS = { characterSheet: true, imageTo3d: true } as const;-const VISITOR_ADAPTERS = { imageTo3d: true } as const;+const VISITOR_ADAPTERS = ADAPTERS;/** The heading over the steps: "Keep going with this picture" (clip, sound, model). */export function keepGoingTitle(kind: string | undefined): string {diff --git a/src/components/photodump/hooks.ts b/src/components/photodump/hooks.tsindex 3dfaf7bd..b791cbbf 100644--- a/src/components/photodump/hooks.ts+++ b/src/components/photodump/hooks.ts@@ -1,9 +1,17 @@"use client";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { COMPUTER_KICK_EVENT, useElements, useSaveElement, useViewer } from "@/lib/api";+import type { StudioElement } from "@/lib/catalog/elements";import type { Generation } from "@/lib/catalog/types";import { responseError } from "@/lib/refusals";+/**+ * A run started: the tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for+ * them at once, as after a studio run.+ */+const kick = () => window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));+async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };if (!res.ok) throw responseError(res, body.error ?? "Something went wrong. Please try again.");@@ -48,6 +56,7 @@ export function useRun<B>(url: string) {return useMutation({mutationFn: (body: B) => post<{ batchId?: string; items: Generation[]; notes?: string[] }>(url, body),onSuccess: () => {+ kick();void qc.invalidateQueries({ queryKey: ["generations"] });void qc.invalidateQueries({ queryKey: ["library"] });},@@ -60,6 +69,7 @@ export function useRetryPhoto() {return useMutation({mutationFn: (id: string) => post<{ items: Generation[] }>("/api/photodump/retry", { id }),onSuccess: () => {+ kick();void qc.invalidateQueries({ queryKey: ["generations"] });void qc.invalidateQueries({ queryKey: ["library"] });},@@ -83,3 +93,49 @@ export function usePackActions() {});return { create, remove };}++/** An account's own character (src/server/photodump.ts PhotoCharacter). */+interface PhotoCharacter {+ id: string;+ name: string;+ references: string[];+ createdAt: number;+}++/** An account's character in the shape the pickers read: no handle to @mention (that's the owner's elements), no Soul ID. */+const asElement = (c: PhotoCharacter): StudioElement => ({ id: c.id, name: c.name, handle: c.name, kind: "character", description: null, references: c.references, loras: [], status: "ready", createdAt: c.createdAt });++/** Whether characters here are the owner's elements (@mentions, Soul IDs) or the visitor's own photo characters. */+export function useOwnsElements(): boolean {+ return useViewer().data?.owner === true;+}++/**+ * The characters Photodump and Fashion Factory pick from: the owner's saved elements, or an account's own characters+ * (none for a guest).+ */+export function usePhotoCharacters(): { data?: StudioElement[]; isLoading: boolean } {+ const owner = useOwnsElements();+ const elements = useElements();+ const own = useQuery({+ queryKey: ["photo-characters"],+ queryFn: async () => (await json<{ items: PhotoCharacter[] }>(await fetch("/api/photodump/characters"))).items.map(asElement),+ enabled: !owner,+ staleTime: 10_000,+ });+ return owner ? { data: elements.data, isLoading: elements.isLoading } : { data: own.data, isLoading: own.isLoading };+}++/** Save a character: an element for the owner, the account's own character otherwise. */+export function useSaveCharacter() {+ const owner = useOwnsElements();+ const element = useSaveElement();+ const qc = useQueryClient();+ const own = useMutation({+ mutationFn: async (b: { name: string; references: string[] }) => asElement(await post<PhotoCharacter>("/api/photodump/characters", b)),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["photo-characters"] }),+ });+ const save = (b: { name: string; references: string[] }, opts?: { onSuccess?: (el: StudioElement) => void; onError?: (e: Error) => void }) =>+ owner ? element.mutate({ ...b, kind: "character" }, opts) : own.mutate(b, opts);+ return { save, owner, isPending: element.isPending || own.isPending, data: owner ? element.data : own.data };+}diff --git a/src/components/photodump/photodump-view.tsx b/src/components/photodump/photodump-view.tsxindex f59fa6f8..a16fcaa2 100644--- a/src/components/photodump/photodump-view.tsx+++ b/src/components/photodump/photodump-view.tsx@@ -5,14 +5,13 @@ import Link from "next/link";import { useCallback, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { PageHeader, PageShell } from "@/components/page-shell";-import { SelfHostNote } from "@/components/self-host-note";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { EngineSwitch } from "@/components/studio/engine-switch";import { fileToList, type SlotValue } from "@/components/studio/media-slot";import { radioKeys, radioTab } from "@/components/studio/radio-keys";-import { useElements, useEngine, useGenerations, useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useAskBeforeUpload, useEngine, useGenerations, useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";import { customPack, DEFAULT_ASPECT, MAX_PACK_REFS, MAX_SELFIE_MB, PACKS, PHOTODUMP_ASPECTS, PHOTODUMP_MODELS, PHOTODUMP_SOUL, soulIdOf, type Pack } from "@/lib/catalog/packs";import type { Generation } from "@/lib/catalog/types";@@ -22,7 +21,7 @@ import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";import { linkTab, TabFromLink } from "@/components/nav/tab-from-link";import { toastError } from "@/lib/refusals";import { PackCover } from "./covers";-import { useRun, useRunPreview, usePackActions, useUserPacks } from "./hooks";+import { usePhotoCharacters, useRun, useRunPreview, usePackActions, useUserPacks } from "./hooks";import { DownloadAll, ResultsGrid, runState } from "./results";import { RunLine, Steps } from "./steps";import { CharacterPicker } from "./subject";@@ -156,11 +155,9 @@ function useRuns(feature: string) {/** /photodump: Photodump (trained characters) and Instadump (one selfie) — choose a pack, add your photo, get the set. */export function PhotodumpView() {const [engine, setEngine] = useEngine();- // A set doesn't run on an account's own GPU or key yet (only the studios' generations do), and a pack of your own is- // saved to the owner's library: said up front, and the upload and Generate are off. The packs stay open. Create pack- // shows once the owner is known (useIsOwner), so a visitor never sees it in the grid and then gone.- const visitor = useLikelyVisitor();- const isOwner = useIsOwner();+ // A pack of your own is made of photos you upload: a guest is asked to sign up first, and an account with neither its+ // own GPU nor its own key to connect one (as before any upload). An account's packs and runs are its own.+ const askFirst = useAskBeforeUpload();const [step, setStep] = useState(0);const [reached, setReached] = useState(0);const [tab, setTab] = useState<PackTab>("all");@@ -198,7 +195,7 @@ export function PhotodumpView() {const subjectReady = subjectMode === "selfie" ? !!selfie?.ref && !selfie.uploading : !!elementId;// The Model choice follows the engine: a pick the other engine had counts as Auto (one radio is always checked).- const elements = useElements();+ const elements = usePhotoCharacters();const character = subjectMode === "character" ? elements.data?.find((e) => e.id === elementId) : undefined;// Models switched off in Settings → Models & licences leave the choices (Auto picks among the ones on).const access = useModelAccess();@@ -221,7 +218,6 @@ export function PhotodumpView() {const product = "photo set";const generate = () => {- if (visitor) return;if (!body) return toast(subjectMode === "selfie" ? "Add your photo first" : "Pick a character first");run.mutate(body, {// The run line showed the model and its notes before Generate: no toast.@@ -237,9 +233,8 @@ export function PhotodumpView() {<PageShell wide><TabFromLink param="tab" ids={TAB_IDS} onTab={tabFromLink} /><PageHeader title="Photodump" description="A whole set of photos of you in one go, from one selfie or a saved character, in a pack of styles.">- <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly />+ <EngineSwitch value={engine} onChange={setEngine} /></PageHeader>- {visitor && <SelfHostNote className="-mt-3 mb-6 max-w-2xl">Photodump isn't available here.</SelfHostNote>}<div className="mb-6"><Steps steps={STEPS} current={step} reached={reached} onGo={go} /></div>@@ -270,18 +265,15 @@ export function PhotodumpView() {</label></div><div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">- {/* A pack of your own is saved to the studio's library, which is its owner's. */}- {isOwner && (- <button- type="button"- onClick={() => setCreatingPack(true)}- className="flex aspect-[3/4] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4 text-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"- >- <Plus className="size-6" />- <span className="text-[13.5px] font-medium">Create pack</span>- <span className="text-[12px]">From up to {MAX_PACK_REFS} reference photos</span>- </button>- )}+ <button+ type="button"+ onClick={() => askFirst() || setCreatingPack(true)}+ className="flex aspect-[3/4] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4 text-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ <Plus className="size-6" />+ <span className="text-[13.5px] font-medium">Create pack</span>+ <span className="text-[12px]">From up to {MAX_PACK_REFS} reference photos</span>+ </button>{shown.map((p) => {const sel = p.id === packId;return (@@ -312,7 +304,7 @@ export function PhotodumpView() {);})}</div>- {!shown.length && <p className="py-10 text-center text-[14px] text-muted-foreground">{tab === "mine" && !needle ? (visitor ? "Saving packs of your own isn't available here." : "No packs of your own yet — create one from your reference photos.") : `No packs match “${q}”`}</p>}+ {!shown.length && <p className="py-10 text-center text-[14px] text-muted-foreground">{tab === "mine" && !needle ? "No packs of your own yet — create one from your reference photos." : `No packs match “${q}”`}</p>}<div className="sticky bottom-[calc(var(--chrome-bottom)+0.75rem)] z-10 flex items-center justify-between gap-3 rounded-2xl border bg-background/95 p-3 shadow-normal backdrop-blur"><p className="min-w-0 truncate text-[13px]">{pack ? <><span className="font-medium">{pack.name}</span> · {pack.count} photos</> : <span className="text-muted-foreground">Pick a pack to continue</span>}</p><Button disabled={!pack} onClick={() => go(1)}>@@ -365,10 +357,7 @@ export function PhotodumpView() {</div>{subjectMode === "selfie" ? (<div className="space-y-2">- {/* A guest's or an account's selfie would be uploaded for a set that can't start here. */}- <div inert={visitor} className={cn(visitor && "opacity-50")}>- <UploadBox value={selfie} onChange={setSelfie} title="Add your photo" hint="Use a clear, well-lit photo for best results." maxMb={MAX_SELFIE_MB} className="aspect-[4/3] max-h-[420px] w-full" />- </div>+ <UploadBox value={selfie} onChange={setSelfie} title="Add your photo" hint="Use a clear, well-lit photo for best results." maxMb={MAX_SELFIE_MB} className="aspect-[4/3] max-h-[420px] w-full" /><p className="text-[12px] text-muted-foreground">A clear, sharp photo of your face works best.</p></div>) : (@@ -440,7 +429,7 @@ export function PhotodumpView() {<Button variant="outline" onClick={() => go(0)}><ArrowLeft /> Back</Button>- <Button className="flex-1" disabled={!body || run.isPending || !!preview.data?.error || visitor} onClick={generate}>+ <Button className="flex-1" disabled={!body || run.isPending || !!preview.data?.error} onClick={generate}>{run.isPending && <Loader2 className="animate-spin" />} Generate {pack.count}</Button></div>diff --git a/src/components/photodump/steps.tsx b/src/components/photodump/steps.tsxindex 263cff91..606a15f3 100644--- a/src/components/photodump/steps.tsx+++ b/src/components/photodump/steps.tsx@@ -1,7 +1,6 @@"use client";import { Check } from "lucide-react";-import { useLikelyVisitor } from "@/lib/api";import { cn } from "@/lib/utils";/** Numbered wizard steps; steps already reached can be revisited. */@@ -39,14 +38,13 @@ export function Steps({ steps, current, reached, onGo }: { steps: string[]; curr}/**- * "Runs on Nano Banana Pro · 10 photos · ≈ $1.50" (or the reason it can't run). A guest or an account reads "Self-hosted- * only" for a free run or a demo: these tools don't run on their own GPU yet, and their button is off.+ * "Runs on Nano Banana Pro · 10 photos · ≈ $1.50" (or the reason it can't run). An account's run is priced on its own GPU+ * or key ("Free · your GPU" on its GPU).*/export function RunLine({ preview, loading }: { preview?: { modelName?: string; count?: number; costUsd?: number | null; demo?: boolean; notes: string[]; error?: string }; loading?: boolean }) {- const visitor = useLikelyVisitor();if (!preview) return <p className="h-5 text-[12.5px] text-muted-foreground">{loading ? "Pricing…" : ""}</p>;if (preview.error) return <p className="text-[12.5px] text-destructive">{preview.error}</p>;- const cost = visitor && (preview.demo || preview.costUsd === 0) ? "Not available here" : preview.demo ? "Placeholder · free" : preview.costUsd === 0 ? "Free · your GPU" : preview.costUsd == null ? "price unknown" : `≈ $${preview.costUsd.toFixed(2)}`;+ const cost = preview.demo ? "Placeholder · free" : preview.costUsd === 0 ? "Free · your GPU" : preview.costUsd == null ? "price unknown" : `≈ $${preview.costUsd.toFixed(2)}`;return (<div className="space-y-0.5 text-[12.5px] text-muted-foreground"><p>diff --git a/src/components/photodump/subject.tsx b/src/components/photodump/subject.tsxindex d6922624..3d21b7f3 100644--- a/src/components/photodump/subject.tsx+++ b/src/components/photodump/subject.tsx@@ -9,11 +9,12 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, Dimport { Input } from "@/components/ui/input";import { Skeleton } from "@/components/ui/skeleton";import { fileToList, type SlotValue } from "@/components/studio/media-slot";-import { useElements, useLikelyVisitor, useSaveElement } from "@/lib/api";+import { useAskBeforeUpload } from "@/lib/api";import type { StudioElement } from "@/lib/catalog/elements";import { SOUL_ID_COPY, SOUL_ID_PHOTOS } from "@/lib/catalog/training";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";+import { usePhotoCharacters, useSaveCharacter } from "./hooks";/** What a character brings: a trained Soul ID (Fuobe Soul), an old Higgsfield one to retrain, or just photos. */export function identityLabel(el: StudioElement): string {@@ -37,7 +38,7 @@ export function QuickCharacter({ open, onOpenChange, onCreated }: { open: booleaconst [photos, setPhotos] = useState<SlotValue[]>([]);const [over, setOver] = useState(false);const fileInput = useRef<HTMLInputElement>(null);- const save = useSaveElement();+ const save = useSaveCharacter();const busy = photos.some((p) => p.uploading);const addFiles = (files: Iterable<File>) => [...files].filter((f) => /^image\/(png|jpe?g|webp)$/.test(f.type)).slice(0, MAX_PHOTOS - photos.length).forEach((f) => fileToList(f, setPhotos, "image"));return (@@ -101,11 +102,12 @@ export function QuickCharacter({ open, onOpenChange, onCreated }: { open: boolea<Buttondisabled={!name.trim() || !photos.length || busy || save.isPending}onClick={() =>- save.mutate(- { name: name.trim(), kind: "character", references: photos.map((p) => p.ref).filter(Boolean) },+ save.save(+ { name: name.trim(), references: photos.map((p) => p.ref).filter(Boolean) },{onSuccess: (el) => {- toast.success(`Saved as @${el.handle}`);+ // The owner's character is an element (@handle); an account's is its own, by name.+ toast.success(save.owner ? `Saved as @${el.handle}` : `Saved ${el.name}`);onCreated(el);setName("");setPhotos([]);@@ -126,28 +128,22 @@ export function QuickCharacter({ open, onOpenChange, onCreated }: { open: boolea/** Your characters as cards (photo, name, what identity they carry), plus "New character". */export function CharacterPicker({ value, onChange }: { value?: string; onChange: (id: string) => void }) {- const { data, isLoading } = useElements();+ // The owner's characters are its elements; an account's are its own (saved here or from a Character Sheet).+ const { data, isLoading } = usePhotoCharacters();const [creating, setCreating] = useState(false);- // A character is saved to the studio's library, which is its owner's: a guest or an account reads where characters- // are made, in the same place, instead of a form whose photos and save would be refused.- const visitor = useLikelyVisitor();+ // A guest is asked to sign up first, and an account with neither its own GPU nor its own key to connect one.+ const askFirst = useAskBeforeUpload();const characters = (data ?? []).filter((e) => e.kind === "character");return (<><div className="grid grid-cols-3 gap-2 sm:grid-cols-4 lg:grid-cols-6">- {visitor ? (- <p className="flex aspect-[3/4] flex-col items-center justify-center gap-1.5 rounded-xl border border-dashed p-3 text-center text-[12px] leading-snug text-pretty text-muted-foreground">- <UserRound className="size-5" /> Saving characters isn't available here- </p>- ) : (- <button- type="button"- onClick={() => setCreating(true)}- className="flex aspect-[3/4] flex-col items-center justify-center gap-1.5 rounded-xl border border-dashed text-[12.5px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"- >- <Plus className="size-5" /> New character- </button>- )}+ <button+ type="button"+ onClick={() => askFirst() || setCreating(true)}+ className="flex aspect-[3/4] flex-col items-center justify-center gap-1.5 rounded-xl border border-dashed text-[12.5px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ <Plus className="size-5" /> New character+ </button>{isLoading? Array.from({ length: 3 }, (_, i) => <Skeleton key={i} className="aspect-[3/4] rounded-xl" />): characters.map((el) => {@@ -183,7 +179,7 @@ export function CharacterPicker({ value, onChange }: { value?: string; onChange:);})}</div>- <QuickCharacter open={creating && !visitor} onOpenChange={setCreating} onCreated={(el) => onChange(el.id)} />+ <QuickCharacter open={creating} onOpenChange={setCreating} onCreated={(el) => onChange(el.id)} /></>);}diff --git a/src/components/photodump/upload-box.tsx b/src/components/photodump/upload-box.tsxindex 6a257d6c..7305fe93 100644--- a/src/components/photodump/upload-box.tsx+++ b/src/components/photodump/upload-box.tsx@@ -4,11 +4,13 @@ import { ImagePlus, Loader2, X } from "lucide-react";import { useRef, useState } from "react";import { toast } from "sonner";import { fileToSlot, type SlotValue } from "@/components/studio/media-slot";+import { useAskBeforeUpload } from "@/lib/api";import { cn } from "@/lib/utils";/*** One big image drop zone (a selfie, an outfit): click, drop or paste; shows the photo once added- * with a remove button. Files over `maxMb` are refused with a toast.+ * with a remove button. Files over `maxMb` are refused with a toast. A guest is asked to sign up first, and an account+ * with neither its own GPU nor its own key to connect one, before a file is chosen.*/export function UploadBox({value,@@ -27,8 +29,9 @@ export function UploadBox({}) {const input = useRef<HTMLInputElement>(null);const [over, setOver] = useState(false);+ const askFirst = useAskBeforeUpload();const take = (f: File | undefined) => {- if (!f) return;+ if (!f || askFirst()) return;if (!/^image\/(png|jpe?g|webp)$/.test(f.type)) return toast("PNG, JPG or WebP only");if (f.size > maxMb * 1024 * 1024) return toast(`That photo is over ${maxMb} MB — try a smaller one`);void fileToSlot(f, onChange, "image");@@ -63,7 +66,7 @@ export function UploadBox({</button></div>) : (- <button type="button" onClick={() => input.current?.click()} className="flex size-full flex-col items-center justify-center gap-2 p-6 text-center outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset">+ <button type="button" onClick={() => askFirst() || input.current?.click()} className="flex size-full flex-col items-center justify-center gap-2 p-6 text-center outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"><span className="grid size-11 place-items-center rounded-2xl bg-brand-faint text-brand-text"><ImagePlus className="size-5" /></span>diff --git a/src/lib/catalog/packs.ts b/src/lib/catalog/packs.tsindex e19f6bf9..6c7c0770 100644--- a/src/lib/catalog/packs.ts+++ b/src/lib/catalog/packs.ts@@ -350,7 +350,8 @@ export function customPack(p: CustomPackLike): Pack {/** Who the photos are of: a saved character (@element) or one uploaded selfie (Instadump, no training). */export type PhotoSubject =| { kind: "element"; handle: string; name: string; references: string[]; loras: ElementLora[] }- | { kind: "selfie"; url: string };+ /** One photo of the person (`name`: an account's own character, which starts from its first photo). */+ | { kind: "selfie"; url: string; name?: string };/** What the server knows about this install, for planning. */export interface PlanCaps {@@ -643,14 +644,17 @@ export function fashionModel(step: keyof typeof FASHION_MODELS, engine: Engine,const element = (s: PhotoSubject) => (s.kind === "element" ? `@${s.handle}` : "the person in image 1");/** Step 2: four base shots of the character in the template's set, 3:4. */-export function fashionBaseRequest(t: FashionTemplate, subject: Extract<PhotoSubject, { kind: "element" }>, engine: Engine, caps: PlanCaps): GenerationRequest {- if (!subject.references.length && !subject.loras.length) throw new Error(`Add a photo of ${subject.name} first`);+export function fashionBaseRequest(t: FashionTemplate, subject: PhotoSubject, engine: Engine, caps: PlanCaps): GenerationRequest {+ if (subject.kind === "element" && !subject.references.length && !subject.loras.length) throw new Error(`Add a photo of ${subject.name} first`);const { modelId } = photodumpModel(subject, engine, caps);+ // A saved character by @mention; one photo of them (an account's character) as image 1, its face kept.+ const photo = subject.kind === "selfie" ? subject.url : undefined;return {feature: "fashion",modelId,engine,- prompt: `A full-body fashion photo of ${element(subject)} in ${t.look}. A natural, relaxed model pose looking at the camera, simple fitted basics so the outfit can be changed later, photorealistic, sharp detail.`,+ prompt: `A full-body fashion photo of ${element(subject)} in ${t.look}. A natural, relaxed model pose looking at the camera, simple fitted basics so the outfit can be changed later, photorealistic, sharp detail.${photo ? ` ${KEEP_FACE}.` : ""}`,+ ...(photo && { inputs: { images: [photo] } }),params: { aspectRatio: "3:4", numOutputs: 4 },step: { label: "Base shots", index: 0, of: 3 },};diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 2787a77e..0dcfc2d1 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -67,6 +67,7 @@ const EMPTY: Record<string, unknown> = {"/api/shares": { items: [], signIn: true },"/api/photodump": { packs: [] },"/api/photodump/packs": { packs: [] },+ "/api/photodump/characters": { items: [] },"/api/generations/facets": NO_FACETS,// GPU pre-flight: a guest has no GPU (Connect your GPU), so no board and no chips."/api/gpu/readiness": { connected: false, reason: "guest" },@@ -296,6 +297,8 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [/^\/api\/swap-studio\/projects\/[^/]+\/(anchors|assemble|clips|masks|prepare|queue|sharpen|transcribe)$/,// Cinema Studio: a take in the account's own project, a retry and a 2K finish of one of its takes./^\/api\/cinema\/projects\/[^/]+\/(generate|items\/[^/]+\/(retry|finish))$/,+ // The photo apps: Photodump, Fashion Factory, Character Sheet, AI Influencer, and a retry of its own photo.+ /^\/api\/(photodump(\/(fashion|character|retry))?|influencer)$/,];/**@@ -315,6 +318,8 @@ export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [// no AI helper, GPU or key), and a ready film made as its own project (src/server/cinema.ts)./^\/api\/cinema\/projects(\/[^/]+(\/(director|folders|items|folders\/[^/]+|items\/[^/]+\/tiles))?)?$/,/^\/api\/starters\/cinema\.[^/]+$/,+ // Photodump and Fashion Factory: its own packs and its own characters (src/server/photodump.ts).+ /^\/api\/photodump\/(packs|characters)(\/[^/]+)?$/,];export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));diff --git a/src/lib/nav-model.ts b/src/lib/nav-model.tsindex 8d613762..18f22add 100644--- a/src/lib/nav-model.ts+++ b/src/lib/nav-model.ts@@ -734,8 +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["character-sheet"].ids,- ...STUDIO_SUBS.photodump.ids,]);/** The studio a feature lives under in the menus (Ads Studio under Marketing Studio). */diff --git a/src/server/influencer.ts b/src/server/influencer.tsindex 35d7f747..8e8566f7 100644--- a/src/server/influencer.ts+++ b/src/server/influencer.ts@@ -5,7 +5,7 @@ import { soulRecipe } from "@/lib/catalog/soul";import { cleanState, INFLUENCER_LOOK, INFLUENCER_OPEN_MODELS, planInfluencer, type InfluencerRun, type InfluencerStart } from "@/lib/influencer";import { createPipeline } from "./chains";import { createGenerations } from "./generations";-import { planCaps, previewRun, runEngine } from "./photodump";+import { ownSteps, planCaps, previewRun, runEngine } from "./photodump";/*** AI Influencer builder runs (/influencer): the pure plan (src/lib/influencer.ts) for the engine the@@ -53,6 +53,9 @@ export function previewInfluencer(body: InfluencerBody) {}}+/** Its steps, for an account's checks: the face or clothing pass waits for the sheet. */+export const influencerSteps = (body: InfluencerBody) => ownSteps(plan(body).steps.map((s) => ({ request: s.request, ...(s.after && { deps: 1 }) })));+export function createInfluencer(body: InfluencerBody) {const p = plan(body);const last = p.steps[p.steps.length - 1];diff --git a/src/server/photo-apps-http.ts b/src/server/photo-apps-http.tsnew file mode 100644index 00000000..86640076--- /dev/null+++ b/src/server/photo-apps-http.ts@@ -0,0 +1,82 @@+import "server-only";+import { z } from "zod";+import { asViewer, bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "./account-tool-run";+import { projectRefused, projectSavesLimited } from "./account-projects";+import { refusedRun } from "./connect-refusal";+import type { PlannedStep } from "./photodump";++/**+ * The photo apps' runs over HTTP: Photodump, Fashion Factory, Character Sheet, AI Influencer and a photo's retry. The+ * owner's run as always; an account's on its own GPU or its own fal.ai or Replicate key, with its own files, after the+ * checks a studio run gets (src/server/account-tool-run.ts); a guest signs up first. A price check (`?preview=1`) is+ * priced as the asker's run would go (priceAsRun), for everyone.+ */++/** A client's id for one press of Generate: a repeat gets the run the first one started (an account's own only). */+export const RequestId = z.string().trim().min(8).max(64).optional();++const isPreview = (request: Request) => !!new URL(request.url).searchParams.get("preview");++/**+ * Before the body is read: a guest's run gets the sign-up card, and an account's body over what a run may weigh a 413.+ * Null: read the body and go on.+ */+export function photoRunGate(request: Request): Response | null {+ if (isPreview(request)) return null;+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ return viewer.kind === "account" ? bodyTooBig(request) : null;+}++export interface PhotoRun<T> {+ /** The tool, for an account's repeat key and its run limit ("photodump"). */+ tool: string;+ /** Every file the body names: only the account's own (its uploads and results). */+ files: (string | null | undefined)[];+ /** The price check's answer. */+ preview: () => unknown;+ /** The steps it will create, planned only (called as the account). */+ steps: () => PlannedStep[];+ /** Creates the run: createGenerations / createPipeline. */+ start: () => T;+}++/** The run (or its price) as the asker's: see the header. */+export async function photoRun<T extends object>(request: Request, requestId: string | undefined, run: PhotoRun<T>): Promise<Response> {+ if (isPreview(request)) return priceAsRun(request, () => Response.json(run.preview()));+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "owner") {+ try {+ return Response.json(run.start(), { status: 201 });+ } catch (e) {+ return refusedRun(e, request);+ }+ }+ return onceForAccount(+ viewer.account,+ run.tool,+ requestId,+ () => runAccountTool(request, viewer.account, { tool: run.tool, files: run.files, plan: run.steps, start: run.start }),+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),+ );+}++/**+ * A change to an account's own packs or characters: a guest signs up first, an account within its saves a minute, as+ * its own work (asViewer). `fn` throws an AccountProjectError (its status) or an Error (400) to refuse.+ */+export function photoProjectChange(request: Request, fn: () => Response): Response {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "account") {+ const limited = projectSavesLimited(viewer.account.id);+ if (limited) return limited;+ }+ try {+ return asViewer(viewer, fn);+ } catch (e) {+ if (e instanceof Error && e.constructor === Error) return Response.json({ error: e.message }, { status: 400 });+ return projectRefused(e);+ }+}diff --git a/src/server/photodump.ts b/src/server/photodump.tsindex 60beb1df..7b1dc9b0 100644--- a/src/server/photodump.ts+++ b/src/server/photodump.ts@@ -19,11 +19,16 @@ import {type PlanCaps,} from "@/lib/catalog/packs";import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";+import { accountInputProblem } from "./account-inputs";+import { generationAccount } from "./account-library";+import { AccountProjectError, createAccountProject, deleteAccountProject, getAccountProject, listAccountProjects, projectRefsProblem } from "./account-projects";import { createPipeline } from "./chains";import { db } from "./db";import { getElement } from "./elements";import { createGenerations, currentRequest, getGeneration, pickOutput, previewGeneration } from "./generations";-import { trashGenerations } from "./library";+import { deleteForever, trashGenerations } from "./library";+import { ShortsError } from "./shorts";+import { tenant, tenantAccount } from "./tenant";import { engineMode } from "./settings";import { isOffered } from "./model-access";import { loadManifest } from "./providers/comfyui";@@ -32,8 +37,16 @@ import { loadManifest } from "./providers/comfyui";* Photodump / Instadump, Fashion Factory and Character Sheet runs: plan with the pure pack logic* (src/lib/catalog/packs.ts), validate every request, then create them as one batch so the feed and* the Library stack them under the run's name.+ *+ * A signed-in account (public sign-up) runs them inside asAccount (src/server/account-tool-run.ts): its packs and its+ * characters are its own projects (account-projects.ts, kinds PACK_KIND and CHARACTER_KIND), never the owner's packs or+ * elements, and its runs are its own generations on its own GPU or key. Which applies goes by tenantAccount().*/+/** An account's own packs and characters, in the account project store. */+export const PACK_KIND = "photodump-pack";+export const CHARACTER_KIND = "photo-character";+// ---------------------------------------------------------------------------// User packs (Instadump "Create pack")@@ -53,31 +66,101 @@ export interface UserPack {const toPack = (r: PackRow): UserPack => ({ id: r.id, name: r.name, refs: JSON.parse(r.refs_json) as string[], createdAt: r.created_at });+/** A guest has no packs, characters or runs of its own: nothing to list, nothing to find. */+const isGuest = () => tenant()?.kind === "guest";++/** Your own packs, newest first: the owner's, or an account's own (never the owner's or another account's). */export function listUserPacks(): UserPack[] {+ const account = tenantAccount();+ if (account) return listAccountProjects(account, PACK_KIND).flatMap((p) => getUserPack(p.id) ?? []);+ if (isGuest()) return [];return (db().prepare("SELECT * FROM photodump_packs ORDER BY created_at DESC").all() as PackRow[]).map(toPack);}export function getUserPack(id: string): UserPack | null {+ const account = tenantAccount();+ if (account) {+ const p = getAccountProject<{ refs: string[] }>(account, PACK_KIND, id);+ return p ? { id: p.id, name: p.name, refs: p.data.refs, createdAt: p.createdAt } : null;+ }+ if (isGuest()) return null;const r = db().prepare("SELECT * FROM photodump_packs WHERE id = ?").get(id) as PackRow | undefined;return r ? toPack(r) : null;}-export function createUserPack(input: { name: string; refs: string[] }): UserPack {+/** A pack's name and photos, checked (the same words for the owner and an account). */+function packInput(input: { name: string; refs: string[] }): { name: string; refs: string[] } {const name = input.name.trim();if (!name) throw new Error("Give the pack a name");if (name.length > 60) throw new Error("Keep the pack name under 60 characters");const refs = [...new Set(input.refs)];if (!refs.length) throw new Error("Upload your reference set up to 15 photos");if (refs.length > MAX_PACK_REFS) throw new Error(`A pack holds up to ${MAX_PACK_REFS} photos`);+ return { name, refs };+}++/** Only an account's own files (its uploads and results): another's, or the owner's, is refused with its status. */+function ownFiles(account: string, files: string[]): void {+ const problem = projectRefsProblem(account, { files });+ if (problem) throw new AccountProjectError(problem.error, problem.status);+}++export function createUserPack(input: { name: string; refs: string[] }): UserPack {+ const { name, refs } = packInput(input);+ const account = tenantAccount();+ if (account) {+ ownFiles(account, refs);+ const p = createAccountProject(account, PACK_KIND, { name, data: { refs }, summary: { count: refs.length } });+ return { id: p.id, name: p.name, refs, createdAt: p.createdAt };+ }const row: PackRow = { id: `user-${nanoid(8)}`, name, refs_json: JSON.stringify(refs), created_at: Date.now() };db().prepare("INSERT INTO photodump_packs (id, name, refs_json, created_at) VALUES (@id, @name, @refs_json, @created_at)").run(row);return toPack(row);}export function deleteUserPack(id: string): boolean {+ const account = tenantAccount();+ if (account) return deleteAccountProject(account, PACK_KIND, id);+ if (isGuest()) return false;return db().prepare("DELETE FROM photodump_packs WHERE id = ?").run(id).changes > 0;}+// ---------------------------------------------------------------------------+// An account's characters (the owner's are elements, src/server/elements.ts)++/** The photos an account's character keeps (Save as character takes a sheet, its views and the photos it came from). */+export const MAX_CHARACTER_PHOTOS = 20;++/** An account's character: a name and photos of one person. Its runs start from its first photo. */+export interface PhotoCharacter {+ id: string;+ name: string;+ references: string[];+ createdAt: number;+}++export function listPhotoCharacters(account: string): PhotoCharacter[] {+ return listAccountProjects(account, CHARACTER_KIND).flatMap((p) => getPhotoCharacter(account, p.id) ?? []);+}++export function getPhotoCharacter(account: string, id: string): PhotoCharacter | null {+ const p = getAccountProject<{ references: string[] }>(account, CHARACTER_KIND, id);+ return p ? { id: p.id, name: p.name, references: p.data.references, createdAt: p.createdAt } : null;+}++export function createPhotoCharacter(account: string, input: { name: string; references: string[] }): PhotoCharacter {+ const name = input.name.replace(/\s+/g, " ").trim();+ if (!name) throw new Error("Give the character a name");+ if (name.length > 60) throw new Error("Keep the name under 60 characters");+ const references = [...new Set(input.references)].slice(0, MAX_CHARACTER_PHOTOS);+ if (!references.length) throw new Error("Add a photo of them first");+ ownFiles(account, references);+ const p = createAccountProject(account, CHARACTER_KIND, { name, data: { references }, summary: { cover: references[0], photos: references.length } });+ return { id: p.id, name: p.name, references, createdAt: p.createdAt };+}++export const deletePhotoCharacter = (account: string, id: string): boolean => deleteAccountProject(account, CHARACTER_KIND, id);+// ---------------------------------------------------------------------------// Planning helpers@@ -94,6 +177,15 @@ export function runEngine(asked: Engine): Engine {export function subjectFor(input: { elementId?: string; selfie?: string }): PhotoSubject {if (input.elementId) {+ // An account's own character: its first photo goes in as the picture (an @mention reaches the owner's elements+ // only). A guest has none, and neither ever reaches the owner's.+ const account = tenantAccount();+ if (account) {+ const c = getPhotoCharacter(account, input.elementId);+ if (!c?.references.length) throw new Error("That character no longer exists");+ return { kind: "selfie", url: c.references[0], name: c.name };+ }+ if (isGuest()) throw new Error("That character no longer exists");const el = getElement(input.elementId);if (!el) throw new Error("That character no longer exists");if (el.kind !== "character") throw new Error(`${el.name} isn't a character`);@@ -161,6 +253,25 @@ export function createBatch(requests: GenerationRequest[], title: string): { batreturn { batchId, items };}+/** One step of a run as it will be created, for an account's checks: its request, and how many earlier steps it waits for. */+export interface PlannedStep {+ request: GenerationRequest;+ deps?: number;+}++/**+ * A run's steps for an account's checks (src/server/account-tool-run.ts plan): sized as they will be created, and+ * every file they read must be the account's own (a pack's or a character's photos too). Called inside asAccount.+ */+export function ownSteps(steps: PlannedStep[]): PlannedStep[] {+ const account = tenantAccount();+ for (const s of steps) {+ const problem = account ? accountInputProblem(s.request, account) : null;+ if (problem) throw new ShortsError(problem.error, problem.status);+ }+ return steps.map((s) => ({ ...s, request: fitted(s.request) }));+}+/** The steps a generation waited for (its chain), by id. */function dependsOn(id: string): string[] {const dep = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null } | undefined)?.depends_on;@@ -192,8 +303,27 @@ const RETRY_FEATURES = new Set(["photodump", "fashion", "character-sheet", "app:* retried as one job of its own share of photos.*/export function retryPhoto(id: string): Generation[] {+ return startRetry(planRetry(id));+}++/** How a photo runs again (planRetry), before anything is created. */+export type RetryPlan =+ /** Its earlier step failed too: both run again, chained as before. */+ | { kind: "both"; g: Generation; step: Generation; request: GenerationRequest }+ /** Its earlier steps finished but it never launched: it waits for them again. */+ | { kind: "wait"; g: Generation; request: GenerationRequest; deps: string[] }+ /** On its own: the same request (one job's share of photos). */+ | { kind: "again"; g: Generation; request: GenerationRequest };++/**+ * Check a photo can run again and plan how, creating nothing. An account retries only its own photos (another's, or+ * the owner's, reads as gone); a guest has none.+ */+export function planRetry(id: string): RetryPlan {const g = getGeneration(id);- if (!g) throw new Error("That photo is gone");+ const account = tenantAccount();+ const mine = !g ? false : account ? generationAccount(id) === account : !isGuest();+ if (!g || !mine) throw new ShortsError("That photo is gone", 404);if (!RETRY_FEATURES.has(g.feature)) throw new Error("This result isn't part of a photo run");if (g.status !== "failed" && g.status !== "canceled") throw new Error("Only a failed or canceled photo can be retried");// A photo made on a model Fuobe retired (Soul 2.0 for a Cast sheet, the AI Influencer app's model) runs again on the@@ -206,28 +336,45 @@ export function retryPhoto(id: string): Generation[] {if (before.some((d) => d?.status !== "succeeded")) {const step = before[0];if (deps.length !== 1 || !step || dependsOn(step.id).length || (step.status !== "failed" && step.status !== "canceled")) throw new Error("The step before it didn't finish — press Generate to run both again");- const { items } = createPipeline(- [- { key: "before", request: currentRequest(step.request).request },- { key: "photo", request, after: "before" },- ],- g.batchId ? { batchId: g.batchId } : {},- );- trashGenerations([step.id, id]);- return items;+ return { kind: "both", g, step, request };}// Its earlier steps finished, but it never launched (it failed or was canceled while it waited): it waits// for them again, so the runner hands it their outputs (the sheet goes in as image 1) and launches it.- if (deps.length && !gotChainInputs(g, before as Generation[])) {- const items = createGenerations(fitted(request), { ...(g.batchId && { batchId: g.batchId }), dependsOn: deps });- trashGenerations([id]);- return items;- }+ if (deps.length && !gotChainInputs(g, before as Generation[])) return { kind: "wait", g, request: fitted(request), deps };const req = fitted(request);const p = previewGeneration(req);const per = p.jobs > 1 ? Math.max(1, Math.round(p.outputs / p.jobs)) : undefined;- const items = createGenerations(per ? { ...req, params: { ...req.params, numOutputs: per } } : req, g.batchId ? { batchId: g.batchId } : {});- trashGenerations([id]);+ return { kind: "again", g, request: per ? { ...req, params: { ...req.params, numOutputs: per } } : req };+}++/** A retry's requests, for an account's checks: each one, and how many earlier steps it waits for. */+export function retrySteps(p: RetryPlan): { request: GenerationRequest; deps?: number }[] {+ if (p.kind === "both") return [{ request: currentRequest(p.step.request).request }, { request: p.request, deps: 1 }];+ if (p.kind === "wait") return [{ request: p.request, deps: p.deps.length }];+ return [{ request: p.request }];+}++/**+ * Run it again in its batch. The photo it replaces goes to the owner's Trash; an account has no Trash, so its own is+ * deleted for good.+ */+export function startRetry(p: RetryPlan): Generation[] {+ const { g } = p;+ const batch = g.batchId ? { batchId: g.batchId } : {};+ const drop = (list: string[]) => (tenantAccount() ? void deleteForever(list) : void trashGenerations(list));+ if (p.kind === "both") {+ const { items } = createPipeline(+ [+ { key: "before", request: currentRequest(p.step.request).request },+ { key: "photo", request: p.request, after: "before" },+ ],+ batch,+ );+ drop([p.step.id, g.id]);+ return items;+ }+ const items = p.kind === "wait" ? createGenerations(p.request, { ...batch, dependsOn: p.deps }) : createGenerations(p.request, batch);+ drop([g.id]);return items;}@@ -258,9 +405,12 @@ export function previewPhotodump(input: PhotodumpRun) {}}+/** A Photodump's steps, for an account's checks. */+export const photodumpSteps = (input: PhotodumpRun) => ownSteps(photodumpPlan(input).plan.requests.map((request) => ({ request })));+export function createPhotodump(input: PhotodumpRun) {const { pack, subject, plan } = photodumpPlan(input);- const who = subject.kind === "element" ? subject.name : "Selfie";+ const who = subject.kind === "element" ? subject.name : (subject.name ?? "Selfie");const { batchId, items } = createBatch(plan.requests, `${pack.name} · ${who}`);return { batchId, items, notes: plan.notes, modelId: plan.modelId };}@@ -279,7 +429,7 @@ function fashionRequests(input: FashionRun): { requests: GenerationRequest[]; ticonst engine = runEngine(input.engine);if (input.step === "base") {const subject = subjectFor({ elementId: input.elementId });- if (subject.kind !== "element") throw new Error("Pick or create a character first");+ if (subject.kind === "selfie" && !subject.name) throw new Error("Pick or create a character first");return { requests: [fashionBaseRequest(t, subject, engine, planCaps())], title: `${t.name} · ${subject.name}` };}// A model switched off in Settings → Models & licences (or Fuobe Try-On with its try-on LoRA off) moves on to the next.@@ -295,6 +445,9 @@ export function previewFashion(input: FashionRun) {}}+/** A Fashion Factory step's requests, for an account's checks. */+export const fashionSteps = (input: FashionRun) => ownSteps(fashionRequests(input).requests.map((request) => ({ request })));+export function createFashion(input: FashionRun) {const { requests, title } = fashionRequests(input);if (requests.length === 1) {@@ -359,6 +512,9 @@ export function previewSheet(input: SheetRun) {}}+/** A Character Sheet's request, for an account's checks. */+export const sheetSteps = (input: SheetRun) => ownSteps([{ request: { ...sheetRequest(input).request, title: "Character sheet" } }]);+export function createSheet(input: SheetRun) {const { request, notes } = sheetRequest(input);const items = createGenerations(fitted({ ...request, title: "Character sheet" }));diff --git a/tests/account-photo-apps.test.ts b/tests/account-photo-apps.test.tsnew file mode 100644index 00000000..afea47b1--- /dev/null+++ b/tests/account-photo-apps.test.ts@@ -0,0 +1,432 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++vi.setConfig({ testTimeout: 120_000 });+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++/**+ * Photodump, Fashion Factory, Character Sheet and AI Influencer for a signed-in account (public sign-up): every photo+ * runs on its own ComfyUI (a stand-in here) through the same generations every studio run makes, with only its own+ * files; its packs and characters are its own projects. A guest gets the sign-up card; another account's packs,+ * characters and photos, and the owner's, are never reached.+ */+const dir = tempDir("fuobe-account-photo-apps-");+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") or an AI helper: recorded, so a test sees 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 photodumpRoute = await import("@/app/api/photodump/route");+const fashionRoute = await import("@/app/api/photodump/fashion/route");+const sheetRoute = await import("@/app/api/photodump/character/route");+const retryRoute = await import("@/app/api/photodump/retry/route");+const packsRoute = await import("@/app/api/photodump/packs/route");+const packRoute = await import("@/app/api/photodump/packs/[id]/route");+const charactersRoute = await import("@/app/api/photodump/characters/route");+const characterRoute = await import("@/app/api/photodump/characters/[id]/route");+const influencerRoute = await import("@/app/api/influencer/route");+const influencerEstimate = await import("@/app/api/influencer/estimate/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 { PACKS, FASHION } = await import("@/lib/catalog/packs");+const { INFLUENCER_START } = await import("@/lib/influencer");+const { getGeneration } = await import("@/server/generations");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { clearAccountLoras } = await import("@/server/account-loras");+const { saveFile } = await import("@/server/storage");+const { runAsTenant } = await import("@/server/tenant");+const { ACCOUNT_LIMITS } = await import("@/server/account-files");+const store = await import("@/server/account-projects");+const { createElement } = await import("@/server/elements");+const { purgeAccount } = await import("@/server/account-sweep");+const { CHARACTER_KIND, PACK_KIND } = await import("@/server/photodump");++let fake: FakeComfy;+let a = "";+let b = "";+let c = "";+const cookies: Record<string, string> = {};+beforeAll(async () => {+ fake = await startFakeComfy({ loras: [], delayMs: 0, output: "image" });+ 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();+ for (const id of [a, b]) clearAccountLoras(id);+});++function json(url: string, method: string, body?: unknown, who?: string): Request {+ const text = body === undefined ? "" : 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] }) },+ ...(method !== "GET" && method !== "HEAD" && text && { body: text }),+ });+}+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) }) as never;++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, 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": "image/png", "x-file-name": name, "content-length": String(TINY_PNG.length) }, body: new Uint8Array(TINY_PNG) }));+ expect(r.status, await r.clone().text()).toBe(201);+ return ((await r.json()) as { url: string }).url;+}++/** Send a run; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */+async function run(send: () => Promise<Response>): Promise<Response> {+ let r = await send();+ for (let i = 0; i < 3 && r.status === 409; i++) {+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };+ if (j.code !== "comfy_missing_model" || !j.fix) break;+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix.items.map((x) => x.file)];+ for (const id of [a, b]) clearAccountLoras(id);+ r = await send();+ }+ return r;+}++interface Started {+ batchId?: string;+ items: { id: string }[];+}++/** Tick the runner until every one of these runs (and the steps they wait for) is done, or the time is up. */+async function settle(ids: string[], ms = 60_000): Promise<void> {+ const end = Date.now() + ms;+ for (;;) {+ await globalThis.__fuobeRunner?.tick();+ const batches = new Set(ids.map((id) => getGeneration(id, { includeDeleted: true })?.batchId).filter(Boolean));+ const all = [...ids, ...(db().prepare(`SELECT id FROM generations WHERE batch_id IN (${[...batches].map(() => "?").join(",") || "''"})`).all(...batches) as { id: string }[]).map((r) => r.id)];+ const busy = all.some((g) => ["queued", "running"].includes(getGeneration(g, { includeDeleted: true })?.status ?? ""));+ if (!busy || Date.now() > end) return;+ await new Promise((r) => setTimeout(r, 100));+ }+}++/** Every generation of the run's batch (or the items when they have none). */+function runOf(s: Started) {+ const batch = s.batchId ?? getGeneration(s.items[0].id)?.batchId;+ const ids = batch ? (db().prepare("SELECT id FROM generations WHERE batch_id = ? OR id = ?").all(batch, batch) as { id: string }[]).map((r) => r.id) : s.items.map((i) => i.id);+ return ids.map((id) => getGeneration(id, { includeDeleted: true })!);+}++/** Start, then expect every step to be the account's, on its ComfyUI, and finished; nothing at the install's ComfyUI. */+async function runsAsOwn(send: () => Promise<Response>, who: string, account: string) {+ fake.log.length = 0;+ fetched.length = 0;+ const r = await run(send);+ expect(r.status, await r.clone().text()).toBe(201);+ const started = (await r.json()) as Started;+ await settle(started.items.map((i) => i.id));+ const gens = runOf(started);+ expect(gens.length).toBeGreaterThan(0);+ for (const g of gens) {+ expect(g.request.account, g.id).toBe(account);+ expect(g.status, `${g.id} ${g.modelId} ${g.error ?? ""}`).toBe("succeeded");+ }+ expect(new Set(gens.map((g) => g.batchId ?? g.id)).size).toBe(1);+ // Every step went to its own ComfyUI; nothing reached the install's (or an AI helper).+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBeGreaterThanOrEqual(gens.length);+ expect(fetched.filter((u) => !u.endsWith("/system_stats"))).toEqual([]);+ // Its results are its own files, and they download for it alone.+ const out = gens[0].outputs[0].url;+ expect(out).toMatch(/^\/api\/files\//);+ expect(passed(viaProxy(out, "GET", who))).toBe(true);+ expect(viaProxy(out, "GET", who === "a" ? "b" : "a").status).toBe(403);+ return { started, gens, out };+}++const PACK = PACKS.find((p) => p.product === "photodump") ?? PACKS[0];+const TEMPLATE = FASHION[0];+const photodump = (extra: Record<string, unknown>) => ({ packId: PACK.id, engine: "open", aspectRatio: "3:4", ...extra });++const RUNS = ["/api/photodump", "/api/photodump/fashion", "/api/photodump/character", "/api/photodump/retry", "/api/influencer"] as const;++describe("the proxy opens the photo apps to accounts, and keeps the sign-up card for guests", () => {+ it("a guest gets the sign-up card on every run and change, and empty lists", async () => {+ for (const [method, p] of [...RUNS.map((r) => ["POST", r] as const), ["POST", "/api/photodump/packs"], ["DELETE", "/api/photodump/packs/p1"], ["POST", "/api/photodump/characters"], ["DELETE", "/api/photodump/characters/c1"]] as const) {+ const r = viaProxy(p, method);+ expect(r.status, `${method} ${p}`).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");+ expect((await r.json()).error).toBe(access.GUEST_RUN_MESSAGE);+ }+ expect(await viaProxy("/api/photodump/packs").json()).toEqual({ packs: [] });+ expect(await viaProxy("/api/photodump/characters").json()).toEqual({ items: [] });+ // Price checks stay open to everyone.+ for (const p of ["/api/photodump?preview=1", "/api/photodump/fashion?preview=1", "/api/photodump/character?preview=1", "/api/influencer?preview=1", "/api/influencer/estimate"]) expect(passed(viaProxy(p, "POST")), p).toBe(true);+ });++ it("an account with a GPU reaches every photo app route (the routes scope them)", () => {+ for (const [method, p] of [...RUNS.map((r) => ["POST", r] as const), ["GET", "/api/photodump/packs"], ["POST", "/api/photodump/packs"], ["DELETE", "/api/photodump/packs/p1"], ["GET", "/api/photodump/characters"], ["POST", "/api/photodump/characters"], ["DELETE", "/api/photodump/characters/c1"]] as const) {+ expect(passed(viaProxy(p, method, "a")), `${method} ${p}`).toBe(true);+ }+ });++ it("an account with neither a GPU nor a key is asked to connect one for a run", async () => {+ for (const p of RUNS) {+ const r = viaProxy(p, "POST", "c");+ expect(r.status, p).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBe("1");+ }+ });++ it("the routes refuse a guest themselves", async () => {+ for (const [name, r] of [+ ["photodump", () => photodumpRoute.POST(json("/api/photodump", "POST", photodump({ selfie: "/api/files/x.png" })))],+ ["fashion", () => fashionRoute.POST(json("/api/photodump/fashion", "POST", { step: "base", templateId: TEMPLATE.id, elementId: "e1", engine: "open" }))],+ ["sheet", () => sheetRoute.POST(json("/api/photodump/character", "POST", { mode: "describe", engine: "open", prompt: "a surfer" }))],+ ["retry", () => retryRoute.POST(json("/api/photodump/retry", "POST", { id: "g1" }))],+ ["influencer", () => influencerRoute.POST(json("/api/influencer", "POST", { engine: "open", state: INFLUENCER_START, start: "scratch" }))],+ ["pack", () => packsRoute.POST(json("/api/photodump/packs", "POST", { name: "x", refs: ["/api/files/x.png"] }))],+ ["character", () => charactersRoute.POST(json("/api/photodump/characters", "POST", { name: "x", references: ["/api/files/x.png"] }))],+ ] as const) {+ const res = await r();+ expect(res.status, name).toBe(401);+ expect(res.headers.get(access.GUEST_HEADER), name).toBe("1");+ }+ expect(await (await packsRoute.GET(json("/api/photodump/packs", "GET"))).json()).toEqual({ packs: [] });+ expect(await (await charactersRoute.GET(json("/api/photodump/characters", "GET"))).json()).toEqual({ items: [] });+ });+});++describe("an account runs every photo app on its own ComfyUI", () => {+ let selfie = "";+ let photoset = "";+ beforeAll(async () => {+ selfie = await upload("a", "selfie.png");+ });++ it("prices a Photodump for its own GPU, never as a demo, and a guest's on the open engine", async () => {+ const r = await photodumpRoute.POST(json("/api/photodump?preview=1", "POST", photodump({ selfie }), "a"));+ const p = (await r.json()) as { demo: boolean; costUsd: number; count: number; error?: string };+ expect(p.error).toBeUndefined();+ expect(p.demo).toBe(false);+ expect(p.costUsd).toBe(0);+ expect(p.count).toBe(PACK.count);+ const g = (await (await influencerEstimate.POST(json("/api/influencer/estimate", "POST", { engine: "open", state: INFLUENCER_START, start: "scratch" }))).json()) as { demo: boolean; error?: string };+ expect(g.error).toBeUndefined();+ expect(g.demo).toBe(false);+ });++ it("makes a Photodump from its own selfie: every photo its own, on its ComfyUI; a repeat id gets the same set", async () => {+ const send = () => photodumpRoute.POST(json("/api/photodump", "POST", photodump({ selfie, requestId: "photodump-request-1" }), "a"));+ const { started, gens } = await runsAsOwn(send, "a", a);+ expect(gens.length).toBe(PACK.count);+ const again = await send();+ expect(again.status).toBe(201);+ expect(((await again.json()) as Started).batchId).toBe(started.batchId);+ // Its History (its own runs) lists them; B's doesn't.+ const list = await import("@/app/api/generations/route");+ const mine = (await (await list.GET(json("/api/generations?features=photodump", "GET", undefined, "a"))).json()) as { items: { id: string }[] };+ expect(mine.items.length).toBe(PACK.count);+ const theirs = (await (await list.GET(json("/api/generations?features=photodump", "GET", undefined, "b"))).json()) as { items: { id: string }[] };+ expect(theirs.items).toEqual([]);+ });++ it("keeps its own packs: makes one from its photos, runs it, and nobody else sees or uses it", async () => {+ const ref = await upload("a", "pack-ref.png");+ const r = await packsRoute.POST(json("/api/photodump/packs", "POST", { name: "Beach", refs: [ref] }, "a"));+ expect(r.status, await r.clone().text()).toBe(201);+ const pack = (await r.json()) as { id: string };+ expect(store.getAccountProject(a, PACK_KIND, pack.id)).not.toBeNull();+ expect(((await (await packsRoute.GET(json("/api/photodump/packs", "GET", undefined, "a"))).json()) as { packs: { id: string }[] }).packs.map((p) => p.id)).toEqual([pack.id]);+ const { gens } = await runsAsOwn(() => photodumpRoute.POST(json("/api/photodump", "POST", photodump({ packId: pack.id, selfie }), "a")), "a", a);+ expect(gens.length).toBe(1);+ expect(gens[0].request.inputs?.images).toContain(ref);+ // B: not in its list, not deletable, not usable; A's photo can't go in B's pack.+ expect(await (await packsRoute.GET(json("/api/photodump/packs", "GET", undefined, "b"))).json()).toEqual({ packs: [] });+ expect((await packRoute.DELETE(json(`/api/photodump/packs/${pack.id}`, "DELETE", undefined, "b"), params({ id: pack.id }))).status).toBe(404);+ const bSelfie = await upload("b", "b.png");+ const use = await photodumpRoute.POST(json("/api/photodump", "POST", photodump({ packId: pack.id, selfie: bSelfie }), "b"));+ expect(use.status).toBe(422);+ expect((await use.json()).error).toBe("That pack no longer exists");+ const steal = await packsRoute.POST(json("/api/photodump/packs", "POST", { name: "Mine", refs: [ref] }, "b"));+ expect(steal.status).toBe(403);+ // A deletes its own.+ expect((await packRoute.DELETE(json(`/api/photodump/packs/${pack.id}`, "DELETE", undefined, "a"), params({ id: pack.id }))).status).toBe(204);+ expect(store.getAccountProject(a, PACK_KIND, pack.id)).toBeNull();+ });++ it("saves its own character and runs Fashion Factory end to end with it: base shots, outfit, photoset", async () => {+ const face = await upload("a", "face.png");+ const r = await charactersRoute.POST(json("/api/photodump/characters", "POST", { name: "Maya", references: [face] }, "a"));+ expect(r.status, await r.clone().text()).toBe(201);+ const character = (await r.json()) as { id: string; name: string };+ expect(((await (await charactersRoute.GET(json("/api/photodump/characters", "GET", undefined, "a"))).json()) as { items: { id: string }[] }).items.map((x) => x.id)).toEqual([character.id]);+ // Base shots: its character's photo goes in as image 1.+ const base = await runsAsOwn(() => fashionRoute.POST(json("/api/photodump/fashion", "POST", { step: "base", templateId: TEMPLATE.id, elementId: character.id, engine: "open" }, "a")), "a", a);+ expect(base.gens[0].request.inputs?.images).toEqual([face]);+ expect(base.gens[0].request.batchTitle).toContain("Maya");+ const garment = await upload("a", "garment.png");+ const outfit = await runsAsOwn(() => fashionRoute.POST(json("/api/photodump/fashion", "POST", { step: "outfit", templateId: TEMPLATE.id, base: base.out, garment, engine: "open" }, "a")), "a", a);+ const set = await runsAsOwn(() => fashionRoute.POST(json("/api/photodump/fashion", "POST", { step: "photoset", templateId: TEMPLATE.id, dressed: outfit.out, engine: "open" }, "a")), "a", a);+ photoset = set.out;+ // B can't use A's character, its results or delete it; the photoset is A's alone.+ const bChar = await fashionRoute.POST(json("/api/photodump/fashion", "POST", { step: "base", templateId: TEMPLATE.id, elementId: character.id, engine: "open" }, "b"));+ expect(bChar.status).toBe(422);+ expect((await bChar.json()).error).toBe("That character no longer exists");+ const bOutfit = await fashionRoute.POST(json("/api/photodump/fashion", "POST", { step: "photoset", templateId: TEMPLATE.id, dressed: photoset, engine: "open" }, "b"));+ expect(bOutfit.status).toBe(403);+ expect((await bOutfit.json()).code).toBe("input-not-yours");+ expect((await characterRoute.DELETE(json(`/api/photodump/characters/${character.id}`, "DELETE", undefined, "b"), params({ id: character.id }))).status).toBe(404);+ expect(await (await charactersRoute.GET(json("/api/photodump/characters", "GET", undefined, "b"))).json()).toEqual({ items: [] });+ // A's photo in B's character: refused.+ expect((await charactersRoute.POST(json("/api/photodump/characters", "POST", { name: "Not mine", references: [face] }, "b"))).status).toBe(403);+ expect(store.getAccountProject(a, CHARACTER_KIND, character.id)).not.toBeNull();+ });++ it("makes Character Sheets from its own photos, from scratch and from a description", async () => {+ const photo = await upload("a", "ref.png");+ await runsAsOwn(() => sheetRoute.POST(json("/api/photodump/character", "POST", { mode: "reference", engine: "open", images: [photo] }, "a")), "a", a);+ await runsAsOwn(() => sheetRoute.POST(json("/api/photodump/character", "POST", { mode: "cast", engine: "open", cast: { gender: "Female" } }, "a")), "a", a);+ await runsAsOwn(() => sheetRoute.POST(json("/api/photodump/character", "POST", { mode: "describe", engine: "open", prompt: "a surfer and photographer from Lisbon" }, "a")), "a", a);+ // Another's photo is refused before anything is made.+ const bRef = await sheetRoute.POST(json("/api/photodump/character", "POST", { mode: "reference", engine: "open", images: [photo] }, "b"));+ expect(bRef.status).toBe(403);+ });++ it("builds an AI Influencer sheet, and dresses it in its own face photo (two chained steps, both its own)", async () => {+ await runsAsOwn(() => influencerRoute.POST(json("/api/influencer", "POST", { engine: "open", state: INFLUENCER_START, start: "scratch" }, "a")), "a", a);+ const face = await upload("a", "influencer-face.png");+ const { gens } = await runsAsOwn(() => influencerRoute.POST(json("/api/influencer", "POST", { engine: "open", state: INFLUENCER_START, start: "face", photo: face }, "a")), "a", a);+ expect(gens.length).toBe(2);+ const bFace = await influencerRoute.POST(json("/api/influencer", "POST", { engine: "open", state: INFLUENCER_START, start: "face", photo: face }, "b"));+ expect(bFace.status).toBe(403);+ });++ it("retries its own failed photo on its GPU (the failed one is deleted for good); never another's or the owner's", async () => {+ const { gens } = await runsAsOwn(() => photodumpRoute.POST(json("/api/photodump", "POST", photodump({ selfie }), "a")), "a", a);+ const failed = gens[0];+ db().prepare("UPDATE generations SET status = 'failed' WHERE id = ?").run(failed.id);+ // B and the owner's photo: gone for A.+ expect((await retryRoute.POST(json("/api/photodump/retry", "POST", { id: failed.id }, "b"))).status).toBe(404);+ 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-photo', 'photodump', 'oss-qwen-image-21', 'open', 'comfyui', 'edit', 'image', 'failed', ?, '[]', ?, ?)")+ .run(JSON.stringify({ feature: "photodump", modelId: "oss-qwen-image-21", prompt: "owner" }), t, t);+ expect((await retryRoute.POST(json("/api/photodump/retry", "POST", { id: "owner-photo" }, "a"))).status).toBe(404);+ expect(getGeneration("owner-photo")?.status).toBe("failed");+ fake.log.length = 0;+ const r = await run(() => retryRoute.POST(json("/api/photodump/retry", "POST", { id: failed.id }, "a")));+ expect(r.status, await r.clone().text()).toBe(201);+ const items = ((await r.json()) as { items: { id: string }[] }).items;+ await settle(items.map((i) => i.id));+ const again = getGeneration(items[0].id)!;+ expect(again.request.account).toBe(a);+ expect(again.status).toBe("succeeded");+ expect(again.batchId).toBe(failed.batchId);+ expect(getGeneration(failed.id, { includeDeleted: true })).toBeFalsy();+ });++ it("never reaches the owner's packs or characters, and the owner's lists stay the owner's", async () => {+ const ownerRef = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "owner-ref.png" }).url;+ db().prepare("INSERT INTO photodump_packs (id, name, refs_json, created_at) VALUES ('user-owner01', 'Owner pack', ?, ?)").run(JSON.stringify([ownerRef]), Date.now());+ const el = createElement({ name: "Owner Star", kind: "character", references: [ownerRef] });+ const list = (await (await packsRoute.GET(json("/api/photodump/packs", "GET", undefined, "a"))).json()) as { packs: { id: string }[] };+ expect(list.packs.map((p) => p.id)).not.toContain("user-owner01");+ expect((await packRoute.DELETE(json("/api/photodump/packs/user-owner01", "DELETE", undefined, "a"), params({ id: "user-owner01" }))).status).toBe(404);+ const usePack = await photodumpRoute.POST(json("/api/photodump?preview=1", "POST", photodump({ packId: "user-owner01", selfie }), "a"));+ expect((await usePack.json()).error).toBe("That pack no longer exists");+ const useEl = await fashionRoute.POST(json("/api/photodump/fashion", "POST", { step: "base", templateId: TEMPLATE.id, elementId: el.id, engine: "open" }, "a"));+ expect(useEl.status).toBe(422);+ expect((await useEl.json()).error).toBe("That character no longer exists");+ // A guest's price check doesn't find them either.+ const guest = await photodumpRoute.POST(json("/api/photodump?preview=1", "POST", photodump({ elementId: el.id })));+ expect((await guest.json()).error).toBe("That character no longer exists");+ expect(db().prepare("SELECT name FROM photodump_packs WHERE id = 'user-owner01'").get()).toEqual({ name: "Owner pack" });+ // The owner's own list still has it, and none of the accounts' packs.+ const owner = (await (await packsRoute.GET(json("/api/photodump/packs", "GET", undefined, "owner"))).json()) as { packs: { id: string }[] };+ expect(owner.packs.map((p) => p.id)).toEqual(["user-owner01"]);+ expect(await (await charactersRoute.GET(json("/api/photodump/characters", "GET", undefined, "owner"))).json()).toEqual({ items: [] });+ });+});++describe("an account's limits", () => {+ it("asks an account with neither a GPU nor a key to connect one, before anything is made", async () => {+ 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;+ for (const send of [+ () => photodumpRoute.POST(json("/api/photodump", "POST", photodump({ selfie: own }), "c")),+ () => sheetRoute.POST(json("/api/photodump/character", "POST", { mode: "reference", engine: "open", images: [own] }, "c")),+ () => influencerRoute.POST(json("/api/influencer", "POST", { engine: "open", state: INFLUENCER_START, start: "scratch" }, "c")),+ ]) {+ const r = await send();+ expect(r.status).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await r.json()).code).toBe("connect-gpu");+ }+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);+ });++ it("keeps runs going at once, a run's weight, and how many packs it keeps", async () => {+ const selfie = await upload("a", "limits.png");+ 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 (?, 'photodump', 'oss-qwen-image-21', 'open', 'comfyui', 'edit', 'image', 'queued', ?, '[]', ?, ?)",+ );+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-photo-${i}`, JSON.stringify({ feature: "photodump", modelId: "oss-qwen-image-21", account: a }), now, now);+ const r = await photodumpRoute.POST(json("/api/photodump", "POST", photodump({ selfie }), "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-photo-%'").run();+ const big = new Request("http://localhost:3000/api/photodump", { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });+ expect((await photodumpRoute.POST(big)).status).toBe(413);+ for (let i = store.listAccountProjects(a, PACK_KIND).length; i < store.ACCOUNT_PROJECT_LIMITS.projects; i++) store.createAccountProject(a, PACK_KIND, { name: `filler ${i}`, data: { refs: [selfie] } });+ const full = await packsRoute.POST(json("/api/photodump/packs", "POST", { name: "One more", refs: [selfie] }, "a"));+ expect(full.status).toBe(409);+ });++ it("goes with the account", async () => {+ const pic = await upload("b", "gone.png");+ expect((await packsRoute.POST(json("/api/photodump/packs", "POST", { name: "B pack", refs: [pic] }, "b"))).status).toBe(201);+ expect((await charactersRoute.POST(json("/api/photodump/characters", "POST", { name: "B", references: [pic] }, "b"))).status).toBe(201);+ await purgeAccount(b);+ expect(store.listAccountProjects(b, PACK_KIND)).toEqual([]);+ expect(store.listAccountProjects(b, CHARACTER_KIND)).toEqual([]);+ });+});diff --git a/tests/e2e/photo-apps-accounts-live.mjs b/tests/e2e/photo-apps-accounts-live.mjsnew file mode 100644index 00000000..9cf717b8--- /dev/null+++ b/tests/e2e/photo-apps-accounts-live.mjs@@ -0,0 +1,162 @@+// Photodump, Fashion Factory, Character Sheet and AI Influencer for visitors (a studio with a password and public+// sign-up, fuobe.com by default), through their routes and in a browser at a phone's width and a desktop's. A guest:+// the sign-up card on every run and change, empty packs and characters, the price checks open, no "isn't available+// here" note, and the sign-up card when it creates a pack, a character or chooses a photo. A signed-in account (a+// throwaway one this script makes and deletes): its own empty packs and characters, the connect card on a run and on+// choosing a photo (it has neither a GPU nor a key), and Generate on.+// No run is started (that needs the account's own GPU or key).+// Usage: node tests/e2e/photo-apps-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(76)}${extra ? ` ${extra}` : ""}`);+ if (!ok) failures.push(label);+};++const RUNS = [+ ["/api/photodump", { packId: "nope", engine: "open", selfie: "/api/files/nope.png" }],+ ["/api/photodump/fashion", { step: "photoset", templateId: "nope", dressed: "/api/files/nope.png", engine: "open" }],+ ["/api/photodump/character", { mode: "describe", engine: "open", prompt: "a surfer" }],+ ["/api/photodump/retry", { id: "nope" }],+ ["/api/influencer", { engine: "open", state: { tier: "normal", picks: {}, locked: [] }, start: "scratch" }],+];++/** The route checks, as a guest (`req`: a context's request, signed out) or as the account (signed in). */+async function routes(req, who) {+ const send = (method, p, data) => req.fetch(`${app}${p}`, { method, headers: { origin: app, "content-type": "application/json" }, ...(data !== undefined && { data }) });+ const body = async (r) => r.json().catch(() => ({}));+ const packs = await send("GET", "/api/photodump/packs");+ check(`${who}: its packs are empty`, packs.status() === 200 && JSON.stringify(await body(packs)) === '{"packs":[]}', String(packs.status()));+ const chars = await send("GET", "/api/photodump/characters");+ check(`${who}: its characters are empty`, chars.status() === 200 && JSON.stringify(await body(chars)) === '{"items":[]}', String(chars.status()));+ for (const [p, data] of [+ ["/api/photodump/character?preview=1", { mode: "describe", engine: "open", prompt: "a surfer and photographer from Lisbon" }],+ ["/api/influencer/estimate", { engine: "open", state: { tier: "normal", picks: {}, locked: [] }, start: "scratch" }],+ ]) {+ const r = await send("POST", p, data);+ const e = await body(r);+ check(`${who}: the price check ${p} works, never as a demo`, r.status() === 200 && !e.error && e.demo === false, `${r.status()} ${JSON.stringify(e).slice(0, 90)}`);+ }+ for (const [p, data] of RUNS) {+ const r = await send("POST", p, data);+ const text = JSON.stringify(await body(r));+ const isntHere = /isn't available here/.test(text);+ if (who === "guest") check(`guest: POST ${p} asks to sign up`, r.status() === 401 && r.headers()["x-fuobe-guest"] === "1" && !isntHere, String(r.status()));+ else check(`account: POST ${p} asks to connect a GPU or key`, r.status() === 403 && r.headers()["x-fuobe-connect-gpu"] === "1" && !isntHere, `${r.status()} ${text.slice(0, 80)}`);+ }+ for (const [method, p, data] of [+ ["POST", "/api/photodump/packs", { name: "x", refs: ["/api/files/not-mine.png"] }],+ ["DELETE", "/api/photodump/packs/nope", undefined],+ ["POST", "/api/photodump/characters", { name: "x", references: ["/api/files/not-mine.png"] }],+ ["DELETE", "/api/photodump/characters/nope", undefined],+ ]) {+ const r = await send(method, p, data);+ if (who === "guest") check(`guest: ${method} ${p} asks to sign up`, r.status() === 401 && r.headers()["x-fuobe-guest"] === "1", String(r.status()));+ else check(`account: ${method} ${p} reaches its own (not its file / not found)`, r.status() === 403 || r.status() === 404, String(r.status()));+ }+}++const PAGES = [+ { path: "/photodump", note: "Photodump isn't available here", run: null, ask: { role: "button", name: /Create pack/ } },+ { path: "/fashion-factory", note: "Fashion Factory isn't available here", run: null, ask: null },+ { path: "/character-sheet", note: "Character Sheet isn't available here", run: /Create AI Avatar/, ask: { role: "button", name: /Drop images here/ } },+ { path: "/influencer", note: "AI Influencer isn't available here", run: /Generate character sheet/, ask: { role: "button", name: "Add clothing references" } },+];++async function look(page, who, width) {+ for (const p of PAGES) {+ const tag = `${who} ${width} ${p.path}`;+ await page.goto(`${app}${p.path}`, { waitUntil: "load", timeout: 60_000 });+ await page.waitForTimeout(2500);+ check(`${tag}: no "isn't available here" note`, (await page.getByText(p.note).count()) === 0 && (await page.getByText(/isn.t available here/).count()) === 0);+ check(`${tag}: no price says "Not available here"`, (await page.getByText("Not available here").count()) === 0);+ const wide = await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1);+ check(`${tag}: no sideways scroll`, wide);+ if (p.run) {+ const run = page.getByRole("button", { name: p.run });+ check(`${tag}: its run button is on`, (await run.count()) > 0 && (await run.first().evaluate((e) => !e.disabled)));+ }+ if (shots) await page.screenshot({ path: path.join(shots, `${p.path.slice(1)}-${who}-${width}.png`), fullPage: false });+ if (p.ask) {+ const b = page.getByRole(p.ask.role, { name: p.ask.name });+ check(`${tag}: ${String(p.ask.name)} is offered`, (await b.count()) > 0);+ if ((await b.count()) > 0) {+ await b.first().click();+ await page.waitForTimeout(1500);+ const card = who === "guest" ? /Create a free account/ : /Connect your GPU|your own files/;+ check(`${tag}: it opens the ${who === "guest" ? "sign-up" : "connect"} card`, (await page.getByText(card).count()) > 0);+ if (shots) await page.screenshot({ path: path.join(shots, `${p.path.slice(1)}-${who}-${width}-ask.png`) });+ await page.keyboard.press("Escape");+ await page.waitForTimeout(400);+ }+ }+ }+ // Fashion Factory's character step: New character asks first too.+ await page.goto(`${app}/fashion-factory`, { waitUntil: "load", timeout: 60_000 });+ await page.waitForTimeout(2000);+ await page.getByRole("radio").first().click();+ await page.getByRole("button", { name: /Continue/ }).click();+ await page.waitForTimeout(800);+ const nc = page.getByRole("button", { name: /New character/ });+ check(`${who} ${width} /fashion-factory: New character is offered`, (await nc.count()) > 0);+ check(`${who} ${width} /fashion-factory: no "Saving characters isn't available here"`, (await page.getByText(/Saving characters/).count()) === 0);+ if ((await nc.count()) > 0) {+ await nc.first().click();+ await page.waitForTimeout(1500);+ const card = who === "guest" ? /Create a free account/ : /Connect your GPU|your own files/;+ check(`${who} ${width} /fashion-factory: New character opens the ${who === "guest" ? "sign-up" : "connect"} card`, (await page.getByText(card).count()) > 0);+ if (shots) await page.screenshot({ path: path.join(shots, `fashion-factory-${who}-${width}-character.png`) });+ await page.keyboard.press("Escape");+ }+ // Leave the template step as it was for the next visit.+ await page.evaluate(() => {+ try {+ localStorage.removeItem("fuobe.fashion");+ } catch {}+ });+}++const browser = await launch();+const email = `photo-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();+ await routes(page.request, "guest");+ for (const width of [1440, 390]) {+ await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 });+ await look(page, "guest", width);+ }+ // A throwaway account (signed in in this browser), then the same checks.+ 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()));+ if (signedUp) {+ await routes(page.request, "account");+ for (const width of [1440, 390]) {+ await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 });+ await look(page, "account", width);+ }+ }+} 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()}`);+ check("deleted the throwaway account", del.status() === 204, String(del.status()));+ }+ await browser.close();+}+console.log(failures.length ? `${failures.length} failed` : "all ok");+process.exit(failures.length ? 1 : 0);diff --git a/tests/nav-nudges.test.ts b/tests/nav-nudges.test.tsindex 4f1c76c7..1da61b0e 100644--- a/tests/nav-nudges.test.ts+++ b/tests/nav-nudges.test.ts@@ -113,15 +113,12 @@ 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 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\b/);+ it("sends everyone to Character Sheet and Image to 3D (an account runs them on its own GPU or key)", () => {+ for (const visitor of [false, true]) {+ viewer.visitor = visitor;+ expect(hrefs(steps(person())).some((h) => h.startsWith("/character-sheet?image=")), String(visitor)).toBe(true);+ expect(hrefs(steps(product())).some((h) => h.startsWith("/image-to-3d?image=")), String(visitor)).toBe(true);}- 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.tsindex a557a84e..088e341a 100644--- a/tests/nav-subfeatures.test.ts+++ b/tests/nav-subfeatures.test.ts@@ -180,8 +180,11 @@ describe("who sees a studio's features", () => {expect(studioSubs("audio", "owner", "sheet").map((e) => e.id)).toContain("audio-split");// 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([]);+ // Character Sheet and Photodump run for accounts too (on their own GPU or key): their modes are linked for everyone.+ for (const kind of [...VISITORS, "owner" as const]) {+ expect(studioSubs("character-sheet", kind, "sheet").length, String(kind)).toBe(3);+ expect(studioSubs("photodump", kind, "sheet").map((e) => e.id), String(kind)).toEqual(["photodump-instadump"]);+ }// 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.tsindex e117fe07..b404c45a 100644--- a/tests/phone-nav.test.ts+++ b/tests/phone-nav.test.ts@@ -247,12 +247,12 @@ describe("the Studios sheet", () => {it("lists what a group's studios hold inside as pills under the tiles, by their tabs' names, as a visitor may run them", () => {const sell = at("/", () => sheet({ group: "sell" }));// Ads Studio is a tile of the group already: not a pill again.- expect(pills(sell)).toEqual(["Click to Ad", "Ad Multiplier"]);+ expect(pills(sell)).toEqual(["Click to Ad", "Ad Multiplier", "From a selfie"]);expect(words(sell)).toContain("Marketing Studio");const people = at("/", () => sheet({ group: "people" }));- expect(pills(people)).toEqual(["Motion transfer", "Character swap", "Object swap", "Restyle", "Insert", "From picture", "Finish"]);+ expect(pills(people)).toEqual(["From Reference", "Build from scratch", "From a description", "Motion transfer", "Character swap", "Object swap", "Restyle", "Insert", "From picture", "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", "Split soundtrack", "Remove dialogue"]) {+ for (const w of ["Split soundtrack", "Remove dialogue"]) {for (const g of LAUNCHER_GROUPS) expect(pills(at("/", () => sheet({ group: g.id }))), `${g.id}: ${w}`).not.toContain(w);}// Cinema Studio's Blockout is linked for everyone (a guest is offered a free account on a run).diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.tsindex 93dfadb4..3ed29383 100644--- a/tests/public-signup.test.ts+++ b/tests/public-signup.test.ts@@ -350,8 +350,10 @@ describe("accounts never see or change the owner's library", () => {const cookie = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;expect(passed(proxy(req("/api/influencer?preview=1", { method: "POST" })))).toBe(true);expect(passed(proxy(req("/api/influencer?preview=1", { method: "POST", cookie })))).toBe(true);- // Its run isn't one an account's GPU runs either: the account's own-gpu-tool, not the sign-up card.- expect(proxy(req("/api/influencer", { method: "POST" })).status).toBe(403);+ // Its run is open to accounts (on their own GPU or key): a guest gets the sign-up card.+ const guest = proxy(req("/api/influencer", { method: "POST" }));+ expect(guest.status).toBe(401);+ expect(guest.headers.get(access.GUEST_HEADER)).toBe("1");});});