Open source CapCut alternative.
TypeScript
feat(site): give each project three timelines with a picker and a shared-timeline setting [rebuild]
David Le6db6cf9cb940
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 97529260..96a5a9ef 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -46,9 +46,11 @@ Browser previews use the browser compositor and replace one cached proxy in OPFSCloud source media, generated media, and retained exports count toward storage. Derived previews, share cards, and HLS ladders are quota-exempt; staging inputs are temporary. An export is weighed twice — the size it is heading for before a frame is drawn, and what actually landed before the account is charged — so one render cannot carry an account past its cap. Transports expose structured storage, credit, and authentication failures. Each host chooses their presentation; the website mounts its storage dialog separately.-Timeline and preview share selection: ⌘/Ctrl-click or Shift-click toggles items; dragging moves them with one undo step. Groups persist. Their preview frame scales and rotates the selection; the group panel edits shared fields, showing Mixed where values differ. Text side grips change wrapping width and corners scale proportionally; height follows content across preview, export and chat. Dropping between timeline rows inserts a row through shared text, video and audio placement.+A project has three timelines, Main, Second and Third, picked from the timeline toolbar; a share link plays the one its settings pick, Main by default.-Guides draw over the preview from the button beside the timeline zoom: thirds, center, safe margins, the short-form keep-out zone where TikTok, Reels and Shorts draw their own UI or crop the sides of a 9:16 frame, and custom lines dragged into place on the preview. They save with the project, snap a dragged element to their edges, never export, and the assistant reads the safe area they leave when it places graphics.+Timeline and preview share selection: ⌘/Ctrl-click or Shift-click toggles items; dragging moves them with one undo step. Groups persist. Their preview frame scales and rotates the selection; the group panel edits shared fields, showing Mixed where values differ. Text side grips change wrapping width and corners scale proportionally; height follows content across preview, export and chat.++Guides draw over the preview from the button beside the timeline zoom: thirds, center, safe margins, the short-form keep-out zone, and custom lines. They save with the project, snap a dragged element to their edges and never export.## The exportdiff --git a/site/src/cut/components/GeneratedAssetMenu.tsx b/site/src/cut/components/GeneratedAssetMenu.tsxindex 7a89fbd9..234c3fa9 100644--- a/site/src/cut/components/GeneratedAssetMenu.tsx+++ b/site/src/cut/components/GeneratedAssetMenu.tsx@@ -21,7 +21,7 @@ import {} from "@/components/ui/dropdown-menu";import { saveAssetToLibrary } from "@/cut/lib/library";import { downloadMedia } from "@/cut/lib/media";-import { useEditor } from "@/cut/lib/store";+import { assetClipUses, useEditor } from "@/cut/lib/store";import type { MediaAsset } from "@/cut/lib/types";/** The "…" menu on a generated asset (image tile, video job row, voiceover@@ -55,9 +55,7 @@ export function GeneratedAssetMenu({const remove = () => {if (!onDelete) return;const s = useEditor.getState();- const uses =- s.clips.filter((c) => c.assetId === asset.id).length +- s.audioClips.filter((c) => c.assetId === asset.id).length;+ const uses = assetClipUses(s, new Set([asset.id]));// Deleting something the cut never used costs the user nothing to redo.if (uses > 0) setConfirmUses(uses);else onDelete();diff --git a/site/src/cut/components/ShareDialog.tsx b/site/src/cut/components/ShareDialog.tsxindex 971effca..59210b51 100644--- a/site/src/cut/components/ShareDialog.tsx+++ b/site/src/cut/components/ShareDialog.tsx@@ -16,6 +16,7 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Switch } from "@/components/ui/switch";import { useQueryClient } from "@tanstack/react-query";import { useSharing, sharingKey } from "@/queries/sharing";@@ -23,7 +24,7 @@ import { requestSharing, type ShareResource } from "@/cut/lib/sharingClient";import { librarySharePath, shareEmailSchema, type ShareSettings as AccessSettings } from "@/cut/lib/librarySharing";import { refreshShareCard, refreshShareLadder } from "@/cut/lib/exportClient";import { useCutBase } from "@/cut/lib/nav";-import type { ShareFeatures } from "@/cut/lib/types";+import { isTimelineId, TIMELINE_IDS, TIMELINE_LABELS, type ShareFeatures, type TimelineId } from "@/cut/lib/types";// One sharing dialog for projects, library folders, and assets. Changes save immediately.@@ -39,7 +40,9 @@ const NO_FEATURES: ShareFeatures = {details: false,};-const FEATURE_ROWS: { key: keyof ShareFeatures; label: string; hint: string }[] = [+type FeatureKey = Exclude<keyof ShareFeatures, "timeline">;++const FEATURE_ROWS: { key: FeatureKey; label: string; hint: string }[] = [{ key: "chat", label: "Chat", hint: "AI chat threads and their cards" },{ key: "media", label: "Media", hint: "Uploaded files beyond the timeline" },{ key: "genai", label: "AI generations", hint: "Generated video, image, and audio" },@@ -147,10 +150,21 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {if (access !== current.access) void save({ ...current, access });};- const setFeature = (key: keyof ShareFeatures, on: boolean) => {+ const setFeature = (key: FeatureKey, on: boolean) => {void save({ ...current, features: { ...current.features, [key]: on } });};+ // A different timeline is a different cut on the link, so its card and+ // stream are rebuilt once the setting lands.+ const setTimeline = async (timeline: TimelineId) => {+ if (timeline === (current.features.timeline ?? "main")) return;+ const saved = await save({ ...current, features: { ...current.features, timeline } });+ if (saved && projectId) {+ refreshShareCard(projectId);+ void refreshShareLadder(projectId);+ }+ };+const copyLink = async () => {// The first copy creates the share, so the link works the moment it's on// the clipboard.@@ -288,6 +302,33 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {</DropdownMenu></div>+ {projectId && (+ <div className="flex min-h-9 items-center justify-between gap-2.5">+ <span className="text-[13px]">+ Timeline+ <span className="block text-[10.5px] text-muted-foreground">What viewers watch</span>+ </span>+ <Select+ value={current.features.timeline ?? "main"}+ disabled={busy}+ onValueChange={(v) => {+ if (isTimelineId(v)) void setTimeline(v);+ }}+ >+ <SelectTrigger className="w-fit min-w-28" aria-label="Timeline">+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end">+ {TIMELINE_IDS.map((id) => (+ <SelectItem key={id} value={id}>+ {TIMELINE_LABELS[id]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}+{projectId ? <details className="group"><summary className="cursor-pointer list-none text-[11px] font-medium tracking-wide text-muted-foreground uppercase select-none"><span className="inline-flex items-center gap-1">diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 5083e281..92d0e6d8 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -105,7 +105,7 @@ import {} from "@/cut/lib/genNotify";import { useGenerate, type GenerateJob } from "@/cut/lib/generate";import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";-import { useEditor } from "@/cut/lib/store";+import { assetClipUses, useEditor } from "@/cut/lib/store";import { useEnvironment } from "@/cut/lib/environment";import { formatTime } from "@/cut/lib/time";import { useLocalPref } from "@/cut/lib/uiState";@@ -975,9 +975,7 @@ function ProjectFilesPanel({const { folders: goneFolders, items } = splitPick(ids);const held = s.assets.filter((a) => !!a.folderId && goneFolders.includes(a.folderId));const gone = new Set([...items, ...held.map((a) => a.id)]);- const uses =- s.clips.filter((c) => gone.has(c.assetId)).length +- s.audioClips.filter((c) => gone.has(c.assetId)).length;+ const uses = assetClipUses(s, gone);if (uses > 0 || held.length > 0) setDeletingIds(ids);else deleteNow(ids);};@@ -1460,9 +1458,7 @@ function AssetCard({const remove = () => {const s = useEditor.getState();- const uses =- s.clips.filter((c) => c.assetId === asset.id).length +- s.audioClips.filter((c) => c.assetId === asset.id).length;+ const uses = assetClipUses(s, new Set([asset.id]));// Deleting an unused asset is harmless; only confirm when it would also// remove clips from the timeline.if (uses > 0) setConfirmUses(uses);diff --git a/site/src/cut/components/Timeline.tools.ts b/site/src/cut/components/Timeline.tools.tsindex 76fc9026..139ffec3 100644--- a/site/src/cut/components/Timeline.tools.ts+++ b/site/src/cut/components/Timeline.tools.ts@@ -17,6 +17,7 @@ import {} from "@/cut/lib/textCompose";import { TEXT_MOVE_IDS, TEXT_MOVE_NOTES } from "@/cut/lib/textMotion";import { OVERLAY_ANIM_STYLE_IDS } from "@donkeycut/effects-kit";+import { TIMELINE_IDS, TIMELINE_LABELS } from "@/cut/lib/types";export const TIMELINE_TOOLS = [{@@ -367,6 +368,13 @@ export const TIMELINE_TOOLS = [["kind", "describe"]),},+ {+ name: "switch_timeline",+ description: `Open another of the project's ${TIMELINE_IDS.length} timelines (${TIMELINE_IDS.map((id) => `${id} = ${TIMELINE_LABELS[id]}`).join(", ")}) — the picker at the left of the timeline toolbar. Each timeline holds its own clips, soundtrack, transitions, elements and subtitles; the media, the frame and the project settings are shared. The preview, the export and every other tool work on the open one, which editor_state project.timeline names, with project.timelines summarizing each. A timeline opened for the first time is empty, and each keeps its own undo history. A share link plays the timeline its share settings pick, Main by default. There are exactly these ${TIMELINE_IDS.length}; none can be added, renamed or deleted.`,+ inputSchema: obj({+ timeline: { type: "string", enum: [...TIMELINE_IDS], description: "The timeline to open" },+ }, ["timeline"]),+ },{name: "set_view",description:diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 7512dd9d..75d81298 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -7,6 +7,7 @@ import { ArrowDownToLine, AudioLines, Check, Clapperboard, Copy, Diamond, Downloimport { EFFECT_CHIP_ICONS, effectIconKind, SHAPE_CHIP_ICONS, TRANSITION_ICONS } from "@/cut/components/entityIcons";import { Button } from "@/components/ui/button";import { GuidesMenu } from "@/cut/components/GuidesMenu";+import { TimelinePicker } from "@/cut/components/TimelinePicker";import {DropdownMenu,DropdownMenuContent,@@ -2209,6 +2210,7 @@ export function Timeline() {measurement below lands: the overlap stops being something to getright and becomes something that cannot be drawn. */}<div className="col-start-1 row-start-1 ml-2.5 flex min-w-0 items-center gap-0.5 overflow-hidden">+ <TimelinePicker />{!barTight && (<TimelineToolssplit={split}@@ -2222,6 +2224,7 @@ export function Timeline() {{/* Measure the contextual icons even when they fold into the menu. */}<div aria-hidden className="invisible pointer-events-none absolute flex items-center gap-0.5"><div ref={toolsBareRef} className="flex items-center gap-0.5">+ <TimelinePicker /><TimelineToolssplit={split}addText={addText}diff --git a/site/src/cut/components/TimelinePicker.tsx b/site/src/cut/components/TimelinePicker.tsxnew file mode 100644index 00000000..b272a9e0--- /dev/null+++ b/site/src/cut/components/TimelinePicker.tsx@@ -0,0 +1,57 @@+"use client";++import { ChevronDown } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { useEditor } from "@/cut/lib/store";+import { switchTimeline, useTimelinePicker } from "@/cut/lib/timelineSwitch";+import { isTimelineId, TIMELINE_IDS, TIMELINE_LABELS } from "@/cut/lib/types";++/** The timeline picker at the head of the toolbar: the open timeline's name,+ * and the project's others under it. Held while work is still landing on the+ * open one. */+export function TimelinePicker() {+ const timeline = useEditor((s) => s.timeline);+ const readOnly = useEditor((s) => s.readOnly);+ const { supported, blocked } = useTimelinePicker();+ if (readOnly || !supported) return null;+ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger+ disabled={blocked}+ render={<Button variant="ghost" size="sm" className="shrink-0 gap-1 px-2" aria-label="Timeline" />}+ >+ {TIMELINE_LABELS[timeline]}+ <ChevronDown className="size-3.5 text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-40">+ <DropdownMenuGroup>+ <DropdownMenuLabel>Timelines</DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={timeline}+ onValueChange={(id) => {+ if (isTimelineId(id)) void switchTimeline(id);+ }}+ >+ {TIMELINE_IDS.map((id) => (+ <DropdownMenuRadioItem key={id} value={id}>+ {TIMELINE_LABELS[id]}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ <div role="separator" aria-orientation="vertical" className="mx-1 h-4 w-px shrink-0 bg-border" />+ </>+ );+}diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex ae63acc4..317adffe 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -1,13 +1,13 @@"use client";import { formatBytes } from "@/lib/bytes";-import { isLinkedAssetType } from "./types";+import { isLinkedAssetType, isTimelineId, sanitizeTimelines, TIMELINE_IDS, TIMELINE_LABELS, type TimelineBody, type TimelineId } from "./types";import { GUIDE_PRESETS, guideFits, guideGeometry, safeAreaOf, sanitizeGuideLines, sanitizeGuides, type GuideId, type GuideLines } from "./guides";import { hasOverlayAnim, retimeOf, speedCurveOf, WHEEL_LABELS, WHEEL_ZONES, type ClipSound, type OutputSpace, type SpeedNode } from "@donkeycut/effects-kit";import { chatOwner } from "./chatAssets";import { useGenerate } from "./generate";import { useMatteBakes } from "./removal/bakeJobs";-import { deriveTransitionFields, getClipSpans, normalizeDocState, overlayLayers, resolveTransitions, totalDuration, useEditor } from "./store";+import { deriveTransitionFields, getClipSpans, normalizeDocState, overlayLayers, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";import type { VideoProject } from "./genvideo/types";import { playheadAt, skimAt } from "./playhead";import { cueWordCount } from "./cueChunk";@@ -307,6 +307,8 @@ export function describeDoc(doc: ProjectDoc, opts?: { fullCues?: boolean; chatIdguideLines: sanitizeGuideLines(doc.guideLines),genvideo: doc.genvideo ?? undefined,mediaFolders: doc.mediaFolders ?? [],+ timeline: isTimelineId(doc.timeline) ? doc.timeline : "main",+ timelines: sanitizeTimelines(doc.timelines) ?? {},},{ fullCues: opts?.fullCues === true, chatId: opts?.chatId ?? null, live: false });@@ -334,6 +336,8 @@ interface DescribedState {guideLines: GuideLines;genvideo?: VideoProject | null;mediaFolders: MediaFolder[];+ timeline: TimelineId;+ timelines: Partial<Record<TimelineId, TimelineBody>>;}/** The media a project's timeline plays: project content whichever chat made it. */@@ -391,6 +395,19 @@ function describeState(id: s.projectId,name: s.projectName,duration: r(duration),+ // The open timeline is what everything else here describes; the others+ // are parked until switch_timeline opens one.+ timeline: s.timeline,+ timelines: TIMELINE_IDS.map((id) => {+ const body = id === s.timeline ? s : s.timelines[id];+ return {+ id,+ label: TIMELINE_LABELS[id],+ ...(id === s.timeline ? { open: true } : {}),+ duration: r(body ? projectDuration(body) : 0),+ clips: body?.clips.length ?? 0,+ };+ }),aspect: s.aspect,frame: `${frameOf(s.aspect).w}x${frameOf(s.aspect).h}`,background: s.background,diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 9c65c16b..cfafdc0c 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -109,6 +109,7 @@ import { chatOwner, tagChatAsset } from "./chatAssets";import { queueMessageFromAgent } from "./chatQueue";import { applyOwnership, useGenerate, type VideoAttempt, type VideoGenOptions } from "./generate";import { useGenScene } from "./genScene";+import { switchTimeline } from "./timelineSwitch";import { folderWithin } from "./folderTree";import { anchorRefused } from "./genvideo/shotAttempts";import {@@ -181,7 +182,7 @@ import { isGradePresetTemplate, listSavedGrades, saveGradePreset } from "./gradeimport { isStylePresetTemplate } from "./stylePresets";import { loadLibraryLut, lutIdOf, lutLabel } from "./linkedLibrary";import { sampleClipBaseFrameData, sourceProfileOf, toBaseRendering } from "./baseFrame";-import { applyOverlayPatchSettled, clipLen, track0Clips, laneGapAt, getClipSpans, overlayLaneOrder, overlayLayers, parkedTransitions, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";+import { applyOverlayPatchSettled, assetClipUses, clipLen, track0Clips, laneGapAt, getClipSpans, overlayLaneOrder, overlayLayers, parkedTransitions, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";import { playheadAt } from "./playhead";import { renderProjectFrame, renderProjectFrames } from "./exportRender";import { framesAt, readMediaFileSize } from "./mediaRead";@@ -258,6 +259,8 @@ import {SHAPE_LABELS,SIDE_PANEL_TABS,SPEED_FLOOR,+ isTimelineId,+ TIMELINE_IDS,TRANSITION_STYLE_IDS,type AnimStyle,type AssetWatch,@@ -4184,9 +4187,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {delete_asset: (s, input) => {const asset = requireItem(s.assets, input.asset_id, "project asset");- const uses =- s.clips.filter((c) => c.assetId === asset.id).length +- s.audioClips.filter((c) => c.assetId === asset.id).length;+ const uses = assetClipUses(s, new Set([asset.id]));s.removeAsset(asset.id);return { removed: asset.name, clipsRemoved: uses };},@@ -4500,6 +4501,21 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {return patch;},+ switch_timeline: async (_s, input) => {+ if (!isTimelineId(input.timeline))+ throw new ToolError(`timeline must be one of ${TIMELINE_IDS.join(", ")}.`);+ const blocked = await switchTimeline(input.timeline);+ if (blocked) throw new ToolError(blocked);+ const s = useEditor.getState();+ return {+ timeline: s.timeline,+ duration: round2(projectDuration(s)),+ clips: s.clips.length,+ audioClips: s.audioClips.length,+ overlays: s.overlays.length,+ };+ },+set_view: (s, input) => {const out: Record<string, number> = {};if (input.fit) {diff --git a/site/src/cut/lib/backend/browser/router.ts b/site/src/cut/lib/backend/browser/router.tsindex e6497165..f8cf78e5 100644--- a/site/src/cut/lib/backend/browser/router.ts+++ b/site/src/cut/lib/backend/browser/router.ts@@ -8,7 +8,7 @@// shelf (./library.ts). Everything else is the driver's cloud proxy.import { resolveParent, settleParents, subtreeOf } from "../../folderTree";import { sanitizeGuideLines, sanitizeGuides } from "../../guides";-import { normalizeAspect, type ProjectDoc, type ProjectFolder } from "../../types";+import { isTimelineId, normalizeAspect, sanitizeTimelines, type ProjectDoc, type ProjectFolder } from "../../types";import {getBrowserExportJob,listBrowserExportJobs,@@ -92,6 +92,8 @@ async function putProject(req: Request, id: string): Promise<Response> {? []: existing.overlayClips,overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,+ timeline: isTimelineId(body.timeline) ? body.timeline : existing.timeline,+ timelines: sanitizeTimelines(body.timelines) ?? existing.timelines,templates: Array.isArray(body.templates) ? body.templates : existing.templates,mediaFolders: Array.isArray(body.mediaFolders) ? body.mediaFolders : existing.mediaFolders,aspect: normalizeAspect(body.aspect) ?? existing.aspect,diff --git a/site/src/cut/lib/chatAssets.ts b/site/src/cut/lib/chatAssets.tsindex e4549b96..114a28e1 100644--- a/site/src/cut/lib/chatAssets.ts+++ b/site/src/cut/lib/chatAssets.ts@@ -2,7 +2,7 @@import { useGenerate } from "./generate";import { usePreviewAudio } from "./previewAudio";-import { assetIdsInUse, useEditor } from "./store";+import { assetIdsOnAnyTimeline, useEditor } from "./store";// Chat-created media belongs to its thread. The files live in the project's// media folder like every other asset (drag-to-timeline and previews need@@ -62,7 +62,7 @@ export function threadOwnsAssets(threadId: string): boolean {* deletion. */export function deleteChatAssets(threadId: string) {const s = useEditor.getState();- const inUse = assetIdsInUse(s);+ const inUse = assetIdsOnAnyTimeline(s);const owned = s.assets.filter((a) => a.origin === "chat" && a.chatId === threadId && !inUse.has(a.id));diff --git a/site/src/cut/lib/engineFeatures.ts b/site/src/cut/lib/engineFeatures.tsindex 07e81874..034e25ac 100644--- a/site/src/cut/lib/engineFeatures.ts+++ b/site/src/cut/lib/engineFeatures.ts@@ -4,6 +4,6 @@* hands an engine work an older app would silently drop. A build from before* the list existed answers with none.*/-export const ENGINE_FEATURES = ["export.range", "export.name", "export.prores4444", "color.v2", "media.proxy", "export.hdr"] as const;+export const ENGINE_FEATURES = ["export.range", "export.name", "export.prores4444", "color.v2", "media.proxy", "export.hdr", "doc.timelines"] as const;export type EngineFeature = (typeof ENGINE_FEATURES)[number];diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex e79da201..5bfc76a7 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -26,7 +26,7 @@ import { withAssetColors } from "./mediaRead";import { renderRemovalPieces } from "./removalVideo";import { drawBlock } from "./blockSource";import { createRasterCanvas, rasterCanvasToPng } from "./raster";-import { clipLen, clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";+import { clipLen, clipSpeed, getClipSpans, openedTimeline, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";import { captionStyle, cueOverlay, cueWordFrames, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";import { isMaskAnimated, isOverlayAnimated, matteLumaToAlpha, normalizeGrade, paintMaskLuma, paintStrokeInk, retimeOf, type SpeedNode } from "@donkeycut/effects-kit";import { renderElementFrames, renderElementPng } from "./textRender";@@ -40,6 +40,7 @@ import type {Overlay,Selection,SubtitlesBlock,+ TimelineId,VideoClip,} from "./types";@@ -1946,7 +1947,7 @@ export async function renderShareLadder(doc: ExportDoc,shareSubtitles: boolean,backend: CutBackend = getBackend()-): Promise<void> {+): Promise<boolean> {// The master renders at "Original" — the ladder caps its top rung at this// frame, so anything given up here is given up for every viewer. The encode// preset is loosened because this master is an intermediate: every rung is@@ -1964,10 +1965,11 @@ export async function renderShareLadder(const burnedSubtitles = shareSubtitles && doc.subtitles?.showOnVideo === true;try {const payload = await buildExportPayload(projectId, source, settings, "hls");- await postExport(projectId, payload, "master.m3u8", backend, { burnedSubtitles });+ return (await postExport(projectId, payload, "master.m3u8", backend, { burnedSubtitles })).ok;} catch {// No clips yet, or a slot was busy. The share keeps playing whatever it// already had until a later attempt lands.+ return false;}}@@ -2111,21 +2113,18 @@ function cardSettings(aspect: Aspect): ExportSettings {** Best-effort throughout — a project with no footage, an unconfigured* backend, or a busy render slot simply keeps the card it already had. */-async function renderShareCard(projectId: string, doc: ExportDoc, backend: CutBackend): Promise<void> {+async function renderShareCard(projectId: string, doc: ExportDoc, backend: CutBackend, force = false): Promise<void> {if (backend.kind !== "cloud") return;- try {- const res = await backend.fetch(`/api/cut/projects/${projectId}/share`);- const body = (await res.json().catch(() => ({}))) as { share?: unknown | null };- if (!res.ok || !body.share) return;- } catch {- return;- }+ const share = await shareSettings(projectId, backend);+ if (!share) return;+ const { cut, key } = sharedCut(doc, share.features?.timeline);+ if (!force && key !== null && lastShareRender.get(`${projectId}:card`) === key) return;let res: Response;try {const payload = await buildExportPayload(projectId,- docFirstSeconds(doc, CARD_SECONDS),- cardSettings(doc.aspect),+ docFirstSeconds(cut, CARD_SECONDS),+ cardSettings(cut.aspect),"card");res = await postExport(projectId, payload, "card.mp4", backend);@@ -2134,17 +2133,49 @@ async function renderShareCard(projectId: string, doc: ExportDoc, backend: CutBa}const body = (await res.json().catch(() => ({}))) as { id?: string };if (!res.ok || !body.id) return;- await pollExport(body.id, () => {}, undefined, backend).catch(() => {});+ await pollExport(body.id, () => {}, undefined, backend)+ .then(() => key !== null && lastShareRender.set(`${projectId}:card`, key))+ .catch(() => {});+}++type ShareRenderSettings = { features?: { subtitles?: boolean; timeline?: TimelineId } };++/** The project's share settings, or null when it is not shared. */+async function shareSettings(projectId: string, backend: CutBackend): Promise<ShareRenderSettings | null> {+ const res = await backend.fetch(`/api/cut/projects/${projectId}/share`).catch(() => null);+ if (!res?.ok) return null;+ const body = (await res.json().catch(() => null)) as { share?: ShareRenderSettings | null } | null;+ return body?.share ?? null;+}++/** The cut a share link plays: the timeline its settings name, Main by+ * default, whichever one the editor has open. A parked one carries a key of+ * what it draws, so editing the open timeline does not re-render a link that+ * plays another; the open one renders on every change, as it always has. */+function sharedCut(doc: ExportDoc, timeline: TimelineId | undefined): { cut: ExportDoc; key: string | null } {+ const { timeline: open = "main", timelines, ...cut } = doc;+ const want = timeline ?? "main";+ if (want === open) return { cut, key: null };+ const parked = { ...cut, ...openedTimeline(timelines?.[want] ?? {}, doc.assets) };+ return { cut: parked, key: shareRenderKey(parked) };}+/** What each share render of a parked timeline last drew, this session. */+const lastShareRender = new Map<string, string>();+const shareRenderKey = (doc: ExportDoc) =>+ JSON.stringify([+ doc.clips, doc.audioClips, doc.overlays, doc.subtitles, doc.aspect, doc.background, doc.colorSpace,+ doc.assets.map((a) => [a.fileName, a.colorProfile, a.color, a.proxy?.fileName]),+ ]);+/** Rebuild the open project's share card from the cut as it stands. Fire and* forget: the card is an accessory to the link, and a failed render leaves the* previous one (or the generated placeholder) in place. */export function refreshShareCard(projectId: string): void {const s = useEditor.getState();- if (!s.loaded || s.projectId !== projectId || projectDuration(s) <= 0) return;+ if (!s.loaded || s.projectId !== projectId) return;const snapshot = captureRenderSnapshot(projectOperation(projectId), renderDoc(s));- void renderShareCard(projectId, snapshot.doc, snapshot.operation.backend).catch(() => {});+ void renderShareCard(projectId, snapshot.doc, snapshot.operation.backend, true).catch(() => {});}/**@@ -2162,20 +2193,24 @@ export function refreshShareCard(projectId: string): void {*/export async function refreshShareLadder(projectId: string): Promise<void> {const s = useEditor.getState();- if (!s.loaded || s.projectId !== projectId || projectDuration(s) <= 0) return;+ if (!s.loaded || s.projectId !== projectId) return;const snapshot = captureRenderSnapshot(projectOperation(projectId), renderDoc(s));- await refreshSnapshotLadder(snapshot);+ await refreshSnapshotLadder(snapshot, true);}-async function refreshSnapshotLadder({ operation, doc }: RenderSnapshot): Promise<void> {+async function refreshSnapshotLadder({ operation, doc }: RenderSnapshot, force = false): Promise<void> {const { projectId, backend } = operation;if (backend.kind !== "cloud") return;- const res = await backend.fetch(`/api/cut/projects/${projectId}/share`).catch(() => null);- if (!res?.ok) return;- const body = (await res.json().catch(() => null)) as {- share?: { features?: { subtitles?: boolean } } | null;- } | null;- if (body?.share) await renderShareLadder(projectId, doc, body.share.features?.subtitles === true, backend);+ const share = await shareSettings(projectId, backend);+ if (!share) return;+ const { cut, key: drawn } = sharedCut(doc, share.features?.timeline);+ const subtitles = share.features?.subtitles === true;+ const key = drawn === null ? null : `${subtitles}:${drawn}`;+ if (!force && key !== null && lastShareRender.get(`${projectId}:ladder`) === key) return;+ // Like the open timeline's ladder, a job the worker accepted counts as drawn;+ // the next change to that cut renders it again.+ if ((await renderShareLadder(projectId, cut, subtitles, backend)) && key !== null)+ lastShareRender.set(`${projectId}:ladder`, key);}/** All derived representations consume the same captured document and transport. */diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.tsindex c16a5d0b..9141792e 100644--- a/site/src/cut/lib/genScene.ts+++ b/site/src/cut/lib/genScene.ts@@ -239,6 +239,13 @@ export function threadHasLiveRun(chatId: string): boolean {return false;}+/** Whether a project's scene run is still working or waiting at the gate:+ * it places onto the timeline that is open, so that timeline stays open. */+export function projectHasLiveRun(projectId: string): boolean {+ const orch = orchestrators.get(projectId);+ return !!orch && !orch.isAborted && !isTerminal(statusFor(orch.project));+}+/** Build a persistable RefAsset list from project asset ids the user pointed at.* Tagged "style" so they anchor both the reference images and every shot. */function toReferences(ids: string[] | undefined): RefAsset[] {diff --git a/site/src/cut/lib/removal/bakeJobs.ts b/site/src/cut/lib/removal/bakeJobs.tsindex 450e69ef..098e9be7 100644--- a/site/src/cut/lib/removal/bakeJobs.ts+++ b/site/src/cut/lib/removal/bakeJobs.ts@@ -435,8 +435,10 @@ function sweepMattes(): void {if (t.projectId !== s.projectId) continue;if (Date.now() - (t.at ?? 0) > TICKET_TTL_MS) dropTicket(t.clipId);}+ // A clip on a closed timeline still owns its matte.const pointed = new Set<string>();- for (const c of s.clips) if (c.removal?.matte) pointed.add(c.removal.matte.assetId);+ for (const body of [s, ...Object.values(s.timelines)])+ for (const c of body.clips) if (c.removal?.matte) pointed.add(c.removal.matte.assetId);for (const a of s.assets) if (a.origin === "matte" && !pointed.has(a.id)) s.removeAsset(a.id);}diff --git a/site/src/cut/lib/renderSnapshot.ts b/site/src/cut/lib/renderSnapshot.tsindex 6116c581..654a70e0 100644--- a/site/src/cut/lib/renderSnapshot.ts+++ b/site/src/cut/lib/renderSnapshot.ts@@ -1,5 +1,5 @@import type { OutputSpace } from "@donkeycut/effects-kit";-import type { Aspect, MediaAsset, VideoClip, AudioClip, Overlay, SubtitlesBlock } from "@/cut/lib/types";+import type { Aspect, MediaAsset, VideoClip, AudioClip, Overlay, SubtitlesBlock, TimelineBody, TimelineId } from "@/cut/lib/types";import type { ProjectOperation } from "@/cut/lib/projectOperation";export type ExportDoc = {@@ -16,6 +16,10 @@ export type ExportDoc = {background?: string;/** The delivery's color space; absent = SDR. */colorSpace?: OutputSpace;+ /** Which timeline the cut above is (absent = main), and the parked ones: a+ * share render reads them when the link plays another timeline. */+ timeline?: TimelineId;+ timelines?: Partial<Record<TimelineId, TimelineBody>>;};export type RenderSnapshot = {@@ -26,7 +30,11 @@ export type RenderSnapshot = {/** Called when work is submitted, outside playback and store subscriptions. */export function captureRenderSnapshot(operation: ProjectOperation, doc: ExportDoc): RenderSnapshot {- return { operation, revision: crypto.randomUUID(), doc: structuredClone(doc) };+ // The parked timelines ride by reference: the store replaces them whole and+ // never edits one in place, and copying them would cost every render the+ // size of timelines nothing on screen draws.+ const { timelines, ...cut } = doc;+ return { operation, revision: crypto.randomUUID(), doc: { ...structuredClone(cut), ...(timelines ? { timelines } : {}) } };}export function renderDoc(doc: ExportDoc): ExportDoc {@@ -34,5 +42,6 @@ export function renderDoc(doc: ExportDoc): ExportDoc {aspect: doc.aspect, assets: doc.assets, clips: doc.clips, audioClips: doc.audioClips,overlays: doc.overlays, subtitles: doc.subtitles, background: doc.background,...(doc.colorSpace ? { colorSpace: doc.colorSpace } : {}),+ ...(doc.timelines && Object.keys(doc.timelines).length > 0 ? { timeline: doc.timeline, timelines: doc.timelines } : {}),};}diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.tsindex db2fd76d..93ded8dc 100644--- a/site/src/cut/lib/store.test.ts+++ b/site/src/cut/lib/store.test.ts@@ -8,7 +8,7 @@ import { expandTimelineGroups } from "./timelineGroups";import { timelineItem } from "./timelineItems";import { normalizeDocState } from "./store";import { playheadAt, setPlayhead, setSkim } from "./playhead";-import { emptySubtitles, uploadedFontId } from "./types";+import { emptySubtitles, sanitizeTimelines, uploadedFontId } from "./types";import type { Selection, AudioClip, MediaAsset, SubtitleCue, TextOverlay, VideoClip } from "./types";/**@@ -208,6 +208,88 @@ describe("the document projection", () => {});});+describe("timelines", () => {+ // A fresh open: empty timelines and no undo history on any of them.+ beforeEach(() => s().openProjectDoc("timelines", { name: "Timelines" }, []));++ test("switching parks the open timeline and opens the other, both ways", () => {+ const a = asset(4);+ const main = vclip({ assetId: a.id, out: 3 });+ useEditor.setState({ assets: [a], clips: [main], overlays: [title({ kind: "text" })] });+ s().switchTimeline("second");+ expect(s().timeline).toBe("second");+ expect(s().clips).toEqual([]);+ expect(s().overlays).toEqual([]);+ expect(s().timelines.main?.clips.map((c) => c.id)).toEqual([main.id]);+ s().addClipFromAsset(a.id, 0);+ s().switchTimeline("main");+ expect(s().clips.map((c) => c.id)).toEqual([main.id]);+ expect(s().overlays).toHaveLength(1);+ expect(s().timelines.second?.clips).toHaveLength(1);+ expect(s().timelines.main).toBeUndefined();+ });++ test("each timeline keeps its own undo history", () => {+ const a = asset(4);+ useEditor.setState({ assets: [a], colorSpace: "sdr" });+ s().addClipFromAsset(a.id, 0);+ s().switchTimeline("second");+ // Main's add is not Second's to undo.+ expect(s().undo()).toBe(false);+ s().addClipFromAsset(a.id, 0);+ s().addClipFromAsset(a.id, 0);+ s().setColorSpace("hlg");+ s().switchTimeline("main");+ expect(s().clips).toHaveLength(1);+ expect(s().undo()).toBe(true);+ expect(s().clips).toHaveLength(0);+ // A project-wide setting changed on Second stays put through Main's undo.+ expect(s().colorSpace).toBe("hlg");+ expect(s().redo()).toBe(true);+ expect(s().clips).toHaveLength(1);+ s().switchTimeline("second");+ expect(s().clips).toHaveLength(2);+ expect(s().undo()).toBe(true);+ expect(s().colorSpace).toBe("sdr");+ expect(s().undo()).toBe(true);+ expect(s().clips).toHaveLength(1);+ });++ test("the document carries which timeline is open and the parked ones", () => {+ useEditor.setState({ clips: [vclip({})] });+ const last = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);+ expect(last.timeline).toBe("main");+ s().switchTimeline("third");+ expect(docFieldsEdited(s(), last, s().transitions)).toBe(true);+ const doc = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);+ expect(doc.timeline).toBe("third");+ expect(doc.timelines?.main?.clips).toHaveLength(1);+ });++ test("deleting an asset takes its clips off the parked timelines too", () => {+ const a = asset(4);+ useEditor.setState({ assets: [a], clips: [vclip({ assetId: a.id })] });+ s().switchTimeline("second");+ expect(assetIdsInUse(s()).has(a.id)).toBe(false);+ s().removeAsset(a.id);+ expect(s().timelines.main?.clips).toEqual([]);+ });++ test("a parked timeline missing a list reads it as empty", () => {+ const parked = sanitizeTimelines({ second: { clips: [] }, bogus: { clips: [] } });+ expect(parked).toEqual({+ second: { clips: [], audioClips: [], transitions: [], overlays: [], subtitles: emptySubtitles() },+ });+ });++ test("a shared view cannot switch", () => {+ useEditor.setState({ readOnly: true });+ s().switchTimeline("second");+ expect(s().timeline).toBe("main");+ useEditor.setState({ readOnly: false });+ });+});+describe("micro gaps", () => {beforeEach(() => {useEditor.setState({ clips: [], audioClips: [], overlays: [], transitions: [], loaded: true });diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 5d2d3028..450051ba 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -52,6 +52,8 @@ import type {TemplateLayer,TemplateMedia,TemplateSaveInput,+ TimelineBody,+ TimelineId,TimelineTransition,TransitionStyle,VideoClip,@@ -87,7 +89,7 @@ import { clampPlayhead, playheadAt, previewAt, setPlayhead, setSkim } from "./plimport { engineTranscribeSamples, withEngineStt } from "./localStt";import { laneCues, subtitleLaneCount, trackLocale } from "./subtitles";import { 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 { 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, isTimelineId, sanitizeTimelines, 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";@@ -435,6 +437,14 @@ export interface EditorState {transitions: TimelineTransition[];audioClips: AudioClip[];overlays: Overlay[];+ /** The open timeline: clips, transitions, audio, elements and subtitles+ * above are its content. */+ timeline: TimelineId;+ /** The closed timelines' content, parked as the document stores it. */+ timelines: Partial<Record<TimelineId, TimelineBody>>;+ /** Park the open timeline and open another. Each timeline keeps its own+ * undo history for the session. */+ switchTimeline: (id: TimelineId) => void;/** Output frame ratio ("W:H", short side 1080), persisted per project. */aspect: Aspect;/** The aspect was chosen deliberately (picker, set_aspect, or saved in the@@ -987,6 +997,44 @@ let docSeq = 0;* beginHistoryBatch). One checkpoint is captured when it goes 0→1. */let batchDepth = 0;+/** The project-wide fields a history snapshot also carries, as they stood+ * when a timeline was closed. */+interface SharedFields {+ guideLines: GuideLines;+ colorSpace: OutputSpace;+ beats: Map<string, AssetBeats | undefined>;+ profiles: Map<string, SourceProfile | undefined>;+}+/** Each closed timeline's undo and redo stacks: opening a timeline again+ * brings its history back. Session only, cleared when a project opens. */+const parkedHistory = new Map<TimelineId, { history: DocSnapshot[]; future: DocSnapshot[]; shared: SharedFields }>();++const sharedFields = (s: Pick<EditorState, "guideLines" | "colorSpace" | "assets">): SharedFields => ({+ guideLines: s.guideLines,+ colorSpace: s.colorSpace,+ beats: new Map(s.assets.map((a) => [a.id, a.beats])),+ profiles: new Map(s.assets.map((a) => [a.id, a.colorProfile])),+});++/** A project-wide setting changed on another timeline while this one was+ * closed is not this timeline's to undo: its snapshots take that setting as+ * it stands now. Settings untouched meanwhile keep their history. */+function rebaseShared(snaps: DocSnapshot[], then: SharedFields, now: SharedFields) {+ const moved = <T,>(a: Map<string, T>, b: Map<string, T>) =>+ new Set([...b].filter(([id, v]) => a.has(id) && a.get(id) !== v).map(([id]) => id));+ const beats = moved(then.beats, now.beats);+ const profiles = moved(then.profiles, now.profiles);+ for (const snap of snaps) {+ if (now.guideLines !== then.guideLines) snap.guideLines = { v: [...now.guideLines.v], h: [...now.guideLines.h] };+ if (now.colorSpace !== then.colorSpace) snap.colorSpace = now.colorSpace;+ if (beats.size) snap.beats = snap.beats.map((b) => (beats.has(b.id) ? { id: b.id, grid: now.beats.get(b.id) } : b));+ if (profiles.size)+ snap.sourceColor = snap.sourceColor.map((c) =>+ profiles.has(c.id) ? { id: c.id, profile: now.profiles.get(c.id) } : c+ );+ }+}+/** Ids of clips a background generation run placed. Those clips are the* orchestrator's to manage — it swaps them idempotently and holds each shot's* timeline id — so the user's undo/redo must neither remove nor resurrect them.@@ -1369,6 +1417,8 @@ export const DOC_KEYS = ["transitions","audioClips","overlays",+ "timeline",+ "timelines","templates","mediaFolders","aspect",@@ -1731,6 +1781,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {history.length = 0;future.length = 0;pending = null;+ parkedHistory.clear();// A fresh project owns no live run — any prior run's render-owned ids are// stale, and the loaded clips are ordinary, fully-undoable content.genClipIds.clear();@@ -1757,6 +1808,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {transitions: [],audioClips: [],overlays: [],+ timeline: "main",+ timelines: {},templates: [],mediaFolders: [],aspect: lastChosenAspect() ?? "9:16",@@ -1810,6 +1863,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {transitions: [],audioClips: [],overlays: [],+ timeline: "main",+ timelines: {},templates: [],mediaFolders: [],aspect: lastChosenAspect() ?? "9:16",@@ -2137,6 +2192,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {transitions: state.transitions,audioClips: state.audioClips,overlays: state.overlays,+ timeline: isTimelineId(doc.timeline) ? doc.timeline : "main",+ timelines: sanitizeTimelines(doc.timelines) ?? {},templates: doc.templates ?? [],mediaFolders: doc.mediaFolders ?? [],aspect: state.aspect ?? lastChosenAspect() ?? "9:16",@@ -2414,6 +2471,52 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {}));},setBackground: (hex) => set({ background: projectBackground(hex) }),+ switchTimeline: (id) => {+ const s = get();+ if (id === s.timeline || s.readOnly || !isTimelineId(id)) return;+ const opened = normalizeDocState(s.timelines[id] ?? {}, s.assets);+ const parked: TimelineBody = {+ clips: s.clips,+ audioClips: s.audioClips,+ transitions: s.transitions,+ overlays: docOverlays(s.overlays),+ subtitles: s.subtitles,+ };+ const rest = { ...s.timelines };+ delete rest[id];+ // The history goes with the timeline it was made on.+ flush();+ const now = sharedFields(s);+ parkedHistory.set(s.timeline, { history: [...history], future: [...future], shared: now });+ const back = parkedHistory.get(id);+ parkedHistory.delete(id);+ history.length = 0;+ future.length = 0;+ if (back) {+ rebaseShared([...back.history, ...back.future], back.shared, now);+ history.push(...back.history);+ future.push(...back.future);+ }+ laneEpoch++; // caption work in flight belongs to the timeline being left+ set({+ timeline: id,+ timelines: { ...rest, [s.timeline]: parked },+ clips: opened.clips,+ transitions: opened.transitions,+ audioClips: opened.audioClips,+ overlays: opened.overlays,+ subtitles: opened.subtitles,+ subtitleLane: 0,+ subtitleStatus: opened.subtitles.cues.length > 0 ? "ready" : "idle",+ subtitleError: null,+ selection: null,+ multiSelection: [],+ selectedKey: null,+ });+ // A batch still open (a chat turn's run of edits) keeps going on this+ // timeline, as one undo step of its own.+ if (batchDepth > 0) pending = { snap: snapshot(), seq: docSeq };+ },setColorSpace: (space) => {if (get().colorSpace === space || get().readOnly) return;push();@@ -2594,6 +2697,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {for (const snap of history) scrub(snap);for (const snap of future) scrub(snap);if (pending) scrub(pending.snap);+ for (const parked of parkedHistory.values()) [...parked.history, ...parked.future].forEach(scrub);const dropFile = () => {const s = get();if (!s.projectId) return;@@ -2619,7 +2723,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {!st.clips.some((c) => c.assetId === id) &&!st.audioClips.some((c) => c.assetId === id)) {- set((s) => ({ assets: s.assets.filter((a) => a.id !== id) }));+ set((s) => ({ assets: s.assets.filter((a) => a.id !== id), timelines: timelinesWithout(s.timelines, id) }));dropFile();return;}@@ -2637,6 +2741,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {assets: s.assets.filter((a) => a.id !== id),clips: s.clips.filter((c) => c.assetId !== id),audioClips: s.audioClips.filter((c) => c.assetId !== id),+ timelines: timelinesWithout(s.timelines, id),multiSelection,selection: keep(s.selection) ? s.selection : multiSelection[multiSelection.length - 1] ?? null,};@@ -2708,7 +2813,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {}));// A block exists for the footage that replaces it; once nothing plays// it, it goes with it.- if (was?.block !== undefined && !get().clips.some((c) => c.assetId === was.id))+ if (was?.block !== undefined && assetClipUses(get(), new Set([was.id])) === 0)get().removeAsset(was.id);get().endHistoryBatch();},@@ -5034,6 +5139,29 @@ export const docOverlays = (() => {};})();+/** The parked timelines as the document stores them: like `docClips`, a clip+ * whose asset is still uploading from this tab stays out. Memoized for the+ * same reason, so autosave compares the projection by reference. */+export const docTimelines = (() => {+ type Parked = Partial<Record<TimelineId, TimelineBody>>;+ let memo: { timelines: Parked; key: string; out: Parked } | null = null;+ return (timelines: Parked, assets: MediaAsset[]): Parked => {+ const key = pendingKey(assets);+ if (memo && memo.timelines === timelines && memo.key === key) return memo.out;+ const held = (c: { assetId: string }) => !assets.some((a) => a.id === c.assetId && tabOnlyUpload(a));+ const out: Parked = key+ ? Object.fromEntries(+ Object.entries(timelines).map(([id, body]) => [+ id,+ { ...body, clips: body.clips.filter(held), audioClips: body.audioClips.filter(held) },+ ])+ )+ : timelines;+ memo = { timelines, key, out };+ return out;+ };+})();+/** The asset fields persisted in project.json — the projection autosave* writes, and the one its change detector compares (runtime fields like* thumbs/peaks must not mark the doc dirty). Assets whose bytes live only in@@ -5075,6 +5203,8 @@ export function serializeDoc(s: {transitions: TimelineTransition[];audioClips: AudioClip[];overlays: Overlay[];+ timeline: TimelineId;+ timelines: Partial<Record<TimelineId, TimelineBody>>;templates: LibraryTemplate[];mediaFolders: MediaFolder[];aspect: Aspect;@@ -5098,6 +5228,10 @@ export function serializeDoc(s: {// Text elements drop the loader-stamped `kind`, so title-only projects// serialize byte-identical to the pre-union shape.overlays: docOverlays(s.overlays),+ // Always sent: the save keeps a field the body leaves out, so going back+ // to Main has to say so.+ timeline: s.timeline,+ timelines: docTimelines(s.timelines, s.assets),templates: s.templates,mediaFolders: s.mediaFolders,aspect: s.aspect,@@ -5135,6 +5269,8 @@ const DOC_FIELD_EDITED: {clips: (s, last) => docClips(s.clips, s.assets) !== (last.clips as unknown),audioClips: (s, last) => docAudioClips(s.audioClips, s.assets) !== (last.audioClips as unknown),overlays: (s, last) => docOverlays(s.overlays) !== (last.overlays as unknown),+ timeline: (s, last) => s.timeline !== last.timeline,+ timelines: (s, last) => docTimelines(s.timelines, s.assets) !== (last.timelines as unknown),transitions: (s, _last, lastBars) => s.transitions !== lastBars,templates: (s, last) => s.templates !== (last.templates as unknown),mediaFolders: (s, last) => s.mediaFolders !== (last.mediaFolders as unknown),@@ -5825,6 +5961,18 @@ export function normalizeDocState(};}+/** A parked timeline's content in the shape the store holds an open one:+ * what a render of a timeline that is not on screen draws from. */+export function openedTimeline(body: Partial<TimelineBody>, assets: MediaAsset[]) {+ const st = normalizeDocState(body, assets);+ return {+ clips: deriveTransitionFields(closeMicroGaps(groundTracks(st.clips)), st.transitions),+ audioClips: st.audioClips,+ overlays: st.overlays,+ subtitles: st.subtitles,+ };+}+/** Assign packed sequential starts (each clip abutting the previous): the* layout older docs implied by array order. */function packStarts(clips: LegacyClip[]): VideoClip[] {@@ -6026,6 +6174,50 @@ let durValue = 0;* decide what an asset is still needed for has to see all of them — dropping* what a sticker draws from is as visible as dropping a clip's.*/+/** The parked timelines with an asset's clips taken out; the same object when+ * none of them used it. */+function timelinesWithout(+ timelines: Partial<Record<TimelineId, TimelineBody>>,+ assetId: string+): Partial<Record<TimelineId, TimelineBody>> {+ const uses = (c: { assetId: string }) => c.assetId === assetId;+ if (!Object.values(timelines).some((b) => b.clips.some(uses) || b.audioClips.some(uses))) return timelines;+ return Object.fromEntries(+ Object.entries(timelines).map(([id, b]) => [+ id,+ { ...b, clips: b.clips.filter((c) => !uses(c)), audioClips: b.audioClips.filter((c) => !uses(c)) },+ ])+ );+}++/** How many clips on any timeline, open or parked, play one of these assets:+ * what deleting them takes with it. */+export function assetClipUses(+ s: { clips: VideoClip[]; audioClips: AudioClip[]; timelines: Partial<Record<TimelineId, TimelineBody>> },+ assetIds: ReadonlySet<string>+): number {+ let n = 0;+ for (const body of [s, ...Object.values(s.timelines)]) {+ for (const c of body.clips) if (assetIds.has(c.assetId)) n++;+ for (const c of body.audioClips) if (assetIds.has(c.assetId)) n++;+ }+ return n;+}++/** Every asset any timeline points at, open or parked. */+export function assetIdsOnAnyTimeline(s: {+ clips: VideoClip[];+ audioClips: AudioClip[];+ overlays: Overlay[];+ transitions: TimelineTransition[];+ subtitles: SubtitlesBlock;+ timelines: Partial<Record<TimelineId, TimelineBody>>;+}): Set<string> {+ const used = assetIdsInUse(s);+ for (const body of Object.values(s.timelines)) for (const id of assetIdsInUse(body)) used.add(id);+ return used;+}+export function assetIdsInUse(s: {clips: VideoClip[];audioClips: AudioClip[];diff --git a/site/src/cut/lib/timelineSwitch.ts b/site/src/cut/lib/timelineSwitch.tsnew file mode 100644index 00000000..3cf4db33--- /dev/null+++ b/site/src/cut/lib/timelineSwitch.ts@@ -0,0 +1,61 @@+import { useEffect, useState } from "react";+import { engineFeatures } from "./api";+import { getBackend } from "./backend";+import { projectHasLiveRun, useGenScene } from "./genScene";+import { useMatteBakes, type MatteBakeJob } from "./removal/bakeJobs";+import { useEditor } from "./store";+import { TIMELINE_LABELS, type TimelineId } from "./types";++/** Whether the open project's storage keeps more than one timeline. An engine+ * from before timelines rebuilds the saved doc without the parked ones, so a+ * Mac project on an older app stays on Main. A headless turn runs inside the+ * same build that stores the doc. */+export async function timelinesSupported(): Promise<boolean> {+ if (typeof window === "undefined" || getBackend().kind !== "local") return true;+ return (await engineFeatures()).has("doc.timelines");+}++const baking = (jobs: Record<string, MatteBakeJob>) => Object.values(jobs).some((j) => j.status === "running");++/** Why the open timeline cannot be left right now, or null when it can. Work+ * still landing on it — a scene run placing shots, captions being written, a+ * cutout matte baking — belongs to the timeline it started on. */+export function timelineSwitchBlocker(): string | null {+ const s = useEditor.getState();+ const open = TIMELINE_LABELS[s.timeline];+ if (s.readOnly) return "A shared project is read-only.";+ if (s.projectId && projectHasLiveRun(s.projectId))+ return `A scene run is placing shots on ${open}; switch once it finishes.`;+ if (s.subtitleStatus === "running") return `Subtitles are being written on ${open}; switch once they land.`;+ if (baking(useMatteBakes.getState().jobs)) return `A cutout is baking on ${open}; switch once it lands.`;+ return null;+}++/** Open another of the project's timelines, or say why it cannot. */+export async function switchTimeline(id: TimelineId): Promise<string | null> {+ if (!(await timelinesSupported())) return "Update the Donkey app to use more than one timeline.";+ const blocked = timelineSwitchBlocker();+ if (blocked) return blocked;+ useEditor.getState().switchTimeline(id);+ return null;+}++/** The picker's state: hidden where the storage cannot keep timelines, held+ * while work is still landing on the open one. */+export function useTimelinePicker(): { supported: boolean; blocked: boolean } {+ const projectId = useEditor((s) => s.projectId);+ const [supported, setSupported] = useState(false);+ useEffect(() => {+ let live = true;+ void timelinesSupported().then((ok) => live && setSupported(ok));+ return () => {+ live = false;+ };+ }, [projectId]);+ const captions = useEditor((s) => s.subtitleStatus === "running");+ const run = useGenScene(+ (g) => !!g.run && g.run.projectId === projectId && g.run.status !== "done" && g.run.status !== "failed"+ );+ const matte = useMatteBakes((m) => baking(m.jobs));+ return { supported, blocked: captions || run || matte };+}diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex c75a3c8d..11714f3c 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -1557,6 +1557,8 @@ export interface ShareFeatures {genai: boolean;subtitles: boolean;details: boolean;+ /** The timeline viewers watch; absent = main. */+ timeline?: TimelineId;}/** The editor's side-panel tabs ("publish" shows as Details). */@@ -1583,6 +1585,46 @@ export const SIDE_PANEL_TABS: SidePanelTab[] = ["publish",];+/** A project's timelines. One is open at a time; the open one's content is+ * the doc's top-level clips, audio, transitions, elements and subtitles, so+ * preview, export and every tool read whichever timeline is on screen. */+export const TIMELINE_IDS = ["main", "second", "third"] as const;+export type TimelineId = (typeof TIMELINE_IDS)[number];+export const TIMELINE_LABELS: Record<TimelineId, string> = { main: "Main", second: "Second", third: "Third" };+export const isTimelineId = (v: unknown): v is TimelineId => TIMELINE_IDS.includes(v as TimelineId);++/** Everything placed on one timeline: what a closed timeline keeps parked in+ * `ProjectDoc.timelines` while another is open. */+export interface TimelineBody {+ clips: VideoClip[];+ audioClips: AudioClip[];+ transitions: TimelineTransition[];+ overlays: Overlay[];+ subtitles: SubtitlesBlock;+}++/** The parked timelines a save sent, each with every list it carries: a+ * missing or malformed one reads as empty. */+export function sanitizeTimelines(v: unknown): Partial<Record<TimelineId, TimelineBody>> | undefined {+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;+ const list = <T,>(x: unknown): T[] => (Array.isArray(x) ? (x as T[]) : []);+ const out: Partial<Record<TimelineId, TimelineBody>> = {};+ for (const [id, raw] of Object.entries(v)) {+ if (!isTimelineId(id) || !raw || typeof raw !== "object") continue;+ const body = raw as Partial<Record<keyof TimelineBody, unknown>>;+ const subtitles = body.subtitles as SubtitlesBlock | undefined;+ out[id] = {+ clips: list(body.clips),+ audioClips: list(body.audioClips),+ transitions: list(body.transitions),+ overlays: list(body.overlays),+ subtitles:+ subtitles && typeof subtitles === "object" && Array.isArray(subtitles.cues) ? subtitles : emptySubtitles(),+ };+ }+ return out;+}+export interface ProjectDoc {version: 1;/** The project's stable API id. On the local engine the folder is named@@ -1606,6 +1648,11 @@ export interface ProjectDoc {* docs. Read on open and merged into `clips`; new saves never write it. */overlayClips?: VideoClip[];overlays: Overlay[];+ /** The timeline the top-level clips, audio, transitions, elements and+ * subtitles belong to; absent = main. */+ timeline?: TimelineId;+ /** The closed timelines' content, parked until one is opened. */+ timelines?: Partial<Record<TimelineId, TimelineBody>>;/** Output frame; absent in older projects (which are all 9:16). */aspect?: Aspect;/** Preview guides turned on: thirds, center, safe margins, platformdiff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 6c23b8cb..1f69314c 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -65,7 +65,7 @@ import {} from "@donkeycut/effects-kit";import type { AiToolDef } from "../../lib/aiToolDef";import { GOOGLE_FONT_IDS } from "../../lib/fontCatalog";-import { FONTS, TRANSITION_STYLE_IDS } from "../../lib/types";+import { FONTS, TIMELINE_IDS, TIMELINE_LABELS, TRANSITION_STYLE_IDS } from "../../lib/types";export const AI_TOOLS: AiToolDef[] = [...AI_PANEL_TOOLS,@@ -233,6 +233,7 @@ Cut is a local, project-based short-video editor. Each project has an output asp- Center: the video preview canvas (composited at the project's frame size) with draggable text overlays and subtitle captions.- Right: the Inspector — its content follows the selection (video clip, overlay video, soundtrack clip, title, or cue).- Bottom: the timeline (resizable by dragging its top border). Rows top-to-bottom: the video tracks in z-order (positive tracks, then track 0, then negative tracks behind it), soundtrack lanes (green), titles (purple), subtitle tracks (amber, when enabled). Every track is free-positioned in time.+- A project has ${TIMELINE_IDS.length} timelines (${TIMELINE_IDS.map((id) => TIMELINE_LABELS[id]).join(", ")}), picked from the menu at the left of the timeline toolbar. Each holds its own clips, soundtrack, transitions, elements and subtitles over the shared media and frame. editor_state project.timeline names the open one; the preview, the export and every edit work on it, and switch_timeline opens another.Everything autosaves to the project folder. Undo/redo is unlimited (⌘Z / ⇧⌘Z).Times are in seconds on the shared timeline. The playhead is currentTime; a skimmer previews under the mouse without moving the playhead.`,diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.tsindex fc7096f3..e6660d27 100644--- a/site/src/cut/server/cloud/projects.ts+++ b/site/src/cut/server/cloud/projects.ts@@ -2,7 +2,7 @@// docs and metadata in Postgres, media bytes in R2. Every query scopes by userId.import { sanitizeGuideLines, sanitizeGuides } from "@/cut/lib/guides";import { resolveParent, subtreeOf } from "@/cut/lib/folderTree";-import { normalizeAspect, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";+import { isTimelineId, normalizeAspect, sanitizeTimelines, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";import type { Prisma } from "@/generated/prisma/client";import { prisma } from "@/lib/prisma";import { deleteLadder } from "./ladderStore";@@ -221,6 +221,8 @@ export const projectsCloud = {? []: existing.overlayClips,overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,+ timeline: isTimelineId(body.timeline) ? body.timeline : existing.timeline,+ timelines: sanitizeTimelines(body.timelines) ?? existing.timelines,templates: Array.isArray(body.templates) ? body.templates : existing.templates,mediaFolders: Array.isArray(body.mediaFolders) ? body.mediaFolders : existing.mediaFolders,aspect: normalizeAspect(body.aspect) ?? existing.aspect,diff --git a/site/src/cut/server/cloud/share.ts b/site/src/cut/server/cloud/share.tsindex ec383b5b..b2fac9be 100644--- a/site/src/cut/server/cloud/share.ts+++ b/site/src/cut/server/cloud/share.ts@@ -2,7 +2,7 @@// (CutProjectShare); the row id is the link token viewers open. Viewer-side// reads live in sharedView.ts.import { randomBytes } from "node:crypto";-import type { ShareFeatures } from "@/cut/lib/types";+import { isTimelineId, type ShareFeatures } from "@/cut/lib/types";import { prisma } from "@/lib/prisma";import { getProject } from "./projects";import { caught, err } from "./util";@@ -23,7 +23,8 @@ function newShareToken(): string {export function normalizeFeatures(raw: unknown): ShareFeatures {const src = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};- return Object.fromEntries(FEATURE_KEYS.map((k) => [k, src[k] === true])) as unknown as ShareFeatures;+ const features = Object.fromEntries(FEATURE_KEYS.map((k) => [k, src[k] === true])) as unknown as ShareFeatures;+ return isTimelineId(src.timeline) && src.timeline !== "main" ? { ...features, timeline: src.timeline } : features;}/** Lowercased, deduped, email-shaped list — or null when the input is not adiff --git a/site/src/cut/server/cloud/sharedView.test.ts b/site/src/cut/server/cloud/sharedView.test.tsindex 95fd0406..69145b5d 100644--- a/site/src/cut/server/cloud/sharedView.test.ts+++ b/site/src/cut/server/cloud/sharedView.test.ts@@ -106,4 +106,22 @@ describe("filterDocForShare", () => {} as unknown as ProjectDoc;expect([...sharedFileNames(proxied, features())].sort()).toEqual(["placed.mp4", "placed.proxy.mp4"]);});++ test("the link plays the timeline its settings pick, Main by default", () => {+ const onSecond = {+ ...doc,+ timeline: "second",+ clips: [{ id: "c2", assetId: "imported", track: 0, start: 0, in: 0, out: 1, muted: false }],+ timelines: { main: { clips: doc.clips, audioClips: [], transitions: [], overlays: [], subtitles: { cues: [] } } },+ } as unknown as ProjectDoc;+ const main = filterDocForShare(onSecond, features());+ expect(main.clips.map((c) => c.id)).toEqual(["c1"]);+ expect(ids(main)).toEqual(["placed"]);+ expect(main.timelines).toBeUndefined();+ expect([...sharedFileNames(onSecond, features())]).toEqual(["placed.mp4"]);+ const second = filterDocForShare(onSecond, features({ timeline: "second" }));+ expect(second.clips.map((c) => c.id)).toEqual(["c2"]);+ expect(ids(second)).toEqual(["imported"]);+ expect(filterDocForShare(onSecond, features({ timeline: "third" })).clips).toEqual([]);+ });});diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.tsindex 6f3f93cf..3c089970 100644--- a/site/src/cut/server/cloud/sharedView.ts+++ b/site/src/cut/server/cloud/sharedView.ts@@ -5,7 +5,7 @@ import { listChatThreads } from "./chats";// the content boundary: the filtered doc and the media allowlist are what// decide which bytes a viewer can reach; the client's tab hiding is// presentation only. Copying a share lives in copyQueue.ts.-import { uploadedFontId, type ProjectDoc, type StoredAsset } from "@/cut/lib/types";+import { isTimelineId, sanitizeTimelines, uploadedFontId, type ProjectDoc, type StoredAsset } from "@/cut/lib/types";import { auth } from "@/lib/auth";import { prisma } from "@/lib/prisma";import { readLadder } from "./ladderStore";@@ -110,7 +110,31 @@ function allowedAssets(doc: ProjectDoc, features: ShareFeatures): StoredAsset[]});}-export function filterDocForShare(doc: ProjectDoc, features: ShareFeatures): ProjectDoc {+/** The doc with the shared timeline as its cut: the one the share settings+ * name, Main by default. The parked timelines stay with the owner. */+function sharedTimelineDoc(doc: ProjectDoc, features: ShareFeatures): ProjectDoc {+ const want = features.timeline ?? "main";+ const open = isTimelineId(doc.timeline) ? doc.timeline : "main";+ const cut =+ want === open+ ? doc+ : (() => {+ const body = sanitizeTimelines(doc.timelines)?.[want];+ return {+ ...doc,+ clips: body?.clips ?? [],+ audioClips: body?.audioClips ?? [],+ transitions: body?.transitions ?? [],+ overlays: body?.overlays ?? [],+ subtitles: body?.subtitles,+ overlayClips: undefined,+ };+ })();+ return { ...cut, timeline: undefined, timelines: undefined };+}++export function filterDocForShare(source: ProjectDoc, features: ShareFeatures): ProjectDoc {+ const doc = sharedTimelineDoc(source, features);const filtered: ProjectDoc = {...doc,assets: allowedAssets(doc, features),@@ -134,7 +158,7 @@ export function filterDocForShare(doc: ProjectDoc, features: ShareFeatures): Pro* one, its preview proxy, which is what the viewer's preview decodes. */export function sharedFileNames(doc: ProjectDoc, features: ShareFeatures): Set<string> {return new Set(- allowedAssets(doc, features).flatMap((a) => (a.proxy ? [a.fileName, a.proxy.fileName] : [a.fileName]))+ allowedAssets(sharedTimelineDoc(doc, features), features).flatMap((a) => (a.proxy ? [a.fileName, a.proxy.fileName] : [a.fileName])));}diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex f8458722..46961f38 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -1,6 +1,6 @@import { sanitizeGuideLines, sanitizeGuides } from "@/cut/lib/guides";import { execFile } from "node:child_process";-import { normalizeAspect, type ProjectDoc } from "@/cut/lib/types";+import { isTimelineId, normalizeAspect, sanitizeTimelines, type ProjectDoc } from "@/cut/lib/types";import { detectSilence, extractAudio, makeFreezeFrame, probeDims, probeDuration } from "../frames";import {createProject,@@ -134,6 +134,8 @@ export const projectsApi = {? []: existing.overlayClips,overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,+ timeline: isTimelineId(body.timeline) ? body.timeline : existing.timeline,+ timelines: sanitizeTimelines(body.timelines) ?? existing.timelines,templates: Array.isArray(body.templates) ? body.templates : existing.templates,mediaFolders: Array.isArray(body.mediaFolders) ? body.mediaFolders : existing.mediaFolders,aspect: normalizeAspect(body.aspect) ?? existing.aspect,