Open source CapCut alternative.
TypeScript
feat(site): chat-owned asset cards in the Cut assistant chat [rebuild]
David Leaada09aa6524
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 68e92eb9..7df1ca00 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useRef, useState } from "react";+import { Fragment, useEffect, useMemo, useRef, useState } from "react";import { useChat } from "@ai-sdk/react";import { DefaultChatTransport, type ChatTransport, type UIMessage } from "ai";import {@@ -13,6 +13,7 @@ import {ExternalLink,FolderPlus,History,+ Maximize2,Plus,Sparkles,Square,@@ -37,6 +38,7 @@ import { apiFetch, engineReady } from "@/cut/lib/api";import { buildAiContext } from "@/cut/lib/aiContext";import { runAiTool } from "@/cut/lib/aiTools";import { setAssetDragData } from "@/cut/lib/assetDrag";+import { deleteChatAssets, setActiveChatThread } from "@/cut/lib/chatAssets";import {addRefOnce,collectRefs,@@ -52,12 +54,14 @@ import { signInUrl, useSignedIn } from "@/cut/lib/generate";import { streamGeminiChat } from "@/cut/lib/geminiChat";import { AI_MODELS } from "@/cut/lib/aiModels";import { saveAssetToLibrary } from "@/cut/lib/library";+import { lightboxItemFromRef, useLightbox } from "@/cut/lib/lightbox";import { refsFromDroppedFiles } from "@/cut/lib/refMedia";import { revealRef } from "@/cut/lib/refReveal";import { useEditor } from "@/cut/lib/store";import { cn } from "@/lib/utils";import { cardIconButton } from "@/cut/components/iconButton";import { MentionTextarea, RefChips, RefThumb, RefTokenChip } from "./AssetRefs";+import { ToolOutputAssets } from "./ChatAssets";// Chat attachments are asset refs — anything in the project, the library, or// the stock catalog. They arrive by drag (media cards, library clips, stock@@ -90,6 +94,8 @@ function readThreads(): ChatThread[] {}function writeThreads(list: ChatThread[]) {+ // A thread falling off the end of history takes its chat-only assets with it.+ for (const t of list.slice(THREAD_LIMIT)) deleteChatAssets(t.id);try {localStorage.setItem(threadsKey(), JSON.stringify(list.slice(0, THREAD_LIMIT)));} catch {@@ -165,6 +171,9 @@ export function AiPanel({ onClose }: { onClose: () => void }) {const deleteThread = (id: string) => {writeThreads(readThreads().filter((t) => t.id !== id));setThreads((p) => p.filter((t) => t.id !== id));+ // The thread's chat-only assets go with it; anything placed or filed+ // into Media/Library stays.+ deleteChatAssets(id);// If the open chat was deleted, start a fresh one so it can't re-save// itself on the next message and resurrect the thread.if (activeChat === id) setActiveChat(crypto.randomUUID());@@ -401,6 +410,13 @@ function ChatSession({const busy = status === "submitted" || status === "streaming";+ // While this thread is open its tools tag created assets with it, so+ // deleting the thread later can clean them up.+ useEffect(() => {+ setActiveChatThread(threadId);+ return () => setActiveChatThread(null);+ }, [threadId]);+// Coalesce every edit the assistant makes in one turn into a single undo// step, so ⌘Z reverts the whole turn rather than one tool call at a time.useEffect(() => {@@ -573,7 +589,8 @@ function ChatSession({}/** Asset card inside a sent message — click to jump back to the original- * asset, drag onto the timeline, "…" menu for more actions. */+ * asset, double-click to expand, drag onto the timeline, "…" menu for more+ * actions. */function MessageAssetCard({ asset }: { asset: AssetRef }) {return (<div className="ai-msg-asset group relative w-16">@@ -589,6 +606,7 @@ function MessageAssetCard({ asset }: { asset: AssetRef }) {setRefDragData(e, asset);}}onClick={() => revealRef(asset)}+ onDoubleClick={() => useLightbox.getState().open(lightboxItemFromRef(asset))}><RefThumb item={asset} className="size-16 transition-colors group-hover:border-input" /><span className="w-full truncate text-[10px] text-muted-foreground">{asset.name}</span>@@ -605,6 +623,11 @@ function MessageAssetCard({ asset }: { asset: AssetRef }) {<Ellipsis className="size-3" /></DropdownMenuTrigger><DropdownMenuContent align="start" className="w-40">+ <DropdownMenuItem+ onClick={() => useLightbox.getState().open(lightboxItemFromRef(asset))}+ >+ <Maximize2 /> Expand+ </DropdownMenuItem><DropdownMenuItem onClick={() => window.open(asset.url, "_blank", "noopener")}><ExternalLink /> Open file</DropdownMenuItem>@@ -734,23 +757,28 @@ function MessageView({ message }: { message: UIMessage }) {const failed = p.state === "output-error";const done = p.state === "output-available";return (- <details key={i} className="ai-tool group max-w-full">- <summary- className={cn(- "flex cursor-pointer list-none items-center gap-1.5 rounded-md border border-border px-2 py-1 text-[11px] text-muted-foreground transition-colors select-none hover:bg-muted/60 [&::-webkit-details-marker]:hidden",- failed && "border-red-200 text-red-700"- )}- >- <Wrench className="size-3 shrink-0" />- <span className="font-mono">{name}</span>- {done && <Check className="size-3 text-emerald-600" />}- {failed && <TriangleAlert className="size-3" />}- {!done && !failed && <CircleDashed className="size-3 animate-spin" />}- </summary>- <pre className="mt-1 max-h-40 overflow-auto rounded-md bg-muted/70 p-2 font-mono text-[10px] leading-relaxed whitespace-pre-wrap">- {JSON.stringify({ input: p.input, output: p.output, error: p.errorText }, null, 2)}- </pre>- </details>+ <Fragment key={i}>+ <details className="ai-tool group max-w-full">+ <summary+ className={cn(+ "flex cursor-pointer list-none items-center gap-1.5 rounded-md border border-border px-2 py-1 text-[11px] text-muted-foreground transition-colors select-none hover:bg-muted/60 [&::-webkit-details-marker]:hidden",+ failed && "border-red-200 text-red-700"+ )}+ >+ <Wrench className="size-3 shrink-0" />+ <span className="font-mono">{name}</span>+ {done && <Check className="size-3 text-emerald-600" />}+ {failed && <TriangleAlert className="size-3" />}+ {!done && !failed && <CircleDashed className="size-3 animate-spin" />}+ </summary>+ <pre className="mt-1 max-h-40 overflow-auto rounded-md bg-muted/70 p-2 font-mono text-[10px] leading-relaxed whitespace-pre-wrap">+ {JSON.stringify({ input: p.input, output: p.output, error: p.errorText }, null, 2)}+ </pre>+ </details>+ {/* Media the tool made previews right under its chip — it stays+ in the chat until the user drags it out or files it away. */}+ {done && <ToolOutputAssets output={p.output} />}+ </Fragment>);}return null;diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsxindex 2a3576c5..83e23908 100644--- a/site/src/cut/components/AudioPanel.tsx+++ b/site/src/cut/components/AudioPanel.tsx@@ -281,8 +281,9 @@ function VoiceGenerator({ projectId }: { projectId: string }) {);}-/** Tiny waveform for a row, from the asset's normalized peaks. */-function PeakStrip({ peaks }: { peaks: number[] }) {+/** Tiny waveform for a row, from the asset's normalized peaks. Also drawn+ * bigger by the lightbox and the chat's audio cards (`className` restyles). */+export function PeakStrip({ peaks, className }: { peaks: number[]; className?: string }) {const BARS = 48;const step = Math.max(1, Math.floor(peaks.length / BARS));const bars: number[] = [];@@ -297,7 +298,7 @@ function PeakStrip({ peaks }: { peaks: number[] }) {<svgviewBox={`0 0 ${BARS * 2} 16`}preserveAspectRatio="none"- className="mt-1 h-4 w-full text-muted-foreground/50"+ className={cn("mt-1 h-4 w-full text-muted-foreground/50", className)}aria-hidden>{bars.map((p, i) => {@@ -352,7 +353,10 @@ function buildAudioDragGhost(name: string, width: number, peaks?: number[]): HTMreturn el;}-function AudioRow({+/** One audio asset as a playable row — the shared audio preview (panels and+ * the chat's audio cards): play button, name, duration, waveform, and a+ * hover-revealed menu + add button. */+export function AudioRow({name,duration,url,diff --git a/site/src/cut/components/ChatAssets.tsx b/site/src/cut/components/ChatAssets.tsxnew file mode 100644index 00000000..1628069c--- /dev/null+++ b/site/src/cut/components/ChatAssets.tsx@@ -0,0 +1,323 @@+"use client";++import { useEffect, useRef, useState, type ReactNode } from "react";+import type React from "react";+import { Copy, ExternalLink, FileText, Film, Loader2, Maximize2, Plus } from "lucide-react";+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";+import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";+import {+ refFromAsset,+ refToken,+ setRefDragData,+ useRefFor,+ type AssetRef,+ type AssetRefKind,+} from "@/cut/lib/assetRef";+import { useGenerate } from "@/cut/lib/generate";+import { lightboxItemFromRef, useLightbox } from "@/cut/lib/lightbox";+import { useEditor } from "@/cut/lib/store";+import { formatTime } from "@/cut/lib/time";+import type { MediaAsset } from "@/cut/lib/types";+import { cn } from "@/lib/utils";+import { AudioRow } from "./AudioPanel";+import { DocText, useDocText } from "./DocText";+import { GeneratedAssetMenu } from "./GeneratedAssetMenu";++// Assets rendered inside chat messages. Anything the assistant makes previews+// here as a media-first card and stays in the chat until the user moves it:+// drag it onto the timeline (standard payloads), or use the card's "…" menu to+// add it to the timeline, Media, or the Library. Double-click — or the expand+// button — opens the lightbox. Cards register per asset kind, so new+// renderable kinds (motion graphics, stickers) plug in beside video, image,+// audio, and text.++/** What a per-kind chat card receives: the ref as recorded in the message and,+ * when it names a live project asset, that asset (fresher name/peaks/size). */+interface ChatCardProps {+ item: AssetRef;+ asset?: MediaAsset;+}++const CHAT_CARDS: Record<AssetRefKind, (props: ChatCardProps) => ReactNode> = {+ video: MediaCard,+ image: MediaCard,+ audio: AudioCard,+ text: DocCard,+};++export function ChatAssetCard({ item }: { item: AssetRef }) {+ const asset = useEditor((s) =>+ item.scope === "project" ? s.assets.find((a) => a.id === item.id) : undefined+ );+ // A project ref whose asset is gone has nothing left to preview.+ if (item.scope === "project" && !asset) return null;+ const Card = CHAT_CARDS[item.kind];+ return <Card item={item} asset={asset} />;+}++/** Chat card for a project asset id — how tool outputs name what they made. */+export function ChatProjectAsset({ assetId }: { assetId: string }) {+ const asset = useEditor((s) => s.assets.find((a) => a.id === assetId));+ if (!asset) return null;+ return <ChatAssetCard item={refFromAsset(asset)} />;+}++/** The assets a finished tool call produced, from its typed output fields:+ * `assetId` for landed media, `jobId` for a video render still in flight. */+export function ToolOutputAssets({ output }: { output: unknown }) {+ if (!output || typeof output !== "object") return null;+ const o = output as { assetId?: unknown; jobId?: unknown };+ if (typeof o.assetId === "string") return <ChatProjectAsset assetId={o.assetId} />;+ if (typeof o.jobId === "string") return <ChatVideoJobCard jobId={o.jobId} />;+ return null;+}++/** A video render the tool started but couldn't wait out: a live card that+ * follows the generation job and becomes the clip's card when it lands. After+ * a reload the job store is empty and the render's home is the Video panel. */+export function ChatVideoJobCard({ jobId }: { jobId: string }) {+ const job = useGenerate((s) => s.jobs.find((j) => j.id === jobId));+ if (!job) return null;+ if (job.status === "done") return job.assetId ? <ChatProjectAsset assetId={job.assetId} /> : null;+ return (+ <div className="ai-chat-job flex w-full max-w-[280px] items-center gap-2.5 rounded-xl border border-border p-2">+ <span className="grid size-9 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground">+ {job.status === "running" ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <Film className="size-4" />+ )}+ </span>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[11px] 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" ? "Rendering…" : (job.error ?? "Failed.")}+ </div>+ </div>+ </div>+ );+}++/** The live ref for a card — the project asset when it exists (fresh name and+ * metadata), the recorded ref otherwise. */+const liveRef = (item: AssetRef, asset?: MediaAsset): AssetRef =>+ asset ? refFromAsset(asset) : item;++const expandRef = (item: AssetRef, asset?: MediaAsset) =>+ useLightbox.getState().open(lightboxItemFromRef(liveRef(item, asset)));++const dragProps = (item: AssetRef, asset?: MediaAsset) => ({+ draggable: true,+ onDragStart: (e: React.DragEvent) => {+ // Project assets carry the timeline-placement payload; the ref rides along+ // either way so composers and creators accept the drag too.+ if (asset) setAssetDragData(e, asset.id);+ else setRefDragData(e, item);+ },+ onDragEnd: clearAssetDrag,+});++/** The chat card's "…" menu: timeline/expand/reference actions around the+ * shared move-to-Media/Library pair. Project assets only. */+function ChatCardMenu({ asset, triggerClassName }: { asset: MediaAsset; triggerClassName: string }) {+ const ref = useRefFor(asset.name);+ const projectId = useEditor((s) => s.projectId);+ if (!projectId) return null;+ return (+ <GeneratedAssetMenu+ asset={asset}+ projectId={projectId}+ triggerClassName={triggerClassName}+ before={+ <>+ <DropdownMenuItem+ onClick={() => {+ const s = useEditor.getState();+ if (asset.type === "audio") s.addAudioFromAsset(asset.id);+ else s.addClipFromAsset(asset.id);+ }}+ >+ <Plus /> Add to timeline+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => expandRef(refFromAsset(asset))}>+ <Maximize2 /> Expand+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() =>+ void navigator.clipboard.writeText(refToken(ref ?? refFromAsset(asset))).catch(() => {})+ }+ >+ <Copy /> Copy reference+ </DropdownMenuItem>+ </>+ }+ after={+ <DropdownMenuItem onClick={() => window.open(asset.url, "_blank", "noopener")}>+ <ExternalLink /> Open file+ </DropdownMenuItem>+ }+ />+ );+}++const scrimButton =+ "grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65";++/** Image / video tile: the preview fills the card at the media's own aspect,+ * sized so portrait and landscape both sit comfortably in the chat column. */+function MediaCard({ item, asset }: ChatCardProps) {+ const videoRef = useRef<HTMLVideoElement>(null);+ const ref = liveRef(item, asset);+ const ratio =+ asset?.width && asset?.height ? asset.width / asset.height : item.kind === "image" ? 1 : 16 / 10;+ const width = Math.round(Math.min(248, Math.max(132, 210 * ratio)));+ return (+ <div+ className="ai-chat-asset group relative shrink-0 cursor-grab overflow-hidden rounded-xl border border-border bg-muted transition-colors hover:border-input"+ style={{ width, aspectRatio: ratio }}+ title={`${ref.name} — double-click to expand · drag to the timeline`}+ {...dragProps(item, asset)}+ onDoubleClick={() => expandRef(item, asset)}+ onMouseEnter={() => {+ void videoRef.current?.play().catch(() => {});+ }}+ onMouseLeave={() => {+ const v = videoRef.current;+ if (v) {+ v.pause();+ v.currentTime = 0.1;+ }+ }}+ >+ {item.kind === "video" ? (+ // Native first frame as the poster — full-resolution, no blurry thumb.+ <video+ ref={videoRef}+ src={`${ref.url}#t=0.1`}+ preload="metadata"+ muted+ loop+ playsInline+ className="size-full object-cover"+ />+ ) : (+ // eslint-disable-next-line @next/next/no-img-element -- engine/static file, not Next-optimizable+ <img src={ref.url} alt={ref.name} loading="lazy" className="size-full object-cover" />+ )}+ {item.kind === "video" && ref.duration !== undefined && (+ <span className="absolute right-1.5 bottom-1.5 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9px] text-white tabular-nums">+ {formatTime(ref.duration)}+ </span>+ )}+ <div className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent px-2 pt-4 pb-1.5 opacity-0 transition-opacity group-hover:opacity-100">+ <span className="block truncate text-[10.5px] font-medium text-white">{ref.name}</span>+ </div>+ <div className="absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100 has-data-popup-open:opacity-100">+ <button title="Expand" className={scrimButton} onClick={() => expandRef(item, asset)}>+ <Maximize2 className="size-3" />+ </button>+ {asset && <ChatCardMenu asset={asset} triggerClassName={scrimButton} />}+ </div>+ </div>+ );+}++/** Audio as the shared playable row (waveform, play, drag), with the chat menu+ * on it; double-click opens the big player. */+function AudioCard({ item, asset }: ChatCardProps) {+ const ref = liveRef(item, asset);+ const audioRef = useRef<HTMLAudioElement | null>(null);+ const [playing, setPlaying] = useState(false);+ useEffect(() => {+ const el = audioRef.current;+ return () => el?.pause();+ }, []);+ const toggle = () => {+ let el = audioRef.current;+ if (!el) {+ el = new Audio(ref.url);+ el.onended = () => setPlaying(false);+ audioRef.current = el;+ }+ if (playing) {+ el.pause();+ setPlaying(false);+ } else {+ void el.play().catch(() => setPlaying(false));+ setPlaying(true);+ }+ };+ return (+ <div+ className="ai-chat-asset w-full max-w-[280px] bg-card"+ onDoubleClick={() => expandRef(item, asset)}+ >+ <AudioRow+ name={ref.name}+ duration={ref.duration ?? 0}+ url={ref.url}+ peaks={asset?.peaks}+ playing={playing}+ onTogglePlay={toggle}+ onAdd={() => asset && useEditor.getState().addAudioFromAsset(asset.id)}+ menu={+ asset && (+ <ChatCardMenu+ asset={asset}+ triggerClassName="grid size-6 shrink-0 place-items-center rounded-full bg-muted text-foreground transition-all hover:bg-muted-foreground/20"+ />+ )+ }+ onDragStart={(e) => {+ if (asset) setAssetDragData(e, asset.id);+ else setRefDragData(e, item);+ }}+ />+ </div>+ );+}++/** How much of a text file the card shows before the fade; the lightbox+ * renders the whole thing. */+const DOC_PREVIEW_CHARS = 1200;++/** A text file (markdown, CSV, plain) as a clipped document card. */+function DocCard({ item, asset }: ChatCardProps) {+ const { text, failed } = useDocText(item.url);+ const clipped = text !== null && text.length > DOC_PREVIEW_CHARS;+ return (+ <div+ className="ai-chat-asset group relative w-full max-w-[280px] cursor-default overflow-hidden rounded-xl border border-border bg-background transition-colors hover:border-input"+ title={`${item.name} — double-click to expand`}+ {...dragProps(item, asset)}+ onDoubleClick={() => expandRef(item, asset)}+ >+ <div className="flex items-center gap-1.5 border-b border-border px-2.5 py-1.5">+ <FileText className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate text-[11px] font-medium">{item.name}</span>+ <button+ title="Expand"+ className={cn(scrimButton, "opacity-0 transition-opacity group-hover:opacity-100")}+ onClick={() => expandRef(item, asset)}+ >+ <Maximize2 className="size-3" />+ </button>+ </div>+ <div className="relative max-h-44 overflow-hidden px-2.5 py-2 text-[11px] leading-relaxed">+ {failed ? (+ <p className="text-muted-foreground">Could not read the file.</p>+ ) : text === null ? (+ <Loader2 className="size-3.5 animate-spin text-muted-foreground" />+ ) : (+ <DocText name={item.name} text={clipped ? text.slice(0, DOC_PREVIEW_CHARS) : text} />+ )}+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-background to-transparent" />+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/DocText.tsx b/site/src/cut/components/DocText.tsxnew file mode 100644index 00000000..d3eaa08c--- /dev/null+++ b/site/src/cut/components/DocText.tsx@@ -0,0 +1,168 @@+"use client";++import { useEffect, useState } from "react";+import Markdown from "react-markdown";+import { cn } from "@/lib/utils";++// Rendering for text assets (a dropped script, notes, a CSV, an assistant+// deliverable): fetch the file behind the ref URL and render it by extension —+// markdown formatted, CSV as a table, everything else as plain text. Shared by+// the chat's document card and the lightbox's full view.++export type DocFormat = "markdown" | "csv" | "plain";++export function docFormat(name: string): DocFormat {+ const ext = name.toLowerCase().split(".").pop() ?? "";+ if (ext === "md" || ext === "markdown") return "markdown";+ if (ext === "csv" || ext === "tsv") return "csv";+ return "plain";+}++/** The file's text, fetched once per URL. `failed` marks an unreadable file so+ * callers can show a plain error instead of an empty card. */+export function useDocText(url: string): { text: string | null; failed: boolean } {+ // The loaded state remembers which URL it answers for, so a URL change+ // reads as loading again without a reset write in the effect.+ const [state, setState] = useState<{ url: string; text: string | null; failed: boolean } | null>(+ null+ );+ useEffect(() => {+ let alive = true;+ fetch(url)+ .then((r) => (r.ok ? r.text() : Promise.reject(new Error(String(r.status)))))+ .then((t) => alive && setState({ url, text: t, failed: false }))+ .catch(() => alive && setState({ url, text: null, failed: true }));+ return () => {+ alive = false;+ };+ }, [url]);+ return state?.url === url ? state : { text: null, failed: false };+}++/** Minimal quote-aware CSV/TSV rows. */+function parseRows(text: string, delim: string): string[][] {+ const rows: string[][] = [];+ let row: string[] = [];+ let cell = "";+ let quoted = false;+ const push = () => {+ row.push(cell);+ cell = "";+ };+ const endRow = () => {+ push();+ // A lone trailing newline yields one empty cell; skip that row.+ if (row.length > 1 || row[0] !== "") rows.push(row);+ row = [];+ };+ for (let i = 0; i < text.length; i++) {+ const c = text[i];+ if (quoted) {+ if (c === '"' && text[i + 1] === '"') {+ cell += '"';+ i++;+ } else if (c === '"') {+ quoted = false;+ } else {+ cell += c;+ }+ } else if (c === '"' && cell === "") {+ quoted = true;+ } else if (c === delim) {+ push();+ } else if (c === "\n") {+ endRow();+ } else if (c !== "\r") {+ cell += c;+ }+ }+ if (cell !== "" || row.length > 0) endRow();+ return rows;+}++const CSV_ROW_CAP = 200;++function CsvTable({ text, delim }: { text: string; delim: string }) {+ const rows = parseRows(text, delim);+ if (rows.length === 0) return <p className="text-muted-foreground">Empty file.</p>;+ const [head, ...body] = rows;+ const shown = body.slice(0, CSV_ROW_CAP);+ return (+ <div className="overflow-x-auto">+ <table className="w-full border-collapse text-left">+ <thead>+ <tr>+ {head.map((h, i) => (+ <th key={i} className="border-b border-border px-2 py-1 font-semibold whitespace-nowrap">+ {h}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {shown.map((r, i) => (+ <tr key={i} className="odd:bg-muted/40">+ {r.map((c, j) => (+ <td key={j} className="px-2 py-1 align-top">+ {c}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ {body.length > shown.length && (+ <p className="mt-1.5 text-muted-foreground">+{body.length - shown.length} more rows</p>+ )}+ </div>+ );+}++/** A text file's content, formatted for its extension. Typography scales with+ * the caller's font-size classes on `className`. */+export function DocText({+ name,+ text,+ className,+}: {+ name: string;+ text: string;+ className?: string;+}) {+ const format = docFormat(name);+ if (format === "csv") {+ return (+ <div className={className}>+ <CsvTable text={text} delim={name.toLowerCase().endsWith(".tsv") ? "\t" : ","} />+ </div>+ );+ }+ if (format === "markdown") {+ return (+ <div className={cn("doc-md", className)}>+ <Markdown+ components={{+ h1: (p) => <h1 className="mt-3 mb-1.5 text-[1.25em] font-semibold first:mt-0" {...p} />,+ h2: (p) => <h2 className="mt-3 mb-1.5 text-[1.1em] font-semibold first:mt-0" {...p} />,+ h3: (p) => <h3 className="mt-2 mb-1 font-semibold first:mt-0" {...p} />,+ p: (p) => <p className="mb-1.5 last:mb-0" {...p} />,+ ul: (p) => <ul className="mb-1.5 list-disc pl-4 last:mb-0" {...p} />,+ ol: (p) => <ol className="mb-1.5 list-decimal pl-4 last:mb-0" {...p} />,+ li: (p) => <li className="mb-0.5" {...p} />,+ code: (p) => <code className="rounded bg-muted px-1 py-px font-mono text-[0.9em]" {...p} />,+ pre: (p) => (+ <pre className="mb-1.5 overflow-x-auto rounded-md bg-muted/70 p-2 font-mono text-[0.9em] last:mb-0" {...p} />+ ),+ a: (p) => <a className="text-[#0a84ff] underline" target="_blank" {...p} />,+ blockquote: (p) => (+ <blockquote className="mb-1.5 border-l-2 border-border pl-2 text-muted-foreground" {...p} />+ ),+ }}+ >+ {text}+ </Markdown>+ </div>+ );+ }+ return <pre className={cn("font-mono whitespace-pre-wrap", className)}>{text}</pre>;+}diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsxindex a4747737..d05c9378 100644--- a/site/src/cut/components/GeneratePanel.tsx+++ b/site/src/cut/components/GeneratePanel.tsx@@ -113,7 +113,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {// The character's poster seed is the point — the same person must// deliver the line — so free-form prompts alone get the ref rewrite.composeRefs: !character,- });+ }).settled;useVideoGen.getState().openWith("");};@@ -387,9 +387,8 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {<DropdownMenuItemonClick={() =>useLightbox.getState().open({+ kind: "video",src: asset.url,- isVideo: true,- playable: true,name: asset.name,prompt: job.prompt,assetId: asset.id,diff --git a/site/src/cut/components/GeneratedAssetMenu.tsx b/site/src/cut/components/GeneratedAssetMenu.tsxindex 0b2ee51d..b0721d06 100644--- a/site/src/cut/components/GeneratedAssetMenu.tsx+++ b/site/src/cut/components/GeneratedAssetMenu.tsx@@ -43,7 +43,11 @@ export function GeneratedAssetMenu({{before}{before != null && <DropdownMenuSeparator />}<DropdownMenuItem- onClick={() => useEditor.getState().updateAsset(asset.id, { origin: undefined })}+ onClick={() =>+ // Clearing the origin files it into Media; a chat-owned asset also+ // sheds its thread so deleting the chat won't touch it.+ useEditor.getState().updateAsset(asset.id, { origin: undefined, chatId: undefined })+ }><Clapperboard /> Add to Media</DropdownMenuItem>diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsxindex 724598a9..5d6372a7 100644--- a/site/src/cut/components/ImageGenPanel.tsx+++ b/site/src/cut/components/ImageGenPanel.tsx@@ -275,8 +275,8 @@ function GeneratedTile({<DropdownMenuItemonClick={() =>useLightbox.getState().open({+ kind: "image",src: asset.url,- isVideo: false,name: asset.name,prompt: asset.name,assetId: asset.id,diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsxindex 23ddb567..0e710946 100644--- a/site/src/cut/components/Lightbox.tsx+++ b/site/src/cut/components/Lightbox.tsx@@ -1,24 +1,27 @@"use client";import { useEffect, useState } from "react";-import { Check, Copy, Loader2, Plus, X } from "lucide-react";+import { Check, Copy, FileText, Loader2, Music, Plus, X } from "lucide-react";import { Button } from "@/components/ui/button";-import { useLightbox } from "@/cut/lib/lightbox";+import { useLightbox, type LightboxItem } from "@/cut/lib/lightbox";import { importImage, importStockVideo } from "@/cut/lib/media";import { useEditor } from "@/cut/lib/store";+import { DocText, useDocText } from "./DocText";+import { PeakStrip } from "./AudioPanel";-// The media lightbox: the big version of a stock or generated item floating-// straight on the backdrop — media on top, name and prompt below, plus a-// button to drop it onto the timeline. Mounted once in the editor. When the-// item's aspect is known the dialog is laid out at its final size before the-// media loads.+// The asset lightbox: the big version of a stock, generated, or chat asset+// floating straight on the backdrop — media on top, name and prompt below,+// plus a button to drop it onto the timeline. Mounted once in the editor.+// Video and images size the dialog from a known aspect before the media+// loads; audio gets a waveform player and text files render formatted+// (markdown, CSV table, plain text).const ASPECT_RATIO: Record<string, number> = { "16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1 };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+ // Keyed to the added item's src, so opening a different item clears the// "Added" confirmation without a reset effect.const [addedSrc, setAddedSrc] = useState<string | null>(null);const [copied, setCopied] = useState(false);@@ -43,12 +46,17 @@ export function Lightbox() {setAdding(true);try {if (item.assetId) {- useEditor.getState().addClipFromAsset(item.assetId);+ if (item.kind === "audio") {+ useEditor.getState().addAudioFromAsset(item.assetId);+ } else {+ useEditor.getState().addClipFromAsset(item.assetId);+ }} else {// A stock clip imports as footage; a stock image bakes into a still.- const asset = item.playable- ? await importStockVideo(projectId, { url: item.src, name: item.name })- : await importImage(projectId, { url: item.src, name: item.name });+ const asset =+ item.kind === "video"+ ? await importStockVideo(projectId, { url: item.src, name: item.name })+ : await importImage(projectId, { url: item.src, name: item.name });useEditor.getState().addClipFromAsset(asset.id);}setAddedSrc(item.src);@@ -59,14 +67,23 @@ export function Lightbox() {}};+ // Audio without a project asset (a library ref) has nowhere direct to land;+ // text never rides the timeline.+ const canAdd = item.kind !== "text" && (item.kind !== "audio" || item.assetId !== null);+// With a known aspect the dialog width follows it — capped so the media// stays within 68vh tall and 860px/92vw wide — and the media box carries the- // same ratio, so nothing shifts when the file loads.+ // same ratio, so nothing shifts when the file loads. Audio and text use+ // fixed reading widths instead.const ratio = item.aspect ? ASPECT_RATIO[item.aspect] : undefined;- const mediaClass = ratio- ? "block w-full rounded-2xl bg-black object-cover shadow-2xl"- : "block max-h-[68vh] w-full rounded-2xl bg-black object-contain shadow-2xl";- const mediaStyle = ratio ? { aspectRatio: ratio } : undefined;+ const width =+ item.kind === "audio"+ ? "min(92vw, 480px)"+ : item.kind === "text"+ ? "min(92vw, 720px)"+ : ratio+ ? `min(92vw, 860px, ${Math.round(68 * ratio * 100) / 100}vh)`+ : "min(92vw, 860px)";return (<div@@ -75,7 +92,7 @@ export function Lightbox() {><divclassName="relative flex max-h-[92vh] flex-col gap-3"- style={{ width: ratio ? `min(92vw, 860px, ${Math.round(68 * ratio * 100) / 100}vh)` : "min(92vw, 860px)" }}+ style={{ width }}onClick={(e) => e.stopPropagation()}><button@@ -86,47 +103,25 @@ export function Lightbox() {<X className="size-4" /></button>- {item.isVideo ? (- item.playable ? (- <video- controls- autoPlay- loop- playsInline- src={item.src}- className={mediaClass}- style={mediaStyle}- />- ) : (- <video- muted- playsInline- preload="metadata"- src={`${item.src}#t=0.1`}- className={mediaClass}- style={mediaStyle}- />- )- ) : (- // eslint-disable-next-line @next/next/no-img-element -- static/project image, client-only page- <img src={item.src} alt={item.name} className={mediaClass} style={mediaStyle} />- )}+ <LightboxMedia item={item} ratio={ratio} /><div className="flex min-h-0 flex-col gap-3 overflow-y-auto"><div className="flex items-center justify-between gap-3"><div className="min-w-0 truncate text-[15px] font-semibold tracking-tight text-white">{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>+ {canAdd && (+ <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 && (@@ -159,3 +154,67 @@ export function Lightbox() {</div>);}++function LightboxMedia({ item, ratio }: { item: LightboxItem; ratio?: number }) {+ if (item.kind === "audio") return <AudioBody item={item} />;+ if (item.kind === "text") return <TextBody item={item} />;++ const mediaClass = ratio+ ? "block w-full rounded-2xl bg-black object-cover shadow-2xl"+ : "block max-h-[68vh] w-full rounded-2xl bg-black object-contain shadow-2xl";+ const mediaStyle = ratio ? { aspectRatio: ratio } : undefined;++ if (item.kind === "video") {+ return (+ <video+ controls+ autoPlay+ loop+ playsInline+ src={item.src}+ className={mediaClass}+ style={mediaStyle}+ />+ );+ }+ return (+ // eslint-disable-next-line @next/next/no-img-element -- static/project image, client-only page+ <img src={item.src} alt={item.name} className={mediaClass} style={mediaStyle} />+ );+}++function AudioBody({ item }: { item: LightboxItem }) {+ const asset = useEditor((s) =>+ item.assetId ? s.assets.find((a) => a.id === item.assetId) : undefined+ );+ return (+ <div className="flex flex-col gap-3 rounded-2xl bg-gradient-to-br from-emerald-500 to-emerald-700 p-5 pt-10 shadow-2xl">+ <Music className="size-8 text-white/90" />+ {asset?.peaks && asset.peaks.length > 0 && (+ <PeakStrip peaks={asset.peaks} className="h-10 text-white/85" />+ )}+ <audio controls autoPlay src={item.src} className="w-full" />+ </div>+ );+}++function TextBody({ item }: { item: LightboxItem }) {+ const { text, failed } = useDocText(item.src);+ return (+ <div className="flex max-h-[68vh] flex-col overflow-hidden rounded-2xl bg-card shadow-2xl">+ <div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5 pr-12">+ <FileText className="size-4 text-muted-foreground" />+ <span className="truncate text-[12.5px] font-medium">{item.name}</span>+ </div>+ <div className="min-h-0 overflow-y-auto px-4 py-3 text-[12.5px] leading-relaxed">+ {failed ? (+ <p className="text-muted-foreground">Could not read the file.</p>+ ) : text === null ? (+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ ) : (+ <DocText name={item.name} text={text} />+ )}+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/StockImagesPanel.tsx b/site/src/cut/components/StockImagesPanel.tsxindex e5adfd85..8741d41b 100644--- a/site/src/cut/components/StockImagesPanel.tsx+++ b/site/src/cut/components/StockImagesPanel.tsx@@ -184,8 +184,8 @@ function StockTile({ item }: { item: StockImage }) {className="grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"onClick={() =>useLightbox.getState().open({+ kind: "image",src: item.file,- isVideo: false,aspect: item.aspect,name: titleFromId(item.id),prompt: item.prompt,diff --git a/site/src/cut/components/StockVideosPanel.tsx b/site/src/cut/components/StockVideosPanel.tsxindex 5a647d13..b028496f 100644--- a/site/src/cut/components/StockVideosPanel.tsx+++ b/site/src/cut/components/StockVideosPanel.tsx@@ -264,9 +264,8 @@ function StockTile({ item }: { item: StockVideo }) {className="grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"onClick={() =>useLightbox.getState().open({+ kind: "video",src: item.file,- isVideo: true,- playable: true,aspect: item.aspect,name: stockTitle(item.id),prompt: item.prompt,diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 62997915..50302cb0 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -2,6 +2,7 @@import { apiFetch, apiJson } from "./api";import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";+import { chatOwner, tagChatAsset } from "./chatAssets";import { useGenerate } from "./generate";import { enrichAsset, ensurePeaks, importImage, importStockVideo } from "./media";import { characterPrompt, stockTitle } from "./stock";@@ -351,6 +352,7 @@ export async function runAiTool(if (sel?.kind === "clip") cur.moveClip(sel.id, index);void enrichAsset(asset);return {+ assetId: asset.id,clipId: sel?.kind === "clip" ? sel.id : null,index,duration: body.duration,@@ -382,6 +384,7 @@ export async function runAiTool(const cur = useEditor.getState();const asset = cur.assets.find((a) => a.id === job.assetId);if (!asset) throw new ToolError("The generated image did not land in the project.");+ tagChatAsset(asset.id);const placed = maybeAddGeneratedClip(asset.id, input);return {assetId: asset.id,@@ -413,8 +416,11 @@ export async function runAiTool(input.reference_asset_id === undefined? []: resolveRefAssets([input.reference_asset_id]);- const addToTimeline = input.add_to_timeline !== false;+ const addToTimeline = input.add_to_timeline === true || isNum(input.index);const promptedIndex = isNum(input.index) ? Math.round(input.index) : undefined;+ // Captured now: the render must file under the chat that asked, even if+ // the user switches threads before it lands.+ const chatId = chatOwner();void gen.generateVideo(projectId, prompt, {tier: input.tier === "high" ? "high" : "fast",durationSeconds: isNum(input.duration_seconds)@@ -425,18 +431,25 @@ export async function runAiTool(? { resolution: input.resolution }: {}),...(refs.length > 0 ? { refs } : {}),- onDone: addToTimeline- ? (asset) => maybeAddGeneratedClip(asset.id, { index: promptedIndex })- : undefined,+ onDone: (asset) => {+ tagChatAsset(asset.id, chatId);+ if (addToTimeline)+ maybeAddGeneratedClip(asset.id, { add_to_timeline: true, index: promptedIndex });+ },});+ // The job entry is prepended synchronously, so the newest job is this+ // render; the chat follows it by id to show a live card.+ const jobId = useGenerate.getState().jobs[0]?.id ?? null;return {kind: "video",started: true,+ jobId,addToTimeline,note:- "Rendering with Veo — it lands " +- (addToTimeline ? "on the timeline" : "in the Video panel's renders") +- " in a minute or two. Track it in the Video panel.",+ "Rendering with Veo — it previews in this chat when it lands, in a minute or two" ++ (addToTimeline+ ? ", and goes onto the timeline."+ : ". It stays in the chat (and the Video panel's renders) until the user places it."),};}@@ -452,8 +465,9 @@ export async function runAiTool(const gen = useGenerate.getState();const signedIn = gen.signedIn ?? (await gen.probeNow());if (!signedIn) throw new ToolError("Sign in to Donkey to generate video.");- const addToTimeline = input.add_to_timeline !== false;+ const addToTimeline = input.add_to_timeline === true || isNum(input.index);const promptedIndex = isNum(input.index) ? Math.round(input.index) : undefined;+ const chatId = chatOwner();void gen.generateVideo(projectId, characterPrompt(character.persona!, line), {tier: input.tier === "high" ? "high" : "fast",durationSeconds: isNum(input.duration_seconds)@@ -464,19 +478,24 @@ export async function runAiTool(// delivers the line — composing would swap the face, so it rides raw.refs: [refFromStockVideo(character)],composeRefs: false,- onDone: addToTimeline- ? (asset) => maybeAddGeneratedClip(asset.id, { index: promptedIndex })- : undefined,+ onDone: (asset) => {+ tagChatAsset(asset.id, chatId);+ if (addToTimeline)+ maybeAddGeneratedClip(asset.id, { add_to_timeline: true, index: promptedIndex });+ },});+ const jobId = useGenerate.getState().jobs[0]?.id ?? null;return {kind: "video",started: true,+ jobId,character: character.id,addToTimeline,note:- "Rendering with Veo — it lands " +- (addToTimeline ? "on the timeline" : "in the Video panel's renders") +- " in a minute or two. Track it in the Video panel.",+ "Rendering with Veo — it previews in this chat when it lands, in a minute or two" ++ (addToTimeline+ ? ", and goes onto the timeline."+ : ". It stays in the chat (and the Video panel's renders) until the user places it."),};}@@ -554,7 +573,9 @@ export async function runAiTool(const asset = vid? await importStockVideo(projectId, { url: vid.file, name: stockTitle(vid.id) }): await importImage(projectId, { url: img!.file, name: stockTitle(img!.id) });- const addToTimeline = input.add_to_timeline !== false;+ tagChatAsset(asset.id);+ // An explicit start is itself the ask to place.+ const addToTimeline = input.add_to_timeline === true || isNum(input.start);let clipId: string | null = null;if (addToTimeline) {useEditor@@ -707,11 +728,14 @@ export async function runAiTool(throw new ToolError("script is required.");const start = isNum(input.start) ? Math.max(0, input.start) : s.currentTime;const lead = input.script.trim().split(/\s+/).slice(0, 4).join(" ");- return synthesizeAndPlace(+ // An explicit start is itself the ask to place on the soundtrack.+ const place = input.add_to_timeline === true || isNum(input.start);+ return synthesizeVoiceover([{ text: input.script, at: 0 }],`AI voice — ${lead}`,start,- input+ input,+ place);}@@ -732,6 +756,8 @@ export async function runAiTool(});const sel = useEditor.getState().selection;return {+ assetId: out.asset.id,+ name: out.asset.name,audioClipId: sel?.kind === "audio" ? sel.id : null,voice,start: round2(out.start),@@ -882,11 +908,12 @@ export async function runAiTool(* sign-in and credits), register the media, and drop one soundtrack clip* (voiceovers duck other audio by default). Shared by voiceover_generate and* read_subtitles_aloud. */-async function synthesizeAndPlace(+async function synthesizeVoiceover(segments: { text: string; at: number }[],name: string,start: number,- input: Record<string, unknown>+ input: Record<string, unknown>,+ place: boolean) {const projectId = useEditor.getState().projectId;if (!projectId) throw new ToolError("No project open.");@@ -904,18 +931,32 @@ async function synthesizeAndPlace(});const cur = useEditor.getState();cur.addAsset(asset);+ tagChatAsset(asset.id);+ void enrichAsset(asset);+ if (!place) {+ return {+ assetId: asset.id,+ name: asset.name,+ voice,+ duration: round2(asset.duration),+ addedToTimeline: false,+ note: "The voiceover previews in this chat — the user can play it and drag it onto the soundtrack; pass add_to_timeline or start when they ask for it in the cut.",+ };+ }// A single script lands at `start`; a multi-line readout is pre-offset to its// first cue, so it lands at that offset.const at = segments.length === 1 ? start : offset;cur.addAudioFromAsset(asset.id, at, { duck: duck < 1 ? duck : undefined });- void enrichAsset(asset);const sel = useEditor.getState().selection;return {+ assetId: asset.id,+ name: asset.name,audioClipId: sel?.kind === "audio" ? sel.id : null,voice,start: round2(at),duration: round2(asset.duration),duck: duck < 1 ? duck : null,+ addedToTimeline: true,};}@@ -972,14 +1013,17 @@ function layoutPatch(layout: string): Partial<OverlayClip> {return { frame: key === "full" ? undefined : { ...L.rect }, fit: L.fit };}-/** Append a generated asset to the video track (default) at an optional index.- * Shared by generate_image (inline) and generate_video (on the render's- * completion). Respects add_to_timeline:false. */+/** Append a generated asset to the video track at an optional index, when the+ * model passed add_to_timeline:true. By default generated media stays on its+ * chat preview card until the user asks for it in the cut. Shared by+ * generate_image (inline) and generate_video (on the render's completion). */function maybeAddGeneratedClip(assetId: string,input: { add_to_timeline?: unknown; index?: unknown }): { added: boolean; clipId: string | null; index: number | null } {- if (input.add_to_timeline === false) return { added: false, clipId: null, index: null };+ // An explicit index is itself the ask to place ("make it the cover frame").+ if (input.add_to_timeline !== true && !isNum(input.index))+ return { added: false, clipId: null, index: null };const s = useEditor.getState();if (!s.assets.some((a) => a.id === assetId)) return { added: false, clipId: null, index: null };s.addClipFromAsset(assetId); // lands at the end, selecteddiff --git a/site/src/cut/lib/chatAssets.ts b/site/src/cut/lib/chatAssets.tsnew file mode 100644index 00000000..dff2d4c7--- /dev/null+++ b/site/src/cut/lib/chatAssets.ts@@ -0,0 +1,48 @@+"use client";++import { useEditor } from "./store";++// Chat-created media belongs to its thread. The files live in the project's+// media folder like every other asset (drag-to-timeline and previews need+// that), but each is tagged origin "chat" plus the owning thread id, so it+// shows only on its chat card — and deleting the thread deletes whatever it+// still owns. Assets the user moved on survive: placed on the timeline+// (referenced by a clip), filed into Media (origin cleared), or copied into+// the Library (its own file).++let activeChatId: string | null = null;++/** The chat thread whose tools are currently running. The chat session sets+ * this while mounted so tool-created assets can be tagged with their owner. */+export function setActiveChatThread(id: string | null) {+ activeChatId = id;+}++/** The owning thread to stamp on an asset created right now. Capture it+ * before a background render so the clip files under the chat that asked,+ * even if the user has switched threads by the time it lands. */+export function chatOwner(): string | null {+ return activeChatId;+}++/** Tag a landed project asset as owned by a chat thread. */+export function tagChatAsset(assetId: string, chatId: string | null = activeChatId) {+ if (!chatId) return;+ useEditor.getState().updateAsset(assetId, { origin: "chat", chatId });+}++/** Delete the assets a thread still owns: origin "chat", tagged with the+ * thread, and not referenced by any clip. One undo step. */+export function deleteChatAssets(threadId: string) {+ const s = useEditor.getState();+ const inUse = new Set(+ [...s.clips, ...s.overlayClips, ...s.audioClips].map((c) => c.assetId)+ );+ const owned = s.assets.filter(+ (a) => a.origin === "chat" && a.chatId === threadId && !inUse.has(a.id)+ );+ if (owned.length === 0) return;+ s.beginHistoryBatch();+ for (const a of owned) useEditor.getState().removeAsset(a.id);+ useEditor.getState().endHistoryBatch();+}diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex 68db6c83..2c58213f 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -58,34 +58,38 @@ interface GenerateState {composeRefs?: boolean;}) => Promise<GenerateJob>;+ /** Kick off a video render. Returns the job id right away (the render+ * outlives most callers) plus the settled job for anyone who waits. */generateVideo: (projectId: string,prompt: string,- opts?: {- tier?: "fast" | "high";- durationSeconds?: number;- /** Composition shape; defaults to the project's orientation. */- aspect?: "16:9" | "9:16";- resolution?: "720p" | "1080p";- /** References of any kind — video, image, text file. Veo takes one- * input image, so at most one picture seeds the render. */- refs?: AssetRef[];- /** Rewrite the prompt around the references before rendering (the- * default when refs are present) — see composeGen.ts. Veo plays the- * input image as the literal first frame, so a prompt that transforms- * the reference must become a standalone description with the image- * dropped; the rewrite decides which. Character mode passes false — the- * poster seed is the point. */- composeRefs?: boolean;- /** Called once with the landed asset when the render completes and the- * project is still open — lets the AI place the clip after a background- * render it couldn't wait out (the assistant tool bridge caps at 2min). */- onDone?: (asset: MediaAsset) => void;- }- ) => Promise<GenerateJob>;+ opts?: VideoGenOptions+ ) => { jobId: string; settled: Promise<GenerateJob> };dismiss: (id: string) => void;}+export interface VideoGenOptions {+ tier?: "fast" | "high";+ durationSeconds?: number;+ /** Composition shape; defaults to the project's orientation. */+ aspect?: "16:9" | "9:16";+ resolution?: "720p" | "1080p";+ /** References of any kind — video, image, text file. Veo takes one+ * input image, so at most one picture seeds the render. */+ refs?: AssetRef[];+ /** Rewrite the prompt around the references before rendering (the+ * default when refs are present) — see composeGen.ts. Veo plays the+ * input image as the literal first frame, so a prompt that transforms+ * the reference must become a standalone description with the image+ * dropped; the rewrite decides which. Character mode passes false — the+ * poster seed is the point. */+ composeRefs?: boolean;+ /** Called once with the landed asset when the render completes and the+ * project is still open — lets the AI place the clip after a background+ * render it couldn't wait out (the assistant tool bridge caps at 2min). */+ onDone?: (asset: MediaAsset) => void;+}+const REFRESH_MS = 8000;const VIDEO_DEADLINE_MS = 12 * 60_000;@@ -206,14 +210,47 @@ function bytesFromBase64(b64: string): Uint8Array<ArrayBuffer> {return bytes;}+/** Settled video jobs persist per browser, so a render left unplaced (a chat+ * card, the Video panel's renders list) survives a reload. Running jobs don't+ * persist: a reload kills the in-flight poll loop, so a restored one would+ * spin forever. */+const JOBS_KEY = "cut-gen-video-jobs";+const JOBS_CAP = 50;++function readPersistedJobs(): GenerateJob[] {+ try {+ const v = JSON.parse(localStorage.getItem(JOBS_KEY) ?? "[]") as unknown;+ return Array.isArray(v)+ ? (v as GenerateJob[]).filter((j) => j?.id && j.status !== "running")+ : [];+ } catch {+ return [];+ }+}++function persistJobs(jobs: GenerateJob[]) {+ try {+ localStorage.setItem(+ JOBS_KEY,+ JSON.stringify(+ jobs.filter((j) => j.kind === "video" && j.status !== "running").slice(0, JOBS_CAP)+ )+ );+ } catch {+ // Storage full/blocked — render history just won't persist.+ }+}+export const useGenerate = create<GenerateState>((set, get) => {// A single session probe is in flight at a time, but the answer stays// re-checkable for the page's whole life: a sign-in can complete in another// tab, or the session cookie can land a beat after this page loads.let probing: Promise<boolean> | null = null;- const update = (id: string, patch: Partial<GenerateJob>) =>+ const update = (id: string, patch: Partial<GenerateJob>) => {set((s) => ({ jobs: s.jobs.map((j) => (j.id === id ? { ...j, ...patch } : j)) }));+ persistJobs(get().jobs);+ };const fail = (id: string, err: unknown) =>update(id, { status: "error", error: err instanceof Error ? err.message : String(err) });@@ -233,7 +270,7 @@ export const useGenerate = create<GenerateState>((set, get) => {return {signedIn: null,- jobs: [],+ jobs: typeof window === "undefined" ? [] : readPersistedJobs(),probe: () => {void get().probeNow();@@ -322,7 +359,7 @@ export const useGenerate = create<GenerateState>((set, get) => {generateVideo: (projectId, prompt, opts) => {const job: GenerateJob = { id: uid(), projectId, kind: "video", prompt, status: "running" };set((s) => ({ jobs: [job, ...s.jobs] }));- return (async () => {+ const settledRun = (async () => {try {// The job (and the landed asset's name) keeps the user's own words;// only the render sees the composed prompt. Veo seeds from a single@@ -397,9 +434,13 @@ export const useGenerate = create<GenerateState>((set, get) => {}return settled(job.id, job);})();+ return { jobId: job.id, settled: settledRun };},- dismiss: (id) => set((s) => ({ jobs: s.jobs.filter((j) => j.id !== id) })),+ dismiss: (id) => {+ set((s) => ({ jobs: s.jobs.filter((j) => j.id !== id) }));+ persistJobs(get().jobs);+ },};});diff --git a/site/src/cut/lib/lightbox.ts b/site/src/cut/lib/lightbox.tsindex 5907ae33..30ae9026 100644--- a/site/src/cut/lib/lightbox.ts+++ b/site/src/cut/lib/lightbox.ts@@ -1,19 +1,16 @@"use client";import { create } from "zustand";+import type { AssetRef } from "./assetRef";-// The media 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.+// The asset lightbox: a full-screen viewer opened from stock tiles, generated+// media, and chat asset cards. Held in its own store so any surface 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. */+ kind: "video" | "image" | "audio" | "text";+ /** Fetchable source for the media or file. */src: string;- /** Generated stills are 8s videos — render the poster frame, not an <img>. */- isVideo: boolean;- /** True for real footage (a stock clip): play it with controls instead of- * showing the poster frame. */- playable?: boolean;name: string;/** The generation prompt, when known. */prompt: string;@@ -21,10 +18,20 @@ export interface LightboxItem {* up front so it opens at its final size instead of growing on media load. */aspect?: "16:9" | "9:16" | "1:1";/** For a project asset, its id (add straight to the timeline); null for a- * stock image, which the lightbox bakes into a still first. */+ * stock item, which the lightbox imports first. */assetId: string | null;}+/** The lightbox view of an asset ref — how chat cards and attachment chips+ * open the big version of whatever they show. */+export const lightboxItemFromRef = (ref: AssetRef): LightboxItem => ({+ kind: ref.kind,+ src: ref.url,+ name: ref.name,+ prompt: "",+ assetId: ref.scope === "project" ? ref.id : null,+});+interface LightboxState {item: LightboxItem | null;open: (item: LightboxItem) => void;diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 50fd1823..246da4f2 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -2040,7 +2040,7 @@ export function serializeDoc(s: {subtitles: SubtitlesBlock;}): Partial<ProjectDoc> {const assets: StoredAsset[] = s.assets.map(- ({ id, fileName, name, type, duration, width, height, origin }) => ({+ ({ id, fileName, name, type, duration, width, height, origin, chatId }) => ({id,fileName,name,@@ -2049,6 +2049,7 @@ export function serializeDoc(s: {...(width !== undefined ? { width } : {}),...(height !== undefined ? { height } : {}),...(origin !== undefined ? { origin } : {}),+ ...(chatId !== undefined ? { chatId } : {}),}));return {diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 378b303b..c8b35050 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -30,9 +30,12 @@ export interface StoredAsset {height?: number;/** 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";+ * Cut created or fetched — it lives where it was made (the timeline, a+ * generation panel, or an AI chat card) and is kept out of the Media panel. */+ origin?: "voiceover" | "generated" | "recording" | "stock" | "freeze" | "chat";+ /** For origin "chat": the chat thread that made it. Deleting that thread+ * deletes the assets it still owns (see chatAssets.ts). */+ chatId?: string;}/** Runtime asset: stored fields plus derived/browser-only data. */diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 59e36d56..48d41e3c 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -223,7 +223,7 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_image",description:- "Generate an AI image from a text prompt (Donkey's hosted image model) and add it to the project as a still clip. Use for B-roll, cover frames, or backgrounds the user doesn't have footage for; when the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the image. reference_asset_ids attaches project images/video frames the render should draw from (the user's attached references, a clip to restyle) — the prompt is recomposed around them. Returns when the image has landed. By default it also drops the still onto the timeline; pass add_to_timeline:false to keep it off (it stays in the Image panel's renders, where a \"…\" menu files it into Media or the Library). Needs the user signed in to Donkey (spends their credits).",+ "Generate an AI image from a text prompt (Donkey's hosted image model). Use for B-roll, cover frames, or backgrounds the user doesn't have footage for; when the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the image. reference_asset_ids attaches project images/video frames the render should draw from (the user's attached references, a clip to restyle) — the prompt is recomposed around them. Returns when the image has landed. The image previews as a card in this chat, where the user can expand it, drag it onto the timeline, or file it into Media or the Library from its \"…\" menu; pass add_to_timeline:true (or an index) only when they asked for it in the cut. Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({prompt: str("What to depict — be specific about subject, style, and lighting"),aspect: { type: "string", enum: ["16:9", "9:16", "1:1"], description: "Image shape (default: the project aspect)" },@@ -233,14 +233,14 @@ export const AI_TOOLS: AiToolDef[] = [items: { type: "string" },description: "Project asset ids (images or videos) to use as visual references",},- add_to_timeline: bool("Insert the still on the video track (default true)"),- index: num("Insert position on the video track (default: end; 0 = first/cover)"),+ add_to_timeline: bool("Insert the still on the video track (default false — it stays on its chat card until the user asks)"),+ index: num("Insert position on the video track (passing it implies add_to_timeline; 0 = first/cover)"),}, ["prompt"]),},{name: "generate_video",description:- "Generate an AI video clip from a text prompt (Donkey's hosted Veo model). Use for B-roll or shots the user doesn't have footage for; when the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the video. reference_asset_id seeds the render with one project image or video frame (it becomes the opening frame when the subject is used as-is). This renders remotely and takes a minute or two, so the tool RETURNS IMMEDIATELY — the clip appears in the Video panel's renders (and on the timeline by default) when it finishes. Tell the user it's rendering. Pass add_to_timeline:false to keep it off the timeline. Needs the user signed in to Donkey (spends their credits).",+ "Generate an AI video clip from a text prompt (Donkey's hosted Veo model). Use for B-roll or shots the user doesn't have footage for; when the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the video. reference_asset_id seeds the render with one project image or video frame (it becomes the opening frame when the subject is used as-is). This renders remotely and takes a minute or two, so the tool RETURNS IMMEDIATELY — the clip previews as a live card in this chat (and in the Video panel's renders) when it finishes. Tell the user it's rendering. Pass add_to_timeline:true (or an index) only when they asked for it in the cut; otherwise the user drags it in from the card. Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({prompt: str("The shot to generate — describe motion, subject, and mood"),tier: { type: "string", enum: ["fast", "high"], description: "fast = quicker/cheaper (default), high = best quality" },@@ -248,21 +248,21 @@ export const AI_TOOLS: AiToolDef[] = [aspect: { type: "string", enum: ["16:9", "9:16"], description: "Clip shape (default: the project aspect)" },resolution: { type: "string", enum: ["720p", "1080p"], description: "Output detail (default 720p)" },reference_asset_id: str("One project asset id (image or video) to seed the render"),- add_to_timeline: bool("Insert the clip on the video track (default true)"),- index: num("Insert position on the video track (default: end)"),+ add_to_timeline: bool("Insert the clip on the video track when it lands (default false — it stays on its chat card until the user asks)"),+ index: num("Insert position on the video track (passing it implies add_to_timeline)"),}, ["prompt"]),},{name: "generate_character_video",description:- "Generate a UGC-style selfie clip of a stock talking character speaking a line you write (Donkey's hosted Veo model). Pick a character id from stock_search kind:\"character\" — each has a persona and look; the same person then delivers the line to camera. Like generate_video this RETURNS IMMEDIATELY and the clip lands in the Video panel's renders (and on the timeline by default) a minute or two later. Needs the user signed in to Donkey (spends their credits).",+ "Generate a UGC-style selfie clip of a stock talking character speaking a line you write (Donkey's hosted Veo model). Pick a character id from stock_search kind:\"character\" — each has a persona and look; the same person then delivers the line to camera. Like generate_video this RETURNS IMMEDIATELY and the clip previews in this chat (and the Video panel's renders) a minute or two later; add_to_timeline:true places it when it lands. Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({character_id: str("Talking-character id from stock_search"),line: str("What the character says, spoken to camera"),tier: { type: "string", enum: ["fast", "high"], description: "fast = quicker/cheaper (default), high = best quality" },duration_seconds: num("Clip length 4–8 seconds (default 8)"),- add_to_timeline: bool("Insert the clip on the video track (default true)"),- index: num("Insert position on the video track (default: end)"),+ add_to_timeline: bool("Insert the clip on the video track when it lands (default false — it stays on its chat card until the user asks)"),+ index: num("Insert position on the video track (passing it implies add_to_timeline)"),}, ["character_id", "line"]),},{@@ -277,11 +277,11 @@ export const AI_TOOLS: AiToolDef[] = [{name: "stock_add",description:- "Import a stock video or image (by stock_search id) into the project and, by default, drop it on the video track. Free — the media ships with Cut.",+ "Import a stock video or image (by stock_search id) into the project. It previews as a card in this chat; pass add_to_timeline:true (or a `start`) to also drop it on the video track when the user asked for it in the cut. Free — the media ships with Cut.",inputSchema: obj({id: str("Stock item id from stock_search"),- add_to_timeline: bool("Place it on video track 0 (default true)"),- start: num("Timeline start s (default: appended at the end)"),+ add_to_timeline: bool("Place it on video track 0 (default false — it stays on its chat card until the user asks)"),+ start: num("Timeline start s (passing it implies add_to_timeline; default when placed: appended at the end)"),}, ["id"]),},{@@ -340,14 +340,15 @@ export const AI_TOOLS: AiToolDef[] = [{name: "voiceover_generate",description:- "Generate a spoken AI voiceover from a script (Donkey's hosted speech model) and drop it on the soundtrack at the playhead (or `start`). Use for 'add a voiceover', 'narrate this', 'read this script aloud'; when the user asks you to write or rework the script itself, put the text in chat and wait for them to ask for the voiceover. Pick a `voice` id from list_voices, or omit for a good default. `direction` steers delivery in natural language and can ask for another language — 'say it in Spanish' translates the script before synthesis; the script itself may carry inline tags like [whispers] or [excited]. `duck` lowers all other audio to that gain while the voice plays (0..1; ~0.3–0.5 is typical, 1 = don't duck). Needs the user signed in to Donkey (spends their credits).",+ "Generate a spoken AI voiceover from a script (Donkey's hosted speech model). The audio previews as a playable card in this chat; pass add_to_timeline:true (or a `start`) to also drop it on the soundtrack when the user asked for it in the cut ('add a voiceover', 'narrate this'). When the user asks you to write or rework the script itself, put the text in chat and wait for them to ask for the voiceover. Pick a `voice` id from list_voices, or omit for a good default. `direction` steers delivery in natural language and can ask for another language — 'say it in Spanish' translates the script before synthesis; the script itself may carry inline tags like [whispers] or [excited]. `duck` lowers all other audio to that gain while the voice plays (0..1; ~0.3–0.5 is typical, 1 = don't duck). Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({script: str("What the voice should say"),voice: str("Voice id from list_voices (optional; a sensible default is chosen)"),direction: str("Delivery instruction, e.g. 'Say warmly, like an old friend'; may include a language ask, which translates the script (optional)"),language: str("Pronunciation language as BCP-47, e.g. es-US, ja-JP (optional; default auto-detects — this reads the script as written, it does not translate)"),duck: num("Lower other audio to this gain while the voice plays, 0..1 (default 0.4; 1 = no ducking)"),- start: num("Timeline start in seconds (default: the playhead)"),+ add_to_timeline: bool("Place it on the soundtrack (default false — it stays on its chat card until the user asks)"),+ start: num("Timeline start in seconds (passing it implies add_to_timeline; default when placed: the playhead)"),}, ["script"]),},{@@ -477,7 +478,7 @@ export const AI_SKILLS: Record<string, string> = {"editor-overview": `# Cut editor overviewCut is a local, project-based short-video editor. Each project has an output aspect — 9:16 vertical (1080×1920, TikTok/Reels/Shorts) or 16:9 widescreen (1920×1080, YouTube) — switchable from the pill in the top bar; the current one is in editor_state project.aspect. Layout:- Left icon rail tabs: Media (user-imported files + Exports list), Library (shared reusable assets), Video (stock clip browser — footage + talking characters — beside the AI video generator), Image (stock images beside the AI image generator), Audio (AI voiceover + audio files), Text (title presets), Subtitles (transcript editor), Publish (caption/tags/sound metadata). Camera/mic recording lives in the top bar next to the aspect picker.-- Media shows only what the user imported. Everything Cut makes carries an origin tag (generated, voiceover, recording, stock, freeze — see \`media\` in editor_state) and lives where it was created, e.g. generated clips in the Video panel's job list; a "…" menu on each files it into Media or the Library.+- Media shows only what the user imported. Everything Cut makes carries an origin tag (generated, voiceover, recording, stock, freeze, chat — see \`media\` in editor_state) and lives where it was created — media you make previews on a card in this chat, panel renders sit in their job lists; a "…" menu on each files it into Media or the Library, and every card drags onto the timeline. Deleting a chat thread deletes the chat media the user never placed or filed away.- Center: the video preview canvas (composited at the project's frame size) with draggable text overlays and subtitle captions.- Right: the Inspector — its content follows the selection (video clip, overlay video, soundtrack clip, title, or cue).- Bottom: the timeline (resizable by dragging its top border). Rows top-to-bottom: the video tracks in z-order (positive tracks, then track 0, then negative tracks behind it), soundtrack lanes (green), titles (purple), subtitle tracks (amber, when enabled). Every track is free-positioned in time.@@ -524,7 +525,7 @@ Titles burn into the export exactly as previewed.`,Soundtrack clips: volume 0..1.5, fadeIn/fadeOut seconds (max half the clip), start = timeline position, in/out = trim inside the source; clips can spread across several soundtrack lanes (the \`lane\` field), new sounds slide to free space in their lane. Fades render with ffmpeg afade on export.Ducking: a soundtrack clip's \`duck\` (0..1, via update_audio) lowers ALL other audio — video-clip sound and other music — to that gain while the clip plays; 1 clears it. Voiceovers set this so narration sits over quieter music. It applies in both the preview and the export.Voiceover (Donkey's hosted speech model — signed in, spends credits, like image/video generation):-- voiceover_generate(script, voice?, direction?, duck?, start?, language?): synthesizes the script and drops it on the soundtrack at the playhead (or start). Defaults to a 0.4 duck so it sits over other audio. Voices are Gemini's prebuilt set — list_voices returns them (id + one-word character like Warm, Upbeat, Gravelly); omit voice for a good default. \`direction\` steers delivery in natural language ("Say warmly, like an old friend") and may ask for another language — "say it in Spanish" translates the script before synthesis; the script itself can carry inline tags like [whispers], [excited], [laughs]. \`language\` only pins pronunciation of the text as written.+- voiceover_generate(script, voice?, direction?, duck?, add_to_timeline?, start?, language?): synthesizes the script into a playable chat card; add_to_timeline:true (or a start) also drops it on the soundtrack at the playhead (or start) when the user asked for it in the cut. Defaults to a 0.4 duck when placed so it sits over other audio. Voices are Gemini's prebuilt set — list_voices returns them (id + one-word character like Warm, Upbeat, Gravelly); omit voice for a good default. \`direction\` steers delivery in natural language ("Say warmly, like an old friend") and may ask for another language — "say it in Spanish" translates the script before synthesis; the script itself can carry inline tags like [whispers], [excited], [laughs]. \`language\` only pins pronunciation of the text as written.- read_subtitles_aloud(voice?, direction?, duck?, track?): speaks one subtitle track's cues, each line at its own cue time — captions become narration. Needs cues first. The Inspector offers the same per-clip: "Generate audio for clip" transcribes just that clip when it has no cues yet, then voices it.Subtitle tracks: a project carries up to 3, one language each (editor_state subtitles.tracks; each cue's \`track\`). Each track shows its own caption line, dragged to its own spot; all share one visual style. The panel and generation write to the ACTIVE track — the track tool param switches it. subtitles_add_track / subtitles_remove_track manage them; subtitles_translate_track("ko-KR") is the whole "add Korean subtitles" flow when captions exist (it adds/reuses the track and translates cue-for-cue).Generating: subtitles_generate transcribes the cut's audio on-device (Apple speech, macOS 26) onto the target track; cues are caption-sized (≈38 chars). subtitles_from_visuals is the fallback for a cut with NO speech — it watches sampled frames (via the user's Claude login) and writes timed narration captions of what's on screen. So: speech present → subtitles_generate; silent/music-only footage the user wants captioned → subtitles_from_visuals. Never fabricate a spoken transcript.@@ -535,10 +536,10 @@ Caption look: the Subtitles panel offers 10 visual presets (clean, hook, punchy,"ai-generation": `# Stock media & AI generationTwo ways to get footage the user doesn't have: bundled stock (local, free) and hosted generation (signed in, spends credits). Prefer stock when it genuinely fits; generate when the shot needs to be specific.-Stock: stock_search browses the bundled catalogs — footage clips and images in 8 categories plus ~20 UGC talking characters — matching prompts, categories, and tags. stock_add imports an item into the project (origin "stock") and drops it on the timeline. In the UI these live in the Video and Image tabs beside the generators; clicking a stock tile seeds the generate panel with its prompt.+Stock: stock_search browses the bundled catalogs — footage clips and images in 8 categories plus ~20 UGC talking characters — matching prompts, categories, and tags. stock_add imports an item into the project as a chat card; add_to_timeline:true (or a start) also drops it on the timeline when the user asked. In the UI these live in the Video and Image tabs beside the generators; clicking a stock tile seeds the generate panel with its prompt.Generation:-- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: project aspect) and 1K/2K/4K. The image rides video track 0 as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.-- generate_video(prompt, tier?, duration_seconds?, aspect?, resolution?, reference_asset_id?, add_to_timeline?, index?): a hosted Veo model renders a 4–8s clip with audio. tier "fast" (default) is quicker/cheaper, "high" is best quality. This takes a minute or two, so the tool returns right away and the clip appears in the Video panel's renders (and on the timeline by default) when it finishes — tell the user it's rendering. Don't call it again for the same shot while one is in flight.+- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: project aspect) and 1K/2K/4K. The still previews in the chat; placed (add_to_timeline:true or an index) it rides video track 0 as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.+- generate_video(prompt, tier?, duration_seconds?, aspect?, resolution?, reference_asset_id?, add_to_timeline?, index?): a hosted Veo model renders a 4–8s clip with audio. tier "fast" (default) is quicker/cheaper, "high" is best quality. This takes a minute or two, so the tool returns right away and the clip previews in the chat and the Video panel's renders when it finishes (on the timeline only when asked) — tell the user it's rendering. Don't call it again for the same shot while one is in flight.- generate_character_video(character_id, line, …): a stock talking character delivers a line to camera, same async render as generate_video. Characters come from stock_search kind:"character" — each has a persona; you write the line (chat deliverable rules apply: asked for "a script", write it in chat first).References: users attach images/clips to their message or the generate panels; project asset ids (see \`media\` in editor_state, including attachments — OS drops become project assets) pass through reference_asset_ids / reference_asset_id. A model recomposes the prompt around them: for video at most one image survives as the literal opening frame; for images any number can be drawn from. When the user says "use this clip/image", pass the reference — don't just describe it in the prompt.If generation fails with a sign-in or credits message, relay that plainly — it needs the user signed in to Donkey with credits; it is not a local fallback. Write vivid, specific prompts (subject, style, lighting, motion); the user's request is usually shorthand, so flesh it out.`,@@ -562,7 +563,7 @@ Rules:- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.- Don't transcribe a video with no speech. If the user wants captions on silent footage, use subtitles_from_visuals (it narrates what's on screen). Never invent a spoken transcript.- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.-- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this". Default to adding the result to the timeline; write a rich, specific prompt from their shorthand. Video renders take a minute or two.+- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this". Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two.- capture_frame shows you the actual rendered frame when visual judgment matters.`;}