Skip to content

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

feat(audio): one voiceover row, one music row, through a single door

EtienneLescot521d0bd9dfe7
diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts
index 18ed32437..469b5d313 100644
--- a/electron/ai-edition/agent-tools.ts
+++ b/electron/ai-edition/agent-tools.ts
@@ -17,9 +17,9 @@
import { z } from "zod";
import {
- anchorAudioTrackFragments,
collapseTracksToPills,
patchAudioTrack,
+ placeAudioTrackInDocument,
trackGroupId,
} from "../../src/lib/ai-edition/document/audioTracks";
import { createId } from "../../src/lib/ai-edition/document/ids";
@@ -2049,7 +2049,8 @@ export function executeAgentTool(
const startMs = toMs(Math.min(startSec, endSec));
const endMs = toMs(Math.max(startSec, endSec));
const trackId = createId("audio");
- const placed = anchorAudioTrackFragments(
+ const withTrack = placeAudioTrackInDocument(
+ document,
{
id: trackId,
trackId,
@@ -2067,16 +2068,14 @@ export function executeAgentTool(
label: asset.label,
origin: "agent",
} as AxcutDocument["audioTracks"][number],
- document.timeline.clips,
() => createId("audio"),
+ "create",
);
- if (placed.length === 0) {
+ if (withTrack === document) {
return coversNoClip("audio", startMs / 1000, endMs / 1000, document);
}
- const next: AxcutDocument = {
- ...document,
- audioTracks: [...document.audioTracks, ...placed],
- };
+ const placed = withTrack.audioTracks.filter((t) => trackGroupId(t) === trackId);
+ const next: AxcutDocument = withTrack;
const landing = landingOf(placed, document);
return {
ok: true,
@@ -2131,7 +2130,11 @@ export function executeAgentTool(
const current =
collapseTracksToPills(next.audioTracks).find((t) => trackGroupId(t) === audioId) ?? pill;
const { startMs, endMs } = resolveSpanMs(current, parsed.data.startSec, parsed.data.endSec);
- const replaced = anchorAudioTrackFragments(
+ // A `kind` flip re-clamps against the DESTINATION lane's neighbours, not the
+ // one it is leaving — moving a take onto the music row must respect what is
+ // already on the music row (issue #560).
+ const moved = placeAudioTrackInDocument(
+ next,
{
...current,
id: audioId,
@@ -2140,19 +2143,13 @@ export function executeAgentTool(
endMs,
...(parsed.data.kind !== undefined ? { kind: parsed.data.kind } : {}),
},
- document.timeline.clips,
() => createId("audio"),
+ "move",
);
- if (replaced.length === 0) {
+ if (moved === next) {
return coversNoClip("audio", startMs / 1000, endMs / 1000, document);
}
- next = {
- ...next,
- audioTracks: [
- ...next.audioTracks.filter((t) => trackGroupId(t) !== audioId),
- ...replaced,
- ],
- };
+ next = moved;
}
const after = collapseTracksToPills(next.audioTracks).find(
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 8f3f77495..1240d5d8e 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -998,7 +998,7 @@ export function NewEditorShell() {
// fragment's source offset — the generic one would copy the offset into
// every fragment and restart the file at each cut.
if (snapshot.kind === "audio") {
- const { anchorAudioTrackFragments } = await import("@/lib/ai-edition/document/audioTracks");
+ const { placeAudioTrackInDocument } = await import("@/lib/ai-edition/document/audioTracks");
const track = {
...(snapshot.region as unknown as AxcutAudioTrack),
id: createId("audio"),
@@ -1006,14 +1006,11 @@ export function NewEditorShell() {
startMs: timeMs,
endMs: timeMs + (Number(src.endMs) - Number(src.startMs)),
};
- const fragments = anchorAudioTrackFragments(track, doc.timeline.clips, () =>
- createId("audio"),
- );
- if (fragments.length === 0) return;
- await saveDocument(
- { ...doc, audioTracks: [...doc.audioTracks, ...fragments] },
- { history: true },
- );
+ // Pasting onto an occupied lane queues behind what is there rather than doubling
+ // the row — the same rule every other placement obeys (issue #560).
+ const next = placeAudioTrackInDocument(doc, track, () => createId("audio"), "create");
+ if (next === doc) return;
+ await saveDocument(next, { history: true });
toast.success("Region pasted");
return;
}
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 4a8f642fd..b85f3c964 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -1050,7 +1050,25 @@ export function V4Timeline({
// not the live drag geometry: a pill that changed rows halfway through a drag
// would jump out from under the pointer.
const audioPills = useMemo(() => collapseTracksToPills(tl.audioTracks), [tl.audioTracks]);
- const audioRows = useMemo(() => packAudioTrackRows(audioPills), [audioPills]);
+ // One row per KIND, and the packer unchanged INSIDE each kind (issue #560). Placement
+ // now clamps same-kind pills apart, so intra-kind packing is the legacy escape hatch —
+ // it keeps a document written before that rule legible instead of stacking its pills on
+ // top of each other. A kind with no tracks takes no row, so the common single-bed
+ // project stays exactly as tall as it was.
+ const audioRows = useMemo(() => {
+ const voice = audioPills.filter((p) => p.kind === "voiceover");
+ const music = audioPills.filter((p) => p.kind !== "voiceover");
+ const voiceRows = packAudioTrackRows(voice);
+ const musicRows = packAudioTrackRows(music);
+ const rowOf = new Map<string, number>();
+ const base = voice.length > 0 ? voiceRows.rowCount : 0;
+ for (const pill of voice) rowOf.set(pill.id, voiceRows.rowOf.get(pill.id) ?? 0);
+ for (const pill of music) rowOf.set(pill.id, base + (musicRows.rowOf.get(pill.id) ?? 0));
+ return {
+ rowOf,
+ rowCount: Math.max(1, base + (music.length > 0 ? musicRows.rowCount : 0)),
+ };
+ }, [audioPills]);
// Whether Alt is held, so an audio pill can show that the next drag slips. Window
// listeners rather than per-pill handlers: the key is pressed BEFORE the pointer
diff --git a/src/lib/ai-edition/document/audioLanes.test.ts b/src/lib/ai-edition/document/audioLanes.test.ts
new file mode 100644
index 000000000..53df11c9d
--- /dev/null
+++ b/src/lib/ai-edition/document/audioLanes.test.ts
@@ -0,0 +1,232 @@
+// Issue #560, step 6. "The voiceover" has to name ONE thing for the transcript tab's lane
+// switch to mean anything, so each kind keeps one row. Enforced at the single placement
+// door every writer goes through, and repaired — never refused — after a structural edit.
+
+import { describe, expect, it } from "vitest";
+import type { AxcutAudioTrack, AxcutClip, AxcutDocument } from "../schema";
+import {
+ audioLanePills,
+ collapseTracksToPills,
+ firstFreeHeadMs,
+ placeAudioTrackInDocument,
+ separateAudioLanes,
+} from "./audioTracks";
+
+const CLIPS: AxcutClip[] = [
+ {
+ id: "c1",
+ assetId: "rec",
+ sourceStartSec: 0,
+ sourceEndSec: 60,
+ timelineStartSec: 0,
+ timelineEndSec: 60,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+];
+
+function track(over: Partial<AxcutAudioTrack> & { id: string }): AxcutAudioTrack {
+ return {
+ trackId: over.id,
+ assetId: "aud",
+ kind: "voiceover",
+ startMs: 0,
+ endMs: 4000,
+ durationSec: 30,
+ offsetMs: 0,
+ gainDb: 0,
+ loop: false,
+ fadeInMs: 0,
+ fadeOutMs: 0,
+ muted: false,
+ label: "",
+ origin: "user",
+ clipId: "c1",
+ sourceStartSec: 0,
+ sourceEndSec: 4,
+ ...over,
+ } as unknown as AxcutAudioTrack;
+}
+
+function doc(audioTracks: AxcutAudioTrack[]): AxcutDocument {
+ return {
+ schemaVersion: 7,
+ project: { id: "p", title: "T", createdAt: "", updatedAt: "" },
+ assets: [],
+ transcript: null,
+ transcripts: [],
+ timeline: {
+ clips: CLIPS,
+ gaps: [],
+ trimRanges: [],
+ muteRanges: [],
+ speedRanges: [],
+ captionRanges: [],
+ },
+ annotations: [],
+ zoomRanges: [],
+ audioTracks,
+ legacyEditor: null,
+ } as unknown as AxcutDocument;
+}
+
+let n = 0;
+const ids = () => `f${n++}`;
+const pills = (d: AxcutDocument, kind: AxcutAudioTrack["kind"] = "voiceover") =>
+ audioLanePills(d.audioTracks, kind).map((p) => [p.startMs, p.endMs]);
+
+describe("one row per kind", () => {
+ it("queues a second take behind the first instead of on top of it", () => {
+ // Two takes recorded from the same playhead. This is what forced a second voiceover
+ // row into existence, and with it a lane switch that could not name what it meant.
+ const first = doc([track({ id: "a", startMs: 2000, endMs: 6000 })]);
+ const next = placeAudioTrackInDocument(
+ first,
+ track({ id: "b", startMs: 2000, endMs: 5000 }),
+ ids,
+ "create",
+ );
+ expect(pills(next)).toEqual([
+ [2000, 6000],
+ [6000, 9000],
+ ]);
+ });
+
+ it("parks a moved take against the wall with its duration intact", () => {
+ const before = doc([
+ track({ id: "a", startMs: 0, endMs: 4000 }),
+ track({ id: "b", startMs: 8000, endMs: 12_000 }),
+ ]);
+ // Dragged from 8s back to 2s, where "a" already sits. A move must never CROP a
+ // take: the user asked to move it, not to shorten it.
+ const next = placeAudioTrackInDocument(
+ before,
+ track({ id: "b", startMs: 2000, endMs: 6000 }),
+ ids,
+ "move",
+ );
+ const moved = audioLanePills(next.audioTracks, "voiceover").find(
+ (p) => (p.trackId ?? p.id) === "b",
+ );
+ expect(moved?.endMs && moved.endMs - moved.startMs).toBe(4000);
+ expect(moved?.startMs).toBe(4000);
+ });
+
+ it("stops a resized edge at the neighbour", () => {
+ const before = doc([
+ track({ id: "a", startMs: 0, endMs: 4000 }),
+ track({ id: "b", startMs: 8000, endMs: 12_000 }),
+ ]);
+ // Dragging "b"'s left edge back to 1s: it stops where "a" ends, and the head is
+ // what moves, not the whole pill.
+ const next = placeAudioTrackInDocument(
+ before,
+ track({ id: "b", startMs: 1000, endMs: 12_000 }),
+ ids,
+ "resize",
+ );
+ const resized = audioLanePills(next.audioTracks, "voiceover").find(
+ (p) => (p.trackId ?? p.id) === "b",
+ );
+ expect([resized?.startMs, resized?.endMs]).toEqual([4000, 12_000]);
+ });
+
+ it("leaves a voiceover over a music bed alone", () => {
+ // Different kinds, different rows: the normal case, and it must not clamp.
+ const before = doc([track({ id: "bed", kind: "music", startMs: 0, endMs: 20_000 })]);
+ const next = placeAudioTrackInDocument(
+ before,
+ track({ id: "vo", startMs: 3000, endMs: 7000 }),
+ ids,
+ "create",
+ );
+ expect(pills(next, "voiceover")).toEqual([[3000, 7000]]);
+ expect(pills(next, "music")).toEqual([[0, 20_000]]);
+ });
+
+ it("does not merge two different files that happen to match", () => {
+ // `regionIdentityKey` puts `assetId` in NON_IDENTITY_FIELDS, so two takes with the
+ // same payload hash identically — reusing it here would splice them into one pill.
+ const before = doc([track({ id: "a", assetId: "one", startMs: 0, endMs: 4000 })]);
+ const next = placeAudioTrackInDocument(
+ before,
+ track({ id: "b", assetId: "two", startMs: 4000, endMs: 8000 }),
+ ids,
+ "create",
+ );
+ expect(collapseTracksToPills(next.audioTracks)).toHaveLength(2);
+ });
+});
+
+describe("firstFreeHeadMs", () => {
+ it("takes the head as given when nothing is in the way", () => {
+ expect(firstFreeHeadMs([{ startMs: 10_000, endMs: 12_000 }], 2000, 4000)).toBe(2000);
+ });
+
+ it("slides past every pill that would overlap, in order", () => {
+ const busy = [
+ { startMs: 0, endMs: 3000 },
+ { startMs: 3000, endMs: 5000 },
+ ];
+ expect(firstFreeHeadMs(busy, 1000, 2000)).toBe(5000);
+ });
+
+ it("fits a pill into a gap big enough for it", () => {
+ const busy = [
+ { startMs: 0, endMs: 2000 },
+ { startMs: 9000, endMs: 12_000 },
+ ];
+ expect(firstFreeHeadMs(busy, 2000, 3000)).toBe(2000);
+ });
+});
+
+describe("separateAudioLanes", () => {
+ it("pushes a pill whose head fell inside its predecessor forward", () => {
+ // What a clip reorder can do with no audio code running.
+ const overlapped = [
+ track({ id: "a", startMs: 0, endMs: 5000 }),
+ track({ id: "b", startMs: 3000, endMs: 6000 }),
+ ];
+ expect(separateAudioLanes(overlapped).map((t) => [t.startMs, t.endMs])).toEqual([
+ [0, 5000],
+ [5000, 8000],
+ ]);
+ });
+
+ it("is idempotent, and leaves a document that is already separated alone", () => {
+ const fine = [
+ track({ id: "a", startMs: 0, endMs: 4000 }),
+ track({ id: "b", startMs: 4000, endMs: 8000 }),
+ ];
+ expect(separateAudioLanes(fine)).toBe(fine); // same reference: nothing to do
+ const once = separateAudioLanes([
+ track({ id: "a", startMs: 0, endMs: 5000 }),
+ track({ id: "b", startMs: 1000, endMs: 4000 }),
+ ]);
+ expect(separateAudioLanes(once)).toBe(once);
+ });
+
+ it("separates each kind on its own, never against the other", () => {
+ const mixed = [
+ track({ id: "vo", startMs: 0, endMs: 5000 }),
+ track({ id: "bed", kind: "music", startMs: 1000, endMs: 9000 }),
+ ];
+ // They overlap, and they should: they are different rows.
+ expect(separateAudioLanes(mixed)).toBe(mixed);
+ });
+
+ it("keeps every fragment of a split take moving together", () => {
+ const split = [
+ track({ id: "a", startMs: 0, endMs: 6000 }),
+ track({ id: "b1", trackId: "b", startMs: 2000, endMs: 4000 }),
+ track({ id: "b2", trackId: "b", startMs: 4000, endMs: 7000 }),
+ ];
+ const out = separateAudioLanes(split);
+ // The pill moves as one thing; its halves do not drift apart.
+ expect(out.filter((t) => t.trackId === "b").map((t) => [t.startMs, t.endMs])).toEqual([
+ [6000, 8000],
+ [8000, 11_000],
+ ]);
+ });
+});
diff --git a/src/lib/ai-edition/document/audioTracks.ts b/src/lib/ai-edition/document/audioTracks.ts
index ecf609d74..3ef9088c7 100644
--- a/src/lib/ai-edition/document/audioTracks.ts
+++ b/src/lib/ai-edition/document/audioTracks.ts
@@ -18,7 +18,11 @@
// outer edges only.
import type { AxcutAudioTrack, AxcutClip, AxcutDocument } from "../schema";
-import { anchorRegionsWithDerivedMs, coalesceRegionsForRuler } from "../timeline/timelineMap";
+import {
+ anchorRegionsWithDerivedMs,
+ clampSpanAgainstNeighbours,
+ coalesceRegionsForRuler,
+} from "../timeline/timelineMap";
/** Every fragment of one user-visible track shares this key. */
export function trackGroupId(track: AxcutAudioTrack): string {
@@ -283,6 +287,132 @@ export function slipAudioOffsetMs(
return Math.round(Math.min(slackMs, Math.max(0, offsetMs + deltaMs)));
}
+/** The document's user-visible pills of one kind, in ruler order. */
+export function audioLanePills(
+ tracks: AxcutAudioTrack[],
+ kind: AxcutAudioTrack["kind"],
+): AxcutAudioTrack[] {
+ return collapseTracksToPills(tracks)
+ .filter((pill) => pill.kind === kind)
+ .sort((a, b) => a.startMs - b.startMs);
+}
+
+/**
+ * The first head at or after `headMs` where a `spanMs` pill fits between its neighbours.
+ *
+ * For CREATING one. Two takes recorded from the same playhead used to land on top of each
+ * other, which is what forced a second voiceover row into existence; the later one now
+ * queues behind the first instead.
+ */
+export function firstFreeHeadMs(
+ pills: Array<{ startMs: number; endMs: number }>,
+ headMs: number,
+ spanMs: number,
+): number {
+ let head = Math.max(0, headMs);
+ for (const pill of [...pills].sort((a, b) => a.startMs - b.startMs)) {
+ if (pill.endMs <= head) continue;
+ if (pill.startMs >= head + spanMs) break; // it fits in front of this one
+ head = pill.endMs;
+ }
+ return head;
+}
+
+/**
+ * Lay a pill down in the document, clamped so its own kind keeps ONE row (issue #560).
+ *
+ * The single door every writer goes through. There were seven hand-rolled
+ * `[...others, ...fragments]` splices before this, and each one was a way to end up with
+ * two voiceover rows — which is what made the transcript tab's lane switch incoherent:
+ * "the voiceover" has to name one thing.
+ *
+ * The mode is the gesture, and each resolves an overlap differently:
+ * - "resize" stops the dragged EDGE at the neighbour, keeping the head still.
+ * - "move" keeps the DURATION and parks the pill against the wall. A take must never be
+ * silently cropped because it was dragged somewhere crowded.
+ * - "create" queues behind whatever is already there.
+ *
+ * Deliberately NOT `regionIdentityKey`: `assetId` is in `NON_IDENTITY_FIELDS`, so two
+ * different voiceover files with matching payload hash the same and would MERGE into one
+ * pill — silently splicing two takes together.
+ *
+ * Only same-kind pills clamp. A voiceover over a music bed is the normal case.
+ */
+export function placeAudioTrackInDocument(
+ doc: AxcutDocument,
+ pill: AxcutAudioTrack,
+ makeId: () => string,
+ mode: "move" | "resize" | "create",
+): AxcutDocument {
+ const groupId = trackGroupId(pill);
+ const others = audioLanePills(doc.audioTracks, pill.kind).filter(
+ (other) => trackGroupId(other) !== groupId,
+ );
+ const spanMs = Math.max(0, pill.endMs - pill.startMs);
+
+ let startMs = pill.startMs;
+ let endMs = pill.endMs;
+ if (mode === "create") {
+ startMs = firstFreeHeadMs(others, pill.startMs, spanMs);
+ endMs = startMs + spanMs;
+ } else if (mode === "move") {
+ startMs = firstFreeHeadMs(others, pill.startMs, spanMs);
+ endMs = startMs + spanMs;
+ } else {
+ const clamped = clampSpanAgainstNeighbours(
+ { start: pill.startMs, end: pill.endMs },
+ `lane:${pill.kind}:${groupId}`,
+ others.map((other) => ({
+ id: other.id,
+ identity: `lane:${other.kind}:${trackGroupId(other)}`,
+ start: other.startMs,
+ end: other.endMs,
+ })),
+ );
+ startMs = clamped.start;
+ endMs = clamped.end;
+ }
+
+ const placed = { ...pill, startMs, endMs };
+ const fragments = anchorAudioTrackFragments(placed, doc.timeline.clips, makeId);
+ if (fragments.length === 0) return doc;
+ const kept = doc.audioTracks.filter((track) => trackGroupId(track) !== groupId);
+ return { ...doc, audioTracks: [...kept, ...fragments] };
+}
+
+/**
+ * Push any same-kind pill whose head fell inside its predecessor forward to that
+ * predecessor's end, so each kind is back to one row.
+ *
+ * REPAIR, not refusal. The generic region pipeline re-derives audio spans with no audio
+ * code running — a clip reorder or a removed clip can slide two disjoint takes into
+ * overlap — and a schema refine there would surface as a thrown save and a "failed to
+ * save" toast on an ordinary clip drag, and would make existing documents unloadable.
+ *
+ * Deterministic, order-preserving and idempotent. It cannot lose audio: a pill pushed
+ * past the end of the programme still plays, because removal is defined by trims and
+ * gaps only and the projection is the identity out there.
+ */
+export function separateAudioLanes(tracks: AxcutAudioTrack[]): AxcutAudioTrack[] {
+ const shift = new Map<string, number>();
+ for (const kind of ["voiceover", "music"] as const) {
+ let cursor = Number.NEGATIVE_INFINITY;
+ for (const pill of audioLanePills(tracks, kind)) {
+ const spanMs = Math.max(0, pill.endMs - pill.startMs);
+ const startMs = Math.max(pill.startMs, cursor);
+ if (startMs !== pill.startMs) shift.set(trackGroupId(pill), startMs - pill.startMs);
+ cursor = startMs + spanMs;
+ }
+ }
+ if (shift.size === 0) return tracks;
+ return tracks.map((track) => {
+ const by = shift.get(trackGroupId(track));
+ return by === undefined
+ ? track
+ : { ...track, startMs: track.startMs + by, endMs: track.endMs + by };
+ });
+}
+
export function packAudioTrackRows(tracks: Array<{ id: string; startMs: number; endMs: number }>): {
rowOf: Map<string, number>;
rowCount: number;
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 87670128c..ab05856bb 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -30,7 +30,7 @@ import {
hasCompleteClipAnchor,
} from "../timeline/timelineMap";
import { dropTrimPillsByIds, trimAppliesToClip } from "../timeline/trim-mapping";
-import { removeAudioTrack } from "./audioTracks";
+import { reanchorAudioTracks, removeAudioTrack, separateAudioLanes } from "./audioTracks";
import { createId } from "./ids";
/** The region families a delete can target by id. Shared with the store so "which kinds
@@ -420,10 +420,28 @@ function mapAllRegionCollections(
document.annotations as unknown as StoredRegion[],
"ann",
) as unknown as AxcutDocument["annotations"],
- audioTracks: fn(
- document.audioTracks as unknown as StoredRegion[],
- "audio",
- ) as unknown as AxcutDocument["audioTracks"],
+ // Repaired here rather than at each of the four call sites, so no structural edit
+ // can skip it (issue #560).
+ //
+ // `reanchorAudioTracks` first: the generic pipeline copies `offsetMs` verbatim into
+ // every fragment, which corrupts a split take's offsets — a live bug, unrelated to
+ // lanes, that this walk was already causing. Then `separateAudioLanes`, because the
+ // same pipeline can slide two disjoint takes into overlap with no audio code
+ // running, and each kind has to keep ONE row.
+ //
+ // Repair, never refusal: a schema refine here would turn an ordinary clip drag into
+ // a thrown save, and would make every existing document with overlapping same-kind
+ // pills unloadable.
+ audioTracks: separateAudioLanes(
+ reanchorAudioTracks(
+ fn(
+ document.audioTracks as unknown as StoredRegion[],
+ "audio",
+ ) as unknown as AxcutDocument["audioTracks"],
+ document.timeline.clips,
+ () => createId("audio"),
+ ),
+ ),
legacyEditor:
legacy && (speedRegions || cameraFullscreenRegions)
? {
diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.ts
index 82348507f..9a832b356 100644
--- a/src/lib/ai-edition/store/documentWriteAudit.test.ts
+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts
@@ -264,7 +264,8 @@ const DECLARED: WritePath[] = [
// Three exits, one gesture: the toggle writes the flag alone when there is
// nothing to fill, and the flag plus the filled span when there is. Either
// way it is one undo step (see setAudioTrackLoop).
- w("src/lib/ai-edition/store/useTimeline.ts", "setAudioTrackLoop", "save", "gesture"),
+ // Two, not three: the fill and its no-op fallback collapsed into one call when the
+ // placement door took over the clamping (#560).
w("src/lib/ai-edition/store/useTimeline.ts", "setAudioTrackLoop", "save", "gesture"),
w("src/lib/ai-edition/store/useTimeline.ts", "setAudioTrackLoop", "save", "gesture"),
w("src/lib/ai-edition/store/useTimeline.ts", "updateAudioTrack", "save", "gesture"),
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index cd2b0e91e..fd47da9cc 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -3,7 +3,7 @@ import { create } from "zustand";
import { toFileUrl } from "@/components/video-editor/projectPersistence";
import { toastText } from "@/i18n/toastText";
import { nativeBridgeClient } from "@/native/client";
-import { anchorAudioTrackFragments } from "../document/audioTracks";
+import { placeAudioTrackInDocument } from "../document/audioTracks";
import { createId } from "../document/ids";
import { type Interval, replaceTimeline as replaceTimelineOp } from "../document/timeline";
import { type AxcutAsset, type AxcutDocument, createAudioTrack, documentSchema } from "../schema";
@@ -432,13 +432,12 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
timelineStartSec: timelineStartSec ?? get().currentTimeSec,
label: asset.label,
});
- // Anchor before saving: the track becomes one fragment per clip it covers,
- // each picking the source up where the previous one left off.
- const fragments = anchorAudioTrackFragments(track, document.timeline.clips, () =>
- createId("audio"),
- );
- if (fragments.length === 0) return null;
- const next = { ...document, audioTracks: [...document.audioTracks, ...fragments] };
+ // Through the placement door: it anchors the track into one fragment per clip it
+ // covers AND queues it behind whatever already occupies its kind's row, so two
+ // takes recorded from the same playhead no longer land on top of each other
+ // (issue #560).
+ const next = placeAudioTrackInDocument(document, track, () => createId("audio"), "create");
+ if (next === document) return null;
if (!(await get().saveDocument(next, { history: true }))) return null;
set({ selectedAudioTrackId: track.id });
return track.id;
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index cb514d15b..025b7c4a4 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -9,9 +9,9 @@ import { toFileUrl } from "@/components/video-editor/projectPersistence";
import type { AnnotationRegion, AnnotationType } from "@/components/video-editor/types";
import { useScopedT } from "@/contexts/I18nContext";
import {
- anchorAudioTrackFragments,
collapseTracksToPills,
patchAudioTrack,
+ placeAudioTrackInDocument,
removeAudioTrack as removeAudioTrackInDocument,
trackGroupId,
} from "../document/audioTracks";
@@ -1352,7 +1352,7 @@ export function useTimeline() {
async (trackId: string, span: { startMs: number; endMs: number; offsetMs?: number }) => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- const others = doc.audioTracks.filter((t) => trackGroupId(t) !== trackId);
+ // The door replaces the whole group, so the survivors no longer need naming here.
const [pill] = collapseTracksToPills(
doc.audioTracks.filter((t) => trackGroupId(t) === trackId),
);
@@ -1368,11 +1368,17 @@ export function useTimeline() {
offsetMs:
span.offsetMs === undefined ? pill.offsetMs : Math.max(0, Math.round(span.offsetMs)),
};
- const fragments = anchorAudioTrackFragments(moved, doc.timeline.clips, () =>
- createId("audio"),
+ // A resize stops the dragged edge at the neighbour; a move keeps the take's
+ // duration and parks it against the wall. Cropping a take because it was
+ // dragged somewhere crowded would lose audio the user never asked to lose.
+ const next = placeAudioTrackInDocument(
+ doc,
+ moved,
+ () => createId("audio"),
+ span.offsetMs === undefined ? "move" : "resize",
);
- if (fragments.length === 0) return;
- await saveDocument({ ...doc, audioTracks: [...others, ...fragments] }, { history: true });
+ if (next === doc) return;
+ await saveDocument(next, { history: true });
},
[saveDocument],
);
@@ -1408,6 +1414,11 @@ export function useTimeline() {
const fragments = doc.audioTracks.filter((t) => trackGroupId(t) === trackId);
const [pill] = collapseTracksToPills(fragments);
if (!pill) return;
+ // Refused on a voiceover. `anchorAudioTrackFragments` does not advance `offsetMs`
+ // across a looping track's fragments, so its words map to raw moments they do not
+ // occupy — the transcript lane drops it, and a cut authored from it would land in
+ // the wrong place. Music loops; narration does not (issue #560).
+ if (loop && pill.kind === "voiceover") return;
const programmeEndMs = Math.round(
doc.timeline.clips.reduce((max, c) => Math.max(max, c.timelineEndSec), 0) * 1000,
);
@@ -1417,17 +1428,15 @@ export function useTimeline() {
await saveDocument(patched, { history: true });
return;
}
- const others = patched.audioTracks.filter((t) => trackGroupId(t) !== trackId);
- const filled = anchorAudioTrackFragments(
+ // The fill stops at the next pill of its own kind, not at the programme end: a
+ // bed filling the timeline must not swallow a second bed that comes after it.
+ const filled = placeAudioTrackInDocument(
+ patched,
{ ...pill, loop, endMs: programmeEndMs },
- doc.timeline.clips,
() => createId("audio"),
+ "resize",
);
- if (filled.length === 0) {
- await saveDocument(patched, { history: true });
- return;
- }
- await saveDocument({ ...doc, audioTracks: [...others, ...filled] }, { history: true });
+ await saveDocument(filled === patched ? patched : filled, { history: true });
},
[saveDocument],
);