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
Shorts, Mixed Media: real restyle prices, segments that stay on the sound, model clip limits
Claude0917e07e13ee
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.pyindex d8f81a87..b1d9c22d 100644--- a/scripts/gen-cloud-models.py+++ b/scripts/gen-cloud-models.py@@ -280,7 +280,9 @@ model("gemini-omni-flash", "Gemini Omni Flash 1.1", "Google", "gemini-omni", "vi"Google's any-to-video model with reference and edit modes",[("t2v", "google/gemini-omni-flash/v1.1/text-to-video"), ("i2v", "google/gemini-omni-flash/v1.1/image-to-video"),("ref2v", "google/gemini-omni-flash/v1.1/reference-to-video"), ("v2v", "google/gemini-omni-flash/v1.1/edit")],- badges=["new", "audio"], defaults={"aspectRatio": "16:9"})+ badges=["new", "audio"], defaults={"aspectRatio": "16:9", "resolution": "720p"},+ # Billed per second of output by resolution (research: $0.03 at 360p, $0.10 at 720p, $0.15 at 1080p, $0.30 at 4K).+ pricing=("second", 0.1, "720p; 360p $0.03, 1080p $0.15, 4K $0.30", {"byResolution": {"360p": 0.03, "720p": 0.1, "1080p": 0.15, "4k": 0.3}}))model("wan-3", "Wan 3.0", "Alibaba Wan", "wan", "video", "Alibaba's newest video model with audio",[("t2v", "alibaba/wan-3.0/text-to-video"), ("i2v", "alibaba/wan-3.0/image-to-video", "fal", "+flf2v"), ("ref2v", "alibaba/wan-3.0/reference-to-video")],badges=["new", "audio"], defaults={"aspectRatio": "16:9", "duration": 5, "resolution": "1080p"})@@ -289,7 +291,9 @@ model("wan-3-prime", "Wan 3.0 Prime", "Alibaba Wan", "wan", "video", "Highest-fibadges=["pro", "audio"], defaults={"aspectRatio": "16:9", "duration": 5, "resolution": "1080p"})model("wan-2-7", "Wan 2.7", "Alibaba Wan", "wan", "video", "Hosted Wan with references and video edit",[("t2v", "fal-ai/wan/v2.7/text-to-video"), ("i2v", "fal-ai/wan/v2.7/image-to-video", "fal", "+flf2v"),- ("ref2v", "fal-ai/wan/v2.7/reference-to-video"), ("v2v", "fal-ai/wan/v2.7/edit-video"),+ # Its video edit's duration defaults to 0 = the input's length: never sent, so a restyle stays as long as its+ # clip (the model's 5 s default would cut it short and drift off the original sound).+ ("ref2v", "fal-ai/wan/v2.7/reference-to-video"), ("v2v", "fal-ai/wan/v2.7/edit-video", "fal", {"drop": ["duration"]}),# Replicate's Wan 2.7 video edit keeps the source's length and framing: its own ratio/duration enums would widen the fal routes'.("v2v", "wan-video/wan-2.7-videoedit", "replicate", {"drop": ["aspectRatio", "duration"]})],badges=["audio"], defaults={"aspectRatio": "16:9", "duration": 5, "resolution": "1080p"})@@ -340,7 +344,7 @@ model("wan-vace-reframe", "Wan VACE Reframe (hosted)", "Alibaba Wan", "wan", "vimodel("happy-horse-video-edit", "Happy Horse Video Edit", "Alibaba", "happy-horse", "video","Restyle or swap things in 3–60 s clips, with up to 5 reference images",[("v2v", "alibaba/happy-horse/video-edit")], badges=["new", "audio"], defaults={"resolution": "720p"},- pricing=("second", 0.28, "720p, input + output seconds; 1080p $0.56"),+ pricing=("second", 0.28, "720p, input + output seconds; 1080p $0.56", {"byResolution": {"720p": 0.28, "1080p": 0.56}, "inputSeconds": True}),controls=[("audio_setting", "Audio")])model("lucy-edit-pro", "Lucy Edit Pro", "Decart", "lucy", "video","Text-guided video edits that keep motion and identity — outfits, props, styles",@@ -968,8 +972,11 @@ for m in M:opts.update(m["options"])pricing = Noneif m["pricing"]:- u, usd, *note = m["pricing"]- pricing = {"unit": u, "usd": usd, **({"note": note[0]} if note else {})}+ u, usd, *rest = m["pricing"]+ # Optional: a note, then extra Pricing fields (byResolution, inputSeconds).+ note = [x for x in rest if isinstance(x, str)]+ extra = next((x for x in rest if isinstance(x, dict)), {})+ pricing = {"unit": u, "usd": usd, **({"note": note[0]} if note else {}), **extra}elif first_e:pricing = parse_price(first_e)d = {diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsxindex 2826ff56..8c72cc3e 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -1,17 +1,48 @@"use client";-import { ArrowDown, Cloud, Cpu, Download, ImageIcon, Info, Loader2, Search, Sparkles, Wand2, X } from "lucide-react";+import {+ ArrowDown,+ Cloud,+ Cpu,+ Download,+ ImageIcon,+ Info,+ Loader2,+ Search,+ Sparkles,+ Wand2,+ X,+} from "lucide-react";import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";import { SidebarTrigger } from "@/components/ui/sidebar";import { EngineSwitch } from "@/components/studio/engine-switch";import { MediaThumb } from "@/components/studio/result-media";-import { VideoTrimmer, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";+import {+ VideoTrimmer,+ type VideoTrimmerHandle,+} from "@/components/studio/video-trimmer";import { LookCard } from "@/components/shorts/preset-card";import { useSubmitGuard } from "@/components/shorts/hooks";-import { ClipBar, ClipDrop, costText, Field, Segmented, tabKeys } from "@/components/shorts/ui";-import { clipDuration, useSourceClip } from "@/components/shorts/use-source-clip";+import {+ ClipBar,+ ClipDrop,+ costText,+ Field,+ Segmented,+ tabKeys,+} from "@/components/shorts/ui";+import {+ clipDuration,+ useSourceClip,+} from "@/components/shorts/use-source-clip";import { uploadFile, useEngine } from "@/lib/api";import {clampFps,@@ -22,17 +53,24 @@ import {mixedFrames,mixedPreview,mixedRangeProblem,+ nearestResolution,type MixedPreset,type MixedResolution,type MixedValues,} from "@/lib/catalog/mixed-media";+import { clipLengthProblem } from "@/lib/catalog/shorts";import type { RestyleModelInfo } from "@/lib/catalog/shorts-models";import type { Engine, Generation } from "@/lib/catalog/types";import { downloadHref, downloadName } from "@/lib/library";import type { TrimRange } from "@/lib/trim-range";import { cn } from "@/lib/utils";import { MixedHistory } from "./history";-import { useMixedActions, useMixedEstimate, useWatchedGeneration, type MixedBody } from "./hooks";+import {+ useMixedActions,+ useMixedEstimate,+ useWatchedGeneration,+ type MixedBody,+} from "./hooks";import { AdvancedSettings, loadSaved } from "./settings";type Tab = "presets" | "history" | "how";@@ -43,14 +81,30 @@ const TABS: { id: Tab; label: string }[] = [];const HOW = [- { step: "Choose a preset", text: "Browse 33 mixed-media looks — sketch, comic, paper, neon, marble — and pick the one that fits your clip." },- { step: "Upload your video", text: "Add a clip and trim it to up to 10 seconds. It needs at least 4 frames per second." },- { step: "Customize settings", text: "Each preset has its own colours, materials and intensity. Save them per preset; they stay in this browser." },- { step: "Generate & preview", text: "Make one preview frame first to check the look, then render the whole video. Frames are restyled at the rate you pick." },+ {+ step: "Choose a preset",+ text: "Browse 33 mixed-media looks — sketch, comic, paper, neon, marble — and pick the one that fits your clip.",+ },+ {+ step: "Upload your video",+ text: "Add a clip and trim it to up to 10 seconds. It needs at least 4 frames per second.",+ },+ {+ step: "Customize settings",+ text: "Each preset has its own colours, materials and intensity. Save them per preset; they stay in this browser.",+ },+ {+ step: "Generate & preview",+ text: "Make one preview frame first to check the look, then render the whole video. The open engine restyles it frame by frame at the rate you pick; cloud models restyle it as smooth video.",+ },];/** Mixed Media: pick a look, add a ≤10 s clip, tune the settings, preview one frame, render. */-export function MixedStudio({ models }: { models: Record<Engine, RestyleModelInfo[]> }) {+export function MixedStudio({+ models,+}: {+ models: Record<Engine, RestyleModelInfo[]>;+}) {const [tab, setTab] = useState<Tab>("presets");const [engine, setEngine] = useEngine();useEffect(() => {@@ -69,8 +123,15 @@ export function MixedStudio({ models }: { models: Record<Engine, RestyleModelInf<div className="flex min-h-svh min-w-0 flex-col"><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="sr-only font-heading text-[22px] leading-none sm:not-sr-only sm:truncate">Mixed Media</h1>- <div role="tablist" aria-label="Mixed Media" onKeyDown={tabKeys} className="fade-x scrollbar-none flex h-8 min-w-0 items-center overflow-x-auto rounded-full bg-muted p-0.5 sm:ml-4">+ <h1 className="sr-only font-heading text-[22px] leading-none sm:not-sr-only sm:truncate">+ Mixed Media+ </h1>+ <div+ role="tablist"+ aria-label="Mixed Media"+ onKeyDown={tabKeys}+ className="fade-x scrollbar-none flex h-8 min-w-0 items-center overflow-x-auto rounded-full bg-muted p-0.5 sm:ml-4"+ >{TABS.map((t) => (<buttonkey={t.id}@@ -79,7 +140,10 @@ export function MixedStudio({ models }: { models: Record<Engine, RestyleModelInfaria-selected={tab === t.id}tabIndex={tab === t.id ? 0 : -1}onClick={() => pick(t.id)}- className={cn("h-7 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground", tab === t.id && "bg-background text-foreground shadow-soft")}+ className={cn(+ "h-7 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground",+ tab === t.id && "bg-background text-foreground shadow-soft",+ )}>{t.label}</button>@@ -97,10 +161,16 @@ export function MixedStudio({ models }: { models: Record<Engine, RestyleModelInf) : (<><div className="mx-auto max-w-[720px] pt-8 pb-6 text-center sm:pt-12">- <p className="text-[12px] font-semibold tracking-[0.14em] text-brand-text uppercase">No prompts, just vibe</p>- <h2 className="mt-2 font-heading text-display text-balance">Turn any video into mixed-media art</h2>+ <p className="text-[12px] font-semibold tracking-[0.14em] text-brand-text uppercase">+ No prompts, just vibe+ </p>+ <h2 className="mt-2 font-heading text-display text-balance">+ Turn any video into mixed-media art+ </h2><p className="mx-auto mt-2 max-w-[560px] text-body text-pretty text-muted-foreground">- 33 looks, each with its own colours and materials. Every frame is restyled at the frame rate you choose — preview one frame first.+ 33 looks, each with its own colours and materials. Preview one+ frame first, then render the clip — frame by frame at the rate+ you choose on the open engine.</p></div><Workspace engine={engine} models={models[engine]} />@@ -114,11 +184,15 @@ export function MixedStudio({ models }: { models: Record<Engine, RestyleModelInffunction How({ onStart }: { onStart: () => void }) {return (<div className="mx-auto max-w-[920px] pt-10">- <h2 className="text-center font-heading text-[34px] leading-tight">How it works</h2>+ <h2 className="text-center font-heading text-[34px] leading-tight">+ How it works+ </h2><ol className="mt-8 grid gap-3 sm:grid-cols-2">{HOW.map((h, i) => (<li key={h.step} className="rounded-2xl border bg-background p-5">- <span className="grid size-7 place-items-center rounded-full bg-primary text-[13px] font-semibold text-primary-foreground">{i + 1}</span>+ <span className="grid size-7 place-items-center rounded-full bg-primary text-[13px] font-semibold text-primary-foreground">+ {i + 1}+ </span><p className="mt-3 text-[15px] font-semibold">{h.step}</p><p className="mt-1 text-[14px] text-muted-foreground">{h.text}</p></li>@@ -127,12 +201,19 @@ function How({ onStart }: { onStart: () => void }) {<div className="mt-6 rounded-2xl bg-muted/60 p-5 text-[13px] text-muted-foreground"><p className="font-medium text-foreground">Cost</p><p className="mt-1">- A render is counted in frames: seconds × frame rate, rounded down (10 s at 8 FPS = 80 frames). On the open engine every frame runs on your GPU for free; cloud- models are priced by the model (per second or per video) and the estimate shows before you generate.+ On the open engine a render is counted in frames: seconds × frame+ rate, rounded down (10 s at 8 FPS = 80 frames), and every frame runs+ on your GPU for free. Cloud models restyle the clip as video and are+ priced by the model (per second or per video); the estimate shows+ before you generate.</p></div><div className="mt-6 text-center">- <button type="button" onClick={onStart} className="h-10 rounded-full bg-primary px-5 text-[14px] font-medium text-primary-foreground hover:bg-primary/90">+ <button+ type="button"+ onClick={onStart}+ className="h-10 rounded-full bg-primary px-5 text-[14px] font-medium text-primary-foreground hover:bg-primary/90"+ >Choose a preset</button></div>@@ -140,19 +221,35 @@ function How({ onStart }: { onStart: () => void }) {);}-function Workspace({ engine, models }: { engine: Engine; models: RestyleModelInfo[] }) {+function Workspace({+ engine,+ models,+}: {+ engine: Engine;+ models: RestyleModelInfo[];+}) {const [presetId, setPresetId] = useState<string | null>(null);const preset = MIXED_PRESETS.find((p) => p.id === presetId) ?? null;const [values, setValues] = useState<MixedValues>({});const [q, setQ] = useState("");const query = useDeferredValue(q.trim().toLowerCase());- const list = useMemo(() => MIXED_PRESETS.filter((p) => !query || `${p.name} ${p.description}`.toLowerCase().includes(query)), [query]);+ const list = useMemo(+ () =>+ MIXED_PRESETS.filter(+ (p) =>+ !query || `${p.name} ${p.description}`.toLowerCase().includes(query),+ ),+ [query],+ );const panel = useRef<HTMLElement>(null);const [panelVisible, setPanelVisible] = useState(false);useEffect(() => {const el = panel.current;if (!el) return;- const io = new IntersectionObserver(([e]) => setPanelVisible(e.isIntersecting), { rootMargin: "0px 0px -30% 0px" });+ const io = new IntersectionObserver(+ ([e]) => setPanelVisible(e.isIntersecting),+ { rootMargin: "0px 0px -30% 0px" },+ );io.observe(el);return () => io.disconnect();}, []);@@ -179,8 +276,13 @@ function Workspace({ engine, models }: { engine: Engine; models: RestyleModelInf<div className="grid min-w-0 gap-6 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-start"><section aria-labelledby="mm-presets" className="min-w-0 space-y-4"><div className="flex flex-col gap-3 sm:flex-row sm:items-center">- <h3 id="mm-presets" className="flex items-center gap-2 text-[15px] font-semibold">- <span className="grid size-6 place-items-center rounded-full bg-primary text-[12px] text-primary-foreground">1</span>+ <h3+ id="mm-presets"+ className="flex items-center gap-2 text-[15px] font-semibold"+ >+ <span className="grid size-6 place-items-center rounded-full bg-primary text-[12px] text-primary-foreground">+ 1+ </span>Choose a preset</h3><div className="relative w-full sm:ml-auto sm:w-64">@@ -194,7 +296,12 @@ function Workspace({ engine, models }: { engine: Engine; models: RestyleModelInfclassName="h-9 w-full rounded-full border bg-background pr-9 pl-9 text-[14px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-4 focus:ring-brand-faint [&::-webkit-search-cancel-button]:hidden"/>{q && (- <button type="button" onClick={() => setQ("")} aria-label="Clear search" className="absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-accent">+ <button+ type="button"+ onClick={() => setQ("")}+ aria-label="Clear search"+ className="absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-accent"+ ><X className="size-3.5" /></button>)}@@ -203,30 +310,62 @@ function Workspace({ engine, models }: { engine: Engine; models: RestyleModelInf{list.length ? (<div className="grid grid-cols-2 gap-1 sm:grid-cols-3 xl:grid-cols-4">{list.map((p) => (- <LookCard key={p.id} id={p.id} name={p.name} description={p.description} preview={mixedPreview(p)} hue={p.hue} selected={presetId === p.id} onSelect={select} />+ <LookCard+ key={p.id}+ id={p.id}+ name={p.name}+ description={p.description}+ preview={mixedPreview(p)}+ hue={p.hue}+ selected={presetId === p.id}+ onSelect={select}+ />))}</div>) : (<div className="py-12 text-center">- <p className="font-heading text-[22px]">No presets match “{q.trim()}”</p>- <button type="button" onClick={() => setQ("")} className="mt-3 h-8 rounded-full border px-3 text-[13px] font-medium hover:bg-accent">+ <p className="font-heading text-[22px]">+ No presets match “{q.trim()}”+ </p>+ <button+ type="button"+ onClick={() => setQ("")}+ className="mt-3 h-8 rounded-full border px-3 text-[13px] font-medium hover:bg-accent"+ >Clear search</button></div>)}</section>- <aside ref={panel} id="mm-editor" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-16 lg:max-h-[calc(100svh-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl">- <Editor engine={engine} models={models} preset={preset} values={values} setValues={setValues} />+ <aside+ ref={panel}+ id="mm-editor"+ className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-16 lg:max-h-[calc(100svh-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl"+ >+ <Editor+ engine={engine}+ models={models}+ preset={preset}+ values={values}+ setValues={setValues}+ /></aside>{preset && !panelVisible && (<div className="fixed inset-x-3 bottom-[max(0.75rem,env(safe-area-inset-bottom))] z-30 lg:hidden"><buttontype="button"- onClick={() => panel.current?.scrollIntoView({ behavior: "smooth", block: "start" })}+ onClick={() =>+ panel.current?.scrollIntoView({+ behavior: "smooth",+ block: "start",+ })+ }className="flex h-12 w-full items-center gap-2 rounded-full bg-foreground px-4 text-[14px] font-medium text-background shadow-strong"><Sparkles className="size-4 shrink-0" />- <span className="min-w-0 flex-1 truncate text-left">{preset.name}</span>+ <span className="min-w-0 flex-1 truncate text-left">+ {preset.name}+ </span><span className="flex shrink-0 items-center gap-1">Add a clip <ArrowDown className="size-4" /></span>@@ -258,16 +397,22 @@ function Editor({// Hand-off: /mixed-media?video=/api/files/… (a result or a Library clip).useEffect(() => {const video = new URLSearchParams(window.location.search).get("video");- if (video?.startsWith("/api/files/")) source.adopt(video, video.split("/").pop());+ if (video?.startsWith("/api/files/"))+ source.adopt(video, video.split("/").pop());// Once, on arrival.// eslint-disable-next-line react-hooks/exhaustive-deps}, []);const trimmer = useRef<VideoTrimmerHandle>(null);const [range, setRange] = useState<TrimRange | null>(null);- const [fpsChoice, setFpsChoice] = useState<FpsChoice>(MIXED.defaultFps as number);+ const [fpsChoice, setFpsChoice] = useState<FpsChoice>(+ MIXED.defaultFps as number,+ );const [manual, setManual] = useState<number>(MIXED.defaultFps);const [resolution, setResolution] = useState<MixedResolution>("1K");- const [pickedModel, setModel] = useState<Record<Engine, string>>({ cloud: "", open: "" });+ const [pickedModel, setModel] = useState<Record<Engine, string>>({+ cloud: "",+ open: "",+ });const modelId = pickedModel[engine] || models[0]?.id;const model = models.find((m) => m.id === modelId);const [previewId, setPreviewId] = useState<string | null>(null);@@ -280,14 +425,58 @@ function Editor({const duration = clipDuration(clip);const sourceFps = clip?.info?.fps;- const fps = clampFps(fpsChoice === "manual" ? manual : fpsChoice, sourceFps);- // A choice above the clip's own frame rate drops to the highest allowed ("Uploaded video has 6 FPS").+ // A choice above the clip's own frame rate drops to the highest one allowed ("Uploaded video has 6 FPS" → 4).const choices = fpsChoices(sourceFps);+ const allowedFps = choices.filter((c) => !c.disabled);+ const fpsShown: FpsChoice =+ typeof fpsChoice === "number" &&+ choices.find((c) => c.fps === fpsChoice)?.disabled+ ? (allowedFps.at(-1)?.fps ?? "manual")+ : fpsChoice;+ const fps = clampFps(fpsShown === "manual" ? manual : fpsShown, sourceFps);const mmRange = range ? { start: range.startTime, end: range.endTime } : null;- const problem = mmRange ? mixedRangeProblem(mmRange, duration, sourceFps) : null;- const frames = mmRange ? mixedFrames(mmRange.end - mmRange.start, fps) : 0;- const previewImage = preview?.status === "succeeded" ? preview.outputs.find((o) => o.kind === "image") : undefined;- const anchor = engine === "cloud" && model?.image && previewImage && !anchorOff ? previewImage.url : undefined;+ const seconds = mmRange ? mmRange.end - mmRange.start : 0;+ const problem = mmRange+ ? mixedRangeProblem(mmRange, duration, sourceFps)+ : null;+ const frames = mmRange ? mixedFrames(seconds, fps) : 0;+ // Cloud models restyle the cut as video: the frame rate is the open engine's, and the resolution+ // is the model's own setting nearest to 1K / 2K / 4K (choices that land on the same one are off).+ const cloud = engine === "cloud";+ const lengthIssue = (m: RestyleModelInfo) =>+ cloud && seconds ? clipLengthProblem(m, seconds) : null;+ const resOptions = MIXED.resolutions.map((r, i) => {+ const at = cloud ? nearestResolution(model?.resolutions, r) : undefined;+ const prev =+ i > 0 && cloud+ ? nearestResolution(model?.resolutions, MIXED.resolutions[i - 1])+ : undefined;+ return {+ value: r,+ label: r,+ hint: at,+ disabled: cloud && !!at && at === prev,+ title: cloud && at === prev ? `${model?.name} renders up to ${at}` : at,+ };+ });+ const showResolution =+ !cloud || resOptions.some((o) => o.hint && !o.disabled && o.value !== "1K");+ const resShown: MixedResolution = resOptions.find(+ (o) => o.value === resolution,+ )?.disabled+ ? ([...resOptions].reverse().find((o) => !o.disabled)?.value ?? "1K")+ : resolution;+ const modelRes = cloud+ ? nearestResolution(model?.resolutions, resShown)+ : undefined;+ const previewImage =+ preview?.status === "succeeded"+ ? preview.outputs.find((o) => o.kind === "image")+ : undefined;+ const anchor =+ engine === "cloud" && model?.image && previewImage && !anchorOff+ ? previewImage.url+ : undefined;const body: MixedBody | null =preset && mmRange && !problem@@ -295,10 +484,15 @@ function Editor({engine,presetId: preset.id,values,- source: { url: clip?.url ?? "/api/files/placeholder.mp4", name: clip?.name, duration, fps: sourceFps },+ source: {+ url: clip?.url ?? "/api/files/placeholder.mp4",+ name: clip?.name,+ duration,+ fps: sourceFps,+ },range: mmRange,fps,- resolution,+ resolution: resShown,modelId,...(anchor ? { anchor } : {}),}@@ -325,13 +519,15 @@ function Editor({? "Reading the clip…": problem? problem- : clip.uploading- ? clip.progress < 1- ? `Uploading… ${Math.round(clip.progress * 100)}%`- : "Reading the clip…"- : estimate.error- ? (estimate.error as Error).message- : null;+ : model && lengthIssue(model)+ ? `${lengthIssue(model)} — select more, or pick another model`+ : clip.uploading+ ? clip.progress < 1+ ? `Uploading… ${Math.round(clip.progress * 100)}%`+ : "Reading the clip…"+ : estimate.error+ ? (estimate.error as Error).message+ : null;// One preview and one render per click: a second click while one is on its way does nothing,// and the server answers a repeated request id with what the first one started.@@ -339,7 +535,8 @@ function Editor({const renderGuard = useSubmitGuard();const previewBusy = actions.preview.isPending || grabbing;const makePreview = () => {- if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });+ if (blocker || !body)+ return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });if (previewBusy) return;void previewGuard(JSON.stringify(body), async (requestId) => {let frameUrl: string | undefined;@@ -347,25 +544,41 @@ function Editor({setGrabbing(true);try {const blob = await trimmer.current?.grabFrame(range!.startTime);- if (!blob) throw new Error("This browser can't read frames of this clip — try an MP4 (H.264), or generate the full video");- frameUrl = (await uploadFile(new File([blob], "frame.jpg", { type: "image/jpeg" }))).url;+ if (!blob)+ throw new Error(+ "This browser can't read frames of this clip — try an MP4 (H.264), or generate the full video",+ );+ frameUrl = (+ await uploadFile(+ new File([blob], "frame.jpg", { type: "image/jpeg" }),+ )+ ).url;} finally {setGrabbing(false);}}- const g = await actions.preview.mutateAsync({ ...body, frameUrl, requestId });+ const g = await actions.preview.mutateAsync({+ ...body,+ frameUrl,+ requestId,+ });setPreviewId(g.id);}).catch((e: Error) => toast.error(e.message));};const generate = () => {- if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });+ if (blocker || !body)+ return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });if (actions.render.isPending) return;- void renderGuard(JSON.stringify(body), (requestId) => actions.render.mutateAsync({ ...body, requestId }))+ void renderGuard(JSON.stringify(body), (requestId) =>+ actions.render.mutateAsync({ ...body, requestId }),+ ).then((r) => {if (!r) return;setRenderId(r.final.id);- toast("Rendering your video", { description: "It shows up in History too." });+ toast("Rendering your video", {+ description: "It shows up in History too.",+ });}).catch((e: Error) => toast.error(e.message));};@@ -376,7 +589,10 @@ function Editor({<Sparkles className="mt-0.5 size-4 shrink-0 text-brand-text" />{preset ? (<span className="min-w-0">- <span className="font-medium">{preset.name}</span> <span className="text-muted-foreground">· {preset.description}</span>+ <span className="font-medium">{preset.name}</span>{" "}+ <span className="text-muted-foreground">+ · {preset.description}+ </span></span>) : (<span className="text-muted-foreground">Pick a preset to start</span>@@ -422,39 +638,90 @@ function Editor({)}</Field>- <Field label="Frame rate" hint={sourceFps ? `Uploaded video has ${Math.round(sourceFps)} FPS` : "8 FPS is the classic stop-motion look"}>- <Segmented<FpsChoice>+ {!cloud && (+ <Fieldlabel="Frame rate"- value={fpsChoice}- onChange={setFpsChoice}- options={[- ...choices.map((c) => ({ value: c.fps as FpsChoice, label: String(c.fps), disabled: c.disabled, title: c.disabled ? "Above the clip's own frame rate" : `${c.fps} FPS` })),- { value: "manual" as FpsChoice, label: "Manual" },- ]}- />- {fpsChoice === "manual" && (- <label className="flex items-center gap-2 text-[12px] text-muted-foreground">- Choose frames manually- <input- type="number"- min={MIXED.manualFps.min}- max={Math.min(MIXED.manualFps.max, sourceFps ? Math.floor(sourceFps) : MIXED.manualFps.max)}- value={manual}- onChange={(e) => setManual(Number(e.target.value) || MIXED.manualFps.min)}- aria-label="Frames per second"- className="h-7 w-16 rounded-md border bg-background px-2 font-mono text-[12px] text-foreground outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint"- />- FPS- </label>- )}- {fps !== (fpsChoice === "manual" ? manual : fpsChoice) && <p className="text-[12px] text-warning">Using {fps} FPS — the clip itself has no more frames than that.</p>}- </Field>+ hint={+ sourceFps+ ? `Uploaded video has ${Math.round(sourceFps)} FPS`+ : "8 FPS is the classic stop-motion look"+ }+ >+ <Segmented<FpsChoice>+ label="Frame rate"+ value={fpsShown}+ onChange={setFpsChoice}+ options={[+ ...choices.map((c) => ({+ value: c.fps as FpsChoice,+ label: String(c.fps),+ disabled: c.disabled,+ title: c.disabled+ ? "Above the clip's own frame rate"+ : `${c.fps} FPS`,+ })),+ { value: "manual" as FpsChoice, label: "Manual" },+ ]}+ />+ {fpsShown === "manual" && (+ <label className="flex items-center gap-2 text-[12px] text-muted-foreground">+ Choose frames manually+ <input+ type="number"+ min={MIXED.manualFps.min}+ max={Math.min(+ MIXED.manualFps.max,+ sourceFps ? Math.floor(sourceFps) : MIXED.manualFps.max,+ )}+ value={manual}+ onChange={(e) =>+ setManual(Number(e.target.value) || MIXED.manualFps.min)+ }+ aria-label="Frames per second"+ className="h-7 w-16 rounded-md border bg-background px-2 font-mono text-[12px] text-foreground outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint"+ />+ FPS+ </label>+ )}+ {fps !== (fpsShown === "manual" ? manual : fpsShown) && (+ <p className="text-[12px] text-warning">+ Using {fps} FPS — the clip itself has no more frames than that.+ </p>+ )}+ {fpsShown !== fpsChoice && (+ <p className="text-[12px] text-muted-foreground">+ Using {fps} FPS — {fpsChoice} is above the clip's own frame+ rate.+ </p>+ )}+ </Field>+ )}- <Field label="Resolution">- <Segmented<MixedResolution> label="Resolution" value={resolution} onChange={setResolution} options={MIXED.resolutions.map((r) => ({ value: r, label: r }))} />- </Field>+ {showResolution && (+ <Field+ label="Resolution"+ hint={+ cloud && modelRes+ ? `${model?.name} renders at ${modelRes}`+ : undefined+ }+ >+ <Segmented<MixedResolution>+ label="Resolution"+ value={resShown}+ onChange={setResolution}+ options={resOptions}+ />+ </Field>+ )}- {preset && <AdvancedSettings preset={preset} values={values} onChange={setValues} />}+ {preset && (+ <AdvancedSettings+ preset={preset}+ values={values}+ onChange={setValues}+ />+ )}<Fieldlabel="Model"@@ -471,57 +738,100 @@ function Editor({}>{models.length > 1 ? (- <Select value={modelId} onValueChange={(v) => setModel((m) => ({ ...m, [engine]: v }))}>+ <Select+ value={modelId}+ onValueChange={(v) => setModel((m) => ({ ...m, [engine]: v }))}+ ><SelectTrigger className="w-full" aria-label="Model"><SelectValue><span className="flex min-w-0 items-center gap-2"><span className="truncate">{model?.name}</span>- <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{model?.price}</span>+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">+ {model?.price}+ </span></span></SelectValue></SelectTrigger><SelectContent>- {models.map((m) => (- <SelectItem key={m.id} value={m.id}>- <span className="flex min-w-0 items-center gap-2">- <span className="truncate">{m.name}</span>- <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{m.price}</span>- </span>- </SelectItem>- ))}+ {models.map((m) => {+ const issue = lengthIssue(m);+ return (+ <SelectItem+ key={m.id}+ value={m.id}+ disabled={!!issue && m.id !== modelId}+ >+ <span className="flex min-w-0 flex-col">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate">{m.name}</span>+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">+ {m.price}+ </span>+ </span>+ {issue && (+ <span className="text-[11px] text-muted-foreground">+ {issue}+ </span>+ )}+ </span>+ </SelectItem>+ );+ })}</SelectContent></Select>) : (<div className="rounded-lg border px-3 py-2 text-[13px]">- <span className="font-medium">{model?.name ?? "—"}</span> <span className="text-muted-foreground">· {model?.price}</span>+ <span className="font-medium">{model?.name ?? "—"}</span>{" "}+ <span className="text-muted-foreground">· {model?.price}</span></div>)}- {model && <p className="text-[12px] leading-snug text-muted-foreground">{model.tagline}</p>}+ {model && (+ <p className="text-[12px] leading-snug text-muted-foreground">+ {model.tagline}+ </p>+ )}</Field><div className="space-y-2 rounded-xl border p-3"><div className="flex items-center justify-between gap-2"><span className="text-[13px] font-medium">Preview frame</span>- <span className="font-mono text-[12px] text-muted-foreground tabular-nums">Preview costs: {est ? costText({ costUsd: est.previewUsd, demo: est.demo }, engine) : "—"}</span>+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">+ Preview costs:{" "}+ {est+ ? costText({ costUsd: est.previewUsd, demo: est.demo }, engine)+ : "—"}+ </span></div>- <p className="text-[12px] text-muted-foreground">Generate one frame with your current settings before creating the full video.</p>+ <p className="text-[12px] text-muted-foreground">+ Generate one frame with your current settings before creating the full+ video.+ </p>{preview && (<div className="relative mx-auto aspect-video w-full max-w-[320px] overflow-hidden rounded-lg bg-muted">{preview.status === "succeeded" && preview.outputs[0] ? (<MediaThumb output={preview.outputs[0]} fit />) : preview.status === "failed" || preview.status === "canceled" ? (- <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">{preview.error ?? "Canceled"}</div>+ <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">+ {preview.error ?? "Canceled"}+ </div>) : (<div className="skeleton-sweep grid size-full animate-skeleton place-items-center">- <span className="shimmer-text animate-shimmer-text text-[12px] font-medium">Restyling one frame…</span>+ <span className="shimmer-text animate-shimmer-text text-[12px] font-medium">+ Restyling one frame…+ </span></div>)}</div>)}{anchor && (<p className="flex items-center gap-1.5 text-[12px] text-brand-text">- <Wand2 className="size-3.5 shrink-0" /> {model?.name} follows this frame for the whole video- <button type="button" onClick={() => setAnchorOff(true)} className="ml-auto text-muted-foreground underline-offset-2 hover:underline">+ <Wand2 className="size-3.5 shrink-0" /> {model?.name} follows this+ frame for the whole video+ <button+ type="button"+ onClick={() => setAnchorOff(true)}+ className="ml-auto text-muted-foreground underline-offset-2 hover:underline"+ >Don't use it</button></p>@@ -533,24 +843,46 @@ function Editor({aria-disabled={!!blocker || previewBusy}className={cn("flex h-9 w-full items-center justify-center gap-2 rounded-full border text-[13px] font-medium",- blocker ? "text-subtle-foreground" : "bg-background hover:bg-accent",+ blocker+ ? "text-subtle-foreground"+ : "bg-background hover:bg-accent",)}>- {previewBusy ? <Loader2 className="size-4 animate-spin" /> : <ImageIcon className="size-4" />}- {preview ? "Generate another preview frame" : "Generate preview frame"}+ {previewBusy ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <ImageIcon className="size-4" />+ )}+ {preview+ ? "Generate another preview frame"+ : "Generate preview frame"}</button></div><div className="space-y-3 border-t pt-4"><div className="flex items-baseline justify-between gap-2">- <span className="text-[13px] text-muted-foreground">{frames ? `${frames} frames · ${fps} FPS` : "Estimate"}</span>- <span className="flex items-center gap-1.5 font-mono text-[13px] font-medium tabular-nums" aria-live="polite">- {estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" />}+ <span className="text-[13px] text-muted-foreground">+ {!mmRange+ ? "Estimate"+ : cloud+ ? `${seconds.toFixed(1)} s${modelRes ? ` · ${modelRes}` : ""}`+ : `${frames} frames · ${fps} FPS`}+ </span>+ <span+ className="flex items-center gap-1.5 font-mono text-[13px] font-medium tabular-nums"+ aria-live="polite"+ >+ {estimate.isFetching && (+ <Loader2 className="size-3 animate-spin text-muted-foreground" />+ )}{body ? costText(est, engine) : "—"}</span></div>{est?.notes.map((n) => (- <p key={n} className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground">+ <p+ key={n}+ className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground"+ ><Info className="mt-0.5 size-3.5 shrink-0" />{n}</p>@@ -563,14 +895,23 @@ function Editor({aria-describedby={blocker ? "mm-blocker" : undefined}className={cn("flex h-11 w-full items-center justify-center gap-2 rounded-full text-[14px] font-medium transition-colors",- blocker ? "bg-muted text-subtle-foreground" : "bg-primary text-primary-foreground hover:bg-primary/90",+ blocker+ ? "bg-muted text-subtle-foreground"+ : "bg-primary text-primary-foreground hover:bg-primary/90",)}>- {actions.render.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}+ {actions.render.isPending ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <Sparkles className="size-4" />+ )}Generate video</button>{blocker && (- <p id="mm-blocker" className="text-center text-[12px] text-muted-foreground">+ <p+ id="mm-blocker"+ className="text-center text-[12px] text-muted-foreground"+ >{blocker}</p>)}@@ -581,23 +922,40 @@ function Editor({}function LatestRender({ g }: { g: Generation }) {- const out = g.status === "succeeded" ? g.outputs.find((o) => o.kind === "video") : undefined;+ const out =+ g.status === "succeeded"+ ? g.outputs.find((o) => o.kind === "video")+ : undefined;return (<div className="space-y-2 rounded-xl bg-muted/50 p-3" aria-live="polite"><p className="text-[13px] font-medium">Your video</p><div className="relative mx-auto aspect-video w-full overflow-hidden rounded-lg bg-muted">{out ? (- <video src={out.url} controls playsInline preload="metadata" className="size-full bg-black object-contain" />+ <video+ src={out.url}+ controls+ playsInline+ preload="metadata"+ className="size-full bg-black object-contain"+ />) : g.status === "failed" || g.status === "canceled" ? (- <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">{g.error ?? "Canceled"}</div>+ <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">+ {g.error ?? "Canceled"}+ </div>) : (<div className="skeleton-sweep grid size-full animate-skeleton place-items-center">- <span className="shimmer-text animate-shimmer-text text-[12px] font-medium">{g.message ?? "Rendering…"}</span>+ <span className="shimmer-text animate-shimmer-text text-[12px] font-medium">+ {g.message ?? "Rendering…"}+ </span></div>)}</div>{out && (- <a href={downloadHref(out.url, downloadName(g, out, 0))} download={downloadName(g, out, 0)} className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent">+ <a+ href={downloadHref(out.url, downloadName(g, out, 0))}+ download={downloadName(g, out, 0)}+ className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent"+ ><Download className="size-3.5" /> Download</a>)}diff --git a/src/components/shorts/ui.tsx b/src/components/shorts/ui.tsxindex d15d102d..4ebe0550 100644--- a/src/components/shorts/ui.tsx+++ b/src/components/shorts/ui.tsx@@ -23,6 +23,9 @@ export function Segmented<T extends string | number>({onChange: (v: T) => void;className?: string;}) {+ // The Tab stop is the checked option, or the first one that can be picked when it's turned off+ // (a disabled button can't take focus, and the whole group would be skipped).+ const stop = options.some((o) => o.value === value && !o.disabled) ? value : options.find((o) => !o.disabled)?.value;return (<div role="radiogroup" aria-label={label} onKeyDown={radioKeys} className={cn("flex w-full rounded-full bg-muted p-0.5", className)}>{options.map((o) => (@@ -31,7 +34,7 @@ export function Segmented<T extends string | number>({type="button"role="radio"aria-checked={value === o.value}- tabIndex={radioTab(value === o.value)}+ tabIndex={radioTab(stop === o.value)}disabled={o.disabled}title={o.title}onClick={() => onChange(o.value)}diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.tsindex 547e1516..03aa6158 100644--- a/src/lib/catalog/cloud-models.generated.ts+++ b/src/lib/catalog/cloud-models.generated.ts@@ -4466,11 +4466,19 @@ export const CLOUD_MODELS: ModelDef[] = ["audio"],"defaults": {- "aspectRatio": "16:9"+ "aspectRatio": "16:9",+ "resolution": "720p"},"pricing": {"unit": "second",- "usd": 0.03+ "usd": 0.1,+ "note": "720p; 360p $0.03, 1080p $0.15, 4K $0.30",+ "byResolution": {+ "360p": 0.03,+ "720p": 0.1,+ "1080p": 0.15,+ "4k": 0.3+ }}},{@@ -4775,11 +4783,7 @@ export const CLOUD_MODELS: ModelDef[] = ["video": "video_url","seed": "seed","aspectRatio": "aspect_ratio",- "resolution": "resolution",- "duration": {- "key": "duration",- "type": "number"- }+ "resolution": "resolution"}},{@@ -5977,7 +5981,12 @@ export const CLOUD_MODELS: ModelDef[] = ["pricing": {"unit": "second","usd": 0.28,- "note": "720p, input + output seconds; 1080p $0.56"+ "note": "720p, input + output seconds; 1080p $0.56",+ "byResolution": {+ "720p": 0.28,+ "1080p": 0.56+ },+ "inputSeconds": true}},{diff --git a/src/lib/catalog/mixed-media.ts b/src/lib/catalog/mixed-media.tsindex 9ee2fe2c..2e1e12a3 100644--- a/src/lib/catalog/mixed-media.ts+++ b/src/lib/catalog/mixed-media.ts@@ -510,7 +510,16 @@ export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: stop: "v2v",prompt: prompts.frame,inputs: { video: input.source.url },- params: { startTime: input.range.start, endTime: input.range.end, fps: input.fps, aspectRatio: "auto", resolution: input.resolution, ...seed, extra: { denoise: denoiseFor(input.values) } },+ // frames: exactly floor(seconds × fps), as the page counts them (the graph's own count would add one).+ params: {+ startTime: input.range.start,+ endTime: input.range.end,+ fps: input.fps,+ aspectRatio: "auto",+ resolution: input.resolution,+ ...seed,+ extra: { denoise: denoiseFor(input.values), frames: mixedFrames(input.range.end - input.range.start, input.fps) },+ },},},],@@ -534,7 +543,8 @@ export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: stprompt: prompts.video,inputs: input.anchor ? { images: [input.anchor] } : undefined,params: {- duration: Math.max(1, Math.round(input.range.end - input.range.start)),+ // The cut's exact length (what per-second prices count); no restyle route is sent a length, each keeps its clip's.+ duration: Math.round((input.range.end - input.range.start) * 1000) / 1000,generateAudio: false,...(input.modelResolution ? { resolution: input.modelResolution } : {}),...seed,diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.tsindex 32e7eb4e..90cc382e 100644--- a/src/lib/catalog/plan.ts+++ b/src/lib/catalog/plan.ts@@ -319,10 +319,12 @@ export function estimateCost(model: ModelDef, params: GenParams, jobs = 1): numbif (model.engine === "open" || !model.pricing) return model.engine === "open" ? 0 : null;const p = model.pricing;const n = params.numOutputs ?? 1;- let per = p.usd;- if (p.unit === "image") per = p.usd * n;- if (p.unit === "second") per = p.usd * (params.duration ?? model.defaults?.duration ?? 5);- if (p.unit === "minute") per = (p.usd * (params.duration ?? 60)) / 60;+ const res = params.resolution ?? model.defaults?.resolution;+ const usd = (res && p.byResolution && (p.byResolution[res] ?? p.byResolution[res.toLowerCase()])) || p.usd;+ let per = usd;+ if (p.unit === "image") per = usd * n;+ if (p.unit === "second") per = usd * (params.duration ?? model.defaults?.duration ?? 5) * (p.inputSeconds ? 2 : 1);+ if (p.unit === "minute") per = (usd * (params.duration ?? 60)) / 60;if (params.generateAudio === false && model.options.audio === true && p.note?.includes("audio-off-half")) per /= 2;return Math.round(per * jobs * 1000) / 1000;}diff --git a/src/lib/catalog/shorts-models.ts b/src/lib/catalog/shorts-models.tsindex 29654e54..989ebc7b 100644--- a/src/lib/catalog/shorts-models.ts+++ b/src/lib/catalog/shorts-models.ts@@ -35,6 +35,23 @@ export function reframes(modelId: string): boolean {return routes.length > 0 && routes.every((r) => r.map?.aspectRatio);}+/**+ * How long a clip each restyle model takes (docs/research/paid-model-apis-3.md, "Input windows"):+ * a cut outside it is paid for and then refused by the provider.+ */+const SOURCE_SECONDS: Record<string, { min?: number; max?: number }> = {+ "kling-o3-4k-edit": { min: 3, max: 15 },+ "happy-horse-video-edit": { min: 3, max: 60 },+ "runway-aleph-2": { min: 2, max: 30 },+ "wan-2-7": { min: 2, max: 10 },+ // Higgsfield feeds Gemini Omni Flash ≤10 s segments.+ "gemini-omni-flash": { max: 10 },+};++export function sourceSeconds(modelId: string): { min?: number; max?: number } {+ return SOURCE_SECONDS[modelId] ?? {};+}+/** The cloud model's 720p setting, when it has one (Higgsfield renders Shorts at 720p). */export function resolutionFor(modelId: string): string | undefined {const m = getModel(modelId);@@ -55,13 +72,26 @@ export interface RestyleModelInfo {reframes: boolean;price: string | null;resolutions?: string[];+ /** Shortest and longest clip it takes, in seconds. */+ minSeconds?: number;+ maxSeconds?: number;+}++/** What one unit costs at the resolution the studios ask for, counting input seconds when the model bills them. */+export function unitPrice(m: ModelDef): number | null {+ const p = m.pricing;+ if (!p) return null;+ const res = resolutionFor(m.id) ?? m.defaults?.resolution;+ const usd = (res && p.byResolution?.[res]) || p.usd;+ return p.unit === "second" && p.inputSeconds ? usd * 2 : usd;}function priceLine(m: ModelDef): string | null {if (m.engine === "open") return "Free · your GPU";const p = m.pricing;- if (!p) return null;- const usd = p.usd < 0.1 ? p.usd.toFixed(3).replace(/0$/, "") : p.usd.toFixed(2);+ const v = unitPrice(m);+ if (!p || v === null) return null;+ const usd = v < 0.1 ? v.toFixed(3).replace(/0$/, "") : v.toFixed(2);return `$${usd} / ${p.unit === "second" ? "s" : p.unit}`;}@@ -82,6 +112,8 @@ export function modelInfos(ids: string[]): RestyleModelInfo[] {reframes: reframes(id),price: priceLine(m),...(m.options.resolutions ? { resolutions: m.options.resolutions } : {}),+ ...(sourceSeconds(id).min ? { minSeconds: sourceSeconds(id).min } : {}),+ ...(sourceSeconds(id).max ? { maxSeconds: sourceSeconds(id).max } : {}),},];});diff --git a/src/lib/catalog/shorts.ts b/src/lib/catalog/shorts.tsindex 7e0458b1..6b9285fb 100644--- a/src/lib/catalog/shorts.ts+++ b/src/lib/catalog/shorts.ts@@ -278,6 +278,13 @@ export interface ShortsSegment {const r3 = (n: number) => Math.round(n * 1000) / 1000;+/** Why a restyle model can't take a clip this long, or null ("Kling O3 4K Edit needs at least 3 s"). */+export function clipLengthProblem(m: { name: string; minSeconds?: number; maxSeconds?: number }, seconds: number): string | null {+ if (m.minSeconds && seconds < m.minSeconds - 0.01) return `${m.name} needs at least ${m.minSeconds} s`;+ if (m.maxSeconds && seconds > m.maxSeconds + 0.01) return `${m.name} takes up to ${m.maxSeconds} s`;+ return null;+}+/** What's wrong with a selection, or null. */export function rangeProblem(range: ShortsRange, duration?: number): string | null {const len = range.end - range.start;@@ -462,8 +469,9 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numbop: "v2v",prompt: restylePrompt(input.look, input.language, refs.length),inputs: refs.length ? { images: refs } : undefined,- // Whole seconds (Wan's edit takes 2–10); the price is per second of video.- params: { aspectRatio: input.aspectRatio, duration: Math.max(2, Math.round(seconds)), ...(input.resolution ? { resolution: input.resolution } : {}), ...seed },+ // The segment's exact length: what per-second prices count. No restyle route is sent a length+ // (each keeps its clip's), so the restyled segments add up to the selection and stay on the sound.+ params: { aspectRatio: input.aspectRatio, duration: r3(seconds), ...(input.resolution ? { resolution: input.resolution } : {}), ...seed },step: segLabel(seg, total, "restyle"),},after: [keys.cut],diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 7c8b75ef..839a8d1a 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -320,6 +320,10 @@ export interface Pricing {unit: "image" | "second" | "video" | "request" | "megapixel" | "minute";usd: number;note?: string;+ /** The price per unit at each resolution (params.resolution), when it differs (Gemini Omni Flash: 360p $0.03/s … 4K $0.30/s); `usd` is the default resolution's. */+ byResolution?: Record<string, number>;+ /** Billed on the input clip's seconds as well as the output's (Happy Horse video edit): a restyle costs about twice the clip's length. */+ inputSeconds?: boolean;}export interface ModelDef {diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.tsindex 1ab27f0e..44603bc6 100644--- a/src/server/mixed-media.ts+++ b/src/server/mixed-media.ts@@ -13,8 +13,8 @@ import {type MixedPlanInput,type MixedResolution,} from "@/lib/catalog/mixed-media";-import type { PlanStep } from "@/lib/catalog/shorts";-import { takesImage } from "@/lib/catalog/shorts-models";+import { clipLengthProblem, type PlanStep } from "@/lib/catalog/shorts";+import { sourceSeconds, takesImage } from "@/lib/catalog/shorts-models";import type { Engine, Generation } from "@/lib/catalog/types";import { createPipeline } from "./chains";import { previewChained } from "./generations";@@ -60,11 +60,20 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ iconst fps = clampFps(body.fps, sourceFps);const modelId = body.modelId && MIXED_MODELS[body.engine].includes(body.modelId) ? body.modelId : MIXED_MODELS[body.engine][0];const model = getModel(modelId);+ // A cut the model won't take is paid for, then refused: say so before anything runs.+ const len = body.range.end - body.range.start;+ const fits = (id: string) => clipLengthProblem({ name: getModel(id)?.name ?? id, minSeconds: sourceSeconds(id).min, maxSeconds: sourceSeconds(id).max }, len);+ const tooShort = body.engine === "cloud" ? fits(modelId) : null;+ if (tooShort) {+ const other = MIXED_MODELS.cloud.find((id) => !fits(id));+ const more = (sourceSeconds(modelId).min ?? 0) > len;+ throw new ShortsError(`${tooShort} — select ${more ? "more" : "less"}${other ? `, or pick ${getModel(other)?.name ?? other}` : ""}`);+ }const notes: string[] = [];const anchor = body.engine === "cloud" && body.anchor && takesImage(modelId) ? body.anchor : undefined;if (body.engine === "cloud") {if (body.anchor && !anchor) notes.push(`${model?.name} restyles from words only — the preview frame isn't sent`);- notes.push(`${model?.name} renders smooth motion at its own frame rate; the frame rate sets the frame count shown here and the open engine's sampling`);+ notes.push(`${model?.name} restyles the clip as smooth video — the open engine restyles it frame by frame at 4–24 FPS`);} else if (body.resolution !== "1K") notes.push("The open engine renders up to 1536 px on the long side");const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);return {diff --git a/src/server/shorts.ts b/src/server/shorts.tsindex b67141aa..4d420029 100644--- a/src/server/shorts.ts+++ b/src/server/shorts.ts@@ -1,12 +1,14 @@import "server-only";import { nanoid } from "nanoid";import { getModel } from "@/lib/catalog";-import { maxRefsFor, reframes, resolutionFor } from "@/lib/catalog/shorts-models";+import { maxRefsFor, reframes, resolutionFor, sourceSeconds } from "@/lib/catalog/shorts-models";import {+ clipLengthProblem,customPresetName,getShortsPreset,lookFromCustom,lookFromPreset,+ planSegments,planShorts,planStitch,planTake,@@ -234,6 +236,12 @@ async function planInput(body: ShortsBody, opts: { probe: boolean }): Promise<{const duration = info.duration ?? body.source.duration;const problem = rangeProblem(body.range, duration);if (problem) throw new ShortsError(problem);+ // Every segment has to be a clip the restyle model takes (a cut outside its window is paid for, then refused).+ const limits = sourceSeconds(modelId);+ const odd = planSegments(body.range, body.engine)+ .map((s) => clipLengthProblem({ name: getModel(modelId)?.name ?? modelId, minSeconds: limits.min, maxSeconds: limits.max }, s.end - s.start))+ .find(Boolean);+ if (odd) throw new ShortsError(`${odd} per segment — pick another model`);const name = fileTitle(body.source.name);return {info,diff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.tsindex 1275cfba..d6007892 100644--- a/tests/shorts-api.test.ts+++ b/tests/shorts-api.test.ts@@ -84,11 +84,11 @@ describe("Shorts sessions", () => {try {const est = await shorts.estimateShorts(body({ source: { url: clip, duration: 12 } }) as never);expect(est.demo).toBe(false);- // Gemini Omni Flash at $0.03/s: two 6 s segments, plus the cuts, the join and the soundtrack (≈ free).- expect(est.costUsd!).toBeGreaterThanOrEqual(0.36);- expect(est.costUsd!).toBeLessThan(0.4);- expect(est.perSegmentUsd!).toBeGreaterThanOrEqual(0.18);- expect(est.perSegmentUsd!).toBeLessThan(0.2);+ // Gemini Omni Flash at 720p ($0.10/s): two 6 s segments, plus the cuts, the join and the soundtrack (≈ free).+ expect(est.costUsd!).toBeGreaterThanOrEqual(1.2);+ expect(est.costUsd!).toBeLessThan(1.25);+ expect(est.perSegmentUsd!).toBeGreaterThanOrEqual(0.6);+ expect(est.perSegmentUsd!).toBeLessThan(0.62);expect(est.notes.join(" ")).toMatch(/keeps your clip's shape/);} finally {setSetting("falKey", "");@@ -322,6 +322,15 @@ describe("Mixed Media renders", () => {await settle(ra.final.id);});+ it("refuses a cut the cloud model won't take, before anything is paid for", async () => {+ const res = await mixedRoute.POST(json("POST", mm({ engine: "cloud", modelId: "kling-o3-4k-edit", range: { start: 2, end: 3.4 } })));+ expect(res.status).toBe(400);+ expect((await res.json()).error).toBe("Kling O3 4K Edit needs at least 3 s — select more, or pick LTX 2.3 Reference Restyle");+ // LTX takes it.+ const est = await mixed.estimateMixed(mm({ engine: "cloud", range: { start: 2, end: 3.4 } }) as never);+ expect(est.costUsd).toBe(0);+ });+it("asks for a grabbed frame before a cloud preview", async () => {const res = await mixedPreviewRoute.POST(json("POST", mm({ engine: "cloud" })));expect(res.status).toBe(400);diff --git a/tests/shorts-pricing.test.ts b/tests/shorts-pricing.test.tsnew file mode 100644index 00000000..ad43518c--- /dev/null+++ b/tests/shorts-pricing.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from "vitest";+import { getModel } from "@/lib/catalog";+import { MIXED_MODELS, MIXED_PRESETS, defaultValues, mixedFrames, planMixed, type MixedPlanInput } from "@/lib/catalog/mixed-media";+import { estimateCost, routesFor } from "@/lib/catalog/plan";+import { clipLengthProblem, lookFromPreset, planCloudSegments, planShorts, SHORTS_MODELS, SHORTS_PRESETS, type ShortsPlanInput } from "@/lib/catalog/shorts";+import { modelInfos, sourceSeconds, unitPrice } from "@/lib/catalog/shorts-models";++const shorts = (over: Partial<ShortsPlanInput> = {}): ShortsPlanInput => ({+ engine: "cloud",+ title: "Claymation · beach",+ source: { url: "/api/files/uploads/beach.mp4", duration: 47, hasAudio: true },+ range: { start: 0, end: 47 },+ look: lookFromPreset(SHORTS_PRESETS[0]),+ aspectRatio: "9:16",+ language: "auto",+ modelId: "gemini-omni-flash",+ maxRefs: 0,+ ...over,+});++describe("restyle prices", () => {+ it("prices Gemini Omni Flash by resolution: 720p (what Shorts asks for) is $0.10/s, not the 360p rate", () => {+ const gemini = getModel("gemini-omni-flash")!;+ expect(estimateCost(gemini, { resolution: "720p", duration: 10 })).toBeCloseTo(1.0);+ expect(estimateCost(gemini, { resolution: "360p", duration: 10 })).toBeCloseTo(0.3);+ expect(estimateCost(gemini, { resolution: "1080p", duration: 10 })).toBeCloseTo(1.5);+ expect(estimateCost(gemini, { resolution: "4k", duration: 10 })).toBeCloseTo(3.0);+ // No resolution asked: the model's default (720p).+ expect(estimateCost(gemini, { duration: 10 })).toBeCloseTo(1.0);+ expect(unitPrice(gemini)).toBeCloseTo(0.1);+ expect(modelInfos(["gemini-omni-flash"])[0].price).toBe("$0.10 / s");+ });++ it("counts the input seconds for Happy Horse (billed on input + output): about twice the clip", () => {+ const hh = getModel("happy-horse-video-edit")!;+ expect(estimateCost(hh, { resolution: "720p", duration: 10 })).toBeCloseTo(5.6);+ expect(estimateCost(hh, { resolution: "1080p", duration: 10 })).toBeCloseTo(11.2);+ expect(modelInfos(["happy-horse-video-edit"])[0].price).toBe("$0.56 / s");+ });++ it("never tells a restyle model a length: each keeps its clip's (Wan's 5 s default would cut segments short)", () => {+ for (const id of new Set([...SHORTS_MODELS.cloud, ...MIXED_MODELS.cloud])) {+ for (const r of routesFor(getModel(id)!, "v2v")) expect(r.map?.duration, `${id} ${r.endpoint}`).toBeUndefined();+ }+ });+});++describe("restyled segments stay in sync with the original sound", () => {+ it("asks for (and prices) every segment at its exact length, so they add up to the selection", () => {+ for (const [start, end] of [+ [0, 47],+ [1.5, 9.3],+ [3.2, 120],+ [0, 10.1],+ ]) {+ for (const modelId of SHORTS_MODELS.cloud) {+ const plan = planShorts(shorts({ modelId, range: { start, end }, source: { url: "/api/files/x.mp4", duration: 130, hasAudio: true } }));+ const looks = plan.steps.filter((s) => s.request.op === "v2v");+ const sum = looks.reduce((n, s) => n + (s.request.params!.duration as number), 0);+ expect(sum).toBeCloseTo(end - start, 2);+ }+ }+ // 47 s → five 9.4 s segments (not 9 s each: 45 s of picture under 47 s of sound).+ expect(planCloudSegments({ start: 0, end: 47 }).map((s) => Math.round((s.end - s.start) * 10) / 10)).toEqual([9.4, 9.4, 9.4, 9.4, 9.4]);+ const wan = planShorts(shorts({ modelId: "wan-2-7" }));+ expect(wan.steps.find((s) => s.key === "look0")!.request.params!.duration).toBe(9.4);+ });++ it("Mixed Media: the cloud render is asked for the cut's exact length; the open render for floor(s × fps) frames", () => {+ const sketch = MIXED_PRESETS.find((p) => p.id === "mixed-sketch")!;+ const mm = (over: Partial<MixedPlanInput>): MixedPlanInput => ({+ engine: "cloud",+ title: "Sketch · skate",+ preset: sketch,+ values: defaultValues(sketch),+ source: { url: "/api/files/skate.mp4", duration: 12, hasAudio: true },+ range: { start: 1.3, end: 2.7 },+ fps: 8,+ resolution: "1K",+ modelId: "wan-2-7",+ ...over,+ });+ const cloud = planMixed(mm({}));+ expect(cloud.steps.find((s) => s.key === "render")!.request.params!.duration).toBe(1.4);+ const open = planMixed(mm({ engine: "open", modelId: "oss-mixed-media", range: { start: 0, end: 10 } }));+ expect(open.steps[0].request.params!.extra).toMatchObject({ frames: 80 });+ expect(mixedFrames(10, 8)).toBe(80);+ const open24 = planMixed(mm({ engine: "open", modelId: "oss-mixed-media", range: { start: 0, end: 10 }, fps: 24 }));+ expect(open24.steps[0].request.params!.extra).toMatchObject({ frames: 240 });+ });+});++describe("clip lengths each restyle model takes", () => {+ it("knows the research windows and words the problem", () => {+ expect(sourceSeconds("kling-o3-4k-edit")).toEqual({ min: 3, max: 15 });+ expect(sourceSeconds("wan-2-7")).toEqual({ min: 2, max: 10 });+ expect(sourceSeconds("ltx-2-3-restyle")).toEqual({});+ const [kling] = modelInfos(["kling-o3-4k-edit"]);+ expect(kling).toMatchObject({ minSeconds: 3, maxSeconds: 15 });+ expect(clipLengthProblem(kling, 1.4)).toBe("Kling O3 4K Edit needs at least 3 s");+ expect(clipLengthProblem(kling, 3)).toBeNull();+ expect(clipLengthProblem(kling, 16)).toBe("Kling O3 4K Edit takes up to 15 s");+ expect(clipLengthProblem(modelInfos(["ltx-2-3-restyle"])[0], 1)).toBeNull();+ });+});