Skip to content

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

26.0 KB
Raw Blame
import { describe, expect, it } from "vitest";
import type { EditorProjectData } from "@/components/video-editor/projectPersistence";
import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import { documentSchema } from "../schema";
import {
	migrateAxcutDocumentToProjectData,
	migrateProjectDataToAxcutDocument,
	migrateRawDocumentToCurrent,
} from "./migrate";

function makeV2Project(overrides: Partial<EditorProjectData> = {}): EditorProjectData {
	return {
		version: 2,
		media: { screenVideoPath: "/recordings/screen.webm" },
		editor: {
			wallpaper: "/wallpapers/wallpaper1.jpg",
			wallpaperMotion: "none",
			shadowIntensity: 0,
			backgroundBlur: 0,
			motionBlurAmount: 0,
			depthOfField: true,
			borderRadius: 0,
			padding: 50,
			cropRegion: { x: 0, y: 0, width: 1, height: 1 },
			zoomRegions: [],
			cameraFullscreenRegions: [],
			autoZoomEnabled: false,
			autoFocusAll: false,
			trimRegions: [],
			speedRegions: [],
			annotationRegions: [],
			aspectRatio: "16:9",
			webcamLayoutPreset: "picture-in-picture",
			webcamMaskShape: "circle",
			webcamMirrored: true,
			webcamReactiveZoom: true,
			webcamSizePreset: 25,
			webcamPosition: { cx: 0.5, cy: 0.5 },
			exportQuality: "good",
			exportFormat: "mp4",
			gifFrameRate: 15,
			gifLoop: true,
			gifSizePreset: "medium",
			cursorTheme: "default",
		},
		...overrides,
	};
}

describe("migrateProjectDataToAxcutDocument", () => {
	it("produces a current-schema document with one asset and one clip from a v2 single-recording project", () => {
		const doc = migrateProjectDataToAxcutDocument(makeV2Project());

		expect(doc.schemaVersion).toBe(9);
		expect(doc.assets).toHaveLength(1);
		const asset = doc.assets[0];
		expect(asset.kind).toBe("video");
		expect(asset.originalPath).toBe("/recordings/screen.webm");
		expect(doc.project.primaryAssetId).toBe(asset.id);

		expect(doc.timeline.clips).toHaveLength(1);
		const clip = doc.timeline.clips[0];
		expect(clip.assetId).toBe(asset.id);
		expect(clip.sourceStartSec).toBe(0);
		expect(clip.sourceEndSec).toBeUndefined();
	});

	it("converts trimRegions to trimRanges on the primary asset (1.5s cut)", () => {
		const doc = migrateProjectDataToAxcutDocument(
			makeV2Project({
				editor: {
					...makeV2Project().editor,
					trimRegions: [{ id: "trim_a", startMs: 1000, endMs: 2500 }],
				},
			}),
		);

		expect(doc.timeline.trimRanges).toHaveLength(1);
		const skip = doc.timeline.trimRanges[0];
		expect(skip.assetId).toBe(doc.assets[0].id);
		expect(skip.startSec).toBeCloseTo(1.0, 3);
		expect(skip.endSec).toBeCloseTo(2.5, 3);
		expect(skip.origin).toBe("user");
	});

	it("converts speedRegions to timeline.speedRanges in seconds", () => {
		const doc = migrateProjectDataToAxcutDocument(
			makeV2Project({
				editor: {
					...makeV2Project().editor,
					speedRegions: [{ id: "spd_a", startMs: 5000, endMs: 8000, speed: 2 }],
				},
			}),
		);
		expect(doc.timeline.speedRanges).toHaveLength(1);
		expect(doc.timeline.speedRanges[0].startSec).toBeCloseTo(5.0, 3);
		expect(doc.timeline.speedRanges[0].endSec).toBeCloseTo(8.0, 3);
	});

	it("converts zoomRegions to seconds with focus normalized", () => {
		const doc = migrateProjectDataToAxcutDocument(
			makeV2Project({
				editor: {
					...makeV2Project().editor,
					zoomRegions: [
						{
							id: "z_1",
							startMs: 0,
							endMs: 2000,
							depth: 4,
							focus: { cx: 1.5, cy: -0.5 },
							focusMode: "manual",
							rotationPreset: "iso" as never,
							customScale: 2.5,
							source: "manual",
							hideCursor: true,
						},
					],
				},
			}),
		);
		expect(doc.zoomRanges).toHaveLength(1);
		const z = doc.zoomRanges[0];
		expect(z.depth).toBe(4);
		expect(z.focus.cx).toBe(1);
		expect(z.focus.cy).toBe(0);
		expect(z.startMs).toBe(0);
		expect(z.endMs).toBe(2000);
		expect(z.customScale).toBe(2.5);
		// `iso`, retired, reads as Left: the angle that kept its look.
		expect(z.rotationPreset).toBe("left");
		expect(z.hideCursor).toBe(true);
	});

	// Up to v1.13.0 the click impact was a zoom option; it is the cursor setting now.
	it("turns a zoom's click impact into the cursor setting", () => {
		const zoom = {
			id: "z_1",
			startMs: 0,
			endMs: 2000,
			depth: 3 as const,
			focus: { cx: 0.5, cy: 0.5 },
		};
		const doc = migrateProjectDataToAxcutDocument(
			makeV2Project({
				editor: {
					...makeV2Project().editor,
					zoomRegions: [{ ...zoom, clickImpact: true } as never],
				},
			}),
		);
		expect(getEditorSettings(doc).cursor.clickImpact).toBe(true);
		expect("clickImpact" in doc.zoomRanges[0]).toBe(false);
	});

	it("converts annotationRegions to seconds with type and content preserved", () => {
		const doc = migrateProjectDataToAxcutDocument(
			makeV2Project({
				editor: {
					...makeV2Project().editor,
					annotationRegions: [
						{
							id: "ann_1",
							startMs: 1000,
							endMs: 3000,
							type: "text",
							content: "Hello",
							position: { x: 4, y: 86 },
							size: { width: 92, height: 12 },
							style: {
								color: "#fff",
								backgroundColor: "transparent",
								fontSize: 24,
								fontFamily: "Inter",
								fontWeight: "bold",
								fontStyle: "normal",
								textDecoration: "none",
								textAlign: "center",
							},
							zIndex: 1,
							annotationSource: "auto-caption",
						},
					],
				},
			}),
		);
		expect(doc.annotations).toHaveLength(1);
		const a = doc.annotations[0];
		expect(a.type).toBe("text");
		expect(a.startMs).toBe(1000);
		expect(a.endMs).toBe(3000);
		expect(a.annotationSource).toBe("auto-caption");
	});

	it("carries a non-identity editor.cropRegion onto the migrated clip", () => {
		const v2 = makeV2Project();
		v2.editor.cropRegion = { x: 0.25, y: 0.25, width: 0.5, height: 0.5 };
		const doc = migrateProjectDataToAxcutDocument(v2);
		expect(doc.timeline.clips).toHaveLength(1);
		expect(doc.timeline.clips[0]?.cropRegion).toEqual({
			x: 0.25,
			y: 0.25,
			width: 0.5,
			height: 0.5,
		});
	});

	it("leaves the migrated clip without a cropRegion for the identity crop", () => {
		const doc = migrateProjectDataToAxcutDocument(makeV2Project());
		expect(doc.timeline.clips[0]?.cropRegion).toBeUndefined();
	});

	it("leaves the migrated clip without a cropRegion when editor.cropRegion is missing", () => {
		const v2 = makeV2Project();
		delete (v2.editor as Partial<typeof v2.editor>).cropRegion;
		const doc = migrateProjectDataToAxcutDocument(v2);
		expect(doc.timeline.clips[0]?.cropRegion).toBeUndefined();
	});

	it.each([
		["NaN", { x: Number.NaN, y: 0, width: 0.5, height: 0.5 }],
		["Infinity", { x: 0, y: 0, width: Number.POSITIVE_INFINITY, height: 0.5 }],
		["-Infinity", { x: 0, y: Number.NEGATIVE_INFINITY, width: 0.5, height: 0.5 }],
	])("ignores a cropRegion with a %s component", (_label, cropRegion) => {
		const v2 = makeV2Project();
		v2.editor.cropRegion = cropRegion;
		const doc = migrateProjectDataToAxcutDocument(v2);
		expect(doc.timeline.clips[0]?.cropRegion).toBeUndefined();
	});

	it("clamps an out-of-range cropRegion into the unit square", () => {
		const v2 = makeV2Project();
		v2.editor.cropRegion = { x: -0.2, y: 0.5, width: 0.6, height: 0.8 };
		const doc = migrateProjectDataToAxcutDocument(v2);
		expect(doc.timeline.clips[0]?.cropRegion).toEqual({ x: 0, y: 0.5, width: 0.6, height: 0.5 });
	});

	it("drops a cropRegion that clamps back to the identity", () => {
		const v2 = makeV2Project();
		v2.editor.cropRegion = { x: -1, y: -1, width: 3, height: 3 };
		const doc = migrateProjectDataToAxcutDocument(v2);
		expect(doc.timeline.clips[0]?.cropRegion).toBeUndefined();
	});

	it.each([
		["zero width", { x: 0.2, y: 0.2, width: 0, height: 0.5 }],
		["negative height", { x: 0.2, y: 0.2, width: 0.5, height: -0.1 }],
		["x at the right edge", { x: 1.5, y: 0.2, width: 0.5, height: 0.5 }],
	])("ignores a cropRegion with %s", (_label, cropRegion) => {
		const v2 = makeV2Project();
		v2.editor.cropRegion = cropRegion;
		const doc = migrateProjectDataToAxcutDocument(v2);
		expect(doc.timeline.clips[0]?.cropRegion).toBeUndefined();
	});

	it("carries cursor tuning keys from a v2 editor into getEditorSettings", () => {
		const v2 = makeV2Project();
		v2.editor.cursorSize = 2.5;
		v2.editor.cursorClickBounce = 0;
		const settings = getEditorSettings(migrateProjectDataToAxcutDocument(v2));
		expect(settings.cursor.size).toBe(2.5);
		expect(settings.cursor.clickBounce).toBe(0);
	});

	it("stores the v2 editor shape under legacyEditor for round-trip", () => {
		const v2 = makeV2Project();
		const doc = migrateProjectDataToAxcutDocument(v2);
		expect(doc.legacyEditor).toMatchObject({
			wallpaper: "/wallpapers/wallpaper1.jpg",
			cursorTheme: "default",
			autoZoomEnabled: false,
		});
	});

	it("keeps migrating a project saved with the retired showTrimWaveform key", () => {
		const v2 = makeV2Project();
		// Projects saved before the setting was removed still carry it.
		const stored = {
			...v2,
			editor: { ...v2.editor, showTrimWaveform: false },
		} as EditorProjectData;
		const doc = migrateProjectDataToAxcutDocument(stored);
		// legacyEditorSchema is a passthrough object, so the retired key rides
		// along inertly rather than failing the parse — and nothing reads it.
		expect(doc.legacyEditor).toMatchObject({ showTrimWaveform: false });
		expect(getEditorSettings(doc)).toEqual(
			getEditorSettings(migrateProjectDataToAxcutDocument(v2)),
		);
	});

	it("handles missing media by creating an empty document", () => {
		const doc = migrateProjectDataToAxcutDocument({
			version: 2,
			editor: makeV2Project().editor,
		});
		expect(doc.assets).toEqual([]);
		expect(doc.timeline.clips).toEqual([]);
		expect(doc.project.primaryAssetId).toBeUndefined();
	});

	it("supports a legacy v1 videoPath-only project", () => {
		const doc = migrateProjectDataToAxcutDocument({
			version: 1,
			videoPath: "/legacy/recording.webm",
			editor: makeV2Project().editor,
		});
		expect(doc.assets).toHaveLength(1);
		expect(doc.assets[0].originalPath).toBe("/legacy/recording.webm");
	});

	it("carries a known webcamVideoPath onto the migrated asset's cameraTrack", () => {
		const doc = migrateProjectDataToAxcutDocument(
			makeV2Project({
				media: {
					screenVideoPath: "/screen.webm",
					webcamVideoPath: "/webcam.webm",
					cursorCaptureMode: "editable-overlay",
				},
			}),
		);
		expect(doc.assets).toHaveLength(1);
		expect(doc.assets[0].originalPath).toBe("/screen.webm");
		expect(doc.assets[0].cameraTrack?.sourcePath).toBe("/webcam.webm");
		expect(doc.assets[0].cameraTrack?.visible).toBe(true);
	});

	it("leaves cameraTrack null when there is no webcamVideoPath", () => {
		const doc = migrateProjectDataToAxcutDocument(makeV2Project());
		expect(doc.assets[0].cameraTrack).toBeNull();
	});
});

describe("migrateAxcutDocumentToProjectData", () => {
	it("round-trips trimRanges back to trimRegions", () => {
		const v2 = makeV2Project({
			editor: {
				...makeV2Project().editor,
				trimRegions: [{ id: "trim_a", startMs: 1000, endMs: 2500 }],
			},
		});
		const doc = migrateProjectDataToAxcutDocument(v2);
		const back = migrateAxcutDocumentToProjectData(doc);
		expect(back.editor.trimRegions).toHaveLength(1);
		expect(back.editor.trimRegions[0].startMs).toBe(1000);
		expect(back.editor.trimRegions[0].endMs).toBe(2500);
	});

	it("round-trips legacyEditor fields back into editor.*", () => {
		const v2 = makeV2Project();
		const doc = migrateProjectDataToAxcutDocument(v2);
		const back = migrateAxcutDocumentToProjectData(doc);
		expect(back.editor.wallpaper).toBe("/wallpapers/wallpaper1.jpg");
		expect(back.editor.cursorTheme).toBe("default");
		expect(back.editor.webcamMaskShape).toBe("circle");
	});

	it("reads a legacyEditor blur switch as the amount it drew", () => {
		const doc = migrateProjectDataToAxcutDocument(makeV2Project());
		const { backgroundBlur: _amount, ...legacy } = doc.legacyEditor as Record<string, unknown>;
		const back = migrateAxcutDocumentToProjectData({
			...doc,
			legacyEditor: { ...legacy, showBlur: true },
		});
		expect(back.editor.backgroundBlur).toBe(0.5);
	});

	it("defaults wallpaperMotion to none when legacyEditor lacks it", () => {
		const doc = migrateProjectDataToAxcutDocument(makeV2Project());
		const { wallpaperMotion: _omitted, ...legacy } = doc.legacyEditor as Record<string, unknown>;
		const back = migrateAxcutDocumentToProjectData({ ...doc, legacyEditor: legacy });
		expect(back.editor.wallpaperMotion).toBe("none");
	});

	it("keeps a legacy wallpaperMotion over the default", () => {
		const v2 = makeV2Project({
			editor: { ...makeV2Project().editor, wallpaperMotion: "aurora" },
		});
		const back = migrateAxcutDocumentToProjectData(migrateProjectDataToAxcutDocument(v2));
		expect(back.editor.wallpaperMotion).toBe("aurora");
	});

	it("round-trips depthOfField: on by default, an explicit off stays off", () => {
		const roundTrip = (depthOfField: boolean) =>
			migrateAxcutDocumentToProjectData(
				migrateProjectDataToAxcutDocument(
					makeV2Project({ editor: { ...makeV2Project().editor, depthOfField } }),
				),
			).editor.depthOfField;
		expect(roundTrip(true)).toBe(true);
		expect(roundTrip(false)).toBe(false);
	});

	it("round-trips zoomRegions and annotationRegions back to ms", () => {
		const v2 = makeV2Project({
			editor: {
				...makeV2Project().editor,
				zoomRegions: [
					{
						id: "z_1",
						startMs: 0,
						endMs: 2000,
						depth: 4,
						focus: { cx: 0.5, cy: 0.5 },
						hideCursor: true,
					},
					{ id: "z_2", startMs: 3000, endMs: 4000, depth: 2, focus: { cx: 0.5, cy: 0.5 } },
				],
				annotationRegions: [
					{
						id: "ann_1",
						startMs: 1000,
						endMs: 3000,
						type: "text",
						content: "Hello",
						position: { x: 50, y: 50 },
						size: { width: 30, height: 20 },
						style: {
							color: "#fff",
							backgroundColor: "transparent",
							fontSize: 24,
							fontFamily: "Inter",
							fontWeight: "bold",
							fontStyle: "normal",
							textDecoration: "none",
							textAlign: "center",
						},
						zIndex: 1,
					},
				],
			},
		});
		const doc = migrateProjectDataToAxcutDocument(v2);
		const back = migrateAxcutDocumentToProjectData(doc);
		expect(back.editor.zoomRegions[0].startMs).toBe(0);
		expect(back.editor.zoomRegions[0].endMs).toBe(2000);
		expect(back.editor.zoomRegions[0].hideCursor).toBe(true);
		expect(back.editor.annotationRegions[0].startMs).toBe(1000);
		expect(back.editor.annotationRegions[0].endMs).toBe(3000);
	});

	it("rebuilds media.screenVideoPath from the primary asset", () => {
		const v2 = makeV2Project();
		const doc = migrateProjectDataToAxcutDocument(v2);
		const back = migrateAxcutDocumentToProjectData(doc);
		expect(back.media?.screenVideoPath).toBe("/recordings/screen.webm");
		expect(back.videoPath).toBe("/recordings/screen.webm");
	});

	it("surfaces the primary asset's cameraTrack as media.webcamVideoPath", () => {
		const v2 = makeV2Project({
			media: {
				screenVideoPath: "/recordings/screen.webm",
				webcamVideoPath: "/recordings/screen-webcam.webm",
			},
		});
		const doc = migrateProjectDataToAxcutDocument(v2);
		const back = migrateAxcutDocumentToProjectData(doc);
		expect(back.media?.webcamVideoPath).toBe("/recordings/screen-webcam.webm");
	});

	it("clamps bad zoom focus to [0, 1] on forward migration", () => {
		const doc = migrateProjectDataToAxcutDocument(
			makeV2Project({
				editor: {
					...makeV2Project().editor,
					zoomRegions: [
						{
							id: "z_1",
							startMs: 0,
							endMs: 1000,
							depth: 1,
							focus: { cx: 2.5, cy: -0.5 },
						},
					],
				},
			}),
		);
		expect(doc.zoomRanges[0].focus.cx).toBe(1);
		expect(doc.zoomRanges[0].focus.cy).toBe(0);
	});
});

// Load-time migration helper. Replaces the `z.preprocess` chain that used to
// run on every `documentSchema.parse(...)` call site. The pre-hoist chain ran
// v3→v4 and v4→v5 on every parse, including in-memory parses that were
// already v5; the post-hoist chain runs once at the disk (or localStorage)
// read site, and the in-memory `documentSchema.parse` is a pure v6 validator.

describe("migrateRawDocumentToCurrent", () => {
	const createdAt = "2024-01-01T00:00:00.000Z";

	function makeV3Doc(overrides: Record<string, unknown> = {}) {
		return {
			schemaVersion: 3,
			project: { id: "p", title: "t", createdAt, updatedAt: createdAt },
			assets: [
				{ id: "asset_1", kind: "video", label: "a1", originalPath: "/a1.mp4" },
				{ id: "asset_2", kind: "video", label: "a2", originalPath: "/a2.mp4" },
			],
			cameraTrack: { sourcePath: "/cam.mp4", startMs: 0, offsetMs: 0, visible: true },
			...overrides,
		};
	}

	function makeV4Doc(overrides: Record<string, unknown> = {}) {
		return {
			schemaVersion: 4,
			project: { id: "p", title: "t", createdAt, updatedAt: createdAt },
			assets: [{ id: "a", kind: "video", label: "A", originalPath: "/a.mp4", cameraTrack: null }],
			timeline: {
				clips: [
					{
						id: "c1",
						assetId: "a",
						sourceStartSec: 0,
						sourceEndSec: 10,
						timelineStartSec: 0,
						timelineEndSec: 10,
						origin: "user",
					},
				],
			},
			...overrides,
		};
	}

	it("upgrades a v3 document to v8 (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
		// what produces the final v5 shape with defaults filled in.
		const migrated = documentSchema.parse(
			migrateRawDocumentToCurrent(
				makeV3Doc({
					project: {
						id: "p",
						title: "t",
						createdAt,
						updatedAt: createdAt,
						primaryAssetId: "asset_2",
					},
				}),
			),
		);
		expect(migrated.schemaVersion).toBe(9);
		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 v8 (anchors modifiers onto clips)", () => {
		const migrated = migrateRawDocumentToCurrent(
			makeV4Doc({
				zoomRanges: [
					{ id: "z1", startMs: 2000, endMs: 5000, depth: 3, focus: { cx: 0.5, cy: 0.5 } },
				],
			}),
		) as Record<string, unknown>;
		expect(migrated.schemaVersion).toBe(9);
		const zooms = migrated.zoomRanges as Array<Record<string, unknown>>;
		expect(zooms).toHaveLength(1);
		expect(zooms[0]).toMatchObject({ id: "z1", clipId: "c1", depth: 3 });
	});

	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: 9 });
		// 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: 9 });
	});

	it("passes non-document input through unchanged (the schema is the gate, not this helper)", () => {
		// null, primitives, arrays — none of these are v3/v4 documents, so the
		// upgraders return them untouched. The downstream `documentSchema.parse`
		// is what rejects them via the `schemaVersion` literal.
		expect(migrateRawDocumentToCurrent(null)).toBe(null);
		expect(migrateRawDocumentToCurrent(undefined)).toBe(undefined);
		expect(migrateRawDocumentToCurrent(42)).toBe(42);
		expect(migrateRawDocumentToCurrent("not-a-doc")).toBe("not-a-doc");
		expect(migrateRawDocumentToCurrent([])).toEqual([]);
	});

	it("passes v2 input through unchanged (the legacy migrator is a separate path)", () => {
		// The pre-hoist schema's `z.preprocess` also passed v2 through; the
		// post-hoist helper keeps the same shape so `documentSchema.parse` is
		// the single rejection point for unknown versions.
		const v2ish = { schemaVersion: 2, project: { id: "p" } };
		const out = migrateRawDocumentToCurrent(v2ish) as Record<string, unknown>;
		expect(out.schemaVersion).toBe(2);
	});

	it("the upgraded v5 result round-trips through documentSchema.parse with no error", () => {
		// The whole point of the hoist: after `migrateRawDocumentToCurrent`
		// runs once at load, the in-memory parse is a pure v6 validation
		// step. This is the contract every load site relies on.
		const upgraded = migrateRawDocumentToCurrent(
			makeV3Doc({
				project: {
					id: "p",
					title: "t",
					createdAt,
					updatedAt: createdAt,
					primaryAssetId: "asset_1",
				},
			}),
		);
		expect(() => documentSchema.parse(upgraded)).not.toThrow();
	});
});

// ─── The ghost trims of b9e0f1ff ─────────────────────────────────────────────
// That build let a cut authored from the voiceover lane be anchored on the AUDIO asset
// the words belonged to. It removed nothing from the film, the preview or the export —
// it only struck the word through. Now that both lanes read one removed set, leaving
// those rows behind would keep striking words through for a cut that never happened.

describe("dropping trims anchored to audio", () => {
	const createdAt = "2024-01-01T00:00:00.000Z";

	function docWith(trimRanges: unknown[], assets?: unknown[]) {
		return {
			schemaVersion: 9,
			project: { id: "p", title: "t", createdAt, updatedAt: createdAt },
			assets: assets ?? [
				{ id: "vid", kind: "video", label: "v", originalPath: "/v.mp4", cameraTrack: null },
				{ id: "aud", kind: "audio", label: "a", originalPath: "/a.mp3", cameraTrack: null },
			],
			transcript: null,
			transcripts: [],
			timeline: {
				clips: [
					{
						id: "c1",
						assetId: "vid",
						sourceStartSec: 0,
						sourceEndSec: 10,
						timelineStartSec: 0,
						timelineEndSec: 10,
						wordRefs: [],
						origin: "user",
						reason: "",
					},
				],
				gaps: [],
				trimRanges,
				muteRanges: [],
				speedRanges: [],
				captionRanges: [],
			},
			annotations: [],
			zoomRanges: [],
			audioTracks: [],
			legacyEditor: null,
		};
	}

	const trims = (raw: unknown) =>
		(
			(raw as Record<string, Record<string, unknown[]>>).timeline.trimRanges as Array<{
				id: string;
			}>
		).map((t) => t.id);

	const ghost = {
		id: "ghost",
		assetId: "aud",
		clipId: "vo_frag",
		startSec: 1,
		endSec: 2,
		origin: "user",
		reason: "",
	};
	const legacy = {
		id: "legacy",
		assetId: "vid",
		startSec: 1,
		endSec: 2,
		origin: "user",
		reason: "",
	};
	const orphan = {
		id: "orphan",
		assetId: "vid",
		clipId: "deleted",
		startSec: 3,
		endSec: 4,
		origin: "user",
		reason: "",
	};

	it("drops a trim anchored to an audio asset", () => {
		expect(trims(migrateRawDocumentToCurrent(docWith([ghost, legacy])))).toEqual(["legacy"]);
	});

	it("keeps a pre-v7 trim that names no clip, and one whose clip is gone", () => {
		// The first is asset-wide back-compat; the second can still come back through undo.
		expect(trims(migrateRawDocumentToCurrent(docWith([legacy, orphan])))).toEqual([
			"legacy",
			"orphan",
		]);
	});

	it("is idempotent, and returns the document untouched when there is nothing to sweep", () => {
		const clean = docWith([legacy]);
		expect(migrateRawDocumentToCurrent(clean)).toBe(clean);
		const swept = migrateRawDocumentToCurrent(docWith([ghost, legacy]));
		expect(migrateRawDocumentToCurrent(swept)).toBe(swept);
	});

	it("leaves a project with no audio asset entirely alone", () => {
		const noAudio = docWith(
			[legacy],
			[{ id: "vid", kind: "video", label: "v", originalPath: "/v.mp4", cameraTrack: null }],
		);
		expect(migrateRawDocumentToCurrent(noAudio)).toBe(noAudio);
	});

	it("still parses after the sweep", () => {
		expect(() =>
			documentSchema.parse(migrateRawDocumentToCurrent(docWith([ghost, legacy]))),
		).not.toThrow();
	});
});

// ─── Transcripts written end-before-start ────────────────────────────────────
// The transcription core before a9fdd97ff clamped an end to the audio length but not its
// start, so a hallucination past the end of the audio was stored inverted. One such word
// failed the schema and hid the whole project from the list.

describe("repairing inverted transcript timings", () => {
	const createdAt = "2024-01-01T00:00:00.000Z";
	const inverted = { startSec: 13.5, endSec: 6.7626875 };

	function docWith(start: number, end: number) {
		const transcript = {
			assetId: "vid",
			language: "auto",
			segments: [
				{
					id: "seg_1",
					kind: "speech",
					startSec: start,
					endSec: end,
					text: "very",
					wordIds: ["word_1"],
				},
				{
					id: "seg_2",
					kind: "speech",
					startSec: start,
					endSec: end,
					text: "good",
					wordIds: ["word_2"],
				},
			],
			words: [
				{ id: "word_1", segmentId: "seg_1", startSec: start, endSec: end, text: "very" },
				{ id: "word_2", segmentId: "seg_2", startSec: start, endSec: end, text: "good" },
			],
		};
		return {
			schemaVersion: 9,
			project: { id: "p", title: "t", createdAt, updatedAt: createdAt },
			assets: [{ id: "vid", kind: "video", label: "v", originalPath: "/v.mp4", cameraTrack: null }],
			transcript,
			transcripts: [transcript],
			timeline: {
				clips: [],
				gaps: [],
				trimRanges: [],
				muteRanges: [],
				speedRanges: [],
				captionRanges: [],
			},
			annotations: [],
			zoomRanges: [],
			audioTracks: [],
			legacyEditor: null,
		};
	}

	it("raises the end to the start, keeps every word, and parses again", () => {
		const broken = docWith(inverted.startSec, inverted.endSec);
		expect(() => documentSchema.parse(broken)).toThrow("endSec must be greater than or equal");
		const doc = documentSchema.parse(migrateRawDocumentToCurrent(broken));
		for (const transcript of [doc.transcript, ...doc.transcripts]) {
			expect(transcript?.words.map((w) => [w.id, w.text, w.startSec, w.endSec])).toEqual([
				["word_1", "very", 13.5, 13.5],
				["word_2", "good", 13.5, 13.5],
			]);
			expect(transcript?.segments.map((s) => [s.wordIds, s.endSec])).toEqual([
				[["word_1"], 13.5],
				[["word_2"], 13.5],
			]);
		}
	});

	it("is idempotent, and returns the document untouched when nothing is inverted", () => {
		const clean = docWith(1, 2);
		expect(migrateRawDocumentToCurrent(clean)).toBe(clean);
		const repaired = migrateRawDocumentToCurrent(docWith(inverted.startSec, inverted.endSec));
		expect(migrateRawDocumentToCurrent(repaired)).toBe(repaired);
	});
});