Skip to content

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

41.2 KB
Raw Blame
// 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 technical-documentation/architecture/timeline-model.md.

import { describe, expect, it } from "vitest";
import { resolvePlaybackSegments } from "../document/timeline";
import type { AxcutClip, AxcutTrimRange } from "../schema";
import {
	anchorRawRegionsToClips,
	anchorRegionsWithDerivedMs,
	clampSpanAgainstNeighbours,
	coalesceByIdentity,
	coalesceRegionsForRuler,
	dropPillById,
	projectRegionsToSource,
	regionIdentityKey,
	replacePillSpan,
	resolveNativePosition,
	resolvePillIds,
	resolveRegionIds,
	wholePillOf,
} from "./timelineMap";

function clip(overrides: Partial<AxcutClip> & Pick<AxcutClip, "id" | "assetId">): AxcutClip {
	// `id`/`assetId` come from the spread below — `Pick` makes them required there,
	// so restating them above would just be overwritten.
	return {
		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("projectRegionsToSource", () => {
	it("passes a region through unchanged (no clipIndex) when there are no segments", () => {
		const out = projectRegionsToSource([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 = projectRegionsToSource([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 = projectRegionsToSource([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 = projectRegionsToSource([region("r", 3, 7, "keep")], [c1, c2], [c1, c2], () => "r2");
		expect(out).toEqual([
			{
				id: "r",
				startMs: 103000,
				endMs: 105000,
				clipIndex: 0,
				payload: "keep",
				continuesAfter: true,
			},
			{
				id: "r2",
				startMs: 200000,
				endMs: 202000,
				clipIndex: 1,
				payload: "keep",
				continuesBefore: true,
			},
		]);
	});

	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 = projectRegionsToSource([region("r", 3, 8)], segments, [c], () => "r2");
		expect(out).toEqual([
			{ id: "r", startMs: 3000, endMs: 4000, clipIndex: 0, continuesAfter: true },
			{ id: "r2", startMs: 6000, endMs: 8000, clipIndex: 1, continuesBefore: true },
		]);
	});

	it("keeps a fully-trimmed region on its own clip instead of leaking it onto a later one", () => {
		// The reported bug: an effect fully UNDER a trim fired later instead of being ignored.
		// Two clips of DIFFERENT assets whose source windows overlap numerically (c1: asset a
		// [0,10] @ raw[0,10]; c2: asset b [0,10] @ raw[10,20]). A zoom anchored to c1 at source
		// [3,5] is then fully trimmed away on c1 (trim removes a[2,8]; c2's asset b is
		// untouched). It is kept so the playhead can be parked on the cut (issue #216), but it
		// must stay ADDRESSED TO c1 — the clipIndex-less passthrough that used to re-emit it
		// with raw coords let native's `belongs()` match it on c2, whose source window [0,10]
		// numerically contains [3,5].
		const c1 = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineStartSec: 0,
			timelineEndSec: 10,
		});
		const c2 = clip({
			id: "c2",
			assetId: "b",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineStartSec: 10,
			timelineEndSec: 20,
		});
		const segments = resolvePlaybackSegments([c1, c2], [trim("a", 2, 8)]);
		// segments: c1[0,2] (0), c1[8,10] (1), c2[0,10] (2).
		const anchored = { ...region("r", 3, 5), clipId: "c1", sourceStartSec: 3, sourceEndSec: 5 };
		expect(projectRegionsToSource([anchored], segments, [c1, c2], () => "x")).toEqual([
			{ ...anchored, startMs: 3000, endMs: 5000, clipIndex: 0, underTrim: true },
		]);
	});

	it("drops a fully-trimmed region whose clip has no kept segment left to address it", () => {
		// Nothing of c1 survives, so there is no index that names it. Emitting one anyway is
		// exactly the leak above: it would land on c2.
		const c1 = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineStartSec: 0,
			timelineEndSec: 10,
		});
		const c2 = clip({
			id: "c2",
			assetId: "b",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineStartSec: 10,
			timelineEndSec: 20,
		});
		const segments = resolvePlaybackSegments([c1, c2], [trim("a", 0, 10)]);
		const anchored = { ...region("r", 3, 5), clipId: "c1", sourceStartSec: 3, sourceEndSec: 5 };
		expect(projectRegionsToSource([anchored], segments, [c1, c2], () => "x")).toEqual([]);
	});

	it("keeps an unanchored region a trim removes entirely, mapped through its raw clip", () => {
		// The same class for an un-migrated (v1.7-imported) region that has only its RAW span:
		// raw[4.5,5.5] sits inside the removed stretch a[4,6]. It maps to no kept segment, so it
		// is emitted once against the segment the cut interrupts (c1[0,4], index 0) on the source
		// span its raw coordinates name — never passed through with raw coords and no clipIndex.
		const c = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineEndSec: 10,
		});
		const segments = resolvePlaybackSegments([c], [trim("a", 4, 6)]);
		expect(projectRegionsToSource([region("r", 4.5, 5.5)], segments, [c], () => "x")).toEqual([
			{ id: "r", startMs: 4500, endMs: 5500, clipIndex: 0, underTrim: true },
		]);
	});

	it("addresses a head trim to the clip's FIRST kept segment", () => {
		// The cut opens the clip, so there is no segment before it; the first one is the only
		// thing that can name it.
		const c = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineEndSec: 10,
		});
		const segments = resolvePlaybackSegments([c], [trim("a", 0, 3)]);
		const anchored = { ...region("r", 1, 2), clipId: "c1", sourceStartSec: 1, sourceEndSec: 2 };
		expect(projectRegionsToSource([anchored], segments, [c], () => "x")).toEqual([
			{ ...anchored, startMs: 1000, endMs: 2000, clipIndex: 0, underTrim: true },
		]);
	});

	it("addresses a fully-trimmed region and the playhead over it to the SAME segment", () => {
		// The agreement `for_clip_window` (scene.rs) depends on: it only keeps a region whose
		// clipIndex equals the clip being composed. Two clips of the same asset so the choice is
		// not trivially unique — c1 raw[0,10], c2 raw[10,20], the trim on c1's tail.
		const c1 = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineEndSec: 10,
		});
		const c2 = clip({
			id: "c2",
			assetId: "a",
			sourceStartSec: 20,
			sourceEndSec: 30,
			timelineStartSec: 10,
			timelineEndSec: 20,
		});
		const segments = resolvePlaybackSegments([c1, c2], [trim("a", 6, 10)]);
		const anchored = { ...region("r", 7, 9), clipId: "c1", sourceStartSec: 7, sourceEndSec: 9 };
		const [projected] = projectRegionsToSource([anchored], segments, [c1, c2], () => "x");
		// raw 8 is inside c1's removed tail; the region covering source [7,9] is that same cut.
		expect(resolveNativePosition(8, segments, [c1, c2])?.clipIndex).toBe(projected.clipIndex);
	});

	// --- anchored path: the anchor is the SSOT, `startMs`/`endMs` are not consulted ---

	it("places an anchored region from its anchor, ignoring a stale startMs/endMs", () => {
		// THE property phase 1 buys: the derived ms cache is deliberately WRONG here
		// (raw[0,1] — nowhere near the truth). A region that reads the anchor lands on
		// source [6,8]; one that still trusted the cache would land on [0,1].
		const c = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineEndSec: 10,
		});
		const stale = {
			...region("r", 0, 1),
			clipId: "c1",
			sourceStartSec: 6,
			sourceEndSec: 8,
		};
		const out = projectRegionsToSource([stale], [c], [c], () => "x");
		expect(out).toEqual([{ ...stale, startMs: 6000, endMs: 8000, clipIndex: 0 }]);
	});

	it("splits an anchored region across the kept segments of its own clip", () => {
		// Same trim geometry as the unanchored split above, driven purely by the anchor.
		const c = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineEndSec: 10,
		});
		const segments = resolvePlaybackSegments([c], [trim("a", 4, 6)]);
		const anchored = {
			...region("r", 3, 8),
			clipId: "c1",
			sourceStartSec: 3,
			sourceEndSec: 8,
		};
		const out = projectRegionsToSource([anchored], segments, [c], () => "r2");
		expect(out).toEqual([
			{ ...anchored, id: "r", startMs: 3000, endMs: 4000, clipIndex: 0, continuesAfter: true },
			{ ...anchored, id: "r2", startMs: 6000, endMs: 8000, clipIndex: 1, continuesBefore: true },
		]);
	});

	it("never places an anchored region on a different clip that shares the asset", () => {
		// Two clips, same asset, overlapping source windows. The anchor names c2, so the
		// region must appear ONCE, on c2 — the camera/record mix-up this model prevents.
		const c1 = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 5,
			timelineStartSec: 0,
			timelineEndSec: 5,
		});
		const c2 = clip({
			id: "c2",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 5,
			timelineStartSec: 5,
			timelineEndSec: 10,
		});
		const anchored = {
			...region("r", 1, 2),
			clipId: "c2",
			sourceStartSec: 1,
			sourceEndSec: 2,
		};
		const out = projectRegionsToSource([anchored], [c1, c2], [c1, c2], () => "x");
		expect(out).toEqual([{ ...anchored, startMs: 1000, endMs: 2000, clipIndex: 1 }]);
	});

	it("falls back to the raw mapping when the anchor is incomplete", () => {
		// Migration keeps un-anchorable regions (never drops them), so a partial anchor
		// must still resolve via the legacy raw path rather than vanishing.
		const c = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineEndSec: 10,
		});
		const partial = { ...region("r", 3, 5), clipId: "c1" }; // no source span
		const out = projectRegionsToSource([partial], [c], [c], () => "x");
		expect(out).toEqual([{ ...partial, startMs: 3000, endMs: 5000, clipIndex: 0 }]);
	});

	// A piece at a cut is gated in f32 by the compositor (`continues_before` → `t < start`,
	// `continues_after` → `t > end`), and a clip's first and last frames land on the clip's own
	// bounds. A bound rounded to the ms past them left that frame out of the Full Camera piece:
	// camera back in its PiP corner, motion blur trailing it there (issue #1300, cuts of the
	// v2.1.0-rc.5 passes). The cuts that rounded the other way were clean: the controls.
	const pieceAcross = (trimStartSec: number, trimEndSec: number) => {
		const c = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 60,
			timelineEndSec: 60,
		});
		const anchored = { ...region("r", 0, 60), clipId: "c1", sourceStartSec: 0, sourceEndSec: 60 };
		const segments = resolvePlaybackSegments([c], [trim("a", trimStartSec, trimEndSec)]);
		return projectRegionsToSource([anchored], segments, [c], () => "r2");
	};

	it.each([
		10.292957, 18.361809, 46.34986635, 6.284394,
	])("keeps the first frame after a cut at %s in the Full Camera piece", (cut) => {
		const [, after] = pieceAcross(cut - 2, cut);
		expect(after.continuesBefore).toBe(true);
		expect(Math.fround(after.startMs / 1000)).toBe(Math.fround(cut));
	});

	it.each([
		6.284394, 14.340314, 10.292957,
	])("keeps the last frame before a cut at %s in the Full Camera piece", (cut) => {
		const [before] = pieceAcross(cut, cut + 2);
		expect(before.continuesAfter).toBe(true);
		expect(Math.fround(before.endMs / 1000)).toBe(Math.fround(cut));
	});
});

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("presents the removed frames themselves when the playhead sits over a trim", () => {
		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. The trim keeps its place on the ruler, so
		// raw 3 IS source 3, and the decoder still holds it — only the kept window was narrowed.
		// It used to answer seg2's first frame (source 4), which is not the frame the ruler
		// points at, and would incrust any modifier under the cut on someone else's image (#216).
		// The segment it borrows is the one the cut interrupts (seg1), so a modifier under that
		// cut — addressed the same way — survives `belongs()`.
		expect(resolveNativePosition(3, segments, [c])).toMatchObject({
			clipIndex: 0,
			sourceTimeSec: 3,
		});
	});

	it("presents a head trim's own frames rather than the clip's first kept one", () => {
		const c = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineEndSec: 10,
		});
		const segments = resolvePlaybackSegments([c], [trim("a", 0, 3)]);
		expect(resolveNativePosition(1, segments, [c])).toMatchObject({
			clipIndex: 0,
			sourceTimeSec: 1,
		});
	});

	it("clamps to the last kept segment past the end of the ruler", () => {
		const c = clip({
			id: "c1",
			assetId: "a",
			sourceStartSec: 0,
			sourceEndSec: 10,
			timelineEndSec: 10,
		});
		const segments = resolvePlaybackSegments([c], [trim("a", 2, 4)]);
		// No raw clip owns raw 99 — nothing to present, so the historical clamp stands.
		expect(resolveNativePosition(99, segments, [c])).toMatchObject({ clipIndex: 1 });
	});

	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 = (start: number, end: number) => ({ start, end });

	it("stops at a neighbour on the right", () => {
		// The right edge dragged from 4 to 8.
		const out = clampSpanAgainstNeighbours({ start: 0, end: 8 }, [other(5, 12)], {
			start: 0,
			end: 4,
		});
		expect(out).toEqual({ start: 0, end: 5 });
	});

	it("stops at a neighbour on the left", () => {
		// The left edge dragged from 6 to 3.
		const out = clampSpanAgainstNeighbours({ start: 3, end: 10 }, [other(0, 5)], {
			start: 6,
			end: 10,
		});
		expect(out).toEqual({ start: 5, end: 10 });
	});

	it("is squeezed by blockers on both sides", () => {
		// Stretched both ways, from 4–6: each edge stops at its own blocker.
		const out = clampSpanAgainstNeighbours({ start: 1, end: 10 }, [other(0, 3), other(7, 12)], {
			start: 4,
			end: 6,
		});
		expect(out).toEqual({ start: 3, end: 7 });
	});

	it("leaves a span that overlaps nothing untouched", () => {
		expect(
			clampSpanAgainstNeighbours({ start: 2, end: 4 }, [other(8, 9)], {
				start: 0,
				end: 2,
			}),
		).toEqual({ start: 2, end: 4 });
	});

	it("keeps a moved span whole, flush against the neighbour it ran into", () => {
		const n = [other(6, 12)];
		// From the left: it stops with its end on the neighbour's start…
		expect(clampSpanAgainstNeighbours({ start: 5, end: 9 }, n, { start: 0, end: 4 })).toEqual({
			start: 2,
			end: 6,
		});
		// …and from the right, with its start on the neighbour's end.
		expect(clampSpanAgainstNeighbours({ start: 9, end: 13 }, n, { start: 20, end: 24 })).toEqual({
			start: 12,
			end: 16,
		});
	});

	it("never throws a moved span to the far side of a neighbour it overlaps", () => {
		// Dropped with its start past the neighbour's start, which decided the side before.
		expect(
			clampSpanAgainstNeighbours({ start: 7, end: 11 }, [other(6, 10)], {
				start: 0,
				end: 4,
			}),
		).toEqual({ start: 2, end: 6 });
	});

	it("keeps a drop that overlaps nothing, even past a neighbour", () => {
		expect(
			clampSpanAgainstNeighbours({ start: 12, end: 16 }, [other(6, 10)], {
				start: 0,
				end: 4,
			}),
		).toEqual({ start: 12, end: 16 });
	});

	it("stops a left edge dragged past a whole neighbour at that neighbour", () => {
		expect(
			clampSpanAgainstNeighbours({ start: 30, end: 77 }, [other(40, 50)], {
				start: 64,
				end: 77,
			}),
		).toEqual({ start: 50, end: 77 });
	});

	it("leaves a move with no room where it was", () => {
		// Neighbours at 0–3 and 7–12, and the span already flush against the second one.
		expect(
			clampSpanAgainstNeighbours({ start: 2, end: 7 }, [other(0, 3), other(7, 12)], {
				start: 12,
				end: 17,
			}),
		).toEqual({ start: 12, end: 17 });
	});

	it("ignores a neighbour the span already overlapped before the edit", () => {
		// An add does not clamp, so two regions can overlap; no position on the way clears that.
		expect(
			clampSpanAgainstNeighbours({ start: 0, end: 5 }, [other(4, 9)], {
				start: 1,
				end: 6,
			}),
		).toEqual({ start: 0, end: 5 });
	});
});

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("wholePillOf gives the pill a fragment belongs to, over its whole span", () => {
		// One zoom cut by the clip boundary at 25.557 s: two fragments, one pill.
		const regions = [
			{ id: "a", startMs: 20000, endMs: 25557, depth: 3 },
			{ id: "b", startMs: 25557, endMs: 30000, depth: 3 },
			{ id: "c", startMs: 30000, endMs: 31000, depth: 5 },
		];
		expect(wholePillOf(regions, "b")).toEqual({ id: "a", startMs: 20000, endMs: 30000, depth: 3 });
		expect(wholePillOf(regions, "c")).toEqual(regions[2]);
		expect(wholePillOf(regions, "gone")).toBeNull();
	});

	it("keeps identical overlapping annotations separate for selection, edits and deletion", () => {
		const regions = [
			{ id: "background", startMs: 0, endMs: 67000, type: "text", content: "Hi", zIndex: 1 },
			{ id: "second", startMs: 35000, endMs: 40000, type: "text", content: "Hi", zIndex: 1 },
		];
		expect(
			coalesceRegionsForRuler(regions, 0.001, { annotations: true }).map((p) => p.ids),
		).toEqual([["background"], ["second"]]);
		expect(resolveRegionIds(regions, "second", 0.001, { annotations: true })).toEqual(["second"]);
		expect(dropPillById(regions, "second", { annotations: true })).toEqual([regions[0]]);
		const moved = replacePillSpan(
			regions,
			"second",
			5000,
			10000,
			[],
			ids(),
			0.001,
			{},
			{ annotations: true },
		);
		expect(moved).toContainEqual(regions[0]);
		expect(moved.find((r) => r.id === "second")).toMatchObject({ startMs: 5000, endMs: 10000 });
	});

	it("lets annotations overlap across layers and preserves a layer change across clip fragments", () => {
		const regions = [
			{ id: "low", startMs: 0, endMs: 10000, type: "text", content: "Low", zIndex: 1 },
			{ id: "high", startMs: 30000, endMs: 40000, type: "text", content: "High", zIndex: 2 },
		];
		const moved = replacePillSpan(
			regions,
			"high",
			5000,
			30000,
			clips,
			ids(),
			0.001,
			{ zIndex: 0 },
			{ annotations: true },
		);
		expect(moved[0]).toEqual(regions[0]);
		const fragments = moved.slice(1);
		expect(fragments.length).toBeGreaterThan(1);
		expect(fragments.every((r) => r.zIndex === 0)).toBe(true);
		const pill = coalesceRegionsForRuler(fragments, 0.001, { annotations: true })[0];
		expect(pill).toMatchObject({ start: 5, end: 30 });
		expect(resolveRegionIds(moved, "high", 0.001, { annotations: true })).toHaveLength(
			fragments.length,
		);
	});

	it("does not exchange ambiguous identical annotation fragments at a shared clip boundary", () => {
		const payload = { type: "text", content: "Same", zIndex: 1 };
		const regions = [
			{ ...payload, id: "back-a", startMs: 0, endMs: 25000, clipId: "a" },
			{ ...payload, id: "back-b", startMs: 25000, endMs: 50000, clipId: "b" },
			{ ...payload, id: "front-a", startMs: 20000, endMs: 25000, clipId: "a" },
			{ ...payload, id: "front-b", startMs: 25000, endMs: 30000, clipId: "b" },
		];
		expect(coalesceRegionsForRuler(regions, 0.001, { annotations: true })).toHaveLength(4);
		expect(resolveRegionIds(regions, "front-a", 0.001, { annotations: true })).toEqual(["front-a"]);
		expect(dropPillById(regions, "front-a", { annotations: true })).toEqual(
			regions.filter((r) => r.id !== "front-a"),
		);
	});

	it("keeps ordinary region merge and repulsion rules when they carry a zIndex", () => {
		const regions = [
			{ id: "a", startMs: 0, endMs: 1000, zIndex: 1, speed: 2 },
			{ id: "b", startMs: 500, endMs: 1500, zIndex: 1, speed: 2 },
		];
		expect(coalesceRegionsForRuler(regions)).toHaveLength(1);
		const separate = [
			{ ...regions[0], endMs: 1000 },
			{ ...regions[1], startMs: 2000, endMs: 3000 },
		];
		expect(
			replacePillSpan(separate, "a", 1500, 2500, [], ids()).find((r) => r.id === "a"),
		).toMatchObject({ startMs: 1000, endMs: 2000 });
	});

	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("resolveRegionIds narrows a pill to one region, with every fragment of it (#1017)", () => {
		// `mine` is drawn across the A|B junction, so it is stored as two fragments; `other`
		// merely matches it and touches it on clip A. One pill, two regions.
		const regions = [
			...anchorRegionsWithDerivedMs(
				[{ id: "other", startMs: 10000, endMs: 20000, speed: 3 }],
				clips,
				ids(),
			),
			...anchorRegionsWithDerivedMs(
				[{ id: "mine", startMs: 20000, endMs: 30000, speed: 3 }],
				clips,
				ids(),
			),
		];
		const mineOnB = regions.find((r) => (r as { clipId?: string }).clipId === "clip_b")?.id;
		expect(resolvePillIds(regions, "other")).toHaveLength(3);
		expect(resolveRegionIds(regions, "other")).toEqual(["other"]);
		expect(resolveRegionIds(regions, mineOnB as string)).toEqual(["mine", mineOnB]);
	});

	it("resolveRegionIds keeps overlapping regions together: one changed alone would overlap", () => {
		const regions = anchorRegionsWithDerivedMs(
			[
				{ id: "a", startMs: 2000, endMs: 6000, speed: 3 },
				{ id: "b", startMs: 5000, endMs: 9000, speed: 3 },
				{ id: "c", startMs: 9000, endMs: 12000, speed: 3 },
			],
			clips,
			ids(),
		);
		expect(resolveRegionIds(regions, "a")).toEqual(["a", "b"]);
		expect(resolveRegionIds(regions, "c")).toEqual(["c"]);
	});

	it("resolveRegionIds keeps a 1 ms overlap together too: only an exact touch splits", () => {
		const regions = anchorRegionsWithDerivedMs(
			[
				{ id: "a", startMs: 2000, endMs: 6001, speed: 3 },
				{ id: "b", startMs: 6000, endMs: 9000, speed: 3 },
			],
			clips,
			ids(),
		);
		expect(resolveRegionIds(regions, "a")).toEqual(["a", "b"]);
	});

	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("a moved pill keeps the id it was grabbed by, so a selection on any member survives", () => {
		const regions = anchorRegionsWithDerivedMs(
			[
				{ id: "a", startMs: 2000, endMs: 5000, speed: 3 },
				{ id: "b", startMs: 5000, endMs: 9000, speed: 3 },
			],
			clips,
			ids(),
		);
		const out = replacePillSpan(regions, "b", 3000, 10000, clips, ids());
		expect(out.map((r) => [r.id, r.startMs, r.endMs])).toEqual([["b", 3000, 10000]]);
	});

	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);
	});

	it.each([
		["speed", { speed: 1.5 }],
		["zoom", { depth: 2 }],
		["annotation", { type: "text", content: "Hi" }],
		["full-camera", {}],
	])("stops a %s region flush against an identical one instead of overlapping it (#1133)", (_kind, payload) => {
		// The report's layout, shifted into clip A: 13.711–16.202 and 16.307–18.798, the second
		// dragged 1.375 s left. It used to land on 14.932–17.423, stored over the first.
		const regions = anchorRegionsWithDerivedMs(
			[
				{ id: "a", startMs: 13_711, endMs: 16_202, ...payload },
				{ id: "b", startMs: 16_307, endMs: 18_798, ...payload },
			],
			clips,
			ids(),
		);
		const out = replacePillSpan(regions, "b", 14_932, 17_423, clips, ids());
		expect(out.map((r) => [r.id, r.startMs, r.endMs])).toEqual([
			["a", 13_711, 16_202],
			["b", 16_202, 18_693],
		]);
		// Flush, they show as one pill, and an edit of either half reaches only that half.
		expect(coalesceRegionsForRuler(out)).toHaveLength(1);
		expect(resolveRegionIds(out, "b")).toEqual(["b"]);
	});
});

describe("a dragged pill stays whole against its neighbour (#1008)", () => {
	const ids = () => {
		let n = 0;
		return () => `gen_${n++}`;
	};
	const spans = (regions: Array<{ startMs: number; endMs: number }>) =>
		regions.map((r) => [r.startMs, r.endMs, (r as { clipId?: string }).clipId]);

	// The report's layout. Clip 1 ends on no whole millisecond, like any real clip, and zoom B
	// (1.5×) ends on that boundary.
	const clip1 = clip({
		id: "clip_1",
		assetId: "rec",
		sourceStartSec: 29.4196,
		sourceEndSec: 135.32,
		timelineStartSec: 0,
		timelineEndSec: 105.9004,
	});
	const clip2 = clip({
		id: "clip_2",
		assetId: "rec_2",
		sourceStartSec: 0,
		sourceEndSec: 60,
		timelineStartSec: 105.9004,
		timelineEndSec: 165.9004,
	});
	const clips = [clip1, clip2];

	it("stops a zoom against a neighbour that ends on a clip boundary, keeping its length", () => {
		const regions = anchorRegionsWithDerivedMs(
			[
				{ id: "a", startMs: 64_030, endMs: 77_000, depth: 3 },
				{ id: "b", startMs: 100_100, endMs: 105_900, depth: 2 },
			],
			clips,
			ids(),
		);
		// A (12.97 s) dropped with its start past B's start: it covers B and runs into clip 2.
		const out = replacePillSpan(regions, "a", 101_160, 114_130, clips, ids());
		expect(spans(out.filter((r) => r.depth === 3))).toEqual([[87_130, 100_100, "clip_1"]]);
		expect(spans(out.filter((r) => r.depth === 2))).toEqual([[100_100, 105_900, "clip_1"]]);
	});

	it("keeps a speed region whole when it is dragged into a neighbour in the same clip", () => {
		// #1017: a 13.6 s 2× region dragged into a 1.5× one came out 1.6 s long.
		const regions = anchorRegionsWithDerivedMs(
			[
				{ id: "fast", startMs: 10_000, endMs: 23_600, speed: 2 },
				{ id: "slow", startMs: 40_000, endMs: 50_000, speed: 1.5 },
			],
			clips,
			ids(),
		);
		const out = replacePillSpan(regions, "fast", 38_400, 52_000, clips, ids());
		expect(spans(out.filter((r) => r.speed === 2))).toEqual([[26_400, 40_000, "clip_1"]]);
		expect(spans(out.filter((r) => r.speed === 1.5))).toEqual([[40_000, 50_000, "clip_1"]]);
	});

	it("keeps a zoom whole when it is dragged left into a neighbour in the same clip", () => {
		// #1017: a 27.1 s zoom came out 19.3 s long.
		const regions = anchorRegionsWithDerivedMs(
			[
				{ id: "z", startMs: 60_000, endMs: 87_100, depth: 4 },
				{ id: "n", startMs: 20_000, endMs: 40_000, depth: 2 },
			],
			clips,
			ids(),
		);
		const out = replacePillSpan(regions, "z", 32_200, 59_300, clips, ids());
		expect(spans(out.filter((r) => r.depth === 4))).toEqual([[40_000, 67_100, "clip_1"]]);
		expect(spans(out.filter((r) => r.depth === 2))).toEqual([[20_000, 40_000, "clip_1"]]);
	});

	it("stores no zero-length fragment for an edge rounded onto a clip boundary", () => {
		// Snapped onto the 105.9004 s junction, a start is stored as 105.900 s: 0.4 ms short of
		// clip 2. That 0.4 ms used to become a fragment of its own on clip 1, zero-length once
		// rounded back to ms, and it took the region's id away from the fragment that plays.
		const out = anchorRegionsWithDerivedMs(
			[{ id: "z", startMs: 105_900, endMs: 114_130, depth: 3 }],
			clips,
			ids(),
		);
		expect(out.map((r) => r.id)).toEqual(["z"]);
		expect(spans(out)).toEqual([[105_900, 114_130, "clip_2"]]);
	});

	it("keeps a half-millisecond piece that rounds to a whole millisecond", () => {
		// A boundary at 1.0005 s leaves 0.5 ms of a 1000–1002 ms region on the first clip. Stored,
		// that piece is 1000–1001 ms: dropping it would bring the region back a millisecond short.
		const halfMsClips = [
			clip({
				id: "clip_1",
				assetId: "rec",
				sourceStartSec: 0,
				sourceEndSec: 1.0005,
				timelineStartSec: 0,
				timelineEndSec: 1.0005,
			}),
			clip({
				id: "clip_2",
				assetId: "rec_2",
				sourceStartSec: 0,
				sourceEndSec: 30,
				timelineStartSec: 1.0005,
				timelineEndSec: 31.0005,
			}),
		];
		const out = anchorRegionsWithDerivedMs(
			[{ id: "z", startMs: 1_000, endMs: 1_002, depth: 3 }],
			halfMsClips,
			ids(),
		);
		expect(out[0].id).toBe("z");
		expect(Math.min(...out.map((r) => r.startMs))).toBe(1_000);
		expect(Math.max(...out.map((r) => r.endMs))).toBe(1_002);
	});
});

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");
	});
});