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
Compact composer, cmdk model picker, static studio shell, per-studio catalog
Claudea831e574e42d
diff --git a/src/app/(studio)/apps/[id]/page.tsx b/src/app/(studio)/apps/[id]/page.tsxindex 5e12eeaf..e3b71b80 100644--- a/src/app/(studio)/apps/[id]/page.tsx+++ b/src/app/(studio)/apps/[id]/page.tsx@@ -1,7 +1,7 @@import type { Metadata } from "next";import { notFound } from "next/navigation";import { Suspense } from "react";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { APPS, getPreset } from "@/lib/catalog";import { appStudio } from "@/lib/studios";@@ -18,7 +18,7 @@ async function AppStudio({ params }: { params: PageProps<"/apps/[id]">["params"]const { id } = await params;const preset = getPreset(id);if (!preset || preset.type !== "app") notFound();- return <StudioPage config={appStudio(preset)} />;+ return <Studio config={appStudio(preset)} />;}export default function Page({ params }: PageProps<"/apps/[id]">) {diff --git a/src/app/(studio)/edit/page.tsx b/src/app/(studio)/edit/page.tsxindex b4d225c1..5a417cfd 100644--- a/src/app/(studio)/edit/page.tsx+++ b/src/app/(studio)/edit/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { EDIT_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Edit image" };export default function Page() {- return <StudioPage config={EDIT_STUDIO} />;+ return <Studio config={EDIT_STUDIO} />;}diff --git a/src/app/(studio)/extend/page.tsx b/src/app/(studio)/extend/page.tsxindex eb1ba847..6bceb411 100644--- a/src/app/(studio)/extend/page.tsx+++ b/src/app/(studio)/extend/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { EXTEND_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Extend video" };export default function Page() {- return <StudioPage config={EXTEND_STUDIO} />;+ return <Studio config={EXTEND_STUDIO} />;}diff --git a/src/app/(studio)/image/page.tsx b/src/app/(studio)/image/page.tsxindex ab0fe5c5..4c712490 100644--- a/src/app/(studio)/image/page.tsx+++ b/src/app/(studio)/image/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { IMAGE_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Create image" };export default function Page() {- return <StudioPage config={IMAGE_STUDIO} />;+ return <Studio config={IMAGE_STUDIO} />;}diff --git a/src/app/(studio)/inpaint/page.tsx b/src/app/(studio)/inpaint/page.tsxindex 3c775554..27874853 100644--- a/src/app/(studio)/inpaint/page.tsx+++ b/src/app/(studio)/inpaint/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { INPAINT_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Inpaint" };export default function Page() {- return <StudioPage config={INPAINT_STUDIO} />;+ return <Studio config={INPAINT_STUDIO} />;}diff --git a/src/app/(studio)/lipsync/page.tsx b/src/app/(studio)/lipsync/page.tsxindex 66aa3053..52fe6cd8 100644--- a/src/app/(studio)/lipsync/page.tsx+++ b/src/app/(studio)/lipsync/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { LIPSYNC_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Lipsync & avatars" };export default function Page() {- return <StudioPage config={LIPSYNC_STUDIO} />;+ return <Studio config={LIPSYNC_STUDIO} />;}diff --git a/src/app/(studio)/motion-control/page.tsx b/src/app/(studio)/motion-control/page.tsxindex 10ce67cc..be3dbc89 100644--- a/src/app/(studio)/motion-control/page.tsx+++ b/src/app/(studio)/motion-control/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { MOTION_CONTROL_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Motion control" };export default function Page() {- return <StudioPage config={MOTION_CONTROL_STUDIO} />;+ return <Studio config={MOTION_CONTROL_STUDIO} />;}diff --git a/src/app/(studio)/reframe/page.tsx b/src/app/(studio)/reframe/page.tsxindex f8690c6e..7426bca9 100644--- a/src/app/(studio)/reframe/page.tsx+++ b/src/app/(studio)/reframe/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { REFRAME_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Reframe" };export default function Page() {- return <StudioPage config={REFRAME_STUDIO} />;+ return <Studio config={REFRAME_STUDIO} />;}diff --git a/src/app/(studio)/video-edit/page.tsx b/src/app/(studio)/video-edit/page.tsxindex 040f9542..558c6dbc 100644--- a/src/app/(studio)/video-edit/page.tsx+++ b/src/app/(studio)/video-edit/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { VIDEO_EDIT_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Edit video" };export default function Page() {- return <StudioPage config={VIDEO_EDIT_STUDIO} />;+ return <Studio config={VIDEO_EDIT_STUDIO} />;}diff --git a/src/app/(studio)/video/page.tsx b/src/app/(studio)/video/page.tsxindex 270d37cd..9a8a4324 100644--- a/src/app/(studio)/video/page.tsx+++ b/src/app/(studio)/video/page.tsx@@ -1,9 +1,9 @@import type { Metadata } from "next";-import { StudioPage } from "@/components/studio/studio-page";+import { Studio } from "@/components/studio/studio";import { VIDEO_STUDIO } from "@/lib/studios";export const metadata: Metadata = { title: "Create video" };export default function Page() {- return <StudioPage config={VIDEO_STUDIO} />;+ return <Studio config={VIDEO_STUDIO} />;}diff --git a/src/components/studio/attach-menu.tsx b/src/components/studio/attach-menu.tsxnew file mode 100644index 00000000..02d90d9a--- /dev/null+++ b/src/components/studio/attach-menu.tsx@@ -0,0 +1,107 @@+"use client";++import { ClipboardPaste, Plus, Upload } from "lucide-react";+import { useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Kbd } from "@/components/ui/kbd";+import type { MediaKind } from "@/lib/catalog/types";+import { ACCEPT, LibraryGrid, type SlotValue } from "./media-slot";+import { ResponsivePanel } from "./responsive-panel";++const KIND_WORD: Record<MediaKind, string> = { image: "images", video: "videos", audio: "audio", text: "text", model3d: "3D models" };++/** Read pasteable media from the clipboard (needs the browser's clipboard permission). */+async function clipboardFiles(): Promise<File[]> {+ const items = await navigator.clipboard.read();+ const files: File[] = [];+ for (const item of items) {+ const type = item.types.find((t) => /^(image|video|audio)\//.test(t));+ if (!type) continue;+ const blob = await item.getType(type);+ files.push(new File([blob], `pasted.${type.split("/")[1]?.replace("jpeg", "jpg") ?? "png"}`, { type }));+ }+ return files;+}++/**+ * The composer's "+": upload from the device, paste, or pick something you made or uploaded+ * before. Attachments land in the first empty slot of their kind, then in the references.+ */+export function AttachMenu({ kinds, onFiles, onPick }: { kinds: MediaKind[]; onFiles: (files: File[]) => void; onPick: (v: SlotValue) => void }) {+ const [open, setOpen] = useState(false);+ const input = useRef<HTMLInputElement>(null);+ const mac = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform);+ const paste = async () => {+ try {+ const files = await clipboardFiles();+ if (!files.length) return toast("Nothing to paste — copy an image first");+ onFiles(files);+ setOpen(false);+ } catch {+ toast(`Press ${mac ? "⌘V" : "Ctrl+V"} in the prompt to paste`);+ }+ };+ const words = kinds.map((k) => KIND_WORD[k]);+ return (+ <ResponsivePanel+ open={open}+ onOpenChange={setOpen}+ title="Add media"+ description={`Attach ${words.join(", ").replace(/, ([^,]*)$/, " or $1")}`}+ className="w-[min(92vw,360px)] p-2.5"+ tooltip="Upload, paste or pick from your library"+ trigger={+ <button+ type="button"+ aria-label="Add media"+ className="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50"+ >+ <Plus className="size-4" />+ </button>+ }+ >+ <div className="space-y-3">+ <div className="grid grid-cols-2 gap-1.5">+ <Button variant="secondary" className="h-10 justify-start gap-2" onClick={() => input.current?.click()}>+ <Upload /> Upload+ </Button>+ <Button variant="secondary" className="h-10 justify-start gap-2" onClick={paste}>+ <ClipboardPaste /> Paste+ <span className="ml-auto hidden items-center gap-0.5 sm:flex">+ <Kbd>{mac ? "⌘" : "Ctrl"}</Kbd>+ <Kbd>V</Kbd>+ </span>+ </Button>+ </div>+ <input+ ref={input}+ type="file"+ multiple+ hidden+ accept={kinds.map((k) => ACCEPT[k]).join(",")}+ onChange={(e) => {+ const files = [...(e.target.files ?? [])];+ e.target.value = "";+ if (files.length) {+ onFiles(files);+ setOpen(false);+ }+ }}+ />+ <div className="space-y-1.5">+ <p className="text-[12px] font-medium text-muted-foreground">From your library</p>+ {open && (+ <LibraryGrid+ kinds={kinds}+ onPick={(v) => {+ onPick(v);+ setOpen(false);+ }}+ />+ )}+ </div>+ </div>+ </ResponsivePanel>+ );+}diff --git a/src/components/studio/attachments.ts b/src/components/studio/attachments.tsnew file mode 100644index 00000000..c6e51f67--- /dev/null+++ b/src/components/studio/attachments.ts@@ -0,0 +1,114 @@+"use client";++import { nanoid } from "nanoid";+import { createContext, useCallback, useContext, useEffect, useMemo } from "react";+import { toast } from "sonner";+import { placeAttachment, replaceAttachment } from "@/lib/composer";+import type { InputSlot, MediaKind } from "@/lib/catalog/types";+import { fileToSlot, kindOfFile, type SlotValue } from "./media-slot";+import { useStudio, type Draft, type SlotKey } from "./studio-context";++/**+ * In-flight uploads by attachment id. `seen` turns true once the attachment is in the draft;+ * when a seen attachment leaves the draft (removed, replaced, the draft reset by Reuse) its+ * upload is aborted, and a result that arrives anyway finds nothing to replace.+ */+const inflight = new Map<string, { ac: AbortController; seen: boolean }>();++/** Abort uploads whose attachment is gone from the draft. Mount once, where the draft is read. */+export function useUploadReaper(draft: Pick<Draft, "slots" | "refs">) {+ useEffect(() => {+ if (!inflight.size) return;+ const ids = new Set([...Object.values(draft.slots), ...draft.refs].map((v) => v?.id).filter(Boolean));+ for (const [id, e] of inflight) {+ if (ids.has(id)) e.seen = true;+ else if (e.seen) {+ e.ac.abort();+ inflight.delete(id);+ }+ }+ }, [draft.slots, draft.refs]);+}++/**+ * Attach files to the studio draft: paste, drop, the "+" menu and the slot tiles all go through+ * here. Each file is placed once with its local preview, then swapped for the uploaded asset by+ * id (never re-added if it was removed meanwhile).+ */+export function useAttach(slots: InputSlot[], refMax: number) {+ const { config, setDraft } = useStudio();++ /** Upload a file: `place` runs once with the local preview, the result replaces it by id. */+ const start = useCallback(+ (file: File, place: (v: SlotValue) => void, kind?: MediaKind) => {+ const id = nanoid(8);+ const entry = { ac: new AbortController(), seen: false };+ inflight.set(id, entry);+ let placed = false;+ void fileToSlot(+ file,+ (v) => {+ if (!placed) {+ placed = true;+ if (v) place({ ...v, id });+ else inflight.delete(id);+ return;+ }+ inflight.delete(id);+ setDraft((d) => replaceAttachment(d, id, v) ?? {});+ },+ kind,+ { signal: entry.ac.signal },+ );+ },+ [setDraft],+ );++ const kinds = useMemo(() => {+ const k = new Set<MediaKind>(slots.filter((s) => s.key !== "mask" && s.key !== "sketch").map((s) => s.accept));+ if (config.multiRef) k.add(config.multiRef.kind ?? "image");+ return k;+ }, [slots, config.multiRef]);++ /** Wherever it fits best: the first empty slot of its kind, else the references. */+ const attach = useCallback((v: SlotValue) => setDraft((d) => placeAttachment(d, slots, config.multiRef, refMax, v) ?? {}), [setDraft, slots, config.multiRef, refMax]);++ const attachFiles = useCallback(+ (files: File[]) => {+ const usable = files.filter((f) => kinds.has(kindOfFile(f)));+ if (usable.length < files.length) toast(files.length - usable.length > 1 ? "This studio doesn't take those files" : "This studio doesn't take that kind of file");+ for (const f of usable.slice(0, 8)) start(f, attach);+ },+ [kinds, start, attach],+ );++ /** A slot tile: replace its value (an upload it held is cancelled by the reaper). */+ const setSlotValue = useCallback(+ (key: SlotKey, v: SlotValue | null) =>+ // A drawing belongs to the image it was made on.+ setDraft((d) => ({ slots: { ...d.slots, [key]: v, ...(key === "image" && d.slots.image?.ref !== v?.ref && { mask: null, sketch: null }) } })),+ [setDraft],+ );++ const uploadToSlot = useCallback((key: SlotKey, file: File, kind: MediaKind) => start(file, (v) => setSlotValue(key, v), kind), [start, setSlotValue]);++ const removeRef = useCallback((r: SlotValue) => setDraft((d) => ({ refs: d.refs.filter((x) => (r.id ? x.id !== r.id : x !== r)) })), [setDraft]);++ const addRefFile = useCallback((file: File) => start(file, (v) => setDraft((d) => ({ refs: [...d.refs, v] })), config.multiRef?.kind), [start, setDraft, config.multiRef]);++ return useMemo(() => ({ kinds, attach, attachFiles, setSlotValue, uploadToSlot, removeRef, addRefFile }), [kinds, attach, attachFiles, setSlotValue, uploadToSlot, removeRef, addRefFile]);+}++/**+ * The page's drop zone hands files to the composer, which knows the current slots (they change+ * with the model and preset). The composer registers its `attachFiles` here.+ */+export interface ComposerBridge {+ current: ((files: File[]) => void) | null;+}++export const ComposerBridgeCtx = createContext<ComposerBridge | null>(null);++export function useComposerBridge(): ComposerBridge | null {+ return useContext(ComposerBridgeCtx);+}diff --git a/src/components/studio/audio-controls.tsx b/src/components/studio/audio-controls.tsxindex 9b012989..cf737970 100644--- a/src/components/studio/audio-controls.tsx+++ b/src/components/studio/audio-controls.tsx@@ -1,6 +1,6 @@"use client";-import { AudioLines, Check, Globe, Minus, Plus, SlidersHorizontal, Upload, User, X } from "lucide-react";+import { AudioLines, Check, Globe, Minus, Plus, Upload, User, X } from "lucide-react";import Link from "next/link";import { useMemo, useRef, useState } from "react";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";@@ -154,38 +154,32 @@ export function VoicePicker({);}-/** Numeric voice settings (stability, similarity, speed…), sent as-is. */-export function SlidersChip({ model, values, onChange }: { model: ModelDef; values: Record<string, unknown>; onChange: (param: string, v?: number) => void }) {+/** Numeric model settings (stability, similarity, speed, strength…), sent as-is. Shown in the settings panel. */+export function SliderControls({ model, values, onChange }: { model: ModelDef; values: Record<string, unknown>; onChange: (param: string, v?: number) => void }) {const sliders = model.options.sliders ?? [];- const changed = sliders.filter((s) => typeof values[s.param] === "number" && values[s.param] !== s.default).length;return (- <Popover>- <PopoverTrigger asChild>- <button type="button" className={cn(chip, changed ? on : idle)}>- <SlidersHorizontal className="size-3.5" /> {changed ? `Settings · ${changed}` : "Settings"}- </button>- </PopoverTrigger>- <PopoverContent className="w-72 space-y-4 p-3" align="start" side="top">- {sliders.map((s) => {- const v = typeof values[s.param] === "number" ? (values[s.param] as number) : s.default;- return (- <div key={s.param} className="space-y-2">- <div className="flex justify-between text-[13px]">- <span>{s.label}</span>- <button- className="font-mono text-[12px] text-muted-foreground"- onDoubleClick={() => onChange(s.param, undefined)}- title="Double-click to reset"- >- {Number(v.toFixed(2))}- </button>- </div>- <Slider value={[v]} min={s.min} max={s.max} step={s.step} onValueChange={([x]) => onChange(s.param, x)} />+ <div className="space-y-3.5">+ {sliders.map((s) => {+ const v = typeof values[s.param] === "number" ? (values[s.param] as number) : s.default;+ const changed = v !== s.default;+ return (+ <div key={s.param} className="space-y-2">+ <div className="flex items-center justify-between text-[13px]">+ <span>{s.label}</span>+ <span className="flex items-center gap-1.5">+ {changed && (+ <button className="rounded text-[11px] text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50" onClick={() => onChange(s.param, undefined)} aria-label={`Reset ${s.label}`}>+ Reset+ </button>+ )}+ <span className="text-[12px] text-muted-foreground tabular-nums">{Number(v.toFixed(2))}</span>+ </span></div>- );- })}- </PopoverContent>- </Popover>+ <Slider value={[v]} min={s.min} max={s.max} step={s.step} onValueChange={([x]) => onChange(s.param, x)} aria-label={s.label} />+ </div>+ );+ })}+ </div>);}diff --git a/src/components/studio/catalog.tsx b/src/components/studio/catalog.tsxnew file mode 100644index 00000000..bb1a6a18--- /dev/null+++ b/src/components/studio/catalog.tsx@@ -0,0 +1,87 @@+"use client";++import { createContext, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";+import type { ModelDef, Preset } from "@/lib/catalog/types";+import type { StudioCatalog } from "@/lib/studio-catalog";+import type { StudioConfig } from "./studio-context";++/**+ * Model and preset lookups for one studio, without the whole catalog in the page bundle.+ *+ * The server passes the studio's slice (`StudioCatalog`) as a prop. Anything outside it — the+ * camera motions and effects for the preset picker, a preset handed over in the URL, a model a+ * reused generation ran on — comes from the full catalog, loaded as a separate chunk on demand.+ */++type FullCatalog = typeof import("@/lib/catalog");++let full: FullCatalog | null = null;+let loading: Promise<FullCatalog> | null = null;+const subscribers = new Set<() => void>();++/** Load the full catalog chunk (once). Safe to call on hover to prefetch. */+export function loadFullCatalog(): Promise<FullCatalog> {+ loading ??= import("@/lib/catalog").then((m) => {+ full = m;+ subscribers.forEach((f) => f());+ return m;+ });+ return loading;+}++const subscribe = (cb: () => void) => {+ subscribers.add(cb);+ return () => void subscribers.delete(cb);+};++function useFullCatalog(): FullCatalog | null {+ return useSyncExternalStore(subscribe, () => full, () => null);+}++export interface CatalogApi {+ /** The studio's models are known (false only while a studio without a server slice loads it). */+ ready: boolean;+ models: ModelDef[];+ getModel: (id: string) => ModelDef | undefined;+ getPreset: (id: string) => Preset | undefined;+ /** Camera motions / effects, once the full catalog is loaded (null before). */+ presets: { motion: Preset[]; effect: Preset[] } | null;+ /** True once the full catalog chunk has arrived. */+ complete: boolean;+}++const Ctx = createContext<CatalogApi | null>(null);++export function useCatalog(): CatalogApi {+ const c = useContext(Ctx);+ if (!c) throw new Error("useCatalog outside CatalogProvider");+ return c;+}++export function CatalogProvider({ catalog, config, children }: { catalog?: StudioCatalog; config: StudioConfig; children: React.ReactNode }) {+ const fullCatalog = useFullCatalog();+ // Studios rendered from client code (an element's page) have no server slice: compute it from the lazy chunk.+ const [lazy, setLazy] = useState<StudioCatalog | null>(null);+ useEffect(() => {+ if (catalog) return;+ let live = true;+ void import("@/lib/studio-catalog").then((m) => live && setLazy(m.studioCatalog(config)));+ return () => {+ live = false;+ };+ }, [catalog, config]);+ const slice = catalog ?? lazy;+ const value = useMemo<CatalogApi>(() => {+ const models = slice?.models ?? [];+ const index = new Map(models.map((m) => [m.id, m]));+ return {+ ready: !!slice,+ models,+ getModel: (id) => index.get(id) ?? fullCatalog?.getModel(id),+ getPreset: (id) => (config.preset?.id === id ? config.preset : fullCatalog?.getPreset(id)),+ presets: fullCatalog ? { motion: fullCatalog.MOTIONS, effect: fullCatalog.EFFECTS } : null,+ complete: !!fullCatalog,+ };+ }, [slice, fullCatalog, config.preset]);+ return <Ctx.Provider value={value}>{children}</Ctx.Provider>;+}diff --git a/src/components/studio/chip.tsx b/src/components/studio/chip.tsxnew file mode 100644index 00000000..6f3a6634--- /dev/null+++ b/src/components/studio/chip.tsx@@ -0,0 +1,43 @@+"use client";++import { X } from "lucide-react";+import { forwardRef } from "react";+import { cn } from "@/lib/utils";++export const chipBase = "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50";+export const chipIdle = "bg-secondary text-secondary-foreground hover:bg-accent";+export const chipOn = "bg-brand-faint text-brand-text hover:bg-brand-faint-hover";++/** A toolbar chip (32 px pill). Forwards its ref so it can be a Popover/Sheet trigger. */+export const Chip = forwardRef<HTMLButtonElement, React.ComponentProps<"button"> & { icon?: React.ComponentType<{ className?: string }>; active?: boolean }>(function Chip(+ { icon: Icon, children, active, className, ...props },+ ref,+) {+ return (+ <button ref={ref} type="button" {...props} className={cn(chipBase, active ? chipOn : chipIdle, className)}>+ {Icon && <Icon className="size-3.5" />}+ {children}+ </button>+ );+});++/**+ * A selected chip with its own clear button next to it (a real, focusable button, so the choice+ * can be removed from the keyboard). `children` is the trigger chip.+ */+export function ClearableChip({ active, onClear, clearLabel, children }: { active: boolean; onClear: () => void; clearLabel: string; children: React.ReactNode }) {+ if (!active) return <>{children}</>;+ return (+ <span className="inline-flex shrink-0 items-center rounded-full bg-brand-faint text-brand-text [&>button:first-child]:bg-transparent [&>button:first-child]:pr-1.5 [&>button:first-child:hover]:bg-brand-faint-hover">+ {children}+ <button+ type="button"+ onClick={onClear}+ aria-label={clearLabel}+ className="mr-1 -ml-0.5 grid size-6 place-items-center rounded-full opacity-70 transition outline-none hover:bg-brand-faint-hover hover:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/50"+ >+ <X className="size-3.5" />+ </button>+ </span>+ );+}diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 7c94f61a..a62e2576 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -1,53 +1,42 @@"use client";-import {- ArrowUp,- AtSign,- FileVideo2,- Clock,- Copy as CopyIcon,- Film,- Loader2,- Maximize,- Ratio,- Settings2,- Shuffle,- Sparkles,- Volume2,- VolumeX,- X,-} from "lucide-react";+import { ArrowUp, AtSign, Loader2, Sparkles, X } from "lucide-react";+import dynamic from "next/dynamic";import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";-import { Slider } from "@/components/ui/slider";-import { Switch } from "@/components/ui/switch";-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { Kbd } from "@/components/ui/kbd";-import { EFFECTS, getModel, getPreset, modelsFor, MOTIONS } from "@/lib/catalog";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";-import { OPERATION_LABELS, type GenerationRequest, type MediaKind, type ModelDef, type Operation, type Preset } from "@/lib/catalog/types";-import { enhance, useCreateGeneration, useElements, useEngine, useStatus } from "@/lib/api";+import type { GenerationRequest, MediaKind, ModelDef, Operation, Preset } from "@/lib/catalog/types";+import { enhance, useCreateGeneration, useElements, useEngine, useHydrated, useStatus } from "@/lib/api";import { applyMentions, type StudioElement } from "@/lib/catalog/elements";import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";-import { formatCost, ratioValue } from "@/lib/format";+import { blockerFor, costLabel, filterModels, firstMissingSlot, PLACEHOLDER, pushRecent, settingsShape } from "@/lib/composer";+import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";-import { PRESET_ICONS } from "@/components/preset-icons";-import { fileToSlot, MediaSlot, SlotPreview, type SlotValue } from "./media-slot";+import { AttachMenu } from "./attach-menu";+import { useAttach, useComposerBridge, useUploadReaper } from "./attachments";+import { DialogueEditor, LanguageChip, VoicePicker } from "./audio-controls";+import { loadFullCatalog, useCatalog } from "./catalog";+import { Chip } from "./chip";+import { MediaSlot, SlotPreview, type SlotValue } from "./media-slot";import { ControlsChip, ProviderPresetChip } from "./model-controls";import { ModelPicker } from "./model-picker";import { ELEMENT_ICONS, PromptInput, type PromptInputHandle } from "./prompt-input";+import { SettingsChip } from "./settings-panel";+import { ShotsEditor } from "./shots-editor";import { SketchTools } from "./sketch-tools";-import { MultiShotChip, ShotsEditor } from "./shots-editor";-import { DialogueEditor, LanguageChip, SlidersChip, VoicePicker } from "./audio-controls";-import { useStudio } from "./studio-context";-import { nanoid } from "nanoid";+import { RECENT_MODELS, useStoredList } from "./stored-list";+import { useStudio, type Draft } from "./studio-context";+import { useEdgeFade } from "./use-edge-fade";const EMPTY: StudioElement[] = [];-/** Operations that transform one input into one result — no batch count. */-const SINGLE_TAKE = new Set<Operation | undefined>(["lipsync", "avatar", "upscale-video", "dub", "extend", "reframe", "finalize", "v2a", "interpolate"]);+/** The motion / effect picker (and its preset icons) is its own chunk: only video studios load it. */+const PresetChips = dynamic(() => import("./preset-chips"), {+ loading: () => <span aria-hidden className="h-8 w-32 shrink-0 animate-pulse rounded-full bg-secondary" />,+});/** Two speakers to start a dialogue with. */const defaultLines = (m: ModelDef) => {@@ -58,259 +47,11 @@ const defaultLines = (m: ModelDef) => {];};-// ----------------------------------------------------------------------------// Chips--function Chip({- icon: Icon,- children,- active,- ...props-}: React.ComponentProps<"button"> & { icon?: typeof Ratio; active?: boolean }) {- return (- <button- type="button"- {...props}- className={cn(- "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors",- active ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",- props.className,- )}- >- {Icon && <Icon className="size-3.5" />}- {children}- </button>- );-}--function RatioGlyph({ ratio }: { ratio: string }) {- const r = ratioValue(ratio === "auto" ? "1:1" : ratio);- const w = r >= 1 ? 18 : 18 * r;- const h = r >= 1 ? 18 / r : 18;- return <span className="inline-block rounded-[3px] border-[1.5px] border-current" style={{ width: w, height: h }} />;-}--function AspectChip({ options, value, onChange }: { options: string[]; value?: string; onChange: (v: string) => void }) {- const [open, setOpen] = useState(false);- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <Chip icon={Ratio}>{value ?? options[0]}</Chip>- </PopoverTrigger>- <PopoverContent className="w-72 p-2" align="start" side="top">- <p className="px-1 pb-2 text-[13px] font-medium">Aspect ratio</p>- <div className="grid grid-cols-4 gap-1">- {options.map((o) => (- <button- key={o}- onClick={() => {- onChange(o);- setOpen(false);- }}- className={cn(- "flex h-16 flex-col items-center justify-center gap-1.5 rounded-lg text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent",- value === o && "bg-brand-faint text-brand-text",- )}- >- <span className="grid h-5 place-items-center">- <RatioGlyph ratio={o} />- </span>- {o === "auto" ? "Auto" : o}- </button>- ))}- </div>- </PopoverContent>- </Popover>- );-}--function SegmentChip<T extends string | number>({- icon,- label,- options,- value,- onChange,- format = (v) => String(v),-}: {- icon: typeof Ratio;- label: string;- options: T[];- value?: T;- onChange: (v: T) => void;- format?: (v: T) => string;-}) {- const [open, setOpen] = useState(false);- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <Chip icon={icon}>{value !== undefined ? format(value) : format(options[0])}</Chip>- </PopoverTrigger>- <PopoverContent className="w-auto min-w-44 p-2" align="start" side="top">- <p className="px-1 pb-2 text-[13px] font-medium">{label}</p>- <div className="flex flex-wrap gap-1 rounded-full bg-muted p-0.5">- {options.map((o) => (- <button- key={String(o)}- onClick={() => {- onChange(o);- setOpen(false);- }}- className={cn(- "h-7 min-w-12 flex-1 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition",- value === o && "bg-background text-foreground shadow-soft",- )}- >- {format(o)}- </button>- ))}- </div>- </PopoverContent>- </Popover>- );-}--function PresetGrid({ list, value, onPick }: { list: Preset[]; value?: string; onPick: (id: string) => void }) {- const [cat, setCat] = useState<string>("All");- const cats = ["All", ...new Set(list.map((p) => p.category))];- return (- <>- <div className="scrollbar-none mb-2 flex gap-1 overflow-x-auto">- {cats.map((c) => (- <button- key={c}- onClick={() => setCat(c)}- className={cn("h-7 shrink-0 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground hover:bg-accent", cat === c && "bg-secondary text-foreground")}- >- {c}- </button>- ))}- </div>- <div className="grid max-h-72 grid-cols-3 gap-1.5 overflow-y-auto">- {list- .filter((p) => cat === "All" || p.category === cat)- .map((p) => {- const PI = PRESET_ICONS[p.look.icon] ?? Film;- return (- <button- key={p.id}- onClick={() => onPick(p.id)}- className={cn("group flex flex-col items-start gap-1 overflow-hidden rounded-lg p-1 text-left ring-primary transition hover:bg-accent", value === p.id && "ring-2")}- >- <span className="grid aspect-video w-full place-items-center rounded-md text-white" style={{ background: `linear-gradient(135deg, ${p.look.from}, ${p.look.to})` }}>- <PI className="size-5 transition-transform duration-300 group-hover:scale-125" />- </span>- <span className="truncate px-0.5 text-[12px] font-medium">{p.name}</span>- </button>- );- })}- </div>- </>- );-}--function PresetChip({ type, value, onChange }: { type: "motion" | "effect"; value?: string; onChange: (id?: string) => void }) {- const [open, setOpen] = useState(false);- const list = type === "motion" ? MOTIONS : EFFECTS;- const selected = value ? getPreset(value) : undefined;- const Icon = selected ? (PRESET_ICONS[selected.look.icon] ?? Film) : Film;- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <Chip icon={Icon} active={!!selected}>- {selected?.name ?? (type === "motion" ? "Camera motion" : "Effect")}- {selected && (- <X- className="-mr-1 size-3.5 opacity-70 hover:opacity-100"- onClick={(e) => {- e.stopPropagation();- onChange(undefined);- }}- />- )}- </Chip>- </PopoverTrigger>- <PopoverContent className="w-[min(92vw,460px)] p-2" align="start" side="top" collisionPadding={12}>- <PresetGrid- list={list}- value={value}- onPick={(id) => {- onChange(id);- setOpen(false);- }}- />- </PopoverContent>- </Popover>- );-}--const MIXABLE = [...MOTIONS, ...EFFECTS];-const pct = (n: number) => `${Math.round(n * 100)}%`;--/** Higgsfield's Mix: a second motion or effect on top of the first, each with a strength. */-function MixChip({- primary,- strength,- mix,- onChange,-}: {- primary: Preset;- strength: number;- mix?: { presetId: string; strength: number };- onChange: (patch: { presetStrength?: number; mix?: { presetId: string; strength: number } | undefined }) => void;-}) {- const [open, setOpen] = useState(false);- const second = mix ? getPreset(mix.presetId) : undefined;- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <Chip icon={Shuffle} active={!!second}>- {second ? `+ ${second.name}` : "Mix"}- {second && (- <X- className="-mr-1 size-3.5 opacity-70 hover:opacity-100"- onClick={(e) => {- e.stopPropagation();- onChange({ mix: undefined });- }}- />- )}- </Chip>- </PopoverTrigger>- <PopoverContent className="w-[min(92vw,460px)] space-y-3 p-3" align="start" side="top" collisionPadding={12}>- <div className="space-y-2.5">- <div className="space-y-1.5">- <div className="flex items-center justify-between text-[12px]">- <span className="font-medium">{primary.name}</span>- <span className="font-mono text-muted-foreground">{pct(strength)}</span>- </div>- <Slider min={0.1} max={1} step={0.05} value={[strength]} onValueChange={([v]) => onChange({ presetStrength: v })} aria-label={`${primary.name} strength`} />- </div>- {second && mix && (- <div className="space-y-1.5">- <div className="flex items-center justify-between text-[12px]">- <span className="font-medium">{second.name}</span>- <span className="font-mono text-muted-foreground">{pct(mix.strength)}</span>- </div>- <Slider min={0.1} max={1} step={0.05} value={[mix.strength]} onValueChange={([v]) => onChange({ mix: { ...mix, strength: v } })} aria-label={`${second.name} strength`} />- </div>- )}- </div>- <p className="text-[12px] text-muted-foreground">{second ? "Swap the second preset:" : "Pick a second motion or effect to combine with it:"}</p>- <PresetGrid- list={MIXABLE.filter((p) => p.id !== primary.id && !p.inputs.some((i) => i.key === "endImage"))}- value={mix?.presetId}- onPick={(id) => onChange({ mix: { presetId: id, strength: mix?.strength ?? 0.6 } })}- />- </PopoverContent>- </Popover>- );-}-// ---------------------------------------------------------------------------function buildRequest(feature: string,- draft: ReturnType<typeof useStudio>["draft"],+ draft: Pick<Draft, "slots" | "refs" | "presetId" | "modelId" | "prompt" | "negativePrompt" | "params" | "presetOptions" | "presetStrength" | "mix">,op: Operation | undefined,promptSuffix?: string,refKind: MediaKind = "image",@@ -344,63 +85,134 @@ function buildRequest(};}+/** Point at an attachment tile: scroll it into view and pulse its outline. */+function pulseSlot(root: HTMLElement | null, key: string) {+ const el = root?.querySelector<HTMLElement>(`[data-slot-key="${key}"]`);+ if (!el) return;+ el.scrollIntoView({ block: "nearest", inline: "nearest" });+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;+ const primary = getComputedStyle(document.documentElement).getPropertyValue("--primary").trim() || "currentColor";+ el.animate(+ [+ { boxShadow: `0 0 0 0 color-mix(in oklab, ${primary} 70%, transparent)` },+ { boxShadow: `0 0 0 7px color-mix(in oklab, ${primary} 0%, transparent)` },+ ],+ { duration: 650, iterations: 2, easing: "ease-out" },+ );+}+export function Composer({ docked }: { docked: boolean }) {- const { config, draft, setDraft, setSlot, addImage } = useStudio();+ const { config, draft, setDraft, setSlot } = useStudio();+ const catalog = useCatalog();const [engine, setEngine] = useEngine();const create = useCreateGeneration();const [enhancing, setEnhancing] = useState(false);+ const [focused, setFocused] = useState(false);const promptRef = useRef<PromptInputHandle>(null);- const status = useStatus().data;- const elements = useElements().data ?? EMPTY;+ const root = useRef<HTMLDivElement>(null);+ // Connection status can arrive before this Suspense subtree hydrates: render the server's view (no status) until then.+ const hydrated = useHydrated();+ const liveStatus = useStatus().data;+ const status = hydrated ? liveStatus : undefined;+ const liveElements = useElements().data;+ const elements = (hydrated && liveElements) || EMPTY;+ const [, setRecent] = useStoredList(RECENT_MODELS);+ const bridgeRef = useComposerBridge();+ const [chipRow, fade] = useEdgeFade<HTMLDivElement>();+ useUploadReaper(draft);- const preset: Preset | undefined = draft.presetId ? getPreset(draft.presetId) : config.preset;+ const preset: Preset | undefined = draft.presetId ? catalog.getPreset(draft.presetId) : config.preset;const lockedModel = preset?.type === "app";- const models = useMemo(() => modelsFor({ kind: config.kind, ops: config.ops }), [config.kind, config.ops]);- const model: ModelDef | undefined = getModel(draft.modelId);+ const models = useMemo(() => filterModels(catalog.models, { kind: config.kind, ops: config.ops }), [catalog.models, config.kind, config.ops]);+ const model: ModelDef | undefined = catalog.getModel(draft.modelId);+ const presetLoading = !!draft.presetId && !preset && !catalog.complete;++ // Presets handed over in the URL, a Mix, or a model outside this studio's slice: fetch the full catalog.+ const needsFull = presetLoading || (!!draft.mix && !catalog.getPreset(draft.mix.presetId)) || (catalog.ready && !model);+ useEffect(() => {+ if (needsFull) void loadFullCatalog();+ }, [needsFull]);// Keep the selected model in sync with the engine switch.useEffect(() => {if (!model || model.engine === engine) return;- const next = lockedModel- ? (engine === "open" ? preset?.open?.modelId : preset?.cloud?.modelId)- : config.defaultModels[engine];- if (next && getModel(next)) setDraft((d) => ({ modelId: next, params: { ...getModel(next)!.defaults, numOutputs: d.params.numOutputs, enhancePrompt: d.params.enhancePrompt } }));- }, [engine, model, lockedModel, preset, config.defaultModels, setDraft]);+ const next = lockedModel ? (engine === "open" ? preset?.open?.modelId : preset?.cloud?.modelId) : config.defaultModels[engine];+ const m = next ? catalog.getModel(next) : undefined;+ if (m) setDraft((d) => ({ modelId: m.id, params: { ...m.defaults, numOutputs: d.params.numOutputs, enhancePrompt: d.params.enhancePrompt } }));+ }, [engine, model, lockedModel, preset, config.defaultModels, setDraft, catalog]);// Single-purpose studios (Extend, Reframe, Edit video…) pin their operation.const studioOp = config.ops.length === 1 && !preset ? config.ops[0] : undefined;- const rawRequest = buildRequest(config.feature, draft, studioOp, config.promptSuffix, config.multiRef?.kind);- const mentions = model ? applyMentions(rawRequest, model, elements) : { request: rawRequest, mentioned: [], notes: [] };- const sketched = model ? applySketch(mentions.request, model) : { request: mentions.request };- const request = model ? stripMotionPaths(sketched.request, model) : sketched.request;+ const slots = preset?.inputs ?? config.slots;+ const opts = model?.options ?? {};+ // Clips: ComfyUI joins 4 at a time. Images: what the model takes beyond the fixed image slots.+ const refMax = !config.multiRef+ ? 0+ : config.multiRef.kind === "video"+ ? Math.min(config.multiRef.max, model?.engine === "open" ? 4 : config.multiRef.max)+ : Math.min(config.multiRef.max, Math.max(0, (opts.maxImages ?? 1) - slots.filter((s) => s.accept === "image").length));+ const attach = useAttach(slots, refMax);++ // The page's drop zone hands its files to this composer.+ useEffect(() => {+ if (!bridgeRef) return;+ bridgeRef.current = attach.attachFiles;+ return () => {+ if (bridgeRef.current === attach.attachFiles) bridgeRef.current = null;+ };+ }, [bridgeRef, attach.attachFiles]);++ const prepare = (d: typeof draft) => {+ const raw = buildRequest(config.feature, d, studioOp, config.promptSuffix, config.multiRef?.kind);+ const mentions = model ? applyMentions(raw, model, elements) : { request: raw, mentioned: [], notes: [] };+ const sketched = model ? applySketch(mentions.request, model) : { request: mentions.request };+ return { mentions, sketched, request: model ? stripMotionPaths(sketched.request, model) : sketched.request };+ };+ const { mentions, sketched } = prepare(draft);const resolvesOnServer = mentions.mentioned.length > 0 || !!draft.slots.mask?.ref || !!draft.slots.sketch?.ref;++ // Plan with stand-ins for attachments that are missing or still uploading, so the cost and the+ // operation are known up front and the blocker can name the slot in the studio's own words.+ const missing = firstMissingSlot(slots, draft.slots);+ const uploading = Object.values(draft.slots).some((v) => v?.uploading) || draft.refs.some((r) => r.uploading);+ const engineError = lockedModel && preset && !(engine === "open" ? preset.open : preset.cloud) ? `${preset.name} has no ${engine === "open" ? "open-source" : "cloud"} version yet` : null;let op: Operation | undefined;- let blocker: string | null = null;let cost: number | null = null;- try {- if (!model) throw new Error("Pick a model");- if (lockedModel && preset && !(engine === "open" ? preset.open : preset.cloud)) {- throw new Error(`${preset.name} has no ${engine === "open" ? "open-source" : "cloud"} version yet`);- }- const plan = planGeneration({ ...request, prompt: request.prompt || (config.promptOptional ? " " : "") }, getModel, getPreset);- op = plan.op;- cost = estimateCost(plan.model, plan.params, plan.jobs);- for (const s of preset?.inputs ?? config.slots) {- if (s.required && !draft.slots[s.key]?.ref) throw new Error(`Add ${s.label.toLowerCase()}`);- }- if (Object.values(draft.slots).some((v) => v?.uploading) || draft.refs.some((r) => r.uploading)) throw new Error("Uploading…");- if (!config.promptOptional && preset?.userPrompt !== "none" && preset?.userPrompt !== "optional" && !draft.prompt.trim() && !draft.params.shots?.some((s) => s.prompt.trim())) {- throw new Error("Write a prompt first");+ let planError: string | null = null;+ if (model && !engineError && !presetLoading) {+ try {+ const stand = (v: SlotValue | null | undefined, kind: MediaKind): SlotValue | null | undefined => (v?.uploading ? { ...v, ref: PLACEHOLDER[kind] } : v);+ const planSlots: Draft["slots"] = Object.fromEntries(Object.entries(draft.slots).map(([k, v]) => [k, stand(v, v?.kind ?? "image")]));+ for (const s of slots) if (s.required && !planSlots[s.key]?.ref) planSlots[s.key] = { ref: PLACEHOLDER[s.accept], preview: "", kind: s.accept };+ const { request: planned } = prepare({ ...draft, slots: planSlots, refs: draft.refs.map((r) => stand(r, r.kind) as SlotValue) });+ const plan = planGeneration({ ...planned, prompt: planned.prompt || (config.promptOptional ? " " : "") }, catalog.getModel, catalog.getPreset);+ op = plan.op;+ cost = estimateCost(plan.model, plan.params, plan.jobs);+ } catch (e) {+ planError = (e as Error).message;}- } catch (e) {- blocker = (e as Error).message;}+ const promptMissing =+ !config.promptOptional && preset?.userPrompt !== "none" && preset?.userPrompt !== "optional" && !draft.prompt.trim() && !draft.params.shots?.some((s) => s.prompt.trim());+ const blocker = blockerFor({+ loading: !catalog.ready ? "Loading models…" : presetLoading ? "Loading presets…" : null,+ model: !!model,+ engineError,+ missing,+ uploading,+ planError,+ promptMissing,+ });const submit = () => {if (blocker || create.isPending) {- if (blocker) toast(blocker);+ if (blocker) {+ toast(blocker.message);+ if (blocker.slot) pulseSlot(root.current, blocker.slot);+ }return;}+ setRecent((r) => pushRecent(r, draft.modelId));// The server resolves @mentions and drawings itself; only pin the operation when there are none.create.mutate(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind), {onSuccess: (items) => {@@ -423,26 +235,14 @@ export function Composer({ docked }: { docked: boolean }) {}};- // Paste images from the clipboard.+ // Paste images, clips or audio from the clipboard (text pastes as usual).const onPaste = (e: React.ClipboardEvent) => {- const file = [...e.clipboardData.files].find((f) => /^(image|video|audio)\//.test(f.type));- if (!file) return;+ const files = [...e.clipboardData.files].filter((f) => /^(image|video|audio)\//.test(f.type));+ if (!files.length) return;e.preventDefault();- const id = nanoid(6);- void fileToSlot(file, (v) => {- if (!v) return;- addImage({ ...v, id });- });+ attach.attachFiles(files);};- const slots = preset?.inputs ?? config.slots;- const opts = model?.options ?? {};- // Clips: ComfyUI joins 4 at a time. Images: what the model takes beyond the fixed image slots.- const refMax = !config.multiRef- ? 0- : config.multiRef.kind === "video"- ? Math.min(config.multiRef.max, model?.engine === "open" ? 4 : config.multiRef.max)- : Math.min(config.multiRef.max, Math.max(0, (opts.maxImages ?? 1) - slots.filter((s) => s.accept === "image").length));const p = draft.params;const setP = (patch: Partial<typeof p>) => setDraft((d) => ({ params: { ...d.params, ...patch } }));const setExtra = (key: string, v: unknown) =>@@ -454,48 +254,70 @@ export function Composer({ docked }: { docked: boolean }) {});const opNote = op && model ? routesFor(model, op)[0]?.note : undefined;const showPrompt = !config.hidePrompt && preset?.userPrompt !== "none";+ const effectiveOp = studioOp ?? op;+ const shape = settingsShape(model, effectiveOp, config.kind, showPrompt, p, config.ops);+ const demo = !!(model && status && status.demoMode !== "off" && !model.routes.some((r) => status.providers[r.provider]?.configured));+ const costText = costLabel({ demo, cost }, formatCost);++ // Attachments: only when something is attached or a required slot is still empty (U8).+ const kinds = [...attach.kinds];+ const hasAttachment = slots.some((s) => draft.slots[s.key]) || draft.refs.length > 0;+ const showAttachments = (slots.length > 0 || !!config.multiRef) && (hasAttachment || !!slots.find((s) => s.required && !draft.slots[s.key]));+ const collapsed = docked && !focused;return (<div+ ref={root}className={cn("group/composer w-full rounded-[20px] border bg-background p-2.5 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer",docked && "shadow-normal",)}onPaste={onPaste}+ onFocus={() => setFocused(true)}+ onBlur={(e) => {+ const to = e.relatedTarget as HTMLElement | null;+ // Moving into one of the composer's own popovers or sheets keeps it open.+ if (e.currentTarget.contains(to) || to?.closest("[data-radix-popper-content-wrapper],[role=dialog]")) return;+ setFocused(false);+ }}+ onKeyDown={(e) => {+ // ⌘/Ctrl+Enter generates from any field (shots, dialogue lines); the prompt handles Enter itself.+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && !e.defaultPrevented && !e.nativeEvent.isComposing) {+ e.preventDefault();+ submit();+ }+ }}>- {/* Attachments */}- {(slots.length > 0 || config.multiRef) && (- <div className="scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-1 pb-2">+ {showAttachments && (+ <div className="scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-1.5 pb-2">{slots.map((s) => (<MediaSlotkey={s.key}+ slotKey={s.key}label={s.label}kind={s.accept}required={s.required}value={draft.slots[s.key] ?? null}- onChange={(v) => {- setSlot(s.key, v);- // A drawing belongs to the image it was made on.- if (s.key === "image") setDraft((d) => ({ slots: { ...d.slots, mask: null, sketch: null } }));- }}+ onChange={(v) => attach.setSlotValue(s.key, v)}+ onFile={(f) => attach.uploadToSlot(s.key, f, s.accept)}/>))}{config.sketch && draft.slots.image?.ref && !draft.slots.image.uploading && (<SketchTools modes={config.sketch} image={draft.slots.image.ref} autoOpen={config.sketchAutoOpen} />)}{config.multiRef &&- draft.refs.map((r) => (+ draft.refs.map((r, i) => (<div key={r.id ?? r.ref} className="relative size-14 shrink-0 overflow-hidden rounded-xl border bg-muted"><SlotPreview value={r} />{r.uploading && (- <div className="absolute inset-0 grid place-items-center bg-background/60">+ <div className="absolute inset-0 grid place-items-center bg-background/60" role="status" aria-label="Uploading"><Loader2 className="size-4 animate-spin" /></div>)}<button- onClick={() => setDraft((d) => ({ refs: d.refs.filter((x) => x !== r) }))}+ onClick={() => attach.removeRef(r)}className="absolute top-0.5 right-0.5 grid size-5 place-items-center rounded-full bg-foreground/80 text-background"- aria-label="Remove reference"+ aria-label={`Remove ${config.multiRef?.kind === "video" ? "clip" : "reference"} ${i + 1}`}><X className="size-3" /></button>@@ -506,23 +328,13 @@ export function Composer({ docked }: { docked: boolean }) {label={config.multiRef.label}kind={config.multiRef.kind ?? "image"}value={null}- onFile={(f) => {- const id = nanoid(6);- void fileToSlot(f, (v) =>- setDraft((d) => {- if (!v) return { refs: d.refs.filter((r) => r.id !== id) };- const exists = d.refs.some((r) => r.id === id);- return { refs: exists ? d.refs.map((r) => (r.id === id ? { ...v, id } : r)) : [...d.refs, { ...v, id }] };- }),- );- }}- onChange={(v) => v && setDraft((d) => ({ refs: [...d.refs, { ...v, id: nanoid(6) }] }))}+ onFile={attach.addRefFile}+ onChange={(v) => v && setDraft((d) => ({ refs: [...d.refs, v] }))}/>)}</div>)}- {/* Prompt */}{showPrompt && (<PromptInputref={promptRef}@@ -531,15 +343,12 @@ export function Composer({ docked }: { docked: boolean }) {onSubmit={submit}placeholder={preset?.promptPlaceholder ?? config.placeholder}elements={elements}+ collapsed={collapsed}/>)}- {/* Dialogue script */}- {model && (studioOp ?? op) === "dialogue" && (- <DialogueEditor model={model} lines={p.dialogue ?? defaultLines(model)} onChange={(dialogue) => setP({ dialogue })} />- )}+ {model && effectiveOp === "dialogue" && <DialogueEditor model={model} lines={p.dialogue ?? defaultLines(model)} onChange={(dialogue) => setP({ dialogue })} />}- {/* Multi-shot */}{model?.options.multiShot && p.shots && <ShotsEditor model={model} shots={p.shots} onChange={(shots) => setP({ shots })} />}{/* @mentioned elements */}@@ -564,10 +373,7 @@ export function Composer({ docked }: { docked: boolean }) {</span></TooltipTrigger><TooltipContent>- {words ??- (el.loras.some((l) => l.modelId === model?.id)- ? `Uses ${el.name}'s trained LoRA on ${model?.name}`- : `${el.name}'s photos are sent as reference images`)}+ {words ?? (el.loras.some((l) => l.modelId === model?.id) ? `Uses ${el.name}'s trained LoRA on ${model?.name}` : `${el.name}'s photos are sent as reference images`)}</TooltipContent></Tooltip>);@@ -579,18 +385,17 @@ export function Composer({ docked }: { docked: boolean }) {{preset?.options?.length ? (<div className="flex flex-wrap gap-3 px-1.5 pb-2">{preset.options.map((o) => (- <div key={o.key} className="flex flex-wrap items-center gap-1">+ <div key={o.key} role="radiogroup" aria-label={o.label} className="flex flex-wrap items-center gap-1"><span className="mr-1 text-[12px] text-muted-foreground">{o.label}</span>{o.choices.map((c) => {const sel = (draft.presetOptions[o.key] ?? o.default ?? o.choices[0].value) === c.value;return (<buttonkey={c.value}+ role="radio"+ aria-checked={sel}onClick={() => setDraft((d) => ({ presetOptions: { ...d.presetOptions, [o.key]: c.value } }))}- className={cn(- "h-7 rounded-full border px-2.5 text-[12px] font-medium transition-colors",- sel ? "border-primary bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent",- )}+ className={cn("h-7 rounded-full border px-2.5 text-[12px] font-medium transition-colors", sel ? "border-primary bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent")}>{c.label}</button>@@ -601,22 +406,35 @@ export function Composer({ docked }: { docked: boolean }) {</div>) : null}- {/* Toolbar */}- <div className="flex items-end gap-2">- <div className="scrollbar-none flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto sm:flex-wrap sm:overflow-visible">+ {/* Toolbar: one row; it scrolls (with faded edges) when it doesn't fit. */}+ <div className="flex items-center gap-2">+ <div ref={chipRow} style={fade} className="scrollbar-none -my-1 flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto py-1">+ {kinds.length > 0 && <AttachMenu kinds={kinds} onFiles={attach.attachFiles} onPick={attach.attach} />}{!lockedModel ? (- <ModelPicker- models={models}- value={model}- engine={engine}- onEngineChange={setEngine}- onChange={(m) => {- setDraft((d) => ({ modelId: m.id, params: { ...m.defaults, numOutputs: d.params.numOutputs, enhancePrompt: d.params.enhancePrompt, seed: d.params.seed } }));- if (m.engine !== engine) setEngine(m.engine);- }}- />+ catalog.ready ? (+ <ModelPicker+ models={models}+ value={model}+ engine={engine}+ onEngineChange={setEngine}+ defaultModels={config.defaultModels}+ onChange={(m) => {+ setDraft((d) => ({ modelId: m.id, params: { ...m.defaults, numOutputs: d.params.numOutputs, enhancePrompt: d.params.enhancePrompt, seed: d.params.seed } }));+ if (m.engine !== engine) setEngine(m.engine);+ }}+ />+ ) : (+ <Chip icon={Loader2} disabled className="[&>svg]:animate-spin">+ Loading models…+ </Chip>+ )) : (- <Chip icon={Sparkles}>{model?.name}</Chip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Chip icon={Sparkles}>{model?.name ?? "…"}</Chip>+ </TooltipTrigger>+ <TooltipContent>{preset?.name} runs on {model?.name ?? "its own model"}</TooltipContent>+ </Tooltip>)}{showPrompt && (<Tooltip>@@ -624,7 +442,8 @@ export function Composer({ docked }: { docked: boolean }) {<buttontype="button"onClick={() => promptRef.current?.startMention()}- className="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors hover:bg-accent"+ // Phones: typing @ does the same, so the button gives its place to the settings chip.+ className="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 max-sm:order-last"aria-label="Add an element"><AtSign className="size-3.5" />@@ -633,44 +452,12 @@ export function Composer({ docked }: { docked: boolean }) {<TooltipContent>Add a character, location or prop · type @</TooltipContent></Tooltip>)}- {config.presetPicker && (- <PresetChip- type={config.presetPicker}- value={draft.presetId}- onChange={(id) => setDraft(id ? { presetId: id } : { presetId: undefined, mix: undefined, presetStrength: undefined })}- />- )}- {preset && (preset.type === "motion" || preset.type === "effect") && (- <MixChip primary={preset} strength={draft.presetStrength ?? 1} mix={draft.mix} onChange={(patch) => setDraft(patch)} />- )}- {opts.aspectRatios && opts.aspectRatios.length > 1 && op !== "i2v" && op !== "flf2v" && (- <AspectChip options={opts.aspectRatios} value={p.aspectRatio} onChange={(v) => setP({ aspectRatio: v })} />- )}- {opts.resolutions && opts.resolutions.length > 1 && (- <SegmentChip icon={Maximize} label="Quality" options={opts.resolutions} value={p.resolution} onChange={(v) => setP({ resolution: v })} />- )}- {opts.durations && opts.durations.length > 1 && !p.shots && (- <SegmentChip- icon={Clock}- label="Duration"- options={opts.durations}- value={p.duration}- onChange={(v) => setP({ duration: v })}- format={(v) => (v >= 1000 ? `${Math.round(v / 1000)}s` : `${v}s`)}- />- )}- {config.kind === "image" && (- <SegmentChip icon={CopyIcon} label="Images" options={[1, 2, 3, 4]} value={p.numOutputs ?? 1} onChange={(v) => setP({ numOutputs: v })} format={(v) => `×${v}`} />- )}- {config.kind === "video" && !SINGLE_TAKE.has((studioOp ?? op)!) && (- <SegmentChip icon={CopyIcon} label="Videos" options={[1, 2, 3, 4]} value={p.numOutputs ?? 1} onChange={(v) => setP({ numOutputs: v })} format={(v) => `×${v}`} />- )}- {model && (opts.voices?.length || opts.voiceClone) && (studioOp ?? op) !== "dialogue" && (+ {model && (opts.voices?.length || opts.voiceClone) && effectiveOp !== "dialogue" && (<VoicePickermodel={model}voice={p.voice}sample={draft.slots.voiceAudio}- label={(studioOp ?? op) === "voice-change" ? "New voice" : "Voice"}+ label={effectiveOp === "voice-change" ? "New voice" : "Voice"}onChange={(c) => {if (c?.kind === "preset") setDraft((d) => ({ params: { ...d.params, voice: c.id }, slots: { ...d.slots, voiceAudio: null } }));if (c?.kind === "sample") setSlot("voiceAudio", c.value);@@ -678,7 +465,9 @@ export function Composer({ docked }: { docked: boolean }) {/>)}{/* Open-source dialogue clones each speaker from a sample. */}- {model && opts.voiceClone && (studioOp ?? op) === "dialogue" &&+ {model &&+ opts.voiceClone &&+ effectiveOp === "dialogue" &&(["voiceAudio", "voiceAudio2"] as const).map((key, i) => (<VoicePickerkey={key}@@ -689,130 +478,66 @@ export function Composer({ docked }: { docked: boolean }) {/>))}{model && opts.languages && (- <LanguageChip- languages={opts.languages}- value={p.targetLanguage}- label={(studioOp ?? op) === "dub" ? "Translate to…" : "Language"}- onChange={(targetLanguage) => setP({ targetLanguage })}- />- )}- {model && opts.sliders && <SlidersChip model={model} values={p.extra ?? {}} onChange={setExtra} />}- {opts.multiShot && model && <MultiShotChip model={model} params={p} onChange={setP} />}- {opts.draft && (- <Tooltip>- <TooltipTrigger asChild>- <Chip icon={FileVideo2} active={!!p.draft} onClick={() => setP({ draft: !p.draft })}>- Draft- </Chip>- </TooltipTrigger>- <TooltipContent>{p.draft ? "Cheap 480p take — finish the one you like in 1080p" : "Draft mode: preview at 480p first, then render the keeper in 1080p"}</TooltipContent>- </Tooltip>+ <LanguageChip languages={opts.languages} value={p.targetLanguage} label={effectiveOp === "dub" ? "Translate to…" : "Language"} onChange={(targetLanguage) => setP({ targetLanguage })} />)}- {opts.presets && (- <ProviderPresetChip- spec={opts.presets}- value={p.extra?.[opts.presets.param] as string | undefined}- onChange={(id) => setExtra(opts.presets!.param, id)}+ <SettingsChip+ model={model}+ op={op}+ shape={shape}+ params={p}+ setP={setP}+ setExtra={setExtra}+ negativePrompt={draft.negativePrompt}+ setNegativePrompt={(negativePrompt) => setDraft({ negativePrompt })}+ kind={config.kind}+ enhancing={enhancing}+ onRewrite={runEnhance}+ opNote={opNote}+ />+ {(config.presetPicker || (preset && (preset.type === "motion" || preset.type === "effect"))) && (+ <PresetChips+ picker={config.presetPicker}+ preset={preset}+ presetId={draft.presetId}+ strength={draft.presetStrength ?? 1}+ mix={draft.mix}+ onPreset={(id) => setDraft(id ? { presetId: id } : { presetId: undefined, mix: undefined, presetStrength: undefined })}+ onMix={(patch) => setDraft(patch)}/>)}+ {opts.presets && <ProviderPresetChip spec={opts.presets} value={p.extra?.[opts.presets.param] as string | undefined} onChange={(id) => setExtra(opts.presets!.param, id)} />}{opts.controls && <ControlsChip controls={opts.controls} values={p.extra ?? {}} onChange={setExtra} />}- {opts.audio === true && (- <Tooltip>- <TooltipTrigger asChild>- <Chip icon={p.generateAudio === false ? VolumeX : Volume2} active={p.generateAudio !== false} onClick={() => setP({ generateAudio: p.generateAudio === false })}>- Audio- </Chip>- </TooltipTrigger>- <TooltipContent>{p.generateAudio === false ? "Silent video (cheaper)" : "Native sound, music and dialogue"}</TooltipContent>- </Tooltip>- )}- {showPrompt && (- <Tooltip>- <TooltipTrigger asChild>- <Chip icon={enhancing ? Loader2 : Sparkles} active={!!p.enhancePrompt} onClick={() => setP({ enhancePrompt: !p.enhancePrompt })} onDoubleClick={runEnhance} className={enhancing ? "[&>svg]:animate-spin" : undefined}>- Enhance- </Chip>- </TooltipTrigger>- <TooltipContent>Rewrite the prompt with an LLM before generating · double-click to rewrite now</TooltipContent>- </Tooltip>- )}- <Popover>- <PopoverTrigger asChild>- <button className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" aria-label="Advanced settings">- <Settings2 className="size-4" />- </button>- </PopoverTrigger>- <PopoverContent className="w-80 space-y-3" align="start" side="top">- <p className="text-[13px] font-medium">Advanced</p>- <div className="space-y-1.5">- <div className="flex items-center justify-between text-[12px] text-muted-foreground">- <span>Seed</span>- <span className="flex items-center gap-2">- Random- <Switch checked={p.seed === undefined} onCheckedChange={(r) => setP({ seed: r ? undefined : Math.floor(Math.random() * 1e9) })} />- </span>- </div>- {p.seed !== undefined && (- <div className="flex gap-1.5">- <input- type="number"- value={p.seed}- onChange={(e) => setP({ seed: Number(e.target.value) })}- className="h-8 flex-1 rounded-md border bg-background px-2 font-mono text-sm outline-none focus:border-primary"- />- <Button variant="secondary" size="icon" className="size-8" onClick={() => setP({ seed: Math.floor(Math.random() * 1e9) })}>- <Shuffle className="size-3.5" />- </Button>- </div>- )}- </div>- {opts.negativePrompt && (- <div className="space-y-1.5">- <span className="text-[12px] text-muted-foreground">Negative prompt</span>- <textarea- value={draft.negativePrompt}- onChange={(e) => setDraft({ negativePrompt: e.target.value })}- rows={3}- placeholder="blurry, low quality, extra fingers…"- className="w-full resize-none rounded-md border bg-background px-2 py-1.5 text-sm outline-none focus:border-primary"- />- </div>- )}- {model && (- <p className="text-[11px] leading-relaxed text-muted-foreground">- {model.name} via {model.engine === "open" ? "ComfyUI" : [...new Set(model.routes.map((r) => r.provider))].join(" / ")}- {op ? ` · ${OPERATION_LABELS[op]}` : ""}- {opNote ? ` · ${opNote}` : ""}- </p>- )}- </PopoverContent>- </Popover></div>- <span className="hidden shrink-0 font-mono text-[12px] text-muted-foreground sm:inline">- {model && status && status.demoMode !== "off" && !model.routes.some((r) => status.providers[r.provider]?.configured)- ? "Demo · free"- : cost === 0- ? "Free"- : cost != null- ? `≈ ${formatCost(cost)}`- : ""}- </span>+ {costText && (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums">+ <span className="sm:hidden">{costLabel({ demo, cost, compact: true }, formatCost)}</span>+ <span className="hidden sm:inline">{costText}</span>+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {demo ? "Demo mode: no key connected for this model, so outputs are free placeholders" : cost === 0 ? "Runs on your own GPU" : "Estimated cost, billed by the provider to your key"}+ </TooltipContent>+ </Tooltip>+ )}<Tooltip><TooltipTrigger asChild><Buttonsize="icon"onClick={submit}disabled={create.isPending}- aria-label="Generate"+ aria-label={blocker ? `Generate — ${blocker.message}` : "Generate"}className={cn("size-10 shrink-0 rounded-full", blocker && "bg-muted text-subtle-foreground hover:bg-muted")}>{create.isPending ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}</Button></TooltipTrigger><TooltipContent>- {blocker ?? (+ {blocker?.message ?? (<span className="flex items-center gap-1.5">Generate <Kbd>↵</Kbd>+ {costText && <span className="text-muted-foreground tabular-nums">· {costText}</span>}</span>)}</TooltipContent>diff --git a/src/components/studio/engine-switch.tsx b/src/components/studio/engine-switch.tsxindex cd0ccd72..16d7c298 100644--- a/src/components/studio/engine-switch.tsx+++ b/src/components/studio/engine-switch.tsx@@ -12,7 +12,11 @@ const OPTIONS: { value: Engine; label: string; icon: typeof Cloud; tip: string }{ value: "open", label: "Open source", icon: Cpu, tip: "Open-weight models running on your ComfyUI server" },];-/** Segmented control with a sliding white thumb (Liner-style). */+/**+ * Segmented control with a sliding white thumb (Liner-style). `md` (page headers) turns+ * icon-only below the sm breakpoint so titles keep their line on phones; the tooltips and+ * aria labels still name each engine.+ */export function EngineSwitch({value,onChange,@@ -24,24 +28,27 @@ export function EngineSwitch({}) {const mode = useEngineMode();const idx = OPTIONS.findIndex((o) => o.value === value);+ const compact = size === "md";if (mode !== "both") {const o = OPTIONS.find((x) => x.value === mode)!;+ const text = mode === "open" ? "Open source only" : "Cloud only";return (<Tooltip><TooltipTrigger asChild><Linkhref="/settings"+ aria-label={`${text} — change in Settings`}className={cn(- "inline-flex items-center gap-1.5 rounded-full bg-muted px-3 text-[13px] font-medium text-muted-foreground transition-colors hover:text-foreground",- size === "sm" ? "h-8" : "h-9",+ "inline-flex shrink-0 items-center gap-1.5 rounded-full bg-muted px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground",+ size === "sm" ? "h-8" : "h-8 sm:h-9",)}><o.icon className="size-3.5" />- {mode === "open" ? "Open source only" : "Cloud only"}+ <span className={cn(compact && "hidden sm:inline")}>{text}</span><Lock className="size-3 opacity-60" /></Link></TooltipTrigger>- <TooltipContent>Locked in Settings → Engine mode</TooltipContent>+ <TooltipContent>{text} · locked in Settings → Engine mode</TooltipContent></Tooltip>);}@@ -49,7 +56,7 @@ export function EngineSwitch({<divrole="radiogroup"aria-label="Engine"- className={cn("relative inline-grid grid-cols-2 rounded-full bg-muted p-0.5", size === "sm" ? "h-8" : "h-9")}+ className={cn("relative inline-grid shrink-0 grid-cols-2 rounded-full bg-muted p-0.5", size === "sm" ? "h-8" : "h-8 sm:h-9")}><spanaria-hidden@@ -62,17 +69,21 @@ export function EngineSwitch({<buttonrole="radio"aria-checked={value === o.value}+ aria-label={o.label}onClick={() => onChange(o.value)}className={cn(- "relative z-10 flex items-center justify-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors",+ "relative z-10 flex items-center justify-center gap-1.5 rounded-full text-[13px] font-medium whitespace-nowrap transition-colors",+ compact ? "w-9 sm:w-auto sm:px-3" : "px-3",value === o.value ? "text-foreground" : "text-muted-foreground hover:text-foreground",)}><o.icon className="size-3.5" />- {size === "sm" && o.value === "open" ? "Open" : o.label}+ <span className={cn(compact && "hidden sm:inline")}>{size === "sm" && o.value === "open" ? "Open" : o.label}</span></button></TooltipTrigger>- <TooltipContent>{o.tip}</TooltipContent>+ <TooltipContent>+ <span className="font-medium">{o.label}</span> · {o.tip}+ </TooltipContent></Tooltip>))}</div>diff --git a/src/components/studio/mode-studio.tsx b/src/components/studio/mode-studio.tsxnew file mode 100644index 00000000..37bba767--- /dev/null+++ b/src/components/studio/mode-studio.tsx@@ -0,0 +1,72 @@+"use client";++import Link from "next/link";+import { useSearchParams } from "next/navigation";+import { Suspense, useEffect, useRef } from "react";+import type { StudioCatalog } from "@/lib/studio-catalog";+import { cn } from "@/lib/utils";+import { StudioPage } from "./studio-page";+import type { StudioConfig } from "./studio-context";+import { useEdgeFade } from "./use-edge-fade";++export interface Mode {+ id: string;+ label: string;+ config: StudioConfig;+ catalog: StudioCatalog;+}++/** Underline tabs on their own row under the page title; they scroll sideways (with faded edges) on phones. */+function ModeTabs({ modes, current }: { modes: Mode[]; current: string }) {+ const [ref, fade] = useEdgeFade<HTMLDivElement>();+ const active = useRef<HTMLAnchorElement>(null);+ // Keep the selected tab in view when the row scrolls.+ useEffect(() => {+ active.current?.scrollIntoView({ block: "nearest", inline: "nearest" });+ }, [current]);+ return (+ <nav aria-label="Modes" className="border-b">+ <div ref={ref} style={fade} className="scrollbar-none flex gap-1 overflow-x-auto px-3 sm:px-6">+ {modes.map((m) => {+ const on = m.id === current;+ return (+ <Link+ key={m.id}+ ref={on ? active : undefined}+ href={`?mode=${m.id}`}+ replace+ scroll={false}+ aria-current={on ? "page" : undefined}+ className={cn(+ "relative flex h-10 shrink-0 items-center px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:text-foreground",+ "after:absolute after:inset-x-2.5 after:bottom-0 after:h-0.5 after:rounded-full after:transition-colors focus-visible:after:bg-ring",+ on && "text-foreground after:bg-foreground",+ )}+ >+ {m.label}+ </Link>+ );+ })}+ </div>+ </nav>+ );+}++function Pick({ modes, current }: { modes: Mode[]; current: Mode }) {+ return <StudioPage key={current.id} config={current.config} catalog={current.catalog} tabs={<ModeTabs modes={modes} current={current.id} />} />;+}++function FromUrl({ modes }: { modes: Mode[] }) {+ const sp = useSearchParams();+ const current = modes.find((m) => m.id === sp.get("mode")) ?? (sp.get("video") ? modes.find((m) => m.id === "video") : undefined) ?? modes[0];+ return <Pick modes={modes} current={current} />;+}++/** Studios switched by `?mode=`; the prerendered shell shows the first mode. */+export function ModeStudio({ modes }: { modes: Mode[] }) {+ return (+ <Suspense fallback={<Pick modes={modes} current={modes[0]} />}>+ <FromUrl modes={modes} />+ </Suspense>+ );+}diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsxindex 2f716feb..512c041a 100644--- a/src/components/studio/mode-switch-studio.tsx+++ b/src/components/studio/mode-switch-studio.tsx@@ -1,7 +1,3 @@-"use client";--import { useRouter, useSearchParams } from "next/navigation";-import { Suspense } from "react";import {AUDIO_STUDIO,DIALOGUE_STUDIO,@@ -18,8 +14,8 @@ import {VIDEO_UPSCALE_STUDIO,VOICE_CHANGE_STUDIO,} from "@/lib/studios";-import { cn } from "@/lib/utils";-import { StudioPage } from "./studio-page";+import { studioCatalog } from "@/lib/studio-catalog";+import { ModeStudio, type Mode } from "./mode-studio";const MODES = {upscale: [@@ -44,34 +40,11 @@ const MODES = {],} as const;-function Inner({ kind }: { kind: keyof typeof MODES }) {- const sp = useSearchParams();- const router = useRouter();- const modes = MODES[kind];- const current = modes.find((m) => m.id === sp.get("mode")) ?? (sp.get("video") ? modes.find((m) => m.id === "video") : undefined) ?? modes[0];- const tabs = (- <div className="scrollbar-none inline-flex h-9 max-w-[52vw] items-center overflow-x-auto rounded-full bg-muted p-0.5 lg:max-w-none">- {modes.map((m) => (- <button- key={m.id}- onClick={() => router.replace(`?mode=${m.id}`)}- className={cn(- "h-8 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition",- current.id === m.id && "bg-background text-foreground shadow-soft",- )}- >- {m.label}- </button>- ))}- </div>- );- return <StudioPage key={current.id} config={current.config} header={tabs} />;-}-+/**+ * A hub of studios switched by `?mode=` (Audio, Video tools, Upscale). Server component: each+ * mode's models are picked here, so the page ships only those.+ */export function ModeSwitchStudio({ kind }: { kind: keyof typeof MODES }) {- return (- <Suspense fallback={null}>- <Inner kind={kind} />- </Suspense>- );+ const modes: Mode[] = MODES[kind].map((m) => ({ id: m.id, label: m.label, config: m.config, catalog: studioCatalog(m.config) }));+ return <ModeStudio modes={modes} />;}diff --git a/src/components/studio/model-controls.tsx b/src/components/studio/model-controls.tsxindex cb1e3d3c..c6174ecf 100644--- a/src/components/studio/model-controls.tsx+++ b/src/components/studio/model-controls.tsx@@ -1,12 +1,13 @@"use client";import { useQuery } from "@tanstack/react-query";-import { Check, Clapperboard, Loader2, Palette, X } from "lucide-react";+import { Ban, Check, Clapperboard, Loader2, Palette } from "lucide-react";import { useMemo, useState } from "react";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import type { ModelOptions } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { Chip, ClearableChip } from "./chip";interface ProviderPreset {id: string;@@ -15,10 +16,6 @@ interface ProviderPreset {group?: string;}-const chip =- "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors bg-secondary text-secondary-foreground hover:bg-accent";-const active = "bg-brand-faint text-brand-text hover:bg-brand-faint-hover";-const label = (v: string | number) =>String(v).replace(/[-_]/g, " ")@@ -46,59 +43,66 @@ export function ProviderPresetChip({const items = useMemo(() => (list.data?.items ?? []).filter((p) => !q || p.name.toLowerCase().includes(q.toLowerCase())), [list.data, q]);const selected = list.data?.items.find((p) => p.id === value);return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <button type="button" className={cn(chip, value && active)}>- <Palette className="size-3.5" />- {selected?.name ?? (value ? spec.label : `${spec.label}${spec.required ? "" : ": default"}`)}- {value && !spec.required && (- <X- className="-mr-1 size-3.5 opacity-70 hover:opacity-100"- onClick={(e) => {- e.stopPropagation();- onChange(undefined);- }}- />+ <ClearableChip active={!!value && !spec.required} onClear={() => onChange(undefined)} clearLabel={`Clear ${spec.label.toLowerCase()}`}>+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Chip icon={Palette} active={!!value}>+ {selected?.name ?? (value ? spec.label : `${spec.label}${spec.required ? "" : ": default"}`)}+ </Chip>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,460px)] p-2" align="start" side="top" collisionPadding={12}>+ <input+ value={q}+ onChange={(e) => setQ(e.target.value)}+ placeholder={`Search ${spec.label.toLowerCase()}s`}+ aria-label={`Search ${spec.label.toLowerCase()}s`}+ className="mb-2 h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:border-primary"+ />+ {list.isLoading ? (+ <div className="grid h-40 place-items-center">+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ </div>+ ) : list.data?.error && !items.length ? (+ <p className="px-1 py-8 text-center text-[13px] text-muted-foreground">{list.data.error}</p>+ ) : (+ <div className="grid max-h-80 grid-cols-3 gap-1.5 overflow-y-auto">+ {!spec.required && !q && (+ <button+ onClick={() => {+ onChange(undefined);+ setOpen(false);+ }}+ className={cn("group flex flex-col gap-1 rounded-lg p-1 text-left ring-primary transition hover:bg-accent", !value && "ring-2")}+ >+ <span className="grid aspect-[3/4] w-full place-items-center rounded-md bg-muted text-muted-foreground">+ <Ban className="size-5" />+ </span>+ <span className="truncate px-0.5 text-[12px] font-medium">Default</span>+ </button>+ )}+ {items.map((p) => (+ <button+ key={p.id}+ onClick={() => {+ onChange(p.id, p.name);+ setOpen(false);+ }}+ className={cn("group flex flex-col gap-1 rounded-lg p-1 text-left ring-primary transition hover:bg-accent", value === p.id && "ring-2")}+ >+ <span className="aspect-[3/4] w-full overflow-hidden rounded-md bg-muted">+ {p.preview && (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={p.preview} alt="" loading="lazy" className="size-full object-cover transition-transform duration-300 group-hover:scale-105" />+ )}+ </span>+ <span className="truncate px-0.5 text-[12px] font-medium">{p.name}</span>+ </button>+ ))}+ </div>)}- </button>- </PopoverTrigger>- <PopoverContent className="w-[min(92vw,460px)] p-2" align="start" side="top" collisionPadding={12}>- <input- value={q}- onChange={(e) => setQ(e.target.value)}- placeholder={`Search ${spec.label.toLowerCase()}s`}- className="mb-2 h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:border-primary"- />- {list.isLoading ? (- <div className="grid h-40 place-items-center">- <Loader2 className="size-4 animate-spin text-muted-foreground" />- </div>- ) : list.data?.error && !items.length ? (- <p className="px-1 py-8 text-center text-[13px] text-muted-foreground">{list.data.error}</p>- ) : (- <div className="grid max-h-80 grid-cols-3 gap-1.5 overflow-y-auto">- {items.map((p) => (- <button- key={p.id}- onClick={() => {- onChange(p.id, p.name);- setOpen(false);- }}- className={cn("group flex flex-col gap-1 rounded-lg p-1 text-left ring-primary transition hover:bg-accent", value === p.id && "ring-2")}- >- <span className="aspect-[3/4] w-full overflow-hidden rounded-md bg-muted">- {p.preview && (- // eslint-disable-next-line @next/next/no-img-element- <img src={p.preview} alt="" loading="lazy" className="size-full object-cover transition-transform duration-300 group-hover:scale-105" />- )}- </span>- <span className="truncate px-0.5 text-[12px] font-medium">{p.name}</span>- </button>- ))}- </div>- )}- </PopoverContent>- </Popover>+ </PopoverContent>+ </Popover>+ </ClearableChip>);}@@ -116,10 +120,9 @@ export function ControlsChip({return (<Popover><PopoverTrigger asChild>- <button type="button" className={cn(chip, set.length > 0 && active)}>- <Clapperboard className="size-3.5" />+ <Chip icon={Clapperboard} active={set.length > 0}>{set.length ? `Director · ${set.length}` : "Director"}- </button>+ </Chip></PopoverTrigger><PopoverContent className="w-[min(92vw,420px)] space-y-2 p-3" align="start" side="top" collisionPadding={12}><p className="text-[13px] font-medium">Director controls</p>@@ -129,7 +132,7 @@ export function ControlsChip({<label key={c.param} className="space-y-1"><span className="text-[12px] text-muted-foreground">{c.label}</span><Select value={values[c.param] === undefined ? "__auto" : String(values[c.param])} onValueChange={(v) => onChange(c.param, v === "__auto" ? undefined : typeof c.values[0] === "number" ? Number(v) : v)}>- <SelectTrigger size="sm" className="w-full">+ <SelectTrigger size="sm" className="w-full" aria-label={c.label}><SelectValue /></SelectTrigger><SelectContent className="max-h-72">@@ -145,7 +148,7 @@ export function ControlsChip({))}</div>{set.length > 0 && (- <button onClick={() => set.forEach((c) => onChange(c.param, undefined))} className="inline-flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground">+ <button onClick={() => set.forEach((c) => onChange(c.param, undefined))} className="inline-flex items-center gap-1 rounded text-[12px] text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"><Check className="size-3" /> Reset to Auto</button>)}diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsxindex 376b4049..1e96c638 100644--- a/src/components/studio/model-picker.tsx+++ b/src/components/studio/model-picker.tsx@@ -1,16 +1,20 @@"use client";-import { Check, ChevronDown, Cloud, Cpu, Search } from "lucide-react";+import { ChevronDown, Cloud, Cpu, SearchX, Star } from "lucide-react";+import Link from "next/link";import { useMemo, useState } from "react";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";-import { ScrollArea } from "@/components/ui/scroll-area";-import { OPERATION_LABELS, type Engine, type ModelDef } from "@/lib/catalog/types";-import { useStatus } from "@/lib/api";+import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";+import { type Engine, type ModelDef } from "@/lib/catalog/types";+import { useEngineMode, useStatus } from "@/lib/api";+import { bestForStudio, groupModels, toggleIn } from "@/lib/composer";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";import { EngineSwitch } from "./engine-switch";+import { ResponsivePanel } from "./responsive-panel";+import { RECENT_MODELS, STARRED_MODELS, useStoredList } from "./stored-list";+import { VendorMark } from "./vendor-mark";const BADGE_LABEL: Record<string, string> = {new: "New",@@ -25,130 +29,207 @@ const BADGE_LABEL: Record<string, string> = {beta: "Beta",};-export function ModelBadges({ model }: { model: ModelDef }) {+export function ModelBadges({ model, max }: { model: ModelDef; max?: number }) {+ const badges = (model.badges ?? []).filter((b) => b !== "open").slice(0, max);+ if (!badges.length) return null;return (- <span className="flex flex-wrap gap-1">- {(model.badges ?? [])- .filter((b) => b !== "open")- .map((b) => (- <Badge- key={b}- variant="secondary"- className={cn(- "h-4 rounded-[4px] px-1 text-[10px] font-medium",- b === "new" && "bg-highlight text-highlight-foreground",- b === "top" && "bg-brand-faint text-brand-text",- )}- >- {BADGE_LABEL[b]}- </Badge>- ))}+ <span className="flex shrink-0 flex-wrap gap-1">+ {badges.map((b) => (+ <Badge+ key={b}+ variant="secondary"+ className={cn(+ "h-4 rounded-[4px] px-1 text-[10px] font-medium",+ b === "new" && "bg-highlight text-highlight-foreground",+ b === "top" && "bg-brand-faint text-brand-text",+ )}+ >+ {BADGE_LABEL[b]}+ </Badge>+ ))}</span>);}function priceHint(m: ModelDef): string {- if (m.engine === "open") return "Free · your GPU";+ if (m.engine === "open") return "Free";if (!m.pricing) return "";const unit = { image: "/image", second: "/sec", video: "/video", request: "/run", megapixel: "/MP", minute: "/min" }[m.pricing.unit];return `${formatCost(m.pricing.usd)}${unit}`;}+function ModelRow({+ m,+ selected,+ starred,+ showEngine,+ onStar,+}: {+ m: ModelDef;+ selected: boolean;+ starred: boolean;+ showEngine: boolean;+ onStar: () => void;+}) {+ return (+ <>+ <VendorMark vendor={m.vendor} engine={m.engine} />+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-1.5">+ <span className={cn("truncate text-[13px] font-medium", selected && "text-brand-text")}>{m.name}</span>+ <ModelBadges model={m} max={2} />+ {showEngine && (+ <span className="inline-flex shrink-0 items-center gap-0.5 rounded-[4px] bg-muted px-1 text-[10px] leading-4 font-medium text-muted-foreground">+ {m.engine === "open" ? <Cpu className="size-2.5!" /> : <Cloud className="size-2.5!" />}+ {m.engine === "open" ? "Open" : "Cloud"}+ </span>+ )}+ </span>+ <span className="block truncate text-[12px] leading-snug text-muted-foreground">+ {m.vendor} · {m.tagline}+ </span>+ </span>+ <span className="shrink-0 text-right text-[11px] text-subtle-foreground tabular-nums">{priceHint(m)}</span>+ <button+ type="button"+ onPointerDown={(e) => e.preventDefault()}+ onClick={(e) => {+ e.stopPropagation();+ onStar();+ }}+ aria-label={starred ? `Unstar ${m.name}` : `Star ${m.name}`}+ aria-pressed={starred}+ className={cn(+ "grid size-7 shrink-0 place-items-center rounded-full text-subtle-foreground transition hover:bg-accent hover:text-foreground focus-visible:opacity-100",+ starred ? "text-highlight-foreground" : "opacity-100 sm:opacity-0 sm:group-hover/command-item:opacity-100 sm:group-data-selected/command-item:opacity-100",+ )}+ >+ <Star className={cn("size-3.5!", starred && "fill-highlight text-highlight-foreground")} />+ </button>+ </>+ );+}++/**+ * Model picker on cmdk: Recent, Starred and "Best for this studio" above the full list for the+ * current engine; typing searches both engines at once (each row says which). A popover on+ * desktop, a bottom sheet on phones.+ */export function ModelPicker({models,value,onChange,engine,onEngineChange,+ defaultModels,}: {models: ModelDef[];value: ModelDef | undefined;onChange: (m: ModelDef) => void;engine: Engine;onEngineChange: (e: Engine) => void;+ defaultModels?: { cloud: string; open: string };}) {const [open, setOpen] = useState(false);const [q, setQ] = useState("");const status = useStatus().data;- const visible = useMemo(- () =>- models.filter(- (m) =>- m.engine === engine &&- (!q || `${m.name} ${m.vendor} ${m.tagline}`.toLowerCase().includes(q.toLowerCase())),- ),- [models, engine, q],- );- const providerReady = (m: ModelDef) =>- m.routes.some((r) => status?.providers[r.provider]?.configured);+ const mode = useEngineMode();+ const [recent] = useStoredList(RECENT_MODELS);+ const [starred, setStarred] = useStoredList(STARRED_MODELS);+ const engines = useMemo<Engine[]>(() => (mode === "both" ? ["cloud", "open"] : [mode]), [mode]);+ const best = useMemo(() => bestForStudio(models, engine, defaultModels?.[engine]).map((m) => m.id), [models, engine, defaultModels]);+ const { groups, count } = useMemo(() => groupModels({ models, engine, engines, query: q, recent, starred, best }), [models, engine, engines, q, recent, starred, best]);+ const ready = (m: ModelDef) => m.routes.some((r) => status?.providers[r.provider]?.configured);+ const shown = groups.flatMap((g) => g.models);+ const demo = status && status.demoMode !== "off" && shown.some((m) => !ready(m));+ const otherEngine = engine === "cloud" ? "open" : "cloud";+ const noneForEngine = !q && !models.some((m) => m.engine === engine);++ const pick = (m: ModelDef) => {+ onChange(m);+ setOpen(false);+ setQ("");+ };return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <Button variant="secondary" size="sm" className="h-8 gap-1.5 rounded-full px-3 text-[13px] font-medium">+ <ResponsivePanel+ open={open}+ onOpenChange={(o) => {+ setOpen(o);+ if (!o) setQ("");+ }}+ title="Choose a model"+ className="w-[min(92vw,440px)] p-0 shadow-strong"+ sheetClassName="h-[80svh]"+ trigger={+ <Button variant="secondary" size="sm" className="h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label={`Model: ${value?.name ?? "none"}. Change model`}>{value?.engine === "open" ? <Cpu className="size-3.5" /> : <Cloud className="size-3.5" />}- <span className="max-w-40 truncate">{value?.name ?? "Choose model"}</span>+ <span className="max-w-32 truncate sm:max-w-44">{value?.name ?? "Choose model"}</span><ChevronDown className="size-3.5 opacity-60" /></Button>- </PopoverTrigger>- <PopoverContent align="start" side="top" collisionPadding={12} className="w-[min(92vw,420px)] p-0 shadow-strong">- <div className="flex items-center gap-2 border-b p-2">- <div className="relative flex-1">- <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />- <input- autoFocus- value={q}- onChange={(e) => setQ(e.target.value)}- placeholder="Search models"- className="h-8 w-full rounded-md bg-muted pr-2 pl-8 text-sm outline-none placeholder:text-subtle-foreground"- />+ }+ >+ <Command shouldFilter={false} loop label="Models" className="rounded-none! bg-transparent p-0">+ <div className="flex items-center gap-2 p-1 sm:p-2 sm:pb-1">+ <div className="min-w-0 flex-1 [&_[data-slot=command-input-wrapper]]:p-0">+ <CommandInput value={q} onValueChange={setQ} placeholder={mode === "both" ? "Search all models" : "Search models"} aria-label="Search models" autoFocus /></div><EngineSwitch value={engine} onChange={onEngineChange} size="sm" /></div>- <ScrollArea className="h-[min(56vh,440px)]">- <div className="p-1">- {visible.length === 0 && (- <p className="px-3 py-8 text-center text-sm text-muted-foreground">- No {engine === "open" ? "open-source" : "cloud"} models for this yet.- </p>- )}- {visible.map((m) => {- const ready = providerReady(m);- return (- <button- key={m.id}- onClick={() => {- onChange(m);- setOpen(false);- }}- className={cn(- "flex w-full items-start gap-3 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-accent",- value?.id === m.id && "bg-brand-faint",- )}+ <div className="flex items-baseline gap-x-2 px-3 pb-1.5 leading-snug text-[11px] text-muted-foreground sm:px-3.5">+ <span className="shrink-0 whitespace-nowrap tabular-nums">{q ? `${count} result${count === 1 ? "" : "s"}` : `${count} ${engine === "open" ? "open-source" : "cloud"} model${count === 1 ? "" : "s"}`}</span>+ {demo && (+ <>+ <span aria-hidden>·</span>+ <span className="min-w-0">+ Demo — no key connected, outputs are placeholders.{" "}+ <Link href="/settings" className="text-brand-text hover:underline">+ Connect+ </Link>+ </span>+ </>+ )}+ </div>+ <CommandList className="max-h-[min(52vh,420px)] border-t sm:max-h-[min(56vh,440px)]">+ {groups.map((g) => (+ <CommandGroup key={g.id} heading={g.label}>+ {g.models.map((m) => (+ <CommandItem+ key={`${g.id}:${m.id}`}+ value={`${g.id}:${m.id}`}+ onSelect={() => pick(m)}+ data-checked={value?.id === m.id}+ className={cn("gap-2.5 rounded-lg px-2 py-1.5 [&>svg:last-child]:hidden", value?.id === m.id && "bg-brand-faint data-selected:bg-brand-faint-hover")}>- <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-md bg-muted text-[11px] font-semibold text-muted-foreground uppercase">- {m.vendor.slice(0, 2)}- </span>- <span className="min-w-0 flex-1">- <span className="flex items-center gap-1.5">- <span className="truncate text-sm font-medium">{m.name}</span>- <ModelBadges model={m} />- </span>- <span className="line-clamp-2 text-[12px] leading-snug text-muted-foreground">{m.tagline}</span>- <span className="mt-1 flex items-center gap-2 text-[11px] text-subtle-foreground">- <span className="font-mono">{priceHint(m)}</span>- <span>·</span>- <span className="truncate">{[...new Set(m.routes.map((r) => OPERATION_LABELS[r.op]))].join(", ")}</span>- {status && !ready && <span className="ml-auto shrink-0 text-warning">demo</span>}- </span>- </span>- {value?.id === m.id && <Check className="mt-1 size-4 text-brand-text" />}- </button>- );- })}- </div>- </ScrollArea>- </PopoverContent>- </Popover>+ <ModelRow m={m} selected={value?.id === m.id} starred={starred.includes(m.id)} showEngine={!!q || m.engine !== engine} onStar={() => setStarred((s) => toggleIn(s, m.id))} />+ </CommandItem>+ ))}+ </CommandGroup>+ ))}+ {!groups.length && (+ <div className="flex flex-col items-center gap-2 px-4 py-10 text-center">+ <SearchX className="size-5 text-subtle-foreground" />+ {noneForEngine ? (+ <>+ <p className="text-[13px] text-muted-foreground">No {engine === "open" ? "open-source" : "cloud"} models for this yet.</p>+ {engines.includes(otherEngine) && (+ <Button variant="secondary" size="sm" onClick={() => onEngineChange(otherEngine)}>+ Show {otherEngine === "open" ? "open-source" : "cloud"} models+ </Button>+ )}+ </>+ ) : (+ <>+ <p className="text-[13px] text-muted-foreground">No models match “{q}”</p>+ <Button variant="secondary" size="sm" onClick={() => setQ("")}>+ Clear search+ </Button>+ </>+ )}+ </div>+ )}+ </CommandList>+ </Command>+ </ResponsivePanel>);}diff --git a/src/components/studio/preset-chips.tsx b/src/components/studio/preset-chips.tsxnew file mode 100644index 00000000..bf22becc--- /dev/null+++ b/src/components/studio/preset-chips.tsx@@ -0,0 +1,200 @@+"use client";++import { Ban, Film, Loader2, Shuffle } from "lucide-react";+import { useState } from "react";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Slider } from "@/components/ui/slider";+import type { Preset } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";+import { PRESET_ICONS } from "@/components/preset-icons";+import { loadFullCatalog, useCatalog } from "./catalog";+import { Chip, ClearableChip } from "./chip";++/**+ * Camera-motion / effect picker and Mix. Loaded as its own chunk (with the preset icons), and+ * the preset lists come from the full catalog chunk, fetched on first hover or open.+ */++function PresetGrid({ list, value, onPick, noneLabel }: { list: Preset[] | null; value?: string; onPick: (id: string | undefined) => void; noneLabel: string }) {+ const [cat, setCat] = useState<string>("All");+ if (!list)+ return (+ <div className="grid h-40 place-items-center" role="status" aria-label="Loading presets">+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ </div>+ );+ const cats = ["All", ...new Set(list.map((p) => p.category))];+ return (+ <>+ <div className="scrollbar-none mb-2 flex gap-1 overflow-x-auto" role="tablist" aria-label="Categories">+ {cats.map((c) => (+ <button+ key={c}+ role="tab"+ aria-selected={cat === c}+ onClick={() => setCat(c)}+ className={cn("h-7 shrink-0 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground hover:bg-accent", cat === c && "bg-secondary text-foreground")}+ >+ {c}+ </button>+ ))}+ </div>+ <div className="grid max-h-72 grid-cols-3 gap-1.5 overflow-y-auto">+ {cat === "All" && (+ <button onClick={() => onPick(undefined)} className={cn("group flex flex-col items-start gap-1 overflow-hidden rounded-lg p-1 text-left ring-primary transition hover:bg-accent", !value && "ring-2")}>+ <span className="grid aspect-video w-full place-items-center rounded-md bg-muted text-muted-foreground">+ <Ban className="size-5" />+ </span>+ <span className="truncate px-0.5 text-[12px] font-medium">{noneLabel}</span>+ </button>+ )}+ {list+ .filter((p) => cat === "All" || p.category === cat)+ .map((p) => {+ const PI = PRESET_ICONS[p.look.icon] ?? Film;+ return (+ <button+ key={p.id}+ onClick={() => onPick(p.id)}+ className={cn("group flex flex-col items-start gap-1 overflow-hidden rounded-lg p-1 text-left ring-primary transition hover:bg-accent", value === p.id && "ring-2")}+ >+ <span className="grid aspect-video w-full place-items-center rounded-md text-white" style={{ background: `linear-gradient(135deg, ${p.look.from}, ${p.look.to})` }}>+ <PI className="size-5 transition-transform duration-300 group-hover:scale-125" />+ </span>+ <span className="truncate px-0.5 text-[12px] font-medium">{p.name}</span>+ </button>+ );+ })}+ </div>+ </>+ );+}++const prefetch = () => void loadFullCatalog();++export function PresetChip({ type, value, onChange }: { type: "motion" | "effect"; value?: string; onChange: (id?: string) => void }) {+ const [open, setOpen] = useState(false);+ const catalog = useCatalog();+ const list = catalog.presets?.[type] ?? null;+ const selected = value ? catalog.getPreset(value) : undefined;+ const Icon = selected ? (PRESET_ICONS[selected.look.icon] ?? Film) : value && !catalog.complete ? Loader2 : Film;+ const noun = type === "motion" ? "camera motion" : "effect";+ return (+ <ClearableChip active={!!value} onClear={() => onChange(undefined)} clearLabel={`Clear ${noun}`}>+ <Popover+ open={open}+ onOpenChange={(o) => {+ setOpen(o);+ if (o) prefetch();+ }}+ >+ <PopoverTrigger asChild>+ <Chip icon={Icon} active={!!value} onPointerEnter={prefetch} onFocus={prefetch} className={cn(value && !selected && "[&>svg]:animate-spin")}>+ {selected?.name ?? (value ? "Loading…" : type === "motion" ? "Camera motion" : "Effect")}+ </Chip>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,460px)] p-2" align="start" side="top" collisionPadding={12} aria-label={type === "motion" ? "Camera motions" : "Effects"}>+ <PresetGrid+ list={list}+ value={value}+ noneLabel="None"+ onPick={(id) => {+ onChange(id);+ setOpen(false);+ }}+ />+ </PopoverContent>+ </Popover>+ </ClearableChip>+ );+}++const pct = (n: number) => `${Math.round(n * 100)}%`;++/** Higgsfield's Mix: a second motion or effect on top of the first, each with a strength. */+export function MixChip({+ primary,+ strength,+ mix,+ onChange,+}: {+ primary: Preset;+ strength: number;+ mix?: { presetId: string; strength: number };+ onChange: (patch: { presetStrength?: number; mix?: { presetId: string; strength: number } | undefined }) => void;+}) {+ const [open, setOpen] = useState(false);+ const catalog = useCatalog();+ const second = mix ? catalog.getPreset(mix.presetId) : undefined;+ const mixable = catalog.presets ? [...catalog.presets.motion, ...catalog.presets.effect].filter((p) => p.id !== primary.id && !p.inputs.some((i) => i.key === "endImage")) : null;+ return (+ <ClearableChip active={!!mix} onClear={() => onChange({ mix: undefined })} clearLabel="Remove the mix">+ <Popover+ open={open}+ onOpenChange={(o) => {+ setOpen(o);+ if (o) prefetch();+ }}+ >+ <PopoverTrigger asChild>+ <Chip icon={Shuffle} active={!!mix} onPointerEnter={prefetch} onFocus={prefetch}>+ {second ? `+ ${second.name}` : "Mix"}+ </Chip>+ </PopoverTrigger>+ <PopoverContent className="w-[min(92vw,460px)] space-y-3 p-3" align="start" side="top" collisionPadding={12} aria-label="Mix">+ <div className="space-y-2.5">+ <div className="space-y-1.5">+ <div className="flex items-center justify-between text-[12px]">+ <span className="font-medium">{primary.name}</span>+ <span className="text-muted-foreground tabular-nums">{pct(strength)}</span>+ </div>+ <Slider min={0.1} max={1} step={0.05} value={[strength]} onValueChange={([v]) => onChange({ presetStrength: v })} aria-label={`${primary.name} strength`} />+ </div>+ {second && mix && (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between text-[12px]">+ <span className="font-medium">{second.name}</span>+ <span className="text-muted-foreground tabular-nums">{pct(mix.strength)}</span>+ </div>+ <Slider min={0.1} max={1} step={0.05} value={[mix.strength]} onValueChange={([v]) => onChange({ mix: { ...mix, strength: v } })} aria-label={`${second.name} strength`} />+ </div>+ )}+ </div>+ <p className="text-[12px] text-muted-foreground">{second ? "Swap the second preset:" : "Pick a second motion or effect to combine with it:"}</p>+ <PresetGrid+ list={mixable}+ value={mix?.presetId}+ noneLabel="No mix"+ onPick={(id) => onChange({ mix: id ? { presetId: id, strength: mix?.strength ?? 0.6 } : undefined })}+ />+ </PopoverContent>+ </Popover>+ </ClearableChip>+ );+}++/** Both chips, as one lazily loaded unit for the composer toolbar. */+export default function PresetChips({+ picker,+ preset,+ presetId,+ strength,+ mix,+ onPreset,+ onMix,+}: {+ picker?: "motion" | "effect";+ preset?: Preset;+ presetId?: string;+ strength: number;+ mix?: { presetId: string; strength: number };+ onPreset: (id?: string) => void;+ onMix: (patch: { presetStrength?: number; mix?: { presetId: string; strength: number } | undefined }) => void;+}) {+ return (+ <>+ {picker && <PresetChip type={picker} value={presetId} onChange={onPreset} />}+ {preset && (preset.type === "motion" || preset.type === "effect") && <MixChip primary={preset} strength={strength} mix={mix} onChange={onMix} />}+ </>+ );+}diff --git a/src/components/studio/prompt-input.tsx b/src/components/studio/prompt-input.tsxindex 52a1a377..34e9249c 100644--- a/src/components/studio/prompt-input.tsx+++ b/src/components/studio/prompt-input.tsx@@ -4,6 +4,7 @@ import { AtSign, AudioLines, MapPin, Package, Palette, Plus, ScanFace } from "luimport Link from "next/link";import { forwardRef, useImperativeHandle, useMemo, useRef, useState } from "react";import { elementKindInfo, mentionAtCaret, type ElementKind, type StudioElement } from "@/lib/catalog/elements";+import { hasMention } from "@/lib/composer";import { cn } from "@/lib/utils";export const ELEMENT_ICONS: Record<ElementKind, typeof ScanFace> = {@@ -55,8 +56,10 @@ export const PromptInput = forwardRef<placeholder?: string;elements: StudioElement[];className?: string;+ /** Docked and not focused: keep the prompt to one line. */+ collapsed?: boolean;}->(function PromptInput({ value, onChange, onSubmit, placeholder, elements, className }, ref) {+>(function PromptInput({ value, onChange, onSubmit, placeholder, elements, className, collapsed }, ref) {const ta = useRef<HTMLTextAreaElement>(null);const mirror = useRef<HTMLDivElement>(null);const [caret, setCaret] = useState<number | null>(null);@@ -126,7 +129,12 @@ export const PromptInput = forwardRef<}}onSelect={syncCaret}onClick={syncCaret}- onBlur={() => setTimeout(() => setCaret(null), 120)}+ onBlur={(e) => {+ const el = e.currentTarget;+ setTimeout(() => setCaret(null), 120);+ // Collapsing to one line: show the start of the prompt, not wherever the caret was.+ if (collapsed) el.scrollTop = 0;+ }}onScroll={(e) => {if (mirror.current) mirror.current.scrollTop = e.currentTarget.scrollTop;}}@@ -155,10 +163,13 @@ export const PromptInput = forwardRef<}}rows={1}placeholder={placeholder}- spellCheck+ aria-label="Prompt"+ // Spellcheck would underline every @handle in red.+ spellCheck={!hasMention(value)}className={cn(shared,- "scrollbar-none relative field-sizing-content max-h-52 min-h-12 resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent",+ "scrollbar-none relative field-sizing-content resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent",+ collapsed ? "max-h-[38px] min-h-[38px] overflow-hidden" : "max-h-52 min-h-12",)}/>{open && (diff --git a/src/components/studio/responsive-panel.tsx b/src/components/studio/responsive-panel.tsxnew file mode 100644index 00000000..e0221f6a--- /dev/null+++ b/src/components/studio/responsive-panel.tsx@@ -0,0 +1,65 @@+"use client";++import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { useIsMobile } from "@/hooks/use-mobile";+import { cn } from "@/lib/utils";++/** A popover above the composer on desktop, a bottom sheet on phones. `trigger` must be one element that takes a ref. */+export function ResponsivePanel({+ open,+ onOpenChange,+ trigger,+ tooltip,+ title,+ description,+ children,+ className,+ sheetClassName,+ align = "start",+}: {+ open: boolean;+ onOpenChange: (o: boolean) => void;+ trigger: React.ReactElement;+ tooltip?: React.ReactNode;+ title: string;+ description?: string;+ children: React.ReactNode;+ className?: string;+ sheetClassName?: string;+ align?: "start" | "center" | "end";+}) {+ const mobile = useIsMobile();+ const withTip = (t: React.ReactNode) =>+ tooltip ? (+ <Tooltip>+ {t}+ <TooltipContent>{tooltip}</TooltipContent>+ </Tooltip>+ ) : (+ t+ );+ const inner = tooltip ? <TooltipTrigger asChild>{trigger}</TooltipTrigger> : trigger;+ if (mobile)+ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ {withTip(<SheetTrigger asChild>{inner}</SheetTrigger>)}+ <SheetContent side="bottom" className={cn("max-h-[88svh] gap-0 rounded-t-2xl pb-[env(safe-area-inset-bottom)]", sheetClassName)}>+ <SheetHeader className="pr-12 pb-2">+ <SheetTitle className="font-sans text-[15px] font-semibold">{title}</SheetTitle>+ <SheetDescription className={cn(!description && "sr-only")}>{description ?? title}</SheetDescription>+ </SheetHeader>+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-4 pb-4">{children}</div>+ </SheetContent>+ </Sheet>+ );+ return (+ <Popover open={open} onOpenChange={onOpenChange}>+ {withTip(<PopoverTrigger asChild>{inner}</PopoverTrigger>)}+ <PopoverContent align={align} side="top" collisionPadding={12} aria-label={title} className={cn("max-h-[min(var(--radix-popover-content-available-height),640px)] w-[min(92vw,420px)] overflow-y-auto p-3", className)}>+ {children}+ </PopoverContent>+ </Popover>+ );+}diff --git a/src/components/studio/settings-panel.tsx b/src/components/studio/settings-panel.tsxnew file mode 100644index 00000000..6dc1edaa--- /dev/null+++ b/src/components/studio/settings-panel.tsx@@ -0,0 +1,247 @@+"use client";++import { ChevronDown, Loader2, Shuffle, SlidersHorizontal, Sparkles, Wand2 } from "lucide-react";+import { useId, useState } from "react";+import { Button } from "@/components/ui/button";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";+import { Switch } from "@/components/ui/switch";+import { OPERATION_LABELS, type GenParams, type ModelDef, type Operation } from "@/lib/catalog/types";+import { durationLabel, hiddenChanges, settingsSummary, type SettingsShape } from "@/lib/composer";+import { ratioValue } from "@/lib/format";+import { cn } from "@/lib/utils";+import { SliderControls } from "./audio-controls";+import { Chip } from "./chip";+import { ResponsivePanel } from "./responsive-panel";+import { MultiShotControl } from "./shots-editor";++function RatioGlyph({ ratio }: { ratio: string }) {+ const r = ratioValue(ratio === "auto" ? "1:1" : ratio);+ const w = r >= 1 ? 18 : 18 * r;+ const h = r >= 1 ? 18 / r : 18;+ return <span className="inline-block rounded-[3px] border-[1.5px] border-current" style={{ width: w, height: h }} />;+}++function Section({ label, children, id }: { label: string; children: React.ReactNode; id?: string }) {+ return (+ <div className="space-y-1.5">+ <p id={id} className="text-[12px] font-medium text-muted-foreground">+ {label}+ </p>+ {children}+ </div>+ );+}++function Segmented<T extends string | number>({ label, options, value, onChange, format = (v) => String(v) }: { label: string; options: T[]; value: T; onChange: (v: T) => void; format?: (v: T) => string }) {+ return (+ <div role="radiogroup" aria-label={label} className="flex flex-wrap gap-0.5 rounded-full bg-muted p-0.5">+ {options.map((o) => (+ <button+ key={String(o)}+ role="radio"+ aria-checked={value === o}+ onClick={() => onChange(o)}+ className={cn(+ "h-7 min-w-11 flex-1 rounded-full px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground tabular-nums transition outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50",+ value === o && "bg-background text-foreground shadow-soft",+ )}+ >+ {format(o)}+ </button>+ ))}+ </div>+ );+}++function Toggle({ label, hint, checked, onChange, children }: { label: string; hint: string; checked: boolean; onChange: (v: boolean) => void; children?: React.ReactNode }) {+ const id = useId();+ return (+ <div className="flex items-center gap-3 py-2">+ <div className="min-w-0 flex-1">+ <label htmlFor={id} className="block cursor-pointer">+ <span className="block text-[13px] font-medium">{label}</span>+ <span className="block text-[12px] leading-snug text-muted-foreground">{hint}</span>+ </label>+ {children}+ </div>+ <Switch id={id} checked={checked} onCheckedChange={onChange} />+ </div>+ );+}++export interface SettingsPanelProps {+ model?: ModelDef;+ op?: Operation;+ shape: SettingsShape;+ params: GenParams;+ setP: (patch: Partial<GenParams>) => void;+ setExtra: (key: string, v: unknown) => void;+ negativePrompt: string;+ setNegativePrompt: (v: string) => void;+ kind: "image" | "video" | string;+ enhancing: boolean;+ onRewrite: () => void;+ opNote?: string;+}++/**+ * One summary chip ("16:9 · 720p · 5s · ×1") for every output setting, opening a popover (a+ * bottom sheet on phones) with segmented controls, the mode toggles and Advanced.+ */+export function SettingsChip(props: SettingsPanelProps) {+ const { model, shape, params, negativePrompt } = props;+ const [open, setOpen] = useState(false);+ const parts = settingsSummary(shape, params, model);+ const extra = hiddenChanges(params, negativePrompt, model);+ const text = parts.length ? parts.join(" · ") : "Settings";+ return (+ <ResponsivePanel+ open={open}+ onOpenChange={setOpen}+ title="Settings"+ className="w-[min(92vw,400px)] p-3.5"+ trigger={+ <Chip icon={SlidersHorizontal} aria-label={`Settings: ${parts.join(", ") || "defaults"}${extra ? `, ${extra} more changed` : ""}`} className="tabular-nums">+ {text}+ {extra > 0 && <span aria-hidden className="-mr-0.5 size-1.5 rounded-full bg-primary" />}+ </Chip>+ }+ >+ <SettingsBody {...props} />+ </ResponsivePanel>+ );+}++function SettingsBody({ model, op, shape, params: p, setP, setExtra, negativePrompt, setNegativePrompt, kind, enhancing, onRewrite, opNote }: SettingsPanelProps) {+ const opts = model?.options ?? {};+ const d = model?.defaults ?? {};+ const [advanced, setAdvanced] = useState(p.seed !== undefined || !!negativePrompt);+ return (+ <div className="space-y-4">+ {shape.aspect && (+ <Section label="Aspect ratio">+ <div role="radiogroup" aria-label="Aspect ratio" className="grid grid-cols-4 gap-1 sm:grid-cols-5">+ {shape.aspect.map((o) => {+ const sel = (p.aspectRatio ?? d.aspectRatio ?? shape.aspect![0]) === o;+ return (+ <button+ key={o}+ role="radio"+ aria-checked={sel}+ onClick={() => setP({ aspectRatio: o })}+ className={cn(+ "flex h-14 flex-col items-center justify-center gap-1.5 rounded-lg text-[11px] font-medium text-muted-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50",+ sel && "bg-brand-faint text-brand-text hover:bg-brand-faint-hover",+ )}+ >+ <span className="grid h-5 place-items-center">+ <RatioGlyph ratio={o} />+ </span>+ {o === "auto" ? "Auto" : o}+ </button>+ );+ })}+ </div>+ </Section>+ )}+ {shape.resolution && (+ <Section label="Quality">+ <Segmented label="Quality" options={shape.resolution} value={p.resolution ?? d.resolution ?? shape.resolution[0]} onChange={(v) => setP({ resolution: v })} />+ </Section>+ )}+ {shape.duration && (+ <Section label="Duration">+ <Segmented label="Duration" options={shape.duration} value={p.duration ?? d.duration ?? shape.duration[0]} onChange={(v) => setP({ duration: v })} format={durationLabel} />+ </Section>+ )}+ {shape.count && (+ <Section label={kind === "video" ? "Videos" : "Images"}>+ <Segmented label={kind === "video" ? "Videos" : "Images"} options={[1, 2, 3, 4]} value={p.numOutputs ?? 1} onChange={(v) => setP({ numOutputs: v })} format={(v) => `×${v}`} />+ </Section>+ )}+ {shape.multiShot && model && (+ <Section label="Multi-shot">+ <MultiShotControl model={model} params={p} onChange={setP} />+ </Section>+ )}+ {(shape.draft || shape.audio || shape.enhance) && (+ <div className="divide-y rounded-xl border px-3">+ {shape.draft && (+ <Toggle label="Draft" hint={p.draft ? "Cheap 480p take — finish the one you like in 1080p" : "Preview at 480p first, then render the keeper in 1080p"} checked={!!p.draft} onChange={(v) => setP({ draft: v })} />+ )}+ {shape.audio && (+ <Toggle label="Audio" hint={p.generateAudio === false ? "Silent video (cheaper)" : "Native sound, music and dialogue"} checked={p.generateAudio !== false} onChange={(v) => setP({ generateAudio: v })} />+ )}+ {shape.enhance && (+ <Toggle label="Enhance prompt" hint="An LLM rewrites your prompt before generating" checked={!!p.enhancePrompt} onChange={(v) => setP({ enhancePrompt: v })}>+ <button+ type="button"+ onClick={onRewrite}+ disabled={enhancing}+ className="mt-1 inline-flex items-center gap-1 rounded text-[12px] font-medium text-brand-text outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-60"+ >+ {enhancing ? <Loader2 className="size-3 animate-spin" /> : <Wand2 className="size-3" />} Rewrite my prompt now+ </button>+ </Toggle>+ )}+ </div>+ )}+ {shape.sliders && model && (+ <Section label="Model settings">+ <SliderControls model={model} values={p.extra ?? {}} onChange={setExtra} />+ </Section>+ )}+ <Collapsible open={advanced} onOpenChange={setAdvanced}>+ <CollapsibleTrigger className="flex w-full items-center gap-1.5 rounded-md text-[12px] font-medium text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50">+ <Sparkles className="size-3.5" /> Advanced+ <ChevronDown className={cn("ml-auto size-3.5 transition-transform", advanced && "rotate-180")} />+ </CollapsibleTrigger>+ <CollapsibleContent className="space-y-3 pt-3">+ <div className="space-y-1.5">+ <div className="flex items-center justify-between text-[12px] text-muted-foreground">+ <span>Seed</span>+ <label className="flex items-center gap-2">+ Random+ <Switch checked={p.seed === undefined} onCheckedChange={(r) => setP({ seed: r ? undefined : Math.floor(Math.random() * 1e9) })} aria-label="Random seed" />+ </label>+ </div>+ {p.seed !== undefined && (+ <div className="flex gap-1.5">+ <input+ type="number"+ value={p.seed}+ onChange={(e) => setP({ seed: Number(e.target.value) })}+ aria-label="Seed"+ className="h-8 flex-1 rounded-md border bg-background px-2 text-sm tabular-nums outline-none focus:border-primary"+ />+ <Button variant="secondary" size="icon" className="size-8" onClick={() => setP({ seed: Math.floor(Math.random() * 1e9) })} aria-label="New random seed">+ <Shuffle className="size-3.5" />+ </Button>+ </div>+ )}+ </div>+ {opts.negativePrompt && (+ <div className="space-y-1.5">+ <span className="text-[12px] text-muted-foreground">Negative prompt</span>+ <textarea+ value={negativePrompt}+ onChange={(e) => setNegativePrompt(e.target.value)}+ rows={3}+ aria-label="Negative prompt"+ placeholder="blurry, low quality, extra fingers…"+ className="w-full resize-none rounded-md border bg-background px-2 py-1.5 text-sm outline-none focus:border-primary"+ />+ </div>+ )}+ {model && (+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ {model.name} via {model.engine === "open" ? "ComfyUI" : [...new Set(model.routes.map((r) => r.provider))].join(" / ")}+ {op ? ` · ${OPERATION_LABELS[op]}` : ""}+ {opNote ? ` · ${opNote}` : ""}+ </p>+ )}+ </CollapsibleContent>+ </Collapsible>+ </div>+ );+}diff --git a/src/components/studio/shots-editor.tsx b/src/components/studio/shots-editor.tsxindex 05773822..5a41be28 100644--- a/src/components/studio/shots-editor.tsx+++ b/src/components/studio/shots-editor.tsx@@ -1,19 +1,14 @@"use client";-import { Clapperboard, FileVideo2, Minus, Plus, X } from "lucide-react";-import { useState } from "react";-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { FileVideo2, Minus, Plus, X } from "lucide-react";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import type { GenParams, ModelDef } from "@/lib/catalog/types";import { cn } from "@/lib/utils";type Shot = NonNullable<GenParams["shots"]>[number];-const chip = "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors";--/** Off · Auto (the model cuts by itself) · Custom (you write each shot). */-export function MultiShotChip({ model, params, onChange }: { model: ModelDef; params: GenParams; onChange: (p: Partial<GenParams>) => void }) {- const [open, setOpen] = useState(false);+/** Off · Auto (the model cuts by itself) · Custom (you write each shot): a segmented control for the settings panel. */+export function MultiShotControl({ model, params, onChange }: { model: ModelDef; params: GenParams; onChange: (p: Partial<GenParams>) => void }) {const ms = model.options.multiShot!;const mode = params.shots ? "custom" : params.multiShot === "auto" ? "auto" : "off";const concat = ms.mode === "concat";@@ -24,49 +19,46 @@ export function MultiShotChip({ model, params, onChange }: { model: ModelDef; pa...(concat ? [] : [{ id: "auto", label: "Auto", hint: "The model plans the cuts" } as const]),{ id: "custom", label: "Custom", hint: `Write up to ${ms.maxShots} shots` },] as const;+ const pick = (id: (typeof options)[number]["id"]) => {+ if (id === "off") onChange({ shots: undefined, multiShot: undefined });+ if (id === "auto") onChange({ shots: undefined, multiShot: "auto" });+ if (id === "custom" && !params.shots)+ onChange({+ multiShot: undefined,+ shots: [+ { prompt: "", duration: each },+ { prompt: "", duration: each },+ ],+ });+ };return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <button type="button" className={cn(chip, mode !== "off" ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent")}>- <Clapperboard className="size-3.5" />- {mode === "custom" ? `${params.shots!.length} shots` : mode === "auto" ? "Multi-shot · Auto" : "Multi-shot"}- </button>- </PopoverTrigger>- <PopoverContent className="w-72 p-2" align="start" side="top">- <p className="px-1 pb-2 text-[13px] font-medium">Multi-shot</p>- <div className="space-y-1">- {options.map((o) => (- <button- key={o.id}- onClick={() => {- if (o.id === "off") onChange({ shots: undefined, multiShot: undefined });- if (o.id === "auto") onChange({ shots: undefined, multiShot: "auto" });- if (o.id === "custom" && !params.shots)- onChange({- multiShot: undefined,- shots: [- { prompt: "", duration: each },- { prompt: "", duration: each },- ],- });- setOpen(false);- }}- className={cn("flex w-full flex-col rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-accent", mode === o.id && "bg-brand-faint")}- >- <span className={cn("text-[13px] font-medium", mode === o.id && "text-brand-text")}>{o.label}</span>- <span className="text-[12px] text-muted-foreground">{o.hint}</span>- </button>- ))}- </div>- <p className="px-1 pt-2 text-[11px] text-muted-foreground">- {ms.mode === "native"- ? `${model.name} takes each shot as its own prompt.`- : concat- ? `Each shot renders as its own ${model.name} clip, then they're joined into one video.`- : `${model.name} follows shots written into the prompt.`}- </p>- </PopoverContent>- </Popover>+ <div className="space-y-1.5">+ <div role="radiogroup" aria-label="Multi-shot" className="flex rounded-full bg-muted p-0.5">+ {options.map((o) => (+ <Tooltip key={o.id}>+ <TooltipTrigger asChild>+ <button+ role="radio"+ aria-checked={mode === o.id}+ onClick={() => pick(o.id)}+ className={cn("h-7 flex-1 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition", mode === o.id && "bg-background text-foreground shadow-soft")}+ >+ {o.label}+ </button>+ </TooltipTrigger>+ <TooltipContent>{o.hint}</TooltipContent>+ </Tooltip>+ ))}+ </div>+ <p className="text-[11px] leading-snug text-muted-foreground">+ {ms.mode === "native"+ ? `${model.name} takes each shot as its own prompt.`+ : concat+ ? `Each shot renders as its own ${model.name} clip, then they're joined into one video.`+ : `${model.name} follows shots written into the prompt.`}+ {mode === "custom" && " Write each shot under the prompt."}+ </p>+ </div>);}diff --git a/src/components/studio/stored-list.ts b/src/components/studio/stored-list.tsnew file mode 100644index 00000000..389b7d45--- /dev/null+++ b/src/components/studio/stored-list.ts@@ -0,0 +1,54 @@+"use client";++import { useCallback, useSyncExternalStore } from "react";++/** A small id list kept in localStorage and shared live across components and tabs (recent and starred models). */+const listeners = new Map<string, Set<() => void>>();+const cache = new Map<string, { raw: string | null; value: string[] }>();+const EMPTY: string[] = [];++function read(key: string): string[] {+ let raw: string | null = null;+ try {+ raw = localStorage.getItem(key);+ } catch {}+ const hit = cache.get(key);+ if (hit && hit.raw === raw) return hit.value;+ let value = EMPTY;+ try {+ const parsed = raw ? JSON.parse(raw) : [];+ value = Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === "string") : EMPTY;+ } catch {}+ cache.set(key, { raw, value });+ return value;+}++export function writeStoredList(key: string, next: string[]) {+ try {+ localStorage.setItem(key, JSON.stringify(next));+ } catch {}+ listeners.get(key)?.forEach((l) => l());+}++export function useStoredList(key: string): [string[], (update: (prev: string[]) => string[]) => void] {+ const value = useSyncExternalStore(+ (cb) => {+ let set = listeners.get(key);+ if (!set) listeners.set(key, (set = new Set()));+ set.add(cb);+ const onStorage = (e: StorageEvent) => e.key === key && cb();+ window.addEventListener("storage", onStorage);+ return () => {+ set.delete(cb);+ window.removeEventListener("storage", onStorage);+ };+ },+ () => read(key),+ () => EMPTY,+ );+ const update = useCallback((fn: (prev: string[]) => string[]) => writeStoredList(key, fn(read(key))), [key]);+ return [value, update];+}++export const RECENT_MODELS = "fuobe.recentModels";+export const STARRED_MODELS = "fuobe.starredModels";diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsxindex 3b7dd7bd..e163db46 100644--- a/src/components/studio/studio-page.tsx+++ b/src/components/studio/studio-page.tsx@@ -4,16 +4,18 @@ import { Upload } from "lucide-react";import { useSearchParams } from "next/navigation";import { Suspense, useMemo, useRef, useState } from "react";import { nanoid } from "nanoid";+import { toast } from "sonner";import { SidebarTrigger } from "@/components/ui/sidebar";-import { Skeleton } from "@/components/ui/skeleton";-import { getModel, getPreset } from "@/lib/catalog";-import type { Generation, MediaKind } from "@/lib/catalog/types";+import type { Generation, MediaKind, ModelDef, Preset } from "@/lib/catalog/types";import { useEngine, useGenerations } from "@/lib/api";+import type { StudioCatalog } from "@/lib/studio-catalog";import { cn } from "@/lib/utils";+import { ComposerBridgeCtx, useComposerBridge, type ComposerBridge } from "./attachments";+import { CatalogProvider, useCatalog } from "./catalog";import { Composer } from "./composer";import { EngineSwitch } from "./engine-switch";import { Feed } from "./feed";-import { fileToSlot, type SlotValue } from "./media-slot";+import type { SlotValue } from "./media-slot";import { StudioProvider, useStudio, type Draft, type StudioConfig } from "./studio-context";function kindOfUrl(url: string): MediaKind {@@ -25,18 +27,25 @@ function kindOfUrl(url: string): MediaKind {const slot = (url: string | null | undefined): SlotValue | null =>url ? { ref: url, preview: url, kind: kindOfUrl(url), id: nanoid(6) } : null;-function initialDraft(config: StudioConfig, sp: URLSearchParams, engine: "cloud" | "open"): Draft {- const preset = sp.get("preset") ? getPreset(sp.get("preset")!) : config.preset;- const presetRoute = preset ? (engine === "open" ? preset.open : preset.cloud) ?? preset.cloud ?? preset.open : null;+function initialDraft(+ config: StudioConfig,+ sp: URLSearchParams,+ engine: "cloud" | "open",+ lookup: { getModel: (id: string) => ModelDef | undefined; getPreset: (id: string) => Preset | undefined },+): Draft {+ const preset = sp.get("preset") ? lookup.getPreset(sp.get("preset")!) : config.preset;+ const presetRoute = preset ? ((engine === "open" ? preset.open : preset.cloud) ?? preset.cloud ?? preset.open) : null;const requested = sp.get("model");const modelId =- (requested && getModel(requested)?.id) ||+ (requested && lookup.getModel(requested)?.id) ||(preset?.type === "app" ? presetRoute?.modelId : undefined) ||config.defaultModels[engine] ||- config.defaultModels.cloud;- const model = getModel(modelId);+ config.defaultModels.cloud ||+ // Open-only tools (Match colors) keep their open model under the Cloud switch, like cloud-only ones do under Open.+ config.defaultModels.open;+ const model = lookup.getModel(modelId);const slots: Draft["slots"] = {};- const imageSlot = config.slots.find((s) => s.accept === "image")?.key ?? (preset?.inputs.find((s) => s.accept === "image")?.key);+ const imageSlot = config.slots.find((s) => s.accept === "image")?.key ?? preset?.inputs.find((s) => s.accept === "image")?.key;const refs: SlotValue[] = [];if (sp.get("image") && imageSlot) slots[imageSlot] = slot(sp.get("image"));if (sp.get("ref")) {@@ -82,31 +91,44 @@ function draftFromGeneration(g: Generation, config: StudioConfig): Partial<Draft};}-function StudioBody({ header }: { header?: React.ReactNode }) {- const { config, setDraft, addImage } = useStudio();+/** Sticky page header (title + engine), with an optional row of mode tabs under it. */+function StudioHeader({ title, header, tabs }: { title: string; header?: React.ReactNode; tabs?: React.ReactNode }) {+ const [engine, setEngine] = useEngine();+ return (+ <div className="sticky top-0 z-20 bg-background/85 backdrop-blur">+ <header className="flex h-14 items-center gap-2 px-3 sm:px-6">+ <SidebarTrigger className="md:hidden" />+ <h1 className="min-w-0 truncate font-heading text-[22px] leading-[1.15]">{title}</h1>+ <div className="ml-auto flex shrink-0 items-center gap-2">+ {header}+ <EngineSwitch value={engine} onChange={setEngine} />+ </div>+ </header>+ {tabs}+ </div>+ );+}++function StudioBody({ header, tabs }: { header?: React.ReactNode; tabs?: React.ReactNode }) {+ const { config, setDraft } = useStudio();const [engine, setEngine] = useEngine();const feed = useGenerations(config.feed);+ const bridge = useComposerBridge();const [dragging, setDragging] = useState(false);const dragDepth = useRef(0);const items = feed.data ?? [];+ // While the feed loads (and in the prerendered shell) the page shows the hero and the composer, never a blank area.const hasItems = items.length > 0;const reuse = (g: Generation) => {setDraft(draftFromGeneration(g, config));- const model = getModel(g.modelId);- if (model && model.engine !== engine) setEngine(model.engine);+ if (g.engine !== engine) setEngine(g.engine);requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>("[data-composer] textarea")?.focus());};- const composer = (docked: boolean) => (- <div data-composer className={cn("mx-auto w-full", docked ? "max-w-[800px]" : "max-w-[760px]")}>- <Composer docked={docked} />- </div>- );-return (<div- className="relative flex min-h-svh flex-col"+ className="relative flex min-h-svh min-w-0 flex-col"onDragEnter={(e) => {if (![...e.dataTransfer.types].includes("Files")) return;dragDepth.current++;@@ -121,31 +143,16 @@ function StudioBody({ header }: { header?: React.ReactNode }) {e.preventDefault();dragDepth.current = 0;setDragging(false);- for (const f of [...e.dataTransfer.files].slice(0, 6)) {- const id = nanoid(6);- void fileToSlot(f, (v) => v && !v.uploading && addImage({ ...v, id }));- }+ const files = [...e.dataTransfer.files];+ if (!files.length) return;+ if (bridge?.current) bridge.current(files);+ else toast("Drop it on the composer");}}>- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />- <h1 className="font-heading text-[22px] leading-none">{config.title}</h1>- <div className="ml-auto flex items-center gap-2">- {header}- <EngineSwitch value={engine} onChange={setEngine} />- </div>- </header>+ <StudioHeader title={config.title} header={header} tabs={tabs} />- <main className="mx-auto w-full max-w-[1240px] flex-1 px-3 pb-8 sm:px-6">- {feed.isLoading ? (- <div className="space-y-3 pt-6">- <Skeleton className="h-6 w-1/3" />- <div className="flex gap-2">- <Skeleton className="h-56 w-56 rounded-xl" />- <Skeleton className="h-56 w-56 rounded-xl" />- </div>- </div>- ) : hasItems ? (+ <main className={cn("mx-auto w-full max-w-[1240px] min-w-0 px-3 sm:px-6", hasItems && "flex-1 pb-8")}>+ {hasItems ? (<div className="pt-4"><Feed items={items} onReuse={reuse} /></div>@@ -153,27 +160,34 @@ function StudioBody({ header }: { header?: React.ReactNode }) {<div className="flex flex-col items-center pt-[16vh] text-center"><h2 className="font-heading text-display text-balance">{config.hero}</h2>{config.subtitle && <p className="mt-2 max-w-xl text-[13px] text-muted-foreground">{config.subtitle}</p>}- <div className="mt-10 w-full">{composer(false)}</div>- {config.suggestions && (- <div className="mt-4 flex max-w-[760px] flex-wrap justify-center gap-2">- {config.suggestions.map((s) => (- <button- key={s}- onClick={() => setDraft({ prompt: s })}- className="h-8 rounded-full border bg-background px-3 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"- >- {s.length > 48 ? `${s.slice(0, 46)}…` : s}- </button>- ))}- </div>- )}</div>)}</main>- {hasItems && (- <div className="sticky bottom-0 z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6">- {composer(true)}+ {/* One composer for both layouts (centred under the hero, docked under the feed), so it keeps focus and state when the first result arrives. */}+ <div+ className={cn(+ hasItems+ ? "sticky bottom-0 z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6"+ : "px-3 pt-10 sm:px-6",+ )}+ >+ <div data-composer className={cn("mx-auto w-full", hasItems ? "max-w-[800px]" : "max-w-[760px]")}>+ <Composer docked={hasItems} />+ </div>+ </div>++ {!hasItems && config.suggestions && (+ <div className="mx-auto mt-4 flex max-w-[760px] flex-wrap justify-center gap-2 px-3 pb-10">+ {config.suggestions.map((s) => (+ <button+ key={s}+ onClick={() => setDraft({ prompt: s })}+ className="h-8 max-w-full truncate rounded-full border bg-background px-3 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ {s.length > 48 ? `${s.slice(0, 46)}…` : s}+ </button>+ ))}</div>)}@@ -181,7 +195,7 @@ function StudioBody({ header }: { header?: React.ReactNode }) {<div className="pointer-events-none absolute inset-0 z-40 grid place-items-center bg-overlay p-8"><div className="flex flex-col items-center gap-2 rounded-2xl border-2 border-dashed border-primary bg-background px-12 py-10 shadow-heavy"><Upload className="size-6 text-brand-text" />- <p className="font-medium">Drop to use as reference</p>+ <p className="font-medium">Drop to attach</p><p className="text-[13px] text-muted-foreground">Images, videos or audio · up to 200 MB</p></div></div>@@ -192,34 +206,60 @@ function StudioBody({ header }: { header?: React.ReactNode }) {interface StudioPageProps {config: StudioConfig;+ /**+ * The models this studio needs, from the server (`studioCatalog(config)` in a server+ * component). Without it the page loads the catalog chunk itself.+ */+ catalog?: StudioCatalog;+ /** Extra header controls, left of the engine switch. */header?: React.ReactNode;+ /** A row under the header (mode tabs). */+ tabs?: React.ReactNode;initialRefs?: string[];/** Prompt to start with when the URL doesn't carry one (e.g. "@Maya "). */initialPrompt?: string;}-function StudioInner({ config, header, initialRefs, initialPrompt }: StudioPageProps) {- const sp = useSearchParams();+type DraftProps = Omit<StudioPageProps, "catalog"> & { sp: URLSearchParams | null };++/** The studio for one set of URL params (null: the static shell, rendered before the URL is known). */+function StudioDraft({ config, sp, header, tabs, initialRefs, initialPrompt }: DraftProps) {const [engine] = useEngine();- // Recompute the initial draft only when the handoff params change.- const key = sp.toString();+ const catalog = useCatalog();+ const bridge = useMemo<ComposerBridge>(() => ({ current: null }), []);+ // Recompute the initial draft only when the handoff params change (or a client-side catalog arrives).+ const key = sp?.toString() ?? "";const initial = useMemo(() => {- const d = initialDraft(config, new URLSearchParams(key), engine);+ const d = initialDraft(config, new URLSearchParams(key), engine, catalog);if (initialRefs?.length) d.refs = [...initialRefs.map((u) => slot(u)!), ...d.refs];if (initialPrompt && !d.prompt) d.prompt = initialPrompt;return d;- }, [config, key]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [config, key, catalog.ready]); // eslint-disable-line react-hooks/exhaustive-depsreturn (- <StudioProvider key={key} config={config} initial={initial}>- <StudioBody header={header} />- </StudioProvider>+ <ComposerBridgeCtx.Provider value={bridge}>+ <StudioProvider key={`${key}|${catalog.ready}`} config={config} initial={initial}>+ <StudioBody header={header} tabs={tabs} />+ </StudioProvider>+ </ComposerBridgeCtx.Provider>);}-export function StudioPage(props: StudioPageProps) {+function StudioFromUrl(props: Omit<DraftProps, "sp">) {+ const sp = useSearchParams();+ return <StudioDraft {...props} sp={sp} />;+}++/**+ * A studio page: header, hero, composer and feed. The URL (hand-off params) is read under+ * Suspense; its fallback is the same studio with a default draft, so the prerendered HTML already+ * holds the title, the hero and a composer instead of an empty main area.+ */+export function StudioPage({ catalog, ...props }: StudioPageProps) {return (- <Suspense fallback={null}>- <StudioInner {...props} />- </Suspense>+ <CatalogProvider catalog={catalog} config={props.config}>+ <Suspense fallback={<StudioDraft {...props} sp={null} />}>+ <StudioFromUrl {...props} />+ </Suspense>+ </CatalogProvider>);}diff --git a/src/components/studio/studio.tsx b/src/components/studio/studio.tsxnew file mode 100644index 00000000..1f9b354f--- /dev/null+++ b/src/components/studio/studio.tsx@@ -0,0 +1,12 @@+import type { ComponentProps } from "react";+import { studioCatalog } from "@/lib/studio-catalog";+import { StudioPage } from "./studio-page";++/**+ * Server entry for a studio page: picks the models this studio needs on the server and passes+ * them down, so the browser never loads the full model catalog. Use it from `page.tsx`:+ * `<Studio config={VIDEO_STUDIO} />`.+ */+export function Studio(props: Omit<ComponentProps<typeof StudioPage>, "catalog">) {+ return <StudioPage {...props} catalog={studioCatalog(props.config)} />;+}diff --git a/src/components/studio/use-edge-fade.ts b/src/components/studio/use-edge-fade.tsnew file mode 100644index 00000000..b0ded8b6--- /dev/null+++ b/src/components/studio/use-edge-fade.ts@@ -0,0 +1,45 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++const FADE = 24;++/**+ * Fade the edges of a horizontally scrolling row where more content hides (a mask, so it works+ * over any background). Returns a ref for the scroller and the style to put on it.+ */+export function useEdgeFade<T extends HTMLElement>() {+ const ref = useRef<T | null>(null);+ const [edges, setEdges] = useState({ left: false, right: false });++ const measure = useCallback(() => {+ const el = ref.current;+ if (!el) return;+ const left = el.scrollLeft > 1;+ const right = el.scrollLeft + el.clientWidth < el.scrollWidth - 1;+ setEdges((e) => (e.left === left && e.right === right ? e : { left, right }));+ }, []);++ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ measure();+ el.addEventListener("scroll", measure, { passive: true });+ const ro = new ResizeObserver(measure);+ ro.observe(el);+ // Chips come and go with the model: watch the content too.+ const mo = new MutationObserver(measure);+ mo.observe(el, { childList: true, subtree: true });+ return () => {+ el.removeEventListener("scroll", measure);+ ro.disconnect();+ mo.disconnect();+ };+ }, [measure]);++ const mask =+ edges.left || edges.right+ ? `linear-gradient(to right, ${edges.left ? "transparent" : "#000"} 0, #000 ${edges.left ? FADE : 0}px, #000 calc(100% - ${edges.right ? FADE : 0}px), ${edges.right ? "transparent" : "#000"} 100%)`+ : undefined;+ return [ref, mask ? { maskImage: mask, WebkitMaskImage: mask } : undefined] as const;+}diff --git a/src/components/studio/vendor-mark.tsx b/src/components/studio/vendor-mark.tsxnew file mode 100644index 00000000..ccacfb13--- /dev/null+++ b/src/components/studio/vendor-mark.tsx@@ -0,0 +1,62 @@+import { Cpu } from "lucide-react";+import { cn } from "@/lib/utils";++/**+ * A small coloured mark per model maker (a glyph on the maker's hue), so rows are easy to scan.+ * Not logos: the hue and glyph only stand in for them.+ */+const MARKS: [RegExp, string, number][] = [+ [/^alibaba wan/i, "W", 265],+ [/^alibaba qwen/i, "Q", 285],+ [/^alibaba/i, "A", 35],+ [/^bytedance/i, "B", 200],+ [/^black forest/i, "F", 250],+ [/^kuaishou/i, "K", 30],+ [/^higgsfield/i, "H", 155],+ [/^google/i, "G", 230],+ [/^elevenlabs/i, "11", 0],+ [/^openai/i, "O", 160],+ [/^minimax/i, "M", 345],+ [/^lightricks/i, "L", 300],+ [/^resemble/i, "R", 15],+ [/^recraft/i, "R", 50],+ [/^ideogram/i, "I", 120],+ [/^luma/i, "L", 280],+ [/^pixverse/i, "P", 320],+ [/^topaz/i, "T", 210],+ [/^xai/i, "x", 240],+ [/^sync/i, "S", 180],+ [/^heygen/i, "H", 260],+ [/^stability/i, "S", 290],+ [/^tencent/i, "T", 215],+ [/^meta/i, "M", 220],+ [/^bria/i, "B", 340],+ [/^shengshu/i, "V", 190],+];++function hash(s: string) {+ let h = 0;+ for (const c of s) h = (h * 31 + c.charCodeAt(0)) % 360;+ return h;+}++export function VendorMark({ vendor, engine, className }: { vendor: string; engine?: "cloud" | "open"; className?: string }) {+ const open = engine === "open" && /^(open source|comfyui|fuobe)/i.test(vendor);+ const hit = MARKS.find(([re]) => re.test(vendor));+ const glyph = hit?.[1] ?? vendor.replace(/[^A-Za-z0-9]/g, "").charAt(0).toUpperCase();+ const hue = hit?.[2] ?? hash(vendor);+ return (+ <span+ aria-hidden+ style={{ "--h": hue } as React.CSSProperties}+ className={cn(+ "grid size-7 shrink-0 place-items-center rounded-lg text-[12px] font-semibold tracking-tight",+ "bg-[oklch(0.94_0.045_var(--h))] text-[oklch(0.42_0.14_var(--h))] dark:bg-[oklch(0.32_0.06_var(--h))] dark:text-[oklch(0.88_0.09_var(--h))]",+ open && "bg-muted text-muted-foreground dark:bg-muted dark:text-muted-foreground",+ className,+ )}+ >+ {open ? <Cpu className="size-3.5" /> : glyph}+ </span>+ );+}