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
refactor: drop legacy 'native' AspectRatio via v6 schema migration
Etienne Lescote756499d6214
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.tsindex 1a2915751..2d2ecd705 100644--- a/electron/ai-edition/document-service.test.ts+++ b/electron/ai-edition/document-service.test.ts@@ -24,9 +24,9 @@ describe("DocumentService", () => {});describe("createProject", () => {- it("creates a v5 doc with the given title and writes it to disk", async () => {+ it("creates a v6 doc with the given title and writes it to disk", async () => {const doc = await service.createProject("Demo Project");- expect(doc.schemaVersion).toBe(5);+ expect(doc.schemaVersion).toBe(6);expect(doc.project.title).toBe("Demo Project");expect(doc.project.id).toMatch(/^proj_/);expect(doc.assets).toEqual([]);@@ -34,7 +34,7 @@ describe("DocumentService", () => {const filePath = path.join(tempDir, `${doc.project.id}.openscreen`);const raw = await fs.readFile(filePath, "utf8");expect(JSON.parse(raw)).toMatchObject({- schemaVersion: 5,+ schemaVersion: 6,project: { title: "Demo Project" },});});diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsxindex eab949305..ce21ac464 100644--- a/src/components/ai-edition/ExportDialog.tsx+++ b/src/components/ai-edition/ExportDialog.tsx@@ -183,9 +183,10 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {// so the sizes shown match what the export produces. Read through `getEditorSettings` — the// same typed façade the ratio dropdown writes through and `buildSceneDescription` reads — so// this dialog can't drift from the compositor if the storage ever moves. `resolveAspectRatioValue`- // owns the legacy "native" case (uncropped reference asset), previously hand-rolled here.+ // is the single funnel preview and export agree on; the v5→v6 upgrader retires the legacy+ // "native" AspectRatio so no document-context argument is needed here.const EXPORT_ASPECT = useMemo(- () => resolveAspectRatioValue(document, getEditorSettings(document).aspectRatio),+ () => resolveAspectRatioValue(getEditorSettings(document).aspectRatio),[document],);// Output dimensions the export will produce for a given tier, from the (crop-aware)diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsxindex 63e7347d2..80abde6aa 100644--- a/src/components/ai-edition/PreviewCanvas.tsx+++ b/src/components/ai-edition/PreviewCanvas.tsx@@ -185,12 +185,12 @@ export function PreviewCanvas(props: PreviewCanvasProps) {// exactly what the frame is styled to (`width: frameSize.width` a few lines below), so it's// used directly everywhere `canvasSize` used to be — one source of truth, no separate// observer that can desync from it.- // `resolveAspectRatioValue`, not bare `getAspectRatioValue`: the latter has no document to- // resolve the legacy "native" selection against and answers 16/9 for it, so a project saved- // with "native" over portrait footage framed the preview 16:9 while `pickOutputDims` handed- // the compositor a portrait `output` — preview and export disagreed on the frame's shape.+ // `resolveAspectRatioValue`, not bare `getAspectRatioValue`: keeps preview and export+ // routing through the same funnel — the v5→v6 upgrader rewrites the legacy "native"+ // selection to a concrete `"W:H"` token, so both paths agree on the resolved shape+ // without an extra document argument.const frameSize = useMemo(() => {- const ratio = resolveAspectRatioValue(document, settings.aspectRatio);+ const ratio = resolveAspectRatioValue(settings.aspectRatio);const { width: containerWidth, height: containerHeight } = containerSize;if (containerWidth <= 0 || containerHeight <= 0)return { width: containerWidth, height: containerHeight };@@ -200,7 +200,7 @@ export function PreviewCanvas(props: PreviewCanvasProps) {}const width = containerWidth;return { width: Math.round(width), height: Math.round(width / ratio) };- }, [containerSize, settings.aspectRatio, document]);+ }, [containerSize, settings.aspectRatio]);// Crop is per-clip (see clipSchema.cropRegion) — resolve it from whichever// clip the playhead is currently inside, the same lookup VirtualPreviewdiff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsxindex d75da33a9..1cbab2988 100644--- a/src/components/ai-edition/v4/V4Timeline.tsx+++ b/src/components/ai-edition/v4/V4Timeline.tsx@@ -30,7 +30,7 @@ import { ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";import { useScopedT } from "@/contexts/I18nContext";import { useAudioPeaks } from "@/hooks/useAudioPeaks";import { createId } from "@/lib/ai-edition/document/ids";-import { collectNativeFormats, referenceClipDims } from "@/lib/ai-edition/document/outputFormat";+import { collectNativeFormats } from "@/lib/ai-edition/document/outputFormat";import type { AxcutClip } from "@/lib/ai-edition/schema";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";@@ -46,11 +46,7 @@ import {} from "@/lib/ai-edition/timeline/trim-mapping";import { buildAutoZoomSuggestions } from "@/lib/ai-edition/timeline/zoom-suggestions";import { nativeBridgeClient } from "@/native/client";-import {- ASPECT_RATIO_PRESETS,- getAspectRatioLabel,- toAspectRatioToken,-} from "@/utils/aspectRatioUtils";+import { ASPECT_RATIO_PRESETS, getAspectRatioLabel } from "@/utils/aspectRatioUtils";import { TransportBar } from "../TransportBar";import type { VideoSource } from "../VirtualPreview";import styles from "./EditorShellV4.module.css";@@ -271,16 +267,6 @@ export function V4Timeline({// stays a pure list of fixed choices, and "which shapes are my clips" lives solely in ORIGINAL// (no more per-preset badge, which split that one answer across two places).const timelineIsMixed = nativeFormats.length > 1;- // A project saved before the shapes were enumerated still stores "native". Resolve it to the- // shape it currently means so the menu highlights a real row (and the button names a real- // ratio) instead of showing a selection that matches nothing. Picking that row rewrites the- // document to the concrete token — which is how those projects self-migrate off the value- // that silently moved with the clip list.- const activeToken = useMemo(() => {- if (settings.aspectRatio !== "native" || !document) return settings.aspectRatio;- const reference = referenceClipDims(document);- return toAspectRatioToken(reference.width, reference.height) ?? settings.aspectRatio;- }, [settings.aspectRatio, document]);const [aspectMenuOpen, setAspectMenuOpen] = useState(false);const [autoEnhanceOpen, setAutoEnhanceOpen] = useState(false);@@ -1115,7 +1101,7 @@ export function V4Timeline({title={t("toolbar.aspectRatio")}aria-label={t("toolbar.aspectRatio")}>- {getAspectRatioLabel(activeToken)}+ {getAspectRatioLabel(settings.aspectRatio)}<ChevronDown size={10} /></button></PopoverTrigger>@@ -1134,7 +1120,7 @@ export function V4Timeline({type="button"key={ratio}className={`${styles.recMenuRow}${- ratio === activeToken ? ` ${styles.active}` : ""+ ratio === settings.aspectRatio ? ` ${styles.active}` : ""}`}onClick={() => {void setSettings({ aspectRatio: ratio });@@ -1152,7 +1138,7 @@ export function V4Timeline({type="button"key={format.token}className={`${styles.recMenuRow}${- format.token === activeToken ? ` ${styles.active}` : ""+ format.token === settings.aspectRatio ? ` ${styles.active}` : ""}`}onClick={() => {void setSettings({ aspectRatio: format.token });diff --git a/src/lib/ai-edition/document/migrate.test.ts b/src/lib/ai-edition/document/migrate.test.tsindex 2b801de15..9b9b0bfcd 100644--- a/src/lib/ai-edition/document/migrate.test.ts+++ b/src/lib/ai-edition/document/migrate.test.ts@@ -43,7 +43,7 @@ describe("migrateProjectDataToAxcutDocument", () => {it("produces a v3 document with one asset and one clip from a v2 single-recording project", () => {const doc = migrateProjectDataToAxcutDocument(makeV2Project());- expect(doc.schemaVersion).toBe(5);+ expect(doc.schemaVersion).toBe(6);expect(doc.assets).toHaveLength(1);const asset = doc.assets[0];expect(asset.kind).toBe("video");diff --git a/src/lib/ai-edition/document/outputFormat.test.ts b/src/lib/ai-edition/document/outputFormat.test.tsindex 9c16552c6..c3490e8ee 100644--- a/src/lib/ai-edition/document/outputFormat.test.ts+++ b/src/lib/ai-edition/document/outputFormat.test.ts@@ -225,13 +225,7 @@ describe("pickOutputDims", () => {[asset("a1", 1366, 768), asset("a2", 3840, 2160)],[clip("c1", "a1"), clip("c2", "a2")],);- const tokens: AspectRatio[] = [- ...ASPECT_RATIO_PRESETS,- "683:384",- "64:27",- "1023:767",- "native",- ];+ const tokens: AspectRatio[] = [...ASPECT_RATIO_PRESETS, "683:384", "64:27", "1023:767"];for (const token of tokens) {const out = pickOutputDims(d, token);expect(out.width % 2, `width for ${token}`).toBe(0);@@ -256,14 +250,6 @@ describe("pickOutputDims", () => {expect(pickOutputDims(after, "16:9")).toEqual({ width: 3840, height: 2160 });});- it('legacy "native" still resolves to the reference clip, drift included', () => {- const portraitWins = doc(- [asset("a1", 1920, 1080), asset("a2", 2160, 3840)],- [clip("c1", "a1"), clip("c2", "a2")],- );- expect(pickOutputDims(portraitWins, "native")).toEqual({ width: 2160, height: 3840 });- });-it("sizes the output off the cropped footprint, not the raw 4K asset", () => {// A single 4K clip cropped to a 16:9 half-width strip: the output must rasterise at the// crop's real size (1920x1080), not the asset's 3840x2160. Before the reference went@@ -277,18 +263,13 @@ describe("pickOutputDims", () => {});describe("resolveAspectRatioValue", () => {- it('resolves legacy "native" against the document instead of the 16/9 fallback', () => {- const d = doc([asset("a1", 1080, 1920)], [clip("c1", "a1")]);- expect(resolveAspectRatioValue(d, "native")).toBeCloseTo(1080 / 1920, 6);- });-- it('falls back to 16/9 for "native" with no document (preview before load)', () => {- expect(resolveAspectRatioValue(null, "native")).toBeCloseTo(16 / 9, 6);- });-+ // The legacy `"native"` AspectRatio is retired — the v5→v6 upgrader (see+ // `src/lib/ai-edition/schema/index.test.ts` — "v5 -> v6 native AspectRatio+ // migration") rewrites every stored "native" to a concrete `"W:H"` token at load+ // time, so by the time this function runs there is no document context to thread+ // through. What remains is a thin wrapper around `getAspectRatioValue`.it("passes concrete tokens straight through", () => {- const d = doc([asset("a1", 1080, 1920)], [clip("c1", "a1")]);- expect(resolveAspectRatioValue(d, "4:5")).toBeCloseTo(0.8, 6);- expect(resolveAspectRatioValue(d, "64:27")).toBeCloseTo(64 / 27, 6);+ expect(resolveAspectRatioValue("4:5")).toBeCloseTo(0.8, 6);+ expect(resolveAspectRatioValue("64:27")).toBeCloseTo(64 / 27, 6);});});diff --git a/src/lib/ai-edition/document/outputFormat.ts b/src/lib/ai-edition/document/outputFormat.tsindex 602db3aa5..faa598ef3 100644--- a/src/lib/ai-edition/document/outputFormat.ts+++ b/src/lib/ai-edition/document/outputFormat.ts@@ -18,7 +18,6 @@ import { calculateEffectiveSourceDimensions } from "@/lib/exporter/mp4ExportSettimport {type AspectRatio,getAspectRatioValue,- getNativeAspectRatioValue,toAspectRatioToken,} from "@/utils/aspectRatioUtils";import type { AxcutAsset, AxcutClip, AxcutDocument } from "../schema";@@ -225,19 +224,13 @@ export function collectNativeFormats(}/**- * Numeric ratio for a stored selection, with the document available to resolve the legacy- * `"native"` value. Every consumer that frames or sizes the output must go through this rather- * than bare `getAspectRatioValue`, which has no document and falls back to 16/9.+ * Numeric ratio for a stored selection. v6 documents never carry the legacy `"native"`+ * AspectRatio (the v5→v6 upgrader rewrites it to a concrete `"W:H"` token), so resolution+ * is a single token lookup. Kept as a function so the preview / export path still has a+ * single funnel — if storage ever moves, this is the one place to update.*/-export function resolveAspectRatioValue(- document: AxcutDocument | null | undefined,- aspectRatio: AspectRatio,- probedAssetDims: Record<string, Dims> = {},-): number {- if (aspectRatio !== "native") return getAspectRatioValue(aspectRatio);- if (!document) return getAspectRatioValue("native");- const reference = referenceClipDims(document, probedAssetDims);- return getNativeAspectRatioValue(reference.width, reference.height);+export function resolveAspectRatioValue(aspectRatio: AspectRatio): number {+ return getAspectRatioValue(aspectRatio);}/**@@ -261,7 +254,7 @@ export function pickOutputDims(probedAssetDims: Record<string, Dims> = {},): Dims {const reference = referenceClipDims(document, probedAssetDims);- const ratio = resolveAspectRatioValue(document, aspectRatio, probedAssetDims);+ const ratio = resolveAspectRatioValue(aspectRatio);const longSide = toEvenPx(Math.max(reference.width, reference.height));if (ratio >= 1) {return { width: longSide, height: toEvenPx(longSide / ratio) };diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.tsindex 4b416a8b2..83a11ab6a 100644--- a/src/lib/ai-edition/schema/index.test.ts+++ b/src/lib/ai-edition/schema/index.test.ts@@ -14,9 +14,9 @@ import {zoomRegionSchema,} from "./index";-describe("axcut-schema v5", () => {- it("uses schema version 4", () => {- expect(axcutSchemaVersion).toBe(5);+describe("axcut-schema v6", () => {+ it("uses schema version 6", () => {+ expect(axcutSchemaVersion).toBe(6);});it("rejects unknown schema versions", () => {@@ -28,9 +28,9 @@ describe("axcut-schema v5", () => {).toThrow();});- it("createEmptyDocument returns a valid v5 doc with empty collections", () => {+ it("createEmptyDocument returns a valid v6 doc with empty collections", () => {const doc = createEmptyDocument({ projectId: "proj_1", title: "Demo" });- expect(doc.schemaVersion).toBe(5);+ expect(doc.schemaVersion).toBe(6);expect(doc.assets).toEqual([]);expect(doc.timeline.clips).toEqual([]);expect(doc.timeline.trimRanges).toEqual([]);@@ -255,7 +255,7 @@ describe("axcut-schema v5", () => {const doc = documentSchema.parse(v3Doc({ project: { ...v3Doc().project, primaryAssetId: "asset_2" } }),);- expect(doc.schemaVersion).toBe(5);+ expect(doc.schemaVersion).toBe(6);expect((doc as Record<string, unknown>).cameraTrack).toBeUndefined();expect(doc.assets.find((a) => a.id === "asset_1")?.cameraTrack).toBeNull();expect(doc.assets.find((a) => a.id === "asset_2")?.cameraTrack?.sourcePath).toBe("/cam.mp4");@@ -269,7 +269,7 @@ describe("axcut-schema v5", () => {it("is a no-op when the v3 document has no legacy cameraTrack", () => {const doc = documentSchema.parse(v3Doc({ cameraTrack: null }));- expect(doc.schemaVersion).toBe(5);+ expect(doc.schemaVersion).toBe(6);for (const asset of doc.assets) {expect(asset.cameraTrack).toBeNull();}@@ -407,7 +407,7 @@ describe("v4 -> v5 clip-anchored modifier migration", () => {],}),);- expect(doc.schemaVersion).toBe(5);+ expect(doc.schemaVersion).toBe(6);expect(doc.zoomRanges).toHaveLength(1);const z = doc.zoomRanges[0];expect(z).toMatchObject({ id: "z1", clipId: "clip_a", depth: 3 });@@ -469,7 +469,7 @@ describe("v4 -> v5 clip-anchored modifier migration", () => {expect(doc.zoomRanges[0].clipId).toBeUndefined();});- it("is idempotent — re-parsing an already-v5 document changes nothing", () => {+ it("is idempotent — re-parsing the migrated document changes nothing", () => {const once = documentSchema.parse(makeV4Doc({zoomRanges: [@@ -481,3 +481,162 @@ describe("v4 -> v5 clip-anchored modifier migration", () => {expect(twice).toEqual(once);});});++// --- v5 -> v6 native AspectRatio migration -----------------------------------+// `"native"` used to be a runtime-only sentinel that resolved to the timeline's largest+// clip. v6 makes that resolution permanent by baking the concrete `"W:H"` token into the+// document. After this upgrader runs, no document ever contains `"native"` again — the+// union arm in `AspectRatio` is dropped, and the runtime bridge in+// `lib/ai-edition/document/outputFormat` is no longer needed.++describe("v5 -> v6 native AspectRatio migration", () => {+ function makeV5Doc(overrides: Record<string, unknown> = {}) {+ const createdAt = "2024-01-01T00:00:00.000Z";+ return {+ schemaVersion: 5,+ project: { id: "p1", title: "v5-aspect", createdAt, updatedAt: createdAt },+ assets: [+ { id: "asset_f", kind: "video", label: "A", originalPath: "/a.mp4", cameraTrack: null },+ ],+ timeline: {+ clips: [+ {+ id: "clip_a",+ assetId: "asset_f",+ sourceStartSec: 0,+ sourceEndSec: 30,+ timelineStartSec: 0,+ timelineEndSec: 30,+ origin: "user",+ },+ ],+ },+ ...overrides,+ };+ }++ it("rewrites legacy aspectRatio === 'native' to the largest clip's concrete token", () => {+ const doc = documentSchema.parse(+ makeV5Doc({+ legacyEditor: { aspectRatio: "native" },+ assets: [+ {+ id: "asset_f",+ kind: "video",+ label: "A",+ originalPath: "/a.mp4",+ cameraTrack: null,+ video: { width: 1920, height: 1080 },+ },+ ],+ }),+ );+ expect(doc.schemaVersion).toBe(6);+ expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("16:9");+ });++ it("picks the largest clip when the timeline is mixed-shape", () => {+ const doc = documentSchema.parse({+ schemaVersion: 5,+ project: {+ id: "p1",+ title: "mixed",+ createdAt: "2024-01-01T00:00:00.000Z",+ updatedAt: "2024-01-01T00:00:00.000Z",+ },+ assets: [+ {+ id: "asset_f",+ kind: "video",+ label: "A",+ originalPath: "/a.mp4",+ cameraTrack: null,+ video: { width: 1920, height: 1080 },+ },+ {+ id: "asset_g",+ kind: "video",+ label: "B",+ originalPath: "/b.mp4",+ cameraTrack: null,+ video: { width: 2160, height: 3840 },+ },+ ],+ timeline: {+ clips: [+ {+ id: "clip_a",+ assetId: "asset_f",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ origin: "user",+ },+ {+ id: "clip_b",+ assetId: "asset_g",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 10,+ timelineEndSec: 20,+ origin: "user",+ },+ ],+ },+ legacyEditor: { aspectRatio: "native" },+ });+ expect(doc.schemaVersion).toBe(6);+ expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("9:16");+ });++ it("falls back to 16:9 when the timeline has no clips with known dimensions", () => {+ const doc = documentSchema.parse(makeV5Doc({ legacyEditor: { aspectRatio: "native" } }));+ expect(doc.schemaVersion).toBe(6);+ expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("16:9");+ });++ it("passes through a concrete aspectRatio unchanged", () => {+ const doc = documentSchema.parse(makeV5Doc({ legacyEditor: { aspectRatio: "4:5" } }));+ expect(doc.schemaVersion).toBe(6);+ expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("4:5");+ });++ it("passes through a legacyEditor without aspectRatio unchanged", () => {+ const doc = documentSchema.parse(makeV5Doc({ legacyEditor: { someOtherField: "preserved" } }));+ expect(doc.schemaVersion).toBe(6);+ const legacy = doc.legacyEditor as Record<string, unknown>;+ expect(legacy.someOtherField).toBe("preserved");+ expect(legacy.aspectRatio).toBeUndefined();+ });++ it("passes through a v5 doc with no legacyEditor at all (only the version bumps)", () => {+ const v5 = makeV5Doc();+ const doc = documentSchema.parse(v5);+ expect(doc.schemaVersion).toBe(6);+ expect(doc.legacyEditor).toBeNull();+ });++ it("is a no-op for non-v5 documents (the upgrader gates on schemaVersion === 5)", () => {+ // A v4 document is handled by the v4→v5 upgrader; v5→v6 must not touch it.+ const v4 = {+ schemaVersion: 4,+ project: {+ id: "p1",+ title: "v4",+ createdAt: "2024-01-01T00:00:00.000Z",+ updatedAt: "2024-01-01T00:00:00.000Z",+ },+ assets: [],+ timeline: { clips: [] },+ };+ // v4 is rejected by the documentSchema (which expects 6 after the chain),+ // but the upgrader itself must not transform an input that isn't v5. We+ // round-trip through a fully-valid v5 doc instead: parse it, then verify the+ // second pass (which is a v6 doc) is unchanged.+ const once = documentSchema.parse(makeV5Doc({ legacyEditor: { aspectRatio: "16:9" } }));+ const twice = documentSchema.parse(once);+ expect(twice).toEqual(once);+ expect(v4.schemaVersion).toBe(4); // the test's input doc is untouched+ });+});diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsindex 990b32557..35d48b18f 100644--- a/src/lib/ai-edition/schema/index.ts+++ b/src/lib/ai-edition/schema/index.ts@@ -11,6 +11,10 @@// shape — runtime ops, IPC, and exporter integration land in Phase 1+.import { z } from "zod";+// Cycle-safe: `aspectRatioUtils` has no schema dependency, and `document/outputFormat`+// is downstream of schema. We import the leaf tokeniser directly so the v5→v6 upgrader+// can rewrite `"native"` without dragging in the whole output-format module.+import { toAspectRatioToken } from "@/utils/aspectRatioUtils";// Cycle-safe: `document/ids` only pulls `uuid`, and `timeline/timelineMap`'s// transitive value-imports (region-ventilation, virtual-preview) import from this// module TYPE-ONLY, so requiring them here never re-enters schema at runtime.@@ -21,7 +25,11 @@ import { anchorRegionsWithDerivedMs } from "../timeline/timelineMap";// CLIP-ANCHORED fragments: `{clipId, sourceStartSec, sourceEndSec}` is the// source of truth, `startMs`/`endMs` stay as a derived cache for the// transition. See technical-documentation/architecture/timeline-model.md-export const axcutSchemaVersion = 5;+// 5. v6 — `"native"` AspectRatio retires. The v5→v6 upgrader rewrites every+// stored `"native"` to a concrete `"W:H"` token (the timeline's largest+// clip, falling back to "16:9"), so the value can be dropped from the+// `AspectRatio` union without a runtime bridge.+export const axcutSchemaVersion = 6;export const isoDateSchema = z.string().datetime({ offset: true });@@ -520,8 +528,84 @@ function upgradeV4DocumentToV5(raw: unknown): unknown {};}+/**+ * Largest raw asset footprint among the timeline's clips. A local copy of the+ * `referenceClipDims` pick from `document/outputFormat` — duplicated here so the schema+ * package doesn't import from a module that itself imports from this one (cycle), and so+ * the upgrader doesn't need the runtime `probedAssetDims` map (it runs at load time, before+ * any asset is probed). Crop is intentionally ignored: v5 docs store the crop on the+ * clip, but a v5→v6 rewrite only needs *some* reasonable concrete token, and the runtime+ * bridge in `resolveAspectRatioValue` already accepted this same approximation.+ */+function largestClipDims(doc: Record<string, unknown>): { width: number; height: number } | null {+ const timeline = (doc.timeline ?? {}) as Record<string, unknown>;+ const clips = Array.isArray(timeline.clips) ? timeline.clips : [];+ const assets = Array.isArray(doc.assets) ? doc.assets : [];+ const assetById = new Map<string, Record<string, unknown>>();+ for (const a of assets) {+ if (a && typeof a === "object" && typeof (a as { id?: unknown }).id === "string") {+ assetById.set((a as { id: string }).id, a as Record<string, unknown>);+ }+ }+ let best: { width: number; height: number } | null = null;+ let bestArea = 0;+ for (const clip of clips) {+ if (!clip || typeof clip !== "object") continue;+ const c = clip as Record<string, unknown>;+ const assetId = c.assetId;+ if (typeof assetId !== "string") continue;+ const asset = assetById.get(assetId);+ if (!asset) continue;+ const video = (asset.video ?? {}) as Record<string, unknown>;+ const w = typeof video.width === "number" ? video.width : 0;+ const h = typeof video.height === "number" ? video.height : 0;+ if (w <= 0 || h <= 0) continue;+ const area = w * h;+ if (area > bestArea) {+ bestArea = area;+ best = { width: w, height: h };+ }+ }+ return best;+}++/**+ * v5 → v6 — retire the `"native"` AspectRatio. `"native"` was a runtime-only sentinel+ * that resolved to the timeline's largest clip; v6 makes that resolution permanent by+ * baking the concrete `"W:H"` token into the document. The new value matches the OLD+ * runtime answer (largest clip), so projects migrate losslessly — preview and export+ * will keep framing the same shape they did yesterday.+ *+ * Falls back to `"16:9"` when the timeline has no clips with known dimensions (the same+ * value the runtime bridge in `resolveAspectRatioValue` returned when no document was+ * available). A document without a `legacyEditor` envelope is unchanged apart from the+ * version bump.+ */+function upgradeV5DocumentToV6(raw: unknown): unknown {+ if (!raw || typeof raw !== "object") return raw;+ const doc = raw as Record<string, unknown>;+ if (doc.schemaVersion !== 5) return raw;++ const legacy =+ doc.legacyEditor && typeof doc.legacyEditor === "object" && !Array.isArray(doc.legacyEditor)+ ? (doc.legacyEditor as Record<string, unknown>)+ : null;++ if (!legacy || legacy.aspectRatio !== "native") {+ return { ...doc, schemaVersion: 6 };+ }++ const dims = largestClipDims(doc);+ const token = dims ? toAspectRatioToken(dims.width, dims.height) : null;+ return {+ ...doc,+ schemaVersion: 6,+ legacyEditor: { ...legacy, aspectRatio: token ?? "16:9" },+ };+}+export const documentSchema = z.preprocess(- (raw) => upgradeV4DocumentToV5(upgradeV3DocumentToV4(raw)),+ (raw) => upgradeV5DocumentToV6(upgradeV4DocumentToV5(upgradeV3DocumentToV4(raw))),documentSchemaShape,);diff --git a/src/utils/aspectRatioUtils.test.ts b/src/utils/aspectRatioUtils.test.tsindex 06d54a664..e1d60181d 100644--- a/src/utils/aspectRatioUtils.test.ts+++ b/src/utils/aspectRatioUtils.test.ts@@ -15,8 +15,7 @@ describe("parseAspectRatio", () => {expect(parseAspectRatio(" 64 : 27 ")).toEqual({ width: 64, height: 27 });});- it('rejects the legacy "native" sentinel and malformed input', () => {- expect(parseAspectRatio("native")).toBeNull();+ it("rejects malformed input", () => {expect(parseAspectRatio("16/9")).toBeNull();expect(parseAspectRatio("16:")).toBeNull();expect(parseAspectRatio("0:9")).toBeNull();@@ -26,10 +25,9 @@ describe("parseAspectRatio", () => {});describe("isAspectRatio", () => {- it("accepts presets, free-form shapes and the legacy sentinel", () => {+ it("accepts presets and free-form shapes", () => {expect(isAspectRatio("16:9")).toBe(true);expect(isAspectRatio("64:27")).toBe(true);- expect(isAspectRatio("native")).toBe(true);});it("rejects anything a project file could hold that isn't a ratio", () => {@@ -62,10 +60,6 @@ describe("getAspectRatioValue", () => {expect(getAspectRatioValue("9:16")).toBeCloseTo(9 / 16, 6);expect(getAspectRatioValue("64:27")).toBeCloseTo(64 / 27, 6);});-- it("falls back to 16/9 for the legacy sentinel, which has no document context here", () => {- expect(getAspectRatioValue("native")).toBeCloseTo(FALLBACK_RATIO, 6);- });});describe("getNativeAspectRatioValue", () => {diff --git a/src/utils/aspectRatioUtils.ts b/src/utils/aspectRatioUtils.tsindex 07d98a207..451f43fff 100644--- a/src/utils/aspectRatioUtils.ts+++ b/src/utils/aspectRatioUtils.ts@@ -15,17 +15,12 @@ export type AspectRatioPreset = (typeof ASPECT_RATIO_PRESETS)[number];* A concrete `"W:H"` shape. The presets are just the well-known members — the picker also* offers the clips' own native shapes ("Original"), which are stored the same way and can be* anything (`"64:27"` for an ultrawide, `"683:384"` for an odd capture size).- *- * `"native"` is a LEGACY value kept only so projects saved before the shapes were enumerated- * still open. It resolves to the timeline's reference asset (largest pixel area), which is- * exactly the silent, drifting behaviour the enumeration replaced — nothing writes it any- * more, so it can be dropped once old projects are assumed migrated.*/-export type AspectRatio = AspectRatioPreset | `${number}:${number}` | "native";+export type AspectRatio = AspectRatioPreset | `${number}:${number}`;-const NATIVE_ASPECT_RATIO_FALLBACK = 16 / 9;+const ASPECT_RATIO_FALLBACK = 16 / 9;-/** Split a `"W:H"` token. Returns null for `"native"` and for anything malformed. */+/** Split a `"W:H"` token. Returns null for anything malformed. */export function parseAspectRatio(value: string): { width: number; height: number } | null {const match = /^\s*(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)\s*$/.exec(value);if (!match) return null;@@ -40,7 +35,7 @@ export function parseAspectRatio(value: string): { width: number; height: number/** Validation gate for anything read back from disk (project files, user prefs). */export function isAspectRatio(value: unknown): value is AspectRatio {if (typeof value !== "string") return false;- return value === "native" || parseAspectRatio(value) !== null;+ return parseAspectRatio(value) !== null;}function greatestCommonDivisor(a: number, b: number): number {@@ -71,15 +66,12 @@ export function toAspectRatioToken(width: number, height: number): AspectRatio |}/**- * Numeric value of an aspect ratio. Legacy `"native"` has no document context here so it- * returns the 16/9 fallback — callers holding a document must resolve it through- * `resolveAspectRatioValue` (lib/ai-edition/document/outputFormat) instead, or preview and- * output silently disagree on old projects.+ * Numeric value of an aspect ratio. Returns the 16/9 fallback for any value that doesn't+ * parse as a `"W:H"` token.*/export function getAspectRatioValue(aspectRatio: AspectRatio): number {- if (aspectRatio === "native") return NATIVE_ASPECT_RATIO_FALLBACK;const parsed = parseAspectRatio(aspectRatio);- return parsed ? parsed.width / parsed.height : NATIVE_ASPECT_RATIO_FALLBACK;+ return parsed ? parsed.width / parsed.height : ASPECT_RATIO_FALLBACK;}export function getNativeAspectRatioValue(@@ -99,11 +91,11 @@ export function getNativeAspectRatioValue(cropW <= 0 ||cropH <= 0) {- return NATIVE_ASPECT_RATIO_FALLBACK;+ return ASPECT_RATIO_FALLBACK;}const ratio = (videoWidth * cropW) / (videoHeight * cropH);- return Number.isFinite(ratio) && ratio > 0 ? ratio : NATIVE_ASPECT_RATIO_FALLBACK;+ return Number.isFinite(ratio) && ratio > 0 ? ratio : ASPECT_RATIO_FALLBACK;}export function getAspectRatioDimensions(@@ -118,7 +110,6 @@ export function getAspectRatioDimensions(}export function getAspectRatioLabel(aspectRatio: AspectRatio): string {- if (aspectRatio === "native") return "Original";return aspectRatio;}@@ -126,7 +117,6 @@ export function isPortraitAspectRatio(aspectRatio: AspectRatio): boolean {return getAspectRatioValue(aspectRatio) < 1;}-export function formatAspectRatioForCSS(aspectRatio: AspectRatio, nativeRatio?: number): string {- if (aspectRatio === "native") return String(nativeRatio ?? NATIVE_ASPECT_RATIO_FALLBACK);+export function formatAspectRatioForCSS(aspectRatio: AspectRatio): string {return aspectRatio.replace(":", "/");}