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
Studio shell: keep the composer across hydration, one path per hub mode, preset header
Claudef70676758189
diff --git a/next.config.ts b/next.config.tsindex 995ff054..9d0eae36 100644--- a/next.config.ts+++ b/next.config.ts@@ -12,6 +12,21 @@ const nextConfig: NextConfig = {return [{ source: "/characters", destination: "/elements", permanent: true },{ source: "/characters/:id", destination: "/elements/:id", permanent: true },+ // Studio hubs have one path per mode (src/lib/hubs.ts): old `?mode=` links, and a clip handed+ // to Upscale or Audio without a mode, open that mode's own page (prerendered with the right studio).+ ...["audio", "video-tools", "upscale"].map((hub) => ({+ source: `/${hub}`,+ has: [{ type: "query" as const, key: "mode", value: "(?<mode>[a-z0-9-]+)" }],+ destination: `/${hub}/:mode`,+ permanent: false,+ })),+ ...["audio", "upscale"].map((hub) => ({+ source: `/${hub}`,+ has: [{ type: "query" as const, key: "video" }],+ missing: [{ type: "query" as const, key: "mode" }],+ destination: `/${hub}/video`,+ permanent: false,+ })),];},turbopack: {diff --git a/src/app/(studio)/audio/[mode]/page.tsx b/src/app/(studio)/audio/[mode]/page.tsxnew file mode 100644index 00000000..d22379f1--- /dev/null+++ b/src/app/(studio)/audio/[mode]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { hubMetadata, HubModePage, hubParams } from "@/components/studio/mode-switch-studio";++export function generateStaticParams() {+ return hubParams("audio");+}++export async function generateMetadata({ params }: PageProps<"/audio/[mode]">): Promise<Metadata> {+ return hubMetadata("audio", (await params).mode);+}++export default function Page({ params }: PageProps<"/audio/[mode]">) {+ return <HubModePage kind="audio" params={params} />;+}diff --git a/src/app/(studio)/upscale/[mode]/page.tsx b/src/app/(studio)/upscale/[mode]/page.tsxnew file mode 100644index 00000000..da7569a5--- /dev/null+++ b/src/app/(studio)/upscale/[mode]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { hubMetadata, HubModePage, hubParams } from "@/components/studio/mode-switch-studio";++export function generateStaticParams() {+ return hubParams("upscale");+}++export async function generateMetadata({ params }: PageProps<"/upscale/[mode]">): Promise<Metadata> {+ return hubMetadata("upscale", (await params).mode);+}++export default function Page({ params }: PageProps<"/upscale/[mode]">) {+ return <HubModePage kind="upscale" params={params} />;+}diff --git a/src/app/(studio)/video-tools/[mode]/page.tsx b/src/app/(studio)/video-tools/[mode]/page.tsxnew file mode 100644index 00000000..04fae5f5--- /dev/null+++ b/src/app/(studio)/video-tools/[mode]/page.tsx@@ -0,0 +1,14 @@+import type { Metadata } from "next";+import { hubMetadata, HubModePage, hubParams } from "@/components/studio/mode-switch-studio";++export function generateStaticParams() {+ return hubParams("video-tools");+}++export async function generateMetadata({ params }: PageProps<"/video-tools/[mode]">): Promise<Metadata> {+ return hubMetadata("video-tools", (await params).mode);+}++export default function Page({ params }: PageProps<"/video-tools/[mode]">) {+ return <HubModePage kind="video-tools" params={params} />;+}diff --git a/src/components/studio/mode-studio.tsx b/src/components/studio/mode-studio.tsxindex 37bba767..08c5a96d 100644--- a/src/components/studio/mode-studio.tsx+++ b/src/components/studio/mode-studio.tsx@@ -1,39 +1,41 @@"use client";import Link from "next/link";-import { useSearchParams } from "next/navigation";-import { Suspense, useEffect, useRef } from "react";+import { 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 {+export interface ModeTab {id: string;label: string;- config: StudioConfig;- catalog: StudioCatalog;+ href: string;}/** 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 }) {+function ModeTabs({ tabs, current }: { tabs: ModeTab[]; current: string }) {const [ref, fade] = useEdgeFade<HTMLDivElement>();const active = useRef<HTMLAnchorElement>(null);- // Keep the selected tab in view when the row scrolls.+ // Keep the selected tab in view when the row scrolls (only the row: the page stays put).useEffect(() => {- active.current?.scrollIntoView({ block: "nearest", inline: "nearest" });- }, [current]);+ const el = active.current;+ const row = ref.current;+ if (!el || !row) return;+ const left = el.offsetLeft - row.offsetLeft;+ if (left < row.scrollLeft || left + el.offsetWidth > row.scrollLeft + row.clientWidth) row.scrollLeft = left - 12;+ }, [current, ref]);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) => {+ {tabs.map((m) => {const on = m.id === current;return (<Linkkey={m.id}ref={on ? active : undefined}- href={`?mode=${m.id}`}+ href={m.href}replacescroll={false}aria-current={on ? "page" : undefined}@@ -52,21 +54,7 @@ function ModeTabs({ modes, current }: { modes: Mode[]; current: string }) {);}-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>- );+/** One mode of a hub (Audio, Video tools, Upscale): its studio with the hub's tabs. Each mode has its own path. */+export function ModeStudio({ tabs, current, config, catalog }: { tabs: ModeTab[]; current: string; config: StudioConfig; catalog: StudioCatalog }) {+ return <StudioPage config={config} catalog={catalog} tabs={<ModeTabs tabs={tabs} current={current} />} />;}diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsxindex 512c041a..f65228f6 100644--- a/src/components/studio/mode-switch-studio.tsx+++ b/src/components/studio/mode-switch-studio.tsx@@ -1,3 +1,6 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { Suspense } from "react";import {AUDIO_STUDIO,DIALOGUE_STUDIO,@@ -15,36 +18,56 @@ import {VOICE_CHANGE_STUDIO,} from "@/lib/studios";import { studioCatalog } from "@/lib/studio-catalog";-import { ModeStudio, type Mode } from "./mode-studio";+import { HUB_MODES, modeHref, type HubKind } from "@/lib/hubs";+import { ModeStudio } from "./mode-studio";+import type { StudioConfig } from "./studio-context";-const MODES = {- upscale: [- { id: "image", label: "Image", config: UPSCALE_STUDIO },- { id: "video", label: "Video", config: VIDEO_UPSCALE_STUDIO },- ],- audio: [- { id: "speech", label: "Speech", config: AUDIO_STUDIO },- { id: "dialogue", label: "Dialogue", config: DIALOGUE_STUDIO },- { id: "voice-change", label: "Voice change", config: VOICE_CHANGE_STUDIO },- { id: "translate", label: "Translate", config: TRANSLATE_STUDIO },- { id: "sfx", label: "Sound effects", config: SFX_STUDIO },- { id: "music", label: "Music", config: MUSIC_STUDIO },- { id: "video", label: "Sound for video", config: FOLEY_STUDIO },- ],- "video-tools": [- { id: "matte", label: "Remove background", config: VIDEO_MATTE_STUDIO },- { id: "relight", label: "Relight", config: VIDEO_RELIGHT_STUDIO },- { id: "depth", label: "Depth map", config: VIDEO_DEPTH_STUDIO },- { id: "join", label: "Join clips", config: JOIN_CLIPS_STUDIO },- { id: "colors", label: "Match colors", config: VIDEO_COLOR_MATCH_STUDIO },- ],-} as const;+const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {+ upscale: { image: UPSCALE_STUDIO, video: VIDEO_UPSCALE_STUDIO },+ audio: {+ speech: AUDIO_STUDIO,+ dialogue: DIALOGUE_STUDIO,+ "voice-change": VOICE_CHANGE_STUDIO,+ translate: TRANSLATE_STUDIO,+ sfx: SFX_STUDIO,+ music: MUSIC_STUDIO,+ video: FOLEY_STUDIO,+ },+ "video-tools": {+ matte: VIDEO_MATTE_STUDIO,+ relight: VIDEO_RELIGHT_STUDIO,+ depth: VIDEO_DEPTH_STUDIO,+ join: JOIN_CLIPS_STUDIO,+ colors: VIDEO_COLOR_MATCH_STUDIO,+ },+};++const HUB_TITLE: Record<HubKind, string> = { upscale: "Upscale", audio: "Audio", "video-tools": "Video tools" };/**- * 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.+ * A hub of studios with one path per mode (Audio → /audio/music, Video tools, Upscale). Server+ * component: the page is prerendered with that mode's hero, tabs and composer, and ships only+ * that mode's models. `mode` omitted = the first mode (the hub's own URL).*/-export function ModeSwitchStudio({ kind }: { kind: keyof typeof MODES }) {- const modes: Mode[] = MODES[kind].map((m) => ({ id: m.id, label: m.label, config: m.config, catalog: studioCatalog(m.config) }));- return <ModeStudio modes={modes} />;+export function ModeSwitchStudio({ kind, mode }: { kind: HubKind; mode?: string }) {+ const current = mode ?? HUB_MODES[kind][0].id;+ const config = CONFIGS[kind][current];+ if (!config) notFound();+ const tabs = HUB_MODES[kind].map((m) => ({ id: m.id, label: m.label, href: modeHref(kind, m.id) }));+ return <ModeStudio key={current} tabs={tabs} current={current} config={config} catalog={studioCatalog(config)} />;+}++/** `generateStaticParams` for /<hub>/[mode]: every mode is prerendered. */+export function hubParams(kind: HubKind): { mode: string }[] {+ return HUB_MODES[kind].map((m) => ({ mode: m.id }));+}++export function hubMetadata(kind: HubKind, mode: string): Metadata {+ const m = HUB_MODES[kind].find((x) => x.id === mode);+ return { title: !m || m.id === HUB_MODES[kind][0].id ? HUB_TITLE[kind] : `${m.label} · ${HUB_TITLE[kind]}` };+}++/** The /<hub>/[mode] page body. */+export function HubModePage({ kind, params }: { kind: HubKind; params: Promise<{ mode: string }> }) {+ return <Suspense fallback={null}>{params.then(({ mode }) => <ModeSwitchStudio kind={kind} mode={mode} />)}</Suspense>;}diff --git a/src/components/studio/prompt-input.tsx b/src/components/studio/prompt-input.tsxindex 34e9249c..a885c777 100644--- a/src/components/studio/prompt-input.tsx+++ b/src/components/studio/prompt-input.tsx@@ -2,7 +2,7 @@import { AtSign, AudioLines, MapPin, Package, Palette, Plus, ScanFace } from "lucide-react";import Link from "next/link";-import { forwardRef, useImperativeHandle, useMemo, useRef, useState } from "react";+import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, 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";@@ -81,6 +81,24 @@ export const PromptInput = forwardRef<const syncCaret = () => setCaret(ta.current?.selectionStart ?? null);+ // Collapsed to one line (docked, not focused): show the start of the prompt, not wherever the caret was.+ useEffect(() => {+ if (!collapsed) return;+ if (ta.current) ta.current.scrollTop = 0;+ if (mirror.current) mirror.current.scrollTop = 0;+ }, [collapsed]);++ // Typed into before the page hydrated: keep those words (React would reset the field to the draft's value on its next update).+ const onChangeRef = useRef(onChange);+ useLayoutEffect(() => {+ onChangeRef.current = onChange;+ });+ useLayoutEffect(() => {+ const el = ta.current;+ if (el && el.value !== value) onChangeRef.current(el.value);+ // Mount only: afterwards the field and the draft move together.+ }, []); // eslint-disable-line react-hooks/exhaustive-deps+const insert = (el: StudioElement) => {if (!mention) return;const end = caret ?? value.length;@@ -129,12 +147,7 @@ export const PromptInput = forwardRef<}}onSelect={syncCaret}onClick={syncCaret}- 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;- }}+ onBlur={() => setTimeout(() => setCaret(null), 120)}onScroll={(e) => {if (mirror.current) mirror.current.scrollTop = e.currentTarget.scrollTop;}}diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsxindex 1f3a3c37..bd1a9531 100644--- a/src/components/studio/studio-context.tsx+++ b/src/components/studio/studio-context.tsx@@ -36,6 +36,8 @@ export interface StudioConfig {sketchAutoOpen?: "mask" | "draw";/** Appended to the user prompt on submit (e.g. identity lock for characters). */promptSuffix?: string;+ /** Optional slots of which one is needed (Lipsync: a portrait or a video): Generate names the group. */+ anyOf?: SlotKey[][];}export interface Draft {diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsxindex d17da159..db0a7d36 100644--- a/src/components/studio/studio-page.tsx+++ b/src/components/studio/studio-page.tsx@@ -1,13 +1,15 @@"use client";import { ArrowUp, Loader2, Upload } from "lucide-react";+import dynamic from "next/dynamic";import { useSearchParams } from "next/navigation";-import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { nanoid } from "nanoid";import { toast } from "sonner";import { SidebarTrigger } from "@/components/ui/sidebar";import type { Generation, MediaKind, ModelDef, Preset } from "@/lib/catalog/types";import { useEngine, useGenerations } from "@/lib/api";+import { handoffKey, mergeHandoff } from "@/lib/composer";import type { StudioCatalog } from "@/lib/studio-catalog";import { cn } from "@/lib/utils";import { ComposerBridgeCtx, useComposerBridge, type ComposerBridge } from "./attachments";@@ -16,7 +18,7 @@ import { Composer } from "./composer";import { EngineSwitch } from "./engine-switch";import { Feed } from "./feed";import type { SlotValue } from "./media-slot";-import { StudioProvider, useStudioActions, type Draft, type StudioConfig } from "./studio-context";+import { StudioProvider, useStudio, useStudioActions, type Draft, type StudioConfig } from "./studio-context";function kindOfUrl(url: string): MediaKind {if (/\.(mp4|webm|mov)(\?|$)/i.test(url)) return "video";@@ -151,6 +153,25 @@ function inView(id: string): boolean {const EMPTY: Generation[] = [];+/** The preset card (U23) is its own chunk: only app pages and studios with a motion or effect picked load it. */+const PresetHeader = dynamic(() => import("@/components/preset-header").then((m) => m.PresetHeader));++/** While a preset (app, camera motion, effect) is active and the feed is empty: what it does and what to add, above the composer. */+function ActivePresetHeader() {+ const { config, draft, setDraft } = useStudio();+ const catalog = useCatalog();+ const preset = draft.presetId ? catalog.getPreset(draft.presetId) : config.preset;+ if (!preset) return null;+ return (+ <PresetHeader+ preset={preset}+ className="mb-3"+ modelName={(id) => catalog.getModel(id)?.name}+ onClear={config.preset ? undefined : () => setDraft({ presetId: undefined, mix: undefined, presetStrength: undefined })}+ />+ );+}+/** 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();@@ -249,6 +270,7 @@ function StudioBody({ header, tabs }: { header?: React.ReactNode; tabs?: React.R</button></div>)}+ {!hasItems && <ActivePresetHeader />}<div data-composer className={cn("mx-auto w-full", hasItems ? "max-w-[800px]" : "max-w-[760px]")}><Composer docked={hasItems} /></div>@@ -297,46 +319,88 @@ interface StudioPageProps {initialPrompt?: string;}-type DraftProps = Omit<StudioPageProps, "catalog"> & { sp: URLSearchParams | null };+type DraftProps = Omit<StudioPageProps, "catalog">;++/** Reports the URL's hand-off params. It reads the URL, so it sits under its own Suspense: the static shell renders without it. */+function UrlParams({ onChange }: { onChange: (key: string) => void }) {+ const key = handoffKey(useSearchParams());+ // Layout effect: on a client navigation the prefilled draft is in place before the first paint.+ useLayoutEffect(() => onChange(key), [key, onChange]);+ return 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) {+/**+ * Applies the URL's hand-off params (`/video?image=…`) to the draft once they're known: right+ * after hydration on a direct visit (the static shell can't know them), or on the first render+ * of a client navigation. Fields the person already changed — a prompt typed before the page+ * hydrated — are kept. A later change of the params (Animate → Video while on Video) starts a+ * fresh draft instead.+ */+function HandoffSync({ startKey, start, build, ready, onNavigate }: { startKey: string; start: Draft; build: React.RefObject<(key: string) => Draft>; ready: boolean; onNavigate: (key: string) => void }) {+ const { setDraft } = useStudioActions();+ const [url, setUrl] = useState<string | null>(null);+ const applied = useRef({ key: startKey, ready, base: start, seen: false });+ useLayoutEffect(() => {+ if (url === null) return;+ const a = applied.current;+ if (a.seen && url !== a.key) return onNavigate(url);+ a.seen = true;+ if (url === a.key && ready === a.ready) return;+ const next = build.current(url);+ const base = a.base;+ setDraft((d) => mergeHandoff(base, d, next));+ applied.current = { key: url, ready, base: next, seen: true };+ }, [url, ready, build, setDraft, onNavigate]);+ return (+ <Suspense fallback={null}>+ <UrlParams onChange={setUrl} />+ </Suspense>+ );+}++/**+ * The studio. It renders the same tree in the static shell and after hydration (the URL is read+ * by HandoffSync alone), so the composer the shell painted is the one you type into: nothing+ * typed or focused before hydration is lost.+ */+function StudioDraft({ config, header, tabs, initialRefs, initialPrompt }: DraftProps) {const [engine] = useEngine();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 build = (key: string) => {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, catalog.ready]); // eslint-disable-line react-hooks/exhaustive-deps+ };+ const buildRef = useRef(build);+ useLayoutEffect(() => {+ buildRef.current = build;+ });+ // The draft the composer starts from: the defaults (the URL is unknown in the static shell), or+ // the hand-off params of a client navigation to new ones (a new epoch remounts the provider).+ const [start, setStart] = useState({ key: "", epoch: 0 });+ const initial = useMemo(() => build(start.key), [start, config]); // eslint-disable-line react-hooks/exhaustive-deps+ const onNavigate = useCallback((key: string) => setStart((s) => ({ key, epoch: s.epoch + 1 })), []);return (<ComposerBridgeCtx.Provider value={bridge}>- <StudioProvider key={`${key}|${catalog.ready}`} config={config} initial={initial}>+ <StudioProvider key={start.epoch} config={config} initial={initial}><StudioBody header={header} tabs={tabs} />+ <HandoffSync startKey={start.key} start={initial} build={buildRef} ready={catalog.ready} onNavigate={onNavigate} /></StudioProvider></ComposerBridgeCtx.Provider>);}-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.+ * A studio page: header, hero, composer and feed. Everything but the URL is in the static shell:+ * the title, the hero and a composer you can start typing into before the page hydrates. The+ * hand-off params (`?image=`, `?prompt=`…) are applied once known (HandoffSync).*/export function StudioPage({ catalog, ...props }: StudioPageProps) {return (<CatalogProvider catalog={catalog} config={props.config}>- <Suspense fallback={<StudioDraft {...props} sp={null} />}>- <StudioFromUrl {...props} />- </Suspense>+ <StudioDraft {...props} /></CatalogProvider>);}diff --git a/src/lib/composer.ts b/src/lib/composer.tsindex 71fe9452..e9572980 100644--- a/src/lib/composer.ts+++ b/src/lib/composer.ts@@ -112,9 +112,32 @@ export function slotMessage(label: string): string {type SlotValues = Partial<Record<InputSlot["key"], { ref: string; uploading?: boolean } | null>>;-/** The first required slot that's still empty (the one Generate should point at). */-export function firstMissingSlot(slots: InputSlot[], values: SlotValues): InputSlot | undefined {- return slots.find((s) => s.required && !values[s.key]?.ref && !values[s.key]?.uploading);+/** A missing input: one required slot, or (`group`) a set of optional slots of which one is needed ("a portrait or a video"). */+export type MissingSlot = InputSlot & { group?: InputSlot[] };++/**+ * The first input Generate is waiting for, in the order the tiles are shown: an empty required+ * slot, or a group from `anyOf` (studio config: "one of these") with none of its slots filled.+ * A group comes back as its first slot plus `group`, so Generate pulses that tile.+ */+export function firstMissingSlot(slots: InputSlot[], values: SlotValues, anyOf: InputSlot["key"][][] = []): MissingSlot | undefined {+ const filled = (k: InputSlot["key"]) => !!values[k]?.ref || !!values[k]?.uploading;+ const groups = anyOf.map((g) => slots.filter((s) => g.includes(s.key))).filter((g) => g.length > 0);+ for (const s of slots) {+ if (s.required && !filled(s.key)) return s;+ const group = groups.find((g) => g[0].key === s.key);+ if (group && !group.some((x) => filled(x.key))) return group.length > 1 ? { ...s, group } : s;+ }+ return undefined;+}++/** ["a portrait", "a video"] → "a portrait or a video"; three → "a, b or c". */+const orList = (xs: string[]) => (xs.length < 2 ? (xs[0] ?? "") : `${xs.slice(0, -1).join(", ")} or ${xs[xs.length - 1]}`);++/** "Add a portrait or a video" for a group, else the slot's own message. */+export function missingMessage(m: MissingSlot): string {+ if (!m.group || m.group.length < 2) return slotMessage(m.label);+ return `Add ${orList(m.group.map((s) => slotMessage(s.label).replace(/^Add /, "")))}`;}export interface Blocker {@@ -132,7 +155,7 @@ export function blockerFor(s: {loading?: string | null;model: boolean;engineError?: string | null;- missing?: InputSlot;+ missing?: MissingSlot;uploading: boolean;planError?: string | null;promptMissing: boolean;@@ -140,7 +163,7 @@ export function blockerFor(s: {if (s.loading) return { message: s.loading };if (!s.model) return { message: "Pick a model" };if (s.engineError) return { message: s.engineError };- if (s.missing) return { message: slotMessage(s.missing.label), slot: s.missing.key };+ if (s.missing) return { message: missingMessage(s.missing), slot: s.missing.key };if (s.uploading) return { message: "Uploading…" };if (s.planError) return { message: s.planError };if (s.promptMissing) return { message: "Write a prompt first" };@@ -211,13 +234,133 @@ export function replaceAttachment<T extends Attachment>(return null;}-/** Which kinds the "+" menu can take for this studio. */+/**+ * Where a batch of files would land, before any of them uploads: each file's index goes to+ * `placed` (it gets a slot or a reference tile) or `rejected` (no room: the references are full or+ * the model takes none). Placement is simulated in order, as `placeAttachment` does it for real.+ */+export function fitAttachments(+ state: AttachState,+ slots: InputSlot[],+ multiRef: { kind?: MediaKind } | undefined,+ refMax: number,+ kinds: MediaKind[],+): { placed: number[]; rejected: number[] } {+ let s = state;+ const placed: number[] = [];+ const rejected: number[] = [];+ kinds.forEach((kind, i) => {+ const next = placeAttachment(s, slots, multiRef, refMax, { id: `fit-${i}`, ref: "", preview: "", kind });+ if (!next) return void rejected.push(i);+ placed.push(i);+ s = { slots: next.slots ?? s.slots, refs: next.refs ?? s.refs };+ });+ return { placed, rejected };+}++/** What to tell someone whose attachment found no room ("This model takes up to 3 reference images"). */+export function noRoomMessage(refMax: number, kind: MediaKind = "image"): string {+ const noun = kind === "video" ? "clip" : kind === "audio" ? "audio file" : "reference image";+ if (refMax <= 0) return `This model doesn't take ${noun}s — pick another model to add one`;+ return `This model takes up to ${refMax} ${noun}${refMax === 1 ? "" : "s"}`;+}++/**+ * A drawing (inpaint mask, sketch, Wan-Move motion paths) belongs to the image it was drawn on:+ * when the image slot gets another image, or none, the drawing goes with it. Returns the patch+ * to apply with the new slots (the same slots when the image didn't change, e.g. its upload finished).+ */+export function onImageChange<T extends Attachment>(+ prev: { slots: Partial<Record<InputSlot["key"], T | null>>; params: GenParams },+ nextSlots: Partial<Record<InputSlot["key"], T | null>>,+): { slots: Partial<Record<InputSlot["key"], T | null>>; params?: GenParams } {+ const before = prev.slots.image ?? null;+ const after = nextSlots.image ?? null;+ const same = before === after || (!!before && !!after && ((!!before.id && before.id === after.id) || (!!before.ref && before.ref === after.ref)));+ if (same) return { slots: nextSlots };+ const slots = { ...nextSlots, mask: null, sketch: null };+ if (prev.params.extra?.motionPaths === undefined) return { slots };+ const extra = { ...prev.params.extra };+ delete extra.motionPaths;+ return { slots, params: { ...prev.params, extra: Object.keys(extra).length ? extra : undefined } };+}++/** Which kinds the "+" menu (and paste / drop) can take for this studio. Voice samples have their own picker. */export function acceptedKinds(slots: InputSlot[], multiRef?: { kind?: MediaKind }): MediaKind[] {const kinds = new Set<MediaKind>(slots.filter((s) => s.key !== "mask" && s.key !== "sketch" && s.key !== "voiceAudio" && s.key !== "voiceAudio2").map((s) => s.accept));if (multiRef) kinds.add(multiRef.kind ?? "image");return [...kinds];}+// ---------------------------------------------------------------------------+// Hand-off params ("/video?image=…") arriving after the first paint++/** The URL params a studio prefills its draft from; anything else in the query is ignored. */+export const HANDOFF_PARAMS = ["image", "ref", "video", "audio", "prompt", "preset", "model"] as const;++/** A stable key for the hand-off part of a query string ("" when there's none). */+export function handoffKey(search: string | URLSearchParams | null | undefined): string {+ const sp = typeof search === "string" || !search ? new URLSearchParams(search ?? "") : search;+ const out = new URLSearchParams();+ for (const k of HANDOFF_PARAMS) {+ const v = sp.get(k);+ if (v) out.set(k, v);+ }+ return out.toString();+}++export interface DraftShape {+ prompt: string;+ negativePrompt: string;+ modelId: string;+ params: GenParams;+ slots: Partial<Record<InputSlot["key"], Attachment | null>>;+ refs: Attachment[];+ presetId?: string;+ presetOptions: Record<string, string>;+ presetStrength?: number;+ mix?: { presetId: string; strength: number };+}++const same = (a: unknown, b: unknown) => a === b || JSON.stringify(a ?? null) === JSON.stringify(b ?? null);+const sameAttachment = (a: Attachment | null | undefined, b: Attachment | null | undefined) => (a ?? null) === (b ?? null) || (!!a && !!b && a.id === b.id && a.ref === b.ref);++/**+ * Apply a draft computed from hand-off params (`next`) to the live draft (`current`) without+ * undoing what the person already did: a field still equal to the draft the composer started+ * with (`base`) takes the hand-off value; a field they changed (typed a prompt before the page+ * hydrated, attached a photo) keeps theirs. Returns the patch.+ */+export function mergeHandoff<D extends DraftShape>(base: D, current: D, next: D): Partial<D> {+ const patch: Partial<D> = {};+ if (current.prompt === base.prompt && current.prompt !== next.prompt) patch.prompt = next.prompt;+ if (current.negativePrompt === base.negativePrompt && current.negativePrompt !== next.negativePrompt) patch.negativePrompt = next.negativePrompt;+ if (current.modelId === base.modelId && same(current.params, base.params) && (current.modelId !== next.modelId || !same(current.params, next.params))) {+ patch.modelId = next.modelId;+ patch.params = next.params;+ }+ const keys = new Set([...Object.keys(base.slots), ...Object.keys(current.slots), ...Object.keys(next.slots)] as InputSlot["key"][]);+ let slotsChanged = false;+ const slots = { ...current.slots };+ for (const k of keys) {+ if (sameAttachment(current.slots[k], base.slots[k]) && !sameAttachment(current.slots[k], next.slots[k])) {+ slots[k] = next.slots[k] ?? null;+ slotsChanged = true;+ }+ }+ if (slotsChanged) patch.slots = slots as D["slots"];+ const refsUntouched = current.refs === base.refs || (current.refs.length === base.refs.length && current.refs.every((r, i) => sameAttachment(r, base.refs[i])));+ if (refsUntouched && (next.refs.length || current.refs.length)) patch.refs = next.refs as D["refs"];+ const preset = (d: D) => [d.presetId, d.presetOptions, d.presetStrength, d.mix];+ if (same(preset(current), preset(base)) && !same(preset(current), preset(next))) {+ patch.presetId = next.presetId;+ patch.presetOptions = next.presetOptions;+ patch.presetStrength = next.presetStrength;+ patch.mix = next.mix;+ }+ return patch;+}+// ---------------------------------------------------------------------------// Models for a studio and the picker's groups@@ -225,9 +368,13 @@ export function filterModels(models: ModelDef[], opts: { kind?: MediaKind; ops?:return models.filter((m) => !m.hidden && (!opts.kind || m.kind === opts.kind) && (!opts.ops || m.routes.some((r) => opts.ops!.includes(r.op))));}-/** "Best for this studio": the studio's default first, then top picks, then what's new. */-export function bestForStudio(models: ModelDef[], engine: Engine, defaultId: string | undefined, max = 4): ModelDef[] {- const pool = models.filter((m) => m.engine === engine);+/**+ * "Best for this studio": the studio's default first, then top picks, then what's new — among+ * the models that do the studio's main operation (`op`, e.g. text-to-image in the Image studio),+ * so a single-purpose tool (garment try-on) never ranks above a general model.+ */+export function bestForStudio(models: ModelDef[], engine: Engine, defaultId: string | undefined, max = 4, op?: Operation): ModelDef[] {+ const pool = models.filter((m) => m.engine === engine && (!op || m.id === defaultId || m.routes.some((r) => r.op === op)));const score = (m: ModelDef) => (m.id === defaultId ? 0 : m.badges?.includes("top") ? 1 : m.badges?.includes("new") ? 2 : 9);return pool.map((m, i) => [m, score(m), i] as const)diff --git a/src/lib/hubs.ts b/src/lib/hubs.tsnew file mode 100644index 00000000..36e2e1c8--- /dev/null+++ b/src/lib/hubs.ts@@ -0,0 +1,36 @@+/**+ * Studio hubs: Audio, Video tools and Upscale group several studios, one path per mode+ * (/audio/music, /video-tools/join, /upscale/video). The hub's own path is its first mode.+ * Pure data (client and server). Old `/audio?mode=music` links redirect in next.config.ts.+ */+export type HubKind = "audio" | "video-tools" | "upscale";++export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {+ upscale: [+ { id: "image", label: "Image" },+ { id: "video", label: "Video" },+ ],+ audio: [+ { id: "speech", label: "Speech" },+ { id: "dialogue", label: "Dialogue" },+ { id: "voice-change", label: "Voice change" },+ { id: "translate", label: "Translate" },+ { id: "sfx", label: "Sound effects" },+ { id: "music", label: "Music" },+ { id: "video", label: "Sound for video" },+ ],+ "video-tools": [+ { id: "matte", label: "Remove background" },+ { id: "relight", label: "Relight" },+ { id: "depth", label: "Depth map" },+ { id: "join", label: "Join clips" },+ { id: "colors", label: "Match colors" },+ ],+};++/** The URL of one mode: the hub itself for the first one, else /<hub>/<mode>. */+export function modeHref(kind: HubKind, mode: string, query?: Record<string, string>): string {+ const path = HUB_MODES[kind][0].id === mode ? `/${kind}` : `/${kind}/${mode}`;+ const q = query ? new URLSearchParams(query).toString() : "";+ return q ? `${path}?${q}` : path;+}diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex fd90e806..f4a4e714 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -88,14 +88,14 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =out.push(file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });link("reframe", "Reframe", `/reframe?video=${q(o.url)}`);link("lipsync", "Lipsync", `/lipsync?video=${q(o.url)}`);- link("upscale", "Upscale", `/upscale?video=${q(o.url)}`);- link("add-sound", "Add sound", `/audio?video=${q(o.url)}`);+ link("upscale", "Upscale", `/upscale/video?video=${q(o.url)}`);+ link("add-sound", "Add sound", `/audio/video?video=${q(o.url)}`);link("grade", "Color grade", `/color-grade?video=${q(o.url)}`);break;case "audio":link("lipsync", "Lipsync", `/lipsync?audio=${q(o.url)}`, "primary");out.push(file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });- link("voice-change", "Change voice", `/audio?mode=voice-change&audio=${q(o.url)}`);+ link("voice-change", "Change voice", `/audio/voice-change?audio=${q(o.url)}`);break;case "text":out.push({ id: "copy-text", label: "Copy", placement: "primary" }, file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });diff --git a/src/lib/studios.ts b/src/lib/studios.tsindex 75e1f871..189eb6fe 100644--- a/src/lib/studios.ts+++ b/src/lib/studios.ts@@ -95,6 +95,7 @@ export const LIPSYNC_STUDIO: StudioConfig = {{ key: "video", label: "Video", accept: "video", hint: "To re-sync an existing clip" },{ key: "audio", label: "Voice", accept: "audio", required: true },],+ anyOf: [["image", "video"]],defaultModels: { cloud: "kling-avatar-2", open: "oss-infinitetalk" },promptOptional: true,};@@ -228,13 +229,8 @@ export function appStudio(preset: Preset): StudioConfig {feature: `app:${preset.id}`,title: preset.name,hero: preset.description,- subtitle: [- preset.cloud ? `Cloud: ${getModel(preset.cloud.modelId)?.name}` : "No cloud version yet",- preset.open ? `Open source: ${getModel(preset.open.modelId)?.name}` : "No open-source version yet",- preset.parity,- ]- .filter(Boolean)- .join(" · "),+ // The models it runs on are in the preset card's Details popover (PresetHeader).+ subtitle: preset.parity,placeholder: preset.promptPlaceholder ?? "Add details (optional)",kind,ops,diff --git a/tests/composer-fixes.test.ts b/tests/composer-fixes.test.tsnew file mode 100644index 00000000..2539e21f--- /dev/null+++ b/tests/composer-fixes.test.ts@@ -0,0 +1,184 @@+import { describe, expect, it } from "vitest";+import { getModel, MODELS } from "@/lib/catalog";+import type { Generation, InputSlot } from "@/lib/catalog/types";+import {+ acceptedKinds,+ bestForStudio,+ blockerFor,+ filterModels,+ firstMissingSlot,+ fitAttachments,+ handoffKey,+ mergeHandoff,+ noRoomMessage,+ onImageChange,+ type Attachment,+ type DraftShape,+} from "@/lib/composer";+import { HUB_MODES, modeHref } from "@/lib/hubs";+import { outputActions } from "@/lib/output-actions";+import { AUDIO_STUDIO, IMAGE_STUDIO, LIPSYNC_STUDIO, VIDEO_STUDIO, VOICE_CHANGE_STUDIO } from "@/lib/studios";++const att = (id: string, kind: Attachment["kind"] = "image", extra: Partial<Attachment> = {}): Attachment => ({ id, ref: `/api/files/${id}`, preview: `/api/files/${id}`, kind, ...extra });++const draft = (p: Partial<DraftShape> = {}): DraftShape => ({+ prompt: "",+ negativePrompt: "",+ modelId: "kling-2-5-turbo",+ params: { duration: 5 },+ slots: {},+ refs: [],+ presetOptions: {},+ ...p,+});++describe("a drawing belongs to its image", () => {+ const motion = { motionPaths: { paths: [[0, 0, 1, 1]] }, cfg: 3 };+ const drawn = { slots: { image: att("a"), mask: att("m"), sketch: att("s") }, params: { extra: motion } };++ it("drops the mask, the sketch and the motion paths when the image is replaced or removed", () => {+ const replaced = onImageChange(drawn, { ...drawn.slots, image: att("b") });+ expect(replaced.slots).toMatchObject({ image: { id: "b" }, mask: null, sketch: null });+ expect(replaced.params?.extra).toEqual({ cfg: 3 });+ const removed = onImageChange(drawn, { ...drawn.slots, image: null });+ expect(removed.slots).toMatchObject({ image: null, mask: null, sketch: null });+ });++ it("keeps the drawing when the same image finishes uploading (same id) or another slot changes", () => {+ const uploading = { ...drawn, slots: { ...drawn.slots, image: att("a", "image", { ref: "", uploading: true }) } };+ expect(onImageChange(uploading, { ...uploading.slots, image: att("a") })).toEqual({ slots: { ...uploading.slots, image: att("a") } });+ const other = onImageChange(drawn, { ...drawn.slots, endImage: att("e") });+ expect(other.slots.mask).toEqual(att("m"));+ expect(other.params).toBeUndefined();+ });++ it("leaves params alone when there were no motion paths", () => {+ const r = onImageChange({ slots: { image: att("a") }, params: { duration: 5 } }, { image: att("b") });+ expect(r.params).toBeUndefined();+ expect(r.slots).toMatchObject({ mask: null, sketch: null });+ });+});++describe("room for attachments", () => {+ const imageSlot: InputSlot[] = [{ key: "image", label: "Image", accept: "image" }];++ it("rejects files with nowhere to go before they upload", () => {+ // Image studio, a model that takes one reference: the second paste has no room.+ expect(fitAttachments({ slots: {}, refs: [] }, [], { kind: "image" }, 1, ["image", "image"])).toEqual({ placed: [0], rejected: [1] });+ expect(fitAttachments({ slots: {}, refs: [att("r")] }, [], { kind: "image" }, 1, ["image"])).toEqual({ placed: [], rejected: [0] });+ // A slot of the kind is always a place (the new file replaces the old one).+ expect(fitAttachments({ slots: { image: att("a") }, refs: [] }, imageSlot, undefined, 0, ["image", "video"])).toEqual({ placed: [0], rejected: [1] });+ });++ it("says why", () => {+ expect(noRoomMessage(3)).toBe("This model takes up to 3 reference images");+ expect(noRoomMessage(1)).toBe("This model takes up to 1 reference image");+ expect(noRoomMessage(0)).toMatch(/doesn't take reference images/);+ expect(noRoomMessage(4, "video")).toBe("This model takes up to 4 clips");+ });++ it("offers the + menu only what paste and drop accept (voice samples have their own picker)", () => {+ expect(acceptedKinds(VOICE_CHANGE_STUDIO.slots)).not.toContain(undefined);+ expect(acceptedKinds([{ key: "voiceAudio", label: "Voice", accept: "audio" }])).toEqual([]);+ });+});++describe("one of several inputs", () => {+ const slots = LIPSYNC_STUDIO.slots;+ const anyOf = LIPSYNC_STUDIO.anyOf;++ it("names the group, in tile order, and points at its first tile", () => {+ const voiceOnly = { audio: { ref: "/a.wav" } };+ const m = firstMissingSlot(slots, voiceOnly, anyOf);+ expect(m?.key).toBe("image");+ expect(blockerFor({ model: true, missing: m, uploading: false, promptMissing: false })).toEqual({ message: "Add a portrait or a video", slot: "image" });+ // Nothing attached: the group comes first (it's the first tile).+ expect(blockerFor({ model: true, missing: firstMissingSlot(slots, {}, anyOf), uploading: false, promptMissing: false })?.message).toBe("Add a portrait or a video");+ });++ it("is satisfied by any member, then asks for the next required slot", () => {+ expect(firstMissingSlot(slots, { video: { ref: "/v.mp4" } }, anyOf)?.key).toBe("audio");+ expect(firstMissingSlot(slots, { image: { ref: "", uploading: true } }, anyOf)?.key).toBe("audio");+ expect(firstMissingSlot(slots, { image: { ref: "/p.png" }, audio: { ref: "/a.wav" } }, anyOf)).toBeUndefined();+ });++ it("ignores groups whose slots the studio doesn't show (a preset's own inputs)", () => {+ expect(firstMissingSlot([{ key: "audio", label: "Voice", accept: "audio", required: true }], {}, anyOf)?.key).toBe("audio");+ });+});++describe("hand-off params after the first paint", () => {+ it("keys only the params a studio prefills from", () => {+ expect(handoffKey("?mode=music&prompt=hi&tab=x&image=%2Fa.png")).toBe("image=%2Fa.png&prompt=hi");+ expect(handoffKey("")).toBe("");+ expect(handoffKey(new URLSearchParams("ref=1&image=2"))).toBe(handoffKey("image=2&ref=1"));+ });++ it("fills what the person hasn't touched and keeps what they typed before hydration", () => {+ const base = draft();+ const typed = { ...base, prompt: "early words" };+ const next = draft({ prompt: "from the link", slots: { image: att("h") }, modelId: "veo-3-1", params: { duration: 8 } });+ const patch = mergeHandoff(base, typed, next);+ expect(patch.prompt).toBeUndefined();+ expect(patch.slots?.image).toEqual(att("h"));+ expect(patch).toMatchObject({ modelId: "veo-3-1", params: { duration: 8 } });+ });++ it("keeps an attachment or a model the person already chose", () => {+ const base = draft();+ const current = { ...base, slots: { image: att("mine") }, modelId: "seedance-2-5", params: { duration: 5 } };+ const patch = mergeHandoff(base, current, draft({ slots: { image: att("h") }, prompt: "go" }));+ expect(patch.slots).toBeUndefined();+ expect(patch.modelId).toBeUndefined();+ expect(patch.prompt).toBe("go");+ });++ it("changes nothing when the link carries nothing new", () => {+ const base = draft();+ expect(mergeHandoff(base, base, draft())).toEqual({});+ });++ it("takes the hand-off references and preset when untouched", () => {+ const base = draft();+ const next = draft({ refs: [att("r")], presetId: "motion-zoom-in" });+ expect(mergeHandoff(base, base, next)).toMatchObject({ refs: [att("r")], presetId: "motion-zoom-in" });+ const withRef = { ...base, refs: [att("mine")] };+ expect(mergeHandoff(base, withRef, next).refs).toBeUndefined();+ });+});++describe("best for this studio", () => {+ it("ranks only models that do the studio's main operation (no try-on in the Image studio)", () => {+ const models = filterModels(MODELS, { kind: IMAGE_STUDIO.kind, ops: IMAGE_STUDIO.ops });+ const def = getModel(IMAGE_STUDIO.defaultModels.cloud)!;+ const best = bestForStudio(models, "cloud", def.id, 4, def.routes[0].op);+ expect(best[0].id).toBe(def.id);+ for (const m of best) expect(m.routes.some((r) => r.op === "t2i")).toBe(true);+ });++ it("uses each studio's default model's first operation as its main one", () => {+ for (const s of [IMAGE_STUDIO, VIDEO_STUDIO, AUDIO_STUDIO, LIPSYNC_STUDIO]) {+ const op = getModel(s.defaultModels.cloud)?.routes[0]?.op;+ expect(op && s.ops.includes(op)).toBe(true);+ }+ });+});++describe("studio hubs", () => {+ it("give every mode its own path; the hub's path is its first mode", () => {+ expect(modeHref("audio", "speech")).toBe("/audio");+ expect(modeHref("audio", "music")).toBe("/audio/music");+ expect(modeHref("upscale", "video", { video: "/v.mp4" })).toBe("/upscale/video?video=%2Fv.mp4");+ for (const modes of Object.values(HUB_MODES)) expect(new Set(modes.map((m) => m.id)).size).toBe(modes.length);+ });++ it("hand results to the mode's own page (prerendered with the right studio)", () => {+ const base = { batchId: null, presetId: null, engine: "cloud", provider: "mock", status: "succeeded", progress: 1, message: null, prompt: "", error: null, costUsd: 0, favorite: false, createdAt: 1, updatedAt: 1, completedAt: null, deletedAt: null, folderId: null } as const;+ const video = { ...base, id: "v1", feature: "video", modelId: "kling-2-5-turbo", op: "t2v", kind: "video", request: { feature: "video", modelId: "kling-2-5-turbo", prompt: "" }, outputs: [{ url: "/api/files/o/v.mp4", kind: "video" }] } as unknown as Generation;+ const audio = { ...base, id: "a1", feature: "audio", modelId: "elevenlabs-v3", op: "tts", kind: "audio", request: { feature: "audio", modelId: "elevenlabs-v3", prompt: "" }, outputs: [{ url: "/api/files/o/a.mp3", kind: "audio" }] } as unknown as Generation;+ const href = (g: Generation, id: string) => outputActions(g, 0).find((a) => a.id === id)?.href;+ expect(href(video, "upscale")).toMatch(/^\/upscale\/video\?video=/);+ expect(href(video, "add-sound")).toMatch(/^\/audio\/video\?video=/);+ expect(href(audio, "voice-change")).toMatch(/^\/audio\/voice-change\?audio=/);+ });+});