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
fix(document): finish migrating v1.7 projects when the media duration lands
Etienne Lescot09da80c92aa4
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex ad187a695..75aa12f1d 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -4,12 +4,15 @@ import type { EditorProjectData } from "@/components/video-editor/projectPersistimport { toFileUrl } from "@/components/video-editor/projectPersistence";import { useShortcuts } from "@/contexts/ShortcutsContext";import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";-import { replaceTimeline as replaceTimelineOp } from "@/lib/ai-edition/document/timeline";+import {+ applyProbedDuration,+ replaceTimeline as replaceTimelineOp,+} from "@/lib/ai-edition/document/timeline";import { transcribeAsset } from "@/lib/ai-edition/document/transcribe";import { type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { useUndoRedoShortcuts } from "@/lib/ai-edition/store/undo";-import { PLACEHOLDER_DURATION_SEC, useTimeline } from "@/lib/ai-edition/store/useTimeline";+import { useTimeline } from "@/lib/ai-edition/store/useTimeline";import { matchesShortcut } from "@/lib/shortcuts";import { nativeBridgeClient } from "@/native";import type { AiEditionProjectSummary } from "@/native/contracts";@@ -324,36 +327,16 @@ export function NewEditorShell() {void state.saveDocument(next);return;}- // Only correct clips belonging to the asset that actually fired this- // event, and only while they still sit at the pre-probe 0..60s- // placeholder — never a clip the user has since trimmed. Patching by- // array index (the previous behavior) clobbered clip[0]'s duration- // whenever a *different* asset's video element loaded, e.g. right- // after dropping a second clip onto the timeline.- const isPlaceholder = (c: (typeof doc.timeline.clips)[number]) =>- c.assetId === assetId &&- c.sourceStartSec === 0 &&- Math.abs((c.sourceEndSec ?? 0) - PLACEHOLDER_DURATION_SEC) < 0.01;- if (Math.abs(known - PLACEHOLDER_DURATION_SEC) < 0.01) return;- if (!doc.timeline.clips.some(isPlaceholder)) return;-- let shiftSec = 0;- const nextClips = doc.timeline.clips.map((c) => {- const shifted = { ...c, timelineStartSec: c.timelineStartSec + shiftSec };- if (!isPlaceholder(c)) {- shifted.timelineEndSec = c.timelineEndSec + shiftSec;- return shifted;- }- const delta = known - PLACEHOLDER_DURATION_SEC;- shifted.sourceEndSec = known;- shifted.timelineEndSec = shifted.timelineStartSec + known;- shiftSec += delta;- return shifted;- });- void state.saveDocument({- ...doc,- timeline: { ...doc.timeline, clips: nextClips },- });+ // Hand the probed duration to the pure document layer: it patches only the+ // clips of THIS asset that are still waiting for a real length (the+ // pre-probe placeholder, or the extent-less clip a legacy v2 import mints),+ // shifts what follows, and brings the modifiers along — anchoring the ones+ // migration had to leave unanchored. Returns the document untouched when+ // nothing is waiting, so there is nothing to guard here.+ const next = applyProbedDuration(doc, assetId, known);+ if (next !== doc) {+ void state.saveDocument(next);+ }},[setSourceDuration],);diff --git a/src/lib/ai-edition/document/applyProbedDuration.test.ts b/src/lib/ai-edition/document/applyProbedDuration.test.tsnew file mode 100644index 000000000..0147f5f69--- /dev/null+++ b/src/lib/ai-edition/document/applyProbedDuration.test.ts@@ -0,0 +1,129 @@+// The v1.7 (PROJECT_VERSION 2) import path, end to end.+//+// That format has no clip list — one recording plus regions — so migration mints a+// single clip with NO source extent and leaves every region unanchored (anchoring+// needs a clip with real extent; dropping the regions instead would lose user data).+// The duration only arrives later, when the renderer loads the media. These tests pin+// the moment that gap closes: the clip gets its real length AND the regions become+// anchored, so nothing is left on the fragile raw-ms-only representation.++import { describe, expect, it } from "vitest";+import type { AxcutDocument } from "../schema";+import { documentSchema } from "../schema";+import { migrateProjectDataToAxcutDocument } from "./migrate";+import { applyProbedDuration, PLACEHOLDER_DURATION_SEC } from "./timeline";++/** A v1.7 project file: one recording, one zoom region at 6–8s of that recording. */+function legacyProjectWithZoom() {+ return {+ version: 2,+ videoPath: "C:/rec/screen.webm",+ media: { videoPath: "C:/rec/screen.webm" },+ editor: {+ zoomRegions: [+ { id: "z1", startMs: 6000, endMs: 8000, depth: 2, focus: { cx: 0.5, cy: 0.5 } },+ ],+ annotationRegions: [],+ trimRegions: [],+ speedRegions: [],+ cameraFullscreenRegions: [],+ },+ } as never;+}++/** The CANONICAL zoom collection — what the native scene and the exporter read.+ * (`legacyEditor.zoomRegions` is the v2 envelope kept for round-tripping back to the+ * old format; nothing on the render path reads it.) */+const zoomsOf = (doc: AxcutDocument) =>+ (doc.zoomRanges ?? []) as unknown as Array<Record<string, unknown>>;++describe("applyProbedDuration — the v1.7 import gap", () => {+ it("opens a legacy project with an extent-less clip and unanchored regions", () => {+ // Documents the STARTING state this function exists to repair. If migration ever+ // learns the duration itself, this expectation is what will flag it.+ const doc = documentSchema.parse(migrateProjectDataToAxcutDocument(legacyProjectWithZoom()));+ const clip = doc.timeline.clips[0];+ expect(clip.sourceEndSec ?? 0).toBeLessThanOrEqual(clip.sourceStartSec);+ expect(zoomsOf(doc)[0].clipId).toBeUndefined();+ });++ it("gives the clip its real length and anchors the region once duration arrives", () => {+ const doc = documentSchema.parse(migrateProjectDataToAxcutDocument(legacyProjectWithZoom()));+ const assetId = doc.assets[0].id;+ const next = applyProbedDuration(doc, assetId, 30);++ const clip = next.timeline.clips[0];+ expect(clip.sourceEndSec).toBe(30);+ expect(clip.timelineEndSec).toBe(30);+ expect(next.assets[0].durationSec).toBe(30);++ // The region keeps the source moment it was authored on (6–8s of the recording),+ // now stated as an anchor rather than a ruler coordinate.+ const zoom = zoomsOf(next)[0];+ expect(zoom.clipId).toBe(clip.id);+ expect(zoom.sourceStartSec).toBeCloseTo(6, 5);+ expect(zoom.sourceEndSec).toBeCloseTo(8, 5);+ expect(zoom.startMs).toBe(6000);+ expect(zoom.endMs).toBe(8000);+ });++ it("also replaces the pre-probe placeholder length", () => {+ // The other clip that waits for a duration: inserted before its media reported one.+ const doc = documentSchema.parse(migrateProjectDataToAxcutDocument(legacyProjectWithZoom()));+ const assetId = doc.assets[0].id;+ const seeded: AxcutDocument = {+ ...doc,+ timeline: {+ ...doc.timeline,+ clips: [+ {+ ...doc.timeline.clips[0],+ sourceEndSec: PLACEHOLDER_DURATION_SEC,+ timelineEndSec: PLACEHOLDER_DURATION_SEC,+ },+ ],+ },+ };+ const next = applyProbedDuration(seeded, assetId, 12);+ expect(next.timeline.clips[0].sourceEndSec).toBe(12);+ expect(next.timeline.clips[0].timelineEndSec).toBe(12);+ });++ it("leaves a clip the user has already trimmed alone", () => {+ const doc = documentSchema.parse(migrateProjectDataToAxcutDocument(legacyProjectWithZoom()));+ const assetId = doc.assets[0].id;+ const trimmed: AxcutDocument = {+ ...doc,+ timeline: {+ ...doc.timeline,+ clips: [{ ...doc.timeline.clips[0], sourceEndSec: 9, timelineEndSec: 9 }],+ },+ };+ expect(applyProbedDuration(trimmed, assetId, 30)).toBe(trimmed);+ });++ it("ignores an unusable duration rather than stamping a bogus extent", () => {+ const doc = documentSchema.parse(migrateProjectDataToAxcutDocument(legacyProjectWithZoom()));+ const assetId = doc.assets[0].id;+ expect(applyProbedDuration(doc, assetId, 0)).toBe(doc);+ expect(applyProbedDuration(doc, assetId, Number.NaN)).toBe(doc);+ });++ it("only touches clips of the asset that reported its duration", () => {+ // Two assets both awaiting a duration: the one that didn't fire must not move.+ const doc = documentSchema.parse(migrateProjectDataToAxcutDocument(legacyProjectWithZoom()));+ const assetId = doc.assets[0].id;+ const other = { ...doc.timeline.clips[0], id: "clip_other", assetId: "asset_other" };+ const twoClips: AxcutDocument = {+ ...doc,+ timeline: { ...doc.timeline, clips: [doc.timeline.clips[0], other] },+ };+ const next = applyProbedDuration(twoClips, assetId, 20);+ expect(next.timeline.clips[0].sourceEndSec).toBe(20);+ expect(next.timeline.clips[1].sourceEndSec ?? 0).toBeLessThanOrEqual(+ next.timeline.clips[1].sourceStartSec,+ );+ // …and the untouched clip is pushed down the ruler by exactly the widening.+ expect(next.timeline.clips[1].timelineStartSec).toBe(20);+ });+});diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsindex da230e951..2b836ff90 100644--- a/src/lib/ai-edition/document/timeline.ts+++ b/src/lib/ai-edition/document/timeline.ts@@ -7,10 +7,26 @@ import type { AxcutClip, AxcutDocument, AxcutTranscript, AxcutTrimRange } from "import { anchoredToRawSpanSec, anchorRegionsWithDerivedMs } from "../timeline/timelineMap";import { createId } from "./ids";+/** Length a clip is given before its media has been probed. Lives here, in the pure+ * document layer, because that layer decides which clips are still waiting for a real+ * duration (`applyProbedDuration`); the store re-exports it for its own callers. */+export const PLACEHOLDER_DURATION_SEC = 60;+export function byStart(a: { startSec: number }, b: { startSec: number }): number {return a.startSec - b.startSec;}+/** A region is anchored once it states WHERE IN THE SOURCE it lives. Anything missing+ * a part of `{clipId, sourceStartSec, sourceEndSec}` still relies on its RAW ms.+ * One definition, so "is this anchored?" can never be asked two different ways. */+function isAnchored<T extends { clipId?: string; sourceStartSec?: number; sourceEndSec?: number }>(+ region: T,+): region is T & { clipId: string; sourceStartSec: number; sourceEndSec: number } {+ return (+ !!region.clipId && region.sourceStartSec !== undefined && region.sourceEndSec !== undefined+ );+}+export interface Interval {startSec: number;endSec: number;@@ -257,11 +273,7 @@ export function rederiveRegionMs(document: AxcutDocument, clips: AxcutClip[]): Aif (clips.length === 0) return document;return mapAllRegionCollections(document, (regions) =>regions.flatMap((region) => {- if (- !region.clipId ||- region.sourceStartSec === undefined ||- region.sourceEndSec === undefined- ) {+ if (!isAnchored(region)) {return [region];}const span = anchoredToRawSpanSec(@@ -300,6 +312,91 @@ export function reanchorRegions(document: AxcutDocument, clips: AxcutClip[]): Ax);}+/** A clip that does not yet describe a real stretch of media: either it carries no+ * source extent at all (what `migrateProjectDataToAxcutDocument` produces — the+ * migration is pure, so it cannot probe the file for a duration), or it still sits at+ * the pre-probe placeholder length. Both mean "waiting for the real duration". */+function clipAwaitsProbedDuration(clip: AxcutClip, assetId: string): boolean {+ if (clip.assetId !== assetId || clip.sourceStartSec !== 0) return false;+ const end = clip.sourceEndSec ?? 0;+ if (end <= clip.sourceStartSec) return true; // no extent at all (v2 migration)+ return Math.abs(end - PLACEHOLDER_DURATION_SEC) < 0.01; // still the placeholder+}++/**+ * Apply a freshly probed media duration to the clips still waiting for it, and bring+ * the modifiers along.+ *+ * This is the moment a project imported from the legacy (v1.7 / `PROJECT_VERSION` 2)+ * format becomes fully described. That format has no clip list at all — one recording+ * plus regions — so migration mints a single clip with NO source extent and leaves+ * every region UNANCHORED (anchoring needs a clip with real extent; dropping the+ * regions instead would lose user data). The duration only shows up later, when the+ * renderer loads the media. Without this step the clip keeps a zero extent forever and+ * the regions never get anchored.+ *+ * Regions are handled by provenance, never wholesale: already-anchored ones only get+ * their derived ms refreshed against the new layout (`rederiveRegionMs`), while+ * unanchored ones are anchored from the RAW ms they still carry. Re-anchoring+ * everything would mint fresh fragment ids for regions whose anchors are already+ * correct.+ *+ * Returns the document unchanged when no clip is waiting, so callers can invoke it on+ * every `loadedmetadata` without guarding.+ */+export function applyProbedDuration(+ document: AxcutDocument,+ assetId: string,+ durationSec: number,+): AxcutDocument {+ if (!Number.isFinite(durationSec) || durationSec <= 0) return document;+ const clips = document.timeline.clips;+ if (!clips.some((clip) => clipAwaitsProbedDuration(clip, assetId))) return document;++ // Widening a clip pushes everything after it down the ruler by the same delta.+ let shiftSec = 0;+ const nextClips = clips.map((clip) => {+ const shifted = {+ ...clip,+ timelineStartSec: clip.timelineStartSec + shiftSec,+ timelineEndSec: clip.timelineEndSec + shiftSec,+ };+ if (!clipAwaitsProbedDuration(clip, assetId)) return shifted;+ const previousLength = clip.timelineEndSec - clip.timelineStartSec;+ shiftSec += durationSec - previousLength;+ return {+ ...shifted,+ sourceEndSec: clip.sourceStartSec + durationSec,+ timelineEndSec: shifted.timelineStartSec + durationSec,+ };+ });++ const withClips: AxcutDocument = {+ ...document,+ assets: document.assets.map((asset) =>+ asset.id === assetId && asset.durationSec == null+ ? { ...asset, durationSec: durationSec }+ : asset,+ ),+ timeline: { ...document.timeline, clips: nextClips },+ };++ // Anchored regions: refresh the derived cache against the new layout.+ const refreshed = rederiveRegionMs(withClips, nextClips);+ // Unanchored regions: NOW anchorable — the clip finally has a real extent. Anchored+ // one at a time so a region that ventilates into several fragments lands in place,+ // and so an already-correct anchor is never re-minted.+ return mapAllRegionCollections(refreshed, (regions, prefix) =>+ regions.flatMap((region) =>+ isAnchored(region)+ ? [region]+ : (anchorRegionsWithDerivedMs([region], nextClips, () =>+ createId(prefix),+ ) as StoredRegion[]),+ ),+ );+}+export function replaceTimeline(document: AxcutDocument,intervals: Interval[],diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex 93158272f..e6e6353cb 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -10,6 +10,7 @@ import { createId } from "../document/ids";import {duplicateClip as duplicateClipInDocument,moveClip as moveClipInDocument,+ PLACEHOLDER_DURATION_SEC,rederiveRegionMs,resequenceClips,} from "../document/timeline";@@ -26,13 +27,13 @@ import { useProjectStore } from "./projectStore";type RegionKind = "zoom" | "trim" | "annotation" | "speed" | "cameraFullscreen";-// Placeholder duration applied to a freshly-inserted clip whose source asset-// hasn't reported its real duration yet (media drag → drop before the preview-// video fires `loadedmetadata`). The renderer's handleLoadedMetadata-// (NewEditorShell) scans for clips sitting at exactly this value and-// auto-corrects them to the probed duration once metadata arrives, so the-// timeline ruler, progress bar, and sourceEndSec all stay in sync.-export const PLACEHOLDER_DURATION_SEC = 60;+// Placeholder duration applied to a freshly-inserted clip whose source asset hasn't+// reported its real duration yet (media drag → drop before the preview video fires+// `loadedmetadata`). `applyProbedDuration` (document layer) swaps it — and the+// extent-less clip a legacy v2 import mints — for the real length once metadata+// arrives. Defined there, re-exported here so existing importers keep working and the+// value has exactly one definition.+export { PLACEHOLDER_DURATION_SEC };interface RegionHandle {kind: RegionKind;