Open source CapCut alternative.
TypeScript
feat(site): chat mentions render timeline entities as atomic pills
David Le3ad9f838eba0
diff --git a/site/src/app/globals.css b/site/src/app/globals.cssindex 4ab1f9eb..e592e314 100644--- a/site/src/app/globals.css+++ b/site/src/app/globals.css@@ -171,3 +171,16 @@ html.app-surface {@apply bg-background font-sans;}}++/* The mention pill's stand-in caret: the real one blinks in the textarea+ underneath the pill cover's left edge. */+@keyframes mention-caret {+ 0%,+ 49% {+ opacity: 1;+ }+ 50%,+ 100% {+ opacity: 0;+ }+}diff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsxindex 59ed7d86..bb90ac7f 100644--- a/site/src/cut/components/AssetRefs.tsx+++ b/site/src/cut/components/AssetRefs.tsx@@ -18,8 +18,9 @@ import { formatTime } from "@/cut/lib/time";import { clipLen, getClipSpans, useEditor } from "@/cut/lib/store";import { playheadAt } from "@/cut/lib/playhead";import { AudioPillSurface } from "@/cut/components/AudioPanel";-import { ScrubValue, parseTimeInput } from "@/cut/components/ScrubValue";-import { Slider } from "@/components/ui/slider";+import { entityGlyph } from "@/cut/components/entityIcons";+import { parseTimeInput } from "@/cut/components/ScrubValue";+import { ValueSlider } from "@/cut/components/ValueSlider";import { cn } from "@/lib/utils";// Shared UI for asset references: the preview thumbnail, attachment chips,@@ -87,7 +88,17 @@ export function RefThumb({ item, className }: { item: AssetRef; className?: stri) : 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">- <FileText className="size-4.5" />+ {item.preview ? (+ // eslint-disable-next-line @next/next/no-img-element -- refs point at engine/static files, not Next-optimizable images+ <img+ src={item.preview}+ alt={item.name}+ loading="lazy"+ className="size-full object-contain p-1"+ />+ ) : (+ (entityGlyph(item, "size-4.5") ?? <FileText className="size-4.5" />)+ )}</div>) : (<AudioPillSurface peaks={peaks} className="size-full rounded-none" />@@ -281,6 +292,26 @@ export function RefTokenChip({peekSide?: "top" | "bottom";}) {const [peek, setPeek] = useState(false);+ // Entity refs have no media to peek at and no card to jump to — the pill+ // itself, icon plus name, is the whole story.+ if (item.scope === "entity") {+ return (+ <span+ className={cn(+ "ref-token inline-flex items-center gap-1 rounded-md px-1 align-middle font-mono text-[11px]",+ onDark ? "bg-white/15 text-[#8ec7ff]" : "bg-[#0a84ff]/10 text-[#0a84ff]"+ )}+ >+ {item.preview ? (+ // eslint-disable-next-line @next/next/no-img-element -- refs point at engine/static files, not Next-optimizable images+ <img src={item.preview} alt="" className="size-3 shrink-0 object-contain" />+ ) : (+ entityGlyph(item, cn("size-2.5 shrink-0", item.keyTrack === "mask" && "text-[#ff9f0a]"))+ )}+ {item.name}+ </span>+ );+ }return (<spanclassName="relative inline-block"@@ -441,11 +472,13 @@ function RefChip({the wide chip stays within the composer. Composer chips (onUpdate)are inert surfaces — hover carries the moment card; click-to-revealbelongs to the read-only rows on past messages. */}- {onUpdate ? (- <RefThumb- item={item}- className={item.kind === "audio" ? "h-12 w-44 max-w-full" : thumbClassName}- />+ {onUpdate || item.scope === "entity" ? (+ <div title={item.scope === "entity" ? item.name : undefined}>+ <RefThumb+ item={item}+ className={item.kind === "audio" ? "h-12 w-44 max-w-full" : thumbClassName}+ />+ </div>) : (<buttontype="button"@@ -487,7 +520,8 @@ function RefChip({<RefMomentPicker item={item} side={peekSide} offsetX={cardDx} onChange={onUpdate} /></div>) : (- hover && <RefPeek item={item} side={peekSide} />+ // Entity refs have nothing more to show than the chip itself.+ hover && item.scope !== "entity" && <RefPeek item={item} side={peekSide} />)}<buttonaria-label={`Remove ${item.name}`}@@ -525,6 +559,36 @@ function playheadMoment(ref: AssetRef): number | null {return a ? a.in + (now - a.start) : null;}+/** The timeline selection the last pill click made, so dismissing the pick in+ * chat can take it back without touching a selection made elsewhere. */+let lastReveal: { kind: string; id: string } | null = null;++/** Select the entity a pill points at, so the timeline highlights and reveals+ * it. The ref id carries the timeline identity (`overlay:<id>`, `cue:<id>`,+ * `key:clip:<id>:pose:<n>`, …). */+function revealEntity(ref: AssetRef) {+ const [kind, a, b, c, d] = ref.id.split(":");+ const st = useEditor.getState();+ if (kind === "overlay" || kind === "cue" || kind === "transition") {+ st.select({ kind, id: a });+ lastReveal = { kind, id: a };+ return;+ }+ if (kind !== "key") return;+ const ownerKind = a === "clip" ? "clip" : "overlay";+ const owner =+ ownerKind === "clip"+ ? st.clips.find((x) => x.id === b)+ : st.overlays.find((x) => x.id === b);+ const track = c === "mask" ? "mask" : "pose";+ const keys = track === "pose" ? owner?.kf : owner?.mask?.kf;+ const key = keys ? [...keys].sort((x, y) => x.t - y.t)[Number(d)] : undefined;+ st.select({ kind: ownerKind, id: b });+ lastReveal = { kind: ownerKind, id: b };+ if (key)+ useEditor.setState({ selectedKey: { kind: ownerKind, id: b, t: key.t, track } });+}+/** 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. */@@ -560,17 +624,10 @@ function MomentControls({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+ <ValueSlider+ label="Pinned moment"+ sliderClassName="min-w-0 flex-1"+ valueClassName="shrink-0 text-muted-foreground"value={t}min={lo}max={Math.max(hi, lo + 0.1)}@@ -578,10 +635,8 @@ function MomentControls({keyStep={1}format={formatTime}parse={parseTimeInput}- onScrub={apply}+ onDraft={apply}onCommit={apply}- label="Pinned moment timestamp"- className="shrink-0 text-muted-foreground"/></div>);@@ -796,6 +851,145 @@ function mentionAtCaret(value: string, caret: number): { start: number; query: sreturn { start: at, query };}+/** One resolved mention in the composer mirror. Entity pills paint over the+ * raw token with the entity's icon (or the sticker's own art) and name — the+ * token glyphs underneath keep their exact layout, so the textarea's caret+ * math never drifts. The overlay steps aside while the caret sits inside the+ * token (the user is editing it) and when the token wraps across lines (an+ * inline overlay can only cover one line box). */+function MentionPill({+ item,+ text,+ editing,+ selected,+ caretAtStart,+ bleedL,+ bleedR,+ pinnable,+ onPin,+ onSelectToken,+}: {+ item: AssetRef;+ text: string;+ editing: boolean;+ /** The selection covers this token — the pill is picked whole. */+ selected: boolean;+ /** A collapsed caret sits right before the token — the cover would hide+ * the real one, so the pill paints its own on top. */+ caretAtStart: boolean;+ bleedL: boolean;+ bleedR: boolean;+ pinnable: boolean;+ onPin: (ref: AssetRef, el: HTMLElement) => void;+ /** Select the whole token in the textarea. */+ onSelectToken: () => void;+}) {+ const spanRef = useRef<HTMLSpanElement>(null);+ const coverRef = useRef<HTMLSpanElement>(null);+ const [wrapped, setWrapped] = useState(false);+ // A cover that needs more room than the raw token has would truncate the+ // name; once it measures too wide for this token text it stays raw.+ const [clippedFor, setClippedFor] = useState<string | null>(null);+ // Measured every render: wrapping depends on everything before the token.+ useLayoutEffect(() => {+ setWrapped((spanRef.current?.getClientRects().length ?? 1) > 1);+ const cover = coverRef.current;+ if (cover && cover.scrollWidth > cover.clientWidth + 1) setClippedFor(text);+ });+ const glyph = entityGlyph(+ item,+ cn(+ "relative size-[0.9em] shrink-0",+ // Mask keyframes carry the timeline's amber; everything else the pill blue.+ item.keyTrack === "mask" ? "text-[#ff9f0a]" : "text-[#0a84ff]"+ )+ );+ const rich =+ item.scope === "entity" &&+ !editing &&+ !wrapped &&+ clippedFor !== text &&+ !!(glyph || item.preview);+ // Entity pills act as one object: a click selects the whole token, so the+ // caret never lands inside and typing replaces it in one stroke.+ const atomic = item.scope === "entity" && !pinnable;+ return (+ <span+ ref={spanRef}+ 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",+ rich && "relative",+ // The cover spans the padding box, so a bleed under it would paint+ // over the character typed right after the token. The cover draws its+ // own pill, sized to the token alone; padding and margin cancel each+ // other, so dropping both leaves the text metrics untouched.+ bleedL && !rich && "pl-[0.15em] -ml-[0.15em]",+ bleedR && !rich && "pr-[0.15em] -mr-[0.15em]",+ pinnable && "pointer-events-auto cursor-pointer hover:bg-[#0a84ff]/25",+ atomic && "pointer-events-auto cursor-default"+ )}+ title={pinnable ? `${item.name} — click to pin the moment` : undefined}+ // mousedown, not click: preventDefault keeps focus in the textarea.+ onMouseDown={+ pinnable+ ? (e) => {+ e.preventDefault();+ onPin(item, e.currentTarget);+ }+ : atomic+ ? (e) => {+ e.preventDefault();+ onSelectToken();+ revealEntity(item);+ }+ : undefined+ }+ >+ {text}+ {rich && (+ // Opaque cover over the raw token: the composer's background, the+ // pill tint on top, then icon + name. It stretches a little past the+ // inline box vertically so the art keeps a visible margin.+ <span+ ref={coverRef}+ className={cn(+ "pointer-events-none absolute inset-x-0 -inset-y-[0.1em] flex items-center overflow-hidden rounded-[4px] bg-background whitespace-nowrap",+ // Sticker art bleeds to the pill's own edges; icons sit inset.+ item.preview ? "gap-[0.25em]" : "gap-[0.3em] pl-[0.25em]"+ )}+ >+ <span className="absolute inset-0 rounded-[4px] bg-[#0a84ff]/12" />+ {item.preview ? (+ // eslint-disable-next-line @next/next/no-img-element -- refs point at engine/static files, not Next-optimizable images+ <img+ src={item.preview}+ alt=""+ className="relative h-full w-[1.05em] shrink-0 rounded-l-[4px] object-cover"+ />+ ) : (+ glyph+ )}+ <span className="relative text-foreground">{item.name}</span>+ {/* Picked whole: the same pill with a blue ring, painted last so it+ rides over the full-bleed art. */}+ {selected && (+ <span className="absolute inset-0 rounded-[4px] ring-[1.5px] ring-[#0a84ff] ring-inset" />+ )}+ </span>+ )}+ {rich && caretAtStart && (+ // The mirror's stand-in for the real caret, which blinks in the+ // textarea underneath the cover's left edge. Mounting on caret+ // arrival restarts the animation, matching the browser's own reset.+ <span className="pointer-events-none absolute -inset-y-[0.1em] -left-px w-[1.5px] animate-[mention-caret_1.1s_steps(1)_infinite] bg-foreground" />+ )}+ </span>+ );+}+/*** Textarea with `@` autocomplete over the given candidates — matches short* handles (`@v2`) and names, and inserts the handle token when there is one.@@ -853,6 +1047,10 @@ export function MentionTextarea({const rootRef = useRef<HTMLDivElement>(null);const backdropRef = useRef<HTMLDivElement>(null);const [caret, setCaret] = useState(0);+ // Selection end and focus, so a pill knows when the user is editing inside+ // its token and should see the raw text.+ const [selEnd, setSelEnd] = useState(0);+ const [focused, setFocused] = useState(false);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). */@@ -891,9 +1089,52 @@ export function MentionTextarea({for (const k of [...autoPinned.current]) if (!present.has(k)) autoPinned.current.delete(k);}, [value, candidates, attachedRefs, onUpsertRef]);+ // Mirror segments with their character offsets, so a pill can tell when+ // the caret sits inside its token.+ const mirrorSegs = useMemo(+ () =>+ highlightMentions(value, candidates).reduce<+ { text: string; ref: AssetRef | null; start: number }[]+ >((acc, seg) => {+ const prev = acc[acc.length - 1];+ acc.push({ ...seg, start: prev ? prev.start + prev.text.length : 0 });+ return acc;+ }, []),+ [value, candidates]+ );++ // A pill cover is one box, so its token must move between lines whole —+ // wrapped mid-token it falls back to raw text. Resolved entity tokens ride+ // no-break spaces (pasted or typed ones get rewritten here); the swap keeps+ // the length, so every caret offset survives and the write settles.+ useEffect(() => {+ let next = value;+ for (const m of mirrorSegs) {+ if (m.ref?.scope !== "entity" || !m.text.includes(" ")) continue;+ next =+ next.slice(0, m.start) ++ m.text.replace(/ /g, " ") ++ next.slice(m.start + m.text.length);+ }+ if (next === value) return;+ const el = taRef.current;+ const s = el?.selectionStart ?? null;+ const e = el?.selectionEnd ?? null;+ onChange(next);+ if (el && s !== null)+ requestAnimationFrame(() => el.setSelectionRange(s, e ?? s));+ }, [mirrorSegs, value, onChange]);+const mention = useMemo(() => mentionAtCaret(value, caret), [value, caret]);const matches = useMemo(() => {if (!mention || dismissed === mention.start) return [];+ // A caret strictly inside an intact, resolved token is a click on the+ // pill — the mention is complete, and offering lookalike suggestions for+ // its half-read query would misdirect it.+ const inResolved = mirrorSegs.some(+ (seg) => seg.ref && caret > seg.start && caret < seg.start + seg.text.length+ );+ if (inResolved) return [];const q = mention.query.toLowerCase();// Best match first, not list order: a typed handle prefix ("c" → c1, c2)// beats a name prefix, which beats a substring hit anywhere in the name —@@ -905,13 +1146,17 @@ export function MentionTextarea({const name = c.name.toLowerCase();return name.startsWith(q) ? 1 : name.includes(q) ? 2 : 3;};+ // Entity refs (keyframes, transitions, cues, elements) reach a prompt by+ // ⌘C copy-paste; the popover offers media and clips, so a long subtitle+ // track never floods the list.return candidates+ .filter((c) => c.scope !== "entity").map((c) => ({ c, r: rank(c) })).filter((x) => x.r < 3).sort((a, b) => a.r - b.r).slice(0, 8).map((x) => x.c);- }, [mention, dismissed, candidates]);+ }, [mention, dismissed, candidates, mirrorSegs, caret]);const open = matches.length > 0;// Each keystroke re-ranks the list, so a highlight chosen under a previous// query derives back to the best (first) match instead of holding a stale@@ -922,9 +1167,64 @@ export function MentionTextarea({const syncCaret = () => {const el = taRef.current;- if (el) setCaret(el.selectionStart ?? 0);+ if (!el) return;+ let start = el.selectionStart ?? 0;+ let end = el.selectionEnd ?? start;+ // Entity tokens are atomic: the caret never rests inside one. A collapsed+ // caret arriving inside (arrow keys) picks the whole token; a range+ // endpoint inside grows to the token edge. The write below echoes another+ // select event, which re-enters here and settles as a no-op.+ const inside = (pos: number) =>+ mirrorSegs.find(+ (m) => m.ref?.scope === "entity" && pos > m.start && pos < m.start + m.text.length+ );+ if (start === end) {+ const seg = inside(start);+ if (seg) {+ start = seg.start;+ end = seg.start + seg.text.length;+ }+ } else {+ start = inside(start)?.start ?? start;+ const seg = inside(end);+ if (seg) end = seg.start + seg.text.length;+ }+ if (start !== el.selectionStart || end !== el.selectionEnd) el.setSelectionRange(start, end);+ setCaret(start);+ setSelEnd(end);+ };++ /** Select a whole token: clicking an entity pill picks it as one object. */+ const selectToken = (start: number, len: number) => {+ const el = taRef.current;+ if (!el) return;+ el.focus();+ el.setSelectionRange(start, start + len);+ setCaret(start);+ setSelEnd(start + len);};+ /** Some entity pill is picked whole right now. */+ const anyPicked =+ focused &&+ selEnd > caret &&+ mirrorSegs.some(+ (m) => m.ref?.scope === "entity" && caret === m.start && selEnd === m.start + m.text.length+ );++ // Dismissing a pick inside the composer (arrowing away, typing over it,+ // clicking elsewhere in the text) takes back the timeline selection that+ // pick made. A blur keeps it — leaving for the timeline or another panel+ // is working with the selection, and clearing it there would fight the+ // click that took focus.+ useEffect(() => {+ if (anyPicked || !focused || !lastReveal) return;+ const st = useEditor.getState();+ const cur = st.selection;+ if (cur && cur.kind === lastReveal.kind && cur.id === lastReveal.id) st.select(null);+ lastReveal = null;+ }, [anyPicked, focused]);+/** 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). */@@ -1005,7 +1305,10 @@ export function MentionTextarea({taRef.current = el;if (inputRef) inputRef.current = el;}}- className={cn(className, "relative block bg-transparent")}+ // While a pill is picked whole, the pill's ring is the selection+ // highlight — the browser's own selection paint would spill out+ // around the cover as a bare blue rectangle.+ className={cn(className, "relative block bg-transparent", anyPicked && "selection:bg-transparent")}rows={rows}placeholder={placeholder}value={value}@@ -1013,7 +1316,10 @@ export function MentionTextarea({setDismissed(null);onChange(e.target.value);setCaret(e.target.selectionStart ?? 0);+ setSelEnd(e.target.selectionEnd ?? e.target.selectionStart ?? 0);}}+ onFocus={() => setFocused(true)}+ onBlur={() => setFocused(false)}onScroll={(e) => {const bd = backdropRef.current;if (bd) {@@ -1023,14 +1329,40 @@ export function MentionTextarea({}}onSelect={syncCaret}onPaste={(e) => {- if (!onPasteFiles) return;- const files = Array.from(e.clipboardData.items)- .filter((item) => item.kind === "file")- .map((item) => item.getAsFile())- .filter((f): f is File => f !== null);- if (files.length === 0) return;+ if (onPasteFiles) {+ const files = Array.from(e.clipboardData.items)+ .filter((item) => item.kind === "file")+ .map((item) => item.getAsFile())+ .filter((f): f is File => f !== null);+ if (files.length > 0) {+ e.preventDefault();+ onPasteFiles(files);+ return;+ }+ }+ // A token pasted flush against a neighbor never resolves — the+ // quote swallows the boundary. Restore the missing space on+ // whichever side needs one.+ const text = e.clipboardData.getData("text/plain");+ if (!text) return;+ const el = e.currentTarget;+ const s = el.selectionStart ?? 0;+ const sEnd = el.selectionEnd ?? s;+ const needL = text.startsWith("@") && /\S/.test(value[s - 1] ?? "");+ const needR = /\S$/.test(text) && (value[sEnd] ?? "") === "@";+ if (!needL && !needR) return;e.preventDefault();- onPasteFiles(files);+ setDismissed(null);+ const insert = (needL ? " " : "") + text + (needR ? " " : "");+ onChange(value.slice(0, s) + insert + value.slice(sEnd));+ const nc = s + (needL ? 1 : 0) + text.length;+ requestAnimationFrame(() => {+ const ta = taRef.current;+ if (!ta) return;+ ta.setSelectionRange(nc, nc);+ setCaret(nc);+ setSelEnd(nc);+ });}}onKeyDown={(e) => {e.stopPropagation();@@ -1052,6 +1384,30 @@ export function MentionTextarea({onRemoveLastRef();return;}+ // Deleting into an entity token picks it whole first; the next+ // press removes it in one stroke, so a half-eaten token never+ // degenerates into raw text.+ if (+ (e.key === "Backspace" || e.key === "Delete") &&+ !e.metaKey &&+ !e.altKey &&+ !e.ctrlKey+ ) {+ const el = e.currentTarget;+ const pos = el.selectionStart ?? 0;+ if (pos === (el.selectionEnd ?? pos)) {+ const seg = mirrorSegs.find(+ (m) =>+ m.ref?.scope === "entity" &&+ pos === (e.key === "Backspace" ? m.start + m.text.length : m.start)+ );+ if (seg) {+ e.preventDefault();+ selectToken(seg.start, seg.text.length);+ return;+ }+ }+ }if (open) {if (e.key === "ArrowDown" || e.key === "ArrowUp") {e.preventDefault();@@ -1098,40 +1454,41 @@ export function MentionTextarea({"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");+ {mirrorSegs.map((seg, i) => {+ if (!seg.ref) return <span key={i}>{seg.text}</span>;// 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+ !!mirrorSegs[gap] &&+ !mirrorSegs[gap].ref &&+ /^\s$/.test(mirrorSegs[gap].text) &&+ !!mirrorSegs[other]?.ref;+ const end = seg.start + seg.text.length;+ // Raw text shows only while a range endpoint rests strictly inside+ // the token; entity endpoints normalize to the token edges, so an+ // entity pill stays covered through any selection sweep (⌘A too).+ const editing =+ focused &&+ ((caret > seg.start && caret < end) || (selEnd > seg.start && selEnd < end));+ // The selection covers the whole token — a pill click or a sweep+ // across it — and the pill wears its ring.+ const covered = focused && selEnd > caret && caret <= seg.start && selEnd >= end;+ return (+ <MentionPillkey={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+ item={seg.ref}+ text={seg.text}+ editing={editing}+ selected={covered}+ caretAtStart={focused && caret === seg.start && selEnd === seg.start}+ bleedL={!facing(i - 1, i - 2)}+ bleedR={!facing(i + 1, i + 2)}+ pinnable={+ !!onUpsertRef && (seg.ref.kind === "video" || seg.ref.kind === "audio")}- >- {seg.text}- </span>- ) : (- <span key={i}>{seg.text}</span>+ onPin={openPin}+ onSelectToken={() => selectToken(seg.start, seg.text.length)}+ />);})}</div>diff --git a/site/src/cut/components/entityIcons.ts b/site/src/cut/components/entityIcons.tsnew file mode 100644index 00000000..47290206--- /dev/null+++ b/site/src/cut/components/entityIcons.ts@@ -0,0 +1,63 @@+import { createElement, type ReactNode } from "react";+import {+ Captions,+ Circle,+ Diamond,+ Heart,+ Hexagon,+ Minus,+ MoveRight,+ Sparkles,+ Square,+ Star,+ Sticker,+ Triangle,+ Type,+ UnfoldHorizontal,+ type LucideIcon,+} from "lucide-react";+import type { AssetRef } from "@/cut/lib/assetRef";+import type { ShapeKind } from "@/cut/lib/types";++/** The glyph a shape wears on its timeline chip and mention pill. */+export const SHAPE_CHIP_ICONS: Record<ShapeKind, LucideIcon> = {+ rect: Square,+ ellipse: Circle,+ triangle: Triangle,+ diamond: Diamond,+ star: Star,+ heart: Heart,+ hexagon: Hexagon,+ line: Minus,+ arrow: MoveRight,+};++/** The entity's icon as a rendered element, sized by `className`. Null for+ * media refs — those show the media itself. */+export function entityGlyph(ref: AssetRef, className: string): ReactNode {+ const icon = entityIcon(ref);+ return icon ? createElement(icon, { className }) : null;+}++/** The icon an entity ref's pill and chip lead with. Null for media refs —+ * those show the media itself. */+export function entityIcon(ref: AssetRef): LucideIcon | null {+ switch (ref.entityKind) {+ case "title":+ return Type;+ case "shape":+ return SHAPE_CHIP_ICONS[ref.shapeKind ?? "rect"];+ case "sticker":+ return Sticker;+ case "effect":+ return Sparkles;+ case "transition":+ return UnfoldHorizontal;+ case "cue":+ return Captions;+ case "keyframe":+ return Diamond;+ default:+ return null;+ }+}diff --git a/site/src/cut/lib/assetRef.test.ts b/site/src/cut/lib/assetRef.test.tsnew file mode 100644index 00000000..f1a76753--- /dev/null+++ b/site/src/cut/lib/assetRef.test.ts@@ -0,0 +1,175 @@+import { describe, expect, test } from "bun:test";+import { entityRefs, selectionRefTokens, type EntitySources } from "./assetRef";+import type { MediaAsset, Overlay, VideoClip } from "./types";++const asset = (id: string): MediaAsset =>+ ({ id, name: `${id}.mp4`, type: "video", url: `/media/${id}.mp4`, duration: 10 }) as MediaAsset;++const clip = (id: string, start: number, patch: Partial<VideoClip> = {}): VideoClip => ({+ id,+ assetId: id,+ track: 0,+ start,+ in: 0,+ out: 4,+ muted: false,+ ...patch,+});++const key = (t: number) => ({ t, x: 0.5, y: 0.5, scale: 1, rotation: 0, opacity: 1 });++const title = (id: string, start: number, patch: Partial<Overlay> = {}): Overlay =>+ ({+ id,+ start,+ end: start + 3,+ x: 0.5,+ y: 0.5,+ text: "Hello",+ size: 64,+ font: "sf",+ weight: 700,+ color: "#fff",+ ...patch,+ }) as Overlay;++const sources = (patch: Partial<EntitySources> = {}): EntitySources => ({+ clips: [],+ assets: [],+ overlays: [],+ transitions: [],+ subtitles: { cues: [] },+ ...patch,+});++describe("entityRefs", () => {+ test("elements name by content and carry ids in the payload", () => {+ const refs = entityRefs(+ sources({+ assets: [+ {+ id: "img-1",+ name: "make the clothes blue.png",+ type: "image",+ url: "/media/img-1.png",+ } as MediaAsset,+ ],+ overlays: [+ title("ov-b", 4, { text: "Snap Test" }),+ title("ov-a", 0),+ title("sh-1", 2, { kind: "shape", shape: "rect" } as Partial<Overlay>),+ title("fx-1", 5, { kind: "effect", effect: "vhs" } as Partial<Overlay>),+ title("st-1", 6, { kind: "sticker", assetId: "img-1" } as Partial<Overlay>),+ ],+ transitions: [{ id: "tr-1", start: 3, seconds: 0.5, style: "crossfade" }],+ subtitles: { cues: [{ id: "cue-1", start: 1, end: 2, text: "hi there" }] },+ })+ );+ const names = refs.map((r) => r.name);+ expect(names).toEqual([+ "Hello",+ "Rectangle",+ "Snap Test",+ "VHS",+ "Sticker",+ "transition 1",+ "cue 1",+ ]);+ // A sticker names by kind — its prompt-shaped asset name stays out of the+ // token — and carries its art for the pill.+ const st = refs.find((r) => r.name === "Sticker")!;+ expect(st.entityKind).toBe("sticker");+ expect(st.preview).toBe("/media/img-1.png");+ const t1 = refs.find((r) => r.name === "Hello")!;+ expect(t1.id).toBe("overlay:ov-a");+ expect(t1.kind).toBe("text");+ expect(decodeURIComponent(t1.url)).toContain("id ov-a");+ expect(decodeURIComponent(t1.url)).toContain('Text: "Hello"');+ expect(t1.entityKind).toBe("title");+ const rect = refs.find((r) => r.name === "Rectangle")!;+ expect(rect.entityKind).toBe("shape");+ expect(rect.shapeKind).toBe("rect");+ });++ test("names number in timeline order only on collision", () => {+ const refs = entityRefs(+ sources({+ overlays: [+ title("sh-b", 4, { kind: "shape", shape: "rect" } as Partial<Overlay>),+ title("sh-a", 0, { kind: "shape", shape: "rect" } as Partial<Overlay>),+ title("sh-c", 2, { kind: "shape", shape: "star" } as Partial<Overlay>),+ title("ov-a", 6, { text: " " }),+ ],+ })+ );+ expect(refs.map((r) => r.name)).toEqual(["Rectangle 1", "Star", "Rectangle 2", "title"]);+ expect(refs.find((r) => r.name === "Rectangle 1")!.id).toBe("overlay:sh-a");+ });++ test("keyframes number per track under their parent's display name", () => {+ const refs = entityRefs(+ sources({+ clips: [clip("c-a", 0, { kf: [key(1), key(0.2)] })],+ assets: [asset("c-a")],+ overlays: [+ title("ov-a", 0, {+ kf: [key(0.5)],+ mask: { kind: "circle", kf: [{ t: 0, x: 0, y: 0, w: 0.5, h: 0.5, rotation: 0, feather: 0 }] },+ } as Partial<Overlay>),+ ],+ })+ );+ const names = refs.map((r) => r.name);+ expect(names).toContain("kf1 c1");+ expect(names).toContain("kf2 c1");+ expect(names).toContain("kf Hello");+ expect(names).toContain("mask kf Hello");+ expect(refs.find((r) => r.name === "kf Hello")!.keyTrack).toBe("pose");+ expect(refs.find((r) => r.name === "mask kf Hello")!.keyTrack).toBe("mask");+ // Keys sort by time: the 0.2s key is keyframe 1.+ const k1 = refs.find((r) => r.name === "kf1 c1")!;+ expect(k1.id).toBe("key:clip:c-a:pose:0");+ expect(decodeURIComponent(k1.url)).toContain("At 0.20s into the clip");+ expect(decodeURIComponent(k1.url)).toContain("clip id c-a");+ });+});++describe("selectionRefTokens", () => {+ const base = {+ clips: [clip("c-a", 0, { kf: [key(0.2), key(1)] })],+ assets: [asset("c-a")],+ audioClips: [],+ overlays: [title("ov-a", 0)],+ transitions: [{ id: "tr-1", start: 3, seconds: 0.5, style: "crossfade" as const }],+ subtitles: { cues: [{ id: "cue-1", start: 1, end: 2, text: "hi" }] },+ selection: null,+ multiSelection: [],+ selectedKey: null,+ };++ test("a picked keyframe wins and tokens by its ordinal under the parent", () => {+ const token = selectionRefTokens({+ ...base,+ selectedKey: { kind: "clip", id: "c-a", t: 1, track: "pose" },+ });+ // Entity tokens carry no-break spaces so the composer pill never wraps.+ expect(token).toBe('@"kf2 c1"');+ });++ test("selected clips, elements, transitions, and cues each token", () => {+ const token = selectionRefTokens({+ ...base,+ multiSelection: [+ { kind: "clip", id: "c-a" },+ { kind: "overlay", id: "ov-a" },+ { kind: "transition", id: "tr-1" },+ { kind: "cue", id: "cue-1" },+ ],+ });+ expect(token).toBe('@c1 @"Hello" @"transition 1" @"cue 1"');+ });++ test("nothing resolvable yields null", () => {+ expect(selectionRefTokens({ ...base, selection: { kind: "clip", id: "gone" } })).toBe(null);+ });+});diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex ddd775b2..0af5812b 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -6,8 +6,25 @@ import { fetchLibrary, libraryMediaUrl, type LibraryAsset } from "./library";import { stockAspectDims, stockTitle, type StockImage, type StockMusic, type StockVideo } from "./stock";import { STOCK_IMAGES } from "./stockManifest";import { STOCK_VIDEOS } from "./stockVideoManifest";+import { EFFECT_LABELS } from "@donkeycut/effects-kit";import { clipLen, getClipSpans, useEditor } from "./store";-import type { AudioClip, MediaAsset } from "./types";+import {+ isEffectOverlay,+ isShapeOverlay,+ isStickerOverlay,+ isTextOverlay,+ SHAPE_LABELS,+ type ShapeKind,+} from "./types";+import type {+ AudioClip,+ MediaAsset,+ Overlay,+ Selection,+ SubtitleCue,+ TimelineTransition,+ VideoClip,+} from "./types";// One reference model for every piece of media in the app. A ref names an// asset wherever it lives — the open project, the shared library, the bundled@@ -29,8 +46,14 @@ import type { AudioClip, MediaAsset } from "./types";* composer) — it lives only in the composer's state, never in a catalog.* "clip" names a clip on the timeline — a video-track clip or a soundtrack* clip (id = the clip id, url = its source media), so chat can talk about- * segments of the cut, not just assets. */-export type AssetRefScope = "project" | "library" | "stock" | "file" | "clip";+ * segments of the cut, not just assets.+ * "entity" names a timeline object with no media of its own — a title, shape,+ * sticker or effect element, a transition bar, a subtitle cue, or one keyframe+ * on an element's or clip's pose/mask track. Its `id` is an internal composite+ * (`overlay:<id>`, `key:clip:<id>:pose:<index>`, …) and its `url` is a+ * data: text payload describing the entity — the parent's id included — so a+ * mention lands in chat as grounded text the tools can act on. */+export type AssetRefScope = "project" | "library" | "stock" | "file" | "clip" | "entity";export type AssetRefKind = "video" | "audio" | "image" | "text";export interface AssetRef {@@ -60,6 +83,15 @@ export interface AssetRef {* media order by `useRefCandidates`. Derived per session, not persisted —* display surfaces re-resolve it live so a stale copy never shows. */handle?: string;+ /** Which timeline entity an `"entity"` ref names — picks the pill's icon. */+ entityKind?: "title" | "shape" | "sticker" | "effect" | "transition" | "cue" | "keyframe";+ /** The shape element's kind, for the pill's per-shape icon. */+ shapeKind?: ShapeKind;+ /** Which track a keyframe ref rides — mask keys color their pill amber to+ * match the timeline's diamonds. */+ keyTrack?: "pose" | "mask";+ /** Tiny image the pill shows instead of an icon — the sticker's own art. */+ preview?: string;}export const refFromAsset = (a: MediaAsset): AssetRef => ({@@ -160,6 +192,10 @@ export function liveRefUrl(scope: AssetRefScope, id: string, url: string): strins.audioClips.find((c) => c.id === id)?.assetId;return s.assets.find((a) => a.id === assetId)?.url ?? url;}+ // An entity payload describes live state (times, pose values), so re-derive+ // it; an entity that no longer resolves keeps the description it was+ // copied with.+ if (scope === "entity") return entityRefs(s).find((r) => r.id === id)?.url ?? url;return url;}@@ -439,10 +475,231 @@ export function audioClipRefs(audioClips: AudioClip[], assets: MediaAsset[]): As});}+/** What `entityRefs` reads; the editor store state satisfies it. */+export interface EntitySources {+ clips: VideoClip[];+ assets: MediaAsset[];+ overlays: Overlay[];+ transitions: TimelineTransition[];+ subtitles: { cues: SubtitleCue[] };+}++const sec = (t: number) => `${t.toFixed(2)}s`;++const entityRef = (+ id: string,+ name: string,+ payload: string,+ extra?: Partial<AssetRef>+): AssetRef => ({+ scope: "entity",+ id,+ name,+ kind: "text",+ url: `data:text/plain;charset=utf-8,${encodeURIComponent(payload)}`,+ ...extra,+});++/** One element's keyframes as refs. `parent` is the display name mentions use+ * ("c3", "Snap Test"); names stay short — "kf c3", numbered only when the+ * track holds more than one key ("kf2 c3"). The payload carries the parent's+ * real id, so chat edits land through the parent's keyframe track. */+function keyRefs(+ ownerKind: "clip" | "overlay",+ ownerId: string,+ parent: string,+ start: number,+ keys: { t: number; x?: number; y?: number; scale?: number; rotation?: number; opacity?: number }[] | undefined,+ track: "pose" | "mask"+): AssetRef[] {+ if (!keys || keys.length === 0) return [];+ const sorted = [...keys].sort((a, b) => a.t - b.t);+ const label = track === "pose" ? "kf" : "mask kf";+ return sorted.map((k, i) => {+ const pose =+ track === "pose"+ ? ` Pose: x ${(k.x ?? 0).toFixed(3)}, y ${(k.y ?? 0).toFixed(3)}, scale ${(k.scale ?? 1).toFixed(2)}, rotation ${(k.rotation ?? 0).toFixed(1)}°, opacity ${(k.opacity ?? 1).toFixed(2)}.`+ : "";+ return entityRef(+ `key:${ownerKind}:${ownerId}:${track}:${i}`,+ sorted.length === 1 ? `${label} ${parent}` : `${label}${i + 1} ${parent}`,+ `keyframe ${i + 1} of ${sorted.length} on the ${track} track of ${parent} (${ownerKind} id ${ownerId}). ` ++ `At ${sec(k.t)} into the ${ownerKind} (timeline ${sec(start + k.t)}).${pose} ` ++ `Edit it by rewriting the parent ${ownerKind}'s ${track} keyframe track.`,+ { entityKind: "keyframe", keyTrack: track }+ );+ });+}++/** A readable name for an element, the same one its timeline chip shows: a+ * title's own text, a shape's or effect's label, a sticker's asset name. The+ * kind word when nothing better exists. Cleaned to survive a mention token+ * (no quotes or newlines) and kept short. */+function overlayBaseName(o: Overlay, fallback: string): string {+ // A sticker's identity is its art — the pill shows the thumbnail — and its+ // asset name is often a generation prompt, which would collide with the+ // media asset carrying the same name. It names by kind.+ const raw = isTextOverlay(o)+ ? o.text+ : isShapeOverlay(o)+ ? SHAPE_LABELS[o.shape]+ : isEffectOverlay(o)+ ? EFFECT_LABELS[o.effect]+ : "Sticker";+ const clean = (raw ?? "")+ .replace(/[\n"]+/g, " ")+ .replace(/\s+/g, " ")+ .trim()+ .slice(0, 40)+ .trim();+ return clean || fallback;+}++/** The timeline's media-less objects as refs: title/shape/sticker/effect+ * elements, transition bars, subtitle cues, and every keyframe on a track-0+ * clip's or element's pose and mask tracks. Elements name by their content+ * ("Snap Test", "Rectangle"), numbered in timeline order only when two share+ * a name ("Rectangle 1", "Rectangle 2"); transitions, cues, and keyframes+ * stay ordinal. Names re-derive from the current timeline, so a pasted+ * mention resolves to whatever holds that name now; the internal ids ride in+ * the ref, never in the prompt text. */+export function entityRefs(src: EntitySources): AssetRef[] {+ const out: AssetRef[] = [];++ const overlayLabel: Record<string, string> = {+ text: "title",+ shape: "shape",+ sticker: "sticker",+ effect: "effect",+ };+ const overlays = [...src.overlays].sort(+ (a, b) => a.start - b.start || (a.lane ?? 0) - (b.lane ?? 0)+ );+ const bases = overlays.map((o) =>+ overlayBaseName(o, overlayLabel[(o as { kind?: string }).kind ?? "text"] ?? "element")+ );+ const dupes = new Map<string, number>();+ for (const b of bases) dupes.set(b.toLowerCase(), (dupes.get(b.toLowerCase()) ?? 0) + 1);+ const taken = new Set<string>();+ const nth = new Map<string, number>();+ const bump = (k: string) => {+ const n = (nth.get(k) ?? 0) + 1;+ nth.set(k, n);+ return n;+ };+ overlays.forEach((o, i) => {+ const label = overlayLabel[(o as { kind?: string }).kind ?? "text"] ?? "element";+ const base = bases[i];+ const key = base.toLowerCase();+ let name = (dupes.get(key) ?? 0) > 1 ? `${base} ${bump(key)}` : base;+ while (taken.has(name.toLowerCase())) name = `${base} ${bump(key)}`;+ taken.add(name.toLowerCase());+ const text = (o as { text?: string }).text;+ const stickerAsset =+ isStickerOverlay(o) && !o.lottie ? src.assets.find((a) => a.id === o.assetId) : undefined;+ out.push(+ entityRef(+ `overlay:${o.id}`,+ name,+ `${name} — a ${label} element on the timeline. id ${o.id}, ` ++ `${sec(o.start)}–${sec(o.end)}, lane ${o.lane ?? 0}.` ++ (text ? ` Text: "${text}"` : ""),+ {+ entityKind: label as AssetRef["entityKind"],+ shapeKind: isShapeOverlay(o) ? o.shape : undefined,+ preview: stickerAsset?.url,+ }+ )+ );+ out.push(...keyRefs("overlay", o.id, name, o.start, o.kf, "pose"));+ out.push(...keyRefs("overlay", o.id, name, o.start, o.mask?.kf, "mask"));+ });++ getClipSpans(src.clips, src.assets).forEach((sp, i) => {+ // The clip's session handle ("c3") — clipRefs numbers the same spans.+ const parent = `c${i + 1}`;+ out.push(...keyRefs("clip", sp.clip.id, parent, sp.start, sp.clip.kf, "pose"));+ out.push(...keyRefs("clip", sp.clip.id, parent, sp.start, sp.clip.mask?.kf, "mask"));+ });++ [...src.transitions].sort((a, b) => a.start - b.start).forEach((t, i) => {+ const name = `transition ${i + 1}`;+ out.push(+ entityRef(+ `transition:${t.id}`,+ name,+ `${name} — a transition bar on the timeline. id ${t.id}, style ${t.style}, ` ++ `window ${sec(t.start)}–${sec(t.start + t.seconds)}.`,+ { entityKind: "transition" }+ )+ );+ });++ [...src.subtitles.cues].sort((a, b) => a.start - b.start).forEach((c, i) => {+ const name = `cue ${i + 1}`;+ out.push(+ entityRef(+ `cue:${c.id}`,+ name,+ `${name} — a subtitle cue. id ${c.id}, ${sec(c.start)}–${sec(c.end)}. Text: "${c.text}"`,+ { entityKind: "cue" }+ )+ );+ });++ return out;+}++/** The prompt tokens for the current timeline selection, ready for the+ * system clipboard — a picked keyframe first, then every selected clip,+ * sound, element, transition, or cue that resolves to a ref. ⌘C writes this+ * so the selection can be pasted straight into the chat composer, where the+ * tokens light up as mentions. Null when nothing selected resolves. */+export function selectionRefTokens(s: EntitySources & {+ audioClips: AudioClip[];+ selection: Selection;+ multiSelection: Selection[];+ selectedKey: { kind: "overlay" | "clip"; id: string; t: number; track: "pose" | "mask" } | null;+}): string | null {+ const entities = entityRefs(s);++ if (s.selectedKey) {+ const k = s.selectedKey;+ const owner =+ k.kind === "clip"+ ? s.clips.find((c) => c.id === k.id)+ : s.overlays.find((o) => o.id === k.id);+ const keys = k.track === "pose" ? owner?.kf : owner?.mask?.kf;+ const idx = keys+ ? [...keys].sort((a, b) => a.t - b.t).findIndex((key) => Math.abs(key.t - k.t) < 1e-6)+ : -1;+ const ref =+ idx >= 0 ? entities.find((r) => r.id === `key:${k.kind}:${k.id}:${k.track}:${idx}`) : undefined;+ if (ref) return refToken(ref);+ }++ const cRefs = clipRefs(s.clips, s.assets);+ const aRefs = audioClipRefs(s.audioClips, s.assets);+ const sels = s.multiSelection.length ? s.multiSelection : s.selection ? [s.selection] : [];+ const tokens: string[] = [];+ for (const sel of sels) {+ if (!sel) continue;+ const ref =+ sel.kind === "clip"+ ? cRefs.find((r) => r.id === sel.id)+ : sel.kind === "audio"+ ? aRefs.find((r) => r.id === sel.id)+ : entities.find((r) => r.id === `${sel.kind}:${sel.id}`);+ if (ref) tokens.push(refToken(ref));+ }+ return tokens.length ? tokens.join(" ") : null;+}+/** Everything referenceable right now, in resolution order: the timeline's* clips first — video-track clips, then soundtrack clips (what's in front of- * the user — a bare `@` leads with the cut), then the open project's media,- * the shared library, and the stock catalog.+ * the user — a bare `@` leads with the cut), then the timeline's media-less+ * entities (elements, transitions, cues, keyframes — pasted in via ⌘C), then+ * the open project's media, the shared library, and the stock catalog.* Names are unique within the list (first scope wins) so a mention resolves* to one asset. Library items mention by name; stock ids are already short* (`@nature-dunes`). */@@ -450,6 +707,9 @@ export function useRefCandidates(): AssetRef[] {const assets = useEditor((s) => s.assets);const clips = useEditor((s) => s.clips);const audioClips = useEditor((s) => s.audioClips);+ const overlays = useEditor((s) => s.overlays);+ const transitions = useEditor((s) => s.transitions);+ const subtitles = useEditor((s) => s.subtitles);const [lib, setLib] = useState<LibraryAsset[]>(libraryCache ?? []);useEffect(() => {@@ -470,6 +730,7 @@ export function useRefCandidates(): AssetRef[] {for (const ref of [...clipRefs(clips, assets),...audioClipRefs(audioClips, assets),+ ...entityRefs({ clips, assets, overlays, transitions, subtitles }),...project,...lib.map(refFromLibrary),...STOCK_IMAGES.map(refFromStock),@@ -481,24 +742,36 @@ export function useRefCandidates(): AssetRef[] {out.push(ref);}return out;- }, [assets, clips, audioClips, lib]);+ }, [assets, clips, audioClips, overlays, transitions, subtitles, lib]);}/** The prompt token for an asset name: `@name`, quoted when it has spaces. */export const mentionToken = (name: string) =>/[\s"]/.test(name) ? `@"${name.replace(/"/g, "")}"` : `@${name}`;+/** Inside an entity token, spaces ride as no-break spaces: the composer+ * paints a single-line pill cover over the token's glyphs, so line wrap must+ * move the whole token. `resolveRefByName` reads both space forms as one, and+ * `parseMentions` restores plain spaces on the way out. */+const NBSP = " ";+/** The preferred prompt token for a ref: its short handle (`@v2`) when it has- * one, the (quoted) name otherwise. */+ * one, the (quoted) name otherwise. Entity tokens always quote: the composer+ * paints an icon + name cover over the token's glyphs, and the quotes buy the+ * width the icon needs. */export const refToken = (ref: AssetRef) =>- ref.handle ? `@${ref.handle}` : mentionToken(ref.name);+ ref.handle+ ? `@${ref.handle}`+ : ref.scope === "entity"+ ? `@"${ref.name.replace(/"/g, "").replace(/ /g, NBSP)}"`+ : mentionToken(ref.name);const MENTION_RE = /@(?:"([^"\n]+)"|([^\s"@]+))/g;/** Resolve one mention body against the candidates: short handle first* (`v2`), then exact name (case-insensitive on both). */export function resolveRefByName(name: string, candidates: AssetRef[]): AssetRef | null {- const q = name.toLowerCase();+ const q = name.replace(/ /g, " ").toLowerCase();return (candidates.find((c) => c.handle?.toLowerCase() === q) ??candidates.find((c) => c.name.toLowerCase() === q) ??@@ -567,7 +840,8 @@ export function parseMentions(if (!refs.some((r) => sameRef(r, ref))) refs.push(ref);return ref.name;});- return { refs, text: out };+ // Composer-side no-break spaces stay behind: prompt text reads plain.+ return { refs, text: out.replace(/ /g, " ") };}/** Resolve a prompt's `@name` mentions and merge them into the already-attached