Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(document): store the pause an added word needs, as a region
EtienneLescot90280dae9aa8
diff --git a/src/components/ai-edition/EditorEmptyState.test.tsx b/src/components/ai-edition/EditorEmptyState.test.tsxindex be7f130b7..0756bc0dd 100644--- a/src/components/ai-edition/EditorEmptyState.test.tsx+++ b/src/components/ai-edition/EditorEmptyState.test.tsx@@ -47,6 +47,7 @@ const sampleDoc = vi.hoisted(clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/components/ai-edition/ExportDialog.showInFolder.test.tsx b/src/components/ai-edition/ExportDialog.showInFolder.test.tsxindex 52eb7b2ad..d2ec1adbd 100644--- a/src/components/ai-edition/ExportDialog.showInFolder.test.tsx+++ b/src/components/ai-edition/ExportDialog.showInFolder.test.tsx@@ -71,6 +71,7 @@ const DOC: AxcutDocument = {],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/components/ai-edition/ExportDialog.test.ts b/src/components/ai-edition/ExportDialog.test.tsindex ed2f1ab1a..1fb005750 100644--- a/src/components/ai-edition/ExportDialog.test.ts+++ b/src/components/ai-edition/ExportDialog.test.ts@@ -51,6 +51,7 @@ function doc(assets: AxcutAsset[], clips: AxcutClip[]): AxcutDocument {clips,gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/components/ai-edition/WebcamOverlay.test.tsx b/src/components/ai-edition/WebcamOverlay.test.tsxindex 0e5575b6a..ffd13f30a 100644--- a/src/components/ai-edition/WebcamOverlay.test.tsx+++ b/src/components/ai-edition/WebcamOverlay.test.tsx@@ -68,6 +68,7 @@ function makeDocument(): AxcutDocument {clips: [CLIP_WITH_CAMERA, CLIP_WITHOUT_CAMERA],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/document/outputFormat.test.ts b/src/lib/ai-edition/document/outputFormat.test.tsindex c7e75ab40..2a614edd0 100644--- a/src/lib/ai-edition/document/outputFormat.test.ts+++ b/src/lib/ai-edition/document/outputFormat.test.ts@@ -61,6 +61,7 @@ function doc(assets: AxcutAsset[], clips: AxcutClip[]): AxcutDocument {clips,gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.tsindex 06f83943d..02b3d5244 100644--- a/src/lib/ai-edition/document/timeline.test.ts+++ b/src/lib/ai-edition/document/timeline.test.ts@@ -52,6 +52,7 @@ function makeDoc(overrides: Partial<AxcutDocument> = {}): AxcutDocument {clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],@@ -212,6 +213,7 @@ describe("timeline pure functions", () => {],gaps: [],trimRanges: [makeTrim({ id: "trim_1", startSec: 12, endSec: 17 })],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],@@ -309,6 +311,7 @@ describe("timeline pure functions", () => {clips: [],gaps: [],trimRanges: [makeTrim({ id: "trim_other", assetId: "asset_2", startSec: 1, endSec: 2 })],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],@@ -410,6 +413,7 @@ describe("timeline pure functions", () => {],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],@@ -535,6 +539,7 @@ describe("timeline pure functions", () => {],gaps: [],trimRanges: [makeTrim({ id: "trim_1", startSec: 12, endSec: 17 })],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],@@ -611,6 +616,7 @@ describe("timeline pure functions", () => {trimRanges: [{ id: "s1", assetId: "asset_1", startSec: 10, endSec: 20, origin: "user", reason: "" },],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],@@ -648,6 +654,7 @@ describe("timeline pure functions", () => {],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],@@ -963,6 +970,7 @@ describe("duplicateClip / moveClip", () => {...makeDoc().timeline,clips: [makeClip({ id: "clip_a", sourceStartSec: 0, sourceEndSec: 10 })],trimRanges: [makeTrim({ id: "t1", clipId: "clip_a", startSec: 2, endSec: 4 })],+ insertRanges: [],},});const next = duplicateClip(doc, "clip_a");@@ -1316,6 +1324,7 @@ describe("removeRegion — the one shared region-delete mutator", () => {timeline: {...makeDoc().timeline,trimRanges: [makeTrim({ id: "trim_1" }), makeTrim({ id: "trim_2" })],+ insertRanges: [],},});const next = removeRegion(doc, "trim", "trim_1");diff --git a/src/lib/ai-edition/document/transcribe.test.ts b/src/lib/ai-edition/document/transcribe.test.tsindex 0ca221a8c..6a0656c23 100644--- a/src/lib/ai-edition/document/transcribe.test.ts+++ b/src/lib/ai-edition/document/transcribe.test.ts@@ -51,6 +51,7 @@ function makeDoc(): AxcutDocument {clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/document/transcript.test.ts b/src/lib/ai-edition/document/transcript.test.tsindex 9e8ace067..2f531542e 100644--- a/src/lib/ai-edition/document/transcript.test.ts+++ b/src/lib/ai-edition/document/transcript.test.ts@@ -1,8 +1,9 @@import { describe, expect, it } from "vitest";-import { type AxcutTranscript, createEmptyDocument } from "../schema";+import { type AxcutTranscript, createEmptyDocument, documentSchema } from "../schema";import {carryOverWordEdits,insertDocumentWord,+ insertRangesMatchWords,insertWord,removeDocumentWords,removeWord,@@ -667,3 +668,100 @@ describe("carryOverWordEdits with inserted words", () => {expect(result.transcript.words.some((w) => w.text === "really")).toBe(true);});});++// ─── The pause an added word needs ───────────────────────────────+// Created time is STORED, as a region beside the trims. Something has to keep those+// records true against the words they belong to, and `withInsertRangesForWords` is the one+// writer — these hold it to the invariant it maintains. The first attempt at this made+// CLIPS instead, and every other writer of `timeline.clips` disagreed with them.++describe("insert ranges", () => {+ function docWithClip() {+ const doc = makeDoc();+ return {+ ...doc,+ timeline: {+ ...doc.timeline,+ clips: [+ {+ id: "clip_1",+ assetId: "asset_1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: [],+ origin: "user" as const,+ reason: "",+ },+ ],+ },+ };+ }++ it("stores a pause when the free silence does not cover the word", () => {+ // "really" after word_2: word_3 starts exactly where word_2 ends, so the word+ // borrows nothing and needs its whole reading time — max(0.4, 6/15) = 0.4s.+ const result = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");+ expect(result.timeline.insertRanges).toHaveLength(1);+ expect(result.timeline.insertRanges[0]).toMatchObject({+ assetId: "asset_1",+ wordId: "synth_1",+ atSec: 3,+ durationSec: 0.4,+ origin: "user",+ });+ expect(insertRangesMatchWords(result)).toBe(true);+ });++ // The clips are the thing the first attempt broke. Nothing here may touch them.+ it("leaves the clips exactly as they were", () => {+ const before = docWithClip();+ const result = insertDocumentWord(before, "asset_1", "word_2", "after", "really");+ expect(result.timeline.clips).toEqual(before.timeline.clips);+ });++ it("stores nothing when the word fits in silence that is already there", () => {+ // word_3 ends at 4 and word_4 starts at 5: a full second, more than "really" needs.+ const result = insertDocumentWord(docWithClip(), "asset_1", "word_3", "after", "really");+ expect(result.timeline.insertRanges).toEqual([]);+ expect(insertRangesMatchWords(result)).toBe(true);+ });++ it("resizes the pause when the word is rewritten longer", () => {+ const added = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");+ const longer = setDocumentWordText(added, "asset_1", "synth_1", "really quite genuinely so");+ const [range] = longer.timeline.insertRanges;+ expect(range.durationSec).toBeCloseTo(25 / 15, 5);+ expect(range.id).toBe(added.timeline.insertRanges[0].id);+ expect(insertRangesMatchWords(longer)).toBe(true);+ });++ it("drops the pause with the word", () => {+ const added = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");+ const gone = removeDocumentWords(added, "asset_1", ["synth_1"]);+ expect(gone.timeline.insertRanges).toEqual([]);+ expect(insertRangesMatchWords(gone)).toBe(true);+ });++ it("keeps one pause per added word, and no more", () => {+ let doc = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");+ doc = insertDocumentWord(doc, "asset_1", "word_1", "after", "personally");+ expect(doc.timeline.insertRanges).toHaveLength(2);+ expect(new Set(doc.timeline.insertRanges.map((r) => r.wordId)).size).toBe(2);+ expect(insertRangesMatchWords(doc)).toBe(true);+ });++ // Correcting a SPOKEN word must not invent a pause: it has audio behind it already.+ it("stores nothing for an ordinary correction", () => {+ const result = setDocumentWordText(docWithClip(), "asset_1", "word_3", "OpenScreenApp");+ expect(result.timeline.insertRanges).toEqual([]);+ });++ it("survives the document schema", () => {+ const added = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");+ const parsed = documentSchema.parse(JSON.parse(JSON.stringify(added)));+ expect(parsed.timeline.insertRanges).toHaveLength(1);+ expect(insertRangesMatchWords(parsed)).toBe(true);+ });+});diff --git a/src/lib/ai-edition/document/transcript.ts b/src/lib/ai-edition/document/transcript.tsindex dec291474..331c2d7ec 100644--- a/src/lib/ai-edition/document/transcript.ts+++ b/src/lib/ai-edition/document/transcript.ts@@ -1,4 +1,5 @@-import type { AxcutDocument, AxcutTranscript, AxcutWord } from "../schema";+import type { AxcutDocument, AxcutInsertRange, AxcutTranscript, AxcutWord } from "../schema";+import { createId } from "./ids";const CJK_EDGE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;const CLOSING_PUNCTUATION = /^[,.;:!?%。,、;:!?…))\]}>》」』】〕]/u;@@ -144,7 +145,12 @@ export function setDocumentWordText(if (!transcript) {throw new Error(`Cannot edit a word of asset "${assetId}": it has no transcript`);}- return withTranscript(document, setWordText(transcript, wordId, text));+ // Rewriting an added word changes how long it takes to read, so its pause is resized+ // here too — the one writer, whatever the edit was.+ return withInsertRangesForWords(+ withTranscript(document, setWordText(transcript, wordId, text)),+ assetId,+ );}/** Where a new word goes relative to the word the caret was resting on. */@@ -301,8 +307,112 @@ export function removeWord(transcript: AxcutTranscript, wordId: string): AxcutTr};}+/**+ * How much created time an added word still needs, on top of the silence it borrowed.+ *+ * Zero when the pause it landed in was already long enough — an added word between two+ * sentences costs the film nothing.+ */+function pauseDeficitSec(word: AxcutWord): number {+ const borrowed = word.endSec - word.startSec;+ return Math.max(0, readingSeconds(word.text) - borrowed);+}++/** Below this, a pause is not worth a record — a few milliseconds of held frame is a+ * stutter, not a slot to speak in. */+const MIN_PAUSE_SEC = 0.05;++/**+ * Bring the document's insert ranges back in line with its words.+ *+ * The ranges are STORED, so something has to keep them true; this is that something, and+ * it is the only writer. Called after every word write, it adds the pause an added word+ * needs, resizes one whose text changed length, and drops the ones whose word is gone —+ * so no caller has to remember any of the three. `insertRangesMatchWords` is the same rule+ * read back, for a test to hold this to.+ */+function withInsertRangesForWords(document: AxcutDocument, assetId: string): AxcutDocument {+ const transcript = document.transcripts.find((t) => t.assetId === assetId);+ const words = transcript?.words ?? [];+ const wanted = new Map<string, number>();+ for (const word of words) {+ if (word.source !== "synth") continue;+ const deficit = pauseDeficitSec(word);+ if (deficit >= MIN_PAUSE_SEC) wanted.set(word.id, deficit);+ }++ const existing = document.timeline.insertRanges;+ const kept: AxcutInsertRange[] = [];+ const seen = new Set<string>();+ for (const range of existing) {+ // Ranges for OTHER assets are none of this call's business.+ if (range.assetId !== assetId) {+ kept.push(range);+ continue;+ }+ const durationSec = wanted.get(range.wordId);+ if (durationSec === undefined) continue; // its word is gone, or needs no pause now+ seen.add(range.wordId);+ const word = words.find((w) => w.id === range.wordId);+ const atSec = word?.endSec ?? range.atSec;+ kept.push(+ durationSec === range.durationSec && atSec === range.atSec+ ? range+ : { ...range, atSec, durationSec },+ );+ }+ for (const [wordId, durationSec] of wanted) {+ if (seen.has(wordId)) continue;+ const word = words.find((w) => w.id === wordId);+ if (!word) continue;+ kept.push({+ id: createId("insert"),+ assetId,+ atSec: word.endSec,+ durationSec,+ wordId,+ reason: `Held frame for the added word "${word.text}".`,+ origin: "user",+ });+ }++ if (kept.length === existing.length && kept.every((range, i) => range === existing[i])) {+ return document;+ }+ return { ...document, timeline: { ...document.timeline, insertRanges: kept } };+}++/**+ * The invariant {@link withInsertRangesForWords} maintains, read back: every stored pause+ * belongs to an added word that still needs one, sits where that word ends, and lasts what+ * its text needs. Exported for the test that holds the writer to it.+ */+export function insertRangesMatchWords(document: AxcutDocument): boolean {+ const byAsset = new Map(document.transcripts.map((t) => [t.assetId, t]));+ const expected = new Set<string>();+ for (const transcript of document.transcripts) {+ for (const word of transcript.words) {+ if (word.source === "synth" && pauseDeficitSec(word) >= MIN_PAUSE_SEC) {+ expected.add(`${transcript.assetId}::${word.id}`);+ }+ }+ }+ const seen = new Set<string>();+ for (const range of document.timeline.insertRanges) {+ const key = `${range.assetId}::${range.wordId}`;+ if (!expected.has(key) || seen.has(key)) return false;+ seen.add(key);+ const word = byAsset.get(range.assetId)?.words.find((w) => w.id === range.wordId);+ if (!word) return false;+ if (range.atSec !== word.endSec) return false;+ if (Math.abs(range.durationSec - pauseDeficitSec(word)) > 1e-9) return false;+ }+ return seen.size === expected.size;+}+/** {@link insertWord}, addressed by asset. Goes through `withTranscript` for the same- * reason {@link setDocumentWordText} does. */+ * reason {@link setDocumentWordText} does, and leaves behind the pause the new word+ * needs — see {@link withInsertRangesForWords}. */export function insertDocumentWord(document: AxcutDocument,assetId: string,@@ -314,7 +424,10 @@ export function insertDocumentWord(if (!transcript) {throw new Error(`Cannot insert a word into asset "${assetId}": it has no transcript`);}- return withTranscript(document, insertWord(transcript, anchorWordId, side, text));+ return withInsertRangesForWords(+ withTranscript(document, insertWord(transcript, anchorWordId, side, text)),+ assetId,+ );}/** {@link removeWord}, addressed by asset and taking the whole set at once: a Backspace@@ -329,9 +442,12 @@ export function removeDocumentWords(if (!transcript) {throw new Error(`Cannot remove a word from asset "${assetId}": it has no transcript`);}- return withTranscript(- document,- wordIds.reduce((acc, wordId) => removeWord(acc, wordId), transcript),+ return withInsertRangesForWords(+ withTranscript(+ document,+ wordIds.reduce((acc, wordId) => removeWord(acc, wordId), transcript),+ ),+ assetId,);}diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsindex bbf1d6820..fcfecebd3 100644--- a/src/lib/ai-edition/schema/index.ts+++ b/src/lib/ai-edition/schema/index.ts@@ -274,6 +274,34 @@ export const trimRangeSchema = endGteStart("startSec",);+/**+ * Time the film does NOT have: the pause an added word needs so a synthesized voice will+ * have somewhere to speak. The film holds the frame at `atSec` for `durationSec`, screen+ * and webcam together, and everything after it shifts.+ *+ * The exact inverse of a trim, and stored the same way and for the same reason. The first+ * attempt created CLIPS for this; every other writer of `timeline.clips` — the duration+ * probe, the recording import, resequencing — is entitled to disagree with a clip it did+ * not make, and they did: a project came back split twice, both pauses gone, and the words+ * they belonged to with them. A region is the shape this timeline already carries safely.+ *+ * `wordId` is what makes it derived-in-spirit while stored in fact: `document/transcript.ts`+ * is the only writer, it creates the range with the word and drops it with the word, and+ * `insertRangesMatchWords` is the invariant a test holds it to. Nothing else may write one.+ */+export const insertRangeSchema = z.object({+ id: z.string().min(1),+ assetId: z.string().min(1),+ /** Source moment the film holds on. */+ atSec: z.number().nonnegative(),+ /** Timeline time created. Always positive — a pause of zero is simply not stored. */+ durationSec: z.number().positive(),+ /** The transcript word this pause exists for. */+ wordId: z.string().min(1),+ reason: z.string().default(""),+ origin: z.enum(["system", "agent", "user"]),+});+export const timelineSchema = z.preprocess(// Back-compat: the field was renamed skipRanges → trimRanges. Old persisted// documents (disk + browser-shim localStorage) still carry `skipRanges`;@@ -291,6 +319,10 @@ export const timelineSchema = z.preprocess(clips: z.array(clipSchema).default([]),gaps: z.array(gapSchema).default([]),trimRanges: z.array(trimRangeSchema).default([]),+ // Additive, like every optional field before it: absent on every document written+ // before this, so no schema bump — an older build simply drops the key on save, and+ // the words it belonged to keep their text and lose only their pause.+ insertRanges: z.array(insertRangeSchema).default([]),muteRanges: z.array(rangeSchema).default([]),speedRanges: z.array(rangeSchema).default([]),captionRanges: z.array(rangeSchema).default([]),@@ -586,6 +618,7 @@ const documentSchemaShape = z.object({clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],@@ -1033,6 +1066,7 @@ export type AxcutClip = z.infer<typeof clipSchema>;export type AxcutClipCropRegion = z.infer<typeof clipCropRegionSchema>;export type AxcutGap = z.infer<typeof gapSchema>;export type AxcutTrimRange = z.infer<typeof trimRangeSchema>;+export type AxcutInsertRange = z.infer<typeof insertRangeSchema>;export type AxcutTimeline = z.infer<typeof timelineSchema>;export type AxcutTimelineOperation = z.infer<typeof timelineOperationSchema>;export type AxcutAnnotationRegion = z.infer<typeof annotationRegionSchema>;diff --git a/src/lib/ai-edition/store/editorSettings.test.ts b/src/lib/ai-edition/store/editorSettings.test.tsindex ec37d7176..1e8cc43de 100644--- a/src/lib/ai-edition/store/editorSettings.test.ts+++ b/src/lib/ai-edition/store/editorSettings.test.ts@@ -23,6 +23,7 @@ const baseDoc: AxcutDocument = {clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.tsindex 2b75f0a04..18df17063 100644--- a/src/lib/ai-edition/store/projectStore.test.ts+++ b/src/lib/ai-edition/store/projectStore.test.ts@@ -67,6 +67,7 @@ const sampleDoc = {clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/store/undo.modalGuard.test.tsx b/src/lib/ai-edition/store/undo.modalGuard.test.tsxindex 46e083b0b..834103e60 100644--- a/src/lib/ai-edition/store/undo.modalGuard.test.tsx+++ b/src/lib/ai-edition/store/undo.modalGuard.test.tsx@@ -29,6 +29,7 @@ function doc(title: string): AxcutDocument {clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/store/useCaptions.test.ts b/src/lib/ai-edition/store/useCaptions.test.tsindex 0cd641328..84694923c 100644--- a/src/lib/ai-edition/store/useCaptions.test.ts+++ b/src/lib/ai-edition/store/useCaptions.test.ts@@ -65,6 +65,7 @@ const docA: AxcutDocument = {clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/store/useEditorSettings.test.ts b/src/lib/ai-edition/store/useEditorSettings.test.tsindex 4122c05bf..fe433f070 100644--- a/src/lib/ai-edition/store/useEditorSettings.test.ts+++ b/src/lib/ai-edition/store/useEditorSettings.test.ts@@ -68,6 +68,7 @@ const docA: AxcutDocument = {clips: [],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.tsindex 7b77e9c46..ecb5dced9 100644--- a/src/lib/ai-edition/store/useTimeline.test.ts+++ b/src/lib/ai-edition/store/useTimeline.test.ts@@ -106,6 +106,7 @@ const sampleDoc: AxcutDocument = {],gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/lib/ai-edition/timeline/inserted-time.test.ts b/src/lib/ai-edition/timeline/inserted-time.test.tsnew file mode 100644index 000000000..4dd217209--- /dev/null+++ b/src/lib/ai-edition/timeline/inserted-time.test.ts@@ -0,0 +1,157 @@+// The ruler arithmetic behind an added word's pause.+//+// The one thing these have to pin: stored raw seconds and the seconds the user scrubs stop+// being the same number the moment a pause exists, and every reader that confuses the two+// puts a region, a playhead or a caption in the wrong place. The pair is an inverse+// everywhere except inside a pause — which is not a gap in the model, it is the pause.++import { describe, expect, it } from "vitest";+import type { AxcutClip, AxcutInsertRange } from "../schema";+import {+ collapseRawSec,+ expandRawSec,+ type RulerInsert,+ rulerInserts,+ totalInsertedSec,+} from "./inserted-time";++function clip(overrides: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {+ return {+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: [],+ origin: "user",+ reason: "",+ ...overrides,+ };+}++function insert(overrides: Partial<AxcutInsertRange> = {}): AxcutInsertRange {+ return {+ id: "ins_1",+ assetId: "a1",+ atSec: 4,+ durationSec: 0.5,+ wordId: "synth_1",+ reason: "",+ origin: "user",+ ...overrides,+ };+}++describe("rulerInserts", () => {+ it("projects a pause through the clip that plays its moment", () => {+ // The clip plays source 4–10 starting at ruler 20, so source 6 is ruler 22.+ const clips = [clip({ id: "c1", sourceStartSec: 4, timelineStartSec: 20, timelineEndSec: 26 })];+ expect(rulerInserts([insert({ atSec: 6 })], clips)).toEqual([+ { id: "ins_1", wordId: "synth_1", atRawSec: 22, durationSec: 0.5 },+ ]);+ });++ // The word is not on the timeline, so its pause has no place on the ruler and adds+ // nothing — the same rule a caption line follows when no clip covers it.+ it("drops a pause no clip plays", () => {+ const clips = [clip({ id: "c1", sourceStartSec: 0, sourceEndSec: 3, timelineEndSec: 3 })];+ expect(rulerInserts([insert({ atSec: 6 })], clips)).toEqual([]);+ });++ it("counts a pause sitting exactly on a clip's edge", () => {+ // A pause sits at the END of the word it follows, which is routinely the boundary.+ const clips = [clip({ id: "c1", sourceStartSec: 0, sourceEndSec: 4, timelineEndSec: 4 })];+ expect(rulerInserts([insert({ atSec: 4 })], clips)).toHaveLength(1);+ });++ it("returns them in ruler order, whatever order they were stored in", () => {+ const clips = [clip({ id: "c1" })];+ const placed = rulerInserts(+ [insert({ id: "b", atSec: 8 }), insert({ id: "a", atSec: 2 })],+ clips,+ );+ expect(placed.map((p) => p.id)).toEqual(["a", "b"]);+ });++ it("places a pause only once when two clips could play its moment", () => {+ const clips = [+ clip({ id: "c1" }),+ clip({ id: "c2", timelineStartSec: 10, timelineEndSec: 20 }),+ ];+ expect(rulerInserts([insert()], clips)).toHaveLength(1);+ });+});++describe("the expanded ruler", () => {+ const INSERTS: RulerInsert[] = [+ { id: "a", wordId: "w_a", atRawSec: 2, durationSec: 0.5 },+ { id: "b", wordId: "w_b", atRawSec: 6, durationSec: 1 },+ ];++ it("leaves everything before the first pause where it was", () => {+ expect(expandRawSec(0, INSERTS)).toBe(0);+ expect(expandRawSec(1.9, INSERTS)).toBe(1.9);+ });++ // The frame about to be held keeps its own instant; the pause opens after it.+ it("keeps the held moment itself in place", () => {+ expect(expandRawSec(2, INSERTS)).toBe(2);+ });++ it("shifts everything after a pause by what it added", () => {+ expect(expandRawSec(3, INSERTS)).toBe(3.5);+ expect(expandRawSec(6, INSERTS)).toBe(6.5);+ expect(expandRawSec(7, INSERTS)).toBe(8.5);+ });++ it("grows the ruler by the pauses' total", () => {+ expect(totalInsertedSec(INSERTS)).toBe(1.5);+ expect(expandRawSec(10, INSERTS)).toBe(10 + totalInsertedSec(INSERTS));+ });++ it("round-trips every moment that is not inside a pause", () => {+ for (const sec of [0, 1.9, 3, 5.99, 7, 10]) {+ const back = collapseRawSec(expandRawSec(sec, INSERTS), INSERTS);+ expect(back.sec).toBeCloseTo(sec, 9);+ expect(back.heldBy).toBeNull();+ }+ });++ // The held moment is the one place the pair is not a clean inverse, and it is not+ // meant to be: source 2 occupies the WHOLE of ruler [2, 2.5) — it is what the pause+ // shows. Expanding picks the start of that stretch; collapsing it back answers with+ // the same source moment and says it is being held, which is the honest reading of a+ // moment that is on screen for half a second.+ it("says the held moment is held, and still names the right source moment", () => {+ const back = collapseRawSec(expandRawSec(2, INSERTS), INSERTS);+ expect(back.sec).toBe(2);+ expect(back.heldBy?.id).toBe("a");+ });++ // Not a gap in the model — this IS the pause. A stretch of ruler stands for one held+ // source moment, and the caller is told which pause is holding it so it parks the+ // decoder instead of seeking through content that belongs after.+ it("collapses a moment inside a pause onto the frame being held", () => {+ for (const sec of [2.01, 2.25, 2.49]) {+ const back = collapseRawSec(sec, INSERTS);+ expect(back.sec).toBe(2);+ expect(back.heldBy?.id).toBe("a");+ }+ });++ it("resumes on the far side of a pause", () => {+ const back = collapseRawSec(2.5, INSERTS);+ expect(back.sec).toBe(2);+ expect(back.heldBy).toBeNull();+ });++ it("counts every earlier pause when collapsing a later moment", () => {+ // Ruler 8.5 is source 7: 0.5s from the first pause and 1s from the second.+ expect(collapseRawSec(8.5, INSERTS)).toEqual({ sec: 7, heldBy: null });+ });++ it("is the identity when there are no pauses", () => {+ expect(expandRawSec(4, [])).toBe(4);+ expect(collapseRawSec(4, [])).toEqual({ sec: 4, heldBy: null });+ });+});diff --git a/src/lib/ai-edition/timeline/inserted-time.ts b/src/lib/ai-edition/timeline/inserted-time.tsnew file mode 100644index 000000000..a7afcf27b--- /dev/null+++ b/src/lib/ai-edition/timeline/inserted-time.ts@@ -0,0 +1,108 @@+// Time the film does not have.+//+// An added word needs somewhere to be spoken. Where the transcript has free silence it+// borrows it; where it does not, the film holds its frame and everything after it moves+// along the ruler. That created time is stored as an `AxcutInsertRange` — the inverse of a+// trim, and deliberately the same shape, because a region is what this timeline already+// carries safely from end to end. (An earlier attempt made CLIPS for it; see the schema's+// note on `insertRangeSchema` for how that ended.)+//+// This module is the arithmetic, and nothing else: pure, no document, no React. It answers+// two questions.+//+// • Where does a pause land on the RULER? A range is anchored in SOURCE time, so it has+// to be projected through whichever clip plays that moment — `rulerInserts`.+// • What does the ruler look like once the pauses are counted? Stored raw seconds and+// the seconds the user actually scrubs are no longer the same number, and+// `expandRawSec` / `collapseRawSec` are the one place that difference is resolved.+//+// The two are inverses everywhere except INSIDE a pause, where they cannot be: a stretch+// of ruler maps to the single source moment being held. `collapseRawSec` returns that+// moment, which is exactly what a decoder parked on a held frame should be told.++import type { AxcutClip, AxcutInsertRange } from "../schema";++/** A pause placed on the raw ruler, ready to be counted. */+export interface RulerInsert {+ id: string;+ wordId: string;+ /** Where the pause begins, in STORED raw seconds — before any pause is counted. */+ atRawSec: number;+ durationSec: number;+}++/**+ * Project each insert onto the raw ruler through the clip that plays its source moment.+ *+ * A range whose moment no clip plays yields nothing: the pause exists for a word that is+ * not on the timeline, so there is no ruler position for it and nothing to add. Same rule+ * the captions follow for a line no clip covers.+ *+ * Ordered by ruler position, which is what lets the accumulation below be a single pass.+ */+export function rulerInserts(+ inserts: readonly AxcutInsertRange[],+ clips: readonly AxcutClip[],+): RulerInsert[] {+ const placed: RulerInsert[] = [];+ for (const insert of inserts) {+ for (const clip of clips) {+ if (clip.assetId !== insert.assetId) continue;+ const sourceEnd = clip.sourceEndSec ?? Number.POSITIVE_INFINITY;+ // Inclusive at both edges: a pause sits at the END of the word it follows, which+ // is routinely a clip's own boundary.+ if (insert.atSec < clip.sourceStartSec || insert.atSec > sourceEnd) continue;+ placed.push({+ id: insert.id,+ wordId: insert.wordId,+ atRawSec: clip.timelineStartSec + (insert.atSec - clip.sourceStartSec),+ durationSec: insert.durationSec,+ });+ break;+ }+ }+ return placed.sort((a, b) => a.atRawSec - b.atRawSec);+}++/** How much time the pauses add in total — what the ruler grows by. */+export function totalInsertedSec(inserts: readonly RulerInsert[]): number {+ return inserts.reduce((sum, insert) => sum + insert.durationSec, 0);+}++/**+ * Stored raw seconds → the ruler the user sees.+ *+ * Monotone and total: every stored moment has exactly one place on the expanded ruler.+ * A moment sitting exactly ON a pause maps to where the pause BEGINS, so the frame that+ * is about to be held keeps its own instant and the pause opens after it.+ */+export function expandRawSec(sec: number, inserts: readonly RulerInsert[]): number {+ let out = sec;+ for (const insert of inserts) {+ if (insert.atRawSec < sec) out += insert.durationSec;+ }+ return out;+}++/**+ * The ruler the user sees → stored raw seconds.+ *+ * The inverse of {@link expandRawSec} outside a pause. Inside one it cannot be an inverse+ * — a whole stretch of ruler stands for a single held moment — and it returns that moment,+ * flagged, so a caller driving a decoder knows to hold rather than to seek.+ */+export function collapseRawSec(+ sec: number,+ inserts: readonly RulerInsert[],+): { sec: number; heldBy: RulerInsert | null } {+ let offset = 0;+ for (const insert of inserts) {+ const startsAt = insert.atRawSec + offset;+ if (sec < startsAt) break;+ if (sec < startsAt + insert.durationSec) {+ return { sec: insert.atRawSec, heldBy: insert };+ }+ offset += insert.durationSec;+ }+ return { sec: sec - offset, heldBy: null };+}diff --git a/src/lib/ai-edition/transcription/status.test.ts b/src/lib/ai-edition/transcription/status.test.tsindex d453936bf..b37b71ece 100644--- a/src/lib/ai-edition/transcription/status.test.ts+++ b/src/lib/ai-edition/transcription/status.test.ts@@ -274,6 +274,7 @@ function doc(assetIds: string[], clipAssetIds: string[]): AxcutDocument {})),gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex 01c656967..32afda410 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -84,6 +84,7 @@ function makeDoc(clips,gaps: [],trimRanges: [],+ insertRanges: [],muteRanges: [],speedRanges: [],captionRanges: [],