Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(timeline): lever l'ambiguïté quand deux clips partagent le même média

Etienne Lescotcd587437affb
diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts
index a4177efaf..4118daed5 100644
--- a/electron/ai-edition/agent-tools.ts
+++ b/electron/ai-edition/agent-tools.ts
@@ -340,6 +340,11 @@ export const addTrimArgs = z.object({
startSec: secondsSchema,
endSec: secondsSchema,
assetId: z.string().min(1).optional(),
+ // A cut belongs to ONE clip. Without this, a project where two clips draw from the same
+ // asset (a duplicated clip) cannot say which of them the model meant, and the cut lands
+ // on both. Resolved from the source range when the model omits it and only one clip
+ // matches; ambiguity is reported back rather than guessed.
+ clipId: z.string().min(1).optional(),
reason: z.string().default(""),
});
@@ -601,6 +606,9 @@ export function documentSnapshotForModel(
trimRanges: document.timeline.trimRanges.map((s) => ({
id: s.id,
assetId: s.assetId,
+ // The clip the cut is on — the only thing separating two cuts over the same
+ // media. `null` is a pre-v7 cut that still applies to every clip of its asset.
+ clipId: s.clipId ?? null,
startSec: s.startSec,
endSec: s.endSec,
reason: s.reason,
@@ -872,9 +880,38 @@ export function executeAgentTool(
}
const startSec = Math.min(parsed.data.startSec, parsed.data.endSec);
const endSec = Math.max(parsed.data.startSec, parsed.data.endSec);
+
+ // Which clip the cut sits on. Named explicitly when the model says so; otherwise
+ // inferred from the source range — but only when the answer is unique. Two clips
+ // over the same asset covering that range is a real question the model has to
+ // answer (their ids are in the snapshot), not one to settle by picking the first.
+ const covering = document.timeline.clips.filter(
+ (c) =>
+ c.assetId === assetId &&
+ endSec > c.sourceStartSec &&
+ startSec < (c.sourceEndSec ?? Number.POSITIVE_INFINITY),
+ );
+ let clipId = parsed.data.clipId;
+ if (clipId) {
+ const target = document.timeline.clips.find((c) => c.id === clipId);
+ if (!target) return failure(`Unknown clip: ${clipId}`);
+ if (target.assetId !== assetId) {
+ return failure(`Clip ${clipId} does not use asset ${assetId}.`);
+ }
+ } else if (covering.length === 1) {
+ clipId = covering[0].id;
+ } else if (covering.length > 1) {
+ return failure(
+ `${covering.length} clips use asset ${assetId} over ${formatSec(startSec)} – ${formatSec(
+ endSec,
+ )} (${covering.map((c) => c.id).join(", ")}). Pass clipId to say which one to trim.`,
+ );
+ }
+
const trim = {
id: createId("trim"),
assetId,
+ ...(clipId ? { clipId } : {}),
startSec,
endSec,
reason: parsed.data.reason,
@@ -904,12 +941,27 @@ export function executeAgentTool(
}
const startSec = Math.min(parsed.data.startSec, parsed.data.endSec);
const endSec = Math.max(parsed.data.startSec, parsed.data.endSec);
+ // Moving a cut out of the clip it is anchored to would leave it storing a range
+ // nothing plays — silently inert. Re-point it at the clip the new range actually
+ // lands in, but only when that clip is unique: with several candidates the old
+ // anchor is the better guess than an arbitrary one.
+ const reanchor = (trim: AxcutDocument["timeline"]["trimRanges"][number]) => {
+ if (!trim.clipId) return undefined;
+ const covers = (c: { sourceStartSec: number; sourceEndSec?: number }) =>
+ endSec > c.sourceStartSec && startSec < (c.sourceEndSec ?? Number.POSITIVE_INFINITY);
+ const current = document.timeline.clips.find((c) => c.id === trim.clipId);
+ if (current && covers(current)) return trim.clipId;
+ const candidates = document.timeline.clips.filter(
+ (c) => c.assetId === trim.assetId && covers(c),
+ );
+ return candidates.length === 1 ? candidates[0].id : trim.clipId;
+ };
const next: AxcutDocument = {
...document,
timeline: {
...document.timeline,
trimRanges: document.timeline.trimRanges.map((r) =>
- r.id === trimRangeId ? { ...r, startSec, endSec } : r,
+ r.id === trimRangeId ? { ...r, clipId: reanchor(r), startSec, endSec } : r,
),
},
};
diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts
index b1fc8466a..bc10c415c 100644
--- a/electron/ai-edition/deep-agent/service.ts
+++ b/electron/ai-edition/deep-agent/service.ts
@@ -142,8 +142,9 @@ export const TOOL_DESCRIPTIONS: Record<string, string> = {
getCursorTrack:
"Read the recorded pointer track for an asset: where the cursor was over time, downsampled to a readable rate. Each point carries atSec (the asset's own source clock), virtualSec (the same instant on the edited timeline — the coordinate addZoom takes, null when no clip carries it), cx/cy as 0–1 fractions of the frame, and `shape`, an index into the pointer bitmaps the recording used (equal values are the same pointer; a change means the pointer changed, e.g. arrow to text caret). Points that are not plain moves carry `kind`; points a trim cuts out of playback carry `trimmed`. These are real samples, not a summary — reading what the pointer was doing is yours. Omit assetId for the primary asset. It answers `available:false` in two DIFFERENT ways you must not confuse: reason 'no-sidecar' means this asset was checked and genuinely has no telemetry, while reason 'unavailable' means it could not be read from here.",
addTrim:
- "Add a trim range: a cut of a span inside a clip (this source-time span will not be played or exported) that does NOT split the clip. Times are in seconds of the asset's source time. This is the preferred (and for 'remove silences' requests, the only) way to handle silences; it preserves the user's placed clips and only adds a cut. Call this once per silent range.",
- setTrim: "Move or resize an existing trim range by id. Times are source-time seconds.",
+ "Add a trim range: a cut of a span inside a clip (this source-time span will not be played or exported) that does NOT split the clip. Times are in seconds of the asset's source time. This is the preferred (and for 'remove silences' requests, the only) way to handle silences; it preserves the user's placed clips and only adds a cut. Call this once per silent range. A cut belongs to ONE clip: `clipId` is inferred when a single clip covers the range, but when several clips draw on the same asset over it the call FAILS and lists them — pass the `clipId` you mean (ids come from getCurrentDocument).",
+ setTrim:
+ "Move or resize an existing trim range by id. Times are source-time seconds. The cut follows to whichever clip the new range lands in, when that clip is unambiguous.",
setClipRange:
"Set a clip's in/out points (source-time seconds) to shorten its head or tail — distinct from a trim (which cuts a span inside the clip). All clips are re-laid back-to-back afterwards, so downstream clips shift automatically. Use this ONLY when the user explicitly asks to shorten or extend a user-placed clip. Do NOT use this for 'remove silences' or 'cut pauses' — for those, use addTrim.",
moveClip:
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.ts
index 2d2ecd705..bd3495e2b 100644
--- a/electron/ai-edition/document-service.test.ts
+++ b/electron/ai-edition/document-service.test.ts
@@ -24,9 +24,9 @@ describe("DocumentService", () => {
});
describe("createProject", () => {
- it("creates a v6 doc with the given title and writes it to disk", async () => {
+ it("creates a v7 doc with the given title and writes it to disk", async () => {
const doc = await service.createProject("Demo Project");
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect(doc.project.title).toBe("Demo Project");
expect(doc.project.id).toMatch(/^proj_/);
expect(doc.assets).toEqual([]);
@@ -34,7 +34,7 @@ describe("DocumentService", () => {
const filePath = path.join(tempDir, `${doc.project.id}.openscreen`);
const raw = await fs.readFile(filePath, "utf8");
expect(JSON.parse(raw)).toMatchObject({
- schemaVersion: 6,
+ schemaVersion: 7,
project: { title: "Demo Project" },
});
});
diff --git a/src/components/ai-edition/EditorEmptyState.test.tsx b/src/components/ai-edition/EditorEmptyState.test.tsx
index 9b33082b6..0ed9d5381 100644
--- a/src/components/ai-edition/EditorEmptyState.test.tsx
+++ b/src/components/ai-edition/EditorEmptyState.test.tsx
@@ -25,7 +25,7 @@ const sampleDoc = vi.hoisted(() => ({
// load site (DocumentService, browserShim) runs `migrateRawDocumentToCurrent`
// before returning, and the renderer's `parseDocument` is a pure v6
// validator. Test fixtures model the post-hoist contract.
- schemaVersion: 6,
+ schemaVersion: 7,
project: {
id: "proj_test",
title: "Test",
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 442573131..f5bba1b39 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -34,6 +34,7 @@ import {
type UnsavedChoice,
} from "./Modals";
import { Preview } from "./Preview";
+import type { TrimTarget } from "./RightPanes";
import v4 from "./v4/EditorShellV4.module.css";
import { type EditorMode, EditorTopBar } from "./v4/EditorTopBar";
import { type Facet, FloatingInspector } from "./v4/FloatingInspector";
@@ -574,8 +575,17 @@ export function NewEditorShell() {
// apps/web/src/App.tsx. The serialised save + inside-the-chain doc
// read is owned by `useSequentialTimelineOps` above.
const handleAddTrimRange = useCallback(
- (assetId: string, startSec: number, endSec: number, reason: string) => {
- void applyTimelineOp({ type: "add_trim_range", assetId, startSec, endSec, reason });
+ (target: TrimTarget, startSec: number, endSec: number, reason: string) => {
+ // `clipId` is what keeps the cut on the block the user typed in: with two clips
+ // over the same media, an asset-only trim showed up on both (see `trimAppliesToClip`).
+ void applyTimelineOp({
+ type: "add_trim_range",
+ assetId: target.assetId,
+ clipId: target.clipId,
+ startSec,
+ endSec,
+ reason,
+ });
},
[applyTimelineOp],
);
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 8470b723b..1e6d380b7 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -486,11 +486,20 @@ function normaliseHex(raw: string): string | null {
return withHash.toLowerCase();
}
+/** Which clip a transcript cut lands on. The clip id is what makes the cut land on ONE
+ * block: two clips over the same media share an asset and a source range, so an
+ * asset-only target had the trim show up on both of them (and on the wrong one in the
+ * ruler). See `trimAppliesToClip`. */
+export interface TrimTarget {
+ assetId: string;
+ clipId: string;
+}
+
// ─── Transcript ────────────────────────────────────────────────────
// Aggregated transcript view: one contentEditable region per clip on the
// timeline, in timeline order. Each word is rendered as a `<span
// data-word-id>` inside the editable div. Words inside any `trimRange`
-// for the clip's asset are styled red+strikethrough and show a bin icon
+// anchored to the clip are styled red+strikethrough and show a bin icon
// on hover (removing the skip restores them). User actions:
//
// - Click on a word → seek (timeline.playhead)
@@ -500,6 +509,14 @@ function normaliseHex(raw: string): string | null {
// text). The deleted word stays in the DOM as
// red text — nothing destructive.
//
+// `data-word-id` carries the CLIP-SCOPED `ClipWord.id`, never the bare `word.id`. A
+// transcript belongs to an asset, so two clips over the same media project the same
+// words twice, and silence tokens are numbered from 1 per clip — a bare word id names
+// a moment in the media, not a thing on screen. Everything that points at a rendered
+// word (React key, cue highlight, caret anchor, the DOM helpers at the bottom of this
+// file) goes through `ClipWord.id`. Those helpers treat it as an opaque string, so they
+// needed no change beyond the ids they are handed.
+//
// Mirrors axcut's apps/web/src/components/CurrentTranscriptView.tsx.
export function TranscriptPane({
clips,
@@ -520,7 +537,7 @@ export function TranscriptPane({
trimRanges: AxcutTrimRange[];
busy: boolean;
onSeek: (sec: number) => void;
- onAddTrimRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
+ onAddTrimRange: (target: TrimTarget, startSec: number, endSec: number, reason: string) => void;
onRemoveTrimRange: (trimId: string) => void;
onTranscribe: () => void;
canTranscribe: boolean;
@@ -542,7 +559,9 @@ export function TranscriptPane({
// the cue position is the playback head's location in the current clip's source time.
// `currentTimeSec` is the RAW/document timeline (same referential as the ruler, see
// NewEditorShell) — looked up against the raw `clips`, matching that referential.
- // `findCueWordId` only reads `assetId`/`sourceTimeSec` off the result.
+ // `clipId` is what `findCueWordId` keys on — do NOT drop it as unused: source time is
+ // per asset, so without it the resolver falls back to the first section of the asset
+ // and the cue tracks clip 1 forever on a timeline that plays one media twice.
const cue = useMemo(() => {
if (clips.length === 0) return null;
const position = locateVirtualPosition(clips, currentTimeSec);
@@ -646,11 +665,17 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
busy: boolean;
cueWordId: string | null;
onSeek: (sec: number) => void;
- onAddTrimRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
+ onAddTrimRange: (target: TrimTarget, startSec: number, endSec: number, reason: string) => void;
onRemoveTrimRange: (trimId: string) => void;
}) {
const ts = useScopedT("settings");
const { clip, asset, words } = section;
+ // Memoised: `TranscriptWord` renders once per word, so a fresh object literal here
+ // would break referential equality for the whole stream on every parent render.
+ const trimTarget = useMemo<TrimTarget>(
+ () => ({ assetId: clip.assetId, clipId: clip.id }),
+ [clip.assetId, clip.id],
+ );
const filename = asset?.label ?? clip.assetId;
const sourceRangeLabel =
clip.sourceEndSec !== undefined
@@ -714,17 +739,17 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
// Only skip words that are currently kept (don't double-skip).
const keptRange = rangeWords.filter((w) => w.kept);
if (keptRange.length === 0) return;
- pendingCaretWordIdRef.current = keptRange[0].word.id;
+ pendingCaretWordIdRef.current = keptRange[0].id;
const startSec = Math.min(...keptRange.map((w) => w.word.startSec));
const endSec = Math.max(...keptRange.map((w) => w.word.endSec));
onAddTrimRange(
- clip.assetId,
+ trimTarget,
startSec,
endSec,
`Skip ${formatMs(startSec * 1000)}-${formatMs(endSec * 1000)} from ${clip.assetId}.`,
);
},
- [busy, clip.assetId, onAddTrimRange],
+ [busy, clip.assetId, trimTarget, onAddTrimRange],
);
const removeTrimRun = useCallback(
@@ -752,7 +777,7 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
words,
);
if (!wordId) return false;
- const cw = words.find((w) => w.word.id === wordId);
+ const cw = words.find((w) => w.id === wordId);
if (!cw) return false;
skipWordRange([cw]);
return true;
@@ -768,8 +793,8 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
const anchorId = findWordId(selection.anchorNode);
const focusId = findWordId(selection.focusNode);
if (!anchorId || !focusId) return false;
- const fromIdx = words.findIndex((w) => w.word.id === anchorId);
- const toIdx = words.findIndex((w) => w.word.id === focusId);
+ const fromIdx = words.findIndex((w) => w.id === anchorId);
+ const toIdx = words.findIndex((w) => w.id === focusId);
if (fromIdx < 0 || toIdx < 0) return false;
const [lo, hi] = fromIdx <= toIdx ? [fromIdx, toIdx] : [toIdx, fromIdx];
skipWordRange(words.slice(lo, hi + 1));
@@ -837,11 +862,18 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
if (!targetEl) return;
const wordEl = targetEl.closest<HTMLElement>("[data-word-id]");
if (!wordEl?.dataset.wordId) return;
- const cw = words.find((w) => w.word.id === wordEl.dataset.wordId);
+ const cw = words.find((w) => w.id === wordEl.dataset.wordId);
if (!cw) return;
- onSeek(cw.word.startSec);
+ // `onSeek` takes RAW TIMELINE seconds (its other callers pass `timelineStartSec`;
+ // `handleSeek` forwards `isSource: false`), but a word's times are the ASSET's
+ // source seconds. Shift by this clip's offset — a raw clip is identity between
+ // source and raw time apart from where it sits on the ruler. Passing the source
+ // value straight through sent every click in a clip that doesn't start at ruler 0
+ // backwards into whichever clip covers that raw moment; it only looked right on a
+ // single clip at the head of the timeline, where the two coordinates coincide.
+ onSeek(clip.timelineStartSec + (cw.word.startSec - clip.sourceStartSec));
},
- [onSeek, words],
+ [onSeek, words, clip.timelineStartSec, clip.sourceStartSec],
);
return (
@@ -944,10 +976,10 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
>
{words.map((cw) => (
<TranscriptWord
- key={cw.word.id}
+ key={cw.id}
cw={cw}
- isCue={cw.word.id === cueWordId}
- assetId={clip.assetId}
+ isCue={cw.id === cueWordId}
+ target={trimTarget}
onRestore={removeTrimRun}
onAddTrimRange={onAddTrimRange}
/>
@@ -965,15 +997,15 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
function TranscriptWord({
cw,
isCue,
- assetId,
+ target,
onRestore,
onAddTrimRange,
}: {
cw: ClipWord;
isCue: boolean;
- assetId: string;
+ target: TrimTarget;
onRestore: (run: TrimRun) => void;
- onAddTrimRange: (assetId: string, startSec: number, endSec: number, reason: string) => void;
+ onAddTrimRange: (target: TrimTarget, startSec: number, endSec: number, reason: string) => void;
}) {
const ts = useScopedT("settings");
const [hover, setHover] = useState(false);
@@ -988,7 +1020,7 @@ function TranscriptWord({
<button
type="button"
contentEditable={false}
- data-word-id={cw.word.id}
+ data-word-id={cw.id}
data-silence="true"
title={ts("transcript.restoreSilence", { duration })}
aria-label={ts("transcript.restoreSilence", { duration })}
@@ -1024,14 +1056,14 @@ function TranscriptWord({
<button
type="button"
contentEditable={false}
- data-word-id={cw.word.id}
+ data-word-id={cw.id}
data-silence="true"
title={ts("transcript.trimSilence", { duration })}
aria-label={ts("transcript.trimSilence", { duration })}
onClick={(e) => {
e.stopPropagation();
onAddTrimRange(
- assetId,
+ target,
cw.word.startSec,
cw.word.endSec,
`Skip silence ${formatMs(cw.word.startSec * 1000)}-${formatMs(cw.word.endSec * 1000)}.`,
@@ -1057,7 +1089,7 @@ function TranscriptWord({
return (
<span
- data-word-id={cw.word.id}
+ data-word-id={cw.id}
data-start-sec={cw.word.startSec}
data-end-sec={cw.word.endSec}
data-skip-id={cw.trimId ?? undefined}
@@ -1124,6 +1156,11 @@ function TranscriptWord({
// Ponytail port of axcut's findCollapsedDeletionWordId. The non-collapsed
// path uses findWordId directly (a range selection's endpoints already
// identify the boundary words — no boundary heuristic needed).
+//
+// Every id here is a `ClipWord.id` (clip-scoped) read straight off `data-word-id`, and
+// every lookup is confined to ONE block's `editor` element — so these stay correct
+// whatever the ids look like. They must never parse an id: the `clipId:wordId` shape is
+// `clipWordId`'s business alone.
function findWordId(node: Node | null): string | null {
const element = node instanceof Element ? node : node?.parentElement;
@@ -1142,7 +1179,7 @@ function findCollapsedDeletionWordId(
// trimId is only set on the next React commit), so a DOM check would
// re-trim an already-trimmed word. The words array is the React state
// captured at the call site — always current.
- const skippedIds = new Set(words.filter((w) => !w.kept).map((w) => w.word.id));
+ const skippedIds = new Set(words.filter((w) => !w.kept).map((w) => w.id));
const direct = closestWordElement(node);
if (direct) {
@@ -1176,34 +1213,37 @@ function findCollapsedDeletionWordId(
if (!boundaryNode) return null;
const childNodes = Array.from(boundaryNode.childNodes);
- // when restoreCaretBeforeWord places the caret before word W
- // (via setStartBefore), `anchorNode` becomes the parent div and
- // `anchorOffset` is W's index. The naive "previous sibling" lookup
- // below would always return the word that was *just* trimmed, which
- // is a no-op (the previous word is already skipped). The user
- // expects Backspace at the start of W to delete W. So when the
- // previous adjacent word is already trimmed, fall forward to W.
- if (direction === "backward" && node instanceof Element && node === editor) {
- const idx = Math.max(0, Math.min(offset, wordNodes.length) - 1);
- const previousWordId = wordNodes[idx]?.dataset.wordId ?? null;
- if (previousWordId && skippedIds.has(previousWordId)) {
- return wordNodes[idx]?.dataset.wordId ?? null;
- }
- }
-
+ // The caret sits BETWEEN words — which is where `restoreCaretBeforeWord` parks it after
+ // every cut (`setStartBefore` collapses to (editor, index-of-word)), so this is the
+ // state the user is in while holding Backspace. Walk outward in the direction of travel
+ // and take the first word that is STILL KEPT.
+ //
+ // Skipping the already-trimmed ones is the whole point: a struck-through word has
+ // nothing left to remove, so resolving to it made `skipWordRange` drop it as not-kept
+ // and the keystroke did nothing at all. The user had to click somewhere else to carry
+ // on cutting — right after a cut, since the caret is parked before the word that was
+ // just removed. A previous guard here tried to special-case that by returning the
+ // already-trimmed word it had just rejected, which is the no-op it meant to avoid (and
+ // was byte-for-byte what the walk below already returned, so it never changed anything).
+ const isKept = (wordId: string | null): wordId is string => !!wordId && !skippedIds.has(wordId);
const candidates =
direction === "backward" ? childNodes.slice(0, offset).reverse() : childNodes.slice(offset);
for (const candidate of candidates) {
const wordId = findWordId(candidate) ?? findDescendantWordId(candidate);
- if (wordId) return wordId;
+ if (isKept(wordId)) return wordId;
}
+ // Fallback for a caret in some wrapper node whose children aren't the word spans: locate
+ // it by document order instead. Same rule — nearest kept word in the direction of travel.
const range = globalThis.document.createRange();
range.setStart(editor, 0);
range.setEnd(node, clampRangeOffset(node, offset));
- const wordsBefore = wordNodes.filter((wordNode) => range.comparePoint(wordNode, 0) <= 0);
- return direction === "backward"
- ? (wordsBefore.at(-1)?.dataset.wordId ?? null)
- : (wordNodes.find((wordNode) => !wordsBefore.includes(wordNode))?.dataset.wordId ?? null);
+ const before: HTMLElement[] = [];
+ const after: HTMLElement[] = [];
+ for (const wordNode of wordNodes) {
+ (range.comparePoint(wordNode, 0) <= 0 ? before : after).push(wordNode);
+ }
+ const pool = direction === "backward" ? [...before].reverse() : after;
+ return pool.find((wordNode) => isKept(wordNode.dataset.wordId ?? null))?.dataset.wordId ?? null;
}
function findDescendantWordId(node: Node): string | null {
diff --git a/src/components/ai-edition/TranscriptPane.keyboardCut.test.tsx b/src/components/ai-edition/TranscriptPane.keyboardCut.test.tsx
new file mode 100644
index 000000000..af75267ad
--- /dev/null
+++ b/src/components/ai-edition/TranscriptPane.keyboardCut.test.tsx
@@ -0,0 +1,233 @@
+// Backspace/Delete in the transcript pane, with the caret sitting BETWEEN words at editor
+// level. That is where `restoreCaretBeforeWord` parks it after every cut, so it is the
+// state the user is in when they hold Backspace to keep trimming — and the state where
+// the keystroke silently stopped doing anything as soon as an already-trimmed word lay in
+// its path. Driving it needs a real Range/Selection, so these are DOM tests.
+
+import "@testing-library/jest-dom";
+import { cleanup, fireEvent, render } from "@testing-library/react";
+import { useState } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@/contexts/I18nContext";
+import type {
+ AxcutAsset,
+ AxcutClip,
+ AxcutTranscript,
+ AxcutTrimRange,
+} from "@/lib/ai-edition/schema";
+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { TranscriptPane } from "./RightPanes";
+
+vi.mock("@/native/client", () => ({ nativeBridgeClient: { aiEdition: {} } }));
+vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
+
+const ASSET: AxcutAsset = {
+ id: "asset_1",
+ kind: "video",
+ label: "recording.mp4",
+ originalPath: "/rec.mp4",
+ durationSec: 4,
+ cameraTrack: null,
+};
+
+const CLIP: AxcutClip = {
+ id: "clip_1",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ timelineStartSec: 0,
+ timelineEndSec: 4,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+};
+
+// Contiguous on purpose: any gap ≥ SILENCE_THRESHOLD_SEC would insert a `[silence]`
+// pseudo-word between them and change the indices these tests set the caret by.
+const TRANSCRIPT: AxcutTranscript = {
+ assetId: "asset_1",
+ language: "fr",
+ segments: [],
+ words: [
+ { id: "w1", segmentId: "s", startSec: 0, endSec: 1, text: "un" },
+ { id: "w2", segmentId: "s", startSec: 1, endSec: 2, text: "deux" },
+ { id: "w3", segmentId: "s", startSec: 2, endSec: 3, text: "trois" },
+ { id: "w4", segmentId: "s", startSec: 3, endSec: 4, text: "quatre" },
+ ],
+};
+
+/** A trim over `deux` only — `findCoveringTrim` matches on the word's centre (1.5s). */
+const W2_TRIMMED: AxcutTrimRange = {
+ id: "t_w2",
+ assetId: "asset_1",
+ clipId: "clip_1",
+ startSec: 1,
+ endSec: 2,
+ origin: "user",
+ reason: "",
+};
+
+function renderPane(trimRanges: AxcutTrimRange[], onAddTrimRange = vi.fn()) {
+ const view = render(
+ <I18nProvider>
+ <TranscriptPane
+ clips={[CLIP]}
+ transcripts={[TRANSCRIPT]}
+ assets={[ASSET]}
+ trimRanges={trimRanges}
+ busy={false}
+ onSeek={vi.fn()}
+ onAddTrimRange={onAddTrimRange}
+ onRemoveTrimRange={vi.fn()}
+ onTranscribe={vi.fn()}
+ canTranscribe
+ isTranscribing={false}
+ />
+ </I18nProvider>,
+ );
+ const editor = view.container.querySelector<HTMLElement>('[role="textbox"]');
+ if (!editor) throw new Error("transcript editor not rendered");
+ return { ...view, editor, onAddTrimRange };
+}
+
+/**
+ * Park the caret between words exactly as `restoreCaretBeforeWord` does: `setStartBefore`
+ * on a word span collapses to (editor, index-of-that-word), so `anchorNode` is the editor
+ * itself rather than any word's text node.
+ */
+function caretBeforeWordAt(editor: HTMLElement, index: number) {
+ const range = document.createRange();
+ range.setStart(editor, index);
+ range.collapse(true);
+ const selection = window.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+}
+
+/** The words the pane cut, as `[startSec, endSec]` — what `onAddTrimRange` was asked for. */
+function cutRange(onAddTrimRange: ReturnType<typeof vi.fn>): [number, number] | null {
+ const call = onAddTrimRange.mock.calls.at(-1);
+ return call ? [call[1] as number, call[2] as number] : null;
+}
+
+beforeEach(() => {
+ useProjectStore.setState({ currentTimeSec: 0 });
+});
+
+afterEach(() => {
+ cleanup();
+ window.getSelection()?.removeAllRanges();
+});
+
+describe("keyboard cut with the caret between words", () => {
+ it("Backspace cuts the word before the caret", () => {
+ // The ordinary case, and the one that already worked: nothing trimmed yet.
+ const { editor, onAddTrimRange } = renderPane([]);
+ caretBeforeWordAt(editor, 3); // before "quatre"
+ fireEvent.keyDown(editor, { key: "Backspace" });
+ expect(cutRange(onAddTrimRange)).toEqual([2, 3]); // "trois"
+ });
+
+ it("Backspace skips over an already-trimmed word instead of doing nothing", () => {
+ // Hold Backspace and you land here: "deux" is already struck through, so the word
+ // immediately before the caret has nothing left to cut. The keystroke used to
+ // resolve to it anyway, `skipWordRange` dropped it as not-kept, and the user got
+ // silence — they had to click elsewhere to carry on.
+ const { editor, onAddTrimRange } = renderPane([W2_TRIMMED]);
+ caretBeforeWordAt(editor, 2); // before "trois", i.e. right after the trimmed "deux"
+ fireEvent.keyDown(editor, { key: "Backspace" });
+ expect(cutRange(onAddTrimRange)).toEqual([0, 1]); // "un" — the nearest word still there
+ });
+
+ it("Delete skips over an already-trimmed word instead of doing nothing", () => {
+ // The mirror case going forward. It had no guard at all: the candidate walk simply
+ // returned the first word it met, trimmed or not.
+ const { editor, onAddTrimRange } = renderPane([W2_TRIMMED]);
+ caretBeforeWordAt(editor, 1); // before the trimmed "deux"
+ fireEvent.keyDown(editor, { key: "Delete" });
+ expect(cutRange(onAddTrimRange)).toEqual([2, 3]); // "trois"
+ });
+
+ it("does nothing when every word in that direction is already trimmed", () => {
+ // Not a regression — there is genuinely nothing left to cut, so no document write.
+ const { editor, onAddTrimRange } = renderPane([
+ { ...W2_TRIMMED, id: "t_head", startSec: 0, endSec: 2 },
+ ]);
+ caretBeforeWordAt(editor, 2); // before "trois"; "un" and "deux" are both gone
+ fireEvent.keyDown(editor, { key: "Backspace" });
+ expect(onAddTrimRange).not.toHaveBeenCalled();
+ });
+
+ it("cuts nothing when the caret is at the very start and Backspace is pressed", () => {
+ const { editor, onAddTrimRange } = renderPane([]);
+ caretBeforeWordAt(editor, 0);
+ fireEvent.keyDown(editor, { key: "Backspace" });
+ expect(onAddTrimRange).not.toHaveBeenCalled();
+ });
+
+ // The story the whole thing exists for, in the shape the user meets it: the tests above
+ // place the caret by hand, this one lets the pane park it itself
+ // (`restoreCaretBeforeWord`) between keystrokes.
+ //
+ // It starts with "deux" ALREADY cut, because that is what it takes to reproduce. A plain
+ // run of Backspaces never stalls: the caret lands before the word just removed and the
+ // next press starts from its neighbour, which is still kept. The stall needs a
+ // previously-trimmed word in the path — then the walk resolved to it, `skipWordRange`
+ // dropped it as not-kept, and the run went quiet mid-hold.
+ it("keeps cutting backwards while Backspace is held, across an earlier cut", () => {
+ function Harness() {
+ const [trims, setTrims] = useState<AxcutTrimRange[]>([W2_TRIMMED]);
+ return (
+ <I18nProvider>
+ <TranscriptPane
+ clips={[CLIP]}
+ transcripts={[TRANSCRIPT]}
+ assets={[ASSET]}
+ trimRanges={trims}
+ busy={false}
+ onSeek={vi.fn()}
+ onAddTrimRange={(_target, startSec, endSec) =>
+ setTrims((prev) => [
+ ...prev,
+ {
+ id: `t_${prev.length}`,
+ assetId: "asset_1",
+ clipId: "clip_1",
+ startSec,
+ endSec,
+ origin: "user" as const,
+ reason: "",
+ },
+ ])
+ }
+ onRemoveTrimRange={vi.fn()}
+ onTranscribe={vi.fn()}
+ canTranscribe
+ isTranscribing={false}
+ />
+ </I18nProvider>
+ );
+ }
+
+ const { container } = render(<Harness />);
+ const editor = container.querySelector<HTMLElement>('[role="textbox"]');
+ if (!editor) throw new Error("transcript editor not rendered");
+
+ // Start inside the last word, as a user would after clicking it.
+ const quatre = container.querySelector<HTMLElement>('[data-word-id="clip_1:w4"]');
+ const range = document.createRange();
+ range.setStart(quatre?.firstChild as Node, 1);
+ range.collapse(true);
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+
+ // quatre, trois, then straight over the already-cut deux to un.
+ for (let i = 0; i < 3; i += 1) fireEvent.keyDown(editor, { key: "Backspace" });
+
+ const struck = Array.from(container.querySelectorAll<HTMLElement>("[data-word-id]"))
+ .filter((el) => el.style.textDecoration === "line-through")
+ .map((el) => el.dataset.wordId);
+ // The third press is the one that used to be swallowed: without it "un" survives.
+ expect(struck).toEqual(["clip_1:w1", "clip_1:w2", "clip_1:w3", "clip_1:w4"]);
+ });
+});
diff --git a/src/components/ai-edition/TranscriptPane.sharedMedia.test.tsx b/src/components/ai-edition/TranscriptPane.sharedMedia.test.tsx
new file mode 100644
index 000000000..36004c5c3
--- /dev/null
+++ b/src/components/ai-edition/TranscriptPane.sharedMedia.test.tsx
@@ -0,0 +1,177 @@
+// The rendered half of the shared-media cue bug. `findCueWordId` returning the right
+// answer is not enough on its own: the cue id is compared against every rendered word,
+// so while `data-word-id` carried the bare `word.id`, the SAME transcript word projected
+// into two clips over one media matched in BOTH blocks and the highlight appeared twice —
+// whichever section the resolver had picked. Only a render can catch that, which is why
+// these assertions count DOM nodes rather than inspect the resolver's return value.
+
+import "@testing-library/jest-dom";
+import { act, cleanup, fireEvent, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@/contexts/I18nContext";
+import type { AxcutAsset, AxcutClip, AxcutTranscript } from "@/lib/ai-edition/schema";
+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { TranscriptPane } from "./RightPanes";
+
+vi.mock("@/native/client", () => ({
+ nativeBridgeClient: { aiEdition: {} },
+}));
+
+vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
+
+const ASSET: AxcutAsset = {
+ id: "asset_1",
+ kind: "video",
+ label: "recording.mp4",
+ originalPath: "/rec.mp4",
+ durationSec: 12,
+ cameraTrack: null,
+};
+
+// One 12s media placed twice on the ruler — the shape the user reported.
+const CLIPS: AxcutClip[] = [
+ {
+ id: "clip_1",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 12,
+ timelineStartSec: 0,
+ timelineEndSec: 12,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ {
+ id: "clip_2",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 12,
+ timelineStartSec: 12,
+ timelineEndSec: 24,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+];
+
+const TRANSCRIPT: AxcutTranscript = {
+ assetId: "asset_1",
+ language: "fr",
+ segments: [],
+ words: [
+ { id: "w1", segmentId: "s", startSec: 0, endSec: 2, text: "Salut" },
+ // 4s gap → `withSilenceGaps` mints a `silence_1` in EACH section.
+ { id: "w2", segmentId: "s", startSec: 6, endSec: 8, text: "voilà" },
+ ],
+};
+
+function renderPane(onSeek: (sec: number) => void = vi.fn()) {
+ return render(
+ <I18nProvider>
+ <TranscriptPane
+ clips={CLIPS}
+ transcripts={[TRANSCRIPT]}
+ assets={[ASSET]}
+ trimRanges={[]}
+ busy={false}
+ onSeek={onSeek}
+ onAddTrimRange={vi.fn()}
+ onRemoveTrimRange={vi.fn()}
+ onTranscribe={vi.fn()}
+ canTranscribe
+ isTranscribing={false}
+ />
+ </I18nProvider>,
+ );
+}
+
+beforeEach(() => {
+ useProjectStore.setState({ currentTimeSec: 0 });
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("transcript pane with two clips over one media", () => {
+ it("gives every rendered word a DOM id unique across both blocks", () => {
+ const { container } = renderPane();
+ const ids = Array.from(container.querySelectorAll<HTMLElement>("[data-word-id]")).map(
+ (el) => el.dataset.wordId,
+ );
+ // Each block renders w1, the 2–6s silence, w2 and the 8–12s trailing silence. The
+ // two blocks are projections of the same transcript, so a bare `word.id` produced
+ // these eight nodes carrying only four distinct ids — and the silence tokens
+ // collided on top of that, being numbered from 1 within each clip.
+ expect(ids).toHaveLength(8);
+ expect(new Set(ids).size).toBe(8);
+ expect(ids).toEqual(
+ expect.arrayContaining(["clip_1:silence_1", "clip_2:silence_1", "clip_1:w2", "clip_2:w2"]),
+ );
+ });
+
+ it("highlights the cue word in the playing clip only", () => {
+ // Playhead at RAW 19s → inside clip_2 (ruler 12–24), source 7s → the word "voilà".
+ useProjectStore.setState({ currentTimeSec: 19 });
+ const { container } = renderPane();
+
+ const cues = Array.from(container.querySelectorAll<HTMLElement>('[data-cue="true"]'));
+ expect(cues).toHaveLength(1);
+ expect(cues[0].dataset.wordId).toBe("clip_2:w2");
+ expect(cues[0]).toHaveTextContent("voilà");
+ });
+
+ it("moves the highlight to the other block when the playhead crosses the boundary", () => {
+ // Same source moment (7s), now reached through clip_1 (ruler 0–12).
+ useProjectStore.setState({ currentTimeSec: 7 });
+ const { container } = renderPane();
+
+ const cues = Array.from(container.querySelectorAll<HTMLElement>('[data-cue="true"]'));
+ expect(cues).toHaveLength(1);
+ expect(cues[0].dataset.wordId).toBe("clip_1:w2");
+ });
+
+ // `onSeek` takes RAW TIMELINE seconds, a word's times are the ASSET's source seconds.
+ // They coincide only for a clip sitting at ruler 0, so this was invisible until a second
+ // clip existed — and stayed invisible while the cue lit up every block regardless of
+ // where the playhead had actually landed.
+ it("seeks to the clicked word's position on the RULER, not its source time", () => {
+ const onSeek = vi.fn();
+ const { container } = renderPane(onSeek);
+
+ const inClip2 = container.querySelector<HTMLElement>('[data-word-id="clip_2:w2"]');
+ expect(inClip2).not.toBeNull();
+ fireEvent.pointerUp(inClip2 as HTMLElement, { button: 0 });
+ // "voilà" is source 6s; clip_2 plays source 0–12 at ruler 12–24 → ruler 18s.
+ expect(onSeek).toHaveBeenCalledWith(18);
+
+ onSeek.mockClear();
+ const inClip1 = container.querySelector<HTMLElement>('[data-word-id="clip_1:w2"]');
+ fireEvent.pointerUp(inClip1 as HTMLElement, { button: 0 });
+ // Same word, same source moment — but reached through the clip at ruler 0.
+ expect(onSeek).toHaveBeenCalledWith(6);
+ });
+
+ it("clears the old block's highlight as the playhead crosses, rather than adding a second", () => {
+ // A transition, not two independent renders: `TranscriptClipBlock` is memoised, so
+ // the block the cue LEAVES only drops its underline if it actually re-renders. Two
+ // highlights at once is the reported symptom, and a lingering stale one would look
+ // identical on screen.
+ useProjectStore.setState({ currentTimeSec: 7 }); // in clip_1
+ const { container } = renderPane();
+ expect(
+ Array.from(container.querySelectorAll<HTMLElement>('[data-cue="true"]')).map(
+ (el) => el.dataset.wordId,
+ ),
+ ).toEqual(["clip_1:w2"]);
+
+ act(() => {
+ useProjectStore.setState({ currentTimeSec: 19 }); // same source moment, in clip_2
+ });
+ expect(
+ Array.from(container.querySelectorAll<HTMLElement>('[data-cue="true"]')).map(
+ (el) => el.dataset.wordId,
+ ),
+ ).toEqual(["clip_2:w2"]);
+ });
+});
diff --git a/src/components/ai-edition/WebcamOverlay.test.tsx b/src/components/ai-edition/WebcamOverlay.test.tsx
index 64386fab7..5fbfc9a04 100644
--- a/src/components/ai-edition/WebcamOverlay.test.tsx
+++ b/src/components/ai-edition/WebcamOverlay.test.tsx
@@ -36,7 +36,7 @@ const CLIP_WITHOUT_CAMERA: AxcutClip = {
function makeDocument(): AxcutDocument {
return {
- schemaVersion: 6,
+ schemaVersion: 7,
project: {
id: "proj_test",
title: "Test",
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index f7e9cb17f..306d3574a 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -978,16 +978,17 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
}
// trim — a trim ventilated across a clip boundary is 2+ DSL rows that render
- // as one coalesced pill (see V4Timeline's trimPills); the inspector must
- // resolve the clicked id back to its whole group so the shown duration and
- // the delete button act on all of it, not just the one row that was clicked.
+ // as one coalesced pill (see V4Timeline's trimPills), so the DURATION shown has to be
+ // the group's, not the clicked row's. Deleting no longer needs the same expansion here:
+ // `removeRegion` drops the whole pill for every kind (`dropTrimPillsByIds`), which is
+ // what this pane used to have to arrange for itself.
const trimGroup = coalescedTrimGroups(tl.trimRanges, tl.clips).find((g) =>
g.ids.includes(selection.id),
);
if (!trimGroup) return null;
const durationSec = Math.max(0, trimGroup.end - trimGroup.start);
const deleteTrimGroup = () => {
- void tl.removeRegions(trimGroup.ids.map((id) => ({ kind: "trim" as const, id })));
+ void tl.removeRegion("trim", selection.id);
onClose();
};
return (
diff --git a/src/lib/ai-edition/document/migrate.test.ts b/src/lib/ai-edition/document/migrate.test.ts
index d0d951a4a..8dc4342f5 100644
--- a/src/lib/ai-edition/document/migrate.test.ts
+++ b/src/lib/ai-edition/document/migrate.test.ts
@@ -48,7 +48,7 @@ describe("migrateProjectDataToAxcutDocument", () => {
it("produces a v3 document with one asset and one clip from a v2 single-recording project", () => {
const doc = migrateProjectDataToAxcutDocument(makeV2Project());
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect(doc.assets).toHaveLength(1);
const asset = doc.assets[0];
expect(asset.kind).toBe("video");
@@ -388,7 +388,7 @@ describe("migrateRawDocumentToCurrent", () => {
};
}
- it("upgrades a v3 document to v6 (cameraTrack relocated onto the primary asset)", () => {
+ it("upgrades a v3 document to v7 (cameraTrack relocated onto the primary asset)", () => {
// Models the full load path: every disk-read site runs the helper, then
// the schema parse fills in defaults (cameraTrack: null on non-target
// assets). The helper alone is just the upgrader chain; the schema is
@@ -406,13 +406,13 @@ describe("migrateRawDocumentToCurrent", () => {
}),
),
);
- expect(migrated.schemaVersion).toBe(6);
+ expect(migrated.schemaVersion).toBe(7);
expect((migrated as Record<string, unknown>).cameraTrack).toBeUndefined();
expect(migrated.assets[0].cameraTrack).toBeNull();
expect(migrated.assets[1].cameraTrack?.sourcePath).toBe("/cam.mp4");
});
- it("upgrades a v4 document to v6 (anchors modifiers onto clips)", () => {
+ it("upgrades a v4 document to v7 (anchors modifiers onto clips)", () => {
const migrated = migrateRawDocumentToCurrent(
makeV4Doc({
zoomRanges: [
@@ -420,7 +420,7 @@ describe("migrateRawDocumentToCurrent", () => {
],
}),
) as Record<string, unknown>;
- expect(migrated.schemaVersion).toBe(6);
+ expect(migrated.schemaVersion).toBe(7);
const zooms = migrated.zoomRanges as Array<Record<string, unknown>>;
expect(zooms).toHaveLength(1);
expect(zooms[0]).toMatchObject({ id: "z1", clipId: "c1", depth: 3 });
@@ -428,12 +428,12 @@ describe("migrateRawDocumentToCurrent", () => {
it("is a no-op for an already-current document (returns an equal value)", () => {
const v5 = makeV4Doc(); // makeV4Doc's body is the v5-compatible shape
- const once = migrateRawDocumentToCurrent({ ...v5, schemaVersion: 6 });
+ const once = migrateRawDocumentToCurrent({ ...v5, schemaVersion: 7 });
// ponytail: the upgrader chain checks schemaVersion and returns the input
// unchanged, so the round-trip allocation is bounded to a property
// comparison per upgrader — the same per-parse overhead the old
// `z.preprocess` carried.
- expect(once).toEqual({ ...v5, schemaVersion: 6 });
+ expect(once).toEqual({ ...v5, schemaVersion: 7 });
});
it("passes non-document input through unchanged (the schema is the gate, not this helper)", () => {
diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.ts
index 283eef372..2b360806a 100644
--- a/src/lib/ai-edition/document/migrate.ts
+++ b/src/lib/ai-edition/document/migrate.ts
@@ -143,6 +143,10 @@ export function migrateProjectDataToAxcutDocument(
}
: null;
+ // Anchored to `clip` right here rather than left to `upgradeV6DocumentToV7`: a v2
+ // project has exactly one clip, so the clip is known and unambiguous, and the upgrader
+ // could not do it anyway — the clip it mints has no source extent yet (the duration only
+ // arrives once the renderer probes the file), and anchoring needs a real window.
const trimRanges: AxcutTrimRange[] = primaryAssetId
? trimRegions
.filter((region) => region && typeof region.id === "string")
@@ -152,6 +156,7 @@ export function migrateProjectDataToAxcutDocument(
return {
id: createId("trim"),
assetId: primaryAssetId,
+ ...(clip ? { clipId: clip.id } : {}),
startSec: clampSec(msToSec(startMs)),
endSec: clampSec(msToSec(endMs)),
origin: "user" as const,
diff --git a/src/lib/ai-edition/document/operations.test.ts b/src/lib/ai-edition/document/operations.test.ts
index 044eab4fd..6fba75312 100644
--- a/src/lib/ai-edition/document/operations.test.ts
+++ b/src/lib/ai-edition/document/operations.test.ts
@@ -116,6 +116,128 @@ describe("applyTimelineOperation.add_trim_range", () => {
expect(afterSecond.timeline.trimRanges.filter((s) => s.assetId === "asset_1")).toHaveLength(1);
expect(afterSecond.timeline.trimRanges.filter((s) => s.assetId === "asset_2")).toHaveLength(1);
});
+
+ // The harder version of the test above: the two clips share ONE asset, so the trims
+ // live in the same source coordinate space. Merging by asset (what the code did) folded
+ // two distinct user edits into one interval list that was then re-applied to both clips.
+ describe("two clips over the same media", () => {
+ function docWithTwins(): AxcutDocument {
+ const doc = makeDoc();
+ return {
+ ...doc,
+ timeline: {
+ ...doc.timeline,
+ clips: [
+ ...doc.timeline.clips,
+ {
+ id: "clip_2",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 60,
+ timelineStartSec: 60,
+ timelineEndSec: 120,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ },
+ };
+ }
+
+ it("anchors the cut to the clip the caller names", () => {
+ const next = applyTimelineOperation(docWithTwins(), {
+ type: "add_trim_range",
+ assetId: "asset_1",
+ clipId: "clip_2",
+ startSec: 3,
+ endSec: 5,
+ }).document;
+ expect(next.timeline.trimRanges).toHaveLength(1);
+ expect(next.timeline.trimRanges[0]).toMatchObject({
+ assetId: "asset_1",
+ clipId: "clip_2",
+ startSec: 3,
+ endSec: 5,
+ });
+ });
+
+ it("keeps each clip's cuts separate instead of merging them by asset", () => {
+ const afterFirst = applyTimelineOperation(docWithTwins(), {
+ type: "add_trim_range",
+ assetId: "asset_1",
+ clipId: "clip_1",
+ startSec: 3,
+ endSec: 5,
+ }).document;
+ // Same source range on the twin. Asset-scoped merging collapsed this into the
+ // row above, so one of the two edits vanished and the survivor cut both clips.
+ const afterSecond = applyTimelineOperation(afterFirst, {
+ type: "add_trim_range",
+ assetId: "asset_1",
+ clipId: "clip_2",
+ startSec: 3,
+ endSec: 5,
+ }).document;
+ expect(afterSecond.timeline.trimRanges).toHaveLength(2);
+ expect(afterSecond.timeline.trimRanges.map((s) => s.clipId).sort()).toEqual([
+ "clip_1",
+ "clip_2",
+ ]);
+ // Ids must not collide either — they used to be keyed by asset alone.
+ expect(new Set(afterSecond.timeline.trimRanges.map((s) => s.id)).size).toBe(2);
+ });
+
+ it("still merges touching cuts on the SAME clip into one row", () => {
+ const afterFirst = applyTimelineOperation(docWithTwins(), {
+ type: "add_trim_range",
+ assetId: "asset_1",
+ clipId: "clip_1",
+ startSec: 3,
+ endSec: 5,
+ }).document;
+ const afterSecond = applyTimelineOperation(afterFirst, {
+ type: "add_trim_range",
+ assetId: "asset_1",
+ clipId: "clip_1",
+ startSec: 5,
+ endSec: 7,
+ }).document;
+ expect(afterSecond.timeline.trimRanges).toHaveLength(1);
+ expect(afterSecond.timeline.trimRanges[0]).toMatchObject({ startSec: 3, endSec: 7 });
+ });
+
+ it("leaves a pre-v7 un-anchored cut alone when adding an anchored one", () => {
+ const withLegacy: AxcutDocument = (() => {
+ const doc = docWithTwins();
+ return {
+ ...doc,
+ timeline: {
+ ...doc.timeline,
+ trimRanges: [
+ {
+ id: "legacy",
+ assetId: "asset_1",
+ startSec: 3,
+ endSec: 5,
+ origin: "user" as const,
+ reason: "",
+ },
+ ],
+ },
+ };
+ })();
+ const next = applyTimelineOperation(withLegacy, {
+ type: "add_trim_range",
+ assetId: "asset_1",
+ clipId: "clip_2",
+ startSec: 3,
+ endSec: 5,
+ }).document;
+ expect(next.timeline.trimRanges).toHaveLength(2);
+ expect(next.timeline.trimRanges.find((s) => s.id === "legacy")).toBeDefined();
+ });
+ });
});
describe("applyTimelineOperation.drop_range", () => {
diff --git a/src/lib/ai-edition/document/operations.ts b/src/lib/ai-edition/document/operations.ts
index 72a0a59e8..94c3ca395 100644
--- a/src/lib/ai-edition/document/operations.ts
+++ b/src/lib/ai-edition/document/operations.ts
@@ -36,6 +36,10 @@ export type AxcutTimelineOperation =
| {
type: "add_trim_range";
assetId?: string;
+ /** Clip the cut was authored on — the v7 anchor. Omit only when the caller
+ * genuinely has no clip context; the trim then keeps the pre-v7 asset-wide
+ * meaning (see `trimAppliesToClip`). */
+ clipId?: string;
startSec: number;
endSec: number;
reason?: string;
@@ -172,15 +176,29 @@ export function applyTimelineOperation(
if (!assetId) return { document, summary: "no asset to trim" };
const lo = Math.max(0, Math.min(op.startSec, op.endSec));
const hi = Math.max(lo, Math.max(op.startSec, op.endSec));
- // BUG corrigé : `merged` (calculé UNIQUEMENT à partir des trims de CET assetId)
+ // The new cut is normalized together with the trims it can actually merge with,
+ // and ONLY those — the rest of the list must survive untouched.
+ //
+ // BUG corrigé (1) : `merged` (calculé UNIQUEMENT à partir des trims de CET assetId)
// remplaçait ensuite `document.timeline.trimRanges` EN ENTIER — les trims de tout
// autre asset (donc tout autre clip, dès qu'un projet a plus d'un enregistrement)
// disparaissaient silencieusement dès qu'on ajoutait un trim sur un asset différent.
- // C'est exactement le "éditer le clip 2 efface les edits du clip 1" observé : les deux
- // clips du repro pointent vers deux fichiers distincts. Il faut conserver les trims des
- // AUTRES assets tels quels et ne remplacer que la tranche de CET asset.
- const otherAssetsRanges = document.timeline.trimRanges.filter((s) => s.assetId !== assetId);
- const existing = document.timeline.trimRanges.filter((s) => s.assetId === assetId);
+ //
+ // BUG corrigé (2) : même à assetId égal, fusionner par asset était trop large dès que
+ // DEUX CLIPS PARTAGENT LE MÊME MÉDIA. Les coupes du clip 1 et du clip 2 vivent dans la
+ // même plage de source ; les fusionner produisait une seule liste d'intervalles
+ // réappliquée aux deux clips — le trim posé sur le clip 2 apparaissait en double dans
+ // le transcript et sur le mauvais clip dans la timeline. La fusion est donc désormais
+ // bornée au GROUPE D'ANCRAGE : les trims du même clip quand on en connaît un, sinon
+ // les trims non ancrés du même asset (comportement pré-v7 conservé).
+ const groupKey = op.clipId ?? `asset:${assetId}`;
+ const keyOf = (s: { assetId: string; clipId?: string }) => s.clipId ?? `asset:${s.assetId}`;
+ const untouched = document.timeline.trimRanges.filter(
+ (s) => s.assetId !== assetId || keyOf(s) !== groupKey,
+ );
+ const existing = document.timeline.trimRanges.filter(
+ (s) => s.assetId === assetId && keyOf(s) === groupKey,
+ );
// ponytail: bound by the trim-range asset's duration, not the
// primary asset's. Recording projects can have a short primary
// asset (snippet) while the clip uses a long video — using
@@ -197,13 +215,16 @@ export function applyTimelineOperation(
timeline: {
...document.timeline,
trimRanges: [
- ...otherAssetsRanges,
+ ...untouched,
...merged.map((iv, i) => ({
// ponytail: id scoped by assetId — plain `trim_${i+1}` collided across
// assets (two different assets could each mint "trim_1"), which would
// have made remove/update_trim_range act on the wrong asset's range by id.
- id: `trim_${assetId}_${i + 1}`,
+ // Scoped by clipId when there is one, for the same reason one step down:
+ // two clips over one asset would otherwise mint the same ids.
+ id: `trim_${op.clipId ?? assetId}_${i + 1}`,
assetId,
+ ...(op.clipId ? { clipId: op.clipId } : {}),
startSec: iv.startSec,
endSec: iv.endSec,
origin: "user" as const,
diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts
index b87701402..ccfafd90d 100644
--- a/src/lib/ai-edition/document/timeline.test.ts
+++ b/src/lib/ai-edition/document/timeline.test.ts
@@ -779,6 +779,59 @@ describe("resolvePlaybackSegments", () => {
sourceEndSec: 55,
});
});
+
+ // Two clips over the SAME media, same source window — the shape the previous test
+ // deliberately avoided by keeping the windows disjoint. Here `assetId` + source
+ // overlap cannot tell the clips apart; only `clipId` can.
+ describe("two clips sharing one asset over the same source window", () => {
+ const sharedClips = () => [
+ makeClip({
+ id: "clip_1",
+ sourceStartSec: 0,
+ sourceEndSec: 11.8,
+ timelineStartSec: 0,
+ timelineEndSec: 11.8,
+ }),
+ makeClip({
+ id: "clip_2",
+ sourceStartSec: 0,
+ sourceEndSec: 11.8,
+ timelineStartSec: 11.8,
+ timelineEndSec: 23.6,
+ }),
+ ];
+
+ it("cuts only the anchored clip, leaving its twin whole", () => {
+ const trim = makeTrim({ id: "t1", clipId: "clip_2", startSec: 3, endSec: 4 });
+ const segments = resolvePlaybackSegments(sharedClips(), [trim]);
+ // clip_1 survives as one untouched segment; clip_2 splits around [3,4].
+ expect(segments).toHaveLength(3);
+ expect(segments[0]).toMatchObject({ id: "clip_1", sourceStartSec: 0, sourceEndSec: 11.8 });
+ expect(segments[1]).toMatchObject({
+ id: "clip_2_seg1",
+ sourceStartSec: 0,
+ sourceEndSec: 3,
+ });
+ expect(segments[2]).toMatchObject({
+ id: "clip_2_seg2",
+ sourceStartSec: 4,
+ sourceEndSec: 11.8,
+ });
+ });
+
+ it("still cuts both clips for a pre-v7 trim that names no clip", () => {
+ // Back-compat: an un-anchored row keeps its historical asset-wide meaning, so a
+ // document written before the anchor existed renders exactly as it used to.
+ const trim = makeTrim({ id: "t1", startSec: 3, endSec: 4 });
+ const segments = resolvePlaybackSegments(sharedClips(), [trim]);
+ expect(segments.map((s) => s.id)).toEqual([
+ "clip_1_seg1",
+ "clip_1_seg2",
+ "clip_2_seg1",
+ "clip_2_seg2",
+ ]);
+ });
+ });
});
describe("duplicateClip / moveClip", () => {
@@ -809,6 +862,55 @@ describe("duplicateClip / moveClip", () => {
expect(next.timeline.clips[2].id).toBe("clip_b");
});
+ // A trim used to reach the copy for free, by matching on `assetId`. Now that it names
+ // its clip the copy has to be given its own, or duplicating a cut clip would silently
+ // produce an uncut one.
+ it("duplicateClip copies the original's anchored trims onto the copy, independently", () => {
+ const doc = makeDoc({
+ timeline: {
+ ...makeDoc().timeline,
+ clips: [makeClip({ id: "clip_a", sourceStartSec: 0, sourceEndSec: 10 })],
+ trimRanges: [makeTrim({ id: "t1", clipId: "clip_a", startSec: 2, endSec: 4 })],
+ },
+ });
+ const next = duplicateClip(doc, "clip_a");
+ const copyId = next.timeline.clips[1].id;
+ expect(next.timeline.trimRanges).toHaveLength(2);
+ const copied = next.timeline.trimRanges.find((t) => t.clipId === copyId);
+ expect(copied).toMatchObject({ startSec: 2, endSec: 4 });
+ // Fresh id — a shared one would make the two cuts one row again.
+ expect(copied?.id).not.toBe("t1");
+ // Both clips are cut, exactly as before the anchor existed.
+ expect(resolvePlaybackSegments(next.timeline.clips, next.timeline.trimRanges)).toHaveLength(4);
+ });
+
+ it("removeClip drops the deleted clip's trims but keeps a twin's", () => {
+ const doc = makeDoc({
+ timeline: {
+ ...makeDoc().timeline,
+ clips: [
+ makeClip({ id: "clip_1", sourceStartSec: 0, sourceEndSec: 10 }),
+ makeClip({
+ id: "clip_2",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ }),
+ ],
+ trimRanges: [
+ makeTrim({ id: "t1", clipId: "clip_1", startSec: 2, endSec: 4 }),
+ makeTrim({ id: "t2", clipId: "clip_2", startSec: 6, endSec: 8 }),
+ makeTrim({ id: "legacy", startSec: 1, endSec: 2 }),
+ ],
+ },
+ });
+ const next = removeClip(doc, "clip_2");
+ // `t2`'s content is gone with its clip; an asset-wide match would have moved it
+ // onto the surviving twin, which is the wrong-clip class this whole change removes.
+ expect(next.timeline.trimRanges.map((t) => t.id)).toEqual(["t1", "legacy"]);
+ });
+
it("moveClip reorders clips", () => {
const doc = makeDoc({
timeline: {
@@ -1116,7 +1218,9 @@ describe("removeRegion — the one shared region-delete mutator", () => {
expect(next.zoomRanges.map((z) => z.id)).toEqual(["z3"]);
});
- it("filters a trim by id without touching other trims", () => {
+ it("falls back to the single row when there is no clip layout to group against", () => {
+ // No clips → `coalescedTrimGroups` can map nothing, so there is no pill to expand to.
+ // The row must still be deletable rather than silently surviving.
const doc = makeDoc({
timeline: {
...makeDoc().timeline,
@@ -1127,6 +1231,68 @@ describe("removeRegion — the one shared region-delete mutator", () => {
expect(next.timeline.trimRanges.map((t) => t.id)).toEqual(["trim_2"]);
});
+ // A trim grown across a clip boundary CANNOT be one row — source time is per clip — so
+ // `ventilateTimelineSpanToTrims` writes one per covered clip and the ruler merges them
+ // back into the single stripe the user clicks. Deleting by bare id left the other half
+ // still cutting content. Every other kind already expanded to its pill.
+ describe("a trim ventilated across a clip boundary", () => {
+ // clip_a plays source 0-10 at ruler 0-10; clip_b plays source 0-10 at ruler 10-20.
+ // One drag from ruler 8 to 12 stores rows at ruler 8-10 and 10-12: they touch, so
+ // they are one pill.
+ const doc = () =>
+ makeDoc({
+ timeline: {
+ ...makeDoc().timeline,
+ clips: [
+ makeClip({
+ id: "clip_a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ }),
+ makeClip({
+ id: "clip_b",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 10,
+ timelineEndSec: 20,
+ }),
+ ],
+ trimRanges: [
+ makeTrim({ id: "half_a", clipId: "clip_a", startSec: 8, endSec: 10 }),
+ makeTrim({ id: "half_b", clipId: "clip_b", startSec: 0, endSec: 2 }),
+ // A separate cut elsewhere on clip_a — its own pill, must survive.
+ makeTrim({ id: "other", clipId: "clip_a", startSec: 2, endSec: 3 }),
+ ],
+ },
+ });
+
+ it("deletes both halves whichever one was clicked", () => {
+ expect(removeRegion(doc(), "trim", "half_a").timeline.trimRanges.map((t) => t.id)).toEqual([
+ "other",
+ ]);
+ expect(removeRegion(doc(), "trim", "half_b").timeline.trimRanges.map((t) => t.id)).toEqual([
+ "other",
+ ]);
+ });
+
+ it("leaves no content still cut once the pill is deleted", () => {
+ // The point of the bug, not just the row count: half the stripe kept removing
+ // footage after the user had deleted it.
+ const next = removeRegion(doc(), "trim", "half_a");
+ const segments = resolvePlaybackSegments(next.timeline.clips, next.timeline.trimRanges);
+ // clip_b is whole again; clip_a is split only by the unrelated `other` cut.
+ expect(segments.map((s) => s.id)).toEqual(["clip_a_seg1", "clip_a_seg2", "clip_b"]);
+ expect(segments.at(-1)).toMatchObject({ sourceStartSec: 0, sourceEndSec: 10 });
+ });
+
+ it("does not swallow a non-touching cut on the same clip", () => {
+ const next = removeRegion(doc(), "trim", "other");
+ expect(next.timeline.trimRanges.map((t) => t.id).sort()).toEqual(["half_a", "half_b"]);
+ });
+ });
+
it("removes speed and camera-fullscreen regions under legacyEditor", () => {
const doc = makeDoc({
legacyEditor: {
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 0e80fe523..96f517e6b 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -9,6 +9,7 @@ import {
anchorRegionsWithDerivedMs,
dropPillById,
} from "../timeline/timelineMap";
+import { dropTrimPillsByIds, trimAppliesToClip } from "../timeline/trim-mapping";
import { createId } from "./ids";
/** The region families a delete can target by id. Shared with the store so "which kinds
@@ -158,13 +159,16 @@ export function subtractInterval(intervals: Interval[], cut: Interval): Interval
* `document.timeline.clips`. Each clip's own `[sourceStartSec, sourceEndSec]` (its media
* in/out, edited via the clip's own modal) is untouched as a concept; this only narrows the
* WINDOW of it handed to playback for the trimmed stretch(es), via `subtractInterval`
- * (existing, tested — no new interval math). Trims are stored per-asset in source time
- * (`AxcutTrimRange`) and may already be ventilated into multiple entries by
+ * (existing, tested — no new interval math). Trims are stored in source time, anchored to
+ * a clip (`AxcutTrimRange`), and may already be ventilated into multiple entries by
* `ventilateTimelineSpanToTrims` when the user drags one across a clip boundary — subtracting
- * by matching `assetId` against every clip naturally narrows however many clips that produces,
- * no special-casing. Everything else about the clip (id, assetId, webcam pairing/offset via
- * the asset, origin/reason) carries through unchanged, which is what makes this apply to the
- * webcam for free: webcam sync is derived from the clip's own asset, not recomputed here.
+ * per matching clip naturally narrows however many clips that produces, no special-casing.
+ * Matching goes through `trimAppliesToClip`, so a cut authored on the second of two clips
+ * over the same media narrows only that clip; matching on `assetId` alone removed the span
+ * from BOTH, which is the same wrong-clip class the ruler and the transcript pane had.
+ * Everything else about the clip (id, assetId, webcam pairing/offset via the asset,
+ * origin/reason) carries through unchanged, which is what makes this apply to the webcam for
+ * free: webcam sync is derived from the clip's own asset, not recomputed here.
*/
export function resolvePlaybackSegments(
clips: AxcutClip[],
@@ -188,7 +192,7 @@ export function resolvePlaybackSegments(
}
let kept: Interval[] = [{ startSec: clip.sourceStartSec, endSec: sourceEnd }];
for (const trim of trimRanges) {
- if (trim.assetId !== clip.assetId) continue;
+ if (!trimAppliesToClip(trim, clip)) continue;
kept = subtractInterval(kept, { startSec: trim.startSec, endSec: trim.endSec });
}
kept.forEach((iv, i) => {
@@ -773,6 +777,15 @@ export function moveClip(
// ponytail: duplicate a clip (preserves the original). Used for "split this
// clip into two" or "make a copy". Mirrors axcut's
// apps/server/src/lib/timeline.ts#duplicateClip.
+//
+// The copy takes its own COPY of the original's trims, re-anchored to the new clip id.
+// Before trims carried a `clipId` this happened by accident — a trim matched on `assetId`,
+// so the duplicate (same asset) was born already cut the same way — and that accident is
+// the behaviour a user expects from "duplicate": an identical clip. Now that a trim names
+// its clip, the copy has to be made on purpose, and the two sets are independent
+// afterwards, which is the point: editing the copy's cut no longer edits the original's.
+// Only ANCHORED trims are copied — an un-anchored one already reaches the copy through
+// the asset-wide fallback, so copying it would cut the same span twice.
export function duplicateClip(
document: AxcutDocument,
clipId: string,
@@ -793,11 +806,15 @@ export function duplicateClip(
const oldClips = document.timeline.clips;
const next = [...oldClips.slice(0, index + 1), copy, ...oldClips.slice(index + 1)];
const newClips = resequenceClips(next);
+ const copiedTrims = document.timeline.trimRanges
+ .filter((t) => t.clipId === original.id)
+ .map((t) => ({ ...t, id: createId("trim"), clipId: copy.id }));
const updatedDoc: AxcutDocument = {
...document,
timeline: {
...document.timeline,
clips: newClips,
+ trimRanges: [...document.timeline.trimRanges, ...copiedTrims],
},
};
return rederiveRegionMs(updatedDoc, newClips);
@@ -841,9 +858,13 @@ export function setClipSourceRange(
/**
* The single mutator for "delete a region by id" — the edit the UI's delete key and the
* LLM's `removeTrim` / `removeModifier` tools all perform. Extracted here (like
- * `setClipSourceRange`) so the recipe lives in one place: a `trim` is a plain filter on the
- * source-time cut list; every other kind is a pill (`dropPillById` removes every region that
- * renders as the same pill as `id`, per the merge rule). Speed / camera-fullscreen live under
+ * `setClipSourceRange`) so the recipe lives in one place: EVERY kind deletes the whole
+ * pill, i.e. every row that renders as one stripe with `id` under the merge rule. Modifiers
+ * go through `dropPillById`; trims need `dropTrimPillsByIds` instead, because `dropPillById`
+ * keys off `startMs`/`endMs` and a trim stores `startSec`/`endSec` plus a `clipId` anchor —
+ * different storage, same rule. Trims used to be the exception here (a bare id filter), so a
+ * cut grown across a clip boundary — necessarily 2+ rows — lost only the row that was
+ * clicked and kept cutting on the other side. Speed / camera-fullscreen live under
* `legacyEditor`. An id that matches nothing is a no-op. Pure.
*/
export function removeRegion(document: AxcutDocument, kind: RegionKind, id: string): AxcutDocument {
@@ -860,7 +881,9 @@ export function removeRegion(document: AxcutDocument, kind: RegionKind, id: stri
...document,
timeline: {
...document.timeline,
- trimRanges: document.timeline.trimRanges.filter((s) => s.id !== id),
+ trimRanges: dropTrimPillsByIds(document.timeline.trimRanges, document.timeline.clips, [
+ id,
+ ]),
},
};
case "speed": {
@@ -893,8 +916,11 @@ export function removeRegion(document: AxcutDocument, kind: RegionKind, id: stri
* The single mutator for "delete a clip". Removing a clip closes the gap: the survivors are
* re-laid back-to-back (`resequenceClips`) and every anchored pill's derived ms is refreshed
* against the new layout (`rederiveRegionMs`) — pills anchored to the removed clip drop out,
- * exactly like `setClipSourceRange`. Shared by the store's delete-clip action and the LLM's
- * `removeClip` tool. An unknown `clipId` is a no-op. Pure.
+ * exactly like `setClipSourceRange`. Trims anchored to it go the same way: their content is
+ * gone, so keeping them would leave rows nothing can reach (they render on no clip and cut
+ * no clip) that a later duplicate of the same asset must not resurrect. Shared by the
+ * store's delete-clip action and the LLM's `removeClip` tool. An unknown `clipId` is a
+ * no-op. Pure.
*/
export function removeClip(document: AxcutDocument, clipId: string): AxcutDocument {
const oldClips = document.timeline.clips;
@@ -903,7 +929,11 @@ export function removeClip(document: AxcutDocument, clipId: string): AxcutDocume
const newClips = resequenceClips(arr);
const next: AxcutDocument = {
...document,
- timeline: { ...document.timeline, clips: newClips },
+ timeline: {
+ ...document.timeline,
+ clips: newClips,
+ trimRanges: document.timeline.trimRanges.filter((t) => t.clipId !== clipId),
+ },
};
return oldClips.length > 0 && newClips.length > 0 ? rederiveRegionMs(next, newClips) : next;
}
diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.ts
index fb5ce1cac..bbba94fd8 100644
--- a/src/lib/ai-edition/schema/index.test.ts
+++ b/src/lib/ai-edition/schema/index.test.ts
@@ -15,9 +15,9 @@ import {
zoomRegionSchema,
} from "./index";
-describe("axcut-schema v6", () => {
- it("uses schema version 6", () => {
- expect(axcutSchemaVersion).toBe(6);
+describe("axcut-schema v7", () => {
+ it("uses schema version 7", () => {
+ expect(axcutSchemaVersion).toBe(7);
});
it("rejects unknown schema versions", () => {
@@ -29,9 +29,9 @@ describe("axcut-schema v6", () => {
).toThrow();
});
- it("createEmptyDocument returns a valid v6 doc with empty collections", () => {
+ it("createEmptyDocument returns a valid v7 doc with empty collections", () => {
const doc = createEmptyDocument({ projectId: "proj_1", title: "Demo" });
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect(doc.assets).toEqual([]);
expect(doc.timeline.clips).toEqual([]);
expect(doc.timeline.trimRanges).toEqual([]);
@@ -205,7 +205,7 @@ describe("axcut-schema v6", () => {
it("documentSchema defaults missing v3 envelopes on a v3 document", () => {
// After the migration hoist, a v3 doc must run through
// `migrateRawDocumentToCurrent` first; this models the new load-time
- // contract: the schema parse is a pure v6 validation step.
+ // contract: the schema parse is a pure v7 validation step.
expect(() =>
documentSchema.parse(
migrateRawDocumentToCurrent({
@@ -259,13 +259,13 @@ describe("axcut-schema v6", () => {
it("relocates a legacy top-level cameraTrack onto the primaryAssetId asset", () => {
// After the migration hoist, v3 input runs through the load-time
- // upgrader before the pure v6 schema parse.
+ // upgrader before the pure v7 schema parse.
const doc = documentSchema.parse(
migrateRawDocumentToCurrent(
v3Doc({ project: { ...v3Doc().project, primaryAssetId: "asset_2" } }),
),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect((doc as Record<string, unknown>).cameraTrack).toBeUndefined();
expect(doc.assets.find((a) => a.id === "asset_1")?.cameraTrack).toBeNull();
expect(doc.assets.find((a) => a.id === "asset_2")?.cameraTrack?.sourcePath).toBe("/cam.mp4");
@@ -279,7 +279,7 @@ describe("axcut-schema v6", () => {
it("is a no-op when the v3 document has no legacy cameraTrack", () => {
const doc = documentSchema.parse(migrateRawDocumentToCurrent(v3Doc({ cameraTrack: null })));
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
for (const asset of doc.assets) {
expect(asset.cameraTrack).toBeNull();
}
@@ -287,7 +287,7 @@ describe("axcut-schema v6", () => {
it("rejects schemaVersion 2 (the load-time helper only upgrades v3/v4)", () => {
// The pre-hoist schema auto-upgraded v3 inside its `z.preprocess`;
- // the post-hoist schema is a pure v6 validator, and the helper
+ // the post-hoist schema is a pure v7 validator, and the helper
// only handles v3/v4. v2 still requires the separate
// `migrateProjectDataToAxcutDocument` pure function.
expect(() => documentSchema.parse(v3Doc({ schemaVersion: 2 }))).toThrow();
@@ -415,7 +415,7 @@ describe("v4 -> v5 clip-anchored modifier migration", () => {
it("bumps the version and anchors a zoom wholly inside one clip", () => {
// After the migration hoist, v4 input runs through the load-time
- // upgrader before the pure v6 schema parse.
+ // upgrader before the pure v7 schema parse.
const doc = documentSchema.parse(
migrateRawDocumentToCurrent(
makeV4Doc({
@@ -425,7 +425,7 @@ describe("v4 -> v5 clip-anchored modifier migration", () => {
}),
),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect(doc.zoomRanges).toHaveLength(1);
const z = doc.zoomRanges[0];
expect(z).toMatchObject({ id: "z1", clipId: "clip_a", depth: 3 });
@@ -493,8 +493,8 @@ describe("v4 -> v5 clip-anchored modifier migration", () => {
expect(doc.zoomRanges[0].clipId).toBeUndefined();
});
- it("is idempotent — re-parsing an already-v6 document changes nothing", () => {
- // First call: v4 input → load-time upgrade → v6.
+ it("is idempotent — re-parsing an already-v7 document changes nothing", () => {
+ // First call: v4 input → load-time upgrade → v7.
const once = documentSchema.parse(
migrateRawDocumentToCurrent(
makeV4Doc({
@@ -505,7 +505,7 @@ describe("v4 -> v5 clip-anchored modifier migration", () => {
),
);
// Second call: already-current input, no upgrade needed; the parse is now a
- // pure v6 validation step.
+ // pure v7 validation step.
const twice = documentSchema.parse(once);
expect(twice).toEqual(once);
});
@@ -562,7 +562,7 @@ describe("v5 -> v6 native AspectRatio migration", () => {
}),
),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("16:9");
});
@@ -619,7 +619,7 @@ describe("v5 -> v6 native AspectRatio migration", () => {
legacyEditor: { aspectRatio: "native" },
}),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("9:16");
});
@@ -630,7 +630,7 @@ describe("v5 -> v6 native AspectRatio migration", () => {
const doc = documentSchema.parse(
migrateRawDocumentToCurrent(makeV5Doc({ legacyEditor: { aspectRatio: "native" } })),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("native");
});
@@ -638,7 +638,7 @@ describe("v5 -> v6 native AspectRatio migration", () => {
const doc = documentSchema.parse(
migrateRawDocumentToCurrent(makeV5Doc({ legacyEditor: { aspectRatio: "4:5" } })),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("4:5");
});
@@ -646,7 +646,7 @@ describe("v5 -> v6 native AspectRatio migration", () => {
const doc = documentSchema.parse(
migrateRawDocumentToCurrent(makeV5Doc({ legacyEditor: { someOtherField: "preserved" } })),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
const legacy = doc.legacyEditor as Record<string, unknown>;
expect(legacy.someOtherField).toBe("preserved");
expect(legacy.aspectRatio).toBeUndefined();
@@ -655,11 +655,11 @@ describe("v5 -> v6 native AspectRatio migration", () => {
it("passes through a v5 doc with no legacyEditor at all (only the version bumps)", () => {
const v5 = makeV5Doc();
const doc = documentSchema.parse(migrateRawDocumentToCurrent(v5));
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect(doc.legacyEditor).toBeNull();
});
- it("is idempotent — re-parsing an already-v6 document changes nothing", () => {
+ it("is idempotent — re-parsing an already-v7 document changes nothing", () => {
const once = documentSchema.parse(
migrateRawDocumentToCurrent(makeV5Doc({ legacyEditor: { aspectRatio: "16:9" } })),
);
@@ -709,7 +709,7 @@ describe("v5 -> v6 native AspectRatio migration", () => {
legacyEditor: { aspectRatio: "native" },
}),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("native");
});
@@ -751,7 +751,7 @@ describe("v5 -> v6 native AspectRatio migration", () => {
legacyEditor: { aspectRatio: "native" },
}),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("9:16");
});
@@ -795,7 +795,170 @@ describe("v5 -> v6 native AspectRatio migration", () => {
legacyEditor: { aspectRatio: "native" },
}),
);
- expect(doc.schemaVersion).toBe(6);
+ expect(doc.schemaVersion).toBe(7);
expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("8:9");
});
});
+
+// --- v6 -> v7 trim clip-anchor migration -------------------------------------
+// A v6 trim names only an asset, so on two clips over the same media it is ambiguous:
+// the transcript pane showed it twice, the ruler drew it on the first clip, and playback
+// cut it from both. The upgrade ventilates each stored trim into one anchored row per
+// clip it covers — a faithful restatement of what the document already rendered, but now
+// separately addressable so the user can delete the copy they did not mean.
+describe("v6 -> v7 trim clip-anchor migration", () => {
+ const v6Doc = (
+ clips: Array<Record<string, unknown>>,
+ trimRanges: Array<Record<string, unknown>>,
+ ) => ({
+ schemaVersion: 6,
+ project: {
+ id: "p",
+ title: "t",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ primaryAssetId: "asset_1",
+ },
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "rec.mp4",
+ originalPath: "/rec.mp4",
+ durationSec: 12,
+ cameraTrack: null,
+ },
+ ],
+ timeline: { clips, trimRanges },
+ });
+
+ const twoSharedClips = [
+ {
+ id: "clip_1",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 12,
+ timelineStartSec: 0,
+ timelineEndSec: 12,
+ origin: "user",
+ },
+ {
+ id: "clip_2",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 12,
+ timelineStartSec: 12,
+ timelineEndSec: 24,
+ origin: "user",
+ },
+ ];
+
+ const trimsOf = (raw: unknown) =>
+ ((raw as Record<string, unknown>).timeline as Record<string, unknown>).trimRanges as Array<
+ Record<string, unknown>
+ >;
+
+ it("anchors a trim to the single clip that covers it", () => {
+ const out = migrateRawDocumentToCurrent(
+ v6Doc(
+ [twoSharedClips[0]],
+ [{ id: "t1", assetId: "asset_1", startSec: 3, endSec: 5, origin: "user", reason: "" }],
+ ),
+ );
+ expect((out as Record<string, unknown>).schemaVersion).toBe(7);
+ expect(trimsOf(out)).toEqual([
+ {
+ id: "t1",
+ assetId: "asset_1",
+ clipId: "clip_1",
+ startSec: 3,
+ endSec: 5,
+ origin: "user",
+ reason: "",
+ },
+ ]);
+ });
+
+ it("ventilates into one row per covering clip, preserving what the document rendered", () => {
+ const out = migrateRawDocumentToCurrent(
+ v6Doc(twoSharedClips, [
+ { id: "t1", assetId: "asset_1", startSec: 3, endSec: 5, origin: "user", reason: "" },
+ ]),
+ );
+ const trims = trimsOf(out);
+ expect(trims).toHaveLength(2);
+ // The first row keeps the original id, so anything already holding it still resolves.
+ expect(trims[0]).toMatchObject({ id: "t1", clipId: "clip_1", startSec: 3, endSec: 5 });
+ expect(trims[1]).toMatchObject({ clipId: "clip_2", startSec: 3, endSec: 5 });
+ expect(trims[1].id).not.toBe("t1");
+ });
+
+ it("clamps each row to its own clip's source window", () => {
+ const out = migrateRawDocumentToCurrent(
+ v6Doc(
+ [
+ { ...twoSharedClips[0], sourceStartSec: 0, sourceEndSec: 6 },
+ { ...twoSharedClips[1], sourceStartSec: 6, sourceEndSec: 12 },
+ ],
+ [{ id: "t1", assetId: "asset_1", startSec: 4, endSec: 9, origin: "user", reason: "" }],
+ ),
+ );
+ expect(trimsOf(out).map((t) => [t.clipId, t.startSec, t.endSec])).toEqual([
+ ["clip_1", 4, 6],
+ ["clip_2", 6, 9],
+ ]);
+ });
+
+ it("keeps a trim that covers no clip rather than dropping user data", () => {
+ // `replaceTimeline` mints exactly these: the complement of the kept intervals, which
+ // lies outside every clip by construction.
+ const out = migrateRawDocumentToCurrent(
+ v6Doc(
+ [{ ...twoSharedClips[0], sourceStartSec: 0, sourceEndSec: 3 }],
+ [{ id: "t1", assetId: "asset_1", startSec: 8, endSec: 9, origin: "user", reason: "" }],
+ ),
+ );
+ expect(trimsOf(out)).toEqual([
+ { id: "t1", assetId: "asset_1", startSec: 8, endSec: 9, origin: "user", reason: "" },
+ ]);
+ });
+
+ it("leaves an unprobed clip's trims un-anchored (no real window to clamp against)", () => {
+ const out = migrateRawDocumentToCurrent(
+ v6Doc(
+ [{ ...twoSharedClips[0], sourceStartSec: 0, sourceEndSec: undefined }],
+ [{ id: "t1", assetId: "asset_1", startSec: 3, endSec: 5, origin: "user", reason: "" }],
+ ),
+ );
+ expect(trimsOf(out)[0].clipId).toBeUndefined();
+ });
+
+ it("is idempotent — an already-anchored trim is left alone", () => {
+ const once = migrateRawDocumentToCurrent(
+ v6Doc(twoSharedClips, [
+ { id: "t1", assetId: "asset_1", startSec: 3, endSec: 5, origin: "user", reason: "" },
+ ]),
+ );
+ expect(migrateRawDocumentToCurrent(once)).toEqual(once);
+ });
+
+ it("survives a malformed clip entry instead of failing the whole project load", () => {
+ const out = migrateRawDocumentToCurrent(
+ v6Doc(
+ [null as unknown as Record<string, unknown>, twoSharedClips[1]],
+ [{ id: "t1", assetId: "asset_1", startSec: 3, endSec: 5, origin: "user", reason: "" }],
+ ),
+ );
+ expect(trimsOf(out)).toEqual([
+ {
+ id: "t1",
+ assetId: "asset_1",
+ clipId: "clip_2",
+ startSec: 3,
+ endSec: 5,
+ origin: "user",
+ reason: "",
+ },
+ ]);
+ });
+});
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index 03810b907..ecc8e0daa 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -33,7 +33,12 @@ import { anchorRegionsWithDerivedMs } from "../timeline/timelineMap";
// actually known; otherwise it leaves the sentinel, which keeps resolving
// dynamically at runtime. See `upgradeV5DocumentToV6` for why guessing
// would corrupt v1.7 imports.
-export const axcutSchemaVersion = 6;
+// 6. v7 — trims join the v5 clip anchor: `AxcutTrimRange` gains `clipId`.
+// They were the last region kind still addressed by `assetId` alone, which
+// made them AMBIGUOUS the moment two clips drew from the same asset (a
+// duplicated clip): every reader either matched both clips or picked the
+// first. See `upgradeV6DocumentToV7`.
+export const axcutSchemaVersion = 7;
// ponytail: every region schema shares the same monotonicity rule
// (end >= start) with the same error shape. Factor the refine so the
@@ -199,10 +204,18 @@ export const rangeSchema = endGteStart(
// ponytail: trimRanges reference asset source-time (not timeline). trimRegions
// in v2 are the inverse — a skip = the region inside the source we DON'T keep.
+//
+// `startSec`/`endSec` ARE the source range of `clipAnchorShape` under their older
+// names, so a trim needs only `clipId` to become a complete v5 clip anchor. Optional
+// for the same reason it is on the other kinds: a trim that could not be anchored
+// (`upgradeV6DocumentToV7`) is kept, not dropped, and falls back to the historical
+// asset-wide matching. Everything that asks "does this trim apply to this clip?" must
+// go through `trimAppliesToClip` (timeline/trim-mapping) so the two rules stay one rule.
export const trimRangeSchema = endGteStart(
z.object({
id: z.string().min(1),
assetId: z.string().min(1),
+ clipId: z.string().min(1).optional(),
startSec: z.number().nonnegative(),
endSec: z.number().nonnegative(),
reason: z.string().default(""),
@@ -259,6 +272,10 @@ export const timelineOperationSchema = z.discriminatedUnion("type", [
type: z.literal("add_trim_range"),
reason: z.string().default(""),
assetId: z.string().min(1),
+ // Which clip the cut was authored on. Optional so callers that genuinely have no
+ // clip context still work, but every UI path knows it — without it a trim on the
+ // second clip of a duplicated asset is indistinguishable from one on the first.
+ clipId: z.string().min(1).optional(),
startSec: z.number().nonnegative(),
endSec: z.number().nonnegative(),
}),
@@ -657,6 +674,76 @@ function upgradeV5DocumentToV6(raw: unknown): unknown {
};
}
+/**
+ * v6 → v7 — trims become CLIP-ANCHORED, the last region kind that wasn't.
+ *
+ * A v6 trim says only "this source span of this asset is cut". That is unambiguous while
+ * one asset backs one clip, and ambiguous the moment it doesn't: with two clips over the
+ * same media every reader had to guess, and each guessed differently — the transcript pane
+ * showed the cut on BOTH clips, the ruler drew it on the FIRST, and playback/export removed
+ * the span from BOTH. Anchoring the trim to the clip it was authored on removes the guess.
+ *
+ * The upgrade VENTILATES rather than picks: a stored trim is replaced by one anchored entry
+ * per clip it currently covers, each clamped to that clip's source window. That is a
+ * faithful restatement of what the document already renders (a v6 trim really did cut every
+ * clip of its asset), so nothing about the output moves — but the entries are now separately
+ * addressable, which is what lets a user delete the copy on the clip they didn't mean.
+ * Mirrors `upgradeV4DocumentToV5`, which ventilated the other kinds the same way.
+ *
+ * A trim covering no clip is kept UNCHANGED rather than dropped — never lose user data.
+ * `replaceTimeline` mints exactly such trims (the inverted kept-intervals lie outside every
+ * clip by construction), and a document with no clips has nothing to anchor against.
+ * Un-anchored trims keep the v6 asset-wide behaviour via `trimAppliesToClip`.
+ */
+export function upgradeV6DocumentToV7(raw: unknown): unknown {
+ if (!raw || typeof raw !== "object") return raw;
+ const doc = raw as Record<string, unknown>;
+ if (doc.schemaVersion !== 6) return raw;
+
+ const timeline =
+ doc.timeline && typeof doc.timeline === "object" && !Array.isArray(doc.timeline)
+ ? (doc.timeline as Record<string, unknown>)
+ : null;
+ const trims = timeline && Array.isArray(timeline.trimRanges) ? timeline.trimRanges : null;
+ const clips = (timeline && Array.isArray(timeline.clips)
+ ? timeline.clips
+ : []) as unknown as AxcutClip[];
+ if (!timeline || !trims || clips.length === 0) return { ...doc, schemaVersion: 7 };
+
+ const anchored = trims.flatMap((entry) => {
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [entry];
+ const trim = entry as Record<string, unknown>;
+ // Already anchored (a re-run, or a doc written by a mixed-version chain): leave it.
+ if (typeof trim.clipId === "string") return [trim];
+ if (typeof trim.assetId !== "string") return [trim];
+ if (typeof trim.startSec !== "number" || typeof trim.endSec !== "number") return [trim];
+ const lo = Math.min(trim.startSec, trim.endSec);
+ const hi = Math.max(trim.startSec, trim.endSec);
+
+ const fragments = clips.flatMap((clip) => {
+ // `clips` is raw, untrusted input at this point (the schema parse runs after the
+ // upgrade chain), so a malformed entry must not take the whole project load down.
+ if (!clip || typeof clip !== "object" || typeof clip.id !== "string") return [];
+ if (clip.assetId !== trim.assetId) return [];
+ const clipEnd = clip.sourceEndSec ?? clip.sourceStartSec;
+ // An unprobed clip has no real window yet; anchoring against it would clamp the
+ // trim to nothing. Leave those to the un-anchored fallback (same reasoning as
+ // `rederiveRegionMs`, which refuses to clamp against an unprobed window).
+ if (clipEnd <= clip.sourceStartSec) return [];
+ const startSec = Math.max(lo, clip.sourceStartSec);
+ const endSec = Math.min(hi, clipEnd);
+ if (endSec <= startSec) return [];
+ return [{ ...trim, clipId: clip.id, startSec, endSec }];
+ });
+ if (fragments.length === 0) return [trim];
+ // The first fragment keeps the original id, so ids already held elsewhere (an undo
+ // entry, an in-flight `removeTrim`) still resolve; extras get fresh ones.
+ return fragments.map((f, i) => (i === 0 ? f : { ...f, id: createId("trim") }));
+ });
+
+ return { ...doc, schemaVersion: 7, timeline: { ...timeline, trimRanges: anchored } };
+}
+
/**
* Runs the whole upgrade chain on a raw, untrusted value. Idempotent: each step
* is gated on an exact `schemaVersion`, so an already-current document passes
@@ -668,16 +755,18 @@ function upgradeV5DocumentToV6(raw: unknown): unknown {
* not configure for the main bundle. Keep this module alias-free.
*/
export function migrateRawDocumentToCurrent(raw: unknown): unknown {
- return upgradeV5DocumentToV6(upgradeV4DocumentToV5(upgradeV3DocumentToV4(raw)));
+ return upgradeV6DocumentToV7(
+ upgradeV5DocumentToV6(upgradeV4DocumentToV5(upgradeV3DocumentToV4(raw))),
+ );
}
-// PURE v6 validation. Callers that read a document from disk (or any other
+// PURE v7 validation. Callers that read a document from disk (or any other
// source that might carry an older `schemaVersion`) MUST run
// `migrateRawDocumentToCurrent` on the raw value first. The previous
// implementation wrapped this schema in a `z.preprocess` that re-ran the whole
-// v3→v4→v5→v6 chain on EVERY parse, including in-memory parses of documents that
+// v3→…→v7 chain on EVERY parse, including in-memory parses of documents that
// were already current. Hoisting it to load time makes the in-memory parse a
-// single `z.literal(6)` + shape check.
+// single `z.literal(7)` + shape check.
export const documentSchema = documentSchemaShape;
export const createProjectInputSchema = z.object({
diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.ts
index a9ae6f026..278f8096d 100644
--- a/src/lib/ai-edition/store/projectStore.test.ts
+++ b/src/lib/ai-edition/store/projectStore.test.ts
@@ -36,11 +36,11 @@ const sampleDoc = {
// load site (DocumentService, browserShim) runs `migrateRawDocumentToCurrent`
// before returning, and the renderer's `parseDocument` is a pure v6
// validator. Test fixtures model the post-hoist contract.
- // `as const` and not a bare 6: the document type pins this field to the
- // LITERAL 6, and an unannotated object literal widens it to `number` — so
+ // `as const` and not a bare 7: the document type pins this field to the
+ // LITERAL 7, and an unannotated object literal widens it to `number` — so
// every `document: sampleDoc` below fails to type-check for a fixture that
// is, in fact, exactly right.
- schemaVersion: 6 as const,
+ schemaVersion: 7 as const,
project: {
id: "proj_test",
title: "Test",
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index e6fb3632c..ebeeacc37 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -53,7 +53,7 @@ const sampleDoc = {
// load site (DocumentService, browserShim) runs `migrateRawDocumentToCurrent`
// before returning, and the renderer's `parseDocument` is a pure v6
// validator. Test fixtures model the post-hoist contract.
- schemaVersion: 6,
+ schemaVersion: 7,
project: {
id: "proj_test",
title: "Test",
@@ -350,7 +350,7 @@ describe("useTimeline.updateClipSourceRange (Edit-clip modal)", () => {
projectId: "proj_test",
document: {
...sampleDoc,
- schemaVersion: 6,
+ schemaVersion: 7,
zoomRanges: [anchoredZoom("z_keep", 2, 3), anchoredZoom("z_drop", 6, 8)],
} as unknown as typeof sampleDoc,
revision: 1,
@@ -396,7 +396,7 @@ describe("useTimeline.updateClipSourceRange (Edit-clip modal)", () => {
useProjectStore.setState({
document: {
...sampleDoc,
- schemaVersion: 6,
+ schemaVersion: 7,
zoomRanges: [anchoredZoom("z_edge", 3, 7)],
} as unknown as typeof sampleDoc,
});
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index c2d702f80..ba20250d8 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -27,7 +27,7 @@ import {
replacePillSpan,
resolvePillIds,
} from "../timeline/timelineMap";
-import { resolveTimelineSpanToTrim } from "../timeline/trim-mapping";
+import { dropTrimPillsByIds, resolveTimelineSpanToTrim } from "../timeline/trim-mapping";
import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions";
import { useProjectStore } from "./projectStore";
@@ -233,6 +233,10 @@ export function useTimeline() {
{
id: createId("trim"),
assetId: resolved?.assetId ?? asset!.id,
+ // The carrier clip, so the cut lands on THAT clip and not on every clip
+ // sharing its media (see `trimAppliesToClip`). Absent only in the
+ // no-clip fallback below, where there is no clip to name.
+ ...(resolved ? { clipId: resolved.clipId } : {}),
startSec: resolved?.sourceStartSec ?? playhead,
endSec: resolved?.sourceEndSec ?? playhead + 2,
reason: "manual",
@@ -338,12 +342,17 @@ export function useTimeline() {
await saveDocument(next);
}, [document, saveDocument]);
- // Like updateTrimRange but also re-attaches the trim to a (possibly
- // different) asset — needed when a trim is dragged across a clip boundary
- // onto a clip backed by another asset. Callers resolve the timeline span to
- // { assetId, sourceStartSec, sourceEndSec } via resolveTimelineSpanToTrim.
+ // Like updateTrimRange but also re-attaches the trim to a (possibly different) CLIP —
+ // needed when a trim is dragged across a clip boundary, whether or not the landing clip
+ // is backed by another asset. Re-pointing `clipId` as well as `assetId` is what makes a
+ // drag onto the second clip of a duplicated asset actually move the cut instead of
+ // leaving it on the first (the two are indistinguishable by asset + source range alone).
+ // Callers resolve the timeline span via `resolveTimelineSpanToTrim`.
const updateTrim = useCallback(
- async (trimId: string, next: { assetId: string; startSec: number; endSec: number }) => {
+ async (
+ trimId: string,
+ next: { assetId: string; clipId?: string; startSec: number; endSec: number },
+ ) => {
if (!document) return;
const s = finiteSec(next.startSec);
const e = finiteSec(next.endSec);
@@ -353,7 +362,13 @@ export function useTimeline() {
...document.timeline,
trimRanges: document.timeline.trimRanges.map((r) =>
r.id === trimId
- ? { ...r, assetId: next.assetId, startSec: Math.min(s, e), endSec: Math.max(s, e) }
+ ? {
+ ...r,
+ assetId: next.assetId,
+ clipId: next.clipId,
+ startSec: Math.min(s, e),
+ endSec: Math.max(s, e),
+ }
: r,
),
},
@@ -374,6 +389,7 @@ export function useTimeline() {
entries: Array<{
id: string;
assetId: string;
+ clipId?: string;
sourceStartSec: number;
sourceEndSec: number;
}>,
@@ -390,6 +406,10 @@ export function useTimeline() {
return {
id: e.id,
assetId: e.assetId,
+ // Ventilation names the covered clip per entry; carrying it through is what
+ // keeps a drag over two clips of the SAME media as two distinct cuts rather
+ // than one that lands on both.
+ clipId: e.clipId,
startSec: Math.min(s, en),
endSec: Math.max(s, en),
reason: prev?.reason ?? "manual",
@@ -680,7 +700,14 @@ export function useTimeline() {
annotations: dropPillsByIds(document.annotations, annotationIds),
timeline: {
...document.timeline,
- trimRanges: document.timeline.trimRanges.filter((s) => !trimIds.has(s.id)),
+ // Whole-pill delete, same as the zoom/annotation lines above — a trim grown
+ // across a clip boundary is 2+ rows rendering as one stripe, and a bare id
+ // filter left the halves the selection didn't name still cutting.
+ trimRanges: dropTrimPillsByIds(
+ document.timeline.trimRanges,
+ document.timeline.clips,
+ trimIds,
+ ),
},
legacyEditor:
speedIds.size > 0 || cameraFullscreenIds.size > 0
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.test.ts b/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
index 1956121bb..61e8c359e 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
@@ -3,6 +3,7 @@ import type { AxcutAsset, AxcutClip, AxcutTranscript, AxcutTrimRange } from "../
import {
buildAggregatedSections,
buildClipSection,
+ clipWordId,
findCueWordId,
isSilenceWord,
} from "./aggregated-transcript";
@@ -39,12 +40,15 @@ function makeTranscript(words: AxcutTranscript["words"]): AxcutTranscript {
function makeTrim(overrides: Partial<AxcutTrimRange>): AxcutTrimRange {
return {
- id: overrides.id ?? "trim_1",
- assetId: overrides.assetId ?? "asset_1",
- startSec: overrides.startSec ?? 0,
- endSec: overrides.endSec ?? 0,
- origin: overrides.origin ?? "user",
- reason: overrides.reason ?? "",
+ id: "trim_1",
+ assetId: "asset_1",
+ startSec: 0,
+ endSec: 0,
+ origin: "user",
+ reason: "",
+ // Spread, not a field-by-field pick: the pick silently dropped any field it did
+ // not name, so `clipId` never reached the code under test.
+ ...overrides,
};
}
@@ -120,6 +124,56 @@ describe("buildClipSection", () => {
});
});
+ // The repro: one media, two clips, same source window. `assetId` + source overlap
+ // matches both, so before trims carried a clip anchor the cut showed up on the clip
+ // the user never touched — and the bin icon on that phantom run deleted the real one.
+ describe("two clips over the same media", () => {
+ const words = () => [
+ { id: "w1", segmentId: "s1", startSec: 0, endSec: 1, text: "a" },
+ { id: "w2", segmentId: "s1", startSec: 1, endSec: 2, text: "b" },
+ { id: "w3", segmentId: "s1", startSec: 2, endSec: 3, text: "c" },
+ ];
+ const clip1 = () => makeClip({ id: "clip_1", sourceStartSec: 0, sourceEndSec: 3 });
+ const clip2 = () =>
+ makeClip({
+ id: "clip_2",
+ sourceStartSec: 0,
+ sourceEndSec: 3,
+ timelineStartSec: 3,
+ timelineEndSec: 6,
+ });
+
+ it("marks the words removed only in the clip the trim is anchored to", () => {
+ const trim = makeTrim({ id: "trim_c2", clipId: "clip_2", startSec: 1, endSec: 2 });
+ const sections = buildAggregatedSections(
+ [clip1(), clip2()],
+ [makeTranscript(words())],
+ [makeAsset()],
+ [trim],
+ );
+
+ expect(sections[0].words.map((cw) => cw.kept)).toEqual([true, true, true]);
+ expect(sections[0].trimRuns).toHaveLength(0);
+ expect(sections[1].words.map((cw) => cw.kept)).toEqual([true, false, true]);
+ expect(sections[1].trimRuns).toHaveLength(1);
+ expect(sections[1].trimRuns[0]).toMatchObject({ trimId: "trim_c2", startWordIndex: 1 });
+ });
+
+ it("still marks both clips for a pre-v7 trim that names no clip", () => {
+ // Back-compat: an un-anchored row keeps the asset-wide meaning it had, so an
+ // existing document reads exactly as it did before the anchor was introduced.
+ const trim = makeTrim({ id: "trim_legacy", startSec: 1, endSec: 2 });
+ const sections = buildAggregatedSections(
+ [clip1(), clip2()],
+ [makeTranscript(words())],
+ [makeAsset()],
+ [trim],
+ );
+ expect(sections[0].trimRuns).toHaveLength(1);
+ expect(sections[1].trimRuns).toHaveLength(1);
+ });
+ });
+
it("does NOT apply trims from a different asset", () => {
const clip = makeClip({ sourceStartSec: 0, sourceEndSec: 3 });
const transcript = makeTranscript([
@@ -278,6 +332,7 @@ describe("findCueWordId", () => {
asset: makeAsset({ id: assetId }),
transcript: null,
words: wordTimes.map(([id, start, end]) => ({
+ id: clipWordId(clipId, id),
word: { id, segmentId: "s1", startSec: start, endSec: end, text: id },
kept: true,
trimId: null,
@@ -303,7 +358,7 @@ describe("findCueWordId", () => {
["w2", 1, 2],
["w3", 2, 3],
]);
- expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 1.5 })).toBe("w2");
+ expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 1.5 })).toBe("c1:w2");
});
it("returns the previous word when the cue is between two words", () => {
@@ -311,7 +366,7 @@ describe("findCueWordId", () => {
["w1", 0, 1],
["w2", 2, 3],
]);
- expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 1.5 })).toBe("w1");
+ expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 1.5 })).toBe("c1:w1");
});
it("returns the previous word when the cue is before the first word", () => {
@@ -327,6 +382,94 @@ describe("findCueWordId", () => {
["w1", 0, 1],
["w2", 1, 2],
]);
- expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 99 })).toBe("w2");
+ expect(findCueWordId([section], { assetId: "asset_1", sourceTimeSec: 99 })).toBe("c1:w2");
+ });
+
+ // Two clips over the same media project the SAME transcript words twice, so the cue
+ // has to be resolved against the clip that is actually playing. Matching on assetId
+ // alone always returned the first section — the highlight tracked clip 1 forever.
+ describe("two clips over the same media", () => {
+ const sections = () => [
+ makeSection("c1", "asset_1", [
+ ["w1", 0, 1],
+ ["w2", 1, 2],
+ ]),
+ makeSection("c2", "asset_1", [
+ ["w1", 0, 1],
+ ["w2", 1, 2],
+ ]),
+ ];
+
+ it("resolves the cue against the clip that is playing", () => {
+ expect(
+ findCueWordId(sections(), { assetId: "asset_1", clipId: "c2", sourceTimeSec: 1.5 }),
+ ).toBe("c2:w2");
+ expect(
+ findCueWordId(sections(), { assetId: "asset_1", clipId: "c1", sourceTimeSec: 1.5 }),
+ ).toBe("c1:w2");
+ });
+
+ it("returns an id that cannot match the other clip's copy of the same word", () => {
+ const cue = findCueWordId(sections(), {
+ assetId: "asset_1",
+ clipId: "c2",
+ sourceTimeSec: 1.5,
+ });
+ // The whole point: `word.id` is "w2" in BOTH sections, so a bare word id lit up
+ // both blocks. Exactly one rendered word may claim the cue.
+ const claiming = sections().flatMap((s) => s.words.filter((cw) => cw.id === cue));
+ expect(claiming).toHaveLength(1);
+ });
+
+ it("falls back to the asset when the caller names no clip", () => {
+ expect(findCueWordId(sections(), { assetId: "asset_1", sourceTimeSec: 1.5 })).toBe("c1:w2");
+ });
+
+ it("returns null rather than another clip's words when the playing clip has none", () => {
+ const withEmptyC2 = [sections()[0], makeSection("c2", "asset_1", [])];
+ expect(
+ findCueWordId(withEmptyC2, { assetId: "asset_1", clipId: "c2", sourceTimeSec: 1.5 }),
+ ).toBeNull();
+ });
+ });
+});
+
+describe("clipWordId", () => {
+ it("separates the same transcript word rendered in two clips", () => {
+ expect(clipWordId("clip_1", "w1")).not.toBe(clipWordId("clip_2", "w1"));
+ });
+
+ it("separates the per-clip silence tokens, which collide for ANY two clips", () => {
+ // `withSilenceGaps` numbers silences from 1 within each clip, so `silence_1` exists
+ // in every section — unrelated assets included.
+ expect(clipWordId("clip_1", "silence_1")).not.toBe(clipWordId("clip_2", "silence_1"));
+ });
+
+ it("gives buildClipSection words ids unique across the whole pane", () => {
+ const transcript = makeTranscript([
+ { id: "w1", segmentId: "s1", startSec: 0, endSec: 1, text: "a" },
+ // 1s gap → a `silence_1` pseudo-word in each section.
+ { id: "w2", segmentId: "s1", startSec: 2, endSec: 3, text: "b" },
+ ]);
+ const sections = buildAggregatedSections(
+ [
+ makeClip({ id: "clip_1", sourceStartSec: 0, sourceEndSec: 3 }),
+ makeClip({
+ id: "clip_2",
+ sourceStartSec: 0,
+ sourceEndSec: 3,
+ timelineStartSec: 3,
+ timelineEndSec: 6,
+ }),
+ ],
+ [transcript],
+ [makeAsset()],
+ [],
+ );
+ const rawIds = sections.flatMap((s) => s.words.map((cw) => cw.word.id));
+ const scopedIds = sections.flatMap((s) => s.words.map((cw) => cw.id));
+ // The raw ids collide across the two sections; the scoped ones do not.
+ expect(new Set(rawIds).size).toBeLessThan(rawIds.length);
+ expect(new Set(scopedIds).size).toBe(scopedIds.length);
});
});
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.ts b/src/lib/ai-edition/timeline/aggregated-transcript.ts
index fed4f7490..1a35e9e61 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.ts
@@ -15,6 +15,7 @@
// kept word; the user or the LLM decides what to mark as skipped.
import type { AxcutAsset, AxcutClip, AxcutTranscript, AxcutTrimRange, AxcutWord } from "../schema";
+import { trimAppliesToClip } from "./trim-mapping";
/** Gaps between words at least this long are surfaced as a `[silence]` token. */
export const SILENCE_THRESHOLD_SEC = 0.2;
@@ -77,8 +78,25 @@ export interface TrimRun {
durationSec: number;
}
+/**
+ * This word AS RENDERED IN THIS CLIP. A transcript belongs to an ASSET, so two clips over
+ * the same media project the very same `AxcutWord` twice; `word.id` therefore identifies
+ * a moment in the media, never a thing on screen. Anything that points AT the rendered
+ * word — the React key, `data-word-id`, the cue highlight, the caret anchor — must use
+ * this instead, or it addresses both copies at once.
+ *
+ * Silence pseudo-words make this unconditional rather than a shared-media special case:
+ * `withSilenceGaps` numbers them from 1 per clip, so `silence_1` collides between ANY two
+ * clips, related assets or not.
+ */
+export function clipWordId(clipId: string, wordId: string): string {
+ return `${clipId}:${wordId}`;
+}
+
/** One word in the clip's source range, tagged kept / removed. */
export interface ClipWord {
+ /** {@link clipWordId} — the word's identity *in this clip*, unique across the pane. */
+ id: string;
word: AxcutWord;
/** Whether the word is inside a trimRange for this clip's asset. */
kept: boolean;
@@ -120,9 +138,12 @@ export function buildClipSection(
asset: AxcutAsset | null,
trimRanges: AxcutTrimRange[],
): ClipSection {
+ // `trimAppliesToClip` — not a bare `assetId` match — is what keeps a cut on the
+ // second of two clips over the same media from also greying out the first one's
+ // words. Same media, same source range: only the clip anchor tells them apart.
const clipTrims = trimRanges.filter(
(trim) =>
- trim.assetId === clip.assetId &&
+ trimAppliesToClip(trim, clip) &&
trim.endSec > clip.sourceStartSec &&
trim.startSec < (clip.sourceEndSec ?? Infinity),
);
@@ -137,6 +158,7 @@ export function buildClipSection(
const tagged: ClipWord[] = words.map((word) => {
const covering = findCoveringTrim(word, clipTrims);
return {
+ id: clipWordId(clip.id, word.id),
word,
kept: covering === null,
trimId: covering?.id ?? null,
@@ -213,41 +235,47 @@ export function buildAggregatedSections(
/** Where the playback head currently is, in source time. */
export interface CuePosition {
assetId: string;
- /** Optional clip id filter (lets the caller restrict to a single clip). */
+ /** Which clip is playing — the primary selector for the cue's section. Source time is
+ * per asset, so `assetId` cannot separate two clips over one media; pass this whenever
+ * the caller knows it (the transcript pane always does). */
clipId?: string;
sourceTimeSec: number;
}
/**
- * Find the word in `sections` that the playback head is currently inside.
- * Used to highlight the active word and auto-scroll the transcript. Mirrors
- * axcut's `findCueWordId` in CurrentTranscriptView.
+ * Find the word in `sections` that the playback head is currently inside, as a
+ * {@link clipWordId} — NOT a bare `word.id`, which would name the same moment in every
+ * clip drawing on that media and light up all of them. Used to highlight the active word
+ * and auto-scroll the transcript. Mirrors axcut's `findCueWordId` in CurrentTranscriptView.
*
* - If the head is before the first word → null.
* - If the head is between two words → the previous word (so the
* highlight "sticks" until the next word starts).
* - Silence tokens (id starts with `silence_`) are skipped over so a
* long pause doesn't surface a fake cue word.
+ *
+ * The section is chosen by `cue.clipId` when the caller knows which clip is playing.
+ * Matching on `assetId` alone always resolved to the FIRST section of that asset, so with
+ * a clip duplicated on the timeline the cue tracked clip 1 while clip 2 played. `assetId`
+ * stays as the fallback for callers that have no clip in hand.
*/
export function findCueWordId(sections: ClipSection[], cue: CuePosition | null): string | null {
if (!cue) return null;
- const assetMatch = sections
- .filter((s) => s.words.length > 0)
- .find((s) => s.clip.assetId === cue.assetId);
- if (!assetMatch) return null;
- // ponytail: clipId is part of the cue position for future use, but the
- // word-id projection already encodes clipId in the prefix; the
- // current iteration just walks every word in the asset. If we need
- // clip-scoped lookup later, store the clip id on each ClipWord.
- const pool = assetMatch.words;
+ const withWords = sections.filter((s) => s.words.length > 0);
+ // No fallback when `clipId` is given but that clip has no transcript: the playing clip
+ // simply has no cue word, and borrowing another clip's would point at the wrong text.
+ const match = cue.clipId
+ ? withWords.find((s) => s.clip.id === cue.clipId)
+ : withWords.find((s) => s.clip.assetId === cue.assetId);
+ if (!match) return null;
const t = cue.sourceTimeSec;
let previous: string | null = null;
- for (const cw of pool) {
- if (cw.word.id.startsWith("silence_")) continue;
+ for (const cw of match.words) {
+ if (isSilenceWord(cw.word)) continue;
if (t < cw.word.startSec) return previous;
- if (t >= cw.word.startSec && t <= cw.word.endSec) return cw.word.id;
- previous = cw.word.id;
+ if (t >= cw.word.startSec && t <= cw.word.endSec) return cw.id;
+ previous = cw.id;
}
return previous;
}
diff --git a/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts b/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts
new file mode 100644
index 000000000..2789dd5e5
--- /dev/null
+++ b/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts
@@ -0,0 +1,96 @@
+// Cross-layer regression for the one bug class the unit tests can each only see a
+// third of: a scene with TWO clips over the SAME media. Source time is per asset, so
+// the two clips share a coordinate space, and a cut authored on the second used to be
+// read back differently by every consumer — struck through in BOTH transcript blocks,
+// drawn on the FIRST clip's ruler, and removed from BOTH clips in playback/export.
+//
+// This walks one trim through the real pipeline (`applyTimelineOperation` → the three
+// readers) and asserts they agree. The per-layer unit tests live next to each layer;
+// what this file adds is that they still agree with each other.
+import { describe, expect, it } from "vitest";
+import { applyTimelineOperation } from "@/lib/ai-edition/document/operations";
+import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
+import { type AxcutDocument, createEmptyDocument } from "@/lib/ai-edition/schema";
+import { buildAggregatedSections } from "@/lib/ai-edition/timeline/aggregated-transcript";
+import { coalescedTrimGroups } from "@/lib/ai-edition/timeline/trim-mapping";
+
+function doc(): AxcutDocument {
+ const base = createEmptyDocument({ title: "repro", projectId: "p" });
+ const asset = {
+ id: "asset_1",
+ kind: "video" as const,
+ label: "recording-1785529823210.mp4",
+ originalPath: "/rec.mp4",
+ durationSec: 11.8,
+ cameraTrack: null,
+ };
+ const clip = (id: string, at: number) => ({
+ id,
+ assetId: asset.id,
+ sourceStartSec: 0,
+ sourceEndSec: 11.8,
+ timelineStartSec: at,
+ timelineEndSec: at + 11.8,
+ wordRefs: [],
+ origin: "user" as const,
+ reason: "",
+ });
+ return {
+ ...base,
+ project: { ...base.project, primaryAssetId: asset.id },
+ assets: [asset],
+ transcripts: [
+ {
+ assetId: asset.id,
+ language: "fr",
+ segments: [],
+ words: [
+ { id: "w1", segmentId: "s", startSec: 1.3, endSec: 3.0, text: "Salut, comment ça va ?" },
+ { id: "w2", segmentId: "s", startSec: 3.4, endSec: 5.0, text: "Ben voilà, c'est tout ?" },
+ { id: "w3", segmentId: "s", startSec: 5.0, endSec: 6.7, text: "Ben voilà." },
+ { id: "w4", segmentId: "s", startSec: 8.4, endSec: 10.4, text: "*sifflement*" },
+ ],
+ },
+ ],
+ timeline: { ...base.timeline, clips: [clip("clip_1", 0), clip("clip_2", 11.8)] },
+ };
+}
+
+describe("repro: trim on clip 2 of two clips sharing one media", () => {
+ it("lands on clip 2 only, in the transcript, on the ruler and in playback", () => {
+ // The user selects "*sifflement*" in CLIP 2's block and hits Delete.
+ const next = applyTimelineOperation(doc(), {
+ type: "add_trim_range",
+ assetId: "asset_1",
+ clipId: "clip_2",
+ startSec: 8.4,
+ endSec: 10.4,
+ reason: "Skip from transcript",
+ }).document;
+
+ // 1. Transcript pane — the word is struck through in clip 2's block, and ONLY there.
+ const sections = buildAggregatedSections(
+ next.timeline.clips,
+ next.transcripts,
+ next.assets,
+ next.timeline.trimRanges,
+ );
+ expect(sections[0].trimRuns).toHaveLength(0);
+ expect(sections[1].trimRuns).toHaveLength(1);
+ expect(sections[0].words.filter((w) => !w.kept)).toHaveLength(0);
+ expect(sections[1].words.filter((w) => !w.kept).map((w) => w.word.text)).toEqual([
+ "*sifflement*",
+ ]);
+
+ // 2. Ruler — one pill, over clip 2 (timeline 11.8 + 8.4 = 20.2 … 22.2).
+ const pills = coalescedTrimGroups(next.timeline.trimRanges, next.timeline.clips);
+ expect(pills).toHaveLength(1);
+ expect(pills[0].start).toBeCloseTo(20.2, 6);
+ expect(pills[0].end).toBeCloseTo(22.2, 6);
+
+ // 3. Playback / export — clip 1 whole, clip 2 split around the cut.
+ const segs = resolvePlaybackSegments(next.timeline.clips, next.timeline.trimRanges);
+ expect(segs.map((s) => s.id)).toEqual(["clip_1", "clip_2_seg1", "clip_2_seg2"]);
+ expect(segs.at(-1)?.timelineEndSec).toBeCloseTo(21.6, 6); // 23.6 − 2s cut, once.
+ });
+});
diff --git a/src/lib/ai-edition/timeline/trim-mapping.test.ts b/src/lib/ai-edition/timeline/trim-mapping.test.ts
index 9f50fe7ca..3ac5cba00 100644
--- a/src/lib/ai-edition/timeline/trim-mapping.test.ts
+++ b/src/lib/ai-edition/timeline/trim-mapping.test.ts
@@ -101,6 +101,7 @@ describe("resolveTimelineSpanToTrim", () => {
// Timeline 18..20 falls in c2 (asset b) → source 16 + (18-14)=20 .. 22.
expect(resolveTimelineSpanToTrim(18, 20, clips)).toEqual({
assetId: "b",
+ clipId: "c2",
sourceStartSec: 20,
sourceEndSec: 22,
});
@@ -152,6 +153,7 @@ describe("resolveTimelineSpanToTrim", () => {
// Span 10..20 starts in c1; end clamps to c1's end (timeline 14 → source 14).
expect(resolveTimelineSpanToTrim(10, 20, clips)).toEqual({
assetId: "a",
+ clipId: "c1",
sourceStartSec: 10,
sourceEndSec: 14,
});
@@ -219,16 +221,16 @@ describe("ventilateTimelineSpanToTrims", () => {
it("stays a single source range inside one clip (matches resolveTimelineSpanToTrim)", () => {
expect(ventilateTimelineSpanToTrims(2, 4, clips)).toEqual([
- { assetId: "a", sourceStartSec: 2, sourceEndSec: 4 },
+ { assetId: "a", clipId: "c1", sourceStartSec: 2, sourceEndSec: 4 },
]);
});
it("splits a span across a clip boundary into one source range per clip", () => {
// Timeline 10..20 covers c1 (10..14) and c2 (14..20).
expect(ventilateTimelineSpanToTrims(10, 20, clips)).toEqual([
- { assetId: "a", sourceStartSec: 10, sourceEndSec: 14 },
+ { assetId: "a", clipId: "c1", sourceStartSec: 10, sourceEndSec: 14 },
// c2: source 16 + (14-14)=16 .. 16 + (20-14)=22.
- { assetId: "b", sourceStartSec: 16, sourceEndSec: 22 },
+ { assetId: "b", clipId: "c2", sourceStartSec: 16, sourceEndSec: 22 },
]);
});
@@ -339,3 +341,80 @@ describe("coalescedTrimGroups", () => {
expect(coalescedTrimGroups(trims, clips)).toEqual([{ ids: ["t1"], start: 3, end: 5 }]);
});
});
+
+// The reported bug, at the ruler: two clips over the SAME media with the SAME source
+// window. Source time is per asset, so it cannot separate them — only `clipId` can.
+// Every earlier fixture in this file sidesteps the ambiguity by giving the two clips
+// disjoint source ranges, which is exactly why none of them caught this.
+describe("two clips sharing one asset over the same source window", () => {
+ const sharedClips = () => [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 12,
+ timelineStartSec: 0,
+ timelineEndSec: 12,
+ }),
+ clip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 12,
+ timelineStartSec: 12,
+ timelineEndSec: 24,
+ }),
+ ];
+
+ it("maps a trim anchored to the second clip onto the SECOND clip's ruler span", () => {
+ // Without the anchor this returned {3,5} — the first clip — because the loop
+ // stopped at the first clip whose asset and source window matched.
+ expect(
+ trimToTimelineSpan({ assetId: "a", clipId: "c2", startSec: 3, endSec: 5 }, sharedClips()),
+ ).toEqual({ start: 15, end: 17 });
+ });
+
+ it("keeps mapping an un-anchored trim to the first matching clip (pre-v7 behaviour)", () => {
+ expect(trimToTimelineSpan({ assetId: "a", startSec: 3, endSec: 5 }, sharedClips())).toEqual({
+ start: 3,
+ end: 5,
+ });
+ });
+
+ it("draws one pill per clip when each clip carries its own trim", () => {
+ const trims = [
+ trim({ id: "t1", assetId: "a", clipId: "c1", startSec: 3, endSec: 5 }),
+ trim({ id: "t2", assetId: "a", clipId: "c2", startSec: 3, endSec: 5 }),
+ ];
+ // Two pills, 12s apart — not one merged pill, and not two stacked on c1.
+ expect(coalescedTrimGroups(trims, sharedClips())).toEqual([
+ { ids: ["t1"], start: 3, end: 5 },
+ { ids: ["t2"], start: 15, end: 17 },
+ ]);
+ });
+
+ it("drops an anchored trim whose clip is gone even though a twin clip remains", () => {
+ // The twin still uses the same asset over the same source range, so an asset-only
+ // match would resurrect the cut on it.
+ const trims = [trim({ id: "orphan", assetId: "a", clipId: "c2", startSec: 3, endSec: 5 })];
+ expect(coalescedTrimGroups(trims, [sharedClips()[0]])).toEqual([]);
+ });
+
+ it("still shows a pill when the anchor clip was re-cut past the trim's start", () => {
+ // c2 narrowed to source [4,12]: the trim [3,5] still cuts [4,5] of it, so the
+ // ruler has to show that remainder rather than hiding a cut the user can't undo.
+ const clips = [
+ clip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 4,
+ sourceEndSec: 12,
+ timelineStartSec: 0,
+ timelineEndSec: 8,
+ }),
+ ];
+ expect(
+ trimToTimelineSpan({ assetId: "a", clipId: "c2", startSec: 3, endSec: 5 }, clips),
+ ).toEqual({ start: 0, end: 1 });
+ });
+});
diff --git a/src/lib/ai-edition/timeline/trim-mapping.ts b/src/lib/ai-edition/timeline/trim-mapping.ts
index a0415907f..98ba9f68a 100644
--- a/src/lib/ai-edition/timeline/trim-mapping.ts
+++ b/src/lib/ai-edition/timeline/trim-mapping.ts
@@ -1,13 +1,18 @@
// Timeline↔source mapping for trim ranges.
//
-// Trims are stored in the DSL in *source-time per asset*
-// (AxcutTrimRange = { assetId, startSec, endSec }) — that's the single source
-// of truth the agent's `add_trim_range` op and the exporter read. But in the
-// editor UI the user manipulates them on the timeline ruler, in *timeline
+// Trims are stored in the DSL in *source time, anchored to one clip*
+// (AxcutTrimRange = { assetId, clipId?, startSec, endSec }) — that's the single
+// source of truth the agent's `add_trim_range` op and the exporter read. But in
+// the editor UI the user manipulates them on the timeline ruler, in *timeline
// (virtual) time*, exactly like zoom/speed/annotation regions. These pure
// helpers bridge the two so the DSL stays source-time while the UI treats
// trims as first-class timeline regions that can be dragged/resized freely
// across the ruler and re-attach to whichever clip they land on.
+//
+// `clipId` is the v7 addition and it is what makes the mapping single-valued.
+// Source time alone is per ASSET, so two clips over the same media (a duplicated
+// clip) share a coordinate space: without the anchor, "which clip is this cut on?"
+// had no answer and each caller invented its own. See `trimAppliesToClip`.
import type { AxcutClip, AxcutTrimRange } from "../schema";
import { type CoalescedSpan, ventilateSpanAcrossClips } from "./region-ventilation";
@@ -18,21 +23,57 @@ function clipSourceLen(clip: AxcutClip): number {
return (clip.sourceEndSec ?? clip.sourceStartSec) - clip.sourceStartSec;
}
+/** The identifying part of a trim: everything "which clip is this cut on?" may consult. */
+export type TrimAnchor = Pick<AxcutTrimRange, "assetId" | "startSec" | "endSec"> & {
+ clipId?: string;
+};
+
+/**
+ * THE rule for "does this cut belong to this clip?" — one definition, because the bug this
+ * replaces was three call sites each answering it differently.
+ *
+ * A v7 trim carries `clipId` and belongs to exactly that clip. That matters as soon as two
+ * clips draw from the SAME asset (a duplicated clip, or the same recording placed twice):
+ * `assetId` + source overlap then matches both, and every reader that used it either showed
+ * the cut twice (transcript pane), drew it on the wrong clip (ruler), or removed the span
+ * from both (playback / export).
+ *
+ * A trim with no `clipId` is pre-v7 or genuinely un-anchorable (`upgradeV6DocumentToV7`
+ * keeps those rather than dropping them). It keeps the historical asset-wide meaning, so
+ * old documents render exactly as they did.
+ */
+export function trimAppliesToClip(trim: TrimAnchor, clip: AxcutClip): boolean {
+ if (trim.clipId !== undefined) return trim.clipId === clip.id;
+ return trim.assetId === clip.assetId;
+}
+
/**
- * Map a source-time trim to its span on the timeline, through the clip that
- * carries it (matches the source range of the trim's asset). Returns null when
- * no clip currently carries the trim's source region (e.g. the clip was trimmed
- * away) — such a trim is simply not shown on the ruler.
+ * Map a source-time trim to its span on the timeline, through the clip that carries it.
+ * An anchored trim resolves through its OWN clip (`trimAppliesToClip`); an un-anchored one
+ * falls back to the first clip of its asset whose source range contains the trim's start.
+ * Returns null when no clip currently carries the trim's source region (e.g. the anchor
+ * clip was deleted, or the range was trimmed away) — such a trim is not shown on the ruler.
+ *
+ * The two branches test the clip differently, on purpose. An UN-ANCHORED trim uses
+ * containment of its start, because that test is doing the disambiguation: it is what
+ * picks one clip out of the asset's several. An ANCHORED trim already names its clip, so
+ * containment would only be a second, stricter question — and a harmful one: a clip re-cut
+ * to start after the trim begins would drop the pill while `resolvePlaybackSegments` went
+ * on cutting the overlap, leaving content removed with nothing on the ruler to click.
+ * Overlap keeps the two in agreement; the mapping below clamps the edges either way.
*/
export function trimToTimelineSpan(
- trim: Pick<AxcutTrimRange, "assetId" | "startSec" | "endSec">,
+ trim: TrimAnchor,
clips: AxcutClip[],
): { start: number; end: number } | null {
for (const c of clips) {
- if (c.assetId !== trim.assetId) continue;
+ if (!trimAppliesToClip(trim, c)) continue;
const srcEnd = c.sourceEndSec ?? c.sourceStartSec;
- // Anchor on the trim's start falling inside this clip's source range.
- if (trim.startSec >= c.sourceStartSec && trim.startSec <= srcEnd) {
+ const carries =
+ trim.clipId !== undefined
+ ? trim.endSec > c.sourceStartSec && trim.startSec < srcEnd
+ : trim.startSec >= c.sourceStartSec && trim.startSec <= srcEnd;
+ if (carries) {
const map = (s: number) =>
c.timelineStartSec + (Math.min(Math.max(s, c.sourceStartSec), srcEnd) - c.sourceStartSec);
return { start: map(trim.startSec), end: map(trim.endSec) };
@@ -44,6 +85,8 @@ export function trimToTimelineSpan(
/** A source range for one clip, the shape a DSL trim entry needs. */
export interface TrimSourceRange {
assetId: string;
+ /** The clip the cut sits on — the v7 anchor (see `trimAppliesToClip`). */
+ clipId: string;
sourceStartSec: number;
sourceEndSec: number;
}
@@ -70,6 +113,7 @@ export function ventilateTimelineSpanToTrims(
return [
{
assetId: c.assetId,
+ clipId: c.id,
sourceStartSec: c.sourceStartSec + f.localStartSec,
sourceEndSec: c.sourceStartSec + f.localEndSec,
},
@@ -117,6 +161,53 @@ export function coalescedTrimGroups(
return coalesceByIdentity(spans, epsilonSec).map(({ ids, start, end }) => ({ ids, start, end }));
}
+/**
+ * The trim rows that render as the SAME pill as `id` — the trim analogue of
+ * `resolvePillIds` (timelineMap), which trims cannot reuse because it keys off
+ * `startMs`/`endMs` and a trim stores `startSec`/`endSec` plus a `clipId` anchor.
+ *
+ * Needed because a pill is not a row: growing a trim across a clip boundary stores one row
+ * per covered clip (`ventilateTimelineSpanToTrims`) and `coalescedTrimGroups` merges them
+ * back into the single pill the user sees. Anything acting on "the trim the user clicked"
+ * has to act on the group, or it leaves the other half behind — a stripe still cutting
+ * content with no obvious way to reach it.
+ *
+ * Falls back to `[id]` when the id belongs to no group, same as `resolvePillIds`: an orphan
+ * row (its anchor clip deleted, so `trimToTimelineSpan` maps it nowhere) is dropped from the
+ * groups but must still be deletable.
+ */
+export function resolveTrimPillIds(
+ trimRanges: AxcutTrimRange[],
+ clips: AxcutClip[],
+ id: string,
+ epsilonSec?: number,
+): string[] {
+ return (
+ coalescedTrimGroups(trimRanges, clips, epsilonSec).find((g) => g.ids.includes(id))?.ids ?? [id]
+ );
+}
+
+/**
+ * Delete the whole pill each of `ids` belongs to. The single definition of "delete a trim",
+ * shared by the document mutator (`removeRegion`), the store's batch delete and — through
+ * them — the Delete key, the inspector button and the LLM's `removeTrim`. Every other
+ * region kind already routes its delete through `dropPillById` / `dropPillsByIds`; this is
+ * the missing counterpart, not a new rule.
+ */
+export function dropTrimPillsByIds(
+ trimRanges: AxcutTrimRange[],
+ clips: AxcutClip[],
+ ids: Iterable<string>,
+ epsilonSec?: number,
+): AxcutTrimRange[] {
+ const under = new Set<string>();
+ for (const id of ids) {
+ for (const member of resolveTrimPillIds(trimRanges, clips, id, epsilonSec)) under.add(member);
+ }
+ if (under.size === 0) return trimRanges;
+ return trimRanges.filter((t) => !under.has(t.id));
+}
+
/**
* Inverse mapping: given a desired **timeline** span, find the clip whose
* timeline extent contains the span's start, clamp the span to that clip's
@@ -131,7 +222,7 @@ export function resolveTimelineSpanToTrim(
startSec: number,
endSec: number,
clips: AxcutClip[],
-): { assetId: string; sourceStartSec: number; sourceEndSec: number } | null {
+): TrimSourceRange | null {
if (clips.length === 0) return null;
const lo = Math.min(startSec, endSec);
const hi = Math.max(startSec, endSec);
@@ -155,6 +246,7 @@ export function resolveTimelineSpanToTrim(
const toSrc = (t: number) => carrier.sourceStartSec + (t - carrier.timelineStartSec);
return {
assetId: carrier.assetId,
+ clipId: carrier.id,
sourceStartSec: toSrc(tStart),
sourceEndSec: toSrc(tEnd),
};
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index f8206e11e..c2be81cff 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -64,7 +64,7 @@ function makeDoc(
const createdAt = "2024-01-01T00:00:00.000Z";
const baseProject = { id: "p1", title: "Test", createdAt, updatedAt: createdAt };
return {
- schemaVersion: 6,
+ schemaVersion: 7,
project: {
...baseProject,
...(overrides.project ?? {}),
diff --git a/technical-documentation/architecture/document-model.md b/technical-documentation/architecture/document-model.md
index 667521ffb..c312ad605 100644
--- a/technical-documentation/architecture/document-model.md
+++ b/technical-documentation/architecture/document-model.md
@@ -11,22 +11,23 @@ the contract.
## `schemaVersion` and top-level shape
-`axcutSchemaVersion` is **5** — exported as a literal at
-`src/lib/ai-edition/schema/index.ts:24`. Every document on disk carries
-`schemaVersion: 5`; anything older is upgraded on parse (see [Migrations](#migrations))
-and anything unknown is rejected by the `z.literal(5)` check at line 477.
+`axcutSchemaVersion` is **7** — exported as a literal at the top of
+`src/lib/ai-edition/schema/index.ts`. Every document on disk carries
+`schemaVersion: 7`; anything older is upgraded on parse (see [Migrations](#migrations))
+and anything unknown is rejected by the `z.literal(axcutSchemaVersion)` check in
+`documentSchemaShape`.
| Field | Holds | Notes |
|---|---|---|
-| `schemaVersion` | `5` | Bumping requires a migration; see the chain below. |
+| `schemaVersion` | `7` | Bumping requires a migration; see the chain below. |
| `project` | `{ id, title, createdAt, updatedAt, primaryAssetId? }` | One project per file. |
| `assets[]` | `AxcutAsset` (one per recorded/imported media file) | Carries `originalPath`, `cameraTrack`, `durationSec` (renderer probes). |
| `transcript` | `AxcutTranscript \| null` | Legacy primary transcript; left for back-compat, no longer the source of truth. |
| `transcripts[]` | `AxcutTranscript[]` | Per-asset transcripts; what the captions layer actually reads. |
-| `timeline` | `{ clips[], gaps[], trimRanges[], muteRanges[], speedRanges[], captionRanges[] }` | Clips carry their own in/out (`sourceStartSec`/`sourceEndSec`); see [timeline-model.md](timeline-model.md). |
+| `timeline` | `{ clips[], gaps[], trimRanges[], muteRanges[], speedRanges[], captionRanges[] }` | Clips carry their own in/out (`sourceStartSec`/`sourceEndSec`); trims are anchored to a clip (`clipId?`) since v7. See [timeline-model.md](timeline-model.md). |
| `annotations[]` | `AxcutAnnotationRegion[]` | Text/image/figure/blur overlays, anchored to a clip (`clipId?`). |
| `zoomRanges[]` | `AxcutZoomRegion[]` | Zoom-in effects, depth 1–6, anchored to a clip (`clipId?`). |
-| `legacyEditor` | OpenScreen v2 `ProjectEditorState` passthrough | Appearance/cursor settings not yet first-class in v5. |
+| `legacyEditor` | OpenScreen v2 `ProjectEditorState` passthrough | Appearance/cursor settings not yet first-class in the AI-edition schema. |
| `agent` | `{ baseIntent?, pendingQuestions[], suggestions[], lastAppliedOperations[], lastReasoningSummary? }` | LLM agent state. |
| `preview` | `{ strategy: "seek" \| "mse-proxy", revision: number }` | `revision` is the bump used to invalidate cached frames after an edit. |
| `export` | `{ preset, lastJobId }` | The last export run. |
@@ -38,14 +39,14 @@ Migrations are **one-way and forward-only**. There is no version downgrade path:
newer document that lands on an older build is rejected by the `schemaVersion`
literal, not silently truncated. The chain runs **at load time** through
`migrateRawDocumentToCurrent` (`src/lib/ai-edition/document/migrate.ts`) — the
-upgraders compose the chain and `documentSchema.parse` is a pure v5 validator.
+upgraders compose the chain and `documentSchema.parse` is a pure v7 validator.
Every JSON-read site (`DocumentService`, the browser shim, the renderer's
`handleBrowseProject` / `openLoadedProject` disk-load paths) must call the
helper before `documentSchema.parse`. The pre-hoist implementation wrapped this
chain in a `z.preprocess`, so it ran on every `setDocument` / `saveDocument` /
`loadProject` parse — measurable per-parse overhead on documents that were
-already v5. Hoisting it to load time makes the in-memory parse a single
-`z.literal(5)` + shape check on already-upgraded data.
+already current. Hoisting it to load time makes the in-memory parse a single
+`z.literal(7)` + shape check on already-upgraded data.
### v3 → v4 (`upgradeV3DocumentToV4`, `schema/index.ts`)
@@ -79,6 +80,45 @@ the transition). The v4→v5 migration lives **only** in this upgrader —
`document/migrate.ts` deliberately emits a v4 draft (see the v2→current
section below) so the same code path is reused for the legacy import.
+### v5 → v6 (`upgradeV5DocumentToV6`, `schema/index.ts`)
+
+v6 retires the `"native"` AspectRatio, a runtime-only sentinel that resolved to
+the timeline's largest clip. The upgrader bakes the concrete `"W:H"` token into
+`legacyEditor.aspectRatio` so the resolution is permanent, matching the answer
+the runtime gave yesterday. It is **opportunistic**: baking needs real source
+dimensions, and a project imported from v1.7 has none until the renderer probes
+its media, so when they are unknown the sentinel is left in place (it keeps
+resolving dynamically) and converts on a later load. Guessing `"16:9"` there
+would permanently reframe every portrait v1.7 project on its first open.
+
+### v6 → v7 (`upgradeV6DocumentToV7`, `schema/index.ts`)
+
+v7 finishes what v5 started: **trims** become clip-anchored too. They were the
+last ruler region addressed by `assetId` alone. `AxcutTrimRange.startSec` /
+`endSec` already *are* a source-time window, so the only missing piece was
+`clipId` — no `sourceStartSec`/`sourceEndSec` pair is added, which would only
+create two fields that can drift.
+
+Source time is per **asset**, so a v6 trim is unambiguous exactly while one asset
+backs one clip. Duplicate a clip (or place the same recording twice) and the two
+clips share a coordinate space: a cut authored on the second was indistinguishable
+from one on the first, and each reader guessed differently — the transcript pane
+showed the cut on **both** clips, the ruler drew it on the **first**, and
+playback/export removed the span from **both**. `trimAppliesToClip`
+(`src/lib/ai-edition/timeline/trim-mapping.ts`) is now the single definition every
+reader routes through.
+
+The upgrader **ventilates** rather than picks: a stored trim is replaced by one
+anchored row per clip it covers, each clamped to that clip's source window, the
+first keeping the original id. A v6 trim genuinely did cut every clip of its
+asset, so this restates the document without moving its output — but the rows are
+now separately addressable, which is what lets a user delete the copy on the clip
+they did not mean. A trim covering no clip is kept **unchanged** rather than
+dropped (`replaceTimeline` mints exactly those: the complement of the kept
+intervals, outside every clip by construction), and an unprobed clip has no real
+window to clamp against so its trims stay un-anchored. Un-anchored trims keep the
+pre-v7 asset-wide meaning, which is what makes the fallback lossless.
+
### Legacy v2 → current (`migrateProjectDataToAxcutDocument`, `document/migrate.ts`)
OpenScreen's pre-merge editor stored projects as `EditorProjectData` (an envelope
@@ -86,12 +126,16 @@ versioned `PROJECT_VERSION = 2`, defined at
`src/components/video-editor/projectPersistence.ts:66`). On first open in the new
editor, the renderer calls this function to produce a current-shape document. The
migration is **pure** — no DOM, no fs, no network — and maps each `EditorProjectData`
-field into the equivalent v5 slot:
+field into the equivalent current slot:
- The single recorded screen video becomes one asset plus one clip spanning its
source, with the webcam path lifted into `asset.cameraTrack`.
- `editor.trimRegions` (kept ranges) invert into `timeline.trimRanges` (kept ranges
- in source seconds). v2 semantics matched v5 here — both are "kept", not "cut".
+ in source seconds). v2 semantics matched here — both are "kept", not "cut". The
+ trims are anchored to the single minted clip right in this function rather than
+ left to `upgradeV6DocumentToV7`: a v2 project has exactly one clip so the answer
+ is unambiguous, and the upgrader could not do it anyway — the clip it mints has
+ no source extent until the renderer probes the media.
- `editor.speedRegions`, `editor.zoomRegions`, and `editor.annotationRegions` carry
over into `legacyEditor.speedRegions`, `document.zoomRanges`, and
`document.annotations` respectively (with v4→v5 anchoring applied during the
@@ -100,12 +144,12 @@ field into the equivalent v5 slot:
and the other ~20 fields without a first-class home — round-trips through
`legacyEditor` so toggling AI-edition off then back on is lossless.
-The function returns the v5 result by emitting a v4-shaped draft and running it
-through `migrateRawDocumentToCurrent` (which composes `upgradeV3DocumentToV4` +
-`upgradeV4DocumentToV5`) before the v5-validating `documentSchema.parse`. That
-is why the draft is labelled `schemaVersion: 4` and not `axcutSchemaVersion`:
-labelling it already-v5 would make the v4→v5 upgrader skip the anchoring and
-leave the imported regions without clip anchors.
+The function returns the current result by emitting a v4-shaped draft and running
+it through `migrateRawDocumentToCurrent` (the whole `upgradeV3DocumentToV4` →
+`upgradeV6DocumentToV7` chain) before `documentSchema.parse`. That is why the
+draft is labelled `schemaVersion: 4` and not `axcutSchemaVersion`: labelling it
+already-current would make the v4→v5 upgrader skip the anchoring and leave the
+imported regions without clip anchors.
## Persistence
diff --git a/technical-documentation/architecture/timeline-model.md b/technical-documentation/architecture/timeline-model.md
index bd3ca100d..75efdadd1 100644
--- a/technical-documentation/architecture/timeline-model.md
+++ b/technical-documentation/architecture/timeline-model.md
@@ -87,7 +87,50 @@ file rather than re-derived per kind:
A kind with no properties (trim, full-camera) collapses to a constant identity, so its
regions always merge — the long-standing trim behaviour, now derived from the general
-rule.
+rule. `clipId` is in `NON_IDENTITY_FIELDS` and must stay there: it says *where* a region
+is, never what it is, and a trim ventilated across a clip boundary is necessarily 2+ rows
+that have to keep rendering and deleting as ONE pill.
+
+### Trims carry a clip anchor too (v7)
+
+A trim is `{assetId, clipId?, startSec, endSec}` — `startSec`/`endSec` *are* its source
+window, so `clipId` was the only field it needed to become a clip-anchored region like
+any other. Before v7 it had none, and source time is per **asset**: two clips over the
+same media (a duplicated clip) share a coordinate space, so "which clip is this cut on?"
+had no answer and each reader invented one. That produced three symptoms from one cause —
+the transcript pane showed the cut on both clips, the ruler drew it on the first, and
+playback/export removed the span from both.
+
+`trimAppliesToClip`
+([`trim-mapping.ts`](../../src/lib/ai-edition/timeline/trim-mapping.ts)) is the single
+definition of that question; `buildClipSection`, `trimToTimelineSpan` and
+`resolvePlaybackSegments` all route through it. A trim with no `clipId` — pre-v7, or the
+inter-clip cuts `replaceTimeline` mints, which lie outside every clip by construction —
+keeps the historical asset-wide meaning, so old documents render unchanged.
+
+One asymmetry with the other kinds, on purpose: `trimToTimelineSpan` places an **anchored**
+trim on any *overlap* with its clip, but an **un-anchored** one only when the clip
+*contains* its start. Containment is doing the disambiguation in the un-anchored case;
+for an anchored trim it would be a second, stricter test that hides the pill of a cut
+`resolvePlaybackSegments` still applies — content removed with nothing on the ruler to
+click.
+
+### The same ambiguity in the transcript pane
+
+Two clips over one media do not only share a source coordinate space — they share the
+**transcript**, which also belongs to the asset. The pane renders one block per clip, so
+the same `AxcutWord` is projected twice and `word.id` names a moment in the media, not a
+thing on screen. `ClipWord.id` = `clipWordId(clip.id, word.id)`
+([`aggregated-transcript.ts`](../../src/lib/ai-edition/timeline/aggregated-transcript.ts))
+is the on-screen identity; the React key, `data-word-id`, the cue highlight and the caret
+anchor all use it, and `findCueWordId` selects its section by `cue.clipId` before
+returning one. The synthetic `[silence]` tokens make the scoping unconditional rather
+than a shared-media special case: `withSilenceGaps` numbers them from 1 inside each clip,
+so `silence_1` exists in every block regardless of asset.
+
+The caret/selection helpers at the bottom of `RightPanes.tsx` never parse that id — they
+read it off `data-word-id` and scope every query to one block's editor element, so they
+stay correct whatever the id looks like.
## Invariants