The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Moodboards: ready without a cover job, style LoRA preset, cloud-only refusal, Soul 2.0 preset cards; tests
Claudedcef1bcdae6a
diff --git a/src/components/moodboards/create-moodboard.tsx b/src/components/moodboards/create-moodboard.tsxindex aa75f70c..3a4f68a5 100644--- a/src/components/moodboards/create-moodboard.tsx+++ b/src/components/moodboards/create-moodboard.tsx@@ -9,7 +9,7 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } fimport { Input } from "@/components/ui/input";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { LibraryGrid } from "@/components/studio/media-slot";-import { uploadFile, useEngine } from "@/lib/api";+import { uploadFile, useEngine, useStatus } from "@/lib/api";import type { RGB } from "@/lib/catalog/palettes";import { cn } from "@/lib/utils";import { useMoodboardActions } from "./hooks";@@ -45,6 +45,8 @@ export function CreateMoodboardDialog({ open, onOpenChange, onCreated }: { open:const [libraryOpen, setLibraryOpen] = useState(false);const input = useRef<HTMLInputElement>(null);const [engine] = useEngine();+ const status = useStatus();+ const [over, setOver] = useState(false);const { create } = useMoodboardActions();const keys = useRef(new Set<string>());@@ -126,6 +128,35 @@ export function CreateMoodboardDialog({ open, onOpenChange, onCreated }: { open:};const q = quality(items.length);+ // "Upload from assets": the Library's images, before and after the first one is added.+ const assets = (+ <Popover open={libraryOpen} onOpenChange={setLibraryOpen}>+ <PopoverTrigger asChild>+ <Button size="sm" variant="outline">+ <Library /> Upload from assets+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-80 p-2" collisionPadding={12}>+ <p className="px-1 pb-2 text-[12.5px] text-muted-foreground">Use images you've already created</p>+ {libraryOpen && <LibraryGrid kinds={["image"]} onPick={(v) => void add({ url: v.ref, key: v.ref })} />}+ </PopoverContent>+ </Popover>+ );+ // What making the board does on this engine, and what it costs (the cloud cover job is a Recraft V4 Styles run).+ const n = Math.min(items.length, MOODBOARD_LIMITS.refs);+ const st = status.data;+ const fal = !!st?.providers.fal?.configured;+ const demo = st?.demoMode === "on" || (!fal && st?.demoMode !== "off");+ const how =+ engine === "open"+ ? `Open source: collages for Qwen-Image-Edit from the ${n} most representative images`+ : !st+ ? `Cloud: a Recraft style from the ${n} most representative images`+ : demo+ ? `Cloud: a Recraft style from the ${n} most representative images · demo, free`+ : fal+ ? `Cloud: Recraft V4 Styles saves a style and draws the cover from the ${n} most representative images · ≈ $0.04 on fal`+ : `Cloud: no fal key, so no saved Recraft style — the ${n} most representative images are used as references`;return (<Dialog open={open} onOpenChange={setOpen}><DialogContent@@ -152,69 +183,63 @@ export function CreateMoodboardDialog({ open, onOpenChange, onCreated }: { open:</div><input ref={input} type="file" accept="image/png,image/jpeg,image/webp" multiple hidden onChange={(e) => (addFiles(e.target.files ?? []), (e.target.value = ""))} />- {items.length === 0 ? (- <div- onDragOver={(e) => e.preventDefault()}- onDrop={(e) => {- e.preventDefault();- addFiles(e.dataTransfer.files);- }}- className="flex flex-col items-center gap-3 rounded-xl border border-dashed px-4 py-8 text-center"- >- <ImagePlus className="size-7 text-muted-foreground" />- <div className="flex flex-wrap justify-center gap-2">- <Button size="sm" onClick={() => input.current?.click()}>- <Upload /> Upload from device- </Button>- <Popover open={libraryOpen} onOpenChange={setLibraryOpen}>- <PopoverTrigger asChild>- <Button size="sm" variant="outline">- <Library /> Upload from assets- </Button>- </PopoverTrigger>- <PopoverContent className="w-80 p-2" collisionPadding={12}>- <p className="px-1 pb-2 text-[12.5px] text-muted-foreground">Use images you've already created</p>- {libraryOpen && <LibraryGrid kinds={["image"]} onPick={(v) => void add({ url: v.ref, key: v.ref })} />}- </PopoverContent>- </Popover>+ <div+ onDragOver={(e) => (e.preventDefault(), setOver(true))}+ onDragLeave={() => setOver(false)}+ onDrop={(e) => {+ e.preventDefault();+ setOver(false);+ addFiles(e.dataTransfer.files);+ }}+ className={cn("rounded-xl transition-colors", over && "bg-brand-faint ring-2 ring-primary/50")}+ >+ {items.length === 0 ? (+ <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed px-4 py-8 text-center">+ <ImagePlus className="size-7 text-muted-foreground" />+ <div className="flex flex-wrap justify-center gap-2">+ <Button size="sm" onClick={() => input.current?.click()}>+ <Upload /> Upload from device+ </Button>+ {assets}+ </div>+ <p className="text-[12px] text-muted-foreground">PNG, JPG or Paste from clipboard</p></div>- <p className="text-[12px] text-muted-foreground">PNG, JPG or Paste from clipboard</p>- </div>- ) : (- <div className="grid grid-cols-4 gap-1.5 sm:grid-cols-6">- {items.map((it, i) => (- <div key={it.id} className="relative aspect-square overflow-hidden rounded-lg bg-muted">- {/* eslint-disable-next-line @next/next/no-img-element */}- <img src={it.preview} alt="" className="size-full object-cover" />- {it.uploading && (- <span className="absolute inset-0 grid place-items-center bg-background/60" role="status" aria-label="Uploading">- <Loader2 className="size-4 animate-spin" />- </span>- )}+ ) : (+ <div className="grid grid-cols-4 gap-1.5 sm:grid-cols-6">+ {items.map((it, i) => (+ <div key={it.id} className="relative aspect-square overflow-hidden rounded-lg bg-muted">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={it.preview} alt="" className="size-full object-cover" />+ {it.uploading && (+ <span className="absolute inset-0 grid place-items-center bg-background/60" role="status" aria-label="Uploading">+ <Loader2 className="size-4 animate-spin" />+ </span>+ )}+ <button+ type="button"+ onClick={() => remove(it)}+ aria-label={`Remove image ${i + 1}`}+ 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>+ ))}+ {items.length < MOODBOARD_LIMITS.max && (<buttontype="button"- onClick={() => remove(it)}- aria-label={`Remove image ${i + 1}`}- className="absolute top-0.5 right-0.5 grid size-5 place-items-center rounded-full bg-foreground/80 text-background"+ onClick={() => input.current?.click()}+ className="grid aspect-square place-items-center rounded-lg border border-dashed text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ aria-label="Add image">- <X className="size-3" />+ <span className="flex flex-col items-center gap-1 text-[11.5px]">+ <Plus className="size-4" /> Add image+ </span></button>- </div>- ))}- {items.length < MOODBOARD_LIMITS.max && (- <button- type="button"- onClick={() => input.current?.click()}- className="grid aspect-square place-items-center rounded-lg border border-dashed text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"- aria-label="Add image"- >- <span className="flex flex-col items-center gap-1 text-[11.5px]">- <Plus className="size-4" /> Add image- </span>- </button>- )}- </div>- )}+ )}+ </div>+ )}+ </div>{items.length > 0 && (<div className="flex flex-wrap items-center gap-3">@@ -226,9 +251,12 @@ export function CreateMoodboardDialog({ open, onOpenChange, onCreated }: { open:{q.label} · {items.length}/{MOODBOARD_LIMITS.max}</span></div>- <Button size="sm" variant="outline" onClick={() => input.current?.click()}>- <Upload /> Upload more- </Button>+ <div className="flex gap-2">+ <Button size="sm" variant="outline" onClick={() => input.current?.click()}>+ <Upload /> Upload more+ </Button>+ {assets}+ </div></div>)}@@ -243,7 +271,7 @@ export function CreateMoodboardDialog({ open, onOpenChange, onCreated }: { open:</label><div className="flex items-center justify-between gap-2">- <p className="text-[12px] text-muted-foreground">{items.length < MOODBOARD_LIMITS.min ? COPY.tooFew : `${engine === "open" ? "Open source: collages for Qwen-Image-Edit" : "Cloud: a Recraft style"} from the ${Math.min(items.length, MOODBOARD_LIMITS.refs)} most representative images`}</p>+ <p className="text-[12px] text-muted-foreground">{items.length < MOODBOARD_LIMITS.min ? COPY.tooFew : how}</p><Button onClick={submit} disabled={busy}>{busy && <Loader2 className="animate-spin" />} Create moodboard</Button>diff --git a/src/components/moodboards/soul-preset-cards.tsx b/src/components/moodboards/soul-preset-cards.tsxnew file mode 100644index 00000000..ef9238fb--- /dev/null+++ b/src/components/moodboards/soul-preset-cards.tsx@@ -0,0 +1,42 @@+"use client";++import { Images, UserRoundPlus } from "lucide-react";+import Link from "next/link";+import { useStudio } from "@/components/studio/studio-context";++/**+ * The empty Image studio on Soul 2.0: Higgsfield's two "Make Soul 2.0 Preset" cards — a character of+ * your own (Character Sheet, then a Soul ID from its page) and a moodboard of your own. Kept free of+ * the moodboard logic (and the preset list it imports): every studio page loads it.+ */+export function SoulPresetCards() {+ const { draft } = useStudio();+ if (draft.modelId !== "soul-2") return null;+ const card =+ "group flex min-w-0 items-center gap-3 rounded-2xl border bg-background p-3 text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50";+ return (+ <section aria-label="Make Soul 2.0 Preset" className="mx-auto w-full max-w-[760px] px-3 pb-10">+ <p className="mb-2 text-center text-[12.5px] font-medium text-muted-foreground">Make Soul 2.0 Preset</p>+ <div className="grid gap-2 sm:grid-cols-2">+ <Link href="/character-sheet" className={card}>+ <span className="grid size-10 shrink-0 place-items-center rounded-xl bg-brand-faint text-brand-text">+ <UserRoundPlus className="size-5" />+ </span>+ <span className="min-w-0">+ <span className="block text-[13.5px] font-medium">Make your own character</span>+ <span className="block truncate text-[12px] text-muted-foreground">A consistent face for every shot — train a Soul ID from it</span>+ </span>+ </Link>+ <Link href="/moodboards?create=1" className={card}>+ <span className="grid size-10 shrink-0 place-items-center rounded-xl bg-brand-faint text-brand-text">+ <Images className="size-5" />+ </span>+ <span className="min-w-0">+ <span className="block text-[13.5px] font-medium">Create your moodboard</span>+ <span className="block truncate text-[12px] text-muted-foreground">20+ photos, one cohesive style, no faces.</span>+ </span>+ </Link>+ </div>+ </section>+ );+}diff --git a/src/lib/catalog/training.ts b/src/lib/catalog/training.tsindex d0478d02..466851c9 100644--- a/src/lib/catalog/training.ts+++ b/src/lib/catalog/training.ts@@ -77,8 +77,19 @@ export function triggerFor(handle: string): string {return `${(consonants.length >= 3 ? consonants : base).slice(0, 6) || "elem"}fz`;}-/** AI-Toolkit job config for a Z-Image Turbo character LoRA (docs/research/comfyui-oss-2.json → character-lora). */-export function aiToolkitJob(opts: { name: string; trigger: string; datasetFolder: string; outputFolder: string; steps?: number }) {+/** What a dataset's captions say: a person ("photo of <trigger>") or a look ("<trigger> style"). */+export function trainingCaption(kind: "character" | "style", trigger: string, description?: string | null): string {+ const extra = description?.trim().replace(/[.\s]+$/, "");+ return `${kind === "style" ? `${trigger} style` : `photo of ${trigger}`}${extra ? `, ${extra}` : ""}`;+}++/**+ * AI-Toolkit job config for a Z-Image Turbo LoRA (docs/research/comfyui-oss-2.json → character-lora).+ * `kind: "style"` is the style preset (a moodboard): fewer steps and samples of new scenes in the+ * look, instead of portraits of the person.+ */+export function aiToolkitJob(opts: { name: string; trigger: string; datasetFolder: string; outputFolder: string; steps?: number; kind?: "character" | "style" }) {+ const style = opts.kind === "style";return {job: "extension",config: {@@ -107,7 +118,7 @@ export function aiToolkitJob(opts: { name: string; trigger: string; datasetFoldedtype: "bf16",cache_text_embeddings: true,ema_config: { use_ema: false },- steps: opts.steps ?? 2500,+ steps: opts.steps ?? (style ? 1500 : 2500),timestep_type: "weighted",},model: {@@ -127,7 +138,9 @@ export function aiToolkitJob(opts: { name: string; trigger: string; datasetFoldeheight: 1024,seed: 42,walk_seed: true,- prompts: [`photo of ${opts.trigger}, close-up portrait, natural window light`, `${opts.trigger} walking in a neon-lit street at night, full body`],+ prompts: style+ ? [`a city street at night, ${opts.trigger} style`, `a bowl of fruit on a wooden table, ${opts.trigger} style`, `a portrait of a woman in a garden, ${opts.trigger} style`]+ : [`photo of ${opts.trigger}, close-up portrait, natural window light`, `${opts.trigger} walking in a neon-lit street at night, full body`],neg: "",guidance_scale: 1,sample_steps: 9,diff --git a/src/server/moodboards.ts b/src/server/moodboards.tsindex 9590fb49..e1837e4f 100644--- a/src/server/moodboards.ts+++ b/src/server/moodboards.ts@@ -125,8 +125,11 @@ function startPrep(id: string, name: string, images: string[], collages: string[title: `Moodboard cover · ${name}`,});update(id, { generation_id: g.id, status: "queued", error: null, cover_url: null, style_id: null, engine });- } catch (e) {- update(id, { status: "failed", error: (e as Error).message });+ } catch {+ // The cover job can't start (no fal key with demo mode off, say). The board still works from its own+ // images — style references on the cloud, collages on the open engine — so it's ready now, with its+ // first image as the cover and no saved Recraft style (Recraft then gets the images inline).+ update(id, { generation_id: null, status: "complete", error: null, cover_url: null, style_id: null, engine });}}@@ -190,6 +193,7 @@ const STYLE_TARGET = "aitk-z-image";export function trainMoodboard(id: string): Moodboard {const m = getMoodboard(id);if (!m) throw new Error("Moodboard not found");+ if (engineMode() === "cloud") throw new Error("This install is set to paid cloud APIs only (Settings → Engine mode) — a style LoRA trains on your own GPU");if (m.status !== "complete") throw new Error("This moodboard is still training. Try again once it is ready.");// Say what's missing (an AI-Toolkit URL) before making the style element, so a refusal leaves nothing behind.const target = getTrainingTarget(STYLE_TARGET);diff --git a/src/server/training.ts b/src/server/training.tsindex f30be353..9681c062 100644--- a/src/server/training.ts+++ b/src/server/training.ts@@ -3,7 +3,7 @@ import fs from "node:fs";import path from "node:path";import { nanoid } from "nanoid";import type { ElementLora, StudioElement } from "@/lib/catalog/elements";-import { aiToolkitJob, getTrainingTarget, triggerFor, type TrainingTarget } from "@/lib/catalog/training";+import { aiToolkitJob, getTrainingTarget, trainingCaption, triggerFor, type TrainingTarget } from "@/lib/catalog/training";import { DATA_DIR, db } from "./db";import { getElement, updateElement } from "./elements";import { falFetch, falProvider } from "./providers/fal";@@ -160,7 +160,7 @@ function addIdentity(elementId: string, loras: ElementLora[]) {/** Photos + one caption per photo: "photo of <trigger>, <description>". */async function dataset(el: StudioElement, trigger: string, images: string[]) {- const caption = `photo of ${trigger}${el.description ? `, ${el.description.replace(/[.\s]+$/, "")}` : ""}`;+ const caption = trainingCaption(el.kind === "style" ? "style" : "character", trigger, el.description);const files: { name: string; data: Buffer }[] = [];for (const [i, ref] of images.entries()) {const f = await readRef(ref);@@ -228,7 +228,7 @@ async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger:fs.mkdirSync(folder, { recursive: true });for (const f of files) fs.writeFileSync(path.join(folder, f.name), f.data);const name = `fuobe_${el.handle.toLowerCase()}_${id.slice(0, 6)}`.replace(/[^a-z0-9_]/g, "_");- const job = aiToolkitJob({ name, trigger, datasetFolder: folder, outputFolder: path.join(root, "output") });+ const job = aiToolkitJob({ name, trigger, datasetFolder: folder, outputFolder: path.join(root, "output"), kind: el.kind === "style" ? "style" : "character" });const created = await aitk("/api/jobs", { method: "POST", body: JSON.stringify({ name, gpu_ids: "0", job_config: job }) });const jobId = String(created.id);await aitk(`/api/jobs/${jobId}/start`);@@ -334,7 +334,7 @@ export async function trainingKit(elementId: string): Promise<{ name: string; daconst trigger = triggerFor(el.handle);const { files } = await dataset(el, trigger, images);const name = `fuobe_${el.handle.toLowerCase()}`.replace(/[^a-z0-9_]/g, "_");- const job = aiToolkitJob({ name, trigger, datasetFolder: "./dataset", outputFolder: "./output" });+ const job = aiToolkitJob({ name, trigger, datasetFolder: "./dataset", outputFolder: "./output", kind: el.kind === "style" ? "style" : "character" });const readme = `# Train ${el.name} with AI-Toolkit1. Install AI-Toolkit: https://github.com/ostris/ai-toolkit (24 GB GPU recommended)diff --git a/tests/image-studios-api.test.ts b/tests/image-studios-api.test.tsindex ba940388..b77c0645 100644--- a/tests/image-studios-api.test.ts+++ b/tests/image-studios-api.test.ts@@ -25,6 +25,16 @@ 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");+const retryRoute = await import("@/app/api/photodump/retry/route");+const trainRoute = await import("@/app/api/moodboards/[id]/train/route");+const generationsRoute = await import("@/app/api/generations/route");+const { db } = await import("@/server/db");+const { listGenerations } = gens;+const { applySignature, withSignatureWords } = await import("@/lib/catalog/palettes");+const { toPick } = await import("@/components/moodboards/logic");+const { extractOutputs } = await import("@/lib/catalog/payload");+const { aiToolkitJob, trainingCaption } = await import("@/lib/catalog/training");+const { getModel } = await import("@/lib/catalog");beforeAll(() => {setSetting("demoMode", "auto");@@ -93,12 +103,33 @@ describe("palettes", () => {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");+ expect((locks[0].request as { title?: string }).title).toBe("a lighthouse");+ expect(items.find((g) => g.modelId === "oss-qwen-image")!.request.step?.label).toBe("Before 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("style signature on the server", () => {+ it("keeps the user's words in the stored request and runs with the signature's sentences", async () => {+ const signed = applySignature(+ { feature: "image", modelId: "nano-banana-pro", prompt: "a lighthouse at dusk", params: { numOutputs: 1 } },+ { palette: { id: "p1", name: "Teal Dusk", colors: ["#102030", "#2A9D8F"], background: "#264653", slug: null } },+ { caps: palettes.signatureCaps(), getModel },+ );+ const res = await generationsRoute.POST(json("POST", signed.request));+ expect(res.status).toBe(201);+ const [g] = (await res.json()).items;+ expect(g.request.prompt).toBe("a lighthouse at dusk");+ expect(g.request.signature.palette.name).toBe("Teal Dusk");+ expect(g.request.signature.from.modelId).toBe("nano-banana-pro");+ // The row's prompt (what the model got) has the palette sentence once.+ expect(g.prompt).toBe(withSignatureWords(signed.request).prompt);+ expect(g.prompt.match(/Color palette/g)).toHaveLength(1);+ });+});+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()] }));@@ -146,6 +177,64 @@ describe("moodboards", () => {expect(moodboards.deleteMoodboard(m.id)).toBe(true);expect(moodboards.getMoodboard(m.id)).toBeNull();});++ it("keeps the Recraft style id a real cover job returns, and Recraft then runs on the saved style", () => {+ // Recraft V4 Styles answers with the style it made from the inline images (fal: images + style_id).+ const out = extractOutputs({ images: [{ url: "https://fal.media/cover.png", content_type: "image/png" }], style_id: "3f6c1a2b-0000-4000-8000-000000000000" }, "edit");+ expect(out[0].meta?.styleId).toBe("3f6c1a2b-0000-4000-8000-000000000000");+ const images = Array.from({ length: 6 }, upload);+ const m = moodboards.createMoodboard({ name: "Paper Cut", images, engine: "cloud" });+ // Stand in for the fal run: the cover job finished on fal with that output.+ db()+ .prepare("UPDATE generations SET status = 'succeeded', provider = 'fal', outputs_json = ? WHERE id = ?")+ .run(JSON.stringify([{ url: images[0], kind: "image", meta: { styleId: "3f6c1a2b-0000-4000-8000-000000000000" } }]), m.generationId);+ const done = moodboards.getMoodboard(m.id)!;+ expect(done.status).toBe("complete");+ expect(done.styleId).toBe("3f6c1a2b-0000-4000-8000-000000000000");+ expect(done.cover).toBe(images[0]);+ const r = applySignature({ feature: "image", modelId: "recraft-4-1", prompt: "a fox", params: { numOutputs: 1 } }, { moodboard: toPick(done) }, { caps: palettes.signatureCaps(), getModel });+ expect(r.modelId).toBe("recraft-4-style-saved");+ expect(r.request.params?.styleId).toBe("3f6c1a2b-0000-4000-8000-000000000000");+ moodboards.deleteMoodboard(m.id);+ });++ it("a cloud board whose cover job can't start (no key, demo off) is ready from its images", () => {+ setSetting("demoMode", "off");+ try {+ const m = moodboards.createMoodboard({ name: "No Key", images: Array.from({ length: 5 }, upload), engine: "cloud" });+ expect(m.status).toBe("complete");+ expect(m.generationId).toBeNull();+ expect(m.styleId).toBeNull();+ expect(toPick(m).refs).toHaveLength(5);+ moodboards.deleteMoodboard(m.id);+ } finally {+ setSetting("demoMode", "auto");+ }+ });++ it("a style LoRA trains with the style preset, and is refused on a cloud-only install", async () => {+ const job = aiToolkitJob({ name: "x", trigger: "nnhzfz", datasetFolder: "/d", outputFolder: "/o", kind: "style" });+ const train = job.config.process[0];+ expect(train.train.steps).toBe(1500);+ expect(train.sample.prompts.every((p: string) => p.endsWith("nnhzfz style"))).toBe(true);+ expect(aiToolkitJob({ name: "x", trigger: "t", datasetFolder: "/d", outputFolder: "/o" }).config.process[0].train.steps).toBe(2500);+ expect(trainingCaption("style", "nnhzfz", "the visual style of the “Neon Haze” moodboard.")).toBe("nnhzfz style, the visual style of the “Neon Haze” moodboard");+ expect(trainingCaption("character", "mayafz")).toBe("photo of mayafz");++ setSetting("demoMode", "off");+ const m = moodboards.createMoodboard({ name: "Cloud Only", images: Array.from({ length: 5 }, upload), engine: "cloud" });+ setSetting("demoMode", "auto");+ setSetting("engineMode", "cloud");+ try {+ const res = await trainRoute.POST(json("POST"), params({ id: m.id }) as never);+ expect(res.status).toBe(409);+ expect((await res.json()).error).toMatch(/cloud APIs only/);+ expect(moodboards.getMoodboard(m.id)!.lora).toBeNull();+ } finally {+ setSetting("engineMode", "both");+ moodboards.deleteMoodboard(m.id);+ }+ });});describe("photodump, fashion factory and character sheet runs", () => {@@ -163,6 +252,38 @@ describe("photodump, fashion factory and character sheet runs", () => {expect((await settle(items[0].id)).status).toBe("succeeded");}, 45_000);+ it("retries a canceled photo inside its batch (the failed one goes to the Trash)", async () => {+ const { batchId, items } = await (await photodumpRoute.POST(json("POST", { packId: "winter-special", engine: "cloud", selfie: upload(), aspectRatio: "3:4" }))).json();+ const victim = items[3];+ await gens.cancelGeneration(victim.id);+ expect(gens.getGeneration(victim.id)!.status).toBe("canceled");+ const res = await retryRoute.POST(json("POST", { id: victim.id }));+ expect(res.status).toBe(201);+ const { items: again } = await res.json();+ expect(again).toHaveLength(1);+ expect(again[0].batchId).toBe(batchId);+ expect(again[0].request.step.label).toBe("Photo 4 of 9");+ expect(again[0].request.batchTitle).toBe(victim.request.batchTitle);+ // The run still has 9 photos: the canceled one is in the Trash.+ const run = listGenerations({ features: ["photodump"], limit: 200 }).filter((g) => g.batchId === batchId);+ expect(run).toHaveLength(9);+ expect(run.some((g) => g.id === victim.id)).toBe(false);+ // Only failed or canceled photos of a photo run can be retried.+ expect((await retryRoute.POST(json("POST", { id: again[0].id }))).status).toBe(422);+ }, 45_000);++ it("says on Qwen-Image-Edit that the aspect ratio doesn't apply", async () => {+ const preview = await (await photodumpRoute.POST(json("POST", { packId: "winter-special", engine: "open", selfie: upload(), aspectRatio: "16:9" }, "http://x/api/photodump?preview=1"))).json();+ expect(preview.modelId).toBe("oss-qwen-edit");+ expect(preview.fixedAspect).toBe(true);+ expect(preview.notes.join()).toMatch(/keeps the shape of your photo/);+ const cloud = await (await photodumpRoute.POST(json("POST", { packId: "winter-special", engine: "cloud", selfie: upload(), aspectRatio: "16:9" }, "http://x/api/photodump?preview=1"))).json();+ expect(cloud.fixedAspect).toBe(false);+ // Picking Z-Image Turbo + LoRA with a selfie says why it runs on Qwen-Image-Edit.+ const z = await (await photodumpRoute.POST(json("POST", { packId: "zen", engine: "open", selfie: upload(), modelId: "oss-z-image-turbo" }, "http://x/api/photodump?preview=1"))).json();+ expect(z.notes[0]).toMatch(/needs a character with a trained LoRA/);+ });+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-/);@@ -194,6 +315,10 @@ describe("photodump, fashion factory and character sheet runs", () => {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 long = await characterRoute.POST(json("POST", { mode: "describe", engine: "cloud", prompt: "x".repeat(2100) }));+ expect((await long.json()).error).toBe("Keep the description under 2,000 characters");+ const badCast = await characterRoute.POST(json("POST", { mode: "cast", engine: "cloud", cast: { genre: { nested: true } } }));+ expect((await badCast.json()).error).toBe("Check the cast fields");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();diff --git a/tests/image-studios.test.ts b/tests/image-studios.test.tsindex 28b62502..76b518ca 100644--- a/tests/image-studios.test.ts+++ b/tests/image-studios.test.ts@@ -7,6 +7,7 @@ import {castFieldVisible,castNameFor,castSheetModel,+ coverTone,customPack,CURATED_MOODBOARDS,FASHION,@@ -19,6 +20,7 @@ import {getPack,inTab,PACKS,+ photodumpModel,planPhotodump,presetFallback,presetPrompt,@@ -26,6 +28,7 @@ import {randomCast,sheetFromReference,shotPrompt,+ spreadHue,type FashionState,type PhotoSubject,} from "@/lib/catalog/packs";@@ -46,6 +49,9 @@ import {type PalettePick,type RGB,type SignatureCaps,+ reuseSignature,+ withBackground,+ withSignatureWords,} from "@/lib/catalog/palettes";import { buildPayload } from "@/lib/catalog/payload";import { planGeneration } from "@/lib/catalog/plan";@@ -82,6 +88,8 @@ const CAPS: SignatureCaps = {};const ctx = { caps: CAPS, getModel };const plan = (r: GenerationRequest) => planGeneration(r, getModel, getPreset);+/** The prompt as the server runs it: the user's words plus the signature's sentences. */+const said = (s: { request: GenerationRequest }) => withSignatureWords(s.request).prompt;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 };@@ -136,6 +144,20 @@ describe("palettes: k-means extraction", () => {});});+describe("palettes: the manual editor", () => {+ it("Use as background keeps the colour that loses the flag", () => {+ const start = { colors: ["#FFFFFF", "#D1FE17", "#1C1E20"], background: "#53C546" };+ const moved = withBackground(start, "#FFFFFF", true);+ expect(moved).toEqual({ colors: ["#FFFFFF", "#D1FE17", "#1C1E20", "#53C546"], background: "#FFFFFF" });+ // Turning the flag off leaves the colour in the palette.+ expect(withBackground(start, "#53C546", false)).toEqual({ colors: ["#FFFFFF", "#D1FE17", "#1C1E20", "#53C546"], background: null });+ // Off on a colour that isn't the background changes nothing; the 12-colour limit holds.+ expect(withBackground(start, "#FFFFFF", false)).toBe(start);+ const full = { colors: Array.from({ length: 12 }, (_, i) => `#0000${(i * 16).toString(16).padStart(2, "0").toUpperCase()}`), background: "#ABCDEF" };+ expect(withBackground(full, full.colors[0], true).colors).toHaveLength(12);+ });+});+describe("palettes: routing per model", () => {it("the Image studio can look up every model a signature routes to, without listing them in its picker", () => {const slice = studioCatalog(IMAGE_STUDIO);@@ -174,7 +196,9 @@ describe("palettes: routing per model", () => {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\.$/);+ // The user's words stay in the prompt; the server adds the palette sentence when it plans the run.+ expect(r.request.prompt).toBe("a lighthouse at dusk");+ expect(said(r)).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();}@@ -196,7 +220,7 @@ describe("palettes: routing per model", () => {const free = applySignature(req("oss-qwen-image"), { palette: PAL }, ctx);expect(free.lock).toBeUndefined();- expect(free.request.prompt).toMatch(/Color palette/);+ expect(said(free)).toMatch(/Color palette/);const locked = applySignature(req("oss-qwen-image"), { palette: { ...PAL, lock: true } }, ctx);expect(locked.lock?.colors).toEqual([...PAL.colors, "#264653"]);expect(locked.notes).toEqual(["Then recoloured to “Teal Dusk” by a palette-transfer step"]);@@ -219,16 +243,18 @@ describe("moodboards: routing per model", () => {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");+ expect(soul.request.signature?.words).toBeUndefined();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"));+ expect(open.request.prompt).toBe("a rooftop party");+ expect(said(open)).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(said(nano)).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);@@ -263,7 +289,7 @@ describe("moodboards: routing per model", () => {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.");+ expect(said(lora)).toBe("a rooftop party. In the style of @Neon_Haze.");});it("Soul's 106 styles are curated picks too: style_id on soul-1, words on Soul 2.0 and everything else", () => {@@ -285,7 +311,7 @@ describe("moodboards: routing per model", () => {expect(soul2.request.params?.extra?.style_id).toBeUndefined();expect(soul2.notes[0]).toBe("Sunset beach is a Soul preset — described in words on Higgsfield Soul 2.0");const turbo = applySignature(req("oss-z-image-turbo"), { moodboard: pick }, ctx);- expect(turbo.request.prompt).toBe(presetPrompt(sunset, "a rooftop party"));+ expect(said(turbo)).toBe(presetPrompt(sunset, "a rooftop party"));});it("curated sets come from the built-in list, with Higgsfield's live previews (and newer presets) on top", () => {@@ -301,14 +327,40 @@ describe("moodboards: routing per model", () => {expect(curatedPick(withLive(CURATED_SETS["soul-v1"], { items: [{ id: "v1-new", name: "New one" }] }, "soul-v1").at(-1)!).source).toBe("soul-v1");});- it("a reused run isn't styled twice (Reuse keeps the composer's chips)", () => {+ it("an older run that kept the sentences in its prompt isn't styled twice; Run again doesn't add the board twice", () => {const once = applySignature(req("oss-z-image-turbo"), { moodboard: curated, palette: PAL }, ctx);- const twice = applySignature({ ...req(once.modelId), prompt: once.request.prompt, inputs: once.request.inputs }, { moodboard: curated, palette: PAL }, ctx);- expect(twice.request.prompt).toBe(once.request.prompt);+ const legacy = { ...req(once.modelId), prompt: said(once), inputs: once.request.inputs };+ const twice = applySignature(legacy, { moodboard: curated, palette: PAL }, ctx);+ expect(said(twice)).toBe(said(once));const nano = applySignature(req("nano-banana-pro"), { moodboard: board }, ctx);- const again = applySignature({ ...nano.request, op: undefined }, { moodboard: board }, ctx);+ const again = applySignature({ ...nano.request, op: undefined, signature: undefined }, { moodboard: board }, ctx);expect(again.request.inputs?.images).toEqual(nano.request.inputs?.images);- expect(again.request.prompt).toBe(nano.request.prompt);+ });++ it("Soul presets go native wherever the model's own preset list is theirs; Soul Cinema (no presets) gets words", () => {+ const style = SOUL_STYLES[0];+ const pick = curatedPick(style);+ const cinema = applySignature(req("soul-cinema"), { moodboard: pick }, ctx);+ expect(cinema.request.params?.extra?.style_id).toBeUndefined();+ expect(cinema.notes[0]).toBe(`Higgsfield Soul Cinema has one fixed look and no presets — ${style.name} is described in words`);+ expect(said(cinema)).toMatch(/In the style of/);+ // A model whose preset picker is Soul's list takes the style id natively, whatever its id.+ const soul1 = getModel("soul-1")!;+ const twin = { ...soul1, id: "soul-twin", options: { ...soul1.options, presets: { ...soul1.options.presets!, param: "style_id" } } };+ const ctx2 = { caps: CAPS, getModel: (id: string) => (id === "soul-twin" ? twin : getModel(id)) };+ const native = applySignature(req("soul-twin"), { moodboard: pick }, ctx2);+ expect(native.request.params?.extra?.style_id).toBe(style.id);+ expect(native.request.prompt).toBe("a rooftop party");+ expect(native.request.signature?.words).toBeUndefined();+ expect(native.notes).toEqual([]);+ });++ it("Recraft V4 Styles keeps your own images first and fills up to 10 with the board's", () => {+ const own = ["/api/files/uploads/mine.png"];+ const r = applySignature(req("recraft-4-1", own), { moodboard: board }, ctx);+ expect(r.modelId).toBe("recraft-4-style");+ expect(r.request.inputs?.images).toEqual([...own, ...refs.slice(0, 9)]);+ expect(r.notes.join()).toMatch(/Your image is used as style references too/);});it("a board that isn't ready blocks with Higgsfield's copy; palette + moodboard combine", () => {@@ -316,7 +368,65 @@ describe("moodboards: routing per model", () => {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/);+ expect(said(both)).toMatch(/Color palette/);+ });+});++describe("style signature: the request record and Reuse", () => {+ const req = (modelId: string, extra: Partial<GenerationRequest> = {}): GenerationRequest => ({ feature: "image", modelId, prompt: "a lighthouse at dusk", params: { numOutputs: 1, aspectRatio: "16:9" }, ...extra });+ const board: MoodboardPick = { id: "mb1", kind: "personal", name: "Neon Haze", status: "complete", refs: ["/api/files/uploads/r1.png", "/api/files/uploads/r2.png"], collages: [] };++ it("keeps the user's words in the prompt and the sentences in signature.words (titles and Reuse show the words)", () => {+ const r = applySignature(req("nano-banana-pro"), { palette: PAL }, ctx);+ expect(r.request.prompt).toBe("a lighthouse at dusk");+ expect(r.request.signature?.words).toMatch(/^Color palette: use only these colors/);+ expect(r.request.signature?.palette).toEqual(PAL);+ expect(r.request.signature?.from).toEqual({ modelId: "nano-banana-pro", params: { numOutputs: 1, aspectRatio: "16:9" }, images: 0 });+ // The server plans it with the sentences.+ expect(plan(withSignatureWords(r.request)).prompt).toMatch(/^a lighthouse at dusk\. Color palette/);+ // Without words there's nothing to add.+ const plain = req("nano-banana-pro");+ expect(withSignatureWords(plain)).toBe(plain);+ });++ it("Reuse of a Recraft palette run: Recraft V4.1 without the hidden palette fields, the palette back on the chip", () => {+ const r = applySignature(req("recraft-4-1"), { palette: PAL }, ctx);+ expect(r.request.params?.palette).toHaveLength(4);+ const back = reuseSignature(r.request)!;+ expect(back.modelId).toBe("recraft-4-1");+ expect(back.params).toEqual({ numOutputs: 1, aspectRatio: "16:9" });+ expect(back.params.extra?.background_color).toBeUndefined();+ expect(back.signature).toEqual({ palette: PAL });+ // Applying the restored chip again gives the same run.+ const again = applySignature({ ...req(back.modelId), params: back.params }, back.signature, ctx);+ expect(again.request.params).toEqual(r.request.params);+ });++ it("Reuse of an open Z-Image palette run goes back to Z-Image Turbo (not the hidden Palette model)", () => {+ const r = applySignature(req("oss-z-image-turbo"), { palette: PAL }, ctx);+ expect(r.modelId).toBe("oss-zimage-palette");+ const back = reuseSignature(r.request)!;+ expect(back.modelId).toBe("oss-z-image-turbo");+ expect(back.params.palette).toBeUndefined();+ expect(back.signature.palette?.id).toBe("p1");+ });++ it("Reuse of a moodboard run keeps only your own images and the board on the chip; Soul's style id too", () => {+ const own = "/api/files/uploads/own.png";+ const r = applySignature(req("nano-banana-pro", { inputs: { images: [own] } }), { moodboard: board }, ctx);+ expect(r.request.inputs?.images).toEqual([own, ...board.refs!]);+ const back = reuseSignature(r.request)!;+ expect(back.images).toEqual([own]);+ expect(back.signature.moodboard?.id).toBe("mb1");++ const look = curatedPick(CURATED_SETS["soul-v2"][3]);+ const soul = applySignature(req("soul-2"), { moodboard: look }, ctx);+ expect(soul.request.params?.extra?.style_id).toBe(look.id);+ const soulBack = reuseSignature(soul.request)!;+ expect(soulBack.params.extra).toBeUndefined();+ expect(soulBack.signature.moodboard).toEqual(look);+ // A run without a signature isn't touched.+ expect(reuseSignature(req("soul-2"))).toBeNull();});});@@ -425,6 +535,24 @@ describe("Photodump packs and planning", () => {});});+describe("Photodump: model choice and retries", () => {+ const selfie: PhotoSubject = { kind: "selfie", url: "/api/files/uploads/me.png" };+ it("says why a pick that can't run ends up on another model", () => {+ expect(photodumpModel(selfie, "open", { higgsfield: false }, "oss-z-image-turbo")).toEqual({ modelId: "oss-qwen-edit", note: "Z-Image Turbo + LoRA needs a character with a trained LoRA — Qwen-Image-Edit works from your photo" });+ expect(photodumpModel(selfie, "open", { higgsfield: false }, "oss-z-image-turbo", true).note).toMatch(/Your own packs recreate each reference photo/);+ expect(photodumpModel(selfie, "open", { higgsfield: false }).note).toBeUndefined();+ });++ it("a retried base shot or outfit takes the failed one's place in the wizard", () => {+ let s: FashionState = { ...FASHION_START, step: "generation", templateId: "red-room", elementId: "el1", baseIds: ["g1", "g2"], outfitIds: ["o1"] };+ s = fashionReducer(s, { type: "retried", from: "g2", to: ["g3"] });+ expect(s.baseIds).toEqual(["g1", "g3"]);+ s = fashionReducer(s, { type: "retried", from: "o1", to: ["o2", "o3"] });+ expect(s.outfitIds).toEqual(["o2", "o3"]);+ expect(fashionReducer(s, { type: "retried", from: "nope", to: ["x"] })).toBe(s);+ });+});+describe("Fashion Factory", () => {const maya = { kind: "element" as const, handle: "Maya", name: "Maya", references: ["/api/files/uploads/m1.png"], loras: [] };@@ -525,6 +653,27 @@ describe("Character Sheet", () => {});});+describe("drawn covers", () => {+ it("curated looks and packs get spread hues and a treatment from their words", () => {+ expect(coverTone("Retro BW", "Grainy black-and-white film portrait")).toBe("mono");+ expect(coverTone("80s horror", "1980s horror lighting: red and blue gels, fog")).toBe("gel");+ expect(coverTone("Flash editorial", "Direct on-camera flash fashion editorial")).toBe("flash");+ expect(coverTone("Neutral pastel film", "Film stock with neutral pastel tones")).toBe("pastel");+ expect(coverTone("Old smartphone", "Low-res early phone camera: noise, soft focus")).toBe("film");+ expect(coverTone("General", "Soul 2.0's neutral default look")).toBe("plain");+ // Neighbours in a set never share a hue band.+ const looks = CURATED_SETS["soul-v2"].slice(0, 6);+ for (let i = 1; i < looks.length; i++) {+ const d = Math.abs(looks[i].hue - looks[i - 1].hue) % 360;+ expect(Math.min(d, 360 - d)).toBeGreaterThan(40);+ }+ expect(CURATED_SETS["soul-v2"].find((l) => l.name === "Retro BW")?.tone).toBe("mono");+ expect(new Set(PACKS.map((p) => p.hue)).size).toBe(PACKS.length);+ expect(getPack("2000s-nostalgia")?.tone).toBe("flash");+ expect(spreadHue(0)).not.toBe(spreadHue(1));+ });+});+describe("moodboard logic", () => {it("uses Higgsfield's limits and copy", () => {const five = Array.from({ length: 5 }, (_, i) => `i${i}`);