Open source CapCut alternative.
TypeScript
feat(site): add Cut AI voiceover, media generation, and caption styles
David Le4a5e27ee3bc8
diff --git a/site/src/app/cut/layout.tsx b/site/src/app/cut/layout.tsxindex c4835d2a..6b92d2d2 100644--- a/site/src/app/cut/layout.tsx+++ b/site/src/app/cut/layout.tsx@@ -1,7 +1,10 @@import type { Metadata } from "next";import type { ReactNode } from "react";+import { headers } from "next/headers";import { AppSurfaceBackground } from "@/app/app/_components/AppSurfaceBackground";+import { isCutHost } from "@/cut/lib/hosts";+import { CutBaseProvider } from "@/cut/lib/nav";export const metadata: Metadata = {title: "Donkey Cut",@@ -12,11 +15,16 @@ export const metadata: Metadata = {// /app, not the cream marketing background. AppSurfaceBackground paints the root// html white so the cream landing background does not show through the overscroll// area, and font-system matches the /app system font stack.-export default function CutLayout({ children }: { children: ReactNode }) {+export default async function CutLayout({ children }: { children: ReactNode }) {+ // The app's routes live under /cut/*. On the cut.* production host a proxy+ // rewrite serves them at the root, so links are root-relative (base ""). In+ // local dev the app is opened at /cut on the apex — same origin as the session+ // cookie — so links carry the "/cut" base. Resolve it once from the host.+ const base = isCutHost((await headers()).get("host")) ? "" : "/cut";return (<div className="min-h-screen bg-white font-system text-foreground antialiased"><AppSurfaceBackground />- {children}+ <CutBaseProvider base={base}>{children}</CutBaseProvider></div>);}diff --git a/site/src/app/cut/p/[id]/page.tsx b/site/src/app/cut/p/[id]/page.tsxindex f9472942..db4116bd 100644--- a/site/src/app/cut/p/[id]/page.tsx+++ b/site/src/app/cut/p/[id]/page.tsx@@ -1,11 +1,22 @@"use client";-import { useParams } from "next/navigation";+import { Suspense } from "react";+import { useParams, useSearchParams } from "next/navigation";import { Editor } from "@/cut/components/Editor";// Client-only: the id comes from the URL in the browser, so the hosted shell-// carries no server-rendered data.-export default function ProjectPage() {+// carries no server-rendered data. `from` records which tab opened the project+// so the editor's back button returns there.+function ProjectEditor() {const { id } = useParams<{ id: string }>();- return <Editor projectId={id} />;+ const from = useSearchParams().get("from");+ return <Editor projectId={id} from={from} />;+}++export default function ProjectPage() {+ return (+ <Suspense>+ <ProjectEditor />+ </Suspense>+ );}diff --git a/site/src/components/ui/slider.tsx b/site/src/components/ui/slider.tsxindex 691fff38..ad12da6b 100644--- a/site/src/components/ui/slider.tsx+++ b/site/src/components/ui/slider.tsx@@ -10,11 +10,18 @@ function Slider({max = 100,...props}: SliderPrimitive.Root.Props) {+ // One thumb per actual value. A scalar renders exactly one thumb — a phantom+ // second thumb has no backing value, so Base UI ignores any rail click that+ // lands closest to it (the click resolves to a thumb index out of range).const _values = Array.isArray(value)? value- : Array.isArray(defaultValue)- ? defaultValue- : [min, max]+ : value !== undefined+ ? [value]+ : Array.isArray(defaultValue)+ ? defaultValue+ : defaultValue !== undefined+ ? [defaultValue]+ : [min]return (<SliderPrimitive.Root@@ -27,7 +34,7 @@ function Slider({thumbAlignment="edge"{...props}>- <SliderPrimitive.Control className="relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-vertical:h-full data-vertical:min-h-40 data-vertical:w-auto data-vertical:flex-col">+ <SliderPrimitive.Control className="relative flex w-full cursor-pointer touch-none items-center select-none data-horizontal:py-2 data-disabled:opacity-50 data-vertical:h-full data-vertical:min-h-40 data-vertical:w-auto data-vertical:flex-col data-vertical:px-2"><SliderPrimitive.Trackdata-slot="slider-track"className="relative grow overflow-hidden rounded-full bg-muted select-none data-horizontal:h-1 data-horizontal:w-full data-vertical:h-full data-vertical:w-1"diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex b5bd73d2..14f1c3cc 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -106,9 +106,10 @@ const PROVIDER_LABEL: Record<string, string> = {const SUGGESTIONS = ["What's in this video?","Add transitions between clips",- "Make my title punchier",- "Add social captions",- "Write a TikTok caption",+ "Improve my title",+ "Watch and create subtitles",+ "Rewrite subtitles for social",+ "Write my post caption + tags",];/** Chat provider bucket for a model id. */diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsxindex 43446a67..93855125 100644--- a/site/src/cut/components/AppSidebar.tsx+++ b/site/src/cut/components/AppSidebar.tsx@@ -14,17 +14,19 @@ import {} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { apiFetch } from "@/cut/lib/api";+import { homeHref, projectHref, tabForPath, useCutBase, type CutTab } from "@/cut/lib/nav";import type { ProjectSummary } from "@/cut/lib/types";import { cn } from "@/lib/utils";-const NAV = [- { href: "/", label: "Projects", icon: Clapperboard },- { href: "/library", label: "Library", icon: FolderOpen },+const NAV: { tab: CutTab; label: string; icon: typeof Clapperboard }[] = [+ { tab: "projects", label: "Projects", icon: Clapperboard },+ { tab: "library", label: "Library", icon: FolderOpen },];export function AppSidebar() {const pathname = usePathname();const router = useRouter();+ const base = useCutBase();const [createOpen, setCreateOpen] = useState(false);const [name, setName] = useState("");const [busy, setBusy] = useState(false);@@ -38,7 +40,7 @@ export function AppSidebar() {body: JSON.stringify({ name: name.trim() || "Untitled" }),});const project = (await res.json()) as ProjectSummary;- router.push(`/p/${project.id}`);+ router.push(projectHref(base, project.id, tabForPath(pathname)));} finally {setBusy(false);}@@ -70,11 +72,12 @@ export function AppSidebar() {</Button><nav className="flex flex-col gap-0.5">- {NAV.map(({ href, label, icon: Icon }) => {+ {NAV.map(({ tab, label, icon: Icon }) => {+ const href = homeHref(base, tab);const active = pathname === href;return (<Link- key={href}+ key={tab}href={href}className={cn("flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",@@ -87,10 +90,6 @@ export function AppSidebar() {);})}</nav>- <div className="mt-auto px-2.5 text-[11px] leading-relaxed text-muted-foreground/70">- Everything stays on this Mac.- </div>-<Dialog open={createOpen} onOpenChange={setCreateOpen}><DialogContent className="sm:max-w-sm"><DialogHeader>diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsxnew file mode 100644index 00000000..0238316b--- /dev/null+++ b/site/src/cut/components/AudioPanel.tsx@@ -0,0 +1,433 @@+"use client";++import { useEffect, useRef, useState } from "react";+import {+ AudioLines,+ Check,+ ChevronDown,+ Loader2,+ Pause,+ Play,+ Plus,+ Trash2,+} from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import {+ addLibraryAssetToProject,+ fetchLibrary,+ libraryMediaUrl,+ type LibraryAsset,+} from "@/cut/lib/library";+import { creditsUrl, signInUrl, useSignedIn } from "@/cut/lib/generate";+import { enrichAsset } from "@/cut/lib/media";+import { useEditor } from "@/cut/lib/store";+import { formatTime } from "@/cut/lib/time";+import { NoCreditsError, synthesizeSpeech } from "@/cut/lib/tts";+import { DUCK_DEFAULT } from "@/cut/lib/voiceover";+import { useSpeakerVoice, VoicePicker } from "@/cut/components/VoicePicker";+import { cn } from "@/lib/utils";++/** Starting points for the direction prompt — picking one fills the input so+ * it can be tweaked before generating. */+const DIRECTION_PRESETS: { label: string; text: string }[] = [+ { label: "Warm", text: "Say warmly, like an old friend" },+ { label: "Energetic", text: "Say with high energy, like a hype announcer" },+ { label: "Documentary", text: "Narrate calmly and evenly, like a nature documentary" },+ { label: "Movie trailer", text: "Say dramatically, with gravity, like a movie trailer" },+ { label: "News anchor", text: "Read briskly and clearly, like a news anchor" },+ { label: "Whisper", text: "Whisper softly, close to the mic" },+ { label: "Bedtime story", text: "Read slowly and gently, like a bedtime story" },+];++/** The Audio tab: AI voiceover on top, then the project's and library's audio+ * as playable rows that drop onto the soundtrack at the playhead. Audio files+ * come in through the Media tab or a drop onto the timeline. */+export function AudioPanel({+ projectId,+ importing,+}: {+ projectId: string;+ importing: boolean;+}) {+ // One shared player for every row so starting a clip stops the last one.+ const player = useRef<HTMLAudioElement | null>(null);+ const [playingUrl, setPlayingUrl] = useState<string | null>(null);+ const togglePlay = (url: string) => {+ const el = (player.current ??= new Audio());+ if (playingUrl === url) {+ el.pause();+ setPlayingUrl(null);+ return;+ }+ el.src = url;+ el.onended = () => setPlayingUrl(null);+ el.onerror = () => setPlayingUrl(null);+ setPlayingUrl(url);+ void el.play().catch(() => setPlayingUrl(null));+ };+ useEffect(+ () => () => {+ player.current?.pause();+ },+ []+ );++ return (+ <>+ <div className="flex h-12 shrink-0 items-center pl-4">+ <span className="text-sm font-semibold tracking-tight">Audio</span>+ </div>++ <div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-3.5 pb-4">+ <VoiceGenerator projectId={projectId} />+ <ProjectAudio importing={importing} onTogglePlay={togglePlay} playingUrl={playingUrl} />+ <LibraryAudio projectId={projectId} onTogglePlay={togglePlay} playingUrl={playingUrl} />+ </div>+ </>+ );+}++function sectionLabel(text: string) {+ return (+ <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">+ {text}+ </span>+ );+}++function VoiceGenerator({ projectId }: { projectId: string }) {+ const voice = useSpeakerVoice();+ const [script, setScript] = useState("");+ const [direction, setDirection] = useState("");+ const [busy, setBusy] = useState(false);+ // `credits` marks a failure caused by an empty balance, which renders with a+ // link to buy more.+ const [error, setError] = useState<{ text: string; credits?: boolean } | null>(null);+ const fail = (e: unknown, fallback: string) =>+ setError(+ e instanceof Error+ ? { text: e.message, credits: e instanceof NoCreditsError }+ : { text: fallback }+ );+ const directionInput = useRef<HTMLTextAreaElement>(null);+ // Voiceovers run on the user's Donkey account, like image/video generation.+ const signedOut = useSignedIn() === false;++ /** Synthesize the script, register the media asset, and drop one clip on the+ * soundtrack at the playhead. */+ const generate = async () => {+ const text = script.trim();+ if (!text) return;+ setBusy(true);+ setError(null);+ try {+ const playhead = useEditor.getState().currentTime;+ const lead = text.split(/\s+/).slice(0, 4).join(" ");+ const { asset } = await synthesizeSpeech(projectId, [{ text, at: 0 }], {+ voice,+ direction,+ name: `AI voice — ${lead}`,+ });+ const cur = useEditor.getState();+ cur.addAsset(asset);+ cur.addAudioFromAsset(asset.id, playhead, {+ // New voiceovers duck everything else to the default; fine-tune on the+ // clip itself ("Duck others" in the inspector).+ duck: DUCK_DEFAULT,+ });+ void enrichAsset(asset);+ } catch (e) {+ fail(e, "Voice generation failed.");+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="voice-generator flex flex-col gap-3.5">+ {/* Voice settings first — pick how the voice sounds, then script it. */}+ <VoicePicker onError={(e) => fail(e, "Could not play the sample.")} />++ <div className="flex flex-col gap-1.5">+ {sectionLabel("Voice direction")}+ <p className="-mt-0.5 text-[11px] leading-snug text-muted-foreground">+ Optional. Tell the voice how to deliver the lines — its tone, pace, and energy.+ </p>+ <div className="relative">+ <textarea+ ref={directionInput}+ rows={2}+ className="voice-direction min-h-[52px] w-full resize-y rounded-lg border border-input bg-transparent py-2 pr-9 pl-2.5 text-[12.5px] leading-relaxed outline-none focus:border-ring"+ placeholder="Say warmly, like an old friend (optional)"+ value={direction}+ onChange={(e) => setDirection(e.target.value)}+ />+ <DropdownMenu>+ <DropdownMenuTrigger+ className="voice-direction-presets absolute top-1.5 right-1 grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ aria-label="Direction presets"+ >+ <ChevronDown className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-64">+ {DIRECTION_PRESETS.map((p) => (+ <DropdownMenuItem key={p.label} onClick={() => setDirection(p.text)}>+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="text-[12px] font-medium">{p.label}</span>+ <span className="truncate text-[11px] text-muted-foreground">{p.text}</span>+ </div>+ {direction === p.text && <Check className="size-3.5 shrink-0" />}+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => {+ setDirection("");+ // The menu hands focus back to the trigger on close; take it after.+ setTimeout(() => directionInput.current?.focus(), 0);+ }}+ >+ <span className="text-[12px] font-medium">Custom…</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>++ <div className="h-px shrink-0 bg-border" />++ {/* The script and its generate button stay together so the button's job —+ and why it's disabled until there's a script — is obvious. */}+ <div className="flex flex-col gap-2">+ {sectionLabel("Script")}+ <textarea+ className="voice-script min-h-[88px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"+ placeholder="What should the voice say?"+ value={script}+ onChange={(e) => setScript(e.target.value)}+ />+ <Button+ className="voice-generate w-full"+ disabled={!script.trim() || busy || signedOut}+ title={!script.trim() ? "Write a script above to generate" : undefined}+ onClick={() => void generate()}+ >+ {busy ? <Loader2 className="animate-spin" /> : <AudioLines data-icon="inline-start" />}+ Generate audio+ </Button>+ </div>++ {signedOut ? (+ <p className="voice-signin text-[11px] leading-relaxed text-muted-foreground">+ Voiceovers run on your Donkey account.{" "}+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>+ Sign in+ </a>{" "}+ to continue.+ </p>+ ) : (+ error && (+ <p className="voice-error text-[11px] leading-relaxed text-red-600">+ {error.text}+ {error.credits && (+ <>+ {" "}+ <a+ className="font-medium underline hover:no-underline"+ href={creditsUrl()}+ target="_blank"+ rel="noreferrer"+ >+ Add credits+ </a>+ </>+ )}+ </p>+ )+ )}+ </div>+ );+}++/** Tiny waveform for a row, from the asset's normalized peaks. */+function PeakStrip({ peaks }: { peaks: number[] }) {+ const BARS = 48;+ const step = Math.max(1, Math.floor(peaks.length / BARS));+ const bars: number[] = [];+ for (let i = 0; i < BARS; i++) {+ let m = 0;+ for (let j = i * step; j < Math.min(peaks.length, (i + 1) * step); j++) {+ if (peaks[j] > m) m = peaks[j];+ }+ bars.push(m);+ }+ return (+ <svg+ viewBox={`0 0 ${BARS * 2} 16`}+ preserveAspectRatio="none"+ className="mt-1 h-4 w-full text-muted-foreground/50"+ aria-hidden+ >+ {bars.map((p, i) => {+ const h = Math.max(1.5, p * 16);+ return <rect key={i} x={i * 2} y={(16 - h) / 2} width={1.2} height={h} rx={0.6} fill="currentColor" />;+ })}+ </svg>+ );+}++function AudioRow({+ name,+ duration,+ url,+ peaks,+ playing,+ onTogglePlay,+ onAdd,+ onDelete,+}: {+ name: string;+ duration: number;+ url: string;+ peaks?: number[];+ playing: boolean;+ onTogglePlay: (url: string) => void;+ onAdd: () => void;+ onDelete?: () => void;+}) {+ return (+ <div className="audio-row group flex items-center gap-2 rounded-lg border border-border p-1.5 pr-2 transition-colors hover:border-input hover:bg-muted/50">+ <button+ type="button"+ className={cn(+ "grid size-8 shrink-0 place-items-center rounded-full transition-colors",+ playing ? "bg-primary text-primary-foreground" : "bg-muted hover:bg-muted/70"+ )}+ title={playing ? "Pause" : "Play"}+ aria-label={playing ? "Pause" : "Play"}+ onClick={() => onTogglePlay(url)}+ >+ {playing ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}+ </button>+ <div className="min-w-0 flex-1">+ <div className="flex items-baseline justify-between gap-2">+ <span className="truncate text-[11.5px] font-medium">{name}</span>+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums">+ {formatTime(duration)}+ </span>+ </div>+ {peaks && peaks.length > 0 && <PeakStrip peaks={peaks} />}+ </div>+ {onDelete && (+ <button+ type="button"+ title="Remove from project"+ aria-label="Remove from project"+ className="grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-destructive/10 hover:text-destructive"+ onClick={onDelete}+ >+ <Trash2 className="size-3.5" />+ </button>+ )}+ <button+ type="button"+ title="Add at the playhead"+ aria-label="Add at the playhead"+ className="grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-muted hover:text-foreground"+ onClick={onAdd}+ >+ <Plus className="size-3.5" />+ </button>+ </div>+ );+}++function ProjectAudio({+ importing,+ onTogglePlay,+ playingUrl,+}: {+ importing: boolean;+ onTogglePlay: (url: string) => void;+ playingUrl: string | null;+}) {+ const assets = useEditor((s) => s.assets);+ const audio = assets.filter((a) => a.type === "audio" && a.origin === "voiceover");+ return (+ <div className="flex flex-col gap-1.5">+ {sectionLabel("Generated audio")}+ {audio.length === 0 && !importing && (+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ No generated audio yet — write a script above and generate one.+ </p>+ )}+ <div className="flex flex-col gap-1.5">+ {audio.map((a) => (+ <AudioRow+ key={a.id}+ name={a.name}+ duration={a.duration}+ url={a.url}+ peaks={a.peaks}+ playing={playingUrl === a.url}+ onTogglePlay={onTogglePlay}+ onAdd={() => useEditor.getState().addAudioFromAsset(a.id)}+ onDelete={() => useEditor.getState().removeAsset(a.id)}+ />+ ))}+ {importing && (+ <div className="flex items-center gap-2 rounded-lg border border-dashed border-input px-2.5 py-2 text-[11px] text-muted-foreground">+ <Loader2 className="size-3.5 animate-spin" /> Importing…+ </div>+ )}+ </div>+ </div>+ );+}++function LibraryAudio({+ projectId,+ onTogglePlay,+ playingUrl,+}: {+ projectId: string;+ onTogglePlay: (url: string) => void;+ playingUrl: string | null;+}) {+ const [assets, setAssets] = useState<LibraryAsset[]>([]);+ useEffect(() => {+ let alive = true;+ fetchLibrary()+ .then((d) => alive && setAssets(d.assets.filter((a) => a.type === "audio")))+ .catch(() => {});+ return () => {+ alive = false;+ };+ }, []);+ if (assets.length === 0) return null;+ return (+ <div className="flex flex-col gap-1.5">+ {sectionLabel("Library")}+ <div className="flex flex-col gap-1.5">+ {assets.map((a) => (+ <AudioRow+ key={a.id}+ name={a.name}+ duration={a.duration}+ url={libraryMediaUrl(a.fileName)}+ playing={playingUrl === libraryMediaUrl(a.fileName)}+ onTogglePlay={onTogglePlay}+ onAdd={() => void addLibraryAssetToProject(projectId, a)}+ />+ ))}+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 3f345572..c6dd61ca 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -8,25 +8,28 @@ import { apiFetch } from "@/cut/lib/api";import { renderPreviewProxy } from "@/cut/lib/exportClient";import { useExport } from "@/cut/lib/exportStore";import { enrichAsset, importFileToProject } from "@/cut/lib/media";-import { projectDuration, serializeDoc, useEditor } from "@/cut/lib/store";+import { backTarget, useCutBase } from "@/cut/lib/nav";+import { getClipSpans, projectDuration, serializeDoc, useEditor } from "@/cut/lib/store";import { AiPanel } from "./AiPanel";import { ExportDialog } from "./ExportDialog";import { ExportStatus } from "./ExportStatus";import { Inspector } from "./Inspector";import { Preview } from "./Preview";import { SidePanel } from "./SidePanel";-import { Timeline } from "./Timeline";+import { Timeline, videoInsertIndex } from "./Timeline";import { TopBar } from "./TopBar";-export function Editor({ projectId }: { projectId: string }) {+export function Editor({ projectId, from }: { projectId: string; from?: string | null }) {+ const back = backTarget(useCutBase(), from);const loaded = useEditor((s) => s.loaded);const loadError = useEditor((s) => s.loadError);const dropActive = useEditor((s) => s.dropActive);const exportOpen = useEditor((s) => s.exportOpen);const aiOpen = useEditor((s) => s.aiOpen);- // The inspector only earns its column when something is selected; otherwise it- // is an empty white panel, so collapse it and let the preview take the space.- const hasInspector = useEditor((s) => s.selection != null);+ // The inspector only earns its column when the selection has a panel to+ // show; otherwise (nothing selected, or a subtitle cue) it is an empty white+ // panel, so collapse it and let the preview take the space.+ const hasInspector = useEditor((s) => s.selection != null && s.selection.kind !== "cue");const [importing, setImporting] = useState(0);const dragDepth = useRef(0);@@ -178,7 +181,7 @@ export function Editor({ projectId }: { projectId: string }) {}, [projectId]);const importFiles = useCallback(- async (files: FileList | File[]) => {+ async (files: FileList | File[], at?: number | null) => {const list = Array.from(files);setImporting((n) => n + list.length);for (const file of list) {@@ -187,8 +190,23 @@ export function Editor({ projectId }: { projectId: string }) {if (!asset) continue;const s = useEditor.getState();s.addAsset(asset);- if (asset.type === "video") s.addClipFromAsset(asset.id);- else s.addAudioFromAsset(asset.id, 0);+ if (asset.type === "video") {+ // A drop on the timeline inserts at the pointer's slot; anywhere+ // else appends at the end.+ if (at == null) {+ s.addClipFromAsset(asset.id);+ } else {+ const spans = getClipSpans(s.clips, s.assets);+ const spanIndex = videoInsertIndex(spans, at);+ const clipsIndex =+ spanIndex < spans.length+ ? s.clips.findIndex((c) => c.id === spans[spanIndex].clip.id)+ : s.clips.length;+ s.addClipFromAsset(asset.id, clipsIndex);+ }+ } else {+ s.addAudioFromAsset(asset.id, at ?? 0);+ }void enrichAsset(asset);} catch (err) {console.error(`Import failed for ${file.name}:`, err);@@ -216,12 +234,25 @@ export function Editor({ projectId }: { projectId: string }) {dragDepth.current = Math.max(0, dragDepth.current - 1);if (dragDepth.current === 0) useEditor.getState().setDropActive(false);};+ // Time under the pointer when the drop lands on the timeline's tracks,+ // else null. Geometric, because the drop veil overlays the whole window+ // and would swallow any target-based check.+ const timelineDropTime = (e: DragEvent): number | null => {+ const scroll = document.querySelector(".tl-scroll");+ const inner = document.querySelector(".tl-content");+ if (!scroll || !inner) return null;+ const r = scroll.getBoundingClientRect();+ if (e.clientY < r.top || e.clientY > r.bottom || e.clientX < r.left || e.clientX > r.right)+ return null;+ const t = (e.clientX - inner.getBoundingClientRect().left) / useEditor.getState().pxPerSec;+ return Math.max(0, t);+ };const drop = (e: DragEvent) => {if (!e.dataTransfer?.files.length) return;e.preventDefault();dragDepth.current = 0;useEditor.getState().setDropActive(false);- void importFiles(e.dataTransfer.files);+ void importFiles(e.dataTransfer.files, timelineDropTime(e));};window.addEventListener("dragenter", enter);window.addEventListener("dragover", over);@@ -300,7 +331,7 @@ export function Editor({ projectId }: { projectId: string }) {<Buttonvariant="outline"nativeButton={false}- render={<Link href="/">Back to projects</Link>}+ render={<Link href={back.href}>Back to {back.tab}</Link>}/></div></div>@@ -318,7 +349,7 @@ export function Editor({ projectId }: { projectId: string }) {return (<div className="flex h-screen min-w-[900px] overflow-hidden"><div className="grid min-w-0 flex-1 grid-rows-[46px_minmax(0,1fr)_auto]">- <TopBar />+ <TopBar onImport={importFiles} from={from} /><divclassName={`grid min-h-0 ${hasInspector ? "grid-cols-[auto_minmax(0,1fr)_272px]" : "grid-cols-[auto_minmax(0,1fr)]"diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsxnew file mode 100644index 00000000..54aee690--- /dev/null+++ b/site/src/cut/components/GeneratePanel.tsx@@ -0,0 +1,191 @@+"use client";++import { useState } from "react";+import { Film, Image as ImageIcon, Loader2, Plus, Sparkles, Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { signInUrl, useGenerate, useSignedIn, type GenerateJob } from "@/cut/lib/generate";+import { useEditor } from "@/cut/lib/store";+import { useLocalPref } from "@/cut/lib/uiState";+import { cn } from "@/lib/utils";++type Kind = "image" | "video";++const chip = (active: boolean) =>+ cn(+ "rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors",+ active+ ? "border-primary bg-primary/10 text-primary"+ : "border-border text-muted-foreground hover:text-foreground"+ );++export function GenerateImagePanel({ projectId }: { projectId: string }) {+ return <GeneratePanel projectId={projectId} kind="image" />;+}++export function GenerateVideoPanel({ projectId }: { projectId: string }) {+ return <GeneratePanel projectId={projectId} kind="video" />;+}++function GeneratePanel({ projectId, kind }: { projectId: string; kind: Kind }) {+ const signedIn = useSignedIn();+ const allJobs = useGenerate((s) => s.jobs);+ const jobs = allJobs.filter((j) => j.projectId === projectId && j.kind === kind);+ const [prompt, setPrompt] = useState("");+ const [tier, setTier] = useLocalPref<"fast" | "high">(+ "cut-gen-tier",+ "fast",+ (v) => v === "fast" || v === "high"+ );+ const [seconds, setSeconds] = useLocalPref<number>(+ "cut-gen-seconds",+ 8,+ (v) => v === 4 || v === 6 || v === 8+ );++ const go = () => {+ const p = prompt.trim();+ if (!p) return;+ if (kind === "image") void useGenerate.getState().generateImage(projectId, p);+ else void useGenerate.getState().generateVideo(projectId, p, { tier, durationSeconds: seconds });+ setPrompt("");+ };++ return (+ <>+ <div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">+ <span className="text-sm font-semibold tracking-tight">+ {kind === "image" ? "Image" : "Video"}+ </span>+ </div>++ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3.5 pb-4">+ <textarea+ className="gen-prompt min-h-[88px] w-full shrink-0 resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"+ placeholder={+ kind === "image"+ ? "A neon-lit street market at night, cinematic…"+ : "A drone shot rising over a foggy coastline at sunrise…"+ }+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ go();+ }+ }}+ />++ {kind === "video" && (+ <div className="flex shrink-0 items-center justify-between gap-2">+ <div className="flex gap-1.5">+ {[4, 6, 8].map((s) => (+ <button key={s} className={chip(seconds === s)} onClick={() => setSeconds(s)}>+ {s}s+ </button>+ ))}+ </div>+ <div className="flex gap-1.5">+ {(["fast", "high"] as const).map((t) => (+ <button key={t} className={chip(tier === t)} onClick={() => setTier(t)}>+ {t === "fast" ? "Fast" : "Best"}+ </button>+ ))}+ </div>+ </div>+ )}++ <Button+ className="gen-go w-full shrink-0"+ disabled={!prompt.trim() || signedIn === false}+ onClick={go}+ >+ <Sparkles data-icon="inline-start" />+ {kind === "image" ? "Generate image" : "Generate video"}+ </Button>++ {signedIn === false ? (+ <p className="gen-signin shrink-0 text-[11px] leading-relaxed text-muted-foreground">+ Generating runs on your Donkey account.{" "}+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>+ Sign in+ </a>{" "}+ to continue.+ </p>+ ) : (+ <p className="shrink-0 text-[11px] leading-relaxed text-muted-foreground">+ {kind === "image"+ ? "Lands in Media as an 8s clip — trim it like footage."+ : "Veo renders take a minute or two — keep editing while it runs."}+ </p>+ )}++ {jobs.length > 0 && (+ <div className="flex flex-col gap-1.5">+ {jobs.map((j) => (+ <JobRow key={j.id} job={j} />+ ))}+ </div>+ )}+ </div>+ </>+ );+}++function JobRow({ job }: { job: GenerateJob }) {+ const asset = useEditor((s) => s.assets.find((a) => a.id === job.assetId));+ const Icon = job.kind === "image" ? ImageIcon : Film;+ return (+ <div className="gen-job group flex items-center gap-2.5 rounded-lg border border-border p-2">+ {asset ? (+ <video+ muted+ playsInline+ preload="metadata"+ src={`${asset.url}#t=0.1`}+ className="size-10 shrink-0 rounded-md bg-black object-cover"+ />+ ) : (+ <span className="grid size-10 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground">+ {job.status === "running" ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <Icon className="size-4" />+ )}+ </span>+ )}+ <div className="min-w-0 flex-1">+ <div className="truncate text-[11.5px] font-medium">{job.prompt}</div>+ <div+ className={cn(+ "text-[10.5px] leading-snug break-words",+ job.status === "error" ? "text-red-600" : "text-muted-foreground"+ )}+ >+ {job.status === "running" &&+ (job.kind === "video" ? "Rendering with Veo…" : "Generating…")}+ {job.status === "done" && "In your media"}+ {job.status === "error" && (job.error ?? "Failed.")}+ </div>+ </div>+ {job.status === "done" && asset && (+ <button+ title="Add to timeline"+ className="grid size-6 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:brightness-110"+ onClick={() => useEditor.getState().addClipFromAsset(asset.id)}+ >+ <Plus className="size-3.5" />+ </button>+ )}+ {job.status !== "running" && (+ <button+ title="Dismiss"+ className="grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-foreground"+ onClick={() => useGenerate.getState().dismiss(job.id)}+ >+ <Trash2 className="size-3.5" />+ </button>+ )}+ </div>+ );+}diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex bc2de2d7..7e342bbf 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { Bold, Smile } from "lucide-react";import { Button } from "@/components/ui/button";import {@@ -18,7 +18,8 @@ import {import { Slider } from "@/components/ui/slider";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";-import { useEditor } from "@/cut/lib/store";+import { getClipSpans, useEditor } from "@/cut/lib/store";+import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";import { PLATE_COLOR, PLATE_OPACITY, PLATE_RADIUS } from "@/cut/lib/textRender";import { writeTextStyle } from "@/cut/lib/textStyle";import { formatTime } from "@/cut/lib/time";@@ -254,6 +255,50 @@ function ClipPanel({ clip }: { clip: VideoClip }) {const fadeOut = useEditor((s) => s.fadeOut);const [speedDraft, setSpeedDraft] = useState<number | null>(null);const [xfadeDraft, setXfadeDraft] = useState<number | null>(null);+ const [volumeDraft, setVolumeDraft] = useState<number | null>(null);+ const volume = volumeDraft ?? clip.volume ?? 1;+ // Subtitle cues overlapping this clip's timeline span, for the per-clip+ // readout. Selected as a joined string so the reference stays stable while+ // the playhead ticks through the same store.+ const clipCueIdsKey = useEditor((s) => {+ const sp = getClipSpans(s.clips, s.assets).find((x) => x.clip.id === clip.id);+ if (!sp) return "";+ return s.subtitles.cues+ .filter((c) => c.text.trim() && c.end > sp.start && c.start < sp.start + sp.len)+ .map((c) => c.id)+ .join("\n");+ });+ const clipCueIds = useMemo(+ () => (clipCueIdsKey ? clipCueIdsKey.split("\n") : []),+ [clipCueIdsKey]+ );+ // Generated voiceover clips overlapping this clip's span — the "Generated+ // audio" slider drives them all, so clip sound and voiceover balance from one+ // panel. Same joined-string trick as the cue ids for reference stability.+ const [genVolDraft, setGenVolDraft] = useState<number | null>(null);+ const genCk = useSliderCheckpoint();+ const genAudioKey = useEditor((s) => {+ const sp = getClipSpans(s.clips, s.assets).find((x) => x.clip.id === clip.id);+ if (!sp) return "";+ const voiceAssets = new Set(+ s.assets.filter((a) => a.origin === "voiceover").map((a) => a.id)+ );+ return s.audioClips+ .filter((a) => {+ const len = (a.out - a.in) / (a.speed && a.speed > 0 ? a.speed : 1);+ return (+ voiceAssets.has(a.assetId) && a.start < sp.start + sp.len && a.start + len > sp.start+ );+ })+ .map((a) => a.id)+ .join("\n");+ });+ const genAudioIds = useMemo(() => (genAudioKey ? genAudioKey.split("\n") : []), [genAudioKey]);+ const genVolStore = useEditor((s) => {+ const first = s.audioClips.find((a) => a.id === genAudioIds[0]);+ return first ? first.volume : 1;+ });+ const genVol = genVolDraft ?? genVolStore;const speed = speedDraft ?? clip.speed ?? 1;const xfade = xfadeDraft ?? clip.transition ?? 0;const speedLen = (clip.out - clip.in) / (speed > 0 ? speed : 1);@@ -358,12 +403,37 @@ function ClipPanel({ clip }: { clip: VideoClip }) {</Row></>)}++ {/* Audio */}+ <div className="my-1.5 h-px bg-border" />+ <Row label="Clip volume">+ <Slider+ className="clip-volume data-horizontal:w-24"+ min={0}+ max={1.5}+ step={0.05}+ value={volume}+ onValueChange={(v) => setVolumeDraft(Number(v))}+ onValueCommitted={() => {+ if (volumeDraft != null) {+ updateClip(clip.id, { volume: volumeDraft === 1 ? undefined : volumeDraft });+ }+ setVolumeDraft(null);+ }}+ />+ <Value className="w-9 text-right text-muted-foreground">+ {Math.round(volume * 100)}%+ </Value>+ </Row><Row label="Mute audio"><Switchchecked={clip.muted}onCheckedChange={(v) => updateClip(clip.id, { muted: v })}/></Row>++ {/* Picture */}+ <div className="my-1.5 h-px bg-border" /><Row label="Hide from output"><Switchchecked={!!clip.hidden}@@ -403,6 +473,33 @@ function ClipPanel({ clip }: { clip: VideoClip }) {rect={rectOf(clip)}onPick={(frame, fit) => updateClip(clip.id, { frame, fit })}/>+ <div className="mt-2 flex flex-col gap-1 border-t border-border pt-3">+ <GenerateSubtitlesAudio cueIds={clipCueIds} label="Generate audio for clip" />+ {genAudioIds.length > 0 && (+ <Row label="Volume">+ <Slider+ className="clip-gen-volume data-horizontal:w-24"+ min={0}+ max={1.5}+ step={0.05}+ value={genVol}+ onValueChange={(v) => {+ genCk.begin();+ setGenVolDraft(Number(v));+ const s = useEditor.getState();+ genAudioIds.forEach((id) => s.updateAudioTransient(id, { volume: Number(v) }));+ }}+ onValueCommitted={() => {+ genCk.end();+ setGenVolDraft(null);+ }}+ />+ <Value className="w-9 text-right text-muted-foreground">+ {Math.round(genVol * 100)}%+ </Value>+ </Row>+ )}+ </div></div></>);@@ -472,6 +569,28 @@ function AudioPanel({ clip }: { clip: AudioClip }) {{(clip.fadeOut ?? 0).toFixed(1)}s</Value></Row>+ <Row label="Duck others">+ <Slider+ className="duck-slider data-horizontal:w-24"+ min={0}+ max={1}+ step={0.05}+ value={clip.duck ?? 1}+ onValueChange={(v) => {+ const n = Number(v);+ setAudio({ duck: n < 0.999 ? n : undefined });+ }}+ onValueCommitted={ck.end}+ />+ <Value className="w-9 text-right text-muted-foreground">+ {clip.duck === undefined ? "Off" : `${Math.round(clip.duck * 100)}%`}+ </Value>+ </Row>+ {clip.duck !== undefined && (+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ While this clip plays, everything else drops to {Math.round(clip.duck * 100)}% volume.+ </p>+ )}<Row label="Hide from output"><Switchchecked={!!clip.hidden}diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsxindex 0404c816..2ab5faaf 100644--- a/site/src/cut/components/OverlayLayer.tsx+++ b/site/src/cut/components/OverlayLayer.tsx@@ -3,7 +3,7 @@import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";import { startDrag } from "@/cut/lib/drag";import { useEditor } from "@/cut/lib/store";-import { captionStyle, cueAt, cueOverlay } from "@/cut/lib/subtitles";+import { captionStyle, cueAt, cueOverlay, cueWordWindows, karaokeLook } from "@/cut/lib/subtitles";import {LINE_HEIGHT,PLATE_PAD_X,@@ -30,6 +30,10 @@ interface Guides {h: number[]; // horizontal lines (y)}+/** The subtitle caption's key in the shared snap-box registry. Overlay ids are+ * uids, so this can't collide. */+const SUBTITLE_BOX_ID = "subtitle-caption";+export function OverlayLayer({ stageWidth }: { stageWidth: number }) {const overlays = useEditor((s) => s.overlays);const currentTime = useEditor((s) => s.currentTime);@@ -40,8 +44,9 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {// Titles preview under the skimmer too (paused only), matching the canvas.const t = !playing && skimTime !== null ? skimTime : currentTime;- // Live box elements per title, so a dragged one can align to the others that- // are on screen at the same time.+ const rootRef = useRef<HTMLDivElement>(null);+ // Live box elements per on-screen item (titles and the subtitle caption), so+ // a dragged one can align to the others that are on screen at the same time.const boxes = useRef<Map<string, HTMLElement>>(new Map());const [guides, setGuides] = useState<Guides>({ v: [], h: [] });const registerBox = useCallback((id: string, el: HTMLElement | null) => {@@ -51,14 +56,15 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {const stageHeight = (stageWidth * FRAME[aspect].h) / FRAME[aspect].w;- // Figma-style smart snapping: while dragging a title, pull its left/center/+ // Figma-style smart snapping: while dragging an item, pull its left/center/// right edges to the frame edges, safe margins, center line, and the edges- // and centers of the other on-screen titles — independently per axis — and+ // and centers of the other on-screen items — independently per axis — and// paint the matched guide lines. Hold ⌘/Ctrl to bypass.const snap = useCallback((id: string, px: number, py: number, ev: PointerEvent): { x: number; y: number } => {const el = boxes.current.get(id);- if (!el || ev.metaKey || ev.ctrlKey) {+ const root = rootRef.current;+ if (!el || !root || ev.metaKey || ev.ctrlKey) {setGuides({ v: [], h: [] });return { x: px, y: py };}@@ -68,16 +74,16 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {// Frame lines: edges, safe margins, center.const vt = [0, CANVAS_MARGIN * stageWidth, stageWidth / 2, (1 - CANVAS_MARGIN) * stageWidth, stageWidth];const ht = [0, CANVAS_MARGIN * stageHeight, stageHeight / 2, (1 - CANVAS_MARGIN) * stageHeight, stageHeight];- // Plus every other on-screen title's edges and center.- for (const o of useEditor.getState().overlays) {- if (o.id === id) continue;- const e = boxes.current.get(o.id);- if (!e) continue;+ // Plus every other on-screen box's edges and center (titles and the+ // subtitle caption alike), read from its rect in stage space.+ const rootRect = root.getBoundingClientRect();+ for (const [bid, e] of boxes.current) {+ if (bid === id) continue;const rr = e.getBoundingClientRect();- const ox = o.x * stageWidth;- const oy = o.y * stageHeight;- vt.push(ox - rr.width / 2, ox, ox + rr.width / 2);- ht.push(oy - rr.height / 2, oy, oy + rr.height / 2);+ const left = rr.left - rootRect.left;+ const top = rr.top - rootRect.top;+ vt.push(left, left + rr.width / 2, left + rr.width);+ ht.push(top, top + rr.height / 2, top + rr.height);}// For one axis, snap the closest of {near edge, center, far edge} to the// closest target line, returning the shifted center and the matched line.@@ -122,7 +128,14 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {const isolate = !!sel && !scrubbing && !(t >= sel.start && t <= sel.end);return (- <div className="pointer-events-none absolute inset-0">+ <div ref={rootRef} className="pointer-events-none absolute inset-0">+ <SubtitleCaption+ stageWidth={stageWidth}+ stageHeight={stageHeight}+ registerBox={registerBox}+ snap={snap}+ onSnapEnd={clearGuides}+ />{overlays.map((o) => {const selected = sel?.id === o.id;const inRange = t >= o.start && t <= o.end;@@ -163,8 +176,23 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {}/** The active subtitle cue, rendered exactly like the export burn-in.- * Nothing renders when subtitles are hidden or there is no cue (no speech). */-export function SubtitleLayer({ stageWidth }: { stageWidth: number }) {+ * Nothing renders when subtitles are hidden or there is no cue (no speech).+ * Dragging the caption moves every cue — the position is one project-wide+ * anchor, not per-cue — and rides the same smart snapping and guide lines as+ * titles. */+function SubtitleCaption({+ stageWidth,+ stageHeight,+ registerBox,+ snap,+ onSnapEnd,+}: {+ stageWidth: number;+ stageHeight: number;+ registerBox: (id: string, el: HTMLElement | null) => void;+ snap: (id: string, x: number, y: number, ev: PointerEvent) => { x: number; y: number };+ onSnapEnd: () => void;+}) {const subtitles = useEditor((s) => s.subtitles);const currentTime = useEditor((s) => s.currentTime);const skimTime = useEditor((s) => s.skimTime);@@ -178,37 +206,91 @@ export function SubtitleLayer({ stageWidth }: { stageWidth: number }) {// Captions ride the same style/opener logic as the export burn-in, so the// preview and the rendered file match exactly.- const ov = cueOverlay(- cue,- captionStyle(subtitles.style),- cue.id === subtitles.cues[0]?.id- );+ const style = captionStyle(subtitles.style);+ const ov = cueOverlay(cue, style, cue.id === subtitles.cues[0]?.id, subtitles);+ // Karaoke: the word under the playhead lights up as it is spoken.+ const wordIndex = subtitles.wordHighlight+ ? cueWordWindows(cue).findIndex((w) => t >= w.start && t < w.end)+ : -1;+ // The spoken word's treatment follows the style (with user overrides): an+ // accent box (drawn with box-shadow spread so the line never reflows), the+ // accent color alone, or accent color + underline.+ const look = karaokeLook(style, subtitles);+ const activeStyle: CSSProperties =+ look.mode === "box"+ ? {+ color: look.text,+ background: look.color,+ boxShadow: `0 0 0 0.12em ${look.color}`,+ borderRadius: "0.18em",+ textShadow: "none",+ }+ : look.mode === "color"+ ? { color: look.color }+ : {+ color: look.color,+ textDecoration: "underline",+ textDecorationThickness: "0.07em",+ textUnderlineOffset: "0.14em",+ };const scale = stageWidth / FRAME[aspect].w;return (- <div className="pointer-events-none absolute inset-0">- <div- className="sub-caption absolute -translate-x-1/2 -translate-y-1/2 text-center whitespace-pre-wrap"- style={{- left: `${ov.x * 100}%`,- top: `${ov.y * 100}%`,- // Hard cap at the safe area so a caption can never spill past the- // frame edge, even if a line slips past the wrap estimate.- maxWidth: `${0.9 * stageWidth}px`,- fontSize: ov.size * scale,- fontFamily: fontStack(ov.font),- fontWeight: ov.weight,- lineHeight: LINE_HEIGHT,- color: ov.color,- textShadow: ov.shadow- ? `0 ${SHADOW.offsetY * scale}px ${SHADOW.blur * scale}px ${SHADOW.color}`- : undefined,- background: ov.plate ? plateFill(ov) : undefined,- padding: ov.plate ? PLATE_PADDING : undefined,- borderRadius: ov.plate ? PLATE_RADIUS_EM : undefined,- }}- >- {ov.text}- </div>+ <div+ ref={(el) => registerBox(SUBTITLE_BOX_ID, el)}+ className="sub-caption pointer-events-auto absolute -translate-x-1/2 -translate-y-1/2 cursor-grab text-center whitespace-pre-wrap active:cursor-grabbing"+ onPointerDown={(e) => {+ const s = useEditor.getState();+ s.pushHistory();+ const { x: x0, y: y0 } = ov;+ startDrag(e, {+ onMove: (dx, dy, ev) => {+ const p = snap(SUBTITLE_BOX_ID, x0 + dx / stageWidth, y0 + dy / stageHeight, ev);+ useEditor.getState().setSubtitlesView({+ x: Math.min(0.98, Math.max(0.02, p.x)),+ y: Math.min(0.98, Math.max(0.02, p.y)),+ });+ },+ onUp: onSnapEnd,+ });+ }}+ style={{+ left: `${ov.x * 100}%`,+ top: `${ov.y * 100}%`,+ // Hard cap at the safe area so a caption can never spill past the+ // frame edge, even if a line slips past the wrap estimate.+ maxWidth: `${0.9 * stageWidth}px`,+ fontSize: ov.size * scale,+ fontFamily: fontStack(ov.font),+ fontWeight: ov.weight,+ lineHeight: LINE_HEIGHT,+ color: ov.color,+ textShadow: ov.shadow+ ? `0 ${SHADOW.offsetY * scale}px ${SHADOW.blur * scale}px ${SHADOW.color}`+ : undefined,+ background: ov.plate ? plateFill(ov) : undefined,+ padding: ov.plate ? PLATE_PADDING : undefined,+ borderRadius: ov.plate ? PLATE_RADIUS_EM : undefined,+ }}+ >+ {wordIndex < 0+ ? ov.text+ : (() => {+ let k = 0;+ return ov.text.split("\n").map((line, li) => (+ <span key={li} className="block">+ {line.split(" ").map((w, wi) => {+ const active = k === wordIndex;+ k++;+ return (+ <span key={wi}>+ {wi > 0 && " "}+ <span style={active ? activeStyle : undefined}>{w}</span>+ </span>+ );+ })}+ </span>+ ));+ })()}</div>);}diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex bb133212..14898db8 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -6,7 +6,7 @@ import { startDrag } from "@/cut/lib/drag";import { getClipSpans, useEditor } from "@/cut/lib/store";import { FRAME, isFullRect, rectOf, type Aspect, type ClipSpan, type FrameRect, type MediaAsset, type VideoClip } from "@/cut/lib/types";import { cn } from "@/lib/utils";-import { OverlayLayer, SubtitleLayer } from "./OverlayLayer";+import { OverlayLayer } from "./OverlayLayer";/** The clip under the playhead, when it overflows the frame in fill mode. */function pannableSpan(s: {@@ -107,7 +107,6 @@ export function Preview() {><canvas ref={canvasRef} width={frame.w} height={frame.h} className="block size-full" /><OverlayPipHandle stage={stage} />- <SubtitleLayer stageWidth={stage.w} /><OverlayLayer stageWidth={stage.w} /></div></div>diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 02fcf196..e0712121 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -43,6 +43,8 @@ import {} from "@/components/ui/dropdown-menu";import { Input } from "@/components/ui/input";import { apiFetch, apiUrl } from "@/cut/lib/api";+import { createProjectFromFile, isMediaFile } from "@/cut/lib/media";+import { projectHref, useCutBase } from "@/cut/lib/nav";import { formatTime } from "@/cut/lib/time";import { mediaUrl, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";import { cn } from "@/lib/utils";@@ -70,6 +72,7 @@ function formatDate(ts: number) {export function ProjectsHome() {const router = useRouter();+ const base = useCutBase();const [projects, setProjects] = useState<ProjectSummary[] | null>(null);const [folders, setFolders] = useState<ProjectFolder[]>([]);const [openFolder, setOpenFolder] = useState<string | null>(null);@@ -81,6 +84,12 @@ export function ProjectsHome() {const [name, setName] = useState("");const [busy, setBusy] = useState(false);const [engineDown, setEngineDown] = useState(false);+ // A count of desktop files still uploading into fresh projects, plus whether an+ // OS-file drag is hovering the surface (a depth counter tames enter/leave noise+ // as the cursor crosses child tiles).+ const [importing, setImporting] = useState(0);+ const [fileOver, setFileOver] = useState(false);+ const dragDepth = useRef(0);useEffect(() => {const saved = localStorage.getItem("cut-projects-view");@@ -176,15 +185,48 @@ export function ProjectsHome() {const res = await apiFetch("/api/cut/projects", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: name.trim() || "Untitled" }),+ body: JSON.stringify({ name: name.trim() || "Untitled", folderId: openFolder }),});const project = (await res.json()) as ProjectSummary;- router.push(`/p/${project.id}`);+ router.push(projectHref(base, project.id, "projects"));} finally {setBusy(false);}};+ // Make a new project in the folder that's open (root when none), then jump+ // straight into it — no naming step.+ const newProjectHere = async (folderId: string | null = openFolder) => {+ const res = await apiFetch("/api/cut/projects", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "Untitled", folderId }),+ });+ const project = (await res.json()) as ProjectSummary;+ router.push(projectHref(base, project.id, "projects"));+ };++ // Turn a batch of desktop files into projects filed under `folderId`. Each+ // becomes its own project and pops into the grid the moment it's ready.+ const importFilesAsProjects = useCallback(+ async (files: FileList | File[], folderId: string | null) => {+ const media = Array.from(files).filter(isMediaFile);+ if (media.length === 0) return;+ setImporting((n) => n + media.length);+ for (const file of media) {+ try {+ await createProjectFromFile(file, folderId);+ } catch {+ // A file the engine can't ingest is skipped; the rest still land.+ } finally {+ setImporting((n) => n - 1);+ }+ await refresh();+ }+ },+ [refresh]+ );+const rename = async () => {if (!renaming) return;setBusy(true);@@ -249,8 +291,49 @@ export function ProjectsHome() {return next;});+ // Only OS-file drags are drop targets here; internal project drags carry+ // PROJECT_MIME and are handled by the folder tiles and breadcrumb instead.+ const isFileDrag = (e: React.DragEvent) => Array.from(e.dataTransfer.types).includes("Files");+return (- <div className="mx-auto w-full max-w-6xl px-10 py-9">+ <div+ className={cn(+ "relative mx-auto w-full max-w-6xl px-10 py-9",+ fileOver &&+ "rounded-3xl outline-2 outline-dashed outline-offset-[-10px] outline-[#0a84ff]/60"+ )}+ onDragEnter={(e) => {+ if (engineDown || !isFileDrag(e)) return;+ e.preventDefault();+ dragDepth.current += 1;+ setFileOver(true);+ }}+ onDragOver={(e) => {+ if (engineDown || !isFileDrag(e)) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ }}+ onDragLeave={(e) => {+ if (!isFileDrag(e)) return;+ dragDepth.current -= 1;+ if (dragDepth.current <= 0) {+ dragDepth.current = 0;+ setFileOver(false);+ }+ }}+ onDrop={(e) => {+ if (engineDown || !isFileDrag(e)) return;+ e.preventDefault();+ dragDepth.current = 0;+ setFileOver(false);+ void importFilesAsProjects(e.dataTransfer.files, openFolder);+ }}+ >+ {importing > 0 && (+ <div className="pointer-events-none fixed right-6 bottom-6 z-50 grid size-11 place-items-center rounded-full bg-foreground/90 text-background shadow-lg">+ <Loader2 className="size-5 animate-spin" />+ </div>+ )}{!engineDown && projects && hasContent && (<div className="mb-5 flex items-center justify-between">{openFolder === null ? (@@ -310,6 +393,7 @@ export function ProjectsHome() {onRename={renameFolder}onDelete={deleteFolder}onDropIds={(ids, fid) => void moveProjects(ids, fid)}+ onDropFiles={(files, fid) => void importFilesAsProjects(files, fid)}/>)}@@ -367,7 +451,7 @@ export function ProjectsHome() {</Button></div></div>- ) : shown.length === 0 ? null : view === "gallery" ? (+ ) : view === "gallery" ? (<MarqueeclassName="grid min-h-[42vh] grid-cols-[repeat(auto-fill,minmax(190px,1fr))] content-start gap-5"selected={selected}@@ -386,7 +470,7 @@ export function ProjectsHome() {toggleSelect(p.id);return;}- router.push(`/p/${p.id}`);+ router.push(projectHref(base, p.id, "projects"));}}>{/* Vertical 9:16 tile — the project is mobile video, show it that way. */}@@ -422,6 +506,17 @@ export function ProjectsHome() {</div></div>))}+ <button+ type="button"+ data-no-marquee+ aria-label="New project"+ onClick={() => void newProjectHere()}+ className="group/new flex flex-col"+ >+ <span className="grid aspect-[9/16] place-items-center rounded-2xl border-2 border-dashed border-border text-muted-foreground transition-colors group-hover/new:border-[#0a84ff] group-hover/new:bg-[#0a84ff]/5 group-hover/new:text-[#0a84ff]">+ <Plus className="size-8" />+ </span>+ </button></Marquee>) : (<div className="overflow-hidden rounded-xl border border-border bg-card">@@ -448,7 +543,7 @@ export function ProjectsHome() {toggleSelect(p.id);return;}- router.push(`/p/${p.id}`);+ router.push(projectHref(base, p.id, "projects"));}}><span className="flex min-w-0 items-center gap-2.5">@@ -475,6 +570,14 @@ export function ProjectsHome() {/></div>))}+ <button+ type="button"+ data-no-marquee+ onClick={() => void newProjectHere()}+ className="flex w-full items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground"+ >+ <Plus className="size-4" /> New project+ </button></div>)}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 29cdf270..910d08ce 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -1,7 +1,7 @@"use client";-import { useEffect, useRef, useState } from "react";-import { Captions, Check, Circle, ClipboardList, Copy, Film, FolderOpen, FolderPlus, Layers, Loader2, Mic, Music, Plus, Trash2, Upload, Video } from "lucide-react";+import { Fragment, useEffect, useRef, useState } from "react";+import { Captions, Check, Clapperboard, ClipboardList, Copy, Film, FolderOpen, FolderPlus, Image as ImageIcon, Layers, Loader2, Music, Plus, Trash2, Upload } from "lucide-react";import { Button } from "@/components/ui/button";import {AlertDialog,@@ -13,12 +13,6 @@ import {AlertDialogHeader,AlertDialogTitle,} from "@/components/ui/alert-dialog";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";import { apiFetch, apiUrl } from "@/cut/lib/api";import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";import { deleteExport, revealExport } from "@/cut/lib/exportClient";@@ -41,23 +35,27 @@ import type { LibraryTemplate } from "@/cut/lib/types";import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";import { useEditor } from "@/cut/lib/store";import { formatTime } from "@/cut/lib/time";+import { useLocalPref } from "@/cut/lib/uiState";import type { MediaAsset } from "@/cut/lib/types";import { cn } from "@/lib/utils";+import { AudioPanel } from "./AudioPanel";import { buildDragGhost, FolderCrumb, FolderShelf } from "./desktopFolders";+import { GenerateImagePanel, GenerateVideoPanel } from "./GeneratePanel";import { LibraryCard } from "./LibraryView";// Drag a library clip onto a folder tile to file it (side panel, single card).const LIBRARY_MOVE_MIME = "application/x-cut-library-move";import { PlatformPreviewDialog, type ExportItem } from "./PlatformPreview";-import { RecordDialog, type RecordMode } from "./RecordDialog";import { SubtitlesPanel } from "./SubtitlesPanel";-type Tab = "media" | "library" | "record" | "subtitles" | "publish";+type Tab = "media" | "video" | "image" | "library" | "audio" | "subtitles" | "publish";const TABS: { id: Tab; label: string; icon: typeof Film }[] = [- { id: "media", label: "Media", icon: Film },+ { id: "media", label: "Media", icon: Clapperboard },{ id: "library", label: "Library", icon: FolderOpen },- { id: "record", label: "Record", icon: Circle },+ { id: "video", label: "Video", icon: Film },+ { id: "image", label: "Image", icon: ImageIcon },+ { id: "audio", label: "Audio", icon: Music },{ id: "subtitles", label: "Subtitles", icon: Captions },{ id: "publish", label: "Details", icon: ClipboardList },];@@ -71,8 +69,9 @@ export function SidePanel({onImport: (files: FileList | File[]) => void;importing: boolean;}) {- const [tab, setTab] = useState<Tab>("media");- const [recordMode, setRecordMode] = useState<RecordMode | null>(null);+ const [tab, setTab] = useLocalPref<Tab>("cut-side-tab", "media", (v) =>+ TABS.some((t) => t.id === v)+ );return (<div className="flex min-h-0 border-r border-border bg-card">@@ -97,37 +96,20 @@ export function SidePanel({</>);- if (id === "record") {- return (- <DropdownMenu key={id}>- <DropdownMenuTrigger render={<button className={tileClass} />}>- {inner}- </DropdownMenuTrigger>- <DropdownMenuContent- align="start"- side="right"- style={{ width: "12rem" }}- >- <DropdownMenuItem onClick={() => setRecordMode("camera")}>- <Video /> Record camera- </DropdownMenuItem>- <DropdownMenuItem onClick={() => setRecordMode("audio")}>- <Mic /> Record audio- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );- }-return (- <button- key={id}- className={tileClass}- aria-pressed={tab === id}- onClick={() => setTab(id)}- >- {inner}- </button>+ <Fragment key={id}>+ {/* Soft breaks between the file tabs, the AI-generate tabs, and the finishing tabs. */}+ {(id === "video" || id === "subtitles") && (+ <div aria-hidden className="my-1 h-px w-8 bg-border" />+ )}+ <button+ className={tileClass}+ aria-pressed={tab === id}+ onClick={() => setTab(id)}+ >+ {inner}+ </button>+ </Fragment>);})}</div>@@ -136,17 +118,13 @@ export function SidePanel({{tab === "media" && (<MediaPanel projectId={projectId} onImport={onImport} importing={importing} />)}+ {tab === "video" && <GenerateVideoPanel projectId={projectId} />}+ {tab === "image" && <GenerateImagePanel projectId={projectId} />}{tab === "library" && <LibraryPanel projectId={projectId} />}+ {tab === "audio" && <AudioPanel projectId={projectId} importing={importing} />}{tab === "subtitles" && <SubtitlesPanel />}{tab === "publish" && <PublishPanel />}</div>- {recordMode && (- <RecordDialog- mode={recordMode}- onClose={() => setRecordMode(null)}- onUse={(file) => onImport([file])}- />- )}</div>);}@@ -492,7 +470,11 @@ function LibraryPanel({ projectId }: { projectId: string }) {const [assets, setAssets] = useState<LibraryAsset[] | null>(null);const [folders, setFolders] = useState<LibraryFolder[]>([]);const [templates, setTemplates] = useState<LibraryTemplate[]>([]);- const [openFolder, setOpenFolder] = useState<string | null>(null);+ const [openFolder, setOpenFolder] = useLocalPref<string | null>(+ "cut-library-folder",+ null,+ (v) => v === null || typeof v === "string"+ );const [deleting, setDeleting] = useState<LibraryAsset | null>(null);const reload = () =>@@ -504,6 +486,12 @@ function LibraryPanel({ projectId }: { projectId: string }) {}).catch(() => setAssets([]));+ // A remembered folder can vanish between sessions; drop back to the root.+ useEffect(() => {+ if (assets !== null && openFolder !== null && !folders.some((f) => f.id === openFolder))+ setOpenFolder(null);+ }, [assets, folders, openFolder, setOpenFolder]);+const removeTemplate = async (id: string) => {setTemplates((prev) => prev.filter((t) => t.id !== id));await deleteTemplate(id).catch(() => void reload());diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsxindex c2341c3a..8614fb9c 100644--- a/site/src/cut/components/SubtitlesPanel.tsx+++ b/site/src/cut/components/SubtitlesPanel.tsx@@ -1,12 +1,14 @@"use client";-import { memo, useEffect, useRef, useState } from "react";-import { AlertCircle, Captions, ChevronDown, Loader2, RefreshCw, Sparkles } from "lucide-react";+import React, { memo, useEffect, useRef, useState } from "react";+import { AlertCircle, Captions, ChevronDown, Loader2, RefreshCw } from "lucide-react";import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";-import { CAPTION_STYLES, fmtCueTime } from "@/cut/lib/subtitles";+import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";+import { CAPTION_STYLES, captionStyle, fmtCueTime, karaokeLook } from "@/cut/lib/subtitles";import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";-import type { SubtitleCue } from "@/cut/lib/types";+import { PLATE_PAD_X, PLATE_PAD_Y, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";+import { fontStack, type SubtitleCue, type WordAccentMode } from "@/cut/lib/types";import { cn } from "@/lib/utils";const LOCALES = [@@ -31,8 +33,7 @@ export function SubtitlesPanel() {const status = useEditor((s) => s.subtitleStatus);const error = useEditor((s) => s.subtitleError);const hasCues = subtitles.cues.length > 0;-- const style = subtitles.style ?? "clean";+ const [tab, setTab] = useState<"content" | "styles" | "settings">("content");const growTimeline = () => {const cur = useEditor.getState();@@ -44,103 +45,243 @@ export function SubtitlesPanel() {void useEditor.getState().generateSubtitles().then(growTimeline);};- const captions = () => {- const s = useEditor.getState();- void s.generateCaptions(s.subtitles.style ?? "hook").then(growTimeline);- };-return (<><div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">- <span className="text-sm font-semibold tracking-tight">Subtitles</span>- {hasCues && (- <Button- variant="ghost"- size="sm"- className="sub-regenerate"- title="Transcribe the cut again (replaces these captions — undoable)"- disabled={status === "running"}- onClick={generate}- >- {status === "running" ? (- <Loader2 className="animate-spin" />- ) : (- <RefreshCw />- )}- Regenerate- </Button>+ {hasCues ? (+ <div className="sub-tabs flex items-center gap-3.5">+ {(+ [+ ["content", "Content"],+ ["styles", "Styles"],+ ["settings", "Settings"],+ ] as const+ ).map(([id, label], i) => (+ <React.Fragment key={id}>+ {i > 0 && <span aria-hidden className="h-4 w-px bg-border" />}+ <button+ className={cn(+ "text-sm font-semibold tracking-tight transition-colors",+ tab === id ? "text-foreground" : "text-muted-foreground/60 hover:text-foreground"+ )}+ aria-pressed={tab === id}+ onClick={() => setTab(id)}+ >+ {label}+ </button>+ </React.Fragment>+ ))}+ </div>+ ) : (+ <span className="text-sm font-semibold tracking-tight">Subtitles</span>)}</div>{!hasCues ? (<EmptyState status={status} error={error} onGenerate={generate} />- ) : (+ ) : tab === "content" ? (<>+ <div className="shrink-0 px-1.5">+ <Button+ variant="ghost"+ size="sm"+ className="sub-regenerate"+ title="Transcribe the cut again (replaces these captions — undoable)"+ disabled={status === "running"}+ onClick={generate}+ >+ {status === "running" ? (+ <Loader2 className="animate-spin" />+ ) : (+ <RefreshCw />+ )}+ Regenerate+ </Button>+ </div><Transcript cues={subtitles.cues} />- <div className="flex shrink-0 flex-col gap-2.5 border-t border-border px-4 py-3">- <label className="flex items-center justify-between text-xs font-medium">- Show- <Switch- className="sub-show"- checked={subtitles.showOnVideo || subtitles.showOnTimeline}- onCheckedChange={(v) => {- const s = useEditor.getState();- s.setSubtitlesView({ showOnVideo: v, showOnTimeline: v });- if (v && s.timelineH < TIMELINE_H_WITH_SUBS) s.setTimelineH(TIMELINE_H_WITH_SUBS);- }}- />- </label>+ <div className="shrink-0 border-t border-border px-3.5 py-3">+ <GenerateSubtitlesAudio />+ </div>+ {status === "error" && error && (+ <p className="sub-error shrink-0 border-t border-border px-4 py-2.5 text-[11px] leading-relaxed text-red-600">+ {error}+ </p>+ )}+ </>+ ) : tab === "styles" ? (+ <StylesTab />+ ) : (+ <SettingsTab />+ )}+ </>+ );+}- <div className="flex flex-col gap-1.5">- <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">- Caption style- </span>- <div className="flex flex-wrap gap-1.5">- {Object.values(CAPTION_STYLES).map((cs) => (- <button- key={cs.id}- className={cn(- "rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors",- style === cs.id- ? "border-primary bg-primary/10 text-primary"- : "border-border text-muted-foreground hover:text-foreground"- )}- onClick={() => useEditor.getState().setSubtitlesView({ style: cs.id })}- >- {cs.label}- </button>- ))}- </div>- <Button- variant="outline"- className="sub-social w-full"- disabled={status === "running"}- onClick={captions}+/** Accent colors offered for the spoken word. */+const ACCENTS = ["#FFE94A", "#FFFFFF", "#FF375F", "#0A84FF", "#30D158"];++const ACCENT_MODES: { id: WordAccentMode; label: string }[] = [+ { id: "color", label: "Color" },+ { id: "underline", label: "Underline" },+ { id: "box", label: "Highlight" },+];++/** The Settings tab: caption visibility, the karaoke word highlight with its+ * treatment and color, and position reset for a dragged caption. */+function SettingsTab() {+ const subtitles = useEditor((s) => s.subtitles);+ const moved = subtitles.x !== undefined || subtitles.y !== undefined;+ // Effective word treatment: the caption style's defaults with the user's+ // overrides on top, so the controls always show what's on the video.+ const look = karaokeLook(captionStyle(subtitles.style), subtitles);++ return (+ <div className="sub-settings flex min-h-0 flex-1 flex-col gap-2.5 overflow-y-auto px-4 py-3">+ <label className="flex min-h-8 items-center justify-between text-xs font-medium">+ Show+ <Switch+ className="sub-show"+ checked={subtitles.showOnVideo || subtitles.showOnTimeline}+ onCheckedChange={(v) => {+ const s = useEditor.getState();+ s.setSubtitlesView({ showOnVideo: v, showOnTimeline: v });+ if (v && s.timelineH < TIMELINE_H_WITH_SUBS) s.setTimelineH(TIMELINE_H_WITH_SUBS);+ }}+ />+ </label>+ <label className="flex min-h-8 items-center justify-between text-xs font-medium">+ Highlight spoken word+ <Switch+ className="sub-word-highlight"+ checked={!!subtitles.wordHighlight}+ onCheckedChange={(v) =>+ useEditor.getState().setSubtitlesView({ wordHighlight: v || undefined })+ }+ />+ </label>+ {subtitles.wordHighlight && (+ <>+ <div className="flex min-h-8 items-center justify-between text-xs font-medium">+ Word style+ <div className="sub-accent-mode flex rounded-lg border border-input p-0.5">+ {ACCENT_MODES.map((m) => (+ <button+ key={m.id}+ className={cn(+ "rounded-md px-2 py-1 text-[11.5px] font-medium transition-colors",+ look.mode === m.id+ ? "bg-neutral-900 text-white"+ : "text-muted-foreground hover:text-foreground"+ )}+ aria-pressed={look.mode === m.id}+ onClick={() => useEditor.getState().setSubtitlesView({ accentMode: m.id })}+ >+ {m.label}+ </button>+ ))}+ </div>+ </div>+ <div className="flex min-h-8 items-center justify-between text-xs font-medium">+ Word color+ <div className="sub-accent-color flex items-center gap-1.5">+ {ACCENTS.map((c) => (+ <button+ key={c}+ title={c}+ aria-label={`Word color ${c}`}+ className={cn(+ "size-5 rounded-full border border-black/15 transition-transform hover:scale-110",+ look.color.toUpperCase() === c.toUpperCase() &&+ "ring-2 ring-primary ring-offset-2 ring-offset-card"+ )}+ style={{ background: c }}+ onClick={() => useEditor.getState().setSubtitlesView({ accentColor: c })}+ />+ ))}+ <label+ title="Custom color"+ className="relative size-5 cursor-pointer rounded-full border border-black/15 bg-[conic-gradient(from_0deg,#f43f5e,#f59e0b,#84cc16,#06b6d4,#6366f1,#d946ef,#f43f5e)] transition-transform hover:scale-110">- {status === "running" ? (- <Loader2 className="animate-spin" />- ) : (- <Sparkles data-icon="inline-start" />- )}- Rewrite for social- </Button>- <p className="text-[11px] leading-relaxed text-muted-foreground">- Punchier lines, a curiosity hook, and a few emoji — timings stay put.- </p>+ <span className="absolute inset-1 rounded-full bg-card" />+ <span className="absolute inset-[5px] rounded-full" style={{ background: look.color }} />+ <input+ type="color"+ aria-label="Pick a custom word color"+ className="absolute inset-0 size-full cursor-pointer opacity-0"+ value={/^#[0-9a-fA-F]{6}$/.test(look.color) ? look.color : "#ffffff"}+ onChange={(e) =>+ useEditor.getState().setSubtitlesView({ accentColor: e.target.value })+ }+ />+ </label></div>-- {status === "running" && (- <p className="flex items-center gap-1.5 text-[11px] text-muted-foreground">- <Loader2 className="size-3 animate-spin" /> Re-transcribing on this Mac…- </p>- )}- {status === "error" && error && (- <p className="sub-error text-[11px] leading-relaxed text-red-600">{error}</p>- )}</div></>)}- </>+ <div className="flex min-h-8 items-center justify-between text-xs font-medium">+ Position+ <Button+ variant="outline"+ size="sm"+ className="sub-position-reset"+ disabled={!moved}+ onClick={() => useEditor.getState().setSubtitlesView({ x: undefined, y: undefined })}+ >+ Reset+ </Button>+ </div>+ <p className="sub-position-hint -mt-1 text-[11px] leading-relaxed text-muted-foreground">+ Drag the caption on the video to reposition every subtitle.+ </p>+ </div>+ );+}++/** The Styles tab: the caption style list, each option rendered as a live+ * preview of that look. */+function StylesTab() {+ const subtitles = useEditor((s) => s.subtitles);+ const style = subtitles.style ?? "clean";++ return (+ <div className="sub-styles flex min-h-0 flex-1 flex-col gap-2.5 overflow-y-auto px-4 py-3">+ <div className="flex flex-col gap-1.5">+ {Object.values(CAPTION_STYLES).map((cs) => (+ <button+ key={cs.id}+ className={cn(+ "sub-style rounded-lg p-1 text-left transition-colors",+ style === cs.id ? "bg-primary/10 ring-1 ring-primary" : "hover:bg-muted"+ )}+ aria-pressed={style === cs.id}+ onClick={() => useEditor.getState().setSubtitlesView({ style: cs.id })}+ >+ <div className="grid h-12 place-items-center overflow-hidden rounded-md">+ <span+ className="whitespace-nowrap"+ style={{+ fontSize: cs.size * 0.48,+ fontFamily: fontStack(cs.font),+ fontWeight: cs.weight,+ color: cs.color,+ // Heavier than the on-video shadow so white captions stay+ // legible against the light panel.+ textShadow: cs.shadow+ ? "0 0 2px rgba(0,0,0,0.75), 0 1px 4px rgba(0,0,0,0.6)"+ : undefined,+ background: cs.plate ? plateFill(cs) : undefined,+ padding: cs.plate ? `${PLATE_PAD_Y}em ${PLATE_PAD_X}em` : undefined,+ borderRadius: cs.plate ? `${PLATE_RADIUS}em` : undefined,+ }}+ >+ Your caption+ </span>+ </div>+ <div className="px-1 pt-1 pb-0.5 text-[11px] font-medium">{cs.label}</div>+ </button>+ ))}+ </div>+ </div>);}@@ -182,12 +323,6 @@ function EmptyState({{error}</div>)}- {status !== "empty" && (- <div className="flex flex-col items-center gap-1 pt-4 pb-1 text-center">- <Captions className="mb-1 size-6 text-muted-foreground" />- <p className="text-[13px] font-semibold">Subtitles from your audio</p>- </div>- )}<div className="relative"><selectclassName="sub-locale w-full appearance-none rounded-lg border border-input bg-transparent py-2 pr-9 pl-2.5 text-[12.5px] outline-none focus:border-ring"diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 95bf7e4f..7065cd01 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -1,7 +1,7 @@"use client";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { AudioLines, Blend, Check, EllipsisVertical, Expand, FolderPlus, Loader2, Pause, Play, Plus, Scissors, SkipBack, Sunrise, Sunset, Trash2, Type, VolumeX, ZoomIn, ZoomOut, type LucideIcon } from "lucide-react";+import { AudioLines, Blend, Check, EllipsisVertical, Expand, Eye, EyeOff, FolderPlus, Loader2, Pause, Play, Plus, Scissors, SkipBack, Sunrise, Sunset, Trash2, Type, VolumeX, ZoomIn, ZoomOut, type LucideIcon } from "lucide-react";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -131,8 +131,9 @@ function dropIndex(spans: ClipSpan[], from: number, dxSec: number): number {}/** Insertion slot for a new clip dropped at time `t`: it lands before the- * first span whose midpoint is past `t` (spans.length = at the very end). */-function videoInsertIndex(spans: ClipSpan[], t: number): number {+ * first span whose midpoint is past `t` (spans.length = at the very end).+ * Exported for the Editor's OS-file drops onto the timeline. */+export function videoInsertIndex(spans: ClipSpan[], t: number): number {for (let k = 0; k < spans.length; k++) if (t < spans[k].start + spans[k].len / 2) return k;return spans.length;}@@ -1306,6 +1307,7 @@ function ClipView({className={cn("tl-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-lg bg-neutral-200 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",selected && SELECTED_SHADOW,+ clip.hidden && "opacity-40 grayscale",isDragged? "tl-clip-ghost pointer-events-none z-7 cursor-grabbing opacity-80 shadow-2xl": parting && "transition-transform duration-150 ease-out"@@ -1361,12 +1363,17 @@ function ClipView({)}{(clip.speed ?? 1) !== 1 && (<span- className="tl-speed-chip absolute right-1.5 bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"+ className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"title={`${clip.speed}× speed`}>{+(clip.speed ?? 1).toFixed(2)}×</span>)}+ <HideChip+ hidden={!!clip.hidden}+ className="bottom-1 right-2"+ onToggle={() => useEditor.getState().updateClip(clip.id, { hidden: !clip.hidden })}+ /><DropdownMenu><DropdownMenuTriggerrender={@@ -1418,6 +1425,35 @@ function ClipView({);}+/** Hover chip that toggles a clip out of the played/exported output ("disable").+ * Stays visible while the clip is hidden so re-enabling is one click. */+function HideChip({+ hidden,+ onToggle,+ className,+}: {+ hidden: boolean;+ onToggle: () => void;+ className?: string;+}) {+ return (+ <button+ type="button"+ title={hidden ? "Enable clip" : "Disable clip"}+ aria-label={hidden ? "Enable clip" : "Disable clip"}+ className={cn(+ "tl-hide-chip absolute z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white transition-opacity hover:bg-black/75",+ hidden ? "opacity-100" : "opacity-0 group-hover:opacity-100",+ className+ )}+ onPointerDown={(e) => e.stopPropagation()}+ onClick={onToggle}+ >+ {hidden ? <EyeOff className="size-3" /> : <Eye className="size-3" />}+ </button>+ );+}+function AudioView({clip,asset,@@ -1506,7 +1542,8 @@ function AudioView({<divclassName={cn("tl-audio-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-[7px] bg-gradient-to-b from-emerald-500 to-emerald-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",- selected && SELECTED_SHADOW+ selected && SELECTED_SHADOW,+ clip.hidden && "opacity-40 grayscale")}style={{ left: clip.start * pps, width: Math.max(10, w - CLIP_GAP), height: AUDIO_H - 4 }}onPointerDown={onBody}@@ -1527,6 +1564,11 @@ function AudioView({<span className="pointer-events-none absolute top-[3px] left-2 text-[9.5px] whitespace-nowrap text-white/90 [text-shadow:0_1px_2px_rgba(0,0,0,0.35)]">{asset.name}</span>+ <HideChip+ hidden={!!clip.hidden}+ className="top-[3px] right-1.5"+ onToggle={() => useEditor.getState().updateAudio(clip.id, { hidden: !clip.hidden })}+ /><span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={onTrimLeft} /><span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={onTrimRight} /></div>@@ -1683,12 +1725,17 @@ function OverlayClipView({)}{(clip.speed ?? 1) !== 1 && (<span- className="tl-speed-chip absolute right-1.5 bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"+ className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"title={`${clip.speed}× speed`}>{+(clip.speed ?? 1).toFixed(2)}×</span>)}+ <HideChip+ hidden={!!clip.hidden}+ className="bottom-1 right-2"+ onToggle={() => useEditor.getState().updateOverlayClip(clip.id, { hidden: !clip.hidden })}+ /><span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={onTrimLeft} /><span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={onTrimRight} /></div>diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxindex 296c054e..538af4a4 100644--- a/site/src/cut/components/TopBar.tsx+++ b/site/src/cut/components/TopBar.tsx@@ -2,7 +2,7 @@import { useState } from "react";import Link from "next/link";-import { Check, ChevronDown, ChevronLeft, Loader2, Monitor, Smartphone, Sparkles, Upload } from "lucide-react";+import { Check, ChevronDown, ChevronLeft, Loader2, Mic, Monitor, Smartphone, Sparkles, Upload, Video } from "lucide-react";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -10,17 +10,27 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { backTarget, useCutBase } from "@/cut/lib/nav";import { useEditor } from "@/cut/lib/store";import { ASPECT_LABEL, type Aspect } from "@/cut/lib/types";import { cn } from "@/lib/utils";+import { RecordDialog, type RecordMode } from "./RecordDialog";-export function TopBar() {+export function TopBar({+ onImport,+ from,+}: {+ onImport: (files: File[]) => void;+ from?: string | null;+}) {+ const back = backTarget(useCutBase(), from);const hasClips = useEditor((s) => s.clips.length > 0);const aspect = useEditor((s) => s.aspect);const projectName = useEditor((s) => s.projectName);const saveState = useEditor((s) => s.saveState);const [editing, setEditing] = useState(false);const [draft, setDraft] = useState("");+ const [recordMode, setRecordMode] = useState<RecordMode | null>(null);const commitName = () => {setEditing(false);@@ -30,7 +40,7 @@ export function TopBar() {return (<header className="relative flex items-center justify-between border-b border-border bg-card pr-3 pl-2">- <div className="absolute left-1/2 -translate-x-1/2">+ <div className="absolute left-1/2 flex -translate-x-1/2 items-center gap-2"><DropdownMenu><DropdownMenuTrigger className="aspect-switch flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-xs transition-colors hover:text-foreground">{aspect === "9:16" ? <Smartphone className="size-3.5" /> : <Monitor className="size-3.5" />}@@ -52,14 +62,36 @@ export function TopBar() {))}</DropdownMenuContent></DropdownMenu>+ <DropdownMenu>+ <DropdownMenuTrigger className="record-switch flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-xs transition-colors hover:text-foreground">+ <span className="size-2 rounded-full bg-red-500" aria-hidden />+ Record+ <ChevronDown className="size-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" style={{ width: "12rem" }}>+ <DropdownMenuItem onClick={() => setRecordMode("camera")}>+ <Video /> Record camera+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => setRecordMode("audio")}>+ <Mic /> Record audio+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></div>+ {recordMode && (+ <RecordDialog+ mode={recordMode}+ onClose={() => setRecordMode(null)}+ onUse={(file) => onImport([file])}+ />+ )}<div className="flex min-w-0 items-center gap-1"><Buttonvariant="ghost"size="icon-sm"- aria-label="Back to projects"+ aria-label={`Back to ${back.tab}`}nativeButton={false}- render={<Link href="/" />}+ render={<Link href={back.href} />}><ChevronLeft /></Button>diff --git a/site/src/cut/components/VoicePicker.tsx b/site/src/cut/components/VoicePicker.tsxnew file mode 100644index 00000000..59cb9b48--- /dev/null+++ b/site/src/cut/components/VoicePicker.tsx@@ -0,0 +1,223 @@+"use client";++import { useEffect, useRef, useState, useSyncExternalStore } from "react";+import { Captions, ChevronDown, Loader2, Pause, Play } from "lucide-react";+import { Button } from "@/components/ui/button";+import { creditsUrl, signInUrl, useSignedIn } from "@/cut/lib/generate";+import { useEditor } from "@/cut/lib/store";+import { NoCreditsError, resolveVoice, speechSampleUrl, SPEECH_VOICES } from "@/cut/lib/tts";+import { generateSubtitlesReadout } from "@/cut/lib/voiceover";++const VOICE_KEY = "cut-tts-voice";++// One shared speaker-voice preference for every surface that generates audio+// (Audio tab, Subtitles tab, clip settings). Module-level so all mounted+// pickers stay in sync; persisted so it survives reloads.+let currentVoice: string | null = null;+const listeners = new Set<() => void>();++function readVoice(): string {+ if (currentVoice === null) {+ currentVoice = resolveVoice(+ typeof window === "undefined" ? undefined : (localStorage.getItem(VOICE_KEY) ?? undefined)+ );+ }+ return currentVoice;+}++function writeVoice(id: string) {+ currentVoice = resolveVoice(id);+ try {+ localStorage.setItem(VOICE_KEY, currentVoice);+ } catch {+ // Preference only.+ }+ listeners.forEach((l) => l());+}++function subscribe(l: () => void) {+ listeners.add(l);+ return () => listeners.delete(l);+}++/** The shared speaker voice; every generation surface reads this. */+export function useSpeakerVoice(): string {+ return useSyncExternalStore(subscribe, readVoice, () => resolveVoice(undefined));+}++/**+ * Speaker-voice row: a play button that samples the voice plus the voice+ * select. Drop it into any surface that generates speech — they all share one+ * persisted voice choice.+ */+export function VoicePicker({+ onError,+ title = "Speaker voice",+}: {+ onError?: (e: unknown) => void;+ title?: string;+}) {+ const voice = useSpeakerVoice();+ const signedOut = useSignedIn() === false;+ const [sampling, setSampling] = useState<null | "loading" | "playing">(null);+ const sampler = useRef<HTMLAudioElement | null>(null);+ const sampleSeq = useRef(0);++ useEffect(+ () => () => {+ sampler.current?.pause();+ },+ []+ );++ const sample = () => {+ const el = (sampler.current ??= new Audio());+ if (sampling) {+ sampleSeq.current++;+ el.pause();+ setSampling(null);+ return;+ }+ const seq = ++sampleSeq.current;+ setSampling("loading");+ speechSampleUrl(voice)+ .then((url) => {+ if (seq !== sampleSeq.current) return;+ el.src = url;+ el.onended = () => setSampling(null);+ el.onerror = () => setSampling(null);+ setSampling("playing");+ return el.play();+ })+ .catch((e: unknown) => {+ if (seq !== sampleSeq.current) return;+ setSampling(null);+ onError?.(e);+ });+ };++ return (+ <div className="voice-picker flex flex-col gap-1.5">+ <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">+ {title}+ </span>+ <div className="flex items-center gap-2">+ <button+ type="button"+ className="voice-sample grid size-8 shrink-0 place-items-center rounded-full bg-muted text-foreground transition-colors hover:bg-muted/70 disabled:opacity-40"+ title="Hear this voice"+ aria-label="Hear this voice"+ disabled={signedOut}+ onClick={sample}+ >+ {sampling === "loading" ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : sampling === "playing" ? (+ <Pause className="size-3.5" />+ ) : (+ <Play className="size-3.5" />+ )}+ </button>+ <div className="relative min-w-0 flex-1">+ <select+ className="voice-select w-full appearance-none truncate rounded-lg border border-input bg-transparent py-2 pr-8 pl-2.5 text-[12.5px] outline-none focus:border-ring"+ value={voice}+ onChange={(e) => writeVoice(e.target.value)}+ >+ {SPEECH_VOICES.map((v) => (+ <option key={v.id} value={v.id}>+ {v.id} · {v.style}+ </option>+ ))}+ </select>+ <ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground" />+ </div>+ </div>+ </div>+ );+}++/**+ * Self-contained "voice the subtitles" block: the voice picker plus a generate+ * button and its error line. `cueIds` scopes the readout (e.g. the cues inside+ * one clip); absent = every cue.+ */+export function GenerateSubtitlesAudio({+ cueIds,+ label = "Generate audio for subtitles",+}: {+ cueIds?: string[];+ label?: string;+}) {+ const voice = useSpeakerVoice();+ const signedOut = useSignedIn() === false;+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<{ text: string; credits?: boolean } | null>(null);+ const wanted = cueIds && new Set(cueIds);+ const cueCount = useEditor(+ (s) => s.subtitles.cues.filter((c) => c.text.trim() && (!wanted || wanted.has(c.id))).length+ );++ const generate = async () => {+ setBusy(true);+ setError(null);+ try {+ await generateSubtitlesReadout(voice, { cueIds });+ } catch (e) {+ setError(+ e instanceof Error+ ? { text: e.message, credits: e instanceof NoCreditsError }+ : { text: "Voice generation failed." }+ );+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="subtitles-audio flex flex-col gap-2.5">+ <VoicePicker+ title="Generated audio"+ onError={(e) => setError({ text: e instanceof Error ? e.message : "Could not play the sample.", credits: e instanceof NoCreditsError })}+ />+ <Button+ variant="outline"+ className="voice-readout w-full"+ disabled={cueCount === 0 || busy || signedOut}+ title={cueCount === 0 ? "Generate subtitles first" : "Voice the subtitle text and drop it on the soundtrack"}+ onClick={() => void generate()}+ >+ {busy ? <Loader2 className="animate-spin" /> : <Captions data-icon="inline-start" />}+ {label}+ </Button>+ {signedOut ? (+ <p className="voice-signin text-[11px] leading-relaxed text-muted-foreground">+ Voiceovers run on your Donkey account.{" "}+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>+ Sign in+ </a>{" "}+ to continue.+ </p>+ ) : (+ error && (+ <p className="voice-error text-[11px] leading-relaxed text-red-600">+ {error.text}+ {error.credits && (+ <>+ {" "}+ <a+ className="font-medium underline hover:no-underline"+ href={creditsUrl()}+ target="_blank"+ rel="noreferrer"+ >+ Add credits+ </a>+ </>+ )}+ </p>+ )+ )}+ </div>+ );+}diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsxindex c19b2104..442841d2 100644--- a/site/src/cut/components/desktopFolders.tsx+++ b/site/src/cut/components/desktopFolders.tsx@@ -206,6 +206,7 @@ export function FolderShelf<F extends DeskFolder>({onRename,onDelete,onDropIds,+ onDropFiles,}: {folders: F[];statOf: (id: string) => { count: number; size?: number };@@ -215,7 +216,14 @@ export function FolderShelf<F extends DeskFolder>({onRename: (id: string, name: string) => void | Promise<void>;onDelete: (id: string) => void | Promise<void>;onDropIds: (ids: string[], folderId: string) => void;+ /** Desktop files dropped onto a folder tile — dropped straight into it. */+ onDropFiles?: (files: FileList, folderId: string) => void;}) {+ // A folder tile accepts both an internal selection (its MIME) and, when the+ // host wires it up, OS files dragged from the desktop.+ const dragTypes = (e: React.DragEvent) => Array.from(e.dataTransfer.types);+ const accepts = (e: React.DragEvent) =>+ dragTypes(e).includes(mime) || (!!onDropFiles && dragTypes(e).includes("Files"));const [creating, setCreating] = useState(false);const [editingId, setEditingId] = useState<string | null>(null);const [draft, setDraft] = useState("");@@ -253,15 +261,23 @@ export function FolderShelf<F extends DeskFolder>({setEditingId(f.id);}}onDragOver={(e) => {- if (!Array.from(e.dataTransfer.types).includes(mime)) return;+ if (!accepts(e)) return;e.preventDefault();- e.dataTransfer.dropEffect = "move";+ e.dataTransfer.dropEffect = dragTypes(e).includes(mime) ? "move" : "copy";setOver(f.id);}}onDragLeave={() => setOver((o) => (o === f.id ? null : o))}onDrop={(e) => {+ if (!accepts(e)) return;e.preventDefault();setOver(null);+ // Files land in this folder; stop the drop bubbling to the page's+ // catch-all so it isn't also imported at the current level.+ if (onDropFiles && dragTypes(e).includes("Files") && e.dataTransfer.files.length) {+ e.stopPropagation();+ onDropFiles(e.dataTransfer.files, f.id);+ return;+ }onDropIds(readDragIds(e, mime), f.id);}}>diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex e5573e8b..ed2c2f1a 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -3,7 +3,21 @@import { useEffect, type RefObject } from "react";import { clipSpeed, getClipSpans, projectDuration, useEditor } from "@/cut/lib/store";import { isFullRect, projectFadeSeconds, rectOf, TRANSITION_ZOOM } from "@/cut/lib/types";-import type { ClipSpan, FrameRect, MediaAsset, OverlayClip, VideoClip } from "@/cut/lib/types";+import type { AudioClip, ClipSpan, FrameRect, MediaAsset, OverlayClip, VideoClip } from "@/cut/lib/types";++/** The gain everything else drops to at time `t` while a ducking voiceover+ * clip is audible: the lowest `duck` among the clips live then, 1 when none+ * (mirrors the export's timeline-windowed volume filters). */+function duckGainAt(audioClips: AudioClip[], t: number): number {+ let g = 1;+ for (const a of audioClips) {+ if (a.hidden || a.duck === undefined || a.duck >= 1) continue;+ const speed = a.speed && a.speed > 0 ? a.speed : 1;+ const len = Math.max(0.1, (a.out - a.in) / speed);+ if (t >= a.start && t < a.start + len) g = Math.min(g, Math.max(0, a.duck));+ }+ return g;+}// The canvas backing store is the full frame resolution (1080×1920 or// 1920×1080, set by Preview from the project aspect) so the preview stays@@ -266,7 +280,10 @@ class Engine {}}}- masterEl.volume = Math.max(0, Math.min(1, gain));+ // A live voiceover ducks the base clip's sound under it. The clip's own+ // volume rides on top (the element clamps at 1; export honors up to 1.5).+ const duck = duckGainAt(useEditor.getState().audioClips, t);+ masterEl.volume = Math.max(0, Math.min(1, gain * duck * (masterSpan.clip.volume ?? 1)));this.pauseExcept(keep);// No clear here — the tick clears once, then draws the below tracks, so the// base composites over them (a regioned base leaves them showing).@@ -407,7 +424,10 @@ class Engine {let gain = 1;if (fi > 0 && rel < fi) gain *= rel / fi;if (fo > 0 && rel > len - fo) gain *= Math.max(0, (len - rel) / fo);- el.volume = Math.max(0, Math.min(1, a.volume * gain * fadeGain));+ // A live voiceover ducks the other soundtrack clips (music) too;+ // ducking clips never duck each other.+ const dg = a.duck !== undefined && a.duck < 1 ? 1 : duckGainAt(s.audioClips, t);+ el.volume = Math.max(0, Math.min(1, a.volume * gain * dg * fadeGain));if (el.playbackRate !== speed) el.playbackRate = speed;const expected = a.in + rel * speed;if (Math.abs(el.currentTime - expected) > 0.25) el.currentTime = expected;diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex 62e3a0ab..59215d06 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -125,7 +125,7 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {}function describeAudio(- a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number; speed?: number },+ a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number; speed?: number; duck?: number },assets: Map<string, { name: string }>) {const speed = a.speed && a.speed > 0 ? a.speed : 1;@@ -139,6 +139,8 @@ function describeAudio(fadeIn: r(a.fadeIn ?? 0),fadeOut: r(a.fadeOut ?? 0),...(speed !== 1 ? { speed: r(speed) } : {}),+ // A voiceover: while it plays, other audio ducks to this gain.+ ...(a.duck !== undefined ? { duck: r(a.duck) } : {}),};}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex f4f42e73..8b9d46fc 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -1,10 +1,15 @@"use client";import { apiFetch } from "./api";+import { useGenerate } from "./generate";import { enrichAsset, ensurePeaks } from "./media";import { getClipSpans, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";import { buildAiContext } from "./aiContext";-import { FRAME, mediaUrl, TRANSITION_STYLE_IDS, type FontId, type MediaAsset, type TransitionStyle } from "./types";+import { resolveVoice, synthesizeSpeech, SPEECH_VOICES } from "./tts";+import { DUCK_DEFAULT, generateSubtitlesReadout } from "./voiceover";+import { FRAME, mediaUrl, TRANSITION_STYLE_IDS, type AudioClip, type FontId, type MediaAsset, type TransitionStyle } from "./types";++const round2 = (n: number) => Math.round(n * 100) / 100;const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);@@ -146,19 +151,22 @@ export async function runAiTool(const a = requireItem(s.audioClips, input.id, "soundtrack clip");const aSpeed = a.speed && a.speed > 0 ? a.speed : 1;const len = (a.out - a.in) / aSpeed;- const patch: Record<string, number> = {};+ const patch: Partial<AudioClip> = {};if (isNum(input.volume)) patch.volume = clamp(input.volume, 0, 1.5);if (isNum(input.fadeIn)) patch.fadeIn = clamp(input.fadeIn, 0, len / 2);if (isNum(input.fadeOut)) patch.fadeOut = clamp(input.fadeOut, 0, len / 2);if (isNum(input.start)) patch.start = Math.max(0, input.start);if (isNum(input.in)) patch.in = Math.max(0, input.in);if (isNum(input.out)) patch.out = input.out;+ // duck >= 1 clears ducking (undefined); below 1 sets the gain.+ if (isNum(input.duck)) patch.duck = input.duck >= 1 ? undefined : clamp(input.duck, 0, 1);if (isNum(patch.in ?? NaN) || isNum(patch.out ?? NaN)) {const nIn = patch.in ?? a.in;const nOut = patch.out ?? a.out;if (nOut - nIn < 0.1) throw new ToolError("Audio clip must stay at least 0.1s long.");}- if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");+ if (!("duck" in patch) && Object.keys(patch).length === 0)+ throw new ToolError("Nothing to change.");s.updateAudio(a.id, patch);return { id: a.id, ...patch };}@@ -220,6 +228,69 @@ export async function runAiTool(};}+ case "generate_image": {+ const projectId = s.projectId;+ if (!projectId) throw new ToolError("No project open.");+ const prompt = String(input.prompt ?? "").trim();+ if (!prompt) throw new ToolError("A prompt is required.");++ // Hosted image generation is synchronous and quick, so wait it out and+ // place the still — it lands in Media (and the panel job list) either way.+ const job = await useGenerate.getState().generateImage(projectId, prompt);+ if (job.status !== "done" || !job.assetId) {+ throw new ToolError(job.error ?? "Image generation failed.");+ }+ const cur = useEditor.getState();+ const asset = cur.assets.find((a) => a.id === job.assetId);+ if (!asset) throw new ToolError("The generated image did not land in the project.");+ const placed = maybeAddGeneratedClip(asset.id, input);+ return {+ assetId: asset.id,+ name: asset.name,+ kind: "image",+ duration: Math.round(asset.duration * 100) / 100,+ addedToTimeline: placed.added,+ clipId: placed.clipId,+ index: placed.index,+ };+ }++ case "generate_video": {+ const projectId = s.projectId;+ if (!projectId) throw new ToolError("No project open.");+ const prompt = String(input.prompt ?? "").trim();+ if (!prompt) throw new ToolError("A prompt is required.");+ const gen = useGenerate.getState();+ // The render is fire-and-forget below, so a signed-out user must be+ // caught here — an unprobed session (null) resolves before we claim+ // success. Deeper errors surface in the panel's job list.+ const signedIn = gen.signedIn ?? (await gen.probeNow());+ if (!signedIn) throw new ToolError("Sign in to Donkey to generate video.");++ // Veo renders can outrun the assistant tool bridge's 2-minute cap, so+ // don't block: start the job and place the clip when it lands.+ const addToTimeline = input.add_to_timeline !== false;+ const promptedIndex = isNum(input.index) ? Math.round(input.index) : undefined;+ void gen.generateVideo(projectId, prompt, {+ tier: input.tier === "high" ? "high" : "fast",+ durationSeconds: isNum(input.duration_seconds)+ ? clamp(Math.round(input.duration_seconds), 4, 8)+ : undefined,+ onDone: addToTimeline+ ? (asset) => maybeAddGeneratedClip(asset.id, { index: promptedIndex })+ : undefined,+ });+ return {+ kind: "video",+ started: true,+ addToTimeline,+ note:+ "Rendering with Veo — it lands in Media" ++ (addToTimeline ? " and on the timeline" : "") ++ " in a minute or two. Track it in the Video panel.",+ };+ }+case "subtitles_generate": {if (typeof input.locale === "string" && input.locale) {s.setSubtitlesView({ locale: input.locale });@@ -261,6 +332,62 @@ export async function runAiTool(};}+ case "subtitles_from_visuals": {+ if (typeof input.locale === "string" && input.locale)+ s.setSubtitlesView({ locale: input.locale });+ await s.generateVisualSubtitles();+ const cur = useEditor.getState();+ if (cur.subtitleStatus === "error")+ throw new ToolError(cur.subtitleError ?? "Visual captioning failed.");+ if (cur.subtitles.cues.length > 0 && cur.timelineH < 276) cur.setTimelineH(276);+ return { status: cur.subtitleStatus, cues: cur.subtitles.cues.length };+ }++ case "list_voices": {+ // Gemini's prebuilt voice catalog is fixed and ships hardcoded.+ return {+ voices: SPEECH_VOICES.map((v) => ({ id: v.id, style: v.style })),+ total: SPEECH_VOICES.length,+ };+ }++ case "voiceover_generate": {+ if (typeof input.script !== "string" || !input.script.trim())+ throw new ToolError("script is required.");+ const start = isNum(input.start) ? Math.max(0, input.start) : s.currentTime;+ const lead = input.script.trim().split(/\s+/).slice(0, 4).join(" ");+ return synthesizeAndPlace(+ [{ text: input.script, at: 0 }],+ `AI voice — ${lead}`,+ start,+ input+ );+ }++ case "read_subtitles_aloud": {+ if (!s.subtitles.cues.some((c) => c.text.trim()))+ throw new ToolError("No subtitles to read — generate subtitles first.");+ const voice = resolveVoice(typeof input.voice === "string" ? input.voice : undefined);+ // The shared readout also re-times the cues to the generated voice's+ // pace, keeping the word highlighter in step.+ const out = await generateSubtitlesReadout(voice, {+ direction:+ typeof input.direction === "string" && input.direction.trim()+ ? input.direction.trim()+ : undefined,+ duck: isNum(input.duck) ? clamp(input.duck, 0, 1) : undefined,+ });+ const sel = useEditor.getState().selection;+ return {+ audioClipId: sel?.kind === "audio" ? sel.id : null,+ voice,+ start: round2(out.start),+ duration: round2(out.asset.duration),+ duck: out.duck,+ lines: out.lines,+ };+ }+case "subtitles_set_view": {const patch: { showOnVideo?: boolean; showOnTimeline?: boolean } = {};if (typeof input.showOnVideo === "boolean") patch.showOnVideo = input.showOnVideo;@@ -397,12 +524,71 @@ export async function runAiTool(}}+/** Synthesize speech segments with hosted Gemini voices (the user's Donkey+ * sign-in and credits), register the media, and drop one soundtrack clip+ * (voiceovers duck other audio by default). Shared by voiceover_generate and+ * read_subtitles_aloud. */+async function synthesizeAndPlace(+ segments: { text: string; at: number }[],+ name: string,+ start: number,+ input: Record<string, unknown>+) {+ const projectId = useEditor.getState().projectId;+ if (!projectId) throw new ToolError("No project open.");+ const voice = resolveVoice(typeof input.voice === "string" ? input.voice : undefined);+ const direction =+ typeof input.direction === "string" && input.direction.trim()+ ? input.direction.trim()+ : undefined;+ const duck = isNum(input.duck) ? clamp(input.duck, 0, 1) : DUCK_DEFAULT;+ const { asset, offset } = await synthesizeSpeech(projectId, segments, {+ voice,+ direction,+ name,+ });+ const cur = useEditor.getState();+ cur.addAsset(asset);+ // A single script lands at `start`; a multi-line readout is pre-offset to its+ // first cue, so it lands at that offset.+ const at = segments.length === 1 ? start : offset;+ cur.addAudioFromAsset(asset.id, at, { duck: duck < 1 ? duck : undefined });+ void enrichAsset(asset);+ const sel = useEditor.getState().selection;+ return {+ audioClipId: sel?.kind === "audio" ? sel.id : null,+ voice,+ start: round2(at),+ duration: round2(asset.duration),+ duck: duck < 1 ? duck : null,+ };+}+function requireItem<T extends { id: string }>(pool: T[], id: unknown, label: string): T {const item = pool.find((x) => x.id === String(id ?? ""));if (!item) throw new ToolError(`No ${label} with id ${String(id)}. Call get_state for current ids.`);return item;}+/** Append a generated asset to the video track (default) at an optional index.+ * Shared by generate_image (inline) and generate_video (on the render's+ * completion). Respects add_to_timeline:false. */+function maybeAddGeneratedClip(+ assetId: string,+ input: { add_to_timeline?: unknown; index?: unknown }+): { added: boolean; clipId: string | null; index: number | null } {+ if (input.add_to_timeline === false) return { added: false, clipId: null, index: null };+ const s = useEditor.getState();+ if (!s.assets.some((a) => a.id === assetId)) return { added: false, clipId: null, index: null };+ s.addClipFromAsset(assetId); // lands at the end, selected+ const sel = useEditor.getState().selection;+ const clipId = sel?.kind === "clip" ? sel.id : null;+ const count = useEditor.getState().clips.length;+ const index = isNum(input.index) ? clamp(Math.round(input.index), 0, count - 1) : count - 1;+ if (clipId && index !== count - 1) s.moveClip(clipId, index);+ return { added: true, clipId, index };+}+function titlePatch(input: Record<string, unknown>) {const patch: Record<string, unknown> = {};if (typeof input.text === "string" && input.text.trim()) patch.text = input.text;diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 814b286e..5232d5b9 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -2,7 +2,7 @@import { apiFetch, apiUrl } from "./api";import { clipSpeed, getClipSpans, projectDuration } from "./store";-import { captionStyle, cueOverlay } from "./subtitles";+import { captionStyle, cueOverlay, cueWordWindows } from "./subtitles";import { renderOverlayPng } from "./textRender";import { FRAME } from "./types";import type {@@ -139,6 +139,7 @@ async function buildExportForm(in: sp.clip.in,out: sp.clip.out,muted: sp.clip.muted,+ volume: sp.clip.volume ?? 1,fit: sp.clip.fit ?? "fit",panX: sp.clip.panX ?? 0,panY: sp.clip.panY ?? 0,@@ -206,6 +207,7 @@ async function buildExportForm(fadeIn: a.fadeIn ?? 0,fadeOut: a.fadeOut ?? 0,speed: a.speed,+ duck: a.duck,}));const overlays: { file: string; start: number; end: number }[] = [];@@ -218,19 +220,41 @@ async function buildExportForm(overlays.push({ file: key, start: o.start, end: Math.min(o.end, duration) });}+ // Subtitle stills travel in their own spec lane: the server plays them as+ // one concat-demuxer slideshow (with a transparent filler frame for gaps),+ // so karaoke word windows don't each become an ffmpeg input.+ const captions: { file: string; start: number; end: number }[] = [];if (doc.subtitles.showOnVideo) {const capStyle = captionStyle(doc.subtitles.style);for (let i = 0; i < doc.subtitles.cues.length; i++) {const cue = doc.subtitles.cues[i];if (cue.start >= duration || !cue.text.trim()) continue;- const png = await renderOverlayPng(- cueOverlay(cue, capStyle, i === 0),- settings.width,- settings.height+ // Karaoke burns one frame per word window (the spoken word accented);+ // otherwise the whole cue is a single still.+ const windows = doc.subtitles.wordHighlight+ ? cueWordWindows(cue)+ : [{ start: cue.start, end: cue.end }];+ for (let wi = 0; wi < windows.length; wi++) {+ const win = windows[wi];+ if (win.start >= duration) break;+ const png = await renderOverlayPng(+ cueOverlay(cue, capStyle, i === 0, doc.subtitles, doc.subtitles.wordHighlight ? wi : undefined),+ settings.width,+ settings.height+ );+ const key = windows.length > 1 ? `sub_${i}_${wi}.png` : `sub_${i}.png`;+ form.append(key, png, key);+ captions.push({ file: key, start: win.start, end: Math.min(win.end, duration) });+ }+ }+ if (captions.length > 0) {+ const blank = document.createElement("canvas");+ blank.width = settings.width;+ blank.height = settings.height;+ const png = await new Promise<Blob>((resolve, reject) =>+ blank.toBlob((b) => (b ? resolve(b) : reject(new Error("Could not render captions."))), "image/png"));- const key = `sub_${i}.png`;- form.append(key, png, key);- overlays.push({ file: key, start: cue.start, end: Math.min(cue.end, duration) });+ form.append("sub_blank.png", png, "sub_blank.png");}}@@ -247,6 +271,7 @@ async function buildExportForm(audio,overlayVideos,overlays,+ captions,}));return form;diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsnew file mode 100644index 00000000..e7228c91--- /dev/null+++ b/site/src/cut/lib/generate.ts@@ -0,0 +1,344 @@+"use client";++import { useEffect } from "react";+import { create } from "zustand";+import { apiFetch } from "./api";+import { enrichAsset, importFileToProject } from "./media";+import { useEditor } from "./store";+import { mediaUrl, type MediaAsset } from "./types";++// AI generation jobs, held outside the panels so a tab switch (which unmounts+// them) doesn't orphan a running generation — Veo renders take minutes.+//+// Generation runs on Donkey's hosted inference routes with the user's Donkey+// sign-in and credits. The cut hosts serve the same Next app and the auth+// cookie rides the registrable domain, so these are plain same-origin calls.+// Finished media lands back in the project through the local engine: videos+// upload as regular files, images bake into still clips.++export interface GenerateJob {+ id: string;+ projectId: string;+ kind: "image" | "video";+ prompt: string;+ status: "running" | "done" | "error";+ error?: string;+ /** The project asset the finished generation landed as. */+ assetId?: string;+}++interface GenerateState {+ /** Whether a Donkey session exists; null = not probed yet. */+ signedIn: boolean | null;+ jobs: GenerateJob[];+ probe: () => void;+ /** Awaitable probe, for callers that must know before acting (the AI+ * assistant's generate tools); resolves the fresh signed-in answer. */+ probeNow: () => Promise<boolean>;+ /** Kick off a generation. Returns when it settles, resolving to the final+ * job (status "done" with assetId, or "error" with a message) so the AI+ * assistant can act on the result; the panel just fires and forgets. */+ generateImage: (projectId: string, prompt: string) => Promise<GenerateJob>;+ generateVideo: (+ projectId: string,+ prompt: string,+ opts?: {+ tier?: "fast" | "high";+ durationSeconds?: number;+ /** Called once with the landed asset when the render completes and the+ * project is still open — lets the AI place the clip after a background+ * render it couldn't wait out (the assistant tool bridge caps at 2min). */+ onDone?: (asset: MediaAsset) => void;+ }+ ) => Promise<GenerateJob>;+ dismiss: (id: string) => void;+}++const CLIENT_ID = "donkey-cut";+const REFRESH_MS = 8000;+const VIDEO_DEADLINE_MS = 12 * 60_000;++const uid = () => crypto.randomUUID().slice(0, 8);+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++/** Display name for the asset: the prompt, tidied and capped. */+const promptName = (prompt: string) => {+ const line = prompt.trim().replace(/\s+/g, " ");+ return line.length > 60 ? `${line.slice(0, 57)}…` : line;+};++const promptSlug = (prompt: string) =>+ prompt+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 40) || "generated";++/** The Donkey sign-in URL for the current host (cut.* → apex). Image, video,+ * and voiceover all run on the user's Donkey account, so every generation+ * surface links here when signed out. */+export function signInUrl(): string {+ if (typeof window === "undefined") return "/sign-in";+ const { protocol, host, href } = window.location;+ // Sign-in runs on the apex (Google's redirect_uri is pinned there), but bring+ // the user back to the Cut page they started from once it completes.+ const apex = `${protocol}//${host.replace(/^cut\./, "")}`;+ return `${apex}/sign-in?callbackURL=${encodeURIComponent(href)}`;+}++/** The Donkey settings page where credits are bought (cut.* → apex). Linked+ * from any generation error caused by an empty balance. */+export function creditsUrl(): string {+ if (typeof window === "undefined") return "/app/settings";+ const { protocol, host } = window.location;+ const apex = `${protocol}//${host.replace(/^cut\./, "")}`;+ return `${apex}/app/settings`;+}++interface GenerationOutput {+ dataBase64?: string;+ contentType?: string;+ filename?: string;+ url?: string;+}++interface GenerationResponse {+ id: string;+ status: string;+ provider: string;+ model: string;+ providerJobId: string | null;+ providerGenerationId: string | null;+ providerPollingUrl: string | null;+ outputs: GenerationOutput[];+ error?: unknown;+ metadata?: Record<string, unknown>;+}++/** POST one of Donkey's hosted inference routes with the user's session. */+const hostedPost = (path: string, body: unknown) =>+ fetch(path, {+ method: "POST",+ headers: { "Content-Type": "application/json", "x-donkey-client-id": CLIENT_ID },+ body: JSON.stringify(body),+ });++async function readError(res: Response, fallback: string): Promise<string> {+ if (res.status === 401) return "Sign in to Donkey to generate media.";+ const body = (await res.json().catch(() => null)) as {+ error?: unknown;+ message?: unknown;+ } | null;+ const message = [body?.message, body?.error].find(+ (v): v is string => typeof v === "string" && v.length > 0+ );+ if (res.status === 402) return message ?? "Not enough Donkey credits — top up to generate.";+ return message ?? fallback;+}++const providerError = (error: unknown): string | null => {+ if (typeof error === "string" && error) return error;+ if (error && typeof error === "object" && "message" in error) {+ const m = (error as { message?: unknown }).message;+ if (typeof m === "string" && m) return m;+ }+ return null;+};++function bytesFromBase64(b64: string): Uint8Array<ArrayBuffer> {+ const bin = atob(b64);+ const bytes = new Uint8Array(new ArrayBuffer(bin.length));+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ return bytes;+}++export const useGenerate = create<GenerateState>((set, get) => {+ // A single session probe is in flight at a time, but the answer stays+ // re-checkable for the page's whole life: a sign-in can complete in another+ // tab, or the session cookie can land a beat after this page loads.+ let probing: Promise<boolean> | null = null;++ const update = (id: string, patch: Partial<GenerateJob>) =>+ set((s) => ({ jobs: s.jobs.map((j) => (j.id === id ? { ...j, ...patch } : j)) }));++ const fail = (id: string, err: unknown) =>+ update(id, { status: "error", error: err instanceof Error ? err.message : String(err) });++ // The job after it has settled, for callers that awaited the run.+ const settled = (id: string, fallback: GenerateJob): GenerateJob =>+ get().jobs.find((j) => j.id === id) ?? fallback;++ // The media file exists either way; only the open project can record it.+ // Returns whether it was adopted (false when the user switched projects).+ const adopt = (projectId: string, asset: MediaAsset): boolean => {+ if (useEditor.getState().projectId !== projectId) return false;+ useEditor.getState().addAsset(asset);+ void enrichAsset(asset);+ return true;+ };++ return {+ signedIn: null,+ jobs: [],++ probe: () => {+ void get().probeNow();+ },++ probeNow: () => {+ probing ??= fetch("/api/auth/get-session", { cache: "no-store" })+ .then((r) => (r.ok ? r.json() : null))+ .then((s) => {+ const signedIn = Boolean((s as { user?: unknown } | null)?.user);+ set({ signedIn });+ return signedIn;+ })+ // A transient failure shouldn't knock a known session back to signed-out;+ // only fall to false when we never learned otherwise.+ .catch(() => {+ const signedIn = get().signedIn ?? false;+ set({ signedIn });+ return signedIn;+ })+ .finally(() => {+ probing = null;+ });+ return probing;+ },++ generateImage: (projectId, prompt) => {+ const job: GenerateJob = { id: uid(), projectId, kind: "image", prompt, status: "running" };+ set((s) => ({ jobs: [job, ...s.jobs] }));+ return (async () => {+ try {+ const aspect = useEditor.getState().aspect;+ const res = await hostedPost("/api/inference/assets", {+ kind: "image",+ // The image route takes no aspect parameter; steer it in the prompt.+ prompt: `${prompt}\n\nCompose the image in a ${+ aspect === "16:9" ? "16:9 widescreen" : "9:16 vertical"+ } frame.`,+ });+ if (!res.ok) throw new Error(await readError(res, "Image generation failed."));+ const gen = (await res.json()) as GenerationResponse;+ const out = gen.outputs.find((o) => o.dataBase64);+ if (!out?.dataBase64) throw new Error("The provider returned no image.");++ const form = new FormData();+ form.append(+ "file",+ new Blob([bytesFromBase64(out.dataBase64)], {+ type: out.contentType ?? "image/png",+ }),+ out.filename ?? "image.png"+ );+ form.append("name", promptName(prompt));+ const baked = await apiFetch(`/api/cut/projects/${projectId}/still`, {+ method: "POST",+ body: form,+ });+ const body = (await baked.json()) as MediaAsset & { error?: string };+ if (!baked.ok || !body.fileName) {+ throw new Error(body.error ?? "Could not add the image to the project.");+ }+ const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName) };+ adopt(projectId, asset);+ update(job.id, { status: "done", assetId: asset.id });+ } catch (err) {+ fail(job.id, err);+ }+ return settled(job.id, job);+ })();+ },++ generateVideo: (projectId, prompt, opts) => {+ const job: GenerateJob = { id: uid(), projectId, kind: "video", prompt, status: "running" };+ set((s) => ({ jobs: [job, ...s.jobs] }));+ return (async () => {+ try {+ const res = await hostedPost("/api/inference/assets", {+ kind: "video",+ prompt,+ parameters: {+ tier: opts?.tier === "high" ? "high" : "fast",+ aspectRatio: useEditor.getState().aspect,+ ...(opts?.durationSeconds ? { durationSeconds: opts.durationSeconds } : {}),+ },+ });+ if (!res.ok) throw new Error(await readError(res, "Video generation failed."));+ let gen = (await res.json()) as GenerationResponse;++ const deadline = Date.now() + VIDEO_DEADLINE_MS;+ while (gen.status === "in_progress") {+ if (Date.now() > deadline) throw new Error("Veo is taking too long — try again.");+ await sleep(REFRESH_MS);+ const poll = await hostedPost("/api/inference/assets/refresh", {+ id: gen.id,+ kind: "video",+ provider: gen.provider,+ model: gen.model,+ providerJobId: gen.providerJobId,+ providerGenerationId: gen.providerGenerationId,+ providerPollingUrl: gen.providerPollingUrl,+ metadata: gen.metadata ?? {},+ });+ if (!poll.ok) throw new Error(await readError(poll, "Video generation failed."));+ gen = (await poll.json()) as GenerationResponse;+ }+ if (gen.status !== "completed") {+ throw new Error(providerError(gen.error) ?? "Video generation failed.");+ }++ const out = gen.outputs.find((o) => o.dataBase64) ?? gen.outputs.find((o) => o.url);+ const fileName = `ai-${promptSlug(prompt)}.mp4`;+ let file: File;+ if (out?.dataBase64) {+ file = new File([bytesFromBase64(out.dataBase64)], fileName, {+ type: out.contentType ?? "video/mp4",+ });+ } else if (out?.url) {+ const dl = await fetch(out.url);+ if (!dl.ok) throw new Error("Could not download the generated video.");+ file = new File([await dl.arrayBuffer()], fileName, {+ type: out.contentType ?? "video/mp4",+ });+ } else {+ throw new Error("The provider returned no video.");+ }++ const asset = await importFileToProject(projectId, file);+ if (!asset) throw new Error("Could not import the generated video.");+ asset.name = promptName(prompt);+ if (adopt(projectId, asset)) opts?.onDone?.(asset);+ update(job.id, { status: "done", assetId: asset.id });+ } catch (err) {+ fail(job.id, err);+ }+ return settled(job.id, job);+ })();+ },++ dismiss: (id) => set((s) => ({ jobs: s.jobs.filter((j) => j.id !== id) })),+ };+});++/** Donkey sign-in state for the generation surfaces. Probes on mount and again+ * whenever the tab regains focus, so signing in — in this tab's round trip or a+ * separate tab — flips the UI without a manual reload. Null until first known. */+export function useSignedIn(): boolean | null {+ const signedIn = useGenerate((s) => s.signedIn);+ useEffect(() => {+ const probe = () => useGenerate.getState().probe();+ probe();+ const onVisible = () => {+ if (document.visibilityState === "visible") probe();+ };+ window.addEventListener("focus", probe);+ document.addEventListener("visibilitychange", onVisible);+ return () => {+ window.removeEventListener("focus", probe);+ document.removeEventListener("visibilitychange", onVisible);+ };+ }, []);+ return signedIn;+}diff --git a/site/src/cut/lib/hosts.ts b/site/src/cut/lib/hosts.tsnew file mode 100644index 00000000..b116e10b--- /dev/null+++ b/site/src/cut/lib/hosts.ts@@ -0,0 +1,13 @@+// Hosts that serve the Cut app at their root. On these, the src/proxy.ts rewrite+// maps "/…" to the app's real "/cut/…" routes, so links stay clean ("/p/[id]").+//+// Local dev is deliberately absent: there Cut is served from the apex under+// /cut, so its session cookie is same-origin. A cookie set on `localhost` never+// reaches a `cut.localhost` subdomain in Chrome, so the subdomain can't hold a+// session — the /cut path on the apex is what dev uses instead.+export const CUT_HOSTS = new Set(["cut.donkeyuse.com"]);++export function isCutHost(host: string | null | undefined): boolean {+ if (!host) return false;+ return CUT_HOSTS.has(host.split(":")[0]);+}diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex 4dc981b1..6a1deb4b 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -2,11 +2,68 @@import { apiFetch } from "./api";import { useEditor } from "./store";-import type { MediaAsset } from "./types";+import type { AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip } from "./types";import { mediaUrl } from "./types";const uid = () => crypto.randomUUID().slice(0, 8);+/** True when a dropped OS file is something Cut can turn into a project. */+export function isMediaFile(file: File) {+ return (+ file.type.startsWith("video/") ||+ file.type.startsWith("audio/") ||+ isVideoFile(file) ||+ isAudioFile(file)+ );+}++/** Create a fresh project seeded from a single desktop file: upload the media,+ * lay it on the timeline, and persist — no editor round-trip. Returns the new+ * project's id, or null if the file isn't video/audio. */+export async function createProjectFromFile(+ file: File,+ folderId: string | null+): Promise<string | null> {+ if (!isMediaFile(file)) return null;+ const name = file.name.replace(/\.[^./]+$/, "") || "Untitled";+ const res = await apiFetch("/api/cut/projects", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name, folderId }),+ });+ const project = (await res.json()) as ProjectSummary;++ const asset = await importFileToProject(project.id, file);+ // Media the engine rejects leaves an empty project rather than a dangling id.+ if (!asset) return project.id;++ const stored: StoredAsset = {+ id: asset.id,+ fileName: asset.fileName,+ name: asset.name,+ type: asset.type,+ duration: asset.duration,+ ...(asset.width !== undefined ? { width: asset.width } : {}),+ ...(asset.height !== undefined ? { height: asset.height } : {}),+ };+ const doc: Partial<{ assets: StoredAsset[]; clips: VideoClip[]; audioClips: AudioClip[] }> = {+ assets: [stored],+ };+ if (asset.type === "video") {+ doc.clips = [{ id: uid(), assetId: asset.id, in: 0, out: asset.duration, muted: false }];+ } else {+ doc.audioClips = [+ { id: uid(), assetId: asset.id, start: 0, in: 0, out: asset.duration, volume: 1 },+ ];+ }+ await apiFetch(`/api/cut/projects/${project.id}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(doc),+ });+ return project.id;+}+export function isVideoFile(file: File) {return file.type.startsWith("video/") || /\.(mp4|mov|m4v|webm|mkv)$/i.test(file.name);}@@ -69,6 +126,32 @@ export async function importFileToProject(return asset;}+/** Build a runtime asset for a media file the engine already wrote into the+ * project folder (freeze frames, AI generations) — probe metadata, no upload. */+export async function assetFromProjectFile(+ projectId: string,+ fileName: string,+ name: string+): Promise<MediaAsset> {+ const url = mediaUrl(projectId, fileName);+ const v = await loadVideoMeta(url);+ const asset: MediaAsset = {+ id: uid(),+ fileName,+ name,+ type: "video",+ duration: v.duration,+ url,+ };+ if (v.videoWidth === 0) {+ asset.type = "audio";+ } else {+ asset.width = v.videoWidth;+ asset.height = v.videoHeight;+ }+ return asset;+}+/** Generate filmstrip thumbnails / waveform peaks and merge them into the* store. Safe to call repeatedly; skips assets that are already enriched. */export async function enrichAsset(asset: MediaAsset) {@@ -128,7 +211,7 @@ function loadVideoMeta(url: string): Promise<HTMLVideoElement> {});}-function loadAudioDuration(url: string): Promise<number> {+export function loadAudioDuration(url: string): Promise<number> {return new Promise((resolve, reject) => {const a = new Audio();a.preload = "metadata";diff --git a/site/src/cut/lib/nav.tsx b/site/src/cut/lib/nav.tsxnew file mode 100644index 00000000..3d178ad3--- /dev/null+++ b/site/src/cut/lib/nav.tsx@@ -0,0 +1,50 @@+"use client";++import { createContext, useContext, type ReactNode } from "react";++// The Cut app's routes live under /cut/*. On the cut.* production host a proxy+// rewrite (src/proxy.ts) serves them at the root, so links are root-relative+// (base ""). In local dev the app is served from the apex under /cut so its+// session cookie is same-origin, and links carry the "/cut" base. The base is+// resolved on the server from the request host (see the cut layout) and handed+// to the client here.+const CutBaseContext = createContext("");++export function CutBaseProvider({ base, children }: { base: string; children: ReactNode }) {+ return <CutBaseContext.Provider value={base}>{children}</CutBaseContext.Provider>;+}++export function useCutBase(): string {+ return useContext(CutBaseContext);+}++// The project editor can be reached from either home tab. The origin tab rides+// along in the project URL (?from=…) so the editor's back button returns to the+// tab you opened the project from — Projects or Library.+export type CutTab = "projects" | "library";++/** Which home tab a pathname is on (base-agnostic). */+export function tabForPath(pathname: string): CutTab {+ return pathname.endsWith("/library") ? "library" : "projects";+}++/** Home tab URL under the given base. Projects is the base root. */+export function homeHref(base: string, tab: CutTab): string {+ return tab === "library" ? `${base}/library` : base || "/";+}++/** Project editor URL that remembers the tab it was opened from. The default+ * tab carries no query so the common URL stays clean. */+export function projectHref(base: string, id: string, from: CutTab): string {+ return from === "library" ? `${base}/p/${id}?from=library` : `${base}/p/${id}`;+}++/** Where the editor's back button goes, and the tab it is named for. An unknown+ * origin falls back to Projects. */+export function backTarget(+ base: string,+ from: string | null | undefined+): { href: string; tab: CutTab } {+ const tab: CutTab = from === "library" ? "library" : "projects";+ return { href: homeHref(base, tab), tab };+}diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 3430e1c2..f64092af 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -25,6 +25,7 @@ import { apiFetch } from "./api";import { emptySubtitles, isCrossStyle, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";import { readTextStyle } from "./textStyle";import { loadUiState, saveUiState } from "./uiState";+import { captureTimelineFrames } from "./visualFrames";const uid = () => crypto.randomUUID().slice(0, 8);@@ -132,7 +133,10 @@ interface EditorState {/** Add a video clip from an asset. With `index`, insert at that position on* the magnetic video track; otherwise append. */addClipFromAsset: (assetId: string, index?: number) => void;- addAudioFromAsset: (assetId: string, start?: number) => void;+ /** Add a soundtrack clip from an audio asset at `start` (default: the+ * playhead). `opts.duck` marks it a voiceover that lowers everything else+ * to that gain while it plays. */+ addAudioFromAsset: (assetId: string, start?: number, opts?: { duck?: number }) => void;addOverlay: () => void;/** Move a title to a title track (row); lanes are renumbered to stay* contiguous, so empty tracks collapse and a past-the-end lane adds one. */@@ -176,10 +180,13 @@ interface EditorState {setNotes: (patch: Partial<{ text: string; publishedAt: string; links: string[] }>) => void;/** Kick off (and poll) an on-device transcription of the current cut. */generateSubtitles: () => Promise<void>;+ /** Caption the cut from its picture alone (no audio needed): sample frames+ * along the timeline and have the AI write timed narration cues. */+ generateVisualSubtitles: () => Promise<void>;/** Transcribe (if needed) then rewrite the cues into social captions in the* given style, one-to-one so cue timings are preserved. */generateCaptions: (style: "clean" | "hook" | "punchy") => Promise<void>;- setSubtitlesView: (patch: Partial<Pick<SubtitlesBlock, "showOnVideo" | "showOnTimeline" | "locale" | "style">>) => void;+ setSubtitlesView: (patch: Partial<Pick<SubtitlesBlock, "showOnVideo" | "showOnTimeline" | "locale" | "style" | "x" | "y" | "wordHighlight" | "accentMode" | "accentColor">>) => void;/** Commit a cue's edited text (empty text deletes the cue). */setCueText: (id: string, text: string) => void;/** Split a cue at a character offset — at real word timings when known. */@@ -187,6 +194,10 @@ interface EditorState {mergeCueIntoPrev: (id: string) => void;deleteCue: (id: string) => void;updateCueTransient: (id: string, patch: Partial<SubtitleCue>) => void;+ /** Re-time listed cues to a generated voiceover: set each cue's [start, end]+ * and spread its words across the new span (the AI voice paces differently+ * from the original recording, so the word highlighter would otherwise drift). */+ retimeCues: (entries: { id: string; start: number; end: number }[]) => void;sortCues: () => void;deleteSelection: () => void;/** Timeline window [start, end) spanned by the current selection, or null if@@ -486,7 +497,7 @@ export const useEditor = create<EditorState>((set, get) => {});},- addAudioFromAsset: (assetId, start) => {+ addAudioFromAsset: (assetId, start, opts) => {const asset = get().assets.find((a) => a.id === assetId);if (!asset || asset.type !== "audio") return;push();@@ -497,6 +508,9 @@ export const useEditor = create<EditorState>((set, get) => {in: 0,out: asset.duration,volume: 1,+ ...(opts?.duck !== undefined && opts.duck < 1+ ? { duck: Math.max(0, opts.duck) }+ : {}),};set((s) => ({audioClips: [...s.audioClips, clip],@@ -964,7 +978,7 @@ export const useEditor = create<EditorState>((set, get) => {if (!c) continue;const mi = mediaFor(c.assetId);if (mi == null) continue;- audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed });+ audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed, duck: c.duck });} else if (sel.kind === "text") {const o = s.overlays.find((x) => x.id === sel.id);if (o) texts.push({ ...o, start: o.start - start0, end: o.end - start0 });@@ -1026,6 +1040,7 @@ export const useEditor = create<EditorState>((set, get) => {...(a.fadeIn ? { fadeIn: a.fadeIn } : {}),...(a.fadeOut ? { fadeOut: a.fadeOut } : {}),...(a.speed ? { speed: a.speed } : {}),+ ...(a.duck !== undefined && a.duck < 1 ? { duck: a.duck } : {}),}));const newTexts: TextOverlay[] = template.texts.map((o) => ({...o,@@ -1178,6 +1193,53 @@ export const useEditor = create<EditorState>((set, get) => {}},+ generateVisualSubtitles: async () => {+ const s = get();+ if (!s.projectId || s.subtitleStatus === "running") return;+ const projectId = s.projectId;+ const spans = getClipSpans(s.clips, s.assets);+ if (spans.length === 0) {+ set({ subtitleStatus: "error", subtitleError: "Add a video to the timeline first." });+ return;+ }+ const duration = totalDuration(s.clips);+ set({ subtitleStatus: "running", subtitleError: null });+ try {+ const frames = await captureTimelineFrames(spans);+ if (frames.length === 0) throw new Error("Could not read any frames from the cut.");+ const res = await apiFetch("/api/cut/ai/visual-subtitles", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ frames, duration, locale: s.subtitles.locale ?? "en-US" }),+ });+ const body = (await res.json()) as {+ cues?: { start: number; end: number; text: string }[];+ error?: string;+ };+ if (!res.ok || !Array.isArray(body.cues)) {+ throw new Error(body.error ?? "Captioning failed.");+ }+ if (get().projectId !== projectId) return; // switched projects mid-run+ const cues: SubtitleCue[] = body.cues.map((c) => ({+ id: uid(),+ start: c.start,+ end: c.end,+ text: c.text,+ }));+ push();+ set((cur) => ({+ subtitles: { ...cur.subtitles, cues, generatedAt: Date.now() },+ subtitleStatus: cues.length > 0 ? "ready" : "empty",+ }));+ } catch (err) {+ if (get().projectId !== projectId) return;+ set({+ subtitleStatus: "error",+ subtitleError: err instanceof Error ? err.message : String(err),+ });+ }+ },+generateCaptions: async (style) => {const s = get();if (!s.projectId || s.subtitleStatus === "running") return;@@ -1356,6 +1418,25 @@ export const useEditor = create<EditorState>((set, get) => {},})),+ retimeCues: (entries) => {+ if (entries.length === 0) return;+ const byId = new Map(entries.map((e) => [e.id, e]));+ if (!get().subtitles.cues.some((c) => byId.has(c.id))) return;+ push();+ set((s) => ({+ subtitles: {+ ...s.subtitles,+ cues: s.subtitles.cues.map((c) => {+ const e = byId.get(c.id);+ if (!e) return c;+ const start = e.start;+ const end = Math.max(start + 0.05, e.end);+ return { ...c, start, end, words: spreadWordsEvenly(c.text, start, end) };+ }),+ },+ }));+ },+sortCues: () =>set((s) => ({subtitles: {@@ -1506,7 +1587,7 @@ export function serializeDoc(s: {subtitles: SubtitlesBlock;}): Partial<ProjectDoc> {const assets: StoredAsset[] = s.assets.map(- ({ id, fileName, name, type, duration, width, height }) => ({+ ({ id, fileName, name, type, duration, width, height, origin }) => ({id,fileName,name,@@ -1514,6 +1595,7 @@ export function serializeDoc(s: {duration,...(width !== undefined ? { width } : {}),...(height !== undefined ? { height } : {}),+ ...(origin !== undefined ? { origin } : {}),}));return {@@ -1524,8 +1606,8 @@ export function serializeDoc(s: {overlayClips: s.overlayClips,overlays: s.overlays,aspect: s.aspect,- ...(s.fadeIn > 0 ? { fadeIn: s.fadeIn } : {}),- ...(s.fadeOut > 0 ? { fadeOut: s.fadeOut } : {}),+ fadeIn: s.fadeIn,+ fadeOut: s.fadeOut,subtitles: s.subtitles,publish: { ...s.publish },notes: { ...s.notes, links: [...s.notes.links] },@@ -1616,6 +1698,28 @@ export function projectDuration(s: {* moves by that clip's shift; one over a removed gap collapses to the join;* one past everything shifts by the whole-timeline length change.*/+/** Spread a cue's words across [start, end], each word's slice proportional to+ * its length. Used when re-timing captions to a generated voiceover, which+ * carries no per-word timestamps of its own. */+function spreadWordsEvenly(+ text: string,+ start: number,+ end: number,+): { t0: number; t1: number; w: string }[] | undefined {+ const parts = text.split(/\s+/).filter(Boolean);+ if (parts.length === 0) return undefined;+ const lengths = parts.map((w) => Math.max(1, w.length));+ const total = lengths.reduce((a, b) => a + b, 0);+ const span = Math.max(0, end - start);+ let acc = 0;+ return parts.map((w, i) => {+ const t0 = start + (acc / total) * span;+ acc += lengths[i];+ const t1 = start + (acc / total) * span;+ return { t0, t1, w };+ });+}+function makeRipple(oldClips: VideoClip[], newClips: VideoClip[], assets: MediaAsset[]) {const newStart = new Map(getClipSpans(newClips, assets).map((sp) => [sp.clip.id, sp.start]));const totalDelta = totalDuration(newClips) - totalDuration(oldClips);diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.tsindex c0f15ded..92045c76 100644--- a/site/src/cut/lib/subtitles.ts+++ b/site/src/cut/lib/subtitles.ts@@ -1,5 +1,7 @@import { formatTime } from "./time";-import type { FontId, SubtitleCue, TextOverlay } from "./types";+import type { CaptionStyleId, FontId, SubtitleCue, TextOverlay, WordAccentMode } from "./types";++export type { CaptionStyleId } from "./types";/** Caption look shared by the preview layer and the export burn-in —* TikTok-style bold white on a translucent plate, low center. */@@ -14,8 +16,6 @@ export const SUB_STYLE = {plate: true,} as const;-export type CaptionStyleId = "clean" | "hook" | "punchy";-/** A caption preset: the shared subtitle look plus optional opener emphasis* (a bigger, punchier first line). */export interface CaptionStyle {@@ -33,6 +33,40 @@ export interface CaptionStyle {plateOpacity?: number;/** Multiply the opening cue's size, so the hook lands bigger. */openerScale?: number;+ /** Karaoke accent for the spoken word; absent = DEFAULT_ACCENT. */+ accent?: string;+ /** How the spoken word lights up: an accent box behind it (plate styles) or+ * the accent color plus underline (open text). Absent = underline. */+ accentMode?: WordAccentMode;+ /** Word color on an accent box; absent = auto contrast. */+ accentText?: string;+}++/** Spoken-word accent for styles that don't pick their own. */+export const DEFAULT_ACCENT = "#FFE94A";++/** Black or white, whichever reads on the given hex fill. */+export function contrastText(hex: string): string {+ const m = /^#?([0-9a-fA-F]{6})$/.exec(hex.trim());+ if (!m) return "#111114";+ const n = parseInt(m[1], 16);+ const lum = 0.299 * ((n >> 16) & 255) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255);+ return lum > 150 ? "#111114" : "#FFFFFF";+}++/** The effective karaoke treatment for the spoken word: user overrides on the+ * subtitles block win over the caption style's defaults, and a custom color+ * picks its own contrast text for the box treatment. */+export function karaokeLook(+ style: CaptionStyle,+ subs?: { accentMode?: WordAccentMode; accentColor?: string }+): { mode: WordAccentMode; color: string; text: string } {+ const color = subs?.accentColor ?? style.accent ?? DEFAULT_ACCENT;+ return {+ mode: subs?.accentMode ?? style.accentMode ?? "underline",+ color,+ text: subs?.accentColor ? contrastText(color) : style.accentText ?? contrastText(color),+ };}export const CAPTION_STYLES: Record<CaptionStyleId, CaptionStyle> = {@@ -47,6 +81,7 @@ export const CAPTION_STYLES: Record<CaptionStyleId, CaptionStyle> = {color: "#FFFFFF",shadow: true,plate: true,+ accentMode: "box",},hook: {id: "hook",@@ -62,6 +97,7 @@ export const CAPTION_STYLES: Record<CaptionStyleId, CaptionStyle> = {plateColor: "#0A84FF",plateOpacity: 0.9,openerScale: 1.28,+ accentMode: "box",},punchy: {id: "punchy",@@ -75,6 +111,105 @@ export const CAPTION_STYLES: Record<CaptionStyleId, CaptionStyle> = {shadow: true,plate: false,openerScale: 1.34,+ accent: "#FFFFFF",+ },+ minimal: {+ id: "minimal",+ label: "Minimal",+ x: 0.5,+ y: 0.82,+ size: 36,+ font: "sf",+ weight: 400,+ color: "#FFFFFF",+ shadow: true,+ plate: false,+ },+ editorial: {+ id: "editorial",+ label: "Editorial",+ x: 0.5,+ y: 0.8,+ size: 42,+ font: "serif",+ weight: 700,+ color: "#FFFFFF",+ shadow: true,+ plate: false,+ },+ typewriter: {+ id: "typewriter",+ label: "Typewriter",+ x: 0.5,+ y: 0.8,+ size: 38,+ font: "mono",+ weight: 400,+ color: "#FFFFFF",+ shadow: false,+ plate: true,+ accentMode: "box",+ },+ block: {+ id: "block",+ label: "Block",+ x: 0.5,+ y: 0.8,+ size: 44,+ font: "sf",+ weight: 700,+ color: "#FFFFFF",+ shadow: false,+ plate: true,+ plateColor: "#111114",+ plateOpacity: 1,+ accentMode: "box",+ },+ highlight: {+ id: "highlight",+ label: "Highlighter",+ x: 0.5,+ y: 0.8,+ size: 42,+ font: "sf",+ weight: 700,+ color: "#111114",+ shadow: false,+ plate: true,+ plateColor: "#FFE94A",+ plateOpacity: 0.95,+ accent: "#FF375F",+ accentMode: "box",+ accentText: "#FFFFFF",+ },+ bubble: {+ id: "bubble",+ label: "Bubblegum",+ x: 0.5,+ y: 0.8,+ size: 42,+ font: "rounded",+ weight: 700,+ color: "#FFFFFF",+ shadow: false,+ plate: true,+ plateColor: "#FF375F",+ plateOpacity: 0.92,+ accentMode: "box",+ },+ neon: {+ id: "neon",+ label: "Neon",+ x: 0.5,+ y: 0.78,+ size: 46,+ font: "impact",+ weight: 700,+ color: "#30D158",+ shadow: true,+ plate: false,+ openerScale: 1.2,+ accent: "#FFFFFF",},};@@ -122,21 +257,54 @@ export function wrapCaptionForSize(text: string, size: number): string {return lines.join("\n");}+/**+ * Per-display-word timeline windows for a cue, partitioning [start, end] with+ * no gaps so the karaoke highlight never blinks off between words. Uses the+ * transcriber's word timings while they still match the text one-to-one;+ * otherwise (hand edits, social rewrites) splits proportionally by word length.+ */+export function cueWordWindows(cue: SubtitleCue): { start: number; end: number }[] {+ const words = cue.text.trim().split(/\s+/).filter(Boolean);+ const n = words.length;+ if (n === 0) return [];+ const starts: number[] = [];+ if (cue.words && cue.words.length === n) {+ for (let i = 0; i < n; i++) {+ const t = i === 0 ? cue.start : Math.min(Math.max(cue.words[i].t0, cue.start), cue.end);+ starts.push(i > 0 && t < starts[i - 1] ? starts[i - 1] : t);+ }+ } else {+ const weights = words.map((w) => w.length + 1);+ const total = weights.reduce((a, b) => a + b, 0);+ let acc = 0;+ for (const w of weights) {+ starts.push(cue.start + ((cue.end - cue.start) * acc) / total);+ acc += w;+ }+ }+ return starts.map((start, i) => ({ start, end: i === n - 1 ? cue.end : starts[i + 1] }));+}+/** A cue as a synthetic overlay, so captions ride the title pipeline. The style- * preset drives the look; the opening cue can render bigger for a punchy hook. */+ * preset drives the look; the opening cue can render bigger for a punchy hook;+ * a dragged caption position (frame fractions) overrides the preset's spot;+ * a word index marks that word for the karaoke accent. */export function cueOverlay(cue: SubtitleCue,style: CaptionStyle = CAPTION_STYLES.clean,- isOpener = false+ isOpener = false,+ pos?: { x?: number; y?: number; accentMode?: WordAccentMode; accentColor?: string },+ wordIndex?: number): TextOverlay {+ const kl = wordIndex !== undefined ? karaokeLook(style, pos) : null;const size = Math.round(style.size * (isOpener && style.openerScale ? style.openerScale : 1));return {id: `sub-${cue.id}`,text: wrapCaptionForSize(cue.text, size),start: cue.start,end: cue.end,- x: style.x,- y: style.y,+ x: pos?.x ?? style.x,+ y: pos?.y ?? style.y,size,font: style.font,weight: style.weight,@@ -145,6 +313,14 @@ export function cueOverlay(plate: style.plate,...(style.plateColor ? { plateColor: style.plateColor } : {}),...(style.plateOpacity !== undefined ? { plateOpacity: style.plateOpacity } : {}),+ ...(kl && wordIndex !== undefined+ ? {+ highlightWord: wordIndex,+ highlightColor: kl.color,+ highlightMode: kl.mode,+ highlightText: kl.text,+ }+ : {}),};}diff --git a/site/src/cut/lib/textRender.ts b/site/src/cut/lib/textRender.tsindex 180a7853..b0a3a8f8 100644--- a/site/src/cut/lib/textRender.ts+++ b/site/src/cut/lib/textRender.ts@@ -71,9 +71,49 @@ export async function renderOverlayPng(}ctx.fillStyle = overlay.color;+ // Karaoke: draw word by word so the spoken word gets the accent color and an+ // underline; the word index counts across all lines.+ let k = 0;lines.forEach((line, i) => {const y = cy - totalH / 2 + lineH * (i + 0.5);- ctx.fillText(line, cx, y);+ if (overlay.highlightWord === undefined) {+ ctx.fillText(line, cx, y);+ return;+ }+ const words = line.split(" ").filter(Boolean);+ const spaceW = ctx.measureText(" ").width;+ const widths = words.map((w) => ctx.measureText(w).width);+ const lineW = widths.reduce((a, b) => a + b, 0) + spaceW * (words.length - 1);+ let x = cx - lineW / 2;+ ctx.textAlign = "left";+ words.forEach((w, wi) => {+ const active = k === overlay.highlightWord;+ if (active && overlay.highlightMode === "box") {+ // Accent box behind the word, contrast text on top — drawn with the+ // shadow off so the box and its word stay crisp.+ const pad = 0.12 * fpx;+ const prevShadow = ctx.shadowColor;+ ctx.shadowColor = "transparent";+ ctx.fillStyle = overlay.highlightColor ?? "#FFE94A";+ ctx.beginPath();+ ctx.roundRect(x - pad, y - fpx * 0.5 - pad, widths[wi] + pad * 2, fpx + pad * 2, 0.18 * fpx);+ ctx.fill();+ ctx.fillStyle = overlay.highlightText ?? "#111114";+ ctx.fillText(w, x, y);+ ctx.shadowColor = prevShadow;+ } else if (active) {+ ctx.fillStyle = overlay.highlightColor ?? "#FFE94A";+ ctx.fillText(w, x, y);+ if (overlay.highlightMode !== "color")+ ctx.fillRect(x, y + fpx * 0.42, widths[wi], Math.max(2 * scale, fpx * 0.07));+ } else {+ ctx.fillStyle = overlay.color;+ ctx.fillText(w, x, y);+ }+ x += widths[wi] + spaceW;+ k++;+ });+ ctx.textAlign = "center";});return new Promise((resolve, reject) =>diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.tsnew file mode 100644index 00000000..f22c1f75--- /dev/null+++ b/site/src/cut/lib/tts.ts@@ -0,0 +1,319 @@+"use client";++import { importFileToProject } from "./media";+import type { MediaAsset } from "./types";++// Client side of AI voiceovers: Gemini speech generation on Donkey's hosted+// inference routes, with the user's Donkey sign-in and credits (same-origin on+// the cut hosts, like image/video generation). Each segment comes back as raw+// PCM; the browser lays the segments out at their timeline offsets, encodes+// one WAV, and saves it into the project through the local engine like any+// other media file.++export interface SpeechVoice {+ id: string;+ /** One-word character from the voice catalog ("Warm", "Upbeat"). */+ style: string;+}++export interface SpeechSegment {+ text: string;+ /** Timeline offset this line should land at, seconds. */+ at: number;+}++/** Gemini's prebuilt voices. The set is fixed by the model, so it ships+ * hardcoded — no listing round-trip. */+export const SPEECH_VOICES: SpeechVoice[] = [+ { id: "Zephyr", style: "Bright" },+ { id: "Puck", style: "Upbeat" },+ { id: "Charon", style: "Informative" },+ { id: "Kore", style: "Firm" },+ { id: "Fenrir", style: "Excitable" },+ { id: "Leda", style: "Youthful" },+ { id: "Orus", style: "Firm" },+ { id: "Aoede", style: "Breezy" },+ { id: "Callirrhoe", style: "Easy-going" },+ { id: "Autonoe", style: "Bright" },+ { id: "Enceladus", style: "Breathy" },+ { id: "Iapetus", style: "Clear" },+ { id: "Umbriel", style: "Easy-going" },+ { id: "Algieba", style: "Smooth" },+ { id: "Despina", style: "Smooth" },+ { id: "Erinome", style: "Clear" },+ { id: "Algenib", style: "Gravelly" },+ { id: "Rasalgethi", style: "Informative" },+ { id: "Laomedeia", style: "Upbeat" },+ { id: "Achernar", style: "Soft" },+ { id: "Alnilam", style: "Firm" },+ { id: "Schedar", style: "Even" },+ { id: "Gacrux", style: "Mature" },+ { id: "Pulcherrima", style: "Forward" },+ { id: "Achird", style: "Friendly" },+ { id: "Zubenelgenubi", style: "Casual" },+ { id: "Vindemiatrix", style: "Gentle" },+ { id: "Sadachbia", style: "Lively" },+ { id: "Sadaltager", style: "Knowledgeable" },+ { id: "Sulafat", style: "Warm" },+];++export const DEFAULT_VOICE = "Puck";++/** Resolve a requested voice against the catalog: an exact (or+ * case-insensitive) id match, else the default. Shared by the Audio panel and+ * the AI copilot so both land on the same voice. */+export function resolveVoice(wanted?: string): string {+ if (typeof wanted === "string" && wanted.trim()) {+ const exact = SPEECH_VOICES.find((v) => v.id === wanted.trim());+ if (exact) return exact.id;+ const ci = SPEECH_VOICES.find(+ (v) => v.id.toLowerCase() === wanted.trim().toLowerCase()+ );+ if (ci) return ci.id;+ }+ return DEFAULT_VOICE;+}++const CLIENT_ID = "donkey-cut";+const MAX_SEGMENTS = 200;+const MAX_SEGMENT_CHARS = 2000;+const MAX_TOTAL_CHARS = 20000;+/** Hosted synthesis calls in flight at once for multi-line readouts. */+const CONCURRENCY = 3;++interface PcmClip {+ samples: Int16Array;+ rate: number;+}++/** The account balance can't cover the generation — callers surface a link to+ * buy credits alongside the message. */+export class NoCreditsError extends Error {}++async function readError(res: Response, fallback: string): Promise<string> {+ if (res.status === 401) return "Sign in to Donkey to generate voiceovers.";+ const body = (await res.json().catch(() => null)) as {+ error?: unknown;+ message?: unknown;+ details?: { message?: unknown };+ } | null;+ const message = [body?.message, body?.error].find(+ (v): v is string => typeof v === "string" && v.length > 0+ );+ if (res.status === 402) return message ?? "Not enough Donkey credits — top up to continue.";+ // The provider's own error (`details.message`) names the actual rejection+ // ("input too long", a rate limit, …); the top-level message is generic.+ const detail = body?.details?.message;+ const full =+ message && typeof detail === "string" && detail && detail !== message+ ? `${message} (${detail})`+ : message;+ return full ?? fallback;+}++/** One hosted Gemini speech call: text in, decoded PCM out. A direction is a+ * natural-language delivery instruction ("Say warmly, like an old friend");+ * the model also honors inline tags like [whispers] in the text itself. */+async function synthesizeSegment(+ text: string,+ voice: string,+ direction?: string+): Promise<PcmClip> {+ const style = direction?.trim();+ const res = await fetch("/api/inference/assets", {+ method: "POST",+ headers: { "Content-Type": "application/json", "x-donkey-client-id": CLIENT_ID },+ body: JSON.stringify({+ kind: "speech",+ prompt: style ? `${style}: ${text}` : text,+ inputs: { voice },+ }),+ });+ if (!res.ok) {+ const message = await readError(res, "Voice generation failed.");+ throw res.status === 402 ? new NoCreditsError(message) : new Error(message);+ }+ const gen = (await res.json()) as {+ outputs?: { dataBase64?: string; contentType?: string }[];+ };+ const out = gen.outputs?.find((o) => o.dataBase64);+ if (!out?.dataBase64) throw new Error("The provider returned no audio.");++ const bin = atob(out.dataBase64);+ const bytes = new Uint8Array(new ArrayBuffer(bin.length));+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ const rate = Number(out.contentType?.match(/rate=(\d+)/)?.[1]) || 24000;+ // Gemini TTS returns raw little-endian 16-bit mono PCM.+ return { samples: new Int16Array(bytes.buffer, 0, bytes.byteLength >> 1), rate };+}++/** Nearest-neighbor resample, only for the off chance segments disagree. */+function resample(clip: PcmClip, rate: number): PcmClip {+ if (clip.rate === rate) return clip;+ const out = new Int16Array(Math.round((clip.samples.length * rate) / clip.rate));+ for (let i = 0; i < out.length; i++) {+ out[i] = clip.samples[Math.min(clip.samples.length - 1, Math.round((i * clip.rate) / rate))];+ }+ return { samples: out, rate };+}++/** Lay the clips out at their offsets (summing any overlap, clamped) and wrap+ * the result in a WAV container. */+function assembleWav(clips: PcmClip[], offsets: number[]): Blob {+ const rate = clips[0].rate;+ const aligned = clips.map((c) => resample(c, rate));+ const starts = offsets.map((o) => Math.round(o * rate));+ const total = Math.max(...aligned.map((c, i) => starts[i] + c.samples.length));++ const mix = new Int32Array(total);+ aligned.forEach((c, i) => {+ const from = starts[i];+ for (let j = 0; j < c.samples.length; j++) mix[from + j] += c.samples[j];+ });++ const data = new Int16Array(total);+ for (let i = 0; i < total; i++) {+ data[i] = Math.max(-32768, Math.min(32767, mix[i]));+ }++ const header = new DataView(new ArrayBuffer(44));+ const write = (at: number, s: string) => {+ for (let i = 0; i < s.length; i++) header.setUint8(at + i, s.charCodeAt(i));+ };+ write(0, "RIFF");+ header.setUint32(4, 36 + data.byteLength, true);+ write(8, "WAVE");+ write(12, "fmt ");+ header.setUint32(16, 16, true);+ header.setUint16(20, 1, true); // PCM+ header.setUint16(22, 1, true); // mono+ header.setUint32(24, rate, true);+ header.setUint32(28, rate * 2, true);+ header.setUint16(32, 2, true);+ header.setUint16(34, 16, true);+ write(36, "data");+ header.setUint32(40, data.byteLength, true);+ return new Blob([header.buffer, data.buffer], { type: "audio/wav" });+}++/**+ * Synthesize segments into one WAV in the project's media folder. The file's+ * t=0 is the earliest segment, and `offset` is that earliest timeline time —+ * drop one audio clip at `offset` and every line lands on its cue.+ */+export interface SpeechLayout {+ /** The input segment's text, so callers can match a line back to its cue. */+ text: string;+ /** Timeline second this line's audio starts at. */+ at: number;+ /** How long the generated audio for this line runs, seconds. */+ duration: number;+}++export async function synthesizeSpeech(+ projectId: string,+ segments: SpeechSegment[],+ opts: { voice: string; direction?: string; name?: string }+): Promise<{ asset: MediaAsset; offset: number; layout: SpeechLayout[] }> {+ const lines = segments+ .map((s) => ({ text: s.text.trim(), at: Math.max(0, s.at) }))+ .filter((s) => s.text);+ if (lines.length === 0) throw new Error("Nothing to say.");+ if (lines.length > MAX_SEGMENTS) throw new Error(`At most ${MAX_SEGMENTS} lines at once.`);+ if (lines.some((s) => s.text.length > MAX_SEGMENT_CHARS)) {+ throw new Error(`Each line must stay under ${MAX_SEGMENT_CHARS} characters.`);+ }+ if (lines.reduce((n, s) => n + s.text.length, 0) > MAX_TOTAL_CHARS) {+ throw new Error(`The script must stay under ${MAX_TOTAL_CHARS} characters.`);+ }++ const offset = Math.min(...lines.map((s) => s.at));+ const voice = resolveVoice(opts.voice);++ // A small pool: readouts can be dozens of lines, one hosted call each.+ const clips: PcmClip[] = new Array(lines.length);+ let next = 0;+ const worker = async () => {+ while (next < lines.length) {+ const i = next++;+ try {+ try {+ clips[i] = await synthesizeSegment(lines[i].text, voice, opts.direction);+ } catch (e) {+ // An empty balance repeats forever — resending only burns the queue.+ if (e instanceof NoCreditsError) throw e;+ // The TTS backend rejects the odd call spuriously; one resend of just+ // this line usually lands and saves the rest of the batch.+ clips[i] = await synthesizeSegment(lines[i].text, voice, opts.direction);+ }+ } catch (e) {+ // Name the line that failed so a one-bad-cue batch is actionable.+ if (lines.length > 1 && e instanceof Error && !(e instanceof NoCreditsError)) {+ const snippet = lines[i].text.length > 40 ? `${lines[i].text.slice(0, 40)}…` : lines[i].text;+ throw new Error(`Line ${i + 1} ("${snippet}"): ${e.message}`);+ }+ throw e;+ }+ }+ };+ await Promise.all(+ Array.from({ length: Math.min(CONCURRENCY, lines.length) }, worker)+ );++ // Each line lands at its cue offset — unless the previous line's speech runs+ // past it. The generated pace differs from the original recording, so such+ // overlaps are common; mixed as-is they'd play two voice lines at once. The+ // pushed-back starts are reported in `layout` so callers re-time their cues.+ const placed: number[] = [];+ let cursor = 0;+ lines.forEach((l, i) => {+ const at = Math.max(l.at - offset, cursor);+ placed.push(at);+ cursor = at + clips[i].samples.length / clips[i].rate;+ });++ const wav = assembleWav(clips, placed);+ const name = opts.name?.trim() || "AI voice";+ const file = new File([wav], `${slug(name)}.wav`, { type: "audio/wav" });+ const asset = await importFileToProject(projectId, file);+ if (!asset) throw new Error("Could not save the voiceover into the project.");+ asset.name = name;+ asset.origin = "voiceover";+ // Report where each line's audio actually lands and how long it runs, so a+ // subtitles readout can re-time its cues to the generated voice (whose pace+ // differs from the original recording).+ const layout: SpeechLayout[] = lines.map((l, i) => ({+ text: l.text,+ at: offset + placed[i],+ duration: clips[i].samples.length / clips[i].rate,+ }));+ return { asset, offset, layout };+}++/** A short spoken sample for the voice picker. Each voice is synthesized once+ * per session and cached as a blob URL. */+const samples = new Map<string, string>();+// Kept punchy but deliberately free of the "Hey!"-style lead that makes the TTS+// model intermittently return an empty clip (it stops before speaking). Change+// with care and re-check reliability across voices.+const SAMPLE_TEXT = "This is how I sound. Let's make something worth remembering.";++export async function speechSampleUrl(voice: string): Promise<string> {+ const id = resolveVoice(voice);+ const cached = samples.get(id);+ if (cached) return cached;+ const clip = await synthesizeSegment(SAMPLE_TEXT, id);+ const url = URL.createObjectURL(assembleWav([clip], [0]));+ samples.set(id, url);+ return url;+}++function slug(name: string) {+ return (+ name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 40) || "ai-voice"+ );+}diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 1acfd2d4..49399272 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -24,6 +24,8 @@ export interface StoredAsset {duration: number; // secondswidth?: number;height?: number;+ /** Set on assets Cut generated itself (AI voiceovers); absent on imports. */+ origin?: "voiceover";}/** Runtime asset: stored fields plus derived/browser-only data. */@@ -96,6 +98,8 @@ export interface VideoClip {in: number; // trim-in inside the source, secondsout: number; // trim-out inside the source, secondsmuted: boolean;+ /** Gain on the clip's own audio, 0..1.5; absent = 1 (unchanged). */+ volume?: number;/** How the clip meets its region: letterboxed ("fit", default) or scaled to* cover it ("fill", cropping the overflow). */fit?: "fit" | "fill";@@ -210,6 +214,10 @@ export interface AudioClip {* a sped-up video clip, so it stays the same length and in sync with the* (now muted) picture. The timeline footprint is (out-in)/speed. */speed?: number;+ /** Voiceover ducking: while this clip is audible, every other sound (clip+ * audio and other soundtrack clips) drops to this gain, 0..1. Absent = no+ * ducking. Ducking clips never duck each other. */+ duck?: number;}/**@@ -249,6 +257,7 @@ export interface TemplateAudio {fadeIn?: number;fadeOut?: number;speed?: number;+ duck?: number;}export interface LibraryTemplate {id: string;@@ -302,8 +311,19 @@ export interface TextOverlay {/** Which title track (row) this sits on, 0-based. Tracks are kept* contiguous: empty ones collapse and dragging past the last adds one. */lane?: number;+ /** Karaoke burn-in: index of the display word (whitespace-split across all+ * lines) drawn per the accent treatment — recolored, underlined, or on an+ * accent box with a contrast text color. */+ highlightWord?: number;+ highlightColor?: string;+ highlightMode?: WordAccentMode;+ highlightText?: string;}+/** How the spoken word lights up in karaoke mode: accent color only, accent+ * color plus underline, or an accent box behind the word. */+export type WordAccentMode = "color" | "underline" | "box";+/** One subtitle caption, timed against the timeline (not the source files). */export interface SubtitleCue {id: string;@@ -316,6 +336,19 @@ export interface SubtitleCue {words?: { t0: number; t1: number; w: string }[];}+/** Caption look preset ids; the presets themselves live in lib/subtitles.ts. */+export type CaptionStyleId =+ | "clean"+ | "hook"+ | "punchy"+ | "minimal"+ | "editorial"+ | "typewriter"+ | "block"+ | "highlight"+ | "bubble"+ | "neon";+export interface SubtitlesBlock {cues: SubtitleCue[];/** Render captions on the preview and burn them into exports. */@@ -325,7 +358,17 @@ export interface SubtitlesBlock {locale?: string;generatedAt?: number;/** Caption look preset; absent = the plain "clean" subtitle style. */- style?: "clean" | "hook" | "punchy";+ style?: CaptionStyleId;+ /** Caption anchor as frame fractions, applied to every cue. Absent = the+ * style preset's spot (low center). Dragging the caption in the preview sets it. */+ x?: number;+ y?: number;+ /** Karaoke mode: each word lights up as it is spoken, in the preview and+ * the export burn-in. */+ wordHighlight?: boolean;+ /** Word treatment overrides; absent = the caption style's defaults. */+ accentMode?: WordAccentMode;+ accentColor?: string;}export const emptySubtitles = (): SubtitlesBlock => ({diff --git a/site/src/cut/lib/uiState.ts b/site/src/cut/lib/uiState.tsindex ebe2b6fe..622f1786 100644--- a/site/src/cut/lib/uiState.ts+++ b/site/src/cut/lib/uiState.ts@@ -1,9 +1,14 @@"use client";+import { useCallback, useState } from "react";+/*** Per-project view state (zoom level, timeline panel height) — how this* browser looks at a project, not part of the cut. Stored in IndexedDB* keyed by project id; project.json only carries real content.+ *+ * Cross-project view prefs (active side-panel tab, segment choices) live in+ * localStorage via useLocalPref below.*/export interface ProjectUiState {pxPerSec?: number;@@ -63,3 +68,39 @@ export function saveUiState(projectId: string, patch: ProjectUiState) {if (timer) clearTimeout(timer);timer = setTimeout(() => void flush(), 300);}++/**+ * useState that survives reloads via localStorage. `accept` guards against+ * stale stored values (a tab or folder that no longer exists falls back to+ * the default). Reads synchronously on mount, so use it only in components+ * that mount client-side (everything inside the editor does).+ */+export function useLocalPref<T>(+ key: string,+ fallback: T,+ accept: (v: unknown) => boolean+): [T, (v: T) => void] {+ const [value, setValue] = useState<T>(() => {+ if (typeof window === "undefined") return fallback;+ try {+ const raw = localStorage.getItem(key);+ if (raw === null) return fallback;+ const parsed = JSON.parse(raw) as unknown;+ return accept(parsed) ? (parsed as T) : fallback;+ } catch {+ return fallback;+ }+ });+ const set = useCallback(+ (v: T) => {+ setValue(v);+ try {+ localStorage.setItem(key, JSON.stringify(v));+ } catch {+ // Private-mode quota — the choice just won't stick across reloads.+ }+ },+ [key]+ );+ return [value, set];+}diff --git a/site/src/cut/lib/visualFrames.ts b/site/src/cut/lib/visualFrames.tsnew file mode 100644index 00000000..1d5c06ca--- /dev/null+++ b/site/src/cut/lib/visualFrames.ts@@ -0,0 +1,104 @@+"use client";++import type { ClipSpan } from "./types";++// Sample the cut's picture for the visual-subtitles pipeline: a handful of+// small jpeg frames spread along the base track, each stamped with its+// timeline time. Captured in the browser from the same media elements the+// preview uses, so nothing re-renders server-side.++export interface CapturedFrame {+ at: number;+ /** data:image/jpeg;base64,… */+ image: string;+}++const FRAME_W = 480;+const JPEG_Q = 0.72;+const MIN_FRAMES = 4;+const MAX_FRAMES = 20;+/** Aim for one frame every ~2.5s of timeline. */+const SECONDS_PER_FRAME = 2.5;++function loadVideo(url: string): Promise<HTMLVideoElement> {+ return new Promise((resolve, reject) => {+ const v = document.createElement("video");+ v.preload = "metadata";+ v.muted = true;+ // Media may come from the engine on another origin; anonymous CORS keeps+ // the canvas grab from tainting.+ v.crossOrigin = "anonymous";+ v.src = url;+ v.onloadedmetadata = () => resolve(v);+ v.onerror = () => reject(new Error("Could not read a video file for frame capture."));+ });+}++function seekTo(v: HTMLVideoElement, t: number): Promise<void> {+ return new Promise((resolve) => {+ const done = () => {+ v.removeEventListener("seeked", done);+ clearTimeout(timer);+ resolve();+ };+ const timer = setTimeout(done, 2000);+ v.addEventListener("seeked", done);+ v.currentTime = t;+ });+}++/** Capture timeline frames from the base track's visible clips. */+export async function captureTimelineFrames(spans: ClipSpan[]): Promise<CapturedFrame[]> {+ const visible = spans.filter((sp) => !sp.clip.hidden);+ if (visible.length === 0) return [];+ const total = Math.max(...visible.map((sp) => sp.start + sp.len));+ const count = Math.min(+ MAX_FRAMES,+ Math.max(MIN_FRAMES, Math.round(total / SECONDS_PER_FRAME))+ );++ const canvas = document.createElement("canvas");+ const ctx = canvas.getContext("2d");+ if (!ctx) return [];+ ctx.imageSmoothingQuality = "high";++ // One shared element per source file; spans of the same asset reuse it.+ const videos = new Map<string, HTMLVideoElement>();+ const frames: CapturedFrame[] = [];+ try {+ for (let i = 0; i < count; i++) {+ const at = ((i + 0.5) * total) / count;+ const span = visible.find((sp) => at >= sp.start && at < sp.start + sp.len);+ if (!span) continue;+ let v = videos.get(span.asset.id);+ if (!v) {+ try {+ v = await loadVideo(span.asset.url);+ } catch {+ continue; // one unreadable source shouldn't sink the whole capture+ }+ videos.set(span.asset.id, v);+ }+ const speed = span.clip.speed && span.clip.speed > 0 ? span.clip.speed : 1;+ const srcTime = span.clip.in + (at - span.start) * speed;+ await seekTo(v, Math.max(0, Math.min(srcTime, Math.max(0, v.duration - 0.05))));+ if (v.readyState < 2 || !v.videoWidth) continue;+ const w = Math.min(FRAME_W, v.videoWidth);+ const h = Math.round((w / v.videoWidth) * v.videoHeight);+ canvas.width = w;+ canvas.height = h;+ ctx.drawImage(v, 0, 0, w, h);+ try {+ frames.push({ at, image: canvas.toDataURL("image/jpeg", JPEG_Q) });+ } catch {+ // A tainted canvas (unexpected CORS setup) — skip the frame.+ }+ }+ } finally {+ for (const v of videos.values()) {+ v.removeAttribute("src");+ v.load();+ }+ }+ return frames;+}diff --git a/site/src/cut/lib/voiceover.ts b/site/src/cut/lib/voiceover.tsnew file mode 100644index 00000000..42279f5b--- /dev/null+++ b/site/src/cut/lib/voiceover.ts@@ -0,0 +1,48 @@+import { enrichAsset } from "@/cut/lib/media";+import { useEditor } from "@/cut/lib/store";+import { synthesizeSpeech } from "@/cut/lib/tts";++/** Default duck: everything else drops to 40% while a voiceover speaks. */+export const DUCK_DEFAULT = 0.4;++/**+ * Voice the subtitle cues (all of them, or just `opts.cueIds`) and drop the+ * result on the soundtrack at the first cue. The spoken pace differs from the+ * original recording, so the read cues are re-timed to the generated audio —+ * keeping the word highlighter in step. Shared by the panel button and the AI+ * assistant's read_subtitles_aloud tool. Throws with a user-facing message on+ * failure.+ */+export async function generateSubtitlesReadout(+ voice: string,+ opts?: { cueIds?: string[]; direction?: string; duck?: number }+) {+ const s = useEditor.getState();+ const projectId = s.projectId;+ if (!projectId) throw new Error("Open a project first.");+ const wanted = opts?.cueIds && new Set(opts.cueIds);+ const cues = s.subtitles.cues.filter((c) => c.text.trim() && (!wanted || wanted.has(c.id)));+ if (cues.length === 0) throw new Error("No subtitles to read.");++ const { asset, offset, layout } = await synthesizeSpeech(+ projectId,+ cues.map((c) => ({ text: c.text, at: c.start })),+ { voice, direction: opts?.direction, name: "Subtitles readout" }+ );+ const duck = opts?.duck ?? DUCK_DEFAULT;+ const cur = useEditor.getState();+ cur.addAsset(asset);+ cur.addAudioFromAsset(asset.id, offset, { duck: duck < 1 ? duck : undefined });+ if (layout.length === cues.length) {+ cur.retimeCues(+ layout.map((seg, i) => ({+ id: cues[i].id,+ start: seg.at,+ // Stop at the next line's start so re-timed captions never overlap.+ end: Math.min(seg.at + seg.duration, layout[i + 1]?.at ?? Infinity),+ }))+ );+ }+ void enrichAsset(asset);+ return { asset, start: offset, lines: cues.length, duck: duck < 1 ? duck : null };+}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 2e6ebc4b..c84b703a 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -137,7 +137,7 @@ export const AI_TOOLS: AiToolDef[] = [{name: "update_audio",description:- "Update a soundtrack clip: volume (0..1.5), fadeIn/fadeOut seconds, start position, or in/out trim.",+ "Update a soundtrack clip: volume (0..1.5), fadeIn/fadeOut seconds, start position, in/out trim, or duck. `duck` is voiceover ducking — while this clip plays, ALL other audio (video-clip sound and other music) drops to that gain (0..1); pass 1 to clear ducking. Use it to make a voiceover sit over quieter music.",inputSchema: obj({id: str("Soundtrack clip id"),volume: num("0..1.5"),@@ -146,6 +146,7 @@ export const AI_TOOLS: AiToolDef[] = [start: num("Timeline start s"),in: num("Source in s"),out: num("Source out s"),+ duck: num("Duck other audio to this gain while this clip plays, 0..1 (1 clears ducking)"),}, ["id"]),},{@@ -169,6 +170,28 @@ export const AI_TOOLS: AiToolDef[] = [index: num("Insert position on the video track (default 0 = first)"),}),},+ {+ name: "generate_image",+ description:+ "Generate an AI image from a text prompt (Donkey's hosted image model) and add it to the project as a still clip, composed for the project's aspect. Use for B-roll, cover frames, or backgrounds the user doesn't have footage for. Returns when the image has landed. By default it also drops the still onto the timeline; pass add_to_timeline:false to only put it in Media. Needs the user signed in to Donkey (spends their credits).",+ inputSchema: obj({+ prompt: str("What to depict — be specific about subject, style, and lighting"),+ add_to_timeline: bool("Insert the still on the video track (default true)"),+ index: num("Insert position on the video track (default: end; 0 = first/cover)"),+ }, ["prompt"]),+ },+ {+ name: "generate_video",+ description:+ "Generate an AI video clip from a text prompt (Donkey's hosted Veo model), framed for the project's aspect. Use for B-roll or shots the user doesn't have footage for. This renders remotely and takes a minute or two, so the tool RETURNS IMMEDIATELY — the clip appears in Media (and on the timeline by default) when it finishes; watch the Video panel. Tell the user it's rendering. Pass add_to_timeline:false to only put it in Media. Needs the user signed in to Donkey (spends their credits).",+ inputSchema: obj({+ prompt: str("The shot to generate — describe motion, subject, and mood"),+ tier: { type: "string", enum: ["fast", "high"], description: "fast = quicker/cheaper (default), high = best quality" },+ duration_seconds: num("Clip length 4–8 seconds (default 8)"),+ add_to_timeline: bool("Insert the clip on the video track (default true)"),+ index: num("Insert position on the video track (default: end)"),+ }, ["prompt"]),+ },{name: "subtitles_generate",description:@@ -181,6 +204,40 @@ export const AI_TOOLS: AiToolDef[] = ["Transcribe (if needed) then rewrite the captions into punchy social-video captions — short lines that fit inside the video frame (they may wrap onto two lines but never overflow), a few emoji, a curiosity-hook opener. style: clean | hook | punchy (default hook). Cue timings are preserved.",inputSchema: obj({ style: str("Caption style: clean, hook, or punchy") }),},+ {+ name: "subtitles_from_visuals",+ description:+ "Caption a cut that has NO usable speech by watching sampled frames and writing timed narration captions (uses the user's Claude login to look at the frames). Use this instead of subtitles_generate when the video is silent b-roll, music-only, or otherwise has nothing to transcribe. Runs in the background; returns when finished.",+ inputSchema: obj({ locale: str("BCP-47 locale like en-US (default en-US)") }),+ },+ {+ name: "list_voices",+ description:+ "List the AI voices available for voiceover (Gemini's prebuilt set; each has a one-word character like Warm, Upbeat, Gravelly). Call this when the user asks for a specific kind of voice so you can pass the right voice id to voiceover_generate or read_subtitles_aloud.",+ inputSchema: obj({}),+ },+ {+ name: "voiceover_generate",+ description:+ "Generate a spoken AI voiceover from a script (Donkey's hosted speech model) and drop it on the soundtrack at the playhead (or `start`). Use for 'add a voiceover', 'narrate this', 'read this script aloud'. Pick a `voice` id from list_voices, or omit for a good default. `direction` steers delivery in natural language; the script itself may carry inline tags like [whispers] or [excited]. `duck` lowers all other audio to that gain while the voice plays (0..1; ~0.3–0.5 is typical, 1 = don't duck). Needs the user signed in to Donkey (spends their credits).",+ inputSchema: obj({+ script: str("What the voice should say"),+ voice: str("Voice id from list_voices (optional; a sensible default is chosen)"),+ direction: str("Delivery instruction, e.g. 'Say warmly, like an old friend' (optional)"),+ duck: num("Lower other audio to this gain while the voice plays, 0..1 (default 0.4; 1 = no ducking)"),+ start: num("Timeline start in seconds (default: the playhead)"),+ }, ["script"]),+ },+ {+ name: "read_subtitles_aloud",+ description:+ "Speak the existing subtitle cues as an AI voiceover (Donkey's hosted speech model) — each line placed at its own cue time — and add it to the soundtrack. Turns captions into narration. Requires subtitles to exist first (generate them if needed). `duck` lowers other audio under the voice (0..1). Needs the user signed in to Donkey (spends their credits).",+ inputSchema: obj({+ voice: str("Voice id from list_voices (optional)"),+ direction: str("Delivery instruction, e.g. 'Narrate briskly, documentary style' (optional)"),+ duck: num("Lower other audio to this gain while the voice plays, 0..1 (default 0.4)"),+ }),+ },{name: "subtitles_set_view",description: "Toggle subtitles on the video (preview + export burn-in) and/or the timeline cue track.",@@ -294,7 +351,7 @@ export const AI_TOOLS: AiToolDef[] = [export const AI_SKILLS: Record<string, string> = {"editor-overview": `# Cut editor overviewCut is a local, project-based short-video editor. Each project has an output aspect — 9:16 vertical (1080×1920, TikTok/Reels/Shorts) or 16:9 widescreen (1920×1080, YouTube) — switchable from the pill in the top bar; the current one is in editor_state project.aspect. Layout:-- Left icon rail tabs: Media (project files + Exports list), Library (shared reusable assets), Record (camera/mic), Text (title presets), Subtitles (transcript editor), Publish (caption/tags/sound metadata).+- Left icon rail tabs: Media (project files + Exports list), Library (shared reusable assets), Video (generate AI video), Image (generate AI images), Audio (AI voiceover + audio files), Text (title presets), Subtitles (transcript editor), Publish (caption/tags/sound metadata). Camera/mic recording lives in the top bar next to the aspect picker; recordings land in Media.- Center: the video preview canvas (composited at the project's frame size) with draggable text overlays and subtitle captions.- Right: the Inspector — its content follows the selection (video clip, soundtrack clip, or title).- Bottom: the timeline (resizable by dragging its top border). Tracks top-to-bottom: video (magnetic, clips snap end-to-end), soundtrack (free-positioned green clips), titles (purple bars), subtitles (amber cue bars, when enabled).@@ -334,12 +391,23 @@ Inspector shows these when a title is selected. The color row has fixed swatchesGood TikTok titles: short punchy lines, high contrast (white/yellow + shadow or plate), size 72–110, keep inside the middle 80% of the frame (x 0.1..0.9, y 0.1..0.9), avoid the caption band (y≈0.8) when subtitles are on.Titles burn into the export exactly as previewed.`,- "audio-and-subtitles": `# Audio & subtitles+ "audio-and-subtitles": `# Audio, voiceover & subtitlesSoundtrack clips: volume 0..1.5, fadeIn/fadeOut seconds (max half the clip), start = timeline position, in/out = trim inside the source. Fades render with ffmpeg afade on export.-Subtitles: subtitles_generate transcribes the current cut fully on-device (Apple speech, macOS 26). Cues are caption-sized (≈38 chars). If no speech exists, no cues are created and nothing renders on the video — never add captions to a speechless video. captions_generate goes further: it rewrites those cues into punchy social captions (emoji, curiosity-hook opener) in a chosen style (clean/hook/punchy), keeping timings — use it when the ask is social/TikTok captions rather than a plain transcript.-Editing: update_cue (text or retime), delete_cue. In the panel, Return splits a caption at the cursor onto real word timings; hand-edited text drops its word timings.+Ducking: a soundtrack clip's \`duck\` (0..1, via update_audio) lowers ALL other audio — video-clip sound and other music — to that gain while the clip plays; 1 clears it. Voiceovers set this so narration sits over quieter music. It applies in both the preview and the export.+Voiceover (Donkey's hosted speech model — signed in, spends credits, like image/video generation):+- voiceover_generate(script, voice?, direction?, duck?, start?): synthesizes the script and drops it on the soundtrack at the playhead (or start). Defaults to a 0.4 duck so it sits over other audio. Voices are Gemini's prebuilt set — list_voices returns them (id + one-word character like Warm, Upbeat, Gravelly); omit voice for a good default. \`direction\` steers delivery in natural language ("Say warmly, like an old friend"); the script itself can carry inline tags like [whispers], [excited], [laughs].+- read_subtitles_aloud(voice?, direction?, duck?): speaks the existing subtitle cues, each line at its own cue time — captions become narration. Needs cues first.+Subtitles: subtitles_generate transcribes the cut's audio on-device (Apple speech, macOS 26); cues are caption-sized (≈38 chars). subtitles_from_visuals is the fallback for a cut with NO speech — it watches sampled frames (via the user's Claude login) and writes timed narration captions of what's on screen. So: speech present → subtitles_generate; silent/music-only footage the user wants captioned → subtitles_from_visuals. Never fabricate a spoken transcript.+captions_generate rewrites existing cues into punchy social captions (emoji, curiosity-hook opener) in a style (clean/hook/punchy), keeping timings — use it when the ask is social/TikTok captions rather than a plain transcript.+Editing: update_cue (text or retime), delete_cue, merge_cue. In the panel, Return splits a caption at the cursor onto real word timings; hand-edited text drops its word timings.subtitles_set_view: showOnVideo (preview + export burn-in), showOnTimeline (amber cue track).-Caption style is fixed: bold white SF, translucent plate, bottom-center (y≈0.8).`,+Caption look: the Subtitles panel offers 10 visual presets (clean, hook, punchy, minimal, editorial, typewriter, block, highlight, bubble, neon), a per-word karaoke highlight with accent overrides, and the caption block drags to a new spot in the preview. No tool sets the look — direct the user to the panel. captions_generate's clean/hook/punchy choice shapes the caption text it writes; the visual preset is separate.`,++ "ai-generation": `# AI image & video generation+Cut can generate media the user doesn't have footage for, through Donkey's hosted models (generation — images, video, voiceovers — is the signed-in, credit-spending feature; everything else is local and free). Both land the result in the project's Media and, by default, drop it on the timeline.+- generate_image(prompt, add_to_timeline?, index?): a hosted image model renders the prompt; the image is baked into an 8s still clip framed for the project aspect. Great for a cover/hook frame (index 0), a background, or a b-roll still. Slower footage the user lacks → generate it rather than asking them to find it.+- generate_video(prompt, tier?, duration_seconds?, add_to_timeline?, index?): a hosted Veo model renders a short clip (4–8s) with audio, framed for the project aspect. tier "fast" (default) is quicker/cheaper, "high" is best quality. This takes a minute or two, so the tool returns right away and the clip appears in Media (and on the timeline by default) when it finishes — tell the user it's rendering. Don't call it again for the same shot while one is in flight.+Both compose for editor_state project.aspect, so set the aspect first if the user wants a different frame. If either fails with a sign-in or credits message, relay that plainly — generation needs the user signed in to Donkey with credits; it is not a local fallback. Write vivid, specific prompts (subject, style, lighting, motion); the user's request is usually shorthand, so flesh it out.`,"publish-and-export": `# Publish & exportPublish tab fields (set_publish): caption (TikTok limit 4,000 chars INCLUDING tags/emoji; hook in the first line), tags (3–5 focused tags recommended; stored space-separated, rendered as #tags), soundTitle (TikTok lets you rename the sound once after posting), handle (shown as @handle in platform previews).@@ -358,7 +426,9 @@ Rules:- All edits are undoable (unlimited undo), so prefer doing over asking. Only ask when the request is genuinely ambiguous.- Times are seconds. The frame is the project's aspect: 1080×1920 (9:16) or 1920×1080 (16:9) — see project.aspect in editor_state.- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.-- Never add subtitles to a video without speech; never invent transcript content.+- Don't transcribe a video with no speech. If the user wants captions on silent footage, use subtitles_from_visuals (it narrates what's on screen). Never invent a spoken transcript.+- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.+- generate_image / generate_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in). Default to adding the result to the timeline; write a rich, specific prompt from their shorthand. generate_video takes a minute or two.- capture_frame shows you the actual rendered frame when visual judgment matters.`;}diff --git a/site/src/cut/server/ai/visualSubtitles.ts b/site/src/cut/server/ai/visualSubtitles.tsnew file mode 100644index 00000000..3374a520--- /dev/null+++ b/site/src/cut/server/ai/visualSubtitles.ts@@ -0,0 +1,150 @@+import os from "node:os";+import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";++// Write subtitle cues for a cut with no usable audio: the client samples frames+// along the timeline, and the user's own Claude login (like the rest of Cut's+// AI) watches them and writes timed narration captions.++/** One sampled frame: its timeline time and a data-URL jpeg/png. */+export interface VisualFrame {+ at: number;+ image: string;+}++export interface VisualCue {+ start: number;+ end: number;+ text: string;+}++const MODEL = "claude-haiku-4-5-20251001";+const MAX_FRAMES = 24;++type ImageBlock = {+ type: "image";+ source: { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/webp"; data: string };+};++function imageBlock(dataUrl: string): ImageBlock | null {+ const m = /^data:(image\/(?:jpeg|png|webp));base64,([A-Za-z0-9+/=]+)$/.exec(dataUrl);+ if (!m) return null;+ return {+ type: "image",+ source: { type: "base64", media_type: m[1] as ImageBlock["source"]["media_type"], data: m[2] },+ };+}++export async function writeVisualCues(+ frames: VisualFrame[],+ duration: number,+ locale?: string+): Promise<VisualCue[]> {+ const usable = frames+ .slice(0, MAX_FRAMES)+ .map((f) => ({ at: Math.max(0, f.at), block: imageBlock(f.image) }))+ .filter((f): f is { at: number; block: ImageBlock } => f.block !== null);+ if (usable.length === 0) throw new Error("No frames to caption.");++ const prompt = `You caption silent short-form videos (TikTok / Reels / Shorts). Below are frames sampled from a ${duration.toFixed(1)}-second video, each labeled with its timeline time. Watch what happens across them and write narration captions that tell that story.++Rules:+- Return ONLY a JSON array: [{"start": seconds, "end": seconds, "text": "caption"}]. No commentary, no code fence.+- Chronological, non-overlapping cues covering the video from 0 to ${duration.toFixed(1)}s.+- Each cue runs 1.5–4 seconds; each text is 2–8 punchy words.+- Narrate what is on screen — actions, changes, the point — not camera trivia.+- Make the first cue a scroll-stopping hook.+- Write in the language of locale "${locale ?? "en-US"}".`;++ const content: ({ type: "text"; text: string } | ImageBlock)[] = [{ type: "text", text: prompt }];+ for (const f of usable) {+ content.push({ type: "text", text: `Frame at ${f.at.toFixed(1)}s:` });+ content.push(f.block);+ }++ async function* messages(): AsyncIterable<SDKUserMessage> {+ yield {+ type: "user",+ message: { role: "user", content },+ parent_tool_use_id: null,+ };+ }++ const text = await runOnce(messages(), 120_000);+ const cues = parseCues(text, duration);+ if (cues.length === 0) throw new Error("The model wrote no captions — try again.");+ return cues;+}++async function runOnce(prompt: AsyncIterable<SDKUserMessage>, timeoutMs: number): Promise<string> {+ const q = query({+ prompt,+ options: {+ model: MODEL,+ ...(process.env.DONKEY_CUT_CLAUDE+ ? { pathToClaudeCodeExecutable: process.env.DONKEY_CUT_CLAUDE }+ : {}),+ tools: [],+ permissionMode: "dontAsk",+ settingSources: [],+ maxTurns: 1,+ cwd: os.tmpdir(),+ },+ });+ const collect = async () => {+ let out = "";+ for await (const msg of q) {+ const m = msg as unknown as { type: string; subtype?: string; result?: unknown };+ if (m.type === "result" && m.subtype === "success" && typeof m.result === "string") {+ out = m.result;+ }+ }+ return out;+ };+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<never>((_resolve, reject) => {+ timer = setTimeout(() => reject(new Error("Captioning timed out.")), timeoutMs);+ timer.unref();+ });+ try {+ return await Promise.race([collect(), timeout]);+ } catch (err) {+ // Losing the race only abandons the promise — stop the underlying Claude+ // subprocess too, or every timeout strands one burning CPU and quota.+ void q.interrupt().catch(() => {});+ throw err;+ } finally {+ clearTimeout(timer);+ }+}++/** Pull the JSON cue array out of the reply and normalize it: clamp to the+ * cut, keep chronological order, and nudge overlaps apart. */+function parseCues(text: string, duration: number): VisualCue[] {+ const start = text.indexOf("[");+ const end = text.lastIndexOf("]");+ if (start === -1 || end <= start) return [];+ let parsed: unknown;+ try {+ parsed = JSON.parse(text.slice(start, end + 1));+ } catch {+ return [];+ }+ if (!Array.isArray(parsed)) return [];+ const cues = parsed+ .map((c) => {+ const v = c as { start?: unknown; end?: unknown; text?: unknown };+ if (typeof v.start !== "number" || typeof v.end !== "number" || typeof v.text !== "string")+ return null;+ const s = Math.max(0, Math.min(v.start, duration));+ const e = Math.max(s + 0.3, Math.min(v.end, duration + 0.5));+ const t = v.text.replace(/\s+/g, " ").trim();+ return t ? { start: s, end: e, text: t } : null;+ })+ .filter((c): c is VisualCue => c !== null)+ .sort((a, b) => a.start - b.start);+ for (let i = 1; i < cues.length; i++) {+ if (cues[i].start < cues[i - 1].end) cues[i].start = cues[i - 1].end;+ if (cues[i].end < cues[i].start + 0.3) cues[i].end = cues[i].start + 0.3;+ }+ return cues;+}diff --git a/site/src/cut/server/frames.ts b/site/src/cut/server/frames.tsindex f2a38a76..ece0c234 100644--- a/site/src/cut/server/frames.ts+++ b/site/src/cut/server/frames.ts@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";import os from "node:os";import path from "node:path";import { mediaPath } from "./projects";+import { uniqueName } from "./util";function run(cmd: string, args: string[]): Promise<void> {return new Promise((resolve, reject) => {@@ -57,6 +58,35 @@ function probeDims(file: string): Promise<{ width: number; height: number }> {});}+/**+ * Bake a still image into an H.264 clip in the project's media folder, so it+ * rides the timeline, preview, and export like any other footage.+ */+export async function makeStillClip(+ projectId: string,+ imagePath: string,+ seconds: number,+ fileBase: string+): Promise<{ fileName: string; duration: number; width: number; height: number }> {+ const fileName = await uniqueName(`${fileBase}.mp4`, (n) => mediaPath(projectId, n));+ const out = mediaPath(projectId, fileName);+ await run("ffmpeg", [+ "-y",+ "-loop", "1",+ "-i", imagePath,+ "-t", seconds.toFixed(3),+ "-r", "30",+ // yuv420p needs even dimensions, whatever size the image came in at.+ "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",+ "-c:v", "libx264",+ "-preset", "veryfast",+ "-pix_fmt", "yuv420p",+ out,+ ]);+ const dims = await probeDims(out);+ return { fileName, duration: seconds, width: dims.width, height: dims.height };+}+export interface FreezeFraming {fit: "fit" | "fill";panX: number;diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.tsindex b756b65e..34012a63 100644--- a/site/src/cut/server/http/ai.ts+++ b/site/src/cut/server/http/ai.ts@@ -12,6 +12,7 @@ import {type UIChunkWriter,} from "../ai/bridge";import { rewriteCaptions } from "../ai/captions";+import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, systemPrompt } from "../ai/catalog";import { AI_MODELS } from "../ai/models";@@ -305,6 +306,28 @@ export const aiApi = {}},+ /** Write subtitle cues from sampled frames — for cuts with no usable audio.+ * Runs through the user's own Claude login, like the captions rewrite. */+ async visualSubtitles(req: Request) {+ try {+ const { frames, duration, locale } = (await req.json()) as {+ frames?: VisualFrame[];+ duration?: number;+ locale?: string;+ };+ if (!Array.isArray(frames) || frames.length === 0 || typeof duration !== "number") {+ return Response.json({ error: "frames and duration are required." }, { status: 400 });+ }+ const cues = await writeVisualCues(frames, duration, typeof locale === "string" ? locale : undefined);+ return Response.json({ cues });+ } catch (e) {+ return Response.json(+ { error: e instanceof Error ? e.message : "Could not caption the visuals." },+ { status: 500 }+ );+ }+ },+async chat(req: Request) {const body = (await req.json()) as ChatBody;const base = new URL(req.url).origin;diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex ff49af18..744b5575 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -1,6 +1,9 @@import { execFile } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";import type { ProjectDoc } from "@/cut/lib/types";-import { makeFreezeFrame } from "../frames";+import { makeFreezeFrame, makeStillClip } from "../frames";import {createProject,createProjectFolder,@@ -78,8 +81,11 @@ export const projectsApi = {async create(req: Request) {try {- const { name } = (await req.json()) as { name?: string };- return Response.json(await createProject(name ?? "Untitled"));+ const { name, folderId } = (await req.json()) as {+ name?: string;+ folderId?: string | null;+ };+ return Response.json(await createProject(name ?? "Untitled", folderId ?? null));} catch (e) {return caught(e, "Could not create project.");}@@ -104,6 +110,9 @@ export const projectsApi = {audioClips: Array.isArray(body.audioClips) ? body.audioClips : existing.audioClips,overlayClips: Array.isArray(body.overlayClips) ? body.overlayClips : existing.overlayClips,overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,+ aspect: body.aspect === "9:16" || body.aspect === "16:9" ? body.aspect : existing.aspect,+ fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,+ fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,subtitles:body.subtitles && typeof body.subtitles === "object"? body.subtitles@@ -256,6 +265,37 @@ export const projectsApi = {});},+ /** Bake an uploaded still image into a video clip in the project's media+ * folder (AI-generated images arrive here after hosted generation). */+ async importStill(req: Request, { id }: { id: string }) {+ try {+ if (!(await readProject(id))) return err("Project not found.", 404);+ const form = await req.formData();+ const file = form.get("file");+ if (!(file instanceof File)) return err("No image in upload.", 400);+ const nameField = form.get("name");+ const name = typeof nameField === "string" && nameField.trim() ? nameField.trim() : file.name;+ const slug =+ name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 40) || "still";+ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-still-"));+ try {+ const src = path.join(tmp, path.basename(file.name).replace(/[^\w.-]+/g, "_") || "image.png");+ await writeFile(src, Buffer.from(await file.arrayBuffer()));+ // 8s of still footage — room to trim like any other clip.+ const made = await makeStillClip(id, src, 8, `ai-${slug}`);+ return Response.json({ id: crypto.randomUUID().slice(0, 8), type: "video", name, ...made });+ } finally {+ void rm(tmp, { recursive: true, force: true });+ }+ } catch (e) {+ return caught(e, "Could not import the image.");+ }+ },+/** Render a freeze-frame still clip from a media file's frame. */async freeze(req: Request, { id }: { id: string }) {try {diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 201dec8f..dc5aa4da 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -38,6 +38,7 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "POST", path: "/api/cut/projects/:id/exports/:file/reveal", handler: (req, p) => projectsApi.revealExport(req, { id: p.id, file: p.file }) },{ method: "POST", path: "/api/cut/projects/:id/transcribe", handler: (req, p) => projectsApi.transcribeStart(req, { id: p.id }) },{ method: "GET", path: "/api/cut/projects/:id/transcribe", handler: (req, p) => projectsApi.transcribePoll(req, { id: p.id }) },+ { method: "POST", path: "/api/cut/projects/:id/still", handler: (req, p) => projectsApi.importStill(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/freeze", handler: (req, p) => projectsApi.freeze(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/duplicate", handler: (req, p) => projectsApi.duplicate(req, { id: p.id }) },{ method: "GET", path: "/api/cut/projects/:id/preview", handler: (req, p) => projectsApi.servePreview(req, { id: p.id }) },@@ -65,6 +66,7 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "POST", path: "/api/cut/ai/chat", handler: (req) => aiApi.chat(req) },{ method: "POST", path: "/api/cut/ai/captions", handler: (req) => aiApi.captions(req) },+ { method: "POST", path: "/api/cut/ai/visual-subtitles", handler: (req) => aiApi.visualSubtitles(req) },{ method: "GET", path: "/api/cut/ai/models", handler: () => aiApi.models() },{ method: "GET", path: "/api/cut/ai/proxy", handler: (req) => aiApi.proxyCatalog(req) },{ method: "POST", path: "/api/cut/ai/proxy", handler: (req) => aiApi.proxyCall(req) },diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex d678fe4b..a5945ba3 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -1,5 +1,5 @@import { spawn, type ChildProcess } from "node:child_process";-import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import { assertLocalRuntime } from "./local-only";@@ -28,6 +28,8 @@ export interface ExportSpec {in: number;out: number;muted: boolean;+ /** Gain on the clip's own audio, 0..1.5; absent = 1 (unchanged). */+ volume?: number;/** "fit" letterboxes (default); "fill" covers the region and crops. */fit?: "fit" | "fill";panX?: number; // crop-window pan -1..1 (fill mode, full frame)@@ -70,8 +72,15 @@ export interface ExportSpec {fadeOut?: number;/** Playback rate (detached-audio clips inherit their video clip's speed). */speed?: number;+ /** Voiceover ducking: while this clip plays, every other sound drops to+ * this gain (0..1). Ducking clips never duck each other. */+ duck?: number;}[];overlays: { file: string; start: number; end: number }[];+ /** Burned-in subtitle stills, non-overlapping and chronological. Kept apart+ * from `overlays` (titles may overlap each other): these render as one+ * concat-demuxer slideshow, so karaoke word windows don't multiply inputs. */+ captions?: { file: string; start: number; end: number }[];}export interface Job {@@ -122,10 +131,33 @@ export function cancelJob(id: string) {}}-function stamp() {- const d = new Date();- const p = (n: number) => String(n).padStart(2, "0");- return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;+/** Export file named after the project, with a " 2", " 3"… suffix when the+ * name is already taken by a file on disk or an export still in flight. */+async function exportName(projectId: string, projectName: string) {+ const base =+ projectName.replace(/[/\\:*?"<>|]/g, "").trim().slice(0, 60) || "export";+ const taken = new Set(+ await readdir(exportsDir(projectId)).catch(() => [] as string[])+ );+ for (const j of jobs.values()) {+ if (j.projectId === projectId && j.outName) taken.add(j.outName);+ }+ for (let n = 1; ; n++) {+ const candidate = n === 1 ? `${base}.mp4` : `${base} ${n}.mp4`;+ if (!taken.has(candidate)) return candidate;+ }+}++// Names resolve one job at a time: exportName only sees a competing job once+// its outName is assigned, so two jobs racing through their first awaits could+// otherwise both claim "<Project>.mp4" and overwrite each other's render.+let namingQueue: Promise<unknown> = Promise.resolve();+function claimExportName(job: Job, projectName: string): Promise<void> {+ const claim = namingQueue.then(async () => {+ job.outName = await exportName(job.projectId, projectName);+ });+ namingQueue = claim.catch(() => {});+ return claim;}export async function createJob(form: FormData): Promise<Job> {@@ -150,13 +182,6 @@ export async function createJob(form: FormData): Promise<Job> {retire(job);return job;}- // Include the unique job id so two exports in the same second can't collide- // on the same output path (which would clobber the first render).- const outName = preview ? "preview.mp4" : `export-${stamp()}-${id}.mp4`;- const outPath = path.join(- preview ? projectDir(spec.projectId) : exportsDir(spec.projectId),- outName- );const job: Job = {id,projectId: spec.projectId,@@ -164,16 +189,23 @@ export async function createJob(form: FormData): Promise<Job> {status: "running",progress: 0,tmpDir: "",- outPath,- outName,+ outPath: "",+ outName: "",log: [],};jobs.set(id, job); // reserve the concurrency slot before the first awaittry {- await mkdir(path.dirname(outPath), { recursive: true });+ const doc = await readProject(spec.projectId);+ if (!doc) throw new Error("Project not found.");+ if (preview) job.outName = "preview.mp4";+ else await claimExportName(job, doc.name);+ job.outPath = path.join(+ preview ? projectDir(spec.projectId) : exportsDir(spec.projectId),+ job.outName+ );+ await mkdir(path.dirname(job.outPath), { recursive: true });job.tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-"));- if (!(await readProject(spec.projectId))) throw new Error("Project not found.");// Overlay PNGs are rendered in the browser and uploaded with the spec.for (const [key, value] of form.entries()) {if (value instanceof File && key !== "spec") {@@ -331,11 +363,14 @@ async function runExport(job: Job, spec: ExportSpec) {const videoPresence = new Map<string, boolean>();const inputs: string[] = [];const inputIndex = new Map<string, number>();+ // Counted explicitly: the concat input below carries extra flags, so the+ // args array is not a clean ["-i", path] pair per input.+ let nInputs = 0;// Resolve paths in order first so ffmpeg input indices stay deterministic,// then probe every file's streams concurrently.const paths = await Promise.all(mediaFiles.map((f) => resolveMedia(spec, f)));mediaFiles.forEach((f, i) => {- inputIndex.set(f, inputs.length / 2);+ inputIndex.set(f, nInputs++);inputs.push("-i", paths[i]);});await Promise.all(@@ -353,10 +388,40 @@ async function runExport(job: Job, spec: ExportSpec) {}));for (const o of spec.overlays) {- inputIndex.set(o.file, inputs.length / 2);+ inputIndex.set(o.file, nInputs++);inputs.push("-i", path.join(job.tmpDir, path.basename(o.file)));}+ // One concat-demuxer input for all subtitle stills: cues never overlap, so+ // they play as a slideshow with transparent filler ("sub_blank.png", uploaded+ // with the stills) covering the gaps.+ let captionsIdx: number | null = null;+ const captions = (spec.captions ?? [])+ .filter((c) => c.end > c.start)+ .sort((a, b) => a.start - b.start);+ if (captions.length > 0) {+ const blank = path.join(job.tmpDir, "sub_blank.png");+ const lines = ["ffconcat version 1.0"];+ let cursor = 0;+ for (const c of captions) {+ const from = Math.max(c.start, cursor);+ if (c.end - from < 1e-3) continue;+ if (from - cursor > 1e-3) lines.push(`file '${blank}'`, `duration ${num(from - cursor)}`);+ lines.push(+ `file '${path.join(job.tmpDir, path.basename(c.file))}'`,+ `duration ${num(c.end - from)}`+ );+ cursor = c.end;+ }+ if (spec.duration - cursor > 1e-3) {+ lines.push(`file '${blank}'`, `duration ${num(spec.duration - cursor)}`);+ }+ const list = path.join(job.tmpDir, "captions.ffconcat");+ await writeFile(list, lines.join("\n") + "\n");+ captionsIdx = nInputs++;+ inputs.push("-f", "concat", "-safe", "0", "-i", list);+ }+const filters: string[] = [];// Per-clip timeline length (source span compressed/expanded by speed).@@ -457,13 +522,14 @@ async function runExport(job: Job, spec: ExportSpec) {}if (!c.muted && !c.hidden && audioPresence.get(c.file)) {const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";+ const vol = (c.volume ?? 1) !== 1 ? `volume=${num(c.volume ?? 1)},` : "";// The picture's fade edges carry the sound with them; zoom edges don't.const afades =(hf > 0.01 ? `,afade=t=in:st=0:d=${num(hf)}` : "") +(tf > 0.01 ? `,afade=t=out:st=${num(Math.max(0, dur - tf))}:d=${num(tf)}` : "");filters.push(`[${idx}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,${tempo}` +- `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,` ++ `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,${vol}` +`apad=whole_dur=${num(dur)},atrim=0:${num(dur)}${afades}[a${j}]`);} else {@@ -569,16 +635,67 @@ async function runExport(job: Job, spec: ExportSpec) {}for (const oc of aboveVideos) vLabel = addOverlay(oc, vLabel);- // Burn in text overlays, each windowed to its timeline range.+ // Burn in text overlays, each windowed to its timeline range. Half-open so+ // back-to-back overlays sharing a boundary never composite on the same frame.spec.overlays.forEach((o, k) => {const idx = inputIndex.get(o.file)!;const next = `vov${k}`;filters.push(- `[${vLabel}][${idx}:v]overlay=0:0:enable='between(t,${num(o.start)},${num(o.end)})'[${next}]`+ `[${vLabel}][${idx}:v]overlay=0:0:enable='gte(t,${num(o.start)})*lt(t,${num(o.end)})'[${next}]`);vLabel = next;});+ // Subtitle stills ride one concat-demuxer slideshow (transparent filler in+ // the gaps), so a karaoke cut with hundreds of word windows still costs a+ // single ffmpeg input instead of one per still.+ if (captionsIdx !== null) {+ filters.push(`[${captionsIdx}:v]fps=${fps},format=yuva420p,setsar=1[caps]`);+ filters.push(`[${vLabel}][caps]overlay=0:0:eof_action=pass[vcaps]`);+ vLabel = "vcaps";+ }++ // Voiceover ducking: while a ducking clip plays, every other sound drops to+ // its gain. The windows are timeline seconds, so the volume automation must+ // run on timeline-aligned streams — the joined clip audio, and each other+ // sound *after* its adelay.+ const duckWindows = spec.audio+ .filter((a) => a.duck !== undefined && a.duck < 1)+ .map((a) => {+ const speed = a.speed && a.speed > 0 ? a.speed : 1;+ const len = Math.max(0.1, (a.out - a.in) / speed);+ return { from: a.start, to: a.start + len, gain: Math.max(0, a.duck!) };+ });+ // Flatten to non-overlapping segments at the lowest covering gain: chained+ // volume filters multiply, so overlapping voiceovers would otherwise duck+ // deeper than the preview (which takes the minimum).+ const duckSegments = (() => {+ const cuts = [...new Set(duckWindows.flatMap((w) => [w.from, w.to]))].sort((a, b) => a - b);+ const segs: { from: number; to: number; gain: number }[] = [];+ for (let i = 0; i + 1 < cuts.length; i++) {+ const [from, to] = [cuts[i], cuts[i + 1]];+ const covering = duckWindows.filter((w) => w.from < to && w.to > from);+ if (covering.length === 0) continue;+ const gain = Math.min(...covering.map((w) => w.gain));+ const prev = segs[segs.length - 1];+ if (prev && prev.to === from && prev.gain === gain) prev.to = to;+ else segs.push({ from, to, gain });+ }+ return segs;+ })();+ let duckSeq = 0;+ const duckOthers = (label: string): string => {+ if (duckSegments.length === 0) return label;+ // Half-open windows: between() includes both ends, so adjacent segments+ // would both fire (and multiply) on the exact boundary frame.+ const chain = duckSegments+ .map((w) => `volume=enable='gte(t,${num(w.from)})*lt(t,${num(w.to)})':volume=${num(w.gain)}`)+ .join(",");+ const out = `dk${duckSeq++}`;+ filters.push(`[${label}]${chain}[${out}]`);+ return out;+ };+// Soundtrack clips: trim, gain, shift into place, mix with clip audio.const soundLabels: string[] = [];spec.audio.forEach((a, k) => {@@ -601,13 +718,15 @@ async function runExport(job: Job, spec: ExportSpec) {(fades.length ? fades.join(",") + "," : "") +`adelay=${delayMs}:all=1[snd${k}]`);- soundLabels.push(`snd${k}`);+ // Music and other non-voiceover sound ducks under the voiceovers.+ soundLabels.push(a.duck !== undefined && a.duck < 1 ? `snd${k}` : duckOthers(`snd${k}`));});- let aLabel = aAcc;- const extraSound = [...soundLabels, ...overlaySoundLabels];+ // The joined clip audio and overlay-video audio duck too.+ let aLabel = duckOthers(aAcc);+ const extraSound = [...soundLabels, ...overlaySoundLabels.map(duckOthers)];if (extraSound.length > 0) {- const mixIn = [aAcc, ...extraSound].map((l) => `[${l}]`).join("");+ const mixIn = [aLabel, ...extraSound].map((l) => `[${l}]`).join("");filters.push(`${mixIn}amix=inputs=${extraSound.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`);diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsindex 524a8f62..28cfde51 100644--- a/site/src/cut/server/projects.ts+++ b/site/src/cut/server/projects.ts@@ -91,11 +91,17 @@ export async function writeProject(id: string, doc: ProjectDoc) {await writeJsonAtomic(docPath(id), doc);}-export async function createProject(name: string): Promise<ProjectSummary> {+export async function createProject(+ name: string,+ folderId: string | null = null+): Promise<ProjectSummary> {const id = crypto.randomUUID().slice(0, 10);await mkdir(mediaDir(id), { recursive: true });await mkdir(exportsDir(id), { recursive: true });const now = Date.now();+ // A folder that no longer exists just falls back to the root.+ const folder =+ folderId && (await readFolders()).some((f) => f.id === folderId) ? folderId : null;const doc: ProjectDoc = {version: 1,name: name.trim() || "Untitled",@@ -105,6 +111,7 @@ export async function createProject(name: string): Promise<ProjectSummary> {clips: [],audioClips: [],overlays: [],+ ...(folder ? { folderId: folder } : {}),};await writeJsonAtomic(docPath(id), doc);return summarize(id, doc);