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.

Composer logic and per-studio model slices (pure, tested)

Claude0f4c58a00f40
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
new file mode 100644
index 00000000..71fe9452
--- /dev/null
+++ b/src/lib/composer.ts
@@ -0,0 +1,328 @@
+/**
+ * Pure composer logic shared by the studio composer and its tests: the settings summary chip,
+ * blocker messages, attachment placement and model-picker grouping. No catalog import here, so
+ * nothing in this file pulls the model list into the browser bundle.
+ */
+import type { Engine, GenParams, InputSlot, MediaKind, ModelDef, Operation } from "./catalog/types";
+
+// ---------------------------------------------------------------------------
+// Settings summary ("16:9 · 720p · 5s · ×1")
+
+/** Operations that transform one input into one result — no batch count. */
+export const SINGLE_TAKE = new Set<Operation>([
+ "lipsync", "avatar", "upscale-video", "upscale-image", "dub", "extend", "reframe", "finalize", "v2a", "interpolate",
+ "bg-remove", "bg-remove-video", "depth-video", "concat", "color-match", "frame",
+]);
+
+export const durationLabel = (v: number) => (v >= 1000 ? `${Math.round(v / 1000)}s` : `${v}s`);
+
+export interface SettingsShape {
+ /** Show the aspect-ratio control (the model offers several and the operation isn't framed by an input). */
+ aspect: string[] | null;
+ resolution: string[] | null;
+ duration: number[] | null;
+ /** Batch count (×1–×4). */
+ count: boolean;
+ draft: boolean;
+ audio: boolean;
+ multiShot: boolean;
+ enhance: boolean;
+ sliders: boolean;
+ negativePrompt: boolean;
+}
+
+/**
+ * Which output settings apply to this model, operation and studio. `studioOps` are the studio's
+ * operations: when the operation isn't known yet (nothing attached) and they're all one-take
+ * transforms (Lipsync), there's still no batch count.
+ */
+export function settingsShape(
+ model: Pick<ModelDef, "options"> | undefined,
+ op: Operation | undefined,
+ kind: MediaKind,
+ showPrompt: boolean,
+ params: GenParams = {},
+ studioOps: Operation[] = [],
+): SettingsShape {
+ const o = model?.options ?? {};
+ const many = <T,>(xs: T[] | undefined) => (xs && xs.length > 1 ? xs : null);
+ const single = op ? SINGLE_TAKE.has(op) : studioOps.length > 0 && studioOps.every((x) => SINGLE_TAKE.has(x));
+ return {
+ aspect: op === "i2v" || op === "flf2v" ? null : many(o.aspectRatios),
+ resolution: many(o.resolutions),
+ duration: params.shots ? null : many(o.durations),
+ count: (kind === "image" || kind === "video") && !single,
+ draft: !!o.draft,
+ audio: o.audio === true,
+ multiShot: !!o.multiShot,
+ enhance: showPrompt,
+ sliders: !!o.sliders?.length,
+ negativePrompt: !!o.negativePrompt,
+ };
+}
+
+/** The parts of the summary chip label, in reading order. */
+export function settingsSummary(shape: SettingsShape, params: GenParams, model?: Pick<ModelDef, "options" | "defaults">): string[] {
+ const parts: string[] = [];
+ const d = model?.defaults ?? {};
+ if (shape.aspect) {
+ const ar = params.aspectRatio ?? d.aspectRatio ?? shape.aspect[0];
+ parts.push(ar === "auto" ? "Auto" : ar);
+ }
+ if (shape.resolution) parts.push(params.resolution ?? d.resolution ?? shape.resolution[0]);
+ if (params.shots?.length) parts.push(`${params.shots.length} shots`);
+ else if (shape.duration) parts.push(durationLabel(params.duration ?? d.duration ?? shape.duration[0]));
+ if (shape.count) parts.push(`×${params.numOutputs ?? 1}`);
+ if (shape.multiShot && !params.shots && params.multiShot === "auto") parts.push("Multi-shot");
+ if (shape.draft && params.draft) parts.push("Draft");
+ if (shape.audio && params.generateAudio === false) parts.push("No audio");
+ if (shape.enhance && params.enhancePrompt) parts.push("Enhance");
+ return parts;
+}
+
+/** How many settings differ from their defaults beyond what the summary shows (seed, negative prompt, sliders). */
+export function hiddenChanges(params: GenParams, negativePrompt: string, model?: Pick<ModelDef, "options">): number {
+ let n = 0;
+ if (params.seed !== undefined) n++;
+ if (negativePrompt.trim()) n++;
+ for (const s of model?.options.sliders ?? []) {
+ const v = params.extra?.[s.param];
+ if (typeof v === "number" && v !== s.default) n++;
+ }
+ return n;
+}
+
+// ---------------------------------------------------------------------------
+// Blockers ("Add a target photo")
+
+const VOWEL = /^[aeiou]/i;
+const DETERMINER = /^(your|the|a|an|some|any|my|this|that)\b/i;
+
+/** "Target photo" → "Add a target photo"; "Your clip" → "Add your clip"; "Image" → "Add an image". */
+export function slotMessage(label: string): string {
+ const l = label.trim();
+ // Keep acronyms ("SVG logo") and proper names as they are; lower-case an ordinary first word.
+ const word = /^[A-Z][a-z]/.test(l) ? l.charAt(0).toLowerCase() + l.slice(1) : l;
+ if (DETERMINER.test(word)) return `Add ${word}`;
+ const head = word.split(/\s+/)[0];
+ // Plurals ("Photos", "Clips") read better without an article.
+ if (/[^s]s$/i.test(head) && !/(us|is|ss)$/i.test(head) && head.length > 3 && !word.includes(" ")) return `Add ${word}`;
+ return `Add ${VOWEL.test(word) ? "an" : "a"} ${word}`;
+}
+
+type SlotValues = Partial<Record<InputSlot["key"], { ref: string; uploading?: boolean } | null>>;
+
+/** The first required slot that's still empty (the one Generate should point at). */
+export function firstMissingSlot(slots: InputSlot[], values: SlotValues): InputSlot | undefined {
+ return slots.find((s) => s.required && !values[s.key]?.ref && !values[s.key]?.uploading);
+}
+
+export interface Blocker {
+ message: string;
+ /** The attachment to point at (pulse) when Generate is pressed. */
+ slot?: InputSlot["key"];
+}
+
+/**
+ * What stops Generate, most actionable first: missing model, missing attachment (named with the
+ * studio's own slot label, not the planner's generic message), uploads in flight, then whatever
+ * the planner says (prompt, voice, language…).
+ */
+export function blockerFor(s: {
+ loading?: string | null;
+ model: boolean;
+ engineError?: string | null;
+ missing?: InputSlot;
+ uploading: boolean;
+ planError?: string | null;
+ promptMissing: boolean;
+}): Blocker | null {
+ if (s.loading) return { message: s.loading };
+ if (!s.model) return { message: "Pick a model" };
+ if (s.engineError) return { message: s.engineError };
+ if (s.missing) return { message: slotMessage(s.missing.label), slot: s.missing.key };
+ if (s.uploading) return { message: "Uploading…" };
+ if (s.planError) return { message: s.planError };
+ if (s.promptMissing) return { message: "Write a prompt first" };
+ return null;
+}
+
+/** Placeholder refs for empty required slots, so cost and plan can be computed before anything is attached. */
+export const PLACEHOLDER: Record<MediaKind, string> = {
+ image: "/api/files/placeholder.png",
+ video: "/api/files/placeholder.mp4",
+ audio: "/api/files/placeholder.wav",
+ text: "/api/files/placeholder.txt",
+ model3d: "/api/files/placeholder.glb",
+};
+
+// ---------------------------------------------------------------------------
+// Attachments: where a pasted / dropped / uploaded file goes
+
+export interface Attachment {
+ id?: string;
+ ref: string;
+ preview: string;
+ kind: MediaKind;
+ name?: string;
+ uploading?: boolean;
+}
+
+export interface AttachState {
+ slots: Partial<Record<InputSlot["key"], Attachment | null>>;
+ refs: Attachment[];
+}
+
+/**
+ * Put a new attachment somewhere sensible: the first empty slot of its kind, else the reference
+ * list (when the studio takes references of that kind and has room), else replace the first slot
+ * of its kind. Returns null when the studio can't take it.
+ */
+export function placeAttachment<T extends Attachment>(
+ state: { slots: Partial<Record<InputSlot["key"], T | null>>; refs: T[] },
+ slots: InputSlot[],
+ multiRef: { kind?: MediaKind } | undefined,
+ refMax: number,
+ v: T,
+): { slots?: Partial<Record<InputSlot["key"], T | null>>; refs?: T[] } | null {
+ const fits = slots.filter((s) => s.accept === v.kind && s.key !== "mask" && s.key !== "sketch");
+ const empty = fits.find((s) => !state.slots[s.key]);
+ if (empty) return { slots: { ...state.slots, [empty.key]: v } };
+ if (multiRef && (multiRef.kind ?? "image") === v.kind && state.refs.length < refMax) return { refs: [...state.refs, v] };
+ if (fits[0]) return { slots: { ...state.slots, [fits[0].key]: v } };
+ return null;
+}
+
+/**
+ * Swap an in-flight upload for its result (or drop it on failure), by id. If the user removed or
+ * replaced it meanwhile, nothing changes: a finished upload never brings a removed item back.
+ */
+export function replaceAttachment<T extends Attachment>(
+ state: { slots: Partial<Record<InputSlot["key"], T | null>>; refs: T[] },
+ id: string,
+ v: T | null,
+): { slots?: Partial<Record<InputSlot["key"], T | null>>; refs?: T[] } | null {
+ for (const [k, s] of Object.entries(state.slots) as [InputSlot["key"], T | null][]) {
+ if (s?.id === id) return { slots: { ...state.slots, [k]: v ? { ...v, id } : null } };
+ }
+ if (state.refs.some((r) => r.id === id)) {
+ return { refs: v ? state.refs.map((r) => (r.id === id ? { ...v, id } : r)) : state.refs.filter((r) => r.id !== id) };
+ }
+ return null;
+}
+
+/** Which kinds the "+" menu can take for this studio. */
+export function acceptedKinds(slots: InputSlot[], multiRef?: { kind?: MediaKind }): MediaKind[] {
+ const kinds = new Set<MediaKind>(slots.filter((s) => s.key !== "mask" && s.key !== "sketch" && s.key !== "voiceAudio" && s.key !== "voiceAudio2").map((s) => s.accept));
+ if (multiRef) kinds.add(multiRef.kind ?? "image");
+ return [...kinds];
+}
+
+// ---------------------------------------------------------------------------
+// Models for a studio and the picker's groups
+
+export function filterModels(models: ModelDef[], opts: { kind?: MediaKind; ops?: Operation[] }): ModelDef[] {
+ return models.filter((m) => !m.hidden && (!opts.kind || m.kind === opts.kind) && (!opts.ops || m.routes.some((r) => opts.ops!.includes(r.op))));
+}
+
+/** "Best for this studio": the studio's default first, then top picks, then what's new. */
+export function bestForStudio(models: ModelDef[], engine: Engine, defaultId: string | undefined, max = 4): ModelDef[] {
+ const pool = models.filter((m) => m.engine === engine);
+ const score = (m: ModelDef) => (m.id === defaultId ? 0 : m.badges?.includes("top") ? 1 : m.badges?.includes("new") ? 2 : 9);
+ return pool
+ .map((m, i) => [m, score(m), i] as const)
+ .filter(([, s]) => s < 9)
+ .sort((a, b) => a[1] - b[1] || a[2] - b[2])
+ .slice(0, max)
+ .map(([m]) => m);
+}
+
+export interface ModelGroup {
+ id: "recent" | "starred" | "best" | "all" | "results";
+ label: string;
+ models: ModelDef[];
+}
+
+const norm = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "");
+
+/** Search score: 0 = name starts with the query, 1 = a word starts with it, 2 = anywhere; -1 = no match. */
+export function matchScore(m: Pick<ModelDef, "name" | "vendor" | "tagline" | "family">, query: string): number {
+ const terms = norm(query).split(/\s+/).filter(Boolean);
+ if (!terms.length) return 0;
+ const name = norm(m.name);
+ const hay = norm(`${m.name} ${m.vendor} ${m.family} ${m.tagline}`);
+ if (!terms.every((t) => hay.includes(t))) return -1;
+ if (name.startsWith(terms[0])) return 0;
+ if (new RegExp(`\\b${terms[0].replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(hay)) return 1;
+ return 2;
+}
+
+/**
+ * The picker's sections. Without a query: Recent (last 3 used), Starred, Best for this studio
+ * and All, for the selected engine; a model sits in the first section it belongs to (All lists
+ * everything). With a query: one list across every allowed engine, best matches first.
+ */
+export function groupModels(input: {
+ models: ModelDef[];
+ engine: Engine;
+ /** Engines the install allows (Settings → Engine mode). */
+ engines: Engine[];
+ query: string;
+ recent: string[];
+ starred: string[];
+ best: string[];
+}): { groups: ModelGroup[]; count: number } {
+ const { models, engine, engines, query, recent, starred, best } = input;
+ const q = query.trim();
+ if (q) {
+ const hits = models
+ .filter((m) => engines.includes(m.engine))
+ .map((m, i) => ({ m, s: matchScore(m, q), i }))
+ .filter((x) => x.s >= 0)
+ .sort((a, b) => a.s - b.s || Number(a.m.engine !== engine) - Number(b.m.engine !== engine) || a.i - b.i)
+ .map((x) => x.m);
+ return { groups: hits.length ? [{ id: "results", label: "Results", models: hits }] : [], count: hits.length };
+ }
+ const pool = models.filter((m) => m.engine === engine);
+ const byId = new Map(pool.map((m) => [m.id, m]));
+ const used = new Set<string>();
+ const take = (ids: string[], max: number) => {
+ const out: ModelDef[] = [];
+ for (const id of ids) {
+ const m = byId.get(id);
+ if (!m || used.has(id) || out.length >= max) continue;
+ used.add(id);
+ out.push(m);
+ }
+ return out;
+ };
+ const groups: ModelGroup[] = [
+ { id: "recent", label: "Recent", models: take(recent, 3) },
+ { id: "starred", label: "Starred", models: take(starred, 50) },
+ { id: "best", label: "Best for this studio", models: take(best, 4) },
+ { id: "all", label: "All models", models: pool },
+ ];
+ return { groups: groups.filter((g) => g.models.length), count: pool.length };
+}
+
+/** Keep a most-recent-first id list without duplicates. */
+export function pushRecent(list: string[], id: string, max = 12): string[] {
+ return [id, ...list.filter((x) => x !== id)].slice(0, max);
+}
+
+export function toggleIn(list: string[], id: string): string[] {
+ return list.includes(id) ? list.filter((x) => x !== id) : [...list, id];
+}
+
+// ---------------------------------------------------------------------------
+// Cost hint
+
+export function costLabel(s: { demo: boolean; cost: number | null; compact?: boolean }, format: (usd: number) => string): string {
+ if (s.demo) return s.compact ? "Demo" : "Demo · free";
+ if (s.cost === 0) return "Free";
+ if (s.cost != null) return `≈ ${format(s.cost)}`;
+ return "";
+}
+
+/** Prompts with an @mention: spellcheck would underline every handle. */
+export const hasMention = (text: string) => /(^|\s)@[\p{L}\p{N}_-]+/u.test(text);
diff --git a/src/lib/studio-catalog.ts b/src/lib/studio-catalog.ts
new file mode 100644
index 00000000..e53034b2
--- /dev/null
+++ b/src/lib/studio-catalog.ts
@@ -0,0 +1,36 @@
+/**
+ * The slice of the model catalog one studio needs, computed on the server and passed to the
+ * studio page as a prop, so the browser never downloads the whole catalog (every cloud, Higgsfield
+ * and open model, 121 apps, 363 motions and effects). Only the composer's lookups are kept:
+ * provider field maps stay on the server, which plans and builds the real request itself.
+ */
+import { getModel, modelsFor } from "./catalog";
+import type { ModelDef } from "./catalog/types";
+import type { StudioConfig } from "@/components/studio/studio-context";
+
+export interface StudioCatalog {
+ /** Models the composer can use or look up (picker list + defaults + the preset's own models). */
+ models: ModelDef[];
+}
+
+/** A model without its provider field maps (server-only detail). */
+export function slimModel(m: ModelDef): ModelDef {
+ return {
+ ...m,
+ routes: m.routes.map((r) => {
+ const copy = { ...r };
+ delete copy.map;
+ return copy;
+ }),
+ };
+}
+
+export function studioCatalog(config: Pick<StudioConfig, "kind" | "ops" | "defaultModels" | "preset">): StudioCatalog {
+ const list = modelsFor({ kind: config.kind, ops: config.ops });
+ const ids = new Set(list.map((m) => m.id));
+ const extra = [config.defaultModels.cloud, config.defaultModels.open, config.preset?.cloud?.modelId, config.preset?.open?.modelId]
+ .filter((id): id is string => !!id && !ids.has(id))
+ .map((id) => getModel(id))
+ .filter((m): m is ModelDef => !!m);
+ return { models: [...list, ...new Map(extra.map((m) => [m.id, m])).values()].map(slimModel) };
+}
diff --git a/tests/composer.test.ts b/tests/composer.test.ts
new file mode 100644
index 00000000..c501846e
--- /dev/null
+++ b/tests/composer.test.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it } from "vitest";
+import { getModel, getPreset, modelsFor, MODELS } from "@/lib/catalog";
+import type { InputSlot, ModelDef } from "@/lib/catalog/types";
+import {
+ acceptedKinds,
+ bestForStudio,
+ blockerFor,
+ costLabel,
+ filterModels,
+ firstMissingSlot,
+ groupModels,
+ hasMention,
+ hiddenChanges,
+ matchScore,
+ placeAttachment,
+ pushRecent,
+ replaceAttachment,
+ settingsShape,
+ settingsSummary,
+ slotMessage,
+ toggleIn,
+ type Attachment,
+} from "@/lib/composer";
+import { appStudio, EDIT_STUDIO, IMAGE_STUDIO, JOIN_CLIPS_STUDIO, LIPSYNC_STUDIO, VIDEO_STUDIO } from "@/lib/studios";
+import { studioCatalog } from "@/lib/studio-catalog";
+
+const model = (id: string) => {
+ const m = getModel(id);
+ if (!m) throw new Error(`no model ${id}`);
+ return m;
+};
+
+const att = (id: string, kind: Attachment["kind"] = "image", extra: Partial<Attachment> = {}): Attachment => ({ id, ref: `/api/files/${id}`, preview: `/api/files/${id}`, kind, ...extra });
+
+describe("settings summary", () => {
+ it("summarises a video model's output settings in reading order", () => {
+ const m = model("seedance-2-5");
+ const shape = settingsShape(m, "t2v", "video", true);
+ expect(settingsSummary(shape, { ...m.defaults }, m)).toEqual(["16:9", "720p", "5s", "×1"]);
+ expect(settingsSummary(shape, { ...m.defaults, aspectRatio: "9:16", numOutputs: 2, draft: true, generateAudio: false, enhancePrompt: true }, m)).toEqual([
+ "9:16",
+ "720p",
+ "5s",
+ "×2",
+ "Draft",
+ "No audio",
+ "Enhance",
+ ]);
+ });
+
+ it("drops the aspect ratio when a start frame frames the shot, and the duration when shots set it", () => {
+ const m = model("seedance-2-5");
+ expect(settingsShape(m, "i2v", "video", true).aspect).toBeNull();
+ const shots = [
+ { prompt: "a", duration: 3 },
+ { prompt: "b", duration: 3 },
+ ];
+ const shape = settingsShape(m, "t2v", "video", true, { shots });
+ expect(shape.duration).toBeNull();
+ expect(settingsSummary(shape, { ...m.defaults, shots }, m)).toContain("2 shots");
+ });
+
+ it("has no batch count for one-take transforms, even before the operation is known", () => {
+ expect(settingsShape(model("kling-avatar-2"), "avatar", "video", true).count).toBe(false);
+ expect(settingsShape(model("kling-avatar-2"), undefined, "video", true, {}, LIPSYNC_STUDIO.ops).count).toBe(false);
+ expect(settingsShape(model("seedance-2-5"), undefined, "video", true, {}, VIDEO_STUDIO.ops).count).toBe(true);
+ expect(settingsShape(model("nano-banana-pro"), "t2i", "image", true).count).toBe(true);
+ expect(settingsShape(undefined, "concat", "video", false).count).toBe(false);
+ });
+
+ it("counts the changes the chip doesn't spell out", () => {
+ const m = model("elevenlabs-v4");
+ const slider = m.options.sliders![0];
+ expect(hiddenChanges({}, "", m)).toBe(0);
+ expect(hiddenChanges({ seed: 4, extra: { [slider.param]: slider.default } }, " ", m)).toBe(1);
+ expect(hiddenChanges({ seed: 4, extra: { [slider.param]: slider.min } }, "blurry", m)).toBe(3);
+ });
+});
+
+describe("blockers", () => {
+ it("names a slot in the studio's own words", () => {
+ expect(slotMessage("Target photo")).toBe("Add a target photo");
+ expect(slotMessage("Image")).toBe("Add an image");
+ expect(slotMessage("Your clip")).toBe("Add your clip");
+ expect(slotMessage("Face")).toBe("Add a face");
+ expect(slotMessage("Driving video")).toBe("Add a driving video");
+ expect(slotMessage("End frame")).toBe("Add an end frame");
+ expect(slotMessage("Photos")).toBe("Add photos");
+ expect(slotMessage("SVG logo")).toBe("Add a SVG logo");
+ });
+
+ it("points at the first empty required slot (not one still uploading)", () => {
+ const face = getPreset("app-face-swap")!;
+ expect(firstMissingSlot(face.inputs, {})?.label).toBe(face.inputs.find((s) => s.required)!.label);
+ const [first, second] = face.inputs;
+ expect(firstMissingSlot(face.inputs, { [first.key]: { ref: "/a.png" } })?.key).toBe(second.key);
+ expect(firstMissingSlot(face.inputs, { [first.key]: { ref: "", uploading: true }, [second.key]: { ref: "/b.png" } })).toBeUndefined();
+ });
+
+ it("orders blockers from most to least actionable", () => {
+ const slot: InputSlot = { key: "image", label: "Target photo", accept: "image", required: true };
+ const base = { model: true, uploading: false, promptMissing: false };
+ expect(blockerFor({ ...base, loading: "Loading models…", model: false })).toEqual({ message: "Loading models…" });
+ expect(blockerFor({ ...base, model: false })).toEqual({ message: "Pick a model" });
+ expect(blockerFor({ ...base, missing: slot, uploading: true, planError: "Add an image to edit", promptMissing: true })).toEqual({ message: "Add a target photo", slot: "image" });
+ expect(blockerFor({ ...base, uploading: true, planError: "Add an image to edit" })).toEqual({ message: "Uploading…" });
+ expect(blockerFor({ ...base, planError: "Pick a language to translate into", promptMissing: true })?.message).toBe("Pick a language to translate into");
+ expect(blockerFor({ ...base, promptMissing: true })?.message).toBe("Write a prompt first");
+ expect(blockerFor({ ...base, engineError: "Face Swap has no cloud version yet", missing: slot })?.message).toMatch(/no cloud version/);
+ expect(blockerFor(base)).toBeNull();
+ });
+});
+
+describe("attachments", () => {
+ const videoSlots = VIDEO_STUDIO.slots;
+
+ it("fills the first empty slot of the file's kind, then the references, then replaces", () => {
+ let s = { slots: {}, refs: [] as Attachment[] } as { slots: Record<string, Attachment | null>; refs: Attachment[] };
+ s = { ...s, ...placeAttachment(s, videoSlots, VIDEO_STUDIO.multiRef, 2, att("a"))! };
+ expect(s.slots.image?.id).toBe("a");
+ s = { ...s, ...placeAttachment(s, videoSlots, VIDEO_STUDIO.multiRef, 2, att("b"))! };
+ expect(s.slots.endImage?.id).toBe("b");
+ s = { ...s, ...placeAttachment(s, videoSlots, VIDEO_STUDIO.multiRef, 2, att("c"))! };
+ expect(s.refs.map((r) => r.id)).toEqual(["c"]);
+ s = { ...s, ...placeAttachment(s, videoSlots, VIDEO_STUDIO.multiRef, 1, att("d"))! };
+ // References full: the first image slot is replaced.
+ expect(s.slots.image?.id).toBe("d");
+ expect(placeAttachment(s, videoSlots, VIDEO_STUDIO.multiRef, 2, att("v", "audio"))).toBeNull();
+ });
+
+ it("puts clips in a clip list (Join clips) and never into mask/sketch slots", () => {
+ const s = { slots: {}, refs: [] as Attachment[] };
+ expect(placeAttachment(s, JOIN_CLIPS_STUDIO.slots, JOIN_CLIPS_STUDIO.multiRef, 4, att("v", "video"))?.refs?.[0].id).toBe("v");
+ const masked: InputSlot[] = [{ key: "mask", label: "Mask", accept: "image" }];
+ expect(placeAttachment(s, masked, undefined, 0, att("m"))).toBeNull();
+ });
+
+ it("swaps an upload for its result by id, and never brings back one that was removed", () => {
+ const uploading = att("up", "image", { ref: "", uploading: true });
+ const state = { slots: { image: uploading }, refs: [att("r1"), { ...att("r2"), ref: "", uploading: true }] };
+ expect(replaceAttachment(state, "up", att("done"))?.slots?.image).toMatchObject({ id: "up", ref: "/api/files/done" });
+ expect(replaceAttachment(state, "r2", att("x"))?.refs?.map((r) => r.ref)).toEqual(["/api/files/r1", "/api/files/x"]);
+ // Failure: the placeholder goes away.
+ expect(replaceAttachment(state, "r2", null)?.refs?.map((r) => r.id)).toEqual(["r1"]);
+ expect(replaceAttachment(state, "up", null)?.slots?.image).toBeNull();
+ // Removed meanwhile: nothing to update.
+ expect(replaceAttachment({ slots: {}, refs: [] }, "up", att("done"))).toBeNull();
+ });
+
+ it("lists what the + menu can take", () => {
+ expect(acceptedKinds(IMAGE_STUDIO.slots, IMAGE_STUDIO.multiRef)).toEqual(["image"]);
+ expect(acceptedKinds(LIPSYNC_STUDIO.slots, LIPSYNC_STUDIO.multiRef).sort()).toEqual(["audio", "image", "video"]);
+ expect(acceptedKinds([], undefined)).toEqual([]);
+ });
+});
+
+describe("model picker groups", () => {
+ const models = filterModels(MODELS, { kind: IMAGE_STUDIO.kind, ops: IMAGE_STUDIO.ops });
+ const cloud = models.filter((m) => m.engine === "cloud");
+
+ it("shows the same models as the catalog query", () => {
+ expect(models.map((m) => m.id)).toEqual(modelsFor({ kind: IMAGE_STUDIO.kind, ops: IMAGE_STUDIO.ops }).map((m) => m.id));
+ });
+
+ it("puts Recent, Starred and Best above All, each model once among them", () => {
+ const best = bestForStudio(models, "cloud", IMAGE_STUDIO.defaultModels.cloud).map((m) => m.id);
+ expect(best[0]).toBe("nano-banana-pro");
+ expect(best.length).toBeLessThanOrEqual(4);
+ const recent = [cloud[3].id, "oss-z-image-turbo", cloud[1].id, cloud[2].id, cloud[5].id];
+ const starred = [cloud[1].id, cloud[6].id];
+ const { groups, count } = groupModels({ models, engine: "cloud", engines: ["cloud", "open"], query: "", recent, starred, best });
+ expect(groups.map((g) => g.id)).toEqual(["recent", "starred", "best", "all"]);
+ // Last 3 used of this engine; the open model is skipped.
+ expect(groups[0].models.map((m) => m.id)).toEqual([cloud[3].id, cloud[1].id, cloud[2].id]);
+ // cloud[1] is already in Recent.
+ expect(groups[1].models.map((m) => m.id)).toEqual([cloud[6].id]);
+ const top = new Set([...groups[0].models, ...groups[1].models, ...groups[2].models].map((m) => m.id));
+ expect(top.size).toBe(groups[0].models.length + groups[1].models.length + groups[2].models.length);
+ expect(groups[3].models).toHaveLength(cloud.length);
+ expect(count).toBe(cloud.length);
+ });
+
+ it("searches both engines (best match first) and respects a locked engine", () => {
+ const both = groupModels({ models, engine: "cloud", engines: ["cloud", "open"], query: "qwen", recent: [], starred: [], best: [] });
+ expect(both.groups).toHaveLength(1);
+ expect(new Set(both.groups[0].models.map((m) => m.engine))).toEqual(new Set(["cloud", "open"]));
+ expect(both.count).toBe(both.groups[0].models.length);
+ const open = groupModels({ models, engine: "open", engines: ["open"], query: "qwen", recent: [], starred: [], best: [] });
+ expect(open.groups[0].models.every((m) => m.engine === "open")).toBe(true);
+ expect(groupModels({ models, engine: "cloud", engines: ["cloud"], query: "zzzz", recent: [], starred: [], best: [] })).toEqual({ groups: [], count: 0 });
+ });
+
+ it("ranks name prefixes above words above anywhere", () => {
+ const m = { name: "Nano Banana Pro", vendor: "Google", family: "gemini", tagline: "best text rendering" } as ModelDef;
+ expect(matchScore(m, "nano")).toBe(0);
+ expect(matchScore(m, "banana")).toBe(1);
+ expect(matchScore(m, "ana")).toBe(2);
+ expect(matchScore(m, "google text")).toBe(1);
+ expect(matchScore(m, "flux")).toBe(-1);
+ });
+
+ it("keeps recent and starred lists tidy", () => {
+ expect(pushRecent(["a", "b", "c"], "b")).toEqual(["b", "a", "c"]);
+ expect(pushRecent(["a", "b"], "c", 2)).toEqual(["c", "a"]);
+ expect(toggleIn(["a"], "b")).toEqual(["a", "b"]);
+ expect(toggleIn(["a", "b"], "a")).toEqual(["b"]);
+ });
+});
+
+describe("cost and mentions", () => {
+ const fmt = (n: number) => `$${n.toFixed(2)}`;
+ it("labels the cost", () => {
+ expect(costLabel({ demo: true, cost: 0.4 }, fmt)).toBe("Demo · free");
+ expect(costLabel({ demo: true, cost: 0.4, compact: true }, fmt)).toBe("Demo");
+ expect(costLabel({ demo: false, cost: 0 }, fmt)).toBe("Free");
+ expect(costLabel({ demo: false, cost: 0.4 }, fmt)).toBe("≈ $0.40");
+ expect(costLabel({ demo: false, cost: null }, fmt)).toBe("");
+ });
+ it("spots @mentions (spellcheck off)", () => {
+ expect(hasMention("@Koi_Pond_Night at dusk")).toBe(true);
+ expect(hasMention("a shot of @Maya")).toBe(true);
+ expect(hasMention("mail [email protected]")).toBe(false);
+ expect(hasMention("no handles here")).toBe(false);
+ });
+});
+
+describe("studio catalog slice", () => {
+ it("ships only the studio's models, without provider field maps", () => {
+ const video = studioCatalog(VIDEO_STUDIO);
+ expect(video.models.map((m) => m.id)).toEqual(expect.arrayContaining(["seedance-2-5", "oss-wan22-14b-fast"]));
+ expect(video.models.length).toBeLessThan(MODELS.length / 2);
+ expect(video.models.every((m) => m.kind === "video")).toBe(true);
+ expect(video.models.every((m) => m.routes.every((r) => r.map === undefined))).toBe(true);
+ expect(JSON.stringify(video).length).toBeLessThan(JSON.stringify(MODELS).length / 3);
+ });
+
+ it("includes the defaults and an app's own (hidden) models", () => {
+ const relight = getPreset("app-relight")!;
+ const app = studioCatalog(appStudio(relight));
+ expect(app.models.map((m) => m.id)).toEqual(expect.arrayContaining([relight.cloud!.modelId, relight.open!.modelId]));
+ const edit = studioCatalog(EDIT_STUDIO);
+ expect(edit.models.map((m) => m.id)).toEqual(expect.arrayContaining([EDIT_STUDIO.defaultModels.cloud, EDIT_STUDIO.defaultModels.open]));
+ });
+});