Skip to content

Open source CapCut alternative.

TypeScript

feat(site): unified asset references and an image generation flyover in Cut

David Leba8b295cda58
diff --git a/site/src/app/cut/p/[id]/page.tsx b/site/src/app/cut/p/[id]/page.tsx
index db4116bd..dae5751a 100644
--- a/site/src/app/cut/p/[id]/page.tsx
+++ b/site/src/app/cut/p/[id]/page.tsx
@@ -5,12 +5,13 @@ import { useParams, useSearchParams } from "next/navigation";
import { Editor } from "@/cut/components/Editor";
// Client-only: the id comes from the URL in the browser, so the hosted shell
-// carries no server-rendered data. `from` records which tab opened the project
-// so the editor's back button returns there.
+// carries no server-rendered data. `from` and `folder` record which tab (and
+// folder within it) opened the project so the editor's back button returns
+// there.
function ProjectEditor() {
const { id } = useParams<{ id: string }>();
- const from = useSearchParams().get("from");
- return <Editor projectId={id} from={from} />;
+ const params = useSearchParams();
+ return <Editor projectId={id} from={params.get("from")} folder={params.get("folder")} />;
}
export default function ProjectPage() {
diff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsx
new file mode 100644
index 00000000..369bdfc0
--- /dev/null
+++ b/site/src/cut/components/AssetRefs.tsx
@@ -0,0 +1,425 @@
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+import { AtSign, Check, Copy, Music, X } from "lucide-react";
+import {
+ mentionToken,
+ refToken,
+ type AssetRef,
+} from "@/cut/lib/assetRef";
+import { useRefFor, useRefCandidates } from "@/cut/lib/assetRef";
+import { revealRef } from "@/cut/lib/refReveal";
+import { formatTime } from "@/cut/lib/time";
+import { cn } from "@/lib/utils";
+
+// Shared UI for asset references: the preview thumbnail, attachment chips,
+// copy-the-reference affordances, interactive `@v2` token chips (hover peek,
+// click to reveal the original asset), and a textarea with `@` autocomplete.
+// Every surface that takes references (AI chat, image/video creators)
+// composes these.
+
+/** Square media preview for a ref: video poster frame, image, or audio glyph. */
+export function RefThumb({ item, className }: { item: AssetRef; className?: string }) {
+ return (
+ <div
+ className={cn(
+ "relative shrink-0 overflow-hidden rounded-lg border border-border bg-muted",
+ className
+ )}
+ >
+ {item.kind === "video" ? (
+ <video
+ src={`${item.url}#t=0.1`}
+ preload="metadata"
+ muted
+ playsInline
+ className="size-full object-cover"
+ />
+ ) : item.kind === "image" ? (
+ // eslint-disable-next-line @next/next/no-img-element -- refs point at engine/static files, not Next-optimizable images
+ <img src={item.url} alt={item.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>
+ )}
+ {item.duration !== undefined && item.kind !== "image" && (
+ <span className="absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[8.5px] text-white tabular-nums">
+ {formatTime(item.duration)}
+ </span>
+ )}
+ </div>
+ );
+}
+
+/** The `v2` badge shown on chips, cards, and the mention menu. */
+export function RefHandleBadge({ handle, className }: { handle: string; className?: string }) {
+ return (
+ <span
+ className={cn(
+ "rounded-[5px] bg-[#0a84ff]/12 px-1 py-px font-mono text-[9px] font-medium text-[#0a84ff]",
+ className
+ )}
+ >
+ {handle}
+ </span>
+ );
+}
+
+/** Hover peek: a larger look at the ref, floated above the anchor. */
+function RefPeek({ item, side = "top" }: { item: AssetRef; side?: "top" | "bottom" }) {
+ return (
+ <div
+ className={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",
+ 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>
+ );
+}
+
+/**
+ * An inline `@v2` reference token: hover peeks at the asset, click jumps back
+ * to it (side panel switches to its tab and the card flashes). Rendered inside
+ * chat messages wherever a mention resolved.
+ */
+export function RefTokenChip({
+ item,
+ onDark,
+ peekSide = "top",
+}: {
+ item: AssetRef;
+ /** Style for a dark bubble (the user message) instead of the light page. */
+ onDark?: boolean;
+ peekSide?: "top" | "bottom";
+}) {
+ const [peek, setPeek] = useState(false);
+ return (
+ <span
+ className="relative inline-block"
+ onMouseEnter={() => setPeek(true)}
+ onMouseLeave={() => setPeek(false)}
+ >
+ <button
+ type="button"
+ title={`${item.name} — click to show`}
+ className={cn(
+ "ref-token rounded-md px-1 font-mono text-[11px] transition-colors",
+ onDark
+ ? "bg-white/15 text-[#8ec7ff] hover:bg-white/25"
+ : "bg-[#0a84ff]/10 text-[#0a84ff] hover:bg-[#0a84ff]/20"
+ )}
+ onClick={() => revealRef(item)}
+ >
+ @{item.handle ?? item.name}
+ </button>
+ {peek && <RefPeek item={item} side={peekSide} />}
+ </span>
+ );
+}
+
+/** Removable attachment chips shown above an input — hover peeks, clicking
+ * the thumb reveals the original asset. */
+export function RefChips({
+ refs,
+ onRemove,
+ className,
+ peekSide = "top",
+}: {
+ refs: AssetRef[];
+ onRemove: (ref: AssetRef) => void;
+ className?: string;
+ /** Open peeks downward when the chips sit near the top of their panel. */
+ peekSide?: "top" | "bottom";
+}) {
+ const candidates = useRefCandidates();
+ if (refs.length === 0) return null;
+ return (
+ <div className={cn("flex flex-wrap gap-2", className)}>
+ {refs.map((r) => {
+ // Handles are session-derived; show the live one, not a stored copy.
+ const handle =
+ candidates.find((c) => c.scope === r.scope && c.id === r.id)?.handle ?? r.handle;
+ return (
+ <RefChip
+ key={`${r.scope}:${r.id}`}
+ item={{ ...r, handle }}
+ onRemove={onRemove}
+ peekSide={peekSide}
+ />
+ );
+ })}
+ </div>
+ );
+}
+
+function RefChip({
+ item,
+ onRemove,
+ peekSide,
+}: {
+ item: AssetRef;
+ onRemove: (ref: AssetRef) => void;
+ peekSide: "top" | "bottom";
+}) {
+ const [peek, setPeek] = useState(false);
+ return (
+ <div
+ className="ref-chip relative"
+ onMouseEnter={() => setPeek(true)}
+ onMouseLeave={() => setPeek(false)}
+ >
+ <button
+ type="button"
+ title={`${item.name} — click to show`}
+ className="block text-left"
+ onClick={() => revealRef(item)}
+ >
+ <RefThumb item={item} className="size-14" />
+ </button>
+ {item.handle && <RefHandleBadge handle={item.handle} className="absolute bottom-1 left-1" />}
+ {peek && <RefPeek item={item} side={peekSide} />}
+ <button
+ aria-label={`Remove ${item.name}`}
+ title="Remove"
+ className="absolute -top-1.5 -right-1.5 grid size-4.5 place-items-center rounded-full bg-neutral-900 text-white shadow-sm transition-colors hover:bg-neutral-700"
+ onClick={() => onRemove(item)}
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ );
+}
+
+function useCopied(): [boolean, (text: string) => void] {
+ const [copied, setCopied] = useState(false);
+ const copy = (text: string) => {
+ void navigator.clipboard.writeText(text).then(() => {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ });
+ };
+ return [copied, copy];
+}
+
+/** Hover icon button that copies the asset's reference token (`@v2`, or the
+ * `@name` form when it has no short handle). */
+export function CopyRefButton({ name, className }: { name: string; className?: string }) {
+ const [copied, copy] = useCopied();
+ const ref = useRefFor(name);
+ const token = ref ? refToken(ref) : mentionToken(name);
+ return (
+ <span
+ role="button"
+ aria-label={`Copy reference to ${name}`}
+ title={`Copy ${token} to reference in prompts`}
+ className={cn(
+ "grid size-5 cursor-pointer place-items-center rounded-full bg-black/45 text-white hover:bg-black/65",
+ className
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ copy(token);
+ }}
+ >
+ {copied ? <Check className="size-3" /> : <Copy className="size-3" />}
+ </span>
+ );
+}
+
+/** A card's name caption with its short handle; clicking copies the reference
+ * token, ready to paste into any prompt. */
+export function CopyNameLabel({ name, className }: { name: string; className?: string }) {
+ const [copied, copy] = useCopied();
+ const ref = useRefFor(name);
+ const token = ref ? refToken(ref) : mentionToken(name);
+ return (
+ <button
+ type="button"
+ title={`Click to copy ${token} — paste it in any prompt to reference this asset`}
+ className={cn("flex min-w-0 items-center gap-1 cursor-copy text-left", className)}
+ onClick={(e) => {
+ e.stopPropagation();
+ copy(token);
+ }}
+ >
+ {ref?.handle && <RefHandleBadge handle={ref.handle} className="shrink-0" />}
+ {copied ? (
+ <span className="truncate text-emerald-600">Copied {token}</span>
+ ) : (
+ <span className="truncate">{name}</span>
+ )}
+ </button>
+ );
+}
+
+/** The open mention being typed at the caret: token start and query text. */
+function mentionAtCaret(value: string, caret: number): { start: number; query: string } | null {
+ const before = value.slice(0, caret);
+ const at = before.lastIndexOf("@");
+ if (at < 0) return null;
+ if (at > 0 && !/[\s([]/.test(before[at - 1])) return null;
+ let query = before.slice(at + 1);
+ if (query.startsWith('"')) query = query.slice(1);
+ // A finished quote or a newline means the caret left the mention.
+ if (query.includes('"') || query.includes("\n") || query.length > 60) return null;
+ return { start: at, query };
+}
+
+/**
+ * Textarea with `@` autocomplete over the given candidates — matches short
+ * handles (`@v2`) and names, and inserts the handle token when there is one.
+ * Submit behavior is the caller's: `submitKey` picks plain Enter (chat) or
+ * ⌘/Ctrl+Enter (creators).
+ */
+export function MentionTextarea({
+ value,
+ onChange,
+ candidates,
+ onSubmit,
+ submitKey = "enter",
+ menuSide = "top",
+ placeholder,
+ className,
+ rows,
+}: {
+ value: string;
+ onChange: (v: string) => void;
+ candidates: AssetRef[];
+ onSubmit?: () => void;
+ submitKey?: "enter" | "mod-enter";
+ /** Where the picker opens relative to the textarea. */
+ menuSide?: "top" | "bottom";
+ placeholder?: string;
+ className?: string;
+ rows?: number;
+}) {
+ const taRef = useRef<HTMLTextAreaElement>(null);
+ const [caret, setCaret] = useState(0);
+ const [dismissed, setDismissed] = useState<number | null>(null);
+ const [sel, setSel] = useState(0);
+
+ const mention = useMemo(() => mentionAtCaret(value, caret), [value, caret]);
+ const matches = useMemo(() => {
+ if (!mention || dismissed === mention.start) return [];
+ const q = mention.query.toLowerCase();
+ return candidates
+ .filter((c) => c.name.toLowerCase().includes(q) || c.handle?.startsWith(q))
+ .slice(0, 8);
+ }, [mention, dismissed, candidates]);
+ const open = matches.length > 0;
+ const selIndex = Math.min(sel, matches.length - 1);
+
+ const syncCaret = () => {
+ const el = taRef.current;
+ if (el) setCaret(el.selectionStart ?? 0);
+ };
+
+ const pick = (ref: AssetRef) => {
+ if (!mention) return;
+ const token = refToken(ref) + " ";
+ const next = value.slice(0, mention.start) + token + value.slice(caret);
+ const newCaret = mention.start + token.length;
+ onChange(next);
+ setSel(0);
+ requestAnimationFrame(() => {
+ const el = taRef.current;
+ if (!el) return;
+ el.focus();
+ el.setSelectionRange(newCaret, newCaret);
+ setCaret(newCaret);
+ });
+ };
+
+ return (
+ <div className="relative min-w-0">
+ {open && (
+ <div
+ className={cn(
+ "ref-mention-menu absolute inset-x-0 z-30 flex max-h-56 flex-col overflow-y-auto rounded-lg border border-border bg-popover p-1 shadow-lg",
+ menuSide === "top" ? "bottom-full mb-1" : "top-full mt-1"
+ )}
+ >
+ {matches.map((c, i) => (
+ <button
+ key={`${c.scope}:${c.id}`}
+ type="button"
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left",
+ i === selIndex ? "bg-muted" : "hover:bg-muted/60"
+ )}
+ onMouseEnter={() => setSel(i)}
+ // mousedown, not click: keep focus (and the mention state) in the textarea.
+ onMouseDown={(e) => {
+ e.preventDefault();
+ pick(c);
+ }}
+ >
+ <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>
+ )}
+ <textarea
+ ref={taRef}
+ className={className}
+ rows={rows}
+ placeholder={placeholder}
+ value={value}
+ onChange={(e) => {
+ setDismissed(null);
+ onChange(e.target.value);
+ setCaret(e.target.selectionStart ?? 0);
+ }}
+ onSelect={syncCaret}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (open) {
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
+ e.preventDefault();
+ setSel((selIndex + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length);
+ return;
+ }
+ if (e.key === "Enter" || e.key === "Tab") {
+ e.preventDefault();
+ pick(matches[selIndex]);
+ return;
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ setDismissed(mention?.start ?? null);
+ return;
+ }
+ }
+ if (!onSubmit) return;
+ const wantsSubmit =
+ submitKey === "enter"
+ ? e.key === "Enter" && !e.shiftKey
+ : e.key === "Enter" && (e.metaKey || e.ctrlKey);
+ if (wantsSubmit) {
+ e.preventDefault();
+ onSubmit();
+ }
+ }}
+ />
+ </div>
+ );
+}
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index c6dd61ca..fbbdbc79 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -14,13 +14,22 @@ import { AiPanel } from "./AiPanel";
import { ExportDialog } from "./ExportDialog";
import { ExportStatus } from "./ExportStatus";
import { Inspector } from "./Inspector";
+import { ImageGenFlyover } from "./ImageGenFlyover";
import { Preview } from "./Preview";
import { SidePanel } from "./SidePanel";
import { Timeline, videoInsertIndex } from "./Timeline";
import { TopBar } from "./TopBar";
-export function Editor({ projectId, from }: { projectId: string; from?: string | null }) {
- const back = backTarget(useCutBase(), from);
+export function Editor({
+ projectId,
+ from,
+ folder,
+}: {
+ projectId: string;
+ from?: string | null;
+ folder?: string | null;
+}) {
+ const back = backTarget(useCutBase(), from, folder);
const loaded = useEditor((s) => s.loaded);
const loadError = useEditor((s) => s.loadError);
const dropActive = useEditor((s) => s.dropActive);
@@ -349,14 +358,18 @@ export function Editor({ projectId, from }: { projectId: string; from?: string |
return (
<div className="flex h-screen min-w-[900px] overflow-hidden">
<div className="grid min-w-0 flex-1 grid-rows-[46px_minmax(0,1fr)_auto]">
- <TopBar onImport={importFiles} from={from} />
+ <TopBar onImport={importFiles} from={from} folder={folder} />
<div
className={`grid min-h-0 ${
hasInspector ? "grid-cols-[auto_minmax(0,1fr)_272px]" : "grid-cols-[auto_minmax(0,1fr)]"
}`}
>
<SidePanel projectId={projectId} onImport={importFiles} importing={importing > 0} />
- <Preview />
+ {/* relative: anchors the generate-image flyover over the canvas column */}
+ <div className="relative grid min-h-0 min-w-0">
+ <Preview />
+ <ImageGenFlyover projectId={projectId} />
+ </div>
{hasInspector && <Inspector />}
</div>
<Timeline />
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index 54aee690..0d2b6340 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -1,14 +1,28 @@
"use client";
import { useState } from "react";
-import { Film, Image as ImageIcon, Loader2, Plus, Sparkles, Trash2 } from "lucide-react";
+import { Film, Loader2, Plus, Sparkles, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
+import {
+ addRefOnce,
+ collectRefs,
+ sameRef,
+ useRefCandidates,
+ useAssetDrop,
+ type AssetRef,
+} from "@/cut/lib/assetRef";
import { signInUrl, useGenerate, useSignedIn, type GenerateJob } from "@/cut/lib/generate";
import { useEditor } from "@/cut/lib/store";
import { useLocalPref } from "@/cut/lib/uiState";
import { cn } from "@/lib/utils";
+import { MentionTextarea, RefChips } from "./AssetRefs";
-type Kind = "image" | "video";
+// AI video generation (Veo). Image generation lives in the stock browser's
+// flyover — see StockImagesPanel / ImageGenFlyover.
+//
+// A visual reference (dragged in or @name-mentioned) seeds the render: Veo
+// takes one input image, so the first reference's picture becomes the start
+// frame.
const chip = (active: boolean) =>
cn(
@@ -18,19 +32,16 @@ const chip = (active: boolean) =>
: "border-border text-muted-foreground hover:text-foreground"
);
-export function GenerateImagePanel({ projectId }: { projectId: string }) {
- return <GeneratePanel projectId={projectId} kind="image" />;
-}
-
export function GenerateVideoPanel({ projectId }: { projectId: string }) {
- return <GeneratePanel projectId={projectId} kind="video" />;
-}
-
-function GeneratePanel({ projectId, kind }: { projectId: string; kind: Kind }) {
const signedIn = useSignedIn();
const allJobs = useGenerate((s) => s.jobs);
- const jobs = allJobs.filter((j) => j.projectId === projectId && j.kind === kind);
+ const jobs = allJobs.filter((j) => j.projectId === projectId && j.kind === "video");
const [prompt, setPrompt] = useState("");
+ const [refs, setRefs] = useState<AssetRef[]>([]);
+ const candidates = useRefCandidates();
+ const { active: dropActive, attachTarget, targetProps } = useAssetDrop((ref) => {
+ if (ref.kind !== "audio") setRefs((prev) => addRefOnce(prev, ref));
+ });
const [tier, setTier] = useLocalPref<"fast" | "high">(
"cut-gen-tier",
"fast",
@@ -43,57 +54,66 @@ function GeneratePanel({ projectId, kind }: { projectId: string; kind: Kind }) {
);
const go = () => {
- const p = prompt.trim();
- if (!p) return;
- if (kind === "image") void useGenerate.getState().generateImage(projectId, p);
- else void useGenerate.getState().generateVideo(projectId, p, { tier, durationSeconds: seconds });
+ const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates, { dropAudio: true });
+ if (!text) return;
+ void useGenerate
+ .getState()
+ .generateVideo(projectId, text, { tier, durationSeconds: seconds, refs: all });
setPrompt("");
+ setRefs([]);
};
return (
<>
<div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">
- <span className="text-sm font-semibold tracking-tight">
- {kind === "image" ? "Image" : "Video"}
- </span>
+ <span className="text-sm font-semibold tracking-tight">Video</span>
</div>
- <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3.5 pb-4">
- <textarea
+ <div
+ ref={attachTarget}
+ {...targetProps}
+ className="relative flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3.5 pb-4"
+ >
+ {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>
+ )}
+ <RefChips
+ refs={refs}
+ onRemove={(ref) => setRefs((prev) => prev.filter((r) => !sameRef(r, ref)))}
+ className="shrink-0"
+ peekSide="bottom"
+ />
+ <MentionTextarea
className="gen-prompt min-h-[88px] w-full shrink-0 resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"
- placeholder={
- kind === "image"
- ? "A neon-lit street market at night, cinematic…"
- : "A drone shot rising over a foggy coastline at sunrise…"
- }
+ placeholder="A drone shot rising over a foggy coastline at sunrise… Drop media in or type @ to reference it."
value={prompt}
- onChange={(e) => setPrompt(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
- e.preventDefault();
- go();
- }
- }}
+ onChange={setPrompt}
+ candidates={candidates}
+ submitKey="mod-enter"
+ menuSide="bottom"
+ onSubmit={go}
/>
- {kind === "video" && (
- <div className="flex shrink-0 items-center justify-between gap-2">
- <div className="flex gap-1.5">
- {[4, 6, 8].map((s) => (
- <button key={s} className={chip(seconds === s)} onClick={() => setSeconds(s)}>
- {s}s
- </button>
- ))}
- </div>
- <div className="flex gap-1.5">
- {(["fast", "high"] as const).map((t) => (
- <button key={t} className={chip(tier === t)} onClick={() => setTier(t)}>
- {t === "fast" ? "Fast" : "Best"}
- </button>
- ))}
- </div>
+ <div className="flex shrink-0 items-center justify-between gap-2">
+ <div className="flex gap-1.5">
+ {[4, 6, 8].map((s) => (
+ <button key={s} className={chip(seconds === s)} onClick={() => setSeconds(s)}>
+ {s}s
+ </button>
+ ))}
</div>
- )}
+ <div className="flex gap-1.5">
+ {(["fast", "high"] as const).map((t) => (
+ <button key={t} className={chip(tier === t)} onClick={() => setTier(t)}>
+ {t === "fast" ? "Fast" : "Best"}
+ </button>
+ ))}
+ </div>
+ </div>
<Button
className="gen-go w-full shrink-0"
@@ -101,7 +121,7 @@ function GeneratePanel({ projectId, kind }: { projectId: string; kind: Kind }) {
onClick={go}
>
<Sparkles data-icon="inline-start" />
- {kind === "image" ? "Generate image" : "Generate video"}
+ Generate video
</Button>
{signedIn === false ? (
@@ -114,9 +134,7 @@ function GeneratePanel({ projectId, kind }: { projectId: string; kind: Kind }) {
</p>
) : (
<p className="shrink-0 text-[11px] leading-relaxed text-muted-foreground">
- {kind === "image"
- ? "Lands in Media as an 8s clip — trim it like footage."
- : "Veo renders take a minute or two — keep editing while it runs."}
+ Veo renders take a minute or two — keep editing while it runs.
</p>
)}
@@ -134,7 +152,6 @@ function GeneratePanel({ projectId, kind }: { projectId: string; kind: Kind }) {
function JobRow({ job }: { job: GenerateJob }) {
const asset = useEditor((s) => s.assets.find((a) => a.id === job.assetId));
- const Icon = job.kind === "image" ? ImageIcon : Film;
return (
<div className="gen-job group flex items-center gap-2.5 rounded-lg border border-border p-2">
{asset ? (
@@ -150,7 +167,7 @@ function JobRow({ job }: { job: GenerateJob }) {
{job.status === "running" ? (
<Loader2 className="size-4 animate-spin" />
) : (
- <Icon className="size-4" />
+ <Film className="size-4" />
)}
</span>
)}
@@ -162,8 +179,7 @@ function JobRow({ job }: { job: GenerateJob }) {
job.status === "error" ? "text-red-600" : "text-muted-foreground"
)}
>
- {job.status === "running" &&
- (job.kind === "video" ? "Rendering with Veo…" : "Generating…")}
+ {job.status === "running" && "Rendering with Veo…"}
{job.status === "done" && "In your media"}
{job.status === "error" && (job.error ?? "Failed.")}
</div>
diff --git a/site/src/cut/components/ImageGenFlyover.tsx b/site/src/cut/components/ImageGenFlyover.tsx
new file mode 100644
index 00000000..210f306f
--- /dev/null
+++ b/site/src/cut/components/ImageGenFlyover.tsx
@@ -0,0 +1,152 @@
+"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/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 86787b59..238666f4 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
import {
Check,
Film,
@@ -52,8 +53,11 @@ import {
type LibraryAsset,
type LibraryFolder,
} from "@/cut/lib/library";
+import { homeHref, useCutBase } from "@/cut/lib/nav";
+import { useRevealFlash } from "@/cut/lib/refReveal";
import { formatTime } from "@/cut/lib/time";
import { cn } from "@/lib/utils";
+import { CopyNameLabel } from "./AssetRefs";
import { buildDragGhost, FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";
// A dragged library selection travels as a JSON array of asset ids, so a whole
@@ -61,9 +65,13 @@ import { buildDragGhost, FolderCrumb, FolderShelf, Marquee } from "./desktopFold
const LIBRARY_MOVE_MIME = "application/x-cut-library-move";
export function LibraryView() {
+ const router = useRouter();
+ const base = useCutBase();
const [assets, setAssets] = useState<LibraryAsset[] | null>(null);
const [folders, setFolders] = useState<LibraryFolder[]>([]);
- const [openFolder, setOpenFolder] = useState<string | null>(null);
+ // The open folder lives in the URL (?folder=…) so the browser's back button
+ // steps folder → root and the location survives reloads.
+ const openFolder = useSearchParams().get("folder");
const [selected, setSelected] = useState<Set<string>>(new Set());
const [uploading, setUploading] = useState(0);
const [addOpen, setAddOpen] = useState(false);
@@ -137,6 +145,13 @@ export function LibraryView() {
}
};
+ // Open a folder (or the root, id null) by navigating, so the location is
+ // shareable and back-button friendly.
+ const gotoFolder = (id: string | null) => {
+ setSelected(new Set());
+ router.push(homeHref(base, "library", id));
+ };
+
const moveAssets = async (ids: string[], folderId: string | null) => {
if (ids.length === 0) return;
const idset = new Set(ids);
@@ -192,10 +207,7 @@ export function LibraryView() {
root="Library"
name={openFolderName ?? "Folder"}
mime={LIBRARY_MOVE_MIME}
- onBack={() => {
- setSelected(new Set());
- setOpenFolder(null);
- }}
+ onBack={() => gotoFolder(null)}
onDropOut={(ids) => void moveAssets(ids, null)}
/>
</div>
@@ -204,10 +216,7 @@ export function LibraryView() {
folders={folders}
mime={LIBRARY_MOVE_MIME}
statOf={(id) => ({ count: all.filter((a) => (a.folderId ?? null) === id).length })}
- onOpen={(id) => {
- setSelected(new Set());
- setOpenFolder(id);
- }}
+ onOpen={gotoFolder}
onCreate={async (name) => {
const f = await createLibraryFolder(name);
setFolders((prev) => [...prev, f]);
@@ -221,7 +230,7 @@ export function LibraryView() {
setAssets((prev) =>
(prev ?? []).map((a) => (a.folderId === id ? { ...a, folderId: null } : a))
);
- if (openFolder === id) setOpenFolder(null);
+ if (openFolder === id) router.replace(homeHref(base, "library"));
await deleteLibraryFolder(id).catch(() => void reload());
}}
onDropIds={(ids, fid) => void moveAssets(ids, fid)}
@@ -362,6 +371,7 @@ export function LibraryCard({
onDragStartExtra?: (e: React.DragEvent) => void;
}) {
const videoRef = useRef<HTMLVideoElement>(null);
+ const { flash, attachReveal } = useRevealFlash("library", a.id);
// Poster from the video itself so the still matches what plays on hover.
// An ffmpeg still washes out iPhone HDR (HLG) footage — the browser tone-maps
// the video correctly, so we render the frame instead of a baked thumbnail.
@@ -369,6 +379,7 @@ export function LibraryCard({
return (
<div
+ ref={attachReveal}
data-sel-id={a.id}
className="group flex flex-col gap-1.5"
draggable
@@ -389,7 +400,7 @@ export function LibraryCard({
<div
className={cn(
"relative aspect-square cursor-grab overflow-hidden rounded-xl border bg-muted transition-shadow group-hover:shadow-[0_4px_20px_rgba(0,0,0,0.1)] active:cursor-grabbing",
- selected ? "border-[#0a84ff] ring-2 ring-[#0a84ff]" : "border-border"
+ selected || flash ? "border-[#0a84ff] ring-2 ring-[#0a84ff]" : "border-border"
)}
>
{a.type === "video" ? (
@@ -473,7 +484,7 @@ export function LibraryCard({
</span>
)}
</div>
- <div className="truncate px-0.5 text-xs text-muted-foreground">{a.name}</div>
+ <CopyNameLabel name={a.name} className="px-0.5 text-xs text-muted-foreground" />
</div>
);
}
diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsx
index 14898db8..677dcb69 100644
--- a/site/src/cut/components/Preview.tsx
+++ b/site/src/cut/components/Preview.tsx
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState } from "react";
import { usePlayback } from "@/cut/hooks/usePlayback";
+import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";
import { startDrag } from "@/cut/lib/drag";
import { getClipSpans, useEditor } from "@/cut/lib/store";
import { FRAME, isFullRect, rectOf, type Aspect, type ClipSpan, type FrameRect, type MediaAsset, type VideoClip } from "@/cut/lib/types";
@@ -105,7 +106,28 @@ export function Preview() {
}
}}
>
- <canvas ref={canvasRef} width={frame.w} height={frame.h} className="block size-full" />
+ <canvas
+ ref={canvasRef}
+ width={frame.w}
+ height={frame.h}
+ className="block size-full"
+ // Drag the viewport to reference what's on screen: the clip under
+ // the playhead travels as a media drag (timeline placement, chat
+ // attachment, generation reference). Pan on a fill clip wins —
+ // its pointerdown cancels the native drag.
+ draggable
+ onDragStart={(e) => {
+ const s = useEditor.getState();
+ const spans = getClipSpans(s.clips, s.assets);
+ const t = s.currentTime;
+ const span =
+ spans.find((sp) => t >= sp.start && sp.start + sp.len > t) ??
+ spans[spans.length - 1];
+ if (!span) return e.preventDefault();
+ setAssetDragData(e, span.asset.id);
+ }}
+ onDragEnd={clearAssetDrag}
+ />
<OverlayPipHandle stage={stage} />
<OverlayLayer stageWidth={stage.w} />
</div>
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 910d08ce..2e328ef7 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -38,9 +38,12 @@ import { formatTime } from "@/cut/lib/time";
import { useLocalPref } from "@/cut/lib/uiState";
import type { MediaAsset } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
+import { useRevealEffect, useRevealFlash } from "@/cut/lib/refReveal";
+import { CopyNameLabel } from "./AssetRefs";
import { AudioPanel } from "./AudioPanel";
import { buildDragGhost, FolderCrumb, FolderShelf } from "./desktopFolders";
-import { GenerateImagePanel, GenerateVideoPanel } from "./GeneratePanel";
+import { GenerateVideoPanel } from "./GeneratePanel";
+import { StockImagesPanel } from "./StockImagesPanel";
import { LibraryCard } from "./LibraryView";
// Drag a library clip onto a folder tile to file it (side panel, single card).
@@ -73,6 +76,12 @@ export function SidePanel({
TABS.some((t) => t.id === v)
);
+ // Clicking a reference token anywhere jumps here: switch to the tab that
+ // owns the asset; the matching card scrolls into view and flashes.
+ useRevealEffect((ref) => {
+ setTab(ref.scope === "project" ? "media" : ref.scope === "library" ? "library" : "image");
+ });
+
return (
<div className="flex min-h-0 border-r border-border bg-card">
{/* Icon rail */}
@@ -119,7 +128,7 @@ export function SidePanel({
<MediaPanel projectId={projectId} onImport={onImport} importing={importing} />
)}
{tab === "video" && <GenerateVideoPanel projectId={projectId} />}
- {tab === "image" && <GenerateImagePanel projectId={projectId} />}
+ {tab === "image" && <StockImagesPanel />}
{tab === "library" && <LibraryPanel projectId={projectId} />}
{tab === "audio" && <AudioPanel projectId={projectId} importing={importing} />}
{tab === "subtitles" && <SubtitlesPanel />}
@@ -335,6 +344,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
// Number of timeline items that would be cascade-deleted; null = no prompt.
const [confirmUses, setConfirmUses] = useState<number | null>(null);
const videoRef = useRef<HTMLVideoElement>(null);
+ const { flash, attachReveal } = useRevealFlash("project", asset.id);
const add = () => {
const s = useEditor.getState();
@@ -368,6 +378,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
return (
<>
<div
+ ref={attachReveal}
className="asset-card group flex flex-col gap-1.5 text-left"
title="Drag onto the timeline, or click + to add"
draggable
@@ -384,7 +395,12 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
}
}}
>
- <div className="relative aspect-square overflow-hidden rounded-lg border border-border bg-muted transition-colors group-hover:border-input">
+ <div
+ className={cn(
+ "relative aspect-square overflow-hidden rounded-lg border border-border bg-muted transition-colors group-hover:border-input",
+ flash && "ring-2 ring-[#0a84ff] ring-offset-1"
+ )}
+ >
{asset.type === "video" ? (
// Native first frame as the poster — full-resolution, no blurry thumb.
<video
@@ -436,7 +452,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
</span>
</span>
</div>
- <div className="truncate text-[11px] text-muted-foreground">{asset.name}</div>
+ <CopyNameLabel name={asset.name} className="text-[11px] text-muted-foreground" />
</div>
<AlertDialog open={confirmUses !== null} onOpenChange={(o) => !o && setConfirmUses(null)}>
<AlertDialogContent>
@@ -492,6 +508,14 @@ function LibraryPanel({ projectId }: { projectId: string }) {
setOpenFolder(null);
}, [assets, folders, openFolder, setOpenFolder]);
+ // A revealed library asset may sit inside a folder — open it so the card is
+ // on screen to scroll to and flash.
+ useRevealEffect((ref) => {
+ if (ref.scope !== "library") return;
+ const a = (assets ?? []).find((x) => x.id === ref.id);
+ if (a) setOpenFolder(a.folderId ?? null);
+ });
+
const removeTemplate = async (id: string) => {
setTemplates((prev) => prev.filter((t) => t.id !== id));
await deleteTemplate(id).catch(() => void reload());
diff --git a/site/src/cut/components/StockImagesPanel.tsx b/site/src/cut/components/StockImagesPanel.tsx
new file mode 100644
index 00000000..d995e67c
--- /dev/null
+++ b/site/src/cut/components/StockImagesPanel.tsx
@@ -0,0 +1,319 @@
+"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 { clearRefDrag, refFromStock, setRefDragData } from "@/cut/lib/assetRef";
+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_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";
+
+// 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.
+
+type View = "all" | StockCategory | "generated";
+type AspectFilter = "all" | StockAspect;
+
+/** Categories shown as chips; the rest sit behind the "…" menu. */
+const PRIMARY_CHIPS = 4;
+
+const chip = (active: boolean) =>
+ cn(
+ "shrink-0 rounded-full px-2.5 py-1 text-[11px] 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.
+ 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);
+
+ 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">
+ <span className="flex min-w-0 items-center gap-1 text-sm font-semibold tracking-tight">
+ {view !== "all" && (
+ <button
+ title="All stock images"
+ className="grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground hover:text-foreground"
+ onClick={() => setView("all")}
+ >
+ <ChevronLeft className="size-4" />
+ </button>
+ )}
+ <span className={cn("truncate", view === "all" && "pl-1.5")}>
+ {view === "all" ? "Stock Images" : view === "generated" ? "Generated" : 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">
+ <label className="flex shrink-0 items-center gap-2 rounded-lg border border-input px-2.5 py-1.5 focus-within:border-ring">
+ <Search className="size-3.5 shrink-0 text-muted-foreground" />
+ <input
+ className="w-full bg-transparent text-[12px] outline-none placeholder:text-muted-foreground"
+ placeholder="Search…"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </label>
+
+ <div className="flex shrink-0 flex-wrap gap-1.5">
+ <button className={chip(view === "all")} onClick={() => setView("all")}>
+ All
+ </button>
+ {STOCK_CATEGORIES.slice(0, PRIMARY_CHIPS).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">
+ {items.slice(0, 6).map((i) => (
+ <StockTile key={i.id} item={i} />
+ ))}
+ </div>
+ </section>
+ );
+ })}
+ {stock.length === 0 && shownGenerated.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 />
+ ))}
+ </div>
+ ) : (
+ <Empty />
+ );
+ })()
+ )}
+ </div>
+ </>
+ );
+}
+
+function SectionHead({ title, onViewAll }: { title: string; onViewAll?: () => void }) {
+ return (
+ <div className="mb-1.5 flex items-center justify-between">
+ <span className="text-[12px] font-semibold">{title}</span>
+ {onViewAll && (
+ <button
+ className="flex items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground"
+ onClick={onViewAll}
+ >
+ View all
+ <ChevronRight className="size-3" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+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 }) {
+ const { flash, attachReveal } = useRevealFlash("stock", item.id);
+ return (
+ <div
+ ref={attachReveal}
+ className={cn(
+ "group relative overflow-hidden rounded-lg",
+ flash && "ring-2 ring-[#0a84ff] ring-offset-1"
+ )}
+ >
+ <button
+ title={item.prompt}
+ className="block w-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ draggable
+ onDragStart={(e) => setRefDragData(e, refFromStock(item))}
+ onDragEnd={clearRefDrag}
+ onClick={() => useImageGen.getState().openWith(item.prompt)}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element -- bundled static thumbs on a client-only page */}
+ <img
+ 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]"
+ )}
+ />
+ </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"
+ />
+ </div>
+ );
+}
+
+function Empty() {
+ return <p className="text-[11px] text-muted-foreground">No matches.</p>;
+}
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 7065cd01..a5419b52 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -19,6 +19,7 @@ import {
hasAssetDrag,
hasLibraryDrag,
} from "@/cut/lib/assetDrag";
+import { refFromAsset, startPointerRefDrag } from "@/cut/lib/assetRef";
import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";
import { startDrag } from "@/cut/lib/drag";
import { ensurePeaks } from "@/cut/lib/media";
@@ -1227,11 +1228,15 @@ function ClipView({
let live = false;
let target: TrackTarget = { kind: "base" };
let dropStart = span.start;
+ // Dragging a clip out of the timeline can also hand its asset to a
+ // reference drop zone (AI chat, the image/video creators).
+ const refDrag = startPointerRefDrag(refFromAsset(asset));
startDrag(e, {
onMove: (dx, dy, ev) => {
if (!live && Math.abs(dx) < 4 && Math.abs(dy) < 4) return;
if (!live) onDragActive(true);
live = true;
+ refDrag.move(ev);
if (el) {
const r = el.getBoundingClientRect();
if (ev.clientX > r.right - 36) el.scrollLeft += 14;
@@ -1250,6 +1255,11 @@ function ClipView({
},
onUp: () => {
onDragActive(false);
+ if (live && refDrag.drop()) {
+ // A zone took the ref; cancel the timeline move.
+ onCrossMove(null);
+ return onDrop(clip.id, null);
+ }
if (!live) return onDrop(clip.id, null);
if (target.kind === "base") onDrop(clip.id, effDx);
else onCrossDrop(clip.id, target, dropStart);
@@ -1503,9 +1513,16 @@ function AudioView({
s.seek(clip.start + (e.clientX - e.currentTarget.getBoundingClientRect().left) / pps);
s.pushHistory();
const start0 = clip.start;
+ const refDrag = startPointerRefDrag(refFromAsset(asset));
startDrag(e, {
- onMove: (dx) =>
- s.updateAudioTransient(clip.id, { start: Math.max(0, start0 + dx / pps) }),
+ onMove: (dx, _dy, ev) => {
+ refDrag.move(ev);
+ s.updateAudioTransient(clip.id, { start: Math.max(0, start0 + dx / pps) });
+ },
+ onUp: () => {
+ // A zone took the ref (e.g. an AI chat attachment); undo the slide.
+ if (refDrag.drop()) s.updateAudioTransient(clip.id, { start: start0 });
+ },
});
};
@@ -1640,6 +1657,7 @@ function OverlayClipView({
let live = false;
let target: TrackTarget = { kind: "track", track: clip.track };
let dropStart = clip.start;
+ const refDrag = startPointerRefDrag(refFromAsset(asset));
startDrag(e, {
onMove: (dx, dy, ev) => {
if (!live && Math.abs(dx) < 4 && Math.abs(dy) < 4) return;
@@ -1648,6 +1666,7 @@ function OverlayClipView({
onDragActive(true);
}
live = true;
+ refDrag.move(ev);
dropStart = Math.max(0, start0 + dx / pps);
s.updateOverlayClipTransient(clip.id, { start: dropStart });
target = resolveTarget(ev.clientX, ev.clientY);
@@ -1658,6 +1677,11 @@ function OverlayClipView({
onUp: () => {
onDragActive(false);
onCrossMove(null);
+ if (live && refDrag.drop()) {
+ // A zone took the ref; put the clip back where the drag started.
+ s.updateOverlayClipTransient(clip.id, { start: start0 });
+ return;
+ }
if (live) onCrossDrop(clip.id, target, dropStart);
},
});
diff --git a/site/src/cut/lib/assetDrag.ts b/site/src/cut/lib/assetDrag.ts
index fe27bc8a..9c2feadb 100644
--- a/site/src/cut/lib/assetDrag.ts
+++ b/site/src/cut/lib/assetDrag.ts
@@ -1,7 +1,9 @@
"use client";
import type React from "react";
+import { clearRefDrag, refFromAsset, refFromLibrary, setRefDragData } from "./assetRef";
import type { LibraryAsset } from "./library";
+import { useEditor } from "./store";
/** Internal HTML5 drag payload for project media assets. The custom MIME
* keeps these drags invisible to the window-level OS-file import overlay,
@@ -17,6 +19,11 @@ export function setAssetDragData(e: React.DragEvent, assetId: string) {
e.dataTransfer.setData(ASSET_MIME, assetId);
e.dataTransfer.effectAllowed = "copy";
inFlightAssetId = assetId;
+ // Every media drag also carries the unified asset ref, so reference drop
+ // zones (AI chat, the image/video creators) accept it without knowing the
+ // source surface.
+ const asset = useEditor.getState().assets.find((a) => a.id === assetId);
+ if (asset) setRefDragData(e, refFromAsset(asset));
}
/** The asset id currently being dragged, readable during `dragover`. */
@@ -35,6 +42,7 @@ export function setLibraryDragData(e: React.DragEvent, asset: LibraryAsset) {
e.dataTransfer.setData(LIBRARY_MIME, asset.id);
e.dataTransfer.effectAllowed = "copy";
inFlightLibrary = asset;
+ setRefDragData(e, refFromLibrary(asset));
}
export function draggingLibrary(): LibraryAsset | null {
@@ -56,6 +64,7 @@ export function draggedLibraryId(e: React.DragEvent | DragEvent): string | null
export function clearAssetDrag() {
inFlightAssetId = null;
inFlightLibrary = null;
+ clearRefDrag();
}
export function draggedAssetId(e: React.DragEvent | DragEvent): string | null {
diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.ts
new file mode 100644
index 00000000..a4c2eab6
--- /dev/null
+++ b/site/src/cut/lib/assetRef.ts
@@ -0,0 +1,380 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type React from "react";
+import { fetchLibrary, libraryMediaUrl, type LibraryAsset } from "./library";
+import type { StockImage } from "./stock";
+import { STOCK_IMAGES } from "./stockManifest";
+import { useEditor } from "./store";
+import type { MediaAsset } from "./types";
+
+// One reference model for every piece of media in the app. A ref names an
+// asset wherever it lives — the open project, the shared library, or the
+// bundled stock catalog — with enough to preview it (url, kind, duration) and
+// to hand it to whatever wants it: an AI chat attachment, an image/video
+// generation reference, or a timeline drop.
+//
+// Refs travel two ways:
+// - Native HTML5 drags (cards, tiles, chat) carry a REF_MIME JSON payload;
+// `setRefDragData` on the source, `useAssetDrop` on the target.
+// - Pointer drags (timeline clips, which move via pointer capture, not DnD)
+// deliver through the same drop-zone registry with `startPointerRefDrag`.
+//
+// Refs are also written as mentions in prompt text — `@v2` by short handle or
+// `@"asset name"` by name. `refToken` makes the token, `parseMentions`
+// resolves tokens back to refs on send.
+
+export type AssetRefScope = "project" | "library" | "stock";
+export type AssetRefKind = "video" | "audio" | "image";
+
+export interface AssetRef {
+ scope: AssetRefScope;
+ id: string;
+ /** Display name; mentions resolve against it (`@"beach sunset"`). */
+ name: string;
+ kind: AssetRefKind;
+ /** Fetchable URL for the media itself (previews and frame capture). */
+ url: string;
+ duration?: number;
+ /** Short mention handle (`v2`, `i1`, `a3`), assigned to project assets in
+ * media order by `useRefCandidates`. Derived per session, not persisted —
+ * display surfaces re-resolve it live so a stale copy never shows. */
+ handle?: string;
+}
+
+export const refFromAsset = (a: MediaAsset): AssetRef => ({
+ scope: "project",
+ id: a.id,
+ name: a.name,
+ kind: a.type,
+ url: a.url,
+ duration: a.duration,
+});
+
+export const refFromLibrary = (a: LibraryAsset): AssetRef => ({
+ scope: "library",
+ id: a.id,
+ name: a.name,
+ kind: a.type,
+ url: libraryMediaUrl(a.fileName),
+ duration: a.duration,
+});
+
+export const refFromStock = (i: StockImage): AssetRef => ({
+ scope: "stock",
+ id: i.id,
+ name: i.id,
+ kind: "image",
+ url: i.file,
+});
+
+export const sameRef = (a: AssetRef, b: AssetRef) => a.scope === b.scope && a.id === b.id;
+
+export const addRefOnce = (list: AssetRef[], ref: AssetRef): AssetRef[] =>
+ list.some((r) => sameRef(r, ref)) ? list : [...list, ref];
+
+/** Tolerant reader for refs persisted before the scope/kind shape (old chat
+ * threads stored `{ id, name, type, duration, url }`). */
+export function normalizeRef(v: unknown): AssetRef | null {
+ if (!v || typeof v !== "object") return null;
+ const o = v as Partial<AssetRef> & { type?: AssetRefKind };
+ if (!o.id || !o.name || !o.url) return null;
+ return {
+ scope: o.scope ?? "project",
+ id: o.id,
+ name: o.name,
+ kind: o.kind ?? o.type ?? "video",
+ url: o.url,
+ duration: o.duration,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Drag transport
+
+/** Unified drag payload; every internal media drag carries this alongside any
+ * surface-specific MIME (timeline placement, folder moves). */
+export const REF_MIME = "application/x-cut-ref";
+
+let inFlightRef: AssetRef | null = null;
+
+export function setRefDragData(e: React.DragEvent, ref: AssetRef) {
+ e.dataTransfer.setData(REF_MIME, JSON.stringify(ref));
+ if (!e.dataTransfer.effectAllowed || e.dataTransfer.effectAllowed === "uninitialized") {
+ e.dataTransfer.effectAllowed = "copy";
+ }
+ inFlightRef = ref;
+}
+
+/** The ref currently being dragged, readable during `dragover`. */
+export function draggingRef(): AssetRef | null {
+ return inFlightRef;
+}
+
+export function hasRefDrag(e: React.DragEvent | DragEvent): boolean {
+ const dt = "dataTransfer" in e ? e.dataTransfer : null;
+ return !!dt && Array.from(dt.types).includes(REF_MIME);
+}
+
+export function draggedRef(e: React.DragEvent | DragEvent): AssetRef | null {
+ const dt = "dataTransfer" in e ? e.dataTransfer : null;
+ if (!dt || !Array.from(dt.types).includes(REF_MIME)) return null;
+ try {
+ return normalizeRef(JSON.parse(dt.getData(REF_MIME)));
+ } catch {
+ return null;
+ }
+}
+
+export function clearRefDrag() {
+ inFlightRef = null;
+}
+
+// ---------------------------------------------------------------------------
+// Drop zones — shared by HTML5 drags and pointer drags
+
+interface RefZone {
+ el: HTMLElement;
+ onDrop: (ref: AssetRef) => void;
+ setActive: (active: boolean) => void;
+}
+
+const zones = new Set<RefZone>();
+
+function zoneAt(x: number, y: number): RefZone | null {
+ const hit = document.elementFromPoint(x, y);
+ if (!hit) return null;
+ for (const z of zones) if (z.el.contains(hit)) return z;
+ return null;
+}
+
+/** Drive a ref through a pointer drag (timeline clips). Call `move` from the
+ * drag's onMove so zones under the pointer light up; call `drop` on release —
+ * true means a zone took the ref and the source should cancel its own move. */
+export function startPointerRefDrag(ref: AssetRef) {
+ let x = -1;
+ let y = -1;
+ return {
+ move(ev: PointerEvent) {
+ x = ev.clientX;
+ y = ev.clientY;
+ const z = zoneAt(x, y);
+ for (const q of zones) q.setActive(q === z);
+ },
+ drop(): boolean {
+ for (const q of zones) q.setActive(false);
+ const z = zoneAt(x, y);
+ if (!z) return false;
+ z.onDrop(ref);
+ return true;
+ },
+ };
+}
+
+/** Make an element accept asset refs from both drag transports:
+ * `<div ref={attachTarget} {...targetProps}>` — `active` styles the highlight. */
+export function useAssetDrop(onDrop: (ref: AssetRef) => void): {
+ active: boolean;
+ attachTarget: (el: HTMLElement | null) => void;
+ targetProps: Pick<
+ React.HTMLAttributes<HTMLElement>,
+ "onDragEnter" | "onDragOver" | "onDragLeave" | "onDrop"
+ >;
+} {
+ const [active, setActive] = useState(false);
+ const [el, setEl] = useState<HTMLElement | null>(null);
+ const depth = useRef(0);
+ const cb = useRef(onDrop);
+ useEffect(() => {
+ cb.current = onDrop;
+ });
+
+ // Register the element as a drop zone for pointer-drag delivery.
+ useEffect(() => {
+ if (!el) return;
+ const zone: RefZone = { el, onDrop: (r) => cb.current(r), setActive };
+ zones.add(zone);
+ return () => {
+ zones.delete(zone);
+ };
+ }, [el]);
+
+ const attachTarget = useCallback((node: HTMLElement | null) => setEl(node), []);
+
+ const targetProps = useMemo<
+ Pick<React.HTMLAttributes<HTMLElement>, "onDragEnter" | "onDragOver" | "onDragLeave" | "onDrop">
+ >(() => {
+ const done = () => {
+ depth.current = 0;
+ setActive(false);
+ };
+ return {
+ onDragEnter: (e) => {
+ if (!hasRefDrag(e)) return;
+ e.preventDefault();
+ depth.current += 1;
+ setActive(true);
+ },
+ onDragOver: (e) => {
+ if (!hasRefDrag(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "copy";
+ },
+ onDragLeave: (e) => {
+ if (!hasRefDrag(e)) return;
+ depth.current -= 1;
+ if (depth.current <= 0) done();
+ },
+ onDrop: (e) => {
+ done();
+ const ref = draggedRef(e);
+ if (!ref) return;
+ e.preventDefault();
+ cb.current(ref);
+ },
+ };
+ }, []);
+
+ return { active, attachTarget, targetProps };
+}
+
+// ---------------------------------------------------------------------------
+// Candidates and @name mentions
+
+let libraryCache: LibraryAsset[] | null = null;
+let libraryLoad: Promise<LibraryAsset[]> | null = null;
+
+/** Everything referenceable right now, in resolution order: the open project's
+ * media, then the shared library, then the stock catalog. Names are unique
+ * within the list (first scope wins) so a mention resolves to one asset.
+ *
+ * Project assets get short handles in media order — `v1` videos, `i1`
+ * generated stills, `a1` audio — so a prompt can say `@v2` instead of the full
+ * name. Library items mention by name; stock ids are already short (`@nature-dunes`). */
+export function useRefCandidates(): AssetRef[] {
+ const assets = useEditor((s) => s.assets);
+ const [lib, setLib] = useState<LibraryAsset[]>(libraryCache ?? []);
+
+ useEffect(() => {
+ libraryLoad ??= fetchLibrary()
+ .then((d) => (libraryCache = d.assets))
+ .catch(() => (libraryCache = []));
+ let alive = true;
+ void libraryLoad.then((l) => alive && setLib(l));
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ 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";
+ counters[prefix] += 1;
+ return { ...refFromAsset(a), handle: `${prefix}${counters[prefix]}` };
+ });
+ const seen = new Set<string>();
+ const out: AssetRef[] = [];
+ for (const ref of [
+ ...project,
+ ...lib.map(refFromLibrary),
+ ...STOCK_IMAGES.map(refFromStock),
+ ]) {
+ const key = ref.name.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(ref);
+ }
+ return out;
+ }, [assets, lib]);
+}
+
+/** The prompt token for an asset name: `@name`, quoted when it has spaces. */
+export const mentionToken = (name: string) =>
+ /[\s"]/.test(name) ? `@"${name.replace(/"/g, "")}"` : `@${name}`;
+
+/** The preferred prompt token for a ref: its short handle (`@v2`) when it has
+ * one, the (quoted) name otherwise. */
+export const refToken = (ref: AssetRef) =>
+ ref.handle ? `@${ref.handle}` : mentionToken(ref.name);
+
+const MENTION_RE = /@(?:"([^"\n]+)"|([^\s"@]+))/g;
+
+/** Resolve one mention body against the candidates: short handle first
+ * (`v2`), then exact name (case-insensitive on both). */
+export function resolveRefByName(name: string, candidates: AssetRef[]): AssetRef | null {
+ const q = name.toLowerCase();
+ return (
+ candidates.find((c) => c.handle?.toLowerCase() === q) ??
+ candidates.find((c) => c.name.toLowerCase() === q) ??
+ null
+ );
+}
+
+/** Split text into literal runs and resolved mention refs, for rendering
+ * tokens as interactive chips (hover peek, click to reveal). Unresolved
+ * tokens stay literal text. */
+export function splitMentions(text: string, candidates: AssetRef[]): (string | AssetRef)[] {
+ const parts: (string | AssetRef)[] = [];
+ 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.slice(last, m.index));
+ parts.push(ref);
+ last = m.index + m[0].length;
+ }
+ if (last < text.length) parts.push(text.slice(last));
+ 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 {
+ const candidates = useRefCandidates();
+ return useMemo(
+ () => candidates.find((c) => c.name.toLowerCase() === name.toLowerCase()) ?? null,
+ [candidates, name]
+ );
+}
+
+/** Pull `@name` mentions out of prompt text. Resolved tokens are replaced by
+ * the plain asset name (the ref rides along separately); unresolved tokens are
+ * left as typed. */
+export function parseMentions(
+ text: string,
+ candidates: AssetRef[]
+): { refs: AssetRef[]; text: string } {
+ const refs: AssetRef[] = [];
+ const out = text.replace(MENTION_RE, (token, quoted: string | undefined, bare: string | undefined) => {
+ const ref = resolveRefByName(quoted ?? bare ?? "", candidates);
+ if (!ref) return token;
+ if (!refs.some((r) => sameRef(r, ref))) refs.push(ref);
+ return ref.name;
+ });
+ return { refs, text: out };
+}
+
+/** Resolve a prompt's `@name` mentions and merge them into the already-attached
+ * `chips`, de-duplicated. `dropAudio` excludes audio refs — image/video
+ * generation take only pictures; chat keeps them. The single place the three
+ * send paths (chat, generate image, generate video) share this composition. */
+export function collectRefs(
+ text: string,
+ chips: AssetRef[],
+ candidates: AssetRef[],
+ opts?: { dropAudio?: boolean }
+): { refs: AssetRef[]; text: string } {
+ const parsed = parseMentions(text, candidates);
+ const mentioned = opts?.dropAudio
+ ? parsed.refs.filter((r) => r.kind !== "audio")
+ : parsed.refs;
+ // Re-resolve each ref's short handle from the live candidates — chips from
+ // drags predate handle assignment, and the model reads handles to talk
+ // about attachments ("v2").
+ const refs = mentioned.reduce(addRefOnce, chips).map((r) => {
+ const live = candidates.find((c) => sameRef(c, r));
+ return live?.handle ? { ...r, handle: live.handle } : r;
+ });
+ return { refs, text: parsed.text };
+}
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index e7228c91..778134c4 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -3,7 +3,9 @@
import { useEffect } from "react";
import { create } from "zustand";
import { apiFetch } from "./api";
+import type { AssetRef } from "./assetRef";
import { enrichAsset, importFileToProject } from "./media";
+import { refsToInlineImages } from "./refMedia";
import { useEditor } from "./store";
import { mediaUrl, type MediaAsset } from "./types";
@@ -37,14 +39,23 @@ interface GenerateState {
probeNow: () => Promise<boolean>;
/** Kick off a generation. Returns when it settles, resolving to the final
* job (status "done" with assetId, or "error" with a message) so the AI
- * assistant can act on the result; the panel just fires and forgets. */
- generateImage: (projectId: string, prompt: string) => Promise<GenerateJob>;
+ * assistant can act on the result; the panel just fires and forgets.
+ * `refs` are visual references — each uploads as an input image (a stock
+ * image as-is, a video by a captured poster frame). */
+ generateImage: (
+ projectId: string,
+ prompt: string,
+ opts?: { refs?: AssetRef[] }
+ ) => Promise<GenerateJob>;
generateVideo: (
projectId: string,
prompt: string,
opts?: {
tier?: "fast" | "high";
durationSeconds?: number;
+ /** Visual references; Veo takes one input image, so the first ref's
+ * picture seeds the render. */
+ refs?: AssetRef[];
/** Called once with the landed asset when the render completes and the
* project is still open — lets the AI place the clip after a background
* render it couldn't wait out (the assistant tool bridge caps at 2min). */
@@ -116,11 +127,12 @@ interface GenerationResponse {
}
/** POST one of Donkey's hosted inference routes with the user's session. */
-const hostedPost = (path: string, body: unknown) =>
+export const hostedPost = (path: string, body: unknown, signal?: AbortSignal) =>
fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json", "x-donkey-client-id": CLIENT_ID },
body: JSON.stringify(body),
+ signal,
});
async function readError(res: Response, fallback: string): Promise<string> {
@@ -206,18 +218,20 @@ export const useGenerate = create<GenerateState>((set, get) => {
return probing;
},
- generateImage: (projectId, prompt) => {
+ generateImage: (projectId, prompt, opts) => {
const job: GenerateJob = { id: uid(), projectId, kind: "image", prompt, status: "running" };
set((s) => ({ jobs: [job, ...s.jobs] }));
return (async () => {
try {
const aspect = useEditor.getState().aspect;
+ const 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.`,
+ ...(images.length > 0 ? { inputs: { images } } : {}),
});
if (!res.ok) throw new Error(await readError(res, "Image generation failed."));
const gen = (await res.json()) as GenerationResponse;
@@ -256,9 +270,13 @@ export const useGenerate = create<GenerateState>((set, get) => {
set((s) => ({ jobs: [job, ...s.jobs] }));
return (async () => {
try {
+ // Veo seeds from a single first-frame image; extra refs would be dropped
+ // silently, so send just the first.
+ const images = await refsToInlineImages((opts?.refs ?? []).slice(0, 1));
const res = await hostedPost("/api/inference/assets", {
kind: "video",
prompt,
+ ...(images.length > 0 ? { inputs: { images } } : {}),
parameters: {
tier: opts?.tier === "high" ? "high" : "fast",
aspectRatio: useEditor.getState().aspect,
diff --git a/site/src/cut/lib/imageGen.ts b/site/src/cut/lib/imageGen.ts
new file mode 100644
index 00000000..0dc670d5
--- /dev/null
+++ b/site/src/cut/lib/imageGen.ts
@@ -0,0 +1,34 @@
+"use client";
+
+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).
+
+interface ImageGenState {
+ open: boolean;
+ prompt: string;
+ /** 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. */
+ openWith: (prompt: string) => void;
+ setPrompt: (prompt: string) => void;
+ addRef: (ref: AssetRef) => void;
+ removeRef: (ref: AssetRef) => void;
+ close: () => void;
+}
+
+export const useImageGen = create<ImageGenState>((set) => ({
+ open: false,
+ prompt: "",
+ refs: [],
+ openWith: (prompt) => set({ open: true, prompt, refs: [] }),
+ setPrompt: (prompt) => set({ prompt }),
+ 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/refMedia.ts b/site/src/cut/lib/refMedia.ts
new file mode 100644
index 00000000..6f8ef46a
--- /dev/null
+++ b/site/src/cut/lib/refMedia.ts
@@ -0,0 +1,106 @@
+"use client";
+
+import type { AssetRef } from "./assetRef";
+
+// Turn an asset ref into the inline-image shape the hosted generation routes
+// take (`inputs.images = [{ data, mimeType }]`). Stock images upload as-is;
+// video refs (project clips, library media, generated stills) upload a single
+// captured frame — the browser reads the same media URLs the previews use.
+
+export interface InlineImage {
+ /** Base64 payload, no data: prefix. */
+ data: string;
+ mimeType: string;
+}
+
+const MAX_W = 1280;
+const JPEG_Q = 0.85;
+
+function splitDataUrl(dataUrl: string): InlineImage {
+ const comma = dataUrl.indexOf(",");
+ // Between "data:" and the first ";" (or "," when there are no params). A
+ // typeless data URL ("data:;base64,…", e.g. a fetched blob with no
+ // Content-Type) leaves this empty — fall back so the hosted route, which
+ // rejects an empty mimeType, still gets a usable image part.
+ const header = dataUrl.slice(5, comma);
+ const mimeType = header.split(";")[0] || "image/png";
+ return { data: dataUrl.slice(comma + 1), mimeType };
+}
+
+function blobToInline(blob: Blob): Promise<InlineImage> {
+ return new Promise((resolve, reject) => {
+ const r = new FileReader();
+ r.onload = () => resolve(splitDataUrl(String(r.result)));
+ r.onerror = () => reject(new Error("Could not read the image."));
+ r.readAsDataURL(blob);
+ });
+}
+
+function captureFrame(url: string, duration?: number): Promise<InlineImage> {
+ return new Promise((resolve, reject) => {
+ const v = document.createElement("video");
+ v.preload = "auto";
+ v.muted = true;
+ // Media may come from the engine on another origin; anonymous CORS keeps
+ // the canvas grab from tainting.
+ v.crossOrigin = "anonymous";
+ let timer = 0;
+ const fail = (msg: string) => {
+ clearTimeout(timer);
+ v.removeAttribute("src");
+ v.load();
+ reject(new Error(msg));
+ };
+ // A seek whose `seeked` never fires (a too-short clip, a source that
+ // resolves currentTime synchronously) would hang refsToInlineImages and
+ // wedge the whole generation. Bail after a few seconds, like visualFrames.
+ timer = window.setTimeout(() => fail("Timed out reading a reference frame."), 4000);
+ v.onerror = () => fail("Could not read the video for a reference frame.");
+ v.onloadedmetadata = () => {
+ // Same poster spot the cards show, so the reference matches the preview.
+ v.currentTime = Math.min(1, Math.max(0.1, (duration || v.duration || 2) / 10));
+ };
+ v.onseeked = () => {
+ if (v.readyState < 2 || !v.videoWidth) return fail("The video has no readable frame.");
+ const w = Math.min(MAX_W, v.videoWidth);
+ const h = Math.round((w / v.videoWidth) * v.videoHeight);
+ const canvas = document.createElement("canvas");
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return fail("Could not draw the reference frame.");
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(v, 0, 0, w, h);
+ try {
+ const out = splitDataUrl(canvas.toDataURL("image/jpeg", JPEG_Q));
+ clearTimeout(timer);
+ v.removeAttribute("src");
+ v.load();
+ resolve(out);
+ } catch {
+ fail("Could not capture a reference frame.");
+ }
+ };
+ v.src = url;
+ });
+}
+
+/** A single reference image for `ref`: the file itself for images, a captured
+ * poster frame for videos. Audio has no picture and rejects. */
+export async function refToInlineImage(ref: AssetRef): Promise<InlineImage> {
+ if (ref.kind === "audio") {
+ throw new Error(`“${ref.name}” is audio — it can't be a visual reference.`);
+ }
+ if (ref.kind === "image") {
+ const res = await fetch(ref.url);
+ if (!res.ok) throw new Error(`Could not load “${ref.name}”.`);
+ return blobToInline(await res.blob());
+ }
+ return captureFrame(ref.url, ref.duration);
+}
+
+/** Reference images for a whole ref list, in order; skips nothing — a broken
+ * ref fails the call so the user knows the reference didn't ride along. */
+export function refsToInlineImages(refs: AssetRef[]): Promise<InlineImage[]> {
+ return Promise.all(refs.map(refToInlineImage));
+}
diff --git a/site/src/cut/lib/refReveal.ts b/site/src/cut/lib/refReveal.ts
new file mode 100644
index 00000000..c3ab0251
--- /dev/null
+++ b/site/src/cut/lib/refReveal.ts
@@ -0,0 +1,76 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { create } from "zustand";
+import type { AssetRef, AssetRefScope } from "./assetRef";
+
+// Clicking a reference token (chat message, attachment chip) jumps back to the
+// original asset: the side panel switches to the owning tab (Media, Library,
+// or Image), the card scrolls into view, and it flashes. The store carries the
+// one-shot target; panels react to `seq` for the tab/folder switch and cards
+// use `useRevealFlash` for the scroll + flash.
+
+interface RefRevealState {
+ target: AssetRef | null;
+ /** Bumps per reveal so re-revealing the same asset still fires effects. */
+ seq: number;
+ /** Timestamp of the reveal; effects ignore stale targets on remount. */
+ at: number;
+ reveal: (ref: AssetRef) => void;
+}
+
+export const useRefReveal = create<RefRevealState>((set) => ({
+ target: null,
+ seq: 0,
+ at: 0,
+ reveal: (ref) => set((s) => ({ target: ref, seq: s.seq + 1, at: Date.now() })),
+}));
+
+export const revealRef = (ref: AssetRef) => useRefReveal.getState().reveal(ref);
+
+/** How long a reveal stays actionable — long enough to survive the tab switch
+ * and mount, short enough that a remount later doesn't replay it. */
+const FRESH_MS = 3000;
+
+/** Card-side reveal handling: attach the returned ref callback to the card's
+ * element; when this asset becomes the reveal target the card scrolls into
+ * view and `flash` turns on briefly for a highlight style. */
+export function useRevealFlash(
+ scope: AssetRefScope,
+ id: string
+): { flash: boolean; attachReveal: (el: HTMLElement | null) => void } {
+ const [el, setEl] = useState<HTMLElement | null>(null);
+ const [flash, setFlash] = useState(false);
+ const seq = useRefReveal((s) =>
+ s.target && s.target.scope === scope && s.target.id === id ? s.seq : 0
+ );
+
+ useEffect(() => {
+ if (!seq || !el) return;
+ if (Date.now() - useRefReveal.getState().at > FRESH_MS) return;
+ el.scrollIntoView({ block: "center", behavior: "smooth" });
+ // Flash on a deferred tick — a sync setState in an effect cascades renders.
+ const on = setTimeout(() => setFlash(true), 0);
+ const off = setTimeout(() => setFlash(false), 1600);
+ return () => {
+ clearTimeout(on);
+ clearTimeout(off);
+ };
+ }, [seq, el]);
+
+ return { flash, attachReveal: setEl };
+}
+
+/** Panel-side reveal handling: runs `onReveal` once per fresh reveal so the
+ * panel can switch tabs, open the owning folder, or change category views. */
+export function useRevealEffect(onReveal: (ref: AssetRef) => void) {
+ const seq = useRefReveal((s) => s.seq);
+ useEffect(() => {
+ if (!seq) return;
+ const { target, at } = useRefReveal.getState();
+ if (!target || Date.now() - at > FRESH_MS) return;
+ onReveal(target);
+ // Re-run on each reveal only; the callback is read fresh per firing.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [seq]);
+}
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 49399272..956074db 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -24,8 +24,9 @@ export interface StoredAsset {
duration: number; // seconds
width?: number;
height?: number;
- /** Set on assets Cut generated itself (AI voiceovers); absent on imports. */
- origin?: "voiceover";
+ /** Set on assets Cut generated itself (AI voiceovers, generated images);
+ * absent on imports. */
+ origin?: "voiceover" | "generated";
}
/** Runtime asset: stored fields plus derived/browser-only data. */
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index 744b5575..12341324 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -287,7 +287,13 @@ export const projectsApi = {
await writeFile(src, Buffer.from(await file.arrayBuffer()));
// 8s of still footage — room to trim like any other clip.
const made = await makeStillClip(id, src, 8, `ai-${slug}`);
- return Response.json({ id: crypto.randomUUID().slice(0, 8), type: "video", name, ...made });
+ return Response.json({
+ id: crypto.randomUUID().slice(0, 8),
+ type: "video",
+ name,
+ origin: "generated",
+ ...made,
+ });
} finally {
void rm(tmp, { recursive: true, force: true });
}