Skip to content

Open source CapCut alternative.

TypeScript

feat(site): replicate a Donkey Cut project from a link [rebuild]

David Lea97491a06a22
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index 00f4ecc7..3b4ffb8e 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -55,9 +55,9 @@ Every knowledge surface is defined once — the catalog file ships in the engine
| Surface | Size today | When it enters context |
| --- | --- | --- |
-| System prompt | ~10K chars (~2.5K tokens) | Claude: replaces the Agent SDK default. Codex: prepended to the first turn (a resumed session already has it). Gemini: the instructions field, every round. |
-| Tool catalog (87 tools) | ~75K chars (~19K tokens) | Claude/Codex: the MCP tool listing. Gemini: function declarations on each request. |
-| Skills library (11 docs) | ~40K chars (~10K tokens) total | On demand only, via the list-skills and read-skill tools. |
+| System prompt | ~13K chars (~3K tokens) | Claude: replaces the Agent SDK default. Codex: prepended to the first turn (a resumed session already has it). Gemini: the instructions field, every round. |
+| Tool catalog (117 tools) | ~140K chars (~35K tokens) | Claude/Codex: the MCP tool listing. Gemini: function declarations on each request. |
+| Skills library (16 docs) | ~97K chars (~24K tokens) total | On demand only, via the list-skills and read-skill tools. |
| Editor snapshot | Grows with the project; media list and subtitle cues capped at 60 each | Attached to the newest user message as `<editor_state>`, rebuilt fresh every turn. |
| Attachments | Metadata JSON per asset | `<attached_assets>` on the message that carried them; on the Gemini path the newest message also carries the actual payloads (frames, images, text contents). |
| Full state | Uncapped | The get-state tool — the model calls it when the snapshot is stale or truncated. |
@@ -90,6 +90,7 @@ With a tab attached, tool calls execute in it against the same store the user is
- **Watching leaves a record.** Contact sheets live in one conversation and the media trim drops the oldest of them, so the model writes each look down: a note-source call stores what a span showed — quoted on-screen text, what happens, where the cuts land — against its source seconds, on the asset, saved with the project. Notes come back in the editor snapshot as `observed`, in full from get-state, and on every watch result beside the spans still undescribed. A close note supersedes the coarse one over the same ground, and a watch of a source that still owes a note is refused, which is what makes an hour-long source workable: it is surveyed coarsely, described, then re-watched densely only where the work is.
- **Speech cuts land on the words.** A recut edge is not left where the model's arithmetic put it. The audio around it is re-read, that recording's own room tone and voice level are measured, and the edge is placed a beat clear of where a word truly starts or finishes — tail and soft attack included, so a quiet take and a noisy one are cut the same way. Pace belongs to that step: fast, natural and relaxed set how big the beat is, and the fastest of them still lets every word finish. So "make it punchy" shortens the air rather than cutting into the speech, and where a pause is too short for both sides' air the two edges meet inside it instead of one clipping a word.
- **Media rides a byte budget.** Contact sheets, audio, and attachment payloads all replay inline, so before each call the session is trimmed to a 16MB media budget — oldest parts leave first, with a note naming the tools that fetch them again. Text, tool calls, tool results, and thought signatures always survive, and the trim runs on a copy so the stored session keeps everything.
+- **A Donkey Cut link is a document.** A project or share link pasted into chat is read as its document, and its edit is rebuilt in the open project on the user's own footage through the Library's template rail, whole or item by item, with the media the project lacks copied across; the reference's document is the recipe, so nothing is reconstructed from pixels, and a project held only in another browser's storage is readable only from that browser.
- **A link comes back as whatever it holds.** The chat's URL import works down a ladder: the bundled downloader for anything with a stream, X's own endpoints for a post's photos or Article, and otherwise the page itself — a content extractor (Defuddle over a parsed DOM) lifts the article out as markdown and the pictures it kept come along as assets. Words with no media are a successful import, so a link the user pasted to explain something reads fine, and that text is quoted for the user beside whatever media came with it. Whatever comes down is H.264 by the time it lands: the downloader sorts on codec before resolution, and a source that publishes nothing Apple can decode — the VP9 and AV1 streams Instagram and YouTube serve at their top tiers — is converted on the way in, so an import plays on the phone, in the Mac's own player, and in a browser.
- **Async when rendering.** Video generation outruns the two-minute tool window, so those tools start the job and return immediately; the clip files under the chat that asked — the owning thread is captured at call time — and lands on the timeline only when the user asked for that. Each render's card state (running, landed, failed) mirrors into the project doc as it changes, so the chat shows the same outcome on machines that never ran the job.
- **Chat owns what it makes.** Media created by chat tools is tagged with its thread and previews on a card in the conversation. Placing it on the timeline or filing it into Media or the Library transfers ownership; deleting the thread deletes whatever it still owns.
diff --git a/site/scripts/lib/cut-eval/cases.ts b/site/scripts/lib/cut-eval/cases.ts
index fa99956f..a7d2352e 100644
--- a/site/scripts/lib/cut-eval/cases.ts
+++ b/site/scripts/lib/cut-eval/cases.ts
@@ -23,6 +23,8 @@ import {
SCENE_DONE_STATE,
STYLED_STATE,
PARKED_STATE,
+ REFERENCE_PROJECT,
+ REPLICATE_STATE,
STRANDED_TITLE_STATE,
TWEET_ASSET,
TWEET_STATE,
@@ -980,5 +982,63 @@ export function cases(audio: { dataBase64: string; mimeType: string }): EvalCase
},
},
},
+ {
+ // A pasted project link is a document: read it, map the reference's two
+ // footage sources onto the user's own by content, leave the music to
+ // copy across, and rebuild in one call — no watching, no import, no
+ // generation, no template rail.
+ name: "replicate-link-reads-then-replicates",
+ bucket: "multi-tool",
+ input: () => [
+ userTurn("replicate https://donkeycut.com/app/p/ref-123 using my clips", {
+ state: REPLICATE_STATE,
+ }),
+ ],
+ reply: /replicat|rebuil|recreat|copied|landed/i,
+ requiredTools: ["read_project", "replicate_project"],
+ maxToolCalls: 6,
+ simulate: () => (name, args) => {
+ if (["watch_video", "import_url", "generate_video", "generate_scene", "generate_music", "template_add", "library_list"].includes(name))
+ throw new Error(`the reference is a document — ${name} is a violation here`);
+ if (name === "replicate_project") {
+ const media = (Array.isArray(args.media) ? args.media : []) as { source_asset_id: string; asset_id: string }[];
+ const by = new Map(media.map((m) => [m.source_asset_id, m.asset_id]));
+ if (by.get("r-v1") !== "a-v1" || by.get("r-v2") !== "a-v2")
+ throw new Error(`the talking head maps to a-v1 and the b-roll to a-v2; got ${JSON.stringify(media)}`);
+ if (by.has("r-m1")) throw new Error("the music has no counterpart here; leave it unmapped so it copies across");
+ if (args.items !== undefined) throw new Error("\"replicate this\" is the whole edit — no items");
+ return {
+ replicated: "the whole edit",
+ from: { id: "ref-123", name: "Kitchen tour" },
+ clipIds: ["c-n1", "c-n2"],
+ audioClipIds: ["au-n1"],
+ overlayIds: ["t-n1"],
+ transitionIds: ["tr-n1"],
+ cueIds: [],
+ mapped: [{ sourceId: "r-v1", assetId: "a-v1" }, { sourceId: "r-v2", assetId: "a-v2" }],
+ assetIds: ["a-m9"],
+ copied: [{ sourceId: "r-m1", assetId: "a-m9", name: "lofi-bed.mp3", kind: "audio" }],
+ adjustments: [],
+ skipped: [],
+ frame: true,
+ captionLook: true,
+ captions: "none copied",
+ videoTrack: [
+ { id: "c-n1", start: 0, len: 6 },
+ { id: "c-n2", start: 5.5, len: 8.5 },
+ ],
+ soundtrack: [{ id: "au-n1", lane: 0, start: 0, len: 14 }],
+ };
+ }
+ return undefined;
+ },
+ stubs: {
+ read_project: REFERENCE_PROJECT,
+ update_overlay: { ok: true },
+ subtitles_generate: { ok: true, cues: 2 },
+ refine_speech_cuts: { ok: true },
+ capture_frame: { image: "data:image/jpeg;base64,", at: 1 },
+ },
+ },
];
}
diff --git a/site/scripts/lib/cut-eval/fixtures.ts b/site/scripts/lib/cut-eval/fixtures.ts
index 6c59d857..955eb4bb 100644
--- a/site/scripts/lib/cut-eval/fixtures.ts
+++ b/site/scripts/lib/cut-eval/fixtures.ts
@@ -370,6 +370,103 @@ export interface EvalMessage {
let turnSeq = 0;
+/** A finished reference project as read_project returns it: two footage
+ * sources with notes and transcripts, a music bed, a crossfade, a title,
+ * captions in a look. The ids are what a replicate maps and picks. */
+export const REFERENCE_PROJECT = {
+ source: { kind: "project", id: "ref-123", name: "Kitchen tour", residency: "cloud" },
+ reference: {
+ project: {
+ id: "ref-123",
+ name: "Kitchen tour",
+ duration: 14,
+ aspect: "9:16",
+ frame: "1080x1920",
+ fadeIn: 0.3,
+ fadeOut: 0.5,
+ background: "#101010",
+ },
+ media: [
+ {
+ id: "r-v1",
+ name: "host-intro.mp4",
+ type: "video",
+ duration: 20,
+ observed: [{ from: 0, to: 20, text: "a person talks to camera in a kitchen, medium shot, warm light" }],
+ speech: "transcribed",
+ transcript: [{ start: 0, end: 6, text: "Welcome to my kitchen, here's how I set it up." }],
+ },
+ {
+ id: "r-v2",
+ name: "counter-broll.mp4",
+ type: "video",
+ duration: 15,
+ observed: [{ from: 0, to: 15, text: "slow pan across a marble counter with a coffee machine, no people" }],
+ speech: "none",
+ },
+ { id: "r-m1", name: "lofi-bed.mp3", type: "audio", duration: 60, origin: "generated" },
+ ],
+ mediaTruncated: false,
+ videoTrack: [
+ { index: 0, id: "rc1", asset: "host-intro.mp4", start: 0, len: 6, in: 0, out: 6, sourceDuration: 20, muted: false, framing: "fill", speed: 1, transitionToNext: { style: "crossfade", seconds: 0.5 } },
+ { index: 1, id: "rc2", asset: "counter-broll.mp4", start: 5.5, len: 8.5, in: 2, out: 10.5, sourceDuration: 15, muted: true, framing: "fill", speed: 1, colorGrade: { saturation: 12, temperature: 8 } },
+ ],
+ overlayVideo: [],
+ transitions: [{ id: "rt1", start: 5.5, seconds: 0.5, style: "crossfade", plays: [{ at: "cut", clipId: "rc2" }] }],
+ soundtrack: [
+ { id: "ra1", asset: "lofi-bed.mp3", start: 0, len: 14, in: 0, out: 14, volume: 0.35, fadeIn: 0.5, fadeOut: 1, duck: 0.4 },
+ ],
+ overlays: [
+ { id: "rt-title", kind: "text", text: "MY KITCHEN SETUP", start: 0.4, end: 3, x: 0.5, y: 0.2, size: 96, font: "sf", weight: 700, color: "#FFFFFF", plate: true },
+ ],
+ subtitles: {
+ count: 2,
+ showOnVideo: true,
+ showOnTimeline: true,
+ activeTrack: 0,
+ tracks: [{ track: 0, locale: "en-US", cues: 2 }],
+ wordsPerCue: 3,
+ style: "bubble",
+ status: "ready",
+ cues: [
+ { id: "rq1", start: 0.2, end: 2.8, text: "Welcome to my kitchen" },
+ { id: "rq2", start: 2.9, end: 6, text: "here's how I set it up" },
+ ],
+ cuesTruncated: false,
+ },
+ },
+ unobserved: [],
+ note: "Every item carries the id replicate_project takes; media[].id are the source asset ids for its `media` mapping and for copy_project_media.",
+};
+
+/** The project a replicate lands in: two transcribed clips of the user's
+ * own, no soundtrack, nothing on the timeline yet. */
+export const REPLICATE_STATE = {
+ ...EDITOR_STATE,
+ project: { ...EDITOR_STATE.project, duration: 0 },
+ media: [
+ {
+ id: "a-v1",
+ name: "me-talking.mp4",
+ type: "video",
+ duration: 25,
+ speech: "transcribed",
+ observed: [{ from: 0, to: 25, text: "a person speaks to camera at a desk, close shot" }],
+ },
+ {
+ id: "a-v2",
+ name: "desk-broll.mp4",
+ type: "video",
+ duration: 12,
+ speech: "none",
+ observed: [{ from: 0, to: 12, text: "slow slide across a desk with a laptop and a lamp, no people" }],
+ },
+ ],
+ videoTrack: [],
+ soundtrack: [],
+ overlays: [],
+};
+
export function userTurn(
text: string,
opts?: {
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.ts
index 57a8b556..d9a3533d 100644
--- a/site/src/cut/components/AiPanel.tools.ts
+++ b/site/src/cut/components/AiPanel.tools.ts
@@ -26,6 +26,9 @@ export const AI_PANEL_TOOLS = [
from: num("Source start s (default: the clip's in, else 0)"),
to: num("Source end s (default: the clip's out, else the source's end; spans at most 600s per call)"),
interval_seconds: num("Seconds between candidate frames, 0.5–30 (default 1; near-duplicates are dropped, so a dense default costs nothing)"),
+ project_link: str(
+ "A reference project's link or id (what read_project took): clip_id / asset_id then name that project's items, so you can look at footage of the reference whose notes and transcript leave it dark before mapping roles. A reference look is for deciding — nothing is written to the reference and no note is owed."
+ ),
}),
},
{
@@ -120,6 +123,54 @@ export const AI_PANEL_TOOLS = [
["url"]
),
},
+ {
+ name: "read_project",
+ description:
+ "Read another Donkey Cut project as a reference: its whole edit in the same shape as <editor_state> — every clip with its trims, speed, framing, grade, look, mask, keyframes and animations; the transition bars; titles, shapes and stickers with their keyframes; the soundtrack; the caption look and cues; aspect, background and fades — plus each source's observed notes, transcript and asset id. Takes a project link (…/app/p/<id>), a share link (…/s/<token>), or a project id. The document IS the edit: never watch_video a reference to learn what its document already states; watch a reference source (project_link) only to see footage its notes leave dark. Every item carries its id, so replicate_project can bring the whole edit or just the items the user wants — a title, one clip's treatment, the music — and copy_project_media can bring files over on their own. Nothing in the open project changes.",
+ inputSchema: obj({ link: str("Project link, share link, or project id") }, ["link"]),
+ },
+ {
+ name: "replicate_project",
+ description:
+ "Rebuild a reference project's edit in this project, once: the whole thing, or only `items` (ids from read_project — clips on any track, soundtrack clips, titles/shapes/stickers, cues, transition bars; a chosen clip brings the bars playing on it). Clips and layers land after the current end of track 0; free-standing items (a title alone, a music clip) drop in at the playhead, timed from the earliest of them. `media` maps the reference's source asset ids to this project's asset ids playing the same role (video for video or a still, audio for audio); every reference source the chosen items use and you did not map — music, stickers, images, fonts, and any footage you left unmapped — is copied from the reference into this project. Trims clamp to each mapped source's real length and every clamp is listed in `adjustments`: fix or report each one. With the whole edit, the reference's frame (aspect, background, fades) and caption look come too; with `items` they come only when frame / caption_look are true. Caption cues copy with the whole edit only when captions is true (this project's speech differs, so generate them after); with `items`, name the cue ids. Background removal on a reference clip stays behind. One undo step reverts every item and the caption look; the frame is a project setting, so set_aspect / set_background / set_project_fade put it back. Afterwards tune with the ordinary tools.",
+ inputSchema: obj(
+ {
+ link: str("The same link read_project took"),
+ items: {
+ type: "array",
+ items: { type: "string" },
+ description: "Reference item ids to bring across (absent = the whole edit)",
+ },
+ media: {
+ type: "array",
+ description: "Role mapping, reference source → this project's asset",
+ items: obj(
+ {
+ source_asset_id: str("Reference asset id (from read_project's media)"),
+ asset_id: str("This project's asset id that plays that role"),
+ },
+ ["source_asset_id", "asset_id"]
+ ),
+ },
+ frame: bool("Also set this project's aspect, background and fades to the reference's (default: true for the whole edit, false with items)"),
+ caption_look: bool("Also apply the reference's caption look — style, font, size, position, words per cue, word effects (default: true for the whole edit, false with items)"),
+ captions: bool("With the whole edit, also copy the reference's caption cues (default false)"),
+ },
+ ["link"]
+ ),
+ },
+ {
+ name: "copy_project_media",
+ description:
+ "Copy files from a reference project into this one without placing anything: a music track, a sticker, a photo, a clip the user wants to reuse. Takes the reference's asset ids from read_project. Each copy keeps its notes, transcript and beat grid, lands on a card in this chat, and is a project asset from then on — add_clip places it when the user asks for it in the cut.",
+ inputSchema: obj(
+ {
+ link: str("The reference project's link or id"),
+ asset_ids: { type: "array", items: { type: "string" }, description: "Reference asset ids to copy" },
+ },
+ ["link", "asset_ids"]
+ ),
+ },
{
name: "list_skills",
description: "List the available skill documents about how this editor works.",
diff --git a/site/src/cut/lib/aiContext.test.ts b/site/src/cut/lib/aiContext.test.ts
new file mode 100644
index 00000000..a5ca8a6f
--- /dev/null
+++ b/site/src/cut/lib/aiContext.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from "bun:test";
+
+import { buildAiContext, describeDoc } from "./aiContext";
+import { richDoc } from "./fixtures/richDoc";
+import { useEditor } from "./store";
+import type { MediaAsset } from "./types";
+
+/**
+ * A document described on its own reads exactly like the same project open
+ * in the editor. That is what lets another project be read as a reference
+ * in the shape the model already knows.
+ */
+
+describe("describeDoc", () => {
+ test("matches the live snapshot's core for the same document", async () => {
+ const doc = richDoc();
+ const assets: MediaAsset[] = doc.assets.map((a) => ({ ...a, url: "" }));
+ await useEditor.getState().openProjectDoc("rich", doc, assets);
+ const live = buildAiContext({ fullCues: true, chatId: null });
+ const read = describeDoc(doc, { fullCues: true });
+ for (const key of ["project", "media", "videoTrack", "overlayVideo", "transitions", "soundtrack", "overlays", "subtitles"] as const) {
+ expect(read[key]).toEqual(live[key]);
+ }
+ expect(read.media[0]).toMatchObject({
+ id: "v0",
+ observed: [{ from: 0, to: 10, text: "a host talks to camera" }],
+ speech: "transcribed",
+ transcript: [{ start: 0, end: 4, text: "hello and welcome" }],
+ });
+ expect(read.videoTrack[1]).toMatchObject({ id: "c1", colorGrade: { brightness: 5 }, animOut: { style: "zoom", seconds: 0.5 } });
+ expect(read.subtitles).toMatchObject({ style: "bubble", size: 60, wordsPerCue: 3, wordHighlight: true, accentColor: "#FF3366" });
+ expect(read.project).toMatchObject({ id: "rich", name: "Rich edit", aspect: "16:9", background: "#102030", fadeIn: 0.3, fadeOut: 0.4 });
+ });
+
+ test("carries no live-only fields", () => {
+ const read = describeDoc(richDoc()) as Record<string, unknown>;
+ for (const key of ["playhead", "selection", "renders", "view", "fonts", "playing"]) {
+ expect(key in read).toBe(false);
+ }
+ });
+
+ test("another chat's unplaced media stays out of a reference, as it does out of the open project", () => {
+ const doc = richDoc();
+ doc.assets.push({ id: "g1", fileName: "g1.mp4", name: "their render", type: "video", duration: 4, origin: "chat", chatId: "thread-a" });
+ const own = describeDoc(doc, { fullCues: true, chatId: "thread-a" });
+ expect(own.media.some((m) => m.id === "g1")).toBe(true);
+ const other = describeDoc(doc, { fullCues: true, chatId: "thread-b" });
+ expect(other.media.some((m) => m.id === "g1")).toBe(false);
+ expect(describeDoc(doc, { fullCues: true }).media.some((m) => m.id === "g1")).toBe(false);
+ });
+});
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 3b62b51f..812977e3 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -1,11 +1,12 @@
"use client";
-import { GUIDE_PRESETS, guideFits, guideGeometry, safeAreaOf } from "./guides";
+import { GUIDE_PRESETS, guideFits, guideGeometry, safeAreaOf, sanitizeGuideLines, sanitizeGuides, type GuideId, type GuideLines } from "./guides";
import { hasOverlayAnim, retimeOf, speedCurveOf, type ClipSound, type SpeedNode } from "@donkeycut/effects-kit";
import { chatOwner } from "./chatAssets";
import { useGenerate } from "./generate";
import { useMatteBakes } from "./removal/bakeJobs";
-import { getClipSpans, overlayLayers, resolveTransitions, totalDuration, useEditor } from "./store";
+import { deriveTransitionFields, getClipSpans, normalizeDocState, overlayLayers, resolveTransitions, totalDuration, useEditor } from "./store";
+import type { VideoProject } from "./genvideo/types";
import { playheadAt, skimAt } from "./playhead";
import { cueWordCount } from "./cueChunk";
import { laneCues, subtitleLaneCount } from "./subtitles";
@@ -17,8 +18,15 @@ import {
rectOf,
regionLabel,
uploadedFontId,
+ type Aspect,
+ type AudioClip,
type ClipSpan,
+ type MediaAsset,
+ type MediaFolder,
type Overlay,
+ type ProjectDoc,
+ type SubtitlesBlock,
+ type TimelineTransition,
type VideoClip,
} from "./types";
@@ -38,7 +46,7 @@ function transitionToNext(sp: ClipSpan, index: number, spans: ClipSpan[]) {
* color state in the shape the grading tools take: the preset ref plus a
* compact summary of the manual grade (nonzero sliders verbatim; curves and
* wheels as presence flags; the touched hue bands by name). */
-function clipEffects(clip: VideoClip) {
+function clipEffects(clip: VideoClip, live: boolean) {
const grade = clip.grade;
const sliders: Record<string, number> = {};
for (const [k, v] of Object.entries(grade ?? {})) {
@@ -68,17 +76,17 @@ function clipEffects(clip: VideoClip) {
: {}),
...color,
...(clip.boxStyle ? { boxStyle: clip.boxStyle } : {}),
- ...describeRemoval(clip),
+ ...describeRemoval(clip, live),
};
}
/** The clip's cutout state: mode, whether its AI matte is ready (and at which
* tier), a live bake's progress, and the stroke/background riding on it —
* what set_removal claims must be grounded in. */
-function describeRemoval(clip: VideoClip) {
+function describeRemoval(clip: VideoClip, live: boolean) {
const rm = clip.removal;
if (!rm) return {};
- const job = useMatteBakes.getState().jobs[clip.id];
+ const job = live ? useMatteBakes.getState().jobs[clip.id] : undefined;
return {
removal: {
mode: rm.mode,
@@ -153,35 +161,10 @@ function noteFields(
*/
export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | null }) {
const s = useEditor.getState();
- const cueCap = opts?.fullCues ? Infinity : 60;
const chatId = opts?.chatId !== undefined ? opts.chatId : chatOwner();
- const placed = new Set([...s.clips, ...s.audioClips].map((c) => c.assetId));
- // An asset still owned by another chat: chat-made, tagged to a different
- // thread, and not yet moved onto the timeline. Placed media is project
- // content, so it stays visible even when a chat made it.
- const ownedByOtherChat = (a: { origin?: string; chatId?: string; id: string }) =>
- a.origin === "chat" && !!a.chatId && a.chatId !== chatId && !placed.has(a.id);
- // A font asset is a typeface, not footage: it is listed under `fonts` with
- // the account's shelf fonts, where a font id is what the model needs.
- const visibleAssets = s.assets.filter((a) => a.type !== "font" && !ownedByOtherChat(a));
- // The cap trims the tail of a huge media list, and a source someone has
- // watched and written up stays regardless of where it sits: the record is
- // what later decisions are made from.
- const shownAssets =
- visibleAssets.length <= cueCap
- ? visibleAssets
- : visibleAssets.filter((a, i) => i < cueCap || (a.watch?.notes?.length ?? 0) > 0);
+ const core = describeState(s, { fullCues: opts?.fullCues === true, chatId, live: true });
const spans = getClipSpans(s.clips, s.assets);
- const duration = totalDuration(s.clips);
const assetById = new Map(s.assets.map((a) => [a.id, a]));
- const subtitleTracks = subtitleLaneCount(s.subtitles);
- // Scene-run lineage: which plan shot (1-based, what regenerate_shot takes)
- // placed each clip, so "fix this clip" maps straight to a shot revision.
- const shotByClip = new Map(
- (s.genvideo?.shots ?? []).flatMap((sh, i) =>
- sh.timelineClipId ? [[sh.timelineClipId, { n: i + 1, still: sh.status === "failed" }] as const] : []
- )
- );
const selection = (() => {
if (!s.selection) return null;
@@ -223,6 +206,174 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
return { kind, id, element, ...rest };
})();
+ return {
+ project: core.project,
+ playhead: r(playheadAt()),
+ skimmer: skimAt() === null ? null : r(skimAt()!),
+ playing: s.playing,
+ selection,
+ // Every font a title or caption can be set in beyond the built-in list:
+ // the account's own, off the Library shelf, plus any still living in this
+ // project from before fonts moved to the shelf.
+ fonts: [
+ ...listLibraryFonts().map((f) => ({ id: libraryFontId(f.key), label: f.label })),
+ ...s.assets
+ .filter((a) => a.type === "font")
+ .map((a) => ({ id: uploadedFontId(a.id), label: a.name })),
+ ],
+ ...(core.mediaFolders ? { mediaFolders: core.mediaFolders } : {}),
+ media: core.media,
+ mediaTruncated: core.mediaTruncated,
+ // AI video renders for this project, live from the job store — what
+ // "rendering" claims must be grounded in. A done render names the asset
+ // it landed as (already in `media`); a failed one carries its error.
+ // Renders another chat launched stay out; chat-less panel renders show to
+ // every chat as shared project activity.
+ renders: useGenerate
+ .getState()
+ .jobs.filter(
+ (j) =>
+ j.kind === "video" &&
+ j.projectId === s.projectId &&
+ !(j.chatId && j.chatId !== chatId)
+ )
+ .slice(0, 8)
+ .map((j) => ({
+ jobId: j.id,
+ prompt: j.prompt.length > 80 ? `${j.prompt.slice(0, 77)}…` : j.prompt,
+ status: j.status,
+ ...(j.status === "running"
+ ? { elapsedSec: Math.round((Date.now() - j.startedAt) / 1000) }
+ : {}),
+ ...(j.status === "done" && j.assetId ? { assetId: j.assetId } : {}),
+ ...(j.status === "error" && j.error ? { error: j.error } : {}),
+ })),
+ videoTrack: core.videoTrack,
+ overlayVideo: core.overlayVideo,
+ transitions: core.transitions,
+ soundtrack: core.soundtrack,
+ overlays: core.overlays,
+ subtitles: core.subtitles,
+ publish: s.publish,
+ view: {
+ pxPerSec: r(s.pxPerSec),
+ timelineH: s.timelineH,
+ exportDialogOpen: s.exportOpen,
+ },
+ };
+}
+
+/** A stored document described the way the open project is: the same
+ * shape the model reads in <editor_state>, built from the document alone.
+ * This is how another project is read as a reference — its edit, its
+ * sources with their notes and transcripts, its caption look — and it goes
+ * through the store's own normalization so an old document reads like a
+ * new one. Live-only fields (playhead, selection, renders, view) stay out. */
+export function describeDoc(doc: ProjectDoc, opts?: { fullCues?: boolean; chatId?: string | null }) {
+ const assets: MediaAsset[] = (doc.assets ?? []).map((a) => ({ ...a, url: "" }));
+ const state = normalizeDocState(doc, assets);
+ const core = describeState(
+ {
+ projectId: doc.id ?? null,
+ projectName: doc.name ?? "",
+ assets,
+ // The store writes each clip's blend into the clip as it lands; the
+ // description reads the same fields.
+ clips: deriveTransitionFields(state.clips, state.transitions),
+ transitions: state.transitions,
+ audioClips: state.audioClips,
+ overlays: state.overlays,
+ subtitles: state.subtitles,
+ subtitleLane: 0,
+ subtitleStatus: state.subtitles.cues.length > 0 ? "ready" : "idle",
+ aspect: state.aspect ?? "9:16",
+ fadeIn: state.fadeIn,
+ fadeOut: state.fadeOut,
+ background: state.background,
+ guides: sanitizeGuides(doc.guides),
+ guideLines: sanitizeGuideLines(doc.guideLines),
+ genvideo: doc.genvideo ?? undefined,
+ mediaFolders: doc.mediaFolders ?? [],
+ },
+ { fullCues: opts?.fullCues === true, chatId: opts?.chatId ?? null, live: false }
+ );
+ const { mediaFolders, ...rest } = core;
+ return { ...rest, ...(mediaFolders ? { mediaFolders } : {}) };
+}
+
+/** The document-shaped part of the editor's state: what the store holds
+ * after opening a project, or a stored document normalized the same way. */
+interface DescribedState {
+ projectId: string | null;
+ projectName: string;
+ assets: MediaAsset[];
+ clips: VideoClip[];
+ transitions: TimelineTransition[];
+ audioClips: AudioClip[];
+ overlays: Overlay[];
+ subtitles: SubtitlesBlock;
+ subtitleLane: number;
+ subtitleStatus: string;
+ aspect: Aspect;
+ fadeIn: number;
+ fadeOut: number;
+ background: string;
+ guides: GuideId[];
+ guideLines: GuideLines;
+ genvideo?: VideoProject | null;
+ mediaFolders: MediaFolder[];
+}
+
+/** The media a project's timeline plays: project content whichever chat made it. */
+export const placedAssetIds = (s: { clips: VideoClip[]; audioClips: AudioClip[] }): Set<string> =>
+ new Set([...s.clips, ...s.audioClips].map((c) => c.assetId));
+
+/** An asset still owned by another chat: chat-made, tagged to a different
+ * thread, and not yet moved onto the timeline. Placed media is project
+ * content, so it stays visible even when a chat made it. The same rule reads
+ * the open project and a reference, so a chat sees no more of a project by
+ * reading it as a reference than by opening it. */
+export const hiddenFromChat = (
+ a: { origin?: string; chatId?: string; id: string },
+ chatId: string | null,
+ placed: Set<string>
+): boolean => a.origin === "chat" && !!a.chatId && a.chatId !== chatId && !placed.has(a.id);
+
+/** `live` marks the open project: the sweep's progress, the matte bakes in
+ * flight, and another chat's private media are facts about this page, and
+ * a document read as a reference has none of them. */
+function describeState(
+ s: DescribedState,
+ opts: { fullCues: boolean; chatId: string | null; live: boolean }
+) {
+ const cueCap = opts.fullCues ? Infinity : 60;
+ const chatId = opts.chatId;
+ const placed = placedAssetIds(s);
+ const ownedByOtherChat = (a: { origin?: string; chatId?: string; id: string }) =>
+ hiddenFromChat(a, chatId, placed);
+ // A font asset is a typeface, not footage: it is listed under `fonts` with
+ // the account's shelf fonts, where a font id is what the model needs.
+ const visibleAssets = s.assets.filter((a) => a.type !== "font" && !ownedByOtherChat(a));
+ // The cap trims the tail of a huge media list, and a source someone has
+ // watched and written up stays regardless of where it sits: the record is
+ // what later decisions are made from.
+ const shownAssets =
+ visibleAssets.length <= cueCap
+ ? visibleAssets
+ : visibleAssets.filter((a, i) => i < cueCap || (a.watch?.notes?.length ?? 0) > 0);
+ const spans = getClipSpans(s.clips, s.assets);
+ const duration = totalDuration(s.clips);
+ const assetById = new Map(s.assets.map((a) => [a.id, a]));
+ const subtitleTracks = subtitleLaneCount(s.subtitles);
+ // Scene-run lineage: which plan shot (1-based, what regenerate_shot takes)
+ // placed each clip, so "fix this clip" maps straight to a shot revision.
+ const shotByClip = new Map(
+ (s.genvideo?.shots ?? []).flatMap((sh, i) =>
+ sh.timelineClipId ? [[sh.timelineClipId, { n: i + 1, still: sh.status === "failed" }] as const] : []
+ )
+ );
+ const live = opts.live;
+
return {
project: {
id: s.projectId,
@@ -260,28 +411,14 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
}
: {}),
},
- playhead: r(playheadAt()),
- skimmer: skimAt() === null ? null : r(skimAt()!),
- playing: s.playing,
- selection,
+ // The Media panel's folders, when the project has any; each filed asset
+ // carries its folderId below (media_organize moves them).
+ mediaFolders:
+ s.mediaFolders.length > 0 ? s.mediaFolders.map((f) => ({ id: f.id, name: f.name })) : null,
// Every project asset visible to this chat, timeline-placed or not (media
// another chat still owns is filtered out above). `origin` marks Cut-made
// media (generated/voiceover/recording/stock/freeze); no origin = a user
// import shown in the Media panel.
- // Every font a title or caption can be set in beyond the built-in list:
- // the account's own, off the Library shelf, plus any still living in this
- // project from before fonts moved to the shelf.
- fonts: [
- ...listLibraryFonts().map((f) => ({ id: libraryFontId(f.key), label: f.label })),
- ...s.assets
- .filter((a) => a.type === "font")
- .map((a) => ({ id: uploadedFontId(a.id), label: a.name })),
- ],
- // The Media panel's folders, when the project has any; each filed asset
- // carries its folderId below (media_organize moves them).
- ...(s.mediaFolders.length > 0
- ? { mediaFolders: s.mediaFolders.map((f) => ({ id: f.id, name: f.name })) }
- : {}),
media: shownAssets.map((a) => ({
id: a.id,
name: a.name,
@@ -297,21 +434,21 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
...(a.watch && a.watch.ranges.length > 0
? { mapped: a.watch.ranges.map((rg) => ({ from: r(rg.from), to: r(rg.to) })) }
: {}),
- ...(watchSweepActive(a.id) ? { watching: true } : {}),
+ ...(live && watchSweepActive(a.id) ? { watching: true } : {}),
// The written record of this source — what someone looked at these
// frames and wrote down (note_source). Unlike `mapped`, this IS seen
// footage, and it survives the contact sheets that showed it, so a
// source too long to hold in one conversation is decided from here.
// The snapshot rides every model call, so it carries the notes while
// they are small and hands the rest to get_state.
- ...noteFields(a.watch?.notes, opts?.fullCues === true),
+ ...noteFields(a.watch?.notes, opts.fullCues),
// The source's own transcript (built quietly by the sweep; no subtitle
// track involved). The snapshot carries the verdict; get_state carries
// the segments — read those for the words instead of inlining audio.
...(a.speech
? {
speech: a.speech.noSpeech ? "none" : "transcribed",
- ...(opts?.fullCues && a.speech.segments.length > 0
+ ...(opts.fullCues && a.speech.segments.length > 0
? {
transcript: a.speech.segments.map((sg) => ({
start: r(sg.start),
@@ -324,30 +461,6 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
: {}),
})),
mediaTruncated: shownAssets.length < visibleAssets.length,
- // AI video renders for this project, live from the job store — what
- // "rendering" claims must be grounded in. A done render names the asset
- // it landed as (already in `media`); a failed one carries its error.
- // Renders another chat launched stay out; chat-less panel renders show to
- // every chat as shared project activity.
- renders: useGenerate
- .getState()
- .jobs.filter(
- (j) =>
- j.kind === "video" &&
- j.projectId === s.projectId &&
- !(j.chatId && j.chatId !== chatId)
- )
- .slice(0, 8)
- .map((j) => ({
- jobId: j.id,
- prompt: j.prompt.length > 80 ? `${j.prompt.slice(0, 77)}…` : j.prompt,
- status: j.status,
- ...(j.status === "running"
- ? { elapsedSec: Math.round((Date.now() - j.startedAt) / 1000) }
- : {}),
- ...(j.status === "done" && j.assetId ? { assetId: j.assetId } : {}),
- ...(j.status === "error" && j.error ? { error: j.error } : {}),
- })),
videoTrack: spans.map((sp, index) => ({
index,
id: sp.clip.id,
@@ -395,7 +508,7 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
...(sp.clip.kf?.length
? { keyframes: sp.clip.kf.map((k) => ({ ...k, t: r(k.t), x: r(k.x), y: r(k.y) })) }
: {}),
- ...clipEffects(sp.clip),
+ ...clipEffects(sp.clip, live),
})),
// Video layers composited over track 0 in track order (the topmost
// full-frame clip covers the rest). Each track carries its own
@@ -409,7 +522,7 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
const t = transitionToNext(sp, i, trackSpans);
return t ? { transitionToNext: t } : {};
})(),
- ...clipEffects(sp.clip),
+ ...clipEffects(sp.clip, live),
}));
}),
// Every transition bar in the doc. A bar is its own object on the
@@ -458,6 +571,18 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
// How the captions READ: how many words one holds at a time. Changing it
// re-cuts every track (set_caption_look words_per_cue).
wordsPerCue: cueWordCount(s.subtitles),
+ // The look the captions wear, so a reference's caption treatment is
+ // legible without the cues: style preset, font, size, anchor, and the
+ // word effect.
+ ...(s.subtitles.style ? { style: s.subtitles.style } : {}),
+ ...(s.subtitles.font ? { font: s.subtitles.font } : {}),
+ ...(s.subtitles.size !== undefined ? { size: s.subtitles.size } : {}),
+ ...(s.subtitles.x !== undefined || s.subtitles.y !== undefined
+ ? { x: r(s.subtitles.x ?? 0.5), y: r(s.subtitles.y ?? 0.5) }
+ : {}),
+ ...(s.subtitles.wordHighlight ? { wordHighlight: true } : {}),
+ ...(s.subtitles.accentMode ? { accentMode: s.subtitles.accentMode } : {}),
+ ...(s.subtitles.accentColor ? { accentColor: s.subtitles.accentColor } : {}),
status: s.subtitleStatus,
// A window of cues by default; when truncated the model calls get_state
// for the whole transcript (e.g. "clean up all the captions").
@@ -470,12 +595,6 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
})),
cuesTruncated: s.subtitles.cues.length > cueCap,
},
- publish: s.publish,
- view: {
- pxPerSec: r(s.pxPerSec),
- timelineH: s.timelineH,
- exportDialogOpen: s.exportOpen,
- },
};
}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index b3451184..14f6e8fb 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -126,6 +126,9 @@ import { STOCK_IMAGES } from "./stockManifest";
import { STOCK_VIDEOS } from "./stockVideoManifest";
import { STOCK_SFX } from "./stockSfxManifest";
import { storedMediaUrl } from "./mediaSync";
+import { parseProjectLink } from "./projectLink";
+import { landReferenceAssets as landReferenceAssetsInto, openReference, referenceMediaUrl, type LandedAsset, type ReferenceProject } from "./projectReference";
+import { clampLayersToAssets, mediaTypeFits, templateFromDoc } from "./projectTemplate";
import { isSoundPresetTemplate, listSoundPresets, saveSoundPreset } from "./soundPresets";
import { isStylePresetTemplate } from "./stylePresets";
import { applyOverlayPatchSettled, clipLen, track0Clips, laneGapAt, getClipSpans, nextFreeStart, overlayLaneOrder, overlayLayers, parkedTransitions, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";
@@ -133,7 +136,7 @@ import { playheadAt } from "./playhead";
import { renderProjectFrame } from "./exportRender";
import { renderStageFrame, storeStageStill } from "./stageFrame";
import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";
-import { buildAiContext } from "./aiContext";
+import { buildAiContext, describeDoc, hiddenFromChat, placedAssetIds } from "./aiContext";
import { sampleClipFrameData } from "./previewCanvas";
import { CAPTION_STYLES, laneCues, subtitleLaneCount } from "./subtitles";
import { fuseTimeline, renderFusedTimeline } from "./watch/fuse";
@@ -205,8 +208,10 @@ import {
type Selection,
type ShapeKind,
type SidePanelTab,
+ type StoredAsset,
type TransitionStyle,
type VideoClip,
+ uploadedFontId,
} from "./types";
const round2 = (n: number) => Math.round(n * 100) / 100;
@@ -825,11 +830,14 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
},
watch_video: async (s, input) => {
- const { asset, clip, speed, from, to } = resolveWatchRange(s, input);
+ // A look at a reference project's footage decides a mapping and writes
+ // nothing: no note owed, no frame map kept, no sweep started.
+ const reference = await resolveReferenceWatch(input);
+ const { asset, clip, speed, from, to } = reference ?? resolveWatchRange(s, input);
// The reading of the last look comes before the next one. Without it a
// long source is watched into a conversation that keeps dropping the
// sheets, and the tail arrives with the head already gone.
- const owed = unwritten.get(asset.id);
+ const owed = reference ? undefined : unwritten.get(asset.id);
if (owed && !spanIsNoted(asset.watch, owed))
throw new ToolError(
`You watched ${round2(owed.from)}-${round2(owed.to)}s of "${asset.name}" and have not written down what it showed. ` +
@@ -869,7 +877,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
// landed while this call was decoding, and a merge computed from the
// pre-decode snapshot would overwrite it.
const st = useEditor.getState();
- const liveAsset = st.assets.find((x) => x.id === asset.id);
+ const liveAsset = reference ? undefined : st.assets.find((x) => x.id === asset.id);
if (liveAsset) {
// A pass that covered nothing records nothing.
if (body.coveredTo > from) {
@@ -892,7 +900,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
queueWatchSweep(asset.id);
}
const unwatched = uncoveredSeconds(
- useEditor.getState().assets.find((x) => x.id === asset.id)?.watch,
+ reference ? asset.watch : useEditor.getState().assets.find((x) => x.id === asset.id)?.watch,
asset.duration
);
// Tile the kept frames 3×3 and stamp each cell's source time.
@@ -904,7 +912,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
// the asset's own transcript serves — it is already source time, so it
// fuses for asset-only watches too.
let speech: { start: number; end: number; text: string }[] = [];
- if (clip) {
+ if (clip && !reference) {
speech = laneCues(s.subtitles, s.subtitleLane)
.map((c) => ({
start: retimeOf(clip).srcAt(c.start - clip.start),
@@ -949,6 +957,9 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
to: round2(g.to),
})),
source: { assetId: asset.id, name: asset.name, duration: round2(asset.duration) },
+ ...(reference
+ ? { reference: { projectId: reference.ref.projectId, name: reference.ref.doc.name ?? "" } }
+ : {}),
...(clip
? {
clip: {
@@ -975,8 +986,10 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
}
: {}),
...(timelineText ? { timeline: timelineText } : {}),
- note:
- "Cells read left→right then top→bottom; each stamp is SOURCE seconds. " +
+ note: reference
+ ? "Cells read left→right then top→bottom; each stamp is SOURCE seconds of the reference's file. This is a look at a reference project for deciding which of this project's sources plays its part — nothing is written to the reference and no note is owed." +
+ (sheets ? "" : " (Sheets unavailable — each image is one frame; sheetFrames lists the times.)")
+ : "Cells read left→right then top→bottom; each stamp is SOURCE seconds. " +
"Cells are distinct moments (near-duplicates removed), so gaps between stamps mean nothing changed there. " +
"sheetFrames says why each cell was kept: global = hard cut, action = local motion, settled = new settled detail (text/UI)." +
(unwatched > 0.5
@@ -2987,6 +3000,176 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
};
},
+ read_project: async (_s, input) => {
+ const ref = await openReferenceLink(input.link);
+ const reference = describeDoc(ref.doc, { fullCues: true, chatId: chatOwner() });
+ // Video sources nothing describes: neither a note nor a transcript. A
+ // role for these is decided by name, length and a reference look.
+ const unobserved = (ref.doc.assets ?? [])
+ .filter((a) => a.type === "video" && !a.watch?.notes?.length && !(a.speech && !a.speech.noSpeech))
+ .map((a) => a.id);
+ return {
+ source: {
+ kind: ref.link.kind,
+ id: ref.projectId,
+ name: ref.doc.name ?? "",
+ residency: ref.residency,
+ },
+ ...(ref.partial.length ? { partial: ref.partial } : {}),
+ reference,
+ unobserved,
+ note:
+ "Every item carries the id replicate_project takes; media[].id are the source asset ids for its `media` mapping and for copy_project_media. The document is the edit — watch a reference source (watch_video with project_link) only when its notes and transcript leave what it shows unclear.",
+ };
+ },
+
+ replicate_project: async (s, input) => {
+ const projectId = s.projectId;
+ if (!projectId) throw new ToolError("No project open.");
+ const ref = await openReferenceLink(input.link);
+ const items = Array.isArray(input.items) && input.items.length > 0 ? input.items.map(String) : undefined;
+ const whole = !items;
+ const built = templateFromDoc(ref.doc, { items });
+ if (built.unknownItems.length)
+ throw new ToolError(
+ `The reference has no items with ids ${built.unknownItems.join(", ")}. read_project lists every item and its id.`
+ );
+ const t = built.template;
+ if (t.layers.length === 0 && t.audio.length === 0 && t.texts.length === 0 && t.cues.length === 0)
+ throw new ToolError(whole ? "The reference's timeline is empty." : "None of those items can be placed.");
+ // The role mapping: each reference source the chosen items use plays
+ // from this project's own asset, or copies across.
+ const docAssets = ref.doc.assets ?? [];
+ const mapping = new Map<string, string>();
+ const rawMedia = Array.isArray(input.media) ? input.media : [];
+ for (const entry of rawMedia) {
+ if (!entry || typeof entry !== "object") continue;
+ const e = entry as Record<string, unknown>;
+ const sid = String(e.source_asset_id ?? "");
+ const aid = String(e.asset_id ?? "");
+ const source = docAssets.find((a) => a.id === sid);
+ if (!source) throw new ToolError(`No asset with id ${sid} in the reference. read_project's media lists them.`);
+ const target = s.assets.find((a) => a.id === aid);
+ if (!target) throw new ToolError(`No asset with id ${aid} in this project. See media in the editor state.`);
+ if (!mediaTypeFits(source.type, target.type))
+ throw new ToolError(
+ `"${target.name}" is ${target.type}; the reference's "${source.name}" is ${source.type}, so it cannot play that part.`
+ );
+ mapping.set(sid, aid);
+ }
+ const chatId = chatOwner();
+ const toCopy = built.sourceAssets.filter((a) => !mapping.has(a.id));
+ const landed = await landReferenceAssets(ref, toCopy, projectId, chatId);
+ const landedBySource = new Map(landed.map((l) => [l.sourceId, l.asset]));
+ const assetIds = built.assetByMedia.map(
+ (sid) => mapping.get(sid) ?? landedBySource.get(sid)?.id ?? ""
+ );
+ // A title or the captions set in a font the reference uploaded now
+ // point at the copy of that font.
+ const fontMap = new Map(
+ landed
+ .filter((l) => l.asset.type === "font")
+ .map((l) => [uploadedFontId(l.sourceId), uploadedFontId(l.asset.id)])
+ );
+ const texts = t.texts.map((o) =>
+ isTextOverlay(o) && fontMap.has(o.font) ? { ...o, font: fontMap.get(o.font)! } : o
+ );
+ const captions =
+ t.captions?.font && fontMap.has(t.captions.font)
+ ? { ...t.captions, font: fontMap.get(t.captions.font)! }
+ : t.captions;
+ const pool = [...useEditor.getState().assets];
+ const { template: clamped, adjustments } = clampLayersToAssets({ ...t, texts }, assetIds, pool, {
+ layers: built.itemByLayer.map((id) => `clip ${id}`),
+ audio: built.itemByAudio.map((id) => `soundtrack clip ${id}`),
+ });
+ const chosenClips = (ref.doc.clips ?? []).filter((c) => whole || items!.includes(c.id));
+ const skipped = chosenClips
+ .filter((c) => c.removal)
+ .map((c) => `background removal on clip ${c.id} stayed behind (its matte was baked from the reference's footage)`);
+ const frame = input.frame === undefined ? whole : input.frame === true;
+ const captionLook = input.caption_look === undefined ? whole : input.caption_look === true;
+ const cues = whole && input.captions !== true ? [] : clamped.cues;
+
+ const st = useEditor.getState();
+ const before = {
+ clips: new Set(st.clips.map((c) => c.id)),
+ audio: new Set(st.audioClips.map((c) => c.id)),
+ overlays: new Set(st.overlays.map((o) => o.id)),
+ transitions: new Set(st.transitions.map((x) => x.id)),
+ cues: new Set(st.subtitles.cues.map((c) => c.id)),
+ };
+ st.beginHistoryBatch();
+ try {
+ if (frame && t.project) {
+ st.setAspect(t.project.aspect);
+ st.setBackground(t.project.background);
+ st.setProjectFade({ fadeIn: t.project.fadeIn, fadeOut: t.project.fadeOut });
+ }
+ if (captionLook && captions && Object.keys(captions).length > 0) st.setSubtitlesView(captions);
+ st.insertTemplate({ ...clamped, cues, id: "", addedAt: 0 }, assetIds, playheadAt());
+ } finally {
+ useEditor.getState().endHistoryBatch();
+ }
+ const after = useEditor.getState();
+ const fresh = <T extends { id: string }>(list: T[], seen: Set<string>) =>
+ list.filter((x) => !seen.has(x.id)).map((x) => x.id);
+ return {
+ replicated: whole ? "the whole edit" : `${items!.length} items`,
+ from: { id: ref.projectId, name: ref.doc.name ?? "" },
+ clipIds: fresh(after.clips, before.clips),
+ audioClipIds: fresh(after.audioClips, before.audio),
+ overlayIds: fresh(after.overlays, before.overlays),
+ transitionIds: fresh(after.transitions, before.transitions),
+ cueIds: fresh(after.subtitles.cues, before.cues),
+ mapped: [...mapping].map(([sourceId, assetId]) => ({ sourceId, assetId })),
+ assetIds: landed.filter((l) => !l.reused).map((l) => l.asset.id),
+ copied: landed.map((l) => ({
+ sourceId: l.sourceId,
+ assetId: l.asset.id,
+ name: l.asset.name,
+ kind: l.asset.type,
+ ...(l.reused ? { reused: true } : {}),
+ })),
+ adjustments: adjustments.map((a) => ({ ...a, from: round2(a.from), to: round2(a.to) })),
+ skipped,
+ frame: frame && !!t.project,
+ captionLook: captionLook && !!captions && Object.keys(captions).length > 0,
+ captions: cues.length > 0 ? "cues copied" : "none copied",
+ ...tracksAfter(),
+ };
+ },
+
+ copy_project_media: async (s, input) => {
+ const projectId = s.projectId;
+ if (!projectId) throw new ToolError("No project open.");
+ const ref = await openReferenceLink(input.link);
+ const ids = Array.isArray(input.asset_ids) ? input.asset_ids.map(String) : [];
+ if (ids.length === 0) throw new ToolError("asset_ids is required — the reference assets to copy.");
+ const docAssets = ref.doc.assets ?? [];
+ const chatId = chatOwner();
+ // Another chat's unplaced media is not the reference's to hand over.
+ const placed = placedAssetIds({ clips: ref.doc.clips ?? [], audioClips: ref.doc.audioClips ?? [] });
+ const assets = ids.map((id) => {
+ const a = docAssets.find((x) => x.id === id);
+ if (!a || hiddenFromChat(a, chatId, placed))
+ throw new ToolError(`No asset with id ${id} in the reference. read_project's media lists them.`);
+ return a;
+ });
+ const landed = await landReferenceAssets(ref, assets, projectId, chatId);
+ return {
+ assets: landed.map((l) => ({
+ assetId: l.asset.id,
+ sourceId: l.sourceId,
+ name: l.asset.name,
+ kind: l.asset.type,
+ duration: round2(l.asset.type === "image" ? IMAGE_CLIP_SECONDS : l.asset.duration),
+ ...(l.reused ? { reused: true } : {}),
+ })),
+ note: "The copies preview on cards in this chat; add_clip places one when the user asks for it in the cut. A source this project already held a copy of comes back as that copy, marked reused.",
+ };
+ },
+
library_list: async () => {
const lib = await fetchLibrary();
return {
@@ -4298,6 +4481,73 @@ function resolveWatchRange(
return { projectId, asset, clip, speed, from, to };
}
+/** A reference link the model typed into a tool argument, opened. Every
+ * failure is the reader's own plain reason. */
+async function openReferenceLink(raw: unknown): Promise<ReferenceProject> {
+ const link = parseProjectLink(String(raw ?? ""));
+ if (!link) throw new ToolError("Pass a Donkey Cut project link, share link, or project id.");
+ return openReference(link).catch((e) => {
+ throw new ToolError(e instanceof Error ? e.message : "Could not read that project.");
+ });
+}
+
+/** watch_video aimed at a reference project's source: the same target and
+ * span rules as the open project's, on the reference's document, with the
+ * file played from wherever the reference lives. */
+async function resolveReferenceWatch(
+ input: Record<string, unknown>
+): Promise<(ReturnType<typeof resolveWatchRange> & { ref: ReferenceProject }) | null> {
+ const raw = input.project_link;
+ if (raw === undefined || raw === null || String(raw).trim() === "") return null;
+ const ref = await openReferenceLink(raw);
+ const docAssets = ref.doc.assets ?? [];
+ let stored: StoredAsset | undefined;
+ let clip: ReturnType<typeof resolveWatchTarget>["clip"] = null;
+ if (input.clip_id !== undefined && input.clip_id !== null) {
+ const id = String(input.clip_id);
+ const c =
+ (ref.doc.clips ?? []).find((x) => x.id === id) ??
+ (ref.doc.audioClips ?? []).find((x) => x.id === id);
+ if (!c) throw new ToolError(`No clip with id ${id} in the reference. read_project lists its clips.`);
+ stored = docAssets.find((a) => a.id === c.assetId);
+ clip = c;
+ } else if (input.asset_id !== undefined && input.asset_id !== null) {
+ stored = docAssets.find((a) => a.id === String(input.asset_id));
+ if (!stored)
+ throw new ToolError(`No asset with id ${String(input.asset_id)} in the reference. read_project lists its media.`);
+ } else {
+ throw new ToolError("Pass clip_id or asset_id from the reference — see read_project's videoTrack and media.");
+ }
+ if (!stored) throw new ToolError("That reference clip's media asset is missing.");
+ const asset: MediaAsset = { ...stored, url: await referenceMediaUrl(ref, stored.fileName) };
+ const speed = clip ? retimeOf(clip).rate : 1;
+ const dur = asset.duration > 0 ? asset.duration : Infinity;
+ const from = clamp(isNum(input.from) ? input.from : clip ? clip.in : 0, 0, dur);
+ const to = isNum(input.to)
+ ? clamp(input.to, 0, dur)
+ : clip
+ ? clip.out
+ : Number.isFinite(dur)
+ ? dur
+ : undefined;
+ if (to !== undefined && to <= from)
+ throw new ToolError("from/to describe an empty range of the source.");
+ return { projectId: ref.projectId, asset, clip, speed, from, to, ref };
+}
+
+/** The shared landing, with every failure a plain tool error. */
+async function landReferenceAssets(
+ ref: ReferenceProject,
+ sources: StoredAsset[],
+ projectId: string,
+ chatId: string | null
+): Promise<LandedAsset[]> {
+ if (sources.length === 0) return [];
+ return landReferenceAssetsInto(ref, sources, projectId, { chatId }).catch((e) => {
+ throw new ToolError(e instanceof Error ? e.message : "Could not copy the reference's media.");
+ });
+}
+
/** Scans, a few clips at a time. Each one opens a decoder over its own span of
* the source, and a recut hands this tool every clip it made. */
async function eachScanned<T>(items: T[], run: (item: T) => Promise<void>) {
diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.ts
index e972d9fc..7a44a2b4 100644
--- a/site/src/cut/lib/backend/cloud.ts
+++ b/site/src/cut/lib/backend/cloud.ts
@@ -16,7 +16,9 @@ export function bindCloudSession(base: string, headers: Record<string, string>)
session = { base: base.replace(/\/$/, ""), headers };
}
-function cloudRequest(path: string, init?: RequestInit): Promise<Response> {
+/** A request on the hosted site as this process's user: same-origin in the
+ * page, the bound session's origin and headers in a headless process. */
+export function cloudRequest(path: string, init?: RequestInit): Promise<Response> {
if (!session) return fetch(path, init);
return fetch(session.base + path, {
...init,
diff --git a/site/src/cut/lib/backend/shared.test.ts b/site/src/cut/lib/backend/shared.test.ts
new file mode 100644
index 00000000..e645aea5
--- /dev/null
+++ b/site/src/cut/lib/backend/shared.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, test } from "bun:test";
+
+import { sharedBackendFor } from "./shared";
+
+describe("sharedBackendFor", () => {
+ test("rewrites the engine's route shapes under its own share", () => {
+ const a = sharedBackendFor("tok-a");
+ const b = sharedBackendFor("tok b");
+ expect(a.url("/api/cut/projects/p1")).toBe("/api/cut-shared/tok-a/projects/p1");
+ expect(a.url("/api/cut/projects/p1/media/clip%201.mp4")).toBe(
+ "/api/cut-shared/tok-a/projects/p1/media/clip%201.mp4"
+ );
+ expect(b.url("/api/cut/projects/p1")).toBe("/api/cut-shared/tok%20b/projects/p1");
+ });
+
+ test("the bare prefix is the share's own meta route", () => {
+ expect(sharedBackendFor("tok").url("/api/cut/")).toBe("/api/cut-shared/tok");
+ expect(sharedBackendFor("tok").url("/api/cut")).toBe("/api/cut-shared/tok");
+ });
+});
diff --git a/site/src/cut/lib/backend/shared.ts b/site/src/cut/lib/backend/shared.ts
index dffcdbbf..8d2d171e 100644
--- a/site/src/cut/lib/backend/shared.ts
+++ b/site/src/cut/lib/backend/shared.ts
@@ -1,21 +1,21 @@
// The shared backend: a read-only view of someone else's cloud project,
// reached through the public /api/cut-shared/<token>/* surface. The token is
-// the share link's id; the viewer page binds it before the editor mounts.
-// Reads only — the viewer never PUTs, so there is no write-conflict version
-// map here; the version it does keep is the one the last doc actually
-// delivered, which is what tells the change poll whether a reload landed.
+// the share link's id. The viewer page binds one token before the editor
+// mounts; the assistant's reference tools open a backend per link, so a
+// share read never disturbs the one the viewer is showing. Reads only — a
+// viewer never PUTs, so there is no write-conflict version map here; the
+// version kept is the one the last doc actually delivered, which is what
+// tells the change poll whether a reload landed.
+import { cloudRequest } from "./cloud";
import type { CutBackend } from "./types";
-let token = "";
+let boundToken = "";
/** Bind the share link token before bindCutMode("shared"). */
export function bindSharedBackend(next: string) {
- token = next;
+ boundToken = next;
}
-const sharedPath = (path: string) =>
- path.replace(/^\/api\/cut\//, `/api/cut-shared/${encodeURIComponent(token)}/`);
-
// /projects/:id only — /projects/folders is the folder collection, not a doc.
const PROJECT_DOC = /^\/api\/cut\/projects\/(?!folders$)([^/?]+)$/;
@@ -30,17 +30,41 @@ export function loadedDocVersion(projectId: string): string | null {
return loadedVersions.get(projectId) ?? null;
}
-async function sharedFetch(path: string, init?: RequestInit): Promise<Response> {
- const res = await fetch(sharedPath(path), init);
- const doc = PROJECT_DOC.exec(path);
- const method = (init?.method ?? "GET").toUpperCase();
- if (doc && method === "GET" && res.ok) {
- const version = res.headers.get("x-cut-doc-version");
- if (version) loadedVersions.set(decodeURIComponent(doc[1]), version);
- }
- return res;
+/** A backend reading one share. The engine's route shapes rewrite under the
+ * share's prefix; the bare prefix is the share's own meta route. The request
+ * rides the cloud transport, so a headless process bound to a hosted origin
+ * reaches the share the same way it reaches its own projects. */
+export function sharedBackendFor(token: string): CutBackend {
+ const prefix = `/api/cut-shared/${encodeURIComponent(token)}`;
+ const sharedPath = (path: string) => {
+ const rest = path.replace(/^\/api\/cut\/?/, "");
+ return rest ? `${prefix}/${rest}` : prefix;
+ };
+ return {
+ kind: "shared",
+ caps: {
+ importUrl: false,
+ liveMic: false,
+ transcribe: false,
+ captionAi: false,
+ revealInFinder: false,
+ watch: false,
+ },
+ fetch: async (path, init) => {
+ const res = await cloudRequest(sharedPath(path), init);
+ const doc = PROJECT_DOC.exec(path);
+ const method = (init?.method ?? "GET").toUpperCase();
+ if (doc && method === "GET" && res.ok) {
+ const version = res.headers.get("x-cut-doc-version");
+ if (version) loadedVersions.set(decodeURIComponent(doc[1]), version);
+ }
+ return res;
+ },
+ url: (path) => sharedPath(path),
+ };
}
+/** The viewer page's backend: the token bound before the editor mounted. */
export const sharedBackend: CutBackend = {
kind: "shared",
caps: {
@@ -51,6 +75,6 @@ export const sharedBackend: CutBackend = {
revealInFinder: false,
watch: false,
},
- fetch: sharedFetch,
- url: (path) => sharedPath(path),
+ fetch: (path, init) => sharedBackendFor(boundToken).fetch(path, init),
+ url: (path) => sharedBackendFor(boundToken).url(path),
};
diff --git a/site/src/cut/lib/fixtures/richDoc.ts b/site/src/cut/lib/fixtures/richDoc.ts
new file mode 100644
index 00000000..65325875
--- /dev/null
+++ b/site/src/cut/lib/fixtures/richDoc.ts
@@ -0,0 +1,127 @@
+// A finished edit as a stored document, carrying one of everything a
+// template can hold: framing, rate, grade, mask, keys, a box-styled layer,
+// transition bars at every edge, a look as an effect element, a grouped
+// keyed title, a title in an uploaded font, a sticker, a music bed with
+// fades, captions in a look, and the project's frame. Tests describe it,
+// template it, and replicate it.
+
+import { transitionBarStart, type ProjectDoc } from "../types";
+
+export const RICH_CLIP_S = 10;
+
+export function richDoc(): ProjectDoc {
+ const now = 1_700_000_000_000;
+ const c0Len = RICH_CLIP_S / 1.25;
+ return {
+ version: 1,
+ id: "rich",
+ name: "Rich edit",
+ createdAt: now,
+ updatedAt: now,
+ aspect: "16:9",
+ background: "#102030",
+ fadeIn: 0.3,
+ fadeOut: 0.4,
+ assets: [
+ {
+ id: "v0",
+ fileName: "clip-0.mp4",
+ name: "host.mp4",
+ type: "video",
+ duration: RICH_CLIP_S,
+ width: 1280,
+ height: 720,
+ watch: {
+ ranges: [{ from: 0, to: RICH_CLIP_S }],
+ frames: [{ t: 0, via: "global" }],
+ sceneChanges: [],
+ notes: [{ from: 0, to: RICH_CLIP_S, text: "a host talks to camera" }],
+ },
+ speech: {
+ ranges: [{ from: 0, to: RICH_CLIP_S }],
+ segments: [{ start: 0, end: 4, text: "hello and welcome" }],
+ },
+ },
+ { id: "v1", fileName: "clip-1.mp4", name: "broll.mp4", type: "video", duration: RICH_CLIP_S, width: 1280, height: 720 },
+ { id: "m0", fileName: "music.m4a", name: "bed.m4a", type: "audio", duration: 8, origin: "generated", beats: { beats: [0.5, 1, 1.5], bpm: 120 } },
+ { id: "s0", fileName: "arrow.png", name: "arrow.png", type: "image", duration: 0, width: 200, height: 200, origin: "sticker" },
+ { id: "f0", fileName: "brand.ttf", name: "Brand", type: "font", duration: 0 },
+ ],
+ clips: [
+ {
+ id: "c0", assetId: "v0", track: 0, start: 0, in: 0, out: RICH_CLIP_S,
+ muted: false, volume: 0.8,
+ fit: "fill", zoom: 1.4, panX: 0.3, panY: -0.2,
+ speed: 1.25,
+ },
+ {
+ id: "c1", assetId: "v1", track: 0, start: c0Len, in: 0, out: RICH_CLIP_S,
+ muted: false,
+ fit: "fit",
+ grade: { brightness: 5, contrast: 8, saturation: -10, temperature: 12, hue: 10 },
+ mask: { kind: "circle", w: 0.7, h: 0.7, feather: 20 },
+ kf: [
+ { t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 0, opacity: 1 },
+ { t: 2, x: 0.6, y: 0.4, scale: 0.85, rotation: 12, opacity: 1 },
+ ],
+ },
+ {
+ id: "c2", assetId: "v0", track: 1, start: 1, in: 0, out: 1.5,
+ muted: true,
+ frame: { x: 0.55, y: 0.05, w: 0.4, h: 0.4 },
+ fit: "fill", rotation: 5, opacity: 0.9,
+ boxStyle: { radius: 24, borderWidth: 4, borderColor: "#ffffff" },
+ hidden: false,
+ },
+ ],
+ transitions: [
+ { id: "tr-in", start: 0, seconds: 0.4, style: "crossfade" },
+ { id: "tr0", start: transitionBarStart("crossfade", "cut", c0Len, 0.5), seconds: 0.5, style: "crossfade" },
+ { id: "tr-out", start: transitionBarStart("crosszoom", "out", c0Len + RICH_CLIP_S, 0.5), seconds: 0.5, style: "crosszoom" },
+ ],
+ audioClips: [
+ { id: "a0", assetId: "m0", start: 0, in: 0, out: 5, volume: 0.5, fadeIn: 0.3, fadeOut: 0.5, lane: 0, duck: 0.4 },
+ ],
+ overlays: [
+ {
+ id: "e0", kind: "effect", effect: "vintage", amount: 0.6,
+ start: 0, end: c0Len, x: 0.5, y: 0.5, lane: 2, hostClipId: "c0",
+ },
+ {
+ id: "t0", kind: "text", text: "Everything test",
+ start: 0.5, end: 3, x: 0.5, y: 0.2, lane: 0,
+ size: 64, font: "sf", weight: 700, color: "#FFFFFF",
+ shadow: true, plate: true, groupId: "g1",
+ kf: [
+ { t: 0, x: 0.5, y: 0.2, scale: 1, rotation: 0, opacity: 0 },
+ { t: 0.5, x: 0.5, y: 0.2, scale: 1, rotation: 0, opacity: 1 },
+ ],
+ },
+ {
+ id: "t1", kind: "text", text: "Brand line",
+ start: 3, end: 5, x: 0.5, y: 0.8, lane: 0,
+ size: 48, font: "asset:f0", weight: 400, color: "#FFDD00",
+ shadow: false, plate: false, groupId: "g1",
+ },
+ {
+ id: "s1", kind: "sticker", assetId: "s0", w: 0.2,
+ start: 2, end: 4, x: 0.8, y: 0.3, lane: 1,
+ },
+ ],
+ subtitles: {
+ cues: [
+ { id: "q0", start: 0.3, end: 1.2, text: "every feature" },
+ { id: "q1", start: 1.4, end: 2.2, text: "in one render" },
+ ],
+ showOnVideo: true,
+ showOnTimeline: false,
+ style: "bubble",
+ size: 60,
+ wordsPerCue: 3,
+ wordHighlight: true,
+ accentColor: "#FF3366",
+ x: 0.5,
+ y: 0.85,
+ },
+ };
+}
diff --git a/site/src/cut/lib/itemKinds.ts b/site/src/cut/lib/itemKinds.ts
new file mode 100644
index 00000000..5cab74d9
--- /dev/null
+++ b/site/src/cut/lib/itemKinds.ts
@@ -0,0 +1,180 @@
+// The timeline's item kinds, in one table.
+//
+// Every kind of thing a person can select on the timeline — a clip, a
+// soundtrack clip, an element, a caption cue, a transition bar — is one entry
+// here, and the entry says what the editor needs to know about it to move it
+// around: where it lives, which assets it plays, how to point it at other
+// assets, and what it sheds when it leaves its project. The clipboard, the
+// cross-project paste, the template rail and the media garbage collector all
+// read this table, so an item kind is copyable, pasteable, templatable and
+// GC-safe by construction.
+//
+// The table is typed against `Selection`, so adding a kind there fails to
+// compile until it has an entry, and `itemKinds.test.ts` walks the table so
+// every entry proves it copies and pastes.
+
+import {
+ fontAssetId,
+ isStickerOverlay,
+ isTextOverlay,
+ uploadedFontId,
+ type AudioClip,
+ type Overlay,
+ type Selection,
+ type SubtitleCue,
+ type TimelineTransition,
+ type VideoClip,
+} from "./types";
+
+export type ItemKind = NonNullable<Selection>["kind"];
+
+/** The item type behind each kind. */
+export interface ItemOf {
+ clip: VideoClip;
+ audio: AudioClip;
+ overlay: Overlay;
+ cue: SubtitleCue;
+ transition: TimelineTransition;
+}
+
+/** One item as the clipboard holds it: the item whole, ids and all, so a
+ * paste can remap what it must and keep the rest. */
+export type TimelineClipboardItem = { [K in ItemKind]: { kind: K; item: ItemOf[K] } }[ItemKind];
+
+/** The lists the items live in, as the store and a document both hold them. */
+export interface ItemLists {
+ clips: VideoClip[];
+ audioClips: AudioClip[];
+ overlays: Overlay[];
+ transitions: TimelineTransition[];
+ subtitles: { cues: SubtitleCue[] };
+}
+
+export interface ItemKindDef<K extends ItemKind> {
+ /** The list this kind lives in. */
+ list(s: ItemLists): ItemOf[K][];
+ /** A copy that shares nothing with the original. */
+ clone(item: ItemOf[K]): ItemOf[K];
+ /** Every asset id on the item: the media it plays, the font it is set in,
+ * the mattes baked for it. The one place that knows where ids sit. */
+ assetIds(item: ItemOf[K]): string[];
+ /** The item with every asset id rewritten through `to`. */
+ remapAssets(item: ItemOf[K], to: (id: string) => string): ItemOf[K];
+ /** The item as it leaves its project: parts baked against that project's
+ * media stay behind. */
+ crossProject(item: ItemOf[K]): ItemOf[K];
+}
+
+const deep = <T>(v: T): T => (v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T));
+
+export const ITEM_KINDS: { [K in ItemKind]: ItemKindDef<K> } = {
+ clip: {
+ list: (s) => s.clips,
+ clone: deep,
+ assetIds: (c) =>
+ [c.assetId, c.removal?.matte?.assetId, c.removal?.backdrop?.assetId].filter(
+ (id): id is string => typeof id === "string" && id.length > 0
+ ),
+ remapAssets: (c, to) => ({
+ ...c,
+ assetId: to(c.assetId),
+ ...(c.removal
+ ? {
+ removal: {
+ ...c.removal,
+ ...(c.removal.matte?.assetId ? { matte: { ...c.removal.matte, assetId: to(c.removal.matte.assetId) } } : {}),
+ ...(c.removal.backdrop?.assetId
+ ? { backdrop: { ...c.removal.backdrop, assetId: to(c.removal.backdrop.assetId) } }
+ : {}),
+ },
+ }
+ : {}),
+ }),
+ // A background removal's matte was baked from this project's footage,
+ // and a clip arriving with a removal and no matte would start a fresh
+ // bake on its own.
+ crossProject: (c) => {
+ const out = { ...c };
+ delete out.removal;
+ return out;
+ },
+ },
+ audio: {
+ list: (s) => s.audioClips,
+ clone: deep,
+ assetIds: (a) => (a.assetId ? [a.assetId] : []),
+ remapAssets: (a, to) => ({ ...a, assetId: to(a.assetId) }),
+ crossProject: (a) => a,
+ },
+ overlay: {
+ list: (s) => s.overlays,
+ clone: deep,
+ assetIds: (o) => {
+ if (isStickerOverlay(o)) return o.assetId ? [o.assetId] : [];
+ if (isTextOverlay(o)) {
+ const font = o.font ? fontAssetId(o.font) : null;
+ return font ? [font] : [];
+ }
+ return [];
+ },
+ remapAssets: (o, to) => {
+ if (isStickerOverlay(o)) return o.assetId ? { ...o, assetId: to(o.assetId) } : o;
+ if (isTextOverlay(o)) {
+ const font = o.font ? fontAssetId(o.font) : null;
+ return font ? { ...o, font: uploadedFontId(to(font)) } : o;
+ }
+ return o;
+ },
+ crossProject: (o) => o,
+ },
+ cue: {
+ list: (s) => s.subtitles.cues,
+ clone: deep,
+ assetIds: () => [],
+ remapAssets: (c) => c,
+ crossProject: (c) => c,
+ },
+ transition: {
+ list: (s) => s.transitions,
+ clone: deep,
+ assetIds: () => [],
+ remapAssets: (t) => t,
+ crossProject: (t) => t,
+ },
+};
+
+export const ITEM_KIND_IDS = Object.keys(ITEM_KINDS) as ItemKind[];
+
+/** The item a selection names, as a clipboard item, or null when gone. */
+export function clipboardItemFor(s: ItemLists, sel: NonNullable<Selection>): TimelineClipboardItem | null {
+ const def = ITEM_KINDS[sel.kind] as ItemKindDef<ItemKind>;
+ const item = (def.list(s) as { id: string }[]).find((x) => x.id === sel.id);
+ return item ? ({ kind: sel.kind, item: def.clone(item as never) } as TimelineClipboardItem) : null;
+}
+
+/** Every asset id a clipboard item names. */
+export const clipboardItemAssetIds = (cb: TimelineClipboardItem): string[] =>
+ (ITEM_KINDS[cb.kind] as ItemKindDef<ItemKind>).assetIds(cb.item as never);
+
+/** A clipboard item as it lands in another project: what crosses, on the
+ * copies' ids. */
+export function clipboardItemAcross(cb: TimelineClipboardItem, to: (id: string) => string): TimelineClipboardItem {
+ const def = ITEM_KINDS[cb.kind] as ItemKindDef<ItemKind>;
+ return { kind: cb.kind, item: def.remapAssets(def.crossProject(cb.item as never), to) } as TimelineClipboardItem;
+}
+
+/** Every asset id the lists name: the media the timeline plays and what is
+ * baked or set on it. */
+export function listedAssetIds(s: ItemLists): Set<string> {
+ const used = new Set<string>();
+ for (const kind of ITEM_KIND_IDS) {
+ const def = ITEM_KINDS[kind] as ItemKindDef<ItemKind>;
+ for (const item of def.list(s) as never[]) for (const id of def.assetIds(item)) used.add(id);
+ }
+ return used;
+}
+
+/** A switch over kinds is complete or it does not compile. */
+export const assertNever = (x: never): never => {
+ throw new Error(`Unhandled item kind ${String(x)}`);
+};
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index e0b25ef7..2aeced5b 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -867,6 +867,10 @@ export async function carryTemplateTo(
audio: t.audio,
texts: t.texts,
cues: t.cues,
+ ...(t.transitions ? { transitions: t.transitions } : {}),
+ ...(t.stickers ? { stickers: t.stickers } : {}),
+ ...(t.captions ? { captions: t.captions } : {}),
+ ...(t.project ? { project: t.project } : {}),
};
const backend = backendFor(to);
let res: Response;
@@ -1052,6 +1056,10 @@ export async function importTemplateToProject(
audio: template.audio,
texts: template.texts,
cues: template.cues,
+ ...(template.transitions ? { transitions: template.transitions } : {}),
+ ...(template.stickers ? { stickers: template.stickers } : {}),
+ ...(template.captions ? { captions: template.captions } : {}),
+ ...(template.project ? { project: template.project } : {}),
});
}
diff --git a/site/src/cut/lib/pi/mutationLedger.ts b/site/src/cut/lib/pi/mutationLedger.ts
index d2625805..b330e727 100644
--- a/site/src/cut/lib/pi/mutationLedger.ts
+++ b/site/src/cut/lib/pi/mutationLedger.ts
@@ -18,6 +18,7 @@ const READ_ONLY = new Set([
"listen_audio",
"measure_level",
"read_color_stats",
+ "read_project",
"library_list",
"library_list_folder",
"stock_search",
@@ -52,6 +53,12 @@ const ID_FIELDS = [
"jobId",
"trackId",
"removed",
+ "clipIds",
+ "audioClipIds",
+ "overlayIds",
+ "transitionIds",
+ "cueIds",
+ "assetIds",
];
export function harvestIds(response: unknown): string[] {
diff --git a/site/src/cut/lib/projectLink.test.ts b/site/src/cut/lib/projectLink.test.ts
new file mode 100644
index 00000000..dc7c6b07
--- /dev/null
+++ b/site/src/cut/lib/projectLink.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from "bun:test";
+
+import { parseProjectLink } from "./projectLink";
+
+describe("parseProjectLink", () => {
+ test("a project page link names the project", () => {
+ expect(parseProjectLink("https://donkeycut.com/app/p/abc-123")).toEqual({ kind: "project", id: "abc-123" });
+ expect(parseProjectLink("donkeycut.com/app/p/abc-123?from=home")).toEqual({ kind: "project", id: "abc-123" });
+ expect(parseProjectLink("http://127.0.0.1:41417/cut/app/p/starter-u1#x")).toEqual({ kind: "project", id: "starter-u1" });
+ expect(parseProjectLink(" https://donkeycut.com/app/p/abc/ ")).toEqual({ kind: "project", id: "abc" });
+ });
+
+ test("a share link names the token", () => {
+ expect(parseProjectLink("https://donkeycut.com/s/tok_ABC-9")).toEqual({ kind: "share", token: "tok_ABC-9" });
+ expect(parseProjectLink("donkeycut.com/cut/s/tok")).toEqual({ kind: "share", token: "tok" });
+ });
+
+ test("a bare id is a project", () => {
+ expect(parseProjectLink("cmf1abc2")).toEqual({ kind: "project", id: "cmf1abc2" });
+ });
+
+ test("anything else is refused", () => {
+ expect(parseProjectLink("")).toBeNull();
+ expect(parseProjectLink("https://youtube.com/watch?v=abc")).toBeNull();
+ expect(parseProjectLink("https://donkeycut.com/app")).toBeNull();
+ expect(parseProjectLink("https://donkeycut.com/app/p/a b")).toBeNull();
+ expect(parseProjectLink("https://a.com/app/p/x https://b.com/app/p/y")).toBeNull();
+ expect(parseProjectLink("mailto:[email protected]")).toBeNull();
+ });
+});
diff --git a/site/src/cut/lib/projectLink.ts b/site/src/cut/lib/projectLink.ts
new file mode 100644
index 00000000..d1e55c13
--- /dev/null
+++ b/site/src/cut/lib/projectLink.ts
@@ -0,0 +1,35 @@
+// A Donkey Cut link as the assistant's tools take it: the project page
+// (/app/p/<id>), a share link (/s/<token>), or a bare project id. The model
+// hands the link over in a typed argument; this only reads its shape. What
+// the link opens — the project's home, the share's grant — is the reader's
+// to resolve.
+
+import { normalizeLink } from "./link";
+
+export type ProjectLink = { kind: "project"; id: string } | { kind: "share"; token: string };
+
+const ID_RE = /^[A-Za-z0-9_-]+$/;
+
+/** The project page and the share page, with or without the physical /cut
+ * prefix the host rewrite hides. */
+const PROJECT_PATH = /^\/(?:cut\/)?app\/p\/([^/]+)\/?$/;
+const SHARE_PATH = /^\/(?:cut\/)?s\/([^/]+)\/?$/;
+
+export function parseProjectLink(value: string): ProjectLink | null {
+ const v = value.trim();
+ if (!v || /\s/.test(v)) return null;
+ if (ID_RE.test(v)) return { kind: "project", id: v };
+ let url: URL;
+ try {
+ url = new URL(normalizeLink(v));
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
+ const path = decodeURIComponent(url.pathname);
+ const project = PROJECT_PATH.exec(path);
+ if (project && ID_RE.test(project[1])) return { kind: "project", id: project[1] };
+ const share = SHARE_PATH.exec(path);
+ if (share && ID_RE.test(share[1])) return { kind: "share", token: share[1] };
+ return null;
+}
diff --git a/site/src/cut/lib/projectReference.ts b/site/src/cut/lib/projectReference.ts
new file mode 100644
index 00000000..0d76ac98
--- /dev/null
+++ b/site/src/cut/lib/projectReference.ts
@@ -0,0 +1,199 @@
+// Reading another Donkey Cut project as a reference for the assistant: its
+// document, and the bytes of any of its media a copy needs. A project of the
+// user's own is reached through whichever home holds it; a share link
+// through the share's own read-only surface. Reads only — nothing here
+// touches the reference.
+//
+// A headless engine holds its projects on disk, so it installs a host store
+// and this module reads the folder directly; a cloud or shared reference
+// needs the editor page's sign-in there and is refused with a plain reason.
+
+import { getBackend, type CutBackend } from "./backend";
+import { sharedBackendFor } from "./backend/shared";
+import { apiJson } from "./api";
+import { tagChatAsset } from "./chatAssets";
+import { registerFontAsset } from "./fontAssets";
+import { enrichAsset, uploadProjectMediaTo } from "./media";
+import { localMediaFile, storedMediaUrl } from "./mediaSync";
+import type { ProjectLink } from "./projectLink";
+import { projectBackend } from "./residency";
+import { useEditor } from "./store";
+import type { MediaAsset, ProjectDoc, ShareFeatures, StoredAsset } from "./types";
+
+/** What a headless host does for itself: read a project it stores, copy a
+ * media file between two of its projects. */
+export interface HostDocStore {
+ readDoc(projectId: string): Promise<ProjectDoc | null>;
+ copyMedia(srcProjectId: string, fileName: string, dstProjectId: string): Promise<string>;
+}
+
+let host: HostDocStore | null = null;
+
+export function setHostDocStore(store: HostDocStore | null) {
+ host = store;
+}
+
+export type ReferenceResidency = "local" | "cloud" | "browser" | "shared";
+
+export interface ReferenceProject {
+ link: ProjectLink;
+ projectId: string;
+ doc: ProjectDoc;
+ residency: ReferenceResidency;
+ /** The backend the reference reads through; null when the host store
+ * answered from disk. */
+ backend: CutBackend | null;
+ /** What a share withheld from the document, in the reader's words. */
+ partial: string[];
+}
+
+const BROWSER_ONLY =
+ "A project kept in a browser's own storage is readable only from that browser.";
+
+export async function openReference(link: ProjectLink): Promise<ReferenceProject> {
+ if (link.kind === "share") return openShare(link.token, link);
+ const id = link.id;
+ if (host) {
+ const doc = await host.readDoc(id);
+ if (!doc)
+ throw new Error(
+ `No project with id ${id} on this Mac. Reading a cloud or shared project needs the editor page's sign-in; open the chat in the editor to read it.`
+ );
+ return { link, projectId: id, doc, residency: "local", backend: null, partial: [] };
+ }
+ const backend = await projectBackend(id);
+ const res = await backend.fetch(`/api/cut/projects/${encodeURIComponent(id)}`);
+ if (res.status === 404)
+ throw new Error(`No project with id ${id} that this account can open. ${BROWSER_ONLY}`);
+ if (!res.ok) throw new Error(`Could not read project ${id} (${res.status}).`);
+ const doc = (await res.json()) as ProjectDoc;
+ const residency: ReferenceResidency =
+ backend.kind === "local" || backend.kind === "browser" ? backend.kind : "cloud";
+ return { link, projectId: id, doc, residency, backend, partial: [] };
+}
+
+async function openShare(token: string, link: ProjectLink): Promise<ReferenceProject> {
+ if (host)
+ throw new Error(
+ "Reading a shared project needs the editor page's sign-in; open the chat in the editor to read it."
+ );
+ const backend = sharedBackendFor(token);
+ const meta = await backend.fetch("/api/cut/");
+ if (meta.status === 401) throw new Error("Sign in to open that share.");
+ if (meta.status === 403) throw new Error("This account was not invited to that share.");
+ if (meta.status === 404) throw new Error("That share link does not exist.");
+ if (!meta.ok) throw new Error(`Could not open that share (${meta.status}).`);
+ const info = await apiJson<{ projectId?: string; features?: ShareFeatures }>(meta);
+ if (!info.projectId) throw new Error(info.error ?? "Could not open that share.");
+ const res = await backend.fetch(`/api/cut/projects/${encodeURIComponent(info.projectId)}`);
+ if (!res.ok) throw new Error(`Could not read the shared project (${res.status}).`);
+ const doc = (await res.json()) as ProjectDoc;
+ const partial: string[] = [];
+ const f = info.features;
+ if (f && !f.subtitles) partial.push("the caption track and caption look");
+ if (f && !f.media) partial.push("media the timeline does not use");
+ if (f && !f.genai) partial.push("generated media the timeline does not use");
+ return { link, projectId: info.projectId, doc, residency: "shared", backend, partial };
+}
+
+/** Where this page can play a reference's file from. The share surface
+ * answers its media route with a signed redirect the decoders follow. */
+export async function referenceMediaUrl(ref: ReferenceProject, fileName: string): Promise<string> {
+ const path = `/api/cut/projects/${encodeURIComponent(ref.projectId)}/media/${encodeURIComponent(fileName)}`;
+ if (!ref.backend) return getBackend().url(path);
+ if (ref.backend.kind === "shared") return ref.backend.url(path);
+ return storedMediaUrl(ref.projectId, fileName, ref.backend);
+}
+
+/** One reference file's bytes, read the way a project copy reads them. */
+async function referenceMediaBlob(ref: ReferenceProject, asset: StoredAsset): Promise<Blob> {
+ if (!ref.backend) throw new Error("No transport for the reference's media.");
+ const local = ref.backend.kind === "cloud" ? await localMediaFile(ref.projectId, asset.fileName) : null;
+ if (local) return local;
+ const res = await ref.backend.fetch(
+ `/api/cut/projects/${encodeURIComponent(ref.projectId)}/media/${encodeURIComponent(asset.fileName)}`
+ );
+ if (!res.ok) throw new Error(`Could not read “${asset.name}” from the reference.`);
+ return res.blob();
+}
+
+/** Copy reference files into a project, one by one; each lands under the
+ * name the target hands back. */
+export async function copyReferenceMedia(
+ ref: ReferenceProject,
+ assets: StoredAsset[],
+ dstProjectId: string,
+ dstBackend: CutBackend = getBackend()
+): Promise<{ source: StoredAsset; fileName: string }[]> {
+ const out: { source: StoredAsset; fileName: string }[] = [];
+ for (const source of assets) {
+ const fileName = host
+ ? await host.copyMedia(ref.projectId, source.fileName, dstProjectId)
+ : await uploadProjectMediaTo(dstBackend, dstProjectId, await referenceMediaBlob(ref, source), source.fileName);
+ out.push({ source, fileName });
+ }
+ return out;
+}
+
+/** A reference asset as it stands in the open project after a copy. */
+export interface LandedAsset {
+ sourceId: string;
+ asset: MediaAsset;
+ /** The project already held a copy of this source, so nothing was copied. */
+ reused: boolean;
+}
+
+/**
+ * Reference files copied into the open project and registered as its assets.
+ * The notes, transcript and beat grid written against the source ride along,
+ * a font installs so titles set in it draw, and each copy remembers where it
+ * came from, so the same source pasted or replicated twice lands once. A
+ * chat's copies preview on its cards; a keyboard paste is the user's own
+ * import.
+ */
+export async function landReferenceAssets(
+ ref: ReferenceProject,
+ sources: StoredAsset[],
+ projectId: string,
+ opts: { chatId?: string | null } = {}
+): Promise<LandedAsset[]> {
+ const out: LandedAsset[] = [];
+ const toCopy: StoredAsset[] = [];
+ for (const source of sources) {
+ const have = useEditor
+ .getState()
+ .assets.find((a) => a.copiedFrom?.projectId === ref.projectId && a.copiedFrom.assetId === source.id);
+ if (have) out.push({ sourceId: source.id, asset: have, reused: true });
+ else toCopy.push(source);
+ }
+ const copied = await copyReferenceMedia(ref, toCopy, projectId);
+ for (const { source, fileName } of copied) {
+ // The copy is this project's: a fresh id, no chat or folder of the
+ // reference's, and the card the asking chat tags below.
+ const asset: MediaAsset = {
+ ...source,
+ id: crypto.randomUUID().slice(0, 8),
+ fileName,
+ url: await storedMediaUrl(projectId, fileName),
+ copiedFrom: { projectId: ref.projectId, assetId: source.id },
+ };
+ delete asset.chatId;
+ delete asset.folderId;
+ // A keyboard paste is the user's own import, so the copy lists in the
+ // Media panel like one; a sticker stays a sticker. A chat's copy keeps
+ // the source's origin under the chat tag below.
+ if (opts.chatId === undefined && asset.origin !== "sticker") delete asset.origin;
+ // The bytes landed in `projectId`; the record lands only if that project
+ // is still the open one.
+ if (useEditor.getState().projectId !== projectId)
+ throw new Error("The project closed while its media was landing.");
+ useEditor.getState().addAsset(asset);
+ if (opts.chatId !== undefined) tagChatAsset(asset.id, opts.chatId);
+ if (asset.type === "font") void registerFontAsset(asset).catch(() => {});
+ else void enrichAsset(asset).catch(() => {});
+ out.push({ sourceId: source.id, asset, reused: false });
+ }
+ // In the order asked for, so a caller's index arithmetic holds.
+ const bySource = new Map(out.map((l) => [l.sourceId, l]));
+ return sources.map((s) => bySource.get(s.id)!);
+}
diff --git a/site/src/cut/lib/projectTemplate.test.ts b/site/src/cut/lib/projectTemplate.test.ts
new file mode 100644
index 00000000..83e6f131
--- /dev/null
+++ b/site/src/cut/lib/projectTemplate.test.ts
@@ -0,0 +1,265 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+
+import { richDoc, RICH_CLIP_S } from "./fixtures/richDoc";
+import { clampLayersToAssets, templateFromDoc } from "./projectTemplate";
+import { resolveTransitions, useEditor } from "./store";
+import { emptySubtitles, isStickerOverlay, isTextOverlay, type MediaAsset, type TemplateSaveInput } from "./types";
+
+/**
+ * The template rail carries a whole edit: what a document holds is what a
+ * template holds, and what a template holds is what stands up on another
+ * timeline. Losing a grade, a key, a bar, or a sticker on the way through
+ * would make a replicate a different video.
+ */
+
+const asset = (id: string, type: MediaAsset["type"], duration: number): MediaAsset => ({
+ id,
+ fileName: `${id}.bin`,
+ name: id,
+ type,
+ duration,
+ url: "",
+});
+
+describe("templateFromDoc", () => {
+ test("the whole edit keeps every treatment, bar, sticker and font", () => {
+ const { template: t, assetByMedia, sourceAssets } = templateFromDoc(richDoc());
+ expect([...assetByMedia].sort()).toEqual(["f0", "m0", "s0", "v0", "v1"]);
+ expect(sourceAssets.map((a) => a.fileName).sort()).toEqual(["arrow.png", "brand.ttf", "clip-0.mp4", "clip-1.mp4", "music.m4a"]);
+ const [l0, l1, l2] = t.layers;
+ expect(l0).toMatchObject({ media: 0, start: 0, asClip: true, track: 1, speed: 1.25, volume: 0.8, fit: "fill", zoom: 1.4 });
+ expect(t.texts.find((o) => o.id === "e0")).toMatchObject({ kind: "effect", effect: "vintage", amount: 0.6 });
+ expect(l1).toMatchObject({ media: 1, asClip: true, mask: { kind: "circle", w: 0.7, h: 0.7, feather: 20 } });
+ expect(l1.grade).toEqual({ brightness: 5, contrast: 8, saturation: -10, temperature: 12, hue: 10 });
+ expect(l1.kf).toHaveLength(2);
+ expect(l2).toMatchObject({ media: 0, track: 2, boxStyle: { radius: 24, borderWidth: 4, borderColor: "#ffffff" }, rotation: 5, opacity: 0.9 });
+ expect(l2.asClip).toBeUndefined();
+ expect(t.audio[0]).toMatchObject({ media: 2, volume: 0.5, fadeIn: 0.3, fadeOut: 0.5, duck: 0.4 });
+ // The head fade, the cut, and the tail zoom: every edge is a bar.
+ expect(t.transitions!.map((b) => b.id)).toEqual(["tr-in", "tr0", "tr-out"]);
+ expect(t.transitions![1]).toMatchObject({ seconds: 0.5, style: "crossfade" });
+ expect(t.stickers).toEqual([{ text: t.texts.findIndex((o) => o.id === "s1"), media: assetByMedia.indexOf("s0") }]);
+ expect(t.texts).toHaveLength(4);
+ expect(t.cues).toHaveLength(2);
+ expect(t.captions).toEqual({ showOnVideo: true, style: "bubble", size: 60, wordsPerCue: 3, wordHighlight: true, accentColor: "#FF3366", x: 0.5, y: 0.85 });
+ expect(t.project).toEqual({ aspect: "16:9", background: "#102030", fadeIn: 0.3, fadeOut: 0.4 });
+ expect(t.duration).toBeCloseTo(RICH_CLIP_S / 1.25 + RICH_CLIP_S, 5);
+ });
+
+ test("items pick a subset, timed from the earliest, with the bars playing on a chosen clip", () => {
+ const { template: t, assetByMedia, unknownItems } = templateFromDoc(richDoc(), { items: ["c1", "t1"] });
+ expect(unknownItems).toEqual([]);
+ const c0Len = RICH_CLIP_S / 1.25;
+ // The title at 3s is the earliest chosen item, so everything is timed from it.
+ expect(t.layers).toHaveLength(1);
+ expect(t.layers[0].start).toBeCloseTo(c0Len - 3, 5);
+ expect(t.texts).toHaveLength(1);
+ expect((t.texts[0] as { start: number }).start).toBeCloseTo(0, 5);
+ // Only the bar on the chosen clip's own edge: the cut bar plays c0's tail.
+ expect(t.transitions!.map((b) => b.id)).toEqual(["tr-out"]);
+ expect(t.transitions![0].start).toBeCloseTo(c0Len + RICH_CLIP_S - 0.5 - 3, 5);
+ expect(t.audio).toHaveLength(0);
+ expect(t.cues).toHaveLength(0);
+ // Only the media the chosen items use: c1's footage and t1's font.
+ expect([...assetByMedia].sort()).toEqual(["f0", "v1"]);
+ });
+
+ test("an id the document lacks is reported", () => {
+ expect(templateFromDoc(richDoc(), { items: ["c1", "nope"] }).unknownItems).toEqual(["nope"]);
+ });
+});
+
+describe("clampLayersToAssets", () => {
+ const base = (): TemplateSaveInput => ({
+ name: "t",
+ duration: 10,
+ media: [
+ { fileName: "a", name: "a", type: "video", duration: 10 },
+ { fileName: "b", name: "b", type: "audio", duration: 10 },
+ ],
+ layers: [{ media: 0, start: 0, in: 2, out: 9, muted: false, track: 1, asClip: true, speedCurve: [[0, 1], [4, 2], [8, 1]] }],
+ audio: [{ media: 1, start: 0, in: 0, out: 9, volume: 1 }],
+ texts: [],
+ cues: [],
+ });
+
+ test("a shorter source ends the trim where it ends and drops curve nodes past it", () => {
+ const { template, adjustments } = clampLayersToAssets(base(), ["x", "y"], [asset("x", "video", 5), asset("y", "audio", 4)]);
+ expect(template.layers[0]).toMatchObject({ in: 2, out: 5, speedCurve: [[0, 1], [4, 2]] });
+ expect(template.audio[0]).toMatchObject({ in: 0, out: 4 });
+ expect(adjustments.map((a) => `${a.item}.${a.field}`)).toEqual(["layer 0.out", "layer 0.speedCurve", "audio 0.out"]);
+ });
+
+ test("a trim starting past the source's end pulls in behind out", () => {
+ const { template, adjustments } = clampLayersToAssets(base(), ["x", "y"], [asset("x", "video", 1), asset("y", "audio", 10)]);
+ expect(template.layers[0].out).toBe(1);
+ expect(template.layers[0].in).toBeCloseTo(0.9, 5);
+ expect(adjustments.some((a) => a.field === "in")).toBe(true);
+ });
+
+ test("a still plays the clip's placed length with no rate", () => {
+ const t = base();
+ t.layers[0] = { ...t.layers[0], speedCurve: undefined, speed: 2 };
+ const { template, adjustments } = clampLayersToAssets(t, ["x", "y"], [asset("x", "image", 0), asset("y", "audio", 10)]);
+ expect(template.layers[0]).toMatchObject({ in: 0, out: 3.5 });
+ expect(template.layers[0].speed).toBeUndefined();
+ expect(adjustments[0].item).toBe("layer 0");
+ });
+
+ test("an unmapped entry is left alone", () => {
+ const { template, adjustments } = clampLayersToAssets(base(), ["", ""], []);
+ expect(template.layers[0].out).toBe(9);
+ expect(adjustments).toEqual([]);
+ });
+});
+
+describe("insertTemplate", () => {
+ beforeEach(() => {
+ useEditor.setState({
+ projectId: "p2",
+ clips: [],
+ transitions: [],
+ audioClips: [],
+ overlays: [],
+ assets: [asset("b0", "video", 30), asset("b1", "video", 30), asset("bm", "audio", 60), asset("bs", "image", 0)],
+ subtitles: emptySubtitles(),
+ selection: null,
+ multiSelection: [],
+ });
+ });
+
+ // v0→b0, v1→b1, m0→bm, s0→bs; the font is unmapped and never placed.
+ const MAP: Record<string, string> = { v0: "b0", v1: "b1", m0: "bm", s0: "bs", f0: "" };
+ const idsFor = (assetByMedia: string[], map = MAP) => assetByMedia.map((id) => map[id] ?? "");
+
+ test("stands the whole edit up on other footage, treatment and all", () => {
+ const { template, assetByMedia } = templateFromDoc(richDoc());
+ useEditor.getState().insertTemplate({ ...template, id: "t", addedAt: 0 }, idsFor(assetByMedia), 0);
+ const s = useEditor.getState();
+ const track0 = s.clips.filter((c) => c.track === 0).sort((a, b) => a.start - b.start);
+ expect(track0).toHaveLength(2);
+ expect(track0[0]).toMatchObject({ assetId: "b0", speed: 1.25, volume: 0.8, animIn: { style: "fade", seconds: 0.4 } });
+ expect(track0[1]).toMatchObject({ assetId: "b1", mask: { kind: "circle", w: 0.7, h: 0.7, feather: 20 }, animOut: { style: "zoom", seconds: 0.5 } });
+ expect(track0[1].grade).toEqual({ brightness: 5, contrast: 8, saturation: -10, temperature: 12, hue: 10 });
+ expect(track0[1].kf).toHaveLength(2);
+ const layer = s.clips.find((c) => c.track !== 0)!;
+ // The reference's track-1 layer lands on track 1 of an empty project.
+ expect(layer).toMatchObject({ track: 1, assetId: "b0", boxStyle: { radius: 24 }, rotation: 5, opacity: 0.9 });
+ expect(s.audioClips[0]).toMatchObject({ assetId: "bm", volume: 0.5, fadeIn: 0.3, fadeOut: 0.5, duck: 0.4 });
+ // Every bar lands on the edge it was saved on, and the clips read their
+ // edges back from the bars.
+ expect(s.transitions).toHaveLength(3);
+ const roles = resolveTransitions(s.clips, s.transitions);
+ for (const bar of s.transitions) expect((roles.get(bar.id) ?? []).length).toBeGreaterThan(0);
+ // Texts keep their keys and group as one new group; the sticker points at the copy.
+ const texts = s.overlays.filter(isTextOverlay);
+ expect(texts).toHaveLength(2);
+ expect(texts[0].kf).toHaveLength(2);
+ expect(texts[0].groupId).toBeDefined();
+ expect(texts[0].groupId).toBe(texts[1].groupId);
+ expect(texts[0].groupId).not.toBe("g1");
+ const sticker = s.overlays.find(isStickerOverlay)!;
+ expect(sticker.assetId).toBe("bs");
+ // Two titles, the sticker, and the look.
+ expect(s.overlays).toHaveLength(4);
+ expect(s.subtitles.cues).toHaveLength(2);
+ });
+
+ test("a sticker whose media is unmapped stays out, like a layer", () => {
+ const { template, assetByMedia } = templateFromDoc(richDoc());
+ useEditor.getState().insertTemplate({ ...template, id: "t", addedAt: 0 }, idsFor(assetByMedia, { ...MAP, s0: "" }), 0);
+ expect(useEditor.getState().overlays.some(isStickerOverlay)).toBe(false);
+ expect(useEditor.getState().overlays).toHaveLength(3);
+ });
+
+ test("a dropped sticker leaves the stickers after it on their own media", () => {
+ const { template, assetByMedia } = templateFromDoc(richDoc());
+ // Two stickers, one before the titles and one after; the first's media is unmapped.
+ const s1 = template.texts.find((o) => o.id === "s1")!;
+ const early = { ...s1, id: "s-early", start: 0, end: 1 };
+ const texts = [early, ...template.texts.filter((o) => o.id !== "s1"), s1];
+ const media = [...template.media, { ...template.media[assetByMedia.indexOf("s0")] }];
+ const stickers = [
+ { text: 0, media: media.length - 1 },
+ { text: texts.length - 1, media: assetByMedia.indexOf("s0") },
+ ];
+ const ids = [...idsFor(assetByMedia), ""];
+ useEditor.getState().insertTemplate({ ...template, texts, media, stickers, id: "t", addedAt: 0 }, ids, 0);
+ const overlays = useEditor.getState().overlays;
+ expect(overlays.filter(isStickerOverlay)).toHaveLength(1);
+ expect(overlays.find(isStickerOverlay)!.assetId).toBe("bs");
+ expect(overlays.filter(isTextOverlay).every((o) => !("assetId" in o))).toBe(true);
+ });
+
+ test("cue word timings move with the cue, out of the reference and onto the timeline", () => {
+ const doc = richDoc();
+ doc.subtitles!.cues[0].words = [
+ { t0: 0.3, t1: 0.7, w: "every" },
+ { t0: 0.8, t1: 1.2, w: "feature" },
+ ];
+ const { template, assetByMedia } = templateFromDoc(doc, { items: ["q0"] });
+ // Timed from the cue itself, so it starts the template at 0.
+ const words = template.cues[0].words!;
+ expect(words.map((w) => w.w)).toEqual(["every", "feature"]);
+ expect(words[0].t0).toBeCloseTo(0, 5);
+ expect(words[0].t1).toBeCloseTo(0.4, 5);
+ expect(words[1].t0).toBeCloseTo(0.5, 5);
+ expect(words[1].t1).toBeCloseTo(0.9, 5);
+ useEditor.getState().insertTemplate({ ...template, id: "t", addedAt: 0 }, idsFor(assetByMedia), 4);
+ const cue = useEditor.getState().subtitles.cues[0];
+ expect(cue.start).toBeCloseTo(4, 5);
+ expect(cue.words![0].t0).toBeCloseTo(4, 5);
+ expect(cue.words![1].t1).toBeCloseTo(4.9, 5);
+ });
+
+ test("a template saved before the rail carried treatments inserts as before", () => {
+ const old = {
+ id: "old",
+ name: "old",
+ addedAt: 0,
+ duration: 4,
+ media: [{ fileName: "x", name: "x", type: "video" as const, duration: 10 }],
+ layers: [{ media: 0, start: 0, in: 0, out: 4, muted: false, track: 1, asClip: true }],
+ audio: [],
+ texts: [],
+ cues: [],
+ };
+ useEditor.getState().insertTemplate(old, ["b0"], 0);
+ const c = useEditor.getState().clips[0];
+ expect(c).toMatchObject({ assetId: "b0", track: 0, start: 0, in: 0, out: 4 });
+ expect(c.grade).toBeUndefined();
+ expect(useEditor.getState().transitions).toHaveLength(0);
+ });
+
+ test("layers stack above a project's existing layers", () => {
+ useEditor.setState({
+ clips: [
+ { id: "spine", assetId: "b1", track: 0, start: 0, in: 0, out: 3, muted: false },
+ { id: "have", assetId: "b1", track: 1, start: 0, in: 0, out: 3, muted: true },
+ ],
+ });
+ const { template, assetByMedia } = templateFromDoc(richDoc());
+ useEditor.getState().insertTemplate({ ...template, id: "t", addedAt: 0 }, idsFor(assetByMedia), 0);
+ const layers = useEditor.getState().clips.filter((c) => c.track !== 0 && c.id !== "have");
+ expect(layers.map((c) => c.track)).toEqual([2]);
+ });
+});
+
+describe("selectionTemplate", () => {
+ test("carries the clip's treatment, the bar on it, and a sticker's media", async () => {
+ const doc = richDoc();
+ const assets: MediaAsset[] = doc.assets.map((a) => ({ ...a, url: "" }));
+ await useEditor.getState().openProjectDoc("rich", doc, assets);
+ const s = useEditor.getState();
+ s.select({ kind: "clip", id: "c0" });
+ s.toggleSelect({ kind: "clip", id: "c1" });
+ s.toggleSelect({ kind: "overlay", id: "s1" });
+ const t = useEditor.getState().selectionTemplate()!;
+ expect(t.layers[0]).toMatchObject({ speed: 1.25, volume: 0.8 });
+ expect(t.layers[1].grade).toBeDefined();
+ expect(t.layers[1].kf).toHaveLength(2);
+ expect(t.transitions).toHaveLength(3);
+ expect(t.stickers).toEqual([{ text: 0, media: 2 }]);
+ expect(t.media.map((m) => m.fileName)).toEqual(["clip-0.mp4", "clip-1.mp4", "arrow.png"]);
+ });
+});
diff --git a/site/src/cut/lib/projectTemplate.ts b/site/src/cut/lib/projectTemplate.ts
new file mode 100644
index 00000000..2de481bc
--- /dev/null
+++ b/site/src/cut/lib/projectTemplate.ts
@@ -0,0 +1,263 @@
+// A stored project document as a template: the whole edit, or the items a
+// caller picked out of it, in the shape the Library template rail already
+// stands up. This is what lets one project's cut be rebuilt in another on
+// different footage — the document is the edit, and the template is the
+// document with its media held by index so a caller can say which asset
+// plays each part.
+
+import { ITEM_KINDS, type ItemKind, type ItemOf } from "./itemKinds";
+import { getClipSpans, layerFromClip, normalizeDocState, resolveTransitions, totalDuration } from "./store";
+import {
+ CAPTION_LOOK_KEYS,
+ fontAssetId,
+ isStickerOverlay,
+ type AssetType,
+ type MediaAsset,
+ type ProjectDoc,
+ type StoredAsset,
+ type TemplateAudio,
+ type TemplateLayer,
+ type TemplateMedia,
+ type TemplateSaveInput,
+} from "./types";
+
+export interface DocTemplate {
+ template: TemplateSaveInput;
+ /** The source asset id behind each `template.media` entry. */
+ assetByMedia: string[];
+ /** The source assets behind each media entry, whole, so a copy keeps the
+ * notes, transcript and beats written against them. */
+ sourceAssets: StoredAsset[];
+ /** Ids asked for that the document does not hold. */
+ unknownItems: string[];
+ /** The source clip id behind each template layer, and behind each
+ * soundtrack clip, so an adjustment can name the item it moved. */
+ itemByLayer: string[];
+ itemByAudio: string[];
+}
+
+/** The document's edit as a template. With `items`, only those timeline
+ * items (clips on any track, soundtrack clips, elements, cues, transition
+ * bars) come along, timed from the earliest of them; without, the whole cut
+ * from 0. Transition bars playing on a chosen clip travel with it. */
+export function templateFromDoc(doc: ProjectDoc, opts: { items?: string[] } = {}): DocTemplate {
+ const assets: MediaAsset[] = (doc.assets ?? []).map((a) => ({ ...a, url: "" }));
+ const state = normalizeDocState(doc, assets);
+ const pick = opts.items ? new Set(opts.items) : null;
+ const wanted = (id: string) => !pick || pick.has(id);
+
+ const clips = state.clips.filter((c) => wanted(c.id));
+ const audioClips = state.audioClips.filter((c) => wanted(c.id));
+ const overlays = state.overlays.filter((o) => wanted(o.id));
+ const cues = state.subtitles.cues.filter((c) => wanted(c.id));
+ const clipIds = new Set(clips.map((c) => c.id));
+ const roles = resolveTransitions(state.clips, state.transitions);
+ const transitions = state.transitions.filter(
+ (t) => wanted(t.id) || (pick !== null && (roles.get(t.id) ?? []).some((rl) => clipIds.has(rl.clipId)))
+ );
+
+ const found = new Set([
+ ...clips.map((c) => c.id),
+ ...audioClips.map((c) => c.id),
+ ...overlays.map((o) => o.id),
+ ...cues.map((c) => c.id),
+ ...transitions.map((t) => t.id),
+ ]);
+ const unknownItems = pick ? [...pick].filter((id) => !found.has(id)) : [];
+
+ const starts = [
+ ...clips.map((c) => c.start),
+ ...audioClips.map((c) => c.start),
+ ...overlays.map((o) => o.start),
+ ...cues.map((c) => c.start),
+ ...transitions.map((t) => t.start),
+ ];
+ const start0 = pick && starts.length ? Math.min(...starts) : 0;
+
+ const media: TemplateMedia[] = [];
+ const assetByMedia: string[] = [];
+ const sourceAssets: StoredAsset[] = [];
+ const indexByAsset = new Map<string, number>();
+ const mediaFor = (assetId: string): number | null => {
+ const cached = indexByAsset.get(assetId);
+ if (cached != null) return cached;
+ const a = (doc.assets ?? []).find((x) => x.id === assetId);
+ if (!a) return null;
+ const i = media.length;
+ media.push({ fileName: a.fileName, name: a.name, type: a.type, duration: a.duration, width: a.width, height: a.height });
+ assetByMedia.push(a.id);
+ sourceAssets.push(a);
+ indexByAsset.set(assetId, i);
+ return i;
+ };
+
+ // What each item names once it leaves its project: the media it plays and
+ // the font it is set in join the template's media; a background removal
+ // stays behind with the footage its matte was baked from.
+ const across = <K extends ItemKind>(kind: K, item: ItemOf[K]): ItemOf[K] => ITEM_KINDS[kind].crossProject(item);
+ const spans = getClipSpans(state.clips, assets);
+ const layers: TemplateLayer[] = [];
+ const itemByLayer: string[] = [];
+ for (const raw of clips) {
+ const c = across("clip", raw);
+ const mi = mediaFor(c.assetId);
+ if (mi == null) continue;
+ const sp = spans.find((x) => x.clip.id === c.id);
+ layers.push(layerFromClip(c, start0, mi, sp ? sp.start : c.start));
+ itemByLayer.push(c.id);
+ }
+ const audio: TemplateAudio[] = [];
+ const itemByAudio: string[] = [];
+ for (const c of audioClips) {
+ const mi = mediaFor(c.assetId);
+ if (mi == null) continue;
+ audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed, speedCurve: c.speedCurve, reverse: c.reverse, sound: c.sound, duck: c.duck, lane: c.lane });
+ itemByAudio.push(c.id);
+ }
+ const texts: TemplateSaveInput["texts"] = [];
+ const stickers: { text: number; media: number }[] = [];
+ for (const raw of overlays) {
+ const o = across("overlay", raw);
+ if (isStickerOverlay(o) && o.assetId) {
+ const mi = mediaFor(o.assetId);
+ if (mi == null) continue;
+ stickers.push({ text: texts.length, media: mi });
+ }
+ // Everything else the element names — a title's uploaded font — brings
+ // its file along; the element itself keeps the id, which the insert
+ // remaps by asset.
+ for (const id of ITEM_KINDS.overlay.assetIds(o)) mediaFor(id);
+ texts.push({ ...o, start: o.start - start0, end: o.end - start0 });
+ }
+
+ const captions: TemplateSaveInput["captions"] = {};
+ for (const k of CAPTION_LOOK_KEYS) {
+ const v = state.subtitles[k];
+ if (v !== undefined) (captions as Record<string, unknown>)[k] = v;
+ }
+ const captionFont = state.subtitles.font ? fontAssetId(state.subtitles.font) : null;
+ if (captionFont) mediaFor(captionFont);
+
+ const ends = [
+ ...layers.map((l) => l.start + (l.out - l.in) / (l.speed ?? 1)),
+ ...audio.map((a) => a.start + (a.out - a.in) / (a.speed ?? 1)),
+ ...texts.map((t) => t.end),
+ ...cues.map((c) => c.end - start0),
+ ];
+ const duration = pick ? Math.max(0.1, ...ends) : Math.max(totalDuration(state.clips), 0.1, ...ends);
+
+ return {
+ template: {
+ name: doc.name ?? "Project",
+ duration,
+ media,
+ layers,
+ audio,
+ texts,
+ cues: cues.map((c) => ({
+ ...c,
+ start: c.start - start0,
+ end: c.end - start0,
+ ...(c.words ? { words: c.words.map((w) => ({ ...w, t0: w.t0 - start0, t1: w.t1 - start0 })) } : {}),
+ })),
+ ...(stickers.length ? { stickers } : {}),
+ ...(transitions.length
+ ? { transitions: transitions.map((t) => ({ ...t, start: t.start - start0 })) }
+ : {}),
+ captions,
+ project: {
+ aspect: state.aspect ?? "9:16",
+ background: state.background,
+ fadeIn: state.fadeIn,
+ fadeOut: state.fadeOut,
+ },
+ },
+ assetByMedia,
+ sourceAssets,
+ unknownItems,
+ itemByLayer,
+ itemByAudio,
+ };
+}
+
+export interface TemplateAdjustment {
+ /** Which part moved: the caller's label for it, `layer N` or `audio N` by
+ * index in the template when none was given. */
+ item: string;
+ field: string;
+ from: number;
+ to: number;
+ reason: string;
+}
+
+/** The template with every trim held inside the asset that will play it.
+ * A layer mapped onto a shorter source ends where the source ends; one mapped
+ * onto a still keeps its placed length and drops its rate; speed-curve nodes
+ * past the source's end go. Every change is listed, so whoever asked can
+ * fix or report it. */
+export function clampLayersToAssets(
+ template: TemplateSaveInput,
+ assetIds: string[],
+ assets: Pick<StoredAsset, "id" | "type" | "duration">[],
+ labels: { layers?: string[]; audio?: string[] } = {}
+): { template: TemplateSaveInput; adjustments: TemplateAdjustment[] } {
+ const byId = new Map(assets.map((a) => [a.id, a]));
+ const adjustments: TemplateAdjustment[] = [];
+ const MIN = 0.1;
+ const clampTrim = <T extends { in: number; out: number; speedCurve?: [number, number][] }>(
+ item: T,
+ label: string,
+ duration: number
+ ): T => {
+ let { in: i, out } = item;
+ if (out > duration + 1e-6) {
+ adjustments.push({ item: label, field: "out", from: out, to: duration, reason: "the mapped source is shorter" });
+ out = duration;
+ }
+ if (i > out - MIN) {
+ const to = Math.max(0, out - MIN);
+ adjustments.push({ item: label, field: "in", from: i, to, reason: "the trim started past the mapped source's end" });
+ i = to;
+ }
+ const nodes = item.speedCurve?.filter((n) => n[0] <= duration);
+ const dropped = (item.speedCurve?.length ?? 0) - (nodes?.length ?? 0);
+ if (dropped > 0)
+ adjustments.push({ item: label, field: "speedCurve", from: item.speedCurve!.length, to: nodes!.length, reason: "nodes past the mapped source's end dropped" });
+ return {
+ ...item,
+ in: i,
+ out,
+ ...(item.speedCurve ? { speedCurve: nodes && nodes.length >= 2 ? nodes : undefined } : {}),
+ };
+ };
+ const layers = template.layers.map((l, n) => {
+ const a = byId.get(assetIds[l.media]);
+ if (!a) return l;
+ const label = labels.layers?.[n] ?? `layer ${n}`;
+ if (a.type === "image") {
+ const placed = (l.out - l.in) / (l.speed ?? 1);
+ if (l.in !== 0 || l.speed || l.speedCurve || l.reverse || l.smoothSlow) {
+ adjustments.push({ item: label, field: "out", from: l.out, to: placed, reason: "a still plays the clip's placed length with no rate" });
+ }
+ const still: TemplateLayer = { ...l, in: 0, out: placed };
+ delete still.speed;
+ delete still.speedCurve;
+ delete still.reverse;
+ delete still.smoothSlow;
+ return still;
+ }
+ return clampTrim(l, label, a.duration);
+ });
+ const audio = template.audio.map((c, n) => {
+ const a = byId.get(assetIds[c.media]);
+ if (!a) return c;
+ return clampTrim(c, labels.audio?.[n] ?? `audio ${n}`, a.duration);
+ });
+ return { template: { ...template, layers, audio }, adjustments };
+}
+
+/** Whether an asset of this type can stand in for a source of that type. */
+export const mediaTypeFits = (source: AssetType, replacement: AssetType): boolean =>
+ source === "audio" || source === "font"
+ ? replacement === source
+ : replacement === "video" || replacement === "image";
diff --git a/site/src/cut/lib/replicateProject.test.ts b/site/src/cut/lib/replicateProject.test.ts
new file mode 100644
index 00000000..eb36b882
--- /dev/null
+++ b/site/src/cut/lib/replicateProject.test.ts
@@ -0,0 +1,206 @@
+import { afterAll, beforeEach, describe, expect, test } from "bun:test";
+
+import { runAiTool } from "./aiTools";
+import { richDoc, RICH_CLIP_S } from "./fixtures/richDoc";
+import { setHostDocStore } from "./projectReference";
+import { useEditor } from "./store";
+import { emptySubtitles, isTextOverlay, type MediaAsset, type ProjectDoc } from "./types";
+
+/**
+ * A Donkey Cut link pasted into another project's chat is read as its
+ * document and rebuilt on that project's own media. What the reference's
+ * assets carried — notes, transcript, beats — travels with a copy, a font
+ * the reference uploaded is the font the titles set in it point at, and
+ * everything the transplant had to trim is named.
+ */
+
+const asset = (id: string, type: MediaAsset["type"], duration: number, extra: Partial<MediaAsset> = {}): MediaAsset => ({
+ id,
+ fileName: `${id}.bin`,
+ name: id,
+ type,
+ duration,
+ url: "",
+ ...extra,
+});
+
+const docs = new Map<string, ProjectDoc>([["rich", richDoc()]]);
+const copies: { src: string; file: string; dst: string }[] = [];
+
+setHostDocStore({
+ readDoc: async (id) => docs.get(id) ?? null,
+ copyMedia: async (src, file, dst) => {
+ copies.push({ src, file, dst });
+ return `copy-${file}`;
+ },
+});
+afterAll(() => setHostDocStore(null));
+
+type Result = {
+ clipIds: string[];
+ audioClipIds: string[];
+ overlayIds: string[];
+ transitionIds: string[];
+ cueIds: string[];
+ mapped: { sourceId: string; assetId: string }[];
+ assetIds: string[];
+ copied: { sourceId: string; assetId: string; kind: string }[];
+ adjustments: { item: string; field: string; from: number; to: number; reason: string }[];
+ frame: boolean;
+ captionLook: boolean;
+ captions: string;
+};
+
+describe("replicate_project", () => {
+ beforeEach(() => {
+ copies.length = 0;
+ useEditor.setState({
+ projectId: "p2",
+ clips: [],
+ transitions: [],
+ audioClips: [],
+ overlays: [],
+ // B's footage is shorter than the reference's second clip, so its trim
+ // has to give.
+ assets: [asset("b0", "video", 30), asset("b1", "video", 6), asset("bs", "image", 0)],
+ subtitles: emptySubtitles(),
+ selection: null,
+ multiSelection: [],
+ aspect: "9:16",
+ });
+ });
+
+ test("the whole edit lands on the mapped media, copies the rest, and names every trim", async () => {
+ const out = (await runAiTool("replicate_project", {
+ link: "rich",
+ media: [
+ { source_asset_id: "v0", asset_id: "b0" },
+ { source_asset_id: "v1", asset_id: "b1" },
+ { source_asset_id: "s0", asset_id: "bs" },
+ ],
+ })) as Result;
+ const s = useEditor.getState();
+ expect(out.clipIds).toHaveLength(3);
+ expect(out.audioClipIds).toHaveLength(1);
+ expect(out.overlayIds).toHaveLength(4);
+ expect(out.transitionIds).toHaveLength(3);
+ // Cues are B's speech to write; the look is the reference's.
+ expect(out.cueIds).toHaveLength(0);
+ expect(out.captions).toBe("none copied");
+ expect(out.captionLook).toBe(true);
+ expect(s.subtitles.style).toBe("bubble");
+ expect(s.subtitles.wordsPerCue).toBe(3);
+ // The frame follows for a whole replicate.
+ expect(out.frame).toBe(true);
+ expect(s.aspect).toBe("16:9");
+ expect(s.background).toBe("#102030");
+ // The music bed and the font had no counterpart, so they copied across
+ // with what the reference knew about them.
+ expect(copies.map((c) => c.file).sort()).toEqual(["brand.ttf", "music.m4a"]);
+ expect(copies.every((c) => c.src === "rich" && c.dst === "p2")).toBe(true);
+ expect(out.copied.map((c) => c.kind).sort()).toEqual(["audio", "font"]);
+ const music = s.assets.find((a) => a.fileName === "copy-music.m4a")!;
+ expect(music).toMatchObject({ type: "audio", origin: "generated", beats: { bpm: 120 } });
+ expect(s.audioClips[0].assetId).toBe(music.id);
+ // The brand title now points at the copied font.
+ const font = s.assets.find((a) => a.type === "font")!;
+ const brand = s.overlays.filter(isTextOverlay).find((o) => o.text === "Brand line")!;
+ expect(brand.font).toBe(`asset:${font.id}`);
+ // b1 runs 6s where the reference's clip ran 10s, so its out was trimmed.
+ const c1 = s.clips.find((c) => c.assetId === "b1")!;
+ expect(c1.out).toBe(6);
+ expect(out.adjustments).toEqual([{ item: "clip c1", field: "out", from: RICH_CLIP_S, to: 6, reason: "the mapped source is shorter" }]);
+ // One undo step reverts the items and the caption look. The frame is a
+ // project setting, outside history like every frame change.
+ s.undo();
+ const back = useEditor.getState();
+ expect(back.clips).toHaveLength(0);
+ expect(back.audioClips).toHaveLength(0);
+ expect(back.overlays).toHaveLength(0);
+ expect(back.transitions).toHaveLength(0);
+ expect(back.subtitles.style).toBe(emptySubtitles().style);
+ expect(back.aspect).toBe("16:9");
+ });
+
+ test("chosen items land alone, leaving the frame and captions as they were", async () => {
+ const out = (await runAiTool("replicate_project", {
+ link: "rich",
+ items: ["t0", "t1"],
+ })) as Result;
+ const s = useEditor.getState();
+ expect(out.clipIds).toHaveLength(0);
+ expect(out.overlayIds).toHaveLength(2);
+ expect(out.frame).toBe(false);
+ expect(out.captionLook).toBe(false);
+ expect(s.aspect).toBe("9:16");
+ expect(s.overlays.filter(isTextOverlay).map((o) => o.text).sort()).toEqual(["Brand line", "Everything test"]);
+ // The titles keep their group.
+ const [g0, g1] = s.overlays.map((o) => o.groupId);
+ expect(g0).toBeDefined();
+ expect(g0).toBe(g1);
+ // Only the font copied: nothing else the titles need.
+ expect(copies.map((c) => c.file)).toEqual(["brand.ttf"]);
+ });
+
+ test("refuses an unknown item, an unknown asset, and a role the media cannot play", async () => {
+ await expect(runAiTool("replicate_project", { link: "rich", items: ["nope"] })).rejects.toThrow("no items with ids nope");
+ await expect(
+ runAiTool("replicate_project", { link: "rich", media: [{ source_asset_id: "v0", asset_id: "zz" }] })
+ ).rejects.toThrow("No asset with id zz in this project");
+ await expect(
+ runAiTool("replicate_project", { link: "rich", media: [{ source_asset_id: "v9", asset_id: "b0" }] })
+ ).rejects.toThrow("No asset with id v9 in the reference");
+ await expect(
+ runAiTool("replicate_project", { link: "rich", media: [{ source_asset_id: "m0", asset_id: "b0" }] })
+ ).rejects.toThrow("cannot play that part");
+ expect(useEditor.getState().clips).toHaveLength(0);
+ });
+
+ test("a link nothing answers is a plain error", async () => {
+ await expect(runAiTool("replicate_project", { link: "https://donkeycut.com/app/p/missing" })).rejects.toThrow(
+ "No project with id missing"
+ );
+ await expect(runAiTool("read_project", { link: "https://youtube.com/watch?v=abc" })).rejects.toThrow(
+ "Pass a Donkey Cut project link"
+ );
+ });
+});
+
+describe("read_project", () => {
+ test("hands back the reference as an editor state, naming the sources nothing describes", async () => {
+ useEditor.setState({ projectId: "p2", assets: [], clips: [], overlays: [] });
+ const out = (await runAiTool("read_project", { link: "https://donkeycut.com/app/p/rich" })) as {
+ source: { kind: string; id: string; name: string; residency: string };
+ reference: { videoTrack: { id: string }[]; media: { id: string }[]; subtitles: { cues: unknown[] } };
+ unobserved: string[];
+ };
+ expect(out.source).toEqual({ kind: "project", id: "rich", name: "Rich edit", residency: "local" });
+ expect(out.reference.videoTrack.map((c) => c.id)).toEqual(["c0", "c1"]);
+ // Fonts list under `fonts`, like the open project's.
+ expect(out.reference.media.map((m) => m.id).sort()).toEqual(["m0", "s0", "v0", "v1"]);
+ expect(out.reference.subtitles.cues).toHaveLength(2);
+ // v0 carries notes and a transcript; v1 carries neither.
+ expect(out.unobserved).toEqual(["v1"]);
+ expect(useEditor.getState().clips).toHaveLength(0);
+ });
+});
+
+describe("copy_project_media", () => {
+ test("lands the chosen assets on this project's cards and places nothing", async () => {
+ copies.length = 0;
+ useEditor.setState({ projectId: "p2", assets: [], clips: [], audioClips: [], overlays: [] });
+ const out = (await runAiTool("copy_project_media", { link: "rich", asset_ids: ["v0", "s0"] })) as {
+ assets: { assetId: string; sourceId: string; kind: string; duration: number }[];
+ };
+ expect(out.assets.map((a) => [a.sourceId, a.kind])).toEqual([
+ ["v0", "video"],
+ ["s0", "image"],
+ ]);
+ const s = useEditor.getState();
+ expect(s.assets).toHaveLength(2);
+ expect(s.assets[0]).toMatchObject({ fileName: "copy-clip-0.mp4", watch: { notes: [{ from: 0 }] } });
+ expect(s.assets[0].speech?.segments).toHaveLength(1);
+ expect(s.clips).toHaveLength(0);
+ await expect(runAiTool("copy_project_media", { link: "rich", asset_ids: [] })).rejects.toThrow("asset_ids is required");
+ });
+});
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index c6c6a794..1ac25754 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -1562,6 +1562,38 @@ describe("bars and clip edges", () => {
expect(parkedTransitions(s().clips, s().transitions).map((t) => t.id)).toEqual([sound]);
});
+ test("a copied cue pastes onto its caption track at the playhead, words and all", () => {
+ const cue: SubtitleCue = {
+ id: "q1",
+ start: 1,
+ end: 2,
+ text: "two words",
+ words: [
+ { t0: 1, t1: 1.4, w: "two" },
+ { t0: 1.5, t1: 2, w: "words" },
+ ],
+ };
+ const blocker: SubtitleCue = { id: "q2", start: 5, end: 6, text: "taken" };
+ useEditor.setState({
+ subtitles: { ...emptySubtitles(), cues: [cue, blocker] },
+ selection: { kind: "cue", id: "q1" },
+ multiSelection: [],
+ });
+ expect(s().copySelection()).toBe(true);
+ // The playhead sits inside the blocker, so the copy slides past it.
+ setPlayhead(5.5);
+ expect(s().paste()).toBe(true);
+ const cues = s().subtitles.cues;
+ expect(cues).toHaveLength(3);
+ const pasted = cues.find((c) => c.id !== "q1" && c.id !== "q2")!;
+ expect(pasted).toMatchObject({ start: 6, end: 7, text: "two words" });
+ expect(pasted.words).toEqual([
+ { t0: 6, t1: 6.4, w: "two" },
+ { t0: 6.5, t1: 7, w: "words" },
+ ]);
+ expect(s().selection).toEqual({ kind: "cue", id: pasted.id });
+ });
+
test("a copied bar pastes onto the cut nearest the playhead", () => {
const av = asset(12);
const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 895e7b64..9ab2d780 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -24,6 +24,7 @@ import {
import { create } from "zustand";
import type {
Aspect,
+ CaptionLook,
AssetBeats,
AudioClip,
ClipAnim,
@@ -80,7 +81,8 @@ import { useGenNotify } from "./genNotify";
import { clampPlayhead, playheadAt, previewAt, setPlayhead, setSkim } from "./playhead";
import { engineTranscribeSamples, withEngineStt } from "./localStt";
import { laneCues, subtitleLaneCount, trackLocale } from "./subtitles";
-import { ANIM_STYLE_IDS, animStyleOfTransition, assetIsSilent, clipPoseAt, DEFAULT_BACKGROUND, emptySubtitles, frameOf, IMAGE_CLIP_SECONDS, isAudioTransition, fontAssetId, isEffectOverlay, isStickerOverlay, isTextOverlay, MAX_SUBTITLE_LANES, mediaUrl, migrateBehindSubject, migrateLegacyTransitions, normalizeAspect, overlayAnimStyle, projectBackground, SPEED_FLOOR, SPEED_MIN, stampOverlayKinds, stripDefaultOverlayKinds, TRANSITION_MAX, TRANSITION_STYLE_IDS, transitionBarAt, transitionBarStart, transitionStyleOfAnim, type TransitionBoundaryKind } from "./types";
+import { assertNever, clipboardItemAssetIds, clipboardItemFor, listedAssetIds, type TimelineClipboardItem } from "./itemKinds";
+import { ANIM_STYLE_IDS, animStyleOfTransition, assetIsSilent, clipPoseAt, DEFAULT_BACKGROUND, emptySubtitles, frameOf, IMAGE_CLIP_SECONDS, isAudioTransition, fontAssetId, isEffectOverlay, isStickerOverlay, MAX_SUBTITLE_LANES, mediaUrl, migrateBehindSubject, migrateLegacyTransitions, normalizeAspect, overlayAnimStyle, projectBackground, SPEED_FLOOR, SPEED_MIN, stampOverlayKinds, stripDefaultOverlayKinds, TRANSITION_MAX, TRANSITION_STYLE_IDS, transitionBarAt, transitionBarStart, transitionStyleOfAnim, type TransitionBoundaryKind } from "./types";
import { liftMoveTracks } from "./textMotion";
import { readTextStyle } from "./textStyle";
import { loadUiState, saveUiState, type ProjectUiState } from "./uiState";
@@ -110,6 +112,63 @@ const templateFraming = (l: TemplateLayer) => ({
...((l.opacity ?? 1) < 1 ? { opacity: l.opacity } : {}),
});
+/** The clip's rate, sound and treatment as a template layer carries them:
+ * everything on the clip that is the edit, so the clip a template stands up
+ * is the clip that was saved. A look is already an effect element by the
+ * time a clip is read (the loader lifts it), the clip's edges are its bars
+ * (the template carries those as transitions), and background removal stays
+ * behind. */
+const clipTreatment = (c: VideoClip) => ({
+ ...(c.volume !== undefined && c.volume !== 1 ? { volume: c.volume } : {}),
+ ...(c.speed ? { speed: c.speed } : {}),
+ ...(c.speedCurve ? { speedCurve: c.speedCurve } : {}),
+ ...(c.reverse ? { reverse: true } : {}),
+ ...(c.smoothSlow ? { smoothSlow: true } : {}),
+ ...(c.sound ? { sound: c.sound } : {}),
+ ...(c.grade ? { grade: c.grade } : {}),
+ ...(c.mask ? { mask: c.mask } : {}),
+ ...(c.boxStyle ? { boxStyle: c.boxStyle } : {}),
+ ...(c.kf?.length ? { kf: c.kf } : {}),
+ ...(c.hidden ? { hidden: true } : {}),
+});
+
+/** One clip as a template layer, timed from the template's start. A track-0
+ * clip re-materializes onto track 0 (asClip); an upper-track clip keeps its
+ * height as `track + 1`. */
+export function layerFromClip(
+ c: VideoClip,
+ start0: number,
+ mediaIndex: number,
+ timelineStart = c.start
+): TemplateLayer {
+ return {
+ media: mediaIndex,
+ start: timelineStart - start0,
+ in: c.in,
+ out: c.out,
+ ...framingOf(c),
+ muted: c.muted,
+ ...clipTreatment(c),
+ track: c.track === 0 ? 1 : c.track + 1,
+ ...(c.track === 0 ? { asClip: true } : {}),
+ };
+}
+
+/** The treatment back on a clip the layer stands up. */
+const templateTreatment = (l: TemplateLayer) => ({
+ ...(l.volume !== undefined ? { volume: l.volume } : {}),
+ ...(l.speed ? { speed: l.speed } : {}),
+ ...(l.speedCurve ? { speedCurve: l.speedCurve } : {}),
+ ...(l.reverse ? { reverse: true } : {}),
+ ...(l.smoothSlow ? { smoothSlow: true } : {}),
+ ...(l.sound ? { sound: l.sound } : {}),
+ ...(l.grade ? { grade: l.grade } : {}),
+ ...(l.mask ? { mask: l.mask } : {}),
+ ...(l.boxStyle ? { boxStyle: l.boxStyle } : {}),
+ ...(l.kf?.length ? { kf: l.kf } : {}),
+ ...(l.hidden ? { hidden: true } : {}),
+});
+
const MIN_LEN = 0.1;
/** Where a video clip lands when dropped: an existing track or a brand-new
@@ -717,7 +776,7 @@ export interface EditorState {
* track's language. Timings copy over; word timings don't survive
* translation, so the new cues carry none. */
translateSubtitleTrack: (fromLane: number) => Promise<void>;
- setSubtitlesView: (patch: Partial<Pick<SubtitlesBlock, "showOnVideo" | "showOnTimeline" | "locale" | "style" | "size" | "font" | "x" | "y" | "wordHighlight" | "accentMode" | "accentColor" | "accentScale" | "accentDim">>) => void;
+ setSubtitlesView: (patch: CaptionLook & Partial<Pick<SubtitlesBlock, "showOnTimeline" | "locale">>) => void;
/** How many words a caption holds at a time. Every track is re-cut on its
* own words and then measured against the cut's mix, so the new captions
* land on the speech instead of on arithmetic. One undo step. */
@@ -840,8 +899,14 @@ export interface EditorState {
* step. Used so a whole assistant turn reverts with a single ⌘Z. */
beginHistoryBatch: () => void;
endHistoryBatch: () => void;
- /** Copy the selected clip/audio/overlay/title(s) to the timeline clipboard. */
+ /** Copy the selected clip/audio/overlay/title/cue(s) to the timeline clipboard. */
copySelection: () => boolean;
+ /** What the timeline clipboard holds, for a copy that leaves the tab. */
+ copiedItems: () => TimelineClipboardItem[];
+ /** Hand the timeline clipboard items that arrived from elsewhere — another
+ * tab, another project — so the next paste lands them the way it lands a
+ * copy made here. */
+ setClipboard: (items: TimelineClipboardItem[]) => void;
/** Empty the timeline clipboard, so the next paste is somebody else's — a
* frame copied off the preview canvas takes the clipboard over this way. */
clearClipboard: () => void;
@@ -881,12 +946,8 @@ const genAudioIds = new Set<string>();
/** Timeline clipboard (⌘C/⌘V) — survives across projects in one session. One
* entry per copied item so a multi-selection round-trips. */
-type ClipboardItem =
- | { kind: "clip"; item: VideoClip }
- | { kind: "audio"; item: AudioClip }
- | { kind: "overlay"; item: Overlay }
- | { kind: "transition"; item: TimelineTransition };
-let clipboard: ClipboardItem[] = [];
+export type { TimelineClipboardItem } from "./itemKinds";
+let clipboard: TimelineClipboardItem[] = [];
/** How far (seconds) a pasted transition bar reaches for a cut or clip edge
* around the playhead. Within it the bar lands playing that boundary, like a
@@ -2093,86 +2154,26 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
},
applyDocState: (doc, assets, ui) => {
- const docClips = doc.clips ?? [];
- // Older docs stored video track 0 packed (array order implied the
- // position); bake explicit starts in once so every clip is free-placed.
- const legacy = (docClips as LegacyClip[]).some((c) => typeof c.start !== "number");
- const folded = (legacy ? packStarts(docClips as LegacyClip[]) : docClips).map((c) => ({
- ...c,
- track: c.track ?? 0,
- }));
- // Older docs kept tracks other than 0 in a separate `overlayClips` array;
- // fold them into the one clip list (each already carries its `track`).
- // Entries whose id already sits in `clips` are the same clip persisted
- // twice by a version-skewed save (an older engine keeps overlayClips
- // after a merged client writes the folded list) — keep the folded copy.
- // Entries with track 0 were unreachable dead data under the split shape
- // (never rendered, never played); promoting them would insert them into
- // track 0's sequence, so they stay dropped.
- const seen = new Set(folded.map((c) => c.id));
- const legacyLayers = (doc.overlayClips ?? []).filter(
- (c) => c.track !== 0 && !seen.has(c.id)
- );
- // Tracks number 0..N bottom-up. Docs saved when tracks could go
- // negative (backdrop rows below the spine) lift wholesale so the
- // lowest row becomes track 0 — the bottom row is the spine now.
- const joined = [...folded, ...legacyLayers];
- const lift = Math.max(0, ...joined.map((c) => -c.track));
- const lifted = lift ? joined.map((c) => ({ ...c, track: c.track + lift })) : joined;
- // Stamp `kind: "text"` on pre-union titles so every in-memory element
- // carries its discriminant; the serializer strips it back. Effects
- // saved onto a shared row move to one of their own, and a clip graded
- // back when a look was a clip property gets that grade as an element
- // over it — so a project made before either rule reads like a new one.
- // The behind-speaker boolean becomes an inverted subject mask on load,
- // so one mask model covers it everywhere in memory and on save. Key
- // tracks written by the retired move picker lift into the move slot,
- // leaving `kf` to the keys users set themselves.
- const stamped = liftMoveTracks(
- normalizeElementLanes(migrateBehindSubject(stampOverlayKinds(doc.overlays ?? [])))
- );
- const subtitles = doc.subtitles ?? emptySubtitles();
- // Docs saved when edge transition styles existed convert them into the
- // equivalent clip animations, and docs saved when a transition was a
- // physical overlap pull their intruding clips apart — clips never
- // overlap, whatever wrote the file. Pulling them apart lengthens the
- // cut, so the whole document goes through it together.
- const merged = separateOverlaps({
- clips: migrateLegacyTransitions(lifted),
- audioClips: doc.audioClips ?? [],
- overlays: stamped,
- cues: subtitles.cues,
- });
- const withLooks =
- liftClipLooks(merged.clips, merged.overlays, getClipSpans(merged.clips, assets)) ?? {
- clips: merged.clips,
- overlays: merged.overlays,
- };
+ const state = normalizeDocState(doc, assets);
hydrating = true;
try {
set({
projectName: doc.name ?? "",
assets,
- clips: withLooks.clips,
- // Bars from the doc, plus one adopted for each transition/animation
- // a pre-bar doc stored as a clip field.
- transitions: adoptTransitionFields(
- withLooks.clips,
- sanitizeTransitions(doc.transitions)
- ),
- audioClips: merged.audioClips,
- // Elements from before they had hosts home to the clips under them.
- overlays: adoptOverlayHosts(withLooks.clips, withLooks.overlays),
+ clips: state.clips,
+ transitions: state.transitions,
+ audioClips: state.audioClips,
+ overlays: state.overlays,
templates: doc.templates ?? [],
mediaFolders: doc.mediaFolders ?? [],
- aspect: normalizeAspect(doc.aspect) ?? lastChosenAspect() ?? "9:16",
+ aspect: state.aspect ?? lastChosenAspect() ?? "9:16",
aspectTouched: doc.aspect !== undefined || lastChosenAspect() !== null,
guides: sanitizeGuides(doc.guides),
guidesHidden: false,
guideLines: sanitizeGuideLines(doc.guideLines),
- fadeIn: doc.fadeIn ?? 0,
- fadeOut: doc.fadeOut ?? 0,
- background: projectBackground(doc.background),
+ fadeIn: state.fadeIn,
+ fadeOut: state.fadeOut,
+ background: state.background,
// View state lives in IndexedDB; doc.ui covers projects saved
// before the move.
pxPerSec: clampPps(ui.pxPerSec ?? doc.ui?.pxPerSec ?? 60),
@@ -2191,8 +2192,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
publishedAt: doc.notes?.publishedAt ?? "",
links: doc.notes?.links ?? [],
},
- subtitles: { ...subtitles, cues: merged.cues },
- subtitleStatus: merged.cues.length > 0 ? "ready" : "idle",
+ subtitles: state.subtitles,
+ subtitleStatus: state.subtitles.cues.length > 0 ? "ready" : "idle",
genvideo: doc.genvideo ?? undefined,
renders: Array.isArray(doc.renders) ? doc.renders : [],
firstOpen: doc.firstOpen,
@@ -3918,23 +3919,20 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const layers: TemplateLayer[] = [];
const audio: TemplateAudio[] = [];
const texts: Overlay[] = [];
+ const stickers: { text: number; media: number }[] = [];
const cues: SubtitleCue[] = [];
+ const clipIds = new Set<string>();
for (const sel of sels) {
if (sel.kind === "clip") {
const sp = spans.find((x) => x.clip.id === sel.id);
- if (sp) {
- const mi = mediaFor(sp.clip.assetId);
- if (mi == null) continue;
- // Track-0 clips re-materialize onto track 0 (asClip), so a template
- // stands up its own video instead of an empty timeline.
- layers.push({ media: mi, start: sp.start - start0, in: sp.clip.in, out: sp.clip.out, ...framingOf(sp.clip), muted: sp.clip.muted, speed: sp.clip.speed, speedCurve: sp.clip.speedCurve, reverse: sp.clip.reverse, smoothSlow: sp.clip.smoothSlow, sound: sp.clip.sound, track: 1, asClip: true });
- } else {
- const c = s.clips.find((x) => x.id === sel.id);
- if (!c) continue;
- const mi = mediaFor(c.assetId);
- if (mi == null) continue;
- layers.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, ...framingOf(c), muted: c.muted, speed: c.speed, speedCurve: c.speedCurve, reverse: c.reverse, smoothSlow: c.smoothSlow, sound: c.sound, track: c.track + 1 });
- }
+ const c = sp?.clip ?? s.clips.find((x) => x.id === sel.id);
+ if (!c) continue;
+ const mi = mediaFor(c.assetId);
+ if (mi == null) continue;
+ clipIds.add(c.id);
+ // Track-0 clips re-materialize onto track 0 (asClip), so a template
+ // stands up its own video instead of an empty timeline.
+ layers.push(layerFromClip(c, start0, mi, sp ? sp.start : c.start));
} else if (sel.kind === "audio") {
const c = s.audioClips.find((x) => x.id === sel.id);
if (!c) continue;
@@ -3943,11 +3941,15 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed, speedCurve: c.speedCurve, reverse: c.reverse, sound: c.sound, duck: c.duck, lane: c.lane });
} else if (sel.kind === "overlay") {
const o = s.overlays.find((x) => x.id === sel.id);
- // Asset-backed stickers stay out: a template copies only the media
- // its layers/audio reference, so the sticker's bytes wouldn't travel.
- if (o && !(isStickerOverlay(o) && o.assetId)) {
- texts.push({ ...o, start: o.start - start0, end: o.end - start0 });
+ if (!o) continue;
+ // A sticker's image travels as template media, so it comes back
+ // pointing at the copy.
+ if (isStickerOverlay(o) && o.assetId) {
+ const mi = mediaFor(o.assetId);
+ if (mi == null) continue;
+ stickers.push({ text: texts.length, media: mi });
}
+ texts.push({ ...o, start: o.start - start0, end: o.end - start0 });
} else if (sel.kind === "cue") {
const c = s.subtitles.cues.find((x) => x.id === sel.id);
if (c) cues.push({ ...c, start: c.start - start0, end: c.end - start0 });
@@ -3957,7 +3959,23 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const duration = range
? range.end - range.start
: Math.max(0.1, ...texts.map((t) => t.end), ...cues.map((c) => c.end));
- return { name: "Template", duration, media, layers, audio, texts, cues };
+ // The bars playing between the saved clips travel too, timed from the
+ // template's start.
+ const roles = resolveTransitions(s.clips, s.transitions);
+ const transitions = s.transitions
+ .filter((t) => (roles.get(t.id) ?? []).some((rl) => clipIds.has(rl.clipId)))
+ .map((t) => ({ ...t, start: t.start - start0 }));
+ return {
+ name: "Template",
+ duration,
+ media,
+ layers,
+ audio,
+ texts,
+ cues,
+ ...(stickers.length ? { stickers } : {}),
+ ...(transitions.length ? { transitions } : {}),
+ };
},
addTemplate: (input) => {
@@ -4069,32 +4087,28 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
out: l.out,
muted: l.muted,
...templateFraming(l),
- ...(l.speed ? { speed: l.speed } : {}),
- ...(l.speedCurve ? { speedCurve: l.speedCurve } : {}),
- ...(l.reverse ? { reverse: true } : {}),
- ...(l.smoothSlow ? { smoothSlow: true } : {}),
- ...(l.sound ? { sound: l.sound } : {}),
+ ...templateTreatment(l),
}));
const topTrack = Math.max(0, ...overlayLayers(get().clips).map((c) => c.track));
// Template layers store `track` as the source track + 1 (so a track-1
// layer saved as 2). Layers stack on top of the project's current top —
// never onto track 0 itself, which would splice them into the transition
- // sequence. Templates saved when tracks could go negative (backdrops)
- // clamp into the stack above too.
+ // sequence — keeping their rows relative to each other: the template's
+ // lowest layer lands on the row above the top, so a project with no
+ // layers yet gets the template's layers on the rows they had. Templates
+ // saved when tracks could go negative (backdrops) clamp into the stack
+ // above too.
+ const lowest = Math.min(...overlayLayerDefs.map((l) => Math.max(1, l.track)));
const newLayers: VideoClip[] = overlayLayerDefs.map((l) => ({
id: uid(),
assetId: assetIds[l.media],
- track: topTrack + Math.max(1, l.track),
+ track: topTrack + 1 + (Math.max(1, l.track) - lowest),
start: l.start + shift,
in: l.in,
out: l.out,
muted: l.muted,
...templateFraming(l),
- ...(l.speed ? { speed: l.speed } : {}),
- ...(l.speedCurve ? { speedCurve: l.speedCurve } : {}),
- ...(l.reverse ? { reverse: true } : {}),
- ...(l.smoothSlow ? { smoothSlow: true } : {}),
- ...(l.sound ? { sound: l.sound } : {}),
+ ...templateTreatment(l),
}));
const newAudio: AudioClip[] = template.audio
.filter((a) => assetIds[a.media])
@@ -4120,27 +4134,49 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
// move in the slot. Groups are remapped per application, so adding the
// same template twice gives two independent groups.
const regroup = groupRemap(uid);
+ // A sticker drawn from template media points at the copy that landed;
+ // one whose media is unmapped stays out, like a layer would.
+ const stickerMedia = new Map((template.stickers ?? []).map((st) => [st.text, st.media]));
const newTexts: Overlay[] = liftMoveTracks(
migrateBehindSubject(stampOverlayKinds(template.texts))
- ).map((o) => ({
- ...o,
- id: uid(),
- start: o.start + shift,
- end: o.end + shift,
- ...regroup(o),
- // A template's element homes to whatever sits under where it lands.
- ...(typeof o.hostClipId === "string" ? { hostClipId: undefined } : {}),
- }));
+ )
+ // The sticker map is keyed by the template's own index, so each
+ // element keeps its index through the filter.
+ .map((o, i) => ({ o, i }))
+ .filter(({ i }) => {
+ const mi = stickerMedia.get(i);
+ return mi === undefined || !!assetIds[mi];
+ })
+ .map(({ o, i }) => ({
+ ...o,
+ id: uid(),
+ start: o.start + shift,
+ end: o.end + shift,
+ ...regroup(o),
+ // A template's element homes to whatever sits under where it lands.
+ ...(typeof o.hostClipId === "string" ? { hostClipId: undefined } : {}),
+ ...(stickerMedia.has(i) ? { assetId: assetIds[stickerMedia.get(i)!] } : {}),
+ }));
const newCues: SubtitleCue[] = template.cues.map((c) => ({
...c,
id: uid(),
start: c.start + shift,
end: c.end + shift,
+ // Word timings are timeline seconds, so they move with the cue.
+ ...(c.words ? { words: c.words.map((w) => ({ ...w, t0: w.t0 + shift, t1: w.t1 + shift })) } : {}),
+ }));
+ const newBars: TimelineTransition[] = (template.transitions ?? []).map((t) => ({
+ id: uid(),
+ start: t.start + shift,
+ seconds: clampBarSeconds(t.seconds),
+ style: t.style,
+ ...(t.hidden ? { hidden: true } : {}),
}));
set((s) => ({
clips: [...s.clips, ...newClips, ...newLayers].sort((a, b) => a.start - b.start),
audioClips: [...s.audioClips, ...newAudio],
overlays: [...s.overlays, ...newTexts],
+ transitions: newBars.length ? [...s.transitions, ...newBars] : s.transitions,
subtitles: {
...s.subtitles,
cues: [...s.subtitles.cues, ...newCues].sort((a, b) => a.start - b.start),
@@ -5025,27 +5061,23 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
copySelection: () => {
const s = get();
const sels = s.multiSelection.length ? s.multiSelection : s.selection ? [s.selection] : [];
- const items: ClipboardItem[] = [];
+ const items: TimelineClipboardItem[] = [];
for (const sel of sels) {
- if (sel?.kind === "clip") {
- const c = s.clips.find((x) => x.id === sel.id);
- if (c) items.push({ kind: "clip", item: { ...c } });
- } else if (sel?.kind === "audio") {
- const a = s.audioClips.find((x) => x.id === sel.id);
- if (a) items.push({ kind: "audio", item: { ...a } });
- } else if (sel?.kind === "overlay") {
- const o = s.overlays.find((x) => x.id === sel.id);
- if (o) items.push({ kind: "overlay", item: { ...o } });
- } else if (sel?.kind === "transition") {
- const t = s.transitions.find((x) => x.id === sel.id);
- if (t) items.push({ kind: "transition", item: { ...t } });
- }
+ if (!sel) continue;
+ const cb = clipboardItemFor(s, sel);
+ if (cb) items.push(cb);
}
if (items.length === 0) return false;
clipboard = items;
return true;
},
+ copiedItems: () => clipboard.map((cb) => ({ ...cb })),
+
+ setClipboard: (items) => {
+ clipboard = items.map((cb) => ({ ...cb }));
+ },
+
clearClipboard: () => {
clipboard = [];
},
@@ -5053,21 +5085,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
paste: () => {
if (clipboard.length === 0) return false;
const s = get();
- // Every copied item's media must still exist in this project (asset
- // stickers included; text and shapes reference none).
- if (
- clipboard.some((cb) => {
- const assetId =
- cb.kind === "transition"
- ? undefined
- : cb.kind === "overlay"
- ? isStickerOverlay(cb.item)
- ? cb.item.assetId
- : undefined
- : cb.item.assetId;
- return assetId !== undefined && !s.assets.some((a) => a.id === assetId);
- })
- )
+ // Every asset a copied item names must still exist in this project.
+ if (clipboard.some((cb) => clipboardItemAssetIds(cb).some((id) => !s.assets.some((a) => a.id === id))))
return false;
push();
// The paste lands under the skimmer while one is live, at the playhead
@@ -5079,6 +5098,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
let audioClips = cur.audioClips;
let overlays = cur.overlays;
let transitions = cur.transitions;
+ let cues = cur.subtitles.cues;
// A copy is its own thing: pasted group members stay grouped with each
// other and join nothing that was already on the timeline.
const regroup = groupRemap(uid);
@@ -5109,7 +5129,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const item: AudioClip = { ...cb.item, id: uid(), start: nextFreeStart(taken, t, clipLen(cb.item)) };
audioClips = [...audioClips, item];
newSel.push({ kind: "audio", id: item.id });
- } else {
+ } else if (cb.kind === "overlay") {
const len = Math.max(0.2, cb.item.end - cb.item.start);
const taken = overlays
.filter((o) => (o.lane ?? 0) === (cb.item.lane ?? 0))
@@ -5126,6 +5146,26 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
};
overlays = [...overlays, item];
newSel.push({ kind: "overlay", id: item.id });
+ } else if (cb.kind === "cue") {
+ // A cue lands on its own caption track, clear of the cues there.
+ const lane = cb.item.lane ?? 0;
+ const len = Math.max(0.1, cb.item.end - cb.item.start);
+ const taken = cues
+ .filter((c) => (c.lane ?? 0) === lane)
+ .map((c) => ({ start: c.start, end: c.end }));
+ const start = nextFreeStart(taken, t, len);
+ const shift = start - cb.item.start;
+ const cue: SubtitleCue = {
+ ...cb.item,
+ id: uid(),
+ start,
+ end: start + len,
+ ...(cb.item.words ? { words: cb.item.words.map((w) => ({ ...w, t0: w.t0 + shift, t1: w.t1 + shift })) } : {}),
+ };
+ cues = [...cues, cue].sort((a, b) => a.start - b.start);
+ newSel.push({ kind: "cue", id: cue.id });
+ } else {
+ assertNever(cb);
}
}
// Transition bars land last, against the row as this paste left it.
@@ -5173,7 +5213,15 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
newSel.push({ kind: "transition", id: bar.id });
}
}
- return { clips, audioClips, overlays, transitions, selection: newSel[newSel.length - 1] ?? null, multiSelection: newSel };
+ return {
+ clips,
+ audioClips,
+ overlays,
+ transitions,
+ ...(cues !== cur.subtitles.cues ? { subtitles: { ...cur.subtitles, cues } } : {}),
+ selection: newSel[newSel.length - 1] ?? null,
+ multiSelection: newSel,
+ };
});
return true;
},
@@ -5289,7 +5337,7 @@ export const docOverlays = (() => {
export function storedAssets(assets: MediaAsset[]): StoredAsset[] {
return assets
.filter((a) => !tabOnlyUpload(a))
- .map(({ id, fileName, name, type, duration, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts }) => ({
+ .map(({ id, fileName, name, type, duration, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts, copiedFrom }) => ({
id,
fileName,
name,
@@ -5305,6 +5353,7 @@ export function storedAssets(assets: MediaAsset[]): StoredAsset[] {
...(speech !== undefined ? { speech } : {}),
...(beats !== undefined ? { beats } : {}),
...(sceneCuts !== undefined ? { sceneCuts } : {}),
+ ...(copiedFrom !== undefined ? { copiedFrom } : {}),
}));
}
@@ -6181,6 +6230,95 @@ export function totalDuration(clips: VideoClip[]) {
/** A track-0 clip as older docs stored it: packed by array order, no `start`. */
type LegacyClip = Omit<VideoClip, "start"> & { start?: number };
+/** The timeline a stored document describes, in the shape the store holds
+ * it: every migration a project made under an older rule goes through here,
+ * so a doc reads the same whether it is opened into the editor, described
+ * to the assistant, or turned into a template. */
+export function normalizeDocState(
+ doc: Partial<ProjectDoc>,
+ assets: MediaAsset[]
+): {
+ clips: VideoClip[];
+ transitions: TimelineTransition[];
+ audioClips: AudioClip[];
+ overlays: Overlay[];
+ subtitles: SubtitlesBlock;
+ aspect: Aspect | null;
+ fadeIn: number;
+ fadeOut: number;
+ background: string;
+} {
+ const docClips = doc.clips ?? [];
+ // Older docs stored video track 0 packed (array order implied the
+ // position); bake explicit starts in once so every clip is free-placed.
+ const legacy = (docClips as LegacyClip[]).some((c) => typeof c.start !== "number");
+ const folded = (legacy ? packStarts(docClips as LegacyClip[]) : docClips).map((c) => ({
+ ...c,
+ track: c.track ?? 0,
+ }));
+ // Older docs kept tracks other than 0 in a separate `overlayClips` array;
+ // fold them into the one clip list (each already carries its `track`).
+ // Entries whose id already sits in `clips` are the same clip persisted
+ // twice by a version-skewed save (an older engine keeps overlayClips
+ // after a merged client writes the folded list) — keep the folded copy.
+ // Entries with track 0 were unreachable dead data under the split shape
+ // (never rendered, never played); promoting them would insert them into
+ // track 0's sequence, so they stay dropped.
+ const seen = new Set(folded.map((c) => c.id));
+ const legacyLayers = (doc.overlayClips ?? []).filter(
+ (c) => c.track !== 0 && !seen.has(c.id)
+ );
+ // Tracks number 0..N bottom-up. Docs saved when tracks could go
+ // negative (backdrop rows below the spine) lift wholesale so the
+ // lowest row becomes track 0 — the bottom row is the spine now.
+ const joined = [...folded, ...legacyLayers];
+ const lift = Math.max(0, ...joined.map((c) => -c.track));
+ const lifted = lift ? joined.map((c) => ({ ...c, track: c.track + lift })) : joined;
+ // Stamp `kind: "text"` on pre-union titles so every in-memory element
+ // carries its discriminant; the serializer strips it back. Effects
+ // saved onto a shared row move to one of their own, and a clip graded
+ // back when a look was a clip property gets that grade as an element
+ // over it — so a project made before either rule reads like a new one.
+ // The behind-speaker boolean becomes an inverted subject mask on load,
+ // so one mask model covers it everywhere in memory and on save. Key
+ // tracks written by the retired move picker lift into the move slot,
+ // leaving `kf` to the keys users set themselves.
+ const stamped = liftMoveTracks(
+ normalizeElementLanes(migrateBehindSubject(stampOverlayKinds(doc.overlays ?? [])))
+ );
+ const subtitles = doc.subtitles ?? emptySubtitles();
+ // Docs saved when edge transition styles existed convert them into the
+ // equivalent clip animations, and docs saved when a transition was a
+ // physical overlap pull their intruding clips apart — clips never
+ // overlap, whatever wrote the file. Pulling them apart lengthens the
+ // cut, so the whole document goes through it together.
+ const merged = separateOverlaps({
+ clips: migrateLegacyTransitions(lifted),
+ audioClips: doc.audioClips ?? [],
+ overlays: stamped,
+ cues: subtitles.cues,
+ });
+ const withLooks =
+ liftClipLooks(merged.clips, merged.overlays, getClipSpans(merged.clips, assets)) ?? {
+ clips: merged.clips,
+ overlays: merged.overlays,
+ };
+ return {
+ clips: withLooks.clips,
+ // Bars from the doc, plus one adopted for each transition/animation
+ // a pre-bar doc stored as a clip field.
+ transitions: adoptTransitionFields(withLooks.clips, sanitizeTransitions(doc.transitions)),
+ audioClips: merged.audioClips,
+ // Elements from before they had hosts home to the clips under them.
+ overlays: adoptOverlayHosts(withLooks.clips, withLooks.overlays),
+ subtitles: { ...subtitles, cues: merged.cues },
+ aspect: normalizeAspect(doc.aspect) ?? null,
+ fadeIn: doc.fadeIn ?? 0,
+ fadeOut: doc.fadeOut ?? 0,
+ background: projectBackground(doc.background),
+ };
+}
+
/** Assign packed sequential starts (each clip abutting the previous): the
* layout older docs implied by array order. */
function packStarts(clips: LegacyClip[]): VideoClip[] {
@@ -6386,24 +6524,20 @@ export function assetIdsInUse(s: {
clips: VideoClip[];
audioClips: AudioClip[];
overlays: Overlay[];
- subtitles?: { font?: string } | null;
+ transitions?: TimelineTransition[];
+ subtitles?: { font?: string; cues?: SubtitleCue[] } | null;
}): Set<string> {
- const used = new Set<string>();
- const font = (id: string | undefined) => {
- const asset = id ? fontAssetId(id) : null;
- if (asset) used.add(asset);
- };
- for (const c of s.clips) {
- if (c.assetId) used.add(c.assetId);
- if (c.removal?.matte?.assetId) used.add(c.removal.matte.assetId);
- if (c.removal?.backdrop?.assetId) used.add(c.removal.backdrop.assetId);
- }
- for (const c of s.audioClips) if (c.assetId) used.add(c.assetId);
- for (const o of s.overlays) {
- if (isStickerOverlay(o) && o.assetId) used.add(o.assetId);
- if (isTextOverlay(o)) font(o.font);
- }
- font(s.subtitles?.font);
+ // Every item kind says where its asset ids sit; the caption track's font
+ // is the one project-level reference beside them.
+ const used = listedAssetIds({
+ clips: s.clips,
+ audioClips: s.audioClips,
+ overlays: s.overlays,
+ transitions: s.transitions ?? [],
+ subtitles: { cues: s.subtitles?.cues ?? [] },
+ });
+ const captionFont = s.subtitles?.font ? fontAssetId(s.subtitles.font) : null;
+ if (captionFont) used.add(captionFont);
return used;
}
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 2e3aad13..7f7111b3 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -211,6 +211,10 @@ export interface StoredAsset {
/** Media panel folder this file is filed in (see ProjectDoc.mediaFolders);
* absent/null = the panel's top level. */
folderId?: string | null;
+ /** The project and asset this file was copied from — a paste or a
+ * replicate out of another project. A second copy of the same source finds
+ * this one and lands nothing twice. */
+ copiedFrom?: { projectId: string; assetId: string };
}
/** A folder in the Media panel's Project Files view — a flat, project-local
@@ -1052,11 +1056,21 @@ export interface TemplateLayer {
rotation?: number;
opacity?: number;
muted: boolean;
+ volume?: number;
speed?: number;
speedCurve?: SpeedNode[];
reverse?: boolean;
smoothSlow?: boolean;
sound?: ClipSound;
+ /** The clip's treatment, carried whole: manual grade, mask, box, pose
+ * keys. Absent on templates saved before the rail carried them. The
+ * clip's edges are bars, carried on the template's transitions; background
+ * removal stays behind, its matte baked from the footage it was cut from. */
+ grade?: ColorGrade;
+ mask?: Mask;
+ boxStyle?: BoxStyle;
+ kf?: OverlayKey[];
+ hidden?: boolean;
track: number;
/** Came from video track 0 — re-materializes as a timeline clip, not an
* overlay, so a template stands up its own footage. */
@@ -1077,6 +1091,24 @@ export interface TemplateAudio {
duck?: number;
lane?: number;
}
+/** The caption settings a template carries: how captions look and read,
+ * without the cues themselves. */
+export const CAPTION_LOOK_KEYS = [
+ "showOnVideo",
+ "style",
+ "size",
+ "font",
+ "x",
+ "y",
+ "wordsPerCue",
+ "wordHighlight",
+ "accentMode",
+ "accentColor",
+ "accentScale",
+ "accentDim",
+] as const;
+export type CaptionLook = Partial<Pick<SubtitlesBlock, (typeof CAPTION_LOOK_KEYS)[number]>>;
+
export interface LibraryTemplate {
id: string;
name: string;
@@ -1088,6 +1120,18 @@ export interface LibraryTemplate {
audio: TemplateAudio[];
texts: Overlay[];
cues: SubtitleCue[];
+ /** Transition bars inside the template, starts relative to its start. */
+ transitions?: TimelineTransition[];
+ /** Which `texts` entries are stickers drawn from a media entry: the
+ * sticker's image travels with the template and its assetId is rewritten
+ * to the copy when the template stands up. */
+ stickers?: { text: number; media: number }[];
+ /** The caption look the source wore. A whole-project template carries it;
+ * placing a template on a timeline leaves the project's own captions
+ * alone, and a replicate applies it. */
+ captions?: CaptionLook;
+ /** The frame the source was cut for, for a whole-project template. */
+ project?: { aspect: Aspect; background: string; fadeIn: number; fadeOut: number };
/** A saved sound treatment: a template carrying only this is a sound
* preset (see soundPresets.ts), listed in the audio inspector and kept
* off the template shelf. */
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 02bea345..20c2d172 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -392,6 +392,14 @@ The Library is shared across every project: folders, reusable assets, and templa
- import_url reads any URL (TikTok, YouTube, Instagram, an X post or Article, a web page, direct links): a page comes back as its article text and its pictures, a post as its video or photos, and a source that is only words as sourceText alone. When the user asks for the sound alone — a song, a soundtrack — pass audio_only and the audio track lands as an audio asset. Media lands as a card in the chat with that text quoted beside it; the user drags a card to the timeline, Media, or the Library. Place it with add_clip only when they asked for it in the cut.
Attachments: media files dropped on the chat import into project media by themselves; library attachments wait for library_add.`,
+ "replicating-a-project": `# Replicating another project
+A link to a Donkey Cut project (…/app/p/<id>) or a share (…/s/<token>) is a document you can read whole. read_project returns it in the editor_state shape — every clip with its id, trims, rate, framing, grade, look, mask, keyframes and animations; the transition bars; titles, shapes and stickers with their keyframes; the soundtrack; the caption look and cues; aspect, background and fades — and each source under \`media\` with its id, its observed notes and its transcript. \`unobserved\` lists video sources with neither. \`partial\` on a share names what its owner withheld.
+The document is the edit. Never watch_video a reference to reconstruct what read_project already states. Watch a reference source (watch_video with project_link and its asset_id or clip_id) only to see footage whose notes leave its content unclear; that look decides a mapping and writes nothing to the reference.
+**Scope is the user's.** "Replicate this" is the whole edit; "use the title from this", "bring over the music", "grade my clip like theirs", "the caption style" are items. replicate_project takes \`items\` (any ids from read_project: clips on any track, soundtrack clips, elements, cues, transition bars) and brings only those, timed from the earliest; a chosen clip brings the bars playing on it. A single clip's treatment onto footage already here is a mapping: items:[that clip], media:[{source_asset_id, asset_id: the clip here}] — its grade, look, mask, keys and animations land on a new clip cut from the user's asset; delete the old one only if they asked for a replacement. A style alone with no clip — a grade, a caption look — is also readable straight off read_project and applied with the ordinary tools (set_color_grade, set_caption_look). Files alone go through copy_project_media.
+**Mapping roles.** Each reference source the chosen items use plays from one of this project's assets or copies across. Match by content — a talking-head source to the talking-head here, b-roll to b-roll — using the reference's notes and transcripts against this project's (\`media\` in editor_state, watch_video on anything unseen). One asset here may play several reference parts. Video and stills stand in for video; audio for audio. Leave unmapped whatever has no counterpart — music, stickers, images, fonts, a clip the user wants as-is — and it copies from the reference into this project, on a card in this chat.
+**After replicate_project.** Clips land after the current end of track 0 (an empty project is the natural target; with a cut already there, say where the copy landed). Read \`adjustments\`: a trim clamped to a shorter source, a still holding a clip's length — fix or report each. Then make the edit the user's: rewrite each title's text for their subject (update_overlay), generate captions when the reference wore them (subtitles_generate; the caption look is already applied for the whole edit), refine_speech_cuts on the user's speech clips, and check a frame with capture_frame. With the whole edit the reference's aspect, background, fades and caption look come too; with \`items\` pass frame / caption_look when the user wants them. Background removal on a reference clip stays behind (its matte was baked from that footage): set_removal on the new clip when they want it.
+Templates (save_template / template_add) ride the same rail and now keep grades, masks, keyframes, transitions and stickers; a whole-project template's frame and caption look are applied only by replicate_project.`,
+
"publish-and-export": `# Publish & export
Publish tab fields (set_publish): caption (TikTok limit 4,000 chars INCLUDING tags/emoji; hook in the first line), tags (3–5 focused tags recommended; stored space-separated, rendered as #tags), soundTitle (TikTok lets you rename the sound once after posting), handle (shown as @handle in platform previews).
Export (open_export): one-click presets — Share (1080p H.264 MP4, plays everywhere), Best (source size, H.264 MP4, high quality), Small (720p, fastest), Master (source size, ProRes 422 HQ in a MOV with PCM audio, for handing to another editor) — and an Advanced panel with every axis: format (MP4 or MOV), codec (H.264, HEVC at about half the size for newer devices, ProRes 422 HQ), resolution (Source, which matches the sharpest clip on the timeline along the project aspect with a 1080p floor and a 4K cap, then every named rung below it: 4K, 1440p, 1080p, 720p), frame rate (24, 30 or 60), quality (High, Balanced, Small, or a typed bitrate in Mbps), audio (AAC or uncompressed PCM). ProRes and PCM take a MOV. The dialog shows the size the choice will land at. Every export renders at the project aspect ratio, titles and subtitles burned in. Files land in the project's exports/ folder and appear in the Media tab's Exports section, where each can be previewed plain or in TikTok/Instagram/YouTube chrome with the publish metadata rendered in place, revealed in Finder, or deleted.`,
@@ -414,6 +422,7 @@ Rules:
- Styling is part of the ask, never a bonus. Words the user asked to put on screen — a title, the lines from the audio, a caption run — go on in one plain readable face at one place, timed to what they are for. Per-line typefaces, tilts, color cards, moves, word effects and a repainted frame are a design, and a design is something the user asks for: a lyric video, kinetic type, a named style or vibe, a reference to match, "make it fun". Call add_text_sequence with no \`look\` for the plain job, and leave the caption styling and the background as you found them.
- Read list_skills / read_skill before working in an area you're unsure about — they document every setting. A tool whose description already answers the ask goes straight through.
- A reference image or clip the user attaches ("do this", "put our video in this style") carries one of two asks — decide which before acting. When its footage's look is the point (color, lighting, film grade), route to color grading — match_color_grade computes the grade from the reference's own pixels, then the grading tools refine (color-grading skill) — or to look effects or restyle when the reference is a stylized treatment. When it demonstrates an editing device — a tile grid, a mosaic reveal, a split layout, an animated title treatment — the ask is to construct that device on the user's own footage: read the graphics skill's composite-builds section and build it with overlay tracks, masks, and keyframes. Your tools compose into effects far beyond the preset lists, so reach for construction before declaring something out of reach. Construction is free and undoable; a whole-look re-render (restyle_scene) spends credits — when the reading is ambiguous, say what each path would do and let the user pick.
+- A Donkey Cut project link or share link the user gives you is a document: read it with read_project (the document is the edit — never watch a reference to learn what its document already states), decide which of this project's sources plays each of its parts from the reference's observed notes and transcripts (a reference look with watch_video's project_link where those leave it dark), then call replicate_project once — the whole edit, or only the items they asked for: a title, one clip's treatment, the music, the caption look — and tune from there. copy_project_media brings files over on their own. The replicating-a-project skill has the flow.
- Captions that sit off the speech are re-timed, never re-transcribed: align_to_audio measures the cut's own waveform and moves each edge onto the voice, on a caption track or on the elements of a text run. Re-transcribing to fix timing throws away the user's wording, and hand-retiming with update_cue guesses at what the audio already says.
- Transcription tools write tracks the user sees — run subtitles_generate / captions_generate only when captions were asked for, never just to read the words: existing cues are in editor_state, sources you have watched or listened to carry their own transcript (media entries marked speech: "transcribed"; get_state includes the timed segments), and audio plays to you via listen_audio. Don't transcribe a video with no speech (subtitles_from_visuals narrates silent footage), and never invent a spoken transcript.
- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.
diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.ts
index 9ccf1d04..4ae47d87 100644
--- a/site/src/cut/server/ai/headlessTools.ts
+++ b/site/src/cut/server/ai/headlessTools.ts
@@ -1,5 +1,7 @@
+import { copyFile } from "node:fs/promises";
import { runAiTool, UI_TOOLS } from "../../lib/aiTools";
import { mp4NameFor, setHostMediaStore } from "../../lib/mediaConvert";
+import { setHostDocStore } from "../../lib/projectReference";
import { serializeDoc, useEditor } from "../../lib/store";
import type { MediaAsset, ProjectDoc } from "../../lib/types";
import { convertToMp4 } from "../convert";
@@ -82,6 +84,18 @@ setHostMediaStore({
},
});
+// Another project on this Mac, read as a reference: the doc off disk and a
+// file copied folder to folder. A cloud or shared reference needs the page's
+// sign-in, and the reader says so.
+setHostDocStore({
+ readDoc: (projectId) => readProject(projectId),
+ async copyMedia(srcProjectId, fileName, dstProjectId) {
+ const target = await uniqueName(fileName, (n) => mediaPath(dstProjectId, n));
+ await copyFile(mediaPath(srcProjectId, fileName), mediaPath(dstProjectId, target));
+ return target;
+ },
+});
+
interface OpenDoc {
projectId: string;
stored: ProjectDoc;
diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.ts
index 850e83e3..fb3113e2 100644
--- a/site/src/cut/server/cloud/library.ts
+++ b/site/src/cut/server/cloud/library.ts
@@ -11,6 +11,7 @@ import type {
TemplateLayer,
TemplateMedia,
} from "../library";
+import { templateExtras } from "../library";
import { resolveParent } from "@/cut/lib/folderTree";
import type { StoredAsset } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
@@ -55,6 +56,10 @@ interface TemplateDoc {
texts: unknown[];
cues: unknown[];
sound?: LibraryTemplate["sound"];
+ transitions?: unknown[];
+ stickers?: unknown[];
+ captions?: unknown;
+ project?: unknown;
}
/** A template with nothing on it saves nothing; a sound preset is a template
@@ -119,6 +124,7 @@ function templateView(row: {
texts: doc.texts ?? [],
cues: doc.cues ?? [],
...(doc.sound ? { sound: doc.sound } : {}),
+ ...(templateExtras(doc) as Pick<LibraryTemplate, "transitions" | "stickers" | "captions" | "project">),
};
}
@@ -869,6 +875,7 @@ export const libraryCloud = {
texts: input.texts ?? [],
cues: input.cues ?? [],
...(input.sound ? { sound: input.sound } : {}),
+ ...templateExtras(input),
};
const row = await prisma.cutTemplate.create({
data: {
@@ -927,6 +934,7 @@ export const libraryCloud = {
texts: input.texts ?? [],
cues: input.cues ?? [],
...(input.sound ? { sound: input.sound } : {}),
+ ...templateExtras(input),
};
const row = await prisma.cutTemplate.create({
data: {
diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.ts
index e0af3739..c4681776 100644
--- a/site/src/cut/server/library.ts
+++ b/site/src/cut/server/library.ts
@@ -63,7 +63,7 @@ export interface LibraryFolder {
export interface TemplateMedia {
fileName: string; // private copy inside the library media folder
name: string;
- type: "video" | "audio" | "image";
+ type: "video" | "audio" | "image" | "font";
duration: number;
width?: number;
height?: number;
@@ -115,7 +115,26 @@ export interface LibraryTemplate {
cues: unknown[]; // opaque SubtitleCue[]
/** A template carrying only this is a saved sound preset. */
sound?: ClipSound;
-}
+ /** Opaque, round-tripped for the client: transition bars, which texts are
+ * stickers drawn from media, the caption look, the source's frame. */
+ transitions?: unknown[];
+ stickers?: unknown[];
+ captions?: unknown;
+ project?: unknown;
+}
+
+/** The parts of a template the server carries whole. */
+export const templateExtras = (input: {
+ transitions?: unknown[];
+ stickers?: unknown[];
+ captions?: unknown;
+ project?: unknown;
+}) => ({
+ ...(input.transitions?.length ? { transitions: input.transitions } : {}),
+ ...(input.stickers?.length ? { stickers: input.stickers } : {}),
+ ...(input.captions ? { captions: input.captions } : {}),
+ ...(input.project ? { project: input.project } : {}),
+});
interface LibraryIndex {
assets: LibraryAsset[];
@@ -471,7 +490,7 @@ export interface TemplateInput {
media: {
fileName: string;
name: string;
- type: "video" | "audio" | "image";
+ type: "video" | "audio" | "image" | "font";
duration: number;
width?: number;
height?: number;
@@ -481,6 +500,10 @@ export interface TemplateInput {
texts: unknown[];
cues: unknown[];
sound?: LibraryTemplate["sound"];
+ transitions?: unknown[];
+ stickers?: unknown[];
+ captions?: unknown;
+ project?: unknown;
}
/** A template with nothing on it saves nothing; a sound preset is a template
@@ -527,6 +550,7 @@ export async function importTemplate(
texts: input.texts ?? [],
cues: input.cues ?? [],
...(input.sound ? { sound: input.sound } : {}),
+ ...templateExtras(input),
folderId: input.folderId ?? null,
};
await mutateIndex((idx) => {
@@ -569,6 +593,7 @@ export async function saveTemplate(
texts: input.texts ?? [],
cues: input.cues ?? [],
...(input.sound ? { sound: input.sound } : {}),
+ ...templateExtras(input),
};
await mutateIndex((idx) => {
idx.templates = [...(idx.templates ?? []), template];
diff --git a/site/src/types/bun-test.d.ts b/site/src/types/bun-test.d.ts
index 4f673919..cbca19d5 100644
--- a/site/src/types/bun-test.d.ts
+++ b/site/src/types/bun-test.d.ts
@@ -24,7 +24,11 @@ declare module "bun:test" {
toBeLessThanOrEqual(expected: number): void;
toContain(expected: string): void;
toBeUndefined(): void;
+ toBeDefined(): void;
toBeNull(): void;
+ toMatchObject(expected: object): void;
+ toThrow(expected?: string | RegExp): void;
+ rejects: Matchers;
toHaveLength(expected: number): void;
toBeTruthy(): void;
toBeFalsy(): void;