Skip to content

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

fix(editor): address CodeRabbit follow-up on the audio-track PR (#502)

Benjamin Freeman8e182888f229
diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts
index 7a6704fd8..af6e056ce 100644
--- a/src/lib/ai-edition/document/timeline.test.ts
+++ b/src/lib/ai-edition/document/timeline.test.ts
@@ -871,6 +871,36 @@ describe("projectRawTimelineSecToPlayback (issue #350 audio-track/trim sync)", (
expect(projectRawTimelineSecToPlayback([clip], [trim], 3)).toBeCloseTo(2, 6);
});
+ it("counts overlapping trims once (union, not sum)", () => {
+ // Trims [2,5] and [3,4] — the second nested in the first — remove 3s total, not 4.
+ // Raw 6 → output 3. The old per-trim accumulation double-counted and returned 2.
+ const trims = [
+ makeTrim({ id: "t1", startSec: 2, endSec: 5 }),
+ makeTrim({ id: "t2", startSec: 3, endSec: 4 }),
+ ];
+ expect(projectRawTimelineSecToPlayback([clip], trims, 6)).toBeCloseTo(3, 6);
+ });
+
+ it("removes a raw gap between clips (concatenated, like the programme)", () => {
+ // Clip A ends at raw 10; clip B starts at raw 15 — a 5s gap with no content. The
+ // programme concatenates B straight after A, so raw 20 (5s into B) → output 15, NOT 20.
+ const clipA = makeClip({
+ id: "clip_a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ });
+ const clipB = makeClip({
+ id: "clip_b",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 15,
+ timelineEndSec: 25,
+ });
+ expect(projectRawTimelineSecToPlayback([clipA, clipB], [], 20)).toBeCloseTo(15, 6);
+ });
+
it("sums cuts across multiple clips", () => {
const clipA = makeClip({
id: "clip_a",
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 0cbbeabd4..56ac9c858 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -207,17 +207,17 @@ export function resolvePlaybackSegments(
* onto the trim-COMPRESSED output programme — the concatenation of the kept segments that
* {@link resolvePlaybackSegments} produces and that `audio::mix_external_tracks` overlays on.
*
- * The only thing the programme removes is trimmed content, so the output position of a raw
- * time `T` is `T` minus however much trimmed span sits before it:
- * `output(T) = T − Σ overlap(each trim's raw extent, [0, T])`.
- * A `T` past a cut lands earlier by exactly the removed duration (the whole point); a `T`
- * INSIDE a trimmed span collapses to the output edge just before it; and a `T` in a region
- * with no trim — including a project with no clips at all — passes straight through.
+ * Built from the SAME kept intervals as `resolvePlaybackSegments` (trims subtracted per clip
+ * via `subtractInterval`, then concatenated with a shared output cursor), so it agrees with the
+ * assembled programme in the two cases a naïve "raw − Σ trimmed-before" got wrong: OVERLAPPING
+ * trims (set subtraction counts the union once, not each trim) and RAW GAPS between clips (the
+ * cursor only advances on kept content, so a gap is removed just as the programme removes it).
*
- * A trim is stored in SOURCE seconds anchored to a clip (`trimAppliesToClip`, same match as
- * `resolvePlaybackSegments`), so its raw extent is the clip's `timelineStartSec` plus the
- * offset of the trimmed sub-range into the clip's own source window. EXACT for trims; like the
- * rest of the audio-track export path it does not model speed regions, which stay an approximation.
+ * `output(T)` = how much kept content precedes `T`. A `T` inside a trimmed span (or an inter-clip
+ * gap) collapses to the output edge of the kept content just before it; a `T` past the last kept
+ * frame carries its raw overhang through unchanged, so a project with no clips is the identity and
+ * a track parked past the programme stays past it (the mixer then skips it). EXACT for trims; like
+ * the rest of the audio-track export path it does not model speed regions, which stay an approximation.
*
* Issue #350: imported audio tracks store their head in RAW seconds (seeded from the playhead),
* but the export mixes onto the compressed programme — passing the raw head through verbatim
@@ -229,23 +229,51 @@ export function projectRawTimelineSecToPlayback(
trimRanges: AxcutTrimRange[],
rawSec: number,
): number {
- let removed = 0;
- for (const clip of clips) {
+ const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
+ let outCursor = 0; // output length of the kept content walked so far
+ let lastRawEnd = 0; // raw end of the last kept segment, for the trailing overhang
+ let landed: number | null = null; // output(rawSec), once it falls in/before a kept segment
+
+ // Each kept segment as a raw extent `{ rawStart, dur }`; its output duration equals `dur`
+ // (trims only remove, they don't scale — speed is the separate approximation noted above).
+ const keptSegments = (clip: AxcutClip): Array<{ rawStart: number; dur: number }> => {
const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
- if (sourceEnd <= clip.sourceStartSec) continue; // unprobed: no trims resolved against it
+ if (sourceEnd <= clip.sourceStartSec) {
+ // Duration not probed yet — the whole raw clip passes through unnarrowed, matching
+ // `resolvePlaybackSegments`' own pass-through branch.
+ return [
+ { rawStart: clip.timelineStartSec, dur: clip.timelineEndSec - clip.timelineStartSec },
+ ];
+ }
+ let ivs: Interval[] = [{ startSec: clip.sourceStartSec, endSec: sourceEnd }];
for (const trim of trimRanges) {
if (!trimAppliesToClip(trim, clip)) continue;
- // The trimmed sub-range clamped to THIS clip's source window, then placed on the raw
- // ruler where source `s` sits at `timelineStartSec + (s − sourceStartSec)`.
- const s0 = Math.max(trim.startSec, clip.sourceStartSec);
- const s1 = Math.min(trim.endSec, sourceEnd);
- if (s1 <= s0) continue;
- const rawStart = clip.timelineStartSec + (s0 - clip.sourceStartSec);
- const rawLen = s1 - s0;
- removed += Math.min(Math.max(rawSec - rawStart, 0), rawLen);
+ ivs = subtractInterval(ivs, { startSec: trim.startSec, endSec: trim.endSec });
+ }
+ // Source time `s` sits at `timelineStartSec + (s − sourceStartSec)` on the raw ruler.
+ return ivs.map((iv) => ({
+ rawStart: clip.timelineStartSec + (iv.startSec - clip.sourceStartSec),
+ dur: iv.endSec - iv.startSec,
+ }));
+ };
+
+ for (const clip of ordered) {
+ for (const seg of keptSegments(clip)) {
+ if (seg.dur <= 0) continue;
+ const rawEnd = seg.rawStart + seg.dur;
+ if (landed === null && rawSec < rawEnd) {
+ // `rawSec` is inside this segment, or before it in a trimmed/gap region (then
+ // `within` clamps to 0 → the output edge just before the gap).
+ const within = Math.min(Math.max(rawSec - seg.rawStart, 0), seg.dur);
+ landed = outCursor + within;
+ }
+ outCursor += seg.dur;
+ lastRawEnd = rawEnd;
}
}
- return rawSec - removed;
+ // Past every kept frame: programme end plus whatever raw time hangs off the end (identity when
+ // there are no clips at all). A value ≥ programme length just means the mixer skips the track.
+ return landed ?? outCursor + Math.max(0, rawSec - lastRawEnd);
}
export function invertIntervals(intervals: Interval[], durationSec: number): Interval[] {
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index 0b0cb47cd..0e301c6b2 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -1435,6 +1435,52 @@ describe("useTimeline audio tracks", () => {
expect(importSpy).toHaveBeenCalledWith("/tmp/bgm.mp3", "bgm.mp3");
});
+ it("addAudio clears region/clip selections after a successful import", async () => {
+ // importAudioAsset must resolve an asset for the success path to run.
+ useProjectStore.setState({ importAudioAsset: vi.fn().mockResolvedValue({ id: "audio_1" }) });
+ Object.defineProperty(window, "electronAPI", {
+ configurable: true,
+ value: {
+ openAudioFilePicker: vi
+ .fn()
+ .mockResolvedValue({ success: true, path: "/tmp/bgm.mp3", name: "bgm.mp3" }),
+ },
+ });
+ const { result } = renderTimeline();
+
+ // A clip selected before the import (selectClip and selectRegion are mutually
+ // exclusive, so a clip is enough to prove the import wipes the local selection)…
+ act(() => result.current.selectClip("clip_1"));
+ expect(result.current.clipSelection).toBe("clip_1");
+
+ await act(async () => {
+ await result.current.addAudio();
+ });
+ // …is gone after it (the imported track becomes the sole selection).
+ expect(result.current.selection).toBeNull();
+ expect(result.current.multiSelection).toEqual([]);
+ expect(result.current.clipSelection).toBeNull();
+ });
+
+ it("addAudio toasts when the file picker itself rejects", async () => {
+ toastErrorMock.mockClear();
+ const importSpy = vi.fn();
+ useProjectStore.setState({ importAudioAsset: importSpy });
+ Object.defineProperty(window, "electronAPI", {
+ configurable: true,
+ value: { openAudioFilePicker: vi.fn().mockRejectedValueOnce(new Error("ipc down")) },
+ });
+ const { result } = renderTimeline();
+
+ await act(async () => {
+ await result.current.addAudio();
+ });
+ // A picker rejection reaches the localized toast, not an unhandled rejection, and never
+ // attempts an import.
+ expect(importSpy).not.toHaveBeenCalled();
+ expect(toastErrorMock).toHaveBeenCalledTimes(1);
+ });
+
// #350 regression: a failed import-time probe leaves durationSec at 0, which
// makes the playback window zero-length. The on-load backfill re-probes and
// stamps the real duration onto the asset AND the track, so it can play again.
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index e107f9b87..55ed7d5ec 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -1283,11 +1283,23 @@ export function useTimeline() {
// through `tl`) share one path. Opens a file picker, so unlike the region adds it takes
// no playhead duration; `importAudioAsset` places the track at the current playhead.
const addAudio = useCallback(async () => {
- const picker = await window.electronAPI?.openAudioFilePicker?.();
- if (!picker?.success || !picker.path) return;
try {
+ // Inside the try so a rejected picker (an IPC failure, not a cancel) still reaches the
+ // localized toast instead of surfacing as an unhandled rejection. A cancel resolves with
+ // `success: false` and is a silent early return, not an error.
+ const picker = await window.electronAPI?.openAudioFilePicker?.();
+ if (!picker?.success || !picker.path) return;
const label = picker.name || picker.path.split(/[\\/]/).pop() || "Audio";
- await importAudioAsset(picker.path, label);
+ const asset = await importAudioAsset(picker.path, label);
+ // `importAudioAsset` selects the new track in the store, but the region/clip
+ // selections are hook-local state it can't touch — clear them here so an import
+ // doesn't leave a stale annotation/clip selected alongside the new track (the same
+ // exclusivity `addAudioTrack` keeps). Only on success: a failed import changes nothing.
+ if (asset) {
+ setSelection(null);
+ setMultiSelection([]);
+ setClipSelection(null);
+ }
} catch (err) {
toast.error(ts("audioTrack.importFailed"), {
description: err instanceof Error ? err.message : String(err),