Open source CapCut alternative.
TypeScript
feat(site): make images first-class media in Cut
David Lea226fa5bcb4c
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex a0152282..d76741de 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -449,14 +449,6 @@ function ChatSession({{...targetProps}className="relative flex min-h-0 flex-1 flex-col">- {dropActive && (- <div className="pointer-events-none absolute inset-1.5 z-10 grid place-items-center rounded-xl border-2 border-dashed border-[#0a84ff] bg-[#0a84ff]/8">- <span className="rounded-full bg-card px-3 py-1 text-[11.5px] font-medium text-[#0a84ff] shadow-sm">- Drop to attach- </span>- </div>- )}-<div ref={scrollRef} className="ai-messages min-h-0 flex-1 overflow-y-auto px-3.5 py-3">{messages.length === 0 && (<div className="flex flex-col gap-3 pt-6">@@ -495,7 +487,19 @@ function ChatSession({</div><div className="shrink-0 border-t border-border p-2.5">- <div className="rounded-xl border border-input bg-background focus-within:border-ring">+ <div+ className={cn(+ "rounded-xl border bg-background transition-colors",+ dropActive+ ? "border-[#0a84ff] ring-2 ring-[#0a84ff]/30"+ : "border-input focus-within:border-ring"+ )}+ >+ {dropActive && (+ <div className="px-3 pt-2 text-[11.5px] font-medium text-[#0a84ff]">+ Drop to attach+ </div>+ )}<RefChipsrefs={attachments}onRemove={(ref) => setAttachments((p) => p.filter((x) => !sameRef(x, ref)))}diff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsxindex 369bdfc0..108168ae 100644--- a/site/src/cut/components/AssetRefs.tsx+++ b/site/src/cut/components/AssetRefs.tsx@@ -1,8 +1,9 @@"use client";import { useMemo, useRef, useState } from "react";-import { AtSign, Check, Copy, Music, X } from "lucide-react";+import { Check, Copy, Music, X } from "lucide-react";import {+ highlightMentions,mentionToken,refToken,type AssetRef,@@ -52,7 +53,7 @@ export function RefThumb({ item, className }: { item: AssetRef; className?: stri);}-/** The `v2` badge shown on chips, cards, and the mention menu. */+/** The `v2` badge shown on chips, cards, and the mention menu (on light UI). */export function RefHandleBadge({ handle, className }: { handle: string; className?: string }) {return (<span@@ -66,23 +67,32 @@ export function RefHandleBadge({ handle, className }: { handle: string; classNam);}+/** A legible reference-token pill for image tiles: dark so it reads over any+ * image, showing the mention to type (`@i2`, `@nature-dunes`). Caller controls+ * visibility (shown on hover). */+export function RefHandlePill({ token, className }: { token: string; className?: string }) {+ return (+ <span+ className={cn(+ "pointer-events-none max-w-[calc(100%-0.5rem)] truncate rounded-[5px] bg-black/65 px-1.5 py-0.5 font-mono text-[10px] font-medium text-white",+ className+ )}+ >+ {token}+ </span>+ );+}+/** Hover peek: a larger look at the ref, floated above the anchor. */function RefPeek({ item, side = "top" }: { item: AssetRef; side?: "top" | "bottom" }) {return (<divclassName={cn(- "ref-peek pointer-events-none absolute left-0 z-50 w-44 rounded-xl border border-border bg-popover p-1.5 shadow-xl",+ "ref-peek pointer-events-none absolute left-0 z-50 w-44 overflow-hidden rounded-xl shadow-xl",side === "top" ? "bottom-full mb-1.5" : "top-full mt-1.5")}><RefThumb item={item} className="aspect-square w-full" />- <div className="mt-1 flex items-center gap-1 px-0.5">- {item.handle && <RefHandleBadge handle={item.handle} />}- <span className="min-w-0 truncate text-[10.5px] text-foreground">{item.name}</span>- </div>- <div className="px-0.5 text-[9.5px] tracking-wide text-muted-foreground uppercase">- {item.scope} · click to show- </div></div>);}@@ -134,12 +144,15 @@ export function RefChips({onRemove,className,peekSide = "top",+ thumbClassName = "size-14",}: {refs: AssetRef[];onRemove: (ref: AssetRef) => void;className?: string;/** Open peeks downward when the chips sit near the top of their panel. */peekSide?: "top" | "bottom";+ /** Thumbnail size, e.g. "size-12" for a compact in-input composer. */+ thumbClassName?: string;}) {const candidates = useRefCandidates();if (refs.length === 0) return null;@@ -155,6 +168,7 @@ export function RefChips({item={{ ...r, handle }}onRemove={onRemove}peekSide={peekSide}+ thumbClassName={thumbClassName}/>);})}@@ -166,10 +180,12 @@ function RefChip({item,onRemove,peekSide,+ thumbClassName,}: {item: AssetRef;onRemove: (ref: AssetRef) => void;peekSide: "top" | "bottom";+ thumbClassName: string;}) {const [peek, setPeek] = useState(false);return (@@ -184,7 +200,7 @@ function RefChip({className="block text-left"onClick={() => revealRef(item)}>- <RefThumb item={item} className="size-14" />+ <RefThumb item={item} className={thumbClassName} /></button>{item.handle && <RefHandleBadge handle={item.handle} className="absolute bottom-1 left-1" />}{peek && <RefPeek item={item} side={peekSide} />}@@ -305,6 +321,7 @@ export function MentionTextarea({rows?: number;}) {const taRef = useRef<HTMLTextAreaElement>(null);+ const backdropRef = useRef<HTMLDivElement>(null);const [caret, setCaret] = useState(0);const [dismissed, setDismissed] = useState<number | null>(null);const [sel, setSel] = useState(0);@@ -368,19 +385,38 @@ export function MentionTextarea({<RefThumb item={c} className="size-8" />{c.handle && <RefHandleBadge handle={c.handle} className="shrink-0" />}<span className="min-w-0 flex-1 truncate text-[11.5px]">{c.name}</span>- <span className="shrink-0 text-[9.5px] tracking-wide text-muted-foreground uppercase">- {c.scope}- </span></button>))}- <div className="flex items-center gap-1 px-1.5 pt-1 pb-0.5 text-[10px] text-muted-foreground">- <AtSign className="size-2.5" /> Reference by handle (@v2) or name- </div></div>)}+ {/* Highlight overlay: a mirror of the text sitting behind the textarea+ that draws a pill behind every resolved @mention. It shares the+ textarea's typography and padding so the pills line up exactly, and+ scrolls in lockstep. */}+ <div+ ref={backdropRef}+ aria-hidden+ className={cn(+ className,+ "pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words text-transparent"+ )}+ >+ {highlightMentions(value, candidates).map((seg, i) =>+ seg.ref ? (+ <span+ key={i}+ className="rounded-[4px] bg-[#0a84ff]/12 shadow-[0_0_0_2px_rgba(10,132,255,0.12)]"+ >+ {seg.text}+ </span>+ ) : (+ <span key={i}>{seg.text}</span>+ )+ )}+ </div><textarearef={taRef}- className={className}+ className={cn(className, "relative bg-transparent")}rows={rows}placeholder={placeholder}value={value}@@ -389,6 +425,13 @@ export function MentionTextarea({onChange(e.target.value);setCaret(e.target.selectionStart ?? 0);}}+ onScroll={(e) => {+ const bd = backdropRef.current;+ if (bd) {+ bd.scrollTop = e.currentTarget.scrollTop;+ bd.scrollLeft = e.currentTarget.scrollLeft;+ }+ }}onSelect={syncCaret}onKeyDown={(e) => {e.stopPropagation();diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex fbbdbc79..614c9369 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -7,14 +7,16 @@ import { Button } from "@/components/ui/button";import { apiFetch } from "@/cut/lib/api";import { renderPreviewProxy } from "@/cut/lib/exportClient";import { useExport } from "@/cut/lib/exportStore";+import { hasRefDrag } from "@/cut/lib/assetRef";import { enrichAsset, importFileToProject } from "@/cut/lib/media";import { backTarget, useCutBase } from "@/cut/lib/nav";import { getClipSpans, projectDuration, serializeDoc, useEditor } from "@/cut/lib/store";+import type { MediaAsset } from "@/cut/lib/types";import { AiPanel } from "./AiPanel";import { ExportDialog } from "./ExportDialog";import { ExportStatus } from "./ExportStatus";import { Inspector } from "./Inspector";-import { ImageGenFlyover } from "./ImageGenFlyover";+import { Lightbox } from "./Lightbox";import { Preview } from "./Preview";import { SidePanel } from "./SidePanel";import { Timeline, videoInsertIndex } from "./Timeline";@@ -190,18 +192,21 @@ export function Editor({}, [projectId]);const importFiles = useCallback(- async (files: FileList | File[], at?: number | null) => {+ async (files: FileList | File[], at?: number | null, origin?: MediaAsset["origin"]) => {const list = Array.from(files);setImporting((n) => n + list.length);for (const file of list) {try {const asset = await importFileToProject(projectId, file);if (!asset) continue;+ // Recordings are created media: tag them so they land on the timeline+ // but never in the Media panel (reserved for user imports).+ if (origin) asset.origin = origin;const s = useEditor.getState();s.addAsset(asset);- if (asset.type === "video") {+ if (asset.type === "video" || asset.type === "image") {// A drop on the timeline inserts at the pointer's slot; anywhere- // else appends at the end.+ // else appends at the end. A still rides the base track like footage.if (at == null) {s.addClipFromAsset(asset.id);} else {@@ -214,7 +219,9 @@ export function Editor({s.addClipFromAsset(asset.id, clipsIndex);}} else {- s.addAudioFromAsset(asset.id, at ?? 0);+ // A timeline drop lands at the pointer; anywhere else drops at the+ // playhead (the store slides it right only if that spot is taken).+ s.addAudioFromAsset(asset.id, at ?? undefined);}void enrichAsset(asset);} catch (err) {@@ -227,19 +234,23 @@ export function Editor({[projectId]);- // Whole-window drag & drop.+ // Whole-window drag & drop for OS files. Chrome tags native <img> drags+ // with `Files` too, so internal drags — which always carry the ref MIME —+ // are filtered out; dragging a stock tile never raises the import veil.useEffect(() => {+ const isFileDrag = (e: DragEvent) =>+ !!e.dataTransfer?.types.includes("Files") && !hasRefDrag(e);const enter = (e: DragEvent) => {- if (!e.dataTransfer?.types.includes("Files")) return;+ if (!isFileDrag(e)) return;e.preventDefault();dragDepth.current++;useEditor.getState().setDropActive(true);};const over = (e: DragEvent) => {- if (e.dataTransfer?.types.includes("Files")) e.preventDefault();+ if (isFileDrag(e)) e.preventDefault();};const leave = (e: DragEvent) => {- if (!e.dataTransfer?.types.includes("Files")) return;+ if (!isFileDrag(e)) return;dragDepth.current = Math.max(0, dragDepth.current - 1);if (dragDepth.current === 0) useEditor.getState().setDropActive(false);};@@ -257,7 +268,7 @@ export function Editor({return Math.max(0, t);};const drop = (e: DragEvent) => {- if (!e.dataTransfer?.files.length) return;+ if (hasRefDrag(e) || !e.dataTransfer?.files.length) return;e.preventDefault();dragDepth.current = 0;useEditor.getState().setDropActive(false);@@ -365,10 +376,8 @@ export function Editor({}`}><SidePanel projectId={projectId} onImport={importFiles} importing={importing > 0} />- {/* relative: anchors the generate-image flyover over the canvas column */}- <div className="relative grid min-h-0 min-w-0">+ <div className="grid min-h-0 min-w-0"><Preview />- <ImageGenFlyover projectId={projectId} /></div>{hasInspector && <Inspector />}</div>@@ -377,6 +386,7 @@ export function Editor({{aiOpen && <AiPanel onClose={() => useEditor.getState().setAiOpen(false)} />}{exportOpen && <ExportDialog />}<ExportStatus />+ <Lightbox />{dropActive && (<div className="fixed inset-0 z-60 grid place-items-center bg-background/70 backdrop-blur-md"><div className="pointer-events-none flex flex-col items-center gap-2 rounded-2xl border-2 border-dashed border-[#0a84ff] bg-[#0a84ff]/10 px-12 py-9 text-[#0a84ff]">diff --git a/site/src/cut/components/ImageGenFlyover.tsx b/site/src/cut/components/ImageGenFlyover.tsxdeleted file mode 100644index 210f306f..00000000--- a/site/src/cut/components/ImageGenFlyover.tsx+++ /dev/null@@ -1,152 +0,0 @@-"use client";--import { Loader2, Plus, Sparkles, X } from "lucide-react";-import { Button } from "@/components/ui/button";-import { collectRefs, useRefCandidates, useAssetDrop } from "@/cut/lib/assetRef";-import { signInUrl, useGenerate, useSignedIn } from "@/cut/lib/generate";-import { useImageGen } from "@/cut/lib/imageGen";-import { useEditor } from "@/cut/lib/store";-import { cn } from "@/lib/utils";-import { MentionTextarea, RefChips } from "./AssetRefs";--// The generate-image flyover: slides over the right edge of the preview canvas-// (covering it is fine — the render is the thing being looked at). Opens from-// the stock browser with a stock image's saved prompt, or blank; the user edits-// the prompt, generates on their Donkey account, and the result shows here-// while also landing in Media and the browser's Generated category.-//-// References ride along as input images: drag any image or video in (stock-// tile, media card, library clip, timeline clip) or mention it by @name.--export function ImageGenFlyover({ projectId }: { projectId: string }) {- const { open, prompt, refs } = useImageGen();- const signedIn = useSignedIn();- const candidates = useRefCandidates();- const job = useGenerate((s) =>- s.jobs.find((j) => j.kind === "image" && j.projectId === projectId)- );- const asset = useEditor((s) =>- job?.assetId ? s.assets.find((a) => a.id === job.assetId) : undefined- );- const { active: dropActive, attachTarget, targetProps } = useAssetDrop((ref) => {- if (ref.kind !== "audio") useImageGen.getState().addRef(ref);- });-- if (!open) return null;-- const go = () => {- const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates, { dropAudio: true });- if (!text) return;- void useGenerate.getState().generateImage(projectId, text, { refs: all });- };-- return (- <aside- ref={attachTarget}- {...targetProps}- className="absolute inset-y-0 right-0 z-40 flex w-[320px] flex-col border-l border-border bg-card shadow-[-12px_0_32px_rgba(0,0,0,0.12)]"- >- {dropActive && (- <div className="pointer-events-none absolute inset-1.5 z-10 grid place-items-center rounded-xl border-2 border-dashed border-[#0a84ff] bg-[#0a84ff]/8">- <span className="rounded-full bg-card px-3 py-1 text-[11.5px] font-medium text-[#0a84ff] shadow-sm">- Drop to use as reference- </span>- </div>- )}- <div className="flex h-12 shrink-0 items-center justify-between border-b border-border pr-2.5 pl-4">- <span className="text-sm font-semibold tracking-tight">Generate image</span>- <button- title="Close"- className="grid size-7 place-items-center rounded-md text-muted-foreground hover:text-foreground"- onClick={() => useImageGen.getState().close()}- >- <X className="size-4" />- </button>- </div>-- <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-3.5">- <RefChips- refs={refs}- onRemove={(r) => useImageGen.getState().removeRef(r)}- className="shrink-0"- peekSide="bottom"- />- <MentionTextarea- className="min-h-[110px] 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="A neon-lit street market at night, cinematic… Drop an image in or type @ to reference one."- value={prompt}- onChange={(v) => useImageGen.getState().setPrompt(v)}- candidates={candidates}- submitKey="mod-enter"- menuSide="bottom"- onSubmit={go}- />-- <Button- className="w-full shrink-0"- disabled={!prompt.trim() || signedIn === false || job?.status === "running"}- onClick={go}- >- {job?.status === "running" ? (- <Loader2 data-icon="inline-start" className="animate-spin" />- ) : (- <Sparkles data-icon="inline-start" />- )}- Generate image- </Button>-- {signedIn === false ? (- <p className="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">- Lands in Media and under Generated in the stock browser.- </p>- )}-- {job && (- <div className="flex shrink-0 flex-col gap-2">- {job.status === "done" && asset && (- <video- muted- playsInline- preload="metadata"- src={`${asset.url}#t=0.1`}- className="w-full rounded-lg bg-black"- />- )}- <div className="flex items-start gap-2">- <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" && "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 hover:brightness-110"- onClick={() => useEditor.getState().addClipFromAsset(asset.id)}- >- <Plus className="size-3.5" />- </button>- )}- </div>- </div>- )}- </div>- </aside>- );-}diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsxnew file mode 100644index 00000000..5eb65a2a--- /dev/null+++ b/site/src/cut/components/ImageGenPanel.tsx@@ -0,0 +1,250 @@+"use client";++import { useEffect, useMemo, useRef } from "react";+import { ChevronDown, Loader2, Maximize2, Sparkles, Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";+import { collectRefs, useRefCandidates, useAssetDrop } from "@/cut/lib/assetRef";+import { signInUrl, useGenerate, useSignedIn } from "@/cut/lib/generate";+import { IMAGE_ASPECT_LABEL, useImageGen, type ImageAspect } from "@/cut/lib/imageGen";+import { useLightbox } from "@/cut/lib/lightbox";+import { useEditor } from "@/cut/lib/store";+import type { MediaAsset } from "@/cut/lib/types";+import { cn } from "@/lib/utils";+import { CopyRefButton, MentionTextarea, RefChips, RefHandlePill } from "./AssetRefs";++// The generate-image panel: an always-on column in the Image tab, sitting left+// of the stock browser. Clicking a stock tile loads its saved prompt here; the+// user picks a size, edits the prompt, generates on their Donkey account, and+// the results stack below as big tiles.+//+// References ride along as input images: drag any image or video in (stock+// tile, media card, library clip, timeline clip) or mention it by @name.++export function ImageGenPanel({ projectId }: { projectId: string }) {+ const { prompt, aspect, refs } = useImageGen();+ const signedIn = useSignedIn();+ const candidates = useRefCandidates();+ const job = useGenerate((s) =>+ s.jobs.find((j) => j.kind === "image" && j.projectId === projectId)+ );+ // Select the stable `assets` reference and derive here: filtering inside the+ // selector returns a fresh array every store write (including usePlayback's+ // per-frame ticks) and would re-render the panel constantly. Newest first.+ const assets = useEditor((s) => s.assets);+ const generated = useMemo(+ () => assets.filter((a) => a.origin === "generated" && a.type === "image").reverse(),+ [assets]+ );+ const { active: dropActive, attachTarget, targetProps } = useAssetDrop((ref) => {+ if (ref.kind !== "audio") useImageGen.getState().addRef(ref);+ });++ // Default the size to the project's own orientation when the panel opens, so+ // a widescreen project generates landscape images by default (the user can+ // still pick another size). 1:1 has no project counterpart.+ useEffect(() => {+ useImageGen.getState().setAspect(useEditor.getState().aspect);+ }, []);++ const go = () => {+ const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates, { dropAudio: true });+ if (!text) return;+ void useGenerate.getState().generateImage(projectId, text, { refs: all, aspect });+ };++ return (+ <div ref={attachTarget} {...targetProps} className="relative flex min-h-0 flex-1 flex-col">+ <div className="flex h-12 shrink-0 items-center pr-2.5 pl-4">+ <span className="text-sm font-semibold tracking-tight">Generate image</span>+ </div>++ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3.5 pb-4">+ {/* Composer: attached references ride as little image thumbnails inside+ the input box, above the prompt (Claude-style). */}+ <div+ className={cn(+ "flex shrink-0 flex-col rounded-lg border border-input focus-within:border-ring",+ dropActive && "border-[#0a84ff] ring-2 ring-[#0a84ff]/30 ring-inset"+ )}+ >+ <RefChips+ refs={refs}+ onRemove={(r) => useImageGen.getState().removeRef(r)}+ className="p-2 pb-0"+ peekSide="bottom"+ />+ <MentionTextarea+ className="min-h-[100px] w-full resize-y bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none"+ placeholder="A neon-lit street market at night, cinematic… Drop an image in or type @ to reference one."+ value={prompt}+ onChange={(v) => useImageGen.getState().setPrompt(v)}+ candidates={candidates}+ submitKey="mod-enter"+ menuSide="bottom"+ onSubmit={go}+ />+ </div>++ <DropdownMenu>+ <DropdownMenuTrigger className="flex w-full shrink-0 items-center justify-between rounded-lg border border-input px-2.5 py-2 text-[12.5px] outline-none hover:border-ring focus-visible:border-ring">+ <span className="text-muted-foreground">Size</span>+ <span className="flex items-center gap-1 font-medium">+ {IMAGE_ASPECT_LABEL[aspect]}+ <ChevronDown className="size-3.5 text-muted-foreground" />+ </span>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="min-w-[190px]">+ <DropdownMenuRadioGroup+ value={aspect}+ onValueChange={(v) => useImageGen.getState().setAspect(v as ImageAspect)}+ >+ {(Object.keys(IMAGE_ASPECT_LABEL) as ImageAspect[]).map((a) => (+ <DropdownMenuRadioItem key={a} value={a} className="whitespace-nowrap">+ {IMAGE_ASPECT_LABEL[a]}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>++ <Button+ className="w-full shrink-0"+ disabled={!prompt.trim() || signedIn === false || job?.status === "running"}+ onClick={go}+ >+ {job?.status === "running" ? (+ <Loader2 data-icon="inline-start" className="animate-spin" />+ ) : (+ <Sparkles data-icon="inline-start" />+ )}+ Generate image+ </Button>++ {signedIn === false && (+ <p className="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>+ )}++ {/* A generation in flight (or a failed one): the finished asset drops+ into the list below, so only surface the transient states here. */}+ {job && job.status !== "done" && (+ <div className="flex shrink-0 items-center gap-2">+ {job.status === "running" && (+ <Loader2 className="size-3.5 shrink-0 animate-spin text-muted-foreground" />+ )}+ <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" ? "Generating…" : (job.error ?? "Failed.")}+ </div>+ </div>+ </div>+ )}++ {generated.length > 0 && (+ <div className="flex shrink-0 flex-col gap-1.5">+ <span className="text-[11px] font-semibold text-muted-foreground">Generated</span>+ {generated.map((a) => (+ <GeneratedTile+ key={a.id}+ asset={a}+ handle={candidates.find((c) => c.scope === "project" && c.id === a.id)?.handle}+ />+ ))}+ </div>+ )}+ </div>+ </div>+ );+}++/** A generated image, shown big: reference it in a prompt by its @handle, drag+ * it onto the timeline or into chat, click to reload its prompt, copy its+ * @reference, or delete it. Its name surfaces on hover so the grid stays clean. */+function GeneratedTile({ asset, handle }: { asset: MediaAsset; handle?: string }) {+ const tileRef = useRef<HTMLDivElement>(null);+ return (+ <div ref={tileRef} className="group relative overflow-hidden rounded-lg">+ <button+ className="block w-full outline-none focus-visible:ring-2 focus-visible:ring-ring"+ title={asset.name}+ draggable+ onDragStart={(e) => {+ setAssetDragData(e, asset.id);+ // Drag the rounded tile itself so the ghost keeps the image's corner+ // radius instead of the browser's square, white-framed default.+ if (tileRef.current) {+ const r = tileRef.current.getBoundingClientRect();+ e.dataTransfer.setDragImage(+ tileRef.current,+ e.clientX - r.left,+ e.clientY - r.top+ );+ }+ }}+ onDragEnd={clearAssetDrag}+ onClick={() => useImageGen.getState().openWith(asset.name)}+ >+ {/* eslint-disable-next-line @next/next/no-img-element -- engine media file, not Next-optimizable */}+ <img+ src={asset.url}+ alt={asset.name}+ loading="lazy"+ className="aspect-[16/10] w-full bg-black object-cover transition-transform group-hover:scale-[1.04]"+ />+ </button>+ {handle && (+ <RefHandlePill+ token={`@${handle}`}+ className="absolute top-1 left-1 opacity-0 transition-opacity group-hover:opacity-100"+ />+ )}+ <div className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent px-2 py-1.5 opacity-0 transition-opacity group-hover:opacity-100">+ <span className="block truncate text-[11px] font-medium text-white">{asset.name}</span>+ </div>+ <div className="absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">+ <button+ title="Expand"+ className="grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"+ onClick={() =>+ useLightbox.getState().open({+ src: asset.url,+ isVideo: false,+ name: asset.name,+ prompt: asset.name,+ assetId: asset.id,+ })+ }+ >+ <Maximize2 className="size-3" />+ </button>+ <CopyRefButton name={asset.name} />+ <button+ title="Delete"+ className="grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"+ onClick={() => useEditor.getState().removeAsset(asset.id)}+ >+ <Trash2 className="size-3" />+ </button>+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex 17cb3ccf..67f1c5d3 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -7,6 +7,7 @@ import {Film,Folder,FolderOpen,+ Image as ImageIcon,Link as LinkIcon,Loader2,Music,@@ -413,14 +414,19 @@ export function LibraryCard({preload="metadata"className="size-full object-cover"/>+ ) : a.type === "image" ? (+ // eslint-disable-next-line @next/next/no-img-element -- library media file, not Next-optimizable+ <img src={libraryMediaUrl(a.fileName)} alt={a.name} loading="lazy" className="size-full object-cover" />) : (<div className="grid size-full place-items-center bg-gradient-to-br from-emerald-100 to-emerald-50 text-emerald-600"><Music className="size-5" /></div>)}- <span className="absolute right-1.5 bottom-1.5 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums">- {formatTime(a.duration)}- </span>+ {a.type !== "image" && (+ <span className="absolute right-1.5 bottom-1.5 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums">+ {formatTime(a.duration)}+ </span>+ )}{onUse && (<buttonaria-label="Add to timeline"@@ -483,6 +489,11 @@ export function LibraryCard({<Film className="size-3.5 drop-shadow" /></span>)}+ {a.type === "image" && (+ <span className="absolute bottom-1.5 left-1.5 text-white/90">+ <ImageIcon className="size-3.5 drop-shadow" />+ </span>+ )}</div><CopyNameLabel name={a.name} className="px-0.5 text-xs text-muted-foreground" /></div>diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsxnew file mode 100644index 00000000..55d6966f--- /dev/null+++ b/site/src/cut/components/Lightbox.tsx@@ -0,0 +1,133 @@+"use client";++import { useEffect, useState } from "react";+import { Check, Copy, Loader2, Plus, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import { useLightbox } from "@/cut/lib/lightbox";+import { importImage } from "@/cut/lib/media";+import { useEditor } from "@/cut/lib/store";++// The image lightbox: the bigger version of a stock or generated image, with+// its name, description, and generation prompt below, plus a button to drop it+// straight onto the timeline. Mounted once in the editor.++export function Lightbox() {+ const item = useLightbox((s) => s.item);+ const [adding, setAdding] = useState(false);+ // Keyed to the added image's src, so opening a different image clears the+ // "Added" confirmation without a reset effect.+ const [addedSrc, setAddedSrc] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);++ // Escape closes the lightbox.+ useEffect(() => {+ if (!item) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") useLightbox.getState().close();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [item]);++ if (!item) return null;++ const added = addedSrc === item.src;++ const add = async () => {+ const projectId = useEditor.getState().projectId;+ if (!projectId) return;+ setAdding(true);+ try {+ if (item.assetId) {+ useEditor.getState().addClipFromAsset(item.assetId);+ } else {+ const asset = await importImage(projectId, { url: item.src, name: item.name });+ useEditor.getState().addClipFromAsset(asset.id);+ }+ setAddedSrc(item.src);+ } catch {+ // Leave the button enabled so the user can retry.+ } finally {+ setAdding(false);+ }+ };++ return (+ <div+ className="fixed inset-0 z-70 grid place-items-center bg-black/70 p-6 backdrop-blur-sm"+ onClick={() => useLightbox.getState().close()}+ >+ <div+ className="relative flex max-h-[92vh] w-full max-w-[860px] flex-col overflow-hidden rounded-2xl bg-card shadow-2xl"+ onClick={(e) => e.stopPropagation()}+ >+ <button+ title="Close"+ className="absolute top-3 right-3 z-10 grid size-8 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"+ onClick={() => useLightbox.getState().close()}+ >+ <X className="size-4" />+ </button>++ {item.isVideo ? (+ <video+ muted+ playsInline+ preload="metadata"+ src={`${item.src}#t=0.1`}+ className="block max-h-[75vh] w-full object-contain"+ />+ ) : (+ // eslint-disable-next-line @next/next/no-img-element -- static/project image, client-only page+ <img+ src={item.src}+ alt={item.name}+ className="block max-h-[75vh] w-full object-contain"+ />+ )}++ <div className="flex flex-col gap-3 overflow-y-auto p-4">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0 truncate text-[15px] font-semibold tracking-tight">{item.name}</div>+ <Button className="shrink-0" disabled={adding} onClick={add}>+ {adding ? (+ <Loader2 data-icon="inline-start" className="animate-spin" />+ ) : added ? (+ <Check data-icon="inline-start" />+ ) : (+ <Plus data-icon="inline-start" />+ )}+ {added ? "Added" : "Use"}+ </Button>+ </div>++ {item.prompt && item.prompt !== item.name && (+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between">+ <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">+ Prompt+ </span>+ <button+ title="Copy prompt"+ className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ onClick={() => {+ void navigator.clipboard.writeText(item.prompt).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ });+ }}+ >+ {copied ? <Check className="size-3 text-emerald-600" /> : <Copy className="size-3" />}+ {copied ? "Copied" : "Copy"}+ </button>+ </div>+ <p className="rounded-lg border border-border bg-muted/40 px-3 py-2 text-[12.5px] leading-relaxed">+ {item.prompt}+ </p>+ </div>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 1c5a06cd..5c8451dd 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -676,6 +676,19 @@ function CardPreview({ project: p }: { project: ProjectSummary }) {// The proxy starts at the edit's first frame; the source starts at the clip's// trim-in, so both posters show what actually plays first.const posterT = p.hasPreview ? 0 : p.previewStart ?? 0.1;++ // A still-image project with no rendered proxy posters as the image itself.+ if (!p.hasPreview && p.previewIsImage) {+ return (+ // eslint-disable-next-line @next/next/no-img-element -- engine media file, not Next-optimizable+ <img+ src={mediaUrl(p.id, p.previewFile!)}+ alt=""+ className="absolute inset-0 size-full object-cover"+ />+ );+ }+const src = p.hasPreview? apiUrl(`/api/cut/projects/${p.id}/preview`): mediaUrl(p.id, p.previewFile!);diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 2e328ef7..6658e9a9 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -43,6 +43,7 @@ import { CopyNameLabel } from "./AssetRefs";import { AudioPanel } from "./AudioPanel";import { buildDragGhost, FolderCrumb, FolderShelf } from "./desktopFolders";import { GenerateVideoPanel } from "./GeneratePanel";+import { ImageGenPanel } from "./ImageGenPanel";import { StockImagesPanel } from "./StockImagesPanel";import { LibraryCard } from "./LibraryView";@@ -123,17 +124,30 @@ export function SidePanel({})}</div>- <div className="flex w-[264px] min-h-0 shrink-0 flex-col">- {tab === "media" && (- <MediaPanel projectId={projectId} onImport={onImport} importing={importing} />- )}- {tab === "video" && <GenerateVideoPanel projectId={projectId} />}- {tab === "image" && <StockImagesPanel />}- {tab === "library" && <LibraryPanel projectId={projectId} />}- {tab === "audio" && <AudioPanel projectId={projectId} importing={importing} />}- {tab === "subtitles" && <SubtitlesPanel />}- {tab === "publish" && <PublishPanel />}- </div>+ {tab === "image" ? (+ // The Image tab is two columns: the generate-image input on the left,+ // the stock reference browser on the right. Clicking a stock tile loads+ // its prompt into the generate panel beside it.+ <>+ <div className="flex w-[252px] min-h-0 shrink-0 flex-col border-r border-border">+ <ImageGenPanel projectId={projectId} />+ </div>+ <div className="flex w-[264px] min-h-0 shrink-0 flex-col">+ <StockImagesPanel />+ </div>+ </>+ ) : (+ <div className="flex w-[264px] min-h-0 shrink-0 flex-col">+ {tab === "media" && (+ <MediaPanel projectId={projectId} onImport={onImport} importing={importing} />+ )}+ {tab === "video" && <GenerateVideoPanel projectId={projectId} />}+ {tab === "library" && <LibraryPanel projectId={projectId} />}+ {tab === "audio" && <AudioPanel projectId={projectId} importing={importing} />}+ {tab === "subtitles" && <SubtitlesPanel />}+ {tab === "publish" && <PublishPanel />}+ </div>+ )}</div>);}@@ -156,7 +170,10 @@ function MediaPanel({onImport: (files: FileList) => void;importing: boolean;}) {- const assets = useEditor((s) => s.assets);+ // Only user-imported media lives here; anything Cut created (recordings, AI+ // generations, voiceovers, freeze frames, stock adds) is tagged with an+ // `origin` and stays where it was made.+ const assets = useEditor((s) => s.assets).filter((a) => a.origin == null);const exportOpen = useEditor((s) => s.exportOpen);// A render that finishes in the background (dialog closed) drops a new file in// the exports folder; re-read the list when it lands so it shows without a@@ -348,7 +365,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: stringconst add = () => {const s = useEditor.getState();- if (asset.type === "video") s.addClipFromAsset(asset.id);+ if (asset.type === "video" || asset.type === "image") s.addClipFromAsset(asset.id);else s.addAudioFromAsset(asset.id);};@@ -412,14 +429,19 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: stringplaysInlineclassName="size-full object-cover"/>+ ) : asset.type === "image" ? (+ // eslint-disable-next-line @next/next/no-img-element -- engine/static file, not Next-optimizable+ <img src={asset.url} alt={asset.name} loading="lazy" className="size-full object-cover" />) : (<div className="grid size-full place-items-center bg-gradient-to-br from-emerald-100 to-emerald-50 text-emerald-600"><Music className="size-4.5" /></div>)}- <span className="absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9.5px] text-white tabular-nums">- {formatTime(asset.duration)}- </span>+ {asset.type !== "image" && (+ <span className="absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9.5px] text-white tabular-nums">+ {formatTime(asset.duration)}+ </span>+ )}<span className="absolute top-1 left-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100"><spanrole="button"@@ -455,13 +477,9 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string<CopyNameLabel name={asset.name} className="text-[11px] text-muted-foreground" /></div><AlertDialog open={confirmUses !== null} onOpenChange={(o) => !o && setConfirmUses(null)}>- <AlertDialogContent>+ <AlertDialogContent aria-describedby={undefined}><AlertDialogHeader><AlertDialogTitle>Remove “{asset.name}” from the project?</AlertDialogTitle>- <AlertDialogDescription>- It’s used by {confirmUses} {confirmUses === 1 ? "clip" : "clips"} on the timeline,- which will be removed too. This can be undone with ⌘Z.- </AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel>diff --git a/site/src/cut/components/StockImagesPanel.tsx b/site/src/cut/components/StockImagesPanel.tsxindex d995e67c..6088a642 100644--- a/site/src/cut/components/StockImagesPanel.tsx+++ b/site/src/cut/components/StockImagesPanel.tsx@@ -1,77 +1,57 @@"use client";-import { useMemo, useState } from "react";-import { ChevronLeft, ChevronRight, MoreHorizontal, Search, SlidersHorizontal, Sparkles } from "lucide-react";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";+import { useState } from "react";+import { ChevronLeft, ChevronRight, Maximize2, Search } from "lucide-react";import { clearRefDrag, refFromStock, setRefDragData } from "@/cut/lib/assetRef";+import { useLightbox } from "@/cut/lib/lightbox";import { useRevealEffect, useRevealFlash } from "@/cut/lib/refReveal";import { useImageGen } from "@/cut/lib/imageGen";-import { STOCK_ASPECT_LABEL, STOCK_CATEGORIES, type StockAspect, type StockCategory, type StockImage } from "@/cut/lib/stock";+import { STOCK_CATEGORIES, type StockCategory, type StockImage } from "@/cut/lib/stock";import { STOCK_IMAGES } from "@/cut/lib/stockManifest";-import { useEditor } from "@/cut/lib/store";-import type { MediaAsset } from "@/cut/lib/types";import { cn } from "@/lib/utils";-import { CopyRefButton } from "./AssetRefs";+import { CopyRefButton, RefHandlePill } from "./AssetRefs";-// The Image tab: a browsable stock catalog of AI-generated images. Every stock-// image carries the prompt that made it — clicking one copies that prompt into-// the generate flyover (over the canvas) to edit and render on the user's-// account. Finished generations land in Media and show up here under Generated.+/** A readable title from a stock id, e.g. "business-boardroom" → "Business Boardroom". */+const titleFromId = (id: string) =>+ id.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());-type View = "all" | StockCategory | "generated";-type AspectFilter = "all" | StockAspect;+// The Image tab's reference browser: a searchable catalog of AI-generated stock+// images. Every image carries the prompt that made it — clicking one loads that+// prompt into the generate panel beside it to edit and render on the user's+// account. Images the user generates show up in that panel, not here.-/** Categories shown as chips; the rest sit behind the "…" menu. */-const PRIMARY_CHIPS = 4;+type View = "all" | StockCategory;+/** Categories shown as chips; the rest sit behind the "…" menu. */const chip = (active: boolean) =>cn(- "shrink-0 rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors",+ "shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium transition-colors",active ? "bg-primary/15 text-primary" : "bg-muted text-muted-foreground hover:text-foreground");export function StockImagesPanel() {const [view, setView] = useState<View>("all");const [query, setQuery] = useState("");- const [aspect, setAspect] = useState<AspectFilter>("all");- // Select the stable `assets` reference and derive here — a `.filter()` in the- // selector returns a fresh array every call, so the panel would re-render on- // every store write, including usePlayback's per-frame currentTime ticks.- const assets = useEditor((s) => s.assets);- const generated = useMemo(() => assets.filter((a) => a.origin === "generated"), [assets]);- // A revealed stock image may sit behind a category view or the shape- // filter — open its category so the tile is on screen to flash.+ // A revealed stock image may sit behind a category view — open its category+ // so the tile is on screen to flash.useRevealEffect((ref) => {if (ref.scope !== "stock") return;const item = STOCK_IMAGES.find((i) => i.id === ref.id);if (!item) return;setView(item.category);- setAspect("all");setQuery("");});const q = query.trim().toLowerCase();const matches = (item: StockImage) =>- (aspect === "all" || item.aspect === aspect) &&- (!q || item.prompt.toLowerCase().includes(q) || item.category.toLowerCase().includes(q));- const matchesGenerated = (a: MediaAsset) => !q || a.name.toLowerCase().includes(q);+ !q || item.prompt.toLowerCase().includes(q) || item.category.toLowerCase().includes(q);const stock = STOCK_IMAGES.filter(matches);- const shownGenerated = generated.filter(matchesGenerated);- const overflow = STOCK_CATEGORIES.slice(PRIMARY_CHIPS);return (<>- <div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-2.5">+ <div className="flex h-12 shrink-0 items-center pr-2.5 pl-2.5"><span className="flex min-w-0 items-center gap-1 text-sm font-semibold tracking-tight">{view !== "all" && (<button@@ -83,39 +63,9 @@ export function StockImagesPanel() {</button>)}<span className={cn("truncate", view === "all" && "pl-1.5")}>- {view === "all" ? "Stock Images" : view === "generated" ? "Generated" : view}+ {view === "all" ? "Stock Images" : view}</span></span>- <span className="flex shrink-0 items-center">- <button- title="Generate an image"- className="grid size-7 place-items-center rounded-md text-muted-foreground hover:text-foreground"- onClick={() => useImageGen.getState().openWith("")}- >- <Sparkles className="size-4" />- </button>- <DropdownMenu>- <DropdownMenuTrigger- title="Filter by shape"- className={cn(- "grid size-7 place-items-center rounded-md hover:text-foreground",- aspect === "all" ? "text-muted-foreground" : "text-primary"- )}- >- <SlidersHorizontal className="size-4" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuRadioGroup value={aspect} onValueChange={(v) => setAspect(v as AspectFilter)}>- <DropdownMenuRadioItem value="all">All</DropdownMenuRadioItem>- {(Object.keys(STOCK_ASPECT_LABEL) as StockAspect[]).map((a) => (- <DropdownMenuRadioItem key={a} value={a}>- {STOCK_ASPECT_LABEL[a]}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- </span></div><div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3.5 pb-4">@@ -129,45 +79,26 @@ export function StockImagesPanel() {/></label>- <div className="flex shrink-0 flex-wrap gap-1.5">+ <div className="flex shrink-0 flex-wrap gap-1"><button className={chip(view === "all")} onClick={() => setView("all")}>All</button>- {STOCK_CATEGORIES.slice(0, PRIMARY_CHIPS).map((c) => (+ {STOCK_CATEGORIES.map((c) => (<button key={c} className={chip(view === c)} onClick={() => setView(c)}>{c}</button>))}- {(view === "generated" || overflow.includes(view as StockCategory)) && (- <button className={chip(true)}>{view === "generated" ? "Generated" : view}</button>- )}- <DropdownMenu>- <DropdownMenuTrigger className={chip(false)} title="More categories">- <MoreHorizontal className="size-3.5" />- </DropdownMenuTrigger>- <DropdownMenuContent align="start">- {overflow.map((c) => (- <DropdownMenuItem key={c} onClick={() => setView(c)}>- {c}- </DropdownMenuItem>- ))}- <DropdownMenuItem onClick={() => setView("generated")}>Generated</DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu></div>{view === "all" ? (<>- {shownGenerated.length > 0 && (- <GeneratedSection assets={shownGenerated.slice(0, 6)} onViewAll={() => setView("generated")} truncated={shownGenerated.length > 6} />- )}{STOCK_CATEGORIES.map((c) => {const items = stock.filter((i) => i.category === c);if (items.length === 0) return null;return (<section key={c} className="shrink-0"><SectionHead title={c} onViewAll={items.length > 6 ? () => setView(c) : undefined} />- <div className="grid grid-cols-3 gap-1.5">+ <div className="grid grid-cols-2 gap-1.5">{items.slice(0, 6).map((i) => (<StockTile key={i.id} item={i} />))}@@ -175,27 +106,15 @@ export function StockImagesPanel() {</section>);})}- {stock.length === 0 && shownGenerated.length === 0 && <Empty />}+ {stock.length === 0 && <Empty />}</>- ) : view === "generated" ? (- shownGenerated.length > 0 ? (- <div className="grid grid-cols-2 gap-1.5">- {shownGenerated.map((a) => (- <GeneratedTile key={a.id} asset={a} />- ))}- </div>- ) : (- <p className="text-[11px] leading-relaxed text-muted-foreground">- Images you generate land here and in Media.- </p>- )) : ((() => {const items = stock.filter((i) => i.category === view);return items.length > 0 ? (<div className="grid grid-cols-2 gap-1.5">{items.map((i) => (- <StockTile key={i.id} item={i} big />+ <StockTile key={i.id} item={i} />))}</div>) : (@@ -225,30 +144,9 @@ function SectionHead({ title, onViewAll }: { title: string; onViewAll?: () => vo);}-function GeneratedSection({- assets,- onViewAll,- truncated,-}: {- assets: MediaAsset[];- onViewAll: () => void;- truncated: boolean;-}) {- return (- <section className="shrink-0">- <SectionHead title="Generated" onViewAll={truncated ? onViewAll : undefined} />- <div className="grid grid-cols-3 gap-1.5">- {assets.map((a) => (- <GeneratedTile key={a.id} asset={a} />- ))}- </div>- </section>- );-}--/** A stock thumbnail; clicking copies its saved prompt into the flyover, and- * it drags as an asset ref (chat attachment, generation reference). */-function StockTile({ item, big }: { item: StockImage; big?: boolean }) {+/** A stock thumbnail; clicking loads its saved prompt into the generate panel,+ * and it drags as an asset ref (chat attachment, generation reference). */+function StockTile({ item }: { item: StockImage }) {const { flash, attachReveal } = useRevealFlash("stock", item.id);return (<div@@ -271,45 +169,31 @@ function StockTile({ item, big }: { item: StockImage; big?: boolean }) {src={item.file}alt={item.prompt}loading="lazy"- className={cn(- "w-full bg-muted object-cover transition-transform group-hover:scale-[1.04]",- big ? "aspect-[16/10]" : "aspect-[4/3]"- )}+ className="aspect-[16/10] w-full bg-muted object-cover transition-transform group-hover:scale-[1.04]"/></button>- <CopyRefButton- name={item.id}- className="absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100"- />- </div>- );-}--/** A previously generated image (an 8s still asset); clicking reopens its- * prompt in the flyover to iterate on it, and it drags like any media card. */-function GeneratedTile({ asset }: { asset: MediaAsset }) {- return (- <div className="group relative overflow-hidden rounded-lg">- <button- title={asset.name}- className="block w-full outline-none focus-visible:ring-2 focus-visible:ring-ring"- draggable- onDragStart={(e) => setAssetDragData(e, asset.id)}- onDragEnd={clearAssetDrag}- onClick={() => useImageGen.getState().openWith(asset.name)}- >- <video- muted- playsInline- preload="metadata"- src={`${asset.url}#t=0.1`}- className="aspect-[4/3] w-full bg-black object-cover transition-transform group-hover:scale-[1.04]"- />- </button>- <CopyRefButton- name={asset.name}- className="absolute top-1 right-1 opacity-0 transition-opacity group-hover:opacity-100"+ <RefHandlePill+ token={`@${item.id}`}+ className="absolute bottom-1 left-1 opacity-0 transition-opacity group-hover:opacity-100"/>+ <div className="absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">+ <button+ title="Expand"+ className="grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"+ onClick={() =>+ useLightbox.getState().open({+ src: item.file,+ isVideo: false,+ name: titleFromId(item.id),+ prompt: item.prompt,+ assetId: null,+ })+ }+ >+ <Maximize2 className="size-3" />+ </button>+ <CopyRefButton name={item.id} />+ </div></div>);}diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex a5419b52..5c0f699a 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -19,14 +19,14 @@ import {hasAssetDrag,hasLibraryDrag,} from "@/cut/lib/assetDrag";-import { refFromAsset, startPointerRefDrag } from "@/cut/lib/assetRef";+import { draggingRef, hasRefDrag, refFromAsset, startPointerRefDrag, type AssetRef } from "@/cut/lib/assetRef";import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";import { startDrag } from "@/cut/lib/drag";-import { ensurePeaks } from "@/cut/lib/media";+import { ensurePeaks, importImage } from "@/cut/lib/media";import { clipLen, clipSpeed, getClipSpans, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";import type { VideoTrackPlacement } from "@/cut/lib/store";import { formatTime, formatTimecode } from "@/cut/lib/time";-import { TRANSITION_STYLE_LABELS } from "@/cut/lib/types";+import { IMAGE_CLIP_SECONDS, TRANSITION_STYLE_LABELS } from "@/cut/lib/types";import type { AudioClip, ClipSpan, MediaAsset, OverlayClip, SubtitleCue, TextOverlay, TransitionStyle } from "@/cut/lib/types";import { cn } from "@/lib/utils";@@ -131,6 +131,22 @@ function dropIndex(spans: ClipSpan[], from: number, dxSec: number): number {return to;}+/** On-timeline length a dropped image occupies (it has no intrinsic duration). */+const STILL_SECONDS = IMAGE_CLIP_SECONDS;++/** A base-track asset type — footage or a still image both ride the video lane. */+const isBaseType = (t: string | undefined): t is "video" | "image" =>+ t === "video" || t === "image";++/** The image ref being dragged (a stock tile), null for any other drag —+ * asset and library drags carry the ref MIME too but with video/audio kinds.+ * On the timeline it lands on the base track as a still image. */+function draggingStill(e: React.DragEvent): AssetRef | null {+ if (!hasRefDrag(e)) return null;+ const ref = draggingRef();+ return ref?.kind === "image" ? ref : null;+}+/** 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).* Exported for the Editor's OS-file drops onto the timeline. */@@ -424,9 +440,9 @@ export function Timeline() {// Drop an asset onto the timeline: video snaps into the nearest slot at time// `t`, audio lands free-form there.- const placeAssetAt = (assetId: string, type: "video" | "audio", t: number) => {+ const placeAssetAt = (assetId: string, type: "video" | "audio" | "image", t: number) => {const s = useEditor.getState();- if (type === "video") {+ if (isBaseType(type)) {const sp = getClipSpans(s.clips, s.assets);const spanIndex = videoInsertIndex(sp, t);const clipsIndex =@@ -439,15 +455,21 @@ export function Timeline() {}};- // The video being dragged, whether it comes from project media or the library.+ // The video being dragged — project media, a library clip, or an image ref+ // (which lands as a still).const draggedVideo = (e: React.DragEvent): { duration: number } | null => {if (hasLibraryDrag(e)) {const lib = draggingLibrary();- return lib && lib.type === "video" ? { duration: lib.duration } : null;+ if (!lib || !isBaseType(lib.type)) return null;+ return { duration: lib.type === "image" ? STILL_SECONDS : lib.duration };}const id = draggingAssetId();- const asset = id ? useEditor.getState().assets.find((a) => a.id === id) : null;- return asset && asset.type === "video" ? { duration: asset.duration } : null;+ if (id) {+ const asset = useEditor.getState().assets.find((a) => a.id === id);+ if (!asset || !isBaseType(asset.type)) return null;+ return { duration: asset.type === "image" ? STILL_SECONDS : asset.duration };+ }+ return draggingStill(e) ? { duration: STILL_SECONDS } : null;};// Drop targets for the upper tracks and between-track gaps: dragging a video@@ -475,9 +497,10 @@ export function Timeline() {setDropType(null);const lib = draggingLibrary();const libId = draggedLibraryId(e);+ const still = draggingStill(e);const projectId = useEditor.getState().projectId;clearAssetDrag();- if (libId && lib && lib.type === "video" && projectId) {+ if (libId && lib && isBaseType(lib.type) && projectId) {void importLibraryAsset(projectId, lib).then((asset) => useEditor.getState().addVideoFromAsset(asset.id, place, t)).catch(() => {});@@ -485,8 +508,14 @@ export function Timeline() {}const id = draggedAssetId(e);const asset = id ? useEditor.getState().assets.find((a) => a.id === id) : null;- if (id && asset?.type === "video") {+ if (id && isBaseType(asset?.type)) {useEditor.getState().addVideoFromAsset(id, place, t);+ return;+ }+ if (still && projectId) {+ void importImage(projectId, still)+ .then((img) => useEditor.getState().addVideoFromAsset(img.id, place, t))+ .catch(() => {});}},});@@ -533,25 +562,30 @@ export function Timeline() {style={{ height: timelineH }}onDragOver={(e) => {const isLib = hasLibraryDrag(e);- if (!hasAssetDrag(e) && !isLib) return;+ const still = draggingStill(e);+ if (!hasAssetDrag(e) && !isLib && !still) return;e.preventDefault();e.dataTransfer.dropEffect = "copy";- // Preview where a video would land; audio drops free-form. Library drags- // carry their own shape since they aren't in the project yet.- let type: "video" | "audio" | undefined;+ // Preview where a video would land; audio drops free-form. Library and+ // image drags carry their own shape since they aren't in the project yet.+ let type: "video" | "audio" | "image" | undefined;let duration = 0;if (isLib) {const lib = draggingLibrary();type = lib?.type;duration = lib?.duration ?? 0;+ } else if (still) {+ type = "video";+ duration = STILL_SECONDS;} else {const id = draggingAssetId();const asset = id ? useEditor.getState().assets.find((a) => a.id === id) : null;type = asset?.type;- duration = asset?.duration ?? 0;+ duration = asset?.type === "image" ? STILL_SECONDS : asset?.duration ?? 0;}- setDropType(type ?? null);- if (type !== "video" || !duration) {+ // A still rides the base (video) lane: light its insertion zones.+ setDropType(isBaseType(type) ? "video" : type ?? null);+ if (!isBaseType(type) || !duration) {setAssetDrop(null);return;}@@ -576,6 +610,7 @@ export function Timeline() {// A library asset must be copied into the project before it can land.const lib = draggingLibrary();const libId = draggedLibraryId(e);+ const still = draggingStill(e);const projectId = useEditor.getState().projectId;clearAssetDrag();if (libId && lib && projectId) {@@ -587,10 +622,20 @@ export function Timeline() {}const id = draggedAssetId(e);- if (!id) return;- e.preventDefault();- const asset = useEditor.getState().assets.find((a) => a.id === id);- if (asset) placeAssetAt(id, asset.type, t);+ if (id) {+ e.preventDefault();+ const asset = useEditor.getState().assets.find((a) => a.id === id);+ if (asset) placeAssetAt(id, asset.type, t);+ return;+ }++ // An image ref imports as a still, then snaps into the base-track slot.+ if (still && projectId) {+ e.preventDefault();+ void importImage(projectId, still)+ .then((asset) => placeAssetAt(asset.id, "image", t))+ .catch(() => {});+ }}}><div@@ -1301,7 +1346,9 @@ function ClipView({const len0 = span.len;startDrag(e, {onMove: (dx) => {- const nout = Math.max(clip.in + 0.15, Math.min(asset.duration, out0 + (dx / pps) * speed));+ // A still has no source length, so its clip can stretch to any duration.+ const maxOut = asset.type === "image" ? Infinity : asset.duration;+ const nout = Math.max(clip.in + 0.15, Math.min(maxOut, out0 + (dx / pps) * speed));s.updateClipTransient(clip.id, { out: nout });},onUp: () => {@@ -1384,32 +1431,34 @@ function ClipView({className="bottom-1 right-2"onToggle={() => useEditor.getState().updateClip(clip.id, { hidden: !clip.hidden })}/>- <DropdownMenu>- <DropdownMenuTrigger- render={- <button- aria-label="Clip options"- className="tl-clip-menu absolute top-1 right-2 z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"- onPointerDown={(e) => e.stopPropagation()}- />- }- >- <EllipsisVertical className="size-3" />- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-44">- <DropdownMenuItem- disabled={clip.muted}- onClick={() => {- const s = useEditor.getState();- s.select({ kind: "clip", id: clip.id });- s.detachAudio();- void ensurePeaks(asset);- }}+ {asset.type === "video" && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ aria-label="Clip options"+ className="tl-clip-menu absolute top-1 right-2 z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"+ onPointerDown={(e) => e.stopPropagation()}+ />+ }>- <AudioLines /> Detach audio- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <EllipsisVertical className="size-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-44">+ <DropdownMenuItem+ disabled={clip.muted}+ onClick={() => {+ const s = useEditor.getState();+ s.select({ kind: "clip", id: clip.id });+ s.detachAudio();+ void ensurePeaks(asset);+ }}+ >+ <AudioLines /> Detach audio+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}<spanclassName={cn(trimHandle, "tl-trim-l", trim?.side === "l" && "z-3 after:opacity-100")}style={{ left: hidPx }}diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex 0e161eff..3ca48632 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -19,6 +19,52 @@ function duckGainAt(audioClips: AudioClip[], t: number): number {return g;}+// A base/overlay clip is backed by a <video> for footage or an <img> for a+// still image. These helpers read either kind uniformly so the compositor+// stays one code path — an image never seeks, plays, or carries audio.+type MediaEl = HTMLVideoElement | HTMLImageElement;+const isImageEl = (el: MediaEl): el is HTMLImageElement =>+ typeof HTMLImageElement !== "undefined" && el instanceof HTMLImageElement;+const elReady = (el: MediaEl) =>+ isImageEl(el) ? el.complete && el.naturalWidth > 0 : el.readyState >= 2 && el.videoWidth > 0;+const elW = (el: MediaEl) => (isImageEl(el) ? el.naturalWidth : el.videoWidth);+const elH = (el: MediaEl) => (isImageEl(el) ? el.naturalHeight : el.videoHeight);+// A source that will never become ready: a video decode error, or an image+// that finished loading (`complete`) with no pixels (a broken/unreachable URL).+// The compositor paints through these instead of wedging on them.+const elErrored = (el: MediaEl) =>+ isImageEl(el) ? el.complete && el.naturalWidth === 0 : !!el.error;+const pauseEl = (el: MediaEl) => {+ if (!isImageEl(el) && !el.paused) el.pause();+};+/** Build the decoder element for a clip's asset: an <img> for a still, a+ * hidden <video> for footage. */+function makeMediaEl(asset: MediaAsset): MediaEl {+ if (asset.type === "image") {+ const img = document.createElement("img");+ img.crossOrigin = "anonymous";+ img.src = asset.url;+ return img;+ }+ const v = document.createElement("video");+ v.playsInline = true;+ v.preload = "auto";+ v.crossOrigin = "anonymous";+ v.src = asset.url;+ return v;+}+/** Release an element's source. Images just drop the src; videos stop and+ * unload the decoder. */+function teardown(el: MediaEl) {+ if (isImageEl(el)) {+ el.removeAttribute("src");+ return;+ }+ el.pause();+ el.removeAttribute("src");+ el.load();+}+// 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// sharp on Retina displays. The engine reads the size off the canvas each@@ -35,10 +81,10 @@ class Engine {// decoders, so a cross-dissolve can show both at once and the incoming clip// warms during the overlap instead of fighting the outgoing one over a single// element's seek head (the black flash between same-source segments).- private videoEls = new Map<string, HTMLVideoElement>();+ private videoEls = new Map<string, MediaEl>();// One element per overlay clip (keyed by clip id, not asset) so the same// source can appear on two tracks at once.- private overlayEls = new Map<string, HTMLVideoElement>();+ private overlayEls = new Map<string, MediaEl>();private audioEls = new Map<string, HTMLAudioElement>();private raf = 0;private activeClipId: string | null = null;@@ -55,30 +101,18 @@ class Engine {dispose() {this.disposed = true;cancelAnimationFrame(this.raf);- for (const el of this.videoEls.values()) {- el.pause();- el.removeAttribute("src");- el.load();- }- for (const el of this.overlayEls.values()) {- el.pause();- el.removeAttribute("src");- el.load();- }+ for (const el of this.videoEls.values()) teardown(el);+ for (const el of this.overlayEls.values()) teardown(el);for (const el of this.audioEls.values()) el.pause();this.videoEls.clear();this.overlayEls.clear();this.audioEls.clear();}- private videoFor(clip: VideoClip, asset: MediaAsset) {+ private videoFor(clip: VideoClip, asset: MediaAsset): MediaEl {let el = this.videoEls.get(clip.id);if (!el) {- el = document.createElement("video");- el.playsInline = true;- el.preload = "auto";- el.crossOrigin = "anonymous";- el.src = asset.url;+ el = makeMediaEl(asset);this.videoEls.set(clip.id, el);}return el;@@ -86,8 +120,11 @@ class Engine {/** Seek/rate/play one clip's element toward its frame at timeline time `t`,* without touching any other element (the caller pauses stale ones). */- private prepare(span: ClipSpan, t: number, play: boolean, muted: boolean) {+ private prepare(span: ClipSpan, t: number, play: boolean, muted: boolean): MediaEl {const el = this.videoFor(span.clip, span.asset);+ // A still never seeks, plays, or carries audio — it's ready as soon as the+ // <img> decodes. Skip every video-clock operation.+ if (isImageEl(el)) return el;const speed = clipSpeed(span.clip);if (el.playbackRate !== speed) el.playbackRate = speed;const target = span.clip.in + Math.max(0, t - span.start) * speed;@@ -113,7 +150,7 @@ class Engine {private pauseExcept(keep: Set<string>) {for (const [clipId, el] of this.videoEls) {- if (!keep.has(clipId) && !el.paused) el.pause();+ if (!keep.has(clipId)) pauseEl(el);}}@@ -121,7 +158,7 @@ class Engine {* region and crops the overflow (clipped to the rect); "fit" contains the* whole picture inside it, centered. `zoom` scales the picture around the* region's center (zoom transitions), clipping the overflow to the rect. */- private drawIntoRect(el: HTMLVideoElement, rect: FrameRect, fill: boolean, alpha: number, zoom = 1) {+ private drawIntoRect(el: MediaEl, rect: FrameRect, fill: boolean, alpha: number, zoom = 1) {const ctx = this.canvas.getContext("2d");if (!ctx) return;const W = this.canvas.width;@@ -130,12 +167,11 @@ class Engine {const ry = rect.y * H;const rw = rect.w * W;const rh = rect.h * H;- const sc =- (fill- ? Math.max(rw / el.videoWidth, rh / el.videoHeight)- : Math.min(rw / el.videoWidth, rh / el.videoHeight)) * zoom;- const dw = el.videoWidth * sc;- const dh = el.videoHeight * sc;+ const vw = elW(el);+ const vh = elH(el);+ const sc = (fill ? Math.max(rw / vw, rh / vh) : Math.min(rw / vw, rh / vh)) * zoom;+ const dw = vw * sc;+ const dh = vh * sc;const dx = rx + (rw - dw) / 2;const dy = ry + (rh - dh) / 2;const prevAlpha = ctx.globalAlpha;@@ -153,7 +189,7 @@ class Engine {ctx.globalAlpha = prevAlpha;}- private drawLayer(el: HTMLVideoElement | null, clip: VideoClip | undefined, clear: boolean, alpha: number, zoom = 1) {+ private drawLayer(el: MediaEl | null, clip: VideoClip | undefined, clear: boolean, alpha: number, zoom = 1) {const ctx = this.canvas.getContext("2d");if (!ctx) return;const W = this.canvas.width;@@ -176,7 +212,7 @@ class Engine {}// Mid-seek the element has no decodable frame; keep the previous frame// on the canvas instead of strobing black (matters while skimming).- if (el.readyState < 2 || !el.videoWidth) return;+ if (!elReady(el)) return;if (clear) {ctx.fillStyle = "#000";ctx.fillRect(0, 0, W, H);@@ -189,12 +225,11 @@ class Engine {return;}const fill = clip?.fit === "fill";- const scale =- (fill- ? Math.max(W / el.videoWidth, H / el.videoHeight)- : Math.min(W / el.videoWidth, H / el.videoHeight)) * zoom;- const dw = el.videoWidth * scale;- const dh = el.videoHeight * scale;+ const vw = elW(el);+ const vh = elH(el);+ const scale = (fill ? Math.max(W / vw, H / vh) : Math.min(W / vw, H / vh)) * zoom;+ const dw = vw * scale;+ const dh = vh * scale;let dx = (W - dw) / 2;let dy = (H - dh) / 2;if (fill) {@@ -224,7 +259,7 @@ class Engine {const next = spans[idx + 1];const prev = spans[idx - 1];const style = masterSpan.clip.transitionStyle ?? "crossfade";- let incEl: HTMLVideoElement | null = null;+ let incEl: MediaEl | null = null;let alpha = 0;let masterZoom = 1;let incZoom = 1;@@ -283,7 +318,9 @@ class Engine {// 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)));+ if (!isImageEl(masterEl)) {+ 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).@@ -296,15 +333,12 @@ class Engine {return masterEl;}- private overlayVideoFor(clip: OverlayClip, asset: MediaAsset) {+ private overlayVideoFor(clip: OverlayClip, asset: MediaAsset): MediaEl {let el = this.overlayEls.get(clip.id);if (!el) {- el = document.createElement("video");- el.playsInline = true;- el.preload = "auto";- el.crossOrigin = "anonymous";- el.muted = true; // overlay audio is mixed on export, not previewed here- el.src = asset.url;+ el = makeMediaEl(asset);+ // Overlay audio is mixed on export, not previewed here.+ if (!isImageEl(el)) el.muted = true;this.overlayEls.set(clip.id, el);}return el;@@ -373,8 +407,9 @@ class Engine {/** Seek/rate/play one overlay clip's element toward its frame at timeline* time `t` (the overlay counterpart of `prepare`). */- private prepareOverlay(clip: OverlayClip, asset: MediaAsset, t: number, play: boolean) {+ private prepareOverlay(clip: OverlayClip, asset: MediaAsset, t: number, play: boolean): MediaEl {const el = this.overlayVideoFor(clip, asset);+ if (isImageEl(el)) return el;const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;if (el.playbackRate !== speed) el.playbackRate = speed;const target = clip.in + Math.max(0, t - clip.start) * speed;@@ -408,11 +443,11 @@ class Engine {play: boolean,side: "below" | "above",active: Set<string>,- prepared?: { clip: OverlayClip; el: HTMLVideoElement }[]+ prepared?: { clip: OverlayClip; el: MediaEl }[]) {for (const { clip, el } of prepared ?? this.prepareSide(t, play, side)) {active.add(clip.id);- if (el.readyState < 2 || !el.videoWidth) continue;+ if (!elReady(el)) continue;const rect = rectOf(clip);const cover = clip.fit === "fill" || (clip.fit == null && isFullRect(rect));this.drawIntoRect(el, rect, cover, 1);@@ -424,10 +459,9 @@ class Engine {const s = useEditor.getState();for (const [id, el] of this.overlayEls) {if (active.has(id)) continue;- if (!el.paused) el.pause();+ pauseEl(el);if (!s.overlayClips.some((c) => c.id === id)) {- el.removeAttribute("src");- el.load();+ teardown(el);this.overlayEls.delete(id);}}@@ -490,9 +524,7 @@ class Engine {const live = new Set(s.clips.map((c) => c.id));for (const [id, el] of this.videoEls) {if (live.has(id)) continue;- el.pause();- el.removeAttribute("src");- el.load();+ teardown(el);this.videoEls.delete(id);}}@@ -529,16 +561,16 @@ class Engine {let ready = true;if (span) {const el = this.prepare(span, Math.min(pt, span.start + span.len), false, true);- if (el.readyState < 2 || !el.videoWidth) ready = false;+ // A broken source never becomes ready; paint without it rather than+ // wedging the preview on it.+ if (!elErrored(el) && !elReady(el)) ready = false;}// Prime each side once; the readiness scan and the draw step below reuse// these instead of re-filtering/seeking the overlays a second time.const belowLive = this.prepareSide(pt, false, "below");const aboveLive = this.prepareSide(pt, false, "above");for (const { el } of [...belowLive, ...aboveLive]) {- // An errored element never becomes ready; paint without it rather- // than wedging the preview on a broken source.- if (!el.error && (el.readyState < 2 || !el.videoWidth)) ready = false;+ if (!elErrored(el) && !elReady(el)) ready = false;}if (!ready) {this.pauseExcept(new Set(span ? [span.clip.id] : []));@@ -567,7 +599,9 @@ class Engine {// this only bites a genuinely cold first frame.)if (span) {const el = this.prepare(span, t, true, span.clip.muted || !!span.clip.hidden);- if (el.readyState < 2 || !el.videoWidth) {+ // A broken source (unreachable still, decode error) never becomes ready;+ // fall through so the wall clock advances past it instead of freezing.+ if (!elReady(el) && !elErrored(el)) {this.pauseExcept(new Set([span.clip.id]));this.syncSoundtrack(t, true);return;@@ -591,14 +625,23 @@ class Engine {// only when the clock genuinely leads.const now = performance.now();const dt = this.lastPlayNow ? Math.min(0.25, (now - this.lastPlayNow) / 1000) : 0;- const speed = clipSpeed(span.clip);- const derived = span.start + (el.currentTime - span.clip.in) / speed;- const cand = Math.min(t + dt, derived + 0.06);- t = derived - cand > 0.25 ? derived : Math.max(t, cand);- t = Math.max(span.start, Math.min(t, span.start + span.len));+ let atEnd: boolean;+ if (isImageEl(el)) {+ // A still has no element clock — advance purely by wall clock and end+ // at the clip's timeline footprint.+ t = Math.max(span.start, Math.min(t + dt, span.start + span.len));+ atEnd = t >= span.start + span.len - 0.0001;+ } else {+ const speed = clipSpeed(span.clip);+ const derived = span.start + (el.currentTime - span.clip.in) / speed;+ const cand = Math.min(t + dt, derived + 0.06);+ t = derived - cand > 0.25 ? derived : Math.max(t, cand);+ t = Math.max(span.start, Math.min(t, span.start + span.len));+ atEnd = el.currentTime >= span.clip.out - 0.02 || el.ended;+ }// Clip boundary: hand off to the next clip, or (if the base is done but an// upper/lower track runs on) fall through to the wall-clock tail.- if (el.currentTime >= span.clip.out - 0.02 || el.ended) {+ if (atEnd) {const idx = spans.indexOf(span);const next = spans[idx + 1];if (next) {@@ -613,7 +656,7 @@ class Engine {} else if (t >= total - 0.001) {// Base and every other track finished.useEditor.setState({ playing: false, currentTime: total });- el.pause();+ pauseEl(el);this.drawOverlays(t, true, "above", active);this.drawProjectFade(this.projectFadeGain(total, total));this.cleanupOverlays(active);@@ -646,7 +689,7 @@ class Engine {const fadeGain = this.projectFadeGain(t, total);if (fadeGain < 1 && span) {const mel = this.videoEls.get(span.clip.id);- if (mel) mel.volume = Math.min(mel.volume, fadeGain);+ if (mel && !isImageEl(mel)) mel.volume = Math.min(mel.volume, fadeGain);}this.drawProjectFade(fadeGain);this.cleanupOverlays(active);diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex 59215d06..f7c51710 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -85,7 +85,8 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {len: r(sp.len),in: r(sp.clip.in),out: r(sp.clip.out),- sourceDuration: r(sp.asset.duration),+ // A still has no source length; report its placed length instead of 0.+ sourceDuration: r(sp.asset.type === "image" ? sp.len : sp.asset.duration),muted: sp.clip.muted,framing: sp.clip.fit ?? "fit",speed: r(sp.clip.speed ?? 1),diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex a808ae6e..b25f1792 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -7,7 +7,7 @@ import { getClipSpans, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditorimport { buildAiContext } from "./aiContext";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";+import { FRAME, IMAGE_CLIP_SECONDS, mediaUrl, TRANSITION_STYLE_IDS, type AudioClip, type FontId, type MediaAsset, type TransitionStyle } from "./types";const round2 = (n: number) => Math.round(n * 100) / 100;@@ -90,7 +90,8 @@ export async function runAiTool(case "trim_clip": {const clip = requireItem(s.clips, input.clipId, "video clip");const asset = s.assets.find((a) => a.id === clip.assetId);- const dur = asset?.duration ?? clip.out;+ // A still has no source bound, so its clip can stretch to any length.+ const dur = asset?.type === "image" ? Infinity : asset?.duration ?? clip.out;const nextIn = isNum(input.in) ? clamp(input.in, 0, dur - 0.1) : clip.in;const nextOut = isNum(input.out) ? clamp(input.out, 0.1, dur) : clip.out;if (nextOut - nextIn < 0.1) throw new ToolError("Clip must stay at least 0.1s long.");@@ -212,7 +213,7 @@ export async function runAiTool(});const body = await apiJson<MediaAsset>(res);if (!res.ok) throw new ToolError(body.error ?? "Could not render the freeze frame.");- const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName) };+ const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName), origin: "freeze" };const cur = useEditor.getState();cur.addAsset(asset);cur.addClipFromAsset(asset.id); // lands at the end, selected@@ -248,7 +249,8 @@ export async function runAiTool(assetId: asset.id,name: asset.name,kind: "image",- duration: Math.round(asset.duration * 100) / 100,+ // A still has no source length; report its default placed length.+ duration: IMAGE_CLIP_SECONDS,addedToTimeline: placed.added,clipId: placed.clipId,index: placed.index,diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex a4c2eab6..07e6215a 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -269,7 +269,7 @@ export function useRefCandidates(): AssetRef[] {return useMemo(() => {const counters = { v: 0, i: 0, a: 0 };const project = assets.map((a) => {- const prefix = a.origin === "generated" ? "i" : a.type === "video" ? "v" : "a";+ const prefix = a.type === "image" ? "i" : a.type === "video" ? "v" : "a";counters[prefix] += 1;return { ...refFromAsset(a), handle: `${prefix}${counters[prefix]}` };});@@ -328,6 +328,26 @@ export function splitMentions(text: string, candidates: AssetRef[]): (string | Areturn parts;}+/** Like {@link splitMentions}, but keeps the literal token text for every+ * resolved mention so an overlay can render it as a pill in place — the+ * rendered characters stay identical to the textarea, so widths align. */+export function highlightMentions(+ text: string,+ candidates: AssetRef[]+): { text: string; ref: AssetRef | null }[] {+ const parts: { text: string; ref: AssetRef | null }[] = [];+ let last = 0;+ for (const m of text.matchAll(MENTION_RE)) {+ const ref = resolveRefByName(m[1] ?? m[2] ?? "", candidates);+ if (!ref) continue;+ if (m.index > last) parts.push({ text: text.slice(last, m.index), ref: null });+ parts.push({ text: m[0], ref });+ last = m.index + m[0].length;+ }+ if (last < text.length) parts.push({ text: text.slice(last), ref: null });+ return parts;+}+/** The current candidate ref for a display name — how card affordances find* their short handle. Null when nothing referenceable carries the name. */export function useRefFor(name: string): AssetRef | null {diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 7a7cd200..02cdb9b9 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -147,6 +147,9 @@ async function buildExportForm(speed: clipSpeed(sp.clip),transition: sp.transitionOut,hidden: sp.clip.hidden,+ // A still: the server loops the image for the clip's length instead of+ // trimming a source span.+ image: sp.asset.type === "image",headFade: 0,tailFade: 0,headZoom: 0,@@ -194,6 +197,7 @@ async function buildExportForm(fit: c.fit,muted: c.muted,speed: c.speed,+ image: assetById.get(c.assetId)!.type === "image",}));const audio = doc.audioClipsdiff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex 06fdf48a..364c66d2 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -45,7 +45,7 @@ interface GenerateState {generateImage: (projectId: string,prompt: string,- opts?: { refs?: AssetRef[] }+ opts?: { refs?: AssetRef[]; aspect?: "16:9" | "9:16" | "1:1" }) => Promise<GenerateJob>;generateVideo: (projectId: string,@@ -223,14 +223,14 @@ export const useGenerate = create<GenerateState>((set, get) => {set((s) => ({ jobs: [job, ...s.jobs] }));return (async () => {try {- const aspect = useEditor.getState().aspect;+ const aspect = opts?.aspect ?? useEditor.getState().aspect;+ const frame =+ aspect === "16:9" ? "16:9 widescreen" : aspect === "1:1" ? "1:1 square" : "9:16 vertical";const images = await refsToInlineImages(opts?.refs ?? []);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.`,+ prompt: `${prompt}\n\nCompose the image in a ${frame} frame.`,...(images.length > 0 ? { inputs: { images } } : {}),});if (!res.ok) throw new Error(await readError(res, "Image generation failed."));@@ -247,7 +247,10 @@ export const useGenerate = create<GenerateState>((set, get) => {out.filename ?? "image.png");form.append("name", promptName(prompt));- const baked = await apiFetch(`/api/cut/projects/${projectId}/still`, {+ // Mark it generated so it surfaces in the generate panel; a stock+ // image imported from a tile sends no origin (plain import).+ form.append("origin", "generated");+ const baked = await apiFetch(`/api/cut/projects/${projectId}/image`, {method: "POST",body: form,});@@ -327,6 +330,7 @@ export const useGenerate = create<GenerateState>((set, get) => {const asset = await importFileToProject(projectId, file);if (!asset) throw new Error("Could not import the generated video.");asset.name = promptName(prompt);+ asset.origin = "generated"; // lives in the generate panel, not Mediaif (adopt(projectId, asset)) opts?.onDone?.(asset);update(job.id, { status: "done", assetId: asset.id });} catch (err) {diff --git a/site/src/cut/lib/imageGen.ts b/site/src/cut/lib/imageGen.tsindex 0dc670d5..37498503 100644--- a/site/src/cut/lib/imageGen.ts+++ b/site/src/cut/lib/imageGen.ts@@ -3,32 +3,42 @@import { create } from "zustand";import { addRefOnce, sameRef, type AssetRef } from "./assetRef";-// The generate-image flyover's state, shared between the stock browser (left-// panel, which opens it with a stock image's saved prompt) and the flyover-// itself (mounted over the preview canvas in the editor).+// The generate-image panel's state, shared between the stock browser (which+// loads a stock image's saved prompt into it on click) and the always-on+// generate panel that sits beside the browser in the Image tab.++/** The shape the next generated image is composed in. */+export type ImageAspect = "16:9" | "9:16" | "1:1";++export const IMAGE_ASPECT_LABEL: Record<ImageAspect, string> = {+ "16:9": "Landscape (16:9)",+ "9:16": "Portrait (9:16)",+ "1:1": "Square (1:1)",+};interface ImageGenState {- open: boolean;prompt: string;+ /** The shape the next generation is composed in. */+ aspect: ImageAspect;/** Visual references attached to the next generation (dragged in or picked* via @name mentions resolved on send). */refs: AssetRef[];- /** Open the flyover with a starting prompt (a stock image's saved prompt,- * or "" for a blank generation). Resets any attached references. */+ /** Load a starting prompt into the panel (a stock image's saved prompt, or+ * "" for a blank generation). Resets any attached references. */openWith: (prompt: string) => void;setPrompt: (prompt: string) => void;+ setAspect: (aspect: ImageAspect) => void;addRef: (ref: AssetRef) => void;removeRef: (ref: AssetRef) => void;- close: () => void;}export const useImageGen = create<ImageGenState>((set) => ({- open: false,prompt: "",+ aspect: "9:16",refs: [],- openWith: (prompt) => set({ open: true, prompt, refs: [] }),+ openWith: (prompt) => set({ prompt, refs: [] }),setPrompt: (prompt) => set({ prompt }),+ setAspect: (aspect) => set({ aspect }),addRef: (ref) => set((s) => ({ refs: addRefOnce(s.refs, ref) })),removeRef: (ref) => set((s) => ({ refs: s.refs.filter((r) => !sameRef(r, ref)) })),- close: () => set({ open: false }),}));diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 15553d7c..979faa0d 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -17,7 +17,7 @@ export interface LibraryAsset {id: string;fileName: string;name: string;- type: "video" | "audio";+ type: "video" | "audio" | "image";duration: number;width?: number;height?: number;@@ -144,7 +144,7 @@ export async function addLibraryAssetToProject(): Promise<MediaAsset> {const asset = await importLibraryAsset(projectId, lib);const s = useEditor.getState();- if (asset.type === "video") s.addClipFromAsset(asset.id);+ if (asset.type === "video" || asset.type === "image") s.addClipFromAsset(asset.id);else s.addAudioFromAsset(asset.id);return asset;}diff --git a/site/src/cut/lib/lightbox.ts b/site/src/cut/lib/lightbox.tsnew file mode 100644index 00000000..c5665b44--- /dev/null+++ b/site/src/cut/lib/lightbox.ts@@ -0,0 +1,32 @@+"use client";++import { create } from "zustand";++// The image lightbox: a full-screen preview opened from a stock tile or a+// generated image. Held in its own store so any tile can open it and a single+// overlay (mounted once in the editor) renders it.++export interface LightboxItem {+ /** Big source. Stock: the static file URL; generated: the still's media URL. */+ src: string;+ /** Generated stills are 8s videos — render the poster frame, not an <img>. */+ isVideo: boolean;+ name: string;+ /** The generation prompt, when known. */+ prompt: string;+ /** For a project asset, its id (add straight to the timeline); null for a+ * stock image, which the lightbox bakes into a still first. */+ assetId: string | null;+}++interface LightboxState {+ item: LightboxItem | null;+ open: (item: LightboxItem) => void;+ close: () => void;+}++export const useLightbox = create<LightboxState>((set) => ({+ item: null,+ open: (item) => set({ item }),+ close: () => set({ item: null }),+}));diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex 8f5ec850..da4c2a0b 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -2,8 +2,8 @@import { apiFetch, apiJson } from "./api";import { useEditor } from "./store";-import type { AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip } from "./types";-import { mediaUrl } from "./types";+import type { AssetType, AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip } from "./types";+import { IMAGE_CLIP_SECONDS, mediaUrl } from "./types";const uid = () => crypto.randomUUID().slice(0, 8);@@ -12,8 +12,10 @@ export function isMediaFile(file: File) {return (file.type.startsWith("video/") ||file.type.startsWith("audio/") ||+ file.type.startsWith("image/") ||isVideoFile(file) ||- isAudioFile(file)+ isAudioFile(file) ||+ isImageFile(file));}@@ -50,8 +52,9 @@ export async function createProjectFromFile(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 }];+ if (asset.type === "video" || asset.type === "image") {+ const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;+ doc.clips = [{ id: uid(), assetId: asset.id, in: 0, out, muted: false }];} else {doc.audioClips = [{ id: uid(), assetId: asset.id, start: 0, in: 0, out: asset.duration, volume: 1 },@@ -73,6 +76,10 @@ export function isAudioFile(file: File) {return file.type.startsWith("audio/") || /\.(mp3|m4a|aac|wav|ogg|flac)$/i.test(file.name);}+export function isImageFile(file: File) {+ return file.type.startsWith("image/") || /\.(png|jpe?g|webp|gif|avif|bmp)$/i.test(file.name);+}+/** Upload a raw file into the project folder, probe it, and return the asset.* Thumbnails/waveform are filled in asynchronously via `enrichAsset`. */export async function importFileToProject(@@ -80,15 +87,19 @@ export async function importFileToProject(file: File): Promise<MediaAsset | null> {// MIME wins over extension: recordings are .webm for both video and audio.- const type = file.type.startsWith("video/")+ const type: AssetType | null = file.type.startsWith("video/")? "video": file.type.startsWith("audio/")? "audio"- : isVideoFile(file)- ? "video"- : isAudioFile(file)- ? "audio"- : null;+ : file.type.startsWith("image/")+ ? "image"+ : isVideoFile(file)+ ? "video"+ : isAudioFile(file)+ ? "audio"+ : isImageFile(file)+ ? "image"+ : null;if (!type) return null;const form = new FormData();@@ -121,12 +132,55 @@ export async function importFileToProject(asset.width = v.videoWidth;asset.height = v.videoHeight;}+ } else if (type === "image") {+ // Images have no intrinsic duration; the timeline clip carries its length.+ const dims = await loadImageMeta(url);+ asset.width = dims.width;+ asset.height = dims.height;} else {asset.duration = await loadAudioDuration(url);}return asset;}+/** Natural pixel size of an image URL, for framing on the timeline. */+function loadImageMeta(url: string): Promise<{ width: number; height: number }> {+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => resolve({ width: img.naturalWidth, height: img.naturalHeight });+ img.onerror = () => resolve({ width: 0, height: 0 });+ img.src = url;+ });+}++/** Store a fetchable image (a stock tile) in the project's media as a+ * first-class image asset at its native resolution — no video baking — and+ * register it, without placing it on the timeline. Callers choose where it+ * lands. */+export async function importImage(+ projectId: string,+ image: { url: string; name: string }+): Promise<MediaAsset> {+ const dl = await fetch(image.url);+ if (!dl.ok) throw new Error("Could not read the image.");+ const blob = await dl.blob();+ const form = new FormData();+ form.append("file", blob, image.url.split("/").pop() || "image.png");+ form.append("name", image.name);+ const res = await apiFetch(`/api/cut/projects/${projectId}/image`, {+ method: "POST",+ body: form,+ });+ const body = await apiJson<MediaAsset>(res);+ if (!res.ok || !body.fileName) throw new Error(body.error ?? "Could not add the image.");+ // A stock image lands on the timeline where the caller places it, not in the+ // Media panel — tag it so it stays out.+ const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName), origin: "stock" };+ useEditor.getState().addAsset(asset);+ void enrichAsset(asset);+ 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(@@ -157,7 +211,12 @@ export async function assetFromProjectFile(* store. Safe to call repeatedly; skips assets that are already enriched. */export async function enrichAsset(asset: MediaAsset) {try {- if (asset.type === "video" && !asset.thumbs?.length) {+ if (asset.type === "image") {+ // A still is its own filmstrip: one frame, tiled across the clip.+ if (!asset.thumbs?.length) {+ useEditor.getState().updateAsset(asset.id, { thumbs: [asset.url], thumbStep: IMAGE_CLIP_SECONDS });+ }+ } else if (asset.type === "video" && !asset.thumbs?.length) {const { thumbs, thumbStep } = await makeThumbs(asset.url, asset.duration);useEditor.getState().updateAsset(asset.id, { thumbs, thumbStep });} else if (asset.type === "audio" && !asset.peaks?.length) {diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 19d2f5a7..9e595d71 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -22,7 +22,7 @@ import type {VideoClip,} from "./types";import { apiFetch, apiJson } from "./api";-import { emptySubtitles, isCrossStyle, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";+import { emptySubtitles, IMAGE_CLIP_SECONDS, isCrossStyle, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";import { readTextStyle } from "./textStyle";import { loadUiState, saveUiState } from "./uiState";import { captureTimelineFrames } from "./visualFrames";@@ -449,11 +449,11 @@ export const useEditor = create<EditorState>((set, get) => {// (landscape footage → 16:9, portrait → 9:16); the user can switch it// any time from the top bar.const guess =- asset.type === "video" &&+ (asset.type === "video" || asset.type === "image") &&asset.width !== undefined &&asset.height !== undefined &&s.clips.length === 0 &&- !s.assets.some((a) => a.type === "video")+ !s.assets.some((a) => a.type === "video" || a.type === "image")? asset.width >= asset.height? ("16:9" as Aspect): ("9:16" as Aspect)@@ -495,13 +495,13 @@ export const useEditor = create<EditorState>((set, get) => {addClipFromAsset: (assetId, index) => {const asset = get().assets.find((a) => a.id === assetId);- if (!asset || asset.type !== "video") return;+ if (!asset || (asset.type !== "video" && asset.type !== "image")) return;push();const clip: VideoClip = {id: uid(),assetId,in: 0,- out: asset.duration,+ out: asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration,muted: false,};set((s) => {@@ -517,10 +517,15 @@ export const useEditor = create<EditorState>((set, get) => {const asset = get().assets.find((a) => a.id === assetId);if (!asset || asset.type !== "audio") return;push();+ // The soundtrack is one lane — slide the clip to the next free slot at or+ // after the target so it never lands on top of an existing sound.+ const want = Math.max(0, start ?? get().currentTime);+ const len = Math.max(MIN_LEN, asset.duration);+ const taken = get().audioClips.map((a) => ({ start: a.start, end: a.start + clipLen(a) }));const clip: AudioClip = {id: uid(),assetId,- start: Math.max(0, start ?? get().currentTime),+ start: nextFreeStart(taken, want, len),in: 0,out: asset.duration,volume: 1,@@ -677,10 +682,11 @@ export const useEditor = create<EditorState>((set, get) => {addVideoFromAsset: (assetId, place, start) => {const asset = get().assets.find((a) => a.id === assetId);- if (!asset || asset.type !== "video") return;+ if (!asset || (asset.type !== "video" && asset.type !== "image")) return;+ const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;push();if (place.kind === "base") {- const v: VideoClip = { id: uid(), assetId, in: 0, out: asset.duration, muted: false };+ const v: VideoClip = { id: uid(), assetId, in: 0, out, muted: false };set((s) => {const spans = getClipSpans(s.clips, s.assets);const at = spans.filter((sp) => sp.start + sp.len / 2 <= start).length;@@ -699,7 +705,7 @@ export const useEditor = create<EditorState>((set, get) => {track,start: Math.max(0, start),in: 0,- out: asset.duration,+ out,muted: false,};set((s) => ({diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 956074db..e13c863c 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -1,6 +1,10 @@import { apiUrl } from "./api";-export type AssetType = "video" | "audio";+export type AssetType = "video" | "audio" | "image";++/** Default on-timeline length (seconds) a still image occupies when placed —+ * an image has no intrinsic duration, so the clip carries this as its `out`. */+export const IMAGE_CLIP_SECONDS = 8;/** Project output frame. Vertical (TikTok/Reels) or widescreen (YouTube). */export type Aspect = "9:16" | "16:9";@@ -24,9 +28,11 @@ export interface StoredAsset {duration: number; // secondswidth?: number;height?: number;- /** Set on assets Cut generated itself (AI voiceovers, generated images);- * absent on imports. */- origin?: "voiceover" | "generated";+ /** How this asset entered the project. Absent = the user imported it (drag,+ * drop, or upload), so it belongs in the Media panel. Any value marks media+ * Cut created or fetched — it lives where it was made (the timeline or a+ * generation panel) and is kept out of the Media panel. */+ origin?: "voiceover" | "generated" | "recording" | "stock" | "freeze";}/** Runtime asset: stored fields plus derived/browser-only data. */@@ -456,6 +462,8 @@ export interface ProjectSummary {assetCount: number;/** Media file used for the card poster / hover fallback. */previewFile?: string;+ /** The poster file is a still image, so the card renders it as an <img>. */+ previewIsImage?: boolean;/** Source time (seconds) of the poster frame — the first clip's trim-in. */previewStart?: number;/** Whether a rendered proxy of the edit exists to play on hover. */diff --git a/site/src/cut/server/frames.ts b/site/src/cut/server/frames.tsindex ece0c234..d614d0e1 100644--- a/site/src/cut/server/frames.ts+++ b/site/src/cut/server/frames.ts@@ -3,7 +3,6 @@ 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) => {@@ -30,7 +29,7 @@ function run(cmd: string, args: string[]): Promise<void> {});}-function probeDims(file: string): Promise<{ width: number; height: number }> {+export function probeDims(file: string): Promise<{ width: number; height: number }> {return new Promise((resolve) => {const p = spawn("ffprobe", ["-v", "error",@@ -58,35 +57,6 @@ 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/projects.ts b/site/src/cut/server/http/projects.tsindex 12341324..f3b5c3c8 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -1,9 +1,6 @@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, makeStillClip } from "../frames";+import { makeFreezeFrame, probeDims } from "../frames";import {createProject,createProjectFolder,@@ -265,9 +262,9 @@ 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 }) {+ /** Store an uploaded image as a first-class image asset at native+ * resolution — no video baking. AI generations and stock tiles land here. */+ async importImage(req: Request, { id }: { id: string }) {try {if (!(await readProject(id))) return err("Project not found.", 404);const form = await req.formData();@@ -275,28 +272,19 @@ export const projectsApi = {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,- origin: "generated",- ...made,- });- } finally {- void rm(tmp, { recursive: true, force: true });- }+ const origin = form.get("origin") === "generated" ? "generated" : undefined;+ const fileName = await saveMedia(id, file);+ const dims = await probeDims(mediaPath(id, fileName));+ return Response.json({+ id: crypto.randomUUID().slice(0, 8),+ type: "image",+ name,+ fileName,+ duration: 0,+ width: dims.width,+ height: dims.height,+ ...(origin ? { origin } : {}),+ });} catch (e) {return caught(e, "Could not import the image.");}diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex dc5aa4da..23deb299 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -38,7 +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/image", handler: (req, p) => projectsApi.importImage(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 }) },diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex a5945ba3..47445781 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -48,6 +48,8 @@ export interface ExportSpec {tailZoom?: number;/** Hidden clips keep their slot but render black + silent. */hidden?: boolean;+ /** A still image: looped for the clip's length instead of trimmed. */+ image?: boolean;}[];/** Upper video tracks composited over the base, bottom track first. */overlayVideos?: {@@ -61,6 +63,8 @@ export interface ExportSpec {fit?: "fit" | "fill";muted: boolean;speed?: number;+ /** A still image: looped for the clip's length instead of trimmed. */+ image?: boolean;}[];audio: {file: string;@@ -356,8 +360,16 @@ async function runExport(job: Job, spec: ExportSpec) {const padColor = hasBelow ? "[email protected]" : "black";// One ffmpeg input per distinct media file (from the project folder),// plus one per uploaded overlay PNG.+ // Still images are excluded here: a plain `-i file` decodes one frame, so+ // each image clip/overlay gets its own looped input below instead.const mediaFiles = [- ...new Set([...spec.clips, ...spec.audio, ...overlayVideos].map((c) => c.file)),+ ...new Set(+ [+ ...spec.clips.filter((c) => !c.image),+ ...spec.audio,+ ...overlayVideos.filter((o) => !o.image),+ ].map((c) => c.file)+ ),];const audioPresence = new Map<string, boolean>();const videoPresence = new Map<string, boolean>();@@ -392,6 +404,26 @@ async function runExport(job: Job, spec: ExportSpec) {inputs.push("-i", path.join(job.tmpDir, path.basename(o.file)));}+ // Looped input per still image, sized to the clip's timeline length so the+ // segment fills without a source trim. Keyed by clip/overlay identity since+ // two clips of the same image can have different lengths.+ const imageClipInput = new Map<number, number>();+ for (let j = 0; j < spec.clips.length; j++) {+ const c = spec.clips[j];+ if (!c.image) continue;+ const dur = Math.max(0.1, (c.out - c.in) / clipRate(c));+ imageClipInput.set(j, nInputs++);+ inputs.push("-loop", "1", "-t", num(dur), "-framerate", String(fps), "-i", await resolveMedia(spec, c.file));+ }+ const imageOverlayInput = new Map<(typeof overlayVideos)[number], number>();+ for (const oc of overlayVideos) {+ if (!oc.image) continue;+ const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;+ const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);+ imageOverlayInput.set(oc, nInputs++);+ inputs.push("-loop", "1", "-t", num(olen), "-framerate", String(fps), "-i", await resolveMedia(spec, oc.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.@@ -430,7 +462,7 @@ async function runExport(job: Job, spec: ExportSpec) {// Per-clip normalized video + audio segments for the join below.spec.clips.forEach((c, j) => {- const idx = inputIndex.get(c.file)!;+ const idx = c.image ? imageClipInput.get(j)! : inputIndex.get(c.file)!;const speed = clipRate(c);const dur = clipDur(c);// Edge-transition ramps, clamped so head+tail never overrun the segment.@@ -438,7 +470,12 @@ async function runExport(job: Job, spec: ExportSpec) {const tz = Math.max(0, Math.min(c.tailZoom ?? 0, dur - hz));const hf = Math.max(0, Math.min(c.headFade ?? 0, dur));const tf = Math.max(0, Math.min(c.tailFade ?? 0, dur - hf));- if (videoPresence.get(c.file) && !c.hidden) {+ // A still's looped input is already the right length at `fps`; it has no+ // source span to trim. Footage trims `in..out` and re-times by speed.+ const timebase = c.image+ ? `[${idx}:v]setpts=PTS-STARTPTS`+ : `[${idx}:v]trim=${num(c.in)}:${num(c.out)},setpts=(PTS-STARTPTS)/${num(speed)}`;+ if ((c.image || videoPresence.get(c.file)) && !c.hidden) {const region = regionPx(c.frame, W, H);let frame: string;if (region) {@@ -461,10 +498,9 @@ async function runExport(job: Job, spec: ExportSpec) {: `scale=${W}:${H}:force_original_aspect_ratio=decrease,` +`pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=${padColor}`;}- // setpts/speed rescales the clip's duration on the timeline.- const core =- `[${idx}:v]trim=${num(c.in)}:${num(c.out)},setpts=(PTS-STARTPTS)/${num(speed)},` +- `fps=${fps},${frame},setsar=1,format=${baseFmt}`;+ // setpts/speed rescales the clip's duration on the timeline (footage);+ // a still just replays its looped input.+ const core = `${timebase},fps=${fps},${frame},setsar=1,format=${baseFmt}`;const fades =(hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}` : "") +(tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, dur - tf))}:d=${num(tf)}` : "");@@ -575,8 +611,8 @@ async function runExport(job: Job, spec: ExportSpec) {// Overlay one track clip onto `onto`, returning the new label; also queues its// audio. Reused for the below backdrop and the above-base stack.const addOverlay = (oc: (typeof overlayVideos)[number], onto: string): string => {- if (!videoPresence.get(oc.file)) return onto;- const idx = inputIndex.get(oc.file)!;+ if (!oc.image && !videoPresence.get(oc.file)) return onto;+ const idx = oc.image ? imageOverlayInput.get(oc)! : inputIndex.get(oc.file)!;const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);const end = Math.min(oc.start + olen, spec.duration);@@ -598,10 +634,13 @@ async function runExport(job: Job, spec: ExportSpec) {}const k = ovk++;const seg = `ovv${k}`;- // tpad delays the clip to its timeline start without a leading-frame stall.+ // A still replays its looped input; footage trims its source span and+ // re-times by speed. tpad then delays the clip to its timeline start.+ const timebase = oc.image+ ? `[${idx}:v]setpts=PTS-STARTPTS`+ : `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)}`;filters.push(- `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)},` +- `fps=${fps},${framing},setsar=1,format=yuv420p,tpad=start_duration=${num(oc.start)}[${seg}]`+ `${timebase},fps=${fps},${framing},setsar=1,format=yuv420p,tpad=start_duration=${num(oc.start)}[${seg}]`);const next = `vovv${k}`;filters.push(diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 1509a7f1..b4508345 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -23,7 +23,7 @@ export interface LibraryAsset {id: string;fileName: string;name: string;- type: "video" | "audio";+ type: "video" | "audio" | "image";duration: number;width?: number;height?: number;@@ -49,7 +49,7 @@ export interface LibraryFolder {export interface TemplateMedia {fileName: string; // private copy inside the library media foldername: string;- type: "video" | "audio";+ type: "video" | "audio" | "image";duration: number;width?: number;height?: number;@@ -156,6 +156,7 @@ export async function listLibrary(): Promise<LibraryAsset[]> {const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;+const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;function ffprobe(args: string[]): Promise<string> {return new Promise((resolve, reject) => {@@ -181,7 +182,7 @@ async function probe(filePath: string) {);let width: number | undefined;let height: number | undefined;- if (VIDEO_RE.test(filePath)) {+ if (VIDEO_RE.test(filePath) || IMAGE_RE.test(filePath)) {const dims = await ffprobe(["-select_streams", "v:0","-show_entries", "stream=width,height",@@ -194,6 +195,7 @@ async function probe(filePath: string) {height = h;}}+ // An image has no timeline duration of its own.return { duration: Number.isFinite(duration) ? duration : 0, width, height };}@@ -202,9 +204,10 @@ async function freeName(original: string) {return uniqueName(base, libMediaPath);}-function typeOf(fileName: string): "video" | "audio" | null {+function typeOf(fileName: string): "video" | "audio" | "image" | null {if (VIDEO_RE.test(fileName)) return "video";if (AUDIO_RE.test(fileName)) return "audio";+ if (IMAGE_RE.test(fileName)) return "image";return null;}@@ -355,7 +358,7 @@ export async function moveAsset(assetId: string, folderId: string | null) {export interface TemplateInput {name: string;duration: number;- media: { fileName: string; name: string; type: "video" | "audio"; duration: number; width?: number; height?: number }[];+ media: { fileName: string; name: string; type: "video" | "audio" | "image"; duration: number; width?: number; height?: number }[];layers: TemplateLayer[];audio: TemplateAudio[];texts: unknown[];diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsindex 28cfde51..7e286cd1 100644--- a/site/src/cut/server/projects.ts+++ b/site/src/cut/server/projects.ts@@ -145,7 +145,8 @@ async function summarize(id: string, doc: ProjectDoc): Promise<ProjectSummary> {const firstClipAsset = firstClip? doc.assets.find((a) => a.id === firstClip.assetId): undefined;- const previewAsset = firstClipAsset ?? doc.assets.find((a) => a.type === "video");+ const previewAsset =+ firstClipAsset ?? doc.assets.find((a) => a.type === "video" || a.type === "image");// Poster the clip's actual first frame (its trim-in), not the source's 0s.const previewStart = firstClipAsset && firstClip ? firstClip.in : 0;const [hasPreview, sizeBytes] = await Promise.all([@@ -161,6 +162,7 @@ async function summarize(id: string, doc: ProjectDoc): Promise<ProjectSummary> {clipCount: doc.clips.length,assetCount: doc.assets.length,previewFile: previewAsset?.fileName,+ previewIsImage: previewAsset?.type === "image",previewStart,hasPreview,folderId: doc.folderId ?? null,