import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { ChannelConfig } from "../lib/channelConfig"; import type { LiveRecordingRecord } from "../lib/liveCapture"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/livePreclip.test.ts // // Live pre-clip's loop (controller/livePreclip.ts) over a temp corpus: the // recording is a record and part files on disk whose LENGTH is a number the // test moves; the worker, the scan, umtool and the clock are stubs. Each // `sleep` the loop takes runs the next step of the script — the world moving // on while it waits. const ROOT = await mkdtemp(path.join(tmpdir(), "live-preclip-ctl-")); const CORPUS = path.join(ROOT, "transcripts"); process.env.TRANSCRIPTS_DIR = CORPUS; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await mkdir(CORPUS, { recursive: true }); await writeFile(process.env.SETTINGS_FILE, "{}"); const { getPaths } = await import("../lib/paths"); const { runLivePreclip, parseLivePreclipBody, memoryFloorMb, finalizeLivePreclip } = await import("./livePreclip"); const { liveRecordingSidecar } = await import("../lib/mediaImport-server"); const { liveTranscriptSidecar, livePreclipSidecar } = await import("../lib/livePreclip-server"); const { PRECLIP_DEFAULTS } = await import("../lib/livePreclip"); type Deps = NonNullable[0]["deps"]>; const paths = getPaths(); test.after(() => rm(ROOT, { recursive: true, force: true })); const SLUG = "synth-live"; const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth", platform: "youtube", name: "Synth" } as ChannelConfig; const slugStore = path.join(paths.savedVideosDir, SLUG); await mkdir(slugStore, { recursive: true }); const stemOf = (id: string, tag: string) => `.${id}.live-2026-10-27T12-00-00-000Z.${tag}`; async function setup(id: string) { const videoDir = path.join(CORPUS, "channels", SLUG, "data", id); await mkdir(videoDir, { recursive: true }); const stem = stemOf(id, "ytdlp"); await writeFile(path.join(slugStore, `${stem}.ts`), "growing"); const record: LiveRecordingRecord = { status: "recording", url: `https://www.youtube.com/watch?v=${id}`, platform: "youtube", fromStart: true, startedAt: "2026-10-27T12:00:00Z", parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: "2026-10-27T12:00:00Z", stem }], }; await liveRecordingSidecar.write(videoDir, record); return { videoDir, stem, record }; } // One cue a minute, at m·60 + 1 (and its word), inside [from, to). function fakeTranscript(from: number, to: number) { const cues = []; const words = []; for (let m = Math.ceil((from - 1) / 60); m * 60 + 1 < to; m += 1) { const t = m * 60 + 1; if (t < from) continue; cues.push({ start: t, end: t + 2, text: `minute ${m}` }); words.push({ w: `m${m}`, start: t, end: t + 0.4 }); } return { cues, words }; } // An envelope of a recording on a given clock: the same "audio" at the same // stream second, offset by the file's `shift` (a clock that differs). const pattern = (t: number, seed: number) => Math.round((-30 + 12 * Math.sin(t * 1.7 + seed) + 6 * Math.sin(t * 0.31 * (seed + 1))) * 10) / 10; function envelopeFor(seedOf: (file: string) => number, shiftOf: (file: string) => number = () => 0) { return async (file: string, from: number, dur: number) => { const out = []; for (let k = 0; k < Math.round(dur / 0.1); k += 1) out.push(pattern(from + k * 0.1 + shiftOf(file), seedOf(file))); return out; }; } function world(o: { recorded: Map; script: (() => void | Promise)[]; deps?: Partial }) { const calls: { from: number; to: number }[] = []; const mined: Record[] = []; let mem = [9000]; const lines: string[] = []; const ac = new AbortController(); let finalHere = false; const deps: Deps = { now: () => new Date("2026-10-27T12:30:00Z"), sleep: async () => { const step = o.script.shift(); if (step) await step(); else ac.abort(); }, memAvailableMb: async () => (mem.length > 1 ? mem.shift()! : mem[0]!), memoryFloorMb: 6000, freeBytes: async () => 1e12, probe: async (file) => ({ seconds: o.recorded.get(path.basename(file)) ?? null, hasVideo: true, hasAudio: true }), transcribe: async ({ from, to, withWav }) => { calls.push({ from, to }); await withWav?.("span.wav", to - from); return { ...fakeTranscript(from, to), worker: "gpu", ms: 1000, waitedMs: 0 }; }, scanWav: async (_wav, from, seconds) => ({ t0: from, hop: 0.5, window: 1, energy: new Array(Math.floor(seconds / 0.5)).fill(-30), laugh: null, model: null }), envelope: envelopeFor(() => 1), mine: async (body) => { mined.push(body); return { project: body.slug, created: mined.length === 1, proposals: mined.length, clips: 0 }; }, savedVideo: async () => null, hasFinalTranscript: async () => finalHere, recordWaitMs: 1000, ...o.deps, }; return { deps, calls, mined, lines, ac, setMem: (m: number[]) => (mem = m), setFinal: (v: boolean) => (finalHere = v), }; } test("ticks: memory floor, a busy worker coalesced, catch-up, the landing, the supersede", async () => { const id = "live001"; const { videoDir, stem, record } = await setup(id); const file = `${stem}.ts`; const recorded = new Map([[file, 600]]); const script: (() => void | Promise)[] = []; const w = world({ recorded, script }); w.setMem([3000, 9000]); // The first tick's worker takes 25 minutes to free up: the recording grows // under it, and the next tick takes all of it (capped at 20 min, then a // catch-up tick at once) — never one tick per period that passed. const transcribe = w.deps.transcribe!; w.deps.transcribe = async (o) => { const r = await transcribe(o); if (w.calls.length === 1) recorded.set(file, 600 + 25 * 60); return r; }; script.push( () => {}, // the memory wait () => {}, // after tick 1 () => {}, // after tick 2 (0 ms: catching up) async () => { // after tick 3: the stream ends and lands. await liveRecordingSidecar.write(videoDir, { ...record, status: "landed", kept: "new", landedPart: 0, endedAt: "2026-10-27T13:00:00Z" }); }, () => void w.setFinal(true), // the wait for the final transcript ); const summary = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS }, onLog: (l) => w.lines.push(l), signal: w.ac.signal, deps: w.deps }); assert.deepEqual(w.calls, [ { from: 0, to: 598 }, { from: 583, to: 1783 }, { from: 1768, to: 2098 }, ]); const doc = (await liveTranscriptSidecar.load(videoDir))!; assert.equal(doc.status, "superseded"); assert.equal(doc.transcribedTo, 2098); const starts = doc.cues.map((c) => c.start); assert.deepEqual(starts, [...new Set(starts)], "no cue twice across the overlaps"); assert.equal(doc.cues.length, 35, "a cue a minute, 0:01 … 34:01"); assert.equal(doc.words.length, 35); // The scan of each span, joined by window index across the overlaps. assert.equal(doc.scan?.energy.length, 2098 / 0.5); assert.equal(doc.landed?.check.verdict, "same-recording"); const state = (await livePreclipSidecar.load(videoDir))!; assert.equal(state.status, "superseded"); assert.equal(state.ticks, 3); assert.equal(state.skipped.memory, 1); assert.ok(w.lines.some((l) => /tick delayed: MemAvailable 3000 MB is under the floor of 6000 MB/.test(l))); // umtool: once per tick, once at the landing (with the check), once final. assert.equal(w.mined.length, 5); assert.deepEqual(w.mined[3], { slug: `${id}-live`, from: `${SLUG}/${id}`, check: doc.landed!.check }); assert.equal(w.mined[4]!.final, true); assert.equal(summary.status, "superseded"); }); test("no new data is a skipped tick; a recording that lands nothing leaves the transcript provisional", async () => { const id = "live002"; const { videoDir, stem, record } = await setup(id); const recorded = new Map([[`${stem}.ts`, 300]]); const script: (() => void | Promise)[] = [ () => {}, // after tick 1; nothing new next time async () => { await liveRecordingSidecar.write(videoDir, { ...record, status: "failed", error: "the stream went private" }); }, ]; const w = world({ recorded, script }); const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps }); assert.equal(w.calls.length, 1); const state = (await livePreclipSidecar.load(videoDir))!; assert.equal(state.skipped["no new data"], 1); assert.ok(state.log.some((l) => /no new data \(0 s new/.test(l))); assert.equal(s.status, "stopped"); assert.equal((await liveTranscriptSidecar.load(videoDir))!.status, "live"); assert.equal(w.mined.length, 0, "mine: false"); }); test("a recorder restart on the same clock goes on; on another clock the transcript starts again", async () => { for (const sameClock of [true, false]) { const id = sameClock ? "live003" : "live004"; const { videoDir, stem, record } = await setup(id); const stem2 = stemOf(id, "browser"); const recorded = new Map([[`${stem}.ts`, 600]]); const script: (() => void | Promise)[] = [ async () => { // The yt-dlp part ended; the browser fallback records from the DVR start. await writeFile(path.join(slugStore, `${stem2}.ts`), "growing"); recorded.set(`${stem2}.ts`, 900); await liveRecordingSidecar.write(videoDir, { ...record, parts: [ { ...record.parts[0]!, endedAt: "2026-10-27T12:10:00Z" }, { method: "browser", url: "u2", fromStart: true, startedAt: "2026-10-27T12:10:00Z", stem: stem2 }, ], }); }, () => {}, async () => { await liveRecordingSidecar.write(videoDir, { ...record, status: "cancelled", endedAt: "x" }); }, ]; const w = world({ recorded, script, deps: { envelope: envelopeFor((f) => (sameClock || !f.includes("browser") ? 1 : 7)) }, }); await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps }); const doc = (await liveTranscriptSidecar.load(videoDir))!; assert.equal(doc.basis?.stem, stem2); if (sameClock) { assert.deepEqual(w.calls, [{ from: 0, to: 598 }, { from: 583, to: 898 }]); assert.equal(doc.restarts, 0); } else { assert.deepEqual(w.calls, [{ from: 0, to: 598 }, { from: 0, to: 898 }]); assert.equal(doc.restarts, 1); assert.equal(doc.transcribedTo, 898); } } }); test("a landed video not the followed part: the clock check compares the fingerprint", async () => { for (const [shift, verdict] of [[0, "same"], [1.5, "shifted"]] as const) { const id = `live05${shift ? "b" : "a"}`; const { videoDir, stem, record } = await setup(id); const recorded = new Map([[`${stem}.ts`, 600]]); const script: (() => void | Promise)[] = [ async () => { await liveRecordingSidecar.write(videoDir, { ...record, status: "landed", kept: "new" }); }, ]; const w = world({ recorded, script, deps: { savedVideo: async () => "/store/landed.mp4", envelope: envelopeFor(() => 1, (f) => (f === "/store/landed.mp4" ? -shift : 0)), finalWaitMs: 0, }, }); const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps }); assert.equal(s.check?.verdict, verdict, JSON.stringify(s.check)); if (verdict === "shifted") assert.equal(s.check?.lagSeconds, 1.5); assert.equal(s.status, "waiting-final", "the final wait ran out"); const state = (await livePreclipSidecar.load(videoDir))!; assert.ok(state.log.some((l) => /finalize/.test(l))); // By hand, once the final transcript is here. await writeFile(path.join(videoDir, "transcript.json"), "{}"); const mined: Record[] = []; const f = await finalizeLivePreclip({ paths, slug: SLUG, id, deps: { mine: async (b) => (mined.push(b), { project: b.slug, created: false, proposals: 1, clips: 1 }) }, }); assert.equal(f.ok, true); assert.equal(mined[0]!.final, true); assert.equal((await liveTranscriptSidecar.load(videoDir))!.status, "superseded"); assert.equal((await livePreclipSidecar.load(videoDir))!.status, "superseded"); } }); test("stopped: the job's cancel leaves the recording alone and says how to resume", async () => { const id = "live006"; const { videoDir, stem } = await setup(id); const recorded = new Map([[`${stem}.ts`, 600]]); const w = world({ recorded, script: [] }); const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps }); assert.equal(s.status, "stopped"); assert.equal((await liveRecordingSidecar.load(videoDir))!.status, "recording"); assert.ok((await livePreclipSidecar.load(videoDir))!.log.some((l) => /resumes/.test(l))); }); test("parseLivePreclipBody and memoryFloorMb", () => { assert.deepEqual(parseLivePreclipBody({ slug: "a", id: "b" }), { ok: true, value: { slug: "a", id: "b", action: "start", options: { ...PRECLIP_DEFAULTS } } }); const r = parseLivePreclipBody({ slug: "a", id: "b", action: "start", everyMinutes: 5 }); assert.equal(r.ok && r.value.options.everyMinutes, 5); assert.equal(parseLivePreclipBody({ slug: "a", id: "b", action: "go" }).ok, false); assert.equal(parseLivePreclipBody({ slug: "a", id: "../x" }).ok, false); assert.equal(memoryFloorMb({}), 6000); assert.equal(memoryFloorMb({ HEAVY_MIN_FREE_MB: "4000" }), 4000); assert.equal(memoryFloorMb({ HEAVY: "0" }), 0); });