Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(timeline): close the same ambiguity in playback and auto-zoom
Etienne Lescot8eefde39dc0a
diff --git a/src/components/ai-edition/VirtualPreview.playback.test.tsx b/src/components/ai-edition/VirtualPreview.playback.test.tsxnew file mode 100644index 000000000..3a56c0266--- /dev/null+++ b/src/components/ai-edition/VirtualPreview.playback.test.tsx@@ -0,0 +1,200 @@+import "@testing-library/jest-dom";+import { act, cleanup, fireEvent, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AxcutClip, AxcutTrimRange } from "@/lib/ai-edition/schema";+import { type VideoSource, VirtualPreview } from "./VirtualPreview";++// The rAF tick is the whole subject here, so it is driven by hand rather than by the+// browser: `tick()` runs exactly one frame, which is what makes "what did the loop decide+// at 9.96 s?" an assertion instead of a race.+let frameCallbacks: FrameRequestCallback[] = [];++beforeEach(() => {+ frameCallbacks = [];+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {+ frameCallbacks.push(cb);+ return frameCallbacks.length;+ });+ vi.stubGlobal("cancelAnimationFrame", () => {+ // Frames are drained by `tick()`, never scheduled, so there is nothing to cancel —+ // the stub only exists so the effect's cleanup has something to call.+ });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++function tick() {+ const pending = frameCallbacks;+ frameCallbacks = [];+ act(() => {+ for (const cb of pending) cb(0);+ });+}++function clip(+ id: string,+ assetId: string,+ sourceStartSec: number,+ sourceEndSec: number,+ timelineStartSec: number,+): AxcutClip {+ return {+ id,+ assetId,+ sourceStartSec,+ sourceEndSec,+ timelineStartSec,+ timelineEndSec: timelineStartSec + (sourceEndSec - sourceStartSec),+ wordRefs: [],+ origin: "user",+ reason: "",+ };+}++/** A `<video>` jsdom will not drive: its clock is set by the test, and play/pause are+ * recorded rather than performed (jsdom implements neither). */+function driveVideo(element: HTMLVideoElement) {+ let currentTime = 0;+ let paused = true;+ const pauseCalls: number[] = [];+ Object.defineProperty(element, "currentTime", {+ configurable: true,+ get: () => currentTime,+ set: (next: number) => {+ currentTime = next;+ },+ });+ Object.defineProperty(element, "paused", { configurable: true, get: () => paused });+ Object.defineProperty(element, "readyState", { configurable: true, get: () => 4 });+ Object.defineProperty(element, "duration", { configurable: true, get: () => 10 });+ element.play = vi.fn(() => {+ paused = false;+ return Promise.resolve();+ });+ element.pause = vi.fn(() => {+ paused = true;+ pauseCalls.push(currentTime);+ });+ return {+ pauseCalls,+ play: () => {+ paused = false;+ },+ seekTo: (next: number) => {+ currentTime = next;+ },+ get currentTime() {+ return currentTime;+ },+ };+}++function mount(clips: AxcutClip[], trimRanges: AxcutTrimRange[] = []) {+ const onTimeChange = vi.fn();+ const sources: VideoSource[] = [{ id: "a1", src: "file:///tmp/a1.mp4", label: "a1" }];+ const { container } = render(+ <VirtualPreview+ videoSources={sources}+ clips={clips}+ trimRanges={trimRanges}+ onTimeChange={onTimeChange}+ />,+ );+ const element = container.querySelector("video");+ if (!element) throw new Error("no <video> rendered");+ const video = driveVideo(element as HTMLVideoElement);+ // How the real app resolves its first clip: metadata arrives, the component seeks to+ // its current virtual time, and that seek is what names the active clip.+ act(() => {+ fireEvent.loadedMetadata(element);+ });+ return { onTimeChange, video, element: element as HTMLVideoElement };+}++const reportedTimes = (onTimeChange: ReturnType<typeof vi.fn>) =>+ onTimeChange.mock.calls.map((call) => call[0] as number);++describe("VirtualPreview playback across a clip boundary", () => {+ // The reported bug: with two clips over ONE recording, playback stopped on reaching+ // the second clip and the playhead landed at the end of the timeline.+ it("crosses into the second clip of the same recording instead of stopping", () => {+ const clips = [clip("clip_1", "a1", 0, 10, 0), clip("clip_2", "a1", 0, 10, 10)];+ const { onTimeChange, video } = mount(clips);++ video.play();+ // Play out clip_1 up to the frame where the boundary advance fires.+ for (const t of [1, 5, 9, 9.96]) {+ video.seekTo(t);+ tick();+ }++ expect(video.pauseCalls).toHaveLength(0);+ // The playhead must never have been reported inside clip_2's span, let alone at the+ // end of the timeline (20), while clip_1 was still playing.+ expect(Math.max(...reportedTimes(onTimeChange))).toBeLessThanOrEqual(10.001);+ // …and the advance rewound the media to clip_2's source in-point and kept playing.+ expect(video.currentTime).toBe(0);+ expect(reportedTimes(onTimeChange).at(-1)).toBeCloseTo(10, 5);++ // Now play clip_2 out; only NOW may playback stop, at the end of the timeline.+ for (const t of [1, 5, 9.96]) {+ video.seekTo(t);+ tick();+ }+ expect(video.pauseCalls).toHaveLength(1);+ expect(reportedTimes(onTimeChange).at(-1)).toBeCloseTo(20, 5);+ });++ it("crosses the boundary the same way whatever order the clips are laid in", () => {+ // The layout that used to escape the bug (a foreign clip last) and the ones that did+ // not must now behave identically.+ const layouts: Array<[string, AxcutClip[]]> = [+ [+ "twins then a foreign clip",+ [clip("clip_1", "a1", 0, 10, 0), clip("clip_2", "a1", 0, 10, 10)],+ ],+ [+ "a foreign clip between the twins",+ [+ clip("clip_1", "a1", 0, 10, 0),+ clip("clip_3", "c1", 0, 10, 10),+ clip("clip_2", "a1", 0, 10, 20),+ ],+ ],+ ];+ for (const [label, clips] of layouts) {+ const { onTimeChange, video } = mount(clips);+ video.play();+ for (const t of [5, 9.96]) {+ video.seekTo(t);+ tick();+ }+ expect(video.pauseCalls, label).toHaveLength(0);+ expect(Math.max(...reportedTimes(onTimeChange)), label).toBeLessThanOrEqual(10.001);+ cleanup();+ }+ });++ it("skips a cut authored on the playing clip even when its twin keeps that stretch", () => {+ // clip_1 cuts source 4–6; clip_2 is the same recording, uncut. The cut must apply+ // while clip_1 plays — the twin keeping the stretch used to answer for it.+ const clips = [clip("clip_1", "a1", 0, 10, 0), clip("clip_2", "a1", 0, 10, 10)];+ const trims: AxcutTrimRange[] = [+ { id: "trim_1", assetId: "a1", clipId: "clip_1", startSec: 4, endSec: 6 },+ ];+ const { video } = mount(clips, trims);++ video.play();+ video.seekTo(3);+ tick();+ expect(video.currentTime).toBe(3); // before the cut: untouched++ video.seekTo(5); // inside clip_1's cut+ tick();+ expect(video.currentTime).toBe(6); // jumped to where clip_1's content resumes+ expect(video.pauseCalls).toHaveLength(0);+ });+});diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsxindex 178c87f88..c3eb6cbbd 100644--- a/src/components/ai-edition/VirtualPreview.tsx+++ b/src/components/ai-edition/VirtualPreview.tsx@@ -12,7 +12,9 @@ import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeliimport {clampVirtualTime,findNextKeptSegment,+ findRawClipForSegment,getRawVirtualStartTime,+ locateKeptSegment,locateSourcePosition,locateVirtualPosition,totalVirtualDuration,@@ -225,10 +227,17 @@ export function VirtualPreview({// jumps by the trim's exact width the instant `v.currentTime` does, so the ruler's// playhead visually skips the trim marker instead of drifting through it.if (!v.paused) {- const inKeptSegment = locateSourcePosition(+ // Resolved against the segments of the clip we are ACTUALLY playing (see+ // `locateKeptSegment`). Asking the whole segment list — all this could do+ // before a trim named its clip — let a twin clip over the same recording+ // answer "yes, that stretch is kept" for a cut authored on this one, so the+ // cut was simply not skipped during playback.+ const inKeptSegment = locateKeptSegment(playbackClipsRef.current,+ clipsRef.current,v.currentTime,activeSourceId,+ activeClipIdRef.current ?? undefined,);if (!inKeptSegment) {const nextKeptSegment = findNextKeptSegment(@@ -237,19 +246,14 @@ export function VirtualPreview({virtualTimeSecRef.current,activeSourceId,v.currentTime,+ activeClipIdRef.current ?? undefined,);if (nextKeptSegment) {- const rawClip =- clipsRef.current.find(- (c) => c.id === nextKeptSegment.id || nextKeptSegment.id.startsWith(`${c.id}_seg`),- ) ??- clipsRef.current.find(- (c) =>- c.assetId === nextKeptSegment.assetId &&- nextKeptSegment.sourceStartSec >= c.sourceStartSec - 0.001 &&- (c.sourceEndSec == null ||- nextKeptSegment.sourceStartSec <= c.sourceEndSec + 0.001),- );+ // `findRawClipForSegment` is the ONE definition of the segment-id+ // convention `resolvePlaybackSegments` emits; this used to re-implement+ // it verbatim, which is precisely the second reader that definition+ // exists to prevent.+ const rawClip = findRawClipForSegment(nextKeptSegment, clipsRef.current);if (rawClip) {activeClipIdRef.current = rawClip.id;}diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsxindex 9aa811d6d..9d905e8d8 100644--- a/src/components/ai-edition/v4/V4Timeline.tsx+++ b/src/components/ai-edition/v4/V4Timeline.tsx@@ -45,7 +45,10 @@ import {resolveTimelineSpanToTrim,ventilateTimelineSpanToTrims,} from "@/lib/ai-edition/timeline/trim-mapping";-import { buildAutoZoomSuggestions } from "@/lib/ai-edition/timeline/zoom-suggestions";+import {+ type AutoZoomSuggestion,+ buildAutoZoomSuggestionsForClips,+} from "@/lib/ai-edition/timeline/zoom-suggestions";import { nativeBridgeClient } from "@/native/client";import { ASPECT_RATIO_PRESETS, getAspectRatioLabel } from "@/utils/aspectRatioUtils";import { TransportBar } from "../TransportBar";@@ -883,26 +886,43 @@ export function V4Timeline({];// Auto-enhance option 1 — the deterministic cursor-telemetry auto-zoom- // (ported from main; NOT AI). Reads the recorded cursor movement for the- // primary asset and drops zoom-ins on the dwell moments.+ // (ported from main; NOT AI). Reads the recorded cursor movement and drops+ // zoom-ins on the dwell moments.+ //+ // Telemetry belongs to a RECORDING, not to a clip: it is fetched per asset and read in+ // that asset's source time. Projecting it onto the ruler is `buildAutoZoomSuggestionsForClips`'+ // job — every clip drawing on the asset gets its own zooms, including the second clip over+ // a recording already used once. Feeding the raw source-time spans to `addZoomsBulk` (which+ // reads RAW TIMELINE ms) is what confined every suggestion to the first clip's stretch of+ // ruler. Each asset with clips is asked, not just the first: a second recording on the+ // timeline was previously never consulted at all.const runAutoZooms = useCallback(async () => {setAutoEnhanceOpen(false);- const source = videoSources[0];- const asset = tl.assets.find((a) => a.id === source?.id) ?? tl.assets[0];- if (!source || !asset) {+ const sources = videoSources.filter((source) => clips.some((c) => c.assetId === source.id));+ if (sources.length === 0) {toast.error(t("toolbar.importRecordingFirst"));return;}setAutoBusy(true);try {- const telemetry =- (await nativeBridgeClient.cursor.getTelemetry(fromFileUrl(source.src))) ?? [];- const suggestions = buildAutoZoomSuggestions({- cursorTelemetry: telemetry,- totalMs: (asset.durationSec ?? 0) * 1000,- existingRegions: tl.zoomRegions.map((z) => ({ startMs: z.startMs, endMs: z.endMs })),- defaultDurationMs: 2000,- });+ // Read once, outside the loop: every clip reserves against the zooms the+ // document ALREADY holds, and two clips can never contest the same stretch+ // of ruler, so no accumulation across assets is needed.+ const existingRegions = tl.zoomRegions.map((z) => ({ startMs: z.startMs, endMs: z.endMs }));+ const suggestions: AutoZoomSuggestion[] = [];+ for (const source of sources) {+ const telemetry =+ (await nativeBridgeClient.cursor.getTelemetry(fromFileUrl(source.src))) ?? [];+ suggestions.push(+ ...buildAutoZoomSuggestionsForClips({+ cursorTelemetry: telemetry,+ assetId: source.id,+ clips,+ existingRegions,+ defaultDurationMs: 2000,+ }),+ );+ }if (suggestions.length === 0) {toast.info(t("toolbar.noAutoZoomMoments"), {description: t("toolbar.noAutoZoomMomentsDescription"),@@ -920,7 +940,7 @@ export function V4Timeline({} finally {setAutoBusy(false);}- }, [videoSources, tl, t]);+ }, [videoSources, clips, tl, t]);// Auto-enhance option 2 — hand a generic prompt to the AI agent (smart// zooms + cuts) via the chat prompt-bus. The chat panel owns the outcomediff --git a/src/lib/ai-edition/timeline/virtual-preview.test.ts b/src/lib/ai-edition/timeline/virtual-preview.test.tsindex 5ceb94e66..baf08d91c 100644--- a/src/lib/ai-edition/timeline/virtual-preview.test.ts+++ b/src/lib/ai-edition/timeline/virtual-preview.test.ts@@ -1,4 +1,5 @@import { describe, expect, it } from "vitest";+import { resolvePlaybackSegments } from "../document/timeline";import type { AxcutClip } from "../schema";import { formatSeconds } from "./format";import {@@ -6,6 +7,7 @@ import {findNextKeptSegment,getRawVirtualStartTime,keptWordIdSet,+ locateKeptSegment,locateSourcePosition,locateVirtualPosition,totalVirtualDuration,@@ -162,6 +164,157 @@ describe("virtual-preview pure functions", () => {expect(outOfRange?.clip.id).toBe("clip_1");});+ // The last ~50 ms of a clip: `reachedClipEnd` (VirtualPreview's rAF) fires at+ // `sourceEndSec - 0.04`, so this is the moment the tick has to still know which clip+ // it is on in order to advance to the RIGHT next one.+ describe("the closing edge of a clip, with a twin over the same recording", () => {+ const twins = (order: Array<{ id: string; assetId: string }>): AxcutClip[] => {+ let timelineStartSec = 0;+ return order.map((spec) => {+ const clip: AxcutClip = {+ ...spec,+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec,+ timelineEndSec: timelineStartSec + 10,+ wordRefs: [],+ origin: "user",+ reason: "",+ };+ timelineStartSec += 10;+ return clip;+ });+ };+ const a1 = { id: "clip_a1", assetId: "a1" };+ const a2 = { id: "clip_a2", assetId: "a1" };+ const c3 = { id: "clip_c3", assetId: "c1" };++ // Before this, the preferred clip shared the ambiguous scan's EXCLUSIVE closing+ // edge, so at 9.96 it disowned its own last frames and the scan handed them to its+ // twin — reporting the playhead near the END of that twin (19.96 / 29.96). The rAF+ // then saw "clip end reached" on a clip nothing follows and stopped playback with+ // the playhead parked at the end of the timeline.+ it.each([+ ["two clips over one recording", [a1, a2], "clip_a1", 9.96],+ ["the same pair, laid down the other way round", [a2, a1], "clip_a2", 9.96],+ ["a foreign clip between the twins", [a1, c3, a2], "clip_a1", 9.96],+ ["a foreign clip before the twins", [c3, a1, a2], "clip_a1", 9.96],+ // This layout never showed the bug: the LAST array element was the foreign+ // clip, which the asset filter excluded, so the scan returned null and the rAF+ // fell back to timeline order. Same answer now, for a reason instead of by luck.+ ["the foreign clip last", [a1, a2, c3], "clip_a1", 9.96],+ ])("stays on the clip it is playing — %s", (_label, order, playing, sourceTimeSec) => {+ const clips = twins(order);+ const playingClip = clips.find((c) => c.id === playing);+ if (!playingClip) throw new Error("bad fixture");+ const pos = locateSourcePosition(+ clips,+ sourceTimeSec,+ playingClip.assetId,+ 0.05,+ playingClip.id,+ );+ expect(pos?.clip.id).toBe(playing);+ expect(pos?.virtualTimeSec).toBeCloseTo(playingClip.timelineStartSec + sourceTimeSec, 6);+ });++ it("resolves the same clip whatever the clips' order, with no clip named", () => {+ // The scan cannot know which twin is playing — but its answer must at least not+ // depend on which twin happens to sit last in the array, which is what+ // `index === clips.length - 1` made it do.+ const forward = locateSourcePosition(twins([a1, a2]), 9.96, "a1");+ const reversed = locateSourcePosition(twins([a2, a1]), 9.96, "a1");+ expect(forward?.clip.id).toBe("clip_a1");+ expect(reversed?.clip.id).toBe("clip_a2");+ // i.e. both resolve to the FIRST clip of the asset — the documented behaviour of+ // the ambiguous scan (see the duplicate-clip case above), not to whichever one+ // was laid down last.+ expect(forward?.virtualTimeSec).toBeCloseTo(9.96, 6);+ expect(reversed?.virtualTimeSec).toBeCloseTo(9.96, 6);+ });++ it("still hands a shared boundary to the clip that starts there", () => {+ // A plain split: clip_1 ends where clip_2 begins. The exclusive edge exists for+ // exactly this, and the two-pass scan must not have loosened it.+ const split: AxcutClip[] = [+ { ...twins([a1])[0], sourceStartSec: 0, sourceEndSec: 10 },+ {+ ...twins([a2])[0],+ sourceStartSec: 10,+ sourceEndSec: 20,+ timelineStartSec: 10,+ timelineEndSec: 20,+ },+ ];+ expect(locateSourcePosition(split, 10, "a1")?.clip.id).toBe("clip_a2");+ expect(locateSourcePosition(split, 9.9, "a1")?.clip.id).toBe("clip_a1");+ // …and the very end of the timeline still resolves rather than falling off it.+ expect(locateSourcePosition(split, 20, "a1")?.clip.id).toBe("clip_a2");+ });++ it("ignores a named clip whose asset is not the one playing", () => {+ // A stale id during an asset swap must fall through to the scan rather than+ // mapping the time through media that is not on screen.+ const clips = twins([a1, c3]);+ const pos = locateSourcePosition(clips, 5, "a1", 0.05, "clip_c3");+ expect(pos?.clip.id).toBe("clip_a1");+ });+ });++ describe("locateKeptSegment", () => {+ // clip_1 and clip_2 are the same recording twice. clip_1 carries a cut at source+ // 4–6; clip_2 carries none, so it KEEPS that stretch.+ const rawClips: AxcutClip[] = [+ {+ id: "clip_1",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ {+ id: "clip_2",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 10,+ timelineStartSec: 10,+ timelineEndSec: 20,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ ];+ const playbackClips = resolvePlaybackSegments(rawClips, [+ { id: "trim_1", assetId: "a1", clipId: "clip_1", startSec: 4, endSec: 6 },+ ]);++ it("reports source time inside the playing clip's own cut as NOT kept", () => {+ // The twin keeps source 4–6, and the asset-wide scan used to accept its segment+ // as the answer — so the cut was never skipped while clip_1 played.+ expect(locateKeptSegment(playbackClips, rawClips, 5, "a1", "clip_1")).toBeNull();+ });++ it("reports the same source time as kept while the twin plays", () => {+ const pos = locateKeptSegment(playbackClips, rawClips, 5, "a1", "clip_2");+ expect(pos).not.toBeNull();+ expect(pos?.clip.id).toBe("clip_2");+ });++ it("keeps answering for content the playing clip does keep", () => {+ expect(locateKeptSegment(playbackClips, rawClips, 2, "a1", "clip_1")).not.toBeNull();+ expect(locateKeptSegment(playbackClips, rawClips, 8, "a1", "clip_1")).not.toBeNull();+ });++ it("falls back to the asset-wide scan when no clip is named yet", () => {+ // Before the first seek resolves a clip, there is nothing to be faithful to.+ expect(locateKeptSegment(playbackClips, rawClips, 5, "a1")).not.toBeNull();+ });+ });+it("getRawVirtualStartTime maps a kept segment back to exact raw virtual start time", () => {const rawClips: AxcutClip[] = [{@@ -266,4 +419,56 @@ describe("virtual-preview pure functions", () => {expect(nextSeg?.assetId).toBe("a2");expect(getRawVirtualStartTime(nextSeg!, rawClips)).toBe(10.7);});++ describe("findNextKeptSegment never goes backwards", () => {+ // A slice from LATE in the recording laid down first, then a slice from early in+ // it, cut at source 5–10. Both draw on the same asset, so "later in source time"+ // spans two unrelated stretches of ruler.+ const rawClips: AxcutClip[] = [+ {+ id: "clip_1",+ assetId: "a1",+ sourceStartSec: 30,+ sourceEndSec: 40,+ timelineStartSec: 0,+ timelineEndSec: 10,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ {+ id: "clip_2",+ assetId: "a1",+ sourceStartSec: 0,+ sourceEndSec: 20,+ timelineStartSec: 10,+ timelineEndSec: 30,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ ];+ const playbackClips = resolvePlaybackSegments(rawClips, [+ { id: "trim_1", assetId: "a1", clipId: "clip_2", startSec: 5, endSec: 10 },+ ]);++ it("resumes after the cut instead of jumping to the top of the timeline", () => {+ // Playing clip_2 at source 7 — inside its own cut — at raw position 10 + 7 = 17.+ // clip_1 starts at source 30, which IS "later in source time", and its raw start+ // is 0: answering it sent playback back to the beginning, straight into the same+ // cut again, forever.+ const next = findNextKeptSegment(playbackClips, rawClips, 17, "a1", 7, "clip_2");+ expect(next).toBeDefined();+ expect(getRawVirtualStartTime(next!, rawClips)).toBe(20);+ expect(next?.sourceStartSec).toBe(10);+ });++ it("uses the source clock to resume within the clip when the ruler lags", () => {+ // Same moment, but the raw position has not caught up (still reads 10, the start+ // of clip_2). The ruler test alone would answer clip_2's FIRST kept segment —+ // the stretch already played. The clip-scoped source test carries it past the cut.+ const next = findNextKeptSegment(playbackClips, rawClips, 10, "a1", 7, "clip_2");+ expect(next?.sourceStartSec).toBe(10);+ });+ });});diff --git a/src/lib/ai-edition/timeline/virtual-preview.ts b/src/lib/ai-edition/timeline/virtual-preview.tsindex aea0c8181..bdd6aace9 100644--- a/src/lib/ai-edition/timeline/virtual-preview.ts+++ b/src/lib/ai-edition/timeline/virtual-preview.ts@@ -81,6 +81,19 @@ export function getRawVirtualStartTime(segment: AxcutClip, rawClips: AxcutClip[]/*** Resolves the next kept segment on the virtual timeline at or after the given position.* `playbackClips` (from `resolvePlaybackSegments`) is the SSOT for kept timeline content.+ *+ * Two ways to be "next", and the second one has to name a clip. The RAW ruler answers the+ * general case: the first segment starting after where we are. The source clock answers+ * the case the ruler cannot, when the video has run into a cut and the raw position has+ * not caught up — but "later in source time" is only meaningful WITHIN one clip. Asked of+ * a whole asset it compares source positions belonging to different stretches of ruler,+ * and returns whichever clip happens to start deeper into the recording: with a slice from+ * late in the recording laid down BEFORE a trimmed slice from early in it, playing into+ * that trim answered "clip_1" — raw start 0 — so playback jumped back to the top of the+ * timeline, replayed into the same cut, and looped there. Scoped to the clip being played,+ * it means "the next kept stretch of THIS clip", which is the only thing the source clock+ * can honestly say. With no clip named there is nothing to scope it to, and the ruler test+ * above is already the general answer, so the fallback simply does not apply.*/export function findNextKeptSegment(playbackClips: AxcutClip[],@@ -88,6 +101,7 @@ export function findNextKeptSegment(currentRawTime: number,activeSourceId?: string,currentSourceTime?: number,+ activeClipId?: string,): AxcutClip | undefined {for (const seg of playbackClips) {const segRawStart = getRawVirtualStartTime(seg, rawClips);@@ -96,8 +110,10 @@ export function findNextKeptSegment(}if (activeSourceId &&+ activeClipId &¤tSourceTime !== undefined &&seg.assetId === activeSourceId &&+ findRawClipForSegment(seg, rawClips)?.id === activeClipId &&seg.sourceStartSec > currentSourceTime + 0.001) {return seg;@@ -124,17 +140,23 @@ function toPositionAt(};}+/** How a clip's CLOSING edge is treated when asking "is this source time on it?".+ *+ * `exclusive` leaves the closing edge to whichever clip starts there — that is the+ * whole job of the epsilon: at a shared boundary (clip A ends where clip B begins)+ * the time belongs to B, not to the clip that just finished. `inclusive` accepts it,+ * which is what lets a clip's own last frames still resolve to that clip. */+type ClosingEdge = "exclusive" | "inclusive";+function isWithinClipBounds(clip: AxcutClip,- index: number,- total: number,sourceTimeSec: number,epsilon: number,+ closingEdge: ClosingEdge,): boolean {- const lowerBound = clip.sourceStartSec - epsilon;- const upperBound =- index === total - 1 ? (clip.sourceEndSec ?? 0) + epsilon : (clip.sourceEndSec ?? 0) - epsilon;- return sourceTimeSec >= lowerBound && sourceTimeSec <= upperBound;+ const sourceEnd = clip.sourceEndSec ?? 0;+ const upperBound = closingEdge === "inclusive" ? sourceEnd + epsilon : sourceEnd - epsilon;+ return sourceTimeSec >= clip.sourceStartSec - epsilon && sourceTimeSec <= upperBound;}export function locateSourcePosition(@@ -154,27 +176,73 @@ export function locateSourcePosition(): VirtualPosition | null {if (preferredClipId) {const preferredIndex = clips.findIndex((clip) => clip.id === preferredClipId);+ // IDENTITY BEATS PROXIMITY. A caller that names the clip it is tracking is not+ // asking us to guess, so its closing edge is INCLUSIVE: the exclusive bound only+ // exists to break ties in the ambiguous scan below, and a named clip has no tie to+ // break. Sharing that bound is what made the last ~50 ms of a clip resolve to a+ // DIFFERENT clip over the same media — the preferred clip disowned its own final+ // frames and the scan handed them to whichever twin would take them, reporting the+ // playhead near the end of that twin. An asset mismatch means the id is stale (an+ // asset swap in flight), so it falls through to the scan rather than mapping the+ // time through a clip whose media is not the one playing.if (preferredIndex >= 0 &&- isWithinClipBounds(- clips[preferredIndex],- preferredIndex,- clips.length,- sourceTimeSec,- epsilon,- )+ (!assetId || clips[preferredIndex].assetId === assetId) &&+ isWithinClipBounds(clips[preferredIndex], sourceTimeSec, epsilon, "inclusive")) {return toPositionAt(clips, preferredIndex, sourceTimeSec);}}- const clipIndex = clips.findIndex((clip, index) => {- if (assetId && clip.assetId !== assetId) return false;- return isWithinClipBounds(clip, index, clips.length, sourceTimeSec, epsilon);- });+ const scan = (closingEdge: ClosingEdge) =>+ clips.findIndex(+ (clip) =>+ (!assetId || clip.assetId === assetId) &&+ isWithinClipBounds(clip, sourceTimeSec, epsilon, closingEdge),+ );+ // Two passes, because "may this clip claim its closing edge?" is a question about the+ // OTHER clips — is anyone else about to start here? — and never about where the clip+ // sits in an array. This used to be approximated by `index === clips.length - 1`, which+ // made the answer depend on CLIP ORDER: with two clips over one recording, the last+ // array element accepted a closing edge its twin had just refused, so the same playback+ // moment resolved to a different clip depending on whether that twin happened to be laid+ // down last. Preferring a strict containment and only then falling back to the closing+ // edge gives the same result for a plain single-asset timeline (where the last clip is+ // the only one nobody follows) without consulting the order at all.+ const strict = scan("exclusive");+ const clipIndex = strict >= 0 ? strict : scan("inclusive");if (clipIndex < 0) return null;return toPositionAt(clips, clipIndex, sourceTimeSec);}+/**+ * "Where am I in the KEPT content of the clip that is playing?" — the trim-aware+ * counterpart of {@link locateSourcePosition}, resolved against the playback segments+ * (`resolvePlaybackSegments`) instead of the raw clips.+ *+ * The segments of the ACTIVE clip are the whole answer once we know which clip is+ * playing: a source time none of them covers is inside THAT clip's trim, however many+ * other clips of the same media keep the stretch. Scanning every segment by+ * (assetId, sourceTime) — which is all this could do before trims carried a `clipId` —+ * let a twin clip's kept segment answer for the one actually playing, so a cut authored+ * on one clip was silently not skipped during playback while its twin kept that stretch.+ * That is the same wrong-clip class `trimAppliesToClip` closed on the storage side, one+ * layer up. Falls back to the asset-wide scan when the clip is unknown (no active clip+ * yet) or has no segments at all.+ */+export function locateKeptSegment(+ playbackClips: AxcutClip[],+ rawClips: AxcutClip[],+ sourceTimeSec: number,+ assetId?: string,+ activeClipId?: string,+): VirtualPosition | null {+ const ownSegments = activeClipId+ ? playbackClips.filter((seg) => findRawClipForSegment(seg, rawClips)?.id === activeClipId)+ : [];+ if (ownSegments.length > 0) return locateSourcePosition(ownSegments, sourceTimeSec, assetId);+ return locateSourcePosition(playbackClips, sourceTimeSec, assetId);+}+export function keptWordIdSet(clips: AxcutClip[]): Set<string> {return new Set(clips.flatMap((clip) => clip.wordRefs));}diff --git a/src/lib/ai-edition/timeline/zoom-suggestions.test.ts b/src/lib/ai-edition/timeline/zoom-suggestions.test.tsindex 2c0229959..75e63ce79 100644--- a/src/lib/ai-edition/timeline/zoom-suggestions.test.ts+++ b/src/lib/ai-edition/timeline/zoom-suggestions.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from "vitest";import type { CursorTelemetryPoint } from "@/components/video-editor/types";-import { buildAutoZoomSuggestions, detectZoomDwellCandidates } from "./zoom-suggestions";+import type { AxcutClip } from "../schema";+import {+ buildAutoZoomSuggestions,+ buildAutoZoomSuggestionsForClips,+ detectZoomDwellCandidates,+} from "./zoom-suggestions";// A dwell = many samples clustered in time at (nearly) the same position.function dwell(@@ -84,3 +89,114 @@ describe("buildAutoZoomSuggestions", () => {).toEqual([]);});});++describe("buildAutoZoomSuggestionsForClips", () => {+ const clip = (+ id: string,+ assetId: string,+ sourceStartSec: number,+ sourceEndSec: number,+ timelineStartSec: number,+ ): AxcutClip => ({+ id,+ assetId,+ sourceStartSec,+ sourceEndSec,+ timelineStartSec,+ timelineEndSec: timelineStartSec + (sourceEndSec - sourceStartSec),+ wordRefs: [],+ origin: "user",+ reason: "",+ });++ // The bug this covers: telemetry is in the recording's SOURCE time, zoom regions are+ // authored in RAW TIMELINE ms, and the two only coincide for a single clip starting at+ // 0. Every other layout put all the zooms on the first clip's stretch of ruler.+ it("gives a dwell to EVERY clip that replays it, not just the first", () => {+ // One recording, laid down twice: source 0-10 at ruler 0-10, then again at 10-20.+ const clips = [clip("clip_1", "a1", 0, 10, 0), clip("clip_2", "a1", 0, 10, 10)];+ const suggestions = buildAutoZoomSuggestionsForClips({+ cursorTelemetry: dwell(4000, 0.3, 0.7),+ assetId: "a1",+ clips,+ existingRegions: [],+ defaultDurationMs: 2000,+ });+ expect(suggestions.map((s) => s.span)).toEqual([+ { start: 3000, end: 5000 }, // clip_1: source 4s sits at ruler 4s+ { start: 13000, end: 15000 }, // clip_2: the SAME source 4s sits at ruler 14s+ ]);+ for (const suggestion of suggestions) {+ expect(suggestion.focus.cx).toBeCloseTo(0.3, 5);+ expect(suggestion.focus.cy).toBeCloseTo(0.7, 5);+ }+ });++ it("shifts a dwell by the clip's own source in-point", () => {+ // A clip that starts 30s into the recording: source 34s is ruler 4s.+ const clips = [clip("clip_1", "a1", 30, 40, 0)];+ const suggestions = buildAutoZoomSuggestionsForClips({+ cursorTelemetry: dwell(34000, 0.5, 0.5),+ assetId: "a1",+ clips,+ existingRegions: [],+ defaultDurationMs: 2000,+ });+ expect(suggestions.map((s) => s.span)).toEqual([{ start: 3000, end: 5000 }]);+ });++ it("ignores a dwell that falls outside every clip's source window", () => {+ // The recording is long; the timeline keeps only its first 10s.+ const clips = [clip("clip_1", "a1", 0, 10, 0)];+ expect(+ buildAutoZoomSuggestionsForClips({+ cursorTelemetry: dwell(45000, 0.5, 0.5),+ assetId: "a1",+ clips,+ existingRegions: [],+ defaultDurationMs: 2000,+ }),+ ).toEqual([]);+ });++ it("reserves an existing zoom on the clip it actually sits on, and only there", () => {+ // A zoom already covers the dwell on clip_1's ruler span. clip_1 yields; clip_2+ // replays the same source moment on a free stretch of ruler, so it still gets one.+ // Compared in source ms — the frame the caller used to hand down — that one region+ // suppressed the whole recording's worth of suggestions.+ const clips = [clip("clip_1", "a1", 0, 10, 0), clip("clip_2", "a1", 0, 10, 10)];+ const suggestions = buildAutoZoomSuggestionsForClips({+ cursorTelemetry: dwell(4000, 0.5, 0.5),+ assetId: "a1",+ clips,+ existingRegions: [{ startMs: 3500, endMs: 4500 }],+ defaultDurationMs: 2000,+ });+ expect(suggestions.map((s) => s.span)).toEqual([{ start: 13000, end: 15000 }]);+ });++ it("only reads the clips of the asset the telemetry belongs to", () => {+ const clips = [clip("clip_1", "a1", 0, 10, 0), clip("clip_2", "a2", 0, 10, 10)];+ const suggestions = buildAutoZoomSuggestionsForClips({+ cursorTelemetry: dwell(4000, 0.5, 0.5),+ assetId: "a2",+ clips,+ existingRegions: [],+ defaultDurationMs: 2000,+ });+ expect(suggestions.map((s) => s.span)).toEqual([{ start: 13000, end: 15000 }]);+ });++ it("skips a clip whose duration has not been probed yet", () => {+ const clips = [clip("clip_1", "a1", 0, 0, 0)];+ expect(+ buildAutoZoomSuggestionsForClips({+ cursorTelemetry: dwell(4000, 0.5, 0.5),+ assetId: "a1",+ clips,+ existingRegions: [],+ defaultDurationMs: 2000,+ }),+ ).toEqual([]);+ });+});diff --git a/src/lib/ai-edition/timeline/zoom-suggestions.ts b/src/lib/ai-edition/timeline/zoom-suggestions.tsindex 0ef78d9cc..79769b6b7 100644--- a/src/lib/ai-edition/timeline/zoom-suggestions.ts+++ b/src/lib/ai-edition/timeline/zoom-suggestions.ts@@ -7,6 +7,7 @@// zoom-in candidates, focused on the average cursor position during the dwell.import type { CursorTelemetryPoint, ZoomFocus } from "@/components/video-editor/types";+import type { AxcutClip } from "../schema";export const MIN_DWELL_DURATION_MS = 450;export const MAX_DWELL_DURATION_MS = 2600;@@ -176,3 +177,77 @@ export function buildAutoZoomSuggestions(options: {return suggestions;}++/**+ * The same detector, run over a TIMELINE instead of over a bare media file — and the+ * only entry point a caller holding an `AxcutDocument` should use.+ *+ * Cursor telemetry is recorded against the ORIGINAL media file, so `timeMs` is the+ * asset's SOURCE time (the same axis `cursor-track.ts` maps through+ * `locateSourcePosition`, and the same one trims are stored in). Zoom regions are+ * authored in RAW TIMELINE ms — that is what `anchorRegionsWithDerivedMs` ventilates+ * across the clips. The two axes coincide for exactly one layout: a single clip,+ * starting at 0, covering the whole recording. Any other timeline made the detector's+ * output land wherever `[0, assetDuration]` happens to fall on the ruler, which is the+ * first clip's span — hence "auto-zoom only decorates the first clip". Two clips over+ * ONE recording make it plainer still: the second clip replays source time the first+ * already used, so no amount of arithmetic on a single asset-wide span can say which of+ * them a dwell belongs to. It belongs to BOTH, and gets one zoom on each.+ *+ * So the projection is per clip, and it is a plain shift: a raw clip is identity between+ * its source time and its raw-virtual time (see timeline/timelineMap.ts), so a dwell at+ * source `t` on a clip covering `[sourceStartSec, sourceEndSec]` sits at+ * `timelineStartSec + (t - sourceStartSec)`. Each clip is handed only the samples inside+ * its own source window, so a dwell that a cut split across two clips is no longer one+ * dwell — which is right: the cursor did not sit still across the cut on the timeline the+ * user is watching. `existingRegions` is in RAW TIMELINE ms (what the store holds), so it+ * reserves the right stretch of ruler on every clip instead of only on the first.+ *+ * Clips of other assets are skipped, as are clips with no probed source window.+ * `buildAutoZoomSuggestions` is reused verbatim per clip — spacing, ranking and the+ * reserve rule keep their single definition.+ */+export function buildAutoZoomSuggestionsForClips(options: {+ /** Samples in the asset's own SOURCE time. */+ cursorTelemetry: CursorTelemetryPoint[];+ assetId: string;+ clips: AxcutClip[];+ /** Already-placed zoom spans, in RAW TIMELINE ms. */+ existingRegions: { startMs: number; endMs: number }[];+ defaultDurationMs: number;+}): AutoZoomSuggestion[] {+ const { cursorTelemetry, assetId, clips, existingRegions, defaultDurationMs } = options;+ const suggestions: AutoZoomSuggestion[] = [];+ for (const clip of clips) {+ if (clip.assetId !== assetId) continue;+ const sourceEndSec = clip.sourceEndSec ?? clip.sourceStartSec;+ const windowMs = (sourceEndSec - clip.sourceStartSec) * 1000;+ if (windowMs <= 0) continue;+ const sourceOffsetMs = clip.sourceStartSec * 1000;+ const timelineOffsetMs = clip.timelineStartSec * 1000;+ const clipTelemetry = cursorTelemetry+ .filter(+ (sample) => sample.timeMs >= sourceOffsetMs && sample.timeMs <= sourceOffsetMs + windowMs,+ )+ .map((sample) => ({ ...sample, timeMs: sample.timeMs - sourceOffsetMs }));+ const clipSuggestions = buildAutoZoomSuggestions({+ cursorTelemetry: clipTelemetry,+ totalMs: windowMs,+ existingRegions: existingRegions.map((region) => ({+ startMs: region.startMs - timelineOffsetMs,+ endMs: region.endMs - timelineOffsetMs,+ })),+ defaultDurationMs,+ });+ suggestions.push(+ ...clipSuggestions.map((suggestion) => ({+ focus: suggestion.focus,+ span: {+ start: suggestion.span.start + timelineOffsetMs,+ end: suggestion.span.end + timelineOffsetMs,+ },+ })),+ );+ }+ return suggestions;+}diff --git a/technical-documentation/architecture/timeline-model.md b/technical-documentation/architecture/timeline-model.mdindex 75efdadd1..b8f92d2b9 100644--- a/technical-documentation/architecture/timeline-model.md+++ b/technical-documentation/architecture/timeline-model.md@@ -115,6 +115,59 @@ for an anchored trim it would be a second, stricter test that hides the pill of`resolvePlaybackSegments` still applies — content removed with nothing on the ruler toclick.+### The same ambiguity at playback time++Storing the anchor settles which clip a cut is *on*; the preview still has to answer,+sixty times a second, which clip is *playing*. It reads the `<video>`'s own source clock,+and a source time is per asset, so the question is the same one — one layer up, against a+moving target. `VirtualPreview` tracks the answer in `activeClipIdRef` and passes it into+`locateSourcePosition` / `locateKeptSegment` / `findNextKeptSegment`+([`virtual-preview.ts`](../../src/lib/ai-edition/timeline/virtual-preview.ts)); the rule+those three now share is that **a named clip is believed over anything inferred from+(assetId, sourceTime)**. Three readers had each weakened it in their own way:++- `locateSourcePosition` gave a clip an *exclusive* closing edge unless it was the last+ element of the clips **array**, and the named clip shared that edge. In the last ~50 ms+ of a clip — exactly when the rAF is deciding what to play next — the clip disowned its+ own final frames and the ambiguous scan handed them to a twin over the same recording,+ reporting the playhead near the END of that twin. Playback then saw "clip end reached"+ on a clip nothing follows and stopped, parking the playhead at the end of the timeline.+ Because the exception keyed off array position, whether it happened depended on clip+ ORDER: with a foreign clip laid down last there was no taker, the scan returned null and+ the rAF's timeline-order fallback quietly did the right thing. The closing edge is now+ inclusive for a named clip, and the scan resolves by strict containment first, falling+ back to the closing edge only if nobody claims the time — the same answer for a plain+ single-asset timeline, reached without consulting the order.+- "Am I inside a cut?" scanned every kept segment by asset, so a twin that KEEPS the+ stretch answered for the clip that cuts it and the cut was never skipped during+ playback. `locateKeptSegment` restricts the question to the segments of the clip being+ played: a source time none of them covers is inside *that* clip's trim, however many+ other clips keep it.+- `findNextKeptSegment`'s source-clock fallback (for when the raw ruler lags behind the+ video) compared source positions across a whole asset. "Later in source time" only means+ anything within one clip: with a slice from late in a recording laid down BEFORE a+ trimmed slice from early in it, playing into that cut answered the first clip — raw start+ 0 — so playback jumped to the top of the timeline, replayed into the same cut, and+ looped. It is now scoped to the clip being played, and simply does not apply when no clip+ is named (the RAW-ruler test above is already the general answer).++### Cursor telemetry is source time, and belongs to every clip that replays it++Auto-zoom reads recorded cursor movement, which is captured against the ORIGINAL media+file: `timeMs` is the asset's SOURCE time, the same axis `cursor-track.ts` maps through+`locateSourcePosition`. Zoom regions are authored in RAW TIMELINE ms — that is what+`anchorRegionsWithDerivedMs` ventilates across clips. The two axes coincide for exactly+one layout: a single clip, starting at 0, covering the whole recording. Feeding the+detector's source-time output straight to the store therefore dropped every suggestion+wherever `[0, assetDuration]` happens to fall on the ruler, i.e. on the first clip —+"automatic zooms only decorate the first clip". `buildAutoZoomSuggestionsForClips`+([`zoom-suggestions.ts`](../../src/lib/ai-edition/timeline/zoom-suggestions.ts)) does the+projection: per clip of the asset, a plain shift (a raw clip is identity between source and+raw-virtual time), so a dwell replayed by two clips over one recording yields one zoom on+each. Each clip sees only the samples inside its own source window, so a dwell a cut split+across two clips is no longer one dwell — the cursor did not sit still across the cut on+the timeline the user is watching.+### The same ambiguity in the transcript paneTwo clips over one media do not only share a source coordinate space — they share the@@ -153,6 +206,15 @@ the contract a reviewer can grade against. Each is asserted inassets whose source windows overlap numerically: a zoom fully trimmed away on itsown clip must not re-appear on the later clip. (`projectRegionsToSource` "drops aregion a trim removes entirely rather than leaking it onto a later clip".)+- **A named clip beats anything inferred from (assetId, sourceTime), and clip ORDER is+ never an input.** Asserted in+ [`virtual-preview.test.ts`](../../src/lib/ai-edition/timeline/virtual-preview.test.ts)+ rather than `timelineMap.test.ts`: two clips over one recording, at the closing edge of+ the one being played, must resolve to *that* clip — and must do so identically however+ the clips are laid out, including with a foreign clip between or around them. The same+ rule governs "am I inside a cut?" (`locateKeptSegment`) and "what plays next?"+ (`findNextKeptSegment`), whose source-clock fallback may only speak about the clip it was+ given.- **Same-identity, same-clip stays one pill; different-identity does not merge.** Tworegions of equal properties that touch → one pill; touch with one propertychanged → two pills, with no memory of ever having been one. (`coalesceByIdentity`