import { test } from "node:test"; import assert from "node:assert/strict"; import { LIVE_CLIP_MAX_SECONDS, PRECLIP_DEFAULTS, PRECLIP_EDGE_SECONDS, appendSpan, coerceLivePreclipState, coerceLiveTranscript, compareEnvelopes, emptyLiveTranscript, envelopeOf, fingerprintSpan, judgeClock, liveClipTooLong, checkLiveWindow, liveProjectSlug, newPreclipState, nextTickDelayMs, parsePreclipKnob, planTick, spliceAt, spliceCut, spliceScan, withLogLine, withSkip, } from "./livePreclip"; const now = new Date("2026-10-27T12:00:00Z"); test("parsePreclipKnob: off, defaults, keys over the defaults, refusals", () => { assert.equal(parsePreclipKnob(undefined), null); assert.equal(parsePreclipKnob(false), null); assert.deepEqual(parsePreclipKnob(true), { ...PRECLIP_DEFAULTS }); assert.deepEqual(parsePreclipKnob(true, { ...PRECLIP_DEFAULTS, everyMinutes: 5 }), { ...PRECLIP_DEFAULTS, everyMinutes: 5 }); assert.deepEqual(parsePreclipKnob({ everyMinutes: 3, scan: false, project: "demo-live" }), { ...PRECLIP_DEFAULTS, everyMinutes: 3, scan: false, project: "demo-live", }); assert.match((parsePreclipKnob({ everyMinutes: 0 }) as { error: string }).error, /everyMinutes/); assert.match((parsePreclipKnob({ every: 3 }) as { error: string }).error, /does not take "every"/); assert.match((parsePreclipKnob({ project: "Not A Slug" }) as { error: string }).error, /project/); assert.match((parsePreclipKnob("yes") as { error: string }).error, /preclip/); assert.match((parsePreclipKnob({ maxChunkMinutes: 2, overlapSeconds: 60 }) as { error: string }).error, /overlap/); }); test("liveProjectSlug: the id, lowercased, -live", () => { assert.equal(liveProjectSlug("5-XlMxKT494"), "5-xlmxkt494-live"); assert.equal(liveProjectSlug("v7h8pxg"), "v7h8pxg-live"); assert.ok(liveProjectSlug("x".repeat(200)).length <= 80); }); test("planTick: no new data, the first tick from 0, the overlap, the cap, behind", () => { const opts = { maxChunkMinutes: 20, overlapSeconds: 15 }; assert.deepEqual(planTick({ transcribedTo: 0, recordedSeconds: null, opts }).action, "wait"); const idle = planTick({ transcribedTo: 600, recordedSeconds: 620, opts }); assert.equal(idle.action, "wait"); assert.match((idle as { reason: string }).reason, /no new data \(18 s new/); assert.deepEqual(planTick({ transcribedTo: 0, recordedSeconds: 600, opts }), { action: "transcribe", from: 0, to: 598, behind: 0 }); assert.deepEqual(planTick({ transcribedTo: 598, recordedSeconds: 1200, opts }), { action: "transcribe", from: 583, to: 1198, behind: 0 }); // Two hours behind (the worker was busy, or pre-clip started late): one chunk, the rest behind. const behind = planTick({ transcribedTo: 0, recordedSeconds: 7200, opts }); assert.deepEqual(behind, { action: "transcribe", from: 0, to: 1200, behind: 7200 - PRECLIP_EDGE_SECONDS - 1200 }); assert.equal(nextTickDelayMs(5998, { everyMinutes: 10 }), 0); assert.equal(nextTickDelayMs(0, { everyMinutes: 10 }), 600_000); }); test("planTick coalesces: however many periods passed, one tick covers what is new (up to the cap)", () => { // The worker was busy for 25 minutes; five 5-minute ticks came due. One // tick, from the overlap to the edge — never five. const p = planTick({ transcribedTo: 300, recordedSeconds: 300 + 25 * 60, opts: { maxChunkMinutes: 30, overlapSeconds: 15 } }); assert.deepEqual(p, { action: "transcribe", from: 285, to: 300 + 25 * 60 - PRECLIP_EDGE_SECONDS, behind: 0 }); }); test("spliceAt / spliceCut: the old before the overlap's middle, the new from it, no duplicate", () => { assert.equal(spliceCut(600, 585), 592.5); assert.equal(spliceCut(600, 600), 600); const old = [ { start: 580, end: 588, text: "a" }, { start: 588, end: 596, text: "b (cut short by the boundary)" }, ]; const incoming = [ { start: 586, end: 590, text: "a-tail" }, { start: 588.1, end: 597, text: "b whole" }, { start: 597, end: 603, text: "c" }, ]; const got = spliceAt(old, incoming, spliceCut(596, 585)); assert.deepEqual(got.map((c) => c.text), ["a", "b (cut short by the boundary)", "c"]); const got2 = spliceAt(old, incoming, 588.05); assert.deepEqual(got2.map((c) => c.text), ["a", "b (cut short by the boundary)", "b whole", "c"]); }); test("appendSpan: transcribedTo, chunks, words spliced the same way", () => { let doc = emptyLiveTranscript(now); doc = appendSpan( doc, { from: 0, to: 598, cues: [{ start: 1, end: 3, text: "hi" }, { start: 590, end: 597, text: "cut" }], words: [{ w: "hi", start: 1, end: 1.4 }, { w: "cut", start: 590, end: 590.5 }], worker: "gpu", ms: 4000, waitedMs: 10 }, now, ); doc = appendSpan( doc, { from: 583, to: 1198, cues: [{ start: 589.9, end: 597.5, text: "cut whole" }, { start: 700, end: 702, text: "later" }], words: [{ w: "cut", start: 589.9, end: 590.4 }, { w: "later", start: 700, end: 700.4 }], worker: "gpu", ms: 4000, waitedMs: 0 }, now, ); assert.equal(doc.transcribedTo, 1198); assert.deepEqual(doc.cues.map((c) => c.text), ["hi", "cut", "later"]); assert.equal(doc.words.length, 3); assert.equal(doc.chunks.length, 2); assert.equal(coerceLiveTranscript(JSON.parse(JSON.stringify(doc)))?.cues.length, 3); assert.equal(coerceLiveTranscript({ version: 2 }), null); }); test("spliceScan: by window index, gaps silent, laugh kept when a span had no tagger", () => { let s = spliceScan(null, { t0: 0, hop: 0.5, window: 1, energy: [-20, -21, -22, -23], laugh: [0.1, 0.2, 0.3, 0.4], model: "ced" }); assert.deepEqual(s.energy, [-20, -21, -22, -23]); // Overlap from window 2 (t0 1.0): rewritten, extended. s = spliceScan(s, { t0: 1, hop: 0.5, window: 1, energy: [-30, -31, -32], laugh: [0.9, 0.8, 0.7], model: "ced" }); assert.deepEqual(s.energy, [-20, -21, -30, -31, -32]); assert.deepEqual(s.laugh, [0.1, 0.2, 0.9, 0.8, 0.7]); // A gap (t0 4.0 = window 8), no tagger on this span. s = spliceScan(s, { t0: 4, hop: 0.5, window: 1, energy: [-10], laugh: null, model: null }); assert.deepEqual(s.energy, [-20, -21, -30, -31, -32, -120, -120, -120, -10]); assert.deepEqual(s.laugh, [0.1, 0.2, 0.9, 0.8, 0.7, 0, 0, 0, 0]); assert.equal(s.model, "ced"); assert.throws(() => spliceScan(s, { t0: 5, hop: 0.25, window: 1, energy: [1], laugh: null, model: null }), /cannot join/); }); function speechLike(seconds: number, rate: number, seed: number, offsetSamples = 0): Float32Array { // Bursts of noise at pseudo-random lengths: an envelope with a shape. const out = new Float32Array(Math.round(seconds * rate)); let x = seed; const rnd = () => ((x = (x * 1103515245 + 12345) % 2 ** 31) / 2 ** 31); let on = true; let left = 0; // Warm the generator so offsetSamples shifts the same signal. const total = out.length + offsetSamples; const all = new Float32Array(total); for (let i = 0; i < total; i += 1) { if (left <= 0) { on = !on; left = Math.round((0.15 + rnd() * 0.6) * rate); } left -= 1; all[i] = on ? (rnd() - 0.5) * 0.6 : (rnd() - 0.5) * 0.01; } out.set(all.subarray(offsetSamples, offsetSamples + out.length)); return out; } test("envelopeOf + compareEnvelopes + judgeClock: same, shifted, mismatch, flat", () => { const rate = 8000; const pad = 20; // 2 s at 0.1 s const base = speechLike(34, rate, 7); // ref = 30 s from 2 s in; probe = 34 s (2 s either side). const ref = envelopeOf(base.subarray(2 * rate, 32 * rate), rate); const probeSame = envelopeOf(base, rate); const same = judgeClock(compareEnvelopes(ref, probeSame, pad), 0.1, now); assert.equal(same.verdict, "same"); // The same audio, 1.2 s later in the probed file. const later = new Float32Array(base.length); later.set(base.subarray(0, base.length - Math.round(1.2 * rate)), Math.round(1.2 * rate)); const shifted = judgeClock(compareEnvelopes(ref, envelopeOf(later, rate), pad), 0.1, now); assert.equal(shifted.verdict, "shifted"); assert.equal(shifted.lagSeconds, 1.2); const other = judgeClock(compareEnvelopes(ref, envelopeOf(speechLike(34, rate, 99), rate), pad), 0.1, now); assert.equal(other.verdict, "mismatch"); const silent = new Float32Array(34 * rate); const flat = judgeClock(compareEnvelopes(ref, envelopeOf(silent, rate), pad), 0.1, now); assert.equal(flat.verdict, "unverified"); }); test("fingerprintSpan: 60 s in, else the start, else none", () => { assert.deepEqual(fingerprintSpan(4000), { from: 60, dur: 30 }); assert.deepEqual(fingerprintSpan(50), { from: 0, dur: 30 }); assert.equal(fingerprintSpan(20), null); }); test("the state: log lines kept to the last twelve, skips counted, coerced back", () => { let s = newPreclipState({ ...PRECLIP_DEFAULTS }, now, "job1"); for (let i = 0; i < 20; i += 1) s = withLogLine(s, `tick ${i}`, now); s = withSkip(withSkip(s, "memory"), "memory"); assert.equal(s.log.length, 12); assert.match(s.log.at(-1)!, /tick 19$/); assert.deepEqual(s.skipped, { memory: 2 }); const back = coerceLivePreclipState(JSON.parse(JSON.stringify(s))); assert.equal(back?.jobId, "job1"); assert.equal(coerceLivePreclipState({ version: 1, status: "nope" }), null); }); test("liveClipTooLong / checkLiveWindow: X's 2:20, inside what is recorded", () => { assert.equal(liveClipTooLong(100, 160), null); assert.equal(liveClipTooLong(0, LIVE_CLIP_MAX_SECONDS), null); assert.match(liveClipTooLong(0, LIVE_CLIP_MAX_SECONDS + 1)!, /2:20/); assert.match(liveClipTooLong(10, 5)!, /start before end/); assert.deepEqual(checkLiveWindow(95.5, 164.5, 3600), { from: 95.5, to: 164.5 }); assert.deepEqual(checkLiveWindow(3500, 3598, 3600), { from: 3500, to: 3598 }); assert.match( (checkLiveWindow(3590, 3610, 3600) as { error: string }).error, /holds 1:00:00 so far; the window ends at 1:00:10 — ask again in 12 s/, ); assert.match((checkLiveWindow(0, 1000, 3600) as { error: string }).error, /at most 3:20/); assert.deepEqual(checkLiveWindow(0, 30, null), { from: 0, to: 30 }); });