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
Composer: drawings follow their image, kind-checked tiles, phone toolbar that fits, one blocker toast
Claudebf07c836f7c5
diff --git a/src/components/studio/attachments.ts b/src/components/studio/attachments.tsindex c6e51f67..3d0647fa 100644--- a/src/components/studio/attachments.ts+++ b/src/components/studio/attachments.ts@@ -1,9 +1,9 @@"use client";import { nanoid } from "nanoid";-import { createContext, useCallback, useContext, useEffect, useMemo } from "react";+import { createContext, useCallback, useContext, useEffect, useMemo, useRef } from "react";import { toast } from "sonner";-import { placeAttachment, replaceAttachment } from "@/lib/composer";+import { acceptedKinds, fitAttachments, noRoomMessage, onImageChange, 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";@@ -30,13 +30,22 @@ export function useUploadReaper(draft: Pick<Draft, "slots" | "refs">) {}, [draft.slots, draft.refs]);}+/** Paste / drop / "+" take at most this many files in one go. */+const MAX_AT_ONCE = 8;+/*** 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).+ * id (never re-added if it was removed meanwhile). A file with no room (references full, or a+ * model that takes none) is never uploaded: the person is told why instead.*/export function useAttach(slots: InputSlot[], refMax: number) {- const { config, setDraft } = useStudio();+ const { config, draft, setDraft } = useStudio();+ // The latest draft, to check for room before an upload starts (callbacks outlive renders).+ const latest = useRef(draft);+ useEffect(() => {+ latest.current = draft;+ });/** Upload a file: `place` runs once with the local preview, the result replaces it by id. */const start = useCallback(@@ -55,7 +64,11 @@ export function useAttach(slots: InputSlot[], refMax: number) {return;}inflight.delete(id);- setDraft((d) => replaceAttachment(d, id, v) ?? {});+ setDraft((d) => {+ const r = replaceAttachment(d, id, v);+ // An image whose upload failed takes its drawing with it.+ return r?.slots ? { ...r, ...onImageChange(d, r.slots) } : (r ?? {});+ });},kind,{ signal: entry.ac.signal },@@ -64,37 +77,59 @@ export function useAttach(slots: InputSlot[], refMax: number) {[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]);+ const kinds = useMemo(() => new Set<MediaKind>(acceptedKinds(slots, config.multiRef)), [slots, config.multiRef]);++ const noRoom = useCallback(() => toast(noRoomMessage(refMax, config.multiRef?.kind)), [refMax, 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]);+ /** Put it wherever it fits best: the first empty slot of its kind, else the references. */+ const place = useCallback(+ (v: SlotValue) =>+ setDraft((d) => {+ const r = placeAttachment(d, slots, config.multiRef, refMax, v);+ if (!r) return {};+ // Pasting over a full image slot drops the drawing made on the old image.+ return r.slots ? { ...r, ...onImageChange(d, r.slots) } : r;+ }),+ [setDraft, slots, config.multiRef, refMax],+ );++ /** A library pick (an attachment that needs no upload). */+ const attach = useCallback(+ (v: SlotValue) => {+ if (!placeAttachment(latest.current, slots, config.multiRef, refMax, v)) return noRoom();+ place(v);+ },+ [place, noRoom, 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);+ if (usable.length > MAX_AT_ONCE) toast(`Added the first ${MAX_AT_ONCE} — that's the most at once`);+ const batch = usable.slice(0, MAX_AT_ONCE);+ // Room first: a file with nowhere to go never uploads.+ const { placed, rejected } = fitAttachments(latest.current, slots, config.multiRef, refMax, batch.map(kindOfFile));+ if (rejected.length) noRoom();+ for (const i of placed) start(batch[i], place);},- [kinds, start, attach],+ [kinds, start, place, noRoom, slots, config.multiRef, refMax],);- /** 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],- );+ /** A slot tile: replace its value (an upload it held is cancelled by the reaper). A drawing belongs to the image it was made on. */+ const setSlotValue = useCallback((key: SlotKey, v: SlotValue | null) => setDraft((d) => onImageChange(d, { ...d.slots, [key]: v })), [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]);+ const addRefFile = useCallback(+ (file: File) => {+ if (latest.current.refs.length >= refMax) return noRoom();+ start(file, (v) => setDraft((d) => ({ refs: [...d.refs, v] })), config.multiRef?.kind);+ },+ [start, setDraft, config.multiRef, refMax, noRoom],+ );return useMemo(() => ({ kinds, attach, attachFiles, setSlotValue, uploadToSlot, removeRef, addRefFile }), [kinds, attach, attachFiles, setSlotValue, uploadToSlot, removeRef, addRefFile]);}diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex f4366817..e97d8e29 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -2,7 +2,7 @@import { ArrowUp, AtSign, Loader2, Sparkles, X } from "lucide-react";import dynamic from "next/dynamic";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Kbd } from "@/components/ui/kbd";@@ -19,11 +19,12 @@ 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 { Chip, chipBase, chipIdle } 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 { radioKeys, radioTab } from "./radio-keys";import { SettingsChip } from "./settings-panel";import { ShotsEditor } from "./shots-editor";import { SketchTools } from "./sketch-tools";@@ -85,10 +86,18 @@ function buildRequest(};}+/** Docked and collapsed, the composer hides its tiles: this event asks it to open first. */+const EXPAND_EVENT = "composer:expand";+/** Point at an attachment tile: scroll it into view and pulse its outline. */-function pulseSlot(root: HTMLElement | null, key: string) {+function pulseSlot(root: HTMLElement | null, key: string, retried = false) {const el = root?.querySelector<HTMLElement>(`[data-slot-key="${key}"]`);- if (!el) return;+ if (!el) {+ if (retried || !root) return;+ root.dispatchEvent(new Event(EXPAND_EVENT));+ requestAnimationFrame(() => pulseSlot(root, key, true));+ 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";@@ -120,6 +129,16 @@ export function Composer({ docked }: { docked: boolean }) {const bridgeRef = useComposerBridge();const [chipRow, fade] = useEdgeFade<HTMLDivElement>();useUploadReaper(draft);+ // Typed into before the page hydrated: the prompt already has focus (onFocus never ran).+ useLayoutEffect(() => {+ if (root.current?.contains(document.activeElement)) setFocused(true);+ }, []);+ useEffect(() => {+ const el = root.current;+ const expand = () => setFocused(true);+ el?.addEventListener(EXPAND_EVENT, expand);+ return () => el?.removeEventListener(EXPAND_EVENT, expand);+ }, []);const preset: Preset | undefined = draft.presetId ? catalog.getPreset(draft.presetId) : config.preset;const lockedModel = preset?.type === "app";@@ -173,7 +192,9 @@ export function Composer({ docked }: { docked: boolean }) {// 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);+ // Studios that need one of several inputs (Lipsync: a portrait or a video) name the group.+ const anyOf = preset?.inputs ? undefined : config.anyOf;+ const missing = firstMissingSlot(slots, draft.slots, anyOf);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;@@ -184,6 +205,10 @@ export function Composer({ docked }: { docked: boolean }) {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 };+ for (const g of anyOf ?? []) {+ const first = slots.find((s) => s.key === g[0]);+ if (first && !g.some((k) => planSlots[k]?.ref)) planSlots[first.key] = { ref: PLACEHOLDER[first.accept], preview: "", kind: first.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;@@ -207,19 +232,19 @@ export function Composer({ docked }: { docked: boolean }) {const submit = () => {if (blocker || create.isPending) {if (blocker) {- toast(blocker.message);+ // One blocker toast at a time (pressing Generate again replaces it), gone once a run starts.+ toast(blocker.message, { id: "composer-blocker" });// Point at the tile to fill: the missing slot, or the clip list of a tool that only takes clips.const target = blocker.slot ?? (config.multiRef && config.hidePrompt && draft.refs.length < 2 ? "refs" : undefined);if (target) pulseSlot(root.current, target);}return;}+ toast.dismiss("composer-blocker");setRecent((r) => pushRecent(r, draft.modelId));// The server resolves @mentions and drawings itself; only pin the operation when there are none.+ // No "Queued" toast: the new card (and the "1 generating ↑" pill when it's off-screen) says it.create.mutate(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind), {- onSuccess: (items) => {- toast.success(items.length > 1 ? `${items.length} jobs queued` : "Queued", { duration: 1500 });- },onError: (e) => toast.error((e as Error).message),});};@@ -268,6 +293,70 @@ export function Composer({ docked }: { docked: boolean }) {const showAttachments =(slots.length > 0 || !!config.multiRef) && (hasAttachment || !!slots.find((s) => s.required && !draft.slots[s.key]) || (!!config.multiRef && !showPrompt));const collapsed = docked && !focused;+ // Docked and not focused, the tiles fold into one chip on the toolbar (the composer stays one line).+ const attached = [...slots.map((s) => draft.slots[s.key]), ...draft.refs].filter((v): v is SlotValue => !!v);++ // A blocker toast goes away once the blocker does (a prompt typed, the photo attached).+ const blocking = blocker?.message;+ useEffect(() => {+ if (!blocking) toast.dismiss("composer-blocker");+ }, [blocking]);++ // Voice, language, motion, style and Director chips: inline from sm up; on phones they live in the settings sheet, so the toolbar fits.+ const voiceChips = (+ <>+ {model && (opts.voices?.length || opts.voiceClone) && effectiveOp !== "dialogue" && (+ <VoicePicker+ model={model}+ voice={p.voice}+ sample={draft.slots.voiceAudio}+ 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);+ }}+ />+ )}+ {/* Open-source dialogue clones each speaker from a sample. */}+ {model &&+ opts.voiceClone &&+ effectiveOp === "dialogue" &&+ (["voiceAudio", "voiceAudio2"] as const).map((key, i) => (+ <VoicePicker+ key={key}+ model={{ ...model, options: { ...model.options, voices: [] } }}+ sample={draft.slots[key]}+ label={`Speaker ${i ? "B" : "A"}`}+ onChange={(c) => c?.kind === "sample" && setSlot(key, c.value)}+ />+ ))}+ {model && opts.languages && (+ <LanguageChip languages={opts.languages} value={p.targetLanguage} label={effectiveOp === "dub" ? "Translate to…" : "Language"} onChange={(targetLanguage) => setP({ targetLanguage })} />+ )}+ </>+ );+ const styleChips = (+ <>+ {(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} />}+ </>+ );+ const hasSecondary =+ (!!model && (!!opts.voices?.length || !!opts.voiceClone || !!opts.languages || !!opts.presets || !!opts.controls)) ||+ !!config.presetPicker ||+ preset?.type === "motion" ||+ preset?.type === "effect";return (<div@@ -292,7 +381,7 @@ export function Composer({ docked }: { docked: boolean }) {}}}>- {showAttachments && (+ {showAttachments && !collapsed && (<div className="scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-1.5 pb-2">{slots.map((s) => (<MediaSlot@@ -390,15 +479,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} role="radiogroup" aria-label={o.label} className="flex flex-wrap items-center gap-1">+ <div key={o.key} role="radiogroup" aria-label={o.label} onKeyDown={radioKeys} 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}+ type="button"role="radio"aria-checked={sel}+ tabIndex={radioTab(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")}>@@ -413,42 +504,71 @@ export function Composer({ docked }: { docked: boolean }) {{/* 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">+ {/* Phones (below sm): "+", Settings (icon), the model (it shrinks to fit) and @; the other chips are in the settings sheet. */}+ <div ref={chipRow} style={fade} data-composer-toolbar 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 ? (- 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>- )- ) : (- <Tooltip>- <TooltipTrigger asChild>- <Chip icon={Sparkles}>{model?.name ?? "…"}</Chip>- </TooltipTrigger>- <TooltipContent>{preset?.name} runs on {model?.name ?? "its own model"}</TooltipContent>- </Tooltip>+ {collapsed && showAttachments && attached.length > 0 && (+ <button+ type="button"+ onClick={() => setFocused(true)}+ aria-label={`${attached.length} attached. Show attachments`}+ className={cn(chipBase, chipIdle, "gap-1.5 pl-1 max-sm:order-1")}+ >+ <span className="flex -space-x-2.5">+ {attached.slice(0, 3).map((v, i) => (+ <span key={v.id ?? `${v.ref}-${i}`} className="size-6 overflow-hidden rounded-full border-2 border-secondary bg-muted">+ <SlotPreview value={v} />+ </span>+ ))}+ </span>+ <span className="tabular-nums">+ {attached.length}+ <span className="max-sm:hidden"> attached</span>+ </span>+ </button>)}+ {/* The model chip may shrink (its name truncates) on phones, so the row fits without scrolling. */}+ <span className="flex min-w-0 shrink-0 max-sm:order-2 max-sm:min-w-[4.5rem] max-sm:shrink max-sm:[&>button]:min-w-0 max-sm:[&>button]:shrink max-sm:[&>button>svg:first-child]:hidden">+ {!lockedModel ? (+ 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>+ )+ ) : (+ <Tooltip>+ <TooltipTrigger asChild>+ <Chip icon={Sparkles}>+ <span className="min-w-0 truncate">{model?.name ?? "…"}</span>+ </Chip>+ </TooltipTrigger>+ <TooltipContent>{preset?.name} runs on {model?.name ?? "its own model"}</TooltipContent>+ </Tooltip>+ )}+ </span>{showPrompt && (<Tooltip><TooltipTrigger asChild><buttontype="button"onClick={() => promptRef.current?.startMention()}- // 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"+ // Phones: at the end of the row (typing @ does the same); folded away with the docked composer.+ className={cn(+ "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-3",+ collapsed && "max-sm:hidden",+ )}aria-label="Add an element"><AtSign className="size-3.5" />@@ -457,34 +577,7 @@ export function Composer({ docked }: { docked: boolean }) {<TooltipContent>Add a character, location or prop · type @</TooltipContent></Tooltip>)}- {model && (opts.voices?.length || opts.voiceClone) && effectiveOp !== "dialogue" && (- <VoicePicker- model={model}- voice={p.voice}- sample={draft.slots.voiceAudio}- 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);- }}- />- )}- {/* Open-source dialogue clones each speaker from a sample. */}- {model &&- opts.voiceClone &&- effectiveOp === "dialogue" &&- (["voiceAudio", "voiceAudio2"] as const).map((key, i) => (- <VoicePicker- key={key}- model={{ ...model, options: { ...model.options, voices: [] } }}- sample={draft.slots[key]}- label={`Speaker ${i ? "B" : "A"}`}- onChange={(c) => c?.kind === "sample" && setSlot(key, c.value)}- />- ))}- {model && opts.languages && (- <LanguageChip languages={opts.languages} value={p.targetLanguage} label={effectiveOp === "dub" ? "Translate to…" : "Language"} onChange={(targetLanguage) => setP({ targetLanguage })} />- )}+ <span className="contents max-sm:hidden">{voiceChips}</span><SettingsChipmodel={model}op={op}@@ -498,20 +591,17 @@ export function Composer({ docked }: { docked: boolean }) {enhancing={enhancing}onRewrite={runEnhance}opNote={opNote}+ className="max-sm:order-1"+ extras={+ hasSecondary ? (+ <>+ {voiceChips}+ {styleChips}+ </>+ ) : undefined+ }/>- {(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} />}+ <span className="contents max-sm:hidden">{styleChips}</span></div>{costText && (<Tooltip>diff --git a/src/components/studio/engine-switch.tsx b/src/components/studio/engine-switch.tsxindex 16d7c298..e2de7e9c 100644--- a/src/components/studio/engine-switch.tsx+++ b/src/components/studio/engine-switch.tsx@@ -6,6 +6,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport type { Engine } from "@/lib/catalog/types";import { useEngineMode } from "@/lib/api";import { cn } from "@/lib/utils";+import { radioKeys, radioTab } from "./radio-keys";const OPTIONS: { value: Engine; label: string; icon: typeof Cloud; tip: string }[] = [{ value: "cloud", label: "Cloud", icon: Cloud, tip: "Frontier paid models via your fal.ai / Replicate key" },@@ -56,6 +57,7 @@ export function EngineSwitch({<divrole="radiogroup"aria-label="Engine"+ onKeyDown={radioKeys}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")}><span@@ -67,8 +69,10 @@ export function EngineSwitch({<Tooltip key={o.value}><TooltipTrigger asChild><button+ type="button"role="radio"aria-checked={value === o.value}+ tabIndex={radioTab(value === o.value)}aria-label={o.label}onClick={() => onChange(o.value)}className={cn(diff --git a/src/components/studio/media-slot.tsx b/src/components/studio/media-slot.tsxindex 5eb58583..1c454504 100644--- a/src/components/studio/media-slot.tsx+++ b/src/components/studio/media-slot.tsx@@ -34,7 +34,25 @@ export const ACCEPT: Record<MediaKind, string> = {const MAX_MB = 200;-export const kindOfFile = (f: File): MediaKind => (f.type.startsWith("video/") ? "video" : f.type.startsWith("audio/") ? "audio" : "image");+const EXT_KIND: [RegExp, MediaKind][] = [+ [/\.(mp4|webm|mov|m4v)$/i, "video"],+ [/\.(mp3|wav|ogg|flac|m4a|aac|opus)$/i, "audio"],+ [/\.(txt|srt|vtt)$/i, "text"],+ [/\.(glb|gltf)$/i, "model3d"],+];++/** What a file is, by its type (or its extension when the browser gives none). Anything else counts as an image. */+export const kindOfFile = (f: File): MediaKind => {+ if (f.type.startsWith("video/")) return "video";+ if (f.type.startsWith("audio/")) return "audio";+ if (f.type.startsWith("image/")) return "image";+ if (f.type.startsWith("text/")) return "text";+ return EXT_KIND.find(([re]) => re.test(f.name))?.[1] ?? "image";+};++/** "Image only — drop a photo here": a tile was given the wrong kind of file. */+export const wrongKindMessage = (kind: MediaKind) =>+ ({ image: "Image only — drop a photo here", video: "Video only — drop a clip here", audio: "Audio only — drop a sound file here", text: "Text only — drop a .txt or .srt file here", model3d: "3D only — drop a .glb file here" })[kind];async function upload(file: File, signal?: AbortSignal): Promise<Asset> {const form = new FormData();@@ -63,6 +81,12 @@ export async function fileToSlot(file: File, onChange: (v: SlotValue | null) =>try {const asset = await upload(file, opts.signal);if (opts.signal?.aborted) return;+ // The server knows best what the file is: a clip uploaded into an image slot doesn't stay there.+ if (kind && asset.kind && asset.kind !== kind) {+ onChange(null);+ toast.error(wrongKindMessage(kind));+ return;+ }onChange({ ref: asset.url, preview: asset.url, kind: asset.kind, name: file.name });} catch (e) {if (opts.signal?.aborted || (e as Error).name === "AbortError") return;@@ -211,7 +235,12 @@ export function MediaSlot({/** Marks the tile so the composer can point at it ("Add a start frame"). */slotKey?: string;}) {- const handleFile = (f: File) => (onFile ? onFile(f) : void fileToSlot(f, onChange, kind));+ const handleFile = (f: File) => {+ // A tile takes its own kind only (a clip dropped on the Image tile would land as a video there).+ if (kindOfFile(f) !== kind) return void toast(wrongKindMessage(kind));+ if (onFile) onFile(f);+ else void fileToSlot(f, onChange, kind);+ };const input = useRef<HTMLInputElement>(null);const [over, setOver] = useState(false);const dim = size === "lg" ? "size-20" : "size-14";diff --git a/src/components/studio/model-controls.tsx b/src/components/studio/model-controls.tsxindex c6174ecf..8949d173 100644--- a/src/components/studio/model-controls.tsx+++ b/src/components/studio/model-controls.tsx@@ -68,6 +68,8 @@ export function ProviderPresetChip({<div className="grid max-h-80 grid-cols-3 gap-1.5 overflow-y-auto">{!spec.required && !q && (<button+ type="button"+ aria-pressed={!value}onClick={() => {onChange(undefined);setOpen(false);@@ -83,6 +85,8 @@ export function ProviderPresetChip({{items.map((p) => (<buttonkey={p.id}+ type="button"+ aria-pressed={value === p.id}onClick={() => {onChange(p.id, p.name);setOpen(false);diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsxindex d9d9031a..c972de17 100644--- a/src/components/studio/model-picker.tsx+++ b/src/components/studio/model-picker.tsx@@ -59,6 +59,21 @@ function priceHint(m: ModelDef): string {return `${formatCost(m.pricing.usd)}${unit}`;}+const STAR_KEY_HINT = "Alt+S";++/**+ * Alt+S (or ⌥S) stars or unstars the highlighted model, so starring works from the keyboard+ * while focus stays in the search field. Rows are cmdk items valued "<group>:<model id>".+ */+function starKey(e: React.KeyboardEvent<HTMLElement>, toggle: (id: string) => void) {+ if (!e.altKey || e.ctrlKey || e.metaKey || e.code !== "KeyS") return;+ const value = e.currentTarget.querySelector('[cmdk-item][data-selected="true"]')?.getAttribute("data-value");+ const id = value?.slice(value.indexOf(":") + 1);+ if (!id) return;+ e.preventDefault();+ toggle(id);+}+function ModelRow({m,selected,@@ -77,7 +92,10 @@ function ModelRow({<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>+ <span className={cn("truncate text-[13px] font-medium", selected && "text-brand-text")}>+ {m.name}+ {starred && <span className="sr-only">, starred</span>}+ </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">@@ -91,15 +109,17 @@ function ModelRow({</span></span><span className="shrink-0 text-right text-[11px] text-subtle-foreground tabular-nums">{priceHint(m)}</span>+ {/* Pointer only: inside an option it would be a nested control. Keyboard: Alt+S on the highlighted row (starKey). */}<buttontype="button"+ tabIndex={-1}+ aria-hidden+ title={starred ? `Unstar (${STAR_KEY_HINT})` : `Star (${STAR_KEY_HINT})`}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",@@ -139,7 +159,12 @@ export function ModelPicker({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]);+ // "Best" ranks models that do what the studio's default does first (its main operation), not single-purpose tools.+ const best = useMemo(() => {+ const id = defaultModels?.[engine];+ const op = models.find((m) => m.id === id)?.routes[0]?.op;+ return bestForStudio(models, engine, id, 4, op).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);@@ -171,7 +196,7 @@ export function ModelPicker({</Button>}>- <Command shouldFilter={false} loop label="Models" className="rounded-none! bg-transparent p-0">+ <Command shouldFilter={false} loop label="Models" onKeyDown={(e) => starKey(e, (id) => setStarred((s) => toggleIn(s, id)))} 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={!mobile} />@@ -191,6 +216,9 @@ export function ModelPicker({</span></>)}+ <span className="ml-auto shrink-0 whitespace-nowrap max-sm:hidden">+ <kbd className="font-sans">{STAR_KEY_HINT}</kbd> stars+ </span></div><CommandList className="max-h-[min(52vh,420px)] border-t sm:max-h-[min(56vh,440px)]">{groups.map((g) => (diff --git a/src/components/studio/preset-chips.tsx b/src/components/studio/preset-chips.tsxindex bf22becc..784d4b3d 100644--- a/src/components/studio/preset-chips.tsx+++ b/src/components/studio/preset-chips.tsx@@ -41,7 +41,7 @@ function PresetGrid({ list, value, onPick, noneLabel }: { list: Preset[] | null;</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")}>+ <button type="button" aria-pressed={!value} 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>@@ -55,6 +55,8 @@ function PresetGrid({ list, value, onPick, noneLabel }: { list: Preset[] | null;return (<buttonkey={p.id}+ type="button"+ aria-pressed={value === 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")}>diff --git a/src/components/studio/radio-keys.ts b/src/components/studio/radio-keys.tsnew file mode 100644index 00000000..8ad73bb6--- /dev/null+++ b/src/components/studio/radio-keys.ts@@ -0,0 +1,19 @@+/**+ * Radio-group keyboard pattern for a row of role="radio" buttons (segmented controls): the arrow+ * keys (and Home / End) move to the next option and pick it, and only the picked option is a Tab+ * stop. Put `onKeyDown={radioKeys}` on the role="radiogroup" element and+ * `tabIndex={radioTab(selected)}` on each option.+ */+export function radioKeys(e: React.KeyboardEvent<HTMLElement>) {+ const step = ({ ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 } as Record<string, number>)[e.key];+ if (step === undefined && e.key !== "Home" && e.key !== "End") return;+ const radios = [...e.currentTarget.querySelectorAll<HTMLElement>('[role="radio"]:not([disabled])')];+ if (!radios.length) return;+ e.preventDefault();+ const at = radios.indexOf(document.activeElement as HTMLElement);+ const next = e.key === "Home" ? 0 : e.key === "End" ? radios.length - 1 : (Math.max(at, 0) + step + radios.length) % radios.length;+ radios[next].focus();+ radios[next].click();+}++export const radioTab = (selected: boolean) => (selected ? 0 : -1);diff --git a/src/components/studio/settings-panel.tsx b/src/components/studio/settings-panel.tsxindex 6dc1edaa..f1b2ac3c 100644--- a/src/components/studio/settings-panel.tsx+++ b/src/components/studio/settings-panel.tsx@@ -11,6 +11,7 @@ import { ratioValue } from "@/lib/format";import { cn } from "@/lib/utils";import { SliderControls } from "./audio-controls";import { Chip } from "./chip";+import { radioKeys, radioTab } from "./radio-keys";import { ResponsivePanel } from "./responsive-panel";import { MultiShotControl } from "./shots-editor";@@ -33,13 +34,17 @@ function Section({ label, children, id }: { label: string; children: React.React}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 }) {+ // Nothing selected (an unexpected value): the first option takes the Tab stop.+ const current = options.includes(value) ? value : options[0];return (- <div role="radiogroup" aria-label={label} className="flex flex-wrap gap-0.5 rounded-full bg-muted p-0.5">+ <div role="radiogroup" aria-label={label} onKeyDown={radioKeys} className="flex flex-wrap gap-0.5 rounded-full bg-muted p-0.5">{options.map((o) => (<buttonkey={String(o)}+ type="button"role="radio"aria-checked={value === o}+ tabIndex={radioTab(current === 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",@@ -53,6 +58,34 @@ function Segmented<T extends string | number>({ label, options, value, onChange,);}+/**+ * The seed field keeps what you type (an empty field while you replace the number) and sends a+ * whole number only; leaving it empty goes back to the last seed.+ */+function SeedInput({ value, onChange }: { value: number; onChange: (v: number) => void }) {+ const [text, setText] = useState(String(value));+ const [prev, setPrev] = useState(value);+ if (value !== prev) {+ setPrev(value);+ setText(String(value));+ }+ return (+ <input+ type="text"+ inputMode="numeric"+ value={text}+ onChange={(e) => {+ const t = e.target.value.replace(/[^\d]/g, "").slice(0, 10);+ setText(t);+ if (t) onChange(Number(t));+ }}+ onBlur={() => !text && setText(String(value))}+ aria-label="Seed"+ className="h-8 min-w-0 flex-1 rounded-md border bg-background px-2 text-sm tabular-nums outline-none focus:border-primary"+ />+ );+}+function Toggle({ label, hint, checked, onChange, children }: { label: string; hint: string; checked: boolean; onChange: (v: boolean) => void; children?: React.ReactNode }) {const id = useId();return (@@ -82,28 +115,43 @@ export interface SettingsPanelProps {enhancing: boolean;onRewrite: () => void;opNote?: string;+ /** Classes for the chip (its place in the toolbar). */+ className?: string;+ /** Chips the toolbar has no room for on phones (voice, motion, style…): shown at the top of the sheet there. */+ extras?: React.ReactNode;}/*** 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.+ * bottom sheet on phones) with segmented controls, the mode toggles and Advanced. On phones the+ * chip is just its icon (a dot when something differs from the defaults); the sheet's header+ * spells the summary out.*/export function SettingsChip(props: SettingsPanelProps) {- const { model, shape, params, negativePrompt } = props;+ const { model, shape, params, negativePrompt, className } = 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";+ // Icon-only on phones: the dot then also says the summary differs from the model's defaults.+ const changed = extra > 0 || parts.join() !== settingsSummary(shape, { ...model?.defaults }, model).join();return (<ResponsivePanelopen={open}onOpenChange={setOpen}title="Settings"+ description={parts.length ? text : undefined}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+ icon={SlidersHorizontal}+ aria-label={`Settings: ${parts.join(", ") || "defaults"}${extra ? `, ${extra} more changed` : ""}`}+ className={cn("relative tabular-nums max-sm:w-8 max-sm:justify-center max-sm:px-0", className)}+ >+ <span className="max-sm:hidden">{text}</span>+ {(extra > 0 || changed) && (+ <span aria-hidden className={cn("-mr-0.5 size-1.5 rounded-full bg-primary max-sm:absolute max-sm:top-1 max-sm:right-1 max-sm:mr-0", extra === 0 && "sm:hidden")} />+ )}</Chip>}>@@ -112,22 +160,25 @@ export function SettingsChip(props: SettingsPanelProps) {);}-function SettingsBody({ model, op, shape, params: p, setP, setExtra, negativePrompt, setNegativePrompt, kind, enhancing, onRewrite, opNote }: SettingsPanelProps) {+function SettingsBody({ model, op, shape, params: p, setP, setExtra, negativePrompt, setNegativePrompt, kind, enhancing, onRewrite, opNote, extras }: SettingsPanelProps) {const opts = model?.options ?? {};const d = model?.defaults ?? {};const [advanced, setAdvanced] = useState(p.seed !== undefined || !!negativePrompt);return (<div className="space-y-4">+ {extras && <div className="flex flex-wrap gap-1.5 sm:hidden">{extras}</div>}{shape.aspect && (<Section label="Aspect ratio">- <div role="radiogroup" aria-label="Aspect ratio" className="grid grid-cols-4 gap-1 sm:grid-cols-5">+ <div role="radiogroup" aria-label="Aspect ratio" onKeyDown={radioKeys} 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 (<buttonkey={o}+ type="button"role="radio"aria-checked={sel}+ tabIndex={radioTab(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",@@ -207,13 +258,7 @@ function SettingsBody({ model, op, shape, params: p, setP, setExtra, negativePro</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"- />+ <SeedInput value={p.seed} onChange={(seed) => setP({ seed })} /><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>diff --git a/src/components/studio/shots-editor.tsx b/src/components/studio/shots-editor.tsxindex 5a41be28..afcc7076 100644--- a/src/components/studio/shots-editor.tsx+++ b/src/components/studio/shots-editor.tsx@@ -4,6 +4,7 @@ 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";+import { radioKeys, radioTab } from "./radio-keys";type Shot = NonNullable<GenParams["shots"]>[number];@@ -33,13 +34,15 @@ export function MultiShotControl({ model, params, onChange }: { model: ModelDef;};return (<div className="space-y-1.5">- <div role="radiogroup" aria-label="Multi-shot" className="flex rounded-full bg-muted p-0.5">+ <div role="radiogroup" aria-label="Multi-shot" onKeyDown={radioKeys} className="flex rounded-full bg-muted p-0.5">{options.map((o) => (<Tooltip key={o.id}><TooltipTrigger asChild><button+ type="button"role="radio"aria-checked={mode === o.id}+ tabIndex={radioTab(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")}>diff --git a/src/components/studio/sketch-editor.tsx b/src/components/studio/sketch-editor.tsxindex 5395549a..99169282 100644--- a/src/components/studio/sketch-editor.tsx+++ b/src/components/studio/sketch-editor.tsx@@ -132,10 +132,17 @@ export function SketchEditor(props: {}) {// The canvas answers Escape first: it closes an open note instead of the whole editor.const escapeRef = useRef<() => boolean>(() => false);+ const content = useRef<HTMLDivElement>(null);return (<Dialog open={props.open} onOpenChange={props.onOpenChange}><DialogContent- className="flex h-[min(92vh,880px)] w-[min(96vw,1100px)] max-w-none flex-col gap-3 sm:max-w-none"+ ref={content}+ className="flex h-[min(92vh,880px)] w-[min(96vw,1100px)] max-w-none flex-col gap-3 outline-none sm:max-w-none"+ // Focus the editor itself, not the first tool: a tool's tooltip would open on focus and eat the first Escape.+ onOpenAutoFocus={(e) => {+ e.preventDefault();+ content.current?.focus();+ }}onEscapeKeyDown={(e) => {if (escapeRef.current()) e.preventDefault();}}