Skip to content

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

fix(timeline): anchor modifiers to clips and merge regions by identity

Etienne Lescot00f4a8290d92
diff --git a/docs/architecture/timeline-coordinate-refactor.md b/docs/architecture/timeline-coordinate-refactor.md
new file mode 100644
index 000000000..bafa06403
--- /dev/null
+++ b/docs/architecture/timeline-coordinate-refactor.md
@@ -0,0 +1,169 @@
+# Timeline coordinate refactor — clip-anchored modifiers
+
+**Statut :** planifié (2026-07-22). Corrige le désync zoom/trim (offsets audio/vidéo, couples
+caméra/record mélangés) en preview **et** au rendu. Aligne le code sur le diagramme
+`ai-edition-data-flow` : *« modifiers represented above the timeline UX-wise but flowed down to
+clip data-wise »*.
+
+## 1. Cause racine (diagnostic)
+
+Le code mélange **deux référentiels de temps timeline** :
+
+| Référentiel | Définition | Qui l'utilise |
+|---|---|---|
+| **RAW / document** | les trims occupent encore leur place sur la règle | `currentTimeSec`, playhead, règle V4, authoring des régions, nav clip (`NewEditorShell`) |
+| **COMPRESSÉ / playback** | trims retirés, clips recollés depuis 0 (`resolvePlaybackSegments`) | `buildSceneDescription` → natif (preview+export), `resolveNativePlaybackPosition` |
+
+Les régions (zoom/speed/annotation) sont stockées en **virtual-ms RAW** au niveau *document*, mais
+`buildSceneDescription` les ventile contre des clips **COMPRESSÉS** (`resolveVisibleClips`). Dès
+qu'un trim retire `Δ` s avant une région, la coordonnée RAW dépasse la position compressée de `Δ`
+→ mauvais clip / mauvais offset source → la région se déclenche `Δ` trop tôt, l'active-clip est
+mal résolu → mauvaise caméra + décalage écran/cam. Contradiction visible :
+`NativeCompositorOverlay.tsx:56-67` (le commentaire dit « currentTimeSec est RAW, ne pas utiliser
+resolveVisibleClips » mais le code utilise resolveVisibleClips). 3ᵉ traitement divergent :
+`reprojectDocumentRegions` reprojette RAW→RAW (correct seulement sans trim).
+
+## 2. Modèle cible
+
+- **`currentTimeSec` / règle / playhead = RAW virtual time** (inchangé, = ce que l'utilisateur voit).
+- **Un modifier est ancré à un clip, en source-time** : `{ clipId, sourceStartSec, sourceEndSec, …payload }`.
+ Unifie trims (`{assetId, sourceStart, sourceEnd}`) et modifiers.
+ - Trim → soustrait la fenêtre source du clip : le modifier ancré est masqué/découpé par la même
+ math d'intervalles, **sans reprojection**.
+ - Reorder / move / duplicate → le modifier voyage avec son `clipId`, **sans reprojection**.
+ - Natif → le modifier porte déjà `clipId` (→ `clipIndex`) + range source = exactement ce que
+ `SceneZoomRegion`/`setActiveClip` consomment. `projectRegionsToSourceTime` devient un simple
+ lookup par segment.
+ - UI → pill placée par map avant unique : `clip.timelineStartSec + (mod.sourceStartSec − clip.sourceStartSec)`
+ (= `trimToTimelineSpan`, déjà éprouvé).
+- **Un seul module de mapping** `src/lib/ai-edition/timeline/timelineMap.ts`, pur, seul endroit qui
+ connaît RAW ↔ source ↔ compressé.
+
+### Contrat `timelineMap.ts`
+
+| Fonction | Rôle | Remplace |
+|---|---|---|
+| `rawVirtualToSource(rawClips, rawSec)` → `{clip, sourceSec}` | playhead RAW → source (clips RAW) | version honnête de `locateVirtualPosition`/`resolveNativePlaybackPosition` |
+| `sourceToRawSpan(clip, srcStart, srcEnd)` → `{start,end}` | range source clip → span RAW (pill) | `trimToTimelineSpan` |
+| `resolveRawSpanToClipSource(rawStart, rawEnd, rawClips)` → `{clipId, srcStart, srcEnd}` | span RAW → ancre clip (authoring) | `resolveTimelineSpanToTrim` |
+| `projectModifierToScene(mod, visibleSegments)` → `SceneRegion[]` | ancre clip → régions source + `clipIndex` (gère trim qui coupe en 2 segments) | `projectRegionsToSourceTime` |
+| `resolveNativePosition(rawSec, rawClips, visibleSegments)` → `{clipIndex, sourceSec}` | playhead RAW → (index compressé, source) pour natif | `resolveNativePlaybackPosition` |
+
+## 3. Stages
+
+| # | Stage | Livrable | Risque | Désync corrigé ? | État |
+|---|---|---|---|---|---|
+| A0 | Test rouge | `sceneDescription.test.ts` : trim + zoom → source time attendu | nul | prouve le bug | ✅ fait |
+| A1 | Module de mapping | `timelineMap.ts` (`projectRawRegionsToSource`, `resolveNativePosition`, `segmentRawSpanSec`) + `timelineMap.test.ts` | nul | — | ✅ fait |
+| A2 | Corriger la projection runtime (schéma actuel) | `buildSceneDescription` (3 projections) + résolution du clip actif (`resolveNativePosition` remplace `resolveNativePlaybackPosition` dans `useNativePlaybackSync` + `NativeCompositorOverlay`) ; contradiction `NativeCompositorOverlay:56-67` levée ; ancien `nativePlaybackPosition.ts` supprimé | moyen | **oui (preview + export natif)** | ✅ fait |
+| A3 | ~~Aligner l'export legacy~~ | **Non nécessaire** : `documentExporter.ts:216` ventile déjà contre les clips **RAW** (`document.timeline.clips`) + coupe les trims séparément → déjà correct. Seul le chemin natif mélangeait RAW/compressé. | — | déjà correct | ⏭️ écarté |
+| B1 | Schéma clip-ancré | `schema` v5 : zoom/annotation portent `{clipId, sourceStartSec, sourceEndSec}` (anchor **optionnel** pendant la transition) + `startMs/endMs` **dérivés** ; migration v4→v5 dans le préprocess via `anchorRegionsWithDerivedMs` (couvre aussi `legacyEditor.speedRegions`/`cameraFullscreenRegions`) ; `migrate.ts` émet la forme v4 → la logique de migration vit à UN seul endroit | élevé | verrouille | ✅ fait |
+| B2 | Supprimer la reprojection hot-path | `reprojectDocumentRegions` + `reprojectRegionsForReorder` + `reprojectSpanForReorder` **supprimés**. Remplacés par `rederiveRegionMs` (ops qui PRÉSERVENT l'identité des clips : move/duplicate/trim/`update_clip_range` → seul le cache ms bouge) et `reanchorRegions` (rebuild d'identités : `replaceTimeline` → ré-ancrage depuis les ms). Câblé dans `document/timeline.ts`, `document/operations.ts`, `store/useTimeline.ts` | moyen | verrouille | ✅ fait |
+| B3.1 | Authoring ancré (`useTimeline`) | `addZoom`/`addZoomsBulk`/`addAnnotation`/`addSpeed`/`addCameraFullscreen` **ancrent à la création** (`anchorRegionsWithDerivedMs`) ; les 4 `update*Span` passent par `replacePillSpan` (clamp + ré-ancrage : re-split au franchissement, collapse au retour) ; `removeRegion`/`removeRegions` suppriment **toute la pill** (`dropPillById`/`dropPillsByIds`, résolue par `resolvePillIds`). **Ferme le trou de B2.** | moyen | verrouille | ✅ fait |
+| B3.2 | Authoring ancré (agent LLM) | `agent-tools.ts` : `addZoom`/`addSpeed`/`addAnnotation` + updates ancrent aussi ; interface **secondes-virtuelles** conservée côté LLM, conversion à l'intérieur : `anchorForAgent` sur add*, `replacePillSpan` sur set*, et `coalesceForAgent` pour que le snapshot présente **une** entrée par région logique | moyen | verrouille | ✅ fait |
+| B3.3 | Pills par identité | `V4Timeline` via `coalesceRegionsForRuler` (règle 1) ; clé de pill = `ids[0]` (unique — voir révision) ; payload edits sur toute la pill (`patchPillById`) ; `coalescedTrimGroups` délègue à `coalesceByIdentity` → **duplication supprimée** | moyen | verrouille | ✅ fait |
+| B4 | Nettoyage final | natif/export/overlays lisent l'ancre directement ; retirer `startMs`/`endMs` | faible | — | ⬜ à faire |
+
+**Le désync utilisateur est corrigé dès A2** (preview + export natif), prouvé par
+`timelineMap.test.ts` + `sceneDescription.test.ts` (trim + zoom → bon temps source). **B*** paie la
+dette pour qu'il ne puisse plus revenir (élimine le double référentiel et la reprojection à chaque
+reorder). La conversion « virtual-ms RAW → source » de A2 devient le code de migration en B1, pas du
+throwaway.
+
+### Découverte (2026-07-22)
+- Le bug était **localisé au chemin natif** (preview + export MP4), pas généralisé : `documentExporter`
+ (WebCodecs) projetait déjà contre les clips RAW. La confusion RAW/compressé vivait uniquement dans
+ `buildSceneDescription` (clips compressés utilisés pour le mapping source) et
+ `resolveNativePlaybackPosition` (horloge RAW lue contre clips compressés → mauvaise caméra après trim).
+- **Caveat env. worktree** : les tests qui *montent* des composants React (`EditorEmptyState`,
+ `CursorPreviewLayer`, `WebcamOverlay`, `useTimeline`) échouent AVANT/APRÈS ce changement (React nul :
+ `react`/`zustand` résolus depuis le repo racine, `react-dom` depuis le worktree → double React).
+ Vérifié par `git stash` : 14 échecs identiques sur le commit de base. Non causé par ce refactor ;
+ cf. `desktop-app-testing-worktree` / `cc-delegate-worker-env`. Tous les tests **pure-logic** passent.
+
+## 4. Invariants de validation
+
+- Un projet `1 clip + trim de 2 s au début + zoom 5 s plus loin` : le zoom se déclenche au **même**
+ frame source en preview et à l'export ; playhead RAW ↔ frame affichée cohérents après le trim.
+- 2 assets, chacun sa caméra : le clip actif (donc la caméra) résolu à un temps RAW donné reste le
+ bon après trim/reorder ; `sourceTime − offset` webcam correct.
+- `biome` + `tsc` + `vitest` verts à chaque stage (commandes : voir `os-editor-verify-commands`).
+
+## 5. Blast radius (fichiers)
+
+- **Core** : `timeline/timelineMap.ts` (neuf), `native/sceneDescription.ts`,
+ `native/nativePlaybackPosition.ts`, `native/useNativePlaybackSync.ts`,
+ `components/ai-edition/NativeCompositorOverlay.tsx`.
+- **Export** : `exporter/renderPlan.ts`, `exporter/documentExporter.ts`, `ExportDialog.tsx`.
+- **Schéma/migration (B)** : `schema/index.ts`, `document/migrate.ts`, `document/timeline.ts`
+ (suppr. `reprojectDocumentRegions`), `timeline/region-ventilation.ts` (élaguer).
+- **UI (B)** : `store/useTimeline.ts`, `v4/V4Timeline.tsx`, `v4/FloatingInspector.tsx`,
+ `AnnotationOverlay.tsx`, `RightPanelStack.tsx`/gimbal, `CursorPreviewLayer.tsx`.
+- **Tests** : `timelineMap.test.ts` (neuf), `sceneDescription.test.ts`, `region-ventilation.test.ts`,
+ `document/timeline.test.ts`, `useTimeline.test.ts`, `migrate.test.ts`, `renderPlan.test.ts`.
+
+## 6. Stage B — modèle retenu : fragments clip-ancrés + règles universelles
+
+Décidé 2026-07-22, **révisé 2026-07-23** après test in-app (voir « révision » plus bas).
+
+**Stockage.** Une région = un ou plusieurs **fragments**, chacun ancré à UN clip en temps
+source : `{ id, clipId, sourceStartSec, sourceEndSec, …propriétés }`. Une région dessinée à
+cheval sur une frontière est stockée en un fragment par clip couvert. **Aucun marqueur ne
+relie les fragments entre eux.**
+
+- Trim d'un clip → rétrécit sa fenêtre source → le fragment est coupé par la même math
+ d'intervalles. Reorder/move → le fragment voyage avec son `clipId`. **Zéro reprojection.**
+
+**Les deux règles universelles** (`timelineMap`), valables pour TOUS les types de région :
+
+| Règle | Énoncé | Primitive |
+|---|---|---|
+| **1. Fusion** | deux régions de même type, aux **propriétés égales**, qui se touchent → **une** pill. Peu importe comment elles sont devenues voisines. | `coalesceByIdentity` |
+| **2. Répulsion** | deux régions de même type aux **propriétés différentes** ne peuvent pas se chevaucher : l'edit **bute** sur le bord du voisin, qui ne bouge jamais (pas de cascade). | `clampSpanAgainstNeighbours` |
+
+L'**identité** (`regionIdentityKey`) = toutes les propriétés qui affectent le rendu,
+sérialisées canoniquement ; **position** (`clipId`, source, ms) et **provenance** (`id`,
+`origin`, `reason`, `source`) exclues. Une nouvelle propriété participe automatiquement.
+
+**Conséquences (toutes dérivées, aucune codée en dur) :**
+- Un **trim** n'a aucune propriété → identité constante → les trims fusionnent toujours.
+ Le comportement historique des trims devient un **cas particulier de la règle 1** :
+ `coalescedTrimGroups` délègue désormais à `coalesceByIdentity`. **La duplication de logique
+ signalée en test est supprimée.**
+- Deux régions **autorées indépendamment**, adjacentes et de mêmes propriétés → fusionnent
+ (ce que le modèle par provenance ne savait pas faire).
+- Split par reorder → on change une propriété d'un morceau → on recolle les clips →
+ **pas de fusion** (mismatch). On remet la propriété → fusion. Sans mémoire du split.
+- Les mutations (resize, suppression, edit de propriété) portent sur **la pill telle qu'elle
+ est vue**, résolue à la volée par `resolvePillIds` — pas sur un groupe mémorisé.
+
+### Révision du 2026-07-23 — pourquoi `groupId` a été supprimé
+La 1ʳᵉ version reliait les fragments par un `groupId` (leur *provenance*). Deux défauts, tous
+deux constatés en test réel :
+1. **Duplication** — les trims fusionnaient par adjacence, les modifiers par provenance : deux
+ mécaniques pour une seule règle, et des voisins identiques qui refusaient de fusionner.
+2. **Collision de clés** — keyer une pill par `groupId` casse dès qu'un groupe se scinde
+ légitimement (deux pills, même clé) : React « duplicates and/or omits » les enfants, l'UI
+ devient non fiable (des régions de goodtest ont été perdues ainsi). **Clé = `ids[0]`.**
+
+L'identité (ce que la région EST) remplace la provenance (d'où elle vient) : plus simple, sans
+bookkeeping, et correcte quelle que soit l'histoire des régions.
+
+### Façades SSOT à ne pas oublier (au-delà de timeline/preview/export)
+La forme des régions zoom/speed/annotation est aussi lue/écrite par d'autres façades :
+- **Chat LLM — `electron/ai-edition/agent-tools.ts` (IMPACT FORT)** : `getCurrentDocument` présente
+ les effets au LLM en **secondes virtuelles (timeline éditée)** (`:425-441`, `:144`) et des tools
+ d'écriture (`addZoom`/`addSpeed`/`addAnnotation` + updates, `:646/:698/:775`) prennent des
+ **secondes virtuelles** et écrivent `startMs/endMs`. **Stratégie** : garder l'interface
+ secondes-virtuelles côté LLM (il raisonne dans le référentiel de la règle, pas en fragments) ; les
+ tools convertissent virtuel↔fragments (`anchorRawRegionsToClips`) et `getCurrentDocument` dérive le
+ span virtuel depuis les fragments. C'est un argument de plus pour la transition additive (ms dérivés).
+- **Transcript agrégé — `aggregated-transcript.ts` + modale (IMPACT MINIMAL)** : consomme clips +
+ mots + trims, PAS la forme des régions ; entêtes = clips (inchangés). Revalider seulement : cuts de
+ mots + annotations `auto-caption` après le flip.
+- **B3 « group-aware »** : pills coalescées par `groupId` (fragments dont les spans ruler se touchent
+ → 1 pill) ; parts sur clips séparés = pills distinctes mais **liées par `groupId`** pour
+ sélection/suppression/resize groupés (calqué sur `coalescedTrimGroups`). Exposer
+ `anchoredToRawSpanSec(fragment, clips)` (le mapping fragment→span ruler qu'utilise
+ `coalesceAnchoredFragments`) pour V4Timeline / FloatingInspector / overlays. **Invariant : un edit
+ cross-clip reste un seul edit côté utilisateur.**
diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts
index 523803428..02f81e26f 100644
--- a/electron/ai-edition/agent-tools.ts
+++ b/electron/ai-edition/agent-tools.ts
@@ -12,6 +12,12 @@ import { z } from "zod";
import { createId } from "../../src/lib/ai-edition/document/ids";
import { replaceTimeline, resequenceClips } from "../../src/lib/ai-edition/document/timeline";
import type { AxcutDocument } from "../../src/lib/ai-edition/schema";
+import {
+ anchorRegionsWithDerivedMs,
+ coalesceRegionsForRuler,
+ replacePillSpan,
+ resolvePillIds,
+} from "../../src/lib/ai-edition/timeline/timelineMap";
export interface AgentToolSpec {
name: string;
@@ -58,6 +64,30 @@ function resolveSpanMs(
return { startMs: toMs(Math.min(s, e)), endMs: toMs(Math.max(s, e)) };
}
+// v5: a modifier is stored as clip-anchored fragment(s), and adjacent regions with the
+// same properties read as ONE pill (timelineMap merge rule). The agent reasons in VIRTUAL
+// seconds over whole regions, so we present exactly the pills the user sees, keyed by the
+// first region under each — which every set*/remove* tool accepts as the id.
+function coalesceForAgent<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+): T[] {
+ return coalesceRegionsForRuler(regions).map((pill) => ({
+ ...pill.member,
+ id: pill.ids[0],
+ startMs: Math.round(pill.start * 1000),
+ endMs: Math.round(pill.end * 1000),
+ }));
+}
+
+/** Every agent write anchors the region to the clip(s) it covers, exactly like the UI. */
+function anchorForAgent<T extends { id: string; startMs: number; endMs: number }>(
+ region: T,
+ document: AxcutDocument,
+ prefix: string,
+) {
+ return anchorRegionsWithDerivedMs([region], document.timeline.clips, () => createId(prefix));
+}
+
const secondsSchema = z.number().finite().nonnegative();
const addTrimArgs = z.object({
@@ -422,20 +452,20 @@ export function documentSnapshotForModel(document: AxcutDocument): Record<string
endSec: s.endSec,
reason: s.reason,
})),
- zoomRanges: document.zoomRanges.map((z) => ({
+ zoomRanges: coalesceForAgent(document.zoomRanges).map((z) => ({
id: z.id,
startSec: roundSec(z.startMs),
endSec: roundSec(z.endMs),
depth: z.depth,
focus: z.focus,
})),
- speedRegions: speedRegions.map((s) => ({
+ speedRegions: coalesceForAgent(speedRegions).map((s) => ({
id: s.id,
startSec: roundSec(s.startMs),
endSec: roundSec(s.endMs),
speed: s.speed,
})),
- annotations: document.annotations.map((a) => ({
+ annotations: coalesceForAgent(document.annotations).map((a) => ({
id: a.id,
startSec: roundSec(a.startMs),
endSec: roundSec(a.endMs),
@@ -643,7 +673,10 @@ export function executeAgentTool(
};
const next: AxcutDocument = {
...document,
- zoomRanges: [...document.zoomRanges, zoom] as AxcutDocument["zoomRanges"],
+ zoomRanges: [
+ ...document.zoomRanges,
+ ...anchorForAgent(zoom, document, "zoom"),
+ ] as AxcutDocument["zoomRanges"],
};
return {
ok: true,
@@ -665,20 +698,28 @@ export function executeAgentTool(
const existing = document.zoomRanges.find((z) => z.id === zoomId);
if (!existing) return failure(`Unknown zoom: ${zoomId}`);
const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);
+ const zoomPill = new Set(resolvePillIds(document.zoomRanges, zoomId));
const next: AxcutDocument = {
...document,
- zoomRanges: document.zoomRanges.map((z) =>
- z.id === zoomId
- ? {
- ...z,
- startMs,
- endMs,
- ...(parsed.data.depth !== undefined
- ? { depth: parsed.data.depth as 1 | 2 | 3 | 4 | 5 | 6 }
- : {}),
- ...(parsed.data.focus ? { focus: parsed.data.focus } : {}),
- }
- : z,
+ zoomRanges: replacePillSpan(
+ // payload edits first, applied to every region under the pill…
+ document.zoomRanges.map((z) =>
+ zoomPill.has(z.id)
+ ? {
+ ...z,
+ ...(parsed.data.depth !== undefined
+ ? { depth: parsed.data.depth as 1 | 2 | 3 | 4 | 5 | 6 }
+ : {}),
+ ...(parsed.data.focus ? { focus: parsed.data.focus } : {}),
+ }
+ : z,
+ ),
+ // …then the span: clamped against different-property pills, then re-ventilated.
+ zoomId,
+ startMs,
+ endMs,
+ document.timeline.clips,
+ () => createId("zoom"),
) as AxcutDocument["zoomRanges"],
};
return {
@@ -699,7 +740,10 @@ export function executeAgentTool(
const region = { id: createId("speed"), startMs, endMs, speed: parsed.data.speed };
const next: AxcutDocument = {
...document,
- legacyEditor: { ...legacy, speedRegions: [...prev, region] },
+ legacyEditor: {
+ ...legacy,
+ speedRegions: [...prev, ...anchorForAgent(region, document, "speed")],
+ },
};
return {
ok: true,
@@ -723,6 +767,7 @@ export function executeAgentTool(
| Array<{ id: string; startMs: number; endMs: number; speed: number }>
| undefined) ?? [];
const existing = prev.find((s) => s.id === parsed.data.speedId);
+ const speedPill = new Set(resolvePillIds(prev, parsed.data.speedId));
if (!existing) return failure(`Unknown speed region: ${parsed.data.speedId}`);
const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);
const speed = parsed.data.speed ?? existing.speed;
@@ -730,8 +775,13 @@ export function executeAgentTool(
...document,
legacyEditor: {
...legacy,
- speedRegions: prev.map((s) =>
- s.id === parsed.data.speedId ? { ...s, startMs, endMs, speed } : s,
+ speedRegions: replacePillSpan(
+ prev.map((s) => (speedPill.has(s.id) ? { ...s, speed } : s)),
+ parsed.data.speedId,
+ startMs,
+ endMs,
+ document.timeline.clips,
+ () => createId("speed"),
),
},
};
@@ -776,7 +826,10 @@ export function executeAgentTool(
};
const next: AxcutDocument = {
...document,
- annotations: [...document.annotations, ann] as AxcutDocument["annotations"],
+ annotations: [
+ ...document.annotations,
+ ...anchorForAgent(ann, document, "ann"),
+ ] as AxcutDocument["annotations"],
};
return {
ok: true,
@@ -795,21 +848,27 @@ export function executeAgentTool(
if (!parsed.success) return failure(parsed.error.message);
const { annotationId } = parsed.data;
const existing = document.annotations.find((a) => a.id === annotationId);
+ const annPill = new Set(resolvePillIds(document.annotations, annotationId));
if (!existing) return failure(`Unknown annotation: ${annotationId}`);
const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);
const next: AxcutDocument = {
...document,
- annotations: document.annotations.map((a) =>
- a.id === annotationId
- ? {
- ...a,
- startMs,
- endMs,
- ...(parsed.data.text !== undefined
- ? { content: parsed.data.text, textContent: parsed.data.text }
- : {}),
- }
- : a,
+ annotations: replacePillSpan(
+ document.annotations.map((a) =>
+ annPill.has(a.id)
+ ? {
+ ...a,
+ ...(parsed.data.text !== undefined
+ ? { content: parsed.data.text, textContent: parsed.data.text }
+ : {}),
+ }
+ : a,
+ ),
+ annotationId,
+ startMs,
+ endMs,
+ document.timeline.clips,
+ () => createId("ann"),
),
};
return {
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.ts
index af3f8726c..15adbd515 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 v4 doc with the given title and writes it to disk", async () => {
+ it("creates a v5 doc with the given title and writes it to disk", async () => {
const doc = await service.createProject("Demo Project");
- expect(doc.schemaVersion).toBe(4);
+ expect(doc.schemaVersion).toBe(5);
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: 4,
+ schemaVersion: 5,
project: { title: "Demo Project" },
});
});
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index 150246246..4c20609c5 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -1,5 +1,6 @@
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { resolveNativePosition } from "@/lib/ai-edition/timeline/timelineMap";
import {
setActiveClip,
setCurrentNativeViewId,
@@ -7,7 +8,6 @@ import {
setNativeScene,
useNativeCompositorView,
} from "@/native";
-import { resolveNativePlaybackPosition } from "@/native/nativePlaybackPosition";
import { buildSceneDescription, resolveVisibleClips } from "@/native/sceneDescription";
import {
getWebcamNativeSize,
@@ -53,22 +53,22 @@ export function NativeCompositorOverlay() {
() => 0,
);
- // BUG corrigé : ceci pointait vers `resolveVisibleClips` (compacté, trim-rétréci) alors que
- // `currentTimeSec` reste — et doit rester — le temps RAW/document (voir NewEditorShell) :
- // un trim ne change jamais quel ASSET/fichier est actif (seul un changement de clip source
- // le fait), donc cette détection de "playhead entré dans un autre clip" (→ setActiveClip,
- // bascule de la paire écran/webcam) n'a besoin d'aucune connaissance des trims — juste la
- // liste RAW triée/filtrée, dans le même référentiel que `currentTimeSec`. Le flux
- // Le flux COMPACTÉ (`resolveVisibleClips`, dans `buildSceneDescription` ci-dessous) reste
- // utilisé pour la SCÈNE envoyée au natif (`setNativeScene`), qui elle doit bien refléter
- // les trims.
+ // `currentTimeSec` est en temps RAW/document (la règle où les trims occupent encore leur
+ // place — même référentiel que le playhead V4 et l'overlay webcam web). Le natif, lui, joue
+ // les segments COMPACTÉS (`resolveVisibleClips`, trims retirés) — le même flux que la SCÈNE
+ // envoyée via `setNativeScene`. `resolveNativePosition` fait le pont : il mappe le playhead
+ // RAW → temps source via le layout RAW (`document.timeline.clips`) PUIS localise le segment
+ // compacté correspondant, d'où sortent le `clipIndex` natif et la bonne paire écran/webcam.
+ // Sans ça (ancien `resolveNativePlaybackPosition(nativeClips, currentTimeSec)`), un playhead
+ // RAW lu contre des clips compactés désignait le mauvais clip après un trim → mauvaise caméra
+ // + décalage écran/cam.
const nativeClips = useMemo(() => {
if (!document) return [];
return resolveVisibleClips(document);
}, [document]);
const activePosition = useMemo(
- () => resolveNativePlaybackPosition(nativeClips, currentTimeSec),
- [nativeClips, currentTimeSec],
+ () => resolveNativePosition(currentTimeSec, nativeClips, document?.timeline.clips ?? []),
+ [nativeClips, currentTimeSec, document],
);
const activeClip = activePosition?.clip ?? null;
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index b9459470f..ad187a695 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -130,7 +130,9 @@ export function NewEditorShell() {
void primaryAssetPath;
const clips: AxcutClip[] = document?.timeline.clips ?? [];
const visibleClips = useMemo(() => (document ? resolveVisibleClips(document) : []), [document]);
- useNativePlaybackSync(playing, currentTimeSec, visibleClips);
+ // visibleClips = trim-compressed native stream; `clips` = RAW layout currentTimeSec
+ // is measured against. resolveNativePosition needs both (see timelineMap).
+ useNativePlaybackSync(playing, currentTimeSec, visibleClips, clips);
const hasProject = Boolean(document);
const hasAsset = projectId !== null && (document?.assets.length ?? 0) > 0;
const project = document?.project
diff --git a/src/components/ai-edition/WebcamOverlay.test.tsx b/src/components/ai-edition/WebcamOverlay.test.tsx
index 5edb4447d..6c003e413 100644
--- a/src/components/ai-edition/WebcamOverlay.test.tsx
+++ b/src/components/ai-edition/WebcamOverlay.test.tsx
@@ -36,7 +36,7 @@ const CLIP_WITHOUT_CAMERA: AxcutClip = {
function makeDocument(): AxcutDocument {
return {
- schemaVersion: 4,
+ schemaVersion: 5,
project: {
id: "proj_test",
title: "Test",
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index f1706736b..82504aa98 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -33,6 +33,7 @@ import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { ventilateSpanAcrossClips } from "@/lib/ai-edition/timeline/region-ventilation";
+import { coalesceRegionsForRuler } from "@/lib/ai-edition/timeline/timelineMap";
import {
coalescedTrimGroups,
resolveTimelineSpanToTrim,
@@ -260,40 +261,46 @@ export function V4Timeline({
// zoom/speed/annotation: one pill per row, never coalesced — each carries
// distinct per-instance content (depth/focus, speed value, text) that two
// touching-but-different regions must not silently merge into one.
- const annPills: LanePill[] = tl.annotationRegions.map((a) => ({
- id: a.id,
+ // Pills follow the universal merge rule (timelineMap): regions of the same kind whose
+ // PROPERTIES are equal and whose spans touch render as ONE pill, however they came to be
+ // adjacent. Different properties never merge (and cannot overlap — they repel on edit).
+ // Trims obey the same rule with an empty property set, so they always merge.
+ const annPills: LanePill[] = coalesceRegionsForRuler(tl.annotationRegions).map((p) => ({
+ id: p.ids[0],
kind: "annotation",
- start: a.startMs / 1000,
- end: a.endMs / 1000,
+ start: p.start,
+ end: p.end,
label: t("toolbar.newAnnotation"),
- sourceIds: [a.id],
+ sourceIds: p.ids,
}));
- const speedPills: LanePill[] = tl.speedRegions.map((s) => ({
- id: s.id,
+ const speedPills: LanePill[] = coalesceRegionsForRuler(tl.speedRegions).map((p) => ({
+ id: p.ids[0],
kind: "speed",
- start: s.startMs / 1000,
- end: s.endMs / 1000,
- label: `${(s as { speed?: number }).speed ?? 1.5}×`,
- sourceIds: [s.id],
+ start: p.start,
+ end: p.end,
+ label: `${(p.member as { speed?: number }).speed ?? 1.5}×`,
+ sourceIds: p.ids,
}));
- const cameraFullscreenPills: LanePill[] = tl.cameraFullscreenRegions.map((c) => ({
- id: c.id,
- kind: "cameraFullscreen",
- start: c.startMs / 1000,
- end: c.endMs / 1000,
- label: "Full Camera",
- sourceIds: [c.id],
- }));
- const zoomPills: LanePill[] = tl.zoomRegions.map((z) => ({
- id: z.id,
+ const cameraFullscreenPills: LanePill[] = coalesceRegionsForRuler(tl.cameraFullscreenRegions).map(
+ (p) => ({
+ id: p.ids[0],
+ kind: "cameraFullscreen",
+ start: p.start,
+ end: p.end,
+ label: "Full Camera",
+ sourceIds: p.ids,
+ }),
+ );
+ const zoomPills: LanePill[] = coalesceRegionsForRuler(tl.zoomRegions).map((p) => ({
+ id: p.ids[0],
kind: "zoom",
- start: z.startMs / 1000,
- end: z.endMs / 1000,
+ start: p.start,
+ end: p.end,
// Matches RightPanelStack's effectiveZoomScale: a custom scale (from the
// slider) overrides the depth preset; otherwise show the depth's actual
// preset value, not a fabricated linear approximation of it.
- label: `${(z.customScale ?? ZOOM_DEPTH_SCALES[z.depth]).toFixed(2)}×`,
- sourceIds: [z.id],
+ label: `${(p.member.customScale ?? ZOOM_DEPTH_SCALES[p.member.depth]).toFixed(2)}×`,
+ sourceIds: p.ids,
}));
// trims: content-free (no per-instance text/settings), so touching rows —
// inevitable once a trim is ventilated across a clip boundary — are
diff --git a/src/lib/ai-edition/document/migrate.test.ts b/src/lib/ai-edition/document/migrate.test.ts
index 9073eaa0e..02884beb1 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(4);
+ expect(doc.schemaVersion).toBe(5);
expect(doc.assets).toHaveLength(1);
const asset = doc.assets[0];
expect(asset.kind).toBe("video");
diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.ts
index 7f57bce5f..330dcf600 100644
--- a/src/lib/ai-edition/document/migrate.ts
+++ b/src/lib/ai-edition/document/migrate.ts
@@ -28,7 +28,6 @@ import {
type AxcutLegacyEditor,
type AxcutTrimRange,
type AxcutZoomRegion,
- axcutSchemaVersion,
documentSchema,
} from "../schema";
import { createId } from "./ids";
@@ -199,8 +198,15 @@ export function migrateProjectDataToAxcutDocument(
const legacyEditor: AxcutLegacyEditor = input.editor ? { ...input.editor } : null;
- const draft: AxcutDocument = {
- schemaVersion: axcutSchemaVersion,
+ // Emits the **v4** shape (per-asset cameraTrack + RAW-virtual-ms regions) and lets
+ // `documentSchema`'s v4→v5 preprocess perform the clip-anchoring, so the
+ // modifier migration lives in exactly ONE place instead of being duplicated here.
+ // Deliberately not `axcutSchemaVersion`: that would label the draft as already-v5
+ // and the preprocess would skip anchoring, leaving v2-imported regions unanchored.
+ // Untyped on purpose — this is the INPUT to `documentSchema.parse` (which upgrades
+ // and validates it), not an already-valid v5 document.
+ const draft = {
+ schemaVersion: 4,
project: {
id: projectId,
title,
diff --git a/src/lib/ai-edition/document/operations.ts b/src/lib/ai-edition/document/operations.ts
index 5b7778ab0..f355db909 100644
--- a/src/lib/ai-edition/document/operations.ts
+++ b/src/lib/ai-edition/document/operations.ts
@@ -15,8 +15,8 @@ import {
moveClip,
normalizeIntervals,
primaryAssetDuration,
+ rederiveRegionMs,
replaceTimeline,
- reprojectDocumentRegions,
resequenceClips,
} from "./timeline";
@@ -295,7 +295,7 @@ export function applyTimelineOperation(
},
preview: { ...document.preview, revision: document.preview.revision + 1 },
};
- const finalDoc = reprojectDocumentRegions(nextDoc, oldClips, newClips);
+ const finalDoc = rederiveRegionMs(nextDoc, newClips);
return {
document: finalDoc,
summary: `trimmed clip to ${formatSec(Math.min(op.sourceStartSec, op.sourceEndSec))}–${formatSec(Math.max(op.sourceStartSec, op.sourceEndSec))}`,
diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts
index 7c9d30694..912d923fa 100644
--- a/src/lib/ai-edition/document/timeline.test.ts
+++ b/src/lib/ai-edition/document/timeline.test.ts
@@ -431,11 +431,25 @@ describe("duplicateClip / moveClip", () => {
],
},
zoomRanges: [
- { id: "z1", startMs: 12000, endMs: 14000, depth: 3, focus: { cx: 0.5, cy: 0.5 } },
+ {
+ id: "z1",
+ groupId: "z1",
+ clipId: "clip_b",
+ sourceStartSec: 22,
+ sourceEndSec: 24,
+ startMs: 12000,
+ endMs: 14000,
+ depth: 3,
+ focus: { cx: 0.5, cy: 0.5 },
+ },
],
annotations: [
{
id: "a1",
+ groupId: "a1",
+ clipId: "clip_b",
+ sourceStartSec: 25,
+ sourceEndSec: 26,
startMs: 15000,
endMs: 16000,
type: "text",
@@ -456,7 +470,20 @@ describe("duplicateClip / moveClip", () => {
zIndex: 1,
},
] as unknown as AxcutDocument["annotations"],
- legacyEditor: { speedRegions: [{ id: "s1", startMs: 11000, endMs: 13000, speed: 1.5 }] },
+ legacyEditor: {
+ speedRegions: [
+ {
+ id: "s1",
+ groupId: "s1",
+ clipId: "clip_b",
+ sourceStartSec: 21,
+ sourceEndSec: 23,
+ startMs: 11000,
+ endMs: 13000,
+ speed: 1.5,
+ },
+ ],
+ },
});
// Move clip_b to the front → clip_b now tl 0-10 (delta -10s). Regions
// over clip_b shift by -10s; the zoom now sits at tl 2-4, etc.
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 189134b50..da230e951 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -4,7 +4,7 @@
// or a new document with updated clips.
import type { AxcutClip, AxcutDocument, AxcutTranscript, AxcutTrimRange } from "../schema";
-import { reprojectRegionsForReorder } from "../timeline/region-ventilation";
+import { anchoredToRawSpanSec, anchorRegionsWithDerivedMs } from "../timeline/timelineMap";
import { createId } from "./ids";
export function byStart(a: { startSec: number }, b: { startSec: number }): number {
@@ -197,54 +197,109 @@ export function invertIntervals(intervals: Interval[], durationSec: number): Int
return cuts;
}
-export function reprojectDocumentRegions(
+/** Shape every stored modifier shares during the v5 transition: the clip anchor is
+ * the source of truth, `startMs`/`endMs` a derived cache. Anchor fields are optional
+ * because a not-yet-migrated region (see `anchorRegionsWithDerivedMs`) has none. */
+type StoredRegion = {
+ id: string;
+ startMs: number;
+ endMs: number;
+ clipId?: string;
+ sourceStartSec?: number;
+ sourceEndSec?: number;
+};
+
+/** Apply `fn` to all four modifier collections (document-level + legacyEditor envelopes). */
+function mapAllRegionCollections(
document: AxcutDocument,
- oldClips: AxcutClip[],
- newClips: AxcutClip[],
+ fn: (regions: StoredRegion[], prefix: string) => StoredRegion[],
): AxcutDocument {
- if (oldClips.length === 0 || newClips.length === 0) return document;
const legacy = document.legacyEditor as Record<string, unknown> | null;
- const speedRegions = legacy?.speedRegions as
- | Array<{ id: string; startMs: number; endMs: number }>
- | undefined;
- const cameraFullscreenRegions = legacy?.cameraFullscreenRegions as
- | Array<{ id: string; startMs: number; endMs: number }>
- | undefined;
+ const speedRegions = legacy?.speedRegions as StoredRegion[] | undefined;
+ const cameraFullscreenRegions = legacy?.cameraFullscreenRegions as StoredRegion[] | undefined;
return {
...document,
- zoomRanges: reprojectRegionsForReorder(document.zoomRanges, oldClips, newClips, () =>
- createId("zoom"),
- ) as AxcutDocument["zoomRanges"],
- annotations: reprojectRegionsForReorder(document.annotations, oldClips, newClips, () =>
- createId("ann"),
- ) as AxcutDocument["annotations"],
+ zoomRanges: fn(
+ document.zoomRanges as unknown as StoredRegion[],
+ "zoom",
+ ) as unknown as AxcutDocument["zoomRanges"],
+ annotations: fn(
+ document.annotations as unknown as StoredRegion[],
+ "ann",
+ ) as unknown as AxcutDocument["annotations"],
legacyEditor:
legacy && (speedRegions || cameraFullscreenRegions)
? {
...legacy,
- ...(speedRegions
- ? {
- speedRegions: reprojectRegionsForReorder(speedRegions, oldClips, newClips, () =>
- createId("speed"),
- ),
- }
- : {}),
+ ...(speedRegions ? { speedRegions: fn(speedRegions, "speed") } : {}),
...(cameraFullscreenRegions
- ? {
- cameraFullscreenRegions: reprojectRegionsForReorder(
- cameraFullscreenRegions,
- oldClips,
- newClips,
- () => createId("camfull"),
- ),
- }
+ ? { cameraFullscreenRegions: fn(cameraFullscreenRegions, "camfull") }
: {}),
}
: document.legacyEditor,
};
}
+/**
+ * Re-derive the transition `startMs`/`endMs` cache of every clip-anchored modifier
+ * from its anchor + the given clip layout.
+ *
+ * Structural ops that PRESERVE clip identity (move / duplicate / trim) leave the
+ * anchors valid — a fragment travels with its clip by `clipId` — so nothing is
+ * reprojected; only the derived cache moves. That is what let the old
+ * `reprojectDocumentRegions` / `reprojectRegionsForReorder` machinery go away.
+ * A fragment whose anchor clip no longer exists is dropped (its content is gone, and
+ * the display coalescer drops it too). Not-yet-anchored regions pass through
+ * untouched. Guards the empty-clip case so a transient wipe can't delete everything.
+ */
+export function rederiveRegionMs(document: AxcutDocument, clips: AxcutClip[]): AxcutDocument {
+ if (clips.length === 0) return document;
+ return mapAllRegionCollections(document, (regions) =>
+ regions.flatMap((region) => {
+ if (
+ !region.clipId ||
+ region.sourceStartSec === undefined ||
+ region.sourceEndSec === undefined
+ ) {
+ return [region];
+ }
+ const span = anchoredToRawSpanSec(
+ {
+ clipId: region.clipId,
+ sourceStartSec: region.sourceStartSec,
+ sourceEndSec: region.sourceEndSec,
+ },
+ clips,
+ );
+ if (!span) return [];
+ return [
+ {
+ ...region,
+ startMs: Math.round(span.startSec * 1000),
+ endMs: Math.round(span.endSec * 1000),
+ },
+ ];
+ }),
+ );
+}
+
+/**
+ * Re-anchor every modifier against a REBUILT clip layout. `replaceTimeline` mints
+ * brand-new clip identities, so existing anchors point at clips that no longer exist;
+ * we re-ventilate each region from its current RAW ms (which still describe where it
+ * sits on the ruler) and rebuild the anchor. Fragments of one region need no shared
+ * marker to keep reading as a single pill: equal properties + adjacency suffice.
+ */
+export function reanchorRegions(document: AxcutDocument, clips: AxcutClip[]): AxcutDocument {
+ if (clips.length === 0) return document;
+ return mapAllRegionCollections(
+ document,
+ (regions, prefix) =>
+ anchorRegionsWithDerivedMs(regions, clips, () => createId(prefix)) as StoredRegion[],
+ );
+}
+
export function replaceTimeline(
document: AxcutDocument,
intervals: Interval[],
@@ -257,7 +312,6 @@ export function replaceTimeline(
}
const duration = primaryAssetDuration(document);
const normalized = normalizeIntervals(duration, intervals);
- const oldClips = document.timeline.clips;
const clips = buildTimelineFromIntervals(assetId, normalized, {
origin,
reason,
@@ -284,7 +338,7 @@ export function replaceTimeline(
revision: document.preview.revision + 1,
},
};
- return oldClips.length > 0 ? reprojectDocumentRegions(next, oldClips, clips) : next;
+ return reanchorRegions(next, clips);
}
// ponytail: reorder an existing clip by removing it from its current
@@ -311,7 +365,6 @@ export function moveClip(
const remaining = document.timeline.clips.filter((c) => c.id !== clipId);
const bounded = Math.max(0, Math.min(insertIndex, remaining.length));
const reordered = [...remaining.slice(0, bounded), movingClip, ...remaining.slice(bounded)];
- const oldClips = document.timeline.clips;
const newClips = resequenceClips(reordered);
const next: AxcutDocument = {
...document,
@@ -324,7 +377,7 @@ export function moveClip(
revision: document.preview.revision + 1,
},
};
- return reprojectDocumentRegions(next, oldClips, newClips);
+ return rederiveRegionMs(next, newClips);
}
// ponytail: duplicate a clip (preserves the original). Used for "split this
@@ -361,7 +414,7 @@ export function duplicateClip(
revision: document.preview.revision + 1,
},
};
- return reprojectDocumentRegions(updatedDoc, oldClips, newClips);
+ return rederiveRegionMs(updatedDoc, newClips);
}
export function restoreFullTimeline(document: AxcutDocument): AxcutDocument {
diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.ts
index 31281dcf4..29781c9f0 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 v4", () => {
+describe("axcut-schema v5", () => {
it("uses schema version 4", () => {
- expect(axcutSchemaVersion).toBe(4);
+ expect(axcutSchemaVersion).toBe(5);
});
it("rejects unknown schema versions", () => {
@@ -28,9 +28,9 @@ describe("axcut-schema v4", () => {
).toThrow();
});
- it("createEmptyDocument returns a valid v4 doc with empty collections", () => {
+ it("createEmptyDocument returns a valid v5 doc with empty collections", () => {
const doc = createEmptyDocument({ projectId: "proj_1", title: "Demo" });
- expect(doc.schemaVersion).toBe(4);
+ expect(doc.schemaVersion).toBe(5);
expect(doc.assets).toEqual([]);
expect(doc.timeline.clips).toEqual([]);
expect(doc.timeline.trimRanges).toEqual([]);
@@ -233,7 +233,7 @@ describe("axcut-schema v4", () => {
const doc = documentSchema.parse(
v3Doc({ project: { ...v3Doc().project, primaryAssetId: "asset_2" } }),
);
- expect(doc.schemaVersion).toBe(4);
+ expect(doc.schemaVersion).toBe(5);
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");
@@ -247,7 +247,7 @@ describe("axcut-schema v4", () => {
it("is a no-op when the v3 document has no legacy cameraTrack", () => {
const doc = documentSchema.parse(v3Doc({ cameraTrack: null }));
- expect(doc.schemaVersion).toBe(4);
+ expect(doc.schemaVersion).toBe(5);
for (const asset of doc.assets) {
expect(asset.cameraTrack).toBeNull();
}
@@ -332,3 +332,130 @@ describe("axcut-schema v4", () => {
});
});
});
+
+// --- v4 -> v5 clip-anchoring migration (round-trip) --------------------------
+// Uses goodtest's real layout: clip A [asset_f] src[0,25.557313] raw[0,25.557313],
+// clip B [asset_e] src[0,8.149313] raw[25.557313,33.706626], and its straddling
+// speed region [8149,28575]ms. See docs/architecture/timeline-coordinate-refactor.md §6.
+
+describe("v4 -> v5 clip-anchored modifier migration", () => {
+ const CLIP_A_END = 25.557313;
+ const CLIP_B_END = 33.706626;
+
+ function makeV4Doc(overrides: Record<string, unknown> = {}) {
+ const createdAt = "2024-01-01T00:00:00.000Z";
+ return {
+ schemaVersion: 4,
+ project: { id: "p1", title: "goodtest-like", createdAt, updatedAt: createdAt },
+ assets: [
+ { id: "asset_f", kind: "video", label: "A", originalPath: "/a.mp4", cameraTrack: null },
+ { id: "asset_e", kind: "video", label: "B", originalPath: "/b.mp4", cameraTrack: null },
+ ],
+ timeline: {
+ clips: [
+ {
+ id: "clip_a",
+ assetId: "asset_f",
+ sourceStartSec: 0,
+ sourceEndSec: CLIP_A_END,
+ timelineStartSec: 0,
+ timelineEndSec: CLIP_A_END,
+ origin: "user",
+ },
+ {
+ id: "clip_b",
+ assetId: "asset_e",
+ sourceStartSec: 0,
+ sourceEndSec: 8.149313,
+ timelineStartSec: CLIP_A_END,
+ timelineEndSec: CLIP_B_END,
+ origin: "user",
+ },
+ ],
+ },
+ ...overrides,
+ };
+ }
+
+ it("bumps the version and anchors a zoom wholly inside one clip", () => {
+ const doc = documentSchema.parse(
+ makeV4Doc({
+ zoomRanges: [
+ { id: "z1", startMs: 2000, endMs: 5000, depth: 3, focus: { cx: 0.5, cy: 0.5 } },
+ ],
+ }),
+ );
+ expect(doc.schemaVersion).toBe(5);
+ expect(doc.zoomRanges).toHaveLength(1);
+ const z = doc.zoomRanges[0];
+ expect(z).toMatchObject({ id: "z1", clipId: "clip_a", depth: 3 });
+ expect(z.sourceStartSec).toBeCloseTo(2, 5);
+ expect(z.sourceEndSec).toBeCloseTo(5, 5);
+ // derived ms cache stays consistent with the anchor
+ expect(z.startMs).toBe(2000);
+ expect(z.endMs).toBe(5000);
+ });
+
+ it("splits a straddling speed region into two fragments that still read as one pill", () => {
+ const doc = documentSchema.parse(
+ makeV4Doc({
+ legacyEditor: { speedRegions: [{ id: "s1", startMs: 8149, endMs: 28575, speed: 3 }] },
+ }),
+ );
+ const speeds = (doc.legacyEditor as Record<string, unknown>).speedRegions as Array<
+ Record<string, unknown>
+ >;
+ expect(speeds).toHaveLength(2);
+ // No shared marker is stored: equal properties + adjacency is what re-merges them.
+ expect(speeds.every((s) => s.speed === 3)).toBe(true);
+ expect(speeds.map((s) => s.clipId)).toEqual(["clip_a", "clip_b"]);
+ expect(speeds[0].sourceStartSec).toBeCloseTo(8.149, 5);
+ expect(speeds[1].sourceStartSec).toBeCloseTo(0, 5);
+ // The two derived ms spans are contiguous and together cover the original.
+ expect(speeds[0].startMs).toBe(8149);
+ expect(speeds[1].endMs).toBe(28575);
+ expect(speeds[0].endMs).toBe(speeds[1].startMs);
+ });
+
+ it("never drops a region it cannot anchor (unknown clip duration → passes through)", () => {
+ // A v2-imported project before its duration is probed: zero-extent clip.
+ const doc = documentSchema.parse({
+ schemaVersion: 4,
+ project: {
+ id: "p2",
+ title: "unprobed",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-01-01T00:00:00.000Z",
+ },
+ assets: [{ id: "a", kind: "video", label: "A", originalPath: "/a.mp4", cameraTrack: null }],
+ timeline: {
+ clips: [
+ {
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ timelineStartSec: 0,
+ timelineEndSec: 0,
+ origin: "user",
+ },
+ ],
+ },
+ zoomRanges: [{ id: "z1", startMs: 1000, endMs: 2000, depth: 3, focus: { cx: 0.5, cy: 0.5 } }],
+ });
+ expect(doc.zoomRanges).toHaveLength(1);
+ expect(doc.zoomRanges[0]).toMatchObject({ id: "z1", startMs: 1000, endMs: 2000 });
+ expect(doc.zoomRanges[0].clipId).toBeUndefined();
+ });
+
+ it("is idempotent — re-parsing an already-v5 document changes nothing", () => {
+ const once = documentSchema.parse(
+ makeV4Doc({
+ zoomRanges: [
+ { id: "z1", startMs: 2000, endMs: 5000, depth: 3, focus: { cx: 0.5, cy: 0.5 } },
+ ],
+ }),
+ );
+ const twice = documentSchema.parse(once);
+ expect(twice).toEqual(once);
+ });
+});
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index 09dc9687d..68b9656b9 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -11,8 +11,17 @@
// shape — runtime ops, IPC, and exporter integration land in Phase 1+.
import { z } from "zod";
-
-export const axcutSchemaVersion = 4;
+// 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.
+import { createId } from "../document/ids";
+import { anchorRegionsWithDerivedMs } from "../timeline/timelineMap";
+
+// 4. v5 — modifiers (zoom / annotation / speed / cameraFullscreen) become
+// CLIP-ANCHORED fragments: `{clipId, sourceStartSec, sourceEndSec}` is the
+// source of truth, `startMs`/`endMs` stay as a derived cache for the
+// transition. See docs/architecture/timeline-coordinate-refactor.md §6.
+export const axcutSchemaVersion = 5;
export const isoDateSchema = z.string().datetime({ offset: true });
@@ -379,11 +388,24 @@ const annotationStyleSchema = z.object({
.optional(),
});
+// v5 clip anchor — the source of truth for a modifier's position. A region the user drew
+// across a clip boundary is stored as one fragment per covered clip; they need no shared
+// marker, because two regions with equal properties that touch render as one pill by the
+// universal merge rule (see timelineMap). Optional during the Stage B transition: the
+// v4→v5 migration fills it in, and regions created by not-yet-migrated code still validate
+// on startMs/endMs alone, which remain a DERIVED cache of the fragment's ruler span.
+const clipAnchorShape = {
+ clipId: z.string().min(1).optional(),
+ sourceStartSec: z.number().nonnegative().optional(),
+ sourceEndSec: z.number().nonnegative().optional(),
+};
+
export const annotationRegionSchema = z
.object({
id: z.string().min(1),
startMs: z.number().nonnegative(),
endMs: z.number().nonnegative(),
+ ...clipAnchorShape,
type: z.enum(["text", "image", "figure", "blur"]),
content: z.string().default(""),
textContent: z.string().optional(),
@@ -412,6 +434,7 @@ export const zoomRegionSchema = z
id: z.string().min(1),
startMs: z.number().nonnegative(),
endMs: z.number().nonnegative(),
+ ...clipAnchorShape,
depth: z.union([
z.literal(1),
z.literal(2),
@@ -512,7 +535,64 @@ function upgradeV3DocumentToV4(raw: unknown): unknown {
return { ...rest, schemaVersion: 4, assets: nextAssets };
}
-export const documentSchema = z.preprocess(upgradeV3DocumentToV4, documentSchemaShape);
+/**
+ * v4 → v5 — modifiers become CLIP-ANCHORED fragments. Every RAW-virtual-ms region
+ * (document `zoomRanges` / `annotations`, plus the `legacyEditor.speedRegions` /
+ * `cameraFullscreenRegions` envelopes) is ventilated across the stored RAW clip
+ * layout it was authored against, yielding one fragment per covered clip, with
+ * `startMs`/`endMs` re-derived as a transition cache. The fragments carry no marker
+ * tying them together: they share the same properties, so the ruler already renders
+ * them as one pill whenever they are adjacent (see timelineMap merge rule).
+ *
+ * A region covering no clip (zero-length, or off the end of the timeline) is
+ * dropped: it could never play. A document with no clips has nothing to anchor to,
+ * so its regions pass through untouched (still valid — the anchor is optional).
+ */
+function upgradeV4DocumentToV5(raw: unknown): unknown {
+ if (!raw || typeof raw !== "object") return raw;
+ const doc = raw as Record<string, unknown>;
+ if (doc.schemaVersion !== 4) return raw;
+
+ const timeline = (doc.timeline ?? {}) as Record<string, unknown>;
+ const clips = (Array.isArray(timeline.clips) ? timeline.clips : []) as unknown as AxcutClip[];
+
+ const anchor = (value: unknown, prefix: string): unknown => {
+ if (!Array.isArray(value) || clips.length === 0) return value;
+ return anchorRegionsWithDerivedMs(
+ value as Array<{ id: string; startMs: number; endMs: number }>,
+ clips,
+ () => createId(prefix),
+ );
+ };
+
+ const legacy =
+ doc.legacyEditor && typeof doc.legacyEditor === "object" && !Array.isArray(doc.legacyEditor)
+ ? (doc.legacyEditor as Record<string, unknown>)
+ : null;
+
+ return {
+ ...doc,
+ schemaVersion: 5,
+ zoomRanges: anchor(doc.zoomRanges, "zoom"),
+ annotations: anchor(doc.annotations, "ann"),
+ legacyEditor: legacy
+ ? {
+ ...legacy,
+ ...(Array.isArray(legacy.speedRegions)
+ ? { speedRegions: anchor(legacy.speedRegions, "speed") }
+ : {}),
+ ...(Array.isArray(legacy.cameraFullscreenRegions)
+ ? { cameraFullscreenRegions: anchor(legacy.cameraFullscreenRegions, "camfull") }
+ : {}),
+ }
+ : doc.legacyEditor,
+ };
+}
+
+export const documentSchema = z.preprocess(
+ (raw) => upgradeV4DocumentToV5(upgradeV3DocumentToV4(raw)),
+ documentSchemaShape,
+);
export const createProjectInputSchema = z.object({
title: z.string().trim().min(1).default("Untitled Project"),
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index f9a978901..93158272f 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -10,11 +10,16 @@ import { createId } from "../document/ids";
import {
duplicateClip as duplicateClipInDocument,
moveClip as moveClipInDocument,
- reprojectDocumentRegions,
+ rederiveRegionMs,
resequenceClips,
} from "../document/timeline";
import type { AxcutClipCropRegion, AxcutDocument } from "../schema";
import { probeVideoDimensions, probeVideoDuration } from "../timeline/duration";
+import {
+ anchorRegionsWithDerivedMs,
+ replacePillSpan,
+ resolvePillIds,
+} from "../timeline/timelineMap";
import { resolveTimelineSpanToTrim } from "../timeline/trim-mapping";
import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions";
import { useProjectStore } from "./projectStore";
@@ -36,6 +41,42 @@ interface RegionHandle {
type Clip = AxcutDocument["timeline"]["clips"][number];
+/**
+ * Deleting a pill deletes every region under it. Which regions those are is RESOLVED
+ * from the universal merge rule (same properties + touching = one pill), never from
+ * stored provenance — so it stays correct however they came to be adjacent.
+ */
+function dropPillById<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+ id: string,
+): T[] {
+ const under = new Set(resolvePillIds(regions, id));
+ return regions.filter((r) => !under.has(r.id));
+}
+
+/**
+ * Patch every region under the pill uid=197609(camil) gid=197609 groups=197609 belongs to. A payload edit must hit them all,
+ * or the pieces of one pill would disagree — and then, by the merge rule, visibly split.
+ */
+function patchPillById<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+ id: string,
+ patch: Partial<T>,
+): T[] {
+ const under = new Set(resolvePillIds(regions, id));
+ return regions.map((r) => (under.has(r.id) ? { ...r, ...patch } : r));
+}
+
+/** Batch variant of {@link dropPillById} — expands every selected id to its whole pill. */
+function dropPillsByIds<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+ ids: Iterable<string>,
+): T[] {
+ let out = regions;
+ for (const id of ids) out = dropPillById(out, id);
+ return out;
+}
+
export function useTimeline() {
const document = useProjectStore((s) => s.document);
const projectId = useProjectStore((s) => s.projectId);
@@ -51,13 +92,16 @@ export function useTimeline() {
const hasDoc = document !== null && projectId !== null;
+ // Every add* below anchors the new region to the clip(s) it covers before storing it.
+ // A modifier MUST own a clip anchor to survive reorder/trim (see
+ // docs/architecture/timeline-coordinate-refactor.md §6) — writing only startMs/endMs
+ // would strand it. A region created across a clip boundary becomes one fragment per
+ // clip; the ruler renders them as one pill because their properties are equal.
const addZoom = useCallback(async () => {
if (!document) return;
const timeMs = Math.round(currentTimeSec * 1000);
- const next: AxcutDocument = {
- ...document,
- zoomRanges: [
- ...document.zoomRanges,
+ const anchored = anchorRegionsWithDerivedMs(
+ [
{
id: createId("zoom"),
startMs: timeMs,
@@ -66,7 +110,13 @@ export function useTimeline() {
focus: { cx: 0.5, cy: 0.5 },
focusMode: "manual" as const,
},
- ] as AxcutDocument["zoomRanges"],
+ ],
+ document.timeline.clips,
+ () => createId("zoom"),
+ );
+ const next: AxcutDocument = {
+ ...document,
+ zoomRanges: [...document.zoomRanges, ...anchored] as AxcutDocument["zoomRanges"],
};
await saveDocument(next);
}, [document, currentTimeSec, saveDocument]);
@@ -78,19 +128,25 @@ export function useTimeline() {
const addZoomsBulk = useCallback(
async (suggestions: AutoZoomSuggestion[]) => {
if (!document || suggestions.length === 0) return 0;
+ const anchored = suggestions.flatMap((s) =>
+ anchorRegionsWithDerivedMs(
+ [
+ {
+ id: createId("zoom"),
+ startMs: Math.round(s.span.start),
+ endMs: Math.round(s.span.end),
+ depth: 3 as const,
+ focus: { cx: s.focus.cx, cy: s.focus.cy },
+ focusMode: "auto" as const,
+ },
+ ],
+ document.timeline.clips,
+ () => createId("zoom"),
+ ),
+ );
const next: AxcutDocument = {
...document,
- zoomRanges: [
- ...document.zoomRanges,
- ...suggestions.map((s) => ({
- id: createId("zoom"),
- startMs: Math.round(s.span.start),
- endMs: Math.round(s.span.end),
- depth: 3 as const,
- focus: { cx: s.focus.cx, cy: s.focus.cy },
- focusMode: "auto" as const,
- })),
- ] as AxcutDocument["zoomRanges"],
+ zoomRanges: [...document.zoomRanges, ...anchored] as AxcutDocument["zoomRanges"],
};
await saveDocument(next);
return suggestions.length;
@@ -188,7 +244,10 @@ export function useTimeline() {
};
const next: AxcutDocument = {
...document,
- annotations: [...document.annotations, ann] as unknown as AxcutDocument["annotations"],
+ annotations: [
+ ...document.annotations,
+ ...anchorRegionsWithDerivedMs([ann], document.timeline.clips, () => createId("ann")),
+ ] as unknown as AxcutDocument["annotations"],
};
await saveDocument(next);
}, [document, currentTimeSec, saveDocument]);
@@ -204,12 +263,11 @@ export function useTimeline() {
...legacy,
speedRegions: [
...prev,
- {
- id: createId("speed"),
- startMs: timeMs,
- endMs: timeMs + 2000,
- speed: 1.5 as const,
- },
+ ...anchorRegionsWithDerivedMs(
+ [{ id: createId("speed"), startMs: timeMs, endMs: timeMs + 2000, speed: 1.5 as const }],
+ document.timeline.clips,
+ () => createId("speed"),
+ ),
],
},
};
@@ -229,11 +287,11 @@ export function useTimeline() {
...legacy,
cameraFullscreenRegions: [
...prev,
- {
- id: createId("camfull"),
- startMs: timeMs,
- endMs: timeMs + 2000,
- },
+ ...anchorRegionsWithDerivedMs(
+ [{ id: createId("camfull"), startMs: timeMs, endMs: timeMs + 2000 }],
+ document.timeline.clips,
+ () => createId("camfull"),
+ ),
],
},
};
@@ -328,6 +386,10 @@ export function useTimeline() {
[saveDocument],
);
+ // Span edits are GROUP-AWARE: dragging/resizing a pill re-anchors every fragment
+ // under the pill to the new ruler span, so an edit that crosses a clip
+ // boundary re-splits and one dragged back inside a clip collapses — one user edit stays
+ // one pill. See timelineMap.reanchorGroupSpan.
const updateZoomSpan = useCallback(
async (id: string, startMs: number, endMs: number) => {
if (!document) return;
@@ -336,8 +398,13 @@ export function useTimeline() {
const e = clampMs(endMs);
const next: AxcutDocument = {
...document,
- zoomRanges: document.zoomRanges.map((z) =>
- z.id === id ? { ...z, startMs: Math.min(s, e), endMs: Math.max(s, e) } : z,
+ zoomRanges: replacePillSpan(
+ document.zoomRanges,
+ id,
+ Math.min(s, e),
+ Math.max(s, e),
+ document.timeline.clips,
+ () => createId("zoom"),
) as AxcutDocument["zoomRanges"],
};
await saveDocument(next);
@@ -357,9 +424,9 @@ export function useTimeline() {
const clamp01 = (n: number) => (Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0.5);
const next: AxcutDocument = {
...doc,
- zoomRanges: doc.zoomRanges.map((z) =>
- z.id === id ? { ...z, focus: { cx: clamp01(focus.cx), cy: clamp01(focus.cy) } } : z,
- ) as AxcutDocument["zoomRanges"],
+ zoomRanges: patchPillById(doc.zoomRanges, id, {
+ focus: { cx: clamp01(focus.cx), cy: clamp01(focus.cy) },
+ }) as AxcutDocument["zoomRanges"],
};
setDocument(next);
},
@@ -380,9 +447,9 @@ export function useTimeline() {
if (!document) return;
const next: AxcutDocument = {
...document,
- zoomRanges: document.zoomRanges.map((z) =>
- z.id === id ? { ...z, depth } : z,
- ) as AxcutDocument["zoomRanges"],
+ zoomRanges: patchPillById(document.zoomRanges, id, {
+ depth,
+ }) as AxcutDocument["zoomRanges"],
};
await saveDocument(next);
},
@@ -397,8 +464,13 @@ export function useTimeline() {
const e = clampMs(endMs);
const next: AxcutDocument = {
...document,
- annotations: document.annotations.map((a) =>
- a.id === id ? { ...a, startMs: Math.min(s, e), endMs: Math.max(s, e) } : a,
+ annotations: replacePillSpan(
+ document.annotations,
+ id,
+ Math.min(s, e),
+ Math.max(s, e),
+ document.timeline.clips,
+ () => createId("ann"),
),
};
await saveDocument(next);
@@ -415,7 +487,7 @@ export function useTimeline() {
if (!doc) return;
const next: AxcutDocument = {
...doc,
- annotations: doc.annotations.map((a) => (a.id === id ? { ...a, ...patch } : a)),
+ annotations: patchPillById(doc.annotations, id, patch),
};
setDocument(next);
},
@@ -445,8 +517,13 @@ export function useTimeline() {
...document,
legacyEditor: {
...legacy,
- speedRegions: prev.map((r) =>
- r.id === id ? { ...r, startMs: Math.min(s, e), endMs: Math.max(s, e) } : r,
+ speedRegions: replacePillSpan(
+ prev,
+ id,
+ Math.min(s, e),
+ Math.max(s, e),
+ document.timeline.clips,
+ () => createId("speed"),
),
},
};
@@ -471,8 +548,13 @@ export function useTimeline() {
...document,
legacyEditor: {
...legacy,
- cameraFullscreenRegions: prev.map((r) =>
- r.id === id ? { ...r, startMs: Math.min(s, e), endMs: Math.max(s, e) } : r,
+ cameraFullscreenRegions: replacePillSpan(
+ prev,
+ id,
+ Math.min(s, e),
+ Math.max(s, e),
+ document.timeline.clips,
+ () => createId("camfull"),
),
},
};
@@ -495,7 +577,7 @@ export function useTimeline() {
...document,
legacyEditor: {
...legacy,
- speedRegions: prev.map((r) => (r.id === id ? { ...r, speed } : r)),
+ speedRegions: patchPillById(prev, id, { speed }),
},
};
await saveDocument(next);
@@ -510,7 +592,7 @@ export function useTimeline() {
if (kind === "zoom") {
next = {
...document,
- zoomRanges: document.zoomRanges.filter((z) => z.id !== id) as AxcutDocument["zoomRanges"],
+ zoomRanges: dropPillById(document.zoomRanges, id) as AxcutDocument["zoomRanges"],
};
} else if (kind === "trim") {
next = {
@@ -523,12 +605,13 @@ export function useTimeline() {
} else if (kind === "annotation") {
next = {
...document,
- annotations: document.annotations.filter((a) => a.id !== id),
+ annotations: dropPillById(document.annotations, id),
};
} else if (kind === "speed") {
const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
- const prev = ((legacy.speedRegions as unknown[]) ?? []).filter(
- (s) => (s as { id: string }).id !== id,
+ const prev = dropPillById(
+ (legacy.speedRegions as Array<{ id: string; startMs: number; endMs: number }>) ?? [],
+ id,
);
next = {
...document,
@@ -536,8 +619,13 @@ export function useTimeline() {
};
} else {
const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
- const prev = ((legacy.cameraFullscreenRegions as unknown[]) ?? []).filter(
- (s) => (s as { id: string }).id !== id,
+ const prev = dropPillById(
+ (legacy.cameraFullscreenRegions as Array<{
+ id: string;
+ startMs: number;
+ endMs: number;
+ }>) ?? [],
+ id,
);
next = {
...document,
@@ -566,18 +654,19 @@ export function useTimeline() {
handles.filter((h) => h.kind === "cameraFullscreen").map((h) => h.id),
);
const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};
- const prevSpeed = ((legacy.speedRegions as unknown[]) ?? []).filter(
- (s) => !speedIds.has((s as { id: string }).id),
+ const prevSpeed = dropPillsByIds(
+ (legacy.speedRegions as Array<{ id: string; startMs: number; endMs: number }>) ?? [],
+ speedIds,
);
- const prevCameraFullscreen = ((legacy.cameraFullscreenRegions as unknown[]) ?? []).filter(
- (s) => !cameraFullscreenIds.has((s as { id: string }).id),
+ const prevCameraFullscreen = dropPillsByIds(
+ (legacy.cameraFullscreenRegions as Array<{ id: string; startMs: number; endMs: number }>) ??
+ [],
+ cameraFullscreenIds,
);
const next: AxcutDocument = {
...document,
- zoomRanges: document.zoomRanges.filter(
- (z) => !zoomIds.has(z.id),
- ) as AxcutDocument["zoomRanges"],
- annotations: document.annotations.filter((a) => !annotationIds.has(a.id)),
+ zoomRanges: dropPillsByIds(document.zoomRanges, zoomIds) as AxcutDocument["zoomRanges"],
+ annotations: dropPillsByIds(document.annotations, annotationIds),
timeline: {
...document.timeline,
trimRanges: document.timeline.trimRanges.filter((s) => !trimIds.has(s.id)),
@@ -748,8 +837,7 @@ export function useTimeline() {
...document,
timeline: { ...document.timeline, clips: newClips },
};
- const finalDoc =
- oldClips.length > 0 ? reprojectDocumentRegions(next, oldClips, newClips) : next;
+ const finalDoc = rederiveRegionMs(next, newClips);
await saveDocument(finalDoc);
},
[document, saveDocument],
@@ -834,8 +922,7 @@ export function useTimeline() {
...document,
timeline: { ...document.timeline, clips: newClips },
};
- const finalDoc =
- oldClips.length > 0 ? reprojectDocumentRegions(next, oldClips, newClips) : next;
+ const finalDoc = rederiveRegionMs(next, newClips);
await saveDocument(finalDoc);
},
[document, saveDocument, addClipAfter],
@@ -951,8 +1038,7 @@ export function useTimeline() {
...currentDoc,
timeline: { ...currentDoc.timeline, clips: newClips },
};
- const finalDoc =
- oldClips.length > 0 ? reprojectDocumentRegions(next, oldClips, newClips) : next;
+ const finalDoc = rederiveRegionMs(next, newClips);
await saveDocument(finalDoc);
setClipSelection(newClip.id);
@@ -1008,9 +1094,7 @@ export function useTimeline() {
timeline: { ...document.timeline, clips: newClips },
};
const finalDoc =
- oldClips.length > 0 && newClips.length > 0
- ? reprojectDocumentRegions(next, oldClips, newClips)
- : next;
+ oldClips.length > 0 && newClips.length > 0 ? rederiveRegionMs(next, newClips) : next;
await saveDocument(finalDoc);
if (clipSelection === clipId) setClipSelection(null);
},
diff --git a/src/lib/ai-edition/timeline/region-ventilation.test.ts b/src/lib/ai-edition/timeline/region-ventilation.test.ts
index b8e0d95d6..de159b99a 100644
--- a/src/lib/ai-edition/timeline/region-ventilation.test.ts
+++ b/src/lib/ai-edition/timeline/region-ventilation.test.ts
@@ -3,8 +3,6 @@ import type { AxcutClip } from "../schema";
import {
coalesceTouchingSpans,
projectRegionsToSourceTime,
- reprojectRegionsForReorder,
- reprojectSpanForReorder,
ventilateSpanAcrossClips,
virtualSpanToSourceSpans,
} from "./region-ventilation";
@@ -60,64 +58,6 @@ describe("ventilateSpanAcrossClips", () => {
});
});
-describe("reprojectSpanForReorder", () => {
- it("shifts a single-clip span to the clip's new position", () => {
- // Move c2 to the front: new layout c2 [0,10) c1 [10,20) c3 [20,30).
- const newClips = [clip("c2", 0, 10), clip("c1", 10, 10), c3];
- // A zoom over c1 (2..6s) must ride c1 to its new [10,20) slot → 12..16s.
- expect(reprojectSpanForReorder(2000, 6000, threeClips, newClips)).toEqual([
- { startMs: 12000, endMs: 16000 },
- ]);
- });
-
- it("splits a cross-clip span into two when the clips separate", () => {
- // Zoom straddling c1 (8..10) + c2 (10..13). Move c3 between them:
- // new layout c1 [0,10) c3 [10,20) c2 [20,30).
- const newClips = [c1, clip("c3", 10, 10), clip("c2", 20, 10)];
- expect(reprojectSpanForReorder(8000, 13000, threeClips, newClips)).toEqual([
- { startMs: 8000, endMs: 10000 }, // stays on c1
- { startMs: 20000, endMs: 23000 }, // rides c2 to its new slot
- ]);
- });
-
- it("merges the pieces back when the clips stay contiguous after the move", () => {
- // Same straddling zoom, but c1 and c2 remain adjacent (just both shifted):
- // swap so order is c2,c1 would break adjacency — instead move c3 to front:
- // new layout c3 [0,10) c1 [10,20) c2 [20,30). c1 then c2 still contiguous.
- const newClips = [clip("c3", 0, 10), clip("c1", 10, 10), clip("c2", 20, 10)];
- expect(reprojectSpanForReorder(8000, 13000, threeClips, newClips)).toEqual([
- { startMs: 18000, endMs: 23000 },
- ]);
- });
-
- it("leaves a span not sitting on any clip unchanged", () => {
- const newClips = [clip("c2", 0, 10), clip("c1", 10, 10), c3];
- // 40..45s is past the end of every clip.
- expect(reprojectSpanForReorder(40000, 45000, threeClips, newClips)).toEqual([
- { startMs: 40000, endMs: 45000 },
- ]);
- });
-});
-
-describe("reprojectRegionsForReorder", () => {
- it("keeps the id on single-piece regions and preserves extra fields", () => {
- const newClips = [clip("c2", 0, 10), clip("c1", 10, 10), c3];
- const regions = [{ id: "z1", startMs: 2000, endMs: 6000, depth: 2 }];
- expect(reprojectRegionsForReorder(regions, threeClips, newClips, () => "NEW")).toEqual([
- { id: "z1", startMs: 12000, endMs: 16000, depth: 2 },
- ]);
- });
-
- it("emits a fresh id for the extra fragment of a split region", () => {
- const newClips = [c1, clip("c3", 10, 10), clip("c2", 20, 10)];
- const regions = [{ id: "z1", startMs: 8000, endMs: 13000, depth: 3 }];
- expect(reprojectRegionsForReorder(regions, threeClips, newClips, () => "z2")).toEqual([
- { id: "z1", startMs: 8000, endMs: 10000, depth: 3 },
- { id: "z2", startMs: 20000, endMs: 23000, depth: 3 },
- ]);
- });
-});
-
describe("virtualSpanToSourceSpans (export coherence)", () => {
it("is a no-op for an identity single clip (source == virtual)", () => {
const clips = [clip("c1", 0, 10, 0)];
diff --git a/src/lib/ai-edition/timeline/region-ventilation.ts b/src/lib/ai-edition/timeline/region-ventilation.ts
index fdda60121..fe45d03de 100644
--- a/src/lib/ai-edition/timeline/region-ventilation.ts
+++ b/src/lib/ai-edition/timeline/region-ventilation.ts
@@ -53,67 +53,6 @@ export interface Span {
endMs: number;
}
-/**
- * Re-project a virtual-ms span through a clip reorder: decompose over the OLD
- * clip layout, re-place over the NEW layout, then merge fragments that stay
- * contiguous. Returns ≥1 spans — more than one only when the covered clips
- * actually separated. A span not sitting on any clip is returned unchanged.
- */
-export function reprojectSpanForReorder(
- startMs: number,
- endMs: number,
- oldClips: AxcutClip[],
- newClips: AxcutClip[],
-): Span[] {
- const frags = ventilateSpanAcrossClips(startMs / 1000, endMs / 1000, oldClips);
- if (frags.length === 0) return [{ startMs, endMs }];
- const newById = new Map(newClips.map((c) => [c.id, c]));
- const spans = frags
- .map((f): Span | null => {
- const nc = newById.get(f.clipId);
- if (!nc) return null;
- return {
- startMs: Math.round((nc.timelineStartSec + f.localStartSec) * 1000),
- endMs: Math.round((nc.timelineStartSec + f.localEndSec) * 1000),
- };
- })
- .filter((x): x is Span => x !== null)
- .sort((a, b) => a.startMs - b.startMs);
- if (spans.length === 0) return [{ startMs, endMs }];
- const merged: Span[] = [];
- for (const s of spans) {
- const last = merged.at(-1);
- // ≤1ms rounding gap counts as contiguous.
- if (last && s.startMs - last.endMs <= 1) last.endMs = Math.max(last.endMs, s.endMs);
- else merged.push({ ...s });
- }
- return merged;
-}
-
-/**
- * Re-project a list of virtual-ms regions through a clip reorder. A region that
- * ends up split across separated clips becomes several regions (extra copies
- * get a fresh id from `makeId`, keeping every other field). The first fragment
- * keeps the original id so single-piece regions are untouched identity-wise.
- */
-export function reprojectRegionsForReorder<
- T extends { id: string; startMs: number; endMs: number },
->(regions: T[], oldClips: AxcutClip[], newClips: AxcutClip[], makeId: () => string): T[] {
- const out: T[] = [];
- for (const region of regions) {
- const spans = reprojectSpanForReorder(region.startMs, region.endMs, oldClips, newClips);
- spans.forEach((span, i) => {
- out.push({
- ...region,
- id: i === 0 ? region.id : makeId(),
- startMs: span.startMs,
- endMs: span.endMs,
- });
- });
- }
- return out;
-}
-
/**
* Map a virtual-ms span down to **source-ms** spans, one per covered clip.
* Effects (zoom / speed / annotation) are authored in virtual time, but the
diff --git a/src/lib/ai-edition/timeline/timelineMap.test.ts b/src/lib/ai-edition/timeline/timelineMap.test.ts
new file mode 100644
index 000000000..80d783fd6
--- /dev/null
+++ b/src/lib/ai-edition/timeline/timelineMap.test.ts
@@ -0,0 +1,571 @@
+// Tests for the timeline coordinate mapper. The invariant under test: a modifier
+// (or the playhead) authored on the RAW ruler must resolve to the SAME source
+// moment regardless of trims earlier on the timeline — the raw↔compressed↔source
+// bug this module exists to kill. See docs/architecture/timeline-coordinate-refactor.md.
+
+import { describe, expect, it } from "vitest";
+import { resolvePlaybackSegments } from "../document/timeline";
+import type { AxcutClip, AxcutTrimRange } from "../schema";
+import {
+ anchorRawRegionsToClips,
+ anchorRegionsWithDerivedMs,
+ clampSpanAgainstNeighbours,
+ coalesceByIdentity,
+ coalesceRegionsForRuler,
+ projectRawRegionsToSource,
+ regionIdentityKey,
+ replacePillSpan,
+ resolveNativePosition,
+ resolvePillIds,
+} from "./timelineMap";
+
+function clip(overrides: Partial<AxcutClip> & Pick<AxcutClip, "id" | "assetId">): AxcutClip {
+ return {
+ id: overrides.id,
+ assetId: overrides.assetId,
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ timelineStartSec: 0,
+ timelineEndSec: 4,
+ wordRefs: [],
+ origin: "user",
+ reason: "test",
+ ...overrides,
+ };
+}
+
+function trim(assetId: string, startSec: number, endSec: number): AxcutTrimRange {
+ return { id: `t_${startSec}_${endSec}`, assetId, startSec, endSec, reason: "", origin: "user" };
+}
+
+type Region = { id: string; startMs: number; endMs: number; payload?: string };
+const region = (id: string, startSec: number, endSec: number, payload?: string): Region => ({
+ id,
+ startMs: startSec * 1000,
+ endMs: endSec * 1000,
+ ...(payload ? { payload } : {}),
+});
+
+describe("projectRawRegionsToSource", () => {
+ it("passes a region through unchanged (no clipIndex) when there are no segments", () => {
+ const out = projectRawRegionsToSource([region("r", 1.5, 4.25)], [], [], () => "x");
+ expect(out).toEqual([{ id: "r", startMs: 1500, endMs: 4250 }]);
+ });
+
+ it("maps a region to source time on an identity single clip", () => {
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineEndSec: 10,
+ });
+ const out = projectRawRegionsToSource([region("r", 3, 5)], [c], [c], () => "x");
+ expect(out).toEqual([{ id: "r", startMs: 3000, endMs: 5000, clipIndex: 0 }]);
+ });
+
+ it("keeps a region on its source moment despite a trim before it (the core bug)", () => {
+ // Identity clip src[0,10]==raw[0,10]; trim removes src[2,4]. A region at raw[6,8]
+ // must still land on source [6,8] — NOT [8,10] (compressed-vs-raw slip by 2s).
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineEndSec: 10,
+ });
+ const segments = resolvePlaybackSegments([c], [trim("a", 2, 4)]);
+ const out = projectRawRegionsToSource([region("r", 6, 8)], segments, [c], () => "x");
+ expect(out).toEqual([{ id: "r", startMs: 6000, endMs: 8000, clipIndex: 1 }]);
+ });
+
+ it("splits a region straddling two clips into one entry per clip, payload preserved", () => {
+ const c1 = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 100,
+ sourceEndSec: 105,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ });
+ const c2 = clip({
+ id: "c2",
+ assetId: "a",
+ sourceStartSec: 200,
+ sourceEndSec: 205,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ });
+ const out = projectRawRegionsToSource(
+ [region("r", 3, 7, "keep")],
+ [c1, c2],
+ [c1, c2],
+ () => "r2",
+ );
+ expect(out).toEqual([
+ { id: "r", startMs: 103000, endMs: 105000, clipIndex: 0, payload: "keep" },
+ { id: "r2", startMs: 200000, endMs: 202000, clipIndex: 1, payload: "keep" },
+ ]);
+ });
+
+ it("splits a region whose source range a trim cuts across two kept segments", () => {
+ // Identity clip src[0,10]; trim removes src[4,6]. Region raw[3,8] covers source
+ // [3,4] (seg1, kept) + [6,8] (seg2, kept); the [4,6] middle is trimmed away.
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineEndSec: 10,
+ });
+ const segments = resolvePlaybackSegments([c], [trim("a", 4, 6)]);
+ const out = projectRawRegionsToSource([region("r", 3, 8)], segments, [c], () => "r2");
+ expect(out).toEqual([
+ { id: "r", startMs: 3000, endMs: 4000, clipIndex: 0 },
+ { id: "r2", startMs: 6000, endMs: 8000, clipIndex: 1 },
+ ]);
+ });
+});
+
+describe("resolveNativePosition", () => {
+ it("tracks later source windows when three clips share one asset (no trims)", () => {
+ const clips = [
+ clip({ id: "c1", assetId: "shared", sourceStartSec: 0, sourceEndSec: 4 }),
+ clip({
+ id: "c2",
+ assetId: "shared",
+ sourceStartSec: 20,
+ sourceEndSec: 24,
+ timelineStartSec: 4,
+ timelineEndSec: 8,
+ }),
+ clip({
+ id: "c3",
+ assetId: "shared",
+ sourceStartSec: 40,
+ sourceEndSec: 44,
+ timelineStartSec: 8,
+ timelineEndSec: 12,
+ }),
+ ];
+ expect(resolveNativePosition(6.5, clips, clips)).toMatchObject({
+ clip: { id: "c2" },
+ clipIndex: 1,
+ sourceTimeSec: 22.5,
+ });
+ expect(resolveNativePosition(10, clips, clips)).toMatchObject({
+ clip: { id: "c3" },
+ clipIndex: 2,
+ sourceTimeSec: 42,
+ });
+ });
+
+ it("tracks the active source clock (and thus the right asset/camera) across distinct assets", () => {
+ const clips = [
+ clip({ id: "a-clip", assetId: "asset-a", sourceStartSec: 5, sourceEndSec: 9 }),
+ clip({
+ id: "b-clip",
+ assetId: "asset-b",
+ sourceStartSec: 100,
+ sourceEndSec: 105,
+ timelineStartSec: 4,
+ timelineEndSec: 9,
+ }),
+ clip({
+ id: "c-clip",
+ assetId: "asset-c",
+ sourceStartSec: 12,
+ sourceEndSec: 15,
+ timelineStartSec: 9,
+ timelineEndSec: 12,
+ }),
+ ];
+ expect(resolveNativePosition(7.25, clips, clips)).toMatchObject({
+ clip: { assetId: "asset-b" },
+ clipIndex: 1,
+ sourceTimeSec: 103.25,
+ });
+ expect(resolveNativePosition(11, clips, clips)).toMatchObject({
+ clip: { assetId: "asset-c" },
+ clipIndex: 2,
+ sourceTimeSec: 14,
+ });
+ });
+
+ it("resolves the playhead to the correct source time after a trim (no compressed slip)", () => {
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineEndSec: 10,
+ });
+ const segments = resolvePlaybackSegments([c], [trim("a", 2, 4)]);
+ // raw 1 → source 1 on seg1; raw 6 → source 6 on seg2 (NOT 8).
+ expect(resolveNativePosition(1, segments, [c])).toMatchObject({
+ clipIndex: 0,
+ sourceTimeSec: 1,
+ });
+ expect(resolveNativePosition(6, segments, [c])).toMatchObject({
+ clipIndex: 1,
+ sourceTimeSec: 6,
+ });
+ });
+
+ it("snaps to the next kept segment when the playhead sits over a trimmed-out stretch", () => {
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineEndSec: 10,
+ });
+ const segments = resolvePlaybackSegments([c], [trim("a", 2, 4)]);
+ // raw 3 is inside the removed [2,4] stretch → resume at seg2's source start (4).
+ expect(resolveNativePosition(3, segments, [c])).toMatchObject({
+ clipIndex: 1,
+ sourceTimeSec: 4,
+ });
+ });
+
+ it("returns null when there are no segments", () => {
+ expect(resolveNativePosition(1, [], [])).toBeNull();
+ });
+});
+
+describe("anchorRawRegionsToClips (v4→v5 migration core)", () => {
+ // goodtest's real layout: clip A [asset_f] src[0,25.557313] raw[0,25.557313],
+ // clip B [asset_e] src[0,8.149313] raw[25.557313,33.706626].
+ const clipA = clip({
+ id: "clip_a",
+ assetId: "asset_f",
+ sourceStartSec: 0,
+ sourceEndSec: 25.557313,
+ timelineStartSec: 0,
+ timelineEndSec: 25.557313,
+ });
+ const clipB = clip({
+ id: "clip_b",
+ assetId: "asset_e",
+ sourceStartSec: 0,
+ sourceEndSec: 8.149313,
+ timelineStartSec: 25.557313,
+ timelineEndSec: 33.706626,
+ });
+
+ it("splits a straddling region into one anchored entry per clip, payload preserved", () => {
+ // goodtest speed [8149,28575]ms straddles A→B; first entry keeps the id.
+ let n = 0;
+ const out = anchorRawRegionsToClips(
+ [{ id: "s_straddle", startMs: 8149, endMs: 28575, speed: 3 }],
+ [clipA, clipB],
+ () => `gen_${n++}`,
+ );
+ expect(out).toHaveLength(2);
+ // The two fragments carry no shared marker: equal properties + adjacency is what
+ // makes them read as one pill.
+ expect(out[0]).toMatchObject({
+ id: "s_straddle",
+ clipId: "clip_a",
+ speed: 3,
+ });
+ expect(out[0].sourceStartSec).toBeCloseTo(8.149, 5);
+ expect(out[0].sourceEndSec).toBeCloseTo(25.557313, 5);
+ expect(out[1]).toMatchObject({
+ id: "gen_0",
+ clipId: "clip_b",
+ speed: 3,
+ });
+ expect(out[1].sourceStartSec).toBeCloseTo(0, 5);
+ expect(out[1].sourceEndSec).toBeCloseTo(3.017687, 5);
+ // No leftover RAW-ms fields on the anchored shape.
+ expect(out[0]).not.toHaveProperty("startMs");
+ expect(out[0]).not.toHaveProperty("endMs");
+ });
+
+ it("anchors a region wholly inside one clip to that clip, keeping its id", () => {
+ let n = 0;
+ const out = anchorRawRegionsToClips(
+ [{ id: "s_inA", startMs: 2151, endMs: 8149, speed: 3 }],
+ [clipA, clipB],
+ () => `gen_${n++}`,
+ );
+ expect(out).toHaveLength(1);
+ expect(out[0]).toMatchObject({ id: "s_inA", clipId: "clip_a", speed: 3 });
+ expect(out[0].sourceStartSec).toBeCloseTo(2.151, 5);
+ expect(out[0].sourceEndSec).toBeCloseTo(8.149, 5);
+ });
+
+ it("drops a zero-length / off-timeline region (covers no clip, can never play)", () => {
+ let n = 0;
+ const out = anchorRawRegionsToClips(
+ [
+ { id: "s_zero", startMs: 8149, endMs: 8149, speed: 3 },
+ { id: "s_past_end", startMs: 40000, endMs: 42000, speed: 3 },
+ ],
+ [clipA, clipB],
+ () => `gen_${n++}`,
+ );
+ expect(out).toEqual([]);
+ });
+});
+
+// ─── The two universal region rules ────────────────────────────────────────
+
+describe("regionIdentityKey (what a region IS)", () => {
+ it("ignores position and provenance entirely", () => {
+ const a = { id: "a", clipId: "c1", startMs: 0, endMs: 1000, sourceStartSec: 0, speed: 3 };
+ const b = {
+ id: "b",
+ clipId: "c2",
+ startMs: 90000,
+ endMs: 92000,
+ sourceStartSec: 40,
+ origin: "agent",
+ reason: "whatever",
+ speed: 3,
+ };
+ expect(regionIdentityKey(a)).toBe(regionIdentityKey(b));
+ });
+
+ it("separates regions whose properties differ", () => {
+ expect(regionIdentityKey({ id: "a", speed: 3 })).not.toBe(
+ regionIdentityKey({ id: "b", speed: 2 }),
+ );
+ expect(regionIdentityKey({ id: "a", depth: 3, focus: { cx: 0.5, cy: 0.5 } })).not.toBe(
+ regionIdentityKey({ id: "b", depth: 3, focus: { cx: 0.2, cy: 0.5 } }),
+ );
+ });
+
+ it("is stable against key order, including nested objects", () => {
+ expect(regionIdentityKey({ id: "a", depth: 3, focus: { cy: 0.4, cx: 0.1 } })).toBe(
+ regionIdentityKey({ focus: { cx: 0.1, cy: 0.4 }, depth: 3, id: "b" }),
+ );
+ });
+
+ it("collapses a property-less kind (trim / full-camera) to a constant → always mergeable", () => {
+ const t1 = { id: "t1", assetId: "a", startSec: 0, endSec: 2, reason: "", origin: "user" };
+ const t2 = { id: "t2", assetId: "b", startSec: 9, endSec: 9.5, reason: "x", origin: "agent" };
+ expect(regionIdentityKey(t1)).toBe(regionIdentityKey(t2));
+ });
+});
+
+describe("coalesceByIdentity (rule 1 — merge)", () => {
+ const span = (id: string, start: number, end: number, identity: string) => ({
+ id,
+ start,
+ end,
+ identity,
+ });
+
+ it("merges touching spans of the same identity regardless of provenance", () => {
+ const out = coalesceByIdentity([span("a", 0, 5, "x"), span("b", 5, 9, "x")]);
+ expect(out).toHaveLength(1);
+ expect(out[0]).toMatchObject({ start: 0, end: 9, ids: ["a", "b"] });
+ });
+
+ it("never merges touching spans of different identity", () => {
+ const out = coalesceByIdentity([span("a", 0, 5, "fast"), span("b", 5, 9, "slow")]);
+ expect(out).toHaveLength(2);
+ });
+
+ it("does not merge same-identity spans separated by a gap", () => {
+ const out = coalesceByIdentity([span("a", 0, 5, "x"), span("b", 7, 9, "x")]);
+ expect(out).toHaveLength(2);
+ });
+
+ it("property-less kinds (constant identity) always merge when adjacent — the trim rule, derived", () => {
+ const out = coalesceByIdentity([
+ span("t1", 0, 2, ""),
+ span("t2", 2, 4, ""),
+ span("t3", 4, 6, ""),
+ ]);
+ expect(out).toHaveLength(1);
+ expect(out[0].ids).toEqual(["t1", "t2", "t3"]);
+ });
+
+ it("split → change a property → rejoined: stays TWO pills (identity mismatch)", () => {
+ // The exact scenario: one region split by a reorder, one half edited, clips restored.
+ const rejoinedButEdited = coalesceByIdentity([
+ span("half1", 0, 5, regionIdentityKey({ speed: 3 })),
+ span("half2", 5, 9, regionIdentityKey({ speed: 2 })),
+ ]);
+ expect(rejoinedButEdited).toHaveLength(2);
+ // …and if the property is put back, they merge again, with no memory of the split.
+ const rejoinedUnedited = coalesceByIdentity([
+ span("half1", 0, 5, regionIdentityKey({ speed: 3 })),
+ span("half2", 5, 9, regionIdentityKey({ speed: 3 })),
+ ]);
+ expect(rejoinedUnedited).toHaveLength(1);
+ });
+});
+
+describe("clampSpanAgainstNeighbours (rule 2 — repel)", () => {
+ const other = (id: string, start: number, end: number, identity: string) => ({
+ id,
+ start,
+ end,
+ identity,
+ });
+
+ it("stops at a different-identity neighbour on the right", () => {
+ const out = clampSpanAgainstNeighbours({ start: 0, end: 8 }, "fast", [
+ other("n", 5, 12, "slow"),
+ ]);
+ expect(out).toEqual({ start: 0, end: 5 });
+ });
+
+ it("stops at a different-identity neighbour on the left", () => {
+ const out = clampSpanAgainstNeighbours({ start: 3, end: 10 }, "fast", [
+ other("n", 0, 5, "slow"),
+ ]);
+ expect(out).toEqual({ start: 5, end: 10 });
+ });
+
+ it("treats a same-identity neighbour as no obstacle (they simply merge)", () => {
+ const out = clampSpanAgainstNeighbours({ start: 0, end: 8 }, "fast", [
+ other("n", 5, 12, "fast"),
+ ]);
+ expect(out).toEqual({ start: 0, end: 8 });
+ });
+
+ it("is squeezed by blockers on both sides", () => {
+ const out = clampSpanAgainstNeighbours({ start: 1, end: 10 }, "fast", [
+ other("l", 0, 3, "slow"),
+ other("r", 7, 12, "other"),
+ ]);
+ expect(out).toEqual({ start: 3, end: 7 });
+ });
+
+ it("leaves a span that overlaps nothing untouched", () => {
+ expect(
+ clampSpanAgainstNeighbours({ start: 2, end: 4 }, "fast", [other("n", 8, 9, "slow")]),
+ ).toEqual({ start: 2, end: 4 });
+ });
+});
+
+describe("pills wired to the universal rules", () => {
+ const clipA = clip({
+ id: "clip_a",
+ assetId: "asset_f",
+ sourceStartSec: 0,
+ sourceEndSec: 25.557313,
+ timelineStartSec: 0,
+ timelineEndSec: 25.557313,
+ });
+ const clipB = clip({
+ id: "clip_b",
+ assetId: "asset_e",
+ sourceStartSec: 0,
+ sourceEndSec: 8.149313,
+ timelineStartSec: 25.557313,
+ timelineEndSec: 33.706626,
+ });
+ const clips = [clipA, clipB];
+ const ids = () => {
+ let n = 0;
+ return () => `gen_${n++}`;
+ };
+
+ it("merges two INDEPENDENTLY authored adjacent regions with equal properties", () => {
+ // Never authored as one region, never split — they merge purely because they are
+ // indistinguishable. This is what the groupId model could not do.
+ const pills = coalesceRegionsForRuler([
+ { id: "a", startMs: 2000, endMs: 5000, speed: 3 },
+ { id: "b", startMs: 5000, endMs: 9000, speed: 3 },
+ ]);
+ expect(pills).toHaveLength(1);
+ expect(pills[0].ids).toEqual(["a", "b"]);
+ });
+
+ it("keeps adjacent regions with different properties as separate pills", () => {
+ const pills = coalesceRegionsForRuler([
+ { id: "a", startMs: 2000, endMs: 5000, speed: 3 },
+ { id: "b", startMs: 5000, endMs: 9000, speed: 1.5 },
+ ]);
+ expect(pills).toHaveLength(2);
+ });
+
+ it("resolvePillIds returns every region under the pill, from any member id", () => {
+ const regions = [
+ { id: "a", startMs: 2000, endMs: 5000, speed: 3 },
+ { id: "b", startMs: 5000, endMs: 9000, speed: 3 },
+ { id: "c", startMs: 20000, endMs: 21000, speed: 3 },
+ ];
+ expect(resolvePillIds(regions, "b").sort()).toEqual(["a", "b"]);
+ expect(resolvePillIds(regions, "c")).toEqual(["c"]);
+ });
+
+ it("resizing a pill across a clip boundary re-anchors it into one fragment per clip", () => {
+ const regions = anchorRegionsWithDerivedMs(
+ [{ id: "s", startMs: 2000, endMs: 5000, speed: 3 }],
+ clips,
+ ids(),
+ );
+ const out = replacePillSpan(regions, "s", 20000, 28000, clips, ids());
+ expect(out).toHaveLength(2);
+ expect(out.map((r) => (r as { clipId?: string }).clipId)).toEqual(["clip_a", "clip_b"]);
+ // …and it still reads as a single pill, because the halves share properties.
+ expect(coalesceRegionsForRuler(out)).toHaveLength(1);
+ });
+
+ it("clamps a resize at a neighbouring pill of different properties (magnet)", () => {
+ const regions = [
+ ...anchorRegionsWithDerivedMs(
+ [{ id: "fast", startMs: 0, endMs: 4000, speed: 3 }],
+ clips,
+ ids(),
+ ),
+ ...anchorRegionsWithDerivedMs(
+ [{ id: "slow", startMs: 10000, endMs: 15000, speed: 1.5 }],
+ clips,
+ ids(),
+ ),
+ ];
+ // Try to stretch `fast` well into `slow`; it must stop at slow's edge (10s).
+ const out = replacePillSpan(regions, "fast", 0, 13000, clips, ids());
+ const fast = out.find((r) => (r as { speed?: number }).speed === 3);
+ const slow = out.find((r) => (r as { speed?: number }).speed === 1.5);
+ expect(fast?.endMs).toBe(10000);
+ // the neighbour is never moved or trimmed
+ expect(slow?.startMs).toBe(10000);
+ expect(slow?.endMs).toBe(15000);
+ });
+});
+
+describe("legacy groupId must never affect identity (regression: test 1)", () => {
+ it("merges two independently authored regions that carry DIFFERENT legacy groupIds", () => {
+ // Reproduces the in-app failure: both regions were migrated to v5 and kept a
+ // groupId from the removed group model. Same speed, exactly adjacent → one pill.
+ const pills = coalesceRegionsForRuler([
+ { id: "a", groupId: "grp_a", startMs: 6599, endMs: 8149, speed: 0.75 },
+ { id: "b", groupId: "grp_b", startMs: 8149, endMs: 14349, speed: 0.75 },
+ ]);
+ expect(pills).toHaveLength(1);
+ expect(pills[0].ids).toEqual(["a", "b"]);
+ });
+
+ it("still separates them when a real property differs", () => {
+ const pills = coalesceRegionsForRuler([
+ { id: "a", groupId: "grp_a", startMs: 6599, endMs: 8149, speed: 0.75 },
+ { id: "b", groupId: "grp_b", startMs: 8149, endMs: 14349, speed: 2 },
+ ]);
+ expect(pills).toHaveLength(2);
+ });
+
+ it("drops groupId when re-anchoring, so it stops propagating", () => {
+ const c = clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 20,
+ timelineEndSec: 20,
+ });
+ const out = anchorRegionsWithDerivedMs(
+ [{ id: "s", groupId: "legacy", startMs: 2000, endMs: 5000, speed: 3 }],
+ [c],
+ () => "gen",
+ );
+ expect(out[0]).not.toHaveProperty("groupId");
+ });
+});
diff --git a/src/lib/ai-edition/timeline/timelineMap.ts b/src/lib/ai-edition/timeline/timelineMap.ts
new file mode 100644
index 000000000..8cca4c3ca
--- /dev/null
+++ b/src/lib/ai-edition/timeline/timelineMap.ts
@@ -0,0 +1,494 @@
+// The single place that maps between the timeline's three coordinate systems.
+// See docs/architecture/timeline-coordinate-refactor.md.
+//
+// RAW virtual — the ruler the user manipulates; trims still occupy their
+// space. `currentTimeSec`, the playhead, region authoring, and
+// `document.timeline.clips[].timelineStartSec` all live here.
+// source — a clip's own media time (assetId + sourceSec); what the
+// decoders, the native compositor, and trims are expressed in.
+// compressed — the trim-narrowed playback sequence (`resolvePlaybackSegments`),
+// laid out back-to-back from 0; what the native free-run stream
+// and the export frame count advance through.
+//
+// A raw clip is identity between source-time and raw-virtual-time (its timeline
+// length equals its source length — no speed baked into the geometry), so raw↔
+// source within one clip is a plain shift by the clip's own start offset. The
+// bug this module fixes was projecting regions authored in RAW coordinates
+// against the COMPRESSED segment layout, which slips every region after a trim
+// forward by the trimmed duration.
+
+import type { AxcutClip } from "../schema";
+import { ventilateSpanAcrossClips } from "./region-ventilation";
+import { getRawVirtualStartTime } from "./virtual-preview";
+
+/** A modifier fragment anchored to one clip in that clip's own source time — the
+ * Stage B storage shape (see docs/architecture/timeline-coordinate-refactor.md).
+ * Trims narrow the clip's kept source ranges, so an anchored fragment is clipped/
+ * hidden by the same interval math with no reprojection; a reorder carries it with
+ * its clip by `clipId`.
+ *
+ * A region the user authored across a clip boundary is stored as one fragment per
+ * covered clip. Nothing records that they belong together: by the universal merge rule
+ * they share the same properties, so they render as one pill whenever they are adjacent —
+ * and stop doing so if one of them is edited. `T` is the payload minus the RAW-ms span. */
+export type ClipAnchored<T> = Omit<T, "startMs" | "endMs"> & {
+ clipId: string;
+ sourceStartSec: number;
+ sourceEndSec: number;
+};
+
+/**
+ * Migrate RAW-virtual-ms regions (the v4 document-level storage) to clip-anchored
+ * source-time fragments (the v5 storage). Each region is ventilated across the RAW
+ * clip layout it was authored against: wholly inside one clip → one fragment;
+ * straddling a boundary → one fragment per covered clip (they re-merge on display by the
+ * merge rule, since they share properties — no bookkeeping). Each fragment
+ * gets its own unique `id` (first keeps the original region id; extras from
+ * `makeId`). A zero-length / off-timeline region covers no clip and is dropped (it
+ * could never play). Pure; reused by the v4→v5 schema migration and by re-anchoring
+ * after a raw edit.
+ */
+export function anchorRawRegionsToClips<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+ rawClips: AxcutClip[],
+ makeId: () => string,
+): ClipAnchored<T>[] {
+ const byId = new Map(rawClips.map((c) => [c.id, c]));
+ const out: ClipAnchored<T>[] = [];
+ for (const region of regions) {
+ const frags = ventilateSpanAcrossClips(region.startMs / 1000, region.endMs / 1000, rawClips);
+ frags.forEach((f, i) => {
+ const clip = byId.get(f.clipId);
+ if (!clip) return;
+ // `groupId` is dropped, not carried: it is a dead marker from the removed group
+ // model, and re-anchoring is the natural place to stop it propagating into new
+ // fragments. (Identity ignores it anyway — see NON_IDENTITY_FIELDS.)
+ const {
+ startMs: _s,
+ endMs: _e,
+ groupId: _g,
+ ...payload
+ } = region as T & { groupId?: string };
+ out.push({
+ ...(payload as Omit<T, "startMs" | "endMs">),
+ id: i === 0 ? region.id : makeId(),
+ clipId: f.clipId,
+ sourceStartSec: clip.sourceStartSec + f.localStartSec,
+ sourceEndSec: clip.sourceStartSec + f.localEndSec,
+ });
+ });
+ }
+ return out;
+}
+
+/**
+ * The RAW ruler span a clip-anchored fragment currently occupies, derived from its
+ * clip's live position — the single forward map source↔raw for one fragment (a raw
+ * clip is identity between source and raw-virtual time). Returns null when the
+ * fragment's `clipId` is gone (clip deleted → the fragment is not shown). Used to
+ * place pills (`V4Timeline`), derive the transition `startMs/endMs`, and by
+ * `coalesceAnchoredFragments`.
+ */
+export function anchoredToRawSpanSec(
+ fragment: { clipId: string; sourceStartSec: number; sourceEndSec: number },
+ clips: AxcutClip[],
+): { startSec: number; endSec: number } | null {
+ const clip = clips.find((c) => c.id === fragment.clipId);
+ if (!clip) return null;
+ return {
+ startSec: clip.timelineStartSec + (fragment.sourceStartSec - clip.sourceStartSec),
+ endSec: clip.timelineStartSec + (fragment.sourceEndSec - clip.sourceStartSec),
+ };
+}
+
+// ─── The two universal region rules ────────────────────────────────────────
+// Every kind of ruler region (trim, zoom, speed, annotation, full-camera) obeys the
+// same two rules, expressed once here rather than re-derived per kind:
+//
+// 1. MERGE — two regions of the same kind with the SAME identity that touch are
+// indistinguishable to the user, so they are one pill. However they
+// came to be adjacent (authored side by side, split by a reorder then
+// rejoined, …) is irrelevant: identity is what a region IS, never where
+// it came from or how it got there.
+// 2. REPEL — two regions of the same kind with DIFFERENT identities may not
+// overlap. An edit clamps to the neighbour's edge; the neighbour never
+// moves (no cascade).
+//
+// A kind with no properties (trim, full-camera) collapses to a constant identity, so
+// its regions always merge — the long-standing trim behaviour, now *derived* from the
+// general rule instead of hand-coded beside it.
+
+/** Fields that say WHERE a region sits or WHERE IT CAME FROM — never what it is. */
+const NON_IDENTITY_FIELDS = new Set([
+ // position
+ "id",
+ "clipId",
+ "assetId",
+ "sourceStartSec",
+ "sourceEndSec",
+ "startMs",
+ "endMs",
+ "startSec",
+ "endSec",
+ // provenance / metadata
+ "reason",
+ "origin",
+ "source",
+ "annotationSource",
+ // Legacy provenance marker from the removed group model. It no longer exists in
+ // code, but it SURVIVES in documents already migrated to v5 (which never re-run the
+ // migration), and two independently authored regions carry different ones. Left in,
+ // it would silently make otherwise identical regions refuse to merge — which is
+ // exactly the bug this list must prevent: provenance never decides identity.
+ "groupId",
+]);
+
+/** Canonical serialisation — key order must not affect identity. */
+function stableStringify(value: unknown): string {
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
+ const obj = value as Record<string, unknown>;
+ const keys = Object.keys(obj)
+ .filter((k) => obj[k] !== undefined)
+ .sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
+}
+
+/**
+ * What a region IS: every property that affects how it renders/behaves, canonically
+ * serialised; position and provenance excluded. Two regions of one kind sharing this
+ * key are the same pill when adjacent. A propertyless kind yields a constant key, so
+ * all its regions merge.
+ */
+export function regionIdentityKey(region: Record<string, unknown>): string {
+ const payload: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(region)) {
+ if (!NON_IDENTITY_FIELDS.has(key) && value !== undefined) payload[key] = value;
+ }
+ return stableStringify(payload);
+}
+
+export interface IdentifiedSpan {
+ id: string;
+ /** RAW timeline seconds. */
+ start: number;
+ end: number;
+ identity: string;
+}
+
+export interface MergedSpan {
+ start: number;
+ end: number;
+ /** Underlying region ids under this span, left-to-right. */
+ ids: string[];
+ identity: string;
+}
+
+/**
+ * Rule 1 — merge touching spans that share an identity, and only those. Spans of
+ * different identities never merge even when they touch. This is the single coalescing
+ * primitive for every region kind: trims pass a constant identity (→ always merge),
+ * modifiers pass {@link regionIdentityKey}.
+ */
+export function coalesceByIdentity(spans: IdentifiedSpan[], epsilonSec = 0.001): MergedSpan[] {
+ const byIdentity = new Map<string, IdentifiedSpan[]>();
+ for (const span of spans) {
+ const list = byIdentity.get(span.identity) ?? [];
+ list.push(span);
+ byIdentity.set(span.identity, list);
+ }
+ const out: MergedSpan[] = [];
+ for (const [identity, list] of byIdentity) {
+ let cur: MergedSpan | null = null;
+ for (const span of [...list].sort((a, b) => a.start - b.start)) {
+ if (cur && span.start - cur.end <= epsilonSec) {
+ cur.end = Math.max(cur.end, span.end);
+ cur.ids.push(span.id);
+ } else {
+ cur = { start: span.start, end: span.end, ids: [span.id], identity };
+ out.push(cur);
+ }
+ }
+ }
+ return out.sort((a, b) => a.start - b.start);
+}
+
+/**
+ * Rule 2 — clamp an edited span so it cannot overlap a same-kind span of a DIFFERENT
+ * identity. Blocking neighbours act as walls: the edited span stops at the nearest
+ * blocking edge on each side and the neighbour is never modified or displaced, so an
+ * edit can never cascade into regions the user did not touch. Same-identity spans are
+ * not obstacles — overlapping them is harmless, they simply merge (rule 1).
+ */
+export function clampSpanAgainstNeighbours(
+ desired: { start: number; end: number },
+ identity: string,
+ others: IdentifiedSpan[],
+): { start: number; end: number } {
+ let start = Math.min(desired.start, desired.end);
+ let end = Math.max(desired.start, desired.end);
+ for (const other of [...others].sort((a, b) => a.start - b.start)) {
+ if (other.identity === identity) continue;
+ if (other.end <= start || other.start >= end) continue; // no overlap
+ if (other.start <= start) start = Math.max(start, other.end);
+ else end = Math.min(end, other.start);
+ }
+ return { start, end: Math.max(start, end) };
+}
+
+/** A pill as the ruler draws it: a run of same-identity regions that touch. */
+export interface RegionPill<T> extends MergedSpan {
+ /** First region under the pill — carries the payload the label needs. */
+ member: T;
+}
+
+/**
+ * Group stored regions into the pills the ruler draws, via the universal merge rule.
+ * Works off the DERIVED `startMs`/`endMs`: they are always present (even before a region
+ * is anchored) and kept in sync with the anchor, so a region can never become invisible
+ * merely because it has no anchor yet.
+ */
+export function coalesceRegionsForRuler<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+ epsilonSec = 0.001,
+): RegionPill<T>[] {
+ const byId = new Map(regions.map((r) => [r.id, r]));
+ const spans = regions.map((r) => ({
+ id: r.id,
+ start: r.startMs / 1000,
+ end: r.endMs / 1000,
+ identity: regionIdentityKey(r as unknown as Record<string, unknown>),
+ }));
+ return coalesceByIdentity(spans, epsilonSec).map((merged) => ({
+ ...merged,
+ member: byId.get(merged.ids[0]) as T,
+ }));
+}
+
+/**
+ * The regions that render as the SAME pill as `id`. Recomputed from the merge rule
+ * rather than stored: nothing records which regions belong together, because equal
+ * properties + adjacency already say so, and that stays correct however they came to be
+ * adjacent. Every mutation routes through this so it acts on exactly what the user sees
+ * as one pill.
+ */
+export function resolvePillIds<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+ id: string,
+ epsilonSec = 0.001,
+): string[] {
+ return coalesceRegionsForRuler(regions, epsilonSec).find((p) => p.ids.includes(id))?.ids ?? [id];
+}
+
+/**
+ * Move/resize the pill containing `id`, obeying both rules: the requested span is first
+ * CLAMPED against pills of a different identity (rule 2 — they act as walls and never
+ * move), then the pill's regions are replaced by fragments re-anchored to the clamped
+ * span, carrying the pill's payload. Crossing a clip boundary re-splits into one fragment
+ * per clip; coming back inside one clip collapses again; and neighbours of the same
+ * identity simply merge on display (rule 1). No provenance is consulted anywhere.
+ */
+export function replacePillSpan<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+ id: string,
+ startMs: number,
+ endMs: number,
+ clips: AxcutClip[],
+ makeId: () => string,
+ epsilonSec = 0.001,
+): T[] {
+ const pills = coalesceRegionsForRuler(regions, epsilonSec);
+ const pill = pills.find((p) => p.ids.includes(id));
+ if (!pill) return regions;
+
+ const clamped = clampSpanAgainstNeighbours(
+ { start: Math.min(startMs, endMs) / 1000, end: Math.max(startMs, endMs) / 1000 },
+ pill.identity,
+ pills
+ .filter((p) => p !== pill)
+ .map((p) => ({ id: p.ids[0], start: p.start, end: p.end, identity: p.identity })),
+ );
+
+ const under = new Set(pill.ids);
+ const { startMs: _s, endMs: _e, ...payload } = pill.member;
+ const rebuilt = anchorRegionsWithDerivedMs(
+ [
+ {
+ ...payload,
+ id: pill.ids[0],
+ startMs: Math.round(clamped.start * 1000),
+ endMs: Math.round(clamped.end * 1000),
+ } as unknown as T,
+ ],
+ clips,
+ makeId,
+ ) as unknown as T[];
+ return [...regions.filter((r) => !under.has(r.id)), ...rebuilt];
+}
+
+/** A region after v5 migration: either an anchored fragment (with its derived ms
+ * cache) or — when nothing could be anchored — the original region, untouched. */
+export type MigratedRegion<T extends { id: string; startMs: number; endMs: number }> =
+ | T
+ | (ClipAnchored<T> & { startMs: number; endMs: number });
+
+/**
+ * The v5 STORED shape of a migrated region: a clip-anchored fragment plus a
+ * DERIVED `startMs`/`endMs` cache (its current RAW ruler span). During the Stage B
+ * transition the anchor is the SSOT while un-migrated consumers keep reading
+ * `startMs`/`endMs`; a structural op (or migration) re-derives them from the anchor.
+ * Shared by the disk-load path (`documentSchema`'s v4→v5 preprocess) and the v2
+ * migration so both emit identical v5 regions.
+ *
+ * **Never loses a region.** Unlike the low-level `anchorRawRegionsToClips` (which
+ * yields no fragments when a region covers no clip — correct for a ventilation
+ * primitive), a region that cannot be anchored is passed through UNANCHORED, keeping
+ * its original `startMs`/`endMs`. That case is real and must not drop user data: a v2
+ * project imported before its asset duration is probed has a zero-extent clip, so
+ * nothing overlaps yet. Such regions stay valid (the anchor is optional) and get
+ * anchored later once the clip has a real duration.
+ */
+export function anchorRegionsWithDerivedMs<
+ T extends { id: string; startMs: number; endMs: number },
+>(regions: T[], clips: AxcutClip[], makeId: () => string): MigratedRegion<T>[] {
+ return regions.flatMap<MigratedRegion<T>>((region) => {
+ const frags = anchorRawRegionsToClips([region], clips, makeId);
+ if (frags.length === 0) return [region];
+ return frags.map((frag) => {
+ const span = anchoredToRawSpanSec(frag, clips);
+ return {
+ ...frag,
+ startMs: span ? Math.round(span.startSec * 1000) : region.startMs,
+ endMs: span ? Math.round(span.endSec * 1000) : region.endMs,
+ };
+ });
+ });
+}
+
+/**
+ * RAW-virtual extent of a (possibly trim-narrowed) playback segment: where it
+ * sits on the ruler, derived from its parent raw clip via `getRawVirtualStartTime`.
+ * Note the raw span of two segments split by a trim has a GAP between them — the
+ * removed stretch keeps its place on the raw ruler — which is exactly what makes
+ * a region land on the source moment it was authored on rather than sliding into
+ * the gap.
+ */
+export function segmentRawSpanSec(
+ segment: AxcutClip,
+ rawClips: AxcutClip[],
+): { startSec: number; endSec: number } {
+ const startSec = getRawVirtualStartTime(segment, rawClips);
+ const lenSec = (segment.sourceEndSec ?? segment.sourceStartSec) - segment.sourceStartSec;
+ return { startSec, endSec: startSec + lenSec };
+}
+
+/**
+ * Project RAW-virtual-ms regions (zoom / speed / camera-fullscreen, as authored
+ * on the ruler) onto the SOURCE-ms ranges the native compositor matches against.
+ * The raw→source map goes through each visible segment's OWN raw extent, and the
+ * trim-compressed order supplies `clipIndex`. A region whose source range a trim
+ * splits across two kept segments yields one entry per segment (fresh id for the
+ * extra copies, original id on the first — matching the previous contract). A
+ * region overlapping no visible segment passes through unchanged with no
+ * `clipIndex` (native falls back to time-overlap), same as before.
+ *
+ * `visibleSegments` MUST be the same array (same order) serialized to
+ * `Scene.clips` so the emitted `clipIndex` lines up with the native stream;
+ * `rawClips` is `document.timeline.clips` (the un-compressed layout the regions
+ * were authored against).
+ */
+export function projectRawRegionsToSource<T extends { id: string; startMs: number; endMs: number }>(
+ regions: T[],
+ visibleSegments: AxcutClip[],
+ rawClips: AxcutClip[],
+ makeId: () => string,
+): (T & { clipIndex?: number })[] {
+ const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips));
+ const out: (T & { clipIndex?: number })[] = [];
+ for (const region of regions) {
+ const lo = Math.min(region.startMs, region.endMs) / 1000;
+ const hi = Math.max(region.startMs, region.endMs) / 1000;
+ let emitted = 0;
+ visibleSegments.forEach((seg, clipIndex) => {
+ const { startSec: segRawStart, endSec: segRawEnd } = spans[clipIndex];
+ const s = Math.max(lo, segRawStart);
+ const e = Math.min(hi, segRawEnd);
+ if (e <= s) return;
+ const srcStart = seg.sourceStartSec + (s - segRawStart);
+ const srcEnd = seg.sourceStartSec + (e - segRawStart);
+ out.push({
+ ...region,
+ id: emitted === 0 ? region.id : makeId(),
+ startMs: Math.round(srcStart * 1000),
+ endMs: Math.round(srcEnd * 1000),
+ clipIndex,
+ });
+ emitted += 1;
+ });
+ if (emitted === 0) out.push(region);
+ }
+ return out;
+}
+
+export interface NativePosition {
+ /** The trim-narrowed playback segment (from `visibleSegments`) that is active. */
+ clip: AxcutClip;
+ /** Its index in `visibleSegments`, matching `SceneDescription.clips` / native `clip_index`. */
+ clipIndex: number;
+ /** Screen-source seconds the native decoder should present for this segment. */
+ sourceTimeSec: number;
+}
+
+// A hair before a segment's source end, so a scrub/seek never asks the decoder
+// for a frame past EOF (returns a null D3D frame → crash). Mirrors the margin the
+// old `resolveNativePlaybackPosition` carried; ~1 frame @ 30fps.
+const NATIVE_EOF_MARGIN_SEC = 0.033;
+
+/**
+ * Resolve a RAW timeline playhead to the active native clip's screen-source clock.
+ *
+ * The playhead (`currentTimeSec`) lives on the RAW ruler (trims still occupy their
+ * space); the native compositor plays the trim-COMPRESSED `visibleSegments`. This
+ * maps raw→source through each segment's OWN raw extent (via `rawClips`, the
+ * un-compressed layout) so the source time is correct after a trim, and returns
+ * the segment's `clipIndex` in the compressed stream so `setActiveClip`/`presentTime`
+ * address the right decoder + the right paired camera. When the raw playhead sits
+ * over a trimmed-out stretch, it snaps to the next kept segment (where content
+ * resumes) rather than the removed frames. Returns null only when there are no
+ * segments at all. Replaces `nativePlaybackPosition.resolveNativePlaybackPosition`,
+ * which conflated the raw and compressed layouts (correct only without trims).
+ */
+export function resolveNativePosition(
+ rawSec: number,
+ visibleSegments: AxcutClip[],
+ rawClips: AxcutClip[],
+): NativePosition | null {
+ if (!Number.isFinite(rawSec) || visibleSegments.length === 0) return null;
+ const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips));
+
+ // Segment whose RAW extent contains the playhead (last segment's end inclusive).
+ let index = spans.findIndex((s, i) => {
+ const isLast = i === spans.length - 1;
+ return rawSec >= s.startSec && (rawSec < s.endSec || (isLast && rawSec <= s.endSec));
+ });
+ // Over a trimmed-out gap (or before the first kept frame): snap to the next kept
+ // segment; if the playhead is past all kept content, clamp into the last one.
+ let clampToSegmentStart = false;
+ if (index < 0) {
+ index = spans.findIndex((s) => s.startSec >= rawSec);
+ if (index < 0) index = visibleSegments.length - 1;
+ else clampToSegmentStart = true;
+ }
+
+ const seg = visibleSegments[index];
+ const segSourceEnd = seg.sourceEndSec ?? seg.sourceStartSec;
+ const unclamped = clampToSegmentStart
+ ? seg.sourceStartSec
+ : seg.sourceStartSec + (rawSec - spans[index].startSec);
+ const maxSource = Math.max(seg.sourceStartSec, segSourceEnd - NATIVE_EOF_MARGIN_SEC);
+ return {
+ clip: seg,
+ clipIndex: index,
+ sourceTimeSec: Math.max(seg.sourceStartSec, Math.min(maxSource, unclamped)),
+ };
+}
diff --git a/src/lib/ai-edition/timeline/trim-mapping.ts b/src/lib/ai-edition/timeline/trim-mapping.ts
index c100de5ef..a0415907f 100644
--- a/src/lib/ai-edition/timeline/trim-mapping.ts
+++ b/src/lib/ai-edition/timeline/trim-mapping.ts
@@ -10,11 +10,8 @@
// across the ruler and re-attach to whichever clip they land on.
import type { AxcutClip, AxcutTrimRange } from "../schema";
-import {
- type CoalescedSpan,
- coalesceTouchingSpans,
- ventilateSpanAcrossClips,
-} from "./region-ventilation";
+import { type CoalescedSpan, ventilateSpanAcrossClips } from "./region-ventilation";
+import { coalesceByIdentity, regionIdentityKey } from "./timelineMap";
/** A clip's on-timeline extent in source-seconds (how much of the source it plays). */
function clipSourceLen(clip: AxcutClip): number {
@@ -81,15 +78,17 @@ export function ventilateTimelineSpanToTrims(
}
/**
- * Group trims whose timeline spans touch into one visual unit — trims carry no
- * user-visible content (no text, no per-instance settings), so unlike zoom /
- * speed / annotation, coalescing them for display and selection loses nothing.
- * This is what lets a trim ventilated across a clip boundary (necessarily 2+
- * DSL rows, see `ventilateTimelineSpanToTrims`) render and act as ONE pill —
- * aligning trims with how zoom/speed/annotation already behave under direct
- * drag (never visibly split). Trims with no mapped timeline span (their
- * carrying clip is gone) are dropped entirely, same as `trimToTimelineSpan`
- * callers already expect.
+ * Group trims whose timeline spans touch into one visual unit.
+ *
+ * This used to be trim-specific logic sitting beside a separate mechanism for the
+ * other region kinds — the duplication is gone: trims now go through the SAME merge
+ * primitive as zoom / speed / annotation (`coalesceByIdentity`). A trim simply has no
+ * user-visible properties, so all trims share one identity and any two that touch
+ * merge; the familiar "trims always merge" behaviour is now a *consequence* of the
+ * general rule rather than a rule of its own. That is what lets a trim ventilated
+ * across a clip boundary (necessarily 2+ DSL rows, see `ventilateTimelineSpanToTrims`)
+ * render and act as ONE pill. Trims with no mapped timeline span (their carrying clip
+ * is gone) are dropped, same as `trimToTimelineSpan` callers already expect.
*/
export function coalescedTrimGroups(
trimRanges: AxcutTrimRange[],
@@ -99,10 +98,23 @@ export function coalescedTrimGroups(
const spans = trimRanges
.map((t) => {
const mapped = trimToTimelineSpan(t, clips);
- return mapped ? { id: t.id, start: mapped.start, end: mapped.end } : null;
+ return mapped
+ ? {
+ id: t.id,
+ start: mapped.start,
+ end: mapped.end,
+ // A trim has no user-visible properties, so every trim shares one identity
+ // and any two that touch merge. That is not a trim-specific rule any more:
+ // it is the SAME merge primitive every modifier uses, reached through an
+ // empty property set. (`regionIdentityKey` excludes position + provenance,
+ // which is all a trim carries.)
+ identity: regionIdentityKey(t as unknown as Record<string, unknown>),
+ }
+ : null;
})
- .filter((x): x is { id: string; start: number; end: number } => x !== null);
- return coalesceTouchingSpans(spans, epsilonSec);
+ .filter((x): x is { id: string; start: number; end: number; identity: string } => x !== null);
+ // Drop the identity key: it is an internal grouping detail, and every trim shares it.
+ return coalesceByIdentity(spans, epsilonSec).map(({ ids, start, end }) => ({ ids, start, end }));
}
/**
diff --git a/src/native/nativePlaybackPosition.test.ts b/src/native/nativePlaybackPosition.test.ts
deleted file mode 100644
index e0aabc135..000000000
--- a/src/native/nativePlaybackPosition.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { describe, expect, it } from "vitest";
-import type { AxcutClip } from "@/lib/ai-edition/schema";
-import { resolveNativePlaybackPosition } from "./nativePlaybackPosition";
-
-function clip(overrides: Partial<AxcutClip> & Pick<AxcutClip, "id" | "assetId">): AxcutClip {
- return {
- id: overrides.id,
- assetId: overrides.assetId,
- sourceStartSec: 0,
- sourceEndSec: 4,
- timelineStartSec: 0,
- timelineEndSec: 4,
- wordRefs: [],
- origin: "user",
- reason: "test",
- ...overrides,
- };
-}
-
-describe("resolveNativePlaybackPosition", () => {
- it("tracks later source windows when three timeline clips share one asset", () => {
- const clips = [
- clip({ id: "c1", assetId: "shared", sourceStartSec: 0, sourceEndSec: 4 }),
- clip({
- id: "c2",
- assetId: "shared",
- sourceStartSec: 20,
- sourceEndSec: 24,
- timelineStartSec: 4,
- timelineEndSec: 8,
- }),
- clip({
- id: "c3",
- assetId: "shared",
- sourceStartSec: 40,
- sourceEndSec: 44,
- timelineStartSec: 8,
- timelineEndSec: 12,
- }),
- ];
-
- expect(resolveNativePlaybackPosition(clips, 6.5)).toMatchObject({
- clip: { id: "c2" },
- clipIndex: 1,
- sourceTimeSec: 22.5,
- });
- expect(resolveNativePlaybackPosition(clips, 10)).toMatchObject({
- clip: { id: "c3" },
- clipIndex: 2,
- sourceTimeSec: 42,
- });
- });
-
- it("tracks the active source clock when each clip references a distinct asset", () => {
- const clips = [
- clip({ id: "a-clip", assetId: "asset-a", sourceStartSec: 5, sourceEndSec: 9 }),
- clip({
- id: "b-clip",
- assetId: "asset-b",
- sourceStartSec: 100,
- sourceEndSec: 105,
- timelineStartSec: 4,
- timelineEndSec: 9,
- }),
- clip({
- id: "c-clip",
- assetId: "asset-c",
- sourceStartSec: 12,
- sourceEndSec: 15,
- timelineStartSec: 9,
- timelineEndSec: 12,
- }),
- ];
-
- expect(resolveNativePlaybackPosition(clips, 7.25)).toMatchObject({
- clip: { id: "b-clip", assetId: "asset-b" },
- clipIndex: 1,
- sourceTimeSec: 103.25,
- });
- expect(resolveNativePlaybackPosition(clips, 11)).toMatchObject({
- clip: { id: "c-clip", assetId: "asset-c" },
- clipIndex: 2,
- sourceTimeSec: 14,
- });
- });
-
- it("selects the new clip exactly at a boundary and returns null in a gap", () => {
- const clips = [
- clip({ id: "first", assetId: "a", sourceStartSec: 10, sourceEndSec: 14 }),
- clip({
- id: "second",
- assetId: "b",
- sourceStartSec: 30,
- sourceEndSec: 34,
- timelineStartSec: 5,
- timelineEndSec: 9,
- }),
- ];
-
- expect(resolveNativePlaybackPosition(clips, 4.5)).toBeNull();
- expect(resolveNativePlaybackPosition(clips, 5)).toMatchObject({
- clip: { id: "second" },
- clipIndex: 1,
- sourceTimeSec: 30,
- });
- });
-});
diff --git a/src/native/nativePlaybackPosition.ts b/src/native/nativePlaybackPosition.ts
deleted file mode 100644
index cbacc3a93..000000000
--- a/src/native/nativePlaybackPosition.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import type { AxcutClip } from "@/lib/ai-edition/schema";
-
-export interface NativePlaybackPosition {
- clip: AxcutClip;
- /** Index in timeline order, matching SceneDescription.clips when the caller passes visible clips. */
- clipIndex: number;
- /** Screen-source seconds expected by the native decoder for this clip. */
- sourceTimeSec: number;
-}
-
-/**
- * Resolve an app timeline playhead to the active clip's screen-source clock.
- *
- * Native `presentTime` and `setActiveClip` do not consume absolute timeline
- * seconds: both decoders seek in the active asset, with webcam time derived as
- * `screenSourceTime - webcamOffset`. Keeping this conversion pure and shared
- * prevents paused scrubs and clip-boundary switches from using different clocks.
- */
-export function resolveNativePlaybackPosition(
- clips: readonly AxcutClip[],
- timelineTimeSec: number,
-): NativePlaybackPosition | null {
- if (!Number.isFinite(timelineTimeSec) || clips.length === 0) return null;
-
- const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
- const clipIndex = ordered.findIndex((clip, index) => {
- const isLast = index === ordered.length - 1;
- return (
- timelineTimeSec >= clip.timelineStartSec &&
- (timelineTimeSec < clip.timelineEndSec || (isLast && timelineTimeSec <= clip.timelineEndSec))
- );
- });
- if (clipIndex < 0) return null;
-
- const clip = ordered[clipIndex];
- const unclampedSourceTime = clip.sourceStartSec + (timelineTimeSec - clip.timelineStartSec);
- const sourceEnd = clip.sourceEndSec !== undefined ? clip.sourceEndSec : unclampedSourceTime;
- const maxAllowedSourceTime = Math.max(clip.sourceStartSec, sourceEnd - 0.033);
- return {
- clip,
- clipIndex,
- sourceTimeSec: Math.max(
- clip.sourceStartSec,
- Math.min(maxAllowedSourceTime, unclampedSourceTime),
- ),
- };
-}
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 23579343f..5d9c763ce 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -59,7 +59,7 @@ function makeDoc(
const createdAt = "2024-01-01T00:00:00.000Z";
const baseProject = { id: "p1", title: "Test", createdAt, updatedAt: createdAt };
return {
- schemaVersion: 4,
+ schemaVersion: 5,
project: {
...baseProject,
...(overrides.project ?? {}),
@@ -426,6 +426,63 @@ describe("buildSceneDescription.zoomRegions", () => {
});
});
+// --- zoomRegions × trims (raw↔compressed regression) ------------------------
+// See docs/architecture/timeline-coordinate-refactor.md. Regions are authored in
+// RAW virtual-ms (trims still occupy the ruler), but the scene handed to native is
+// built from TRIM-COMPRESSED playback segments (`resolveVisibleClips`). A region
+// after a trim must still fire at the SAME source moment the user placed it on the
+// raw ruler; today it slips by the total trimmed duration before it. This block is
+// the failing witness for that bug (preview AND export both build the scene here).
+
+describe("buildSceneDescription.zoomRegions with an earlier trim", () => {
+ it("keeps a zoom on the source moment it was authored on, despite a trim before it", () => {
+ // Identity clip: source [0,10] == timeline [0,10] (raw ruler == source time).
+ const asset = makeAsset({ id: "a", originalPath: "/a.mp4" });
+ const clip = makeClip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ // Trim removes source [2,4]. Playback compresses to two kept segments:
+ // seg1 source [0,2] @ compressed timeline [0,2]
+ // seg2 source [4,10] @ compressed timeline [2,8]
+ // Zoom authored at RAW timeline [6,8] → identity clip → source [6,8]. Source 6
+ // is kept (after the trim) so it belongs to seg2 (clipIndex 1). The CORRECT
+ // scene zoom is source [6,8] on clipIndex 1 — NOT [8,10] (what raw-coords-vs-
+ // compressed-clips ventilation produces: it shifts the region forward by the 2s
+ // the trim removed earlier on the timeline).
+ const doc = makeDoc({
+ assets: [asset],
+ clips: [clip],
+ timeline: {
+ trimRanges: [
+ { id: "t1", assetId: "a", startSec: 2, endSec: 4, reason: "", origin: "user" },
+ ],
+ },
+ zoomRanges: [
+ makeZoom({ id: "z", startMs: 6000, endMs: 8000, depth: 3, focus: { cx: 0.5, cy: 0.5 } }),
+ ],
+ });
+ const { zoomRegions } = buildSceneDescription(doc);
+ expect(zoomRegions).toEqual([
+ {
+ id: "z",
+ startSec: 6,
+ endSec: 8,
+ scale: 2,
+ focusX: 0.5,
+ focusY: 0.5,
+ focusMode: null,
+ rotation: null,
+ clipIndex: 1,
+ },
+ ]);
+ });
+});
+
// --- cameraFullscreenRegions -------------------------------------------------
describe("buildSceneDescription.cameraFullscreenRegions", () => {
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 8ce1a1cc2..586a029e0 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -22,7 +22,7 @@ import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
import type { AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";
import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";
-import { projectRegionsToSourceTime } from "@/lib/ai-edition/timeline/region-ventilation";
+import { projectRawRegionsToSource } from "@/lib/ai-edition/timeline/timelineMap";
import { computeCompositeLayout, webcamSizeToFraction } from "@/lib/compositeLayout";
import type { AspectRatio } from "@/utils/aspectRatioUtils";
import { getAspectRatioValue, getNativeAspectRatioValue } from "@/utils/aspectRatioUtils";
@@ -353,45 +353,48 @@ export function buildSceneDescription(
},
);
- // Zoom + Full Camera regions are authored in virtual (timeline) ms in the
- // document, but the compositor matches them against each frame's SOURCE
- // time the same way the web export's frame loop does. Project them onto the
- // covered clips' source ranges (splitting any region that straddles a clip
- // boundary) so the native side gets the same shape the export pipeline
- // already proves correct.
+ // Zoom + Full Camera + speed regions are authored in RAW virtual (timeline) ms
+ // in the document — the ruler where trims still occupy their space — but the
+ // compositor matches them against each frame's SOURCE time. `projectRawRegionsToSource`
+ // bridges the two through `timelineMap`: it resolves each region's RAW coordinate
+ // against every visible segment's OWN raw extent (via `document.timeline.clips`,
+ // the un-compressed layout) and maps the overlap to that segment's source range,
+ // tagging it with the segment's `clipIndex` in `visibleClips` (= the order of
+ // `Scene.clips`). A region whose source range a trim splits across two kept
+ // segments yields one entry per segment.
//
- // BUG corrigé : ces trois projections utilisaient `document.timeline.clips` BRUT
- // (ordre non trié, non filtré) au lieu de `visibleClips` (trié par timelineStartSec
- // + filtré, = l'ordre EXACT de `clips[]` envoyé au natif). Le `clipIndex` projeté sur
- // chaque région ne correspondait donc jamais à l'index réel dans `Scene.clips`, ET
- // `clipIndex` n'était de toute façon jamais émis avant ce fix (voir `region-ventilation.ts`)
- // — le natif retombait alors sur un simple recouvrement temporel (`belongs` dans
- // `for_clip_window`, compositor.rs), qui laissait fuir un zoom d'un clip vers un autre
- // dès que leurs fenêtres source se chevauchaient numériquement (typiquement deux clips
- // qui démarrent tous les deux près du temps source 0 de leur propre fichier).
- const projectedZoomRegions = projectRegionsToSourceTime(
+ // BUG corrigé : ces projections utilisaient `visibleClips` (COMPRESSÉ, trims retirés)
+ // à la fois pour le recouvrement ET la source, alors que les régions sont posées en
+ // coordonnées RAW. Dès qu'un trim retirait Δs avant une région, la coordonnée RAW
+ // dépassait la position compressée de Δ → la région se déclenchait Δ trop tôt (offset
+ // visible en preview ET au rendu). On passe désormais le layout RAW pour le mapping
+ // raw→source et on ne garde `visibleClips` que pour l'ordre/`clipIndex`.
+ const projectedZoomRegions = projectRawRegionsToSource(
document.zoomRanges ?? [],
visibleClips,
+ document.timeline.clips,
() => createId("zoom"),
);
- const projectedCameraFullscreenRegions = projectRegionsToSourceTime(
+ const projectedCameraFullscreenRegions = projectRawRegionsToSource(
((document.legacyEditor as Record<string, unknown> | null)?.cameraFullscreenRegions as
| CameraFullscreenRegion[]
| undefined) ?? [],
visibleClips,
+ document.timeline.clips,
() => createId("camfull"),
);
// Speed regions carry an extra `speed` field the standard `rangeSchema` does not, so we
// can't read from `document.timeline.speedRanges` today (see SceneDescription.speedRegions
// comment). The legacy web exporter reads from `legacyEditor.speedRegions`; we mirror it.
- // `projectRegionsToSourceTime` accepts any `T extends { id; startMs; endMs }` and copies
+ // `projectRawRegionsToSource` accepts any `T extends { id; startMs; endMs }` and copies
// every other field verbatim via `{...region}` — so the `speed` field passes through,
// and the splitting-across-clips semantics match zoomRegions / cameraFullscreenRegions.
- const projectedSpeedRegions = projectRegionsToSourceTime(
+ const projectedSpeedRegions = projectRawRegionsToSource(
((document.legacyEditor as Record<string, unknown> | null)?.speedRegions as
| SpeedRegion[]
| undefined) ?? [],
visibleClips,
+ document.timeline.clips,
() => createId("speed"),
);
diff --git a/src/native/useNativePlaybackSync.ts b/src/native/useNativePlaybackSync.ts
index 6b82cb4f8..f7ea7dd29 100644
--- a/src/native/useNativePlaybackSync.ts
+++ b/src/native/useNativePlaybackSync.ts
@@ -19,22 +19,25 @@
*/
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import type { AxcutClip } from "@/lib/ai-edition/schema";
+import { resolveNativePosition } from "@/lib/ai-edition/timeline/timelineMap";
import {
getCurrentNativeViewId,
setNativePlaying,
setNativeTime,
subscribeNativeCompositor,
} from "./nativeCompositorStore";
-import { resolveNativePlaybackPosition } from "./nativePlaybackPosition";
export function useNativePlaybackSync(
playing: boolean,
currentTimeSec: number,
- clips: readonly AxcutClip[],
+ /** Trim-compressed playback segments (`resolveVisibleClips`) — the native stream. */
+ visibleSegments: readonly AxcutClip[],
+ /** RAW clip layout (`document.timeline.clips`) `currentTimeSec` is expressed against. */
+ rawClips: readonly AxcutClip[],
): void {
const activePosition = useMemo(
- () => resolveNativePlaybackPosition(clips, currentTimeSec),
- [clips, currentTimeSec],
+ () => resolveNativePosition(currentTimeSec, [...visibleSegments], [...rawClips]),
+ [visibleSegments, rawClips, currentTimeSec],
);
const activeClipId = activePosition?.clip.id ?? null;
const sourceTimeSec = activePosition?.sourceTimeSec ?? null;