Open source CapCut alternative.
TypeScript
feat(site): pin reference moments on video and audio references [rebuild]
David Lec4b8a220a939
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 1a6d2f88..df6075d8 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -74,6 +74,7 @@ import {sameRef,setRefDragData,splitMentions,+ upsertRef,useRefCandidates,useAssetDrop,type AssetRef,@@ -969,6 +970,9 @@ function ChatSession({onRemove={(ref) =>setAttachments((p) => p.filter((x) => !sameRef(x, ref)))}+ onUpdate={(ref) =>+ setAttachments((p) => p.map((x) => (sameRef(x, ref) ? ref : x)))+ }className="px-2.5 pt-2.5"/><MentionTextarea@@ -983,6 +987,8 @@ function ChatSession({menuSide="top"inputRef={composerRef}onSubmit={() => send(input)}+ attachedRefs={attachments}+ onUpsertRef={(ref) => setAttachments((p) => upsertRef(p, ref))}/><div className="flex items-center gap-1 px-1.5 pb-1.5"><ModelSelectordiff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsxindex 0d77b47e..54f65b7e 100644--- a/site/src/cut/components/AssetRefs.tsx+++ b/site/src/cut/components/AssetRefs.tsx@@ -6,6 +6,7 @@ import {highlightMentions,mentionToken,refToken,+ sameRef,type AssetRef,} from "@/cut/lib/assetRef";import { MEDIA_CORS } from "@/cut/lib/mediaCors";@@ -13,8 +14,10 @@ import { useRefFor, useRefCandidates } from "@/cut/lib/assetRef";import { useInView } from "@/cut/hooks/useInView";import { revealRef } from "@/cut/lib/refReveal";import { formatTime } from "@/cut/lib/time";-import { useEditor } from "@/cut/lib/store";+import { clipLen, getClipSpans, useEditor } from "@/cut/lib/store";import { AudioPillSurface } from "@/cut/components/AudioPanel";+import { ScrubValue, parseTimeInput } from "@/cut/components/ScrubValue";+import { Slider } from "@/components/ui/slider";import { cn } from "@/lib/utils";// Shared UI for asset references: the preview thumbnail, attachment chips,@@ -36,6 +39,18 @@ export function RefThumb({ item, className }: { item: AssetRef; className?: stri);// Chips render for every past message; the media loads only once on screen.const [thumbRef, seen] = useInView<HTMLDivElement>();+ // A pinned moment is what the ref means now — show that frame. The source+ // rides the pin only on first load; afterwards the pin seeks the same+ // element in place, which keeps the last frame up until the new one decodes+ // (a fresh #t= src blanks the thumb white on every scrub step).+ const videoEl = useRef<HTMLVideoElement>(null);+ const [firstT] = useState(item.t ?? 0.1);+ useEffect(() => {+ const el = videoEl.current;+ if (el && item.t !== undefined && el.readyState >= HTMLMediaElement.HAVE_METADATA) {+ el.currentTime = item.t;+ }+ }, [item.t]);return (<divref={thumbRef}@@ -45,17 +60,28 @@ export function RefThumb({ item, className }: { item: AssetRef; className?: stri)}>{item.kind === "video" ? (- <video crossOrigin={MEDIA_CORS}- src={seen ? `${item.url}#t=0.1` : undefined}+ <video+ crossOrigin={MEDIA_CORS}+ ref={videoEl}+ src={seen ? `${item.url}#t=${firstT}` : undefined}preload="metadata"mutedplaysInlineclassName="size-full object-cover"+ onLoadedMetadata={(e) => {+ if (item.t !== undefined) e.currentTarget.currentTime = item.t;+ }}/>) : item.kind === "image" ? (seen ? (// eslint-disable-next-line @next/next/no-img-element -- refs point at engine/static files, not Next-optimizable images- <img crossOrigin={MEDIA_CORS} src={item.url} alt={item.name} loading="lazy" className="size-full object-cover" />+ <img+ crossOrigin={MEDIA_CORS}+ src={item.url}+ alt={item.name}+ loading="lazy"+ className="size-full object-cover"+ />) : null) : item.kind === "text" ? (<div className="grid size-full place-items-center bg-gradient-to-br from-slate-100 to-slate-50 text-slate-500">@@ -64,9 +90,10 @@ export function RefThumb({ item, className }: { item: AssetRef; className?: stri) : (<AudioPillSurface peaks={peaks} className="size-full rounded-none" />)}- {item.duration !== undefined && item.kind !== "image" && (+ {/* One badge: the pinned moment when the user chose one, the length otherwise. */}+ {(item.t !== undefined || (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)}+ {formatTime(item.t ?? item.duration!)}</span>)}</div>@@ -112,9 +139,11 @@ function RefPeek({ item, side = "top" }: { item: AssetRef; side?: "top" | "bottoside === "top" ? "bottom-full mb-1.5" : "top-full mt-1.5")}>- {item.kind === "video" ? (+ {item.kind === "video" && item.t === undefined ? (<PeekVideo item={item} />) : (+ // A pinned video peeks as its pinned frame, still — the pin names one+ // moment, so playing from the top would show everything but it.<RefThumbitem={item}className={item.kind === "audio" ? "h-14 w-full" : "aspect-square w-full"}@@ -139,7 +168,14 @@ function PeekVideo({ item }: { item: AssetRef }) {}, []);return (<div className="relative aspect-square w-full border border-border bg-muted">- <video crossOrigin={MEDIA_CORS} ref={videoRef} src={item.url} loop playsInline className="size-full object-cover" />+ <video+ crossOrigin={MEDIA_CORS}+ ref={videoRef}+ src={item.url}+ loop+ playsInline+ className="size-full object-cover"+ />{item.duration !== undefined && (<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)}@@ -190,16 +226,21 @@ export function RefTokenChip({}/** Removable attachment chips shown above an input — hover peeks, clicking- * the thumb reveals the original asset. */+ * the thumb reveals the original asset. With `onUpdate`, a video or audio+ * chip opens the moment picker on click instead, so the user can pin the+ * exact moment the reference means. */export function RefChips({refs,onRemove,+ onUpdate,className,peekSide = "top",thumbClassName = "size-14",}: {refs: AssetRef[];onRemove: (ref: AssetRef) => void;+ /** Replace a chip's ref in place (moment picker) — omit for read-only rows. */+ onUpdate?: (ref: AssetRef) => void;className?: string;/** Open peeks downward when the chips sit near the top of their panel. */peekSide?: "top" | "bottom";@@ -219,6 +260,7 @@ export function RefChips({key={`${r.scope}:${r.id}`}item={{ ...r, handle }}onRemove={onRemove}+ onUpdate={onUpdate}peekSide={peekSide}thumbClassName={thumbClassName}/>@@ -228,39 +270,135 @@ export function RefChips({);}+/** Moment-card width, shared by the card and the chip's overflow measurement. */+const CARD_W = 224;++/** The one moment card allowed open anywhere — whoever opens next calls the+ * previous owner's dismiss first, so a stuck hold can never strand a card. */+let dismissOpenCard: (() => void) | null = null;++/** Claim the open-card slot while `open`; call inside an effect. */+function claimOpenCard(open: boolean, dismiss: () => void): (() => void) | undefined {+ if (!open) return undefined;+ if (dismissOpenCard && dismissOpenCard !== dismiss) dismissOpenCard();+ dismissOpenCard = dismiss;+ return () => {+ if (dismissOpenCard === dismiss) dismissOpenCard = null;+ };+}+function RefChip({item,onRemove,+ onUpdate,peekSide,thumbClassName,}: {item: AssetRef;onRemove: (ref: AssetRef) => void;+ onUpdate?: (ref: AssetRef) => void;peekSide: "top" | "bottom";thumbClassName: string;}) {- const [peek, setPeek] = useState(false);+ const [hover, setHover] = useState(false);+ // The moment card must survive interactions that take the pointer or focus+ // off the chip — a slider/hot-text drag (pointer capture) and typing in the+ // timestamp editor — or it would unmount mid-gesture.+ const [held, setHeld] = useState(false);+ const [focused, setFocused] = useState(false);+ useEffect(() => {+ if (!held) return;+ const up = () => setHeld(false);+ window.addEventListener("pointerup", up);+ return () => window.removeEventListener("pointerup", up);+ }, [held]);+ const pinnable = !!onUpdate && (item.kind === "video" || item.kind === "audio");+ const showCard = pinnable && (hover || held || focused);+ useEffect(+ () =>+ claimOpenCard(showCard, () => {+ setHover(false);+ setHeld(false);+ setFocused(false);+ }),+ [showCard]+ );+ // The card opens on the chip's left edge, shifted just enough to stay+ // inside the nearest clipping ancestor (a panel's scroll area cuts off+ // whatever crosses its edges). Measured once as the card opens.+ const chipEl = useRef<HTMLDivElement>(null);+ const [cardDx, setCardDx] = useState(0);+ useEffect(() => {+ if (!showCard) return;+ const el = chipEl.current;+ if (!el) return;+ let clip = el.parentElement;+ while (clip && getComputedStyle(clip).overflowX === "visible") clip = clip.parentElement;+ const bound = (clip ?? document.documentElement).getBoundingClientRect();+ const chip = el.getBoundingClientRect();+ const minLeft = bound.left + 8;+ const maxLeft = Math.max(minLeft, bound.right - 8 - CARD_W);+ setCardDx(Math.min(Math.max(chip.left, minLeft), maxLeft) - chip.left);+ }, [showCard]);return (<div+ ref={chipEl}className="ref-chip relative"- onMouseEnter={() => setPeek(true)}- onMouseLeave={() => setPeek(false)}+ onMouseEnter={() => setHover(true)}+ onMouseLeave={() => setHover(false)}>- <button- type="button"- title={`${item.name} — click to show`}- className="block text-left"- onClick={() => revealRef(item)}- >- {/* Audio stretches to the timeline-pill shape; the chip row wraps, so- the wide chip stays within the composer. */}+ {/* Audio stretches to the timeline-pill shape; the chip row wraps, so+ the wide chip stays within the composer. Composer chips (onUpdate)+ are inert surfaces — hover carries the moment card; click-to-reveal+ belongs to the read-only rows on past messages. */}+ {onUpdate ? (<RefThumbitem={item}className={item.kind === "audio" ? "h-12 w-44 max-w-full" : thumbClassName}/>- </button>- {item.handle && <RefHandleBadge handle={item.handle} className="absolute bottom-1 left-1" />}- {peek && <RefPeek item={item} side={peekSide} />}+ ) : (+ <button+ type="button"+ title={`${item.name} — click to show`}+ className="block text-left"+ onClick={() => revealRef(item)}+ >+ <RefThumb+ item={item}+ className={item.kind === "audio" ? "h-12 w-44 max-w-full" : thumbClassName}+ />+ </button>+ )}+ {item.handle && (+ // The timeline's token look — black pill, white mono @handle — so the+ // chip names itself the way the clip does on the timeline.+ <RefHandlePill+ token={`@${item.handle}`}+ // The pinned-time badge owns the bottom edge; the handle steps up+ // to the top corner so the two never overlap on a small thumb.+ className={cn("absolute left-1", item.t !== undefined ? "top-1" : "bottom-1")}+ />+ )}+ {/* Hover: pinnable chips open the moment card — preview plus controls,+ adjustable in place; everything else peeks. */}+ {showCard && onUpdate ? (+ <div+ onPointerDown={() => setHeld(true)}+ // Hold for the timestamp text editor only. The slider keeps focus+ // after a drag ends — its thumb wraps a hidden range input — so+ // holding for it would pin this card open while the user moves on.+ onFocusCapture={(e) => {+ if (e.target instanceof HTMLInputElement && e.target.type === "text") setFocused(true);+ }}+ onBlurCapture={(e) => {+ if (e.target instanceof HTMLInputElement && e.target.type === "text") setFocused(false);+ }}+ >+ <RefMomentPicker item={item} side={peekSide} offsetX={cardDx} onChange={onUpdate} />+ </div>+ ) : (+ hover && <RefPeek item={item} side={peekSide} />+ )}<buttonaria-label={`Remove ${item.name}`}title="Remove"@@ -273,6 +411,209 @@ function RefChip({);}+/** The playhead's moment on `ref` in source seconds, when the playhead+ * currently sits on that media on the timeline — the clip itself for clip+ * refs, any timeline clip playing the asset for project refs (freeze_frame's+ * playhead→source mapping). Null when the playhead is elsewhere. */+function playheadMoment(ref: AssetRef): number | null {+ if (ref.scope !== "clip" && ref.scope !== "project") return null;+ const s = useEditor.getState();+ const now = s.currentTime;+ const sp = getClipSpans(s.clips, s.assets).find(+ (x) =>+ now >= x.start &&+ now < x.start + x.len &&+ (ref.scope === "clip" ? x.clip.id === ref.id : x.asset.id === ref.id)+ );+ if (sp) return sp.clip.in + (now - sp.start);+ const a = s.audioClips.find(+ (x) =>+ now >= x.start &&+ now < x.start + clipLen(x) &&+ (ref.scope === "clip" ? x.id === ref.id : x.assetId === ref.id)+ );+ return a ? a.in + (now - a.start) : null;+}++/** The scrubbable range behind a ref's pin: a clip ref covers its trimmed+ * [in, out] of the source (its pin is source seconds), anything else the whole+ * media. `dur` supplies a probed duration when the ref doesn't know its own. */+function momentBounds(ref: AssetRef, dur?: number): { lo: number; hi: number } {+ if (ref.scope === "clip") {+ const s = useEditor.getState();+ const c = s.clips.find((x) => x.id === ref.id);+ if (c) return { lo: c.in, hi: c.out };+ const a = s.audioClips.find((x) => x.id === ref.id);+ if (a) return { lo: a.in, hi: a.out };+ }+ return { lo: 0, hi: dur ?? ref.duration ?? 0 };+}++/** The pin's controls — the zoom-style slider and the hot-text timestamp+ * (drag to nudge, click to type) — shared by the chip's inline row and the+ * picker popover. Controlled by the ref itself: every change lands through+ * `onChange`. */+function MomentControls({+ item,+ dur,+ onChange,+ className,+}: {+ item: AssetRef;+ dur?: number;+ onChange: (ref: AssetRef) => void;+ className?: string;+}) {+ const { lo, hi } = momentBounds(item, dur);+ const t = item.t ?? lo;+ const apply = (next: number) =>+ onChange({ ...item, t: Math.min(Math.max(lo, next), hi > lo ? hi : next) });+ return (+ <div className={cn("flex items-center gap-2", className)}>+ <div className="min-w-0 flex-1">+ <Slider+ min={lo}+ max={Math.max(hi, lo + 0.1)}+ step={0.1}+ value={t}+ aria-label="Pinned moment"+ onValueChange={(v) => apply(Number(v))}+ />+ </div>+ <ScrubValue+ value={t}+ min={lo}+ max={Math.max(hi, lo + 0.1)}+ step={0.1}+ keyStep={1}+ format={formatTime}+ parse={parseTimeInput}+ onScrub={apply}+ onCommit={apply}+ label="Pinned moment timestamp"+ className="shrink-0 text-muted-foreground"+ />+ </div>+ );+}++/** Pin a moment on a video/audio ref: the preview bleeds to the popover's+ * edges (the video seeking live, or the audio waveform with a playhead), the+ * controls sit padded below. Changes apply as the user scrubs. */+function RefMomentPicker({+ item,+ side,+ offsetX = 0,+ onChange,+ onClose,+}: {+ item: AssetRef;+ side: "top" | "bottom";+ /** Horizontal shift (px) off the anchor's left edge — how a chip keeps the+ * card inside its panel's clipping bounds. */+ offsetX?: number;+ onChange: (ref: AssetRef) => void;+ /** Close on click-away — pass it when the picker opens from a click (a+ * mention pill). A hover-opened card omits it: hover-out closes instead,+ * and a page-covering backdrop would swallow the next click. */+ onClose?: () => void;+}) {+ const videoRef = useRef<HTMLVideoElement>(null);+ const [dur, setDur] = useState(item.duration ?? 0);+ const { lo, hi } = momentBounds(item, dur);+ // When the playhead already sits on this media on the timeline, that moment+ // is almost always the one the user means — the picker opens there and pins+ // it outright. Read once at open.+ // eslint-disable-next-line react-hooks/exhaustive-deps -- open-time read, keyed by identity+ const playheadAt = useMemo(() => playheadMoment(item), [item.scope, item.id]);+ const t = item.t ?? playheadAt ?? lo;+ const peaks = useEditor((s) =>+ item.kind === "audio" && item.scope === "project"+ ? s.assets.find((a) => a.id === item.id)?.peaks+ : undefined+ );++ // Opening on the playhead's moment IS the pick — land it right away so the+ // chip shows its badge without a scrub.+ useEffect(() => {+ if (item.t === undefined && playheadAt !== null)+ onChange({+ ...item,+ t: Math.min(Math.max(lo, playheadAt), hi > lo ? hi : playheadAt),+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps -- open-time seed only+ }, []);++ // The preview tracks the pin wherever it's adjusted from — this popover's+ // controls or the chip's inline row.+ useEffect(() => {+ const el = videoRef.current;+ if (el && Number.isFinite(el.duration)) el.currentTime = Math.min(t, el.duration);+ }, [t]);++ return (+ <>+ {/* Click-away closes; the picker floats above it. */}+ {onClose && <div className="fixed inset-0 z-40" onClick={onClose} />}+ {/* The offset is transparent padding, not margin: it keeps the card+ hover-connected to its chip, so the cursor can cross from thumb to+ controls without the card unmounting under it. */}+ <div+ style={{ left: offsetX }}+ className={cn("absolute z-50", side === "top" ? "bottom-full pb-1.5" : "top-full pt-1.5")}+ >+ <div+ style={{ width: CARD_W }}+ className="overflow-hidden rounded-xl border border-border bg-popover shadow-xl"+ >+ {item.kind === "video" ? (+ <video+ crossOrigin={MEDIA_CORS}+ ref={videoRef}+ src={item.url}+ preload="metadata"+ muted+ playsInline+ className="aspect-video w-full bg-muted object-cover"+ onLoadedMetadata={(e) => {+ const el = e.currentTarget;+ if (!dur && Number.isFinite(el.duration)) setDur(el.duration);+ el.currentTime = Math.min(t, el.duration || t);+ }}+ />+ ) : (+ <div className="relative h-10 w-full overflow-hidden">+ <AudioPillSurface peaks={peaks} className="size-full rounded-none" />+ {hi > lo && (+ <div+ // The timeline playhead's blue, but with a white keyline —+ // on the emerald waveform the bare line all but vanishes.+ className="absolute inset-y-0 w-[2px] bg-[#0a84ff] shadow-[0_0_0_1.5px_rgba(255,255,255,0.95),0_0_8px_rgba(10,132,255,0.6)]"+ style={{+ left: `${Math.min(100, Math.max(0, ((t - lo) / (hi - lo)) * 100))}%`,+ }}+ />+ )}+ {!item.duration && (+ <audio+ crossOrigin={MEDIA_CORS}+ src={item.url}+ preload="metadata"+ className="hidden"+ onLoadedMetadata={(e) => {+ if (Number.isFinite(e.currentTarget.duration)) setDur(e.currentTarget.duration);+ }}+ />+ )}+ </div>+ )}+ <MomentControls item={item} dur={dur} onChange={onChange} className="p-2" />+ </div>+ </div>+ </>+ );+}+function useCopied(): [boolean, (text: string) => void] {const [copied, setCopied] = useState(false);const copy = (text: string) => {@@ -383,6 +724,8 @@ export function MentionTextarea({rows,autoGrow = false,inputRef,+ attachedRefs,+ onUpsertRef,}: {value: string;onChange: (v: string) => void;@@ -400,15 +743,56 @@ export function MentionTextarea({autoGrow?: boolean;/** Caller's handle on the underlying textarea (e.g. to restore focus). */inputRef?: RefObject<HTMLTextAreaElement | null>;+ /** The composer's already-attached refs — a pill click reads its pinned+ * moment from here so mention and chip stay one ref. */+ attachedRefs?: AssetRef[];+ /** Land a ref (with its pin) among the composer's attachments. Providing it+ * makes video/audio mention pills clickable: the pill opens the moment+ * picker in place, and the pinned ref lands here so it rides at send. */+ onUpsertRef?: (ref: AssetRef) => void;}) {const taRef = useRef<HTMLTextAreaElement>(null);+ const rootRef = useRef<HTMLDivElement>(null);const backdropRef = useRef<HTMLDivElement>(null);const [caret, setCaret] = useState(0);const [dismissed, setDismissed] = useState<number | null>(null);+ /** The open pill picker: the ref it edits and where it anchors, in the+ * container's coordinates (the pill's top and bottom edges). */+ const [pin, setPin] = useState<{+ ref: AssetRef;+ left: number;+ top: number;+ bottom: number;+ } | null>(null);+ // The pill popover competes for the same one-open-card slot as chip cards.+ useEffect(() => claimOpenCard(pin !== null, () => setPin(null)), [pin]);// The row highlight, remembered with the query it was chosen for — see// `sel` below.const [selState, setSelState] = useState<{ q?: string; i: number }>({ i: 0 });+ // Auto-pin on mention add: the moment a video/audio mention resolves in the+ // text while the playhead sits on that media, the pinned chip lands on its+ // own — no picker step. One shot per mention; deleting the token and+ // re-typing it pins again at the playhead's new spot.+ const autoPinned = useRef(new Set<string>());+ useEffect(() => {+ if (!onUpsertRef) return;+ const present = new Set<string>();+ for (const seg of highlightMentions(value, candidates)) {+ const ref = seg.ref;+ if (!ref || (ref.kind !== "video" && ref.kind !== "audio")) continue;+ const key = `${ref.scope}:${ref.id}`;+ present.add(key);+ if (autoPinned.current.has(key)) continue;+ autoPinned.current.add(key);+ const attached = attachedRefs?.find((a) => sameRef(a, ref));+ if (attached?.t !== undefined) continue;+ const at = playheadMoment(ref);+ if (at !== null) onUpsertRef({ ...(attached ?? ref), t: at });+ }+ for (const k of [...autoPinned.current]) if (!present.has(k)) autoPinned.current.delete(k);+ }, [value, candidates, attachedRefs, onUpsertRef]);+const mention = useMemo(() => mentionAtCaret(value, caret), [value, caret]);const matches = useMemo(() => {if (!mention || dismissed === mention.start) return [];@@ -443,6 +827,24 @@ export function MentionTextarea({if (el) setCaret(el.selectionStart ?? 0);};+ /** Open the moment picker anchored on a mention pill. The pill spans live+ * in the mirror overlay, so the anchor is measured into the container's+ * coordinates and the picker rendered at the root (the mirror clips). */+ const openPin = (ref: AssetRef, el: HTMLElement) => {+ const root = rootRef.current;+ if (!root) return;+ const r = el.getBoundingClientRect();+ const c = root.getBoundingClientRect();+ const current = attachedRefs?.find((a) => sameRef(a, ref)) ?? ref;+ setPin({+ ref: current,+ // Keep the 224px popover inside the composer.+ left: Math.max(0, Math.min(r.left - c.left, c.width - 228)),+ top: r.top - c.top,+ bottom: r.bottom - c.top,+ });+ };+const pick = (ref: AssetRef) => {if (!mention) return;const token = refToken(ref) + " ";@@ -470,7 +872,7 @@ export function MentionTextarea({}, [autoGrow, value]);return (- <div className="relative min-w-0">+ <div ref={rootRef} className="relative min-w-0">{open && (<divclassName={cn(@@ -500,33 +902,6 @@ export function MentionTextarea({))}</div>)}- {/* Highlight overlay: a mirror of the text sitting behind the textarea- that draws a pill behind every resolved @mention. It shares the- textarea's typography and padding so the pills line up exactly, and- scrolls in lockstep. */}- <div- ref={backdropRef}- aria-hidden- className={cn(- className,- // Keep the border width for identical text metrics, but draw nothing:- // only the real textarea should paint a box.- "pointer-events-none absolute inset-0 overflow-hidden border-transparent bg-transparent whitespace-pre-wrap break-words text-transparent"- )}- >- {highlightMentions(value, candidates).map((seg, i) =>- seg.ref ? (- <span- key={i}- className="rounded-[4px] bg-[#0a84ff]/12 shadow-[0_0_0_2px_rgba(10,132,255,0.12)]"- >- {seg.text}- </span>- ) : (- <span key={i}>{seg.text}</span>- )- )}- </div><textarearef={(el) => {taRef.current = el;@@ -554,7 +929,9 @@ export function MentionTextarea({if (open) {if (e.key === "ArrowDown" || e.key === "ArrowUp") {e.preventDefault();- setSel((selIndex + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length);+ setSel(+ (selIndex + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length+ );return;}if (e.key === "Enter" || e.key === "Tab") {@@ -579,6 +956,78 @@ export function MentionTextarea({}}}/>+ {/* Highlight overlay: a mirror of the text over the textarea that draws+ a pill on every resolved @mention. It shares the textarea's+ typography and padding so the pills line up exactly, and scrolls in+ lockstep. It ignores the pointer except on pinnable pills, so typing+ and caret clicks land in the textarea while a video/audio pill takes+ the click and opens the moment picker. */}+ <div+ ref={backdropRef}+ aria-hidden+ className={cn(+ className,+ // Keep the border width for identical text metrics, but draw nothing:+ // only the real textarea should paint a box.+ "pointer-events-none absolute inset-0 overflow-hidden border-transparent bg-transparent whitespace-pre-wrap break-words text-transparent"+ )}+ >+ {highlightMentions(value, candidates).map((seg, i, segs) => {+ const pinnable =+ !!onUpsertRef && (seg.ref?.kind === "video" || seg.ref?.kind === "audio");+ // A side facing another pill across a single space keeps its bleed+ // off — two bleeds would swallow the only gap between the pills.+ const facing = (gap: number, other: number) =>+ !!segs[gap] && !segs[gap].ref && /^\s$/.test(segs[gap].text) && !!segs[other]?.ref;+ return seg.ref ? (+ <span+ key={i}+ className={cn(+ // Padding cancelled by negative margin: the background gains+ // side padding to match the font's own vertical inset while+ // every glyph stays exactly where the textarea draws it.+ "rounded-[4px] bg-[#0a84ff]/12",+ !facing(i - 1, i - 2) && "pl-[0.15em] -ml-[0.15em]",+ !facing(i + 1, i + 2) && "pr-[0.15em] -mr-[0.15em]",+ pinnable && "pointer-events-auto cursor-pointer hover:bg-[#0a84ff]/25"+ )}+ title={pinnable ? `${seg.ref.name} — click to pin the moment` : undefined}+ // mousedown, not click: preventDefault keeps focus in the textarea.+ onMouseDown={+ pinnable+ ? (e) => {+ e.preventDefault();+ openPin(seg.ref!, e.currentTarget);+ }+ : undefined+ }+ >+ {seg.text}+ </span>+ ) : (+ <span key={i}>{seg.text}</span>+ );+ })}+ </div>+ {pin && onUpsertRef && (+ <div+ className="absolute z-50"+ style={{+ left: pin.left,+ top: menuSide === "top" ? pin.top : pin.bottom,+ }}+ >+ <RefMomentPicker+ item={pin.ref}+ side={menuSide}+ onChange={(r) => {+ setPin((p) => (p ? { ...p, ref: r } : p));+ onUpsertRef(r);+ }}+ onClose={() => setPin(null)}+ />+ </div>+ )}</div>);}diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsxindex a285c152..b12fbea5 100644--- a/site/src/cut/components/GeneratePanel.tsx+++ b/site/src/cut/components/GeneratePanel.tsx@@ -59,14 +59,12 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {const { prompt, refs, character, aspect } = useVideoGen();const candidates = useRefCandidates();const { active: dropActive, attachTarget, targetProps } = useAssetDrop(- (ref) => {- if (ref.kind !== "audio") useVideoGen.getState().addRef(ref);- },+ (ref) => useVideoGen.getState().addRef(ref),// OS files dropped on the panel attach as references (media files import// into the project on the way; text files ride as-is).(files) =>void refsFromDroppedFiles(projectId, files).then((refs) => {- for (const r of refs) if (r.kind !== "audio") useVideoGen.getState().addRef(r);+ for (const r of refs) useVideoGen.getState().addRef(r);}));const [tier, setTier] = useLocalPref<VideoModelOption["tier"]>(@@ -91,7 +89,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {}, []);const go = () => {- const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates, { dropAudio: true });+ const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates);if (!text) return;// Character mode: the text is the spoken line — compose it with the// persona, and seed the render with the character's poster frame so the@@ -152,6 +150,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {<RefChipsrefs={refs}onRemove={(ref) => useVideoGen.getState().removeRef(ref)}+ onUpdate={(ref) => useVideoGen.getState().updateRef(ref)}className="p-2 pb-0"peekSide="bottom"/>@@ -168,6 +167,8 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {submitKey="mod-enter"menuSide="bottom"onSubmit={go}+ attachedRefs={refs}+ onUpsertRef={(r) => useVideoGen.getState().updateRef(r)}/><DictationControltext={prompt}diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsxindex 234550e5..3ab17d3d 100644--- a/site/src/cut/components/ImageGenPanel.tsx+++ b/site/src/cut/components/ImageGenPanel.tsx@@ -74,14 +74,12 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {[assets]);const { active: dropActive, attachTarget, targetProps } = useAssetDrop(- (ref) => {- if (ref.kind !== "audio") useImageGen.getState().addRef(ref);- },+ (ref) => useImageGen.getState().addRef(ref),// OS files dropped on the panel attach as references (media files import// into the project on the way; text files ride as-is).(files) =>void refsFromDroppedFiles(projectId, files).then((refs) => {- for (const r of refs) if (r.kind !== "audio") useImageGen.getState().addRef(r);+ for (const r of refs) useImageGen.getState().addRef(r);}));@@ -95,7 +93,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {}, []);const go = () => {- const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates, { dropAudio: true });+ const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates);if (!text) return;void useGenerate.getState().generateImage(projectId, text, { refs: all, aspect, resolution });};@@ -119,6 +117,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {<RefChipsrefs={refs}onRemove={(r) => useImageGen.getState().removeRef(r)}+ onUpdate={(r) => useImageGen.getState().updateRef(r)}className="p-2 pb-0"peekSide="bottom"/>@@ -131,6 +130,8 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {submitKey="mod-enter"menuSide="bottom"onSubmit={go}+ attachedRefs={refs}+ onUpsertRef={(r) => useImageGen.getState().updateRef(r)}/><DictationControltext={prompt}diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex c86e3946..8aeb7406 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -42,6 +42,12 @@ export interface AssetRef {/** Fetchable URL for the media itself (previews and frame capture). */url: string;duration?: number;+ /** The moment the user pinned on this reference, seconds into the source —+ * set only by an explicit pick in the chip's moment picker. When present,+ * a video ref reads from this frame (with a little sampling around it) and+ * an audio ref reads as a segment around it; absent, the ref reads from its+ * default spot. 0 is a real pick, distinct from unset. */+ t?: 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. */@@ -117,6 +123,13 @@ export const sameRef = (a: AssetRef, b: AssetRef) => a.scope === b.scope && a.idexport const addRefOnce = (list: AssetRef[], ref: AssetRef): AssetRef[] =>list.some((r) => sameRef(r, ref)) ? list : [...list, ref];+/** Replace a ref in place (same scope+id), attaching it when absent — how a+ * pinned moment lands whether the ref arrived as a chip or a typed mention. */+export const upsertRef = (list: AssetRef[], ref: AssetRef): AssetRef[] =>+ list.some((r) => sameRef(r, ref))+ ? list.map((r) => (sameRef(r, ref) ? ref : r))+ : [...list, ref];+/** A ref's fetchable URL, re-read from the live catalogs. Cloud asset URLs are* short-lived signed R2 URLs, so a ref persisted in a saved chat thread* outlives its `url`; project and clip refs resolve through the current asset@@ -149,6 +162,7 @@ export function normalizeRef(v: unknown): AssetRef | null {kind: o.kind ?? o.type ?? "video",url: liveRefUrl(scope, o.id, o.url),duration: o.duration,+ ...(typeof o.t === "number" && Number.isFinite(o.t) ? { t: o.t } : {}),};}@@ -536,23 +550,18 @@ export function parseMentions(}/** 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. */+ * `chips`, de-duplicated. 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 }+ candidates: AssetRef[]): { 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 refs = parsed.refs.reduce(addRefOnce, chips).map((r) => {const live = candidates.find((c) => sameRef(c, r));return live?.handle ? { ...r, handle: live.handle } : r;});diff --git a/site/src/cut/lib/imageGen.ts b/site/src/cut/lib/imageGen.tsindex 9f3f60c9..a4a28434 100644--- a/site/src/cut/lib/imageGen.ts+++ b/site/src/cut/lib/imageGen.ts@@ -1,7 +1,7 @@"use client";import { create } from "zustand";-import { addRefOnce, sameRef, type AssetRef } from "./assetRef";+import { addRefOnce, sameRef, upsertRef, type AssetRef } from "./assetRef";// The generate-image panel's state, shared between the stock browser (which// loads a stock image's saved prompt into it on click) and the always-on@@ -46,6 +46,10 @@ interface ImageGenState {setAspect: (aspect: ImageAspect) => void;setResolution: (resolution: ImageResolution) => void;addRef: (ref: AssetRef) => void;+ /** Land a ref's new shape — replaced in place when attached, attached when+ * not — how the moment picker lands a pinned timestamp from a chip or a+ * typed mention. */+ updateRef: (ref: AssetRef) => void;removeRef: (ref: AssetRef) => void;}@@ -59,5 +63,6 @@ export const useImageGen = create<ImageGenState>((set) => ({setAspect: (aspect) => set({ aspect }),setResolution: (resolution) => set({ resolution }),addRef: (ref) => set((s) => ({ refs: addRefOnce(s.refs, ref) })),+ updateRef: (ref) => set((s) => ({ refs: upsertRef(s.refs, ref) })),removeRef: (ref) => set((s) => ({ refs: s.refs.filter((r) => !sameRef(r, ref)) })),}));diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.tsindex e990bbd9..c09e26a5 100644--- a/site/src/cut/lib/refMedia.ts+++ b/site/src/cut/lib/refMedia.ts@@ -2,9 +2,10 @@import { refFromAsset, refFromTextFile, type AssetRef } from "./assetRef";import { tagChatAsset } from "./chatAssets";-import { enrichAsset, importFileToProject, isMediaFile, isTextFile } from "./media";+import { enrichAsset, importFileToProject, isMediaFile, isTextFile, renderAudioSpanWav } from "./media";import { frameSink, openMedia, videoTrackOf } from "./mediaRead";import { useEditor } from "./store";+import { formatTime } from "./time";// Turn refs and dropped files into what the hosted models take. Generation// routes read `inputs.images = [{ data, mimeType }]`: stock images upload@@ -197,14 +198,23 @@ export function mediaAddress(url: string): string {}}-async function captureFrame(url: string, duration?: number): Promise<InlineImage> {+async function captureFrame(+ url: string,+ duration?: number,+ opts?: { at?: number; width?: number }+): Promise<InlineImage> {const input = openMedia(url);try {const track = await videoTrackOf(input);if (!track) throw new Error(`Could not read ${mediaAddress(url)} for a reference frame.`);- // Same poster spot the cards show, so the reference matches the preview.- const at = Math.min(1, Math.max(0.1, (duration || (await input.computeDuration()) || 2) / 10));- const width = Math.min(MAX_W, await track.getDisplayWidth());+ const dur = duration || (await input.computeDuration()) || 2;+ // A pinned moment reads exactly there (kept inside the source); otherwise+ // the same poster spot the cards show, so the reference matches the preview.+ const at =+ opts?.at !== undefined+ ? Math.min(Math.max(0, opts.at), Math.max(0, dur - 0.05))+ : Math.min(1, Math.max(0.1, dur / 10));+ const width = Math.min(opts?.width ?? MAX_W, await track.getDisplayWidth());const frame = await frameSink(track, { width }).getCanvas(at);if (!frame) throw new Error("The video has no readable frame.");const canvas = frame.canvas;@@ -218,14 +228,22 @@ async function captureFrame(url: string, duration?: number): Promise<InlineImage}}+/** The length of the SOURCE behind a ref, as far as the ref knows it. A clip+ * ref's `duration` is the clip's own length, not its source file's — times on+ * a clip ref (its `t` pin) are source seconds, so the capture must probe the+ * real source length instead. */+const sourceDuration = (ref: AssetRef): number | undefined =>+ ref.scope === "clip" ? undefined : ref.duration;+/** A single reference image for `ref`: the file itself for images, a captured- * poster frame for videos. Audio and text have no picture and reject. */+ * frame for videos — the pinned moment when the user chose one, the poster+ * spot otherwise. Audio and text have no picture and reject. */export async function refToInlineImage(ref: AssetRef): Promise<InlineImage> {if (ref.kind === "audio" || ref.kind === "text") {throw new Error(`“${ref.name}” has no picture — it can't be a visual reference.`);}if (ref.kind === "image") return blobToInline(await readRefBytes(ref));- return captureFrame(ref.url, ref.duration);+ return captureFrame(ref.url, sourceDuration(ref), ref.t !== undefined ? { at: ref.t } : undefined);}/** Reference images for a whole ref list, in order; skips nothing — a broken@@ -277,26 +295,67 @@ export async function readRefText(ref: AssetRef): Promise<string> {return res.text();}+// A pinned video moment also samples a frame this far to each side, so the+// pick lands even when the user's scrub was a beat off the exact frame.+const PIN_SAMPLE_SPREAD = 1;+const PIN_SAMPLE_W = 640;+// A pinned audio moment reads as a segment reaching this far back and forward+// — enough lead-in to place the moment and enough tail to hear the passage.+const PIN_AUDIO_BACK = 5;+const PIN_AUDIO_FORWARD = 25;++/** The audio around a pinned moment as an inline part, rendered in the+ * browser from the source URL. Null when the span can't be read (no audio+ * track, an unreadable source) — the caller falls back to the whole file. */+async function pinnedAudioSegment(+ ref: AssetRef,+ t: number+): Promise<{ audio: InlineImage; from: number; to: number } | null> {+ const dur = sourceDuration(ref);+ const from = Math.max(0, t - PIN_AUDIO_BACK);+ const to = dur !== undefined ? Math.min(dur, t + PIN_AUDIO_FORWARD) : t + PIN_AUDIO_FORWARD;+ if (to <= from) return null;+ try {+ const audio = await blobToInlineAudio(await renderAudioSpanWav(ref.url, from, to));+ return audio ? { audio, from, to } : null;+ } catch {+ return null;+ }+}+/** A ref list as hosted-Responses content parts, for any Gemini call that* should actually see the attachments: each visual ref contributes a numbered* label plus its picture (image as-is, video by poster frame), each text ref* its contents, and each audio ref its actual sound (so the model can answer* about what's said without touching the project; oversized files fall back- * to a name-only marker). `visuals` returns the pictures in label order- * (`Image 1` = visuals[0]) so a model can pick among them. */+ * to a name-only marker). A ref with a pinned moment (`t`) reads from there+ * instead: a video contributes the pinned frame plus a sampled frame each+ * side, an audio ref the segment around the moment. `visuals` returns the+ * pictures in label order (`Image 1` = visuals[0]) so a model can pick among+ * them. */export async function refsToParts(refs: AssetRef[]): Promise<{ parts: Record<string, unknown>[]; visuals: InlineImage[] }> {const parts: Record<string, unknown>[] = [];const visuals: InlineImage[] = [];+ const pushImage = (image: InlineImage, label: string) => {+ visuals.push(image);+ parts.push({ text: `Image ${visuals.length} — ${label}` });+ parts.push({ type: "input_image", dataBase64: image.data, mimeType: image.mimeType });+ };for (const ref of refs) {if (ref.kind === "audio") {- const audio = await refToInlineAudio(ref);+ const segment = ref.t !== undefined ? await pinnedAudioSegment(ref, ref.t) : null;+ const audio = segment?.audio ?? (await refToInlineAudio(ref));if (!audio) {parts.push({ text: `Attached audio "${ref.name}" (too large to include inline).` });continue;}- parts.push({ text: `Attached audio "${ref.name}":` });+ parts.push({+ text: segment+ ? `Attached audio "${ref.name}" — the segment around the user's pinned moment ${formatTime(ref.t!)} (${formatTime(segment.from)}–${formatTime(segment.to)}):`+ : `Attached audio "${ref.name}":`,+ });parts.push({ type: "input_audio", dataBase64: audio.data, mimeType: audio.mimeType });continue;}@@ -304,14 +363,29 @@ export async function refsToParts(parts.push({ text: `Attached file "${ref.name}":\n${await readRefText(ref)}` });continue;}- const image = await refToInlineImage(ref);- visuals.push(image);- parts.push({- text:- `Image ${visuals.length} — ` +- (ref.kind === "video" ? `a frame of video "${ref.name}":` : `image "${ref.name}":`),- });- parts.push({ type: "input_image", dataBase64: image.data, mimeType: image.mimeType });+ if (ref.kind === "video" && ref.t !== undefined) {+ const t = ref.t;+ const dur = sourceDuration(ref);+ pushImage(+ await refToInlineImage(ref),+ `the frame the user pinned, ${formatTime(t)} into video "${ref.name}":`+ );+ for (const dt of [-PIN_SAMPLE_SPREAD, PIN_SAMPLE_SPREAD]) {+ const at = Math.max(0, dur !== undefined ? Math.min(t + dt, dur) : t + dt);+ // A neighbor clamped onto the pin itself adds nothing.+ if (Math.abs(at - t) < 0.25) continue;+ const image = await captureFrame(ref.url, dur, { at, width: PIN_SAMPLE_W }).catch(+ () => null+ );+ if (!image) continue;+ pushImage(image, `the same video ${formatTime(at)}, sampled near the pinned frame:`);+ }+ continue;+ }+ pushImage(+ await refToInlineImage(ref),+ ref.kind === "video" ? `a frame of video "${ref.name}":` : `image "${ref.name}":`+ );}return { parts, visuals };}diff --git a/site/src/cut/lib/videoGen.ts b/site/src/cut/lib/videoGen.tsindex d0c62fe1..9b489eef 100644--- a/site/src/cut/lib/videoGen.ts+++ b/site/src/cut/lib/videoGen.ts@@ -1,7 +1,7 @@"use client";import { create } from "zustand";-import { addRefOnce, sameRef, type AssetRef } from "./assetRef";+import { addRefOnce, sameRef, upsertRef, type AssetRef } from "./assetRef";import type { StockVideo } from "./stock";import type { VideoAspect } from "./videoModels";@@ -29,6 +29,10 @@ interface VideoGenState {setPrompt: (prompt: string) => void;setAspect: (aspect: VideoAspect) => void;addRef: (ref: AssetRef) => void;+ /** Land a ref's new shape — replaced in place when attached, attached when+ * not — how the moment picker lands a pinned timestamp from a chip or a+ * typed mention. */+ updateRef: (ref: AssetRef) => void;removeRef: (ref: AssetRef) => void;}@@ -43,5 +47,6 @@ export const useVideoGen = create<VideoGenState>((set) => ({setPrompt: (prompt) => set({ prompt }),setAspect: (aspect) => set({ aspect }),addRef: (ref) => set((s) => ({ refs: addRefOnce(s.refs, ref) })),+ updateRef: (ref) => set((s) => ({ refs: upsertRef(s.refs, ref) })),removeRef: (ref) => set((s) => ({ refs: s.refs.filter((r) => !sameRef(r, ref)) })),}));diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 006e6b8a..532b1396 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -298,7 +298,7 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_image",description:- "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).",+ "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 media the render should draw from (the user's attached references, a clip to restyle) — the prompt is recomposed around them; an audio reference contributes what it carries (its speech transcribed, its sound described) to that recomposed prompt. 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 supported shape closest to the project aspect)" },@@ -306,7 +306,7 @@ export const AI_TOOLS: AiToolDef[] = [reference_asset_ids: {type: "array",items: { type: "string" },- description: "Project asset ids (images or videos) to use as visual references",+ description: "Project asset ids to reference — images and videos ride as pictures; audio folds what it carries into the prompt",},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)"),@@ -315,11 +315,11 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_video",description:- "Generate an AI video clip from a text prompt (Donkey's hosted video model: one pass, audio included, 720p, up to ~10s — the model picks the length) — the default for any video ask: \"generate/make a video of/about X\" means ONE clip from this tool, even though it sounds whole. Reach for generate_scene only when they name a narrated multi-shot production (a story, episode, or narrated short). 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 anchors the render on one project image or video: by default the tool first designs the opening frame from it with the image model (that still previews in this chat), then animates that exact frame — so tell the user it designs the frame, then renders. When the user wants the referenced image itself brought to life (\"animate this image/picture\"), pass animate_reference:true — the image becomes the literal first frame, unchanged, and the prompt describes only the motion. A safety-blocked or rejected anchor degrades the render on its own (identity reference, then text-only — the same ladder scene shots walk), so never resubmit a failed render with weaker inputs yourself. The render takes a minute or two and the tool RETURNS as soon as it's started — the clip previews as a live card in this chat when it finishes. 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).",+ "Generate an AI video clip from a text prompt (Donkey's hosted video model: one pass, audio included, 720p, up to ~10s — the model picks the length) — the default for any video ask: \"generate/make a video of/about X\" means ONE clip from this tool, even though it sounds whole. Reach for generate_scene only when they name a narrated multi-shot production (a story, episode, or narrated short). 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 anchors the render on one project asset: for an image or video, by default the tool first designs the opening frame from it with the image model (that still previews in this chat), then animates that exact frame — so tell the user it designs the frame, then renders; for audio, what it carries (speech transcribed, sound described) folds into the prompt instead. When the user wants the referenced image itself brought to life (\"animate this image/picture\"), pass animate_reference:true — the image becomes the literal first frame, unchanged, and the prompt describes only the motion. A safety-blocked or rejected anchor degrades the render on its own (identity reference, then text-only — the same ladder scene shots walk), so never resubmit a failed render with weaker inputs yourself. The render takes a minute or two and the tool RETURNS as soon as it's started — the clip previews as a live card in this chat when it finishes. 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"),aspect: { type: "string", enum: ["16:9", "9:16"], description: "Clip shape (default: the supported shape closest to the project aspect)" },- reference_asset_id: str("One project asset id (image or video) the clip's opening frame is designed from"),+ reference_asset_id: str("One project asset id to reference — an image or video anchors the clip's opening frame; audio folds what it carries into the prompt"),animate_reference: bool("The referenced image IS the opening frame: animate it directly, unchanged, skipping the frame-design step (use when the user says to animate that image)"),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)"),@@ -904,5 +904,5 @@ export function attachedAssetsBlock(refs: unknown[]): string {const clipHint = refs.some((r) => (r as { scope?: string }).scope === "clip")? '\nA "clip" attachment means the user is pointing at that segment of the cut: diagnose with read-only looks (watch_video, listen_audio — never subtitles_generate, which writes captions), then revise the clip in place — regenerate_shot for its sceneShot, edit tools otherwise — without deleting it.': "";- return `\n\n<attached_assets>\nThe user attached these assets to this message; their text may cite one by @handle or @name. Assets with scope "project" are in the open project (ids usable with the editor tools); "clip" assets are clips on the timeline — a video clip's id matches videoTrack in editor_state (a scene-run clip carries its sceneShot number there), an audio clip's (kind "audio") id matches soundtrack; "library" and "stock" assets live outside the project until imported; "file" assets came straight from the user's computer and exist only on this message:\n${JSON.stringify(refs)}${clipHint}\n</attached_assets>`;+ return `\n\n<attached_assets>\nThe user attached these assets to this message; their text may cite one by @handle or @name. Assets with scope "project" are in the open project (ids usable with the editor tools); "clip" assets are clips on the timeline — a video clip's id matches videoTrack in editor_state (a scene-run clip carries its sceneShot number there), an audio clip's (kind "audio") id matches soundtrack; "library" and "stock" assets live outside the project until imported; "file" assets came straight from the user's computer and exist only on this message. An asset with "t" carries a moment the user pinned, in seconds into it — the attached frame (or audio segment) reads from there, and that moment is what they mean by the reference:\n${JSON.stringify(refs)}${clipHint}\n</attached_assets>`;}