Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Image studios: Photodump/Instadump, Fashion Factory, Character Sheet

Claudeef7877e24972
diff --git a/src/app/(studio)/character-sheet/page.tsx b/src/app/(studio)/character-sheet/page.tsx
new file mode 100644
index 00000000..6fd8dc8b
--- /dev/null
+++ b/src/app/(studio)/character-sheet/page.tsx
@@ -0,0 +1,23 @@
+import type { Metadata } from "next";
+import { CharacterSheetView } from "@/components/fashion/character-sheet";
+import { castDefaults, SOUL_CAST_FIELDS } from "@/lib/catalog/cinema";
+import type { CastFieldData } from "@/lib/catalog/packs";
+
+export const metadata: Metadata = { title: "Character Sheet" };
+
+/** Soul Cast's fields without their visibility functions (the page applies the same rules, castFieldVisible). */
+const FIELDS: CastFieldData[] = SOUL_CAST_FIELDS.map(({ key, label, tab, question, kind, options, default: d, format, manual }) => ({
+ key,
+ label,
+ tab,
+ kind,
+ options,
+ ...(question && { question }),
+ ...(d !== undefined && { default: d }),
+ ...(format && { format }),
+ ...(manual && { manual }),
+}));
+
+export default function Page() {
+ return <CharacterSheetView fields={FIELDS} defaults={castDefaults()} />;
+}
diff --git a/src/app/(studio)/fashion-factory/page.tsx b/src/app/(studio)/fashion-factory/page.tsx
new file mode 100644
index 00000000..080b5e2f
--- /dev/null
+++ b/src/app/(studio)/fashion-factory/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { FashionView } from "@/components/fashion/fashion-view";
+
+export const metadata: Metadata = { title: "Fashion Factory" };
+
+export default function Page() {
+ return <FashionView />;
+}
diff --git a/src/app/(studio)/photodump/page.tsx b/src/app/(studio)/photodump/page.tsx
new file mode 100644
index 00000000..48b8d0a5
--- /dev/null
+++ b/src/app/(studio)/photodump/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { PhotodumpView } from "@/components/photodump/photodump-view";
+
+export const metadata: Metadata = { title: "Photodump" };
+
+export default function Page() {
+ return <PhotodumpView />;
+}
diff --git a/src/components/fashion/character-sheet.tsx b/src/components/fashion/character-sheet.tsx
new file mode 100644
index 00000000..5a8dc776
--- /dev/null
+++ b/src/components/fashion/character-sheet.tsx
@@ -0,0 +1,288 @@
+"use client";
+
+import { AtSign, ImagePlus, Loader2, RotateCcw, Shuffle, Sparkles, UserRoundPlus, X } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import { PageHeader, PageShell } from "@/components/page-shell";
+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 { ResultsGrid } from "@/components/photodump/results";
+import { RunLine } from "@/components/photodump/steps";
+import { useEngine, useGenerations, useSaveElement } from "@/lib/api";
+import { castFieldVisible, castNameFor, randomCast, SHEET_MAX_REFS, type CastAnswers, type CastFieldData } from "@/lib/catalog/packs";
+import type { Generation } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+
+type Mode = "reference" | "cast" | "describe";
+const MODES: [Mode, string][] = [
+ ["reference", "From Reference"],
+ ["cast", "Build from scratch"],
+ ["describe", "From a description"],
+];
+
+const fmt = (f: CastFieldData, v: string | number) => (f.format ? f.format.replace("{v}", String(v)) : String(v));
+
+function CastForm({ fields, values, set }: { fields: CastFieldData[]; values: CastAnswers; set: (patch: CastAnswers) => void }) {
+ const tabs = useMemo(() => [...new Set(fields.map((f) => f.tab))], [fields]);
+ const [tab, setTab] = useState(tabs[0]);
+ return (
+ <div className="space-y-4">
+ <div role="tablist" aria-label="Soul Cast" className="scrollbar-none flex gap-1 overflow-x-auto">
+ {tabs.map((t) => (
+ <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={cn("h-8 shrink-0 rounded-full px-3 text-[12.5px] font-medium transition-colors", tab === t ? "bg-brand-faint text-brand-text" : "bg-secondary text-secondary-foreground hover:bg-accent")}>
+ {t}
+ </button>
+ ))}
+ </div>
+ {fields
+ .filter((f) => f.tab === tab && castFieldVisible(f.key, values))
+ .map((f) => {
+ const v = values[f.key];
+ const multi = f.kind === "multi";
+ const chosen = (o: string | number) => (multi ? Array.isArray(v) && v.includes(String(o)) : v === o);
+ return (
+ <div key={f.key} className="space-y-2">
+ <p className="text-[13px] font-medium">{f.question ?? f.label}</p>
+ <div role={multi ? "group" : "radiogroup"} aria-label={f.label} onKeyDown={multi ? undefined : radioKeys} className="flex flex-wrap gap-1.5">
+ {f.options.map((o) => {
+ const sel = chosen(o);
+ return (
+ <button
+ key={String(o)}
+ type="button"
+ role={multi ? undefined : "radio"}
+ aria-checked={multi ? undefined : sel}
+ aria-pressed={multi ? sel : undefined}
+ tabIndex={multi ? undefined : radioTab(sel || (v === undefined && o === f.options[0]))}
+ onClick={() => {
+ if (multi) {
+ const cur = Array.isArray(v) ? v : [];
+ set({ [f.key]: sel ? cur.filter((x) => x !== String(o)) : [...cur, String(o)] });
+ } else set({ [f.key]: sel && f.default === undefined ? undefined : o });
+ }}
+ className={cn("h-8 rounded-full border px-3 text-[12.5px] font-medium transition-colors", sel ? "border-primary bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent")}
+ >
+ {fmt(f, o)}
+ </button>
+ );
+ })}
+ </div>
+ {f.manual && (
+ <Input
+ value={String(values[`${f.key}_text`] ?? "")}
+ onChange={(e) => set({ [`${f.key}_text`]: e.target.value.slice(0, 300) })}
+ placeholder={`Or describe the ${f.label.toLowerCase()}`}
+ aria-label={`Describe the ${f.label.toLowerCase()}`}
+ className="h-8 max-w-md"
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+/** Save a finished sheet as a character (its sheet, views and the source photos as references). */
+function SaveCharacter({ item, extra, defaultName }: { item: Generation; extra: string[]; defaultName: string }) {
+ const [name, setName] = useState(defaultName);
+ const save = useSaveElement();
+ const router = useRouter();
+ const refs = [...item.outputs.filter((o) => o.kind === "image").map((o) => o.url), ...extra].slice(0, 20);
+ return (
+ <div className="flex flex-wrap items-end gap-2 rounded-2xl border bg-background p-3">
+ <label className="min-w-40 flex-1 space-y-1">
+ <span className="text-[12px] text-muted-foreground">Character name</span>
+ <Input value={name} onChange={(e) => setName(e.target.value)} maxLength={60} className="h-8" />
+ </label>
+ <Button
+ disabled={!name.trim() || save.isPending}
+ onClick={() =>
+ save.mutate(
+ { name: name.trim(), kind: "character", references: refs },
+ {
+ onSuccess: (el) =>
+ toast.success(`Saved as @${el.handle}`, { action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } }),
+ onError: (e) => toast.error((e as Error).message),
+ },
+ )
+ }
+ >
+ {save.isPending ? <Loader2 className="animate-spin" /> : <UserRoundPlus />} Save as character
+ </Button>
+ <p className="w-full text-[12px] text-muted-foreground">
+ Use it anywhere with <AtSign className="inline size-3" />
+ mentions, in <Link href="/photodump" className="text-brand-text hover:underline">Photodump</Link> or <Link href="/fashion-factory" className="text-brand-text hover:underline">Fashion Factory</Link> — or train a Soul ID / LoRA from its page.
+ </p>
+ </div>
+ );
+}
+
+/**
+ * /character-sheet ("Build your AI avatar"): a consistent character as a turnaround sheet — from 1–5
+ * reference photos, from a Soul Cast build, or from a description (the AI Influencer app) — saved as
+ * a character element.
+ */
+export function CharacterSheetView({ fields, defaults }: { fields: CastFieldData[]; defaults: CastAnswers }) {
+ const [engine, setEngine] = useEngine();
+ const [mode, setMode] = useState<Mode>("reference");
+ const [photos, setPhotos] = useState<SlotValue[]>([]);
+ const [details, setDetails] = useState("");
+ const [cast, setCast] = useState<CastAnswers>(defaults);
+ const [brief, setBrief] = useState("");
+ const [ids, setIds] = useState<string[]>([]);
+ const [over, setOver] = useState(false);
+ const run = useRun<Record<string, unknown>>("/api/photodump/character");
+ const { data } = useGenerations({ features: ["character-sheet", "app:app-ai-influencer"], limit: 60 });
+ const mine = useMemo(() => (data ?? []).filter((g) => ids.includes(g.id)), [data, ids]);
+ const latest = mine.find((g) => g.status === "succeeded");
+
+ const uploading = photos.some((p) => p.uploading);
+ const body =
+ mode === "reference"
+ ? photos.length && !uploading
+ ? { mode, engine, images: photos.map((p) => p.ref), details: details || undefined }
+ : null
+ : mode === "cast"
+ ? { mode, engine, cast, details: details || undefined }
+ : brief.trim()
+ ? { mode, engine, prompt: brief }
+ : null;
+ const preview = useRunPreview("/api/photodump/character", body);
+ const addFiles = (files: Iterable<File>) => {
+ 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"));
+ };
+ const create = () => {
+ 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, {
+ onSuccess: (r) => {
+ setIds((xs) => [...r.items.map((g) => g.id), ...xs]);
+ r.notes?.forEach((n) => toast(n));
+ },
+ onError: (e) => toast.error((e as Error).message || "Failed to create character sheet"),
+ });
+ };
+
+ return (
+ <PageShell wide>
+ <PageHeader title="Build your AI avatar" description="Create a consistent AI character for your videos — from reference or define your character's look from scratch.">
+ <EngineSwitch value={engine} onChange={setEngine} />
+ </PageHeader>
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
+ <section className="min-w-0 space-y-4">
+ <div role="tablist" aria-label="How to build it" className="scrollbar-none inline-flex max-w-full overflow-x-auto rounded-full bg-muted p-0.5">
+ {MODES.map(([id, label]) => (
+ <button key={id} role="tab" aria-selected={mode === id} onClick={() => setMode(id)} className={cn("h-8 shrink-0 rounded-full px-3.5 text-[13px] font-medium text-muted-foreground transition", mode === id && "bg-background text-foreground shadow-soft")}>
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {mode === "reference" && (
+ <div className="space-y-3">
+ <label
+ onDragOver={(e) => (e.preventDefault(), setOver(true))}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ addFiles(e.dataTransfer.files);
+ }}
+ className={cn("flex cursor-pointer flex-col items-center justify-center gap-2 rounded-2xl border border-dashed px-4 py-10 text-center transition-colors hover:bg-accent", over && "border-primary bg-brand-faint")}
+ >
+ <ImagePlus className="size-6 text-muted-foreground" />
+ <span className="text-[14px] font-medium">Drop images here</span>
+ <span className="text-[12.5px] text-muted-foreground">1–{SHEET_MAX_REFS} photos of one person · PNG, JPG or WebP</span>
+ <input type="file" accept="image/png,image/jpeg,image/webp" multiple hidden onChange={(e) => (addFiles(e.target.files ?? []), (e.target.value = ""))} />
+ </label>
+ {photos.length > 0 && (
+ <div className="grid grid-cols-5 gap-2">
+ {photos.map((p, i) => (
+ <div key={p.id ?? i} className="relative aspect-square overflow-hidden rounded-lg bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={p.preview} alt="" className="size-full object-cover" />
+ {p.uploading && (
+ <span className="absolute inset-0 grid place-items-center bg-background/60">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ )}
+ <button type="button" aria-label={`Remove photo ${i + 1}`} onClick={() => setPhotos((xs) => xs.filter((x) => x !== p))} className="absolute top-0.5 right-0.5 grid size-5 place-items-center rounded-full bg-foreground/80 text-background">
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ <Input value={details} onChange={(e) => setDetails(e.target.value.slice(0, 300))} placeholder="Optional details, e.g. “keep the denim jacket”" aria-label="Details" />
+ </div>
+ )}
+
+ {mode === "cast" && (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="mr-auto text-[13px] text-muted-foreground">Build your film&apos;s cast from scratch - genre, budget, appearance, and every detail in between.</p>
+ <Button variant="outline" size="sm" onClick={() => setCast((v) => randomCast(fields, v))}>
+ <Shuffle /> Randomize
+ </Button>
+ <Button variant="ghost" size="sm" onClick={() => setCast(defaults)}>
+ <RotateCcw /> Reset
+ </Button>
+ </div>
+ <CastForm fields={fields} values={cast} set={(patch) => setCast((v) => ({ ...v, ...patch }))} />
+ <Input value={details} onChange={(e) => setDetails(e.target.value.slice(0, 300))} placeholder="Distinguishing details (optional)" aria-label="Distinguishing details" />
+ </div>
+ )}
+
+ {mode === "describe" && (
+ <div className="space-y-2">
+ <Textarea value={brief} onChange={(e) => setBrief(e.target.value)} rows={5} placeholder="Who are they? e.g. “a 26-year-old surfer and photographer from Lisbon, freckles, sun-bleached curls”" aria-label="Describe your character" />
+ <p className="text-[12px] text-muted-foreground">Runs the AI Influencer app: Higgsfield&apos;s character-sheet model on the cloud, Z-Image Turbo on the open engine.</p>
+ </div>
+ )}
+
+ <div className="flex flex-wrap items-center gap-3 rounded-2xl border p-3">
+ <div className="min-w-0 flex-1">
+ <RunLine preview={body ? preview.data : undefined} loading={preview.isFetching} />
+ </div>
+ <Button onClick={create} disabled={run.isPending || uploading}>
+ {run.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} {run.isPending ? "Submitting..." : "Create AI Avatar"}
+ </Button>
+ </div>
+ </section>
+
+ <section className="min-w-0 space-y-3" aria-label="Your sheets">
+ {mine.length ? (
+ <>
+ <ResultsGrid items={mine} ratio={16 / 9} className="sm:grid-cols-1 lg:grid-cols-1" />
+ {latest && (
+ <SaveCharacter
+ key={latest.id}
+ item={latest}
+ extra={(latest.request.inputs?.images ?? []).filter((u) => u.startsWith("/api/files/"))}
+ defaultName={mode === "cast" ? castNameFor(cast) : "My character"}
+ />
+ )}
+ </>
+ ) : (
+ <div className="grid min-h-64 place-items-center rounded-2xl border border-dashed p-6 text-center">
+ <div className="max-w-sm space-y-1">
+ <p className="font-heading text-[22px]">Your character sheet appears here</p>
+ <p className="text-[13px] text-muted-foreground">Front, three-quarter, profile and back views of the same person — then save it as a character to use in any prompt with @.</p>
+ </div>
+ </div>
+ )}
+ </section>
+ </div>
+ </PageShell>
+ );
+}
diff --git a/src/components/fashion/fashion-view.tsx b/src/components/fashion/fashion-view.tsx
new file mode 100644
index 00000000..6522eebd
--- /dev/null
+++ b/src/components/fashion/fashion-view.tsx
@@ -0,0 +1,307 @@
+"use client";
+
+import { ArrowLeft, ArrowRight, Library, Loader2, RefreshCw, RotateCcw, Sparkles, X } from "lucide-react";
+import Link from "next/link";
+import { useMemo, useState, useSyncExternalStore } from "react";
+import { toast } from "sonner";
+import { PageHeader, PageShell } from "@/components/page-shell";
+import { Button } from "@/components/ui/button";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
+import { DownloadAll, ResultsGrid } from "@/components/photodump/results";
+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 } from "@/lib/api";
+import { FASHION, FASHION_START, FASHION_STEPS, fashionBlocker, fashionReducer, getTemplate, type FashionState } from "@/lib/catalog/packs";
+import type { Generation } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+import { useStoredReducer } from "./stored";
+import { TemplatePreview } from "./template-preview";
+
+const LABELS = ["Select presets", "Character", "Generation", "Clothing", "Photoset"];
+const BANNER_KEY = "fuobe.fashion.banner";
+const OUTFIT_MODELS = [
+ ["fashn-tryon", "FASHN Try-On"],
+ ["nano-banana-pro", "Nano Banana Pro"],
+] as const;
+
+const bannerListeners = new Set<() => void>();
+function readBanner(): boolean {
+ try {
+ return localStorage.getItem(BANNER_KEY) === "1";
+ } catch {
+ return true;
+ }
+}
+
+/** The first-visit banner: hidden on the server and until the browser says it hasn't been seen. */
+function useBannerSeen(): [boolean, () => void] {
+ const seen = useSyncExternalStore(
+ (cb) => {
+ bannerListeners.add(cb);
+ return () => bannerListeners.delete(cb);
+ },
+ readBanner,
+ () => true,
+ );
+ return [
+ seen,
+ () => {
+ try {
+ localStorage.setItem(BANNER_KEY, "1");
+ } catch {}
+ bannerListeners.forEach((l) => l());
+ },
+ ];
+}
+
+/** /fashion-factory: template → character → pick 1 of 4 base shots → outfit → photoset. */
+export function FashionView() {
+ const [s, dispatch] = useStoredReducer<FashionState, Parameters<typeof fashionReducer>[1]>("fuobe.fashion", fashionReducer, FASHION_START);
+ const [engine, setEngine] = useEngine();
+ const [garment, setGarment] = useState<SlotValue | null>(null);
+ const [outfitModel, setOutfitModel] = useState<string>("fashn-tryon");
+ const [bannerSeen, hideBanner] = useBannerSeen();
+ const { data } = useGenerations({ features: ["fashion"], limit: 200 });
+ const base = useRun<Record<string, unknown>>("/api/photodump/fashion");
+ const outfit = useRun<Record<string, unknown>>("/api/photodump/fashion");
+ const photoset = useRun<Record<string, unknown>>("/api/photodump/fashion");
+ const t = s.templateId ? getTemplate(s.templateId) : undefined;
+ const at = FASHION_STEPS.indexOf(s.step);
+ const reached = Math.max(at, s.photosetBatch ? 4 : s.outfitIds.length ? 3 : s.baseIds.length ? 2 : s.elementId ? 1 : 0);
+
+ const baseItems = useMemo(() => (data ?? []).filter((g) => s.baseIds.includes(g.id)), [data, s.baseIds]);
+ const outfitItems = useMemo(() => (data ?? []).filter((g) => s.outfitIds.includes(g.id)), [data, s.outfitIds]);
+ const setItems = useMemo(() => (data ?? []).filter((g) => !!s.photosetBatch && g.batchId === s.photosetBatch), [data, s.photosetBatch]);
+ const busy = (gs: Generation[]) => gs.some((g) => g.status === "queued" || g.status === "running");
+
+ // The garment shown: the one being uploaded here, else the saved one (after a reload).
+ const garmentValue: SlotValue | null = garment ?? (s.garment?.url ? { ref: s.garment.url, preview: s.garment.url, kind: "image" } : null);
+ const setGarmentValue = (v: SlotValue | null) => {
+ setGarment(v);
+ dispatch({ type: "garment", garment: v ? { url: v.ref, uploading: !!v.uploading } : undefined });
+ };
+
+ const baseBody = t && s.elementId ? { step: "base", templateId: t.id, elementId: s.elementId, engine } : null;
+ const outfitBody = t && s.base && s.garment && !s.garment.uploading ? { step: "outfit", templateId: t.id, base: s.base, garment: s.garment.url, engine, modelId: outfitModel } : null;
+ const setBody = t && s.outfit ? { step: "photoset", templateId: t.id, dressed: s.outfit, engine } : null;
+ const preview = useRunPreview("/api/photodump/fashion", s.step === "character" ? baseBody : s.step === "clothing" ? (s.outfit ? setBody : outfitBody) : null);
+
+ const block = (msg: string | null) => {
+ if (msg) toast(msg, { id: "fashion-blocker" });
+ return !!msg;
+ };
+ const startBase = () => {
+ if (block(fashionBlocker(s)) || !baseBody) return;
+ base.mutate(baseBody, {
+ onSuccess: (r) => dispatch({ type: "baseStarted", ids: r.items.map((g) => g.id) }),
+ onError: (e) => toast.error((e as Error).message || "JobSet wasn't created"),
+ });
+ };
+ const startOutfit = () => {
+ if (block(fashionBlocker(s, "outfit")) || !outfitBody) return;
+ outfit.mutate(outfitBody, {
+ onSuccess: (r) => dispatch({ type: "outfitStarted", ids: r.items.map((g) => g.id) }),
+ onError: (e) => toast.error((e as Error).message || "JobSet wasn't created"),
+ });
+ };
+ const startSet = () => {
+ 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) => toast.error((e as Error).message || "JobSet wasn't created"),
+ });
+ };
+
+ return (
+ <PageShell wide>
+ <PageHeader title="Fashion Factory" description="Next generation ultra-realistic fashion visuals: your product on a consistent character, in a full photoshoot.">
+ <div className="flex items-center gap-2">
+ {at > 0 && (
+ <Button variant="ghost" size="sm" onClick={() => (dispatch({ type: "reset" }), setGarment(null))}>
+ <RotateCcw /> Start over
+ </Button>
+ )}
+ <EngineSwitch value={engine} onChange={setEngine} />
+ </div>
+ </PageHeader>
+
+ {!bannerSeen && at === 0 && (
+ <div className="relative mb-6 overflow-hidden rounded-2xl border bg-gradient-to-br from-brand-faint to-background p-5">
+ <button type="button" onClick={hideBanner} aria-label="Hide" className="absolute top-3 right-3 grid size-7 place-items-center rounded-full hover:bg-accent">
+ <X className="size-4" />
+ </button>
+ <p className="font-heading text-[26px] leading-tight">Fashion factory</p>
+ <p className="mt-1 max-w-xl text-[14px] text-muted-foreground">Easily create branded photoshoots by combining your product with a consistent character, delivering unique and professional visuals every time.</p>
+ <Button className="mt-3" size="sm" onClick={hideBanner}>
+ Select template
+ </Button>
+ </div>
+ )}
+
+ <div className="mb-6">
+ <Steps steps={LABELS} current={at} reached={reached} onGo={(i) => dispatch({ type: "goto", step: FASHION_STEPS[i] })} />
+ </div>
+
+ {s.step === "template" && (
+ <section aria-label="Select presets" className="space-y-4">
+ <div>
+ <h2 className="font-heading text-[26px] leading-tight">Select presets</h2>
+ <p className="text-[14px] text-muted-foreground">Choose a template or aesthetic for the photo set</p>
+ </div>
+ <div role="radiogroup" aria-label="Templates" className="grid grid-cols-2 gap-3 lg:grid-cols-3">
+ {FASHION.map((x) => {
+ const sel = x.id === s.templateId;
+ return (
+ <div key={x.id} className="min-w-0">
+ <div
+ onClick={() => dispatch({ type: "template", id: x.id })}
+ className={cn("relative cursor-pointer overflow-hidden rounded-xl ring-offset-2 ring-offset-background", sel && "ring-3 ring-primary")}
+ >
+ <TemplatePreview t={x} className="aspect-[6/7]" />
+ </div>
+ <button
+ type="button"
+ role="radio"
+ aria-checked={sel}
+ onClick={() => dispatch({ type: "template", id: x.id })}
+ className="mt-1.5 block w-full rounded px-0.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <span className="block text-[13px] font-semibold tracking-wide uppercase">{x.name}</span>
+ <span className="block text-[12px] text-muted-foreground">
+ {x.shots} shots · {x.description}
+ </span>
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ <div className="sticky bottom-3 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]">{t ? <span className="font-medium">{t.name}</span> : <span className="text-muted-foreground">Pick a template</span>}</p>
+ <Button aria-disabled={!t} className={cn(!t && "opacity-50")} onClick={() => !block(fashionBlocker(s)) && dispatch({ type: "next" })}>
+ Continue <ArrowRight />
+ </Button>
+ </div>
+ </section>
+ )}
+
+ {s.step === "character" && t && (
+ <section aria-label="Character" className="space-y-4">
+ <div>
+ <h2 className="font-heading text-[26px] leading-tight">Pick your character</h2>
+ <p className="text-[14px] text-muted-foreground">Select or create the character who wears your product. Next makes 4 base shots in the {t.name} set at 3:4.</p>
+ </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)}>
+ {base.isPending ? <Loader2 className="animate-spin" /> : null} {base.isPending ? "Generating..." : "Next"}
+ </Button>
+ </Footer>
+ </section>
+ )}
+
+ {s.step === "generation" && t && (
+ <section aria-label="Generation" className="space-y-4">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <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)}>
+ <RefreshCw /> Regenerate
+ </Button>
+ </div>
+ <ResultsGrid items={baseItems} picked={s.base} onPick={(url) => dispatch({ type: "pickBase", url })} />
+ <Footer onBack={() => dispatch({ type: "back" })}>
+ <Button onClick={() => !block(fashionBlocker(s)) && dispatch({ type: "next" })}>
+ Next <ArrowRight />
+ </Button>
+ </Footer>
+ </section>
+ )}
+
+ {s.step === "clothing" && t && (
+ <section aria-label="Clothing" className="grid gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
+ <div className="space-y-3">
+ <h2 className="font-heading text-[26px] leading-tight">Upload outfit</h2>
+ <div className="grid grid-cols-2 gap-2">
+ <div className="overflow-hidden rounded-xl bg-muted">
+ {s.base && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={s.base} alt="Base shot" className="aspect-[3/4] w-full object-cover" />
+ )}
+ </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>
+ {engine === "cloud" && (
+ <div role="radiogroup" aria-label="Outfit model" onKeyDown={radioKeys} className="flex flex-wrap gap-1">
+ {OUTFIT_MODELS.map(([id, label]) => (
+ <button key={id} role="radio" aria-checked={outfitModel === id} tabIndex={radioTab(outfitModel === id)} onClick={() => setOutfitModel(id)} className={cn("h-8 rounded-full border px-2.5 text-[12.5px] font-medium transition-colors", outfitModel === id ? "border-primary bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent")}>
+ {label}
+ </button>
+ ))}
+ </div>
+ )}
+ <RunLine preview={outfitBody && !s.outfit ? preview.data : undefined} loading={preview.isFetching} />
+ <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>
+ <div className="min-w-0 space-y-3">
+ {s.outfitIds.length ? (
+ <>
+ <p className="text-[14px] text-muted-foreground">Select a result to generate your photoset from. Edit your outfit or continue</p>
+ <ResultsGrid items={outfitItems} picked={s.outfit} onPick={(url) => dispatch({ type: "pickOutfit", url })} className="lg:grid-cols-3" />
+ </>
+ ) : (
+ <div className="grid h-full min-h-48 place-items-center rounded-2xl border border-dashed p-6 text-center text-[13px] text-muted-foreground">Upload the outfit, then Generate outfit to dress your base shot.</div>
+ )}
+ <Footer onBack={() => dispatch({ type: "back" })} line={s.outfit ? <RunLine preview={preview.data} loading={preview.isFetching} /> : undefined}>
+ <Button onClick={startSet} disabled={photoset.isPending}>
+ {photoset.isPending ? <Loader2 className="animate-spin" /> : null} {photoset.isPending ? "Generating..." : "Get your photoset"}
+ </Button>
+ </Footer>
+ </div>
+ </section>
+ )}
+
+ {s.step === "photoset" && t && (
+ <section aria-label="Photoset" className="space-y-4">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <h2 className="font-heading text-[26px] leading-tight">Get your photoset</h2>
+ <p className="text-[14px] text-muted-foreground">{busy(setItems) ? `Shooting ${setItems.length} photos in the ${t.name} set…` : `${t.name} · ${setItems.length} photos`}</p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <DownloadAll items={setItems} />
+ <Button variant="outline" size="sm" className="h-8" onClick={() => dispatch({ type: "goto", step: "clothing" })}>
+ <ArrowLeft /> Edit outfit
+ </Button>
+ <Button asChild variant="outline" size="sm" className="h-8">
+ <Link href="/library">
+ <Library /> Go to Library
+ </Link>
+ </Button>
+ </div>
+ </div>
+ <ResultsGrid items={setItems} />
+ </section>
+ )}
+ </PageShell>
+ );
+}
+
+function Footer({ onBack, line, children }: { onBack: () => void; line?: React.ReactNode; children: React.ReactNode }) {
+ return (
+ <div className="sticky bottom-3 z-10 flex flex-wrap items-center justify-between gap-3 rounded-2xl border bg-background/95 p-3 shadow-normal backdrop-blur">
+ <Button variant="outline" onClick={onBack}>
+ <ArrowLeft /> Back
+ </Button>
+ <div className="min-w-0 flex-1">{line}</div>
+ {children}
+ </div>
+ );
+}
diff --git a/src/components/fashion/stored.ts b/src/components/fashion/stored.ts
new file mode 100644
index 00000000..d6950e37
--- /dev/null
+++ b/src/components/fashion/stored.ts
@@ -0,0 +1,66 @@
+"use client";
+
+import { useCallback, useSyncExternalStore } from "react";
+
+/**
+ * A small localStorage-backed value that survives reloads (a wizard's progress). The server and the
+ * first client render see `initial`, so hydration matches; the saved value arrives right after.
+ */
+const listeners = new Map<string, Set<() => void>>();
+const cache = new Map<string, { raw: string | null; value: unknown }>();
+/** Values that couldn't be saved (private mode, full storage) live here for this page's life. */
+const memory = new Map<string, unknown>();
+
+function read<T>(key: string, initial: T): T {
+ if (memory.has(key)) return memory.get(key) as T;
+ try {
+ const raw = localStorage.getItem(key);
+ const hit = cache.get(key);
+ if (hit && hit.raw === raw) return hit.value as T;
+ const value = raw ? ({ ...initial, ...(JSON.parse(raw) as T) } as T) : initial;
+ cache.set(key, { raw, value });
+ return value;
+ } catch {
+ return initial;
+ }
+}
+
+function write<T>(key: string, value: T) {
+ try {
+ localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ // Private mode or full storage: the state just won't survive a reload.
+ memory.set(key, value);
+ }
+ listeners.get(key)?.forEach((l) => l());
+}
+
+export function useStoredReducer<S, A>(key: string, reducer: (s: S, a: A) => S, initial: S): [S, (a: A) => void] {
+ const subscribe = useCallback(
+ (cb: () => void) => {
+ const set = listeners.get(key) ?? new Set();
+ set.add(cb);
+ listeners.set(key, set);
+ const onStorage = (e: StorageEvent) => e.key === key && cb();
+ window.addEventListener("storage", onStorage);
+ return () => {
+ set.delete(cb);
+ window.removeEventListener("storage", onStorage);
+ };
+ },
+ [key],
+ );
+ const state = useSyncExternalStore(
+ subscribe,
+ () => read(key, initial),
+ () => initial,
+ );
+ const dispatch = useCallback(
+ (a: A) => {
+ const next = reducer(read(key, initial), a);
+ write(key, next);
+ },
+ [key, reducer, initial],
+ );
+ return [state, dispatch];
+}
diff --git a/src/components/fashion/template-preview.tsx b/src/components/fashion/template-preview.tsx
new file mode 100644
index 00000000..57b5b023
--- /dev/null
+++ b/src/components/fashion/template-preview.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { ChevronLeft, ChevronRight } from "lucide-react";
+import { useState } from "react";
+import type { FashionTemplate } from "@/lib/catalog/packs";
+import { cn } from "@/lib/utils";
+
+/** A fashion figure (long coat, legs, head) as one path in a 60×70 box; `pose` shifts the stance. */
+function Figure({ x, y, s, pose = 0, fill }: { x: number; y: number; s: number; pose?: number; fill: string }) {
+ const lean = pose * 2;
+ return (
+ <g transform={`translate(${x} ${y}) scale(${s})`}>
+ <circle cx={lean * 0.4} cy={-29} r={3.6} fill={fill} />
+ <path
+ d={`M${-5 + lean * 0.3} -24 Q0 -26 ${5 + lean * 0.3} -24 L${7 + lean} -6 L${3.5 + lean} -6 L${3 + pose * 3} 14 L${1 + pose * 3} 14 L0 -2 L-1 14 L-3 14 L${-3.5 + lean * 0.2} -6 L${-7 + lean * 0.2} -6 Z`}
+ fill={fill}
+ />
+ </g>
+ );
+}
+
+const SCENES: Record<string, (slide: number) => React.ReactNode> = {
+ "ultra-bold": (k) => (
+ <>
+ <rect width="60" height="70" fill="#1f3fd1" />
+ <rect y="48" width="60" height="22" fill="#ffcc1a" />
+ <rect x={k === 1 ? 6 : 38} y="34" width="14" height="14" fill="#e8331c" />
+ <rect x={k === 2 ? 0 : 44} y="0" width="16" height="48" fill="#13a35a" opacity={k === 2 ? 1 : 0} />
+ <Figure x={k === 1 ? 36 : 24} y={k === 2 ? 42 : 34} s={k === 2 ? 1.5 : 1} pose={k - 1} fill="#141414" />
+ </>
+ ),
+ "blue-green-gradient": (k) => (
+ <>
+ <defs>
+ <linearGradient id="bgg" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0" stopColor="#2f6fe0" />
+ <stop offset="1" stopColor="#2fd39a" />
+ </linearGradient>
+ </defs>
+ <rect width="60" height="70" fill="url(#bgg)" />
+ <ellipse cx="30" cy="62" rx="22" ry="3" fill="#000" opacity="0.12" />
+ <Figure x={k === 1 ? 22 : 30} y={k === 2 ? 44 : 36} s={k === 2 ? 1.55 : 1.05} pose={k === 1 ? 1 : 0} fill="#f4f1ea" />
+ </>
+ ),
+ "street-style-paparazzi": (k) => (
+ <>
+ <rect width="60" height="70" fill="#151821" />
+ <rect y="50" width="60" height="20" fill="#262a33" />
+ {[8, 22, 47].map((cx, i) => (
+ <g key={cx} opacity={i === k ? 1 : 0.55}>
+ <circle cx={cx} cy={12 + i * 6} r="5" fill="#fff" opacity="0.18" />
+ <circle cx={cx} cy={12 + i * 6} r="1.6" fill="#fff" />
+ </g>
+ ))}
+ <rect x="4" y="38" width="10" height="7" rx="1.5" fill="#e4b425" opacity={k === 1 ? 1 : 0.4} />
+ <Figure x={k === 2 ? 34 : 28} y={k === 2 ? 40 : 37} s={k === 2 ? 1.4 : 1.05} pose={k === 0 ? 1 : -1} fill="#d9d4ca" />
+ </>
+ ),
+ "view-from-the-top": (k) => (
+ <>
+ <rect width="60" height="70" fill="#d8cbb2" />
+ {Array.from({ length: 7 }, (_, i) => (
+ <rect key={i} x={i * 9 - (k % 2) * 4} y="0" width="4.5" height="70" fill="#bfae8d" opacity="0.7" />
+ ))}
+ <g transform={`rotate(${k === 0 ? -35 : k === 1 ? 20 : 0} 30 35)`}>
+ <Figure x={30} y={40} s={k === 2 ? 0.7 : 1.1} pose={0.5} fill="#7a2f22" />
+ </g>
+ </>
+ ),
+ "light-blue-studio": (k) => (
+ <>
+ <rect width="60" height="70" fill="#cfe3f5" />
+ <rect y="46" width="60" height="24" fill="#bcd6ee" />
+ {k === 1 && <rect x="34" y="42" width="14" height="12" fill="#a9c9e8" />}
+ <Figure x={k === 1 ? 26 : 30} y={k === 2 ? 44 : 36} s={k === 2 ? 1.5 : 1.05} pose={k - 1} fill="#2a3442" />
+ </>
+ ),
+ "red-room": (k) => (
+ <>
+ <rect width="60" height="70" fill="#b5161b" />
+ <rect y="48" width="60" height="22" fill="#8f0f13" />
+ <rect x={k === 1 ? 36 : 6} y="22" width="16" height="26" fill="#9c1217" />
+ {k === 2 && <rect x="36" y="36" width="16" height="14" rx="3" fill="#7a0b0f" />}
+ <Figure x={k === 1 ? 22 : 30} y={k === 2 ? 42 : 36} s={k === 2 ? 1.35 : 1.05} pose={k === 1 ? 1 : -0.5} fill="#160406" />
+ </>
+ ),
+};
+
+/** A template's drawn preview: three framings in a carousel (arrows on hover, dots below). */
+export function TemplatePreview({ t, className }: { t: Pick<FashionTemplate, "id" | "name">; className?: string }) {
+ const [slide, setSlide] = useState(0);
+ const scene = SCENES[t.id] ?? SCENES["light-blue-studio"];
+ const arrow = "absolute top-1/2 grid size-7 -translate-y-1/2 place-items-center rounded-full bg-background/85 text-foreground opacity-0 shadow-soft transition outline-none group-hover/tpl:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/50";
+ return (
+ <span className={cn("group/tpl relative block overflow-hidden", className)}>
+ <svg viewBox="0 0 60 70" preserveAspectRatio="xMidYMid slice" role="img" aria-label={`${t.name} preview ${slide + 1} of 3`} className="size-full">
+ {scene(slide)}
+ </svg>
+ <button type="button" aria-label="Previous preview" onClick={(e) => (e.stopPropagation(), setSlide((s) => (s + 2) % 3))} className={cn(arrow, "left-1.5")}>
+ <ChevronLeft className="size-4" />
+ </button>
+ <button type="button" aria-label="Next preview" onClick={(e) => (e.stopPropagation(), setSlide((s) => (s + 1) % 3))} className={cn(arrow, "right-1.5")}>
+ <ChevronRight className="size-4" />
+ </button>
+ <span className="absolute inset-x-0 bottom-2 flex justify-center gap-1">
+ {[0, 1, 2].map((i) => (
+ <span key={i} className={cn("size-1.5 rounded-full bg-white/60", i === slide && "bg-white")} />
+ ))}
+ </span>
+ </span>
+ );
+}
diff --git a/src/components/photodump/covers.tsx b/src/components/photodump/covers.tsx
new file mode 100644
index 00000000..a1dcd120
--- /dev/null
+++ b/src/components/photodump/covers.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { hueOf } from "@/lib/catalog/packs";
+import { cn } from "@/lib/utils";
+
+/**
+ * A drawn pack cover (Fuobe ships no copies of Higgsfield's sample photos): a 2×2 contact sheet of
+ * soft tiles in the pack's hue family, its name and photo count.
+ */
+export function PackCover({ id, name, count, className, refs }: { id: string; name: string; count: number; className?: string; refs?: string[] }) {
+ const h = hueOf(id);
+ const tiles = [0, 40, 200, 320].map((d, i) => `linear-gradient(${140 + i * 30}deg, oklch(0.8 0.1 ${(h + d) % 360}), oklch(0.5 0.13 ${(h + d + 40) % 360}))`);
+ return (
+ <span className={cn("relative block overflow-hidden bg-muted", className)}>
+ <span className="grid size-full grid-cols-2 grid-rows-2 gap-0.5">
+ {tiles.map((bg, i) =>
+ refs?.[i] ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img key={i} src={refs[i]} alt="" loading="lazy" className="size-full object-cover" />
+ ) : (
+ <span key={i} style={{ background: bg }} />
+ ),
+ )}
+ </span>
+ <span className="absolute inset-0 bg-gradient-to-t from-black/65 via-black/10 to-transparent" />
+ <span className="absolute inset-x-2.5 bottom-2.5 text-white">
+ <span className="block font-heading text-[19px] leading-tight drop-shadow-sm">{name}</span>
+ <span className="text-[11.5px] font-medium opacity-90">{count} photos</span>
+ </span>
+ </span>
+ );
+}
diff --git a/src/components/photodump/hooks.ts b/src/components/photodump/hooks.ts
new file mode 100644
index 00000000..bdc32af1
--- /dev/null
+++ b/src/components/photodump/hooks.ts
@@ -0,0 +1,70 @@
+"use client";
+
+import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import type { Generation } from "@/lib/catalog/types";
+
+async function json<T>(res: Response): Promise<T> {
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
+ return body;
+}
+
+const post = async <T,>(url: string, body: unknown) => json<T>(await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
+
+export interface RunPreview {
+ modelId?: string;
+ modelName?: string;
+ count?: number;
+ costUsd?: number | null;
+ demo?: boolean;
+ notes: string[];
+ error?: string;
+}
+
+export interface UserPack {
+ id: string;
+ name: string;
+ refs: string[];
+ createdAt: number;
+}
+
+/** What a run would make and cost, priced on the server (`body` null = nothing to price yet). */
+export function useRunPreview(url: string, body: unknown | null) {
+ return useQuery({
+ queryKey: ["run-preview", url, body],
+ queryFn: () => post<RunPreview>(`${url}?preview=1`, body),
+ enabled: body !== null,
+ placeholderData: keepPreviousData,
+ staleTime: 15_000,
+ });
+}
+
+/** Start a run; its generations appear in the feeds through the live stream. */
+export function useRun<B>(url: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (body: B) => post<{ batchId?: string; items: Generation[]; notes?: string[] }>(url, body),
+ onSuccess: () => {
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ void qc.invalidateQueries({ queryKey: ["library"] });
+ },
+ });
+}
+
+export function useUserPacks() {
+ return useQuery({ queryKey: ["photodump-packs"], queryFn: async () => (await json<{ packs: UserPack[] }>(await fetch("/api/photodump/packs"))).packs });
+}
+
+export function usePackActions() {
+ const qc = useQueryClient();
+ const done = () => void qc.invalidateQueries({ queryKey: ["photodump-packs"] });
+ const create = useMutation({ mutationFn: (b: { name: string; refs: string[] }) => post<UserPack>("/api/photodump/packs", b), onSuccess: done });
+ const remove = useMutation({
+ mutationFn: async (id: string) => {
+ const res = await fetch(`/api/photodump/packs/${id}`, { method: "DELETE" });
+ if (!res.ok && res.status !== 404) await json(res);
+ },
+ onSuccess: done,
+ });
+ return { create, remove };
+}
diff --git a/src/components/photodump/photodump-view.tsx b/src/components/photodump/photodump-view.tsx
new file mode 100644
index 00000000..0bc046da
--- /dev/null
+++ b/src/components/photodump/photodump-view.tsx
@@ -0,0 +1,399 @@
+"use client";
+
+import { ArrowLeft, ArrowRight, History, Library, Loader2, Plus, RotateCcw, Search, Trash2, X } from "lucide-react";
+import Link from "next/link";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import { PageHeader, PageShell } from "@/components/page-shell";
+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 { useEngine, useGenerations } from "@/lib/api";
+import { customPack, DEFAULT_ASPECT, MAX_PACK_REFS, MAX_SELFIE_MB, PACKS, PHOTODUMP_ASPECTS, PHOTODUMP_MODELS, type Pack } from "@/lib/catalog/packs";
+import type { Generation } from "@/lib/catalog/types";
+import { timeAgo } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { PackCover } from "./covers";
+import { useRun, useRunPreview, usePackActions, useUserPacks } from "./hooks";
+import { DownloadAll, ResultsGrid } from "./results";
+import { RunLine, Steps } from "./steps";
+import { CharacterPicker } from "./subject";
+import { UploadBox } from "./upload-box";
+
+const STEPS = ["Choose a Pack", "Add your photo", "Get your photos"];
+const MODEL_NAMES: Record<string, string> = {
+ "soul-2": "Soul 2.0",
+ "nano-banana-pro": "Nano Banana Pro",
+ "seedream-5-pro": "Seedream 5.0 Pro",
+ "oss-z-image-turbo": "Z-Image Turbo + LoRA",
+ "oss-qwen-edit": "Qwen-Image-Edit",
+};
+const TABS = [
+ ["all", "All"],
+ ["photodump", "Photodump"],
+ ["instadump", "Instadump"],
+ ["mine", "My packs"],
+] as const;
+const ratioOf = (a: string) => {
+ const [w, h] = a.split(":").map(Number);
+ return w && h ? w / h : 3 / 4;
+};
+
+/** Instadump's "Create pack": a name and up to 15 reference photos, each recreated with you in it. */
+function CreatePack({ open, onOpenChange, onCreated }: { open: boolean; onOpenChange: (o: boolean) => void; onCreated: (id: string) => void }) {
+ const [name, setName] = useState("");
+ const [refs, setRefs] = useState<SlotValue[]>([]);
+ const { create } = usePackActions();
+ const busy = refs.some((r) => r.uploading);
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Create new pack</DialogTitle>
+ <DialogDescription>Create a pack from reference photos to generate new images in that style.</DialogDescription>
+ </DialogHeader>
+ <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Pack name" aria-label="Pack name" maxLength={60} />
+ <p className="text-[12.5px] text-muted-foreground">Upload your reference set up to {MAX_PACK_REFS} photos</p>
+ <div className="grid grid-cols-5 gap-1.5">
+ {refs.map((r, i) => (
+ <div key={r.id ?? i} className="relative aspect-square overflow-hidden rounded-md bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={r.preview} alt="" className="size-full object-cover" />
+ {r.uploading && (
+ <span className="absolute inset-0 grid place-items-center bg-background/60">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ )}
+ <button type="button" aria-label={`Remove photo ${i + 1}`} onClick={() => setRefs((xs) => xs.filter((x) => x !== r))} className="absolute top-0.5 right-0.5 grid size-5 place-items-center rounded-full bg-foreground/80 text-background">
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ {refs.length < MAX_PACK_REFS && (
+ <label className="grid aspect-square cursor-pointer place-items-center rounded-md border border-dashed text-muted-foreground hover:bg-accent">
+ <Plus className="size-4" />
+ <span className="sr-only">Add reference photos</span>
+ <input
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ multiple
+ hidden
+ onChange={(e) => ([...(e.target.files ?? [])].slice(0, MAX_PACK_REFS - refs.length).forEach((f) => fileToList(f, setRefs, "image")), (e.target.value = ""))}
+ />
+ </label>
+ )}
+ </div>
+ <DialogFooter>
+ <Button
+ disabled={!name.trim() || !refs.length || busy || create.isPending}
+ onClick={() =>
+ create.mutate(
+ { name: name.trim(), refs: refs.map((r) => r.ref).filter(Boolean) },
+ {
+ onSuccess: (p) => {
+ toast.success("Pack created");
+ setName("");
+ setRefs([]);
+ onOpenChange(false);
+ onCreated(p.id);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ },
+ )
+ }
+ >
+ {(busy || create.isPending) && <Loader2 className="animate-spin" />} Create pack
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+interface Run {
+ batchId: string;
+ title: string;
+ items: Generation[];
+ at: number;
+}
+
+/** Past runs (this feature's generations grouped by batch), newest first. */
+function useRuns(feature: string) {
+ const { data } = useGenerations({ features: [feature], limit: 200 });
+ return useMemo(() => {
+ const by = new Map<string, Run>();
+ for (const g of data ?? []) {
+ const id = g.batchId ?? g.id;
+ const run = by.get(id) ?? { batchId: id, title: g.request.batchTitle ?? g.prompt ?? "Run", items: [], at: g.createdAt };
+ run.items.push(g);
+ run.at = Math.max(run.at, g.createdAt);
+ by.set(id, run);
+ }
+ return [...by.values()].sort((a, b) => b.at - a.at);
+ }, [data]);
+}
+
+/** /photodump: Photodump (trained characters) and Instadump (one selfie) — choose a pack, add your photo, get the set. */
+export function PhotodumpView() {
+ const [engine, setEngine] = useEngine();
+ const [step, setStep] = useState(0);
+ const [reached, setReached] = useState(0);
+ const [tab, setTab] = useState<(typeof TABS)[number][0]>("all");
+ const [q, setQ] = useState("");
+ const [packId, setPackId] = useState<string>();
+ const [subjectMode, setSubjectMode] = useState<"selfie" | "character">("selfie");
+ const [selfie, setSelfie] = useState<SlotValue | null>(null);
+ const [elementId, setElementId] = useState<string>();
+ const [aspect, setAspect] = useState(DEFAULT_ASPECT);
+ const [modelPick, setModelPick] = useState<string>();
+ const [batchId, setBatchId] = useState<string>();
+ const [creatingPack, setCreatingPack] = useState(false);
+ const userPacks = useUserPacks();
+ const { remove } = usePackActions();
+ const run = useRun<Record<string, unknown>>("/api/photodump");
+ const runs = useRuns("photodump");
+
+ const all: Pack[] = useMemo(() => [...PACKS, ...(userPacks.data ?? []).map(customPack)], [userPacks.data]);
+ const needle = q.trim().toLowerCase();
+ const shown = all.filter(
+ (p) =>
+ (tab === "all" || (tab === "mine" ? p.custom : !p.custom && p.product === tab)) &&
+ (!needle || `${p.name} ${p.description} ${p.author ?? ""}`.toLowerCase().includes(needle)),
+ );
+ const pack = all.find((p) => p.id === packId);
+ const go = (i: number) => {
+ setStep(i);
+ setReached((r) => Math.max(r, i));
+ };
+
+ const subjectReady = subjectMode === "selfie" ? !!selfie?.ref && !selfie.uploading : !!elementId;
+ const body = pack && subjectReady
+ ? { packId: pack.id, engine, aspectRatio: aspect, modelId: modelPick, ...(subjectMode === "selfie" ? { selfie: selfie!.ref } : { elementId }) }
+ : null;
+ const preview = useRunPreview("/api/photodump", step === 1 ? body : null);
+ const current = runs.find((r) => r.batchId === batchId);
+ const items = current?.items ?? [];
+ const finished = items.length > 0 && items.every((g) => g.status !== "queued" && g.status !== "running");
+ const product = pack?.product === "photodump" ? "Photodump" : "Instadump";
+
+ const generate = () => {
+ if (!body) return toast(subjectMode === "selfie" ? "Add your photo first" : "Pick a character first");
+ run.mutate(body, {
+ onSuccess: (res) => {
+ setBatchId(res.batchId ?? res.items[0]?.batchId ?? undefined);
+ res.notes?.forEach((n) => toast(n));
+ go(2);
+ },
+ onError: (e) => toast.error((e as Error).message || "Cannot start photodump generation, please try again"),
+ });
+ };
+
+ return (
+ <PageShell wide>
+ <PageHeader title="Photodump" description="A whole set of photos of you in one go — from one selfie (Instadump) or a saved character, in a pack of styles.">
+ <EngineSwitch value={engine} onChange={setEngine} />
+ </PageHeader>
+ <div className="mb-6">
+ <Steps steps={STEPS} current={step} reached={reached} onGo={go} />
+ </div>
+
+ {step === 0 && (
+ <section aria-label="Choose a Pack" className="space-y-4">
+ <div className="flex flex-wrap items-center gap-3">
+ <div role="tablist" aria-label="Packs" className="scrollbar-none inline-flex max-w-full overflow-x-auto rounded-full bg-muted p-0.5">
+ {TABS.map(([id, label]) => (
+ <button key={id} role="tab" aria-selected={tab === id} onClick={() => setTab(id)} className={cn("h-8 shrink-0 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition", tab === id && "bg-background text-foreground shadow-soft")}>
+ {label}
+ </button>
+ ))}
+ </div>
+ <label className="flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full border bg-background px-3 focus-within:border-primary sm:max-w-xs">
+ <Search className="size-4 text-muted-foreground" />
+ <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search packs" aria-label="Search packs" className="min-w-0 flex-1 bg-transparent text-[13px] outline-none" />
+ </label>
+ </div>
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
+ <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>
+ {shown.map((p) => {
+ const sel = p.id === packId;
+ return (
+ <div key={p.id} className="group/pack relative min-w-0">
+ <button
+ type="button"
+ aria-pressed={sel}
+ onClick={() => setPackId(p.id)}
+ onDoubleClick={() => (setPackId(p.id), go(1))}
+ className={cn("block w-full overflow-hidden rounded-xl text-left outline-none focus-visible:ring-2 focus-visible:ring-ring", sel && "ring-3 ring-primary")}
+ >
+ <PackCover id={p.id} name={p.name} count={p.count} refs={p.refs} className="aspect-[3/4]" />
+ </button>
+ <p className="mt-1.5 line-clamp-2 px-0.5 text-[12px] text-muted-foreground">
+ {p.custom ? "Your pack" : p.product === "instadump" ? `Instadump${p.author ? ` · by ${p.author}` : ""}` : "Soul 2.0 Photodump"} · {p.description}
+ </p>
+ {p.custom && (
+ <button
+ type="button"
+ aria-label={`Delete pack ${p.name}`}
+ onClick={() => remove.mutate(p.id, { onSuccess: () => (packId === p.id && setPackId(undefined), toast("Pack deleted")) })}
+ className="absolute top-2 right-2 grid size-7 place-items-center rounded-full bg-background/90 opacity-100 shadow-soft transition sm:opacity-0 sm:group-hover/pack:opacity-100 sm:focus-visible:opacity-100"
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ {!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-3 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)}>
+ Use this preset <ArrowRight />
+ </Button>
+ </div>
+ {runs.length > 0 && (
+ <section aria-label="History" className="space-y-2 pt-4">
+ <h2 className="flex items-center gap-2 text-[14px] font-medium">
+ <History className="size-4" /> History
+ </h2>
+ <ul className="divide-y rounded-xl border">
+ {runs.slice(0, 8).map((r) => {
+ const ok = r.items.filter((g) => g.status === "succeeded").length;
+ return (
+ <li key={r.batchId}>
+ <button type="button" onClick={() => (setBatchId(r.batchId), go(2))} className="flex w-full items-center justify-between gap-3 px-3 py-2.5 text-left hover:bg-accent">
+ <span className="min-w-0 truncate text-[13px] font-medium">{r.title}</span>
+ <span className="shrink-0 text-[12px] text-muted-foreground tabular-nums">
+ {ok}/{r.items.length} · {timeAgo(r.at)}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ )}
+ </section>
+ )}
+
+ {step === 1 && pack && (
+ <section aria-label="Add your photo" className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_340px]">
+ <div className="min-w-0 space-y-4">
+ <div>
+ <h2 className="font-heading text-[26px] leading-tight">Add your photo</h2>
+ <p className="text-[14px] text-muted-foreground">Upload one selfie or photo - it’ll be the base for your photodump styles. Or use a saved character.</p>
+ </div>
+ <div role="radiogroup" aria-label="Who is in the photos" onKeyDown={radioKeys} className="inline-flex rounded-full bg-muted p-0.5">
+ {(
+ [
+ ["selfie", "One selfie"],
+ ["character", "My character"],
+ ] as const
+ ).map(([id, label]) => (
+ <button key={id} role="radio" aria-checked={subjectMode === id} tabIndex={radioTab(subjectMode === id)} onClick={() => setSubjectMode(id)} className={cn("h-8 rounded-full px-3.5 text-[13px] font-medium text-muted-foreground transition", subjectMode === id && "bg-background text-foreground shadow-soft")}>
+ {label}
+ </button>
+ ))}
+ </div>
+ {subjectMode === "selfie" ? (
+ <div className="space-y-2">
+ <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">Portrait-to-portrait works best: a clear, high-resolution photo with a visible face, without heavy stylization.</p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ <CharacterPicker value={elementId} onChange={setElementId} />
+ <p className="text-[12px] text-muted-foreground">Characters with a trained Soul ID (cloud) or LoRA (open source) keep the face best; others are sent as reference photos.</p>
+ </div>
+ )}
+ </div>
+ <aside className="space-y-5 rounded-2xl border p-4 lg:sticky lg:top-6 lg:self-start">
+ <div className="flex items-center gap-3">
+ <PackCover id={pack.id} name="" count={pack.count} refs={pack.refs} className="size-14 shrink-0 rounded-lg" />
+ <div className="min-w-0">
+ <p className="truncate text-[14px] font-medium">{pack.name}</p>
+ <p className="text-[12px] text-muted-foreground">{pack.count} photos</p>
+ </div>
+ </div>
+ <div className="space-y-2">
+ <p className="text-[12.5px] font-medium">Aspect ratio</p>
+ <div role="radiogroup" aria-label="Aspect ratio" onKeyDown={radioKeys} className="flex flex-wrap gap-1">
+ {PHOTODUMP_ASPECTS.map((a) => (
+ <button key={a} role="radio" aria-checked={aspect === a} tabIndex={radioTab(aspect === a)} onClick={() => setAspect(a)} className={cn("h-8 rounded-full border px-2.5 text-[12.5px] font-medium transition-colors", aspect === a ? "border-primary bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent")}>
+ {a === "auto" ? "Auto" : a}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="space-y-2">
+ <p className="text-[12.5px] font-medium">Model</p>
+ <div role="radiogroup" aria-label="Model" onKeyDown={radioKeys} className="flex flex-wrap gap-1">
+ {[undefined, ...PHOTODUMP_MODELS[engine]].map((m) => (
+ <button key={m ?? "auto"} role="radio" aria-checked={modelPick === m} tabIndex={radioTab(modelPick === m)} onClick={() => setModelPick(m)} className={cn("h-8 rounded-full border px-2.5 text-[12.5px] font-medium transition-colors", modelPick === m ? "border-primary bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent")}>
+ {m ? MODEL_NAMES[m] : "Auto"}
+ </button>
+ ))}
+ </div>
+ </div>
+ <RunLine preview={body ? preview.data : undefined} loading={preview.isFetching} />
+ <div className="flex gap-2">
+ <Button variant="outline" onClick={() => go(0)}>
+ <ArrowLeft /> Back
+ </Button>
+ <Button className="flex-1" disabled={!body || run.isPending || !!preview.data?.error} onClick={generate}>
+ {run.isPending && <Loader2 className="animate-spin" />} Generate {pack.count}
+ </Button>
+ </div>
+ </aside>
+ </section>
+ )}
+
+ {step === 2 && (
+ <section aria-label="Get your photos" className="space-y-4">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div className="min-w-0">
+ <h2 className="font-heading text-[26px] leading-tight">Get your {product}</h2>
+ <p className="text-[14px] text-muted-foreground">
+ {!items.length ? "Starting…" : finished ? "Your new photos are ready - download, post, share and enjoy!" : `Making ${items.length} photos — they appear here as they finish.`}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <DownloadAll items={items} />
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8"
+ onClick={() => {
+ setBatchId(undefined);
+ setStep(0);
+ setReached(0);
+ }}
+ >
+ <RotateCcw /> Restart
+ </Button>
+ <Button asChild variant="outline" size="sm" className="h-8">
+ <Link href="/library">
+ <Library /> Go to Library
+ </Link>
+ </Button>
+ </div>
+ </div>
+ <ResultsGrid items={items} ratio={ratioOf(items[0]?.request.params?.aspectRatio ?? aspect)} />
+ </section>
+ )}
+
+ <CreatePack open={creatingPack} onOpenChange={setCreatingPack} onCreated={(id) => (setTab("mine"), setPackId(id))} />
+ </PageShell>
+ );
+}
diff --git a/src/components/photodump/results.tsx b/src/components/photodump/results.tsx
new file mode 100644
index 00000000..99229194
--- /dev/null
+++ b/src/components/photodump/results.tsx
@@ -0,0 +1,161 @@
+"use client";
+
+import { Check, Download, Film, Maximize2, Pencil, Trash2 } from "lucide-react";
+import Link from "next/link";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { FailedTile, MediaThumb, PendingTile } from "@/components/studio/feed";
+import { Viewer } from "@/components/studio/viewer";
+import { useCreateGeneration, useGenerationActions } from "@/lib/api";
+import type { Generation, OutputFile } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+
+export interface Tile {
+ g: Generation;
+ /** Index into g.outputs (finished tiles). */
+ i?: number;
+ o?: OutputFile;
+ key: string;
+}
+
+const order = (g: Generation) => g.request.step?.index ?? 0;
+
+/** One tile per finished image, one per expected image while a job runs (a ×4 job shows four placeholders). */
+export function tilesOf(items: Generation[]): Tile[] {
+ return [...items]
+ .sort((a, b) => order(a) - order(b) || a.createdAt - b.createdAt)
+ .flatMap((g) =>
+ g.status === "succeeded"
+ ? g.outputs.filter((o) => o.kind === "image").map((o, i) => ({ g, i, o, key: `${g.id}:${i}` }))
+ : g.status === "queued" || g.status === "running"
+ ? Array.from({ length: Math.max(1, Math.min(4, g.request.params?.numOutputs ?? 1)) }, (_, k) => ({ g, key: `${g.id}:p${k}` }))
+ : [{ g, key: `${g.id}:x` }],
+ );
+}
+
+function IconLink({ href, label, icon: Icon, onClick }: { href?: string; label: string; icon: typeof Film; onClick?: () => void }) {
+ const cls = "grid size-7 place-items-center rounded-full bg-background/90 text-foreground shadow-soft outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring/50";
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {href ? (
+ <Link href={href} prefetch={false} aria-label={label} className={cls}>
+ <Icon className="size-3.5" />
+ </Link>
+ ) : (
+ <button type="button" aria-label={label} onClick={onClick} className={cls}>
+ <Icon className="size-3.5" />
+ </button>
+ )}
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+/**
+ * A grid of results: placeholders while they render, a retry card when one fails, and finished images
+ * with Animate / Edit / Delete. With `onPick`, clicking an image selects it (Fashion Factory's "pick 1")
+ * and the expand button opens the viewer; otherwise clicking opens the viewer.
+ */
+export function ResultsGrid({
+ items,
+ ratio = 3 / 4,
+ picked,
+ onPick,
+ className,
+}: {
+ items: Generation[];
+ ratio?: number;
+ picked?: string;
+ onPick?: (url: string) => void;
+ className?: string;
+}) {
+ const tiles = useMemo(() => tilesOf(items), [items]);
+ const done = tiles.filter((t) => t.o);
+ const [open, setOpen] = useState<number | null>(null);
+ const { trash } = useGenerationActions();
+ const create = useCreateGeneration();
+ const viewing = open !== null ? done[open] : undefined;
+ return (
+ <>
+ <div className={cn("grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4", className)}>
+ {tiles.map((t) => {
+ if (!t.o) {
+ if (t.g.status === "queued" || t.g.status === "running") return <PendingTile key={t.key} g={t.g} ratio={ratio} />;
+ return (
+ <FailedTile
+ key={t.key}
+ g={t.g}
+ ratio={ratio}
+ onRetry={() => create.mutate({ ...t.g.request, title: undefined, batchTitle: undefined }, { onError: (e) => toast.error((e as Error).message) })}
+ />
+ );
+ }
+ const url = t.o.url;
+ const sel = picked === url;
+ const idx = done.indexOf(t);
+ return (
+ <div key={t.key} className="group/tile relative overflow-hidden rounded-xl bg-muted animate-fade-up" style={{ aspectRatio: ratio }}>
+ <button
+ type="button"
+ onClick={() => (onPick ? onPick(url) : setOpen(idx))}
+ aria-pressed={onPick ? sel : undefined}
+ aria-label={onPick ? `Pick ${t.g.request.step?.label ?? "this image"}` : `Open ${t.g.request.step?.label ?? "image"}`}
+ className={cn("block size-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset", sel && "ring-3 ring-primary ring-inset")}
+ >
+ <MediaThumb output={t.o} g={t.g} />
+ </button>
+ {sel && (
+ <span className="absolute top-2 left-2 grid size-6 place-items-center rounded-full bg-primary text-primary-foreground shadow-soft">
+ <Check className="size-3.5" />
+ </span>
+ )}
+ <div className="absolute top-2 right-2 flex gap-1 opacity-100 transition-opacity sm:opacity-0 sm:group-focus-within/tile:opacity-100 sm:group-hover/tile:opacity-100">
+ {onPick && <IconLink label="View" icon={Maximize2} onClick={() => setOpen(idx)} />}
+ <IconLink href={`/video?image=${encodeURIComponent(url)}`} label="Animate" icon={Film} />
+ <IconLink href={`/edit?image=${encodeURIComponent(url)}`} label="Edit" icon={Pencil} />
+ <IconLink label="Delete" icon={Trash2} onClick={() => void trash([t.g])} />
+ </div>
+ {t.g.request.step && <span className="pointer-events-none absolute bottom-2 left-2 rounded-full bg-background/85 px-2 py-0.5 text-[11px] font-medium">{t.g.request.step.label}</span>}
+ </div>
+ );
+ })}
+ </div>
+ {viewing?.o && (
+ <Viewer
+ generation={viewing.g}
+ index={viewing.i ?? 0}
+ onClose={() => setOpen(null)}
+ onPrev={open! > 0 ? () => setOpen(open! - 1) : undefined}
+ onNext={open! < done.length - 1 ? () => setOpen(open! + 1) : undefined}
+ />
+ )}
+ </>
+ );
+}
+
+/** "Download (8 /10)": a zip of the finished images (the Library's zip endpoint). */
+export function DownloadAll({ items, label = "Download" }: { items: Generation[]; label?: string }) {
+ const tiles = tilesOf(items);
+ const ready = items.filter((g) => g.status === "succeeded");
+ const available = tiles.filter((t) => t.o).length;
+ const total = tiles.length;
+ const href = ready.length ? `/api/generations/zip?ids=${ready.map((g) => g.id).join(",")}` : undefined;
+ return (
+ <a
+ href={href}
+ download
+ aria-disabled={!href}
+ onClick={(e) => !href && e.preventDefault()}
+ className={cn(
+ "inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3 text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/90",
+ !href && "pointer-events-none opacity-50",
+ )}
+ >
+ <Download className="size-3.5" />
+ {available === total ? `${label} all` : `${label} (${available} /${total})`}
+ </a>
+ );
+}
diff --git a/src/components/photodump/steps.tsx b/src/components/photodump/steps.tsx
new file mode 100644
index 00000000..6449ae8b
--- /dev/null
+++ b/src/components/photodump/steps.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import { Check } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+/** Numbered wizard steps; steps already reached can be revisited. */
+export function Steps({ steps, current, reached, onGo }: { steps: string[]; current: number; reached: number; onGo?: (i: number) => void }) {
+ return (
+ <ol aria-label="Steps" className="scrollbar-none flex items-center gap-1 overflow-x-auto">
+ {steps.map((label, i) => {
+ const done = i < current;
+ const active = i === current;
+ const can = !!onGo && i <= reached && !active;
+ return (
+ <li key={label} className="flex shrink-0 items-center gap-1">
+ {i > 0 && <span aria-hidden className={cn("h-px w-3 sm:w-6", i <= current ? "bg-primary/60" : "bg-border")} />}
+ <button
+ type="button"
+ disabled={!can}
+ aria-current={active ? "step" : undefined}
+ onClick={() => can && onGo(i)}
+ className={cn(
+ "inline-flex h-8 items-center gap-1.5 rounded-full px-2.5 text-[12.5px] font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ active ? "bg-brand-faint text-brand-text" : done ? "text-foreground hover:bg-accent" : "text-muted-foreground",
+ !can && !active && "cursor-default",
+ )}
+ >
+ <span className={cn("grid size-5 place-items-center rounded-full text-[11px]", active ? "bg-primary text-primary-foreground" : done ? "bg-success text-white" : "bg-muted")}>
+ {done ? <Check className="size-3" /> : i + 1}
+ </span>
+ <span className={cn(!active && "max-sm:hidden")}>{label}</span>
+ </button>
+ </li>
+ );
+ })}
+ </ol>
+ );
+}
+
+/** "Runs on Nano Banana Pro · 10 photos · ≈ $1.50" (or the reason it can't run). */
+export function RunLine({ preview, loading }: { preview?: { modelName?: string; count?: number; costUsd?: number | null; demo?: boolean; notes: string[]; error?: string }; loading?: boolean }) {
+ 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 = preview.demo ? "Demo · 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>
+ Runs on <span className="font-medium text-foreground">{preview.modelName}</span> · {preview.count} photo{preview.count === 1 ? "" : "s"} · <span className="tabular-nums">{cost}</span>
+ </p>
+ {preview.notes.map((n) => (
+ <p key={n}>{n}</p>
+ ))}
+ </div>
+ );
+}
diff --git a/src/components/photodump/subject.tsx b/src/components/photodump/subject.tsx
new file mode 100644
index 00000000..5e066071
--- /dev/null
+++ b/src/components/photodump/subject.tsx
@@ -0,0 +1,143 @@
+"use client";
+
+import { Check, Loader2, Plus, UserRound, X } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Skeleton } from "@/components/ui/skeleton";
+import { fileToList, type SlotValue } from "@/components/studio/media-slot";
+import { useElements, useSaveElement } from "@/lib/api";
+import type { StudioElement } from "@/lib/catalog/elements";
+import { cn } from "@/lib/utils";
+
+/** What a character brings: a trained Soul ID, a trained LoRA, or just photos. */
+export function identityLabel(el: StudioElement): string {
+ if (el.loras.some((l) => l.referenceId)) return "Soul ID";
+ if (el.loras.length) return "LoRA";
+ return `${el.references.length} photo${el.references.length === 1 ? "" : "s"}`;
+}
+
+/** Create a character from a few photos, without leaving the page. */
+export function QuickCharacter({ open, onOpenChange, onCreated }: { open: boolean; onOpenChange: (o: boolean) => void; onCreated: (el: StudioElement) => void }) {
+ const [name, setName] = useState("");
+ const [photos, setPhotos] = useState<SlotValue[]>([]);
+ const save = useSaveElement();
+ const busy = photos.some((p) => p.uploading);
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>New character</DialogTitle>
+ <DialogDescription>A few clear photos of one person: different angles, at least one full-body, no sunglasses, filters or group shots.</DialogDescription>
+ </DialogHeader>
+ <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. “Maya”" maxLength={60} aria-label="Character name" />
+ <div className="grid grid-cols-4 gap-1.5">
+ {photos.map((p, i) => (
+ <div key={p.id ?? i} className="relative aspect-square overflow-hidden rounded-md bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={p.preview} alt="" className="size-full object-cover" />
+ {p.uploading && (
+ <span className="absolute inset-0 grid place-items-center bg-background/60">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ )}
+ <button type="button" aria-label={`Remove photo ${i + 1}`} onClick={() => setPhotos((xs) => xs.filter((x) => x !== p))} className="absolute top-0.5 right-0.5 grid size-5 place-items-center rounded-full bg-foreground/80 text-background">
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ {photos.length < 20 && (
+ <label className="grid aspect-square cursor-pointer place-items-center rounded-md border border-dashed text-muted-foreground hover:bg-accent">
+ <Plus className="size-4" />
+ <span className="sr-only">Add photos</span>
+ <input type="file" accept="image/png,image/jpeg,image/webp" multiple hidden onChange={(e) => ([...(e.target.files ?? [])].slice(0, 20 - photos.length).forEach((f) => fileToList(f, setPhotos, "image")), (e.target.value = ""))} />
+ </label>
+ )}
+ </div>
+ <p className="text-[12px] text-muted-foreground">
+ Or <Link href="/character-sheet" className="text-brand-text hover:underline">build one with Character Sheet</Link>, then pick it here.
+ </p>
+ <DialogFooter>
+ <Button
+ disabled={!name.trim() || !photos.length || busy || save.isPending}
+ onClick={() =>
+ save.mutate(
+ { name: name.trim(), kind: "character", references: photos.map((p) => p.ref).filter(Boolean) },
+ {
+ onSuccess: (el) => {
+ toast.success(`Saved as @${el.handle}`);
+ onCreated(el);
+ setName("");
+ setPhotos([]);
+ onOpenChange(false);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ },
+ )
+ }
+ >
+ {(busy || save.isPending) && <Loader2 className="animate-spin" />} Save character
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/** 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();
+ const [creating, setCreating] = useState(false);
+ 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">
+ <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>
+ {isLoading
+ ? Array.from({ length: 3 }, (_, i) => <Skeleton key={i} className="aspect-[3/4] rounded-xl" />)
+ : characters.map((el) => {
+ const sel = value === el.id;
+ return (
+ <button
+ key={el.id}
+ type="button"
+ aria-pressed={sel}
+ onClick={() => onChange(el.id)}
+ className={cn("group relative min-w-0 overflow-hidden rounded-xl bg-muted text-left outline-none focus-visible:ring-2 focus-visible:ring-ring", sel && "ring-3 ring-primary")}
+ >
+ <span className="block aspect-[3/4]">
+ {el.references[0] ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={el.references[0]} alt="" loading="lazy" className="size-full object-cover" />
+ ) : (
+ <span className="grid size-full place-items-center text-muted-foreground">
+ <UserRound className="size-6" />
+ </span>
+ )}
+ </span>
+ <span className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent px-2 pt-6 pb-1.5 text-white">
+ <span className="block truncate text-[12.5px] font-medium">{el.name}</span>
+ <span className="text-[11px] opacity-85">{identityLabel(el)}</span>
+ </span>
+ {sel && (
+ <span className="absolute top-1.5 right-1.5 grid size-5 place-items-center rounded-full bg-primary text-primary-foreground">
+ <Check className="size-3" />
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ <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.tsx
new file mode 100644
index 00000000..6a257d6c
--- /dev/null
+++ b/src/components/photodump/upload-box.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+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 { 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.
+ */
+export function UploadBox({
+ value,
+ onChange,
+ title,
+ hint,
+ maxMb = 20,
+ className,
+}: {
+ value: SlotValue | null;
+ onChange: (v: SlotValue | null) => void;
+ title: string;
+ hint?: string;
+ maxMb?: number;
+ className?: string;
+}) {
+ const input = useRef<HTMLInputElement>(null);
+ const [over, setOver] = useState(false);
+ const take = (f: File | undefined) => {
+ if (!f) 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");
+ };
+ return (
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ take(e.dataTransfer.files[0]);
+ }}
+ onPaste={(e) => take([...e.clipboardData.files][0])}
+ className={cn("relative overflow-hidden rounded-2xl border border-dashed bg-background transition-colors", over && "border-primary bg-brand-faint", className)}
+ >
+ <input ref={input} type="file" accept="image/png,image/jpeg,image/webp" hidden onChange={(e) => (take(e.target.files?.[0]), (e.target.value = ""))} />
+ {value ? (
+ <div className="relative size-full">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={value.preview} alt={title} className="size-full object-contain" />
+ {value.uploading && (
+ <span className="absolute inset-0 grid place-items-center bg-background/60" role="status" aria-label="Uploading">
+ <Loader2 className="size-5 animate-spin" />
+ </span>
+ )}
+ <button type="button" onClick={() => onChange(null)} aria-label={`Remove ${title.toLowerCase()}`} className="absolute top-2 right-2 grid size-7 place-items-center rounded-full bg-foreground/80 text-background">
+ <X className="size-4" />
+ </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">
+ <span className="grid size-11 place-items-center rounded-2xl bg-brand-faint text-brand-text">
+ <ImagePlus className="size-5" />
+ </span>
+ <span className="text-[14px] font-medium">{title}</span>
+ {hint && <span className="max-w-xs text-[12.5px] text-muted-foreground">{hint}</span>}
+ <span className="text-[11.5px] text-muted-foreground">PNG, JPG or paste · up to {maxMb} MB</span>
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/src/lib/catalog/apps.ts b/src/lib/catalog/apps.ts
index daa06c9b..0931945a 100644
--- a/src/lib/catalog/apps.ts
+++ b/src/lib/catalog/apps.ts
@@ -378,14 +378,15 @@ export const APPS: Preset[] = [
placeholder: "Who are they? e.g. “a 26-year-old surfer and photographer from Lisbon, freckles, sun-bleached curls”",
prompt: "{prompt}",
cloud: { modelId: "ai-influencer", op: "t2i" },
+ // The Soul Cast sheet workflow: Z-Image Turbo draws the turnaround (front, three-quarter, profile, back) and
+ // cuts it into the four views, which make a better character element than one wide sheet.
open: {
- modelId: "oss-z-image-turbo",
+ modelId: "oss-zimage-soul-cast",
op: "t2i",
- params: { aspectRatio: "16:9" },
- promptTemplate:
- "Character design sheet of an original character: {prompt}. Front view, three-quarter view, side view and back view side by side, plus a row of four facial expressions; full body, the same face, hairstyle and outfit in every view; plain light-grey studio background, soft even light, photorealistic, high detail.",
+ promptTemplate: "An original character: {prompt}. The same face, hairstyle and outfit in every view, photorealistic, high detail.",
},
- parity: "Save the sheet as a character (tile menu) to use it in any prompt with @. The open version prompts Z-Image Turbo for the sheet",
+ parity:
+ "Save the sheet as a character (tile menu) to use it in any prompt with @. From your own photos or a Soul Cast build, use Character Sheet. The open version draws the turnaround on Z-Image Turbo and cuts it into the four views",
}),
app({
name: "Match Lighting",
diff --git a/src/lib/catalog/packs.ts b/src/lib/catalog/packs.ts
index ef9fc25f..81ecf025 100644
--- a/src/lib/catalog/packs.ts
+++ b/src/lib/catalog/packs.ts
@@ -681,7 +681,7 @@ export function fashionReducer(s: FashionState, a: FashionAction): FashionState
switch (a.type) {
case "template":
// A new set invalidates everything made in the old one.
- return a.id === s.templateId ? s : { ...FASHION_START, step: s.step, templateId: a.id, elementId: s.elementId };
+ return a.id === s.templateId ? s : { ...FASHION_START, templateId: a.id, elementId: s.elementId };
case "element":
return a.id === s.elementId ? s : { ...s, elementId: a.id, baseIds: [], base: undefined, outfitIds: [], outfit: undefined, photosetBatch: undefined };
case "next":
@@ -760,3 +760,38 @@ export function castFieldVisible(key: string, values: Record<string, unknown>):
if (key === "facial_hair_color") return values.gender !== "Female" && BEARDED.includes(String(values.facial_hair));
return true;
}
+
+/** A Soul Cast field as the page gets it from the server (cinema.ts's SOUL_CAST_FIELDS without `when`). */
+export interface CastFieldData {
+ key: string;
+ label: string;
+ tab: string;
+ question?: string;
+ kind: "list" | "ruler" | "multi";
+ options: (string | number)[];
+ default?: string | number;
+ format?: string;
+ manual?: boolean;
+}
+
+export type CastAnswers = Record<string, string | number | string[] | undefined>;
+
+/** Higgsfield's Randomize (mirrors cinema.ts randomizeCast): genre, era, race, gender, age and archetype. */
+export function randomCast(fields: CastFieldData[], values: CastAnswers, rand: () => number = Math.random): CastAnswers {
+ const next: CastAnswers = { ...values };
+ for (const key of ["genre", "era", "race", "gender", "age", "archetype"]) {
+ const f = fields.find((x) => x.key === key);
+ if (f?.options.length) next[key] = f.options[Math.floor(rand() * f.options.length) % f.options.length];
+ }
+ if (next.gender === "Female") {
+ delete next.facial_hair;
+ delete next.facial_hair_color;
+ }
+ return next;
+}
+
+/** A starting name for the saved character (mirrors cinema.ts castName): "Rebel 30", "Western lead". */
+export function castNameFor(values: CastAnswers): string {
+ if (values.archetype) return values.age ? `${values.archetype} ${values.age}` : String(values.archetype);
+ return values.genre ? `${values.genre} lead` : "Cast member";
+}
diff --git a/src/lib/catalog/palettes.ts b/src/lib/catalog/palettes.ts
index 8b34d646..7ca5ecb7 100644
--- a/src/lib/catalog/palettes.ts
+++ b/src/lib/catalog/palettes.ts
@@ -366,8 +366,8 @@ export const SIGNATURE_MODELS = {
const NOT_READY = "This moodboard is still training. Try again once it is ready.";
const hasOp = (m: ModelDef, op: string) => m.routes.some((r) => r.op === op);
-/** Room for style references beyond the user's own images (multi-reference edit models). */
-const refBudget = (m: ModelDef, existing: number) => (hasOp(m, "edit") ? Math.max(0, (m.options.maxImages ?? 1) - existing) : 0);
+/** Room for style references beyond the user's own images (multi-reference edit models; a one-image edit would just edit the reference). */
+const refBudget = (m: ModelDef, existing: number) => (hasOp(m, "edit") && (m.options.maxImages ?? 1) >= 2 ? Math.max(0, (m.options.maxImages ?? 1) - existing) : 0);
const tidy = (s: string | undefined) => (s ?? "").trim().replace(/[.\s]+$/, "");
const join = (prompt: string | undefined, sentence: string) => (tidy(prompt) ? `${tidy(prompt)}. ${sentence}` : sentence);
diff --git a/src/server/photodump.ts b/src/server/photodump.ts
index 73a6e9dc..c83fe42e 100644
--- a/src/server/photodump.ts
+++ b/src/server/photodump.ts
@@ -1,6 +1,6 @@
import "server-only";
import { nanoid } from "nanoid";
-import { getModel } from "@/lib/catalog";
+import { getModel, getPreset } from "@/lib/catalog";
import { castPrompt, type CastValues } from "@/lib/catalog/cinema";
import {
castSheetModel,
@@ -228,6 +228,8 @@ export function createFashion(input: FashionRun) {
// ---------------------------------------------------------------------------
// Character Sheet
+const AI_INFLUENCER = "app-ai-influencer";
+
export type SheetRun =
| { mode: "reference"; engine: Engine; images: string[]; details?: string }
| { mode: "cast"; engine: Engine; cast: CastValues; details?: string }
@@ -249,7 +251,7 @@ function sheetRequest(input: SheetRun): { request: GenerationRequest; notes: str
// A description: the AI Influencer app (Higgsfield's character-sheet model, or Z-Image Turbo).
if (!input.prompt.trim()) throw new Error("Describe your character first");
return {
- request: { feature: "app:app-ai-influencer", presetId: "app-ai-influencer", modelId: engine === "open" ? "oss-z-image-turbo" : "ai-influencer", prompt: input.prompt.trim() },
+ request: { feature: "app:app-ai-influencer", presetId: AI_INFLUENCER, modelId: (engine === "open" ? getPreset(AI_INFLUENCER)?.open : getPreset(AI_INFLUENCER)?.cloud)?.modelId ?? "ai-influencer", prompt: input.prompt.trim() },
notes: [],
};
}
diff --git a/tests/image-studios-api.test.ts b/tests/image-studios-api.test.ts
new file mode 100644
index 00000000..dccd59b7
--- /dev/null
+++ b/tests/image-studios-api.test.ts
@@ -0,0 +1,205 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-image-studios-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+delete process.env.HF_KEY;
+delete process.env.HF_API_KEY;
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+const { createElement } = await import("@/server/elements");
+const palettes = await import("@/server/palettes");
+const moodboards = await import("@/server/moodboards");
+const { PALETTES } = await import("@/lib/catalog/cinema");
+const { MODELS } = await import("@/lib/catalog");
+const palettesRoute = await import("@/app/api/palettes/route");
+const paletteRoute = await import("@/app/api/palettes/[id]/route");
+const lockRoute = await import("@/app/api/palettes/lock/route");
+const moodboardsRoute = await import("@/app/api/moodboards/route");
+const photodumpRoute = await import("@/app/api/photodump/route");
+const packsRoute = await import("@/app/api/photodump/packs/route");
+const fashionRoute = await import("@/app/api/photodump/fashion/route");
+const characterRoute = await import("@/app/api/photodump/character/route");
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("higgsfieldKey", "");
+});
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const json = (method: string, body?: unknown, url = "http://x/api") =>
+ new Request(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) });
+
+// A 1×1 PNG.
+const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", "base64");
+const upload = () => saveFile({ data: PNG, contentType: "image/png", source: "upload" }).url;
+
+async function settle(id: string, ms = 40_000) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id, { includeDeleted: true })!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+describe("palettes", () => {
+ it("seeds Cinema Studio's 50 palettes once, with their slugs and the 12th colour as background", async () => {
+ // (GET /api/palettes returns exactly these two; route GETs need a request scope, so the server functions are called here.)
+ const body = { items: palettes.listPalettes(), caps: palettes.signatureCaps() };
+ const builtins = body.items.filter((p) => p.source === "builtin");
+ expect(builtins).toHaveLength(50);
+ expect(builtins.map((p) => p.slug)).toEqual(PALETTES.map((p) => p.slug));
+ expect(builtins[0].colors).toHaveLength(12);
+ expect(builtins[0].background).toBe(builtins[0].colors[11]);
+ expect(palettes.listPalettes().filter((p) => p.source === "builtin")).toHaveLength(50);
+ // Which models take a palette comes from their field maps.
+ const native = Object.keys(body.caps.native).sort();
+ const fromMaps = MODELS.filter((m) => m.routes.some((r) => r.map?.palette)).map((m) => m.id).sort();
+ expect(native).toEqual(fromMaps);
+ expect(body.caps.native["recraft-4-1"]).toEqual({ max: 10, background: "background_color" });
+ expect(body.caps.native["ideogram-3"]).toEqual({ max: 12 });
+ });
+
+ it("saves, renames and deletes your palettes; built-ins stay", async () => {
+ const bad = await palettesRoute.POST(json("POST", { name: "x", colors: ["#zzzzzz"] }));
+ expect(bad.status).toBe(400);
+ const res = await palettesRoute.POST(json("POST", { name: "Sea Glass", colors: ["#aabbcc", "112233"], background: "#000000", source: "manual" }));
+ expect(res.status).toBe(201);
+ const p = await res.json();
+ expect(p.colors).toEqual(["#AABBCC", "#112233"]);
+ expect(palettes.listPalettes()[0].id).toBe(p.id);
+ expect((await paletteRoute.PATCH(json("PATCH", { name: "Sea Glass II" }), params({ id: p.id }))).status).toBe(200);
+ expect((await paletteRoute.DELETE(json("DELETE"), params({ id: "builtin-static-noon" }))).status).toBe(400);
+ expect((await paletteRoute.DELETE(json("DELETE"), params({ id: p.id }))).status).toBe(204);
+ expect((await paletteRoute.DELETE(json("DELETE"), params({ id: p.id }))).status).toBe(404);
+ });
+
+ it("locks an open image to the palette with a chained palette-transfer step", async () => {
+ const res = await lockRoute.POST(
+ json("POST", { request: { feature: "image", modelId: "oss-qwen-image", prompt: "a lighthouse", params: { numOutputs: 2, palette: ["#102030"] } }, colors: ["#102030", "#2a9d8f"] }),
+ );
+ expect(res.status).toBe(201);
+ const { items } = (await res.json()) as { items: { id: string; modelId: string; op: string; batchId: string; request: { step?: { label: string } } }[] };
+ expect(items).toHaveLength(4);
+ expect(new Set(items.map((g) => g.batchId)).size).toBe(1);
+ const locks = items.filter((g) => g.modelId === "oss-palette-image");
+ expect(locks.map((g) => g.op)).toEqual(["color-match", "color-match"]);
+ expect(locks[0].request.step?.label).toBe("Palette lock 1 of 2");
+ const done = await settle(locks[0].id);
+ expect(done.status).toBe("succeeded");
+ expect(done.request.params?.palette).toEqual(["#102030", "#2A9D8F"]);
+ }, 45_000);
+});
+
+describe("moodboards", () => {
+ it("refuses boards outside Higgsfield's limits, in its words", async () => {
+ const few = await moodboardsRoute.POST(json("POST", { name: "x", images: [upload(), upload()] }));
+ expect(few.status).toBe(400);
+ expect((await few.json()).error).toBe("Upload at least 5 photos to continue.");
+ const noName = await moodboardsRoute.POST(json("POST", { name: " ", images: Array.from({ length: 5 }, upload) }));
+ expect((await noName.json()).error).toBe("Please enter a moodboard name");
+ });
+
+ it("builds a board through its cover job (open: collages on Qwen-Image-Edit Style Reference), then it's usable", async () => {
+ const images = Array.from({ length: 6 }, upload);
+ const res = await moodboardsRoute.POST(json("POST", { name: "Neon Haze", images, collages: [upload()], engine: "open" }));
+ expect(res.status).toBe(201);
+ const m = await res.json();
+ expect(["queued", "running", "cover"]).toContain(m.status);
+ expect(m.refs).toEqual(images);
+ const g = gens.getGeneration(m.generationId)!;
+ expect(g.modelId).toBe("oss-style-qwen-edit");
+ expect(g.feature).toBe("moodboard");
+ expect(g.request.inputs?.images).toEqual(m.collages);
+ await settle(m.generationId);
+ const done = moodboards.getMoodboard(m.id)!;
+ expect(done.status).toBe("complete");
+ // A demo cover makes no Recraft style and keeps the first image as the cover.
+ expect(done.styleId).toBeNull();
+ expect(done.cover).toBe(images[0]);
+ const list = { items: moodboards.listMoodboards(), curated: moodboards.curatedMoodboards() };
+ expect(list.items.map((x) => x.id)).toContain(m.id);
+ expect(list.curated).toHaveLength(33);
+ expect(new Set(list.curated.map((c) => c.category))).toEqual(new Set(["All presets", "Mood", "Styles", "Camera"]));
+ }, 45_000);
+
+ it("prepares cloud boards on Recraft V4 Styles with the 10 most representative images", () => {
+ const images = Array.from({ length: 12 }, upload);
+ const m = moodboards.createMoodboard({ name: "Paper Cut", images, engine: "cloud" });
+ const g = gens.getGeneration(m.generationId!)!;
+ expect(g.modelId).toBe("recraft-4-style");
+ expect(g.request.inputs?.images).toEqual(images.slice(0, 10));
+ expect(m.refs).toHaveLength(10);
+ // Training a style LoRA needs AI-Toolkit; until then it says where to set it up.
+ expect(() => moodboards.trainMoodboard(m.id)).toThrow(/still training/);
+ expect(moodboards.deleteMoodboard(m.id)).toBe(true);
+ expect(moodboards.getMoodboard(m.id)).toBeNull();
+ });
+});
+
+describe("photodump, fashion factory and character sheet runs", () => {
+ it("prices and makes an Instadump from one selfie as one batch", async () => {
+ const selfie = upload();
+ const preview = await (await photodumpRoute.POST(json("POST", { packId: "winter-special", engine: "cloud", selfie, aspectRatio: "3:4" }, "http://x/api/photodump?preview=1"))).json();
+ expect(preview).toMatchObject({ modelId: "nano-banana-pro", count: 9, demo: true });
+ const res = await photodumpRoute.POST(json("POST", { packId: "winter-special", engine: "cloud", selfie, aspectRatio: "3:4" }));
+ expect(res.status).toBe(201);
+ const { batchId, items } = await res.json();
+ expect(items).toHaveLength(9);
+ expect(items.every((g: { batchId: string; feature: string }) => g.batchId === batchId && g.feature === "photodump")).toBe(true);
+ expect(items[0].request.batchTitle).toBe("Winter special · Selfie");
+ expect(items[0].request.inputs.images).toEqual([selfie]);
+ expect((await settle(items[0].id)).status).toBe("succeeded");
+ }, 45_000);
+
+ it("makes a user pack and a character's photodump on the open engine", async () => {
+ const pack = await (await packsRoute.POST(json("POST", { name: "Mine", refs: [upload(), upload()] }))).json();
+ expect(pack.id).toMatch(/^user-/);
+ const el = createElement({ name: "Maya", kind: "character", references: [upload()] });
+ const { items } = await (await photodumpRoute.POST(json("POST", { packId: pack.id, engine: "open", elementId: el.id }))).json();
+ expect(items).toHaveLength(2);
+ expect(items[0].modelId).toBe("oss-qwen-edit");
+ // The pack's photo, then Maya's reference (her @mention resolves on the server).
+ expect(items[0].request.inputs.images).toEqual([pack.refs[0]]);
+ expect(items[0].request.prompt).toMatch(/^@Maya recreated in image 1/);
+ const bad = await photodumpRoute.POST(json("POST", { packId: "zen", engine: "cloud" }));
+ expect(bad.status).toBe(400);
+ });
+
+ it("runs the Fashion Factory steps", async () => {
+ const el = createElement({ name: "Ines", kind: "character", references: [upload()] });
+ const base = await (await fashionRoute.POST(json("POST", { step: "base", templateId: "red-room", elementId: el.id, engine: "cloud" }))).json();
+ expect(base.items[0]).toMatchObject({ modelId: "nano-banana-pro", feature: "fashion" });
+ expect(base.items[0].request.params).toMatchObject({ aspectRatio: "3:4", numOutputs: 4 });
+ const outfit = await (await fashionRoute.POST(json("POST", { step: "outfit", templateId: "red-room", base: upload(), garment: upload(), engine: "cloud" }))).json();
+ expect(outfit.items[0].modelId).toBe("fashn-tryon");
+ const set = await (await fashionRoute.POST(json("POST", { step: "photoset", templateId: "red-room", dressed: upload(), engine: "open" }))).json();
+ expect(set.items).toHaveLength(9);
+ expect(set.items.every((g: { modelId: string; batchId: string }) => g.modelId === "oss-qwen-edit" && g.batchId === set.batchId)).toBe(true);
+ const missing = await fashionRoute.POST(json("POST", { step: "photoset", templateId: "nope", dressed: upload(), engine: "open" }));
+ expect((await missing.json()).error).toBe("Template required");
+ });
+
+ it("makes character sheets from references, a Soul Cast build and a description", async () => {
+ const tooMany = await characterRoute.POST(json("POST", { mode: "reference", engine: "cloud", images: Array.from({ length: 6 }, upload) }));
+ expect((await tooMany.json()).error).toBe("Maximum 5 images");
+ const ref = await (await characterRoute.POST(json("POST", { mode: "reference", engine: "cloud", images: [upload(), upload()] }))).json();
+ expect(ref.items[0]).toMatchObject({ modelId: "nano-banana-pro", op: "edit", feature: "character-sheet" });
+ const cast = await (await characterRoute.POST(json("POST", { mode: "cast", engine: "open", cast: { genre: "Western", gender: "Female", age: 30, archetype: "Rebel" } }))).json();
+ expect(cast.items[0].modelId).toBe("oss-zimage-soul-cast");
+ expect(cast.items[0].prompt).toMatch(/30-year-old woman, the rebel archetype/);
+ const noKey = await (await characterRoute.POST(json("POST", { mode: "cast", engine: "cloud", cast: { genre: "Drama" } }))).json();
+ expect(noKey.items[0].modelId).toBe("nano-banana-pro");
+ expect(noKey.notes[0]).toMatch(/Higgsfield key/);
+ const app = await (await characterRoute.POST(json("POST", { mode: "describe", engine: "open", prompt: "a surfer from Lisbon" }))).json();
+ expect(app.items[0]).toMatchObject({ presetId: "app-ai-influencer", modelId: "oss-zimage-soul-cast", feature: "app:app-ai-influencer" });
+ });
+});
diff --git a/tests/image-studios.test.ts b/tests/image-studios.test.ts
new file mode 100644
index 00000000..0ef6f179
--- /dev/null
+++ b/tests/image-studios.test.ts
@@ -0,0 +1,492 @@
+import { describe, expect, it } from "vitest";
+import { getModel, getPreset } from "@/lib/catalog";
+import { castName, randomizeCast, SOUL_CAST_FIELDS } from "@/lib/catalog/cinema";
+import { applyMentions, type StudioElement } from "@/lib/catalog/elements";
+import { PHOTODUMP_PACKS, SOUL_DEFAULT, SOUL_PRESETS } from "@/lib/catalog/higgsfield-presets.generated";
+import {
+ castFieldVisible,
+ castNameFor,
+ castSheetModel,
+ customPack,
+ CURATED_MOODBOARDS,
+ FASHION,
+ FASHION_START,
+ fashionBaseRequest,
+ fashionBlocker,
+ fashionOutfitRequest,
+ fashionPhotosetRequests,
+ fashionReducer,
+ getPack,
+ inTab,
+ PACKS,
+ planPhotodump,
+ presetFallback,
+ presetPrompt,
+ presetTabs,
+ randomCast,
+ sheetFromReference,
+ shotPrompt,
+ type FashionState,
+ type PhotoSubject,
+} from "@/lib/catalog/packs";
+import {
+ applySignature,
+ cardStrip,
+ extractPalette,
+ kmeans,
+ normalizeHex,
+ paletteColors,
+ paletteError,
+ randomPalettes,
+ rng,
+ samplePixels,
+ suggestName,
+ type MoodboardPick,
+ type PalettePick,
+ type RGB,
+ type SignatureCaps,
+} from "@/lib/catalog/palettes";
+import { buildPayload } from "@/lib/catalog/payload";
+import { planGeneration } from "@/lib/catalog/plan";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import { collageGroups, colorFeature, coverCrop, imageProblem, moodboardError, moodboardStatus, representativeOrder } from "@/components/moodboards/logic";
+
+// The caps GET /api/palettes sends (src/server/palettes.ts signatureCaps, checked against the catalog in image-studios-api.test.ts).
+const CAPS: SignatureCaps = {
+ native: {
+ "recraft-4-1": { max: 10, background: "background_color" },
+ "recraft-4-1-pro": { max: 10, background: "background_color" },
+ "recraft-4-style": { max: 10, background: "background_color" },
+ "recraft-4-style-pro": { max: 10, background: "background_color" },
+ "recraft-4-style-saved": { max: 10, background: "background_color" },
+ "ideogram-3": { max: 12 },
+ },
+};
+const ctx = { caps: CAPS, getModel };
+const plan = (r: GenerationRequest) => planGeneration(r, getModel, getPreset);
+
+const fill = (rgb: RGB, n: number): RGB[] => Array.from({ length: n }, () => [...rgb] as RGB);
+const PAL: PalettePick = { id: "p1", name: "Teal Dusk", colors: ["#102030", "#2A9D8F", "#E9C46A", "#F4A261"], background: "#264653", slug: null };
+const CINEMA_PAL: PalettePick = { id: "builtin-static-noon", name: "Static Noon", colors: ["#0C0C0C", "#69483B"], background: "#69483B", slug: "static-noon" };
+
+describe("palettes: k-means extraction", () => {
+ it("finds each image's colours, gives every image a say, and orders them dark → light", () => {
+ const a = [...fill([200, 30, 30], 900), ...fill([20, 20, 20], 100)];
+ const b = fill([30, 60, 220], 50);
+ const r = extractPalette([a, b], { count: 4, seed: 1 });
+ expect(r.colors).toContain("#C81E1E");
+ expect(r.colors).toContain("#1E3CDC");
+ expect(r.colors).toContain("#141414");
+ // Dark → light by luminance.
+ expect(r.colors[0]).toBe("#141414");
+ // The dominant colour is the background.
+ expect(["#C81E1E", "#1E3CDC"]).toContain(r.background);
+ expect(r.weights.reduce((x, y) => x + y, 0)).toBeCloseTo(1, 1);
+ });
+
+ it("merges near-identical clusters and is deterministic", () => {
+ const px = [...fill([100, 100, 100], 500), ...fill([104, 102, 101], 500), ...fill([250, 250, 250], 200)];
+ const one = extractPalette([px], { count: 6, seed: 3 });
+ expect(one).toEqual(extractPalette([px], { count: 6, seed: 3 }));
+ expect(one.colors.length).toBeLessThanOrEqual(2);
+ });
+
+ it("k-means sorts clusters by share; samplePixels skips transparent pixels", () => {
+ const cl = kmeans([...fill([0, 0, 0], 30), ...fill([255, 255, 255], 70)], 2);
+ expect(cl.map((c) => c.color)).toEqual(["#FFFFFF", "#000000"]);
+ expect(cl[0].share).toBeCloseTo(0.7);
+ const rgba = [10, 20, 30, 255, 1, 2, 3, 0];
+ expect(samplePixels(rgba)).toEqual([[10, 20, 30]]);
+ expect(extractPalette([[]])).toEqual({ colors: [], background: null, weights: [] });
+ });
+
+ it("validates, normalises and names palettes; random palettes have 2–12 colours", () => {
+ expect(normalizeHex(" #abc ")).toBe("#AABBCC");
+ expect(normalizeHex("12345g")).toBeNull();
+ expect(paletteError({ name: "x", colors: [] })).toMatch(/at least one/);
+ expect(paletteError({ name: "x", colors: Array(13).fill("#FFFFFF") })).toMatch(/up to 12/);
+ expect(paletteError({ name: "x", colors: ["#GG0000"] })).toMatch(/isn't a colour/);
+ expect(paletteError({ name: "ok", colors: ["#FFFFFF"], background: "#000000" })).toBeNull();
+ expect(cardStrip({ colors: ["#111111", "#222222", "#111111"], background: "#222222" })).toEqual(["#222222", "#111111"]);
+ expect(paletteColors({ colors: ["#111111"], background: "#333333" })).toEqual(["#111111", "#333333"]);
+ expect(suggestName(["#0A0A0A", "#123456"])).toMatch(/\w+ \w+/);
+ for (const row of randomPalettes(rng(5))) {
+ expect(row.length).toBeGreaterThanOrEqual(2);
+ expect(row.length).toBeLessThanOrEqual(12);
+ expect(row.every((c) => /^#[0-9A-F]{6}$/.test(c))).toBe(true);
+ }
+ });
+});
+
+describe("palettes: routing per model", () => {
+ const req = (modelId: string, extra: Partial<GenerationRequest> = {}): GenerationRequest => ({ feature: "image", modelId, prompt: "a lighthouse at dusk", params: { numOutputs: 1 }, ...extra });
+
+ it("sends the palette field to Recraft (≤10 colours, background in its own field) and Ideogram", () => {
+ const r = applySignature(req("recraft-4-1"), { palette: PAL }, ctx);
+ expect(r.request.params?.palette).toEqual(PAL.colors);
+ expect(r.request.params?.extra?.background_color).toBe("#264653");
+ expect(r.request.prompt).toBe("a lighthouse at dusk");
+ const payload = buildPayload(getModel("recraft-4-1")!.routes[0].map!, { prompt: "x", palette: r.request.params!.palette, extra: r.request.params!.extra });
+ expect(payload.colors).toEqual([{ r: 16, g: 32, b: 48 }, { r: 42, g: 157, b: 143 }, { r: 233, g: 196, b: 106 }, { r: 244, g: 162, b: 97 }]);
+ expect(payload.background_color).toEqual({ r: 38, g: 70, b: 83 });
+
+ const twelve = { ...PAL, colors: Array.from({ length: 12 }, (_, i) => `#0000${(i * 16).toString(16).padStart(2, "0").toUpperCase()}`) };
+ const trimmed = applySignature(req("recraft-4-1"), { palette: twelve }, ctx);
+ expect(trimmed.request.params?.palette).toHaveLength(10);
+ expect(trimmed.notes.join()).toMatch(/takes 10 colours/);
+
+ const ideo = applySignature(req("ideogram-3"), { palette: PAL }, ctx);
+ expect(ideo.request.params?.palette).toEqual(PAL.colors);
+ expect(ideo.request.params?.extra).toBeUndefined();
+ });
+
+ it("writes the hex list into the prompt for other cloud models (Soul 2.0, Nano Banana Pro)", () => {
+ for (const id of ["nano-banana-pro", "soul-2", "gpt-image-2-5"]) {
+ const r = applySignature(req(id), { palette: PAL }, ctx);
+ expect(r.modelId).toBe(id);
+ expect(r.request.prompt).toMatch(/^a lighthouse at dusk\. Color palette: use only these colors.*#102030.*background color #264653\.$/);
+ expect(r.lock).toBeUndefined();
+ expect(() => plan(r.request)).not.toThrow();
+ }
+ });
+
+ it("passes a built-in palette's slug to Cinema Studio 4.0", () => {
+ const r = applySignature({ feature: "video", modelId: "cinema-studio-4", prompt: "a chase" }, { palette: CINEMA_PAL }, ctx);
+ expect(r.request.params?.extra?.color_palette).toBe("static-noon");
+ expect(r.request.prompt).toBe("a chase");
+ });
+
+ it("moves open Z-Image Turbo to Z-Image Turbo · Palette, and locks other open models with a post-step", () => {
+ const r = applySignature(req("oss-z-image-turbo", { params: { aspectRatio: "16:9", resolution: "1K" } }), { palette: PAL }, ctx);
+ expect(r.modelId).toBe("oss-zimage-palette");
+ expect(r.request.params?.palette).toEqual([...PAL.colors, "#264653"]);
+ expect(r.request.params?.aspectRatio).toBe("16:9");
+ expect(r.notes[0]).toMatch(/Z-Image Turbo · Palette/);
+ expect(plan(r.request).model.id).toBe("oss-zimage-palette");
+
+ const free = applySignature(req("oss-qwen-image"), { palette: PAL }, ctx);
+ expect(free.lock).toBeUndefined();
+ expect(free.request.prompt).toMatch(/Color palette/);
+ const locked = applySignature(req("oss-qwen-image"), { palette: { ...PAL, lock: true } }, ctx);
+ expect(locked.lock?.colors).toEqual([...PAL.colors, "#264653"]);
+ });
+
+ it("leaves requests alone without a signature or an unknown model", () => {
+ const r = req("nano-banana-pro");
+ expect(applySignature(r, undefined, ctx).request).toBe(r);
+ expect(applySignature({ ...r, modelId: "nope" }, { palette: PAL }, ctx).request.modelId).toBe("nope");
+ });
+});
+
+describe("moodboards: routing per model", () => {
+ const refs = Array.from({ length: 12 }, (_, i) => `/api/files/uploads/r${i}.png`);
+ const board: MoodboardPick = { id: "mb1", kind: "personal", name: "Neon Haze", status: "complete", refs: refs.slice(0, 10), collages: ["/api/files/uploads/c1.jpg", "/api/files/uploads/c2.jpg"] };
+ const curated: MoodboardPick = { id: CURATED_MOODBOARDS[0].id, kind: "curated", name: CURATED_MOODBOARDS[0].name, description: "Soul 2.0's neutral default look", status: "complete" };
+ const req = (modelId: string, images?: string[]): GenerationRequest => ({ feature: "image", modelId, prompt: "a rooftop party", inputs: images ? { images } : undefined, params: { numOutputs: 1 } });
+
+ it("curated looks are Soul 2.0's style_id on soul-2, words elsewhere (the open route's prompt template)", () => {
+ const soul = applySignature(req("soul-2"), { moodboard: curated }, ctx);
+ expect(soul.request.params?.extra?.style_id).toBe(curated.id);
+ expect(soul.request.prompt).toBe("a rooftop party");
+ const open = applySignature(req("oss-z-image-turbo"), { moodboard: curated }, ctx);
+ expect(open.modelId).toBe("oss-z-image-turbo");
+ expect(open.request.prompt).toBe(presetPrompt({ name: curated.name, description: curated.description! }, "a rooftop party"));
+ });
+
+ it("personal boards: style references on multi-reference cloud models, Nano Banana Pro for the rest", () => {
+ const nano = applySignature(req("nano-banana-pro", ["/api/files/uploads/own.png"]), { moodboard: board }, ctx);
+ expect(nano.request.op).toBe("edit");
+ expect(nano.request.inputs?.images).toEqual(["/api/files/uploads/own.png", ...refs.slice(0, 6)]);
+ expect(nano.request.prompt).toMatch(/Use images 2–7 only as a style reference/);
+ expect(plan(nano.request).op).toBe("edit");
+
+ const soul = applySignature(req("soul-2"), { moodboard: board }, ctx);
+ expect(soul.modelId).toBe("nano-banana-pro");
+ expect(soul.notes[0]).toMatch(/can't take style references/);
+ expect(soul.request.inputs?.images).toHaveLength(6);
+ });
+
+ it("Recraft models use the board's saved style id, or its 10 images on Recraft V4 Styles", () => {
+ const saved = applySignature(req("recraft-4-1"), { moodboard: { ...board, styleId: "3f6c1a2b-0000-4000-8000-000000000000" } }, ctx);
+ expect(saved.modelId).toBe("recraft-4-style-saved");
+ expect(saved.request.params?.styleId).toBe("3f6c1a2b-0000-4000-8000-000000000000");
+ const p = plan(saved.request);
+ expect(p.op).toBe("t2i");
+ expect(buildPayload(p.model.routes[0].map!, { prompt: p.prompt, styleId: p.params.styleId })).toMatchObject({ prompt: "a rooftop party", style_id: "3f6c1a2b-0000-4000-8000-000000000000" });
+
+ const fresh = applySignature(req("recraft-4-1"), { moodboard: board }, ctx);
+ expect(fresh.modelId).toBe("recraft-4-style");
+ expect(fresh.request.inputs?.images).toEqual(refs.slice(0, 10));
+ expect(plan(fresh.request).op).toBe("edit");
+ });
+
+ it("open engine: collages on Qwen-Image-Edit Style Reference, single refs on FLUX.2 klein, the trained LoRA on Z-Image Turbo", () => {
+ const def = applySignature(req("oss-z-image-turbo"), { moodboard: board }, ctx);
+ expect(def.modelId).toBe("oss-style-qwen-edit");
+ expect(def.request.inputs?.images).toEqual(board.collages);
+ expect(() => plan(def.request)).not.toThrow();
+
+ const klein = applySignature(req("oss-style-flux2-klein"), { moodboard: board }, ctx);
+ expect(klein.modelId).toBe("oss-style-flux2-klein");
+ expect(klein.request.inputs?.images).toEqual(refs.slice(0, 4));
+
+ const lora = applySignature(req("oss-z-image-turbo"), { moodboard: { ...board, loraHandle: "Neon_Haze" } }, ctx);
+ expect(lora.modelId).toBe("oss-z-image-turbo");
+ expect(lora.request.prompt).toBe("a rooftop party. In the style of @Neon_Haze.");
+ });
+
+ it("a board that isn't ready blocks with Higgsfield's copy; palette + moodboard combine", () => {
+ expect(applySignature(req("nano-banana-pro"), { moodboard: { ...board, status: "running" } }, ctx).blocker).toBe("This moodboard is still training. Try again once it is ready.");
+ const both = applySignature(req("oss-z-image-turbo"), { moodboard: board, palette: PAL }, ctx);
+ // The moodboard moves it to the style model, which then gets the palette in words (not the palette model).
+ expect(both.modelId).toBe("oss-style-qwen-edit");
+ expect(both.request.prompt).toMatch(/Color palette/);
+ });
+});
+
+describe("Soul presets fallback", () => {
+ it("maps the researched list per source with Higgsfield's categories", () => {
+ const v1 = presetFallback("soul-v1")!;
+ expect(v1.items).toHaveLength(106);
+ expect(v1.categories).toEqual(["New", "TikTok Core", "Instagram Aesthetics", "Camera Presets", "Beauty", "Mood", "Surreal", "Graphic Art"]);
+ const tabs = presetTabs(v1.items, v1.categories);
+ expect(tabs[0]).toBe("All");
+ expect(v1.items.filter((p) => inTab(p, "Graphic Art")).map((p) => p.name)).toContain("Glitch");
+ expect(v1.items.filter((p) => inTab(p, "New"))).toHaveLength(10);
+ expect(v1.items.find((p) => p.id === SOUL_DEFAULT["soul-v1"])?.name).toBe("General");
+ const v2 = presetFallback("soul-v2")!;
+ expect(v2.items).toHaveLength(33);
+ expect(v2.categories).toEqual(["Mood", "Styles", "Camera"]);
+ expect(v2.items.every((p) => p.hue >= 0 && p.hue < 360)).toBe(true);
+ expect(presetFallback("genjutsu-restyle")).toBeNull();
+ expect(new Set(SOUL_PRESETS.map((p) => p.id)).size).toBe(SOUL_PRESETS.length);
+ });
+
+ it("turns a preset into a prompt template for the open route", () => {
+ expect(presetPrompt({ name: "Retro BW", description: "Grainy black-and-white film portrait" }, "a dancer ")).toBe("a dancer. In the style of “Retro BW”: grainy black-and-white film portrait.");
+ expect(presetPrompt({ name: "Retro BW", description: "" }, "")).toBe("A photo. In the style of “Retro BW”.");
+ });
+});
+
+describe("Photodump packs and planning", () => {
+ const maya: PhotoSubject = { kind: "element", handle: "Maya", name: "Maya", references: ["/api/files/uploads/m1.png", "/api/files/uploads/m2.png"], loras: [] };
+ const selfie: PhotoSubject = { kind: "selfie", url: "/api/files/uploads/me.jpg" };
+
+ it("has exactly as many photo prompts as Higgsfield's packs have photos", () => {
+ expect(PACKS).toHaveLength(14);
+ for (const p of PACKS) {
+ expect(p.shots, p.name).toHaveLength(p.count);
+ expect(new Set(p.shots).size, p.name).toBe(p.count);
+ }
+ expect(PHOTODUMP_PACKS.filter((p) => p.product === "instadump").map((p) => [p.name, p.count])).toEqual([
+ ["Winter special", 9],
+ ["Aura farming", 14],
+ ["Looksmaxing", 15],
+ ["2000s nostalgia", 15],
+ ["Editorial shots", 15],
+ ]);
+ });
+
+ it("builds per-photo prompts: @mention for a character, image 1 for a selfie, the reference photo in user packs", () => {
+ const pack = getPack("zen")!;
+ expect(shotPrompt(pack, pack.shots[0], maya)).toMatch(/^A photo of @Maya, seated cross-legged/);
+ expect(shotPrompt(pack, pack.shots[0], selfie)).toMatch(/^A photo of The person in image 1, .*Keep their exact face/);
+ const mine = customPack({ id: "user-1", name: "Mine", refs: ["/api/files/uploads/a.png", "/api/files/uploads/b.png"] });
+ expect(mine.count).toBe(2);
+ expect(shotPrompt(mine, mine.shots[0], selfie, 2)).toMatch(/^The person in image 1 recreated in image 2: .*Replace the person in image 2/);
+ });
+
+ it("plans one single-image request per photo, on the identity's own model when it has one", () => {
+ const pack = getPack("winter-special")!;
+ const cloud = planPhotodump({ pack, subject: maya, engine: "cloud", aspectRatio: "3:4" }, { higgsfield: false });
+ expect(cloud.modelId).toBe("nano-banana-pro");
+ expect(cloud.requests).toHaveLength(9);
+ expect(cloud.requests[2].step).toEqual({ label: "Photo 3 of 9", index: 2, of: 9 });
+ expect(cloud.requests.every((r) => r.params?.numOutputs === 1 && r.params.aspectRatio === "3:4" && r.feature === "photodump")).toBe(true);
+
+ const soulMaya: PhotoSubject = { ...maya, loras: [{ engine: "cloud", modelId: "soul-2", file: "", trigger: "", referenceId: "ref-123" }] };
+ expect(planPhotodump({ pack, subject: soulMaya, engine: "cloud" }, { higgsfield: true }).modelId).toBe("soul-2");
+ const noKey = planPhotodump({ pack, subject: soulMaya, engine: "cloud", modelId: "soul-2" }, { higgsfield: false });
+ expect(noKey.modelId).toBe("nano-banana-pro");
+ expect(noKey.notes[0]).toMatch(/Higgsfield key/);
+ expect(planPhotodump({ pack, subject: maya, engine: "cloud", modelId: "seedream-5-pro" }, { higgsfield: false }).modelId).toBe("seedream-5-pro");
+
+ const loraMaya: PhotoSubject = { ...maya, loras: [{ engine: "open", modelId: "oss-z-image-turbo", file: "maya.safetensors", trigger: "mayfz" }] };
+ expect(planPhotodump({ pack, subject: loraMaya, engine: "open" }, { higgsfield: false }).modelId).toBe("oss-z-image-turbo");
+ const qwen = planPhotodump({ pack, subject: selfie, engine: "open", aspectRatio: "auto" }, { higgsfield: false });
+ expect(qwen.modelId).toBe("oss-qwen-edit");
+ expect(qwen.requests[0].inputs?.images).toEqual([selfie.url]);
+ expect(qwen.requests[0].params?.aspectRatio).toBeUndefined();
+
+ const mine = customPack({ id: "user-1", name: "Mine", refs: ["/api/files/uploads/a.png", "/api/files/uploads/b.png"] });
+ const custom = planPhotodump({ pack: mine, subject: selfie, engine: "cloud" }, { higgsfield: true });
+ expect(custom.requests.map((r) => r.inputs?.images)).toEqual([
+ [selfie.url, "/api/files/uploads/a.png"],
+ [selfie.url, "/api/files/uploads/b.png"],
+ ]);
+ expect(() => planPhotodump({ pack, subject: { ...maya, references: [] }, engine: "cloud" }, { higgsfield: false })).toThrow(/Add a photo of Maya/);
+ });
+
+ it("each planned photo resolves and plans (mentions become references, LoRAs or a Soul ID)", () => {
+ const el = (loras: StudioElement["loras"]): StudioElement => ({ id: "e1", name: "Maya", handle: "Maya", kind: "character", description: null, references: ["/api/files/uploads/m1.png"], loras, status: "ready", createdAt: 0 });
+ const check = (subject: PhotoSubject, engine: "cloud" | "open", element: StudioElement) => {
+ const p = planPhotodump({ pack: getPack("zen")!, subject, engine, aspectRatio: "3:4" }, { higgsfield: true });
+ const r = p.requests[0];
+ const resolved = applyMentions(r, getModel(r.modelId)!, [element]).request;
+ return { resolved, plan: plan(resolved) };
+ };
+ const refs = check(maya, "cloud", el([]));
+ expect(refs.plan.op).toBe("edit");
+ expect(refs.resolved.inputs?.images).toEqual(["/api/files/uploads/m1.png"]);
+ const soulLoras = [{ engine: "cloud" as const, modelId: "soul-2", file: "", trigger: "", referenceId: "ref-1" }];
+ const soul = check({ ...maya, loras: soulLoras }, "cloud", el(soulLoras));
+ expect(soul.resolved.params?.extra?.custom_reference_id).toBe("ref-1");
+ expect(soul.plan.model.id).toBe("soul-2");
+ const turbo = [{ engine: "open" as const, modelId: "oss-z-image-turbo", file: "maya.safetensors", trigger: "mayfz" }];
+ const lora = check({ ...maya, loras: turbo }, "open", el(turbo));
+ expect(lora.plan.loras[0].file).toBe("maya.safetensors");
+ expect(lora.plan.prompt).toMatch(/mayfz Maya/);
+ });
+});
+
+describe("Fashion Factory", () => {
+ const maya = { kind: "element" as const, handle: "Maya", name: "Maya", references: ["/api/files/uploads/m1.png"], loras: [] };
+
+ it("has the six templates with one photoset prompt per preview shot", () => {
+ expect(FASHION.map((t) => t.name)).toEqual(["Ultra bold", "Blue-Green Gradient", "Street style Paparazzi", "View from the top", "Light blue studio", "Red room"]);
+ for (const t of FASHION) expect(t.photoset, t.name).toHaveLength(t.shots);
+ });
+
+ it("plans the three generating steps on both engines", () => {
+ const t = FASHION[0];
+ const base = fashionBaseRequest(t, maya, "cloud", { higgsfield: false });
+ expect(base).toMatchObject({ modelId: "nano-banana-pro", params: { aspectRatio: "3:4", numOutputs: 4 } });
+ expect(base.prompt).toMatch(/@Maya in a bold, saturated colour-blocked studio set/);
+ expect(fashionBaseRequest(t, maya, "open", { higgsfield: false }).modelId).toBe("oss-qwen-edit");
+
+ const outfit = fashionOutfitRequest(t, "/api/files/base.png", "/api/files/shirt.png", "cloud");
+ expect(outfit).toMatchObject({ modelId: "fashn-tryon", op: "edit", inputs: { images: ["/api/files/base.png", "/api/files/shirt.png"] } });
+ expect(plan(outfit).op).toBe("edit");
+ expect(fashionOutfitRequest(t, "b", "g", "cloud", "nano-banana-pro").prompt).toMatch(/Dress the person in image 1/);
+ const openOutfit = fashionOutfitRequest(t, "/api/files/base.png", "/api/files/shirt.png", "open");
+ expect(openOutfit.modelId).toBe("oss-tryon-klein");
+ expect(() => plan(openOutfit)).not.toThrow();
+
+ const set = fashionPhotosetRequests(t, "/api/files/dressed.png", "cloud");
+ expect(set).toHaveLength(t.shots);
+ expect(set[0]).toMatchObject({ modelId: "nano-banana-pro", inputs: { images: ["/api/files/dressed.png"] }, step: { label: `Photoset 1 of ${t.shots}` } });
+ expect(fashionPhotosetRequests(t, "/api/files/dressed.png", "open")[0].modelId).toBe("oss-qwen-edit");
+ });
+
+ it("walks the wizard with Higgsfield's validation messages", () => {
+ let s: FashionState = FASHION_START;
+ expect(fashionBlocker(s)).toBe("Template required");
+ expect(fashionReducer(s, { type: "next" })).toBe(s);
+ s = fashionReducer(s, { type: "template", id: "red-room" });
+ s = fashionReducer(s, { type: "next" });
+ expect(s.step).toBe("character");
+ expect(fashionBlocker(s)).toMatch(/character/);
+ s = fashionReducer(s, { type: "element", id: "el1" });
+ s = fashionReducer(s, { type: "baseStarted", ids: ["g1", "g2"] });
+ expect(s.step).toBe("generation");
+ expect(fashionBlocker(s)).toBe("Select an image at the generation step");
+ s = fashionReducer(s, { type: "pickBase", url: "/api/files/b.png" });
+ s = fashionReducer(s, { type: "next" });
+ expect(s.step).toBe("clothing");
+ expect(fashionBlocker(s, "outfit")).toBe("No product to generate");
+ s = fashionReducer(s, { type: "garment", garment: { url: "", uploading: true } });
+ expect(fashionBlocker(s, "outfit")).toBe("Please wait for the image to finish processing before generating");
+ s = fashionReducer(s, { type: "garment", garment: { url: "/api/files/g.png", uploading: false } });
+ expect(fashionBlocker(s, "outfit")).toBeNull();
+ expect(fashionBlocker(s)).toBe("Select an image at the clothing step");
+ s = fashionReducer(s, { type: "outfitStarted", ids: ["o1"] });
+ s = fashionReducer(s, { type: "pickOutfit", url: "/api/files/o.png" });
+ s = fashionReducer(s, { type: "photosetStarted", batchId: "b1" });
+ expect(s.step).toBe("photoset");
+ // Back to an earlier step keeps the picks; a new template starts over (but keeps the character).
+ expect(fashionReducer(s, { type: "goto", step: "template" }).outfit).toBe("/api/files/o.png");
+ const fresh = fashionReducer(s, { type: "template", id: "ultra-bold" });
+ expect(fresh).toMatchObject({ step: "template", templateId: "ultra-bold", elementId: "el1", baseIds: [] });
+ expect(fresh.outfit).toBeUndefined();
+ // Jumping ahead stops at the first step that isn't done.
+ expect(fashionReducer({ ...FASHION_START, templateId: "red-room" }, { type: "goto", step: "photoset" }).step).toBe("character");
+ expect(fashionReducer(s, { type: "reset" })).toBe(FASHION_START);
+ });
+});
+
+describe("Character Sheet", () => {
+ it("From Reference takes 1–5 photos (3 on the open route)", () => {
+ const imgs = Array.from({ length: 5 }, (_, i) => `/api/files/uploads/p${i}.png`);
+ expect(() => sheetFromReference([], "cloud")).toThrow("Upload at least 1 image");
+ expect(() => sheetFromReference([...imgs, "x"], "cloud")).toThrow("Maximum 5 images");
+ const cloud = sheetFromReference(imgs, "cloud", "freckles");
+ expect(cloud.request).toMatchObject({ modelId: "nano-banana-pro", op: "edit", inputs: { images: imgs } });
+ expect(cloud.request.prompt).toMatch(/turnaround sheet.*freckles\.$/);
+ const open = sheetFromReference(imgs, "open");
+ expect(open.request.inputs?.images).toHaveLength(3);
+ expect(open.notes[0]).toMatch(/first 3/);
+ expect(() => plan(open.request)).not.toThrow();
+ });
+
+ it("Build from scratch runs on Soul 2.0 / Nano Banana Pro or the Soul Cast sheet workflow", () => {
+ expect(castSheetModel("cloud", { higgsfield: true })).toBe("soul-2");
+ expect(castSheetModel("cloud", { higgsfield: false })).toBe("nano-banana-pro");
+ expect(castSheetModel("open", { higgsfield: false, has: () => true })).toBe("oss-zimage-soul-cast");
+ expect(castSheetModel("open", { higgsfield: false, has: () => false })).toBe("oss-z-image-turbo");
+ });
+
+ it("randomizes and names a cast like Cinema Studio", () => {
+ const fields = SOUL_CAST_FIELDS.map((f) => ({ key: f.key, label: f.label, tab: f.tab, kind: f.kind, options: f.options }));
+ for (const seed of [1, 2, 3, 4, 5]) {
+ expect(randomCast(fields, { budget: 250 }, rng(seed))).toEqual(randomizeCast({ budget: 250 }, rng(seed)));
+ }
+ for (const v of [{ archetype: "Rebel", age: 30 }, { archetype: "Sage" }, { genre: "Western" }, {}]) expect(castNameFor(v)).toBe(castName(v));
+ });
+
+ it("hides the same Soul Cast fields as Cinema Studio", () => {
+ const cases = [{ gender: "Female" }, { gender: "Male" }, { gender: "Male", facial_hair: "Beard" }, { gender: "Male", facial_hair: "Clean-shaven" }, {}];
+ for (const v of cases) for (const f of SOUL_CAST_FIELDS) expect(castFieldVisible(f.key, v), `${f.key} ${JSON.stringify(v)}`).toBe(f.when ? f.when(v) : true);
+ });
+});
+
+describe("moodboard logic", () => {
+ it("uses Higgsfield's limits and copy", () => {
+ const five = Array.from({ length: 5 }, (_, i) => `i${i}`);
+ expect(moodboardError({ name: "x", images: five.slice(0, 4) })).toBe("Upload at least 5 photos to continue.");
+ expect(moodboardError({ name: "x", images: Array(81).fill("i") })).toBe("Maximum images per moodboard is 80");
+ expect(moodboardError({ name: " ", images: five })).toBe("Please enter a moodboard name");
+ expect(moodboardError({ name: "x".repeat(101), images: five })).toBe("Name is too long, maximum 100 characters allowed");
+ expect(moodboardError({ name: "Ok", images: five })).toBeNull();
+ expect(imageProblem({ width: 255, height: 900, key: "a" }, [])).toBe("Image dimensions too small: minimum size is 256x256px.");
+ expect(imageProblem({ width: 300, height: 300, key: "a" }, ["a"])).toBe("This image is already added");
+ expect(imageProblem({ width: 256, height: 256, key: "b" }, ["a"])).toBeNull();
+ });
+
+ it("follows the cover job: In queue → In progress → Preparing cover → Complete / Failed", () => {
+ expect(moodboardStatus({ status: "queued", progress: null, error: null }).status).toBe("queued");
+ expect(moodboardStatus({ status: "running", progress: 0.2, error: null }).status).toBe("running");
+ expect(moodboardStatus({ status: "running", progress: 0.7, error: null }).status).toBe("cover");
+ expect(moodboardStatus({ status: "succeeded", progress: 1, error: null }).status).toBe("complete");
+ expect(moodboardStatus({ status: "failed", progress: null, error: "boom" })).toEqual({ status: "failed", error: "boom" });
+ expect(moodboardStatus(null).status).toBe("failed");
+ });
+
+ it("orders images so the first ones cover the board's range, and groups collages of 4", () => {
+ const red = colorFeature(fill([220, 20, 20], 50));
+ const blue = colorFeature(fill([20, 20, 220], 50));
+ const order = representativeOrder([red, red, red, blue, red]);
+ // The typical (red) one first, then the outlier that represents the rest, not another red.
+ expect(order[0]).toBe(0);
+ expect(order[1]).toBe(3);
+ expect(order).toHaveLength(5);
+ expect(collageGroups([1, 2, 3, 4, 5, 6, 7, 8, 9])).toEqual([
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ ]);
+ expect(collageGroups([1, 2, 3, 4, 5, 6])).toEqual([
+ [1, 2, 3, 4],
+ [5, 6, 3, 4],
+ ]);
+ expect(coverCrop(200, 100, 50, 50)).toEqual({ sx: 50, sy: 0, sw: 100, sh: 100 });
+ });
+});