Skip to content

Open source CapCut alternative.

TypeScript
113 KB
Raw Blame
import { beforeEach, describe, expect, test } from "bun:test";
import { groupRemap } from "@donkeycut/effects-kit";
import { adoptTransitionFields, assetIdsInUse, clipLen, closeMicroGaps, cutTranscribeSpec, deriveTransitionFields, docOverlays, getClipSpans, liftClipLooks, moveOverlayGroup, overlayLaneOrder, normalizeElementLanes, parkedTransitions, placeInRun, projectDuration, rippleInsert, separateOverlaps, serializeDoc, useEditor, DOC_KEYS, docFieldsEdited } from "./store";
import type React from "react";
import { runAiTool } from "./aiTools";
import { withGroupCamera } from "./groupCamera";
import { selectedMembers, startLaneMove } from "./laneTracks";
import { expandTimelineGroups } from "./timelineGroups";
import { timelineItem } from "./timelineItems";
import { normalizeDocState } from "./store";
import { playheadAt, setPlayhead, setSkim } from "./playhead";
import { emptySubtitles, sanitizeTimelines, uploadedFontId } from "./types";
import type { Selection, AudioClip, MediaAsset, SubtitleCue, TextOverlay, VideoClip } from "./types";

/**
 * The lane invariant: segments never overlap, with no exceptions. Every
 * placement and committed update — user drops, AI-chat tools, inspector
 * edits — must land items on a free stretch of their lane (video per track,
 * audio/title/cue per lane). A transition is a render-time blend at the cut,
 * never a physical overlap.
 */

let n = 0;
const asset = (duration = 4, type: MediaAsset["type"] = "video"): MediaAsset => ({
  id: `a${++n}`,
  fileName: `f${n}.mp4`,
  name: `A${n}`,
  type,
  duration,
  url: "",
});
const vclip = (o: Partial<VideoClip>): VideoClip => ({
  id: `c${++n}`,
  assetId: "x",
  track: 0,
  start: 0,
  in: 0,
  out: 2,
  muted: false,
  ...o,
});
const aclip = (o: Partial<AudioClip>): AudioClip => ({
  id: `au${++n}`,
  assetId: "x",
  start: 0,
  in: 0,
  out: 2,
  volume: 1,
  ...o,
});
const title = (o: Partial<TextOverlay>): TextOverlay => ({
  id: `t${++n}`,
  text: "T",
  start: 0,
  end: 2,
  x: 0.5,
  y: 0.5,
  size: 88,
  font: "sf",
  weight: 700,
  color: "#fff",
  shadow: true,
  plate: false,
  ...o,
});
const cue = (o: Partial<SubtitleCue>): SubtitleCue => ({
  id: `q${++n}`,
  start: 0,
  end: 1,
  text: "hi",
  ...o,
});

const s = () => useEditor.getState();
const clipById = (id: string) => s().clips.find((c) => c.id === id)!;
const audioById = (id: string) => s().audioClips.find((c) => c.id === id)!;

/** Assert no two footprints on one lane intrude into each other beyond the
 * per-pair allowance (a declared dissolve). */
function expectLaneSound(
  spans: { start: number; end: number }[],
  allow: (prev: number, next: number) => number = () => 0
) {
  const sorted = [...spans].sort((a, b) => a.start - b.start);
  for (let i = 1; i < sorted.length; i++) {
    expect(sorted[i].start).toBeGreaterThanOrEqual(
      sorted[i - 1].end - allow(i - 1, i) - 1e-6
    );
  }
}
const videoLane = (track: number) =>
  s()
    .clips.filter((c) => c.track === track)
    .map((c) => ({ start: c.start, end: c.start + clipLen(c) }));

beforeEach(() => {
  setSkim(null);
  useEditor.setState({
    clips: [],
    transitions: [],
    audioClips: [],
    overlays: [],
    assets: [],
    subtitles: emptySubtitles(),
    selection: null,
    multiSelection: [],
  });
});

describe("brush stroke history", () => {
  // The removal brush writes each finished stroke as pushHistory + a
  // transient seeds update; one undo steps back exactly one stroke.
  test("each stroke is one undo step", () => {
    const clip = vclip({ removal: { mode: "custom" } });
    useEditor.setState({ clips: [clip] });
    const stroke = (t: number) => {
      const st = useEditor.getState();
      const cur = st.clips[0].removal!;
      st.pushHistory();
      st.updateClipTransient(clip.id, {
        removal: {
          ...cur,
          seeds: {
            prompts: [
              ...(cur.seeds?.prompts ?? []),
              { t, points: [{ x: 0.5, y: 0.5, label: 1 as const }] },
            ],
          },
        },
      });
    };
    useEditor.setState({ selection: { kind: "clip", id: clip.id } });
    stroke(0);
    stroke(1);
    expect(useEditor.getState().clips[0].removal?.seeds?.prompts.length).toBe(2);
    useEditor.getState().undo();
    expect(useEditor.getState().clips[0].removal?.seeds?.prompts.length).toBe(1);
    // The clip survived the restore, so the brush session's selection holds
    // and the stage keeps its overlay.
    expect(useEditor.getState().selection).toEqual({ kind: "clip", id: clip.id });
    useEditor.getState().undo();
    expect(useEditor.getState().clips[0].removal?.seeds?.prompts ?? []).toHaveLength(0);
  });

  test("undoing an add drops the selection with the clip", () => {
    useEditor.setState({ clips: [], selection: null, multiSelection: [] });
    useEditor.getState().pushHistory();
    const clip = vclip({});
    useEditor.setState({ clips: [clip], selection: { kind: "clip", id: clip.id } });
    useEditor.getState().undo();
    expect(useEditor.getState().clips).toHaveLength(0);
    expect(useEditor.getState().selection).toBeNull();
  });
});

describe("the document projection", () => {
  // Autosave tells an edit from a re-read by comparing this projection's
  // identity. A projection that rebuilt itself on every read would mark the
  // document dirty forever — and, since saving sets state, feed itself.
  test("re-reading an unchanged document hands back the same arrays", () => {
    useEditor.setState({
      overlays: [title({ kind: "text" }), title({ kind: "text", start: 3, end: 5 })],
    });
    const a = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    const b = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    expect(b.overlays).toBe(a.overlays!);
    expect(b.clips).toBe(a.clips!);
    expect(docOverlays(s().overlays)).toBe(a.overlays!);
  });

  test("the frame color survives the round trip, and a bad one falls back", () => {
    s().setBackground("#ff5500");
    expect(s().background).toBe("#FF5500");
    expect(serializeDoc(s() as Parameters<typeof serializeDoc>[0]).background).toBe("#FF5500");
    s().setBackground("burnt orange");
    expect(s().background).toBe("#000000");
  });

  test("an edit gives a new projection, and the stamp still comes off", () => {
    useEditor.setState({ overlays: [title({ kind: "text" })] });
    const before = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    s().updateOverlay(s().overlays[0].id, { x: 0.2 });
    const after = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    expect(after.overlays).not.toBe(before.overlays!);
    // Text elements still serialize without the loader's stamp.
    expect("kind" in after.overlays![0]).toBe(false);
  });

  test("a project color change alone is an edit the autosave sees", () => {
    const last = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    expect(docFieldsEdited(s(), last, s().transitions)).toBe(false);
    s().setColorSpace(s().colorSpace === "hlg" ? "pq" : "hlg");
    expect(docFieldsEdited(s(), last, s().transitions)).toBe(true);
  });

  test("every serialized document field is a doc key the autosave compares", () => {
    const doc = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    const keys = Object.keys(doc)
      .filter((k) => k !== "firstOpen")
      .map((k) => (k === "name" ? "projectName" : k));
    for (const k of keys) expect(DOC_KEYS as readonly string[]).toContain(k);
  });

  test("a document with nothing to strip is passed straight through", () => {
    const overlays = [
      { id: "s1", kind: "shape", shape: "rect", start: 0, end: 2, x: 0.5, y: 0.5, w: 0.2, h: 0.2, fill: "#fff" },
    ] as unknown as Parameters<typeof docOverlays>[0];
    expect(docOverlays(overlays)).toBe(overlays);
  });
});

describe("timelines", () => {
  // A fresh open: empty timelines and no undo history on any of them.
  beforeEach(() => s().openProjectDoc("timelines", { name: "Timelines" }, []));

  test("switching parks the open timeline and opens the other, both ways", () => {
    const a = asset(4);
    const main = vclip({ assetId: a.id, out: 3 });
    useEditor.setState({ assets: [a], clips: [main], overlays: [title({ kind: "text" })] });
    s().switchTimeline("second");
    expect(s().timeline).toBe("second");
    expect(s().clips).toEqual([]);
    expect(s().overlays).toEqual([]);
    expect(s().timelines.main?.clips.map((c) => c.id)).toEqual([main.id]);
    s().addClipFromAsset(a.id, 0);
    s().switchTimeline("main");
    expect(s().clips.map((c) => c.id)).toEqual([main.id]);
    expect(s().overlays).toHaveLength(1);
    expect(s().timelines.second?.clips).toHaveLength(1);
    expect(s().timelines.main).toBeUndefined();
  });

  test("each timeline keeps its own undo history", () => {
    const a = asset(4);
    useEditor.setState({ assets: [a], colorSpace: "sdr" });
    s().addClipFromAsset(a.id, 0);
    s().switchTimeline("second");
    // Main's add is not Second's to undo.
    expect(s().undo()).toBe(false);
    s().addClipFromAsset(a.id, 0);
    s().addClipFromAsset(a.id, 0);
    s().setColorSpace("hlg");
    s().switchTimeline("main");
    expect(s().clips).toHaveLength(1);
    expect(s().undo()).toBe(true);
    expect(s().clips).toHaveLength(0);
    // A project-wide setting changed on Second stays put through Main's undo.
    expect(s().colorSpace).toBe("hlg");
    expect(s().redo()).toBe(true);
    expect(s().clips).toHaveLength(1);
    s().switchTimeline("second");
    expect(s().clips).toHaveLength(2);
    expect(s().undo()).toBe(true);
    expect(s().colorSpace).toBe("sdr");
    expect(s().undo()).toBe(true);
    expect(s().clips).toHaveLength(1);
  });

  test("the document carries which timeline is open and the parked ones", () => {
    useEditor.setState({ clips: [vclip({})] });
    const last = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    expect(last.timeline).toBe("main");
    s().switchTimeline("third");
    expect(docFieldsEdited(s(), last, s().transitions)).toBe(true);
    const doc = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    expect(doc.timeline).toBe("third");
    expect(doc.timelines?.main?.clips).toHaveLength(1);
  });

  test("deleting an asset takes its clips off the parked timelines too", () => {
    const a = asset(4);
    useEditor.setState({ assets: [a], clips: [vclip({ assetId: a.id })] });
    s().switchTimeline("second");
    expect(assetIdsInUse(s()).has(a.id)).toBe(false);
    s().removeAsset(a.id);
    expect(s().timelines.main?.clips).toEqual([]);
  });

  test("each timeline keeps its own aspect", () => {
    s().setAspect("16:9");
    s().switchTimeline("second");
    // Opened for the first time: Main's frame.
    expect(s().aspect).toBe("16:9");
    s().setAspect("9:16");
    s().switchTimeline("third");
    expect(s().aspect).toBe("16:9");
    s().switchTimeline("main");
    expect(s().aspect).toBe("16:9");
    expect(s().timelines.second?.aspect).toBe("9:16");
    const doc = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);
    expect(sanitizeTimelines(doc.timelines)?.second?.aspect).toBe("9:16");
    s().switchTimeline("second");
    expect(s().aspect).toBe("9:16");
  });

  test("a timeline parked where the frame was project-wide keeps the doc's", () => {
    const body = { clips: [], audioClips: [], transitions: [], overlays: [], subtitles: emptySubtitles() };
    expect(sanitizeTimelines({ main: body }, { aspect: "16:9" })?.main?.aspect).toBe("16:9");
    // A save from such a client keeps the frame the doc already holds.
    const prior = { aspect: "9:16", timelines: { main: { ...body, aspect: "4:3" as const } } };
    expect(sanitizeTimelines({ main: body }, prior)?.main?.aspect).toBe("4:3");
    expect(sanitizeTimelines({ main: { ...body, aspect: "1:1" } }, prior)?.main?.aspect).toBe("1:1");
  });

  test("an engine without per-timeline frames keeps one frame across switches", () => {
    s().setAspect("16:9");
    s().switchTimeline("second", { ownAspect: false });
    s().setAspect("9:16");
    s().switchTimeline("main", { ownAspect: false });
    expect(s().aspect).toBe("9:16");
  });

  test("a parked timeline missing a list reads it as empty", () => {
    const parked = sanitizeTimelines({ second: { clips: [] }, bogus: { clips: [] } });
    expect(parked).toEqual({
      second: { clips: [], audioClips: [], transitions: [], overlays: [], subtitles: emptySubtitles() },
    });
  });

  test("a shared view cannot switch", () => {
    useEditor.setState({ readOnly: true });
    s().switchTimeline("second");
    expect(s().timeline).toBe("main");
    useEditor.setState({ readOnly: false });
  });
});

describe("micro gaps", () => {
  beforeEach(() => {
    useEditor.setState({ clips: [], audioClips: [], overlays: [], transitions: [], loaded: true });
  });

  test("a clip dropped a hair short of its neighbour lands on it, on every write", () => {
    useEditor.setState({
      clips: [
        vclip({ id: "a", start: 0, out: 4 }),
        vclip({ id: "b", start: 4.03, out: 3 }),
        vclip({ id: "c", start: 7.06, out: 2 }),
        vclip({ id: "p", track: 1, start: 0.02, out: 1 }),
      ],
    });
    const by = (id: string) => useEditor.getState().clips.find((c) => c.id === id)!;
    expect(by("b").start).toBe(4);
    expect(by("c").start).toBe(7);
    expect(by("p").start).toBe(0);
  });

  test("a shrink that pulls the run left carries the clips that abutted it", () => {
    useEditor.setState({
      clips: [
        vclip({ id: "a", start: 0, out: 4 }),
        vclip({ id: "b", start: 4, out: 3 }),
        vclip({ id: "c", start: 7, out: 2 }),
        vclip({ id: "p", track: 1, start: 1, out: 1 }),
      ],
    });
    useEditor.getState().setClipTrim("a", 0, 3.97);
    const by = (id: string) => useEditor.getState().clips.find((c) => c.id === id)!;
    expect(by("a").out).toBeCloseTo(3.97, 5);
    expect(by("b").start).toBeCloseTo(3.97, 5);
    expect(by("c").start).toBeCloseTo(6.97, 5);
  });

  test("a real gap stays, and so does a clip already on the edge", () => {
    const clips = [vclip({ id: "a", start: 0, out: 4 }), vclip({ id: "b", start: 4, out: 3 }), vclip({ id: "c", start: 7.2, out: 2 })];
    expect(closeMicroGaps(clips)).toBe(clips);
  });
});

describe("video placement", () => {
  test("adding onto an occupied upper track inserts at the pointer and ripples the resident", () => {
    const a = asset(2);
    const resident = vclip({ track: 1, start: 1, out: 2 });
    useEditor.setState({
      assets: [a],
      clips: [vclip({ track: 0, start: 0, out: 2 }), resident],
    });
    s().addVideoFromAsset(a.id, { kind: "track", track: 1 }, 1.5);
    expectLaneSound(videoLane(1));
    const added = s().clips.find((c) => c.assetId === a.id)!;
    expect(added.start).toBeCloseTo(1.5);
    expect(clipById(resident.id).start).toBeCloseTo(3.5);
  });

  test("a clip longer than the row lands beside the pointer, never at the end", () => {
    const a = asset(60);
    const first = vclip({ track: 0, start: 0, out: 3 });
    const second = vclip({ track: 0, start: 3, out: 3 });
    const third = vclip({ track: 0, start: 6, out: 3 });
    useEditor.setState({ assets: [a], clips: [first, second, third] });
    s().addVideoFromAsset(a.id, { kind: "track", track: 0 }, 2);
    const added = s().clips.find((c) => c.assetId === a.id)!;
    expect(added.start).toBeCloseTo(3);
    expect(clipById(first.id).start).toBeCloseTo(0);
    expect(clipById(second.id).start).toBeCloseTo(63);
    expect(clipById(third.id).start).toBeCloseTo(66);
    expectLaneSound(videoLane(0));
  });

  test("rippleInsert keys the insertion point off the pointer", () => {
    const row = [
      vclip({ track: 0, start: 0, out: 4 }),
      vclip({ track: 0, start: 4, out: 4 }),
    ];
    // Left half of the first clip: the drop goes ahead of it.
    expect(rippleInsert(row, 1, 10)).toEqual({
      start: 1,
      shifts: [
        { id: row[0].id, start: 11 },
        { id: row[1].id, start: 15 },
      ],
    });
    // Right half: the drop lands right after it.
    expect(rippleInsert(row, 3, 10)).toEqual({
      start: 4,
      shifts: [{ id: row[1].id, start: 14 }],
    });
    // A leading gap the drop fits in moves nothing.
    expect(rippleInsert([vclip({ track: 0, start: 5, out: 2 })], 0, 2).shifts).toEqual([]);
  });

  test("adding onto a freshly inserted track keeps the requested start", () => {
    const a = asset(2);
    const spine = vclip({ track: 0, start: 0, out: 2 });
    const resident = vclip({ track: 1, start: 1, out: 2 });
    useEditor.setState({ assets: [a], clips: [spine, resident] });
    s().addVideoFromAsset(a.id, { kind: "insert", level: 1 }, 1.5);
    const added = s().clips.find((c) => c.assetId === a.id)!;
    expect(added.start).toBeCloseTo(1.5);
    expect(added.track).toBe(1);
    expect(clipById(resident.id).track).toBe(2); // renumbered above the insert
  });

  test("a block fills a gap its own length at the time asked", () => {
    const block: MediaAsset = { ...asset(0.5, "image"), fileName: "", block: { label: "s22" } };
    const before = vclip({ track: 0, start: 0, out: 12.7 });
    const after = vclip({ track: 0, start: 13.2, out: 2 });
    useEditor.setState({ assets: [block], clips: [before, after] });
    const id = s().addClipFromAsset(block.id, 12.7)!;
    expect(clipById(id).start).toBeCloseTo(12.7);
    expect(clipLen(clipById(id))).toBeCloseTo(0.5);
    expectLaneSound(videoLane(0));
  });

});

describe("committed video updates (AI chat / inspector)", () => {
  test("a start move into a resident slides to the next free slot", () => {
    const c1 = vclip({ track: 1, start: 0, out: 2 });
    const c2 = vclip({ track: 1, start: 3, out: 2 });
    useEditor.setState({ clips: [c1, c2] });
    s().updateClip(c2.id, { start: 1 });
    expect(clipById(c2.id).start).toBeCloseTo(2);
    expectLaneSound(videoLane(1));
  });

  test("a move only collides with its own track", () => {
    const c1 = vclip({ track: 1, start: 0, out: 2 });
    const c2 = vclip({ track: 2, start: 3, out: 2 });
    useEditor.setState({ clips: [c1, c2] });
    s().updateClip(c2.id, { start: 1 });
    expect(clipById(c2.id).start).toBeCloseTo(1);
  });

  test("retracking onto an occupied track slides clear", () => {
    // Grounded on write: the stack always sits on track 0, so the pair is
    // written as the rows they would ground to.
    const c1 = vclip({ track: 0, start: 0, out: 2 });
    const c2 = vclip({ track: 1, start: 0.5, out: 2 });
    useEditor.setState({ clips: [c1, c2] });
    s().updateClip(c2.id, { track: 0 });
    expect(clipById(c2.id).start).toBeCloseTo(2);
    expectLaneSound(videoLane(0));
  });

  test("extending a clip pushes the same-track run right", () => {
    const c1 = vclip({ track: 1, start: 0, out: 2 });
    const c2 = vclip({ track: 1, start: 2.5, out: 2 });
    const c3 = vclip({ track: 1, start: 5, out: 2 });
    useEditor.setState({ clips: [c1, c2, c3] });
    s().updateClip(c1.id, { out: 4 });
    expect(clipById(c2.id).start).toBeCloseTo(4);
    expect(clipById(c3.id).start).toBeCloseTo(6.5); // gap preserved
    expectLaneSound(videoLane(1));
  });

  test("a speed change that lengthens the footprint pushes the run", () => {
    const c1 = vclip({ track: 1, start: 0, out: 2, speed: 2 }); // 1s footprint
    const c2 = vclip({ track: 1, start: 1, out: 2 });
    useEditor.setState({ clips: [c1, c2] });
    s().updateClip(c1.id, { speed: undefined }); // back to 1x → 2s footprint
    expect(clipById(c2.id).start).toBeCloseTo(2);
    expectLaneSound(videoLane(1));
  });

  test("a non-footprint patch moves nothing", () => {
    const c1 = vclip({ track: 1, start: 0, out: 2 });
    const c2 = vclip({ track: 1, start: 2, out: 2 });
    useEditor.setState({ clips: [c1, c2] });
    s().updateClip(c1.id, { muted: true });
    expect(clipById(c1.id).start).toBeCloseTo(0);
    expect(clipById(c2.id).start).toBeCloseTo(2);
  });

  test("separateOverlaps pulls an old physically-overlapped doc apart", () => {
    // A doc saved when a transition slid clips into each other: b starts
    // inside a, c rides 1s behind b across a gap.
    const a = vclip({ track: 0, start: 0, out: 4, transition: 1 });
    const b = vclip({ track: 0, start: 3, out: 4 });
    const c = vclip({ track: 0, start: 8, out: 2 });
    const other = vclip({ track: 1, start: 3, out: 2 });
    const out = separateOverlaps({
      clips: [a, b, c, other],
      audioClips: [],
      overlays: [],
      cues: [],
    });
    const by = (id: string) => out.clips.find((x) => x.id === id)!;
    expect(by(b.id).start).toBeCloseTo(4); // pushed out to the cut
    expect(by(c.id).start).toBeCloseTo(9); // the run keeps its gap
    expect(by(other.id).start).toBeCloseTo(3); // other tracks untouched
    // A doc with nothing intruding passes through untouched.
    const clean = { clips: [vclip({ start: 0, out: 2 }), vclip({ start: 2, out: 2 })], audioClips: [], overlays: [], cues: [] };
    expect(separateOverlaps(clean)).toBe(clean);
  });

  test("the cut getting longer carries the sound, titles and captions with it", () => {
    // Same doc, now annotated: a voiceover, a title and a caption timed
    // against the shorter overlapped timeline.
    const a = vclip({ track: 0, start: 0, out: 4, transition: 1 });
    const b = vclip({ track: 0, start: 3, out: 4 });
    const out = separateOverlaps({
      clips: [a, b],
      audioClips: [aclip({ start: 0, out: 2 }), aclip({ start: 5, out: 2 })],
      overlays: [title({ start: 1, end: 2 }), title({ start: 4, end: 6 })],
      cues: [cue({ start: 5, end: 6, words: [{ w: "hi", t0: 5, t1: 6 }] })],
    });
    expect(out.clips.find((c) => c.id === b.id)!.start).toBeCloseTo(4);
    // Before the joint nothing moves; after it, everything moves with b.
    expect(out.audioClips[0].start).toBeCloseTo(0);
    expect(out.audioClips[1].start).toBeCloseTo(6);
    expect(out.overlays[0].start).toBeCloseTo(1);
    expect(out.overlays[1].start).toBeCloseTo(5);
    expect(out.cues[0].start).toBeCloseTo(6);
    expect(out.cues[0].words![0].t0).toBeCloseTo(6);
  });

  test("clips never overlap, transition or not", () => {
    const a = vclip({ track: 0, start: 0, out: 4, transition: 1 });
    const b = vclip({ track: 0, start: 4, out: 4 });
    useEditor.setState({ clips: [a, b] });
    // Re-committing the abutting start moves nothing.
    s().updateClip(b.id, { start: 4 });
    expect(clipById(b.id).start).toBeCloseTo(4);
    // A move into the leading clip settles back out to contact — a
    // transition is a blend at the cut, never a licence to intrude.
    s().updateClip(b.id, { start: 1 });
    expect(clipById(b.id).start).toBeCloseTo(4);
  });
});

describe("the panel + add", () => {
  test("a video lands under the playhead when its track has room there", () => {
    const a = asset(2);
    useEditor.setState({ assets: [a], clips: [vclip({ start: 0, out: 2 })] });
    setPlayhead(5);
    s().addAssetAtPlayhead(a.id);
    const added = s().clips.find((c) => c.assetId === a.id)!;
    expect(added.start).toBeCloseTo(5);
    expect(added.track).toBe(0);
  });

  test("an occupied playhead climbs to the first open track, opening one when the stack is full", () => {
    const a = asset(2);
    useEditor.setState({
      assets: [a],
      clips: [vclip({ start: 0, out: 8 }), vclip({ track: 1, start: 4, out: 4 })],
    });
    setPlayhead(5);
    s().addAssetAtPlayhead(a.id);
    const added = s().clips.find((c) => c.assetId === a.id)!;
    expect(added.start).toBeCloseTo(5);
    expect(added.track).toBe(2);
    expectLaneSound(videoLane(0));
    expectLaneSound(videoLane(1));
  });

  test("a gap too small for the clip counts as occupied", () => {
    const a = asset(4);
    useEditor.setState({
      assets: [a],
      clips: [vclip({ start: 0, out: 2 }), vclip({ start: 4, out: 2 })],
    });
    setPlayhead(2); // 2s gap, 4s clip
    s().addAssetAtPlayhead(a.id);
    const added = s().clips.find((c) => c.assetId === a.id)!;
    expect(added.start).toBeCloseTo(2);
    expect(added.track).toBe(1);
    expectLaneSound(videoLane(0));
  });

  test("a live skimmer wins over the playhead", () => {
    const a = asset(2);
    useEditor.setState({ assets: [a], clips: [] });
    setPlayhead(1);
    setSkim(6);
    s().addAssetAtPlayhead(a.id);
    expect(s().clips.find((c) => c.assetId === a.id)!.start).toBeCloseTo(6);
  });

  test("audio under a full lane opens the next lane at the same moment", () => {
    const a = asset(3, "audio");
    useEditor.setState({ assets: [a], audioClips: [aclip({ start: 0, out: 10 })] });
    setPlayhead(2);
    s().addAssetAtPlayhead(a.id);
    const added = s().audioClips.find((c) => c.assetId === a.id)!;
    expect(added.start).toBeCloseTo(2);
    expect(added.lane).toBe(1);
  });
});

describe("audio lanes", () => {
  test("adding at an occupied time slides right", () => {
    const a = asset(2, "audio");
    useEditor.setState({
      assets: [a],
      audioClips: [aclip({ start: 0, out: 2 })],
    });
    s().addAudioFromAsset(a.id, 1);
    const added = s().audioClips.find((c) => c.assetId === a.id)!;
    expect(added.start).toBeCloseTo(2);
  });

  test("a committed start move slides on its own lane only", () => {
    const a1 = aclip({ start: 0, out: 2 });
    const a2 = aclip({ start: 3, out: 2 });
    const other = aclip({ start: 1, out: 2, lane: 1 });
    useEditor.setState({ audioClips: [a1, a2, other] });
    s().updateAudio(a2.id, { start: 0.5 });
    expect(audioById(a2.id).start).toBeCloseTo(2);
    expect(audioById(other.id).start).toBeCloseTo(1); // other lane untouched
  });

  test("retracking to another lane lands on a free slot there", () => {
    const a1 = aclip({ start: 0, out: 2 });
    const a2 = aclip({ start: 0.5, out: 2, lane: 1 });
    useEditor.setState({ audioClips: [a1, a2] });
    s().updateAudio(a2.id, { lane: undefined });
    expect(audioById(a2.id).start).toBeCloseTo(2);
  });

  test("extending pushes the same-lane run right", () => {
    const a1 = aclip({ start: 0, out: 2 });
    const a2 = aclip({ start: 2.5, out: 2 });
    useEditor.setState({ audioClips: [a1, a2] });
    s().updateAudio(a1.id, { out: 4 });
    expect(audioById(a2.id).start).toBeCloseTo(4);
  });

  test("volume/fade patches move nothing", () => {
    const a1 = aclip({ start: 0, out: 2 });
    const a2 = aclip({ start: 2, out: 2 });
    useEditor.setState({ audioClips: [a1, a2] });
    s().updateAudio(a1.id, { volume: 0.4, fadeIn: 0.5 });
    expect(audioById(a1.id).start).toBeCloseTo(0);
    expect(audioById(a2.id).start).toBeCloseTo(2);
  });
});

describe("row reordering", () => {
  test("a video track carried down the stack renumbers the ones it passes", () => {
    const bottom = vclip({ track: 0 });
    const mid = vclip({ track: 1 });
    const top = vclip({ track: 2 });
    useEditor.setState({ clips: [bottom, mid, top] });
    s().moveVideoTrack(2, 0); // the frontmost layer becomes the spine
    expect(clipById(top.id).track).toBe(0);
    expect(clipById(bottom.id).track).toBe(1);
    expect(clipById(mid.id).track).toBe(2);
  });

  test("reordering closes track number holes", () => {
    const a = vclip({ track: 0 });
    const b = vclip({ track: 3 });
    useEditor.setState({ clips: [a, b] });
    s().moveVideoTrack(0, 1);
    expect(clipById(b.id).track).toBe(0);
    expect(clipById(a.id).track).toBe(1);
  });

  test("an element row lands where it was carried, times untouched", () => {
    const t0 = title({ start: 1, end: 2, lane: 0 });
    const t1 = title({ start: 0, end: 3, lane: 1 });
    const t2 = title({ start: 4, end: 5, lane: 2 });
    useEditor.setState({ overlays: [t0, t1, t2] });
    s().moveOverlayLane(0, 2); // the top row goes to the bottom
    const by = (id: string) => s().overlays.find((o) => o.id === id)!;
    expect(by(t1.id).lane).toBe(0);
    expect(by(t2.id).lane).toBe(1);
    expect(by(t0.id).lane).toBe(2);
    expect(by(t0.id).start).toBeCloseTo(1);
  });

  test("a soundtrack lane move takes every segment on the row", () => {
    const a1 = aclip({ start: 0, out: 2 });
    const a2 = aclip({ start: 4, out: 2 });
    const b1 = aclip({ start: 0, out: 2, lane: 1 });
    useEditor.setState({ audioClips: [a1, a2, b1] });
    s().moveAudioLane(1, 0);
    expect(audioById(b1.id).lane ?? 0).toBe(0);
    expect(audioById(a1.id).lane).toBe(1);
    expect(audioById(a2.id).lane).toBe(1);
  });

  test("a move to the row it already sits on changes nothing", () => {
    const t0 = title({ lane: 0 });
    const t1 = title({ lane: 1 });
    useEditor.setState({ overlays: [t0, t1] });
    const before = s().overlays;
    s().moveOverlayLane(1, 1);
    expect(s().overlays).toBe(before);
  });
});

describe("title lanes", () => {
  const overlayById = (id: string) => s().overlays.find((o) => o.id === id)!;

  test("a committed start move slides clear, keeping its length", () => {
    const t1 = title({ start: 0, end: 2 });
    const t2 = title({ start: 3, end: 4 });
    useEditor.setState({ overlays: [t1, t2] });
    s().updateOverlay(t2.id, { start: 1 });
    expect(overlayById(t2.id).start).toBeCloseTo(2);
    expect(overlayById(t2.id).end).toBeCloseTo(3);
  });

  test("growing the end pushes the same-lane run right", () => {
    const t1 = title({ start: 0, end: 2 });
    const t2 = title({ start: 2.5, end: 4 });
    useEditor.setState({ overlays: [t1, t2] });
    s().updateOverlay(t1.id, { end: 3 });
    expect(overlayById(t2.id).start).toBeCloseTo(3);
    expect(overlayById(t2.id).end).toBeCloseTo(4.5); // length kept
  });

  test("lanes are independent", () => {
    const t1 = title({ start: 0, end: 2 });
    const t2 = title({ start: 3, end: 4, lane: 1 });
    useEditor.setState({ overlays: [t1, t2] });
    s().updateOverlay(t2.id, { start: 0.5 });
    expect(overlayById(t2.id).start).toBeCloseTo(0.5);
  });

  describe("group moves", () => {
    test("peers ride along keeping their length and spacing", () => {
      const a = title({ start: 5, end: 7, groupId: "g" });
      const b = title({ start: 9, end: 13, lane: 1, groupId: "g" });
      useEditor.setState({ overlays: [a, b] });
      // The dragged element lands first; the group follows it.
      s().updateOverlaysTransient([{ id: a.id, patch: { start: 6, end: 8 } }]);
      moveOverlayGroup(a, 1);
      expect(overlayById(b.id).start).toBeCloseTo(10);
      expect(overlayById(b.id).end).toBeCloseTo(14); // 4s long, still
    });

    test("a shift past zero moves the whole group, never squashing one", () => {
      const a = title({ start: 5, end: 7, groupId: "g" });
      const b = title({ start: 1, end: 4, lane: 1, groupId: "g" });
      useEditor.setState({ overlays: [a, b] });
      s().updateOverlaysTransient([{ id: a.id, patch: { start: 0, end: 2 } }]);
      moveOverlayGroup(a, -5);
      // b would have gone to -4; the group lands 4 later instead.
      expect(overlayById(b.id).start).toBeCloseTo(0);
      expect(overlayById(b.id).end).toBeCloseTo(3); // 3s long, still
      expect(overlayById(a.id).start).toBeCloseTo(4);
    });

    test("unrelated elements are pushed clear of where the group lands", () => {
      const a = title({ start: 0, end: 2, groupId: "g" });
      const b = title({ start: 0, end: 2, lane: 1, groupId: "g" });
      const resident = title({ start: 4, end: 6, lane: 1 });
      const far = title({ start: 20, end: 21, lane: 1 });
      useEditor.setState({ overlays: [a, b, resident, far] });
      s().updateOverlaysTransient([{ id: a.id, patch: { start: 3.5, end: 5.5 } }]);
      moveOverlayGroup(a, 3.5);
      expect(overlayById(b.id).start).toBeCloseTo(3.5); // rigid
      expect(overlayById(resident.id).start).toBeCloseTo(5.5); // pushed clear
      expect(overlayById(far.id).start).toBeCloseTo(20); // untouched
      expectLaneSound(
        s()
          .overlays.filter((o) => (o.lane ?? 0) === 1)
          .map((o) => ({ start: o.start, end: o.end }))
      );
    });
  });

  describe("group camera on a lone move", () => {
    const push = [
      { t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 0 },
      { t: 2, x: 0.5, y: 0.5, scale: 2, rotation: 0 },
    ];

    test("moving one member keeps its camera on the timeline", () => {
      const a = title({ start: 0, end: 4, groupId: "g" });
      const b = title({ start: 0, end: 4, lane: 1, groupId: "g" });
      useEditor.setState({ overlays: withGroupCamera([a, b], "g", { keys: push }) });
      s().updateOverlay(b.id, { start: 1 });
      // b now starts 1s later, so the push at timeline 2s sits 1s into it.
      expect(overlayById(a.id).camera!.kf.map((k) => k.t)).toEqual([0, 2]);
      expect(overlayById(b.id).camera!.kf.map((k) => k.t)).toEqual([-1, 1]);
    });

    test("a member pushed clear of a moved group keeps its camera on the timeline", () => {
      const x = title({ start: 0, end: 2, groupId: "m" });
      const y = title({ start: 10, end: 11, lane: 1, groupId: "m" });
      const a = title({ start: 3, end: 6, groupId: "g" });
      const b = title({ start: 3, end: 6, lane: 1, groupId: "g" });
      useEditor.setState({ overlays: [x, y, ...withGroupCamera([a, b], "g", { keys: push })] });
      s().updateOverlaysTransient([{ id: x.id, patch: { start: 2, end: 4 } }]);
      moveOverlayGroup(x, 2);
      // a slid to 4 to clear the mover; the push still lands at timeline 5s.
      expect(overlayById(a.id).start).toBeCloseTo(4);
      expect(overlayById(a.id).camera!.kf.map((k) => k.t)).toEqual([-1, 1]);
      expect(overlayById(b.id).camera!.kf.map((k) => k.t)).toEqual([0, 2]);
    });

    test("the chat places a grouped element beyond the frame", async () => {
      const a = title({ start: 0, end: 4, groupId: "g" });
      const b = title({ start: 0, end: 4, lane: 1 });
      useEditor.setState({ overlays: [a, b] });
      await runAiTool("update_overlay", { id: a.id, x: 1.4, y: -0.3 });
      await runAiTool("update_overlay", { id: b.id, x: 1.4 });
      expect(overlayById(a.id).x).toBeCloseTo(1.4);
      expect(overlayById(a.id).y).toBeCloseTo(-0.3);
      expect(overlayById(b.id).x).toBeCloseTo(0.98);
      await runAiTool("set_overlay_keyframes", { id: a.id, keys: [{ t: 1, x: 1.8 }] });
      expect(overlayById(a.id).kf![0].x).toBeCloseTo(1.8);
    });

    test("a whole group moving carries its camera", () => {
      const a = title({ start: 5, end: 7, groupId: "g" });
      const b = title({ start: 9, end: 13, lane: 1, groupId: "g" });
      useEditor.setState({ overlays: withGroupCamera([a, b], "g", { keys: push }) });
      s().updateOverlaysTransient([{ id: a.id, patch: { start: 6, end: 8 } }]);
      moveOverlayGroup(a, 1);
      expect(overlayById(a.id).camera!.kf.map((k) => k.t)).toEqual([0, 2]);
      expect(overlayById(b.id).camera!.kf.map((k) => k.t)).toEqual([-4, -2]);
    });
  });

  describe("keyframes", () => {
    test("the chat keys an element in from beyond the frame while its rest stays on it", async () => {
      const t1 = title({ start: 0, end: 4 });
      useEditor.setState({ overlays: [t1] });
      await runAiTool("set_overlay_keyframes", { id: t1.id, keys: [{ t: 0, x: -0.2, y: 1.1 }, { t: 1, x: 0.5, y: 0.5 }, { t: 2, y: 9 }] });
      expect(overlayById(t1.id).kf!.map((k) => [k.x, k.y])).toEqual([[-0.2, 1.1], [0.5, 0.5], [0.5, 1.5]]);
      await runAiTool("update_overlay", { id: t1.id, y: 1.1 });
      expect(overlayById(t1.id).y).toBeCloseTo(0.98);
    });

    test("the chat's keys merge into the track unless it asks to replace it", async () => {
      const t1 = title({ start: 0, end: 4 });
      useEditor.setState({ overlays: [t1] });
      await runAiTool("set_overlay_keyframes", { id: t1.id, keys: [{ t: 0, x: 0.2 }, { t: 3, x: 0.8 }] });
      await runAiTool("set_overlay_keyframes", { id: t1.id, keys: [{ t: 1, x: 0.4 }] });
      expect(overlayById(t1.id).kf!.map((k) => k.t)).toEqual([0, 1, 3]);
      const out = await runAiTool("set_overlay_keyframes", { id: t1.id, replace: true, keys: [{ t: 0.5, x: 0.3 }, { t: 2, x: 0.6 }] });
      expect(overlayById(t1.id).kf!.map((k) => [k.t, k.x])).toEqual([[0.5, 0.3], [2, 0.6]]);
      expect((out as { keys: { t: number }[] }).keys.map((k) => k.t)).toEqual([0.5, 2]);
    });

    test("a loop's rate comes back as the seconds one cycle takes", async () => {
      const t1 = title({ start: 0, end: 4 });
      useEditor.setState({ overlays: [t1] });
      const out = (await runAiTool("set_overlay_animation", { id: t1.id, loop_style: "spin", loop_speed: 5 })) as { loop_cycle_seconds?: number };
      expect(out.loop_cycle_seconds).toBeCloseTo(0.8, 5);
    });

    test("a sticker can be drawn as small as a mouse pointer", async () => {
      const st = title({ kind: "sticker", assetId: "img", w: 0.2 } as unknown as Partial<TextOverlay>);
      useEditor.setState({ overlays: [st] });
      await runAiTool("update_overlay", { id: st.id, w: 0.012 });
      expect((overlayById(st.id) as unknown as { w: number }).w).toBeCloseTo(0.012, 4);
      await runAiTool("update_overlay", { id: st.id, w: 0.001 });
      expect((overlayById(st.id) as unknown as { w: number }).w).toBeCloseTo(0.005, 4);
    });

    test("a key captures the pose and the track drops when the last one goes", () => {
      const t1 = title({ start: 2, end: 6, x: 0.4, rotation: 30, opacity: 0.5 });
      useEditor.setState({ overlays: [t1] });
      s().setOverlayKey(t1.id, 1);
      const [k] = overlayById(t1.id).kf!;
      expect(k).toEqual({ t: 1, x: 0.4, y: 0.5, scale: 1, rotation: 30, opacity: 0.5 });
      s().removeOverlayKey(t1.id, 1);
      expect(overlayById(t1.id).kf).toBe(undefined);
    });

    test("a key past the element's end clamps into it, and re-keying replaces", () => {
      const t1 = title({ start: 0, end: 3 });
      useEditor.setState({ overlays: [t1] });
      s().setOverlayKey(t1.id, 99, { x: 0.9 });
      expect(overlayById(t1.id).kf![0].t).toBeCloseTo(3);
      s().setOverlayKey(t1.id, 3, { x: 0.1 });
      expect(overlayById(t1.id).kf!.length).toBe(1);
      expect(overlayById(t1.id).kf![0].x).toBeCloseTo(0.1);
    });

    test("a picked key is what Delete takes, and the element stays", () => {
      const t1 = title({ start: 0, end: 4 });
      useEditor.setState({ overlays: [t1] });
      s().setOverlayKey(t1.id, 1, { x: 0.1 });
      s().setOverlayKey(t1.id, 3, { x: 0.9 });
      s().selectOverlayKey(t1.id, 3);
      s().deleteSelection();
      expect(s().overlays.length).toBe(1); // the element is untouched
      expect(overlayById(t1.id).kf!.map((k) => k.t)).toEqual([1]);
      expect(s().selectedKey).toBe(null);
      // With no key picked, Delete goes back to taking the element.
      s().deleteSelection();
      expect(s().overlays.length).toBe(0);
    });

    test("retiming a key carries the pick with it", () => {
      const t1 = title({ start: 0, end: 4 });
      useEditor.setState({ overlays: [t1] });
      s().setOverlayKey(t1.id, 1);
      s().selectOverlayKey(t1.id, 1);
      s().moveOverlayKey(t1.id, 1, 2.5, { transient: true });
      expect(s().selectedKey).toEqual({ kind: "overlay", id: t1.id, t: 2.5, track: "pose" });
      s().deleteSelection();
      expect(overlayById(t1.id).kf).toBe(undefined);
    });

    test("a picked mask key deletes from the mask track and leaves the pose", () => {
      const t1 = title({ start: 0, end: 4, mask: { kind: "rect" as const } });
      useEditor.setState({ overlays: [t1] });
      s().setOverlayKey(t1.id, 1);
      s().setOverlayMaskKey(t1.id, 1);
      s().setOverlayMaskKey(t1.id, 3, { w: 0.8 });
      s().selectOverlayMaskKey(t1.id, 3);
      s().moveOverlayMaskKey(t1.id, 3, 2, { transient: true });
      expect(s().selectedKey).toEqual({ kind: "overlay", id: t1.id, t: 2, track: "mask" });
      s().deleteSelection();
      expect(overlayById(t1.id).mask!.kf!.map((k) => k.t)).toEqual([1]);
      expect(overlayById(t1.id).kf!.length).toBe(1); // the pose track is untouched
    });

    test("selecting anything else drops the pick", () => {
      const t1 = title({ start: 0, end: 4 });
      useEditor.setState({ overlays: [t1] });
      s().setOverlayKey(t1.id, 1);
      s().selectOverlayKey(t1.id, 1);
      s().select({ kind: "overlay", id: t1.id });
      expect(s().selectedKey).toBe(null);
    });

    test("clearing returns the element to its resting pose", () => {
      const t1 = title({ start: 0, end: 4 });
      useEditor.setState({ overlays: [t1] });
      s().setOverlayKey(t1.id, 0, { x: 0.1 });
      s().setOverlayKey(t1.id, 2, { x: 0.9 });
      expect(overlayById(t1.id).kf!.length).toBe(2);
      s().clearOverlayKeys(t1.id);
      expect(overlayById(t1.id).kf).toBe(undefined);
      expect(overlayById(t1.id).x).toBeCloseTo(0.5); // never moved the element itself
    });
  });

  test("copies get their own group, and members copied together stay together", () => {
    let seq = 0;
    const remap = groupRemap(() => `g${++seq}`);
    const a = title({ groupId: "g" });
    const b = title({ groupId: "g" });
    const loner = title({});
    expect(remap(a).groupId).toBe(remap(b).groupId!);
    expect(remap(a).groupId).not.toBe("g");
    expect(remap(loner).groupId).toBe(undefined);
    // A second operation is a second group.
    expect(groupRemap(() => `g${++seq}`)(a).groupId).not.toBe(remap(a).groupId!);
  });
});

describe("subtitle cues", () => {
  test("retiming slides past occupied stretches and drops word timings", () => {
    const q1 = cue({ start: 0, end: 1 });
    const q2 = cue({ start: 2, end: 3, words: [{ t0: 2, t1: 3, w: "hi" }] });
    useEditor.setState({
      subtitles: { ...emptySubtitles(), cues: [q1, q2] },
    });
    s().setCueTiming(q2.id, 0.5, 1.5);
    const next = s().subtitles.cues.find((c) => c.id === q2.id)!;
    expect(next.start).toBeCloseTo(1);
    expect(next.end).toBeCloseTo(2);
    expect(next.words).toBeUndefined();
  });

  test("retiming on another lane ignores this lane's cues", () => {
    const q1 = cue({ start: 0, end: 1 });
    const q2 = cue({ start: 2, end: 3, lane: 1 });
    useEditor.setState({
      subtitles: { ...emptySubtitles(), cues: [q1, q2] },
    });
    s().setCueTiming(q2.id, 0.5, 1.5);
    const next = s().subtitles.cues.find((c) => c.id === q2.id)!;
    expect(next.start).toBeCloseTo(0.5);
  });
});

describe("independent deletion and gaps", () => {
  test("single-track delete keeps all other items in place", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 2, out: 2 });
    const au = aclip({ start: 3, out: 2 });
    const t = title({ start: 3, end: 4 });
    useEditor.setState({
      clips: [a, b],
      audioClips: [au],
      overlays: [t],
      selection: { kind: "clip", id: a.id },
    });
    s().deleteSelection();
    expect(clipById(b.id).start).toBeCloseTo(2);
    expect(audioById(au.id).start).toBeCloseTo(3);
    expect(s().overlays[0].start).toBeCloseTo(3);
  });

  test("deleting a clip leaves independent transitions in place", () => {
    const av = asset(2);
    const a = vclip({ track: 0, start: 0, out: 2, assetId: av.id });
    const b = vclip({ track: 0, start: 2, out: 2, assetId: av.id });
    const c = vclip({ track: 0, start: 4, out: 2, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b, c] });
    s().setClipTransition(a.id, 0.5);
    s().setClipTransition(b.id, 0.5);
    s().select({ kind: "clip", id: a.id });
    s().deleteSelection();
    expect(s().transitions.length).toBe(2);
    expect(clipById(b.id).start).toBeCloseTo(2);
    expect(clipById(b.id).transition).toBeCloseTo(0.5);
    expect(s().transitions[0].start).toBeCloseTo(1.5);
  });

  test("a trim pushes its row and leaves independent transitions in place", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, in: 0, out: 2, assetId: av.id });
    const b = vclip({ track: 0, start: 2, in: 0, out: 2, assetId: av.id });
    const c = vclip({ track: 0, start: 4, in: 0, out: 2, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b, c] });
    s().setClipTransition(a.id, 0.5);
    s().setClipTransition(b.id, 0.5);
    s().updateClip(a.id, { out: 3 }); // a grows by 1s, pushing b and c right
    expect(clipById(b.id).start).toBeCloseTo(3);
    expect(s().transitions.map((t) => t.start)).toEqual([1.5, 3.5]);
    expect(parkedTransitions(s().clips, s().transitions)).toHaveLength(2);
  });

  test("clearing track 0 leaves the titles and captions standing", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 2, out: 2 });
    const t = title({ start: 1, end: 3 });
    const au = aclip({ start: 1, out: 2 });
    useEditor.setState({
      clips: [a, b],
      audioClips: [au],
      overlays: [t],
      multiSelection: [
        { kind: "clip", id: a.id },
        { kind: "clip", id: b.id },
      ],
      selection: { kind: "clip", id: b.id },
    });
    s().deleteSelection();
    expect(s().clips).toEqual([]);
    // No footage left means no hole to close, so nothing laid over it moves
    // and nothing goes with it.
    expect(s().overlays.map((o) => o.id)).toEqual([t.id]);
    expect(s().overlays[0].start).toBeCloseTo(1);
    expect(audioById(au.id).start).toBeCloseTo(1);
  });

  test("deleting the only clip keeps the elements written over it", () => {
    const only = vclip({ track: 0, start: 0, out: 6 });
    const t = title({ start: 1, end: 3 });
    useEditor.setState({
      clips: [only],
      overlays: [t],
      selection: { kind: "clip", id: only.id },
    });
    s().deleteSelection();
    expect(s().clips).toEqual([]);
    expect(s().overlays.map((o) => o.id)).toEqual([t.id]);
    expect(s().overlays[0].start).toBeCloseTo(1);
  });

  test("a title on its own row survives the clip it was written over", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 2, out: 2 });
    const t = title({ start: 2.5, end: 3.5, lane: 1 });
    useEditor.setState({
      clips: [a, b],
      overlays: [t],
      selection: { kind: "clip", id: b.id },
    });
    s().deleteSelection();
    expect(s().overlays.map((o) => o.id)).toEqual([t.id]);
    expect(s().overlays[0].start).toBeCloseTo(2.5);
    expect(s().overlays[0].end).toBeCloseTo(3.5);
  });

  test("a soundtrack spanning the deleted clip keeps every second of it", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 2, out: 2 });
    const c = vclip({ track: 0, start: 4, out: 2 });
    const bed = aclip({ start: 0, out: 6 });
    useEditor.setState({
      clips: [a, b, c],
      audioClips: [bed],
      selection: { kind: "clip", id: b.id },
    });
    s().deleteSelection();
    expect(s().audioClips.map((x) => x.id)).toEqual([bed.id]);
    expect(audioById(bed.id).start).toBeCloseTo(0);
    expect(clipLen(audioById(bed.id))).toBeCloseTo(6);
    expect(clipById(c.id).start).toBeCloseTo(4);
  });

  test("captions over deleted footage keep their times and words", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 2, out: 4 });
    const q1 = cue({ start: 2.5, end: 3, words: [{ t0: 2.5, t1: 3, w: "one" }] });
    const q2 = cue({ start: 3.5, end: 4 });
    useEditor.setState({
      clips: [a, b],
      subtitles: { ...emptySubtitles(), cues: [q1, q2] },
      selection: { kind: "clip", id: b.id },
    });
    s().deleteSelection();
    const cues = s().subtitles.cues;
    expect(cues.map((c) => c.id)).toEqual([q1.id, q2.id]);
    expect(cues[0].start).toBeCloseTo(2.5);
    expect(cues[0].end).toBeCloseTo(3);
    expect(cues[0].words![0].t0).toBeCloseTo(2.5);
    expect(cues[1].start).toBeCloseTo(3.5);
    expectLaneSound(cues);
  });

  test("two titles on one row keep their times after video deletion", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 2, out: 4 });
    const t1 = title({ start: 2.5, end: 3 });
    const t2 = title({ start: 3.5, end: 4 });
    useEditor.setState({
      clips: [a, b],
      overlays: [t1, t2],
      selection: { kind: "clip", id: b.id },
    });
    s().deleteSelection();
    expect(s().overlays.map((o) => o.id)).toEqual([t1.id, t2.id]);
    expectLaneSound(s().overlays);
    expect(s().overlays.find((o) => o.id === t2.id)!.start).toBeCloseTo(3.5);
  });

  test("an unrelated group keeps its times after video deletion", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 2, out: 6 });
    // Lane 0 is crowded right where the group wants to land, so its member
    // packs in behind the resident — and its peer on lane 1 comes along.
    const resident = title({ start: 2.2, end: 2.9 });
    const g1 = title({ start: 4, end: 5, groupId: "g" });
    const g2 = title({ start: 4, end: 5, lane: 1, groupId: "g" });
    useEditor.setState({
      clips: [a, b],
      overlays: [resident, g1, g2],
      selection: { kind: "clip", id: b.id },
    });
    s().deleteSelection();
    const byId = (id: string) => s().overlays.find((o) => o.id === id)!;
    expect(s().overlays.length).toBe(3);
    expect(byId(g1.id).start).toBeCloseTo(byId(g2.id).start);
    expectLaneSound(s().overlays.filter((o) => (o.lane ?? 0) === 0));
  });

  test("delete with an overlay video track leaves the gap in place", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 2, out: 2 });
    const layer = vclip({ track: 1, start: 1, out: 2 });
    useEditor.setState({
      clips: [a, b, layer],
      selection: { kind: "clip", id: a.id },
    });
    s().deleteSelection();
    expect(clipById(b.id).start).toBeCloseTo(2);
    expect(clipById(layer.id).start).toBeCloseTo(1);
  });

  test("shortening the project pulls the playhead back to the new end", () => {
    // The playhead placed past the end stretched the timeline's scroll area
    // into empty space, because it is positioned with a transform.
    const keep = vclip({ track: 0, start: 0, out: 4 });
    const far = vclip({ track: 0, start: 30, out: 4 });
    useEditor.setState({ clips: [keep, far] });
    s().seek(32);
    expect(playheadAt()).toBeCloseTo(32);
    s().select({ kind: "clip", id: far.id });
    s().deleteSelection();
    expect(playheadAt()).toBeCloseTo(projectDuration(s()));
    expect(playheadAt()).toBeLessThanOrEqual(4);
  });

  test("an overlay left standing keeps the playhead reachable", () => {
    const clip = vclip({ track: 0, start: 0, out: 2 });
    const late = title({ start: 6, end: 9 });
    useEditor.setState({ clips: [clip], overlays: [late], audioClips: [] });
    s().seek(8);
    expect(playheadAt()).toBeCloseTo(8);
  });

  test("removeLaneGap closes the gap on its own track only", () => {
    const b = vclip({ track: 0, start: 2, out: 2 });
    const layer = vclip({ track: 1, start: 2.5, out: 2 });
    const au = aclip({ start: 3, out: 2 });
    useEditor.setState({ clips: [b, layer], audioClips: [au] });
    s().removeLaneGap({ kind: "video", index: 0 }, 1);
    expect(clipById(b.id).start).toBeCloseTo(0);
    expect(clipById(layer.id).start).toBeCloseTo(2.5);
    expect(audioById(au.id).start).toBeCloseTo(3);
  });

  test("removeLaneGap between clips on an upper track slides only that track", () => {
    const base = vclip({ track: 0, start: 0, out: 2 });
    const l1 = vclip({ track: 1, start: 0, out: 1 });
    const l2 = vclip({ track: 1, start: 3, out: 1 });
    useEditor.setState({ clips: [base, l1, l2] });
    s().removeLaneGap({ kind: "video", index: 1 }, 2);
    expect(clipById(l2.id).start).toBeCloseTo(1);
    expect(clipById(base.id).start).toBeCloseTo(0);
  });

  test("removeLaneGap outside a gap is a no-op", () => {
    const a = vclip({ track: 0, start: 0, out: 2 });
    const b = vclip({ track: 0, start: 3, out: 2 });
    useEditor.setState({ clips: [a, b] });
    s().removeLaneGap({ kind: "video", index: 0 }, 1); // on a clip
    s().removeLaneGap({ kind: "video", index: 0 }, 6); // past the end
    expect(clipById(a.id).start).toBeCloseTo(0);
    expect(clipById(b.id).start).toBeCloseTo(3);
  });

  test("removeLaneGap closes an audio row without moving its neighbours", () => {
    const keep = aclip({ start: 0, out: 1 });
    const late = aclip({ start: 3, out: 1 });
    const other = aclip({ start: 3, out: 1, lane: 1 });
    const vid = vclip({ track: 0, start: 3, out: 1 });
    useEditor.setState({ clips: [vid], audioClips: [keep, late, other] });
    s().removeLaneGap({ kind: "audio", index: 0 }, 2);
    expect(audioById(late.id).start).toBeCloseTo(1);
    expect(audioById(other.id).start).toBeCloseTo(3);
    expect(clipById(vid.id).start).toBeCloseTo(3);
  });

  test("removeLaneGap slides a title row and keeps each length", () => {
    const byId = (id: string) => s().overlays.find((o) => o.id === id)!;
    const first = title({ start: 0, end: 1 });
    const late = title({ start: 4, end: 6 });
    const other = title({ start: 4, end: 6, lane: 1 });
    useEditor.setState({ clips: [], overlays: [first, late, other] });
    s().removeLaneGap({ kind: "overlay", index: 0 }, 2);
    expect(byId(late.id).start).toBeCloseTo(1);
    expect(byId(late.id).end).toBeCloseTo(3);
    expect(byId(other.id).start).toBeCloseTo(4);
  });
});

describe("independent resize", () => {
  test("shrinking a clip leaves other items in place", () => {
    const a = vclip({ track: 0, start: 0, out: 4 });
    const b = vclip({ track: 0, start: 4, out: 2 });
    const t = title({ start: 4.5, end: 5.5 });
    const au = aclip({ start: 5, out: 1 });
    const q = cue({ start: 4.2, end: 4.8, words: [{ t0: 4.2, t1: 4.8, w: "hi" }] });
    useEditor.setState({
      clips: [a, b],
      overlays: [t],
      audioClips: [au],
      subtitles: { ...emptySubtitles(), cues: [q] },
    });
    s().setClipTrim(a.id, 0, 3);
    expect(clipById(b.id).start).toBeCloseTo(4);
    expect(s().overlays[0].start).toBeCloseTo(4.5);
    expect(audioById(au.id).start).toBeCloseTo(5);
    expect(s().subtitles.cues[0].start).toBeCloseTo(4.2);
    expect(s().subtitles.cues[0].words![0].t0).toBeCloseTo(4.2);
  });

  test("growing a clip pushes overlapping neighbors on its own row", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 5, out: 2, assetId: av.id }); // a 1s gap before b
    const t = title({ start: 5, end: 6 });
    useEditor.setState({ assets: [av], clips: [a, b], overlays: [t] });
    s().setClipTrim(a.id, 0, 6);
    expect(clipById(b.id).start).toBeCloseTo(6);
    expect(s().overlays[0].start).toBeCloseTo(5);
  });

  test("growing into an abutting neighbor carries it along, never over it", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 2, assetId: av.id }); // butted joint
    const t = title({ start: 4, end: 5 });
    useEditor.setState({ assets: [av], clips: [a, b], overlays: [t] });
    s().setClipTrim(a.id, 0, 6);
    expect(clipById(b.id).start).toBeCloseTo(6);
    expect(s().overlays[0].start).toBeCloseTo(4);
    expectLaneSound(videoLane(0));
  });



  test("an item over the shortened tail keeps its time", () => {
    const a = vclip({ track: 0, start: 0, out: 4 });
    const t = title({ start: 3, end: 5 });
    useEditor.setState({ clips: [a], overlays: [t] });
    s().setClipTrim(a.id, 0, 2);
    expect(s().overlays[0].start).toBeCloseTo(3);
    expect(s().overlays[0].end).toBeCloseTo(5);
  });

  test("with an overlay video track a shrink keeps its own-track rules", () => {
    const a = vclip({ track: 0, start: 0, out: 4 });
    const b = vclip({ track: 0, start: 4, out: 2 });
    const layer = vclip({ track: 1, start: 1, out: 2 });
    useEditor.setState({ clips: [a, b, layer] });
    s().setClipTrim(a.id, 0, 3);
    expect(clipById(b.id).start).toBeCloseTo(4); // the gap stays
    expect(clipById(layer.id).start).toBeCloseTo(1);
  });






});

describe("spine grounding", () => {
  test("deleting the last track-0 clip grounds the layers above it", () => {
    const spine = vclip({ track: 0, start: 0, out: 2 });
    const layer = vclip({ track: 1, start: 2, out: 2 });
    const upper = vclip({ track: 2, start: 2.5, out: 2 });
    useEditor.setState({
      clips: [spine, layer, upper],
      selection: { kind: "clip", id: spine.id },
    });
    s().deleteSelection();
    expect(clipById(layer.id).track).toBe(0);
    expect(clipById(upper.id).track).toBe(1);
  });

});

describe("upper-track transitions", () => {
  test("setClipTransition on an upper track moves nothing", () => {
    const av = asset(4);
    const bv = asset(4);
    const spine = vclip({ track: 0, start: 0, out: 4 });
    const a = vclip({ track: 1, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 1, start: 4, out: 4, assetId: bv.id });
    useEditor.setState({ assets: [av, bv], clips: [spine, a, b] });
    s().setClipTransition(a.id, 1);
    expect(clipById(a.id).transition).toBeCloseTo(1);
    expect(clipById(b.id).start).toBeCloseTo(4); // layout untouched
    expect(clipById(spine.id).start).toBeCloseTo(0);
    // The blend is live at the cut the pair already makes.
    const spans = getClipSpans(s().clips, s().assets, 1);
    expect(spans[0].transitionOut).toBeCloseTo(1);
  });

  test("a transition on a gapped pair stays dormant until they touch", () => {
    const av = asset(4);
    const spine = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const a = vclip({ track: 1, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 1, start: 6, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [spine, a, b] });
    s().setClipTransition(a.id, 1);
    expect(clipById(b.id).start).toBeCloseTo(6); // no gap-closing, no motion
    expect(getClipSpans(s().clips, s().assets, 1)[0].transitionOut).toBe(0);
    s().updateClip(b.id, { start: 4 });
    expect(getClipSpans(s().clips, s().assets, 1)[0].transitionOut).toBeCloseTo(1);
  });

  test("splitting a layer clip leaves the tail's transition with the right half", () => {
    const av = asset(8);
    const spine = vclip({ track: 0, start: 0, out: 12 });
    const a = vclip({ track: 1, start: 0, out: 8, assetId: av.id });
    const c = vclip({ track: 1, start: 8, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [spine, a, c] });
    s().setClipTransition(a.id, 1);
    useEditor.setState({ selection: { kind: "clip", id: a.id } });
    setPlayhead(4);
    s().splitAtPlayhead();
    const halves = s().clips.filter((x) => x.track === 1 && x.id !== c.id);
    expect(halves.length).toBe(2);
    const left = halves.find((x) => x.start === 0)!;
    const right = halves.find((x) => x.start === 4)!;
    // The bar sits at the original tail cut, so the right half plays it and
    // the new mid-footage cut stays plain.
    expect(left.transition).toBeUndefined();
    expect(right.transition).toBe(1);
  });
});

describe("bars and clip edges", () => {
  test("a transition and the far-edge animations live together", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipAnim(a.id, "in", { style: "fade", seconds: 0.5 });
    s().setClipAnim(b.id, "out", { style: "fade", seconds: 0.5 });
    s().setClipTransition(a.id, 0.8, "pushdown");
    expect(clipById(a.id).transition).toBeCloseTo(0.8);
    expect(clipById(a.id).animIn).toEqual({ style: "fade", seconds: 0.5 });
    expect(clipById(b.id).animOut).toEqual({ style: "fade", seconds: 0.5 });
    // The joint has no open edges, so nothing else can play there.
    expect(clipById(a.id).animOut).toBeUndefined();
    expect(clipById(b.id).animIn).toBeUndefined();
  });

  test("clearing a transition leaves the neighbors' animations alone", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipAnim(b.id, "out", { style: "fade", seconds: 0.5 });
    s().setClipTransition(a.id, 0.8);
    s().setClipTransition(a.id, 0);
    expect(clipById(a.id).transition).toBeUndefined();
    expect(clipById(b.id).animOut).toEqual({ style: "fade", seconds: 0.5 });
  });

  test("an entrance picked at a joint parks its bar; the transition keeps playing", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "pushdown");
    expect(clipById(b.id).start).toBeCloseTo(4); // layout never moves
    s().setClipAnim(b.id, "in", { style: "slideleft", seconds: 0.5 });
    // b's head is a cut, so there is no entrance to make: the bar sits on the
    // row inert and the joint's transition plays on.
    expect(clipById(a.id).transition).toBeCloseTo(0.8);
    expect(clipById(b.id).animIn).toBeUndefined();
    expect(s().transitions.length).toBe(2);
  });

  test("an exit picked at a joint retunes the joint's bar", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "circleopen");
    s().setClipAnim(a.id, "out", { style: "fade", seconds: 0.4 });
    // The clip's tail IS the joint, so the pick lands on the same bar: it
    // becomes a 0.4s crossfade there, and no second bar appears.
    expect(clipById(a.id).transition).toBeCloseTo(0.4);
    expect(clipById(a.id).transitionStyle).toBeUndefined();
    expect(clipById(a.id).animOut).toBeUndefined();
    expect(s().transitions.length).toBe(1);
    expect(clipById(b.id).start).toBeCloseTo(4);
  });

  test("a cross dissolve hands over on the audio and leaves the picture cut", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "audiocross");
    const spans = getClipSpans(s().clips, s().assets, 0);
    // The window rides the sound field; every reader of the picture blend
    // sees a plain cut. The handover crosses the cut, so each side ramps over
    // half the declared length.
    expect(spans[0].transitionOut).toBe(0);
    expect(spans[0].soundOut).toBeCloseTo(0.4);
    // Switching the same bar to a picture style moves the window back.
    s().setClipTransition(a.id, 0.8, "crossfade");
    const after = getClipSpans(s().clips, s().assets, 0);
    expect(after[0].transitionOut).toBeCloseTo(0.8);
    expect(after[0].soundOut).toBe(0);
  });

  test("a cross dissolve's bar sits across the cut it plays", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "audiocross");
    // Half the handover either side of the cut, which is where the sound
    // crosses — a picture blend ends on the cut instead.
    expect(s().transitions[0].start).toBeCloseTo(3.6);
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([]);
    s().setClipTransition(a.id, 0.8, "crossfade");
    expect(s().transitions[0].start).toBeCloseTo(3.2);
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([]);
  });

  test("a hidden bar keeps its cut and renders nothing", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "crossfade");
    const bar = s().transitions[0];
    s().updateTransition(bar.id, { hidden: true });
    // The clip fields are what every renderer reads, so hiding has to clear
    // them: the joint plays as a hard cut.
    expect(s().clips[0].transition ?? 0).toBe(0);
    expect(getClipSpans(s().clips, s().assets, 0)[0].transitionOut).toBe(0);
    // It still owns the boundary, so nothing reports it as debris and no
    // other bar can claim the same cut.
    expect(s().transitions).toHaveLength(1);
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([]);
    s().updateTransition(bar.id, { hidden: undefined });
    expect(s().clips[0].transition).toBeCloseTo(0.8);
  });

  test("the transitions row hides and shows every bar at once", () => {
    const av = asset(12);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    const c = vclip({ track: 0, start: 8, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b, c] });
    s().setClipTransition(a.id, 0.8, "crossfade");
    s().setClipTransition(b.id, 0.8, "audiocross");
    s().setTransitionsHidden(true);
    expect(s().transitions.every((t) => t.hidden)).toBe(true);
    const hidden = getClipSpans(s().clips, s().assets, 0);
    expect(hidden[0].transitionOut).toBe(0);
    expect(hidden[1].soundOut).toBe(0);
    s().setTransitionsHidden(false);
    const shown = getClipSpans(s().clips, s().assets, 0);
    expect(shown[0].transitionOut).toBeCloseTo(0.8);
    expect(shown[1].soundOut).toBeCloseTo(0.4);
  });

  test("a hidden bar survives a save", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "crossfade");
    s().updateTransition(s().transitions[0].id, { hidden: true });
    const doc = serializeDoc(useEditor.getState());
    expect(doc.transitions?.[0].hidden).toBe(true);
  });

  test("a cross dissolve reaches into the media each clip was trimmed from", () => {
    const av = asset(8);
    // Both clips are cut out of the middle of an eight-second source, so each
    // has media on either side of its trim for the crossing to reach into.
    const a = vclip({ track: 0, start: 0, in: 1, out: 5, assetId: av.id });
    const b = vclip({ track: 0, start: 4, in: 1, out: 5, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "audiocross");
    const spans = getClipSpans(s().clips, s().assets, 0);
    expect(spans[0].soundOut).toBeCloseTo(0.4);
    expect(spans[0].soundAhead).toBeCloseTo(0.4);
    expect(spans[1].soundBack).toBeCloseTo(0.4);
    // Nothing reaches past a cut with no crossing on it.
    expect(spans[0].soundBack).toBe(0);
    expect(spans[1].soundAhead).toBe(0);
  });

  test("a clip trimmed to its source's edge has no handle to cross with", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "audiocross");
    const spans = getClipSpans(s().clips, s().assets, 0);
    expect(spans[0].soundOut).toBeCloseTo(0.4);
    expect(spans[0].soundAhead).toBe(0);
    expect(spans[1].soundBack).toBe(0);
  });

  test("a sped-up clip's handle is measured in timeline seconds", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, in: 0, out: 4, speed: 2, assetId: av.id });
    const b = vclip({ track: 0, start: 2, in: 4, out: 8, speed: 2, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "audiocross");
    const spans = getClipSpans(s().clips, s().assets, 0);
    // Four source seconds are left past a's out point, which at 2× is two
    // timeline seconds — more than the crossing wants, so it takes its half.
    expect(spans[0].soundAhead).toBeCloseTo(0.4);
    // b starts four source seconds in: two timeline seconds of handle.
    expect(spans[1].soundBack).toBeCloseTo(0.4);
  });

  test("a cross dissolve on an open edge plays nothing", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a] });
    // Dropped on a clip's head there is no next clip's sound to cross into,
    // so it becomes no entrance animation at all.
    const bar = s().addTransition({ start: 0, seconds: 0.6, style: "audiocross" });
    expect(bar).toBeTruthy();
    expect(clipById(a.id).animIn).toBeUndefined();
    expect(clipById(a.id).animOut).toBeUndefined();
  });

  test("a pre-bar doc's clip fields become bars once, and derive back unchanged", () => {
    const av = asset(4);
    const a = vclip({
      track: 0,
      start: 0,
      out: 4,
      assetId: av.id,
      transition: 0.8,
      transitionStyle: "pushleft",
      animIn: { style: "fade", seconds: 0.5 },
    });
    const b = vclip({
      track: 0,
      start: 4,
      out: 4,
      assetId: av.id,
      animOut: { style: "zoom", seconds: 0.6 },
    });
    const bars = adoptTransitionFields([a, b], []);
    expect(bars.length).toBe(3);
    const derived = deriveTransitionFields([a, b], bars);
    const da = derived.find((c) => c.id === a.id)!;
    const db = derived.find((c) => c.id === b.id)!;
    expect(da.transition).toBeCloseTo(0.8);
    expect(da.transitionStyle).toBe("pushleft");
    expect(da.animIn).toEqual({ style: "fade", seconds: 0.5 });
    expect(db.animOut).toEqual({ style: "zoom", seconds: 0.6 });
    // A second load adopts nothing new: every field already has its bar.
    expect(adoptTransitionFields(derived, bars)).toBe(bars);
  });

  test("a pre-bar entrance at a joint becomes that joint's blend", () => {
    // The old model let a clip fade in against the previous clip's held frame.
    // A joint carries one blend now, so the entrance becomes it — no bar is
    // left on the row with nothing to play.
    const a = vclip({ track: 0, start: 0, out: 4 });
    const b = vclip({ track: 0, start: 4, out: 4, animIn: { style: "fade", seconds: 0.5 } });
    const bars = adoptTransitionFields([a, b], []);
    expect(bars.length).toBe(1);
    expect(bars[0].start).toBeCloseTo(3.5);
    const derived = deriveTransitionFields([a, b], bars);
    expect(derived.find((c) => c.id === a.id)!.transition).toBeCloseTo(0.5);
    // The joint's own blend outranks it: nothing extra is adopted.
    const withCut = [{ ...a, transition: 0.8 }, b];
    expect(adoptTransitionFields(withCut, []).length).toBe(1);
  });

  test("a bar is not tied to a clip: the pair separating turns its cut into an exit, and moving further parks it", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "pushdown");
    // The pair separates: the bar stays put, still ends on a's tail — now an
    // open edge — so it plays as a's exit.
    s().updateClipTransient(b.id, { start: 6 });
    expect(clipById(a.id).transition).toBeUndefined();
    expect(clipById(a.id).animOut).toEqual({ style: "slidedown", seconds: 0.8 });
    expect(s().transitions.length).toBe(1);
    // Back together, the cut outranks the exit and the transition returns.
    s().updateClipTransient(b.id, { start: 4 });
    expect(clipById(a.id).transition).toBeCloseTo(0.8);
    expect(clipById(a.id).animOut).toBeUndefined();
    // Both clips gone, the bar survives, aligned with nothing.
    useEditor.setState({ selection: null, multiSelection: [] });
    s().updateClipTransient(a.id, { start: 20 });
    s().updateClipTransient(b.id, { start: 40 });
    expect(s().transitions.length).toBe(1);
    expect(clipById(a.id).transition).toBeUndefined();
  });

  test("a trim leaves independent bars in place and refreshes render fields", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8, "wipeleft");
    s().setClipTrim(a.id, 0, 3);
    expect(clipById(b.id).start).toBeCloseTo(4);
    expect(s().transitions[0].start).toBeCloseTo(3.2);
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([s().transitions[0]]);
    expect(clipById(a.id).transition ?? 0).toBe(0);
  });

  test("a bar lining up with nothing reads as parked, and reanchorBars brings it back", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 6, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    // A blend on a's open tail, the bar ending on 4s.
    s().setClipAnim(a.id, "out", { style: "fade", seconds: 0.8 });
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([]);
    // The clip slides — the move an assistant makes with place_clip — and the
    // bar stays where it was, now lining up with nothing.
    const before = s().clips;
    s().updateClip(a.id, { start: 1 });
    const parked = parkedTransitions(s().clips, s().transitions);
    expect(parked.length).toBe(1);
    expect(parked[0].style).toBe("crossfade");
    expect(clipById(a.id).animOut).toBeUndefined();
    // Carrying the bars through that move lands it back on the edge it
    // played, and the render fields follow.
    s().reanchorBars(before);
    expect(s().transitions[0].start).toBeCloseTo(4.2);
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([]);
    expect(clipById(a.id).animOut).toEqual({ style: "fade", seconds: 0.8 });
  });

  test("a cross dissolve on an open edge reads as parked, not as a live bar", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 6, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    // A cross dissolve straddling a's open tail. It has no picture ramp and
    // nothing to blend into, so it plays nothing and has to say so.
    const id = s().addTransition({ start: 3.6, seconds: 0.8, style: "audiocross" });
    expect(parkedTransitions(s().clips, s().transitions).map((t) => t.id)).toEqual([id]);
    expect(clipById(a.id).animOut).toBeUndefined();
    // The same bar on a real cut plays it, and stops reading as parked:
    // pulling b up to a's tail turns that open edge into a handover.
    s().updateClip(b.id, { start: 4 });
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([]);
    expect(clipById(a.id).transition).toBeCloseTo(0.8);
    expect(clipById(a.id).transitionStyle).toBe("audiocross");
  });

  test("a cross dissolve on an open edge leaves the boundary for a bar that plays it", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a] });
    const sound = s().addTransition({ start: 3.6, seconds: 0.8, style: "audiocross" });
    // A picture bar on the same tail takes the edge the sound bar cannot.
    s().addTransition({ start: 3.2, seconds: 0.8, style: "crossfade" });
    expect(clipById(a.id).animOut).toEqual({ style: "fade", seconds: 0.8 });
    expect(parkedTransitions(s().clips, s().transitions).map((t) => t.id)).toEqual([sound]);
  });

  test("a copied cue pastes onto its caption track at the playhead, words and all", () => {
    const cue: SubtitleCue = {
      id: "q1",
      start: 1,
      end: 2,
      text: "two words",
      words: [
        { t0: 1, t1: 1.4, w: "two" },
        { t0: 1.5, t1: 2, w: "words" },
      ],
    };
    const blocker: SubtitleCue = { id: "q2", start: 5, end: 6, text: "taken" };
    useEditor.setState({
      subtitles: { ...emptySubtitles(), cues: [cue, blocker] },
      selection: { kind: "cue", id: "q1" },
      multiSelection: [],
    });
    expect(s().copySelection()).toBe(true);
    // The playhead sits inside the blocker, so the copy slides past it.
    setPlayhead(5.5);
    expect(s().paste()).toBe(true);
    const cues = s().subtitles.cues;
    expect(cues).toHaveLength(3);
    const pasted = cues.find((c) => c.id !== "q1" && c.id !== "q2")!;
    expect(pasted).toMatchObject({ start: 6, end: 7, text: "two words" });
    expect(pasted.words).toEqual([
      { t0: 6, t1: 6.4, w: "two" },
      { t0: 6.5, t1: 7, w: "words" },
    ]);
    expect(s().selection).toEqual({ kind: "cue", id: pasted.id });
  });

  test("a copied bar pastes at the requested time with its properties", () => {
    const av = asset(12);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    const c = vclip({ track: 0, start: 8, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b, c] });
    s().setClipTransition(a.id, 0.8, "wipeleft");
    const bar = s().transitions[0];
    useEditor.setState({
      selection: { kind: "transition", id: bar.id },
      multiSelection: [{ kind: "transition", id: bar.id }],
    });
    expect(s().copySelection()).toBe(true);
    setPlayhead(7.7); // in reach of the b|c cut at 8
    expect(s().paste()).toBe(true);
    expect(s().transitions.length).toBe(2);
    expect(s().transitions[1]).toMatchObject({ start: 7.7, seconds: 0.8, style: "wipeleft" });
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([s().transitions[1]]);
    expect(s().selection).toEqual({ kind: "transition", id: s().transitions[1].id });
  });

  test("a pasted bar preserves existing bars", () => {
    const av = asset(12);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    const c = vclip({ track: 0, start: 8, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b, c] });
    s().setClipTransition(a.id, 0.8, "wipeleft");
    s().setClipTransition(b.id, 0.4, "crossfade");
    const bar = s().transitions.find((t) => t.style === "wipeleft")!;
    useEditor.setState({
      selection: { kind: "transition", id: bar.id },
      multiSelection: [{ kind: "transition", id: bar.id }],
    });
    s().copySelection();
    setPlayhead(8.2);
    s().paste();
    expect(s().transitions.length).toBe(3);
    expect(clipById(b.id).transition).toBeCloseTo(0.4);
    expect(clipById(b.id).transitionStyle ?? "crossfade").toBe("crossfade");
    expect(s().transitions[2]).toMatchObject({ start: 8.2, seconds: 0.8, style: "wipeleft" });

  });

  test("a bar pasted far from any boundary parks at the playhead", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.6, "dipblack");
    const bar = s().transitions[0];
    useEditor.setState({
      selection: { kind: "transition", id: bar.id },
      multiSelection: [{ kind: "transition", id: bar.id }],
    });
    s().copySelection();
    setPlayhead(6); // 2s from the cuts at 4 and 8
    s().paste();
    expect(s().transitions.length).toBe(2);
    const pasted = s().transitions[1];
    expect(pasted.start).toBeCloseTo(6);
    expect(pasted.style).toBe("dipblack");
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([pasted]);
  });

  test("clips copied with their bar keep the blend on their own cut", () => {
    const av = asset(12);
    const a = vclip({ track: 0, start: 0, out: 3, assetId: av.id });
    const b = vclip({ track: 0, start: 3, out: 3, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.5, "crosszoom");
    const bar = s().transitions[0];
    useEditor.setState({
      selection: { kind: "transition", id: bar.id },
      multiSelection: [
        { kind: "clip", id: a.id },
        { kind: "clip", id: b.id },
        { kind: "transition", id: bar.id },
      ],
    });
    expect(s().copySelection()).toBe(true);
    setPlayhead(8);
    expect(s().paste()).toBe(true);
    const pastedClips = s().clips.filter((x) => x.id !== a.id && x.id !== b.id);
    expect(pastedClips.map((x) => x.start)).toEqual([8, 11]);
    // The bar followed the pair, so the copied cut at 11 plays the same blend.
    expect(pastedClips[0].transition).toBeCloseTo(0.5);
    expect(pastedClips[0].transitionStyle).toBe("crosszoom");
    expect(parkedTransitions(s().clips, s().transitions)).toEqual([]);
  });

  test("paste lands under the skimmer when one is live, sliding clear of the lane", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 3, assetId: av.id });
    useEditor.setState({
      assets: [av],
      clips: [a],
      selection: { kind: "clip", id: a.id },
      multiSelection: [{ kind: "clip", id: a.id }],
    });
    expect(s().copySelection()).toBe(true);
    setPlayhead(10);
    setSkim(5);
    expect(s().paste()).toBe(true);
    // The skimmer wins over the playhead.
    expect(s().clips.map((c) => c.start)).toEqual([0, 5]);
    // A skim into occupied ground slides to the lane's next gap that fits.
    setSkim(1);
    expect(s().paste()).toBe(true);
    expect(s().clips.map((c) => c.start)).toEqual([0, 5, 8]);
    expectLaneSound(videoLane(0));
    // With the pointer off the timeline, the playhead takes over.
    setSkim(null);
    expect(s().paste()).toBe(true);
    expect(s().clips.map((c) => c.start)).toEqual([0, 5, 8, 11]);
  });

  test("an animation on a far edge leaves an unrelated transition alone", () => {
    const av = asset(4);
    const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });
    const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipTransition(a.id, 0.8);
    s().setClipAnim(a.id, "in", { style: "fade", seconds: 0.5 }); // A's entrance, not the joint
    s().setClipAnim(b.id, "out", { style: "fade", seconds: 0.5 }); // B's exit, not the joint
    expect(clipById(a.id).transition).toBeCloseTo(0.8);
    expect(clipById(a.id).animIn).toEqual({ style: "fade", seconds: 0.5 });
    expect(clipById(b.id).animOut).toEqual({ style: "fade", seconds: 0.5 });
  });

  test("tracks cutting at the same instant share one bar, never a stack", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 2, assetId: av.id });
    const b = vclip({ track: 0, start: 2, in: 2, out: 4, assetId: av.id });
    const c = vclip({ track: 1, start: 0, out: 2, assetId: av.id });
    const d = vclip({ track: 1, start: 2, in: 2, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b, c, d] });
    s().setClipTransition(a.id, 0.5);
    s().setClipTransition(c.id, 0.5); // same cut instant on the other track
    expect(s().transitions.length).toBe(1);
    expect(clipById(a.id).transition).toBeCloseTo(0.5);
    expect(clipById(c.id).transition).toBeCloseTo(0.5);
    // Retiming through the same calls updates that one bar in place.
    s().setClipTransition(a.id, 0.4);
    s().setClipTransition(c.id, 0.4);
    expect(s().transitions.length).toBe(1);
    expect(s().transitions[0].seconds).toBeCloseTo(0.4);
  });

  test("simultaneous entrances on several tracks ride one bar", () => {
    const av = asset(8);
    const a = vclip({ track: 1, start: 1, in: 1, out: 3, assetId: av.id });
    const b = vclip({ track: 2, start: 1, in: 1, out: 3, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b] });
    s().setClipAnim(a.id, "in", { style: "zoom", seconds: 0.3 });
    s().setClipAnim(b.id, "in", { style: "zoom", seconds: 0.3 });
    expect(s().transitions.length).toBe(1);
    expect(clipById(a.id).animIn).toEqual({ style: "zoom", seconds: 0.3 });
    expect(clipById(b.id).animIn).toEqual({ style: "zoom", seconds: 0.3 });
  });

  test("deleting a clip leaves ungrouped parked bars", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 2, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a] });
    // A parked twin sitting exactly on the clip's tail, playing nothing.
    s().addTransition({ start: 1.7, seconds: 0.3, style: "crosszoom" });
    s().addTransition({ start: 1.7, seconds: 0.3, style: "crosszoom" });
    expect(s().transitions.length).toBe(2);
    s().select({ kind: "clip", id: a.id });
    s().deleteSelection();
    expect(s().clips.length).toBe(0);
    expect(s().transitions.length).toBe(2);
  });

  test("a shared bar survives while one of its clips does", () => {
    const av = asset(8);
    const a = vclip({ track: 0, start: 0, out: 2, assetId: av.id });
    const b = vclip({ track: 0, start: 2, in: 2, out: 4, assetId: av.id });
    const c = vclip({ track: 1, start: 0, out: 2, assetId: av.id });
    const d = vclip({ track: 1, start: 2, in: 2, out: 4, assetId: av.id });
    useEditor.setState({ assets: [av], clips: [a, b, c, d] });
    s().setClipTransition(a.id, 0.5);
    expect(s().transitions.length).toBe(1);
    // Track 1's pair goes; the bar still plays track 0's cut.
    useEditor.setState({ multiSelection: [{ kind: "clip", id: c.id }, { kind: "clip", id: d.id }] });
    s().deleteSelection();
    expect(s().transitions.length).toBe(1);
    expect(clipById(a.id).transition).toBeCloseTo(0.5);
  });
});

describe("generated-scene placement (placeInRun)", () => {
  const span = (id: string, start: number, end: number) => ({ id, start, end });

  test("with no run neighbors it slides right past residents", () => {
    const { start, shifts } = placeInRun([span("u1", 0, 4)], 2, 3, new Set());
    expect(start).toBeCloseTo(4);
    expect(shifts).toEqual([]);
  });

  test("never slides past a later shot's clip — pushes it right instead", () => {
    const row = [span("u1", 0, 4), span("s2", 4, 8), span("u2", 8, 10)];
    const { start, shifts } = placeInRun(row, 0, 4, new Set(["s2"]));
    expect(start).toBeCloseTo(4); // slid clear of the resident, not past s2
    // s2 and everything after it open the slot as one run.
    expect(shifts).toEqual([
      { id: "s2", start: 8 },
      { id: "u2", start: 12 },
    ]);
  });

  test("out-of-order landings assemble gapless in shot order on an empty track", () => {
    const row: { id: string; start: number; end: number }[] = [];
    const p3 = placeInRun(row, 15, 5, new Set());
    row.push(span("s3", p3.start, p3.start + 5));
    const p1 = placeInRun(row, 0, 8, new Set(["s3"]));
    expect(p1.start).toBeCloseTo(0);
    expect(p1.shifts).toEqual([]);
    row.push(span("s1", 0, 8));
    const p2 = placeInRun(row, 8, 7, new Set(["s3"])); // want = live end of s1
    expect(p2.start).toBeCloseTo(8);
    expect(p2.shifts).toEqual([]);
  });

  test("placeGenClip anchors after the run's earlier clip when the plan's frames are stale", () => {
    const av = asset(4);
    const user = vclip({ start: 0, out: 4, assetId: "x" });
    const s1 = vclip({ start: 4, out: 4, assetId: "x" });
    useEditor.setState({ assets: [av], clips: [user, s1] });
    // Planned [4, 8) went stale when the user's clip pushed the run to 4..8.
    const id = s().placeGenClip(av.id, 4, 8, { anchorAfterIds: [s1.id] })!;
    expect(clipById(id).start).toBeCloseTo(8);
    expectLaneSound(videoLane(0));
  });

  test("placeGenClip pushes a later shot's clip instead of landing on or past it", () => {
    const av = asset(4);
    const user = vclip({ start: 0, out: 4, assetId: "x" });
    const s2 = vclip({ start: 4, out: 4, assetId: "x" });
    useEditor.setState({ assets: [av], clips: [user, s2] });
    const id = s().placeGenClip(av.id, 0, 4, { followClipIds: [s2.id] })!;
    expect(clipById(id).start).toBeCloseTo(4); // after the resident
    expect(clipById(s2.id).start).toBeCloseTo(8); // pushed, still after the new take
    expectLaneSound(videoLane(0));
  });

  test("placeGenAudio slides to its lane's next free slot", () => {
    const aa = asset(4, "audio");
    const resident = aclip({ start: 0, out: 4, assetId: "x" });
    useEditor.setState({ assets: [aa], audioClips: [resident] });
    const id = s().placeGenAudio(aa.id, 1, 4)!;
    expect(audioById(id).start).toBeCloseTo(4);
  });
});

describe("overlay row order", () => {
  const fx = (id: string, start: number, end: number, lane = 0) =>
    ({ id, kind: "effect", effect: "blur", start, end, x: 0.5, y: 0.5, lane }) as unknown as TextOverlay;

  test("rows read in lane order, so a dragged element stays where it was put", () => {
    expect(overlayLaneOrder([title({ lane: 2 }), fx("e1", 0, 2, 0), title({ lane: 1 })])).toEqual([
      0, 1, 2,
    ]);
    // An effect dragged below a title keeps that row: nothing about a kind
    // reorders the band.
    expect(overlayLaneOrder([title({ lane: 0 }), fx("e2", 0, 2, 1)])).toEqual([0, 1]);
  });

  test("loading repairs a shared row and leaves a sound one alone", () => {
    // One shared row: the effect lifts off it and the rows renumber to how
    // they show — the effect on top, the title under it.
    const out = normalizeElementLanes([title({ lane: 0 }), fx("e1", 0, 2)]);
    expect(out.map((o) => o.lane)).toEqual([1, 0]);
    // Two effects overlapping in time cannot share a row, so they take two.
    const pair = normalizeElementLanes([title({ lane: 0 }), fx("e3", 0, 2), fx("e4", 1, 3)]);
    expect(pair.map((o) => o.lane)).toEqual([2, 0, 1]);
    // An effect dragged below a title and saved comes back below it: no
    // shared row, so the load has nothing to repair.
    const dragged = [title({ lane: 0 }), fx("e2", 0, 2, 1)];
    expect(normalizeElementLanes(dragged)).toBe(dragged);
  });

  test("a saved clip look opens as an effect covering that clip", () => {
    const a = asset(4);
    const c1 = vclip({ start: 0, out: 4, assetId: a.id, look: "noir" });
    const c2 = vclip({ start: 4, out: 4, assetId: a.id });
    const spans = [
      { clip: c1, start: 0, len: 4 },
      { clip: c2, start: 4, len: 4 },
    ];
    const out = liftClipLooks([c1, c2], [title({ lane: 0 })], spans)!;
    // The grade covers exactly the clip it graded, on the row above the title.
    const fx = out.overlays.find((o) => o.kind === "effect")!;
    expect([fx.effect, fx.start, fx.end, fx.lane]).toEqual(["noir", 0, 4, 0]);
    expect(out.overlays.find((o) => (o.kind ?? "text") === "text")!.lane).toBe(1);
    // …and the clip no longer carries it, so nothing grades twice.
    expect(out.clips[0].look).toBeUndefined();
    // A doc with no looks is left alone.
    expect(liftClipLooks([c2], [], spans)).toBe(null);
  });

  test("a look saved at full strength lifts at full strength", () => {
    // The old store left lookAmount off at full strength, and an effect with
    // no amount is half — so the lift has to say it.
    const a = asset(4);
    const c = vclip({ start: 0, out: 4, assetId: a.id, look: "noir" });
    const out = liftClipLooks([c], [], [{ clip: c, start: 0, len: 4 }])!;
    expect(out.overlays.find((o) => o.kind === "effect")!.amount).toBe(1);
  });

  test("a graded layer clip keeps its look, which grades that layer alone", () => {
    const a = asset(4);
    const spine = vclip({ track: 0, start: 0, out: 4, assetId: a.id, look: "noir" });
    const layer = vclip({ track: 1, start: 0, out: 2, assetId: a.id, look: "vintage" });
    const out = liftClipLooks([spine, layer], [], [{ clip: spine, start: 0, len: 4 }])!;
    expect(out.overlays.filter((o) => o.kind === "effect").length).toBe(1);
    expect(out.clips.find((c) => c.id === spine.id)!.look).toBeUndefined();
    expect(out.clips.find((c) => c.id === layer.id)!.look).toBe("vintage");
  });

  test("an added effect opens the top row, and later ones join it", () => {
    useEditor.setState({ overlays: [title({ lane: 0 })] });
    s().addEffect("blur");
    const held = useEditor.getState().overlays;
    expect(held.find((o) => o.kind === "effect")!.lane).toBe(0);
    expect(held.find((o) => (o.kind ?? "text") === "text")!.lane).toBe(1); // pushed down a row
    s().addEffect("grain");
    const effectLanes = useEditor
      .getState()
      .overlays.filter((o) => o.kind === "effect")
      .map((o) => o.lane);
    expect(effectLanes).toEqual([0, 0]);
  });

  test("a title added onto an effects-only project takes the row below", () => {
    useEditor.setState({ overlays: [] });
    s().addEffect("blur");
    s().addOverlay();
    const text = useEditor.getState().overlays.find((o) => (o.kind ?? "text") === "text")!;
    expect(text.lane).toBe(1);
    expect(overlayLaneOrder(useEditor.getState().overlays)).toEqual([0, 1]);
  });
});

describe("transcribe spec", () => {
  test("mutes a still on track 0, which has no sound to read", () => {
    const video = asset(6);
    const still = { ...asset(0, "image"), fileName: "frame-0m55s.png" };
    const spec = cutTranscribeSpec({
      clips: [
        vclip({ assetId: still.id, start: 0, in: 0, out: 0.2 }),
        vclip({ assetId: video.id, start: 0.2, in: 0, out: 4 }),
      ],
      assets: [video, still],
      audioClips: [],
      overlays: [],
    })!;
    expect(spec.clips.find((c) => c.file === still.fileName)?.muted).toBe(true);
    expect(spec.clips.find((c) => c.file === video.fileName)?.muted).toBe(false);
  });

  test("a curved clip ships its curve, so the mix lays it at the length it plays", () => {
    const video = asset(6);
    const clip = vclip({ assetId: video.id, start: 0, in: 0, out: 4, speedCurve: [[0, 0.5], [4, 0.5]] });
    const spec = cutTranscribeSpec({
      clips: [clip],
      assets: [video],
      audioClips: [],
      overlays: [],
    })!;
    expect(spec.clips[0].speedCurve).toEqual([[0, 0.5], [4, 0.5]]);
    expect(spec.duration).toBeCloseTo(8, 3);
  });

  test("leaves a still on an upper track out of the audio items", () => {
    const video = asset(6);
    const still = { ...asset(0, "image"), fileName: "still.png" };
    const spec = cutTranscribeSpec({
      clips: [
        vclip({ assetId: video.id, start: 0, in: 0, out: 4 }),
        vclip({ assetId: still.id, track: 1, start: 0, in: 0, out: 2 }),
      ],
      assets: [video, still],
      audioClips: [],
      overlays: [],
    })!;
    expect(spec.audio.some((a) => a.file === still.fileName)).toBe(false);
  });
});

describe("assetIdsInUse", () => {
  const clip = (id: string, extra: Partial<VideoClip> = {}) =>
    ({ id, assetId: id, track: 0, start: 0, in: 0, out: 1, ...extra }) as VideoClip;

  test("counts what a clip names and what its removal names", () => {
    const used = assetIdsInUse({
      clips: [clip("v1", { removal: { matte: { assetId: "m1" }, backdrop: { assetId: "b1" } } } as Partial<VideoClip>)],
      audioClips: [{ id: "a1", assetId: "snd" } as AudioClip],
      overlays: [],
    });
    expect([...used].sort()).toEqual(["b1", "m1", "snd", "v1"]);
  });

  test("counts a sticker's picture and an uploaded font, and neither built-in", () => {
    // A chat-made image placed as a sticker, and a chat-made font a title is
    // set in, are both still needed by a document no clip points at.
    const used = assetIdsInUse({
      clips: [],
      audioClips: [],
      overlays: [
        { id: "o1", kind: "sticker", assetId: "pic" } as unknown as TextOverlay,
        { id: "o2", kind: "text", font: uploadedFontId("fnt") } as unknown as TextOverlay,
        { id: "o3", kind: "text", font: "inter" } as unknown as TextOverlay,
      ],
      subtitles: { font: uploadedFontId("capfnt") },
    });
    expect([...used].sort()).toEqual(["capfnt", "fnt", "pic"]);
  });

  test("says nothing is in use for an empty document", () => {
    expect(assetIdsInUse({ clips: [], audioClips: [], overlays: [] }).size).toBe(0);
  });
});

describe("speed curves", () => {
  test("a curve that lengthens a track-0 clip pushes the run behind it", () => {
    const a = asset(4);
    const c1 = vclip({ assetId: a.id, start: 0, in: 0, out: 2 });
    const c2 = vclip({ assetId: a.id, start: 2, in: 0, out: 2 });
    useEditor.setState({ assets: [a], clips: [c1, c2] });
    useEditor.getState().setClipSpeedCurve(c1.id, [
      [0, 0.5],
      [2, 0.5],
    ]);
    const s = useEditor.getState();
    expect(clipLen(s.clips[0])).toBeCloseTo(4, 3);
    expect(s.clips[1].start).toBeCloseTo(4, 3);
    // Leaving curve mode keeps the length as a uniform rate.
    useEditor.getState().setClipSpeedCurve(c1.id, undefined);
    const t = useEditor.getState();
    expect(t.clips[0].speedCurve).toBeUndefined();
    expect(t.clips[0].speed).toBeCloseTo(0.5, 3);
    expect(t.clips[1].start).toBeCloseTo(4, 3);
  });

  test("a crossing's handles read the rate at their own edge", () => {
    const a = asset(10);
    // Trimmed the same distance from both ends, so an edge picked by the
    // amount of source left would read the wrong one.
    const c1 = vclip({
      assetId: a.id,
      start: 0,
      in: 2,
      out: 8,
      speedCurve: [[2, 1], [8, 4]],
    });
    // The next clip abuts, so there is a cut for the crossing to play on.
    const c2 = vclip({ assetId: a.id, start: clipLen(c1), in: 2, out: 8 });
    useEditor.setState({ assets: [a], clips: [c1, c2] });
    useEditor.getState().setClipTransition(c1.id, 1.4, "audiocross");
    const s = useEditor.getState();
    const [sp] = getClipSpans(s.clips, s.assets);
    // Two source seconds past the out point, played at the tail's 4x: half a
    // timeline second, short of the 0.7 the crossing wanted.
    expect(sp.soundAhead).toBeCloseTo(0.5, 3);
  });

  test("a picked speed node that is gone leaves the clip's pose keys alone", () => {
    const a = asset(4);
    const c1 = vclip({
      assetId: a.id,
      start: 0,
      in: 0,
      out: 2,
      kf: [{ t: 1, x: 0.5, y: 0.5, scale: 1.2, rotation: 0, opacity: 1 }],
    });
    useEditor.setState({
      assets: [a],
      clips: [c1],
      selection: { kind: "clip", id: c1.id },
      // The strip left this behind; the clip carries no curve any more.
      selectedKey: { kind: "clip", id: c1.id, t: 1, track: "speed" },
    });
    useEditor.getState().deleteSelection();
    const s = useEditor.getState();
    expect(s.clips).toHaveLength(1);
    expect(s.clips[0].kf).toHaveLength(1);
  });

  test("Delete takes a picked node, never the clip", () => {
    const a = asset(4);
    const c1 = vclip({ assetId: a.id, start: 0, in: 0, out: 2, speedCurve: [[0, 1], [1, 2], [2, 1]] });
    useEditor.setState({
      assets: [a],
      clips: [c1],
      selection: { kind: "clip", id: c1.id },
      selectedKey: { kind: "clip", id: c1.id, t: 1, track: "speed" },
    });
    useEditor.getState().deleteSelection();
    const s = useEditor.getState();
    expect(s.clips).toHaveLength(1);
    expect(s.clips[0].speedCurve?.map((n) => n[0])).toEqual([0, 2]);
  });
});

describe("repairAssetDuration", () => {
  test("gives an unmeasured video its length and opens its zero-length clips to the footage", () => {
    const a = asset(0);
    const other = asset(4);
    useEditor.setState({
      assets: [a, other],
      clips: [
        vclip({ id: "empty", assetId: a.id, start: 0, in: 0, out: 0 }),
        vclip({ id: "next", assetId: other.id, start: 3, in: 0, out: 2 }),
        vclip({ id: "upper", assetId: a.id, track: 1, start: 0, in: 0, out: 0 }),
      ],
    });
    s().repairAssetDuration(a.id, { duration: 10, width: 1080, height: 1920 });
    const repaired = s().assets.find((x) => x.id === a.id)!;
    expect(repaired.duration).toBe(10);
    expect(repaired.width).toBe(1080);
    expect(repaired.height).toBe(1920);
    // Held short of the next clip on track 0; the whole footage on an open track.
    expect(clipById("empty").out).toBe(3);
    expect(clipById("upper").out).toBe(10);
    expect(clipById("next").out).toBe(2);
    expectLaneSound(videoLane(0));
  });

  test("leaves a measured asset and its clips alone", () => {
    const a = asset(4);
    useEditor.setState({ assets: [a], clips: [vclip({ id: "c", assetId: a.id, out: 2 })] });
    s().repairAssetDuration(a.id, { duration: 10 });
    expect(s().assets[0].duration).toBe(4);
    expect(clipById("c").out).toBe(2);
  });
});

for (const outcome of ["document", "deleted", "network error"] as const) {
  test(`a superseded load cannot change the next project after ${outcome}`, async () => {
    const { engineGateOpen } = await import("./api");
    engineGateOpen();
    const originalFetch = globalThis.fetch;
    let finish!: (response: Response) => void;
    let fail!: (error: Error) => void;
    let started!: () => void;
    const ready = new Promise<void>((resolve) => { started = resolve; });
    const doc = { name: "Old project", assets: [], clips: [], audioClips: [], overlays: [] };
    globalThis.fetch = (async (url: string | URL | Request) => {
      if (String(url).includes("/projects/old-project")) {
        started();
        return new Promise<Response>((resolve, reject) => { finish = resolve; fail = reject; });
      }
      return Response.json({});
    }) as typeof fetch;
    try {
      const pending = s().loadProject("old-project", { inPlace: true });
      await ready;
      await s().openProjectDoc("next-project", { name: "Next project" }, []);
      if (outcome === "network error") fail(new Error("Disconnected"));
      else finish(Response.json(doc, { status: outcome === "deleted" ? 404 : 200 }));
      await pending;
      expect(s().projectId).toBe("next-project");
      expect(s().projectName).toBe("Next project");
      expect(s().loaded).toBe(true);
      expect(s().loadError).toBeNull();
    } finally {
      globalThis.fetch = originalFetch;
    }
  });
}

test("closing a project invalidates its pending load and releases its editor identity", async () => {
  const { engineGateOpen } = await import("./api");
  engineGateOpen();
  const originalFetch = globalThis.fetch;
  let finish!: (response: Response) => void;
  let started!: () => void;
  const ready = new Promise<void>((resolve) => { started = resolve; });
  globalThis.fetch = (async (url: string | URL | Request) => {
    if (String(url).includes("/projects/closing-project")) {
      started();
      return new Promise<Response>((resolve) => { finish = resolve; });
    }
    return Response.json({});
  }) as typeof fetch;
  try {
    const pending = s().loadProject("closing-project", { inPlace: true });
    await ready;
    s().closeProject("closing-project");
    finish(Response.json({ name: "Closed project", assets: [], clips: [], audioClips: [], overlays: [] }));
    await pending;
    expect(s().projectId).toBeNull();
    expect(s().loaded).toBe(false);
  } finally { globalThis.fetch = originalFetch; }
});


describe("explicit timeline groups", () => {
  function setup(): NonNullable<Selection>[] {
    const av = asset(30);
    useEditor.setState({
      assets: [av],
      clips: [vclip({ id: "v", assetId: av.id, start: 2, out: 8 })],
      audioClips: [aclip({ id: "a", assetId: av.id, start: 3 })],
      overlays: [title({ id: "text", start: 4, end: 6 }), { id: "rect", kind: "shape", shape: "rect", x: 0.5, y: 0.5, w: 0.5, h: 0.5, fill: "#fff", start: 4, end: 6, lane: 1 }],
      transitions: [{ id: "bar", start: 9, seconds: 1, style: "crossfade" }],
      subtitles: { ...emptySubtitles(), cues: [cue({ id: "cue", start: 5, end: 6, words: [{ w: "hi", t0: 5, t1: 6 }] })] },
    });
    return [{ kind: "clip", id: "v" }, { kind: "audio", id: "a" }, { kind: "overlay", id: "text" }, { kind: "overlay", id: "rect" }, { kind: "cue", id: "cue" }, { kind: "transition", id: "bar" }];
  }
  function grouped() {
    const members = setup();
    s().setMultiSelection(members);
    expect(s().groupSelection()).toBeTruthy();
    return members;
  }

  test("new and loaded overlays stay independent when the underlying video moves", () => {
    const members = setup();
    for (const member of members) expect(timelineItem(s(), member)?.groupId).toBeUndefined();
    // A saved attachment from an earlier build has no behavioral effect.
    const doc = JSON.parse(JSON.stringify(serializeDoc(s())));
    doc.overlays[0].hostClipId = "v";
    const loaded = normalizeDocState(doc, s().assets);
    useEditor.setState({ ...loaded, aspect: loaded.aspect ?? s().aspect });
    s().updateClip("v", { start: 15 });
    expect(s().overlays.map((o) => [o.start, o.end])).toEqual([[4, 6], [4, 6]]);
  });

  test("every member selects and starts a drag with the complete mixed group", () => {
    const members = grouped();
    for (const member of members) {
      s().select(null);
      const drag = selectedMembers(s(), member.kind === "clip" ? "video" : member.kind, member.id);
      expect(drag?.members).toHaveLength(members.length);
      s().select(member);
      expect(s().multiSelection).toHaveLength(members.length);
      expect(s().selection).toEqual(member);
    }
    s().toggleSelect(members[0]);
    expect(s().multiSelection).toHaveLength(0);
    s().toggleSelect(members[5]);
    expect(s().multiSelection).toHaveLength(members.length);
  });

  test("moving a mixed group preserves offsets and caption words, with one undo", () => {
    const members = grouped();
    s().select(members[5]);
    expect(s().moveTimelineSelection(10)).toBe(10);
    expect(members.map((sel) => timelineItem(s(), sel)?.start)).toEqual([12, 13, 14, 14, 15, 19]);
    expect(s().subtitles.cues[0].words).toEqual([{ w: "hi", t0: 15, t1: 16 }]);
    s().undo();
    expect(members.map((sel) => timelineItem(s(), sel)?.start)).toEqual([2, 3, 4, 4, 5, 9]);
    s().redo();
    expect(s().transitions[0].start).toBe(19);
  });

  test("a real pointer gesture from a video or transition moves every member once", () => {
    const saved = new Map(["window", "document", "requestAnimationFrame", "cancelAnimationFrame"].map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
    try {
      const events = new EventTarget();
      Object.defineProperty(globalThis, "window", { configurable: true, value: events });
      Object.defineProperty(globalThis, "document", { configurable: true, value: { activeElement: null } });
      Object.defineProperty(globalThis, "requestAnimationFrame", { configurable: true, value: () => 1 });
      Object.defineProperty(globalThis, "cancelAnimationFrame", { configurable: true, value: () => {} });
      for (const kind of ["video", "transition"] as const) {
        const members = grouped();
        s().select(null);
        const target = { getBoundingClientRect: () => ({ left: 0 }), closest: () => null };
        const down = { button: 0, clientX: 0, clientY: 0, metaKey: false, ctrlKey: false, shiftKey: false, currentTarget: target, preventDefault() {}, stopPropagation() {} } as unknown as React.PointerEvent;
        const ui = { pps: 10, homeRow: 0, rows: () => [], onSnap: () => {}, onDrag: () => {} };
        startLaneMove(down, kind, kind === "transition" ? "bar" : "v", ui);
        for (const type of ["pointermove", "pointerup"]) {
          events.dispatchEvent(Object.assign(new Event(type), { clientX: 100, clientY: 0, metaKey: true, ctrlKey: true }));
        }
        expect(members.map((sel) => timelineItem(s(), sel)?.start)).toEqual([12, 13, 14, 14, 15, 19]);
        expect(s().subtitles.cues[0].words).toEqual([{ w: "hi", t0: 15, t1: 16 }]);
        s().undo();
        expect(s().transitions[0].start).toBe(9);
      }
    } finally {
      for (const [key, descriptor] of saved) {
        if (descriptor) Object.defineProperty(globalThis, key, descriptor);
        else Reflect.deleteProperty(globalThis, key);
      }
    }
  });

  test("chat selects, groups, moves and ungroups every timeline kind", async () => {
    const members = setup();
    for (const [i, member] of members.entries()) await runAiTool("select", { ...member, additive: i > 0 });
    await runAiTool("group_items", {});
    await runAiTool("select", members[5]);
    expect(s().multiSelection).toHaveLength(6);
    await runAiTool("move_timeline_selection", { delta: 10 });
    expect(s().transitions[0].start).toBe(19);
    await runAiTool("ungroup_items", {});
    await runAiTool("select", members[5]);
    expect(s().multiSelection).toHaveLength(1);
  });

  test("chat reorder carries every group member and caption words in one undo step", async () => {
    const members = grouped();
    useEditor.setState({ clips: [...s().clips, vclip({ id: "tail", start: 12, out: 2 })] });
    const before = members.map((member) => timelineItem(s(), member)?.start);
    const groupId = s().clips[0].groupId;
    await runAiTool("move_clip", { clipId: "v", toIndex: 1 });
    expect(members.map((member) => timelineItem(s(), member)?.start)).toEqual([14, 15, 16, 16, 17, 21]);
    expect(s().subtitles.cues[0].words).toEqual([{ w: "hi", t0: 17, t1: 18 }]);
    expect(clipById("tail").start).toBe(12);
    for (const member of members) expect(timelineItem(s(), member)?.groupId).toBe(groupId);
    s().undo();
    expect(members.map((member) => timelineItem(s(), member)?.start)).toEqual(before);
    expect(clipById("tail").start).toBe(12);
    s().redo();
    expect(s().subtitles.cues[0].start).toBe(17);
  });

  test("reordering earlier carries displaced groups and leaves independent items in place", async () => {
    const members = grouped();
    useEditor.setState({
      clips: [...s().clips, vclip({ id: "tail", start: 12, out: 2 })],
      overlays: [...s().overlays, title({ id: "independent", start: 20, end: 22 })],
    });
    await runAiTool("move_clip", { clipId: "tail", toIndex: 0 });
    expect(clipById("tail").start).toBe(2);
    expect(members.map((member) => timelineItem(s(), member)?.start)).toEqual([4, 5, 6, 6, 7, 11]);
    expect(s().subtitles.cues[0].words).toEqual([{ w: "hi", t0: 7, t1: 8 }]);
    expect(s().overlays.find((o) => o.id === "independent")?.start).toBe(20);
    s().undo();
    expect(clipById("tail").start).toBe(12);
    expect(members.map((member) => timelineItem(s(), member)?.start)).toEqual([2, 3, 4, 4, 5, 9]);
  });

  test("reorder respects occupied member rows and keeps groups above zero", async () => {
    useEditor.setState({
      clips: [vclip({ id: "first", start: 0 }), vclip({ id: "moving", start: 4, groupId: "group" })],
      subtitles: { ...emptySubtitles(), cues: [
        cue({ id: "blocker", start: 0, end: 3 }),
        cue({ id: "caption", start: 3, end: 5, groupId: "group", words: [{ w: "hi", t0: 3, t1: 4 }] }),
      ] },
    });
    await runAiTool("move_clip", { clipId: "moving", toIndex: 0 });
    expect(clipById("moving").start).toBe(4);
    expect(clipById("first").start).toBe(6);
    expect(s().subtitles.cues.map((c) => [c.start, c.end])).toEqual([[0, 3], [3, 5]]);
    expectLaneSound(videoLane(0));
  });

  test("reorder reserves room for multiple video members in one group", async () => {
    useEditor.setState({ clips: [
      vclip({ id: "first", start: 0 }),
      vclip({ id: "moving", start: 4, groupId: "group" }),
      vclip({ id: "second-member", start: 8, groupId: "group" }),
    ] });
    await runAiTool("move_clip", { clipId: "moving", toIndex: 0 });
    expect(clipById("moving").start).toBe(0);
    expect(clipById("second-member").start).toBe(4);
    expect(clipById("first").start).toBe(6);
    expectLaneSound(videoLane(0));
  });

  test("reordering within a group leaves its timing intact", () => {
    const clips = [
      vclip({ id: "first-member", start: 4, groupId: "group" }),
      vclip({ id: "second-member", start: 8, groupId: "group" }),
    ];
    useEditor.setState({ clips });
    s().moveClip("first-member", 1);
    expect(s().clips).toBe(clips);
  });

  test("ungroup leaves every member in place and makes each independently selectable", () => {
    const members = grouped();
    s().ungroupSelection();
    for (const member of members) {
      expect(timelineItem(s(), member)?.groupId).toBeUndefined();
      s().select(member);
      expect(s().multiSelection).toEqual([member]);
    }
    expect(members.map((sel) => timelineItem(s(), sel)?.start)).toEqual([2, 3, 4, 4, 5, 9]);
    s().undo();
    expect(expandTimelineGroups(s(), [members[0]])).toHaveLength(6);
  });

  test("a grouped move stops the entire set at zero and avoids occupied rows", () => {
    const members = grouped();
    expect(s().moveTimelineSelection(-10)).toBe(-2);
    expect(members.map((sel) => timelineItem(s(), sel)?.start)).toEqual([0, 1, 2, 2, 3, 7]);
    useEditor.setState({ overlays: [...s().overlays, title({ id: "other", start: 12, end: 14 })] });
    expect(s().moveTimelineSelection(10)).toBe(12);
    expect(s().overlays.find((o) => o.id === "other")?.start).toBe(12);
    expect(s().overlays.find((o) => o.id === "text")?.start).toBe(14);
  });

  test("copy and paste preserve all offsets with a fresh shared group id", () => {
    const members = grouped();
    const originalGroup = timelineItem(s(), members[0])?.groupId;
    expect(s().copySelection()).toBe(true);
    setPlayhead(15);
    expect(s().paste()).toBe(true);
    const copies = s().multiSelection.filter((sel): sel is NonNullable<Selection> => !!sel);
    expect(copies.map((sel) => timelineItem(s(), sel)?.start)).toEqual([15, 16, 17, 17, 18, 22]);
    const ids = new Set(copies.map((sel) => timelineItem(s(), sel)?.groupId));
    expect(ids.size).toBe(1);
    expect(ids.has(originalGroup)).toBe(false);
    expect(ids.has(undefined)).toBe(false);
    s().select(copies[5]);
    expect(s().multiSelection).toHaveLength(6);
  });

  test("saving and reloading preserves every group member, including transitions", () => {
    const members = grouped();
    const loaded = normalizeDocState(serializeDoc(s()), s().assets);
    useEditor.setState({ ...loaded, aspect: loaded.aspect ?? s().aspect });
    for (const member of members) expect(expandTimelineGroups(s(), [member])).toHaveLength(6);
  });

  test("templates carry all group members and remap their group together on insertion", () => {
    grouped();
    const template = s().selectionTemplate()!;
    expect(template.transitions).toHaveLength(1);
    const original = s().clips[0].groupId;
    const assetId = s().assets[0].id;
    useEditor.setState({ clips: [], overlays: [], audioClips: [], transitions: [], subtitles: emptySubtitles() });
    s().insertTemplate({ ...template, id: "template", addedAt: 0 }, [assetId], 0);
    const group = s().clips[0].groupId;
    expect(group).toBeTruthy();
    expect(group).not.toBe(original);
    expect(expandTimelineGroups(s(), [{ kind: "transition", id: s().transitions[0].id }])).toHaveLength(6);
  });

  test("regrouping merges complete groups without leaving former members behind", () => {
    const members = grouped();
    useEditor.setState({ overlays: [...s().overlays, title({ id: "extra", start: 20, end: 22 })] });
    s().setMultiSelection([members[0], { kind: "overlay", id: "extra" }]);
    s().groupSelection();
    expect(expandTimelineGroups(s(), [members[5]])).toHaveLength(7);
  });
});