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(document): reconcile clip geometry with the insertions on every load

EtienneLescoted8216bb944d
diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.ts
index 9c9b958b9..1199bee50 100644
--- a/electron/ai-edition/document-service.ts
+++ b/electron/ai-edition/document-service.ts
@@ -13,6 +13,10 @@
import fs, { type FileHandle } from "node:fs/promises";
import path from "node:path";
import { createId } from "../../src/lib/ai-edition/document/ids";
+import {
+ parseStoredDocument,
+ reconcileClipsWithInserts,
+} from "../../src/lib/ai-edition/document/load";
import { removeClip } from "../../src/lib/ai-edition/document/timeline";
import {
type AxcutAsset,
@@ -122,7 +126,7 @@ function safeProjectId(raw: string): string {
// `getProject` spells the same two steps out inline because it relinks moved
// media between them; keep the order (upgrade, then validate) in step.
function parseLoadedDocument(raw: string): AxcutDocument {
- return documentSchema.parse(migrateRawDocumentToCurrent(JSON.parse(raw)));
+ return parseStoredDocument(JSON.parse(raw));
}
/**
@@ -273,7 +277,9 @@ export class DocumentService {
// back, and it is not persisted from here: the renderer saves the document
// it was given, as it does for any other load-time repair.
const migrated = migrateRawDocumentToCurrent(JSON.parse(raw));
- return documentSchema.parse(await relinkProjectMedia(migrated, this.mediaRegistryDir));
+ return reconcileClipsWithInserts(
+ documentSchema.parse(await relinkProjectMedia(migrated, this.mediaRegistryDir)),
+ );
}
async createProject(title: string): Promise<AxcutDocument> {
diff --git a/src/components/ai-edition/EditorEmptyState.tsx b/src/components/ai-edition/EditorEmptyState.tsx
index 226171dca..18101e699 100644
--- a/src/components/ai-edition/EditorEmptyState.tsx
+++ b/src/components/ai-edition/EditorEmptyState.tsx
@@ -14,11 +14,8 @@ import { AlertCircle, Film, FolderOpen, Upload, X } from "lucide-react";
import { useCallback, useRef, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useScopedT } from "@/contexts/I18nContext";
-import {
- migrateProjectDataToAxcutDocument,
- migrateRawDocumentToCurrent,
-} from "@/lib/ai-edition/document/migrate";
-import { documentSchema } from "@/lib/ai-edition/schema";
+import { parseStoredDocument } from "@/lib/ai-edition/document/load";
+import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { nativeBridgeClient } from "@/native";
import styles from "./NewEditorShell.module.css";
@@ -82,7 +79,7 @@ export function EditorEmptyState({
const isAxcutDocument =
typeof raw === "object" && raw !== null && "schemaVersion" in raw && "timeline" in raw;
const doc = isAxcutDocument
- ? documentSchema.parse(migrateRawDocumentToCurrent(raw)) // disk-load: upgrade v3/v4 → v5, then validate
+ ? parseStoredDocument(raw) // disk-load: upgrade, validate, reconcile clip geometry
: migrateProjectDataToAxcutDocument(raw as never);
const saved = await nativeBridgeClient.aiEdition.save(doc);
if (!saved.success || !saved.document) return false;
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 93c5c7eb4..385df2a3d 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -6,10 +6,8 @@ import { useEditorDialogActions } from "@/contexts/EditorDialogsContext";
import { useScopedT } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
import { createId } from "@/lib/ai-edition/document/ids";
-import {
- migrateProjectDataToAxcutDocument,
- migrateRawDocumentToCurrent,
-} from "@/lib/ai-edition/document/migrate";
+import { parseStoredDocument } from "@/lib/ai-edition/document/load";
+import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";
import {
applyProbedDuration,
replaceTimeline as replaceTimelineOp,
@@ -25,7 +23,6 @@ import {
type AxcutAudioTrack,
type AxcutClip,
type AxcutInsertRange,
- documentSchema,
} from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import {
@@ -590,7 +587,7 @@ export function NewEditorShell() {
const isAxcutDocument =
typeof raw === "object" && raw !== null && "schemaVersion" in raw && "timeline" in raw;
const doc = isAxcutDocument
- ? documentSchema.parse(migrateRawDocumentToCurrent(raw)) // disk-load: upgrade v3/v4 → v5, then validate
+ ? parseStoredDocument(raw) // disk-load: upgrade, validate, reconcile clip geometry
: migrateProjectDataToAxcutDocument(raw as EditorProjectData);
const saved = await nativeBridgeClient.aiEdition.save(doc);
if (saved.success && saved.document) {
diff --git a/src/lib/ai-edition/document/load.test.ts b/src/lib/ai-edition/document/load.test.ts
new file mode 100644
index 000000000..589d49ca0
--- /dev/null
+++ b/src/lib/ai-edition/document/load.test.ts
@@ -0,0 +1,87 @@
+// A document written before insertions took up time on the timeline.
+//
+// Nothing else reconciles it: `withInsertRangesForWords` only runs when a transcript word is
+// written, so a project the user merely OPENS keeps its old geometry while all the code
+// around it assumes the new — the film's ruler stops short, the insertion pills are drawn at
+// their source position, and the subtitles slide further out of step with every insertion
+// passed (issue #560).
+
+import { describe, expect, it } from "vitest";
+import type { AxcutClip, AxcutDocument, AxcutInsertRange } from "../schema";
+import { reconcileClipsWithInserts } from "./load";
+
+function clip(over: Partial<AxcutClip> & { id: string }): AxcutClip {
+ return {
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ ...over,
+ };
+}
+
+const insert = (over: Partial<AxcutInsertRange> & { id: string }): AxcutInsertRange => ({
+ assetId: "a1",
+ atSec: 5,
+ durationSec: 1,
+ wordId: "w1",
+ reason: "",
+ origin: "user",
+ ...over,
+});
+
+function doc(clips: AxcutClip[], insertRanges: AxcutInsertRange[]): AxcutDocument {
+ return { timeline: { clips, insertRanges } } as unknown as AxcutDocument;
+}
+
+describe("reconcileClipsWithInserts", () => {
+ it("gives a short clip back the time its insertions take", () => {
+ const before = doc([clip({ id: "c1" })], [insert({ id: "i1" })]);
+ const [after] = reconcileClipsWithInserts(before).timeline.clips;
+ expect(after.timelineEndSec - after.timelineStartSec).toBeCloseTo(11, 6);
+ // The recording is untouched: no frame was added to or taken from the file.
+ expect(after.sourceStartSec).toBe(0);
+ expect(after.sourceEndSec).toBe(10);
+ });
+
+ it("pushes every later clip along by what the one before it gained", () => {
+ const before = doc(
+ [clip({ id: "c1" }), clip({ id: "c2", timelineStartSec: 10, timelineEndSec: 20 })],
+ [insert({ id: "i1" })],
+ );
+ const [, second] = reconcileClipsWithInserts(before).timeline.clips;
+ expect(second.timelineStartSec).toBeCloseTo(11, 6);
+ expect(second.timelineEndSec).toBeCloseTo(21, 6);
+ });
+
+ it("is idempotent, so it can run on every load", () => {
+ const before = doc([clip({ id: "c1" })], [insert({ id: "i1" })]);
+ const once = reconcileClipsWithInserts(before);
+ const twice = reconcileClipsWithInserts(once);
+ expect(twice.timeline.clips).toEqual(once.timeline.clips);
+ // And a document already in step is returned as-is, not rebuilt.
+ expect(twice).toBe(once);
+ });
+
+ it("leaves a document with no insertions completely alone", () => {
+ const before = doc([clip({ id: "c1" })], []);
+ expect(reconcileClipsWithInserts(before)).toBe(before);
+ });
+
+ it("counts several insertions in one clip, and only that clip's", () => {
+ const before = doc(
+ [
+ clip({ id: "c1" }),
+ clip({ id: "c2", assetId: "a2", timelineStartSec: 10, timelineEndSec: 20 }),
+ ],
+ [insert({ id: "i1", atSec: 3 }), insert({ id: "i2", atSec: 7, durationSec: 0.5 })],
+ );
+ const [first, second] = reconcileClipsWithInserts(before).timeline.clips;
+ expect(first.timelineEndSec).toBeCloseTo(11.5, 6);
+ expect(second.timelineEndSec - second.timelineStartSec).toBeCloseTo(10, 6);
+ });
+});
diff --git a/src/lib/ai-edition/document/load.ts b/src/lib/ai-edition/document/load.ts
new file mode 100644
index 000000000..e4a4b3087
--- /dev/null
+++ b/src/lib/ai-edition/document/load.ts
@@ -0,0 +1,46 @@
+// The one way to turn a document on disk into a document in memory.
+//
+// Three steps, in this order, and no caller may do two of them and skip the third:
+//
+// 1. UPGRADE — `migrateRawDocumentToCurrent` walks the vN → vN+1 chain.
+// 2. VALIDATE — `documentSchema.parse` is a pure current-version shape check.
+// 3. RECONCILE — clip geometry is brought back in line with the insert ranges.
+//
+// Step 3 is the one that is easy to forget and impossible to notice. An insertion is MEDIA
+// inside a clip (issue #560), so a clip carrying one is longer than its source window by
+// exactly that much — every reader downstream depends on it, and a document written before
+// that was true carries SHORT clips. Nothing else reconciles them: `withInsertRangesForWords`
+// only runs when a transcript word is written, so a project the user merely OPENS keeps its
+// old geometry while all the code around it assumes the new. The visible result is a film
+// whose ruler stops short, insertion pills drawn at their source position instead of their
+// timeline one, and subtitles sliding further out of step with every insertion passed.
+//
+// `reflowClipsForInserts` is absolute rather than incremental, so this is idempotent: a
+// document already in step is returned unchanged, and running it on every load costs nothing
+// while also repairing anything that writes clip geometry without allowing for insertions.
+
+import type { AxcutDocument } from "../schema";
+import { documentSchema, migrateRawDocumentToCurrent } from "../schema";
+import { reflowClipsForInserts } from "./timeline";
+
+/** Clip geometry brought back in line with the document's insert ranges. Idempotent. */
+export function reconcileClipsWithInserts(document: AxcutDocument): AxcutDocument {
+ const insertRanges = document.timeline.insertRanges ?? [];
+ if (insertRanges.length === 0) return document;
+ const clips = reflowClipsForInserts(document.timeline.clips, insertRanges);
+ const unchanged =
+ clips.length === document.timeline.clips.length &&
+ clips.every((clip, i) => {
+ const was = document.timeline.clips[i];
+ return (
+ Math.abs(clip.timelineStartSec - was.timelineStartSec) < 1e-9 &&
+ Math.abs(clip.timelineEndSec - was.timelineEndSec) < 1e-9
+ );
+ });
+ return unchanged ? document : { ...document, timeline: { ...document.timeline, clips } };
+}
+
+/** Raw JSON (any stored version) → a validated, reconciled document. */
+export function parseStoredDocument(raw: unknown): AxcutDocument {
+ return reconcileClipsWithInserts(documentSchema.parse(migrateRawDocumentToCurrent(raw)));
+}
diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.ts
index 2b360806a..8d06f6b85 100644
--- a/src/lib/ai-edition/document/migrate.ts
+++ b/src/lib/ai-edition/document/migrate.ts
@@ -28,10 +28,9 @@ import {
type AxcutLegacyEditor,
type AxcutTrimRange,
type AxcutZoomRegion,
- documentSchema,
- migrateRawDocumentToCurrent,
} from "../schema";
import { createId } from "./ids";
+import { parseStoredDocument } from "./load";
const MS_TO_SEC = 1 / 1000;
const SEC_TO_MS = 1000;
@@ -63,7 +62,7 @@ function clampSec(sec: number): number {
* v2 inputs are not handled by it — `migrateProjectDataToAxcutDocument` below
* still owns the legacy EditorProjectData → AxcutDocument translation.
*/
-export { migrateRawDocumentToCurrent };
+export { migrateRawDocumentToCurrent } from "../schema";
function toLegacyMedia(input: ProjectMedia | undefined): ProjectMedia | null {
if (!input) return null;
@@ -250,7 +249,7 @@ export function migrateProjectDataToAxcutDocument(
legacyEditor,
};
- return documentSchema.parse(migrateRawDocumentToCurrent(draft));
+ return parseStoredDocument(draft);
}
/**
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 791389d2b..1ba70d480 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -21,6 +21,7 @@ import type {
*/
export type PlaybackSegment = AxcutClip & { heldSec?: number };
+import { assignInsertsToClips } from "../timeline/inserted-time";
import { type Interval, subtractInterval } from "../timeline/intervals";
import { keptRawSpans } from "../timeline/programme-time";
import {
@@ -135,26 +136,6 @@ function collectWordRefs(
// after any structural change (insert / move / remove / trim) so the timeline
// never has gaps or overlaps between clips. Shared by useTimeline (UI) and
// the agent tool executor (main process) so both enforce the same invariant.
-/** How much media this clip's own insertions add to it, in seconds.
- *
- * Half-open at the start and closed at the end, matching where an insertion sits: at the
- * END of the word it follows, which is a moment the clip plays. */
-export function insertedSecForClip(
- clip: AxcutClip,
- insertRanges: readonly AxcutInsertRange[],
-): number {
- const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
- return insertRanges.reduce(
- (sum, range) =>
- range.assetId === clip.assetId &&
- range.atSec > clip.sourceStartSec &&
- range.atSec <= sourceEnd + 1e-6
- ? sum + range.durationSec
- : sum,
- 0,
- );
-}
-
/**
* Clip geometry that accounts for the media inserted inside each clip (issue #560).
*
@@ -173,12 +154,19 @@ export function reflowClipsForInserts(
clips: AxcutClip[],
insertRanges: readonly AxcutInsertRange[],
): AxcutClip[] {
+ // Through `assignInsertsToClips`, so the length a clip gains and the pills drawn inside it
+ // come from the same assignment. They used to be computed separately, and with two clips
+ // over one recording the film grew twice for an insertion drawn once.
+ const byClip = assignInsertsToClips(clips, insertRanges);
return resequenceClips(
clips.map((clip) => {
const sourceLen = (clip.sourceEndSec ?? clip.sourceStartSec) - clip.sourceStartSec;
if (sourceLen <= 0) return clip; // duration not probed yet; leave it to the prober
- const len = sourceLen + insertedSecForClip(clip, insertRanges);
- return { ...clip, timelineEndSec: clip.timelineStartSec + len };
+ const owed = (byClip.get(clip.id) ?? []).reduce((sum, r) => sum + r.durationSec, 0);
+ return {
+ ...clip,
+ timelineEndSec: clip.timelineStartSec + sourceLen + owed,
+ };
}),
);
}
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index fd47da9cc..cee4be4ad 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -5,6 +5,7 @@ import { toastText } from "@/i18n/toastText";
import { nativeBridgeClient } from "@/native/client";
import { placeAudioTrackInDocument } from "../document/audioTracks";
import { createId } from "../document/ids";
+import { reconcileClipsWithInserts } from "../document/load";
import { type Interval, replaceTimeline as replaceTimelineOp } from "../document/timeline";
import { type AxcutAsset, type AxcutDocument, createAudioTrack, documentSchema } from "../schema";
import { probeAudioDuration, probeVideoDimensions } from "../timeline/duration";
@@ -158,7 +159,10 @@ export interface ProjectState {
}
function parseDocument(value: unknown): AxcutDocument {
- return documentSchema.parse(value);
+ // Reconciled here too, not only in the main process: this is the renderer's own gate on
+ // every document it accepts, and it is idempotent, so a document that arrived correct
+ // passes through untouched.
+ return reconcileClipsWithInserts(documentSchema.parse(value));
}
/**
diff --git a/src/lib/ai-edition/timeline/inserted-time.ts b/src/lib/ai-edition/timeline/inserted-time.ts
index c921ce878..c061b5ff0 100644
--- a/src/lib/ai-edition/timeline/inserted-time.ts
+++ b/src/lib/ai-edition/timeline/inserted-time.ts
@@ -32,7 +32,7 @@ export interface RulerInsert {
}
/**
- * Project each insert onto the raw ruler through the clip that plays its source moment.
+ * Project each insert onto the ruler through the clip that owns it.
*
* A range whose moment no clip plays yields nothing: the insertion exists for a word that is
* not on the timeline, so there is no ruler position for it and nothing to add. Same rule
@@ -40,19 +40,26 @@ export interface RulerInsert {
*
* Ordered by ruler position, which is what lets the accumulation below be a single pass.
*/
-export function rulerInserts(
- inserts: readonly AxcutInsertRange[],
+/**
+ * Which clip owns each insertion.
+ *
+ * ONE definition, because the geometry and the drawing must not answer this differently.
+ * An insertion is anchored to an ASSET and a source moment, not to a clip, so two clips over
+ * the same recording could both claim it — and when they did, the film grew twice while the
+ * pill was drawn once. It is claimed by the FIRST clip that plays its moment, in timeline
+ * order: the insertion is stored once and the word exists once, so it happens once.
+ */
+export function assignInsertsToClips(
clips: readonly AxcutClip[],
-): RulerInsert[] {
- const placed: RulerInsert[] = [];
+ inserts: readonly AxcutInsertRange[],
+): Map<string, AxcutInsertRange[]> {
+ const byClip = new Map<string, AxcutInsertRange[]>();
const claimed = new Set<string>();
- for (const clip of clips) {
+ for (const clip of [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec)) {
const sourceEnd = clip.sourceEndSec ?? Number.POSITIVE_INFINITY;
const mine = inserts
// Inclusive at both edges: an insertion sits at the END of the word it follows,
- // which is routinely a clip's own boundary. Claimed once, by the first clip that
- // plays the moment — two clips over the same recording are two places, not two
- // insertions.
+ // which is routinely a clip's own boundary.
.filter(
(insert) =>
insert.assetId === clip.assetId &&
@@ -61,12 +68,24 @@ export function rulerInserts(
insert.atSec <= sourceEnd,
)
.sort((a, b) => a.atSec - b.atSec);
+ for (const insert of mine) claimed.add(insert.id);
+ if (mine.length > 0) byClip.set(clip.id, mine);
+ }
+ return byClip;
+}
+
+export function rulerInserts(
+ inserts: readonly AxcutInsertRange[],
+ clips: readonly AxcutClip[],
+): RulerInsert[] {
+ const byClip = assignInsertsToClips(clips, inserts);
+ const placed: RulerInsert[] = [];
+ for (const clip of clips) {
// Each insertion opens after the ones before it in the same clip: the clip's length
// already carries all of them, so a plain source-shift would stack them all at the
// first one's position.
let carriedSec = 0;
- for (const insert of mine) {
- claimed.add(insert.id);
+ for (const insert of byClip.get(clip.id) ?? []) {
placed.push({
id: insert.id,
wordId: insert.wordId,