Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

test(ui): pin the load-bearing pure logic - echo commits, chains, peaks

Jareerdd9726c64d4f
diff --git a/desktop/src/lib/assets.test.ts b/desktop/src/lib/assets.test.ts
new file mode 100644
index 00000000..2914e693
--- /dev/null
+++ b/desktop/src/lib/assets.test.ts
@@ -0,0 +1,133 @@
+// @vitest-environment jsdom
+/**
+ * The waveform cache's wire format.
+ *
+ * `encodePeaks`/`decodePeaks` are the two halves of the on-disk artwork cache:
+ * what encode writes today, decode must read on every future launch. A break
+ * in the round-trip does not crash anything - loadPeaks falls back to a full
+ * re-decode - but it silently voids the cache, and a decode that misreads
+ * lengths would draw garbage waveforms. When a layout expectation here fails,
+ * remember the old files on disk: decode must keep reading yesterday's bytes,
+ * or the cache key (in `loadPeaks`) must change so stale entries miss.
+ *
+ * jsdom because `assets.ts` reads `window.devicePixelRatio` at module scope.
+ */
+import { describe, expect, test } from "vitest";
+
+import { decodePeaks, encodePeaks, type Peaks } from "./assets";
+
+function peaks(min: number[], max: number[], bucketsPerSecond = 200): Peaks {
+ return {
+ min: Float32Array.from(min),
+ max: Float32Array.from(max),
+ bucketsPerSecond,
+ };
+}
+
+const roundTrip = (source: Peaks) => decodePeaks(encodePeaks(source).buffer);
+
+describe("the peaks round-trip", () => {
+ test("decode(encode(x)) preserves every bucket exactly", () => {
+ // Samples are already Float32 on both sides, so the only quantisation
+ // happened before encode ever saw them: the trip itself must be lossless.
+ const source = peaks([-1, -0.5, 0, -0.001], [1, 0.5, 0, 0.001]);
+ const decoded = roundTrip(source);
+ expect(decoded).not.toBeNull();
+ expect(decoded!.min).toEqual(source.min);
+ expect(decoded!.max).toEqual(source.max);
+ expect(decoded!.bucketsPerSecond).toBe(200);
+ });
+
+ test("a fractional bucket rate survives to Float32 precision", () => {
+ // loadPeaks computes sampleRate / bucketSize, rarely a round number.
+ const rate = 44100 / 220; // 200.4545...
+ const decoded = roundTrip(peaks([0], [0], rate));
+ expect(decoded!.bucketsPerSecond).toBe(Math.fround(rate));
+ expect(decoded!.bucketsPerSecond).toBeCloseTo(rate, 4);
+ });
+
+ test("many arbitrary values survive within Float32 quantisation", () => {
+ // A deterministic pseudo-random spread across the full sample range.
+ const values = Array.from({ length: 1000 }, (_, index) =>
+ Math.sin(index * 12.9898) * ((index % 7) / 7),
+ );
+ const source = peaks(values.map((value) => -Math.abs(value)), values);
+ const decoded = roundTrip(source);
+ expect(decoded!.min).toEqual(source.min);
+ expect(decoded!.max).toEqual(source.max);
+ for (let index = 0; index < values.length; index += 1) {
+ expect(Math.abs(decoded!.max[index] - values[index])).toBeLessThanOrEqual(
+ Math.abs(Math.fround(values[index]) - values[index]) + Number.EPSILON,
+ );
+ }
+ });
+
+ test("the extremes 0, 1 and -1 come back exact", () => {
+ const decoded = roundTrip(peaks([-1, 0], [1, 0]));
+ expect(Array.from(decoded!.min)).toEqual([-1, 0]);
+ expect(Array.from(decoded!.max)).toEqual([1, 0]);
+ });
+
+ test("a single bucket round-trips", () => {
+ const decoded = roundTrip(peaks([-0.25], [0.75]));
+ expect(decoded!.min).toHaveLength(1);
+ expect(decoded!.min[0]).toBeCloseTo(-0.25, 10);
+ expect(decoded!.max[0]).toBeCloseTo(0.75, 10);
+ });
+
+ test("empty peaks round-trip as a valid header-only file", () => {
+ const bytes = encodePeaks(peaks([], []));
+ expect(bytes.byteLength).toBe(8);
+ const decoded = decodePeaks(bytes.buffer);
+ expect(decoded).not.toBeNull();
+ expect(decoded!.min).toHaveLength(0);
+ expect(decoded!.max).toHaveLength(0);
+ });
+});
+
+describe("the encoded layout", () => {
+ test("[bucketsPerSecond f32][count u32][min f32...][max f32...], little-endian", () => {
+ // This is the on-disk contract. Changing it strands every existing cache
+ // file, so a failure here demands either a compatible decode or a new key.
+ const bytes = encodePeaks(peaks([-0.5, -1], [0.5, 1], 200));
+ expect(bytes.byteLength).toBe(8 + 2 * 8);
+ const view = new DataView(bytes.buffer);
+ expect(view.getFloat32(0, true)).toBe(200);
+ expect(view.getUint32(4, true)).toBe(2);
+ expect(view.getFloat32(8, true)).toBe(-0.5); // min block first
+ expect(view.getFloat32(12, true)).toBe(-1);
+ expect(view.getFloat32(16, true)).toBe(0.5); // then the max block
+ expect(view.getFloat32(20, true)).toBe(1);
+ });
+});
+
+describe("decodePeaks fails soft on bad files", () => {
+ const valid = () => encodePeaks(peaks([-1], [1])).buffer;
+
+ test("a file too short for the header is null", () => {
+ expect(decodePeaks(new ArrayBuffer(0))).toBeNull();
+ expect(decodePeaks(new ArrayBuffer(7))).toBeNull();
+ });
+
+ test("a truncated or padded body is null, never a misread", () => {
+ const truncated = valid().slice(0, 12);
+ expect(decodePeaks(truncated)).toBeNull();
+ const padded = new Uint8Array(24);
+ padded.set(new Uint8Array(valid()));
+ expect(decodePeaks(padded.buffer)).toBeNull();
+ });
+
+ test("a count that overruns the file is null", () => {
+ const bytes = new Uint8Array(valid());
+ new DataView(bytes.buffer).setUint32(4, 1000, true);
+ expect(decodePeaks(bytes.buffer)).toBeNull();
+ });
+
+ test("a zero, negative or NaN bucket rate is null", () => {
+ for (const rate of [0, -200, Number.NaN]) {
+ const bytes = new Uint8Array(valid());
+ new DataView(bytes.buffer).setFloat32(0, rate, true);
+ expect(decodePeaks(bytes.buffer)).toBeNull();
+ }
+ });
+});
diff --git a/desktop/src/lib/assets.ts b/desktop/src/lib/assets.ts
index be43e163..1d199b4d 100644
--- a/desktop/src/lib/assets.ts
+++ b/desktop/src/lib/assets.ts
@@ -217,7 +217,7 @@ function writeArtwork(project: string | null, key: string, bytes: Uint8Array): v
}
/** [bucketsPerSecond f32][count u32][min f32...][max f32...], little-endian. */
-function encodePeaks(peaks: Peaks): Uint8Array {
+export function encodePeaks(peaks: Peaks): Uint8Array {
const count = peaks.min.length;
const buffer = new ArrayBuffer(8 + count * 8);
const view = new DataView(buffer);
@@ -228,7 +228,7 @@ function encodePeaks(peaks: Peaks): Uint8Array {
return new Uint8Array(buffer);
}
-function decodePeaks(bytes: ArrayBuffer): Peaks | null {
+export function decodePeaks(bytes: ArrayBuffer): Peaks | null {
if (bytes.byteLength < 8) return null;
const view = new DataView(bytes);
const bucketsPerSecond = view.getFloat32(0, true);
diff --git a/desktop/src/lib/editor-echo.test.ts b/desktop/src/lib/editor-echo.test.ts
new file mode 100644
index 00000000..b5a23c2b
--- /dev/null
+++ b/desktop/src/lib/editor-echo.test.ts
@@ -0,0 +1,262 @@
+/**
+ * The echo's commit: accumulated drag patches into engine commands.
+ *
+ * `commandsForEcho` is the moment the preview becomes real. Every drag in the
+ * app funnels through it on release, so a wrong translation here does not
+ * mislead a preview - it commits a wrong edit to the document. These tests pin
+ * the exact command list for each echo shape. When one fails, decide which
+ * side moved: the echo builders in `lib/editor.ts` (trimPatch/speedPatch/
+ * transformPatch write the patches this function reads) or the command
+ * vocabulary in `engine/crates/wolfcut-project/src/commands.rs`.
+ */
+import { describe, expect, test } from "vitest";
+
+import {
+ commandsForEcho,
+ speedPatch,
+ transformPatch,
+ trimPatch,
+ withEcho,
+ type Clip,
+ type EditorProject,
+} from "./editor";
+
+function clip(overrides: Partial<Clip> = {}): Clip {
+ return {
+ id: "c1",
+ trackId: "T1",
+ mediaId: "m1",
+ name: "a.mp4",
+ kind: "video",
+ start: 0,
+ duration: 10,
+ sourceStart: 0,
+ volume: 1,
+ fadeIn: 0,
+ fadeOut: 0,
+ scale: 1,
+ offsetX: 0,
+ offsetY: 0,
+ rotation: 0,
+ opacity: 1,
+ speed: 1,
+ preservePitch: true,
+ filters: [],
+ videoEffects: [],
+ ...overrides,
+ };
+}
+
+describe("commandsForEcho: moves", () => {
+ test("a start change alone is one move on the same track", () => {
+ expect(commandsForEcho(clip(), { start: 3 })).toEqual([
+ { op: "moveClips", moves: [{ clipId: "c1", start: 3, trackId: "T1" }] },
+ ]);
+ });
+
+ test("a track change alone is one move keeping the start", () => {
+ expect(commandsForEcho(clip({ start: 2 }), { trackId: "T2" })).toEqual([
+ { op: "moveClips", moves: [{ clipId: "c1", start: 2, trackId: "T2" }] },
+ ]);
+ });
+
+ test("start and track together stay one move", () => {
+ expect(commandsForEcho(clip(), { start: 5, trackId: "T3" })).toEqual([
+ { op: "moveClips", moves: [{ clipId: "c1", start: 5, trackId: "T3" }] },
+ ]);
+ });
+
+ test("a trackId echoed back unchanged still emits the move", () => {
+ // Current behaviour, pinned deliberately: dropping a clip back onto its
+ // own track at its own start commits a do-nothing MoveClips (and so an
+ // empty undo step). If this ever changes to [], that is an improvement -
+ // update this expectation, not the caller.
+ expect(commandsForEcho(clip(), { trackId: "T1" })).toEqual([
+ { op: "moveClips", moves: [{ clipId: "c1", start: 0, trackId: "T1" }] },
+ ]);
+ });
+});
+
+describe("commandsForEcho: trims", () => {
+ test("a head trim becomes one start-edge TrimClip carrying the travel", () => {
+ const base = clip();
+ // trimPatch writes start+duration+sourceStart; the commit sends only the
+ // start delta and trusts the engine to redo the same arithmetic.
+ const patch = trimPatch(base, "start", 1);
+ expect(patch).toEqual({ start: 1, duration: 9, sourceStart: 1 });
+ expect(commandsForEcho(base, patch)).toEqual([
+ { op: "trimClip", clipId: "c1", edge: "start", delta: 1 },
+ ]);
+ });
+
+ test("a clamped head trim commits the applied travel, not the request", () => {
+ const base = clip({ start: 1 });
+ const patch = trimPatch(base, "start", -3); // only 1s exists before zero
+ expect(commandsForEcho(base, patch)).toEqual([
+ { op: "trimClip", clipId: "c1", edge: "start", delta: -1 },
+ ]);
+ });
+
+ test("a head trim at speed keeps the delta in timeline seconds", () => {
+ const base = clip({ duration: 5, speed: 2 });
+ const patch = trimPatch(base, "start", 1); // sourceStart moves 2, start moves 1
+ expect(commandsForEcho(base, patch)).toEqual([
+ { op: "trimClip", clipId: "c1", edge: "start", delta: 1 },
+ ]);
+ });
+
+ test("an end trim becomes one end-edge TrimClip with the duration delta", () => {
+ expect(commandsForEcho(clip(), trimPatch(clip(), "end", 2))).toEqual([
+ { op: "trimClip", clipId: "c1", edge: "end", delta: 2 },
+ ]);
+ expect(commandsForEcho(clip(), { duration: 7 })).toEqual([
+ { op: "trimClip", clipId: "c1", edge: "end", delta: -3 },
+ ]);
+ });
+
+ test("sourceStart never rides in a command", () => {
+ // The engine owns that arithmetic; if a sourceStart ever leaks into the
+ // wire format the two sides can disagree about the in-point.
+ const commands = commandsForEcho(clip(), trimPatch(clip(), "start", 2));
+ expect(JSON.stringify(commands)).not.toContain("sourceStart");
+ });
+});
+
+describe("commandsForEcho: speed", () => {
+ test("a speed change is SetClipSpeed alone - the engine re-derives duration", () => {
+ const base = clip();
+ const patch = speedPatch(base, 2); // writes speed AND duration into the echo
+ expect(patch).toEqual({ speed: 2, duration: 5 });
+ expect(commandsForEcho(base, patch)).toEqual([
+ { op: "setClipSpeed", clipId: "c1", speed: 2 },
+ ]);
+ });
+});
+
+describe("commandsForEcho: transforms", () => {
+ test("only the echoed transform fields ride the command", () => {
+ expect(commandsForEcho(clip(), { scale: 1.5, rotation: 90 })).toEqual([
+ { op: "setClipTransform", clipId: "c1", scale: 1.5, rotation: 90 },
+ ]);
+ expect(commandsForEcho(clip(), transformPatch({ offsetX: 0.25 }))).toEqual([
+ { op: "setClipTransform", clipId: "c1", offsetX: 0.25 },
+ ]);
+ });
+});
+
+describe("commandsForEcho: the update patch", () => {
+ test("plain fields collect into one UpdateClip", () => {
+ expect(
+ commandsForEcho(clip(), {
+ name: "renamed",
+ volume: 0.5,
+ fadeIn: 0.2,
+ fadeOut: 0.3,
+ opacity: 0.8,
+ preservePitch: false,
+ filters: [{ id: "bass", params: { gain: 6 } }],
+ videoEffects: [{ id: "sepia", params: {} }],
+ }),
+ ).toEqual([
+ {
+ op: "updateClip",
+ clipId: "c1",
+ patch: {
+ name: "renamed",
+ volume: 0.5,
+ fadeIn: 0.2,
+ fadeOut: 0.3,
+ opacity: 0.8,
+ preservePitch: false,
+ filters: [{ id: "bass", params: { gain: 6 } }],
+ videoEffects: [{ id: "sepia", params: {} }],
+ },
+ },
+ ]);
+ });
+
+ test("a present-but-undefined transitionIn or text means clear, as null", () => {
+ // The wire keeps the engine's double-option distinction: absent leaves the
+ // field alone, null clears it. The echo spells "clear" as a present
+ // undefined, and the commit must translate that to null, never drop it.
+ expect(commandsForEcho(clip(), { transitionIn: undefined })).toEqual([
+ { op: "updateClip", clipId: "c1", patch: { transitionIn: null } },
+ ]);
+ expect(commandsForEcho(clip(), { text: undefined })).toEqual([
+ { op: "updateClip", clipId: "c1", patch: { text: null } },
+ ]);
+ });
+
+ test("a real transition value passes through", () => {
+ expect(
+ commandsForEcho(clip(), { transitionIn: { id: "cross-fade", duration: 1 } }),
+ ).toEqual([
+ {
+ op: "updateClip",
+ clipId: "c1",
+ patch: { transitionIn: { id: "cross-fade", duration: 1 } },
+ },
+ ]);
+ });
+});
+
+describe("commandsForEcho: mixed accumulations and no-ops", () => {
+ test("a busy panel commits in the documented order: speed, transform, move, patch", () => {
+ const commands = commandsForEcho(clip(), {
+ volume: 0.7,
+ start: 4,
+ scale: 2,
+ speed: 2,
+ duration: 5, // speedPatch wrote this; it must NOT read as a trim
+ });
+ expect(commands).toEqual([
+ { op: "setClipSpeed", clipId: "c1", speed: 2 },
+ { op: "setClipTransform", clipId: "c1", scale: 2 },
+ { op: "moveClips", moves: [{ clipId: "c1", start: 4, trackId: "T1" }] },
+ { op: "updateClip", clipId: "c1", patch: { volume: 0.7 } },
+ ]);
+ });
+
+ test("an empty echo commits nothing", () => {
+ expect(commandsForEcho(clip(), {})).toEqual([]);
+ });
+
+ test("echoed values equal to the base commit nothing", () => {
+ // A drag that ends where it began, or a trim clamped to zero travel.
+ expect(commandsForEcho(clip({ start: 2 }), { start: 2 })).toEqual([]);
+ expect(commandsForEcho(clip(), { duration: 10 })).toEqual([]);
+ const pinned = clip(); // at 0: dragging the head left cannot travel at all
+ expect(commandsForEcho(pinned, trimPatch(pinned, "start", -1))).toEqual([]);
+ });
+});
+
+describe("withEcho", () => {
+ const project = (clips: Clip[]): EditorProject => ({
+ media: [],
+ fonts: [],
+ timelines: [
+ {
+ id: "TL1",
+ name: "Timeline 1",
+ tracks: [{ id: "T1", name: "Track 1", visible: true, muted: false }],
+ clips,
+ },
+ { id: "TL2", name: "Timeline 2", tracks: [], clips: [clip({ id: "other" })] },
+ ],
+ activeTimelineId: "TL1",
+ });
+
+ test("patches land only on the active timeline's clips", () => {
+ const p = project([clip()]);
+ const echoed = withEcho(p, { c1: { start: 5 }, other: { start: 9 } });
+ expect(echoed.timelines[0].clips[0].start).toBe(5);
+ // A clip with the same id on another timeline is untouched.
+ expect(echoed.timelines[1].clips[0].start).toBe(0);
+ });
+
+ test("no echo returns the project untouched, same reference", () => {
+ const p = project([clip()]);
+ expect(withEcho(p, null)).toBe(p);
+ expect(withEcho(p, {})).toBe(p);
+ });
+});
diff --git a/desktop/src/lib/effects.test.ts b/desktop/src/lib/effects.test.ts
new file mode 100644
index 00000000..88a60a51
--- /dev/null
+++ b/desktop/src/lib/effects.test.ts
@@ -0,0 +1,169 @@
+/**
+ * The video effect catalogue's export strings, pinned character for character.
+ *
+ * `buildEffectChain` writes the FFmpeg fragment the exporter runs; a typo here
+ * ships as a silently broken or subtly different-looking export. There is no
+ * second implementation to cross-check against, so these tests ARE the check:
+ * every catalogue entry at its default, minimum and maximum settings, spelled
+ * out inline. When one fails, the export string changed - confirm FFmpeg still
+ * accepts the new spelling and that existing projects render the same picture
+ * before updating the expectation.
+ */
+import { describe, expect, test } from "vitest";
+
+import { buildEffectChain, EFFECTS, findEffect } from "./effects";
+
+const one = (id: string, params: Record<string, number> = {}) =>
+ buildEffectChain([{ id, params }]);
+
+/** The definition's sliders, all pushed to one bound. */
+const bound = (id: string, which: "min" | "max"): Record<string, number> =>
+ Object.fromEntries(findEffect(id)!.params.map((param) => [param.key, param[which]]));
+
+const DEFAULT_CHAINS: Record<string, string> = {
+ "black-white": "hue=s=0",
+ sepia: "colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131",
+ invert: "negate",
+ sharpen: "unsharp=5:5:1.00:5:5:0",
+ "gaussian-blur": "gblur=sigma=10.0",
+ "box-blur": "boxblur=6:1",
+ "motion-blur": "gblur=sigma=18.0:sigmaV=0.1",
+ warm: "colortemperature=temperature=4600",
+ cool: "colortemperature=temperature=8500",
+ vibrance: "vibrance=intensity=0.70",
+ "contrast-pop": "eq=contrast=1.25",
+ vignette: "vignette=angle=0.775",
+ "film-grain": "noise=alls=12:allf=t+u",
+ glow:
+ "split[glowa][glowb];[glowb]gblur=sigma=18[glowg];" +
+ "[glowa][glowg]blend=all_mode=screen:all_opacity=0.45",
+ posterize: "lutrgb=r=trunc(val/64)*64:g=trunc(val/64)*64:b=trunc(val/64)*64",
+ pixelate: "pixelize=width=16:height=16",
+ mirror: "crop=iw/2:ih:0:0,split[mirl][mirr];[mirr]hflip[mirf];[mirl][mirf]hstack",
+ fisheye: "lenscorrection=k1=-0.275:k2=-0.100:i=bilinear",
+ shake: "crop=iw-24:ih-24:12+12*sin(t*13):12+12*cos(t*17)",
+};
+
+const MIN_CHAINS: Record<string, string> = {
+ sharpen: "unsharp=5:5:0.20:5:5:0",
+ "gaussian-blur": "gblur=sigma=1.0",
+ "box-blur": "boxblur=1:1",
+ "motion-blur": "gblur=sigma=2.0:sigmaV=0.1",
+ warm: "colortemperature=temperature=3000",
+ cool: "colortemperature=temperature=7000",
+ vibrance: "vibrance=intensity=0.10",
+ "contrast-pop": "eq=contrast=1.00",
+ vignette: "vignette=angle=0.355",
+ "film-grain": "noise=alls=2:allf=t+u",
+ glow:
+ "split[glowa][glowb];[glowb]gblur=sigma=18[glowg];" +
+ "[glowa][glowg]blend=all_mode=screen:all_opacity=0.10",
+ posterize: "lutrgb=r=trunc(val/128)*128:g=trunc(val/128)*128:b=trunc(val/128)*128",
+ pixelate: "pixelize=width=2:height=2",
+ fisheye: "lenscorrection=k1=-0.028:k2=-0.010:i=bilinear",
+ shake: "crop=iw-4:ih-4:2+2*sin(t*2):2+2*cos(t*3)",
+};
+
+const MAX_CHAINS: Record<string, string> = {
+ sharpen: "unsharp=5:5:3.00:5:5:0",
+ "gaussian-blur": "gblur=sigma=50.0",
+ "box-blur": "boxblur=30:1",
+ "motion-blur": "gblur=sigma=60.0:sigmaV=0.1",
+ warm: "colortemperature=temperature=6000",
+ cool: "colortemperature=temperature=11000",
+ vibrance: "vibrance=intensity=2.00",
+ "contrast-pop": "eq=contrast=2.00",
+ vignette: "vignette=angle=1.300",
+ "film-grain": "noise=alls=40:allf=t+u",
+ glow:
+ "split[glowa][glowb];[glowb]gblur=sigma=18[glowg];" +
+ "[glowa][glowg]blend=all_mode=screen:all_opacity=1.00",
+ posterize: "lutrgb=r=trunc(val/32)*32:g=trunc(val/32)*32:b=trunc(val/32)*32",
+ pixelate: "pixelize=width=64:height=64",
+ fisheye: "lenscorrection=k1=-0.550:k2=-0.200:i=bilinear",
+ shake: "crop=iw-80:ih-80:40+40*sin(t*30):40+40*cos(t*39)",
+};
+
+describe("the effect catalogue's export strings", () => {
+ test("this suite knows every effect - a new effect must pin its strings here", () => {
+ expect(Object.keys(DEFAULT_CHAINS).sort()).toEqual(
+ EFFECTS.map((effect) => effect.id).sort(),
+ );
+ const parameterised = EFFECTS.filter((effect) => effect.params.length > 0).map(
+ (effect) => effect.id,
+ );
+ expect(Object.keys(MIN_CHAINS).sort()).toEqual([...parameterised].sort());
+ expect(Object.keys(MAX_CHAINS).sort()).toEqual([...parameterised].sort());
+ });
+
+ test("every effect at its default settings", () => {
+ for (const effect of EFFECTS) {
+ // No params passed: resolveEffectParams must fill every default.
+ expect(one(effect.id), effect.id).toBe(DEFAULT_CHAINS[effect.id]);
+ }
+ });
+
+ test("every effect at its sliders' minimum", () => {
+ for (const [id, expected] of Object.entries(MIN_CHAINS)) {
+ expect(one(id, bound(id, "min")), id).toBe(expected);
+ }
+ });
+
+ test("every effect at its sliders' maximum", () => {
+ for (const [id, expected] of Object.entries(MAX_CHAINS)) {
+ expect(one(id, bound(id, "max")), id).toBe(expected);
+ }
+ });
+});
+
+describe("buildEffectChain composition", () => {
+ test("stacked effects join with commas in applied order", () => {
+ expect(
+ buildEffectChain([
+ { id: "gaussian-blur", params: {} },
+ { id: "black-white", params: {} },
+ ]),
+ ).toBe("gblur=sigma=10.0,hue=s=0");
+ // The reverse order is a different picture and a different string.
+ expect(
+ buildEffectChain([
+ { id: "black-white", params: {} },
+ { id: "gaussian-blur", params: {} },
+ ]),
+ ).toBe("hue=s=0,gblur=sigma=10.0");
+ });
+
+ test("a bypassed effect contributes nothing", () => {
+ expect(
+ buildEffectChain([
+ { id: "invert", params: {} },
+ { id: "sepia", params: {}, enabled: false },
+ { id: "black-white", params: {} },
+ ]),
+ ).toBe("negate,hue=s=0");
+ });
+
+ test("an unknown id is skipped, not exported as garbage", () => {
+ // A project written by a newer WolfCut may carry effects this build does
+ // not know. The chain must stay valid for the effects it does know.
+ expect(
+ buildEffectChain([
+ { id: "from-the-future", params: {} },
+ { id: "invert", params: {} },
+ ]),
+ ).toBe("negate");
+ });
+
+ test("no effects means null, never an empty string", () => {
+ expect(buildEffectChain(undefined)).toBeNull();
+ expect(buildEffectChain([])).toBeNull();
+ expect(buildEffectChain([{ id: "invert", params: {}, enabled: false }])).toBeNull();
+ });
+
+ test("stray parameter keys are dropped, missing ones default", () => {
+ expect(one("sharpen", { amount: 2, bogus: 99 })).toBe("unsharp=5:5:2.00:5:5:0");
+ expect(one("shake", { amount: 20 })).toBe(
+ "crop=iw-40:ih-40:20+20*sin(t*13):20+20*cos(t*17)",
+ );
+ });
+});
diff --git a/desktop/src/lib/filters.test.ts b/desktop/src/lib/filters.test.ts
new file mode 100644
index 00000000..bfa7b0d4
--- /dev/null
+++ b/desktop/src/lib/filters.test.ts
@@ -0,0 +1,182 @@
+/**
+ * The audio filter catalogue's export strings, pinned character for character.
+ *
+ * `buildChain` is the single description of every filter: the exporter and the
+ * preview both run exactly this string through FFmpeg, so there is nothing to
+ * cross-check it against - these expectations are the check. Every catalogue
+ * entry is spelled out at its default, minimum and maximum settings. When one
+ * fails, the export sound changed - confirm FFmpeg accepts the new spelling
+ * (aphaser caps speed at 2, atempo floors at 0.5) and that existing projects
+ * still sound the same before updating the expectation.
+ */
+import { describe, expect, test } from "vitest";
+
+import { buildChain, chainKey, FILTERS, findFilter } from "./filters";
+
+const one = (id: string, params: Record<string, number> = {}) =>
+ buildChain([{ id, params }]);
+
+/** The definition's sliders, all pushed to one bound. */
+const bound = (id: string, which: "min" | "max"): Record<string, number> =>
+ Object.fromEntries(findFilter(id)!.params.map((param) => [param.key, param[which]]));
+
+// The Voice category is built on the pitchShift helper: asetrate moves pitch
+// and formants together, atempo puts the duration back. The rates below are
+// 48000 * 2^(semitones/12) and its reciprocal, to the helper's own precision.
+const DEFAULT_CHAINS: Record<string, string> = {
+ sweet:
+ "aresample=48000,asetrate=59334.357554,aresample=48000,atempo=0.80897480," +
+ "highpass=f=85,equalizer=f=300:t=q:w=1.1:g=-1.4," +
+ "equalizer=f=4200:t=q:w=0.8:g=4.180,equalizer=f=10500:t=q:w=0.7:g=5.550," +
+ "compand=attacks=0.010:decays=0.180:points=-80/-80|-30/-24|-18/-13|-8/-5|0/-1.5:soft-knee=5:gain=1," +
+ "deesser=i=0.388:m=0.45:f=0.55,aecho=0.8:0.82:38:0.0432," +
+ "alimiter=limit=0.94:attack=5:release=60",
+ deep:
+ "aresample=48000,asetrate=40363.027932,aresample=48000,atempo=1.18920712," +
+ "highpass=f=55,equalizer=f=140:t=q:w=1.0:g=3.00," +
+ "equalizer=f=2600:t=q:w=0.9:g=-1.2,alimiter=limit=0.94:attack=5:release=60",
+ chipmunk:
+ "aresample=48000,asetrate=71918.739690,aresample=48000,atempo=0.66741993," +
+ "highpass=f=120,alimiter=limit=0.94",
+ robot:
+ "aphaser=type=t:speed=1.20:decay=0.6,flanger=delay=2:depth=4:speed=0.8," +
+ "equalizer=f=1800:t=q:w=1.2:g=3,alimiter=limit=0.94",
+ bass: "bass=g=5.00:f=110:w=0.6,alimiter=limit=0.95",
+ treble: "treble=g=4.00:f=9000:w=0.7,alimiter=limit=0.95",
+ telephone:
+ "highpass=f=400,lowpass=f=3400,equalizer=f=1600:t=q:w=1.4:g=4.50,alimiter=limit=0.92",
+ echo: "aecho=0.8:0.85:250:0.40",
+ room: "aecho=0.8:0.88:24|43|70|101:0.320|0.240|0.170|0.110",
+};
+
+const MIN_CHAINS: Record<string, string> = {
+ sweet:
+ "aresample=48000,asetrate=51445.126202,aresample=48000,atempo=0.93303299," +
+ "highpass=f=85,equalizer=f=300:t=q:w=1.1:g=-1.4," +
+ "equalizer=f=4200:t=q:w=0.8:g=0.800,equalizer=f=10500:t=q:w=0.7:g=1.000," +
+ "compand=attacks=0.010:decays=0.180:points=-80/-80|-30/-24|-18/-13|-8/-5|0/-1.5:soft-knee=5:gain=1," +
+ "deesser=i=0.180:m=0.45:f=0.55,aecho=0.8:0.82:38:0.0120," +
+ "alimiter=limit=0.94:attack=5:release=60",
+ deep:
+ "aresample=48000,asetrate=30238.105197,aresample=48000,atempo=1.58740105," +
+ "highpass=f=55,equalizer=f=140:t=q:w=1.0:g=0.00," +
+ "equalizer=f=2600:t=q:w=0.9:g=-1.2,alimiter=limit=0.94:attack=5:release=60",
+ chipmunk:
+ "aresample=48000,asetrate=57081.941520,aresample=48000,atempo=0.84089642," +
+ "highpass=f=120,alimiter=limit=0.94",
+ robot:
+ "aphaser=type=t:speed=0.56:decay=0.6,flanger=delay=2:depth=4:speed=0.8," +
+ "equalizer=f=1800:t=q:w=1.2:g=3,alimiter=limit=0.94",
+ bass: "bass=g=0.00:f=110:w=0.6,alimiter=limit=0.95",
+ treble: "treble=g=0.00:f=9000:w=0.7,alimiter=limit=0.95",
+ telephone:
+ "highpass=f=400,lowpass=f=3400,equalizer=f=1600:t=q:w=1.4:g=3.00,alimiter=limit=0.92",
+ echo: "aecho=0.8:0.85:50:0.10",
+ room: "aecho=0.8:0.88:9|16|27|39:0.320|0.240|0.170|0.110",
+};
+
+const MAX_CHAINS: Record<string, string> = {
+ sweet:
+ "aresample=48000,asetrate=76195.250494,aresample=48000,atempo=0.62996052," +
+ "highpass=f=85,equalizer=f=300:t=q:w=1.1:g=-1.4," +
+ "equalizer=f=4200:t=q:w=0.8:g=6.000,equalizer=f=10500:t=q:w=0.7:g=8.000," +
+ "compand=attacks=0.010:decays=0.180:points=-80/-80|-30/-24|-18/-13|-8/-5|0/-1.5:soft-knee=5:gain=1," +
+ "deesser=i=0.500:m=0.45:f=0.55,aecho=0.8:0.82:38:0.0600," +
+ "alimiter=limit=0.94:attack=5:release=60",
+ deep:
+ "aresample=48000,asetrate=45305.967009,aresample=48000,atempo=1.05946309," +
+ "highpass=f=55,equalizer=f=140:t=q:w=1.0:g=8.00," +
+ "equalizer=f=2600:t=q:w=0.9:g=-1.2,alimiter=limit=0.94:attack=5:release=60",
+ chipmunk:
+ // +12 semitones is exactly double: the one point the maths comes out round.
+ "aresample=48000,asetrate=96000.000000,aresample=48000,atempo=0.50000000," +
+ "highpass=f=120,alimiter=limit=0.94",
+ robot:
+ // Depth 10 must land exactly on aphaser's speed cap of 2, never above it -
+ // above the cap the filter refuses and the whole export fails.
+ "aphaser=type=t:speed=2.00:decay=0.6,flanger=delay=2:depth=4:speed=0.8," +
+ "equalizer=f=1800:t=q:w=1.2:g=3,alimiter=limit=0.94",
+ bass: "bass=g=12.00:f=110:w=0.6,alimiter=limit=0.95",
+ treble: "treble=g=12.00:f=9000:w=0.7,alimiter=limit=0.95",
+ telephone:
+ "highpass=f=400,lowpass=f=3400,equalizer=f=1600:t=q:w=1.4:g=8.00,alimiter=limit=0.92",
+ echo: "aecho=0.8:0.85:1000:0.90",
+ room: "aecho=0.8:0.88:46|82|134|194:0.320|0.240|0.170|0.110",
+};
+
+describe("the filter catalogue's export strings", () => {
+ test("this suite knows every filter - a new filter must pin its strings here", () => {
+ const ids = FILTERS.map((filter) => filter.id).sort();
+ expect(Object.keys(DEFAULT_CHAINS).sort()).toEqual(ids);
+ expect(Object.keys(MIN_CHAINS).sort()).toEqual(ids);
+ expect(Object.keys(MAX_CHAINS).sort()).toEqual(ids);
+ });
+
+ test("every filter at its default settings", () => {
+ for (const filter of FILTERS) {
+ // No params passed: resolveParams must fill every default.
+ expect(one(filter.id), filter.id).toBe(DEFAULT_CHAINS[filter.id]);
+ }
+ });
+
+ test("every filter at its sliders' minimum", () => {
+ for (const [id, expected] of Object.entries(MIN_CHAINS)) {
+ expect(one(id, bound(id, "min")), id).toBe(expected);
+ }
+ });
+
+ test("every filter at its sliders' maximum", () => {
+ for (const [id, expected] of Object.entries(MAX_CHAINS)) {
+ expect(one(id, bound(id, "max")), id).toBe(expected);
+ }
+ });
+});
+
+describe("buildChain composition", () => {
+ test("stacked filters join with commas in applied order", () => {
+ // EQ into a limiter is a different sound from a limiter into EQ; the
+ // array's order is the contract.
+ expect(
+ buildChain([
+ { id: "bass", params: {} },
+ { id: "echo", params: {} },
+ ]),
+ ).toBe("bass=g=5.00:f=110:w=0.6,alimiter=limit=0.95,aecho=0.8:0.85:250:0.40");
+ });
+
+ test("a bypassed filter contributes nothing", () => {
+ expect(
+ buildChain([
+ { id: "bass", params: {}, enabled: false },
+ { id: "echo", params: {} },
+ ]),
+ ).toBe("aecho=0.8:0.85:250:0.40");
+ });
+
+ test("an unknown id is skipped, not exported as garbage", () => {
+ expect(
+ buildChain([
+ { id: "from-the-future", params: {} },
+ { id: "echo", params: {} },
+ ]),
+ ).toBe("aecho=0.8:0.85:250:0.40");
+ });
+
+ test("no audible filters means null, never an empty string", () => {
+ expect(buildChain([])).toBeNull();
+ expect(buildChain([{ id: "bass", params: {}, enabled: false }])).toBeNull();
+ });
+});
+
+describe("chainKey", () => {
+ test("identifies exactly one rendered sound", () => {
+ const filters = [{ id: "echo", params: { delay: 0.5 } }];
+ expect(chainKey("m1", 1.25, 4, filters)).toBe(
+ "m1|1.250|4.000|aecho=0.8:0.85:500:0.40",
+ );
+ // A bypassed chain keys the same as no chain: both play the raw file.
+ expect(chainKey("m1", 0, 4, [{ id: "echo", params: {}, enabled: false }])).toBe(
+ chainKey("m1", 0, 4, []),
+ );
+ });
+});
diff --git a/desktop/src/lib/text.test.ts b/desktop/src/lib/text.test.ts
new file mode 100644
index 00000000..271f3eae
--- /dev/null
+++ b/desktop/src/lib/text.test.ts
@@ -0,0 +1,39 @@
+/**
+ * Font identity from a file path.
+ *
+ * `familyForPath` names the CSS family a custom font registers under, and that
+ * name is written into the project's font list and referenced by text clips.
+ * Two files that end up with one name would silently render as each other -
+ * exactly the collision the uniquing exists to prevent.
+ */
+import { describe, expect, test } from "vitest";
+
+import { familyForPath } from "./text";
+
+describe("familyForPath", () => {
+ test("the file's own name, without its extension", () => {
+ expect(familyForPath("/fonts/Inter-Bold.otf", [])).toBe("Inter-Bold");
+ expect(familyForPath("/fonts/Cabinet Grotesk.TTF", [])).toBe("Cabinet Grotesk");
+ });
+
+ test("windows paths split on backslashes too", () => {
+ expect(familyForPath("C:\\Fonts\\Regular.otf", [])).toBe("Regular");
+ });
+
+ test("a taken name gets a counter, and the counter keeps counting", () => {
+ expect(familyForPath("/a/Regular.otf", ["Regular"])).toBe("Regular 2");
+ expect(familyForPath("/b/Regular.otf", ["Regular", "Regular 2"])).toBe("Regular 3");
+ });
+
+ test("punctuation CSS would choke on is stripped", () => {
+ expect(familyForPath("/f/Font™.otf", [])).toBe("Font");
+ // Inner dots go with the punctuation; only the last extension was an
+ // extension.
+ expect(familyForPath("/f/My.Font.v2.otf", [])).toBe("MyFontv2");
+ });
+
+ test("a name with nothing usable left falls back, and still uniques", () => {
+ expect(familyForPath("/f/★.otf", [])).toBe("Custom font");
+ expect(familyForPath("/f/★.otf", ["Custom font"])).toBe("Custom font 2");
+ });
+});
diff --git a/desktop/src/lib/time.test.ts b/desktop/src/lib/time.test.ts
new file mode 100644
index 00000000..6777f654
--- /dev/null
+++ b/desktop/src/lib/time.test.ts
@@ -0,0 +1,118 @@
+/**
+ * Time as the reader sees it.
+ *
+ * These helpers only format - the arithmetic lives in the engine - but they
+ * are on screen constantly: the monitor's timecode, the bin's durations, the
+ * recents list. A wrong digit here misreports the edit everywhere at once.
+ */
+import { afterEach, describe, expect, test, vi } from "vitest";
+
+import { relativeTime, shortDuration, timecode } from "./time";
+
+describe("timecode", () => {
+ test("zero is all zeros", () => {
+ expect(timecode(0, 30)).toBe("00:00:00:00");
+ });
+
+ test("frames count within the second at the given rate", () => {
+ expect(timecode(1.5, 30)).toBe("00:00:01:15");
+ expect(timecode(1.5, 24)).toBe("00:00:01:12");
+ expect(timecode(2.96, 25)).toBe("00:00:02:24"); // the second's last frame
+ });
+
+ test("hours, minutes and seconds carry like a clock", () => {
+ expect(timecode(59, 30)).toBe("00:00:59:00");
+ expect(timecode(60, 30)).toBe("00:01:00:00");
+ expect(timecode(3599, 30)).toBe("00:59:59:00");
+ expect(timecode(3600, 30)).toBe("01:00:00:00");
+ expect(timecode(3661.5, 30)).toBe("01:01:01:15");
+ });
+
+ test("the frame counter never reaches the rate", () => {
+ // 0.999s at 30fps is frame 29, not a rollover into :30.
+ expect(timecode(0.999, 30)).toBe("00:00:00:29");
+ expect(timecode(1, 30)).toBe("00:00:01:00");
+ });
+
+ test("negative time clamps to zero rather than going surreal", () => {
+ expect(timecode(-5, 30)).toBe("00:00:00:00");
+ });
+});
+
+describe("shortDuration", () => {
+ test("unknown duration reads as placeholder dashes", () => {
+ expect(shortDuration(null)).toBe("--:--");
+ });
+
+ test("whole seconds, floor not round", () => {
+ expect(shortDuration(0)).toBe("0:00");
+ expect(shortDuration(59.9)).toBe("0:59");
+ expect(shortDuration(61)).toBe("1:01");
+ });
+
+ test("minutes keep counting past an hour - no third field appears", () => {
+ expect(shortDuration(3600)).toBe("60:00");
+ expect(shortDuration(3725)).toBe("62:05");
+ });
+
+ test("negative clamps to zero", () => {
+ expect(shortDuration(-3)).toBe("0:00");
+ });
+});
+
+describe("relativeTime", () => {
+ const NOW = new Date("2026-08-28T12:00:00Z").getTime();
+ const ago = (seconds: number) => relativeTime(NOW - seconds * 1000);
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ const freeze = () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ };
+
+ test("under ninety seconds is just now", () => {
+ freeze();
+ expect(ago(0)).toBe("just now");
+ expect(ago(89)).toBe("just now");
+ });
+
+ test("minutes until the hour", () => {
+ freeze();
+ expect(ago(90)).toBe("2 min ago"); // 1.5 min rounds up
+ expect(ago(10 * 60)).toBe("10 min ago");
+ expect(ago(3599)).toBe("60 min ago");
+ });
+
+ test("hours until a day, singular reads as singular", () => {
+ freeze();
+ expect(ago(3600)).toBe("1 hour ago");
+ expect(ago(2 * 3600)).toBe("2 hours ago");
+ });
+
+ test("days until a week, one day ago reads as yesterday", () => {
+ freeze();
+ expect(ago(86_400)).toBe("yesterday");
+ expect(ago(3 * 86_400)).toBe("3 days ago");
+ });
+
+ test("a week or more becomes a real date in the reader's locale", () => {
+ freeze();
+ const timestamp = NOW - 30 * 86_400 * 1000;
+ expect(relativeTime(timestamp)).toBe(
+ new Date(timestamp).toLocaleDateString(undefined, {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+ }),
+ );
+ });
+
+ test("a timestamp from the future clamps to just now", () => {
+ // Clock skew between machines must not render "-3 min ago".
+ freeze();
+ expect(relativeTime(NOW + 60_000)).toBe("just now");
+ });
+});